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
6ac676fd50f864bd51c26697b165a991cf1e35bc
10,368
cpp
C++
TDEngine2/source/utils/Utils.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
1
2019-07-15T01:14:15.000Z
2019-07-15T01:14:15.000Z
TDEngine2/source/utils/Utils.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
76
2018-10-27T16:59:36.000Z
2022-03-30T17:40:39.000Z
TDEngine2/source/utils/Utils.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
1
2019-07-29T02:02:08.000Z
2019-07-29T02:02:08.000Z
#include "./../../include/utils/Utils.h" #define STR_UTILS_IMPLEMENTATION #include "stringUtils.hpp" #define MEM_TRACKER_IMPLEMENTATION #include "memTracker.hpp" #include <algorithm> #include <cctype> namespace TDEngine2 { TDE2_API E_ENDIAN_TYPE GetHostEndianType() { U32 checker = 0x1; return (*((U8*)&checker) == 0x1) ? E_ENDIAN_TYPE::ET_LITTLE_ENDIAN : E_ENDIAN_TYPE::ET_BIG_ENDIAN; } TDE2_API U16 Swap2Bytes(U16 value) { return (value & 0x00FF) << 8 | (value & 0xFF00) >> 8; } TDE2_API U32 Swap4Bytes(U32 value) { return (value & 0x000000FF) << 24 | (value & 0x0000FF00) << 8 | (value & 0x00FF0000) >> 8 | (value & 0xFF000000) >> 24; } TDE2_API U64 Swap8Bytes(U64 value) { return (value & 0x00000000000000FF) << 56 | (value & 0x000000000000FF00) << 40 | (value & 0x0000000000FF0000) << 24 | (value & 0x00000000FF000000) << 8 | (value & 0x000000FF00000000) >> 8 | (value & 0x0000FF0000000000) >> 24 | (value & 0x00FF000000000000) >> 40 | (value & 0xFF00000000000000) >> 56; } TDE2_API U8* SwapObjectBytes(U8* pPtr, U32 size) { std::reverse(pPtr, pPtr + size); return pPtr; } std::string CStringUtils::RemoveSingleLineComments(const std::string& source, const std::string& commentPrefixStr) { if (source.empty() || commentPrefixStr.empty()) { return source; } std::string::size_type startPos = 0; std::string::size_type endPos = 0; std::string processedStr { source }; while ((startPos = processedStr.find(commentPrefixStr)) != std::string::npos) { endPos = processedStr.find_first_of("\n\r", startPos); if (endPos == std::string::npos) { return source.substr(0, startPos); /// assume that the rest part is a comment } processedStr = processedStr.substr(0, startPos) + processedStr.substr(endPos + 1, processedStr.length() - endPos); } return processedStr; } std::string CStringUtils::RemoveMultiLineComments(const std::string& source, const std::string& commentPrefixStr, const std::string& commentPostfixStr) { if (source.empty() || commentPrefixStr.empty() || commentPostfixStr.empty()) { return source; } std::string::size_type firstPos = 0; std::string::size_type secondPos = 0; std::string::size_type thirdPos = 0; const U32 commentPrefixLength = commentPrefixStr.length(); const U32 commentPostfixLength = commentPostfixStr.length(); U8 numOfNestedCommentsBlocks = 0; std::string::size_type seekPos; std::string processedStr { source }; while (((firstPos = processedStr.find(commentPrefixStr)) != std::string::npos)) { ++numOfNestedCommentsBlocks; seekPos = firstPos + commentPrefixLength; do { secondPos = processedStr.find(commentPostfixStr, seekPos); thirdPos = processedStr.find(commentPrefixStr, seekPos); if ((secondPos == thirdPos) && (secondPos == std::string::npos)) { break; } if (secondPos < thirdPos) { --numOfNestedCommentsBlocks; seekPos = secondPos + commentPostfixLength; continue; } if (thirdPos < secondPos) { ++numOfNestedCommentsBlocks; seekPos = thirdPos + commentPrefixLength; continue; } } while (seekPos < processedStr.length() && (numOfNestedCommentsBlocks > 0)); if (numOfNestedCommentsBlocks == 0) { processedStr = processedStr.substr(0, firstPos) + processedStr.substr(secondPos + commentPostfixLength, processedStr.length() - secondPos - commentPostfixLength); } else { processedStr = processedStr.substr(0, firstPos); } } return processedStr; } TDE2_API std::string GraphicsContextTypeToString(E_GRAPHICS_CONTEXT_GAPI_TYPE graphicsContextType) { switch (graphicsContextType) { case GCGT_DIRECT3D11: return "d3d11"; case GCGT_OPENGL3X: return "gl3x"; } return "unknown"; } TDE2_API E_GRAPHICS_CONTEXT_GAPI_TYPE StringToGraphicsContextType(const std::string& value) { if (value.find("d3d11") != std::string::npos) { return GCGT_DIRECT3D11; } else if (value.find("gl3x") != std::string::npos) { return GCGT_OPENGL3X; } return GCGT_UNKNOWN; } /*! \brief CFormatUtils's definition */ U8 CFormatUtils::GetNumOfChannelsOfFormat(E_FORMAT_TYPE format) { switch (format) { case FT_BYTE1: case FT_NORM_BYTE1: case FT_UBYTE1: case FT_NORM_UBYTE1: case FT_FLOAT1: case FT_D32: case FT_SHORT1: case FT_NORM_SHORT1: case FT_USHORT1: case FT_NORM_USHORT1: case FT_UINT1: case FT_NORM_UINT1: case FT_SINT1: case FT_NORM_SINT1: return 1; case FT_BYTE2: case FT_NORM_BYTE2: case FT_UBYTE2: case FT_NORM_UBYTE2: case FT_FLOAT2: case FT_FLOAT2_TYPELESS: case FT_SHORT2: case FT_NORM_SHORT2: case FT_USHORT2: case FT_NORM_USHORT2: case FT_UINT2: case FT_NORM_UINT2: case FT_SINT2: case FT_NORM_SINT2: return 2; case FT_BYTE3: case FT_NORM_BYTE3: case FT_UBYTE3: case FT_NORM_UBYTE3: case FT_FLOAT3: case FT_FLOAT3_TYPELESS: case FT_SHORT3: case FT_NORM_SHORT3: case FT_USHORT3: case FT_NORM_USHORT3: case FT_UINT3: case FT_NORM_UINT3: case FT_SINT3: case FT_NORM_SINT3: return 3; case FT_BYTE4: case FT_NORM_BYTE4: case FT_UBYTE4: case FT_NORM_UBYTE4: case FT_NORM_BYTE4_SRGB: case FT_UBYTE4_BGRA_UNORM: case FT_SHORT4: case FT_NORM_SHORT4: case FT_SINT4: case FT_NORM_SINT4: case FT_UINT4: case FT_NORM_UINT4: case FT_USHORT4: case FT_NORM_USHORT4: case FT_FLOAT4: case FT_FLOAT4_TYPELESS: return 4; } return 0; } U32 CFormatUtils::GetFormatSize(E_FORMAT_TYPE format) { switch (format) { case FT_BYTE1: case FT_NORM_BYTE1: return sizeof(char); case FT_BYTE2: case FT_NORM_BYTE2: return 2 * sizeof(char); case FT_BYTE3: case FT_NORM_BYTE3: return 3 * sizeof(char); case FT_BYTE4: case FT_NORM_BYTE4: return 4 * sizeof(char); case FT_UBYTE1: case FT_NORM_UBYTE1: return sizeof(unsigned char); case FT_UBYTE2: case FT_NORM_UBYTE2: return 2 * sizeof(unsigned char); case FT_UBYTE3: case FT_NORM_UBYTE3: return 3 * sizeof(unsigned char); case FT_UBYTE4: case FT_NORM_UBYTE4: case FT_NORM_BYTE4_SRGB: case FT_UBYTE4_BGRA_UNORM: return 4 * sizeof(unsigned char); case FT_FLOAT1: case FT_D32: return sizeof(float); case FT_FLOAT2: case FT_FLOAT2_TYPELESS: return 2 * sizeof(float); case FT_FLOAT3: case FT_FLOAT3_TYPELESS: return 3 * sizeof(float); case FT_FLOAT4: case FT_FLOAT4_TYPELESS: return 4 * sizeof(float); case FT_SHORT1: case FT_NORM_SHORT1: return 1 * sizeof(short); case FT_SHORT2: case FT_NORM_SHORT2: return 2 * sizeof(short); case FT_SHORT3: case FT_NORM_SHORT3: return 3 * sizeof(short); case FT_SHORT4: case FT_NORM_SHORT4: return 4 * sizeof(short); case FT_USHORT1: case FT_NORM_USHORT1: return 1 * sizeof(short); case FT_USHORT2: case FT_NORM_USHORT2: return 2 * sizeof(short); case FT_USHORT3: case FT_NORM_USHORT3: return 3 * sizeof(short); case FT_USHORT4: case FT_NORM_USHORT4: return 4 * sizeof(short); case FT_UINT1: case FT_NORM_UINT1: return 1 * sizeof(int); case FT_UINT2: case FT_NORM_UINT2: return 2 * sizeof(int); case FT_UINT3: case FT_NORM_UINT3: return 3 * sizeof(int); case FT_UINT4: case FT_NORM_UINT4: return 4 * sizeof(int); case FT_SINT1: case FT_NORM_SINT1: return 1 * sizeof(int); case FT_SINT2: case FT_NORM_SINT2: return 2 * sizeof(int); case FT_SINT3: case FT_NORM_SINT3: return 3 * sizeof(int); case FT_SINT4: case FT_NORM_SINT4: return 4 * sizeof(int); } return 0; } E_FORMAT_TYPE CFormatUtils::GetFormatFromString(const std::string& str) { static std::unordered_map<std::string, E_FORMAT_TYPE> formatsMap { { "R8_UNORM" , FT_NORM_UBYTE1 }, { "R8G8_UNORM" , FT_NORM_UBYTE2 }, { "R8G8B8_UNORM" , FT_NORM_UBYTE3 }, { "R8G8B8A8_UNORM" , FT_NORM_UBYTE4 }, }; if (formatsMap.find(str) == formatsMap.cend()) { /// \todo not all values of E_FORMAT_TYPE are represented here TDE2_UNIMPLEMENTED(); return FT_UNKNOWN; } return formatsMap.at(str); } /*! \brief CDeferOperation's definition */ CDeferOperation::CDeferOperation(const TCallbackType& callback) : mCallback(callback) { } CDeferOperation::~CDeferOperation() { mCallback(); } template <> TDE2_API U32 ComputeStateDescHash<TBlendStateDesc>(const TBlendStateDesc& object) { return static_cast<U32>(object.mIsEnabled) << 31 | static_cast<U32>(object.mAlphaOpType) << 15 | static_cast<U32>(object.mDestAlphaValue) << 12 | static_cast<U32>(object.mDestValue) << 9 | static_cast<U32>(object.mOpType) << 6 | static_cast<U32>(object.mScrAlphaValue) << 3 | static_cast<U32>(object.mScrValue); } template <> TDE2_API U32 ComputeStateDescHash<TDepthStencilStateDesc>(const TDepthStencilStateDesc& object) { return static_cast<U32>(object.mIsDepthTestEnabled) << 31 | static_cast<U32>(object.mIsDepthWritingEnabled) << 30 | static_cast<U32>(object.mIsStencilTestEnabled) << 29 | static_cast<U32>(object.mDepthCmpFunc) << 26 | static_cast<U32>(object.mStencilBackFaceOp.mDepthFailOp) << 23 | static_cast<U32>(object.mStencilBackFaceOp.mFailOp) << 21 | static_cast<U32>(object.mStencilBackFaceOp.mFunc) << 19 | static_cast<U32>(object.mStencilBackFaceOp.mPassOp) << 17 | static_cast<U32>(object.mStencilFrontFaceOp.mDepthFailOp) << 15 | static_cast<U32>(object.mStencilFrontFaceOp.mFailOp) << 13 | static_cast<U32>(object.mStencilFrontFaceOp.mFunc) << 11 | static_cast<U32>(object.mStencilFrontFaceOp.mPassOp) << 9 | static_cast<U32>(object.mStencilReadMaskValue) << 8 | static_cast<U32>(object.mStencilWriteMaskValue); } template <> TDE2_API U32 ComputeStateDescHash<TTextureSamplerDesc>(const TTextureSamplerDesc& object) { std::array<C8, sizeof(U32) * 4> data; memcpy(&data[0], &object.mFilterFlags, sizeof(U32)); memcpy(&data[4], &object.mUAddressMode, sizeof(U32)); memcpy(&data[8], &object.mVAddressMode, sizeof(U32)); memcpy(&data[12], &object.mWAddressMode, sizeof(U32)); return ComputeHash(&data.front()); } }
24.74463
166
0.691069
[ "object" ]
6ace681e84214b6b52a8bcc30796ac723f230844
11,884
cc
C++
test/unit_test_json.cc
o-ran-sc/ric-app-admin
0a168f272a81ac4c3afe42e014f8032f2a159d97
[ "Apache-2.0" ]
null
null
null
test/unit_test_json.cc
o-ran-sc/ric-app-admin
0a168f272a81ac4c3afe42e014f8032f2a159d97
[ "Apache-2.0" ]
null
null
null
test/unit_test_json.cc
o-ran-sc/ric-app-admin
0a168f272a81ac4c3afe42e014f8032f2a159d97
[ "Apache-2.0" ]
null
null
null
/* ================================================================================== Copyright (c) 2018-2019 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. ================================================================================== */ /* Author : Ashwin Sridharan Date : Sept 2019 */ #define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include <json_handler.hpp> void gen_message(std::string & message_string, bool enforce, int blocking_rate, int trigger_threshold, int window_length){ std::string enforce_string ((enforce? "true":"false")); message_string = "{\"enforce\":" + enforce_string + ","; message_string += std::string("\"blocking_rate\":") + std::to_string(blocking_rate) + ","; message_string += std::string("\"window_length\":") + std::to_string(window_length) + ","; message_string += std::string("\"trigger_threshold\":") + std::to_string(trigger_threshold) + "}"; } TEST_CASE("JSON-schema", "Schema Check"){ jsonHandler json_test; std::vector<TrieNode> schema_path; TrieNode * test_node; std::string valid_schema_file = "../schemas/adm-ctrl-xapp-policy-schema.json"; std::string valid_sample_file = "../schemas/sample.json"; std::string response; SECTION("Invalid Schema File"){ REQUIRE_THROWS( json_test.load_schema("hello there")); REQUIRE_THROWS( json_test.load_schema("hello there", NULL)); REQUIRE_THROWS( json_test.load_schema("hello there", test_node)); } SECTION("Invalid JSON"){ REQUIRE_THROWS( json_test.load_schema("invalid_json.txt")); REQUIRE_THROWS( json_test.load_schema("invalid_json.txt", NULL)); REQUIRE_THROWS( json_test.load_schema("invalid_json.txt", test_node)); } // SECTION("Valid File and JSON"){ // bool res = json_test.load_schema(valid_schema_file); // REQUIRE(res == TRUE); // } SECTION("Valid File and JSON, invalid schema root "){ schema_path.clear(); schema_path.emplace_back("controlS"); schema_path.emplace_back((int)0); schema_path.emplace_back("message_receives_payload_schema"); schema_path[0].add_child(&schema_path[1]); schema_path[1].add_child(&schema_path[2]); REQUIRE_THROWS(json_test.load_schema(valid_schema_file, &schema_path[0])); } SECTION("Valid File and JSON & root"){ schema_path.clear(); schema_path.emplace_back("controls"); schema_path.emplace_back((int)0); schema_path.emplace_back("message_receives_payload_schema"); schema_path[0].add_child(&schema_path[1]); schema_path[1].add_child(&schema_path[2]); std::string message_string; bool res; json_test.load_schema(valid_schema_file, &schema_path[0]); gen_message(message_string, 0, 10, 20, 30); res = json_test.is_valid(message_string.c_str(), message_string.length(), response); REQUIRE(res == true); gen_message(message_string, 0, 10, -5, 30); res = json_test.is_valid(message_string.c_str(), message_string.length(), response); REQUIRE(res == false); gen_message(message_string, 0, 120, 10, 5); res = json_test.is_valid(message_string.c_str(), message_string.length(), response); REQUIRE(res == false); gen_message(message_string, 0, 20, 10, 5); message_string = message_string + "}"; res = json_test.is_valid(message_string.c_str(), message_string.length(), response); REQUIRE(res == false); } } TEST_CASE("DataContainer", "Get/set"){ std::string test_string = "Hello there"; int test_int = 101; double test_real = 123.8; long int test_long = 2839289; unsigned int test_uint = 189; unsigned long test_ulong = 29392329; SECTION("Validate data types"){ TrieNode test("Test Node"); test.set_value(test_string); const DataContainer * val = test.get_value(); REQUIRE(val->tag == DataContainer::Types::str); REQUIRE(val->value.s == test_string); test.set_value(test_int); val = test.get_value(); REQUIRE(val->tag == DataContainer::Types::integer); REQUIRE(val->value.i == test_int); test.set_value(test_uint); val = test.get_value(); REQUIRE(val->tag == DataContainer::Types::uinteger); REQUIRE(val->value.ui == test_uint); test.set_value(test_real); val = test.get_value(); REQUIRE(val->tag == DataContainer::Types::real); REQUIRE(val->value.f == test_real); test.set_value(test_long); val = test.get_value(); REQUIRE(val->tag == DataContainer::Types::big_integer); REQUIRE(val->value.l == test_long); test.set_value(test_ulong); val = test.get_value(); REQUIRE(val->tag == DataContainer::Types::ubig_integer); REQUIRE(val->value.ul == test_ulong); test.print_id(); test.print_value(); REQUIRE(test.is_child() == true); TrieNode test_child("child"); test.add_child(&test_child); REQUIRE(test.is_child() == false); } } TEST_CASE("JSON-getset", "Get/Set values"){ jsonHandler json_test; std::vector<TrieNode> schema_path; std::vector<TrieNode> key_path; TrieNode *test_node; std::string valid_schema_file = "../schemas/adm-ctrl-xapp-policy-schema.json"; std::string valid_sample_file = "../schemas/samples.json"; std::string response; bool res; SECTION("Invalid buffer file"){ REQUIRE_THROWS( json_test.load_buffer("hello there")); REQUIRE_THROWS( json_test.load_buffer("hello there", NULL)); REQUIRE_THROWS( json_test.load_buffer("hello there", test_node)); } SECTION("Validate buffer"){ schema_path.clear(); schema_path.emplace_back("controls"); schema_path.emplace_back((int)0); schema_path.emplace_back("message_receives_payload_schema"); schema_path[0].add_child(&schema_path[1]); schema_path[1].add_child(&schema_path[2]); json_test.load_schema(valid_schema_file, &schema_path[0]); schema_path.clear(); schema_path.emplace_back("message_receives_example"); json_test.load_buffer(valid_sample_file, &schema_path[0]); std::string buffer = json_test.get_buffer(); res = json_test.is_valid(buffer.c_str(), buffer.length(), response); REQUIRE(res == true); } SECTION("Get correct value from internal buffer"){ int res; std::string message_string; std::vector<TrieNode *> available_keys; TrieNode test("window_length"); TrieNode invalid_test("Window_length"); // Try with no buffer loaded res = json_test.get_values(response, &test, available_keys); REQUIRE(res == -4); // Try with buffer loaded schema_path.clear(); schema_path.emplace_back("message_receives_example"); json_test.load_buffer(valid_sample_file, &schema_path[0]); available_keys.clear(); res = json_test.get_values(response, &test, available_keys); REQUIRE (res == 1); REQUIRE(available_keys.size() == 1); REQUIRE(available_keys[0]->get_value()->value.i == 10); available_keys.clear(); res = json_test.get_values(response, &invalid_test, available_keys); REQUIRE (res == 0); REQUIRE(available_keys.size() == 0); } SECTION("Get values from supplied buffer"){ int res; std::string message_string; std::vector<TrieNode *> available_keys; bool enforce = true; int blocking_rate = 10; int trigger_threshold = 5000; int window_length = 25; TrieNode test("window_length"); available_keys.clear(); gen_message(message_string, enforce, blocking_rate, trigger_threshold, window_length); res = json_test.get_values(message_string.c_str(), message_string.length(), response, &test, available_keys); REQUIRE(res == 0); REQUIRE(available_keys.size() == 1); REQUIRE(available_keys[0]->get_value()->value.i == 25); TrieNode invalid_test("Window_length"); available_keys.clear(); gen_message(message_string, enforce, blocking_rate, trigger_threshold, window_length); res = json_test.get_values(message_string.c_str(), message_string.length(), response, &invalid_test, available_keys); REQUIRE(res == -3); REQUIRE(available_keys.size() == 0); } SECTION("Get/Set from memory"){ int res; std::vector<TrieNode *> keys; TrieNode test1("blocking_rate"); int blocking_rate = 23; test1.set_value(blocking_rate); TrieNode test2("window_length"); int window_length = 45; test2.set_value(window_length); schema_path.clear(); schema_path.emplace_back("message_receives_example"); json_test.load_buffer(valid_sample_file, &schema_path[0]); keys.clear(); keys.push_back(&test1); keys.push_back(&test2); res = json_test.set_values(response, keys); REQUIRE(res == 0); keys.clear(); std::string message_string(response); res = json_test.get_values(message_string.c_str(), message_string.length(), response, &test1, keys); REQUIRE(res == 0); REQUIRE(keys.size() == 1); REQUIRE(keys[0]->get_value()->value.i == blocking_rate); keys.clear(); res = json_test.get_values(message_string.c_str(), message_string.length(), response, &test2, keys); REQUIRE(res == 0); REQUIRE(keys.size() == 1); REQUIRE(keys[0]->get_value()->value.i == window_length); } SECTION("Get/Set from buffer "){ int res; std::vector<TrieNode *> keys; std::string message_string; bool enforce = true; int blocking_rate = 10; int trigger_threshold = 5000; int window_length = 25; gen_message(message_string, enforce, blocking_rate, trigger_threshold, window_length); TrieNode test_node("blocking_rate"); blocking_rate = 33; test_node.set_value(blocking_rate); keys.clear(); keys.push_back(&test_node); res = json_test.set_values(message_string.c_str(), message_string.length(), response, keys); REQUIRE(res == 0); keys.clear(); message_string = response; res = json_test.get_values(message_string.c_str(), message_string.length(), response, &test_node, keys); REQUIRE(res == 0); REQUIRE(keys.size() == 1); REQUIRE(keys[0]->get_value()->value.i == blocking_rate); } SECTION("multi-level get/set"){ std::vector<TrieNode *> keys; schema_path.clear(); schema_path.emplace_back("test1"); schema_path.emplace_back(1); schema_path[0].add_child(&schema_path[1]); std::string sample_file = "test-data/test_sample.json"; REQUIRE_THROWS(json_test.load_buffer(sample_file, &schema_path[0])); schema_path.clear(); schema_path.emplace_back("test1"); schema_path.emplace_back(1); schema_path.emplace_back("test4"); schema_path[0].add_child(&schema_path[1]); schema_path[1].add_child(&schema_path[2]); json_test.load_buffer(sample_file, &schema_path[0]); std::string buffer = json_test.get_buffer(); TrieNode test("test5"); keys.clear(); res = json_test.get_values(response, &test, keys); REQUIRE(res == 1); REQUIRE(keys.size() == 1); REQUIRE(keys[0]->get_value()->value.s == "new target"); } }
32.828729
123
0.653989
[ "vector" ]
6ad3b937067355f8362be9fcfbe299432aec4718
8,573
cpp
C++
openstudiocore/src/model/PipeOutdoor.cpp
hellok-coder/OS-Testing
e9e18ad9e99f709a3f992601ed8d2e0662175af4
[ "blessing" ]
1
2019-11-12T02:07:03.000Z
2019-11-12T02:07:03.000Z
openstudiocore/src/model/PipeOutdoor.cpp
hellok-coder/OS-Testing
e9e18ad9e99f709a3f992601ed8d2e0662175af4
[ "blessing" ]
1
2019-02-04T23:30:45.000Z
2019-02-04T23:30:45.000Z
openstudiocore/src/model/PipeOutdoor.cpp
hellok-coder/OS-Testing
e9e18ad9e99f709a3f992601ed8d2e0662175af4
[ "blessing" ]
null
null
null
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other 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: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 "PipeOutdoor.hpp" #include "PipeOutdoor_Impl.hpp" #include "Construction.hpp" #include "Construction_Impl.hpp" #include "Node.hpp" #include "Node_Impl.hpp" #include <utilities/idd/IddEnums.hxx> #include <utilities/idd/OS_Pipe_Outdoor_FieldEnums.hxx> #include "../utilities/core/Assert.hpp" #include "../utilities/units/Unit.hpp" namespace openstudio { namespace model { namespace detail { PipeOutdoor_Impl::PipeOutdoor_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : StraightComponent_Impl(idfObject,model,keepHandle) { OS_ASSERT(idfObject.iddObject().type() == PipeOutdoor::iddObjectType()); } PipeOutdoor_Impl::PipeOutdoor_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : StraightComponent_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == PipeOutdoor::iddObjectType()); } PipeOutdoor_Impl::PipeOutdoor_Impl(const PipeOutdoor_Impl& other, Model_Impl* model, bool keepHandle) : StraightComponent_Impl(other,model,keepHandle) {} const std::vector<std::string>& PipeOutdoor_Impl::outputVariableNames() const { static std::vector<std::string> result{ "Pipe Fluid Heat Transfer Rate", "Pipe Fluid Heat Transfer Energy", "Pipe Mass Flow Rate", "Pipe Inlet Temperature", "Pipe Outlet Temperature", "Pipe Volume Flow Rate" }; return result; } IddObjectType PipeOutdoor_Impl::iddObjectType() const { return PipeOutdoor::iddObjectType(); } unsigned PipeOutdoor_Impl::inletPort() const { return OS_Pipe_OutdoorFields::FluidInletNode; } unsigned PipeOutdoor_Impl::outletPort() const { return OS_Pipe_OutdoorFields::FluidOutletNode; } boost::optional<Construction> PipeOutdoor_Impl::construction() const { return getObject<ModelObject>().getModelObjectTarget<Construction>(OS_Pipe_OutdoorFields::Construction); } boost::optional<Node> PipeOutdoor_Impl::ambientTemperatureOutdoorAirNode() const { return getObject<ModelObject>().getModelObjectTarget<Node>(OS_Pipe_OutdoorFields::AmbientTemperatureOutdoorAirNode); } double PipeOutdoor_Impl::pipeInsideDiameter() const { boost::optional<double> value = getDouble(OS_Pipe_OutdoorFields::PipeInsideDiameter,true); OS_ASSERT(value); return value.get(); } double PipeOutdoor_Impl::pipeLength() const { boost::optional<double> value = getDouble(OS_Pipe_OutdoorFields::PipeLength,true); OS_ASSERT(value); return value.get(); } bool PipeOutdoor_Impl::setConstruction(const boost::optional<Construction>& construction) { bool result(false); if (construction) { result = setPointer(OS_Pipe_OutdoorFields::Construction, construction.get().handle()); } else { resetConstruction(); result = true; } return result; } void PipeOutdoor_Impl::resetConstruction() { bool result = setString(OS_Pipe_OutdoorFields::Construction, ""); OS_ASSERT(result); } bool PipeOutdoor_Impl::setAmbientTemperatureOutdoorAirNode(const boost::optional<Node>& node) { bool result(false); if (node) { result = setPointer(OS_Pipe_OutdoorFields::AmbientTemperatureOutdoorAirNode, node.get().handle()); } else { resetAmbientTemperatureOutdoorAirNode(); result = true; } return result; } void PipeOutdoor_Impl::resetAmbientTemperatureOutdoorAirNode() { bool result = setString(OS_Pipe_OutdoorFields::AmbientTemperatureOutdoorAirNode, ""); OS_ASSERT(result); } bool PipeOutdoor_Impl::setPipeInsideDiameter(double pipeInsideDiameter) { bool result = setDouble(OS_Pipe_OutdoorFields::PipeInsideDiameter, pipeInsideDiameter); return result; } bool PipeOutdoor_Impl::setPipeLength(double pipeLength) { bool result = setDouble(OS_Pipe_OutdoorFields::PipeLength, pipeLength); return result; } bool PipeOutdoor_Impl::addToNode(Node & node) { if(node.plantLoop()) { return StraightComponent_Impl::addToNode(node); } return false; } } // detail PipeOutdoor::PipeOutdoor(const Model& model) : StraightComponent(PipeOutdoor::iddObjectType(),model) { OS_ASSERT(getImpl<detail::PipeOutdoor_Impl>()); bool ok = true; // ok = setHandle(); OS_ASSERT(ok); ok = setPipeInsideDiameter(0.05); OS_ASSERT(ok); ok = setPipeLength(100.0); OS_ASSERT(ok); } IddObjectType PipeOutdoor::iddObjectType() { return IddObjectType(IddObjectType::OS_Pipe_Outdoor); } boost::optional<Construction> PipeOutdoor::construction() const { return getImpl<detail::PipeOutdoor_Impl>()->construction(); } boost::optional<Node> PipeOutdoor::ambientTemperatureOutdoorAirNode() const { return getImpl<detail::PipeOutdoor_Impl>()->ambientTemperatureOutdoorAirNode(); } double PipeOutdoor::pipeInsideDiameter() const { return getImpl<detail::PipeOutdoor_Impl>()->pipeInsideDiameter(); } double PipeOutdoor::pipeLength() const { return getImpl<detail::PipeOutdoor_Impl>()->pipeLength(); } bool PipeOutdoor::setConstruction(const Construction& construction) { return getImpl<detail::PipeOutdoor_Impl>()->setConstruction(construction); } void PipeOutdoor::resetConstruction() { getImpl<detail::PipeOutdoor_Impl>()->resetConstruction(); } bool PipeOutdoor::setAmbientTemperatureOutdoorAirNode(const Node& node) { return getImpl<detail::PipeOutdoor_Impl>()->setAmbientTemperatureOutdoorAirNode(node); } void PipeOutdoor::resetAmbientTemperatureOutdoorAirNode() { getImpl<detail::PipeOutdoor_Impl>()->resetAmbientTemperatureOutdoorAirNode(); } bool PipeOutdoor::setPipeInsideDiameter(double pipeInsideDiameter) { return getImpl<detail::PipeOutdoor_Impl>()->setPipeInsideDiameter(pipeInsideDiameter); } bool PipeOutdoor::setPipeLength(double pipeLength) { return getImpl<detail::PipeOutdoor_Impl>()->setPipeLength(pipeLength); } /// @cond PipeOutdoor::PipeOutdoor(std::shared_ptr<detail::PipeOutdoor_Impl> impl) : StraightComponent(std::move(impl)) {} /// @endcond } // model } // openstudio
35.720833
125
0.714219
[ "vector", "model" ]
6ad73ed7144492fc9d26ce085ac9c71fe075056b
23,636
cc
C++
src/win32/tip/tip_edit_session_impl.cc
phoepsilonix/mozc
3b9135b76247a9fe464cadd1a3c8ea5a07032e0c
[ "BSD-3-Clause" ]
1
2021-04-03T10:08:21.000Z
2021-04-03T10:08:21.000Z
src/win32/tip/tip_edit_session_impl.cc
phoepsilonix/mozc
3b9135b76247a9fe464cadd1a3c8ea5a07032e0c
[ "BSD-3-Clause" ]
null
null
null
src/win32/tip/tip_edit_session_impl.cc
phoepsilonix/mozc
3b9135b76247a9fe464cadd1a3c8ea5a07032e0c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2010-2021, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "win32/tip/tip_edit_session_impl.h" #include <Windows.h> #define _ATL_NO_AUTOMATIC_NAMESPACE #define _WTL_NO_AUTOMATIC_NAMESPACE #include <atlbase.h> #include <atlcom.h> #include <msctf.h> #include <string> #include "base/logging.h" #include "base/util.h" #include "client/client_interface.h" #include "protocol/commands.pb.h" #include "win32/base/conversion_mode_util.h" #include "win32/base/input_state.h" #include "win32/base/string_util.h" #include "win32/tip/tip_composition_util.h" #include "win32/tip/tip_edit_session.h" #include "win32/tip/tip_input_mode_manager.h" #include "win32/tip/tip_private_context.h" #include "win32/tip/tip_range_util.h" #include "win32/tip/tip_status.h" #include "win32/tip/tip_text_service.h" #include "win32/tip/tip_thread_context.h" #include "win32/tip/tip_ui_handler.h" namespace mozc { namespace win32 { namespace tsf { using ATL::CComBSTR; using ATL::CComPtr; using ATL::CComQIPtr; using ATL::CComVariant; using ::mozc::commands::Output; using ::mozc::commands::Preedit; using ::mozc::commands::Result; using ::mozc::commands::SessionCommand; using ::mozc::commands::Status; typedef ::mozc::commands::CompositionMode CompositionMode; typedef ::mozc::commands::Preedit::Segment Segment; typedef ::mozc::commands::Preedit::Segment::Annotation Annotation; namespace { HRESULT SetReadingProperties(ITfContext *context, ITfRange *range, const string &reading_string_utf8, TfEditCookie write_cookie) { HRESULT result = S_OK; // Get out the reading property CComPtr<ITfProperty> reading_property; result = context->GetProperty(GUID_PROP_READING, &reading_property); if (FAILED(result)) { return result; } const std::wstring &canonical_reading_string = StringUtil::KeyToReading(reading_string_utf8); CComVariant reading(CComBSTR(canonical_reading_string.c_str())); result = reading_property->SetValue(write_cookie, range, &reading); if (FAILED(result)) { return result; } return result; } HRESULT ClearReadingProperties(ITfContext *context, ITfRange *range, TfEditCookie write_cookie) { HRESULT result = S_OK; // Get out the reading property CComPtr<ITfProperty> reading_property; result = context->GetProperty(GUID_PROP_READING, &reading_property); if (FAILED(result)) { return result; } // Clear existing attributes. result = reading_property->Clear(write_cookie, range); if (FAILED(result)) { return result; } return result; } CComPtr<ITfComposition> CreateComposition(TipTextService *text_service, ITfContext *context, TfEditCookie write_cookie) { CComQIPtr<ITfContextComposition> composition_context = context; if (!composition_context) { return nullptr; } TfActiveSelEnd sel_end = TF_AE_NONE; CComQIPtr<ITfInsertAtSelection> insert_selection = context; if (!insert_selection) { return nullptr; } CComPtr<ITfRange> insertion_pos; if (FAILED(insert_selection->InsertTextAtSelection( write_cookie, TF_IAS_QUERYONLY, nullptr, 0, &insertion_pos))) { return nullptr; } CComPtr<ITfComposition> composition; if (FAILED(composition_context->StartComposition( write_cookie, insertion_pos, text_service->CreateCompositionSink(context), &composition))) { return nullptr; } return composition; } // Note: Committing a text is a tricky part in TSF/CUAS. Basically it should be // done as following steps. // 1. Create a composition (if not exists). // 2. Replace the text stored in the composition range with the text to be // committed. Note that CUAS updates GCS_RESULTCLAUSE and // GCS_RESULTREADCLAUSE by using the segment structure of GUID_PROP_READING // property. For example, CUAS generates two segments for the following // reading text structure. // "今日は(きょうは)/晴天(せいてん)" // 3. Call ITfComposition::ShiftStart to shrink the composition range. Note // that the text that is pushed out from the composition range is // interpreted as the "committed text". // 4. Update the caret position explicitly. Note that some applications // such as WPF's TextBox do not update the caret position automatically // when an composition is commited. // See also b/8406545 and b/9747361. CComPtr<ITfComposition> CommitText(TipTextService *text_service, ITfContext *context, TfEditCookie write_cookie, CComPtr<ITfComposition> composition, const Output &output) { if (!composition) { composition = CreateComposition(text_service, context, write_cookie); } if (!composition) { return nullptr; } HRESULT result = S_OK; CComPtr<ITfRange> composition_range; result = composition->GetRange(&composition_range); if (FAILED(result)) { return nullptr; } std::wstring result_text; Util::UTF8ToWide(output.result().value(), &result_text); std::wstring composition_text; TipRangeUtil::GetText(composition_range, write_cookie, &composition_text); // Make sure that |composition_text| begins with |result_text| so that // CUAS can generate an appropriate GCS_RESULTREADCLAUSE information. // See b/8406545 if (composition_text.find(result_text) != 0) { result = composition_range->SetText(write_cookie, 0, result_text.c_str(), result_text.size()); if (FAILED(result)) { return nullptr; } result = SetReadingProperties(context, composition_range, output.result().key(), write_cookie); if (FAILED(result)) { return nullptr; } } CComPtr<ITfRange> new_composition_start; result = composition_range->Clone(&new_composition_start); if (FAILED(result)) { return nullptr; } LONG moved = 0; result = new_composition_start->ShiftStart(write_cookie, result_text.size(), &moved, nullptr); if (FAILED(result)) { return nullptr; } result = new_composition_start->Collapse(write_cookie, TF_ANCHOR_START); if (FAILED(result)) { return nullptr; } result = composition->ShiftStart(write_cookie, new_composition_start); if (FAILED(result)) { return nullptr; } // We need to update the caret position manually for WPF's TextBox, where // caret position is not updated automatically when a composition text is // committed by ITfComposition::ShiftStart. result = TipRangeUtil::SetSelection(context, write_cookie, new_composition_start, TF_AE_END); if (FAILED(result)) { return nullptr; } return composition; } HRESULT UpdateComposition(TipTextService *text_service, ITfContext *context, CComPtr<ITfComposition> composition, TfEditCookie write_cookie, const Output &output) { HRESULT result = S_OK; // Clear composition if (composition) { CComPtr<ITfRange> composition_range; result = composition->GetRange(&composition_range); if (FAILED(result)) { return result; } BOOL is_empty = FALSE; result = composition_range->IsEmpty(write_cookie, &is_empty); if (FAILED(result)) { return result; } if (is_empty != TRUE) { std::wstring str; TipRangeUtil::GetText(composition_range, write_cookie, &str); result = composition_range->SetText(write_cookie, 0, L"", 0); if (FAILED(result)) { return result; } result = ClearReadingProperties(context, composition_range, write_cookie); if (FAILED(result)) { return result; } } } if (!output.has_preedit()) { if (composition) { result = composition->EndComposition(write_cookie); if (FAILED(result)) { return result; } } return S_OK; } DCHECK(output.has_preedit()); if (!composition) { CComQIPtr<ITfInsertAtSelection> insert_selection = context; if (!insert_selection) { return E_FAIL; } CComPtr<ITfRange> insertion_pos; result = insert_selection->InsertTextAtSelection( write_cookie, TF_IAS_QUERYONLY, nullptr, 0, &insertion_pos); if (FAILED(result)) { return result; } composition = CreateComposition(text_service, context, write_cookie); } if (!composition) { return E_FAIL; } CComPtr<ITfRange> composition_range; result = composition->GetRange(&composition_range); if (FAILED(result)) { return result; } const Preedit &preedit = output.preedit(); const std::wstring &preedit_text = StringUtil::ComposePreeditText(preedit); result = composition_range->SetText(write_cookie, 0, preedit_text.c_str(), preedit_text.size()); if (FAILED(result)) { return result; } // Get out the display attribute property CComPtr<ITfProperty> display_attribute; result = context->GetProperty(GUID_PROP_ATTRIBUTE, &display_attribute); if (FAILED(result)) { return result; } // Get out the reading property CComPtr<ITfProperty> reading_property; result = context->GetProperty(GUID_PROP_READING, &reading_property); if (FAILED(result)) { return result; } // Set each segment's display attribute int start = 0; int end = 0; for (int i = 0; i < preedit.segment_size(); ++i) { const Preedit::Segment &segment = preedit.segment(i); end = start + Util::WideCharsLen(segment.value()); const Preedit::Segment::Annotation &annotation = segment.annotation(); TfGuidAtom attribute = TF_INVALID_GUIDATOM; if (annotation == Preedit::Segment::UNDERLINE) { attribute = text_service->input_attribute(); } else if (annotation == Preedit::Segment::HIGHLIGHT) { attribute = text_service->converted_attribute(); } else { // mozc::commands::Preedit::Segment::NONE or unknown value continue; } CComPtr<ITfRange> segment_range; result = composition_range->Clone(&segment_range); if (FAILED(result)) { return result; } result = segment_range->Collapse(write_cookie, TF_ANCHOR_START); if (FAILED(result)) { return result; } LONG shift = 0; result = segment_range->ShiftEnd(write_cookie, end, &shift, nullptr); if (FAILED(result)) { return result; } result = segment_range->ShiftStart(write_cookie, start, &shift, nullptr); if (FAILED(result)) { return result; } CComVariant var; // set the value over the range var.vt = VT_I4; var.lVal = attribute; result = display_attribute->SetValue(write_cookie, segment_range, &var); if (segment.has_key()) { const std::wstring &reading_string = StringUtil::KeyToReading(segment.key()); CComVariant reading(CComBSTR(reading_string.c_str())); result = reading_property->SetValue(write_cookie, segment_range, &reading); } start = end; } // Update cursor. { string preedit_text; for (int i = 0; i < preedit.segment_size(); ++i) { preedit_text += preedit.segment(i).value(); } CComPtr<ITfRange> cursor_range; result = composition_range->Clone(&cursor_range); if (FAILED(result)) { return result; } // |output.preedit().cursor()| is in the unit of UTF-32. We need to convert // it to UTF-16 for TSF. const uint32 cursor_pos_utf16 = Util::WideCharsLen( Util::Utf8SubString(preedit_text, 0, preedit.cursor())); result = cursor_range->Collapse(write_cookie, TF_ANCHOR_START); if (FAILED(result)) { return result; } LONG shift = 0; result = cursor_range->ShiftEnd(write_cookie, cursor_pos_utf16, &shift, nullptr); if (FAILED(result)) { return result; } result = cursor_range->ShiftStart(write_cookie, cursor_pos_utf16, &shift, nullptr); if (FAILED(result)) { return result; } result = TipRangeUtil::SetSelection(context, write_cookie, cursor_range, TF_AE_END); } return result; } HRESULT UpdatePrivateContext(TipTextService *text_service, ITfContext *context, TfEditCookie write_cookie, const Output &output) { TipPrivateContext *private_context = text_service->GetPrivateContext(context); if (private_context == nullptr) { return S_FALSE; } private_context->mutable_last_output()->CopyFrom(output); if (!output.has_status()) { return S_FALSE; } const Status &status = output.status(); TipInputModeManager *input_mode_manager = text_service->GetThreadContext()->GetInputModeManager(); const TipInputModeManager::NotifyActionSet action_set = input_mode_manager->OnReceiveCommand( status.activated(), status.comeback_mode(), status.mode()); if ((action_set & TipInputModeManager::kNotifySystemOpenClose) == TipInputModeManager::kNotifySystemOpenClose) { TipStatus::SetIMEOpen(text_service->GetThreadManager(), text_service->GetClientID(), input_mode_manager->GetEffectiveOpenClose()); } if ((action_set & TipInputModeManager::kNotifySystemConversionMode) == TipInputModeManager::kNotifySystemConversionMode) { const CompositionMode mozc_mode = static_cast<CompositionMode>( input_mode_manager->GetEffectiveConversionMode()); uint32 native_mode = 0; if (ConversionModeUtil::ToNativeMode( mozc_mode, private_context->input_behavior().prefer_kana_input, &native_mode)) { TipStatus::SetInputModeConversion(text_service->GetThreadManager(), text_service->GetClientID(), native_mode); } } return S_OK; } HRESULT UpdatePreeditAndComposition(TipTextService *text_service, ITfContext *context, TfEditCookie write_cookie, const Output &output) { CComPtr<ITfComposition> composition = CComQIPtr<ITfComposition>( TipCompositionUtil::GetComposition(context, write_cookie)); // Clear the display attributes first. if (composition) { const HRESULT result = TipCompositionUtil::ClearDisplayAttributes( context, composition, write_cookie); if (FAILED(result)) { return result; } } if (output.has_result()) { CComPtr<ITfComposition> new_composition = CommitText(text_service, context, write_cookie, composition, output); composition = new_composition; if (!new_composition) { return E_FAIL; } } return UpdateComposition(text_service, context, composition, write_cookie, output); } HRESULT DoEditSessionInComposition(TipTextService *text_service, ITfContext *context, TfEditCookie write_cookie, const Output &output) { const HRESULT result = UpdatePrivateContext(text_service, context, write_cookie, output); if (FAILED(result)) { return result; } return UpdatePreeditAndComposition(text_service, context, write_cookie, output); } HRESULT DoEditSessionAfterComposition(TipTextService *text_service, ITfContext *context, TfEditCookie write_cookie, const Output &output) { return UpdatePrivateContext(text_service, context, write_cookie, output); } HRESULT OnEndEditImpl(TipTextService *text_service, ITfContext *context, TfEditCookie write_cookie, ITfEditRecord *edit_record, bool *update_ui) { bool dummy_bool = false; if (update_ui == nullptr) { update_ui = &dummy_bool; } *update_ui = false; HRESULT result = S_OK; { CComPtr<ITfRange> selection_range; TfActiveSelEnd active_sel_end = TF_AE_NONE; result = TipRangeUtil::GetDefaultSelection( context, write_cookie, &selection_range, &active_sel_end); if (FAILED(result)) { return result; } std::vector<InputScope> input_scopes; result = TipRangeUtil::GetInputScopes(selection_range, write_cookie, &input_scopes); TipInputModeManager *input_mode_manager = text_service->GetThreadContext()->GetInputModeManager(); const auto actions = input_mode_manager->OnChangeInputScope(input_scopes); if (actions == TipInputModeManager::kUpdateUI) { *update_ui = true; } // If the indicator is visible, update UI just in case. if (input_mode_manager->IsIndicatorVisible()) { *update_ui = true; } } CComPtr<ITfCompositionView> composition_view = TipCompositionUtil::GetComposition(context, write_cookie); if (!composition_view) { // If there is no composition, nothing to check. return S_OK; } CComPtr<ITfComposition> composition; result = composition_view.QueryInterface(&composition); if (FAILED(result)) { return result; } if (!composition) { // Nothing to do. return S_OK; } CComPtr<ITfRange> composition_range; result = composition->GetRange(&composition_range); if (FAILED(result)) { return result; } BOOL selection_changed = FALSE; result = edit_record->GetSelectionStatus(&selection_changed); if (FAILED(result)) { return result; } if (selection_changed) { // When the selection is changed, make sure the new selection range is // covered by the composition range. Otherwise, terminate the composition. CComPtr<ITfRange> selected_range; TfActiveSelEnd active_sel_end = TF_AE_NONE; result = TipRangeUtil::GetDefaultSelection( context, write_cookie, &selected_range, &active_sel_end); if (FAILED(result)) { return result; } if (!TipRangeUtil::IsRangeCovered(write_cookie, selected_range, composition_range)) { // We enqueue another edit session to sync the composition state between // the application and Mozc server because we are already in // ITfTextEditSink::OnEndEdit and some operations (e.g., // ITfComposition::EndComposition) result in failure in this edit // session. result = TipEditSession::SubmitAsync(text_service, context); if (FAILED(result)) { return result; } // Cancels further operations. return S_OK; } } BOOL is_empty = FALSE; result = composition_range->IsEmpty(write_cookie, &is_empty); if (FAILED(result)) { return result; } if (is_empty) { // When the composition range is empty, we assume the composition is // canceled by the application or something. Actually CUAS does this when // it receives NI_COMPOSITIONSTR/CPS_CANCEL. You can see this as Excel's // auto-completion. If this happens, send REVERT command to the server to // keep the state consistent. See b/1793331 for details. // We enqueue another edit session to sync the composition state between // the application and Mozc server because we are already in // ITfTextEditSink::OnEndEdit and some operations (e.g., // ITfComposition::EndComposition) result in failure in this edit session. result = TipEditSession::CancelCompositionAsync(text_service, context); *update_ui = false; if (FAILED(result)) { return result; } } return S_OK; } } // namespace HRESULT TipEditSessionImpl::OnEndEdit(TipTextService *text_service, ITfContext *context, TfEditCookie write_cookie, ITfEditRecord *edit_record) { bool update_ui = false; const HRESULT result = OnEndEditImpl(text_service, context, write_cookie, edit_record, &update_ui); if (update_ui) { TipEditSessionImpl::UpdateUI(text_service, context, write_cookie); } return result; } HRESULT TipEditSessionImpl::OnCompositionTerminated( TipTextService *text_service, ITfContext *context, ITfComposition *composition, TfEditCookie write_cookie) { if (text_service == nullptr) { return E_FAIL; } if (context == nullptr) { return E_FAIL; } // Clear the display attributes first. if (composition) { const HRESULT result = TipCompositionUtil::ClearDisplayAttributes( context, composition, write_cookie); if (FAILED(result)) { return result; } } SessionCommand command; command.set_type(SessionCommand::SUBMIT); Output output; TipPrivateContext *private_context = text_service->GetPrivateContext(context); if (private_context == nullptr) { return E_FAIL; } if (!private_context->GetClient()->SendCommand(command, &output)) { return E_FAIL; } const HRESULT result = DoEditSessionAfterComposition(text_service, context, write_cookie, output); UpdateUI(text_service, context, write_cookie); return result; } HRESULT TipEditSessionImpl::UpdateContext(TipTextService *text_service, ITfContext *context, TfEditCookie write_cookie, const commands::Output &output) { const HRESULT result = DoEditSessionInComposition(text_service, context, write_cookie, output); UpdateUI(text_service, context, write_cookie); return result; } void TipEditSessionImpl::UpdateUI(TipTextService *text_service, ITfContext *context, TfEditCookie read_cookie) { TipUiHandler::Update(text_service, context, read_cookie); } } // namespace tsf } // namespace win32 } // namespace mozc
34.964497
80
0.669403
[ "vector" ]
6ad84a843b6b71e141ce3c085a870f56f33c55a8
4,318
cc
C++
test/priors.cc
TeoGiane/bayesmix
43182d61c3f332aefb832426cc9e8e2b2394bd68
[ "BSD-3-Clause" ]
null
null
null
test/priors.cc
TeoGiane/bayesmix
43182d61c3f332aefb832426cc9e8e2b2394bd68
[ "BSD-3-Clause" ]
null
null
null
test/priors.cc
TeoGiane/bayesmix
43182d61c3f332aefb832426cc9e8e2b2394bd68
[ "BSD-3-Clause" ]
1
2022-02-11T09:03:46.000Z
2022-02-11T09:03:46.000Z
#include <google/protobuf/stubs/casts.h> #include <gtest/gtest.h> #include <memory> #include "algorithm_state.pb.h" #include "src/hierarchies/nnig_hierarchy.h" #include "src/hierarchies/nnw_hierarchy.h" #include "src/mixings/dirichlet_mixing.h" #include "src/utils/proto_utils.h" TEST(mixing, fixed_value) { DirichletMixing mix; bayesmix::DPPrior prior; double m = 2.0; prior.mutable_fixed_value()->set_totalmass(m); double m_state = prior.fixed_value().totalmass(); ASSERT_DOUBLE_EQ(m, m_state); mix.get_mutable_prior()->CopyFrom(prior); mix.initialize(); double m_mix = mix.get_state().totalmass; ASSERT_DOUBLE_EQ(m, m_mix); std::vector<std::shared_ptr<AbstractHierarchy>> hiers(100); unsigned int n_data = 1000; mix.update_state(hiers, std::vector<unsigned int>(n_data)); double m_mix_after = mix.get_state().totalmass; ASSERT_DOUBLE_EQ(m, m_mix_after); } TEST(mixing, gamma_prior) { DirichletMixing mix; bayesmix::DPPrior prior; double alpha = 1.0; double beta = 2.0; double m_prior = alpha / beta; prior.mutable_gamma_prior()->mutable_totalmass_prior()->set_shape(alpha); prior.mutable_gamma_prior()->mutable_totalmass_prior()->set_rate(beta); mix.get_mutable_prior()->CopyFrom(prior); mix.initialize(); double m_mix = mix.get_state().totalmass; ASSERT_DOUBLE_EQ(m_prior, m_mix); std::vector<std::shared_ptr<AbstractHierarchy>> hiers(100); unsigned int n_data = 1000; mix.update_state(hiers, std::vector<unsigned int>(n_data)); double m_mix_after = mix.get_state().totalmass; std::cout << " after = " << m_mix_after << std::endl; ASSERT_TRUE(m_mix_after > m_mix); } TEST(hierarchies, fixed_values) { bayesmix::NNIGPrior prior; bayesmix::AlgorithmState::HierarchyHypers prior_out; prior.mutable_fixed_values()->set_mean(5.0); prior.mutable_fixed_values()->set_var_scaling(0.1); prior.mutable_fixed_values()->set_shape(2.0); prior.mutable_fixed_values()->set_scale(2.0); auto hier = std::make_shared<NNIGHierarchy>(); hier->get_mutable_prior()->CopyFrom(prior); hier->initialize(); std::vector<std::shared_ptr<AbstractHierarchy>> unique_values; std::vector<bayesmix::AlgorithmState::ClusterState> states; // Check equality before update unique_values.push_back(hier); for (size_t i = 1; i < 4; i++) { unique_values.push_back(hier->clone()); unique_values[i]->write_hypers_to_proto(&prior_out); ASSERT_EQ(prior.fixed_values().DebugString(), prior_out.nnig_state().DebugString()); } // Check equality after update unique_values[0]->update_hypers(states); unique_values[0]->write_hypers_to_proto(&prior_out); for (size_t i = 1; i < 4; i++) { unique_values[i]->write_hypers_to_proto(&prior_out); ASSERT_EQ(prior.fixed_values().DebugString(), prior_out.nnig_state().DebugString()); } } TEST(hierarchies, normal_mean_prior) { bayesmix::NNWPrior prior; bayesmix::AlgorithmState::HierarchyHypers prior_out; Eigen::Vector2d mu00; mu00 << 0.0, 0.0; auto ident = Eigen::Matrix2d::Identity(); prior.mutable_normal_mean_prior()->set_var_scaling(0.1); bayesmix::to_proto( mu00, prior.mutable_normal_mean_prior()->mutable_mean_prior()->mutable_mean()); bayesmix::to_proto( ident, prior.mutable_normal_mean_prior()->mutable_mean_prior()->mutable_var()); prior.mutable_normal_mean_prior()->set_deg_free(2.0); bayesmix::to_proto(ident, prior.mutable_normal_mean_prior()->mutable_scale()); std::vector<bayesmix::AlgorithmState::ClusterState> states(4); for (int i = 0; i < states.size(); i++) { double mean = 9.0 + i; Eigen::Vector2d vec; vec << mean, mean; bayesmix::to_proto(vec, states[i].mutable_multi_ls_state()->mutable_mean()); bayesmix::to_proto(ident, states[i].mutable_multi_ls_state()->mutable_prec()); } NNWHierarchy hier; hier.get_mutable_prior()->CopyFrom(prior); hier.initialize(); hier.update_hypers(states); hier.write_hypers_to_proto(&prior_out); Eigen::Vector2d mean_out = bayesmix::to_eigen(prior_out.nnw_state().mean()); std::cout << " after = " << mean_out(0) << " " << mean_out(1) << std::endl; assert(mu00(0) < mean_out(0) && mu00(1) < mean_out(1)); }
34
79
0.699861
[ "vector" ]
6adc4aaa5145f53edde2cd41c7653bfd6e68a78a
14,040
hxx
C++
Components/Metrics/StatisticalShapePenalty/elxStatisticalShapePenalty.hxx
dzenanz/elastix
10fcb451080b272aecb2b58e7f174d693acaf079
[ "Apache-2.0" ]
null
null
null
Components/Metrics/StatisticalShapePenalty/elxStatisticalShapePenalty.hxx
dzenanz/elastix
10fcb451080b272aecb2b58e7f174d693acaf079
[ "Apache-2.0" ]
null
null
null
Components/Metrics/StatisticalShapePenalty/elxStatisticalShapePenalty.hxx
dzenanz/elastix
10fcb451080b272aecb2b58e7f174d693acaf079
[ "Apache-2.0" ]
1
2021-01-16T08:59:39.000Z
2021-01-16T08:59:39.000Z
/*========================================================================= * * Copyright UMC Utrecht and contributors * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __elxStatisticalShapePenalty_HXX__ #define __elxStatisticalShapePenalty_HXX__ #include "elxStatisticalShapePenalty.h" #include "itkTransformixInputPointFileReader.h" #include "itkPointSet.h" #include "itkDefaultStaticMeshTraits.h" #include "itkVTKPolyDataReader.h" #include "itkVTKPolyDataWriter.h" #include "itkTransformMeshFilter.h" #include <itkMesh.h> #include <typeinfo> namespace elastix { /** * ******************* Initialize *********************** */ template< class TElastix > void StatisticalShapePenalty< TElastix > ::Initialize( void ) throw ( ExceptionObject ) { itk::TimeProbe timer; timer.Start(); this->Superclass1::Initialize(); timer.Stop(); elxout << "Initialization of StatisticalShape metric took: " << static_cast< long >( timer.GetMean() * 1000 ) << " ms." << std::endl; } // end Initialize() /** * ***************** BeforeRegistration *********************** */ template< class TElastix > void StatisticalShapePenalty< TElastix > ::BeforeRegistration( void ) { /** Get and set NormalizedShapeModel. Default TRUE. */ bool normalizedShapeModel = true; this->GetConfiguration()->ReadParameter( normalizedShapeModel, "NormalizedShapeModel", 0, 0 ); this->SetNormalizedShapeModel( normalizedShapeModel ); /** Get and set NormalizedShapeModel. Default TRUE. */ int shapeModelCalculation = 0; this->GetConfiguration()->ReadParameter( shapeModelCalculation, "ShapeModelCalculation", 0, 0 ); this->SetShapeModelCalculation( shapeModelCalculation ); /** Read and set the fixed pointset. */ std::string fixedName = this->GetConfiguration()->GetCommandLineArgument( "-fp" ); typename PointSetType::Pointer fixedPointSet = 0; const typename ImageType::ConstPointer fixedImage = this->GetElastix()->GetFixedImage(); const unsigned int nrOfFixedPoints = this->ReadShape( fixedName, fixedPointSet, fixedImage ); this->SetFixedPointSet( fixedPointSet ); // itkCombinationImageToImageMetric.hxx checks if metric base class is ImageMetricType or PointSetMetricType. // This class is derived from SingleValuedPointSetToPointSetMetric which needs a moving pointset. this->SetMovingPointSet( fixedPointSet ); // TODO: make itkCombinationImageToImageMetric check for a base class metric that doesn't use an image or moving pointset. /** Read meanVector filename. */ std::string meanVectorName = this->GetConfiguration()->GetCommandLineArgument( "-mean" ); vcl_ifstream datafile; vnl_vector< double > * const meanVector = new vnl_vector< double >(); datafile.open( meanVectorName.c_str() ); if( datafile.is_open() ) { meanVector->read_ascii( datafile ); datafile.close(); datafile.clear(); elxout << " meanVector " << meanVectorName << " read" << std::endl; } else { itkExceptionMacro( << "Unable to open meanVector file: " << meanVectorName ); } this->SetMeanVector( meanVector ); /** Check. */ if( normalizedShapeModel ) { if( nrOfFixedPoints * Self::FixedPointSetDimension != meanVector->size() - Self::FixedPointSetDimension - 1 ) { itkExceptionMacro( << "ERROR: the number of elements in the meanVector (" << meanVector->size() << ") does not match the number of points of the fixed pointset (" << nrOfFixedPoints << ") times the point dimensionality (" << Self::FixedPointSetDimension << ") plus a Centroid of dimension " << Self::FixedPointSetDimension << " plus a size element" ); } } else { if( nrOfFixedPoints * Self::FixedPointSetDimension != meanVector->size() ) { itkExceptionMacro( << "ERROR: the number of elements in the meanVector (" << meanVector->size() << ") does not match the number of points of the fixed pointset (" << nrOfFixedPoints << ") times the point dimensionality (" << Self::FixedPointSetDimension << ")" ); } } /** Read covariance matrix filename. */ std::string covarianceMatrixName = this->GetConfiguration()->GetCommandLineArgument( "-covariance" ); vnl_matrix< double > * const covarianceMatrix = new vnl_matrix< double >(); datafile.open( covarianceMatrixName.c_str() ); if( datafile.is_open() ) { covarianceMatrix->read_ascii( datafile ); datafile.close(); datafile.clear(); elxout << "covarianceMatrix " << covarianceMatrixName << " read" << std::endl; } else { itkExceptionMacro( << "Unable to open covarianceMatrix file: " << covarianceMatrixName ); } this->SetCovarianceMatrix( covarianceMatrix ); /** Read eigenvector matrix filename. */ std::string eigenVectorsName = this->GetConfiguration()->GetCommandLineArgument( "-evectors" ); vnl_matrix< double > * const eigenVectors = new vnl_matrix< double >(); datafile.open( eigenVectorsName.c_str() ); if( datafile.is_open() ) { eigenVectors->read_ascii( datafile ); datafile.close(); datafile.clear(); elxout << "eigenvectormatrix " << eigenVectorsName << " read" << std::endl; } else { // \todo: remove outcommented code: //itkExceptionMacro( << "Unable to open EigenVectors file: " << eigenVectorsName); } this->SetEigenVectors( eigenVectors ); /** Read eigenvalue vector filename. */ std::string eigenValuesName = this->GetConfiguration()->GetCommandLineArgument( "-evalues" ); vnl_vector< double > * const eigenValues = new vnl_vector< double >(); datafile.open( eigenValuesName.c_str() ); if( datafile.is_open() ) { eigenValues->read_ascii( datafile ); datafile.close(); datafile.clear(); elxout << "eigenvaluevector " << eigenValuesName << " read" << std::endl; } else { //itkExceptionMacro( << "Unable to open EigenValues file: " << eigenValuesName); } this->SetEigenValues( eigenValues ); } // end BeforeRegistration() /** * ***************** BeforeEachResolution *********************** */ template< class TElastix > void StatisticalShapePenalty< TElastix > ::BeforeEachResolution( void ) { /** Get the current resolution level. */ unsigned int level = this->m_Registration->GetAsITKBaseType()->GetCurrentLevel(); /** Get and set ShrinkageIntensity. Default 0.5. */ double shrinkageIntensity = 0.5; this->GetConfiguration()->ReadParameter( shrinkageIntensity, "ShrinkageIntensity", this->GetComponentLabel(), level, 0 ); if( this->GetShrinkageIntensity() != shrinkageIntensity ) { this->SetShrinkageIntensityNeedsUpdate( true ); } this->SetShrinkageIntensity( shrinkageIntensity ); /** Get and set BaseVariance. Default 1000. */ double baseVariance = 1000; this->GetConfiguration()->ReadParameter( baseVariance, "BaseVariance", this->GetComponentLabel(), level, 0 ); if( this->GetBaseVariance() != baseVariance ) { this->SetBaseVarianceNeedsUpdate( true ); } this->SetBaseVariance( baseVariance ); /** Get and set CentroidXVariance. Default 10. */ double centroidXVariance = 10; this->GetConfiguration()->ReadParameter( centroidXVariance, "CentroidXVariance", this->GetComponentLabel(), level, 0 ); if( this->GetCentroidXVariance() != centroidXVariance ) { this->SetVariancesNeedsUpdate( true ); } this->SetCentroidXVariance( centroidXVariance ); /** Get and set CentroidYVariance. Default 10. */ double centroidYVariance = 10; this->GetConfiguration()->ReadParameter( centroidYVariance, "CentroidYVariance", this->GetComponentLabel(), level, 0 ); if( this->GetCentroidYVariance() != centroidYVariance ) { this->SetVariancesNeedsUpdate( true ); } this->SetCentroidYVariance( centroidYVariance ); /** Get and set CentroidZVariance. Default 10. */ double centroidZVariance = 10; this->GetConfiguration()->ReadParameter( centroidZVariance, "CentroidZVariance", this->GetComponentLabel(), level, 0 ); if( this->GetCentroidZVariance() != centroidZVariance ) { this->SetVariancesNeedsUpdate( true ); } this->SetCentroidZVariance( centroidZVariance ); /** Get and set SizeVariance. Default 10. */ double sizeVariance = 10; this->GetConfiguration()->ReadParameter( sizeVariance, "SizeVariance", this->GetComponentLabel(), level, 0 ); if( this->GetSizeVariance() != sizeVariance ) { this->SetVariancesNeedsUpdate( true ); } this->SetSizeVariance( sizeVariance ); /** Get and set CutOffValue. Default 0. */ double cutOffValue = 0; this->GetConfiguration()->ReadParameter( cutOffValue, "CutOffValue", this->GetComponentLabel(), level, 0 ); this->SetCutOffValue( cutOffValue ); /** Get and set CutOffSharpness. Default 2. */ double cutOffSharpness = 2.0; this->GetConfiguration()->ReadParameter( cutOffSharpness, "CutOffSharpness", this->GetComponentLabel(), level, 0 ); this->SetCutOffSharpness( cutOffSharpness ); } // end BeforeEachResolution() /** * ***************** ReadLandmarks *********************** */ template< class TElastix > unsigned int StatisticalShapePenalty< TElastix > ::ReadLandmarks( const std::string & landmarkFileName, typename PointSetType::Pointer & pointSet, const typename ImageType::ConstPointer image ) { /** Typedefs. */ typedef typename ImageType::IndexType IndexType; typedef typename ImageType::IndexValueType IndexValueType; typedef typename ImageType::PointType PointType; typedef itk::TransformixInputPointFileReader< PointSetType > PointSetReaderType; elxout << "Loading landmarks for " << this->GetComponentLabel() << ":" << this->elxGetClassName() << "." << std::endl; /** Read the landmarks. */ typename PointSetReaderType::Pointer reader = PointSetReaderType::New(); reader->SetFileName( landmarkFileName.c_str() ); elxout << " Reading landmark file: " << landmarkFileName << std::endl; try { reader->Update(); } catch( itk::ExceptionObject & err ) { xl::xout[ "error" ] << " Error while opening " << landmarkFileName << std::endl; xl::xout[ "error" ] << err << std::endl; itkExceptionMacro( << "ERROR: unable to configure " << this->GetComponentLabel() ); } /** Some user-feedback. */ const unsigned int nrofpoints = reader->GetNumberOfPoints(); if( reader->GetPointsAreIndices() ) { elxout << " Landmarks are specified as image indices." << std::endl; } else { elxout << " Landmarks are specified in world coordinates." << std::endl; } elxout << " Number of specified points: " << nrofpoints << std::endl; /** Get the pointset. */ pointSet = reader->GetOutput(); /** Convert from index to point if necessary */ pointSet->DisconnectPipeline(); if( reader->GetPointsAreIndices() ) { /** Convert to world coordinates */ for( unsigned int j = 0; j < nrofpoints; ++j ) { /** The landmarks from the pointSet are indices. We first cast to the * proper type, and then convert it to world coordinates. */ PointType point; IndexType index; pointSet->GetPoint( j, &point ); for( unsigned int d = 0; d < FixedImageDimension; ++d ) { index[ d ] = static_cast< IndexValueType >( vnl_math_rnd( point[ d ] ) ); } /** Compute the input point in physical coordinates. */ image->TransformIndexToPhysicalPoint( index, point ); pointSet->SetPoint( j, point ); } // end for all points } // end for points are indices return nrofpoints; } // end ReadLandmarks() /** * ************** TransformPointsSomePointsVTK ********************* */ template< class TElastix > unsigned int StatisticalShapePenalty< TElastix > ::ReadShape( const std::string & ShapeFileName, typename PointSetType::Pointer & pointSet, const typename ImageType::ConstPointer image ) { /** Typedef's. \todo test DummyIPPPixelType=bool. */ typedef double DummyIPPPixelType; typedef DefaultStaticMeshTraits< DummyIPPPixelType, FixedImageDimension, FixedImageDimension, CoordRepType > MeshTraitsType; typedef Mesh< DummyIPPPixelType, FixedImageDimension, MeshTraitsType > MeshType; typedef VTKPolyDataReader< MeshType > MeshReaderType; /** Read the input points. */ typename MeshReaderType::Pointer meshReader = MeshReaderType::New(); meshReader->SetFileName( ShapeFileName.c_str() ); elxout << " Reading input point file: " << ShapeFileName << std::endl; try { meshReader->Update(); } catch( ExceptionObject & err ) { xl::xout[ "error" ] << " Error while opening input point file." << std::endl; xl::xout[ "error" ] << err << std::endl; } /** Some user-feedback. */ elxout << " Input points are specified in world coordinates." << std::endl; unsigned long nrofpoints = meshReader->GetOutput()->GetNumberOfPoints(); elxout << " Number of specified input points: " << nrofpoints << std::endl; typename MeshType::Pointer mesh = meshReader->GetOutput(); pointSet = PointSetType::New(); pointSet->SetPoints( mesh->GetPoints() ); return nrofpoints; } // end ReadShape() } // end namespace elastix #endif // end #ifndef __elxStatisticalShapePenalty_HXX__
34.07767
124
0.665527
[ "mesh", "vector" ]
6adc6ee5bc3f1e14652b29ebcde096c55db987f9
3,079
cpp
C++
damc_common/Osc/OscFlatArray.cpp
amurzeau/waveplay
e0fc097137138c4a6985998db502468074bf739f
[ "MIT" ]
5
2021-10-02T03:01:56.000Z
2022-01-24T20:59:19.000Z
damc_common/Osc/OscFlatArray.cpp
amurzeau/waveplay
e0fc097137138c4a6985998db502468074bf739f
[ "MIT" ]
null
null
null
damc_common/Osc/OscFlatArray.cpp
amurzeau/waveplay
e0fc097137138c4a6985998db502468074bf739f
[ "MIT" ]
null
null
null
#include "OscFlatArray.h" #include "OscRoot.h" #include <algorithm> #include <spdlog/spdlog.h> #include <type_traits> EXPLICIT_INSTANCIATE_OSC_VARIABLE(template, OscFlatArray); template<typename T> OscFlatArray<T>::OscFlatArray(OscContainer* parent, std::string name) noexcept : OscContainer(parent, name) { this->getRoot()->addPendingConfigNode(this); } template<typename T> const std::vector<T>& OscFlatArray<T>::getData() const { return values; } template<typename T> bool OscFlatArray<T>::setData(const std::vector<T>& newData) { return updateData([&newData](std::vector<T>& data) { data = newData; }); } template<typename T> bool OscFlatArray<T>::setData(std::vector<T>&& newData) { return updateData([newData = std::move(newData)](std::vector<T>& data) { data = std::move(newData); }); } template<typename T> std::string OscFlatArray<T>::getAsString() const { std::string result = "["; for(const auto& item : values) { if constexpr(std::is_same_v<T, std::string>) { result += " \"" + item + "\","; } else { result += " " + std::to_string(item) + ","; } } if(result.back() == ',') result.pop_back(); return result + " ]"; } template<typename T> void OscFlatArray<T>::execute(const std::vector<OscArgument>& arguments) { auto oldValues = values; updateData( [this, &arguments](std::vector<T>& data) { data.clear(); for(const auto& arg : arguments) { T v; if(this->template getArgumentAs<T>(arg, v)) { data.push_back(v); } } }, true); } template<typename T> void OscFlatArray<T>::addCheckCallback(std::function<bool(const std::vector<T>&)> checkCallback) { checkCallbacks.push_back(checkCallback); checkCallback(this->getData()); } template<typename T> void OscFlatArray<T>::addChangeCallback(std::function<void(const std::vector<T>&, const std::vector<T>&)> onChange) { this->onChangeCallbacks.push_back(onChange); onChange({}, values); } template<typename T> bool OscFlatArray<T>::callCheckCallbacks(const std::vector<T>& v) { bool isDataValid = true; for(auto& callback : checkCallbacks) { isDataValid = isDataValid && callback(v); } return isDataValid; } template<typename T> void OscFlatArray<T>::notifyOsc() { std::vector<OscArgument> valueToSend; valueToSend.reserve(values.size()); for(const auto& v : values) { valueToSend.push_back(v); } sendMessage(&valueToSend[0], valueToSend.size()); } template<typename T> bool OscFlatArray<T>::checkData(const std::vector<T>& savedValues, bool fromOsc) { if(values != savedValues) { bool isDataValid = callCheckCallbacks(values); if(isDataValid) { for(auto& callback : onChangeCallbacks) { callback(savedValues, values); } if(!fromOsc || getRoot()->isOscValueAuthority()) notifyOsc(); getRoot()->notifyValueChanged(); return true; } else { SPDLOG_WARN("{}: refused invalid value", getFullAddress()); values = savedValues; if(fromOsc) { // Ensure the client that set this is notified that the value didn't changed notifyOsc(); } } } return false; }
27.008772
119
0.680741
[ "vector" ]
6adf67636cfb53bfd90fa9c301b298c420a4de57
3,009
cpp
C++
python/dartpy/dynamics/module.cpp
JShep1/dart
0ed33f028386bf5f2cdfe52858a6042ae8b45c38
[ "BSD-2-Clause" ]
null
null
null
python/dartpy/dynamics/module.cpp
JShep1/dart
0ed33f028386bf5f2cdfe52858a6042ae8b45c38
[ "BSD-2-Clause" ]
null
null
null
python/dartpy/dynamics/module.cpp
JShep1/dart
0ed33f028386bf5f2cdfe52858a6042ae8b45c38
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2011-2019, The DART development contributors * All rights reserved. * * The list of contributors can be found at: * https://github.com/dartsim/dart/blob/master/LICENSE * * This file is provided under the following "BSD-style" License: * 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 <pybind11/pybind11.h> namespace dart { namespace python { void Shape(pybind11::module& sm); void Entity(pybind11::module& sm); void Frame(pybind11::module& sm); void ShapeFrame(pybind11::module& sm); void SimpleFrame(pybind11::module& sm); void Node(pybind11::module& sm); void JacobianNode(pybind11::module& sm); void ShapeNode(pybind11::module& sm); void DegreeOfFreedom(pybind11::module& sm); void BodyNode(pybind11::module& sm); void Joint(pybind11::module& sm); void GenericJoint(pybind11::module& sm); void RevoluteJoint(pybind11::module& sm); void BallJoint(pybind11::module& sm); void FreeJoint(pybind11::module& sm); void MetaSkeleton(pybind11::module& sm); void ReferentialSkeleton(pybind11::module& sm); void Linkage(pybind11::module& sm); void Chain(pybind11::module& sm); void Skeleton(pybind11::module& sm); void InverseKinematics(pybind11::module& sm); void dart_dynamics(pybind11::module& m) { auto sm = m.def_submodule("dynamics"); Shape(sm); Entity(sm); Frame(sm); ShapeFrame(sm); SimpleFrame(sm); Node(sm); JacobianNode(sm); ShapeNode(sm); DegreeOfFreedom(sm); BodyNode(sm); Joint(sm); GenericJoint(sm); RevoluteJoint(sm); BallJoint(sm); FreeJoint(sm); MetaSkeleton(sm); ReferentialSkeleton(sm); Linkage(sm); Chain(sm); Skeleton(sm); InverseKinematics(sm); } } // namespace python } // namespace dart
29.213592
70
0.732469
[ "shape" ]
6ae00448663dfa702093d717fcaf88c4f0c232b9
37,759
cpp
C++
Training CD/IDA Pro/IDA Plug-ins/Selected Plugin Source Code/Loop Detection/loop_detection.cpp
phoemark2o20/Malware-Analysis-Training
0706a1fd74be666e9ec1de0946afa0d1e161491d
[ "MIT" ]
872
2020-02-19T20:26:46.000Z
2022-03-31T02:32:46.000Z
Training CD/IDA Pro/IDA Plug-ins/Selected Plugin Source Code/Loop Detection/loop_detection.cpp
youngyt/Malware-Analysis-Training
0a301951ed82346b39fb9840ecae393e2d60723c
[ "MIT" ]
1
2020-02-23T03:37:16.000Z
2020-03-17T20:05:56.000Z
Training CD/IDA Pro/IDA Plug-ins/Selected Plugin Source Code/Loop Detection/loop_detection.cpp
youngyt/Malware-Analysis-Training
0a301951ed82346b39fb9840ecae393e2d60723c
[ "MIT" ]
161
2020-02-19T21:06:31.000Z
2022-03-23T14:49:29.000Z
// loop_detection.cpp: implementation of the loop_detection class. // ////////////////////////////////////////////////////////////////////// #define USE_DANGEROUS_FUNCTIONS #include "loop_detection.h" //#include "function_analyzer.h" #include "color_palette.h" #include <ida.hpp> #include <idp.hpp> #include <bytes.hpp> #include <expr.hpp> #include <frame.hpp> #include <gdl.hpp> #include <kernwin.hpp> #include <loader.hpp> #include <md5.h> #include <name.hpp> #include <ua.hpp> #include <struct.hpp> ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // loop_detection() // // inititalizes the base class. And this instance // // arguments: fid - function id. // returns: none // loop_detection::loop_detection(int fid) : function_analyzer(fid) { constructor(); } ///////////////////////////////////////////////////////////////////////////////////////// // loop_detection() // // inititalizes the base class. And this instance // // arguments: ea - ea of the function. // returns: none // loop_detection::loop_detection(ea_t ea) : function_analyzer(ea) { constructor(); } ///////////////////////////////////////////////////////////////////////////////////////// // loop_detection() // // inititalizes the base class. And this instance // // arguments: ea - ea of the function. // returns: none // loop_detection::loop_detection(func_t * fptr) : function_analyzer(fptr) { constructor(); } ///////////////////////////////////////////////////////////////////////////////////////// // loop_detection() // // destructor // // arguments: none // returns: none // loop_detection::~loop_detection() { } ///////////////////////////////////////////////////////////////////////////////////////// // find_loop() // // runs the analysis on the current function. // // arguments: ea_t master - master would be the entry point of the node // ea_t slave - is the node that links back to the head // returns: none. // int loop_detection::find_loop(ea_t master, ea_t slave) { ea_t ea; ea_t master_src = find_src(master); ea_t slave_src = find_src(slave); ea_t frag; int i = 0; int bFrag = 0; int num_ref = get_num_references_to(slave); // // if our src is BADADDR then leave // if(slave_src == BADADDR) return 0; if(master_src == BADADDR) return 0; if(get_first_fcref_from(master_src) == master) return 1; // // To be a loop we need a back edge so we check to make sure our slave // references our master then we make sure that our master can reach our slave // so that we can verify there is a loop // if(is_reference_to(master, slave_src) && is_path_to(master,slave)) { //msg("0x%08x is referenced by 0x%08x\n", master, slave_src); return 1; } return 0; } ///////////////////////////////////////////////////////////////////////////////////////// // run_analysis() // // a virtual function so that we can still call our base class run_analysis // this function does the analysis of loops and parses the users input requests // // arguments: none // returns: none // void loop_detection::run_analysis() { // //run analysis of function_analyzer first // function_analyzer::run_analysis(); // // setup our entry point variable // entry_point = first_ea(); // //find all the loops in the function if // natural loops wasn't selected // if(!get_natural_loops() ) find_loops(); else find_natural_loops(); if(get_highlight_function() ) highlight_functions(); if(get_highlight_code() ) highlight_codes(); if(get_recursive_function() ) find_recursive_functions(); // //do we graph the results? // if(get_graph()) graph(); } ///////////////////////////////////////////////////////////////////////////////////////// // find_natural_loop() // // will look for only natural loops // // arguments: master - the node that should dominate // slave - the node that is dominated by master and references master // returns: true or false // int loop_detection::find_natural_loop(ea_t master, ea_t slave) { ea_t master_src = find_src(master); ea_t slave_src = find_src(slave); // // Does master dominate slave? // if(is_path_to(entry_point,slave,master) ) { // // Master dominates slaves now can we get from // if( is_reference_to(master, slave_src) ) { return 1; } } else return 0; } ///////////////////////////////////////////////////////////////////////////////////////// // is_path_to() // // tries to find a path from -> to verifying the flow of the program can hit to // // arguments: from - the ea of the start address // to - the ea of the destination // returns: true or false // int loop_detection::is_path_to(ea_t from, ea_t to) { ea_t from_src = find_src(from); ea_t to_src = find_src(to); ea_t next; ea_t fcref; char disasm_buf[512]; int result = 0; // // Check if our edges are valid if not exit // if(from_src == BADADDR || to_src == BADADDR) { #ifdef DEBUG_LOOP msg("Could not find a src from 0x%08x\n", from); #endif return 0; } // // make sure our "start" and "end" are valid // if(from == BADADDR || to == BADADDR) { #ifdef DEBUG_LOOP msg("from 0x%08x or to 0x%08x is BADADDR\n", from, to); #endif return 0; } // // if from_src is a reference to our destination we got to our goal // if(is_reference_to(to, from_src) ) { #ifdef DEBUG_LOOP msg("is_reference_to(0x%08x, 0x%08x)\n", to, from_src); #endif add_loop(to); return 1; } //get the jump ea fcref = get_first_fcref_from(from_src); //get the next instruction next = next_ea(from_src); #ifdef DEBUG_LOOP msg("FCREF 0x%08x NEXT 0x%08x to 0x%08x from 0x%08x\n", fcref, next, to, from); #endif //kill infinite loop if(fcref == from) { #ifdef DEBUG_LOOP msg("fcref 0x%08x is equal to from 0x%08x\n",fcref,from); #endif return 0; } //we got to our goal if(fcref == to) { #ifdef DEBUG_LOOP msg("fcref 0x%08x is equal to 0x%08x our goal\n",fcref,to); #endif add_loop(to); return 1; } //we got to our goal if(next == to) { #ifdef DEBUG_LOOP msg("next 0x%08x equal to 0x%08x\n", next, to); #endif add_loop(to); return 1; } //get instruction ua_mnem(from_src, disasm_buf, 512); tag_remove(disasm_buf, disasm_buf, 512); if(strstr(disasm_buf,"j") != NULL) { #ifdef DEBUG_LOOP msg("J** instruction\n"); #endif //makes sure we don't look at nodes that are exit if(find_src(fcref) == BADADDR) { #ifdef DEBUG_LOOP msg("could not find a src for fcref 0x%08x\n", fcref); #endif result = is_path_to(fcref, to); if(result) { add_loop(fcref); add_loop(to); return 1; } } #ifdef DEBUG_LOOP msg("No path from 0x%08x to 0x%08x\n", fcref, to); #endif result = is_path_to(next, to); if(result) { #ifdef DEBUG_LOOP msg("Took next and found a path\n"); #endif add_loop(next); add_loop(to); return 1; } } else return is_path_to(next, to); return 0; } ///////////////////////////////////////////////////////////////////////////////////////// // is_fragmented_head() // // // // arguments: // returns: none // ea_t loop_detection::is_fragmented_head(ea_t head) { ea_t to = get_first_cref_to(head); while(head != BADADDR) { if(find_src(to) == BADADDR) return to; to = get_next_cref_to(head, to); } return BADADDR; } ///////////////////////////////////////////////////////////////////////////////////////// // is_valid_node() // // makes sure it is a valid ea/node by checking if there is an instruction at the location // // arguments: ea - ea of node to check. // returns: true or false // int loop_detection::is_valid_node(ea_t ea) { char disasm_buf[512]; memset(disasm_buf,0,sizeof disasm_buf); ua_mnem(ea, disasm_buf, 512); tag_remove(disasm_buf, disasm_buf, 512); if(strlen(disasm_buf) <= 1) return 0; return 1; } ///////////////////////////////////////////////////////////////////////////////////////// // is_path_to() - overloaded // // checks to see if there is a path from "start" to "destination but in this overloaded // function. We specify a node to avoid. This allows us to verify if we can't get to our desitnation // avoiding a node then that node dominates the destination // // arguments: fid - function id. // returns: none // int loop_detection::is_path_to(ea_t from, ea_t to, ea_t avoid) { ea_t from_src = find_src(from); ea_t to_src = find_src(to); ea_t next; ea_t fcref; char disasm_buf[512]; int result = 0; if(from_src == BADADDR) { #ifdef DEBUG_DOM msg("Could not find a src from 0x%08x\n", from); #endif return 0; } if(from == BADADDR || to == BADADDR) { #ifdef DEBUG_DOM msg("from 0x%08x or to 0x%08x is BADADDR\n", from, to); #endif return 0; } if(to == avoid) { #ifdef DEBUG_DOM msg("to 0x%08x is == to avoid 0x%08x ", to, avoid); #endif return 0; } if(from == avoid) { #ifdef DEBUG_DOM msg("from 0x%08x is == to avoid 0x%08x ", from, avoid); #endif return 0; } if(from_src == avoid) { #ifdef DEBUG_DOM msg("from src 0x%08x is == to avoid 0x%08x ", from_src, avoid); #endif return 0; } if(is_reference_to(to, from_src) ) { #ifdef DEBUG_DOM msg("is_reference_to(0x%08x, 0x%08x)\n", to, from_src); #endif return 1; } fcref = get_first_fcref_from(from_src); next = next_ea(from_src); #ifdef DEBUG_DOM msg("FCREF 0x%08x NEXT 0x%08x to 0x%08x from 0x%08x\n", fcref, next, to, from); #endif //kill infinite loop if(fcref == from) { #ifdef DEBUG_DOM msg("fcref 0x%08x is equal to from 0x%08x\n",fcref,from); #endif return 0; } if(fcref== avoid) { #ifdef DEBUG_DOM msg("fcref 0x%08x is == to avoid 0x%08x ", fcref, avoid); #endif return 0; } if(next == avoid) { #ifdef DEBUG_DOM msg("next 0x%08x is == to avoid 0x%08x ", next, avoid); #endif return 0; } //we got to our goal if(fcref == to) { #ifdef DEBUG_DOM msg("fcref 0x%08x is equal to 0x%08x our goal\n",fcref,to); #endif return 1; } //we got to our goal if(next == to) { #ifdef DEBUG_DOM msg("next 0x%08x equal to 0x%08x\n", next, to); #endif return 1; } ua_mnem(from_src, disasm_buf, 512); tag_remove(disasm_buf, disasm_buf, 512); if(strstr(disasm_buf,"j") != NULL) { #ifdef DEBUG_DOM msg("J** instruction\n"); #endif //makes sure we don't look at nodes that are exit if(find_src(fcref) == BADADDR) { #ifdef DEBUG_DOM msg("could not find a src for fcref 0x%08x\n", fcref); #endif result = is_path_to(fcref, to, avoid); if(result) return 1; } #ifdef DEBUG_DOM msg("No path from 0x%08x to 0x%08x\n", fcref, to); #endif result = is_path_to(next, to, avoid); if(result) { #ifdef DEBUG_DOM msg("Took next and found a path\n"); #endif return 1; } //msg("No path from 0x%08x to 0x%08x\n", next, to); //return 0; } else return is_path_to(next, to, avoid); return 0; } ///////////////////////////////////////////////////////////////////////////////////////// // add_loop() // // adds ea to the list of nodes // // arguments: ea - adds ea to loop. // returns: true or false. // int loop_detection::add_loop(ea_t ea) { int i; // search for an existing node. for (i = 1; i <= num_loops; i++) if (loops[i] == ea) return FALSE; #ifdef FA_DEBUG msg("FA_DEBUG> add_loop(%08x)\n", ea); #endif // no existing node was found. ensure we have space for the new node // we are about to add. if ((num_loops + 1) % 10 == 0) loops = (ea_t *) qrealloc(loops, (num_loops + 10 + 1) * sizeof(ea_t)); // record the new node. num_loops++; loops[num_loops] = ea; return TRUE; } ///////////////////////////////////////////////////////////////////////////////////////// // is_loop() // // checks to see if the ea is in our loop // // arguments: ea - ea to check. // returns: true or false. // int loop_detection::is_loop(ea_t ea) { int i; // search for an existing node. for (i = 1; i <= num_loops; i++) if (loops[i] == ea) return TRUE; return FALSE; } ///////////////////////////////////////////////////////////////////////////////////////// // add_start_loop() // // adds ea to the list of start nodes // // arguments: ea - adds ea to list. // returns: true or false. // int loop_detection::add_start_loop(ea_t ea) { int i; // search for an existing node. for (i = 1; i <= num_start_loops; i++) if (start_loops[i] == ea) return FALSE; #ifdef FA_DEBUG msg("FA_DEBUG> add_start_loop(%08x)\n", ea); #endif // no existing node was found. ensure we have space for the new node // we are about to add. if ((num_start_loops + 1) % 10 == 0) start_loops = (ea_t *) qrealloc(start_loops, (num_start_loops + 10 + 1) * sizeof(ea_t)); // record the new node. num_start_loops++; start_loops[num_start_loops] = ea; return TRUE; } ///////////////////////////////////////////////////////////////////////////////////////// // add_end_loop() // // adds ea to the list of end nodes // // arguments: ea - adds ea to list. // returns: true or false. // int loop_detection::add_end_loop(ea_t ea) { int i; // search for an existing node. for (i = 1; i <= num_end_loops; i++) if (end_loops[i] == ea) return FALSE; #ifdef FA_DEBUG msg("FA_DEBUG> add_end_loop(%08x)\n", ea); #endif // no existing node was found. ensure we have space for the new node // we are about to add. if ((num_end_loops + 1) % 10 == 0) end_loops = (ea_t *) qrealloc(end_loops, (num_end_loops + 10 + 1) * sizeof(ea_t)); // record the new node. num_end_loops++; end_loops[num_end_loops] = ea; return TRUE; } ///////////////////////////////////////////////////////////////////////////////////////// // is_start_loop() // // checks to see if the node starts a loop. // // arguments: ea - to check to see if the node is in our list. // returns: true or false. // int loop_detection::is_start_loop(ea_t ea) { int i; // search for an existing node. for (i = 1; i <= num_start_loops; i++) if (start_loops[i] == ea) return TRUE; return FALSE; } ///////////////////////////////////////////////////////////////////////////////////////// // is_end_loop() // // checks to see if the node ends a loop. // // arguments: ea - to check to see if the node is in our list. // returns: true or false. // int loop_detection::is_end_loop(ea_t ea) { int i; // search for an existing node. for (i = 1; i <= num_end_loops; i++) if (end_loops[i] == ea) return TRUE; return FALSE; } ///////////////////////////////////////////////////////////////////////////////////////// // graph() // // generate and display a graph for this routine. // // arguments: none. // returns: none. // void loop_detection::graph (void) { FILE *fp = NULL; char disasm_buf[FA_DISASM_BUFLEN]; char tmp_buf [FA_DISASM_BUFLEN]; char path[1024]; char *tmp, *dis,*name; int i; int t = 0; int idx = 0; ea_t ea; ea_t fcref; ea_t src; ea_t endOffset; ea_t beginOffset; struc_t * struc = get_frame(get_func(first_ea() ) ); member_t* member; funcx * fx = new funcx(get_func(first_ea() ) ); // generate a random file name in the temp directory to store our graph. qtmpnam(path); // open the output file. if ((fp = qfopen(path, "wb")) == NULL) { msg("graph> Failed to open %s for writing.\n", path); return; } /////////////////////////////////////////////////////////////////////////////////////////////// // graph header. // qfprintf(fp, "graph:\n" "{\n" "\ttitle: \"graph of %08x\"\n" "\tmanhattan_edges: %s\n" "\tsplines: %s\n" "\tfinetuning: %s\n" "\tlayoutalgorithm: %s\n" "\tlayout_downfactor: %d\n" "\txlspace: %d\n" "\txspace: %d\n" "\tcolor: %s\n" "\n"FA_COLOR_PALETTE"\n", nodes[1], manhattan_edges ? "yes" : "no", splines ? "yes" : "no", finetuning ? "yes" : "no", layout_algorithm, layout_downfactor, xlspace, xspace, color); /////////////////////////////////////////////////////////////////////////////////////////////// // graph nodes. // // graph the nodes. for (i = 1; i <= num_nodes; i++) { // open the node. qfprintf(fp, "\tnode: { title: \"%08x\" label: \""FA_COLOR_LABEL"%08x:", nodes[i], nodes[i]); if(get_output_stack() ) { if(nodes[i] == first_ea()) { struc = get_frame( get_func(first_ea()) ); while(t != struc->memqty ) { endOffset = struc->members[t].soff; if(t == struc->memqty-1) { beginOffset = struc->members[ t ].eoff; } else beginOffset = struc->members[ t + 1 ].soff; size = ( beginOffset - endOffset ) ; name = get_member_name(struc->members[t].id); if(struc->members[t].soff < (fx->GetReturnAddressSize() + fx->GetLocalVariableSize() + fx->GetSavedRegsSize()) ) qfprintf(fp, "\n"FA_COLOR_ADDRESS"%08x Local Variable: %s[%d]", first_ea() , name, size); else qfprintf(fp, "\n"FA_COLOR_ADDRESS"%08x Function Arguement: %s[%d]", first_ea() , name, size); t++; }//end whhile } } // insert the disassembly of this node into the label. for (ea = nodes[i]; ea != BADADDR; ea = next_ea(ea)) { // clear our disassembly buffers. memset(disasm_buf, 0, sizeof(disasm_buf)); memset(tmp_buf, 0, sizeof(tmp_buf)); // generate the disassembly for the current effective address. generate_disasm_line(ea, tmp_buf, FA_DISASM_BUFLEN); // strip out comments from the generated disassembly. // comments start with a semi-colon ';'. if (strip_comments) { if ((tmp = strchr(tmp_buf, ';')) != NULL) { // cut through all the whitespace. for(tmp--; *tmp == ' '; tmp--) *tmp = 0x00; } } // replace all double quotes (") with single quotes ('). else { while ((tmp = strchr(tmp_buf, '"')) != NULL) *tmp = '\''; } // convert IDA coloring to wingraph32 compatible format. for (tmp = tmp_buf, dis = disasm_buf; tmp <= tmp_buf + strlen(tmp_buf); tmp++) { // escape character on. (convert format) if (*tmp == COLOR_ON) { // go to the next character. tmp++; switch (*tmp) { case COLOR_DEFAULT: strcat(disasm_buf, FA_COLOR_DEFAULT ); break; case COLOR_REGCMT: strcat(disasm_buf, FA_COLOR_REGCMT ); break; case COLOR_RPTCMT: strcat(disasm_buf, FA_COLOR_RPTCMT ); break; case COLOR_AUTOCMT: strcat(disasm_buf, FA_COLOR_AUTOCMT ); break; case COLOR_INSN: strcat(disasm_buf, FA_COLOR_INSN ); break; case COLOR_DATNAME: strcat(disasm_buf, FA_COLOR_DATNAME ); break; case COLOR_DNAME: strcat(disasm_buf, FA_COLOR_DNAME ); break; case COLOR_DEMNAME: strcat(disasm_buf, FA_COLOR_DEMNAME ); break; case COLOR_SYMBOL: strcat(disasm_buf, FA_COLOR_SYMBOL ); break; case COLOR_CHAR: strcat(disasm_buf, FA_COLOR_CHAR ); break; case COLOR_STRING: strcat(disasm_buf, FA_COLOR_STRING ); break; case COLOR_NUMBER: strcat(disasm_buf, FA_COLOR_NUMBER ); break; case COLOR_VOIDOP: strcat(disasm_buf, FA_COLOR_VOIDOP ); break; case COLOR_CREF: strcat(disasm_buf, FA_COLOR_CREF ); break; case COLOR_DREF: strcat(disasm_buf, FA_COLOR_DREF ); break; case COLOR_CREFTAIL: strcat(disasm_buf, FA_COLOR_CREFTAIL ); break; case COLOR_DREFTAIL: strcat(disasm_buf, FA_COLOR_DREFTAIL ); break; case COLOR_ERROR: strcat(disasm_buf, FA_COLOR_ERROR ); break; case COLOR_PREFIX: strcat(disasm_buf, FA_COLOR_PREFIX ); break; case COLOR_BINPREF: strcat(disasm_buf, FA_COLOR_BINPREF ); break; case COLOR_EXTRA: strcat(disasm_buf, FA_COLOR_EXTRA ); break; case COLOR_ALTOP: strcat(disasm_buf, FA_COLOR_ALTOP ); break; case COLOR_HIDNAME: strcat(disasm_buf, FA_COLOR_HIDNAME ); break; case COLOR_LIBNAME: strcat(disasm_buf, FA_COLOR_LIBNAME ); break; case COLOR_LOCNAME: strcat(disasm_buf, FA_COLOR_LOCNAME ); break; case COLOR_CODNAME: strcat(disasm_buf, FA_COLOR_CODNAME ); break; case COLOR_ASMDIR: strcat(disasm_buf, FA_COLOR_ASMDIR ); break; case COLOR_MACRO: strcat(disasm_buf, FA_COLOR_MACRO ); break; case COLOR_DSTR: strcat(disasm_buf, FA_COLOR_DSTR ); break; case COLOR_DCHAR: strcat(disasm_buf, FA_COLOR_DCHAR ); break; case COLOR_DNUM: strcat(disasm_buf, FA_COLOR_DNUM ); break; case COLOR_KEYWORD: strcat(disasm_buf, FA_COLOR_KEYWORD ); break; case COLOR_REG: strcat(disasm_buf, FA_COLOR_REG ); break; case COLOR_IMPNAME: strcat(disasm_buf, FA_COLOR_IMPNAME ); break; case COLOR_SEGNAME: strcat(disasm_buf, FA_COLOR_SEGNAME ); break; case COLOR_UNKNAME: strcat(disasm_buf, FA_COLOR_UNKNAME ); break; case COLOR_CNAME: strcat(disasm_buf, FA_COLOR_CNAME ); break; case COLOR_UNAME: strcat(disasm_buf, FA_COLOR_UNAME ); break; case COLOR_COLLAPSED: strcat(disasm_buf, FA_COLOR_COLLAPSED); break; case COLOR_FG_MAX: strcat(disasm_buf, FA_COLOR_FG_MAX); // NOTE - generate_disasm_line returns locational references in the form: // ????????loc_???????? /// where ??????? is the 8 digit 0-padded hexidecimal address of the // location. the simplest way to deal with this is to simply increment // past the initial location address (the following +8) thereby only // leaving the remaining name to be used by our grapher. tmp += 8; break; default: strcat(disasm_buf, FA_COLOR_DEFAULT); } dis += 3; } // escape character off. (ignore these) else if (*tmp == COLOR_OFF) tmp++; // quote next character. else if (*tmp == COLOR_ESC) { // go to the next character. tmp++; // copy the character as a string. _snprintf(disasm_buf, sizeof(disasm_buf) - 1, "%s0x%02x", disasm_buf, *tmp); } // inverse colors. (ignore these) else if (*tmp == COLOR_INV) tmp++; else { *dis = *tmp; dis++; } } // write this line to the output file. qfprintf(fp, "\n"FA_COLOR_ADDRESS"%08x %s", ea, disasm_buf); // break if the next instruction is the start of another node. if (is_node(next_ea(ea))) break; // if the current instruction is far off. if (ea < ea_start || ea > ea_end) { memset(disasm_buf, 0, sizeof(disasm_buf)); disasm(ea, disasm_buf); fcref = get_first_fcref_from(ea); // break if the current instruction returns back to our original code. if (fcref >= ea_start && fcref <= ea_start && strnicmp(disasm_buf, "jmp", 3) == 0) break; if (strnicmp(disasm_buf, "ret", 3) == 0) break; } } // // select the appropriate color/shape for this node and close it. // //qfprintf(fp, ""); // entry point. if (nodes[i] == ea_start) qfprintf(fp, "\" borderwidth: 7 color: %s }\n", color_node); else if(is_start_loop(nodes[i]) ) qfprintf(fp, "\" borderwidth: 7 bordercolor: green }\n"); else if(is_end_loop(nodes[i]) ) qfprintf(fp, "\" borderwidth: 7 bordercolor: red }\n"); else if(is_loop(nodes[i]) ) qfprintf(fp, "\" borderwidth: 7 bordercolor: yellow }\n"); // far off nodes. else if (nodes[i] < ea_start || nodes[i] > ea_end) qfprintf(fp, "\" color: %s }\n", color_far_off); // regular nodes. else qfprintf(fp, "\" color: %s }\n", color_node); } /////////////////////////////////////////////////////////////////////////////////////////////// // graph edges. // // graph all the recorded edges. for (i = 1; i <= num_edges; i++) { // determine the source node by looking backwards until we find the start of a node. for (src = edges_src[i]; src != BADADDR; src = prev_visea(src)) if (is_node(src)) break; qfprintf(fp, "\tedge: { sourcename: \"%08x\" targetname: \"%08x\"", src, edges_dst[i]); // find the end of this node, ie: the branching instruction. for (fcref = BADADDR, ea = edges_src[i]; fcref == BADADDR; ea = next_ea(ea)) { if ((fcref = get_first_fcref_from(ea)) != BADADDR) { memset(disasm_buf, 0, sizeof(disasm_buf)); disasm(ea, disasm_buf); // we are looking for a jump. if (disasm_buf[0] != 'j') fcref = BADADDR; } } // unconditional jump. if (strnicmp(disasm_buf, "jmp", 3) == 0) qfprintf(fp, " color: black }\n"); // conditional jump, true branch. else if (fcref == edges_dst[i]) qfprintf(fp, " color: green }\n"); // conditional jump, false branch. else qfprintf(fp, " color: red }\n"); } // graph the implicit edges. // these are the edges from one instruction to the next, where the next instruction is the // start of a new node. // branching / return instructions are ignored here. for (ea = first_ea(); ea != BADADDR; ea = next_ea(ea)) { memset(disasm_buf, 0, sizeof(disasm_buf)); disasm(ea, disasm_buf); if (strnicmp(disasm_buf, "ret", 3) == 0) continue; if (get_first_fcref_from(ea) != BADADDR && disasm_buf[0] == 'j') continue; if (is_node(next_ea(ea))) { // determine the source node by looking backwards until we find the start of a node. for (src = ea; src != BADADDR; src = prev_visea(src)) if (is_node(src)) break; qfprintf(fp, "\tedge: { sourcename: \"%08x\" targetname: \"%08x\" color: blue }\n", src, next_ea(ea)); } } /////////////////////////////////////////////////////////////////////////////////////////////// // graph footer. // qfprintf(fp, "}\n"); // close the output stream. qfclose(fp); // display the graph. display_gdl(path); } void loop_detection::constructor() { graph_loop = 0; highlight_function = 0; output_stack = 0; highlight_code = 0; natural_loops = 0; recursive_function = 0; verbose_output = 0; auto_comment = 0; num_loops = 0; num_start_loops = 0; num_end_loops = 0; loops = (ea_t *) qalloc(10 * sizeof(ea_t)); start_loops = (ea_t *) qalloc(10 * sizeof(ea_t)); end_loops = (ea_t *) qalloc(10 * sizeof(ea_t)); } ///////////////////////////////////////////////////////////////////////////////////////// // find_loops() // // is a wrapper function that uses the find_loop function to identify loops within // two nodes. This function helps to impelment the algorithm described in the paper. // // arguments: none // returns: none // void loop_detection::find_loops() { int i = 1; int t = 1; ea_t d; ea_t n; char comment_line[400]; // //our first for loop // for(i = 1; i <= num_nodes; i++) { // //our nested for loop // for(t = 1; t <= num_nodes; t++) { // // Check if the node is valid this check // makes sure there actual instructions at the ea and // that the ea doesn't just contain garbage // if( is_valid_node(nodes[i]) ) { // // Go through the nodes sequentially // if(nodes[i] <= nodes[t] ) { // // call find_loop which returns a true or false if it finds // a loop or not // if(find_loop(nodes[i], nodes[t]) ) { // // Check if the head is actually fragmented // d = is_fragmented_head(nodes[i]); n = is_fragmented_head(nodes[t]); // // head isn't fragmented replace it with the aactual node value // if(d == BADADDR) d = nodes[i]; // // head isn't fragmented replace with actual node value // if(n == BADADDR) n = nodes[t]; // // add ea's to our lists // if(get_auto_comment() ) { qsnprintf(comment_line, 400, "Begining of Loop. Ends at 0x%08x\n", n); append_cmt(d,comment_line,false); qsnprintf(comment_line, 400, "End of Loop. Begins at 0x%08x\n", d); append_cmt(n,comment_line,false); } add_start_loop(d); add_end_loop(n); add_loop(d); add_loop(n); add_loop(nodes[t]); add_loop(nodes[i]); // // if our master is actually two nodes in one // this check will add the second node // if(nodes[i] != get_node(find_src(nodes[i]) ) ) { add_loop(get_node(find_src(nodes[i]) ) ); } // // Tell the user we found a loop // //msg("Found Loop: 0x%08x -> 0x%08x\n", d,n); } }//end if } }//end for }//end for } ///////////////////////////////////////////////////////////////////////////////////////// // highlight_functions() // // this function will highlight any ea's that have function calls within a loop // // arguments: none // returns: none // void loop_detection::highlight_functions() { int i = 1; ea_t ea; ea_t loop_begin; char instruction[512]; char func_name[512]; // // go through all our nodes involved in loops // while( i < num_loops) { ea = loops[i]; // // set the begining of our loop // loop_begin = ea; // // while we are on a valid ea and we aren't where we began // while(ea != BADADDR && ea != find_src(loop_begin) ) { ua_mnem(ea, instruction, 512); tag_remove(instruction, instruction, 512); // // if the instructino is a call then lets mark it // if(strstr(instruction,"call") != NULL) { // // if the user wants verbose output then tell them in the output window what // is going on // if(get_verbose_output() ) { ua_outop(ea, func_name, 512, 0); tag_remove(func_name, func_name, 512); msg("Found function %s within a loop at 0x%08x\n",func_name, ea); } // // set the background // set_item_color(ea, 0x0e); } ea = next_ea(ea); } i++; } } ///////////////////////////////////////////////////////////////////////////////////////// // highlight_codes() // // inititalizes the base class. And this instance // // arguments: ea - ea of the function. // returns: none // void loop_detection::highlight_codes() { int i = 1; ea_t ea; ea_t loop_begin; // // loop through all our loop nodes // while( i < num_loops) { ea = loops[i]; loop_begin = ea; // // while our ea is valid and we have not reached the begining of our // loop node // while(ea != BADADDR && ea != find_src(loop_begin) ) { // // set our background // set_item_color(ea, 0x0b); ea = next_ea(ea); } i++; } } ///////////////////////////////////////////////////////////////////////////////////////// // find_recursive_functions() // // will attempt to find functions that call themsleves (recursion) // // arguments: none // returns: none // void loop_detection::find_recursive_functions() { ea_t ea = first_ea(); char instruction[512]; ea_t fcref; ea_t ea_xref; // // go through whole function // while(last_ea() != ea) { ua_mnem(ea, instruction, 512); tag_remove(instruction, instruction, 512); if(strstr(instruction,"call") != NULL) { fcref = get_first_fcref_from(ea); if(fcref == ea ) { // // Recursive Function // msg("Found Recursive Function at 0x%08x\n", ea); append_cmt(ea,"Recursive Function Call",0); } }//end if ea = next_ea(ea); } } ///////////////////////////////////////////////////////////////////////////////////////// // find_natural_loops() // // is a wrapper function that uses the find_loop function to identify loops within // two nodes // // arguments: none // returns: none // void loop_detection::find_natural_loops() { int i = 1; int t = 1; ea_t d; ea_t n; // //our first for loop // for(i = 1; i <= num_nodes; i++) { // //our nested for loop // for(t = 1; t <= num_nodes; t++) { // // Check if the node is valid this check // makes sure there actual instructions at the ea and // that the ea doesn't just contain garbage // if( is_valid_node(nodes[i]) ) { // // Go through the nodes sequentially // if(nodes[i] <= nodes[t] ) { // // call find_loop which returns a true or false if it finds // a loop or not // if(find_natural_loop(nodes[i], nodes[t]) ) { // // Check if the head is actually fragmented // d = is_fragmented_head(nodes[i]); n = is_fragmented_head(nodes[t]); // // head isn't fragmented replace it with the aactual node value // if(d == BADADDR) d = nodes[i]; // // head isn't fragmented replace with actual node value // if(n == BADADDR) n = nodes[t]; // // add ea's to our lists // add_start_loop(d); add_end_loop(n); add_loop(d); add_loop(n); add_loop(nodes[t]); add_loop(nodes[i]); // // if our master is actually two nodes in one // this check will add the second node // if(nodes[i] != get_node(find_src(nodes[i]) ) ) { add_loop(get_node(find_src(nodes[i]) ) ); } // // Tell the user we found a loop // //msg("Found Loop: 0x%08x -> 0x%08x\n", d,n); } }//end if } }//end for }//end for }
26.478962
119
0.506316
[ "shape" ]
6ae1ba38498f08e2a54a5f40ff23ffb6c82dcce4
12,832
cpp
C++
base/remoteboot/rigpsnap/compdata.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/remoteboot/rigpsnap/compdata.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/remoteboot/rigpsnap/compdata.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// // Microsoft Corporation 1998 // // COMPDATA.CPP - CComponentData and CComponentDataCF routines // #include "main.h" /////////////////////////////////////////////////////////////////////////////// // CComponentData object implementation CComponentData::CComponentData() { m_cRef = 1; InterlockedIncrement(&g_cRefThisDll); m_hwndFrame = NULL; m_pScope = NULL; m_pConsole = NULL; m_hRoot = NULL; m_pGPTInformation = NULL; } CComponentData::~CComponentData() { if (m_pScope) { m_pScope->Release(); } if (m_pConsole) { m_pConsole->Release(); } if (m_pGPTInformation) { m_pGPTInformation->Release(); } InterlockedDecrement(&g_cRefThisDll); } /////////////////////////////////////////////////////////////////////////////// // CComponentData object implementation (IUnknown) HRESULT CComponentData::QueryInterface (REFIID riid, void **ppv) { if (IsEqualIID(riid, IID_IComponentData) || IsEqualIID(riid, IID_IUnknown)) { *ppv = (LPCOMPONENT)this; m_cRef++; return S_OK; } else if (IsEqualIID(riid, IID_ISnapinHelp )) { *ppv = (ISnapinHelp *) this; m_cRef++; return S_OK; } else if (IsEqualIID(riid, IID_IPersistStreamInit)) { *ppv = (LPPERSISTSTREAMINIT)this; m_cRef++; return S_OK; } else { *ppv = NULL; return E_NOINTERFACE; } } ULONG CComponentData::AddRef (void) { return ++m_cRef; } ULONG CComponentData::Release (void) { if (--m_cRef == 0) { delete this; return 0; } return m_cRef; } /////////////////////////////////////////////////////////////////////////////// // CComponentData object implementation (IComponentData) STDMETHODIMP CComponentData::Initialize(LPUNKNOWN pUnknown) { HRESULT hr; HBITMAP bmp16x16; LPIMAGELIST lpScopeImage; // // QI for IConsoleNameSpace // hr = pUnknown->QueryInterface(IID_IConsoleNameSpace, (LPVOID *)&m_pScope); if (FAILED(hr)) { DebugMsg((DM_WARNING, TEXT("CComponentData::Initialize: Failed to QI for IConsoleNameSpace."))); return hr; } // // QI for IConsole // hr = pUnknown->QueryInterface(IID_IConsole, (LPVOID *)&m_pConsole); if (FAILED(hr)) { DebugMsg((DM_WARNING, TEXT("CComponentData::Initialize: Failed to QI for IConsole."))); m_pScope->Release(); m_pScope = NULL; return hr; } m_pConsole->GetMainWindow (&m_hwndFrame); // // Query for the scope imagelist interface // hr = m_pConsole->QueryScopeImageList(&lpScopeImage); if (FAILED(hr)) { DebugMsg((DM_WARNING, TEXT("CComponentData::Initialize: Failed to QI for scope imagelist."))); m_pScope->Release(); m_pScope = NULL; m_pConsole->Release(); m_pConsole=NULL; return hr; } // Load the bitmaps from the dll bmp16x16=LoadBitmap(g_hInstance, MAKEINTRESOURCE(IDB_16x16)); // Set the images lpScopeImage->ImageListSetStrip(reinterpret_cast<PLONG_PTR>(bmp16x16), reinterpret_cast<PLONG_PTR>(bmp16x16), 0, RGB(255, 0, 255)); lpScopeImage->Release(); DeleteObject( bmp16x16 ); return S_OK; } STDMETHODIMP CComponentData::Destroy(VOID) { return S_OK; } STDMETHODIMP CComponentData::CreateComponent(LPCOMPONENT *ppComponent) { HRESULT hr; CSnapIn *pSnapIn; DebugMsg((DM_VERBOSE, TEXT("CComponentData::CreateComponent: Entering."))); // // Initialize // *ppComponent = NULL; // // Create the snapin view // pSnapIn = new CSnapIn(this); if (!pSnapIn) { DebugMsg((DM_WARNING, TEXT("CComponentData::CreateComponent: Failed to create CSnapIn."))); return E_OUTOFMEMORY; } // // QI for IComponent // hr = pSnapIn->QueryInterface(IID_IComponent, (LPVOID *)ppComponent); pSnapIn->Release(); // release QI return hr; } STDMETHODIMP CComponentData::QueryDataObject(MMC_COOKIE cookie, DATA_OBJECT_TYPES type, LPDATAOBJECT* ppDataObject) { HRESULT hr = E_NOINTERFACE; CDataObject *pDataObject; LPGPTDATAOBJECT pGPTDataObject; // // Create a new DataObject // pDataObject = new CDataObject(this); // ref == 1 if (!pDataObject) return E_OUTOFMEMORY; // // QI for the private GPTDataObject interface so we can set the cookie // and type information. // hr = pDataObject->QueryInterface(IID_IGPTDataObject, (LPVOID *)&pGPTDataObject); if (FAILED(hr)) { pDataObject->Release(); return (hr); } pGPTDataObject->SetType(type); pGPTDataObject->SetCookie(cookie); pGPTDataObject->Release(); // // QI for a normal IDataObject to return. // hr = pDataObject->QueryInterface(IID_IDataObject, (LPVOID *)ppDataObject); pDataObject->Release(); // release initial ref return hr; } STDMETHODIMP CComponentData::Notify(LPDATAOBJECT lpDataObject, MMC_NOTIFY_TYPE event, LPARAM arg, LPARAM param) { HRESULT hr = S_OK; switch(event) { case MMCN_EXPAND: if (arg == TRUE) if (!m_pGPTInformation) { lpDataObject->QueryInterface(IID_IGPEInformation, (LPVOID *)&m_pGPTInformation); } if (m_pGPTInformation) { hr = EnumerateScopePane(lpDataObject, (HSCOPEITEM)param); } break; default: break; } return hr; } STDMETHODIMP CComponentData::GetDisplayInfo(LPSCOPEDATAITEM pItem) { DWORD dwIndex; if (pItem == NULL) return E_POINTER; for (dwIndex = 0; dwIndex < NUM_NAMESPACE_ITEMS; dwIndex++) { if (g_NameSpace[dwIndex].dwID == (DWORD) pItem->lParam) break; } if (dwIndex == NUM_NAMESPACE_ITEMS) pItem->displayname = NULL; else { pItem->displayname = g_NameSpace[dwIndex].szDisplayName; } return S_OK; } STDMETHODIMP CComponentData::CompareObjects(LPDATAOBJECT lpDataObjectA, LPDATAOBJECT lpDataObjectB) { HRESULT hr = S_FALSE; LPGPTDATAOBJECT pGPTDataObjectA, pGPTDataObjectB; MMC_COOKIE cookie1, cookie2; if (lpDataObjectA == NULL || lpDataObjectB == NULL) return E_POINTER; // // QI for the private GPTDataObject interface // if (FAILED(lpDataObjectA->QueryInterface(IID_IGPTDataObject, (LPVOID *)&pGPTDataObjectA))) { return S_FALSE; } if (FAILED(lpDataObjectB->QueryInterface(IID_IGPTDataObject, (LPVOID *)&pGPTDataObjectB))) { pGPTDataObjectA->Release(); return S_FALSE; } pGPTDataObjectA->GetCookie(&cookie1); pGPTDataObjectB->GetCookie(&cookie2); if (cookie1 == cookie2) { hr = S_OK; } pGPTDataObjectA->Release(); pGPTDataObjectB->Release(); return hr; } /////////////////////////////////////////////////////////////////////////////// // CComponentData object implementation (IPersistStreamInit) STDMETHODIMP CComponentData::GetClassID(CLSID *pClassID) { if (!pClassID) { return E_POINTER; } *pClassID = CLSID_GPTRemoteInstall; return S_OK; } STDMETHODIMP CComponentData::IsDirty(VOID) { return S_FALSE; } STDMETHODIMP CComponentData::Load(IStream *pStm) { return S_OK; } STDMETHODIMP CComponentData::Save(IStream *pStm, BOOL fClearDirty) { return S_OK; } STDMETHODIMP CComponentData::GetSizeMax(ULARGE_INTEGER *pcbSize) { DWORD dwSize = 0; if (!pcbSize) { return E_POINTER; } ULISet32(*pcbSize, dwSize); return S_OK; } STDMETHODIMP CComponentData::InitNew(void) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // CComponentData object implementation (Internal functions) HRESULT CComponentData::EnumerateScopePane (LPDATAOBJECT lpDataObject, HSCOPEITEM hParent) { SCOPEDATAITEM item; HRESULT hr; DWORD dwIndex, i; if (!m_hRoot) m_hRoot = hParent; if (m_hRoot == hParent) dwIndex = 0; else { item.mask = SDI_PARAM; item.ID = hParent; hr = m_pScope->GetItem (&item); if (FAILED(hr)) return hr; dwIndex = (DWORD) item.lParam; } for (i = 0; i < NUM_NAMESPACE_ITEMS; i++) { if (g_NameSpace[i].dwParent == dwIndex) { item.mask = SDI_STR | SDI_STATE | SDI_IMAGE | SDI_OPENIMAGE | SDI_PARAM | SDI_CHILDREN; item.displayname = MMC_CALLBACK; item.nImage = 0; item.nOpenImage = 0; item.nState = 0; item.cChildren = g_NameSpace[i].cChildren; item.lParam = g_NameSpace[i].dwID; item.relativeID = hParent; m_pScope->InsertItem (&item); } } return S_OK; } /////////////////////////////////////////////////////////////////////////////// // Class factory object implementation CComponentDataCF::CComponentDataCF() { m_cRef = 1; InterlockedIncrement(&g_cRefThisDll); } CComponentDataCF::~CComponentDataCF() { InterlockedDecrement(&g_cRefThisDll); } /////////////////////////////////////////////////////////////////////////////// // Class factory object implementation (IUnknown) STDMETHODIMP_(ULONG) CComponentDataCF::AddRef() { return ++m_cRef; } STDMETHODIMP_(ULONG) CComponentDataCF::Release() { if (--m_cRef == 0) { delete this; return 0; } return m_cRef; } STDMETHODIMP CComponentDataCF::QueryInterface(REFIID riid, LPVOID FAR* ppv) { if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IClassFactory)) { *ppv = (LPCLASSFACTORY)this; m_cRef++; return S_OK; } else { *ppv = NULL; return E_NOINTERFACE; } } /////////////////////////////////////////////////////////////////////////////// // Class factory object implementation (IClassFactory) STDMETHODIMP CComponentDataCF::CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid, LPVOID FAR* ppvObj) { *ppvObj = NULL; if (pUnkOuter) return CLASS_E_NOAGGREGATION; CComponentData *pComponentData = new CComponentData(); // ref count == 1 if (!pComponentData) return E_OUTOFMEMORY; HRESULT hr = pComponentData->QueryInterface(riid, ppvObj); pComponentData->Release(); // release initial ref return hr; } STDMETHODIMP CComponentDataCF::LockServer(BOOL fLock) { return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // Class factory object creation (IClassFactory) HRESULT CreateComponentDataClassFactory (REFCLSID rclsid, REFIID riid, LPVOID* ppv) { HRESULT hr; if (IsEqualCLSID (rclsid, CLSID_GPTRemoteInstall)) { CComponentDataCF *pComponentDataCF = new CComponentDataCF(); // ref == 1 if (!pComponentDataCF) return E_OUTOFMEMORY; hr = pComponentDataCF->QueryInterface(riid, ppv); pComponentDataCF->Release(); // release initial ref return hr; } return CLASS_E_CLASSNOTAVAILABLE; } /////////////////////////////////////////////////////////////////////////////// // // CComponentData object implementation (ISnapinHelp) // STDMETHODIMP CComponentData::GetHelpTopic(LPOLESTR *lpCompiledHelpFile) { LPOLESTR lpHelpFile; lpHelpFile = (LPOLESTR) CoTaskMemAlloc (MAX_PATH * sizeof(WCHAR)); if (!lpHelpFile) { return E_OUTOFMEMORY; } if (!ExpandEnvironmentStringsW (L"%SystemRoot%\\Help\\ris.chm", lpHelpFile, MAX_PATH)) { HRESULT hr = HRESULT_FROM_WIN32(GetLastError()); CoTaskMemFree(lpHelpFile); return hr; } *lpCompiledHelpFile = lpHelpFile; return S_OK; }
21.935043
112
0.548628
[ "object" ]
6ae4e63eccf6384217eb35b24eccffa3d2b35202
1,249
hpp
C++
cli.hpp
openbmc/openpower-hw-diags
d94291aa2f3248cd829b29a91caa137b24aea5e1
[ "Apache-2.0" ]
null
null
null
cli.hpp
openbmc/openpower-hw-diags
d94291aa2f3248cd829b29a91caa137b24aea5e1
[ "Apache-2.0" ]
1
2021-05-05T14:27:26.000Z
2021-05-06T20:46:56.000Z
cli.hpp
openbmc/openpower-hw-diags
d94291aa2f3248cd829b29a91caa137b24aea5e1
[ "Apache-2.0" ]
null
null
null
#pragma once #include <attn/attn_config.hpp> #include <string> /* * @brief Search the command line arguments for an option * * @param i_begin command line args vector begin * @param i_end command line args vector end * @param i_option configuration option to look for * * @return true = option found on command line */ bool getCliOption(char** i_begin, char** i_end, const std::string& i_option); /* * @brief Search the command line arguments for a setting value * * @param i_begin command line args vector begin * @param i_end command line args vectory end * @param i_setting configuration setting to look for * * @return value of the setting or 0 if setting not found or value not given */ char* getCliSetting(char** i_begin, char** i_end, const std::string& i_setting); /* * * @brief Get configuration flags from command line * * Parse the command line for configuration options and update the * attention handler configuration object as needed. * * @param i_begin command line args vector begin * @param i_end command line args vector end * @param o_config pointer to attention handler configuration object */ void parseConfig(char** i_begin, char** i_end, attn::Config* o_config);
30.463415
80
0.722178
[ "object", "vector" ]
6aef47a875cec6027b529dd8f6208428c9315298
13,882
cpp
C++
src/qt/unionaccounthistory.cpp
maxmaxj/ipchain
99c1943ca65fd4acdef5b4eb5e75c4bee3d59365
[ "MIT" ]
34
2018-01-25T10:29:35.000Z
2021-04-22T18:40:40.000Z
src/qt/unionaccounthistory.cpp
joshuabond/ipchain
5bd6792b1754890fae6648bec9d60519b55406cd
[ "MIT" ]
9
2018-07-25T09:41:40.000Z
2021-03-05T16:13:01.000Z
src/qt/unionaccounthistory.cpp
joshuabond/ipchain
5bd6792b1754890fae6648bec9d60519b55406cd
[ "MIT" ]
11
2018-01-28T03:02:44.000Z
2022-01-09T04:26:23.000Z
#include "unionaccounthistory.h" #include "forms/ui_unionaccounthistory.h" #include "log/log.h" #include "base58.h" #include "validation.h" #include "timedata.h" #include <guiutil.h> #include <QDateTime> #include "upgradewidget.h" #include <QHBoxLayout> #include <QPalette> #include <QFont> #include <QSpacerItem> #include <QPainter> #include "ipchainunits.h" #include "walletmodel.h" unionaccounthistory::unionaccounthistory(QWidget *parent) : QWidget(parent),m_pwalletmodel(NULL), ui(new Ui::unionaccounthistory) { ui->setupUi(this); } unionaccounthistory::~unionaccounthistory() { delete ui; } void unionaccounthistory::setAdd(std::string add) { m_add = add; } void unionaccounthistory::setnum(CAmount num) { m_num = num; LOG_WRITE(LOG_INFO,"setnum ",QString::number(m_num).toStdString().c_str()); } std::string unionaccounthistory::getAdd() { return m_add; } CAmount unionaccounthistory::getnum() { return m_num ; } bool comp(const tra_info &a,const tra_info &b) { return a.strtime>b.strtime; } void unionaccounthistory::updateinfo(std::map<uint256,const CWalletTx*> s) { m_tra.clear(); std::vector<tra_info> m_tra_plus; m_tra_plus.clear(); LOG_WRITE(LOG_INFO,"updateinfoupdateinfo--------detaildetail",QString::number(s.size()).toStdString().c_str()); if(s.size() > 0 ) { std::map<uint256,const CWalletTx*>::iterator it; it = s.begin(); while(it != s.end()) { uint256 txid = it->first; // LOG_WRITE(LOG_INFO,"tra detail",(const char*)(char*)(unsigned char*)&txid); const CWalletTx* wtx =it->second; LOG_WRITE(LOG_INFO,"tra detailtwice",it->second->GetHash().ToString().c_str()); bool isSend = false; bool isRecv = false; if(m_pwalletmodel&&m_pwalletmodel->vinsFindAddress(wtx->tx->vin,m_add)) { isSend = true; } else { isRecv = true; } LOG_WRITE(LOG_INFO,"TEST---IsSend,IsRecv",QString::number(isSend).toStdString().c_str(),QString::number(isRecv).toStdString().c_str()); if (isSend&&!isRecv) { CAmount num = 0; CTxDestination address; std::string add; for (unsigned int nOut = 0; nOut < wtx->tx->vout.size(); nOut++) { const CTxOut& txout = wtx->tx->vout[nOut]; if(nOut < wtx->tx->vout.size()-1||wtx->tx->vout.size()==1) { if (ExtractDestination(txout.scriptPubKey, address)) add= CBitcoinAddress(address).ToString(); } uint256 hash = wtx->GetHash(); QString m_status=m_pwalletmodel->FormatTxStatus(*wtx); QString m_strtime =m_pwalletmodel->FormatTxTimeP2SH(*wtx); CAmount m_fee = Getfeebytxid(static_cast<CTransaction>(*wtx)); if(nOut < wtx->tx->vout.size()-1||wtx->tx->vout.size()==1) { num+= txout.nValue; } LOG_WRITE(LOG_INFO,"Total Num",QString::number(num).toStdString().c_str()); if(0==txout.txType && (nOut == wtx->tx->vout.size()-1||wtx->tx->vout.size()==1)) { LOG_WRITE(LOG_INFO,"num +++ ",QString::number(txout.nValue).toStdString().c_str(),QString::number(m_num).toStdString().c_str()); tra_info m_trainfo; m_trainfo.add = add; m_trainfo.fee= m_fee; m_trainfo.isSend = true; m_trainfo.num =num ; m_trainfo.strtime = m_strtime; m_trainfo.status = m_status; m_trainfo.txid = QString::fromStdString(txid.ToString()); LOG_WRITE(LOG_INFO,"txid ",hash.ToString().c_str(),\ "starttime ",m_strtime.toStdString().c_str(),\ QString::number((*wtx).nTimeSmart).toStdString().c_str(),\ QString::number((*wtx).nTimeReceived).toStdString().c_str()); LOG_WRITE(LOG_INFO,"IsSend",QString::number(m_trainfo.isSend).toStdString().c_str()); m_tra.push_back(m_trainfo); } } } if(isRecv && ! isSend) { for (unsigned int nOut = 0; nOut < wtx->tx->vout.size()-1; nOut++) { const CTxOut& txout = wtx->tx->vout[nOut]; CTxDestination address; std::string add; if (ExtractDestination(txout.scriptPubKey, address)) add= CBitcoinAddress(address).ToString(); int64_t nTime = wtx->GetTxTime(); CAmount num = 0; num +=txout.nValue; uint256 hash = wtx->GetHash(); QString m_status=m_pwalletmodel->FormatTxStatus(*wtx); QString m_strtime =m_pwalletmodel->FormatTxTimeP2SH(*wtx); if(nOut == wtx->tx->vout.size()-2) { tra_info m_trainfo; m_trainfo.add = add; m_trainfo.fee= 0; m_trainfo.isSend = false; m_trainfo.num =num; m_trainfo.strtime = m_strtime; m_trainfo.status = m_status; m_trainfo.txid = QString::fromStdString(txid.ToString()); LOG_WRITE(LOG_INFO,"ISRECV",QString::number(m_trainfo.isSend).toStdString().c_str()); m_tra.push_back(m_trainfo); } } if(wtx->tx->vout.size()==1){ const CTxOut& txout = wtx->tx->vout[0]; CTxDestination address; std::string add; if (ExtractDestination(txout.scriptPubKey, address)) add= CBitcoinAddress(address).ToString(); int64_t nTime = wtx->GetTxTime(); CAmount num = 0; num +=txout.nValue; uint256 hash = wtx->GetHash(); QString m_status=m_pwalletmodel->FormatTxStatus(*wtx); QString m_strtime =m_pwalletmodel->FormatTxTimeP2SH(*wtx); tra_info m_trainfo; m_trainfo.add = add; m_trainfo.fee= 0; m_trainfo.isSend = false; m_trainfo.num =num; m_trainfo.strtime = m_strtime; m_trainfo.status = m_status; m_trainfo.txid = QString::fromStdString(txid.ToString()); LOG_WRITE(LOG_INFO,"txid ",hash.ToString().c_str(),\ "starttime ",m_strtime.toStdString().c_str(),\ QString::number((*wtx).nTimeSmart).toStdString().c_str(),\ QString::number((*wtx).nTimeReceived).toStdString().c_str()); LOG_WRITE(LOG_INFO,"ISRECV",QString::number(m_trainfo.isSend).toStdString().c_str()); m_tra.push_back(m_trainfo); } } it ++; } } //m_tra sort if(m_tra.size() >0) { for(int i = 0;i<m_tra.size();i++) { m_tra_plus.push_back(m_tra.at(i)); } } for(int i = 0;i<m_tra_plus.size();i++) { LOG_WRITE(LOG_INFO,"befort sort",m_tra_plus.at(i).strtime.toStdString().c_str()); } sort(m_tra_plus.begin(),m_tra_plus.end(),comp); if(m_tra.size() >0) { for(int i = 0;i<m_tra_plus.size();i++) { LOG_WRITE(LOG_INFO,"m_tra strtimr",m_tra_plus.at(i).strtime.toStdString().c_str()); } } QWidget * pnewall = new QWidget(); pvboxlayoutall = new QVBoxLayout(); pnewall->setLayout(pvboxlayoutall); ui->scrollArea->setWidget(pnewall); LOG_WRITE(LOG_INFO,"m_tra size",QString::number(m_tra.size()).toStdString().c_str()); m_tra.clear(); if(m_tra_plus.size() > 0 ) { for(int i = 0;i<m_tra_plus.size();i++) { LOG_WRITE(LOG_INFO,"addinfo issend true or flase ==",QString::number(m_tra_plus.at(i).isSend).toStdString().c_str()); addinfo(m_tra_plus.at(i).add,m_tra_plus.at(i).fee, m_tra_plus.at(i).isSend, m_tra_plus.at(i).num, m_tra_plus.at(i).status, m_tra_plus.at(i).strtime, m_tra_plus.at(i).txid); addline(); } } QSpacerItem* horizontalSpacer = new QSpacerItem(20,40,QSizePolicy::Minimum, QSizePolicy::Expanding); pvboxlayoutall->addSpacerItem(horizontalSpacer); } void unionaccounthistory::addline() { upgradewidget * pnewone = new upgradewidget(); pnewone->m_isunion = true; pnewone->setMaximumHeight(17); pnewone->setMinimumHeight(17); pnewone->setAutoFillBackground(true); QPalette palette(pnewone->palette()); palette.setColor(QPalette::Background, QColor(0,0,0)); pnewone->setPalette(palette); QHBoxLayout * phboxlayout = new QHBoxLayout(); phboxlayout->setContentsMargins(0,0,0,0); pnewone->setLayout(phboxlayout); QLabel* namelabel = new QLabel("______________________________________________________________________"); namelabel->setAttribute(Qt::WA_TranslucentBackground); QFont ftname; ftname.setPointSize(15); namelabel->setFont(ftname); QPalette paname; paname.setColor(QPalette::WindowText,Qt::gray); namelabel->setPalette(paname); namelabel->setStyleSheet("font-size : 15px;color: rgb(192,192,192);"); phboxlayout->addWidget(namelabel); pvboxlayoutall->addWidget(pnewone); } void unionaccounthistory::addinfo(std::string add, CAmount fee,bool isSend,CAmount num, QString status,QString strtime,QString txid) { LOG_WRITE(LOG_INFO,"addinfo",add.c_str(),QString::number(fee).toStdString().c_str(),QString::number(num).toStdString().c_str(),status.toStdString().c_str(),strtime.toStdString().c_str()); upgradewidget * pnewone = new upgradewidget(); pnewone->setunioninfo( add, fee,isSend, num,status, strtime); connect(pnewone,SIGNAL(lookinfo(std::string,bool,QString,QString,CAmount,CAmount,QString)),this,SLOT(lookupinfodetail(std::string,bool,QString,QString,CAmount,CAmount,QString))); pnewone->m_isunion = true; pnewone->m_txid = txid; pnewone->setMaximumHeight(70); pnewone->setMinimumHeight(70); pnewone->setAutoFillBackground(true); QPalette palette(pnewone->palette()); palette.setColor(QPalette::Background, QColor(0,0,0)); pnewone->setPalette(palette); QHBoxLayout * phboxlayout = new QHBoxLayout(); phboxlayout->setContentsMargins(0,0,0,0); pnewone->setLayout(phboxlayout); QLabel* pictypelabel = new QLabel(); pictypelabel->setAutoFillBackground(true); phboxlayout->addWidget(pictypelabel); QLabel* tag; if(isSend) { tag = new QLabel(tr("isSend")); } else { tag = new QLabel(tr("isRecv")); } tag->setAutoFillBackground(true); phboxlayout->addWidget(tag); QSpacerItem* horizontalSpacer = new QSpacerItem(40,20,QSizePolicy::Expanding); phboxlayout->addSpacerItem(horizontalSpacer); QVBoxLayout * pvboxlayout = new QVBoxLayout(); phboxlayout->addLayout(pvboxlayout); // QLabel* namelabel = new QLabel(BitcoinUnits::formatWithUnit2(0, num, false, BitcoinUnits::separatorAlways)); QLabel* namelabel; if(isSend) { namelabel= new QLabel("-" + BitcoinUnits::formatWithUnit(BitcoinUnit::IPC, num)); } else { namelabel= new QLabel("+" + BitcoinUnits::formatWithUnit(BitcoinUnit::IPC, num)); } namelabel->setAttribute(Qt::WA_TranslucentBackground); QFont ftname; ftname.setPointSize(16); namelabel->setFont(ftname); QPalette paname; paname.setColor(QPalette::WindowText,Qt::white); namelabel->setPalette(paname); namelabel->setStyleSheet("font-size : 16px;color: rgb(0,0,0);"); pvboxlayout->addWidget(namelabel); QLabel* timelabel = new QLabel(strtime); timelabel->setAttribute(Qt::WA_TranslucentBackground); QFont fttime; fttime.setPointSize(12); timelabel->setFont(fttime); QPalette patime; patime.setColor(QPalette::WindowText,Qt::white); timelabel->setPalette(patime); timelabel->setStyleSheet("font-size : 12px;color: rgb(0,0,0);"); pvboxlayout->addWidget(timelabel); QString picpath; if(isSend) { picpath = ":/res/png/sendico.png"; } else { picpath = ":/res/png/recvicon.png"; } pictypelabel->setFixedSize(41,41); pictypelabel->setPixmap(QPixmap(picpath)); pvboxlayoutall->addWidget(pnewone); } void unionaccounthistory::lookupinfodetail(std::string add,bool isSend,QString status,QString strtime,CAmount s1,CAmount s2,QString txid) { LOG_WRITE(LOG_INFO,"lookupinfodetail"); if(isSend) { Q_EMIT jumptohistorysend(add, s1,isSend,s2,status,strtime,txid); } else { Q_EMIT jumptohistoryrecv(add, s1,isSend,s2,status,strtime,txid); } } void unionaccounthistory::on_btn_back_pressed() { Q_EMIT backtoTraPage(); } void unionaccounthistory::setModel(WalletModel *_model) { this->m_pwalletmodel = _model; }
32.586854
191
0.573837
[ "vector" ]
6af268306bd2522895d3b8bbbe9331a5e0529f52
805
cpp
C++
tests/arrays/prog.cpp
mcfarljm/fortwrap
e82840a2b8d105cc3655da33dbf4b2073fa462d8
[ "MIT" ]
25
2017-06-05T01:54:15.000Z
2021-05-04T02:50:13.000Z
tests/arrays/prog.cpp
mcfarljm/fortwrap
e82840a2b8d105cc3655da33dbf4b2073fa462d8
[ "MIT" ]
1
2019-09-18T15:31:38.000Z
2019-09-19T02:45:38.000Z
tests/arrays/prog.cpp
mcfarljm/fortwrap
e82840a2b8d105cc3655da33dbf4b2073fa462d8
[ "MIT" ]
6
2017-12-03T05:35:58.000Z
2021-03-20T00:12:30.000Z
#include "FortWrap.h" #include <algorithm> // For count #include <iostream> int main(void) { // Set up v = [1,2,3,4] std::vector<int> v(4); for (std::vector<int>::size_type i=0; i<v.size(); i++) v[i] = i+1; if (FortFuncs::array_in(&v) != 10) return 1; std::vector<int> v2(10); FortFuncs::array_out(&v,&v2); if (static_cast<size_t>(count(v.begin(), v.end(), 20)) != v.size()) return 2; else if (static_cast<size_t>(count(v2.begin(), v2.end(), 30)) != v2.size()) return 3; std::vector<int> a(3), b(3); for (std::vector<int>::size_type i=0; i<a.size(); i++) { a[i] = i; b[i] = i+1; } if (FortFuncs::inner_prod(&a,&b) != 8) return 4; // Test assumed size if (FortFuncs::inner_prod_2(3,&a,&b) != 8) return 5; return 0; }
20.125
77
0.545342
[ "vector" ]
6af43416a41458c18fc7e31450014bc21cd2f4f4
8,865
cpp
C++
sparta/test/VirtualParameterTree/VPT_test.cpp
knute-sifive/map
fb25626830a56ad68ab896bcd01929023ff31c48
[ "MIT" ]
null
null
null
sparta/test/VirtualParameterTree/VPT_test.cpp
knute-sifive/map
fb25626830a56ad68ab896bcd01929023ff31c48
[ "MIT" ]
null
null
null
sparta/test/VirtualParameterTree/VPT_test.cpp
knute-sifive/map
fb25626830a56ad68ab896bcd01929023ff31c48
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> #include "sparta/sparta.hpp" #include "sparta/simulation/ParameterTree.hpp" #include "sparta/utils/SpartaAssert.hpp" #include "sparta/utils/SpartaTester.hpp" #include "sparta/utils/Printing.hpp" #include "sparta/parsers/ConfigParserYAML.hpp" #include "sparta/simulation/TreeNode.hpp" using sparta::ParameterTree; TEST_INIT; /* * Tests virtual parameter tree construction and extraction. * * This is a tree containing all command line configuration file parameters which have not * necessarily been applied to the actual sparta device (TreeNode) tree. */ int main () { // Instantiation // Specific Parameter Set ParameterTree pt; // Test various constructors in ParameterTree ParameterTree pt2; pt2 = pt; ParameterTree pt3(pt2); //EXPECT_EQUAL(pt, pt2); //EXPECT_EQUAL(pt, pt3); // Commutativity // Apply "command-line" parameters pt.set("top.foo.bar", "1", true, "origin #1"); auto tfb = pt.create("top.foo.buz"); EXPECT_EQUAL(tfb->getPath(), "top.foo.buz"); tfb->setValue("topfoobuz"); EXPECT_EQUAL(tfb->getValue(), "topfoobuz"); EXPECT_EQUAL(pt.get("top.foo.buz").getValue(), "topfoobuz"); //pt"top.foo.biz"] = "0x2"; //pt["top"]["foo"]["baz"] = "03"; pt.recursPrint(std::cout); // Read some values EXPECT_EQUAL(pt.get("top.foo.bar"), "1"); //EXPECT_EQUAL(pt["top.foo.bar"], "1"); //EXPECT_EQUAL(pt["top"]["foo"]["bar"], "1"); EXPECT_THROW(pt["top"]["nope"]); EXPECT_THROW(pt["nope"]); EXPECT_NOTHROW(pt[""]); EXPECT_NOTHROW(pt.get("")); EXPECT_EQUAL(pt.get("").getName(), ""); EXPECT_NOTHROW(pt.get("top")["foo"]); EXPECT_EQUAL(pt.get("top.foo.bar").getAs<char[]>(), "1"); EXPECT_EQUAL(pt.get("top.foo.bar").getAs<uint32_t>(), 1); EXPECT_EQUAL(pt.get("top.foo.bar").getOrigin(), "origin #1"); // Test wildcard access pt.set("top.foo.*", "2", true, "origin #2"); std::cout << "A:" << std::endl; pt.recursPrint(std::cout); EXPECT_EQUAL(pt.get("top.foo.bar"), "2"); EXPECT_EQUAL(pt.get("top.foo.bar").getOrigin(), "origin #2"); EXPECT_EQUAL(pt.get("top.foo.something_else"), "2"); pt.set("top.foo.biz", "3", true); std::cout << "B:" << std::endl; pt.recursPrint(std::cout); EXPECT_EQUAL(pt.get("top.foo.bar"), "2"); EXPECT_EQUAL(pt.get("top.foo.biz"), "3"); EXPECT_EQUAL(pt.get("top.foo.something_else"), "2"); EXPECT_EQUAL(pt.get("top.foo.something_else").getAs<uint32_t>(), 2); pt.set("top.*.biz", "4", true); std::cout << "C:" << std::endl; pt.recursPrint(std::cout); EXPECT_EQUAL(pt.get("top.foo.bar"), "2"); EXPECT_EQUAL(pt.get("top.foo.biz"), "4"); EXPECT_EQUAL(pt.get("top.foo.something_else"), "2"); EXPECT_EQUAL(pt.get("top.something_else.biz"), "4"); pt.set("top.foo+.biz", "5", true); std::cout << "D:" << std::endl; pt.recursPrint(std::cout); EXPECT_EQUAL(pt.get("top.foo.bar"), "2"); EXPECT_EQUAL(pt.get("top.foo.biz"), "4"); EXPECT_EQUAL(pt.get("top.foo.something_else"), "2"); EXPECT_EQUAL(pt.get("top.something_else.biz"), "4"); EXPECT_EQUAL(pt.get("top.fooze.biz"), "5"); EXPECT_EQUAL(pt.get("top.fooze.biz").getAs<uint32_t>(), 5); // For now parent (..) access when setting a parameter, changes NOTHING EXPECT_EQUAL(pt.set("top.foo+..", "6", true), false); std::cout << "E:" << std::endl; pt.recursPrint(std::cout); EXPECT_EQUAL(pt.get("top.foo.bar"), "2"); EXPECT_EQUAL(pt.get("top.foo.biz"), "4"); EXPECT_EQUAL(pt.get("top.foo.something_else"), "2"); EXPECT_EQUAL(pt.get("top.something_else.biz"), "4"); EXPECT_EQUAL(pt.get("top.fooze.biz"), "5"); EXPECT_EQUAL(pt.get("top.fooze.biz").getAs<uint32_t>(), 5); // Creating a node does not require it. Setting a value somewhere in it does (if that value is required) auto tfbfb1 = pt.create("top.foo.bar.fiz.bin1"); auto tfbfb2 = pt.create("top.foo.bar.fiz.bin2"); auto tfbfbpat = pt.create("top.foo.bar.fiz.bin*"); tfbfb1->setValue("NUMBER ONE", true); // Required (typical behavior) tfbfb2->setValue("NUMBER TWO", true); // Required (typical behavior) tfbfbpat->setValue("NUMBER THREE", true); // Required (typical behavior) EXPECT_TRUE(tfbfb1->isRequired()); EXPECT_TRUE(tfbfb2->isRequired()); tfbfbpat->unrequire(); // Supporting deprecated parameters, ignoring a param if missing from model, etc. EXPECT_FALSE(tfbfb1->isRequired()); // Hits "top.foo.bar.fiz.bin*" node first EXPECT_FALSE(tfbfb2->isRequired()); // Hits "top.foo.bar.fiz.bin*" node first EXPECT_FALSE(tfbfbpat->isRequired()); std::vector<const sparta::ParameterTree::Node*> unreads; pt.getUnreadValueNodes(&unreads); std::cout << "Unreads: " << unreads << std::endl; std::cout << "After all nodes" << std::endl; pt.recursPrint(std::cout); // Test unrequire at the path level pt.set("top.foo.bar.fiz.bin1", "blah", true); pt.set("top.foo.bar.fiz.bin2", "blee", true); EXPECT_TRUE(pt.isRequired("top.foo.bar.fiz.bin1")); EXPECT_TRUE(tfbfb2->isRequired()); pt.unrequire("top.foo.bar.fiz"); EXPECT_FALSE(pt.isRequired("top.foo.bar.fiz.bin1")); EXPECT_FALSE(tfbfb2->isRequired()); // Parse YAML file reading sparta::ConfigParser::YAML param_file("input.yaml", {}); param_file.allowMissingNodes(true); sparta::TreeNode tmp("top", "dummy top"); sparta::TreeNode tmp2(&tmp, "foo", "dummy top.foo"); param_file.consumeParameters(&tmp, false); // verbose? //ParameterTree ypt = param_file.getParameterTree(); // Copy std::cout << "ParameterTree from config file" << std::endl; param_file.getParameterTree().recursPrint(std::cout); EXPECT_EQUAL(param_file.getParameterTree().get("top.foo.bar"), "0x001"); EXPECT_EQUAL(param_file.getParameterTree().get("top.foo.biz"), "0x2"); EXPECT_EQUAL(param_file.getParameterTree().get("top.foo.baz"), "03"); EXPECT_EQUAL(param_file.getParameterTree().get("top.foo.a.b.c"), "abc_value"); EXPECT_EQUAL(param_file.getParameterTree().get("top.fiz.bin"), "top.fiz.bin"); EXPECT_EQUAL(param_file.getParameterTree().get("top.something_else.pez"), "top.*.pez"); EXPECT_EQUAL(param_file.getParameterTree().get("top.foo.poz"), "0"); EXPECT_EQUAL(param_file.getParameterTree().get("top.fiz.piz").getValue(), "[1,2,3]"); EXPECT_EQUAL(param_file.getParameterTree().get("top.fiz.paz").getValue(), "[[1,2,3],[4,5,6],[],[7,8,9]]"); EXPECT_EQUAL(param_file.getParameterTree().get("top.fiz.puz").getValue(), "[a,b,c,\"\"]"); EXPECT_FALSE(param_file.getParameterTree().isRead("top.foo.eiohewfoewhjfoihefwo9hwe")); EXPECT_FALSE(param_file.getParameterTree().isRead("top.something_else.efoejhwfiojn390ewjfofief")); EXPECT_FALSE(param_file.getParameterTree().isRead("top.foo.baro9jkdfoijdfoindf")); EXPECT_FALSE(param_file.getParameterTree().isRead("top.foo890hiw8nhfedf.bar")); EXPECT_FALSE(param_file.getParameterTree().isRead("top.foo.a.b.c.d.e.f.g")); EXPECT_FALSE(param_file.getParameterTree().isRead("top")); EXPECT_FALSE(param_file.getParameterTree().isRead("top.foo")); EXPECT_TRUE(param_file.getParameterTree().isRead("top.foo.bar")); EXPECT_TRUE(param_file.getParameterTree().isRead("top.foo.biz")); EXPECT_TRUE(param_file.getParameterTree().isRead("top.foo.baz")); EXPECT_TRUE(param_file.getParameterTree().isRead("top.foo.a.b.c")); EXPECT_TRUE(param_file.getParameterTree().isRead("top.fiz.bin")); EXPECT_TRUE(param_file.getParameterTree().isRead("top.something_else.pez")); EXPECT_FALSE(param_file.getParameterTree().isRead("top.foo.bar.fiz.bin")); // Test PT assignment pt2 = pt; ParameterTree pt4; pt4.set("top.biz.buz", "pt4", true); pt4 = param_file.getParameterTree(); std::cout << "After cloning yaml file output tree to pt4" << std::endl; pt4.recursPrint(std::cout); EXPECT_THROW(pt4.get("top.biz.buz")); // Cleared as part of pt3 = ... EXPECT_EQUAL(pt4.get("top.foo.a.b.c"), "abc_value"); EXPECT_EQUAL(pt4.get("top.fiz.bin"), "top.fiz.bin"); EXPECT_EQUAL(pt4.get("top.something_else.pez"), "top.*.pez"); // Test PT comparison //EXPECT_EQUAL(pt, pt2); pt2.set("top.foo.bar", "nothing will possilbly match this value!!!", true); //EXPECT_NOTEQUAL(pt, pt2); pt2.clear(); std::cout << "After clearing pt2" << std::endl; pt2.recursPrint(std::cout); // Walk to apply to a device tree // Test Value (get, access, invalid, copy-construct, assign, lexical cast access) //Value v = pt.get("top.foo"); //Value v2; //v2 = v; //Value v3(v2); //EXPECT_EQUAL(v, v2); //EXPECT_EQUAL(v, v3); // Commutativity // Test Node (get, access, copy-construct) // Done REPORT_ERROR; return ERROR_CODE; }
40.479452
110
0.657191
[ "vector", "model" ]
6af8a626b2ec0202719d4ef3908402a2e596fee2
2,012
cpp
C++
src/net/TgLongPoll.cpp
dendisuhubdy/tgbot-cpp
89ec4e3d1186e1a250adb18cb6a8cce7c4756bf6
[ "MIT" ]
1
2020-07-03T20:09:30.000Z
2020-07-03T20:09:30.000Z
src/net/TgLongPoll.cpp
dendisuhubdy/tgbot-cpp
89ec4e3d1186e1a250adb18cb6a8cce7c4756bf6
[ "MIT" ]
1
2018-11-25T12:15:51.000Z
2018-11-26T12:34:40.000Z
src/net/TgLongPoll.cpp
dendisuhubdy/tgbot-cpp
89ec4e3d1186e1a250adb18cb6a8cce7c4756bf6
[ "MIT" ]
1
2018-11-12T12:56:23.000Z
2018-11-12T12:56:23.000Z
/* * Copyright (c) 2015 Oleg Morozenkov * * 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 "tgbot/net/TgLongPoll.h" namespace TgBot { TgLongPoll::TgLongPoll(const Api* api, const EventHandler* eventHandler, int32_t limit, int32_t timeout, const std::shared_ptr<std::vector<std::string>>& allowupdates) : _api(api), _eventHandler(eventHandler), _limit(limit), _timeout(timeout), _allowupdates(allowupdates) { } TgLongPoll::TgLongPoll(const Bot& bot, int32_t limit, int32_t timeout, const std::shared_ptr<std::vector<std::string>>& allowupdates) : TgLongPoll(&bot.getApi(), &bot.getEventHandler(), limit, timeout, allowupdates) { } void TgLongPoll::start() { std::vector<Update::Ptr> updates = _api->getUpdates(_lastUpdateId, _limit, _timeout, _allowupdates); for (Update::Ptr& item : updates) { if (item->updateId >= _lastUpdateId) { _lastUpdateId = item->updateId + 1; } _eventHandler->handleUpdate(item); } } }
43.73913
167
0.735586
[ "vector" ]
6afc9ed030271b93464f9cc21ed6f8bada7990eb
6,111
cpp
C++
modfile/records/SrMatoRecord.cpp
uesp/tes5lib
07b052983f2e26b9ba798f234ada00f83c90e9a4
[ "MIT" ]
11
2015-07-19T08:33:00.000Z
2021-07-28T17:40:26.000Z
modfile/records/SrMatoRecord.cpp
uesp/tes5lib
07b052983f2e26b9ba798f234ada00f83c90e9a4
[ "MIT" ]
null
null
null
modfile/records/SrMatoRecord.cpp
uesp/tes5lib
07b052983f2e26b9ba798f234ada00f83c90e9a4
[ "MIT" ]
1
2015-02-28T22:52:18.000Z
2015-02-28T22:52:18.000Z
/*=========================================================================== * * File: SrMatoRecord.CPP * Author: Dave Humphrey (dave@uesp.net) * Created On: 5 December 2011 * * Description * *=========================================================================*/ /* Include Files */ #include "srMatorecord.h" /*=========================================================================== * * Begin Subrecord Creation Array * *=========================================================================*/ BEGIN_SRSUBRECCREATE(CSrMatoRecord, CSrIdRecord) DEFINE_SRSUBRECCREATE(SR_NAME_MODL, CSrStringSubrecord::Create) DEFINE_SRSUBRECCREATE(SR_NAME_DATA, CSrDataSubrecord::Create) DEFINE_SRSUBRECCREATE(SR_NAME_DNAM, CSrDataSubrecord::Create) END_SRSUBRECCREATE() /*=========================================================================== * End of Subrecord Creation Array *=========================================================================*/ /*=========================================================================== * * Begin CSrIdRecord Field Map * *=========================================================================*/ BEGIN_SRFIELDMAP(CSrMatoRecord, CSrIdRecord) ADD_SRFIELDALL("Model", SR_FIELD_MODEL, 0, CSrMatoRecord, FieldModel) END_SRFIELDMAP() /*=========================================================================== * End of CObRecord Field Map *=========================================================================*/ /*=========================================================================== * * Class CSrMatoRecord Constructor * *=========================================================================*/ CSrMatoRecord::CSrMatoRecord () { m_pModlData = NULL; m_pDataData = NULL; m_pDnamData = NULL; } /*=========================================================================== * End of Class CSrMatoRecord Constructor *=========================================================================*/ /*=========================================================================== * * Class CSrMatoRecord Method - void Destroy (void); * *=========================================================================*/ void CSrMatoRecord::Destroy (void) { m_pModlData = NULL; m_pDataData = NULL; m_pDnamData = NULL; CSrIdRecord::Destroy(); } /*=========================================================================== * End of Class Method CSrMatoRecord::Destroy() *=========================================================================*/ /*=========================================================================== * * Class CSrMatoRecord Method - void InitializeNew (void); * *=========================================================================*/ void CSrMatoRecord::InitializeNew (void) { CSrIdRecord::InitializeNew(); } /*=========================================================================== * End of Class Method CSrMatoRecord::InitializeNew() *=========================================================================*/ /*=========================================================================== * * Class CSrMatoRecord Event - void OnAddSubrecord (pSubrecord); * *=========================================================================*/ void CSrMatoRecord::OnAddSubrecord (CSrSubrecord* pSubrecord) { if (pSubrecord->GetRecordType() == SR_NAME_MODL) { m_pModlData = SrCastClass(CSrStringSubrecord, pSubrecord); } else if (pSubrecord->GetRecordType() == SR_NAME_DATA) { m_pDataData = SrCastClass(CSrDataSubrecord, pSubrecord); } else if (pSubrecord->GetRecordType() == SR_NAME_DNAM) { m_pDnamData = SrCastClass(CSrDataSubrecord, pSubrecord); } else { CSrIdRecord::OnAddSubrecord(pSubrecord); } } /*=========================================================================== * End of Class Event CSrMatoRecord::OnAddSubRecord() *=========================================================================*/ /*=========================================================================== * * Class CSrMatoRecord Event - void OnDeleteSubrecord (pSubrecord); * *=========================================================================*/ void CSrMatoRecord::OnDeleteSubrecord (CSrSubrecord* pSubrecord) { if (m_pModlData == pSubrecord) m_pModlData = NULL; else if (m_pDataData == pSubrecord) m_pDataData = NULL; else if (m_pDnamData == pSubrecord) m_pDnamData = NULL; else CSrIdRecord::OnDeleteSubrecord(pSubrecord); } /*=========================================================================== * End of Class Event CSrMatoRecord::OnDeleteSubrecord() *=========================================================================*/ /*=========================================================================== * * Begin CSrMatoRecord Get Field Methods * *=========================================================================*/ /*=========================================================================== * End of CSrMatoRecord Get Field Methods *=========================================================================*/ /*=========================================================================== * * Begin CSrMatoRecord Compare Field Methods * *=========================================================================*/ /*=========================================================================== * End of CSrMatoRecord Compare Field Methods *=========================================================================*/ /*=========================================================================== * * Begin CSrMatoRecord Set Field Methods * *=========================================================================*/ /*=========================================================================== * End of CSrMatoRecord Set Field Methods *=========================================================================*/
35.323699
78
0.32286
[ "model" ]
13923d3de57128e8de209fbdfb347100ffb2e827
1,538
hpp
C++
unittests/mcrepo/transaction.hpp
paulhuggett/pstore2
a0c663d10a2e2713fdf39ecdae1f9c1e96041f5c
[ "Apache-2.0" ]
11
2018-02-02T21:24:49.000Z
2020-12-11T04:06:03.000Z
unittests/mcrepo/transaction.hpp
SNSystems/pstore
74e9dd960245d6bfc125af03ed964d8ad660a62d
[ "Apache-2.0" ]
63
2018-02-05T17:24:59.000Z
2022-03-22T17:26:28.000Z
unittests/mcrepo/transaction.hpp
paulhuggett/pstore
067be94d87c87fce524c8d76c6f47c347d8f1853
[ "Apache-2.0" ]
5
2020-01-13T22:47:11.000Z
2021-05-14T09:31:15.000Z
//===- unittests/mcrepo/transaction.hpp -------------------*- mode: C++ -*-===// //* _ _ _ * //* | |_ _ __ __ _ _ __ ___ __ _ ___| |_(_) ___ _ __ * //* | __| '__/ _` | '_ \/ __|/ _` |/ __| __| |/ _ \| '_ \ * //* | |_| | | (_| | | | \__ \ (_| | (__| |_| | (_) | | | | * //* \__|_| \__,_|_| |_|___/\__,_|\___|\__|_|\___/|_| |_| * //* * //===----------------------------------------------------------------------===// // // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions. // See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license // information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef MCREPO_TRANSACTION_HPP #define MCREPO_TRANSACTION_HPP #include "gmock/gmock.h" #include <memory> #include <vector> #include "pstore/core/address.hpp" class transaction { public: using storage_type = std::map<std::uint8_t *, std::shared_ptr<std::uint8_t>>; auto allocate (std::size_t size, unsigned align) -> pstore::address; auto getrw (pstore::address addr, std::size_t size) -> std::shared_ptr<void>; auto alloc_rw (std::size_t size, unsigned align) -> std::pair<std::shared_ptr<void>, pstore::address>; storage_type const & get_storage () const { return storage_; } private: storage_type storage_; }; #endif // MCREPO_TRANSACTION_HPP
35.767442
82
0.509753
[ "vector" ]
139f5d48c516b12992d969dedf09eb95b2f1b51e
1,971
cpp
C++
SourceCode/Prototypes/MinimumSpanningTree/MinimumSpanningTree/main.cpp
JosephBarber96/FinalProject
60400efa64c36b7cdbc975e0df7b937cbaae1d0b
[ "MIT" ]
2
2019-05-18T21:37:17.000Z
2021-07-16T04:08:23.000Z
SourceCode/Prototypes/MinimumSpanningTree/MinimumSpanningTree/main.cpp
JosephBarber96/FinalProject
60400efa64c36b7cdbc975e0df7b937cbaae1d0b
[ "MIT" ]
1
2020-04-29T05:37:48.000Z
2020-04-29T11:14:57.000Z
SourceCode/Prototypes/MinimumSpanningTree/MinimumSpanningTree/main.cpp
JosephBarber96/FinalProject
60400efa64c36b7cdbc975e0df7b937cbaae1d0b
[ "MIT" ]
1
2021-07-16T04:08:31.000Z
2021-07-16T04:08:31.000Z
#include <iostream> #include <vector> #include <ctime> #include <stdlib.h> #include <glut.h> #include "Defines.h" #include "Edge.h" #include "MinimumSpanningTree.h" #include "Node.h" #include "V2.h" MinimumSpanningTree* mst; void Display() { glClear(GL_COLOR_BUFFER_BIT); // Draw all edges glColor4f(0.8, 1.0, 0.8, 0.1); glLineWidth(1.0); for (Edge* edge : mst->GetAllEdges()) { glBegin(GL_LINE_STRIP); glVertex2f(edge->start->position->x, edge->start->position->y); glVertex2f(edge->end->position->x, edge->end->position->y); glEnd(); } // Draw only minimum spanning graph glColor3f(0.0, 0.0, 1.0); glLineWidth(5.0); for (Edge edge : mst->GetTreeEdges()) { glBegin(GL_LINE_STRIP); glVertex2f(edge.start->position->x, edge.start->position->y); glVertex2f(edge.end->position->x, edge.end->position->y); glEnd(); } // Draw nodes glPointSize(6.0f); glColor3f(1.0, 0.0, 0.0); glBegin(GL_POINTS); for (Node* node : mst->GetNodes()) { glVertex2f(node->position->x, node->position->y); } glEnd(); glutSwapBuffers(); glutPostRedisplay(); } void InitGL() { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Matrix mode glMatrixMode(GL_PROJECTION); // Setup coordinate system gluOrtho2D(0, WIN_SIZE, 0, WIN_SIZE); } int main(int argc, char* argv[]) { // Seed random srand(time(0)); // Minimum spanning tree mst = new MinimumSpanningTree; // Plot points int numOfPoints = 50; mst->SpawnPoints(numOfPoints, 0, 0, WIN_SIZE, WIN_SIZE); // Assign neighbours float maxDist = WIN_SIZE / 2; mst->AssignNighbours(maxDist); // Edges mst->CreateAllEdges(); // Sort the MST mst->Sort(); std::cout << "The complete MST has " << mst->GetTreeEdges().size() << " edges."; // Init OpenGL glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(WIN_SIZE, WIN_SIZE); glutCreateWindow("Minimum spanning tree."); InitGL(); // Display glutDisplayFunc(Display); glutMainLoop(); return 0; }
18.951923
81
0.676814
[ "vector" ]
13a02694d6dcb1fc4c1b53d00fa0550d53704051
46,275
tcc
C++
BinaryMeshFitting/mic/vector.tcc
torss/BinaryMeshFitting
d44ee7c995d461ae704f6da83f2a0b96c3957580
[ "MIT" ]
229
2018-03-07T05:25:08.000Z
2022-02-21T22:31:41.000Z
BinaryMeshFitting/mic/vector.tcc
torss/BinaryMeshFitting
d44ee7c995d461ae704f6da83f2a0b96c3957580
[ "MIT" ]
2
2018-03-09T01:52:56.000Z
2019-10-19T09:29:42.000Z
BinaryMeshFitting/mic/vector.tcc
torss/BinaryMeshFitting
d44ee7c995d461ae704f6da83f2a0b96c3957580
[ "MIT" ]
20
2018-03-08T18:49:49.000Z
2021-12-12T11:22:12.000Z
/* This file is part of the Vc library. {{{ Copyright © 2010-2015 Matthias Kretz <kretz@kde.org> 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 names of contributing organizations 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 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 <type_traits> #include "../common/x86_prefetches.h" #include "interleaveimpl.h" #include "debug.h" #include "macros.h" namespace Vc_VERSIONED_NAMESPACE { namespace Detail { // bitwise operators {{{1 template <typename T> Vc_INTRINSIC MIC::Vector<T> operator^(MIC::Vector<T> a, MIC::Vector<T> b) { return xor_(a.data(), b.data()); } template <typename T> Vc_INTRINSIC MIC::Vector<T> operator&(MIC::Vector<T> a, MIC::Vector<T> b) { return and_(a.data(), b.data()); } template <typename T> Vc_INTRINSIC MIC::Vector<T> operator|(MIC::Vector<T> a, MIC::Vector<T> b) { return or_(a.data(), b.data()); } // compare operators {{{1 Vc_INTRINSIC MIC::double_m operator==(MIC::double_v a, MIC::double_v b) { return _mm512_cmp_pd_mask(a.data(), b.data(), _CMP_EQ_OQ); } Vc_INTRINSIC MIC:: float_m operator==(MIC:: float_v a, MIC:: float_v b) { return _mm512_cmp_ps_mask(a.data(), b.data(), _CMP_EQ_OQ); } Vc_INTRINSIC MIC:: int_m operator==(MIC:: int_v a, MIC:: int_v b) { return _mm512_cmp_epi32_mask(a.data(), b.data(), _MM_CMPINT_EQ); } Vc_INTRINSIC MIC:: uint_m operator==(MIC:: uint_v a, MIC:: uint_v b) { return _mm512_cmp_epu32_mask(a.data(), b.data(), _MM_CMPINT_EQ); } Vc_INTRINSIC MIC:: short_m operator==(MIC:: short_v a, MIC:: short_v b) { return _mm512_cmp_epi32_mask(a.data(), b.data(), _MM_CMPINT_EQ); } Vc_INTRINSIC MIC::double_m operator!=(MIC::double_v a, MIC::double_v b) { return _mm512_cmp_pd_mask(a.data(), b.data(), _CMP_NEQ_UQ); } Vc_INTRINSIC MIC:: float_m operator!=(MIC:: float_v a, MIC:: float_v b) { return _mm512_cmp_ps_mask(a.data(), b.data(), _CMP_NEQ_UQ); } Vc_INTRINSIC MIC:: int_m operator!=(MIC:: int_v a, MIC:: int_v b) { return _mm512_cmp_epi32_mask(a.data(), b.data(), _MM_CMPINT_NE); } Vc_INTRINSIC MIC:: uint_m operator!=(MIC:: uint_v a, MIC:: uint_v b) { return _mm512_cmp_epu32_mask(a.data(), b.data(), _MM_CMPINT_NE); } Vc_INTRINSIC MIC:: short_m operator!=(MIC:: short_v a, MIC:: short_v b) { return _mm512_cmp_epi32_mask(a.data(), b.data(), _MM_CMPINT_NE); } Vc_INTRINSIC MIC::double_m operator>=(MIC::double_v a, MIC::double_v b) { return _mm512_cmp_pd_mask(a.data(), b.data(), _CMP_NLT_US); } Vc_INTRINSIC MIC:: float_m operator>=(MIC:: float_v a, MIC:: float_v b) { return _mm512_cmp_ps_mask(a.data(), b.data(), _CMP_NLT_US); } Vc_INTRINSIC MIC:: int_m operator>=(MIC:: int_v a, MIC:: int_v b) { return _mm512_cmp_epi32_mask(a.data(), b.data(), _MM_CMPINT_NLT); } Vc_INTRINSIC MIC:: uint_m operator>=(MIC:: uint_v a, MIC:: uint_v b) { return _mm512_cmp_epu32_mask(a.data(), b.data(), _MM_CMPINT_NLT); } Vc_INTRINSIC MIC:: short_m operator>=(MIC:: short_v a, MIC:: short_v b) { return _mm512_cmp_epi32_mask(a.data(), b.data(), _MM_CMPINT_NLT); } Vc_INTRINSIC MIC::double_m operator<=(MIC::double_v a, MIC::double_v b) { return _mm512_cmp_pd_mask(a.data(), b.data(), _CMP_LE_OS); } Vc_INTRINSIC MIC:: float_m operator<=(MIC:: float_v a, MIC:: float_v b) { return _mm512_cmp_ps_mask(a.data(), b.data(), _CMP_LE_OS); } Vc_INTRINSIC MIC:: int_m operator<=(MIC:: int_v a, MIC:: int_v b) { return _mm512_cmp_epi32_mask(a.data(), b.data(), _MM_CMPINT_LE); } Vc_INTRINSIC MIC:: uint_m operator<=(MIC:: uint_v a, MIC:: uint_v b) { return _mm512_cmp_epu32_mask(a.data(), b.data(), _MM_CMPINT_LE); } Vc_INTRINSIC MIC:: short_m operator<=(MIC:: short_v a, MIC:: short_v b) { return _mm512_cmp_epi32_mask(a.data(), b.data(), _MM_CMPINT_LE); } Vc_INTRINSIC MIC::double_m operator> (MIC::double_v a, MIC::double_v b) { return _mm512_cmp_pd_mask(a.data(), b.data(), _CMP_NLE_US); } Vc_INTRINSIC MIC:: float_m operator> (MIC:: float_v a, MIC:: float_v b) { return _mm512_cmp_ps_mask(a.data(), b.data(), _CMP_NLE_US); } Vc_INTRINSIC MIC:: int_m operator> (MIC:: int_v a, MIC:: int_v b) { return _mm512_cmp_epi32_mask(a.data(), b.data(), _MM_CMPINT_NLE); } Vc_INTRINSIC MIC:: uint_m operator> (MIC:: uint_v a, MIC:: uint_v b) { return _mm512_cmp_epu32_mask(a.data(), b.data(), _MM_CMPINT_NLE); } Vc_INTRINSIC MIC:: short_m operator> (MIC:: short_v a, MIC:: short_v b) { return _mm512_cmp_epi32_mask(a.data(), b.data(), _MM_CMPINT_NLE); } Vc_INTRINSIC MIC::double_m operator< (MIC::double_v a, MIC::double_v b) { return _mm512_cmp_pd_mask(a.data(), b.data(), _CMP_LT_OS); } Vc_INTRINSIC MIC:: float_m operator< (MIC:: float_v a, MIC:: float_v b) { return _mm512_cmp_ps_mask(a.data(), b.data(), _CMP_LT_OS); } Vc_INTRINSIC MIC:: int_m operator< (MIC:: int_v a, MIC:: int_v b) { return _mm512_cmp_epi32_mask(a.data(), b.data(), _MM_CMPINT_LT); } Vc_INTRINSIC MIC:: uint_m operator< (MIC:: uint_v a, MIC:: uint_v b) { return _mm512_cmp_epu32_mask(a.data(), b.data(), _MM_CMPINT_LT); } Vc_INTRINSIC MIC:: short_m operator< (MIC:: short_v a, MIC:: short_v b) { return _mm512_cmp_epi32_mask(a.data(), b.data(), _MM_CMPINT_LT); } // only unsigned integers have well-defined behavior on over-/underflow Vc_INTRINSIC MIC::ushort_m operator==(MIC::ushort_v a, MIC::ushort_v b) { return _mm512_cmpeq_epu32_mask(and_(a.data(), MIC::_set1(0xffff)), and_(b.data(), MIC::_set1(0xffff))); } Vc_INTRINSIC MIC::ushort_m operator!=(MIC::ushort_v a, MIC::ushort_v b) { return _mm512_cmpneq_epu32_mask(and_(a.data(), MIC::_set1(0xffff)), and_(b.data(), MIC::_set1(0xffff))); } Vc_INTRINSIC MIC::ushort_m operator>=(MIC::ushort_v a, MIC::ushort_v b) { return _mm512_cmpge_epu32_mask(and_(a.data(), MIC::_set1(0xffff)), and_(b.data(), MIC::_set1(0xffff))); } Vc_INTRINSIC MIC::ushort_m operator<=(MIC::ushort_v a, MIC::ushort_v b) { return _mm512_cmple_epu32_mask(and_(a.data(), MIC::_set1(0xffff)), and_(b.data(), MIC::_set1(0xffff))); } Vc_INTRINSIC MIC::ushort_m operator> (MIC::ushort_v a, MIC::ushort_v b) { return _mm512_cmpgt_epu32_mask(and_(a.data(), MIC::_set1(0xffff)), and_(b.data(), MIC::_set1(0xffff))); } Vc_INTRINSIC MIC::ushort_m operator< (MIC::ushort_v a, MIC::ushort_v b) { return _mm512_cmplt_epu32_mask(and_(a.data(), MIC::_set1(0xffff)), and_(b.data(), MIC::_set1(0xffff))); } // only unsigned integers have well-defined behavior on over-/underflow Vc_INTRINSIC MIC::uchar_m operator==(MIC::uchar_v a, MIC::uchar_v b) { return _mm512_cmpeq_epu32_mask (and_(a.data(), MIC::_set1(0xff)), and_(b.data(), MIC::_set1(0xff))); } Vc_INTRINSIC MIC::uchar_m operator!=(MIC::uchar_v a, MIC::uchar_v b) { return _mm512_cmpneq_epu32_mask(and_(a.data(), MIC::_set1(0xff)), and_(b.data(), MIC::_set1(0xff))); } Vc_INTRINSIC MIC::uchar_m operator>=(MIC::uchar_v a, MIC::uchar_v b) { return _mm512_cmpge_epu32_mask (and_(a.data(), MIC::_set1(0xff)), and_(b.data(), MIC::_set1(0xff))); } Vc_INTRINSIC MIC::uchar_m operator> (MIC::uchar_v a, MIC::uchar_v b) { return _mm512_cmpgt_epu32_mask (and_(a.data(), MIC::_set1(0xff)), and_(b.data(), MIC::_set1(0xff))); } Vc_INTRINSIC MIC::uchar_m operator<=(MIC::uchar_v a, MIC::uchar_v b) { return _mm512_cmple_epu32_mask (and_(a.data(), MIC::_set1(0xff)), and_(b.data(), MIC::_set1(0xff))); } Vc_INTRINSIC MIC::uchar_m operator< (MIC::uchar_v a, MIC::uchar_v b) { return _mm512_cmplt_epu32_mask (and_(a.data(), MIC::_set1(0xff)), and_(b.data(), MIC::_set1(0xff))); } // arithmetic operators {{{1 template <typename T> Vc_INTRINSIC MIC::Vector<T> operator+(MIC::Vector<T> a, MIC::Vector<T> b) { return add(a.data(), b.data(), T()); } template <typename T> Vc_INTRINSIC MIC::Vector<T> operator-(MIC::Vector<T> a, MIC::Vector<T> b) { return sub(a.data(), b.data(), T()); } template <typename T> Vc_INTRINSIC MIC::Vector<T> operator*(MIC::Vector<T> a, MIC::Vector<T> b) { return mul(a.data(), b.data(), T()); } template <typename T> Vc_INTRINSIC MIC::Vector<T> operator/(MIC::Vector<T> a, MIC::Vector<T> b) { return div(a.data(), b.data(), T()); } template <typename T> Vc_INTRINSIC enable_if<std::is_integral<T>::value, MIC::Vector<T>> operator%( MIC::Vector<T> a, MIC::Vector<T> b) { return rem(a.data(), b.data(), T()); //return a - a / b * b; } // }}}1 } // namespace Detail // LoadHelper {{{1 namespace { template<typename V, typename T> struct LoadHelper2; template<typename V> struct LoadHelper/*{{{*/ { typedef typename V::VectorType VectorType; static Vc_INTRINSIC VectorType _load(const void *m, _MM_UPCONV_PS_ENUM upconv, int memHint) { return _mm512_extload_ps(m, upconv, _MM_BROADCAST32_NONE, memHint); } static Vc_INTRINSIC VectorType _load(const void *m, _MM_UPCONV_PD_ENUM upconv, int memHint) { return _mm512_extload_pd(m, upconv, _MM_BROADCAST64_NONE, memHint); } static Vc_INTRINSIC VectorType _load(const void *m, _MM_UPCONV_EPI32_ENUM upconv, int memHint) { return _mm512_extload_epi32(m, upconv, _MM_BROADCAST32_NONE, memHint); } static Vc_INTRINSIC VectorType _loadu(const void *m, _MM_UPCONV_PS_ENUM upconv, int memHint) { return MIC::mm512_loadu_ps(m, upconv, memHint); } static Vc_INTRINSIC VectorType _loadu(const void *m, _MM_UPCONV_PD_ENUM upconv, int memHint) { return MIC::mm512_loadu_pd(m, upconv, memHint); } static Vc_INTRINSIC VectorType _loadu(const void *m, _MM_UPCONV_EPI32_ENUM upconv, int memHint) { return MIC::mm512_loadu_epi32(m, upconv, memHint); } template<typename T, typename Flags> static Vc_INTRINSIC VectorType load(const T *mem, Flags) { return LoadHelper2<V, T>::template load<Flags>(mem); } };/*}}}*/ template<typename V, typename T = typename V::VectorEntryType> struct LoadHelper2 { typedef typename V::VectorType VectorType; template<typename Flags> static Vc_INTRINSIC VectorType genericLoad(const T *mem, typename Flags::EnableIfAligned = nullptr) { return LoadHelper<V>::_load(mem, MIC::UpDownConversion<typename V::VectorEntryType, T>(), _MM_HINT_NONE); } template<typename Flags> static Vc_INTRINSIC VectorType genericLoad(const T *mem, typename Flags::EnableIfUnalignedNotStreaming = nullptr) { return LoadHelper<V>::_loadu(mem, MIC::UpDownConversion<typename V::VectorEntryType, T>(), _MM_HINT_NONE); } template<typename Flags> static Vc_INTRINSIC VectorType genericLoad(const T *mem, typename Flags::EnableIfStreaming = nullptr) { return LoadHelper<V>::_load(mem, MIC::UpDownConversion<typename V::VectorEntryType, T>(), _MM_HINT_NT); } template<typename Flags> static Vc_INTRINSIC VectorType genericLoad(const T *mem, typename Flags::EnableIfUnalignedAndStreaming = nullptr) { return LoadHelper<V>::_loadu(mem, MIC::UpDownConversion<typename V::VectorEntryType, T>(), _MM_HINT_NT); } template<typename Flags> static Vc_INTRINSIC VectorType load(const T *mem) { return genericLoad<Flags>(mem); } }; template<> template<typename Flags> Vc_INTRINSIC __m512 LoadHelper2<MIC::float_v, double>::load(const double *mem) { return MIC::mic_cast<__m512>(_mm512_mask_permute4f128_epi32(MIC::mic_cast<__m512i>( _mm512_cvt_roundpd_pslo(LoadHelper<MIC::double_v>::load(&mem[0], Flags()), _MM_FROUND_CUR_DIRECTION)), 0xff00, MIC::mic_cast<__m512i>( _mm512_cvt_roundpd_pslo(LoadHelper<MIC::double_v>::load(&mem[MIC::double_v::Size], Flags()), _MM_FROUND_CUR_DIRECTION)), _MM_PERM_BABA)); } template<> template<typename Flags> Vc_INTRINSIC __m512 LoadHelper2<MIC::float_v, int>::load(const int *mem) { return MIC::convert<int, float>(LoadHelper<MIC::int_v>::load(mem, Flags())); } template<> template<typename Flags> Vc_INTRINSIC __m512 LoadHelper2<MIC::float_v, unsigned int>::load(const unsigned int *mem) { return MIC::convert<unsigned int, float>(LoadHelper<MIC::uint_v>::load(mem, Flags())); } } // anonymous namespace // constants {{{1 template <typename T> Vc_ALWAYS_INLINE Vector<T, VectorAbi::Mic>::Vector(VectorSpecialInitializerZero) : d(Detail::zero<VectorType>()) { } template <typename T> Vc_ALWAYS_INLINE Vector<T, VectorAbi::Mic>::Vector(VectorSpecialInitializerOne) : d(Detail::one(EntryType())) { } template <typename T> Vc_ALWAYS_INLINE Vector<T, VectorAbi::Mic>::Vector( VectorSpecialInitializerIndexesFromZero) : d(LoadHelper<Vector<T, VectorAbi::Mic>>::load(MIC::IndexesFromZeroHelper<T>(), Aligned)) { } template <> Vc_ALWAYS_INLINE MIC::float_v::Vector(VectorSpecialInitializerIndexesFromZero) : d(_mm512_extload_ps(&MIC::_IndexesFromZero, _MM_UPCONV_PS_SINT8, _MM_BROADCAST32_NONE, _MM_HINT_NONE)) { } template <> Vc_ALWAYS_INLINE MIC::double_v::Vector(VectorSpecialInitializerIndexesFromZero) : d(MIC::convert<int, double>(MIC::int_v::IndexesFromZero().data())) { } // loads {{{1 template <typename T> template <typename U, typename Flags> Vc_INTRINSIC typename Vector<T, VectorAbi::Mic>::template load_concept<U, Flags>::type Vector<T, VectorAbi::Mic>::load(const U *x, Flags flags) { Common::handleLoadPrefetches(x, flags); d.v() = LoadHelper<Vector<T, VectorAbi::Mic>>::load(x, flags); } /////////////////////////////////////////////////////////////////////////////////////////// // zeroing {{{1 template<typename T> Vc_INTRINSIC void Vector<T, VectorAbi::Mic>::setZero() { data() = Detail::zero<VectorType>(); } template<typename T> Vc_INTRINSIC void Vector<T, VectorAbi::Mic>::setZero(MaskArgument k) { data() = MIC::_xor(data(), k.data(), data(), data()); } template<typename T> Vc_INTRINSIC void Vector<T, VectorAbi::Mic>::setZeroInverted(MaskArgument k) { data() = MIC::_xor(data(), (!k).data(), data(), data()); } template<typename T> Vc_INTRINSIC void Vector<T, VectorAbi::Mic>::setQnan() { data() = MIC::allone<VectorType>(); } template<typename T> Vc_INTRINSIC void Vector<T, VectorAbi::Mic>::setQnan(MaskArgument k) { data() = MIC::mask_mov(data(), k.data(), MIC::allone<VectorType>()); } /////////////////////////////////////////////////////////////////////////////////////////// // assign {{{1 template<> Vc_INTRINSIC void MIC::double_v::assign(MIC::double_v v, MIC::double_m m) { d.v() = _mm512_mask_mov_pd(d.v(), m.data(), v.d.v()); } template<> Vc_INTRINSIC void MIC::float_v::assign(MIC::float_v v, MIC::float_m m) { d.v() = _mm512_mask_mov_ps(d.v(), m.data(), v.d.v()); } template<> Vc_INTRINSIC void MIC::int_v::assign(MIC::int_v v, MIC::int_m m) { d.v() = _mm512_mask_mov_epi32(d.v(), m.data(), v.d.v()); } template<> Vc_INTRINSIC void MIC::uint_v::assign(MIC::uint_v v, MIC::uint_m m) { d.v() = _mm512_mask_mov_epi32(d.v(), m.data(), v.d.v()); } template<> Vc_INTRINSIC void MIC::short_v::assign(MIC::short_v v, MIC::short_m m) { d.v() = _mm512_mask_mov_epi32(d.v(), m.data(), v.d.v()); } template<> Vc_INTRINSIC void MIC::ushort_v::assign(MIC::ushort_v v, MIC::ushort_m m) { d.v() = _mm512_mask_mov_epi32(d.v(), m.data(), v.d.v()); } // stores {{{1 template <typename V> Vc_INTRINSIC V foldAfterOverflow(V vector) { return vector; } Vc_INTRINSIC MIC::ushort_v foldAfterOverflow(MIC::ushort_v vector) { using Detail::operator&; return vector & MIC::ushort_v(0xffffu); } namespace MIC { template <typename Parent, typename T> template <typename U, typename Flags, typename std::enable_if<std::is_arithmetic<U>::value, int>::type> Vc_INTRINSIC void StoreMixin<Parent, T>::store(U *mem, Flags flags) const { Common::handleStorePrefetches(mem, flags); MicIntrinsics::store<Flags>(mem, foldAfterOverflow(*static_cast<const Parent *>(this)).data(), UpDownC<U>()); } } // namespace MIC constexpr int alignrCount(int rotationStride, int offset) { return 16 - (rotationStride * offset > 16 ? 16 : rotationStride * offset); } template<int rotationStride> inline __m512i rotationHelper(__m512i v, int offset, std::integral_constant<int, rotationStride>) { switch (offset) { case 1: return _mm512_alignr_epi32(v, v, alignrCount(rotationStride, 1)); case 2: return _mm512_alignr_epi32(v, v, alignrCount(rotationStride, 2)); case 3: return _mm512_alignr_epi32(v, v, alignrCount(rotationStride, 3)); case 4: return _mm512_alignr_epi32(v, v, alignrCount(rotationStride, 4)); case 5: return _mm512_alignr_epi32(v, v, alignrCount(rotationStride, 5)); case 6: return _mm512_alignr_epi32(v, v, alignrCount(rotationStride, 6)); case 7: return _mm512_alignr_epi32(v, v, alignrCount(rotationStride, 7)); case 8: return _mm512_alignr_epi32(v, v, alignrCount(rotationStride, 8)); case 9: return _mm512_alignr_epi32(v, v, alignrCount(rotationStride, 9)); case 10: return _mm512_alignr_epi32(v, v, alignrCount(rotationStride, 10)); case 11: return _mm512_alignr_epi32(v, v, alignrCount(rotationStride, 11)); case 12: return _mm512_alignr_epi32(v, v, alignrCount(rotationStride, 12)); case 13: return _mm512_alignr_epi32(v, v, alignrCount(rotationStride, 13)); case 14: return _mm512_alignr_epi32(v, v, alignrCount(rotationStride, 14)); case 15: return _mm512_alignr_epi32(v, v, alignrCount(rotationStride, 15)); default: return v; } } template <typename V, typename Mem, typename Mask, typename Flags, typename Flags::EnableIfUnaligned = nullptr> inline void storeDispatch(V vector, Mem *address, Mask mask, Flags flags) { constexpr std::ptrdiff_t alignment = sizeof(Mem) * V::Size; constexpr std::ptrdiff_t alignmentMask = ~(alignment - 1); const auto loAddress = reinterpret_cast<Mem *>((reinterpret_cast<char *>(address) - static_cast<const char*>(0)) & alignmentMask); const auto offset = address - loAddress; if (offset == 0) { MicIntrinsics::store<Flags::UnalignedRemoved>(mask.data(), address, vector.data(), V::template UpDownC<Mem>()); return; } constexpr int rotationStride = sizeof(typename V::VectorEntryType) / 4; // palignr shifts by 4 Bytes per "count" auto v = rotationHelper(MIC::mic_cast<__m512i>(vector.data()), offset, std::integral_constant<int, rotationStride>()); auto rotated = MIC::mic_cast<typename V::VectorType>(v); MicIntrinsics::store<Flags::UnalignedRemoved>(mask.data() << offset, loAddress, rotated, V::template UpDownC<Mem>()); MicIntrinsics::store<Flags::UnalignedRemoved>(mask.data() >> (V::Size - offset), loAddress + V::Size, rotated, V::template UpDownC<Mem>()); } template <typename V, typename Mem, typename Mask, typename Flags, typename Flags::EnableIfNotUnaligned = nullptr> Vc_INTRINSIC void storeDispatch(V vector, Mem *address, Mask mask, Flags flags) { MicIntrinsics::store<Flags>(mask.data(), address, vector.data(), V::template UpDownC<Mem>()); } namespace MIC { template <typename Parent, typename T> template <typename U, typename Flags, typename std::enable_if<std::is_arithmetic<U>::value, int>::type> Vc_INTRINSIC void StoreMixin<Parent, T>::store(U *mem, Mask mask, Flags flags) const { Common::handleStorePrefetches(mem, flags); // MicIntrinsics::store does not exist for Flags containing Vc::Unaligned storeDispatch(foldAfterOverflow(*static_cast<const Parent *>(this)), mem, mask, flags); } template<typename Parent, typename T> Vc_INTRINSIC void StoreMixin<Parent, T>::store(VectorEntryType *mem, decltype(Vc::Streaming)) const { // NR = No-Read hint, NGO = Non-Globally Ordered hint // It is not clear whether we will get issues with nrngo if users only expected nr //_mm512_storenr_ps(mem, MIC::mic_cast<__m512>(data())); _mm512_storenrngo_ps(mem, MIC::mic_cast<__m512>(data())); // the ICC auto-vectorizer adds clevict after storenrngo, but testing shows this to be slower... //_mm_clevict(mem, _MM_HINT_T1); } } // namespace MIC // negation {{{1 template<typename T> Vc_ALWAYS_INLINE Vc_PURE Vector<T, VectorAbi::Mic> Vector<T, VectorAbi::Mic>::operator-() const { return Zero() - *this; } template<> Vc_ALWAYS_INLINE Vc_PURE MIC::double_v MIC::double_v::operator-() const { return MIC::_xor(d.v(), MIC::mic_cast<VectorType>(MIC::_set1(0x8000000000000000ull))); } template<> Vc_ALWAYS_INLINE Vc_PURE MIC::float_v MIC::float_v::operator-() const { return MIC::_xor(d.v(), MIC::mic_cast<VectorType>(MIC::_set1(0x80000000u))); } // horizontal ops {{{1 template<typename T> Vc_ALWAYS_INLINE Vector<T, VectorAbi::Mic> Vector<T, VectorAbi::Mic>::partialSum() const { // a b c d e f g h // + a b c d e f g -> a ab bc cd de ef fg gh // + a ab bc cd de ef -> a ab abc abcd bcde cdef defg efgh // + a ab abc abcd -> a ab abc abcd abcde abcdef abcdefg abcdefgh Vector<T, VectorAbi::Mic> tmp = *this; if (Size > 1) tmp += tmp.shifted(-1); if (Size > 2) tmp += tmp.shifted(-2); if (Size > 4) tmp += tmp.shifted(-4); if (Size > 8) tmp += tmp.shifted(-8); if (Size > 16) tmp += tmp.shifted(-16); return tmp; } template<typename T> inline typename Vector<T, VectorAbi::Mic>::EntryType Vector<T, VectorAbi::Mic>::min(MaskArgument m) const { return _mm512_mask_reduce_min_epi32(m.data(), data()); } template<> inline float Vector<float>::min(MaskArgument m) const { return _mm512_mask_reduce_min_ps(m.data(), data()); } template<> inline double Vector<double>::min(MaskArgument m) const { return _mm512_mask_reduce_min_pd(m.data(), data()); } template<typename T> inline typename Vector<T, VectorAbi::Mic>::EntryType Vector<T, VectorAbi::Mic>::max(MaskArgument m) const { return _mm512_mask_reduce_max_epi32(m.data(), data()); } template<> inline float Vector<float>::max(MaskArgument m) const { return _mm512_mask_reduce_max_ps(m.data(), data()); } template<> inline double Vector<double>::max(MaskArgument m) const { return _mm512_mask_reduce_max_pd(m.data(), data()); } template<typename T> inline typename Vector<T, VectorAbi::Mic>::EntryType Vector<T, VectorAbi::Mic>::product(MaskArgument m) const { return _mm512_mask_reduce_mul_epi32(m.data(), data()); } template<> inline float Vector<float>::product(MaskArgument m) const { return _mm512_mask_reduce_mul_ps(m.data(), data()); } template<> inline double Vector<double>::product(MaskArgument m) const { return _mm512_mask_reduce_mul_pd(m.data(), data()); } template<typename T> inline typename Vector<T, VectorAbi::Mic>::EntryType Vector<T, VectorAbi::Mic>::sum(MaskArgument m) const { return _mm512_mask_reduce_add_epi32(m.data(), data()); } template<> inline float Vector<float>::sum(MaskArgument m) const { return _mm512_mask_reduce_add_ps(m.data(), data()); } template<> inline double Vector<double>::sum(MaskArgument m) const { return _mm512_mask_reduce_add_pd(m.data(), data()); } // integer ops {{{1 template<> Vc_ALWAYS_INLINE MIC::int_v MIC::int_v::operator<<( MIC::int_v::AsArg x) const { return _mm512_sllv_epi32(d.v(), x.d.v()); } template<> Vc_ALWAYS_INLINE MIC::uint_v MIC::uint_v::operator<<( MIC::uint_v::AsArg x) const { return _mm512_sllv_epi32(d.v(), x.d.v()); } template<> Vc_ALWAYS_INLINE MIC::short_v MIC::short_v::operator<<( MIC::short_v::AsArg x) const { return _mm512_sllv_epi32(d.v(), x.d.v()); } template<> Vc_ALWAYS_INLINE MIC::ushort_v MIC::ushort_v::operator<<(MIC::ushort_v::AsArg x) const { return _mm512_sllv_epi32(d.v(), x.d.v()); } template<> Vc_ALWAYS_INLINE MIC::int_v MIC::int_v::operator>>( MIC::int_v::AsArg x) const { return _mm512_srav_epi32(d.v(), x.d.v()); } template<> Vc_ALWAYS_INLINE MIC::uint_v MIC::uint_v::operator>>( MIC::uint_v::AsArg x) const { return _mm512_srlv_epi32(d.v(), x.d.v()); } template<> Vc_ALWAYS_INLINE MIC::short_v MIC::short_v::operator>>( MIC::short_v::AsArg x) const { return _mm512_srav_epi32(d.v(), x.d.v()); } template<> Vc_ALWAYS_INLINE MIC::ushort_v MIC::ushort_v::operator>>(MIC::ushort_v::AsArg x) const { return _mm512_srlv_epi32(d.v(), x.d.v()); } template<typename T> Vc_ALWAYS_INLINE Vector<T, VectorAbi::Mic> &Vector<T, VectorAbi::Mic>::operator<<=(AsArg x) { return *this = *this << x; } template<typename T> Vc_ALWAYS_INLINE Vector<T, VectorAbi::Mic> &Vector<T, VectorAbi::Mic>::operator>>=(AsArg x) { return *this = *this >> x; } template<> Vc_ALWAYS_INLINE MIC::int_v MIC::int_v::operator<<(unsigned int x) const { return _mm512_slli_epi32(d.v(), x); } template<> Vc_ALWAYS_INLINE MIC::uint_v MIC::uint_v::operator<<(unsigned int x) const { return _mm512_slli_epi32(d.v(), x); } template<> Vc_ALWAYS_INLINE MIC::short_v MIC::short_v::operator<<(unsigned int x) const { return _mm512_slli_epi32(d.v(), x); } template<> Vc_ALWAYS_INLINE MIC::ushort_v MIC::ushort_v::operator<<(unsigned int x) const { return _mm512_slli_epi32(d.v(), x); } template<> Vc_ALWAYS_INLINE MIC::schar_v MIC::schar_v::operator<<(unsigned int x) const { return _mm512_slli_epi32(d.v(), x); } template<> Vc_ALWAYS_INLINE MIC::uchar_v MIC::uchar_v::operator<<(unsigned int x) const { return _mm512_slli_epi32(d.v(), x); } template<> Vc_ALWAYS_INLINE MIC::int_v MIC::int_v::operator>>(unsigned int x) const { return _mm512_srai_epi32(d.v(), x); } template<> Vc_ALWAYS_INLINE MIC::uint_v MIC::uint_v::operator>>(unsigned int x) const { return _mm512_srli_epi32(d.v(), x); } template<> Vc_ALWAYS_INLINE MIC::short_v MIC::short_v::operator>>(unsigned int x) const { return _mm512_srai_epi32(d.v(), x); } template<> Vc_ALWAYS_INLINE MIC::ushort_v MIC::ushort_v::operator>>(unsigned int x) const { return _mm512_srli_epi32(d.v(), x); } template<> Vc_ALWAYS_INLINE MIC::schar_v MIC::schar_v::operator>>(unsigned int x) const { return _mm512_srai_epi32(d.v(), x); } template<> Vc_ALWAYS_INLINE MIC::uchar_v MIC::uchar_v::operator>>(unsigned int x) const { return _mm512_srli_epi32(d.v(), x); } template<typename T> Vc_ALWAYS_INLINE Vector<T, VectorAbi::Mic> &Vector<T, VectorAbi::Mic>::operator<<=(unsigned int x) { return *this = *this << x; } template<typename T> Vc_ALWAYS_INLINE Vector<T, VectorAbi::Mic> &Vector<T, VectorAbi::Mic>::operator>>=(unsigned int x) { return *this = *this >> x; } // isnegative {{{1 Vc_INTRINSIC Vc_CONST MIC::float_m isnegative(MIC::float_v x) { return _mm512_cmpge_epu32_mask(MIC::mic_cast<__m512i>(x.data()), MIC::_set1(MIC::c_general::signMaskFloat[1])); } Vc_INTRINSIC Vc_CONST MIC::double_m isnegative(MIC::double_v x) { return _mm512_cmpge_epu32_mask(MIC::mic_cast<__m512i>(_mm512_cvtpd_pslo(x.data())), MIC::_set1(MIC::c_general::signMaskFloat[1])); } // ensureVector helper {{{1 namespace { template <typename IT> Vc_ALWAYS_INLINE enable_if<MIC::is_vector<IT>::value, __m512i> ensureVector(IT indexes) { return indexes.data(); } template <typename IT> Vc_ALWAYS_INLINE enable_if<Traits::isAtomicSimdArray<IT>::value, __m512i> ensureVector( IT indexes) { return internal_data(indexes).data(); } template <typename IT> Vc_ALWAYS_INLINE enable_if<(!MIC::is_vector<IT>::value && !Traits::isAtomicSimdArray<IT>::value && Traits::has_subscript_operator<IT>::value && Traits::has_contiguous_storage<IT>::value), __m512i> ensureVector(IT indexes) { return MIC::int_v(std::addressof(indexes[0]), Vc::Unaligned).data(); } Vc_ALWAYS_INLINE __m512i ensureVector(const SimdArray<int, 8> &indexes) { return _mm512_mask_loadunpacklo_epi32(_mm512_setzero_epi32(), 0x00ff, &indexes); } template <typename IT> Vc_ALWAYS_INLINE enable_if<(!MIC::is_vector<IT>::value && !Traits::isAtomicSimdArray<IT>::value && !(Traits::has_subscript_operator<IT>::value && Traits::has_contiguous_storage<IT>::value)), __m512i> ensureVector(IT) = delete; } // anonymous namespace // gathers {{{1 template <typename T> template <typename MT, typename IT> Vc_INTRINSIC Vc_PURE void Vector<T, VectorAbi::Mic>::gatherImplementation( const MT *mem, const IT &indexes) { d.v() = MicIntrinsics::gather(ensureVector(std::forward<IT>(indexes)), mem, UpDownC<MT>()); } template <typename T> template <typename MT, typename IT> Vc_INTRINSIC Vc_PURE void Vector<T, VectorAbi::Mic>::gatherImplementation( const MT *mem, const IT &indexes, MaskArgument mask) { d.v() = MicIntrinsics::gather( d.v(), mask.data(), ensureVector(std::forward<IT>(indexes)), mem, UpDownC<MT>()); } // scatters {{{1 template <typename T> template <typename MT, typename IT> Vc_INTRINSIC void Vector<T, VectorAbi::Mic>::scatterImplementation(MT *mem, IT &&indexes) const { using namespace Detail; const auto v = std::is_same<T, ushort>::value ? (*this & Vector(0xffff)).data() : d.v(); MicIntrinsics::scatter(mem, ensureVector(std::forward<IT>(indexes)), v, UpDownC<MT>(), sizeof(MT)); } template <typename T> template <typename MT, typename IT> Vc_INTRINSIC void Vector<T, VectorAbi::Mic>::scatterImplementation(MT *mem, IT &&indexes, MaskArgument mask) const { using namespace Detail; const auto v = std::is_same<T, ushort>::value ? (*this & Vector(0xffff)).data() : d.v(); MicIntrinsics::scatter(mask.data(), mem, ensureVector(std::forward<IT>(indexes)), d.v(), UpDownC<MT>(), sizeof(MT)); } // exponent {{{1 Vc_INTRINSIC Vc_CONST MIC::float_v exponent(MIC::float_v x) { using Detail::operator>=; Vc_ASSERT((x >= x.Zero()).isFull()); return _mm512_getexp_ps(x.data()); } Vc_INTRINSIC Vc_CONST MIC::double_v exponent(MIC::double_v x) { using Detail::operator>=; Vc_ASSERT((x >= x.Zero()).isFull()); return _mm512_getexp_pd(x.data()); } // Random {{{1 static Vc_ALWAYS_INLINE void _doRandomStep(Vector<unsigned int> &state0, Vector<unsigned int> &state1) { using MIC::uint_v; using namespace Detail; state0.load(&Common::RandomState[0]); state1.load(&Common::RandomState[uint_v::Size]); (state1 * uint_v(0xdeece66du) + uint_v(11)).store(&Common::RandomState[uint_v::Size]); uint_v(xor_((state0 * uint_v(0xdeece66du) + uint_v(11)).data(), _mm512_srli_epi32(state1.data(), 16))).store(&Common::RandomState[0]); } template<typename T> Vc_ALWAYS_INLINE Vector<T, VectorAbi::Mic> Vector<T, VectorAbi::Mic>::Random() { Vector<unsigned int> state0, state1; _doRandomStep(state0, state1); if (std::is_same<T, short>::value) { // short and ushort vectors would hold values that are outside of their range // for ushort this doesn't matter because overflow behavior is defined in the compare // operators return state0.reinterpretCast<Vector<T, VectorAbi::Mic>>() >> 16; } return state0.reinterpretCast<Vector<T, VectorAbi::Mic> >(); } template<> Vc_ALWAYS_INLINE Vector<float> Vector<float>::Random() { Vector<unsigned int> state0, state1; _doRandomStep(state0, state1); using namespace Detail; return (reinterpret_components_cast<Vector<float>>(state0 >> 2) | One()) - One(); } // _mm512_srli_epi64 is neither documented nor defined in any header, here's what it does: //Vc_INTRINSIC __m512i _mm512_srli_epi64(__m512i v, int n) { // return _mm512_mask_mov_epi32( // _mm512_srli_epi32(v, n), // 0x5555, // _mm512_swizzle_epi32(_mm512_slli_epi32(v, 32 - n), _MM_SWIZ_REG_CDAB) // ); //} template<> Vc_ALWAYS_INLINE Vector<double> Vector<double>::Random() { using MicIntrinsics::swizzle; const auto state = LoadHelper<MIC::uint_v>::load(&Common::RandomState[0], Vc::Aligned); const auto factor = MIC::_set1(0x5deece66dull); _mm512_store_epi32(&Common::RandomState[0], _mm512_add_epi64( // the following is not _mm512_mullo_epi64, but something close... _mm512_add_epi32(_mm512_mullo_epi32(state, factor), swizzle(_mm512_mulhi_epu32(state, factor), _MM_SWIZ_REG_CDAB)), MIC::_set1(11ull))); using Detail::operator|; using Detail::operator-; return (Vector<double>(_cast(_mm512_srli_epi64(MIC::mic_cast<__m512i>(state), 12))) | One()) - One(); } // }}}1 // shifted / rotated {{{1 namespace { template<size_t SIMDWidth, size_t Size> struct VectorShift; template<> struct VectorShift<64, 8>/*{{{*/ { typedef __m512i VectorType; static Vc_INTRINSIC VectorType shifted(VectorType v, int amount, VectorType z = _mm512_setzero_epi32()) { switch (amount) { case 15: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 14); case 14: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 12); case 13: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 10); case 12: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 8); case 11: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 6); case 10: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 4); case 9: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 2); case 8: return z; case 7: return _mm512_alignr_epi32(z, v, 14); case 6: return _mm512_alignr_epi32(z, v, 12); case 5: return _mm512_alignr_epi32(z, v, 10); case 4: return _mm512_alignr_epi32(z, v, 8); case 3: return _mm512_alignr_epi32(z, v, 6); case 2: return _mm512_alignr_epi32(z, v, 4); case 1: return _mm512_alignr_epi32(z, v, 2); case 0: return v; case -1: return _mm512_alignr_epi32(v, z, 14); case -2: return _mm512_alignr_epi32(v, z, 12); case -3: return _mm512_alignr_epi32(v, z, 10); case -4: return _mm512_alignr_epi32(v, z, 8); case -5: return _mm512_alignr_epi32(v, z, 6); case -6: return _mm512_alignr_epi32(v, z, 4); case -7: return _mm512_alignr_epi32(v, z, 2); case -8: return z; case -9: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 14); case-10: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 12); case-11: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 10); case-12: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 8); case-13: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 6); case-14: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 4); case-15: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 2); } return z; } };/*}}}*/ template<> struct VectorShift<64, 16>/*{{{*/ { typedef __m512i VectorType; static Vc_INTRINSIC VectorType shifted(VectorType v, int amount, VectorType z = _mm512_setzero_epi32()) { switch (amount) { case 31: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 15); case 30: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 14); case 29: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 13); case 28: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 12); case 27: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 11); case 26: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 10); case 25: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 9); case 24: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 8); case 23: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 7); case 22: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 6); case 21: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 5); case 20: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 4); case 19: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 3); case 18: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 2); case 17: return _mm512_alignr_epi32(_mm512_setzero_epi32(), z, 1); case 16: return z; case 15: return _mm512_alignr_epi32(z, v, 15); case 14: return _mm512_alignr_epi32(z, v, 14); case 13: return _mm512_alignr_epi32(z, v, 13); case 12: return _mm512_alignr_epi32(z, v, 12); case 11: return _mm512_alignr_epi32(z, v, 11); case 10: return _mm512_alignr_epi32(z, v, 10); case 9: return _mm512_alignr_epi32(z, v, 9); case 8: return _mm512_alignr_epi32(z, v, 8); case 7: return _mm512_alignr_epi32(z, v, 7); case 6: return _mm512_alignr_epi32(z, v, 6); case 5: return _mm512_alignr_epi32(z, v, 5); case 4: return _mm512_alignr_epi32(z, v, 4); case 3: return _mm512_alignr_epi32(z, v, 3); case 2: return _mm512_alignr_epi32(z, v, 2); case 1: return _mm512_alignr_epi32(z, v, 1); case 0: return v; case -1: return _mm512_alignr_epi32(v, z, 15); case -2: return _mm512_alignr_epi32(v, z, 14); case -3: return _mm512_alignr_epi32(v, z, 13); case -4: return _mm512_alignr_epi32(v, z, 12); case -5: return _mm512_alignr_epi32(v, z, 11); case -6: return _mm512_alignr_epi32(v, z, 10); case -7: return _mm512_alignr_epi32(v, z, 9); case -8: return _mm512_alignr_epi32(v, z, 8); case -9: return _mm512_alignr_epi32(v, z, 7); case-10: return _mm512_alignr_epi32(v, z, 6); case-11: return _mm512_alignr_epi32(v, z, 5); case-12: return _mm512_alignr_epi32(v, z, 4); case-13: return _mm512_alignr_epi32(v, z, 3); case-14: return _mm512_alignr_epi32(v, z, 2); case-15: return _mm512_alignr_epi32(v, z, 1); case-16: return z; case-17: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 15); case-18: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 14); case-19: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 13); case-20: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 12); case-21: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 11); case-22: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 10); case-23: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 9); case-24: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 8); case-25: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 7); case-26: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 6); case-27: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 5); case-28: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 4); case-29: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 3); case-30: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 2); case-31: return _mm512_alignr_epi32(z, _mm512_setzero_epi32(), 1); } return z; } };/*}}}*/ } // anonymous namespace template<typename T> Vc_INTRINSIC Vector<T, VectorAbi::Mic> Vector<T, VectorAbi::Mic>::shifted(int amount) const { typedef VectorShift<sizeof(VectorType), Size> VS; return _cast(VS::shifted(MIC::mic_cast<typename VS::VectorType>(d.v()), amount)); } template<typename T> Vc_INTRINSIC Vector<T, VectorAbi::Mic> Vector<T, VectorAbi::Mic>::shifted(int amount, Vector shiftIn) const { typedef VectorShift<sizeof(VectorType), Size> VS; return _cast(VS::shifted(MIC::mic_cast<typename VS::VectorType>(d.v()), amount, MIC::mic_cast<typename VS::VectorType>(shiftIn.d.v()))); } namespace { template<size_t SIMDWidth, size_t Size> struct VectorRotate; template<> struct VectorRotate<64, 8>/*{{{*/ { typedef __m512i VectorType; static Vc_INTRINSIC VectorType rotated(VectorType v, int amount) { switch (static_cast<unsigned int>(amount) % 8) { case 0: return v; case 1: return _mm512_alignr_epi32(v, v, 2); case 2: return _mm512_alignr_epi32(v, v, 4); case 3: return _mm512_alignr_epi32(v, v, 6); case 4: return _mm512_alignr_epi32(v, v, 8); case 5: return _mm512_alignr_epi32(v, v, 10); case 6: return _mm512_alignr_epi32(v, v, 12); case 7: return _mm512_alignr_epi32(v, v, 14); } return _mm512_setzero_epi32(); } };/*}}}*/ template<> struct VectorRotate<64, 16>/*{{{*/ { typedef __m512i VectorType; static Vc_INTRINSIC VectorType rotated(VectorType v, int amount) { switch (static_cast<unsigned int>(amount) % 16) { case 15: return _mm512_alignr_epi32(v, v, 15); case 14: return _mm512_alignr_epi32(v, v, 14); case 13: return _mm512_alignr_epi32(v, v, 13); case 12: return _mm512_alignr_epi32(v, v, 12); case 11: return _mm512_alignr_epi32(v, v, 11); case 10: return _mm512_alignr_epi32(v, v, 10); case 9: return _mm512_alignr_epi32(v, v, 9); case 8: return _mm512_alignr_epi32(v, v, 8); case 7: return _mm512_alignr_epi32(v, v, 7); case 6: return _mm512_alignr_epi32(v, v, 6); case 5: return _mm512_alignr_epi32(v, v, 5); case 4: return _mm512_alignr_epi32(v, v, 4); case 3: return _mm512_alignr_epi32(v, v, 3); case 2: return _mm512_alignr_epi32(v, v, 2); case 1: return _mm512_alignr_epi32(v, v, 1); case 0: return v; } return _mm512_setzero_epi32(); } };/*}}}*/ } // anonymous namespace template<typename T> Vc_INTRINSIC Vector<T, VectorAbi::Mic> Vector<T, VectorAbi::Mic>::rotated(int amount) const { typedef VectorRotate<sizeof(VectorType), Size> VR; return _cast(VR::rotated(MIC::mic_cast<typename VR::VectorType>(d.v()), amount)); } // interleaveLow/-High {{{1 template <typename T> Vc_INTRINSIC Vector<T, VectorAbi::Mic> Vector<T, VectorAbi::Mic>::interleaveLow( Vector<T, VectorAbi::Mic> x) const { using namespace MIC; __m512i lo = mic_cast<__m512i>(d.v()); __m512i hi = mic_cast<__m512i>(x.d.v()); lo = _mm512_permute4f128_epi32(lo, _MM_PERM_BBAA); lo = _mm512_mask_swizzle_epi32(lo, 0xf0f0, lo, _MM_SWIZ_REG_BADC); lo = _mm512_shuffle_epi32(lo, _MM_PERM_BBAA); hi = _mm512_permute4f128_epi32(hi, _MM_PERM_BBAA); hi = _mm512_mask_swizzle_epi32(hi, 0xf0f0, hi, _MM_SWIZ_REG_BADC); return mic_cast<VectorType>(_mm512_mask_shuffle_epi32(lo, 0xaaaa, hi, _MM_PERM_BBAA)); } template <typename T> Vc_INTRINSIC Vector<T, VectorAbi::Mic> Vector<T, VectorAbi::Mic>::interleaveHigh( Vector<T, VectorAbi::Mic> x) const { using namespace MIC; __m512i lo = mic_cast<__m512i>(d.v()); __m512i hi = mic_cast<__m512i>(x.d.v()); lo = _mm512_permute4f128_epi32(lo, _MM_PERM_DDCC); lo = _mm512_mask_swizzle_epi32(lo, 0xf0f0, lo, _MM_SWIZ_REG_BADC); lo = _mm512_shuffle_epi32(lo, _MM_PERM_BBAA); hi = _mm512_permute4f128_epi32(hi, _MM_PERM_DDCC); hi = _mm512_mask_swizzle_epi32(hi, 0xf0f0, hi, _MM_SWIZ_REG_BADC); return mic_cast<VectorType>(_mm512_mask_shuffle_epi32(lo, 0xaaaa, hi, _MM_PERM_BBAA)); } template <> Vc_INTRINSIC Vector<double, VectorAbi::Mic> Vector<double, VectorAbi::Mic>::interleaveLow( Vector<double, VectorAbi::Mic> x) const { using namespace MIC; __m512i lo = mic_cast<__m512i>(d.v()); __m512i hi = mic_cast<__m512i>(x.d.v()); lo = _mm512_permute4f128_epi32(lo, _MM_PERM_BBAA); lo = _mm512_mask_swizzle_epi32(lo, 0xf0f0, lo, _MM_SWIZ_REG_BADC); lo = _mm512_shuffle_epi32(lo, _MM_PERM_BABA); hi = _mm512_permute4f128_epi32(hi, _MM_PERM_BBAA); hi = _mm512_mask_swizzle_epi32(hi, 0xf0f0, hi, _MM_SWIZ_REG_BADC); return mic_cast<VectorType>(_mm512_mask_shuffle_epi32(lo, 0xcccc, hi, _MM_PERM_BABA)); } template <> Vc_INTRINSIC Vector<double, VectorAbi::Mic> Vector<double, VectorAbi::Mic>::interleaveHigh(Vector<double, VectorAbi::Mic> x) const { using namespace MIC; __m512i lo = mic_cast<__m512i>(d.v()); __m512i hi = mic_cast<__m512i>(x.d.v()); lo = _mm512_permute4f128_epi32(lo, _MM_PERM_DDCC); lo = _mm512_mask_swizzle_epi32(lo, 0xf0f0, lo, _MM_SWIZ_REG_BADC); lo = _mm512_shuffle_epi32(lo, _MM_PERM_BABA); hi = _mm512_permute4f128_epi32(hi, _MM_PERM_DDCC); hi = _mm512_mask_swizzle_epi32(hi, 0xf0f0, hi, _MM_SWIZ_REG_BADC); return mic_cast<VectorType>(_mm512_mask_shuffle_epi32(lo, 0xcccc, hi, _MM_PERM_BABA)); } // reversed {{{1 template <typename T> Vc_INTRINSIC Vc_PURE Vector<T, VectorAbi::Mic> Vector<T, VectorAbi::Mic>::reversed() const { return MIC::mic_cast<VectorType>(MIC::permute128( _mm512_shuffle_epi32(MIC::mic_cast<__m512i>(data()), _MM_PERM_ABCD), _MM_PERM_ABCD)); } template <> Vc_INTRINSIC Vc_PURE MIC::double_v MIC::double_v::reversed() const { return _mm512_castps_pd(MIC::permute128( _mm512_swizzle_ps(_mm512_castpd_ps(d.v()), _MM_SWIZ_REG_BADC), _MM_PERM_ABCD)); } // }}}1 } // namespace Vc // vim: foldmethod=marker
48.659306
180
0.686094
[ "vector" ]
13a1503139420bce6b4c34c71e3308ee29a44caf
8,617
cpp
C++
src/net868client.cpp
MaksimNichikov/LoRaPackConverter
6715ae10a5ed36cc62324d21e10e810c22eb9988
[ "MIT" ]
1
2020-10-27T09:03:44.000Z
2020-10-27T09:03:44.000Z
src/net868client.cpp
MaksimNichikov/LoRaPackConverter
6715ae10a5ed36cc62324d21e10e810c22eb9988
[ "MIT" ]
null
null
null
src/net868client.cpp
MaksimNichikov/LoRaPackConverter
6715ae10a5ed36cc62324d21e10e810c22eb9988
[ "MIT" ]
null
null
null
/********************************************************************************************* ** ** ** Copyright © «2019» «OBSHCHESTVO S OGRANICHENNOY OTVETSTVENNOST'YU "INTERNET VESHCHEY"» ** ** Copyright © «2019» «ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ "ИНТЕРНЕТ ВЕЩЕЙ"» ** ** ** ** Класс взаимодействия с сервером Сеть868 ** ** ** **********************************************************************************************/ #include "net868client.h" Net868Client::Net868Client(QObject *parent) : QObject(parent) { qDebug() << "D::Net868 client started!"; net868Token.clear(); net868Adr = WEB_SERV_ADR; net868Port = WEB_SERV_PORT; QVariant _tok = Settings::getSetting("Net868_Server", "token"); if(!_tok.isNull()){ net868Token = _tok.toString(); } else { Settings::setSetting("Net868_Server", "token", net868Token); } QVariant _serv = Settings::getSetting("Net868_Server", "adr"); if(!_serv.isNull()){ net868Adr = _serv.toString(); } else { Settings::setSetting("Net868_Server", "adr", net868Adr); } QVariant _port = Settings::getSetting("Net868_Server", "port"); if(!_port.isNull()){ net868Port = _port.toInt(); } else { Settings::setSetting("Net868_Server", "port", net868Port); } if(net868Token.isEmpty() || net868Adr.isEmpty()){ qDebug() << "Connection parameters invalid. Check connection parameters and try againe."; exit(0); } startWebSocket(); prepareParser(); } Net868Client::~Net868Client() { parser->stopParser(); QEventLoop loop; QTimer::singleShot(3000, &loop, SLOT(quit())); connect(parserThread, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); disconnect(&m_webSocket, &QWebSocket::disconnected, this, &Net868Client::webSocketClosed); m_webSocket.close(); qDebug() << "D::Destroyed Net868 client."; } void Net868Client::onConnected() { qDebug() << "I::Connect to Net868 server OK!"; //connect(&m_webSocket, &QWebSocket::textMessageReceived, this, &Net868Client::onTextMessageReceived); QString req = "{\"type\":\"Config\",\"container\":{\"deviceDataPortGlobal\":{\"exclude\":\"false\",\"port\":[\"2\",\"4\"]},\"deviceStatusPortGlobal\":{\"exclude\":\"false\",\"port\":[\"4\",\"2\"]}," "\"deviceGlobal\":{\"exclude\":\"true\",\"eui\":[]},\"gatewayGlobal\":{\"exclude\":\"true\",\"eui\":[]},\"deviceDataPort\":{\"1\":{\"exclude\":\"false\",\"port\":[\"1\",\"2\"]}}}}"; m_webSocket.sendTextMessage(req); } void Net868Client::startWebSocket() { qDebug() << "D::SSL lib ver: " << QSslSocket::sslLibraryBuildVersionString(); connect(&m_webSocket, &QWebSocket::connected, this, &Net868Client::onConnected); connect(&m_webSocket, &QWebSocket::disconnected, this, &Net868Client::webSocketClosed); connect(&m_webSocket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(printSslErrors(QList<QSslError>))); connect(&m_webSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(printWsErrors(QAbstractSocket::SocketError))); connect(&m_webSocket, &QWebSocket::textMessageReceived, this, &Net868Client::onTextMessageReceived); m_webSocket.open(QUrl(QString(net868Adr) + ":" + QString::number(net868Port) + "/wsapi?token=" + net868Token)); qDebug() << "D::Connecting to server Net868 " << net868Adr << ":" << net868Port; } void Net868Client::onTextMessageReceived(QString message) { //qDebug() << "D::Message received: " << message; QJsonDocument jsDoc = QJsonDocument::fromJson(message.toUtf8()); QJsonObject jsObj = jsDoc.object(); if(jsObj.value("type") == "AppDataMessage"){ QJsonObject params = jsObj.value("container").toObject(); QByteArray _arr; _arr.append(params.value("port").toInt()); _arr.append(QByteArray::fromHex(params.value("data").toString().toUtf8())); loraQue.enqueue(qMakePair(params.value("deviceEui").toString(), _arr)); } if(jsObj.value("type") == "ExternalCommandStatus"){ QJsonObject params = jsObj.value("container").toObject(); QString _status = params.value("status").toString(); if(_status == "overdue") loraQue.enqueue(qMakePair(params.value("deviceEui").toString(), _status.toUtf8())); } } void Net868Client::webSocketClosed() { qDebug() << "I::Net868 server connection lost"; //disconnect(&m_webSocket, &QWebSocket::textMessageReceived, this, &Net868Client::onTextMessageReceived); QEventLoop loop; QTimer::singleShot(3000, &loop, SLOT(quit())); loop.exec(); qDebug() << "D::Reconnecting to Net868 server..."; m_webSocket.open(QUrl(QString(net868Adr) + ":" + QString::number(net868Port) + "/wsapi?token=" + net868Token)); } void Net868Client::printSslErrors(QList<QSslError> errors) { qDebug() << "E::SSL Errors: " << errors; } void Net868Client::printWsErrors(QAbstractSocket::SocketError) { qDebug() << "E::WS Errors: " << m_webSocket.errorString(); } void Net868Client::prepareParser() { parser = new PackParser(); parser->setLoraQueue(&loraQue); parserThread = new QThread(); parser->moveToThread(parserThread); connect(parserThread, SIGNAL(started()), parser, SLOT(startParser())); connect(parser, SIGNAL(finished(int)), parserThread, SLOT(quit())); connect(parser, SIGNAL(finished(int)), parser, SLOT(deleteLater())); connect(parser, SIGNAL(sendLoraPack(LORA_PACK)), this, SLOT(sendMessageToNetServer(LORA_PACK))); connect(parser, SIGNAL(receivePackage(quint8,QString,QByteArray)), this, SLOT(transitReceivePackage(quint8,QString,QByteArray))); connect(parser, SIGNAL(createBufferAnswer(quint8,quint8,quint16,QString)), this, SLOT(transitCreateBufferAnswer(quint8,quint8,quint16,QString))); connect(parser, SIGNAL(sendDataBlockAnswer(quint8,quint8,quint16,quint16,QString)), this, SLOT(transitSendDataBlockAnswer(quint8,quint8,quint16,quint16,QString))); connect(parser, SIGNAL(finishSendPackAnswer(quint8,QString)), this, SLOT(transitFinishSendPackAnswer(quint8,QString))); connect(parser, SIGNAL(createBufferCmd(quint8,quint16,QString)), this, SLOT(transitCreateBufferCmd(quint8,quint16,QString))); connect(parser, SIGNAL(receivedDataBlock(quint8,quint16,QByteArray,QString)), this, SLOT(transitReceivedDataBlock(quint8,quint16,QByteArray,QString))); connect(parser, SIGNAL(finishReceivedPackAnswer(quint8,quint16,qint32,QString)), this, SLOT(transitFinishReceivedPackAnswer(quint8,quint16,qint32,QString))); parserThread->start(); } void Net868Client::sendMessageToNetServer(LORA_PACK _loraPack) { qDebug() << "D::Sending data to Net868 server!"; mutex.lock(); QString req = "{\"type\":\"SendData\",\"container\":{\"eui\":\"" + _loraPack.dev_eui + "\",\"port\":\"" + QString::number(_loraPack.port) + "\",\"try_count\":\"0\",\"data\":\"" + _loraPack.data.toHex() + "\"}}"; m_webSocket.sendTextMessage(req); mutex.unlock(); } void Net868Client::addDataToQuery(LORA_PACK _lp) { parser->addDataToQuery(_lp); } void Net868Client::transitReceivePackage(quint8 _interface, QString _devEui, QByteArray _data) { emit receivePackage(_interface, _devEui, _data); } void Net868Client::transitCreateBufferAnswer(quint8 _resultCode, quint8 _port, quint16 _dataSize, QString _dev_eui) { emit createBufferAnswer(_resultCode, _port, _dataSize, _dev_eui); } void Net868Client::transitSendDataBlockAnswer(quint8 _resultCode, quint8 _port, quint16 _offset, quint16 _dataWriten, QString _dev_eui) { emit sendDataBlockAnswer(_resultCode, _port, _offset, _dataWriten, _dev_eui); } void Net868Client::transitFinishSendPackAnswer(quint8 _resultCode, QString _dev_eui) { emit finishSendPackAnswer(_resultCode, _dev_eui); } void Net868Client::transitCreateBufferCmd(quint8 _port, quint16 _dataSize, QString _dev_eui) { emit createBufferCmd(_port, _dataSize, _dev_eui); } void Net868Client::transitReceivedDataBlock(quint8 _port, quint16 _offset, QByteArray _data, QString _dev_eui) { emit receivedDataBlock(_port, _offset, _data, _dev_eui); } void Net868Client::transitFinishReceivedPackAnswer(quint8 _port, quint16 _dataSize, qint32 _crc, QString _dev_eui) { emit finishReceivedPackAnswer(_port, _dataSize, _crc, _dev_eui); }
44.880208
202
0.658698
[ "object" ]
13a7961486bc0288411b8d2fed656e4b6600fc0a
5,608
cxx
C++
examples/convergence.cxx
Bonelab/ITKMorphometry
ee1480bc1a93425ae7fff1c9595b0688fc58abc5
[ "Apache-2.0" ]
null
null
null
examples/convergence.cxx
Bonelab/ITKMorphometry
ee1480bc1a93425ae7fff1c9595b0688fc58abc5
[ "Apache-2.0" ]
null
null
null
examples/convergence.cxx
Bonelab/ITKMorphometry
ee1480bc1a93425ae7fff1c9595b0688fc58abc5
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include "itkImageRegionIterator.h" #include "itkImageFileWriter.h" #include "itkInitializeSignedDistanceTransform.h" #include "itkBinaryThresholdImageFilter.h" #include "itkHighOrderSignedDistanceTransformCorrectionImageFilter.h" #include "itkHighOrderSignedFastSweeping.h" constexpr unsigned int ImageDimension = 3; using EmbeddingPixelType = double; using EmbeddingImageType = itk::Image<EmbeddingPixelType, ImageDimension>; using BinaryPixelType = unsigned char; using BinaryImageType = itk::Image<BinaryPixelType, ImageDimension>; using BinarizeType = itk::BinaryThresholdImageFilter< EmbeddingImageType, BinaryImageType >; using InitializeType = itk::InitializeSignedDistanceTransform< BinaryImageType, EmbeddingImageType >; // using SDTType = itk::HighOrderSignedDistanceTransformCorrectionImageFilter< EmbeddingImageType >; using SDTType = itk::HighOrderSignedFastSweeping< EmbeddingImageType >; using WriterType = itk::ImageFileWriter<EmbeddingImageType>; using Writer2Type = itk::ImageFileWriter<BinaryImageType>; EmbeddingImageType::Pointer create_sphere(EmbeddingImageType::SpacingType physicalSize, EmbeddingImageType::SpacingType spacing, double radius) { /* Create region */ EmbeddingImageType::IndexType start; EmbeddingImageType::SizeType size; EmbeddingImageType::PointType origin; EmbeddingImageType::PointType center; for (unsigned int i = 0; i < ImageDimension; i++) { start[i] = 0; size[i] = int(physicalSize[i] / spacing[i]); origin[i] = -physicalSize[i] / 2.0; center[i] = -spacing[2]; } EmbeddingImageType::RegionType region; region.SetSize(size); region.SetIndex(start); /* Create image */ typename EmbeddingImageType::Pointer image = EmbeddingImageType::New(); image->SetRegions(region); image->SetOrigin(origin); image->SetSpacing(spacing); image->Allocate(); /* Fill */ itk::ImageRegionIterator<EmbeddingImageType> in(image, region); for (in.GoToBegin(); !in.IsAtEnd(); ++in) { EmbeddingImageType::PointType thisIndex; image->TransformIndexToPhysicalPoint(in.GetIndex(), thisIndex); in.Set(thisIndex.EuclideanDistanceTo(center) - radius); } return image; } struct norm { double l1; double linf; double h; }; norm measure_norm(EmbeddingImageType::Pointer const truth, EmbeddingImageType::Pointer const predicted, double h) { /* Setup iterators */ itk::ImageRegionConstIterator<EmbeddingImageType> t(truth, truth->GetRequestedRegion()); itk::ImageRegionConstIterator<EmbeddingImageType> p(predicted, predicted->GetRequestedRegion()); /* Compute best shift */ int i = 0; double shift = 0; for (t.GoToBegin(), p.GoToBegin(); !t.IsAtEnd() && !p.IsAtEnd(); ++t, ++p) { double truth = t.Get(); double predicted = p.Get(); shift += (truth - predicted); i++; } shift /= (double)i; i = 0; double l1 = 0.; double linf = 0.; for (t.GoToBegin(), p.GoToBegin(); !t.IsAtEnd() && !p.IsAtEnd(); ++t, ++p) { double truth = t.Get(); double predicted = p.Get() + shift; l1 += std::abs(truth - predicted); linf = std::max(linf, std::abs(truth - predicted)); i++; } norm n; n.l1 = l1 / (double)i; n.linf = linf; n.h = h; return n; } norm run_value(double h, double radius) { WriterType::Pointer writer = WriterType::New(); EmbeddingImageType::SpacingType physicalSize(100.); // physicalSize[2] = h; EmbeddingImageType::SpacingType spacing(h); EmbeddingImageType::Pointer dt = create_sphere(physicalSize, spacing, radius); writer->SetFileName("dt.nii"); writer->SetInput(dt); writer->Update(); BinarizeType::Pointer thresh = BinarizeType::New(); thresh->SetInput(dt); thresh->SetInsideValue(1); thresh->SetOutsideValue(0); thresh->SetUpperThreshold(0); Writer2Type::Pointer w2 = Writer2Type::New(); w2->SetFileName("seg.nii"); w2->SetInput(thresh->GetOutput()); w2->Update(); InitializeType::Pointer init = InitializeType::New(); init->SetInput(thresh->GetOutput()); init->SetLabel(1); init->SetDither(false); // init->Update(); writer->SetFileName("init.nii"); writer->SetInput(init->GetOutput()); writer->Update(); // return measure_norm(dt, init->GetOutput(), h); SDTType::Pointer correct = SDTType::New(); // correct->SetInput(dt); correct->SetInput(init->GetOutput()); correct->SetMaxIteration(100); correct->SetNarrowbandSize(15.); correct->SetMaxError(0.); correct->Update(); writer->SetFileName("correct.nii"); writer->SetInput(correct->GetOutput()); writer->Update(); return measure_norm(dt, correct->GetOutput(), h); } int main(int argc, char * argv[]) { std::string filename = "temp.nii"; std::vector<double> hs {4., 2., 1.};//{8., 4., 2., 1., 0.5};// {2., 1., 0.5, 0.25};//{8., 4., 2., 1.};//0.25};//{2.0, 1.0, 0.5, 0.25}; for(double &h: hs) { norm n = run_value(h, 25.0); std::cout << "! " << n.l1 << " " << n.linf << " " << n.h << std::endl; } return EXIT_SUCCESS; } // int main(int argc, char * argv[]) // { // std::string filename = "temp.nii"; // EmbeddingImageType::SpacingType physicalSize(100.); // EmbeddingImageType::SpacingType spacing(1.); // double radius = 10.; // std::cout << "Creating sphere" << std::endl; // EmbeddingImageType::Pointer dt = create_sphere(physicalSize, spacing, radius); // std::cout << "Writing to " << filename << std::endl; // WriterType::Pointer writer = WriterType::New(); // writer->SetFileName(filename); // writer->SetInput(dt); // writer->Update(); // return EXIT_SUCCESS; // }
28.907216
143
0.688124
[ "vector" ]
13aee46fa4f8a716b52fad5f9e213e8145d158c4
50,634
hpp
C++
boost/boost/polygon/rectangle_concept.hpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
61
2015-12-05T19:34:20.000Z
2021-06-25T09:07:09.000Z
boost/boost/polygon/rectangle_concept.hpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
38
2015-07-22T07:35:45.000Z
2019-03-14T16:03:06.000Z
boost/boost/polygon/rectangle_concept.hpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
39
2015-01-07T02:03:15.000Z
2021-01-15T00:41:50.000Z
/* Copyright 2008 Intel Corporation Use, modification and distribution are subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt). */ #ifndef BOOST_POLYGON_RECTANGLE_CONCEPT_HPP #define BOOST_POLYGON_RECTANGLE_CONCEPT_HPP #include "isotropy.hpp" //point #include "point_data.hpp" #include "point_traits.hpp" #include "point_concept.hpp" //interval #include "interval_data.hpp" #include "interval_traits.hpp" #include "interval_concept.hpp" #include "rectangle_data.hpp" #include "rectangle_traits.hpp" namespace boost { namespace polygon{ struct rectangle_concept {}; template <typename T> struct is_rectangle_concept { typedef gtl_no type; }; template <> struct is_rectangle_concept<rectangle_concept> { typedef gtl_yes type; }; template <typename T> struct is_mutable_rectangle_concept { typedef gtl_no type; }; template <> struct is_mutable_rectangle_concept<rectangle_concept> { typedef gtl_yes type; }; template <> struct geometry_domain<rectangle_concept> { typedef manhattan_domain type; }; template <typename T, typename CT> struct rectangle_interval_type_by_concept { typedef void type; }; template <typename T> struct rectangle_interval_type_by_concept<T, gtl_yes> { typedef typename rectangle_traits<T>::interval_type type; }; template <typename T> struct rectangle_interval_type { typedef typename rectangle_interval_type_by_concept<T, typename is_rectangle_concept<typename geometry_concept<T>::type>::type>::type type; }; template <typename T, typename CT> struct rectangle_coordinate_type_by_concept { typedef void type; }; template <typename T> struct rectangle_coordinate_type_by_concept<T, gtl_yes> { typedef typename rectangle_traits<T>::coordinate_type type; }; template <typename T> struct rectangle_coordinate_type { typedef typename rectangle_coordinate_type_by_concept<T, typename is_rectangle_concept<typename geometry_concept<T>::type>::type>::type type; }; template <typename T, typename CT> struct rectangle_difference_type_by_concept { typedef void type; }; template <typename T> struct rectangle_difference_type_by_concept<T, gtl_yes> { typedef typename coordinate_traits<typename rectangle_traits<T>::coordinate_type>::coordinate_difference type; }; template <typename T> struct rectangle_difference_type { typedef typename rectangle_difference_type_by_concept< T, typename is_rectangle_concept<typename geometry_concept<T>::type>::type>::type type; }; template <typename T, typename CT> struct rectangle_distance_type_by_concept { typedef void type; }; template <typename T> struct rectangle_distance_type_by_concept<T, gtl_yes> { typedef typename coordinate_traits<typename rectangle_coordinate_type<T>::type>::coordinate_distance type; }; template <typename T> struct rectangle_distance_type { typedef typename rectangle_distance_type_by_concept< T, typename is_rectangle_concept<typename geometry_concept<T>::type>::type>::type type; }; struct y_r_get_interval : gtl_yes {}; template <typename T> typename enable_if< typename gtl_and<y_r_get_interval, typename is_rectangle_concept<typename geometry_concept<T>::type>::type>::type, typename rectangle_interval_type<T>::type>::type get(const T& rectangle, orientation_2d orient) { return rectangle_traits<T>::get(rectangle, orient); } struct y_r_h : gtl_yes {}; template <typename T> typename enable_if< typename gtl_and<y_r_h, typename is_rectangle_concept<typename geometry_concept<T>::type>::type>::type, typename rectangle_interval_type<T>::type>::type horizontal(const T& rectangle) { return rectangle_traits<T>::get(rectangle, HORIZONTAL); } struct y_r_v : gtl_yes {}; template <typename T> typename enable_if< typename gtl_and<y_r_v, typename is_rectangle_concept<typename geometry_concept<T>::type>::type>::type, typename rectangle_interval_type<T>::type>::type vertical(const T& rectangle) { return rectangle_traits<T>::get(rectangle, VERTICAL); } struct y_r_set : gtl_yes {}; template <orientation_2d_enum orient, typename T, typename T2> typename enable_if< typename gtl_and_3<y_r_set, typename is_mutable_rectangle_concept<typename geometry_concept<T>::type>::type, typename is_interval_concept<typename geometry_concept<T2>::type>::type>::type, void>::type set(T& rectangle, const T2& interval) { rectangle_mutable_traits<T>::set(rectangle, orient, interval); } struct y_r_set2 : gtl_yes {}; template <typename T, typename T2> typename enable_if< typename gtl_and_3<y_r_set2, typename is_mutable_rectangle_concept<typename geometry_concept<T>::type>::type, typename is_interval_concept<typename geometry_concept<T2>::type>::type>::type, void>::type set(T& rectangle, orientation_2d orient, const T2& interval) { rectangle_mutable_traits<T>::set(rectangle, orient, interval); } struct y_r_h2 : gtl_yes {}; template <typename T, typename T2> typename enable_if< typename gtl_and_3<y_r_h2, typename is_mutable_rectangle_concept<typename geometry_concept<T>::type>::type, typename is_interval_concept<typename geometry_concept<T2>::type>::type>::type, void>::type horizontal(T& rectangle, const T2& interval) { rectangle_mutable_traits<T>::set(rectangle, HORIZONTAL, interval); } struct y_r_v2 : gtl_yes {}; template <typename T, typename T2> typename enable_if< typename gtl_and_3<y_r_v2, typename is_mutable_rectangle_concept<typename geometry_concept<T>::type>::type, typename is_interval_concept<typename geometry_concept<T2>::type>::type>::type, void>::type vertical(T& rectangle, const T2& interval) { rectangle_mutable_traits<T>::set(rectangle, VERTICAL, interval); } struct y_r_construct : gtl_yes {}; template <typename T, typename T2, typename T3> typename enable_if< typename gtl_and<y_r_construct, typename is_mutable_rectangle_concept<typename geometry_concept<T>::type>::type>::type, T>::type construct(const T2& interval_horizontal, const T3& interval_vertical) { return rectangle_mutable_traits<T>::construct(interval_horizontal, interval_vertical); } struct y_r_construct2 : gtl_yes {}; template <typename T, typename coord_type> typename enable_if< typename gtl_and<y_r_construct2, typename is_mutable_rectangle_concept<typename geometry_concept<T>::type>::type>::type, T>::type construct(coord_type xl, coord_type yl, coord_type xh, coord_type yh) { return rectangle_mutable_traits<T>::construct(interval_data<coord_type>(xl, xh), interval_data<coord_type>(yl, yh)); } struct y_r_cconstruct : gtl_yes {}; template <typename T, typename T2> typename enable_if< typename gtl_and_3<y_r_cconstruct, typename is_mutable_rectangle_concept<typename geometry_concept<T>::type>::type, typename is_rectangle_concept<typename geometry_concept<T2>::type>::type>::type, T>::type copy_construct(const T2& rectangle) { return construct<T> (get(rectangle, HORIZONTAL), get(rectangle, VERTICAL)); } struct y_r_assign : gtl_yes {}; template <typename rectangle_type_1, typename rectangle_type_2> typename enable_if< typename gtl_and_3< y_r_assign, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, rectangle_type_1>::type & assign(rectangle_type_1& lvalue, const rectangle_type_2& rvalue) { set(lvalue, HORIZONTAL, get(rvalue, HORIZONTAL)); set(lvalue, VERTICAL, get(rvalue, VERTICAL)); return lvalue; } struct y_r_equiv : gtl_yes {}; template <typename T, typename T2> typename enable_if< typename gtl_and_3< y_r_equiv, typename is_rectangle_concept<typename geometry_concept<T>::type>::type, typename is_rectangle_concept<typename geometry_concept<T2>::type>::type>::type, bool>::type equivalence(const T& rect1, const T2& rect2) { return equivalence(get(rect1, HORIZONTAL), get(rect2, HORIZONTAL)) && equivalence(get(rect1, VERTICAL), get(rect2, VERTICAL)); } struct y_r_get : gtl_yes {}; template <typename rectangle_type> typename enable_if< typename gtl_and<y_r_get, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, typename rectangle_coordinate_type<rectangle_type>::type>::type get(const rectangle_type& rectangle, orientation_2d orient, direction_1d dir) { return get(rectangle_traits<rectangle_type>::get(rectangle, orient), dir); } struct y_r_set3 : gtl_yes {}; template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_set3, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, void>::type set(rectangle_type& rectangle, orientation_2d orient, direction_1d dir, typename rectangle_coordinate_type<rectangle_type>::type value) { typename rectangle_interval_type<rectangle_type>::type ivl = get(rectangle, orient); set(ivl, dir, value); set(rectangle, orient, ivl); } struct y_r_xl : gtl_yes {}; template <typename rectangle_type> typename enable_if< typename gtl_and<y_r_xl, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, typename rectangle_coordinate_type<rectangle_type>::type>::type xl(const rectangle_type& rectangle) { return get(rectangle, HORIZONTAL, LOW); } struct y_r_xl2 : gtl_yes {}; template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_xl2, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, void>::type xl(rectangle_type& rectangle, typename rectangle_coordinate_type<rectangle_type>::type value) { return set(rectangle, HORIZONTAL, LOW, value); } struct y_r_xh : gtl_yes {}; template <typename rectangle_type> typename enable_if< typename gtl_and<y_r_xh, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, typename rectangle_coordinate_type<rectangle_type>::type>::type xh(const rectangle_type& rectangle) { return get(rectangle, HORIZONTAL, HIGH); } struct y_r_xh2 : gtl_yes {}; template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_xh2, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, void>::type xh(rectangle_type& rectangle, typename rectangle_coordinate_type<rectangle_type>::type value) { return set(rectangle, HORIZONTAL, HIGH, value); } struct y_r_yl : gtl_yes {}; template <typename rectangle_type> typename enable_if< typename gtl_and<y_r_yl, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, typename rectangle_coordinate_type<rectangle_type>::type>::type yl(const rectangle_type& rectangle) { return get(rectangle, VERTICAL, LOW); } struct y_r_yl2 : gtl_yes {}; template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_yl2, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, void>::type yl(rectangle_type& rectangle, typename rectangle_coordinate_type<rectangle_type>::type value) { return set(rectangle, VERTICAL, LOW, value); } struct y_r_yh : gtl_yes {}; template <typename rectangle_type> typename enable_if< typename gtl_and<y_r_yh, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, typename rectangle_coordinate_type<rectangle_type>::type>::type yh(const rectangle_type& rectangle) { return get(rectangle, VERTICAL, HIGH); } struct y_r_yh2 : gtl_yes {}; template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_yh2, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, void>::type yh(rectangle_type& rectangle, typename rectangle_coordinate_type<rectangle_type>::type value) { return set(rectangle, VERTICAL, HIGH, value); } struct y_r_ll : gtl_yes {}; template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_ll, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, point_data<typename rectangle_coordinate_type<rectangle_type>::type> >::type ll(const rectangle_type& rectangle) { return point_data<typename rectangle_coordinate_type<rectangle_type>::type> (xl(rectangle), yl(rectangle)); } struct y_r_lr : gtl_yes {}; template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_lr, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, point_data<typename rectangle_coordinate_type<rectangle_type>::type> >::type lr(const rectangle_type& rectangle) { return point_data<typename rectangle_coordinate_type<rectangle_type>::type> (xh(rectangle), yl(rectangle)); } struct y_r_ul : gtl_yes {}; template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_ul, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, point_data<typename rectangle_coordinate_type<rectangle_type>::type> >::type ul(const rectangle_type& rectangle) { return point_data<typename rectangle_coordinate_type<rectangle_type>::type> (xl(rectangle), yh(rectangle)); } struct y_r_ur : gtl_yes {}; template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_ur, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, point_data<typename rectangle_coordinate_type<rectangle_type>::type> >::type ur(const rectangle_type& rectangle) { return point_data<typename rectangle_coordinate_type<rectangle_type>::type> (xh(rectangle), yh(rectangle)); } struct y_r_contains : gtl_yes {}; template <typename rectangle_type, typename rectangle_type_2> typename enable_if< typename gtl_and_3<y_r_contains, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, bool>::type contains(const rectangle_type& rectangle, const rectangle_type_2 rectangle_contained, bool consider_touch = true) { return contains(horizontal(rectangle), horizontal(rectangle_contained), consider_touch) && contains(vertical(rectangle), vertical(rectangle_contained), consider_touch); } struct y_r_contains2 : gtl_yes {}; template <typename rectangle_type, typename point_type> typename enable_if< typename gtl_and_3<y_r_contains2, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type, typename is_point_concept<typename geometry_concept<point_type>::type>::type>::type, bool>::type contains(const rectangle_type& rectangle, const point_type point_contained, bool consider_touch = true) { return contains(horizontal(rectangle), x(point_contained), consider_touch) && contains(vertical(rectangle), y(point_contained), consider_touch); } struct y_r_set_points : gtl_yes {}; // set all four coordinates based upon two points template <typename rectangle_type, typename point_type_1, typename point_type_2> typename enable_if< typename gtl_and_4< y_r_set_points, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type, typename is_point_concept<typename geometry_concept<point_type_1>::type>::type, typename is_point_concept<typename geometry_concept<point_type_2>::type>::type>::type, rectangle_type>::type & set_points(rectangle_type& rectangle, const point_type_1& p1, const point_type_2& p2) { typedef typename rectangle_coordinate_type<rectangle_type>::type Unit; Unit x1(x(p1)); Unit x2(x(p2)); Unit y1(y(p1)); Unit y2(y(p2)); horizontal(rectangle, construct<typename rectangle_interval_type<rectangle_type>::type>(x1, x2)); vertical(rectangle, construct<typename rectangle_interval_type<rectangle_type>::type>(y1, y2)); return rectangle; } struct y_r_move : gtl_yes {}; // move rectangle by delta in orient template <typename rectangle_type> typename enable_if< typename gtl_and<y_r_move, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, rectangle_type>::type & move(rectangle_type& rectangle, orientation_2d orient, typename coordinate_traits<typename rectangle_coordinate_type<rectangle_type>::type>::coordinate_difference delta) { typename rectangle_interval_type<rectangle_type>::type ivl = get(rectangle, orient); move(ivl, delta); set(rectangle, orient, ivl); return rectangle; } struct y_r_convolve : gtl_yes {}; // convolve this with b template <typename rectangle_type_1, typename rectangle_type_2> typename enable_if< typename gtl_and_3< y_r_convolve, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, rectangle_type_1>::type & convolve(rectangle_type_1& rectangle, const rectangle_type_2& convolution_rectangle) { typename rectangle_interval_type<rectangle_type_1>::type ivl = horizontal(rectangle); horizontal(rectangle, convolve(ivl, horizontal(convolution_rectangle))); ivl = vertical(rectangle); vertical(rectangle, convolve(ivl, vertical(convolution_rectangle))); return rectangle; } struct y_r_deconvolve : gtl_yes {}; // deconvolve this with b template <typename rectangle_type_1, typename rectangle_type_2> typename enable_if< typename gtl_and_3< y_r_deconvolve, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, rectangle_type_1>::type & deconvolve(rectangle_type_1& rectangle, const rectangle_type_2& convolution_rectangle) { typename rectangle_interval_type<rectangle_type_1>::type ivl = horizontal(rectangle); horizontal(rectangle, deconvolve(ivl, horizontal(convolution_rectangle))); ivl = vertical(rectangle); vertical(rectangle, deconvolve(ivl, vertical(convolution_rectangle))); return rectangle; } struct y_r_reconvolve : gtl_yes {}; // reflectedConvolve this with b template <typename rectangle_type_1, typename rectangle_type_2> typename enable_if< typename gtl_and_3<y_r_reconvolve, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, rectangle_type_1>::type & reflected_convolve(rectangle_type_1& rectangle, const rectangle_type_2& convolution_rectangle) { typename rectangle_interval_type<rectangle_type_1>::type ivl = horizontal(rectangle); horizontal(rectangle, reflected_convolve(ivl, horizontal(convolution_rectangle))); ivl = vertical(rectangle); vertical(rectangle, reflected_convolve(ivl, vertical(convolution_rectangle))); return rectangle; } struct y_r_redeconvolve : gtl_yes {}; // reflectedDeconvolve this with b // deconvolve this with b template <typename rectangle_type_1, typename rectangle_type_2> typename enable_if< typename gtl_and_3<y_r_redeconvolve, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, rectangle_type_1>::type & reflected_deconvolve(rectangle_type_1& rectangle, const rectangle_type_2& convolution_rectangle) { typename rectangle_interval_type<rectangle_type_1>::type ivl = horizontal(rectangle); horizontal(rectangle, reflected_deconvolve(ivl, horizontal(convolution_rectangle))); ivl = vertical(rectangle); vertical(rectangle, reflected_deconvolve(ivl, vertical(convolution_rectangle))); return rectangle; } struct y_r_convolve2 : gtl_yes {}; // convolve with point template <typename rectangle_type, typename point_type> typename enable_if< typename gtl_and_3<y_r_convolve2, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type, typename is_point_concept<typename geometry_concept<point_type>::type>::type>::type, rectangle_type>::type & convolve(rectangle_type& rectangle, const point_type& convolution_point) { typename rectangle_interval_type<rectangle_type>::type ivl = horizontal(rectangle); horizontal(rectangle, convolve(ivl, x(convolution_point))); ivl = vertical(rectangle); vertical(rectangle, convolve(ivl, y(convolution_point))); return rectangle; } struct y_r_deconvolve2 : gtl_yes {}; // deconvolve with point template <typename rectangle_type, typename point_type> typename enable_if< typename gtl_and_3<y_r_deconvolve2, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type, typename is_point_concept<typename geometry_concept<point_type>::type>::type>::type, rectangle_type>::type & deconvolve(rectangle_type& rectangle, const point_type& convolution_point) { typename rectangle_interval_type<rectangle_type>::type ivl = horizontal(rectangle); horizontal(rectangle, deconvolve(ivl, x(convolution_point))); ivl = vertical(rectangle); vertical(rectangle, deconvolve(ivl, y(convolution_point))); return rectangle; } struct y_r_delta : gtl_yes {}; // get the magnitude of the interval range depending on orient template <typename rectangle_type> typename enable_if< typename gtl_and<y_r_delta, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, typename rectangle_difference_type<rectangle_type>::type>::type delta(const rectangle_type& rectangle, orientation_2d orient) { return delta(get(rectangle, orient)); } struct y_r_area : gtl_yes {}; // get the area of the rectangle template <typename rectangle_type> typename enable_if< typename gtl_and<y_r_area, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, typename coordinate_traits<typename rectangle_coordinate_type<rectangle_type>::type>::manhattan_area_type>::type area(const rectangle_type& rectangle) { typedef typename coordinate_traits<typename rectangle_coordinate_type<rectangle_type>::type>::manhattan_area_type area_type; return (area_type)delta(rectangle, HORIZONTAL) * (area_type)delta(rectangle, VERTICAL); } struct y_r_go : gtl_yes {}; // returns the orientation of the longest side template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_go, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, orientation_2d>::type guess_orientation(const rectangle_type& rectangle) { return delta(rectangle, HORIZONTAL) >= delta(rectangle, VERTICAL) ? HORIZONTAL : VERTICAL; } struct y_r_half_p : gtl_yes {}; // get the half perimeter of the rectangle template <typename rectangle_type> typename enable_if< typename gtl_and<y_r_half_p, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, typename rectangle_difference_type<rectangle_type>::type>::type half_perimeter(const rectangle_type& rectangle) { return delta(rectangle, HORIZONTAL) + delta(rectangle, VERTICAL); } struct y_r_perimeter : gtl_yes {}; // get the perimeter of the rectangle template <typename rectangle_type> typename enable_if< typename gtl_and<y_r_perimeter, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, typename rectangle_difference_type<rectangle_type>::type>::type perimeter(const rectangle_type& rectangle) { return 2 * half_perimeter(rectangle); } struct y_r_intersects : gtl_yes {}; // check if Rectangle b intersects `this` Rectangle // [in] b Rectangle that will be checked // [in] considerTouch If true, return true even if b touches the boundary // [ret] . true if `t` intersects b template <typename rectangle_type_1, typename rectangle_type_2> typename enable_if< typename gtl_and_3<y_r_intersects, typename is_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, bool>::type intersects(const rectangle_type_1& rectangle, const rectangle_type_2& b, bool consider_touch = true) { return intersects(horizontal(rectangle), horizontal(b), consider_touch) && intersects(vertical(rectangle), vertical(b), consider_touch); } struct y_r_b_intersect : gtl_yes {}; // Check if boundaries of Rectangle b and `this` Rectangle intersect // [in] b Rectangle that will be checked // [in] considerTouch If true, return true even if p is on the foundary // [ret] . true if `t` contains p template <typename rectangle_type_1, typename rectangle_type_2> typename enable_if< typename gtl_and_3<y_r_b_intersect, typename is_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, bool>::type boundaries_intersect(const rectangle_type_1& rectangle, const rectangle_type_2& b, bool consider_touch = true) { return (intersects(rectangle, b, consider_touch) && !(contains(rectangle, b, !consider_touch)) && !(contains(b, rectangle, !consider_touch))); } struct y_r_b_abuts : gtl_yes {}; // check if b is touching 'this' on the end specified by dir template <typename rectangle_type_1, typename rectangle_type_2> typename enable_if< typename gtl_and_3<y_r_b_abuts, typename is_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, bool>::type abuts(const rectangle_type_1& rectangle, const rectangle_type_2& b, direction_2d dir) { return abuts(get(rectangle, orientation_2d(dir)), get(b, orientation_2d(dir)), direction_1d(dir)) && intersects(get(rectangle, orientation_2d(dir).get_perpendicular()), get(b, orientation_2d(dir).get_perpendicular()), true); } struct y_r_b_abuts2 : gtl_yes {}; // check if they are touching in the given orientation template <typename rectangle_type_1, typename rectangle_type_2> typename enable_if< typename gtl_and_3<y_r_b_abuts2, typename is_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, bool>::type abuts(const rectangle_type_1& rectangle, const rectangle_type_2& b, orientation_2d orient) { return abuts(get(rectangle, orient), get(b, orient)) && intersects(get(rectangle, orient.get_perpendicular()), get(b, orient.get_perpendicular()), true); } struct y_r_b_abuts3 : gtl_yes {}; // check if they are touching but not overlapping template <typename rectangle_type_1, typename rectangle_type_2> typename enable_if< typename gtl_and_3<y_r_b_abuts3, typename is_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, bool>::type abuts(const rectangle_type_1& rectangle, const rectangle_type_2& b) { return abuts(rectangle, b, HORIZONTAL) || abuts(rectangle, b, VERTICAL); } struct y_r_b_intersect2 : gtl_yes {}; // intersect rectangle with interval on orient template <typename rectangle_type, typename interval_type> typename enable_if< typename gtl_and_3<y_r_b_intersect2, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type, typename is_interval_concept<typename geometry_concept<interval_type>::type>::type>::type, bool>::type intersect(rectangle_type& rectangle, const interval_type& b, orientation_2d orient, bool consider_touch = true) { typename rectangle_interval_type<rectangle_type>::type ivl = get(rectangle, orient); if(intersect(ivl, b, consider_touch)) { set(rectangle, orient, ivl); return true; } return false; } struct y_r_b_intersect3 : gtl_yes {}; // clip rectangle to b template <typename rectangle_type_1, typename rectangle_type_2> typename enable_if< typename gtl_and_3<y_r_b_intersect3, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, bool>::type intersect(rectangle_type_1& rectangle, const rectangle_type_2& b, bool consider_touch = true) { if(intersects(rectangle, b)) { intersect(rectangle, horizontal(b), HORIZONTAL, consider_touch); intersect(rectangle, vertical(b), VERTICAL, consider_touch); return true; } return false; } struct y_r_g_intersect : gtl_yes {}; // Sets this to the generalized intersection of this and the given rectangle template <typename rectangle_type_1, typename rectangle_type_2> typename enable_if< typename gtl_and_3<y_r_g_intersect, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, rectangle_type_1>::type & generalized_intersect(rectangle_type_1& rectangle, const rectangle_type_2& b) { typename rectangle_interval_type<rectangle_type_1>::type ivl = get(rectangle, HORIZONTAL); generalized_intersect(ivl, horizontal(b)); horizontal(rectangle, ivl); ivl = vertical(rectangle); generalized_intersect(ivl, vertical(b)); vertical(rectangle, ivl); return rectangle; } struct y_r_bloat : gtl_yes {}; // bloat the interval specified by orient by bloating template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_bloat, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, rectangle_type>::type & bloat(rectangle_type& rectangle, orientation_2d orient, typename rectangle_coordinate_type<rectangle_type>::type bloating) { typename rectangle_interval_type<rectangle_type>::type ivl = get(rectangle, orient); bloat(ivl, bloating); set(rectangle, orient, ivl); return rectangle; } struct y_r_bloat2 : gtl_yes {}; // bloat the Rectangle by bloating template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_bloat2, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, rectangle_type>::type & bloat(rectangle_type& rectangle, typename rectangle_coordinate_type<rectangle_type>::type bloating) { bloat(rectangle, HORIZONTAL, bloating); return bloat(rectangle, VERTICAL, bloating); } struct y_r_bloat3 : gtl_yes {}; // bloat the interval cooresponding to orient by bloating in dir direction template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_bloat3, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, rectangle_type>::type & bloat(rectangle_type& rectangle, direction_2d dir, typename rectangle_coordinate_type<rectangle_type>::type bloating) { typename rectangle_interval_type<rectangle_type>::type ivl = get(rectangle, orientation_2d(dir)); bloat(ivl, direction_1d(dir), bloating); set(rectangle, orientation_2d(dir), ivl); return rectangle; } struct y_r_shrink : gtl_yes {}; // shrink the interval specified by orient by bloating template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_shrink, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, rectangle_type>::type & shrink(rectangle_type& rectangle, orientation_2d orient, typename rectangle_coordinate_type<rectangle_type>::type shrinking) { return bloat(rectangle, orient, -shrinking); } struct y_r_shrink2 : gtl_yes {}; // shrink the Rectangle by bloating template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_shrink2, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, rectangle_type>::type & shrink(rectangle_type& rectangle, typename rectangle_coordinate_type<rectangle_type>::type shrinking) { return bloat(rectangle, -shrinking); } struct y_r_shrink3 : gtl_yes {}; // shrink the interval cooresponding to orient by bloating in dir direction template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_shrink3, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, rectangle_type>::type & shrink(rectangle_type& rectangle, direction_2d dir, typename rectangle_coordinate_type<rectangle_type>::type shrinking) { return bloat(rectangle, dir, -shrinking); } struct y_r_encompass : gtl_yes {}; // encompass interval on orient template <typename rectangle_type, typename interval_type> typename enable_if<typename gtl_and_3< y_r_encompass, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type, typename is_interval_concept<typename geometry_concept<interval_type>::type>::type>::type, bool>::type encompass(rectangle_type& rectangle, const interval_type& b, orientation_2d orient) { typename rectangle_interval_type<rectangle_type>::type ivl = get(rectangle, orient); if(encompass(ivl, b)) { set(rectangle, orient, ivl); return true; } return false; } struct y_r_encompass2 : gtl_yes {}; // enlarge rectangle to encompass the Rectangle b template <typename rectangle_type_1, typename rectangle_type_2> typename enable_if< typename gtl_and_3< y_r_encompass2, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type >::type, bool>::type encompass(rectangle_type_1& rectangle, const rectangle_type_2& b) { //note that operator | is intentional because both should be called regardless return encompass(rectangle, horizontal(b), HORIZONTAL) | encompass(rectangle, vertical(b), VERTICAL); } struct y_r_encompass3 : gtl_yes {}; // enlarge rectangle to encompass the point b template <typename rectangle_type_1, typename point_type> typename enable_if<typename gtl_and_3< y_r_encompass3, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_point_concept<typename geometry_concept<point_type>::type>::type>::type, bool>::type encompass(rectangle_type_1& rectangle, const point_type& b) { typename rectangle_interval_type<rectangle_type_1>::type hivl, vivl; hivl = horizontal(rectangle); vivl = vertical(rectangle); //note that operator | is intentional because both should be called regardless bool retval = encompass(hivl, x(b)) | encompass(vivl, y(b)); if(retval) { horizontal(rectangle, hivl); vertical(rectangle, vivl); } return retval; } struct y_r_center : gtl_yes {}; // returns the center of the rectangle template <typename point_type, typename rectangle_type> typename enable_if< typename gtl_and_3<y_r_center, typename is_mutable_point_concept<typename geometry_concept<point_type>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, bool>::type center(point_type& center_point, const rectangle_type& rectangle) { center_point = construct<point_type>(center(horizontal(rectangle)), center(vertical(rectangle))); return true; } struct y_r_get_corner : gtl_yes {}; template <typename point_type, typename rectangle_type> typename enable_if< typename gtl_and_3<y_r_get_corner, typename is_mutable_point_concept<typename geometry_concept<point_type>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, bool>::type get_corner(point_type& corner_point, const rectangle_type& rectangle, direction_2d direction_facing, direction_1d direction_turning) { typedef typename rectangle_coordinate_type<rectangle_type>::type Unit; Unit u1 = get(rectangle, direction_facing); Unit u2 = get(rectangle, direction_facing.turn(direction_turning)); if(orientation_2d(direction_facing).to_int()) std::swap(u1, u2); corner_point = construct<point_type>(u1, u2); return true; } struct y_r_get_half : gtl_yes {}; template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_get_half, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, rectangle_type>::type get_half(const rectangle_type& rectangle, direction_2d dir) { rectangle_type retval(rectangle); set(retval, orientation_2d(dir), get_half(get(rectangle, orientation_2d(dir)), direction_1d(dir))); return retval; } struct y_r_join_with : gtl_yes {}; template <typename rectangle_type_1, typename rectangle_type_2> typename enable_if< typename gtl_and_3<y_r_join_with, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, bool>::type join_with(rectangle_type_1& rectangle, const rectangle_type_2& b) { typedef typename rectangle_interval_type<rectangle_type_1>::type Interval1; typedef typename rectangle_interval_type<rectangle_type_2>::type Interval2; Interval1 hi1 = get(rectangle, HORIZONTAL); Interval1 vi1 = get(rectangle, VERTICAL); Interval2 hi2 = get(b, HORIZONTAL), vi2 = get(b, VERTICAL); Interval1 temp; if (equivalence(hi1, hi2) && join_with(vi1, vi2)) { vertical(rectangle, vi1); return true; } if (equivalence(vi1, vi2) && join_with(hi1, hi2)) { horizontal(rectangle, hi1); return true; } return false; } struct y_r_eda2 : gtl_yes {}; template <typename rectangle_type, typename point_type> typename enable_if< typename gtl_and_3<y_r_eda2, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type, typename is_point_concept<typename geometry_concept<point_type>::type>::type>::type, typename rectangle_difference_type<rectangle_type>::type>::type euclidean_distance(const rectangle_type& lvalue, const point_type& rvalue, orientation_2d orient) { return euclidean_distance(get(lvalue, orient), get(rvalue, orient)); } struct y_r_eda : gtl_yes {}; template <typename rectangle_type, typename rectangle_type_2> typename enable_if< typename gtl_and_3<y_r_eda, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, typename rectangle_difference_type<rectangle_type>::type>::type euclidean_distance(const rectangle_type& lvalue, const rectangle_type_2& rvalue, orientation_2d orient) { return euclidean_distance(get(lvalue, orient), get(rvalue, orient)); } struct y_r_sed : gtl_yes {}; template <typename rectangle_type, typename point_type> typename enable_if< typename gtl_and_3<y_r_sed, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type, typename is_point_concept<typename geometry_concept<point_type>::type>::type>::type, typename rectangle_difference_type<rectangle_type>::type>::type square_euclidean_distance(rectangle_type& lvalue, const point_type& rvalue) { typename coordinate_traits<typename rectangle_coordinate_type<rectangle_type>::type>::coordinate_difference xdist, ydist; xdist = euclidean_distance(lvalue, rvalue, HORIZONTAL); ydist = euclidean_distance(lvalue, rvalue, VERTICAL); return (xdist * xdist) + (ydist * ydist); } struct y_r_sed2 : gtl_yes {}; template <typename rectangle_type, typename rectangle_type_2> typename enable_if< typename gtl_and_3<y_r_sed2, typename is_rectangle_concept< typename geometry_concept<rectangle_type>::type>::type, typename is_rectangle_concept< typename geometry_concept<rectangle_type_2>::type>::type>::type, typename rectangle_difference_type<rectangle_type>::type>::type square_euclidean_distance(const rectangle_type& lvalue, const rectangle_type_2& rvalue) { typename coordinate_traits<typename rectangle_coordinate_type<rectangle_type>::type>::coordinate_difference xdist, ydist; xdist = euclidean_distance(lvalue, rvalue, HORIZONTAL); ydist = euclidean_distance(lvalue, rvalue, VERTICAL); return (xdist * xdist) + (ydist * ydist); } struct y_r_edist : gtl_yes {}; template <typename rectangle_type, typename point_type> typename enable_if< typename gtl_and_3<y_r_edist, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type, typename is_point_concept<typename geometry_concept<point_type>::type>::type>::type, typename rectangle_distance_type<rectangle_type>::type>::type euclidean_distance(rectangle_type& lvalue, const point_type& rvalue) { return std::sqrt((double)(square_euclidean_distance(lvalue, rvalue))); } struct y_r_edist2 : gtl_yes {}; template <typename rectangle_type, typename rectangle_type_2> typename enable_if< typename gtl_and_3<y_r_edist2, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, typename rectangle_distance_type<rectangle_type>::type>::type euclidean_distance(const rectangle_type& lvalue, const rectangle_type_2& rvalue) { double val = (int)square_euclidean_distance(lvalue, rvalue); return std::sqrt(val); } struct y_r_mdist : gtl_yes {}; template <typename rectangle_type, typename point_type> typename enable_if< typename gtl_and_3<y_r_mdist, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type, typename is_point_concept<typename geometry_concept<point_type>::type>::type>::type, typename rectangle_difference_type<rectangle_type>::type>::type manhattan_distance(rectangle_type& lvalue, const point_type& rvalue) { typename coordinate_traits<typename rectangle_coordinate_type<rectangle_type>::type>::coordinate_difference xdist, ydist; xdist = euclidean_distance(lvalue, rvalue, HORIZONTAL); ydist = euclidean_distance(lvalue, rvalue, VERTICAL); return xdist + ydist; } struct y_r_mdist2 : gtl_yes {}; template <typename rectangle_type, typename rectangle_type_2> typename enable_if< typename gtl_and_3<y_r_mdist2, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, typename rectangle_difference_type<rectangle_type>::type>::type manhattan_distance(const rectangle_type& lvalue, const rectangle_type_2& rvalue) { typename coordinate_traits<typename rectangle_coordinate_type<rectangle_type>::type>::coordinate_difference xdist, ydist; xdist = euclidean_distance(lvalue, rvalue, HORIZONTAL); ydist = euclidean_distance(lvalue, rvalue, VERTICAL); return xdist + ydist; } struct y_r_scale_up : gtl_yes {}; template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_scale_up, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, rectangle_type>::type & scale_up(rectangle_type& rectangle, typename coordinate_traits<typename rectangle_coordinate_type<rectangle_type>::type>::unsigned_area_type factor) { horizontal(rectangle, scale_up(horizontal(rectangle), factor)); vertical(rectangle, scale_up(vertical(rectangle), factor)); return rectangle; } struct y_r_scale_down : gtl_yes {}; template <typename rectangle_type> typename enable_if<typename gtl_and<y_r_scale_down, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, rectangle_type>::type & scale_down(rectangle_type& rectangle, typename coordinate_traits<typename rectangle_coordinate_type<rectangle_type>::type>::unsigned_area_type factor) { horizontal(rectangle, scale_down(horizontal(rectangle), factor)); vertical(rectangle, scale_down(vertical(rectangle), factor)); return rectangle; } struct y_r_scale : gtl_yes {}; template <typename rectangle_type, typename scaling_type> typename enable_if<typename gtl_and<y_r_scale, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, rectangle_type>::type & scale(rectangle_type& rectangle, const scaling_type& scaling) { point_data<typename rectangle_coordinate_type<rectangle_type>::type> llp(xl(rectangle), yl(rectangle)); point_data<typename rectangle_coordinate_type<rectangle_type>::type> urp(xl(rectangle), yl(rectangle)); scale(llp, scaling); scale(urp, scaling); set_points(rectangle, llp, urp); return rectangle; } struct y_r_transform : gtl_yes {}; template <typename rectangle_type, typename transformation_type> typename enable_if<typename gtl_and<y_r_transform, typename is_mutable_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type>::type, rectangle_type>::type & transform(rectangle_type& rectangle, const transformation_type& transformation) { point_data<typename rectangle_coordinate_type<rectangle_type>::type> llp(xl(rectangle), yl(rectangle)); point_data<typename rectangle_coordinate_type<rectangle_type>::type> urp(xh(rectangle), yh(rectangle)); transform(llp, transformation); transform(urp, transformation); set_points(rectangle, llp, urp); return rectangle; } template <typename rectangle_type_1, typename rectangle_type_2> class less_rectangle_concept { private: orientation_2d orient_; public: inline less_rectangle_concept(orientation_2d orient = VERTICAL) : orient_(orient) {} typename enable_if< typename gtl_and< typename is_rectangle_concept<typename geometry_concept<rectangle_type_1>::type>::type, typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type, bool>::type operator () (const rectangle_type_1& a, const rectangle_type_2& b) const { typedef typename rectangle_coordinate_type<rectangle_type_1>::type Unit; Unit vl1 = get(get(a, orient_), LOW); Unit vl2 = get(get(b, orient_), LOW); if(vl1 > vl2) return false; if(vl1 == vl2) { orientation_2d perp = orient_.get_perpendicular(); Unit hl1 = get(get(a, perp), LOW); Unit hl2 = get(get(b, perp), LOW); if(hl1 > hl2) return false; if(hl1 == hl2) { Unit vh1 = get(get(a, orient_), HIGH); Unit vh2 = get(get(b, orient_), HIGH); if(vh1 > vh2) return false; if(vh1 == vh2) { Unit hh1 = get(get(a, perp), HIGH); Unit hh2 = get(get(b, perp), HIGH); return hh1 < hh2; } } } return true; } }; template <typename T> template <typename interval_type_1> inline void rectangle_data<T>::set(orientation_2d orient, const interval_type_1& interval) { assign(ranges_[orient.to_int()], interval); } template <class T> template <class T2> rectangle_data<T>& rectangle_data<T>::operator=(const T2& rvalue) { assign(*this, rvalue); return *this; } template <class T> template <class T2> bool rectangle_data<T>::operator==(const T2& rvalue) const { return equivalence(*this, rvalue); } template <typename T> struct geometry_concept<rectangle_data<T> > { typedef rectangle_concept type; }; } } #endif
46.926784
160
0.73419
[ "transform" ]
13b5def40e5c94c014a05af64d5ffc9c74402ad2
6,668
cc
C++
cfs/test/benchmark/simpleBench.cc
chenhao-ye/uFS
c344d689b33e30dd83bcd1b4de26602549a90fc3
[ "MIT" ]
13
2021-08-23T03:37:46.000Z
2022-02-16T03:00:09.000Z
cfs/test/benchmark/simpleBench.cc
chenhao-ye/uFS
c344d689b33e30dd83bcd1b4de26602549a90fc3
[ "MIT" ]
2
2021-11-12T10:19:47.000Z
2021-12-21T14:26:36.000Z
cfs/test/benchmark/simpleBench.cc
chenhao-ye/uFS
c344d689b33e30dd83bcd1b4de26602549a90fc3
[ "MIT" ]
4
2021-09-03T13:55:05.000Z
2021-11-09T10:59:33.000Z
#include <iostream> #include <chrono> #include <string> #include <vector> #include <thread> #include <atomic> #include <mutex> #include <stdint.h> #include <fcntl.h> #include <unistd.h> #include <cassert> #include <random> #include <functional> #include "param.h" #include "fsapi.h" //uint32_t maxFileSize = 2 * 1024 * 1024; uint32_t maxFileSize = 1024 * 1024 * 1024; std::string binName; static int pIdx; static int numThreads; std::atomic_bool workerRun(true); std::mutex lmutex; #ifdef USE_SPDK std::string fileDir = std::string("/"); #else std::string fileDir = std::string("/mnt/optanemnt/data/"); #endif enum WorkloadType { RAND_READ = 1, RAND_WRITE = 2, SEQ_READ = 3, SEQ_WRITE = 4, }; class BenchWorker{ std::chrono::steady_clock::time_point startTs; std::chrono::steady_clock::time_point finishTs; uint64_t reqFinished; public: void operator() (int wid, bool timeout, int endCond, WorkloadType type, uint32_t reqByte) { reqFinished = 0; char *userBuf = new char[reqByte]; // random generator auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); auto dice_rand = std::bind(std::uniform_int_distribution<uint32_t>(0, maxFileSize-2*reqByte), std::mt19937(seed)); std::string pathStr = fileDir + std::string("t"); pathStr += std::to_string(wid); std::cout << "open file" << pathStr << std::endl; // do work switch (type) { case RAND_READ: { ssize_t rc; off_t curOff; int fd = fs_open(pathStr.c_str(), O_RDWR, 0); if(fd < 0) { std::cerr << "ERROR cannot open file " << pathStr.c_str() << std::endl; return; } startTs = std::chrono::steady_clock::now(); while (workerRun) { if (!timeout && reqFinished >= endCond) { break; } curOff = dice_rand(); rc = fs_pread(fd, userBuf, reqByte, curOff); assert(rc == reqByte); reqFinished++; } finishTs = std::chrono::steady_clock::now(); break; } case RAND_WRITE: // not supported break; case SEQ_READ: { int fd = fs_open(pathStr.c_str(), O_RDWR, 0); if(fd < 0) { std::cerr << "ERROR cannot open file " << pathStr.c_str() << std::endl; return; } uint64_t numReqs = maxFileSize / reqByte; ssize_t rc; startTs = std::chrono::steady_clock::now(); for (uint i = 0; i < numReqs; i++) { //rc = fs_read(fd, userBuf, reqByte); rc = fs_pread(fd, userBuf, reqByte, i * reqByte); assert(rc == reqByte); } reqFinished = numReqs; finishTs = std::chrono::steady_clock::now(); break; } case SEQ_WRITE: // not supported break; default: std::cerr << "unkown workload" << std::endl; throw; } // end of work cases std::lock_guard<std::mutex> lock(lmutex); { // report result double durUs = std::chrono::duration_cast<std::chrono::microseconds>(finishTs - startTs).count(); std::cout << "wid:" << wid << " reqFinished:" << reqFinished << " timeUs:" << durUs << std::endl; // clean up } delete(userBuf); } }; void printUsage() { std::cout << "Usage: " << binName << " <PID> " << " <numThreads>" << " <T|N+secs|numTotal>" << " <workload ID> <reqByte> " << std::endl; std::cout << "---------------------------------------------------------------------\n" << "<PID>: index of process (from 0, used to get shmid for cfs\n" << "<numThreas>: number of threads\n" << "<T|N>: T means benchmark until time is used up (in seconds), " "N means total number of requests (all the threads)\n" << "<workload id>: 1:random read, 2:random write, 3:seq read, 4:seq write.\n" << "<reqByte>: size in Bytes of each request\n"; } void benchMain(std::vector<std::string> & cmdStrVec) { std::cout << fileDir << std::endl; if(cmdStrVec.size() != 5) { printUsage(); exit(1); } // process params int vecIdx = 0; pIdx = std::stoi(cmdStrVec[vecIdx++]); numThreads = std::stoi(cmdStrVec[vecIdx++]); bool timeOut; if(cmdStrVec[vecIdx][0] == 'T') { timeOut = true; }else if(cmdStrVec[vecIdx][0] == 'N') { timeOut = false; }else{ throw; } int endCond = std::stoi((cmdStrVec[vecIdx++]).substr(1)); WorkloadType workloadType = (WorkloadType) std::stoi(cmdStrVec[vecIdx++]); int reqByte = std::stoi(cmdStrVec[vecIdx++]); std::cout << "pIdx:" << pIdx << " numThreads:" << numThreads << " timeOut:" << timeOut << " endCond:" << endCond << " workload:" << workloadType << " reqByte:" << reqByte << std::endl; if(!timeOut) { endCond = endCond / numThreads; } // init fs fs_init(FS_SHM_KEY_BASE + pIdx); // init workers std::thread *workers = new std::thread[numThreads]; for(int i = 0; i < numThreads; i++) { // assume pIdx is a virtual pid starting from 0 // when using this benchmark, each process has the same # of threads (numthreads) // to make sure each thread access unique file, i+pIdx * numthreads will generate // filename workers[i] = std::thread(BenchWorker(), i + pIdx * numThreads, timeOut, endCond, workloadType, reqByte); // use this when needs to make sure threads from different process write to single file // workers[i] = std::thread(BenchWorker(), i + pIdx * numThreads, timeOut, endCond, workloadType, reqByte); } if(timeOut) { sleep(endCond); workerRun = false; } for(int i = 0; i < numThreads; i++) { workers[i].join(); } } int main(int argc, char ** argv) { std::vector<std::string> tokens; binName = std::string(argv[0]); for(int i = 1; i < argc; i++) { tokens.push_back(std::string(argv[i])); } benchMain(tokens); return 0; }
33.34
115
0.518746
[ "vector" ]
13b77d512056e6f3a308fbc472da2bb56f500d7a
2,332
cpp
C++
ArrtModel/ViewModel/Settings/ArrAccountSettingsModel.cpp
MichaelZp0/azure-remote-rendering-asset-tool
fe979bfe1923589f11487565ececdc575f5e940a
[ "MIT" ]
42
2020-06-12T19:10:52.000Z
2022-03-04T02:20:59.000Z
ArrtModel/ViewModel/Settings/ArrAccountSettingsModel.cpp
MichaelZp0/azure-remote-rendering-asset-tool
fe979bfe1923589f11487565ececdc575f5e940a
[ "MIT" ]
91
2020-06-12T12:10:46.000Z
2022-03-02T13:46:00.000Z
ArrtModel/ViewModel/Settings/ArrAccountSettingsModel.cpp
MichaelZp0/azure-remote-rendering-asset-tool
fe979bfe1923589f11487565ececdc575f5e940a
[ "MIT" ]
10
2020-07-29T21:19:14.000Z
2021-09-22T11:48:27.000Z
#include <Model/ArrFrontend.h> #include <Model/Settings/ArrAccountSettings.h> #include <ViewModel/Parameters/ComboBoxModel.h> #include <ViewModel/Parameters/TextModel.h> #include <ViewModel/Settings/ArrAccountSettingsModel.h> #include <string_view> Q_DECLARE_METATYPE(std::string); ArrAccountSettingsModel::ArrAccountSettingsModel(ArrAccountSettings* arrAccountSettings, ArrFrontend* frontend, QObject* parent) : SettingsBaseModel(parent) , m_arrAccountSettings(arrAccountSettings) , m_frontend(frontend) { using namespace std::literals; addControl(new TextModel(tr("ID"), m_arrAccountSettings, "id"sv, true)); addControl(new TextModel(tr("Key"), m_arrAccountSettings, "key"sv, true, true)); auto* accountDomainModel = new ComboBoxModelFromMap(tr("Account Domain"), m_arrAccountSettings, "accountDomain"sv); for (auto&& accountDomain : m_arrAccountSettings->getSupportedAccountDomains()) { accountDomainModel->addEntry(accountDomain.m_label, QVariant::fromValue(accountDomain.m_accountDomain)); } addControl(accountDomainModel); auto* regionModel = new ComboBoxModelFromMap(tr("Region"), m_arrAccountSettings, "region"sv); for (auto&& region : m_arrAccountSettings->getAvailableRegions()) { // TODO This does not have to be a vector.... regionModel->addEntry(region.m_label, QVariant::fromValue(region.m_domainUrl)); } addControl(regionModel); connect(m_frontend, &ArrFrontend::onStatusChanged, this, [this]() { Q_EMIT updateUi(); }); auto connectAccount = [this]() { m_frontend->connectAccount( m_arrAccountSettings->getId().toStdString().c_str(), m_arrAccountSettings->getKey().toStdString().c_str(), m_arrAccountSettings->getAccountDomain().toStdString().c_str(), m_arrAccountSettings->getRegion().c_str()); }; QObject::connect(m_arrAccountSettings, &ArrAccountSettings::changed, this, connectAccount); connectAccount(); } bool ArrAccountSettingsModel::isEnabled() const { return getStatus() != AccountConnectionStatus::CheckingCredentials; } AccountConnectionStatus ArrAccountSettingsModel::getStatus() const { return m_frontend->getStatus(); } void ArrAccountSettingsModel::reconnectAccount() { m_frontend->reconnectAccount(); }
36.4375
128
0.733276
[ "vector", "model" ]
13ba46b43792b4304605f4b2f900d72acd49b4ed
12,153
cpp
C++
src/Arabic/relations/ar_RelationUtilities.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
1
2022-03-24T19:57:00.000Z
2022-03-24T19:57:00.000Z
src/Arabic/relations/ar_RelationUtilities.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
src/Arabic/relations/ar_RelationUtilities.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
// Copyright 2008 by BBN Technologies Corp. // All Rights Reserved. #include "Generic/common/leak_detection.h" // This must be the first #include #include "Generic/common/ParamReader.h" #include "Arabic/relations/ar_RelationUtilities.h" #include "Arabic/relations/ar_RelationFinder.h" #include "Generic/theories/Mention.h" #include "Generic/theories/SynNode.h" #include "Generic/theories/PropositionSet.h" #include "Generic/parse/LanguageSpecificFunctions.h" #include "Arabic/parse/ar_STags.h" #include "Generic/theories/RelationConstants.h" #include "Generic/wordClustering/WordClusterClass.h" int ArabicRelationUtilities::getRelationCutoff() { static bool init = false; static int relation_cutoff; if (!init) { relation_cutoff = ParamReader::getRequiredIntParam("relation_mention_dist_cutoff"); init = true; if (relation_cutoff < 0) { throw UnexpectedInputException("ArabicRelationUtilities::getRelationCutoff()", "Parameter 'relation_mention_dist_cutoff' must be greater than or equal to 0"); } } return relation_cutoff; } int ArabicRelationUtilities::getAllowableRelationDistance() { static bool init = false; static int allow_relations_within_distance; if (!init) { allow_relations_within_distance = ParamReader::getRequiredIntParam("allow_relations_within_distance"); init = true; if (allow_relations_within_distance <= 0) { throw UnexpectedInputException("ArabicRelationUtilities::getAllowableRelationDistance()", "Parameter 'allow_relations_within_distance' must be greater than 0"); } } return allow_relations_within_distance; } std::vector<bool> ArabicRelationUtilities::identifyFalseOrHypotheticalProps(const PropositionSet *propSet, const MentionSet *mentionSet) { return std::vector<bool>(propSet->getNPropositions(), false); } void ArabicRelationUtilities::fillClusterArray(const Mention* ment, int* clust){ Symbol hw = ment->getNode()->getHeadWord(); Mention::Type mtype = ment->getMentionType(); WordClusterClass wc1(hw); for(int k =0; k<4; k++){ clust[k] = 0; } if(mtype != Mention::PRON){ clust[0] = wc1.c8(); clust[1] = wc1.c12(); clust[2] = wc1.c16(); clust[3] = wc1.c20(); } } bool ArabicRelationUtilities::validRelationArgs(Mention *m1, Mention *m2) { // This uses the same cutoff parameter as is used to distinguish between FAR/CLOSE in a number // of other features. This is probably not what we want, so I am commenting it out and // have added a new parameter below. //if(ArabicRelationUtilities::distIsLessThanCutoff(m1, m2)){ // return true; //} // We allow all mention pairs that are within distance X. // (We might allow some others if they meet the following criteria, // but these we definitely allow.) if (calcMentionDist(m1, m2) < getAllowableRelationDistance()) { return true; } const SynNode *chunk1 = findNPChunk(m1->getNode()); const SynNode *chunk2 = findNPChunk(m2->getNode()); if (chunk1 == chunk2) return true; const SynNode *parent = chunk1->getParent(); int i; for (i = 0; i < parent->getNChildren(); i++) { if (parent->getChild(i) == chunk1 || parent->getChild(i) == chunk2) { i++; break; } } for (int j = i; j < parent->getNChildren(); j++) { if (parent->getChild(j) == chunk1 || parent->getChild(j) == chunk2) { return true; } //if (parent->getChild(j)->getTag() != ArabicSTags::PREP && if (parent->getChild(j)->getTag() != ArabicSTags::IN && !LanguageSpecificFunctions::isNPtypeLabel(parent->getChild(j)->getTag())){ if((parent->getChild(j)->getTag() == ArabicSTags::LRB) || (parent->getChild(j)->getTag() == ArabicSTags::RRB)) { //std::cout<<"!!!!invalid relation: ! "<<std::endl; //m1->getNode()->dump(std::cout, 5); //std::cout<<std::endl; //m2->getNode()->dump(std::cout, 5); //std::cout<<std::endl; } return false; } /*if (parent->getChild(j)->getTag() == ArabicSTags::VERB || parent->getChild(j)->getTag() == ArabicSTags::VERB_IMPERATIVE || parent->getChild(j)->getTag() == ArabicSTags::VERB_IMPERFECT || parent->getChild(j)->getTag() == ArabicSTags::VERB_PERFECT) return false;*/ } return true; } const SynNode *ArabicRelationUtilities::findNPChunk(const SynNode *node) { if (node->getParent() == 0) { if (LanguageSpecificFunctions::isNPtypeLabel(node->getTag()) || ArabicSTags::isPronoun(node->getTag())) return node; else return 0; } const SynNode *parent = node->getParent(); if (parent->getParent() == 0) { //(LanguageSpecificFunctions::isNPtypeLabel(node->getTag()) || ArabicSTags::isPronoun(node->getTag()))) { return node; } else { return findNPChunk(parent); } } int ArabicRelationUtilities::getMentionStartToken(const Mention *m1){ int start_ment1 = -1; if(m1->mentionType == Mention::NAME){ start_ment1 = m1->getNode()->getStartToken(); } else{ if(m1->getHead() != 0){ start_ment1 = m1->getHead()->getStartToken(); } else if(m1->getNode() != 0){ if(m1->getNode()->getHead() != 0){ start_ment1 = m1->getNode()->getHead()->getStartToken(); } else{ start_ment1 = m1->getNode()->getStartToken(); } } } return start_ment1; } int ArabicRelationUtilities::getMentionEndToken(const Mention *m1){ int end_ment1 = -1; if(m1->mentionType == Mention::NAME){ end_ment1 = m1->getNode()->getEndToken(); } else{ if(m1->getHead() != 0){ end_ment1 = m1->getHead()->getEndToken(); } else if(m1->getNode() != 0){ if(m1->getNode()->getHead() != 0){ end_ment1 = m1->getNode()->getHead()->getEndToken(); } else{ end_ment1 = m1->getNode()->getEndToken(); } } } return end_ment1; } int ArabicRelationUtilities::calcMentionDist(const Mention *m1, const Mention *m2){ int start_ment1; int end_ment1; int start_ment2; int end_ment2; start_ment1 = getMentionStartToken(m1); end_ment1 = getMentionEndToken(m1); start_ment2 = getMentionStartToken(m2); end_ment2 = getMentionEndToken(m2); if((start_ment1 < 0) || (end_ment1 < 0) || (start_ment2 < 0) || (end_ment2 < 0) ){ return getRelationCutoff() + 50; } int dist = end_ment1 - start_ment2; if(dist < 0){ dist = end_ment2 - start_ment1; } return dist; } bool ArabicRelationUtilities::distIsLessThanCutoff(const Mention *m1, const Mention *m2){ int dist = calcMentionDist(m1, m2); if(dist < getRelationCutoff()){ return true; } else{ return false; } } bool ArabicRelationUtilities::isValidRelationEntityTypeCombo(Symbol validation_type, const Mention* m1, const Mention* m2, Symbol relType) { if(wcscmp(validation_type.to_string(), L"NONE") == 0){ return true; } if(wcscmp(validation_type.to_string(), L"2005") == 0){ if(is2005ValidRelationEntityTypeCombo(m1, m2, relType)) return true; if(is2005ValidRelationEntityTypeCombo(m2, m1, relType)) return true; return false; } if(wcscmp(validation_type.to_string(), L"2005_ORDERED") == 0){ if(is2005ValidRelationEntityTypeCombo(m1, m2, relType)) return true; return false; } return true; } bool ArabicRelationUtilities::is2005ValidRelationEntityTypeCombo(const Mention* arg1, const Mention* arg2, Symbol relType ) { Symbol relCat = RelationConstants::getBaseTypeSymbol(relType); Symbol relSubtype = RelationConstants::getSubtypeSymbol(relType); Symbol PER = EntityType::getPERType().getName(); Symbol ORG = EntityType::getORGType().getName(); Symbol LOC = EntityType::getLOCType().getName(); Symbol FAC = EntityType::getFACType().getName(); Symbol GPE = EntityType::getGPEType().getName(); Symbol WEA = Symbol(L"WEA"); Symbol VEH = Symbol(L"VEH"); Symbol arg1_type = arg1->getEntityType().getName(); Symbol arg1_subtype = EntitySubtype::getUndetType().getName(); if(arg1->getEntitySubtype().isDetermined()){ Symbol arg1_subtype = arg1->getEntitySubtype().getName(); } Symbol arg2_type = arg2->getEntityType().getName(); Symbol arg2_subtype = EntitySubtype::getUndetType().getName(); if(arg2->getEntitySubtype().isDetermined()){ Symbol arg2_subtype = arg1->getEntitySubtype().getName(); } if(relCat == Symbol(L"PER-SOC")){ if((arg1_type == PER) && (arg2_type == PER)){ return true; } return false; } if(relType == Symbol(L"PHYS.Located")){ //Arabic guidelines allow arg 1 to be a wea/veh English guidelines do not?? //if((arg1_type == PER) || (arg1_type == VEH) || (arg1_type == WEA)){ if(arg1_type == PER){ if((arg2_type == GPE) || (arg2_type == LOC) || (arg2_type == FAC)){ return true; } } return false; } if(relType == Symbol(L"PHYS.Near")){ if((arg1_type== PER)|| (arg1_type == GPE) || (arg1_type == LOC) || (arg1_type == FAC)) { if((arg2_type == GPE) || (arg2_type == LOC) || (arg2_type == FAC)){ return true; } } return false; } if(relType == Symbol(L"PART-WHOLE.Geographical")){ if((arg1_type == GPE) || (arg1_type == LOC) ||(arg1_type == FAC)) { if((arg2_type == GPE) || (arg2_type == LOC) || (arg2_type == FAC)){ return true; } } return false; } if(relType == Symbol(L"PART-WHOLE.Subsidiary")){ if((arg1_type == ORG) ) { if((arg2_type == GPE) || (arg2_type == ORG)){ return true; } } return false; } if(relType == Symbol(L"PART-WHOLE.Artifact")){ if(arg1_type != arg2_type){ return false; } if((arg1_type == VEH) ||(arg1_type == WEA) ) { if((arg2_type == VEH) ||(arg2_type == WEA) ){ return true; } } return false; } if(relType == Symbol(L"ORG-AFF.Employment")){ if(arg1_type == PER){ if( (arg2_type == GPE) || (arg2_type == ORG) ){ return true; } } return false; } if(relType == Symbol(L"ORG-AFF.Ownership")){ if(arg1_type == PER){ if( arg2_type == ORG){ return true; } } return false; } if(relType == Symbol(L"ORG-AFF.Founder")){ if((arg1_type == PER) || (arg1_type == ORG)){ if( (arg2_type == GPE) || (arg2_type == ORG) ){ return true; } } return false; } if(relType == Symbol(L"ORG-AFF.Student-Alum")){ if(arg1_type == PER){ if( (arg2_type == ORG) ){ if(arg2_subtype == EntitySubtype::getUndetType().getName()){ //subtype hasn't been determined, so keep the relation return true; } if(arg2_subtype == Symbol(L"Educational")){ return true; } } } return false; } if(relType == Symbol(L"ORG-AFF.Sports-Affiliation")){ if(arg1_type == PER){ if( (arg2_type == ORG) ){ if(arg2_subtype == EntitySubtype::getUndetType().getName()){ //subtype hasn't been determined, so keep the relation return true; } if(arg2_subtype == Symbol(L"Sports")){ return true; } } } return false; } if(relType == Symbol(L"ORG-AFF.Investor-Shareholder")){ if((arg1_type == PER) || (arg1_type == ORG) || (arg1_type == GPE)){ if( (arg2_type == GPE) || (arg2_type == ORG) ){ return true; } } return false; } if(relType == Symbol(L"ORG-AFF.Membership")){ if((arg1_type == PER) || (arg1_type == ORG) || (arg1_type == GPE)){ if( (arg2_type == ORG) ){ return true; } } return false; } if(relType == Symbol(L"ART.User-Owner-Inventor-Manufacturer")){ if((arg1_type == PER) || (arg1_type == ORG) || (arg1_type == GPE)){ if( (arg2_type == WEA) || (arg2_type == VEH) || (arg2_type == FAC) ){ return true; } } return false; } if(relType == Symbol(L"GEN-AFF.Citizen-Resident-Religion-Ethnicity")){ if((arg1_type == PER) ){ if( (arg2_type == ORG)|| (arg2_type == GPE) || (arg2_type == LOC) || (arg2_type == PER)){ return true; } } return false; } if(relType == Symbol(L"GEN-AFF.Org-Location")){ if((arg1_type == ORG) ){ if( (arg2_type == GPE) || (arg2_type == LOC) ){ return true; } } return false; } // ignore metonymy for now return true; }
29.355072
110
0.636304
[ "vector" ]
13bc9bed5a82ed91ab84c066b654914bca20593f
25,037
cpp
C++
IVT/src/Math/LinearAlgebraCV.cpp
Tobi2001/asr_ivt
146abe4324a14d7b8acccec7b1bfbdb74590fb5f
[ "BSD-3-Clause" ]
null
null
null
IVT/src/Math/LinearAlgebraCV.cpp
Tobi2001/asr_ivt
146abe4324a14d7b8acccec7b1bfbdb74590fb5f
[ "BSD-3-Clause" ]
null
null
null
IVT/src/Math/LinearAlgebraCV.cpp
Tobi2001/asr_ivt
146abe4324a14d7b8acccec7b1bfbdb74590fb5f
[ "BSD-3-Clause" ]
1
2019-11-24T17:09:19.000Z
2019-11-24T17:09:19.000Z
// **************************************************************************** // This file is part of the Integrating Vision Toolkit (IVT). // // The IVT is maintained by the Karlsruhe Institute of Technology (KIT) // (www.kit.edu) in cooperation with the company Keyetech (www.keyetech.de). // // Copyright (C) 2014 Karlsruhe Institute of Technology (KIT). // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the KIT 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 KIT 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 KIT 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. // **************************************************************************** // **************************************************************************** // Includes // **************************************************************************** #include <new> // for explicitly using correct new/delete operators on VC DSPs #include "LinearAlgebraCV.h" #include "LinearAlgebra.h" #include "Math/FloatMatrix.h" #include "Math/FloatVector.h" #include "Math/DoubleMatrix.h" #include "Math/DoubleVector.h" #include "Math/Math2d.h" #include "Math/Math3d.h" #include "Helpers/helpers.h" #include <float.h> #include <math.h> #include <stdio.h> // **************************************************************************** // Functions // **************************************************************************** void LinearAlgebraCV::SolveLinearLeastSquaresHomogeneousSVD(const CFloatMatrix *A, CFloatVector *x) { if (A->columns != x->dimension) { printf("error: A, b, x do not match LinearAlgebraCV::SolveLinearLeastSquaresHomogeneousSVD"); return; } if (A->rows < A->columns) { printf("error: equation system is underdetermined in LinearAlgebraCV::SolveLinearLeastSquaresHomogeneousSVD\n"); return; } const int m = A->rows; const int n = A->columns; CFloatMatrix W(n, m), V(n, n); SVD(A, &W, 0, &V, false, false, false); for (int i = 0, offset = n - 1; i < n; i++, offset += n) x->data[i] = V.data[offset]; } void LinearAlgebraCV::SolveLinearLeastSquaresSVD(const CFloatMatrix *A, const CFloatVector *b, CFloatVector *x) { if (A->columns != x->dimension || A->rows != b->dimension) { printf("error: A, b, x do not match LinearAlgebraCV::SolveLinearLeastSquaresSVD"); return; } if (A->rows < A->columns) { printf("error: equation system is underdetermined in LinearAlgebraCV::SolveLinearLeastSquaresSVD\n"); return; } CFloatMatrix A_(A->rows, A->columns); CalculatePseudoInverseSVD(A, &A_); LinearAlgebra::MulMatVec(&A_, b, x); } void LinearAlgebraCV::SolveLinearLeastSquaresSimple(const CFloatMatrix *A, const CFloatVector *b, CFloatVector *x) { if (A->columns != x->dimension || A->rows != b->dimension) { printf("error: A, b, x do not match LinearAlgebraCV::SolveLinearLeastSquaresSimple"); return; } if (A->rows < A->columns) { printf("error: equation system is underdetermined in LinearAlgebraCV::SolveLinearLeastSquaresSimple\n"); return; } CFloatMatrix A_(A->rows, A->columns); CalculatePseudoInverseSimple(A, &A_); LinearAlgebra::MulMatVec(&A_, b, x); } void LinearAlgebraCV::CalculatePseudoInverseSVD(const CFloatMatrix *pInputMatrix, CFloatMatrix *pResultMatrix) { if (pInputMatrix->columns != pResultMatrix->rows || pInputMatrix->rows != pResultMatrix->columns) { printf("error: input and output matrix do not match LinearAlgebraCV::CalculatePseudoInverseSVD"); return; } // algorithm: // 1: compute U * W * V^T = A // 2: compute W' = W^T with all non-zero values inverted // 3: compute V * W' * U^T (=pseudoinverse of A) const CFloatMatrix *A = pInputMatrix; const int m = pInputMatrix->rows; const int n = pInputMatrix->columns; CFloatMatrix W(n, m), WT(m, n), UT(m, m), V(n, n); // calculate SVD SVD(A, &W, &UT, &V, false, true, false); // transpose middle diagonal matrix Transpose(&W, &WT); const int min = MY_MIN(m, n); int i; float fThreshold = 0.0f; for (i = 0; i < min; i++) fThreshold += WT(i, i); fThreshold *= 2 * FLT_EPSILON; // invert non-zero values (along diagonal) for (i = 0; i < min; i++) if (WT(i, i) < fThreshold) WT(i, i) = 0.0f; else WT(i, i) = 1.0f / WT(i, i); // calculate pseudoinverse CFloatMatrix temp(m, n); Multiply(&V, &WT, &temp); Multiply(&temp, &UT, pResultMatrix); } void LinearAlgebraCV::CalculatePseudoInverseSimple(const CFloatMatrix *pInputMatrix, CFloatMatrix *pResultMatrix) { if (pInputMatrix->columns != pResultMatrix->rows || pInputMatrix->rows != pResultMatrix->columns) { printf("error: input and output matrix do not match LinearAlgebraCV::CalculatePseudoInverseSimple"); return; } // algorithm: // compute (A * A^T)^-1 * A^T const CFloatMatrix *A = pInputMatrix; const int m = pInputMatrix->rows; const int n = pInputMatrix->columns; CFloatMatrix AT(m, n), ATA(n, n), ATA_inverted(n, n); Transpose(A, &AT); Multiply(&AT, A, &ATA); Invert(&ATA, &ATA_inverted); Multiply(&ATA_inverted, &AT, pResultMatrix); } void LinearAlgebraCV::Invert(const CFloatMatrix *pInputMatrix, const CFloatMatrix *pResultMatrix) { if (pInputMatrix->columns != pInputMatrix->rows) { printf("error: input is not square matrix in LinearAlgebraCV::Invert"); return; } if (pInputMatrix->columns != pResultMatrix->columns || pInputMatrix->rows != pResultMatrix->rows) { printf("error: input and output matrix are not the same in LinearAlgebraCV::Invert"); return; } CvMat inputMatrix = cvMat(pInputMatrix->rows, pInputMatrix->columns, CV_32FC1, pInputMatrix->data); CvMat resultMatrix = cvMat(pResultMatrix->rows, pResultMatrix->columns, CV_32FC1, pResultMatrix->data); cvInvert(&inputMatrix, &resultMatrix); } void LinearAlgebraCV::Transpose(const CFloatMatrix *pInputMatrix, const CFloatMatrix *pResultMatrix) { if (pInputMatrix->columns != pResultMatrix->rows || pInputMatrix->rows != pResultMatrix->columns) { printf("error: input and output matrix do not match LinearAlgebraCV::Transpose"); return; } CvMat inputMatrix = cvMat(pInputMatrix->rows, pInputMatrix->columns, CV_32FC1, pInputMatrix->data); CvMat resultMatrix = cvMat(pResultMatrix->rows, pResultMatrix->columns, CV_32FC1, pResultMatrix->data); cvTranspose(&inputMatrix, &resultMatrix); } void LinearAlgebraCV::CalculateCovarianceMatrix(const CFloatMatrix *pMatrix, CFloatMatrix *pCovarianceMatrix) { if (pCovarianceMatrix->columns != pMatrix->columns || pCovarianceMatrix->rows != pMatrix->columns) return; const int columns = pMatrix->columns; const int rows = pMatrix->rows; CvMat covarianceMatrix = cvMat(columns, columns, CV_32FC1, pCovarianceMatrix->data); CvMat **ppInput = new CvMat*[rows]; for (int i = 0; i < rows; i++) { CvMat *vector = cvCreateMatHeader(1, columns, CV_32FC1); cvInitMatHeader(vector, 1, columns, CV_32FC1, pMatrix->data + i * columns); ppInput[i] = vector; } CvMat *avg = cvCreateMat(1, columns, CV_32FC1); #ifdef CV_COVAR_NORMAL cvCalcCovarMatrix((const CvArr **) ppInput, rows, &covarianceMatrix, avg, CV_COVAR_NORMAL); #else cvCalcCovarMatrix((const CvArr **) ppInput, &covarianceMatrix, avg); #endif cvReleaseMat(&avg); } void LinearAlgebraCV::Multiply(const CFloatMatrix *A, const CFloatMatrix *B, CFloatMatrix *pResultMatrix, bool bTransposeB) { if (!bTransposeB && (A->columns != B->rows || pResultMatrix->columns != B->columns || pResultMatrix->rows != A->rows)) { printf("error: matrices A, B, and pResultMatrix do not satisfy requirements for LinearAlgebraCV::Multiply\n"); return; } if (bTransposeB && (A->columns != B->columns || pResultMatrix->columns != B->rows || pResultMatrix->rows != A->rows)) { printf("error: matrices A, B, and pResultMatrix do not satisfy requirements for LinearAlgebraCV::Multiply\n"); return; } int flags = 0; if (bTransposeB) flags = CV_GEMM_B_T; CvMat matrixA = cvMat(A->rows, A->columns, CV_32FC1, A->data); CvMat matrixB = cvMat(B->rows, B->columns, CV_32FC1, B->data); CvMat result_matrix = cvMat(pResultMatrix->rows, pResultMatrix->columns, CV_32FC1, pResultMatrix->data); cvGEMM(&matrixA, &matrixB, 1, 0, 1, &result_matrix, flags); } void LinearAlgebraCV::SelfProduct(const CFloatMatrix *pMatrix, CFloatMatrix *pResultMatrix, bool bTransposeSecond) { if (pResultMatrix->columns != pMatrix->columns || pResultMatrix->rows != pMatrix->columns) return; CvMat matrix = cvMat(pMatrix->rows, pMatrix->columns, CV_32FC1, pMatrix->data); CvMat result_matrix = cvMat(pResultMatrix->rows, pResultMatrix->columns, CV_32FC1, pResultMatrix->data); if (bTransposeSecond) cvGEMM(&matrix, &matrix, 1, 0, 1, &result_matrix, CV_GEMM_B_T); else cvGEMM(&matrix, &matrix, 1, 0, 1, &result_matrix, CV_GEMM_A_T); } void LinearAlgebraCV::SVD(const CFloatMatrix *A, CFloatMatrix *W, CFloatMatrix *U, CFloatMatrix *V, bool bAllowModifyA, bool bReturnUTransposed, bool bReturnVTransposed) { const int columns = A->columns; const int rows = A->rows; if (W->columns != columns || W->rows != rows) { printf("error: W should have %i columns and %i rows for LinearAlgebra::SVD\n", columns, rows); return; } if (U && (U->columns != rows || U->rows != rows)) { printf("error: U should have %i columns and %i rows for LinearAlgebra::SVD\n", rows, rows); return; } if (V && (V->columns != columns || V->rows != columns)) { printf("error: V should have %i columns and %i rows for LinearAlgebra::SVD\n", columns, columns); return; } int flags = 0; if (bAllowModifyA) flags |= CV_SVD_MODIFY_A; if (bReturnUTransposed) flags |= CV_SVD_U_T; if (bReturnVTransposed) flags |= CV_SVD_V_T; CvMat matrixA = cvMat(rows, columns, CV_32FC1, A->data); CvMat matrixW = cvMat(rows, columns, CV_32FC1, W->data); if (U && V) { CvMat matrixU = cvMat(rows, rows, CV_32FC1, U->data); CvMat matrixV = cvMat(columns, columns, CV_32FC1, V->data); cvSVD(&matrixA, &matrixW, &matrixU, &matrixV, flags); } else if (U) { CvMat matrixU = cvMat(rows, rows, CV_32FC1, U->data); cvSVD(&matrixA, &matrixW, &matrixU, 0, flags); } else if (V) { CvMat matrixV = cvMat(columns, columns, CV_32FC1, V->data); cvSVD(&matrixA, &matrixW, 0, &matrixV, flags); } else { cvSVD(&matrixA, &matrixW, 0, 0, flags); } } void LinearAlgebraCV::PCA(const CFloatMatrix *pData, CFloatMatrix *pTransformationMatrix, CFloatMatrix *pTransformedData, int nTargetDimension) { if (nTargetDimension > pData->columns) { printf("error: target dimension is greater than number of columns in training data matrix in LinearAlgebraCV::PCA\n"); return; } const int samples = pData->rows; const int dimension = pData->columns; if (pTransformationMatrix->columns != dimension || pTransformationMatrix->rows != nTargetDimension || pTransformedData->columns != samples || pTransformedData->rows != nTargetDimension) { printf("error: input to LinearAlgebraCV::PCA does not match\n"); return; } CFloatMatrix adjustedData(pData); CFloatMatrix covarianceMatrix(dimension, dimension); CFloatMatrix eigenValues(dimension, dimension); CFloatMatrix eigenVectors(dimension, dimension); printf("subtracting mean from columns...\n"); LinearAlgebra::SubtractMeanFromColumns(pData, &adjustedData); printf("calculating covariance matrix...\n"); LinearAlgebraCV::SelfProduct(&adjustedData, &covarianceMatrix); printf("calculating SVD on %ix%i matrix...\n", dimension, dimension); LinearAlgebraCV::SVD(&covarianceMatrix, &eigenValues, &eigenVectors, 0, true, true); printf("SVD calculated\n"); for (int i = 0, offset = 0; i < nTargetDimension; i++) { for (int j = 0; j < dimension; j++) { pTransformationMatrix->data[offset] = eigenVectors.data[i * dimension + j]; offset++; } } LinearAlgebraCV::Multiply(pTransformationMatrix, pData, pTransformedData, true); } void LinearAlgebraCV::PCA(const CFloatMatrix *pData, CFloatMatrix *pTransformationMatrix, CFloatMatrix *pEigenValues) { const int samples = pData->rows; const int dimension = pData->columns; if (pTransformationMatrix->columns != dimension || pTransformationMatrix->rows != dimension || pEigenValues->columns != 1 || pEigenValues->rows != dimension) return; CFloatMatrix adjustedData(pData); CFloatMatrix covarianceMatrix(dimension, dimension); CFloatMatrix eigenValues(dimension, dimension); CFloatMatrix eigenVectors(dimension, dimension); printf("subtracting mean from columns...\n"); LinearAlgebra::SubtractMeanFromColumns(pData, &adjustedData); printf("calculating covariance matrix...\n"); LinearAlgebraCV::SelfProduct(&adjustedData, &covarianceMatrix); printf("calculating SVD on %ix%i matrix...\n", dimension, dimension); LinearAlgebraCV::SVD(&covarianceMatrix, &eigenValues, pTransformationMatrix, 0, true, true); printf("SVD calculated\n"); for (int i = 0; i < dimension; i++) pEigenValues->data[i] = eigenValues.data[i * dimension + i]; } bool LinearAlgebraCV::DetermineAffineTransformation(const Vec2d *pSourcePoints, const Vec2d *pTargetPoints, int nPoints, Mat3d &A, bool bUseSVD) { if (nPoints < 3) { printf("error: not enough input point pairs for LinearAlgebraCV::DetermineAffineTransformation (must be at least 3)\n"); return false; } CFloatMatrix M(6, 2 * nPoints); CFloatVector b(2 * nPoints); float *data = M.data; for (int i = 0, offset = 0; i < nPoints; i++, offset += 12) { data[offset] = pSourcePoints[i].x; data[offset + 1] = pSourcePoints[i].y; data[offset + 2] = 1; data[offset + 3] = 0; data[offset + 4] = 0; data[offset + 5] = 0; data[offset + 6] = 0; data[offset + 7] = 0; data[offset + 8] = 0; data[offset + 9] = pSourcePoints[i].x; data[offset + 10] = pSourcePoints[i].y; data[offset + 11] = 1; const int index = 2 * i; b.data[index] = pTargetPoints[i].x; b.data[index + 1] = pTargetPoints[i].y; } CFloatVector x(6); if (bUseSVD) LinearAlgebraCV::SolveLinearLeastSquaresSVD(&M, &b, &x); else LinearAlgebraCV::SolveLinearLeastSquaresSimple(&M, &b, &x); Math3d::SetMat(A, x.data[0], x.data[1], x.data[2], x.data[3], x.data[4], x.data[5], 0, 0, 1); return true; } bool LinearAlgebraCV::DetermineHomography(const Vec2d *pSourcePoints, const Vec2d *pTargetPoints, int nPoints, Mat3d &A, bool bUseSVD) { if (nPoints < 4) { printf("error: not enough input point pairs for LinearAlgebraCV::DetermineHomography (must be at least 4)\n"); return false; } // this least squares problem becomes numerically instable when // using float instead of double!! CDoubleMatrix M(8, 2 * nPoints); CDoubleVector b(2 * nPoints); double *data = M.data; for (int i = 0, offset = 0; i < nPoints; i++, offset += 16) { data[offset] = pSourcePoints[i].x; data[offset + 1] = pSourcePoints[i].y; data[offset + 2] = 1; data[offset + 3] = 0; data[offset + 4] = 0; data[offset + 5] = 0; data[offset + 6] = -pSourcePoints[i].x * pTargetPoints[i].x; data[offset + 7] = -pSourcePoints[i].y * pTargetPoints[i].x; data[offset + 8] = 0; data[offset + 9] = 0; data[offset + 10] = 0; data[offset + 11] = pSourcePoints[i].x; data[offset + 12] = pSourcePoints[i].y; data[offset + 13] = 1; data[offset + 14] = -pSourcePoints[i].x * pTargetPoints[i].y; data[offset + 15] = -pSourcePoints[i].y * pTargetPoints[i].y; const int index = 2 * i; b.data[index] = pTargetPoints[i].x; b.data[index + 1] = pTargetPoints[i].y; } CDoubleVector x(8); if (bUseSVD) LinearAlgebraCV::SolveLinearLeastSquaresSVD(&M, &b, &x); else LinearAlgebraCV::SolveLinearLeastSquaresSimple(&M, &b, &x); Math3d::SetMat(A, float(x.data[0]), float(x.data[1]), float(x.data[2]), float(x.data[3]), float(x.data[4]), float(x.data[5]), float(x.data[6]), float(x.data[7]), 1); return true; } // copy & paste implementation for CDoubleMatrix and CDoubleVector // not nice, but i don't like templates. void LinearAlgebraCV::SolveLinearLeastSquaresHomogeneousSVD(const CDoubleMatrix *A, CDoubleVector *x) { if (A->columns != x->dimension) { printf("error: A, b, x do not match LinearAlgebraCV::SolveLinearLeastSquaresHomogeneousSVD"); return; } if (A->rows < A->columns) { printf("error: equation system is underdetermined in LinearAlgebraCV::SolveLinearLeastSquaresHomogeneousSVD\n"); return; } const int m = A->rows; const int n = A->columns; CDoubleMatrix W(n, m), V(n, n); SVD(A, &W, 0, &V, false, false, false); for (int i = 0, offset = n - 1; i < n; i++, offset += n) x->data[i] = V.data[offset]; } void LinearAlgebraCV::SolveLinearLeastSquaresSVD(const CDoubleMatrix *A, const CDoubleVector *b, CDoubleVector *x) { if (A->columns != x->dimension || A->rows != b->dimension) { printf("error: A, b, x do not match LinearAlgebraCV::SolveLinearLeastSquaresSVD"); return; } if (A->rows < A->columns) { printf("error: equation system is underdetermined in LinearAlgebraCV::SolveLinearLeastSquaresSVD\n"); return; } #if 0 CvMat *AA = cvCreateMat(A->rows, A->columns, CV_64FC1); CvMat *BB = cvCreateMat(b->dimension, 1, CV_64FC1); CvMat *XX = cvCreateMat(x->dimension, 1, CV_64FC1); int i; for (i = 0; i < A->rows * A->columns; i++) AA->data.db[i] = A->data[i]; for (i = 0; i < b->dimension; i++) BB->data.db[i] = b->data[i]; cvSolve(AA, BB, XX, CV_SVD); for (int k = 0; k < 8; k++) x->data[k] = XX->data.db[k]; cvReleaseMat(&AA); cvReleaseMat(&BB); cvReleaseMat(&XX); #else CDoubleMatrix A_(A->rows, A->columns); CalculatePseudoInverseSVD(A, &A_); LinearAlgebra::MulMatVec(&A_, b, x); #endif } void LinearAlgebraCV::SolveLinearLeastSquaresSimple(const CDoubleMatrix *A, const CDoubleVector *b, CDoubleVector *x) { if (A->columns != x->dimension || A->rows != b->dimension) { printf("error: A, b, x do not match LinearAlgebraCV::SolveLinearLeastSquaresSimple"); return; } if (A->rows < A->columns) { printf("error: equation system is underdetermined in LinearAlgebraCV::SolveLinearLeastSquaresSimple\n"); return; } CDoubleMatrix A_(A->rows, A->columns); CalculatePseudoInverseSimple(A, &A_); LinearAlgebra::MulMatVec(&A_, b, x); } void LinearAlgebraCV::CalculatePseudoInverseSVD(const CDoubleMatrix *pInputMatrix, CDoubleMatrix *pResultMatrix) { if (pInputMatrix->columns != pResultMatrix->rows || pInputMatrix->rows != pResultMatrix->columns) { printf("error: input and output matrix do not match LinearAlgebraCV::CalculatePseudoInverseSVD"); return; } // algorithm: // 1: compute U * W * V^T = A // 2: compute W' = W^T with all non-zero values inverted // 3: compute V * W' * U^T (=pseudoinverse of A) const CDoubleMatrix *A = pInputMatrix; const int m = pInputMatrix->rows; const int n = pInputMatrix->columns; CDoubleMatrix W(n, m), WT(m, n), UT(m, m), V(n, n); // calculate SVD SVD(A, &W, &UT, &V, false, true, false); // transpose middle diagonal matrix Transpose(&W, &WT); const int min = MY_MIN(m, n); int i; double dThreshold = 0.0; for(i = 0; i < min; i++) dThreshold += WT(i, i); dThreshold *= 2 * DBL_EPSILON; // invert non-zero values (along diagonal) for (i = 0; i < min; i++) if (WT(i, i) < dThreshold) WT(i, i) = 0; else WT(i, i) = 1.0 / WT(i, i); // calculate pseudoinverse CDoubleMatrix temp(m, n); Multiply(&V, &WT, &temp); Multiply(&temp, &UT, pResultMatrix); } void LinearAlgebraCV::CalculatePseudoInverseSimple(const CDoubleMatrix *pInputMatrix, CDoubleMatrix *pResultMatrix) { if (pInputMatrix->columns != pResultMatrix->rows || pInputMatrix->rows != pResultMatrix->columns) { printf("error: input and output matrix do not match LinearAlgebraCV::CalculatePseudoInverseSimple"); return; } // algorithm: // compute (A * A^T)^-1 * A^T const CDoubleMatrix *A = pInputMatrix; const int m = pInputMatrix->rows; const int n = pInputMatrix->columns; CDoubleMatrix AT(m, n), ATA(n, n), ATA_inverted(n, n); Transpose(A, &AT); Multiply(&AT, A, &ATA); Invert(&ATA, &ATA_inverted); Multiply(&ATA_inverted, &AT, pResultMatrix); } void LinearAlgebraCV::Invert(const CDoubleMatrix *pInputMatrix, const CDoubleMatrix *pResultMatrix) { if (pInputMatrix->columns != pInputMatrix->rows) { printf("error: input is not square matrix in LinearAlgebraCV::Invert"); return; } if (pInputMatrix->columns != pResultMatrix->columns || pInputMatrix->rows != pResultMatrix->rows) { printf("error: input and output matrix are not the same in LinearAlgebraCV::Invert"); return; } CvMat inputMatrix = cvMat(pInputMatrix->rows, pInputMatrix->columns, CV_64FC1, pInputMatrix->data); CvMat resultMatrix = cvMat(pResultMatrix->rows, pResultMatrix->columns, CV_64FC1, pResultMatrix->data); cvInvert(&inputMatrix, &resultMatrix); } void LinearAlgebraCV::Transpose(const CDoubleMatrix *pInputMatrix, const CDoubleMatrix *pResultMatrix) { if (pInputMatrix->columns != pResultMatrix->rows || pInputMatrix->rows != pResultMatrix->columns) { printf("error: input and output matrix do not match LinearAlgebraCV::Transpose"); return; } CvMat inputMatrix = cvMat(pInputMatrix->rows, pInputMatrix->columns, CV_64FC1, pInputMatrix->data); CvMat resultMatrix = cvMat(pResultMatrix->rows, pResultMatrix->columns, CV_64FC1, pResultMatrix->data); cvTranspose(&inputMatrix, &resultMatrix); } void LinearAlgebraCV::Multiply(const CDoubleMatrix *A, const CDoubleMatrix *B, CDoubleMatrix *pResultMatrix, bool bTransposeB) { if (!bTransposeB && (A->columns != B->rows || pResultMatrix->columns != B->columns || pResultMatrix->rows != A->rows)) { printf("error: matrices A, B, and pResultMatrix do not satisfy requirements for LinearAlgebraCV::Multiply\n"); return; } if (bTransposeB && (A->columns != B->columns || pResultMatrix->columns != B->rows || pResultMatrix->rows != A->rows)) { printf("error: matrices A, B, and pResultMatrix do not satisfy requirements for LinearAlgebraCV::Multiply\n"); return; } int flags = 0; if (bTransposeB) flags = CV_GEMM_B_T; CvMat matrixA = cvMat(A->rows, A->columns, CV_64FC1, A->data); CvMat matrixB = cvMat(B->rows, B->columns, CV_64FC1, B->data); CvMat result_matrix = cvMat(pResultMatrix->rows, pResultMatrix->columns, CV_64FC1, pResultMatrix->data); cvGEMM(&matrixA, &matrixB, 1, 0, 1, &result_matrix, flags); } void LinearAlgebraCV::SVD(const CDoubleMatrix *A, CDoubleMatrix *W, CDoubleMatrix *U, CDoubleMatrix *V, bool bAllowModifyA, bool bReturnUTransposed, bool bReturnVTransposed) { const int columns = A->columns; const int rows = A->rows; if (W->columns != columns || W->rows != rows) { printf("error: W should have %i columns and %i rows for LinearAlgebra::SVD\n", columns, rows); return; } if (U && (U->columns != rows || U->rows != rows)) { printf("error: U should have %i columns and %i rows for LinearAlgebra::SVD\n", rows, rows); return; } if (V && (V->columns != columns || V->rows != columns)) { printf("error: V should have %i columns and %i rows for LinearAlgebra::SVD\n", columns, columns); return; } int flags = 0; if (bAllowModifyA) flags |= CV_SVD_MODIFY_A; if (bReturnUTransposed) flags |= CV_SVD_U_T; if (bReturnVTransposed) flags |= CV_SVD_V_T; CvMat matrixA = cvMat(rows, columns, CV_64FC1, A->data); CvMat matrixW = cvMat(rows, columns, CV_64FC1, W->data); if (U && V) { CvMat matrixU = cvMat(rows, rows, CV_64FC1, U->data); CvMat matrixV = cvMat(columns, columns, CV_64FC1, V->data); cvSVD(&matrixA, &matrixW, &matrixU, &matrixV, flags); } else if (U) { CvMat matrixU = cvMat(rows, rows, CV_64FC1, U->data); cvSVD(&matrixA, &matrixW, &matrixU, 0, flags); } else if (V) { CvMat matrixV = cvMat(columns, columns, CV_64FC1, V->data); cvSVD(&matrixA, &matrixW, 0, &matrixV, flags); } else { cvSVD(&matrixA, &matrixW, 0, 0, flags); } }
30.532927
173
0.686784
[ "vector" ]
13bcc30b8b25f49f972a226c8dc0630d4513ce18
445
hpp
C++
archive/cmdstan/src/cmdstan/arguments/arg_diagnose.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
archive/cmdstan/src/cmdstan/arguments/arg_diagnose.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
archive/cmdstan/src/cmdstan/arguments/arg_diagnose.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#ifndef CMDSTAN_ARGUMENTS_ARG_DIAGNOSE_HPP #define CMDSTAN_ARGUMENTS_ARG_DIAGNOSE_HPP #include <cmdstan/arguments/categorical_argument.hpp> #include <cmdstan/arguments/arg_test.hpp> namespace cmdstan { class arg_diagnose: public categorical_argument { public: arg_diagnose() { _name = "diagnose"; _description = "Model diagnostics"; _subarguments.push_back(new arg_test()); } }; } #endif
21.190476
54
0.710112
[ "model" ]
13c16da2cd14a1af78f3f08dd8198ecd81ee7bd4
13,283
cc
C++
ui/ozone/platform/dri/dri_gpu_platform_support.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ui/ozone/platform/dri/dri_gpu_platform_support.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ui/ozone/platform/dri/dri_gpu_platform_support.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/ozone/platform/dri/dri_gpu_platform_support.h" #include "base/bind.h" #include "base/thread_task_runner_handle.h" #include "ipc/ipc_message_macros.h" #include "ui/display/types/display_mode.h" #include "ui/display/types/display_snapshot.h" #include "ui/ozone/common/display_util.h" #include "ui/ozone/common/gpu/ozone_gpu_message_params.h" #include "ui/ozone/common/gpu/ozone_gpu_messages.h" #include "ui/ozone/platform/dri/dri_window_delegate_impl.h" #include "ui/ozone/platform/dri/dri_window_delegate_manager.h" #include "ui/ozone/platform/dri/native_display_delegate_dri.h" namespace ui { namespace { void MessageProcessedOnMain( scoped_refptr<base::SingleThreadTaskRunner> io_thread_task_runner, const base::Closure& io_thread_task) { io_thread_task_runner->PostTask(FROM_HERE, io_thread_task); } class DriGpuPlatformSupportMessageFilter : public IPC::MessageFilter { public: DriGpuPlatformSupportMessageFilter(DriWindowDelegateManager* window_manager, IPC::Listener* main_thread_listener) : window_manager_(window_manager), main_thread_listener_(main_thread_listener), main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()), pending_main_thread_operations_(0), cursor_animating_(false), start_on_main_(true) {} void OnFilterAdded(IPC::Sender* sender) override { io_thread_task_runner_ = base::ThreadTaskRunnerHandle::Get(); } // This code is meant to be very temporary and only as a special case to fix // cursor movement jank resulting from slowdowns on the gpu main thread. // It handles cursor movement on IO thread when display config is stable // and returns it to main thread during transitions. bool OnMessageReceived(const IPC::Message& message) override { // If this message affects the state needed to set cursor, handle it on // the main thread. If a cursor move message arrives but we haven't // processed the previous main thread message, keep processing on main // until nothing is pending. bool cursor_position_message = MessageAffectsCursorPosition(message.type()); bool cursor_state_message = MessageAffectsCursorState(message.type()); // Only handle cursor related messages here. if (!cursor_position_message && !cursor_state_message) return false; bool cursor_was_animating = cursor_animating_; UpdateAnimationState(message); if (cursor_state_message || pending_main_thread_operations_ || cursor_animating_ || cursor_was_animating || start_on_main_) { start_on_main_ = false; pending_main_thread_operations_++; base::Closure main_thread_message_handler = base::Bind(base::IgnoreResult(&IPC::Listener::OnMessageReceived), base::Unretained(main_thread_listener_), message); main_thread_task_runner_->PostTask(FROM_HERE, main_thread_message_handler); // This is an echo from the main thread to decrement pending ops. // When the main thread is done with the task, it posts back to IO to // signal completion. base::Closure io_thread_task = base::Bind( &DriGpuPlatformSupportMessageFilter::DecrementPendingOperationsOnIO, this); base::Closure message_processed_callback = base::Bind( &MessageProcessedOnMain, io_thread_task_runner_, io_thread_task); main_thread_task_runner_->PostTask(FROM_HERE, message_processed_callback); return true; } // Otherwise, we are in a steady state and it's safe to move cursor on IO. bool handled = true; IPC_BEGIN_MESSAGE_MAP(DriGpuPlatformSupportMessageFilter, message) IPC_MESSAGE_HANDLER(OzoneGpuMsg_CursorMove, OnCursorMove) IPC_MESSAGE_HANDLER(OzoneGpuMsg_CursorSet, OnCursorSet) IPC_MESSAGE_UNHANDLED(handled = false); IPC_END_MESSAGE_MAP() return handled; } protected: ~DriGpuPlatformSupportMessageFilter() override {} void OnCursorMove(gfx::AcceleratedWidget widget, const gfx::Point& location) { window_manager_->GetWindowDelegate(widget)->MoveCursor(location); } void OnCursorSet(gfx::AcceleratedWidget widget, const std::vector<SkBitmap>& bitmaps, const gfx::Point& location, int frame_delay_ms) { window_manager_->GetWindowDelegate(widget) ->SetCursorWithoutAnimations(bitmaps, location); } void DecrementPendingOperationsOnIO() { pending_main_thread_operations_--; } bool MessageAffectsCursorState(uint32 message_type) { switch (message_type) { case OzoneGpuMsg_CreateWindowDelegate::ID: case OzoneGpuMsg_DestroyWindowDelegate::ID: case OzoneGpuMsg_WindowBoundsChanged::ID: case OzoneGpuMsg_ConfigureNativeDisplay::ID: case OzoneGpuMsg_DisableNativeDisplay::ID: return true; default: return false; } } bool MessageAffectsCursorPosition(uint32 message_type) { switch (message_type) { case OzoneGpuMsg_CursorMove::ID: case OzoneGpuMsg_CursorSet::ID: return true; default: return false; } } void UpdateAnimationState(const IPC::Message& message) { if (message.type() != OzoneGpuMsg_CursorSet::ID) return; OzoneGpuMsg_CursorSet::Param param; if (!OzoneGpuMsg_CursorSet::Read(&message, &param)) return; int frame_delay_ms = get<3>(param); cursor_animating_ = frame_delay_ms != 0; } DriWindowDelegateManager* window_manager_; IPC::Listener* main_thread_listener_; scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> io_thread_task_runner_; int32 pending_main_thread_operations_; bool cursor_animating_; // The filter is not installed early enough, so some messages may // get routed to main thread. Once we get our first message on io, send it // to main to ensure all prior main thread operations are finished before we // continue on io. // TODO: remove this once filter is properly installed. bool start_on_main_; }; } DriGpuPlatformSupport::DriGpuPlatformSupport( DriWrapper* drm, DriWindowDelegateManager* window_manager, ScreenManager* screen_manager, scoped_ptr<NativeDisplayDelegateDri> ndd) : sender_(NULL), drm_(drm), window_manager_(window_manager), screen_manager_(screen_manager), ndd_(ndd.Pass()) { filter_ = new DriGpuPlatformSupportMessageFilter(window_manager, this); } DriGpuPlatformSupport::~DriGpuPlatformSupport() { } void DriGpuPlatformSupport::AddHandler(scoped_ptr<GpuPlatformSupport> handler) { handlers_.push_back(handler.release()); } void DriGpuPlatformSupport::OnChannelEstablished(IPC::Sender* sender) { sender_ = sender; for (size_t i = 0; i < handlers_.size(); ++i) handlers_[i]->OnChannelEstablished(sender); } bool DriGpuPlatformSupport::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(DriGpuPlatformSupport, message) IPC_MESSAGE_HANDLER(OzoneGpuMsg_CreateWindowDelegate, OnCreateWindowDelegate) IPC_MESSAGE_HANDLER(OzoneGpuMsg_DestroyWindowDelegate, OnDestroyWindowDelegate) IPC_MESSAGE_HANDLER(OzoneGpuMsg_WindowBoundsChanged, OnWindowBoundsChanged) IPC_MESSAGE_HANDLER(OzoneGpuMsg_CursorSet, OnCursorSet) IPC_MESSAGE_HANDLER(OzoneGpuMsg_CursorMove, OnCursorMove) IPC_MESSAGE_HANDLER(OzoneGpuMsg_ForceDPMSOn, OnForceDPMSOn) IPC_MESSAGE_HANDLER(OzoneGpuMsg_RefreshNativeDisplays, OnRefreshNativeDisplays) IPC_MESSAGE_HANDLER(OzoneGpuMsg_ConfigureNativeDisplay, OnConfigureNativeDisplay) IPC_MESSAGE_HANDLER(OzoneGpuMsg_DisableNativeDisplay, OnDisableNativeDisplay) IPC_MESSAGE_HANDLER(OzoneGpuMsg_TakeDisplayControl, OnTakeDisplayControl) IPC_MESSAGE_HANDLER(OzoneGpuMsg_RelinquishDisplayControl, OnRelinquishDisplayControl) IPC_MESSAGE_HANDLER(OzoneGpuMsg_AddGraphicsDevice, OnAddGraphicsDevice) IPC_MESSAGE_HANDLER(OzoneGpuMsg_RemoveGraphicsDevice, OnRemoveGraphicsDevice) IPC_MESSAGE_UNHANDLED(handled = false); IPC_END_MESSAGE_MAP() if (!handled) for (size_t i = 0; i < handlers_.size(); ++i) if (handlers_[i]->OnMessageReceived(message)) return true; return false; } void DriGpuPlatformSupport::OnCreateWindowDelegate( gfx::AcceleratedWidget widget) { // Due to how the GPU process starts up this IPC call may happen after the IPC // to create a surface. Since a surface wants to know the window associated // with it, we create it ahead of time. So when this call happens we do not // create a delegate if it already exists. if (!window_manager_->HasWindowDelegate(widget)) { scoped_ptr<DriWindowDelegate> delegate(new DriWindowDelegateImpl( widget, drm_, window_manager_, screen_manager_)); delegate->Initialize(); window_manager_->AddWindowDelegate(widget, delegate.Pass()); } } void DriGpuPlatformSupport::OnDestroyWindowDelegate( gfx::AcceleratedWidget widget) { scoped_ptr<DriWindowDelegate> delegate = window_manager_->RemoveWindowDelegate(widget); delegate->Shutdown(); } void DriGpuPlatformSupport::OnWindowBoundsChanged(gfx::AcceleratedWidget widget, const gfx::Rect& bounds) { window_manager_->GetWindowDelegate(widget)->OnBoundsChanged(bounds); } void DriGpuPlatformSupport::OnCursorSet(gfx::AcceleratedWidget widget, const std::vector<SkBitmap>& bitmaps, const gfx::Point& location, int frame_delay_ms) { window_manager_->GetWindowDelegate(widget) ->SetCursor(bitmaps, location, frame_delay_ms); } void DriGpuPlatformSupport::OnCursorMove(gfx::AcceleratedWidget widget, const gfx::Point& location) { window_manager_->GetWindowDelegate(widget)->MoveCursor(location); } void DriGpuPlatformSupport::OnForceDPMSOn() { ndd_->ForceDPMSOn(); } void DriGpuPlatformSupport::OnRefreshNativeDisplays() { std::vector<DisplaySnapshot_Params> displays; std::vector<DisplaySnapshot*> native_displays = ndd_->GetDisplays(); for (size_t i = 0; i < native_displays.size(); ++i) displays.push_back(GetDisplaySnapshotParams(*native_displays[i])); sender_->Send(new OzoneHostMsg_UpdateNativeDisplays(displays)); } void DriGpuPlatformSupport::OnConfigureNativeDisplay( int64_t id, const DisplayMode_Params& mode_param, const gfx::Point& origin) { DisplaySnapshot* display = ndd_->FindDisplaySnapshot(id); if (!display) { LOG(ERROR) << "There is no display with ID " << id; sender_->Send(new OzoneHostMsg_DisplayConfigured(id, false)); return; } const DisplayMode* mode = NULL; for (size_t i = 0; i < display->modes().size(); ++i) { if (mode_param.size == display->modes()[i]->size() && mode_param.is_interlaced == display->modes()[i]->is_interlaced() && mode_param.refresh_rate == display->modes()[i]->refresh_rate()) { mode = display->modes()[i]; break; } } // If the display doesn't have the mode natively, then lookup the mode from // other displays and try using it on the current display (some displays // support panel fitting and they can use different modes even if the mode // isn't explicitly declared). if (!mode) mode = ndd_->FindDisplayMode(mode_param.size, mode_param.is_interlaced, mode_param.refresh_rate); if (!mode) { LOG(ERROR) << "Failed to find mode: size=" << mode_param.size.ToString() << " is_interlaced=" << mode_param.is_interlaced << " refresh_rate=" << mode_param.refresh_rate; sender_->Send(new OzoneHostMsg_DisplayConfigured(id, false)); return; } bool success = ndd_->Configure(*display, mode, origin); if (success) { display->set_origin(origin); display->set_current_mode(mode); } sender_->Send(new OzoneHostMsg_DisplayConfigured(id, success)); } void DriGpuPlatformSupport::OnDisableNativeDisplay(int64_t id) { DisplaySnapshot* display = ndd_->FindDisplaySnapshot(id); bool success = false; if (display) success = ndd_->Configure(*display, NULL, gfx::Point()); else LOG(ERROR) << "There is no display with ID " << id; sender_->Send(new OzoneHostMsg_DisplayConfigured(id, success)); } void DriGpuPlatformSupport::OnTakeDisplayControl() { ndd_->TakeDisplayControl(); } void DriGpuPlatformSupport::OnRelinquishDisplayControl() { ndd_->RelinquishDisplayControl(); } void DriGpuPlatformSupport::OnAddGraphicsDevice(const base::FilePath& path) { NOTIMPLEMENTED(); } void DriGpuPlatformSupport::OnRemoveGraphicsDevice(const base::FilePath& path) { NOTIMPLEMENTED(); } void DriGpuPlatformSupport::RelinquishGpuResources( const base::Closure& callback) { callback.Run(); } IPC::MessageFilter* DriGpuPlatformSupport::GetMessageFilter() { return filter_.get(); } } // namespace ui
36.69337
80
0.726417
[ "vector" ]
13c49e94294f56fdc701797326f454860211b760
12,922
cpp
C++
moto.cpp
Immac/tron-light-cycle-old
4e6830b89c40047acc4654340637f321520ab25e
[ "MIT" ]
null
null
null
moto.cpp
Immac/tron-light-cycle-old
4e6830b89c40047acc4654340637f321520ab25e
[ "MIT" ]
null
null
null
moto.cpp
Immac/tron-light-cycle-old
4e6830b89c40047acc4654340637f321520ab25e
[ "MIT" ]
null
null
null
#include "moto.h" enum { F_UP,F_DOWN,F_LEFT,F_RIGHT }; Moto::Moto(sf::Vector2<float> intialPosition){ this->setPosition(intialPosition); this->skipAFrame = true; this->velocity = 4; this->size = sf::Vector2f(10,25); this-> name = "Moto"; this->facing = F_UP; this->setPlayer(1); this->sensitivity = 25; this->setTag("player"); this->playerColor = sf::Color::Blue; this->isInvulnerable = false; this->hasInvisWalls = false; this->isFaster = false; this->hasInvisibilityPower = false; this->hasInvisibilityPower = false; this->hasSpeedPower = false; center = sf::Vector2f(this->getSize().x/2,this->getSize().y/2); timer[SPEED] = 0; timer[INVIS] = 0; timer[INVUL] = 0; timer[FRAMES] = 0; srand(time(0)); srand(rand()); // createWall(); //ctor } Moto::~Moto() { //dtor } void Moto::update() { bool isHorizontal = (facing != F_DOWN && facing != F_UP); bool isVertical = (facing != F_LEFT && facing != F_RIGHT); float JoyX = sf::Joystick::getAxisPosition(playerNumber, sf::Joystick::X); float JoyY = sf::Joystick::getAxisPosition(playerNumber, sf::Joystick::Y); /* if (sf::Joystick::isButtonPressed(PlayerNumber, 1)) facing = F_UP; if (sf::Joystick::isButtonPressed(PlayerNumber, 2)) facing = F_RIGHT;*/ if(!skipAFrame) { if ( abs(JoyX)>25 && abs(JoyY) > 25) isHorizontal = isVertical = false; if(JoyY < -25 && isHorizontal) { facing = F_UP;createWall(); } if(JoyY > 25 && isHorizontal) { facing = F_DOWN;createWall(); } if(JoyX > 25 && isVertical) { facing = F_RIGHT;createWall(); } if(JoyX < -25 && isVertical) { facing = F_LEFT;createWall(); } if (!sf::Joystick::isConnected(playerNumber)) { keyboardInputs(isHorizontal,isVertical); } } skipAFrame = false; if(currentWall !=0) { if(facing != F_DOWN) currentWall->setSize(this->getPosition()); else currentWall->setSize(sf::Vector2<float>(getPosition().x,getPosition().y)); } float speed = velocity; if(isFaster) speed += 4; if (this->facing == F_UP){ this->position.y -= speed; } if (this->facing == F_DOWN){ this->position.y += speed; } if (this->facing == F_RIGHT){ this->position.x += speed; } if (this->facing == F_LEFT){ this->position.x -= speed; } timer[FRAMES]++; if(timer[FRAMES]%120 == 0) { if(rand()%2 == 0) SceneManager::getInstance()->createPowerup(); } reset(); if(position.x > 1280 || position.x < 0 || position.y > 720 || position.y < 0) tag = "dead"; } void Moto::createWall() { currentWall = new Wall(this->getPosition()); if(facing != F_DOWN) currentWall->wallEnd = this->getPosition(); else currentWall->wallEnd = sf::Vector2<float>(this->getPosition().x,this->getPosition().y - this->getSize().y/2); if(hasInvisWalls) currentWall->wallColor = sf::Color::Transparent; else currentWall->wallColor = playerColor; currentWall->setHorizontal((facing == F_LEFT || facing == F_RIGHT)); SceneManager::getInstance()->addGameObject(currentWall); } void Moto::render(sf::RenderWindow * win){ sf::RectangleShape shape; shape.setOrigin(this->getSize().x/2,this->getSize().y/2); shape.setSize(size); shape.setOutlineThickness(2); shape.setOutlineColor(sf::Color::White); shape.setFillColor(playerColor); shape.setPosition(position); sf::RectangleShape hitBox; if (this->facing == F_UP) { shape.setRotation(180); hitBox.setPosition(sf::Vector2f(position.x - getSize().x/2 ,position.y - getSize().y/2)); hitBox.setSize(sf::Vector2f(10,2)); } if (this->facing == F_DOWN) { shape.setRotation(0); hitBox.setPosition(sf::Vector2f(position.x - getSize().x/2 ,position.y + getSize().y/2)); hitBox.setSize(sf::Vector2f(10,2)); } if (this->facing == F_RIGHT){ shape.setRotation(90); hitBox.setPosition(sf::Vector2f(position.x + getSize().x ,position.y - getSize().x/2)); hitBox.setSize(sf::Vector2f(2,10)); } if (this->facing == F_LEFT){ shape.setRotation(270); hitBox.setPosition(sf::Vector2f(position.x - getSize().x ,position.y - getSize().x/2)); hitBox.setSize(sf::Vector2f(2,10)); } win->draw(shape); // win->draw(hitBox); } void Moto::setPlayer(int index) { if (index >= 0 && index < 8) this->playerNumber = index; } sf::Rect<float> Moto::getHitBox() { sf::Rect<float> hitBox; if (this->facing == F_UP) { hitBox.left = position.x - getSize().x/2; hitBox.top = position.y - getSize().y/2; hitBox.width = 10; hitBox.height = 2; } if (this->facing == F_DOWN) { hitBox.left = position.x - getSize().x/2; hitBox.top = position.y + getSize().y/2; hitBox.width = 10; hitBox.height = 2; } if (this->facing == F_RIGHT) { hitBox.left = position.x + getSize().x ; hitBox.top = position.y - getSize().x/2; hitBox.width = 2; hitBox.height = 10; } if (this->facing == F_LEFT){ hitBox.left = position.x - getSize().x ; hitBox.top = position.y - getSize().x/2; hitBox.width = 2; hitBox.height = 10; } if (this->isInvulnerable) { hitBox.left = playerNumber*280 ; hitBox.top = 800; hitBox.width = 1; hitBox.height = 1; } return hitBox; } void Moto::keyboardInputs(bool isHorizontal,bool isVertical) { switch (playerNumber) { case 0: if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && !sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && !sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && isHorizontal) { facing = F_UP;createWall(); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && !sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && !sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && isHorizontal) { facing = F_DOWN;createWall(); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && !sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && !sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && isVertical) { facing = F_RIGHT;createWall(); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && !sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && !sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && isVertical) { facing = F_LEFT;createWall(); } break; case 1: if(sf::Keyboard::isKeyPressed(sf::Keyboard::W) && !sf::Keyboard::isKeyPressed(sf::Keyboard::D) && !sf::Keyboard::isKeyPressed(sf::Keyboard::A) && isHorizontal) { facing = F_UP;createWall(); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::S) && !sf::Keyboard::isKeyPressed(sf::Keyboard::D) && !sf::Keyboard::isKeyPressed(sf::Keyboard::A) && isHorizontal) { facing = F_DOWN;createWall(); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::D) && !sf::Keyboard::isKeyPressed(sf::Keyboard::W) && !sf::Keyboard::isKeyPressed(sf::Keyboard::S) && isVertical) { facing = F_RIGHT;createWall(); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::A) && !sf::Keyboard::isKeyPressed(sf::Keyboard::W) && !sf::Keyboard::isKeyPressed(sf::Keyboard::S) && isVertical) { facing = F_LEFT;createWall(); } break; case 2: if(sf::Keyboard::isKeyPressed(sf::Keyboard::I) && !sf::Keyboard::isKeyPressed(sf::Keyboard::L) && !sf::Keyboard::isKeyPressed(sf::Keyboard::J) && isHorizontal) { facing = F_UP;createWall(); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::K) && !sf::Keyboard::isKeyPressed(sf::Keyboard::L) && !sf::Keyboard::isKeyPressed(sf::Keyboard::J) && isHorizontal) { facing = F_DOWN;createWall(); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::L) && !sf::Keyboard::isKeyPressed(sf::Keyboard::I) && !sf::Keyboard::isKeyPressed(sf::Keyboard::K) && isVertical) { facing = F_RIGHT;createWall(); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::J) && !sf::Keyboard::isKeyPressed(sf::Keyboard::I) && !sf::Keyboard::isKeyPressed(sf::Keyboard::K) && isVertical) { facing = F_LEFT;createWall(); } break; case 3: if(sf::Keyboard::isKeyPressed(sf::Keyboard::T) && !sf::Keyboard::isKeyPressed(sf::Keyboard::H) && !sf::Keyboard::isKeyPressed(sf::Keyboard::F) && isHorizontal) { facing = F_UP;createWall(); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::G) && !sf::Keyboard::isKeyPressed(sf::Keyboard::H) && !sf::Keyboard::isKeyPressed(sf::Keyboard::F) && isHorizontal) { facing = F_DOWN;createWall(); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::H) && !sf::Keyboard::isKeyPressed(sf::Keyboard::T) && !sf::Keyboard::isKeyPressed(sf::Keyboard::G) && isVertical) { facing = F_RIGHT;createWall(); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::F) && !sf::Keyboard::isKeyPressed(sf::Keyboard::T) && !sf::Keyboard::isKeyPressed(sf::Keyboard::G) && isVertical) { facing = F_LEFT;createWall(); } break; } } void Moto::setFacing(int faceIndex) { this->facing = faceIndex; } float Moto::getVelocity() { return velocity; } void Moto::setVelocity(float value) { velocity = value; } void Moto::speedUp() { if (timer[SPEED] == 0) { isFaster = true; hasSpeedPower = false; timer[SPEED] = 60; } } void Moto::invulnerability() { if (timer[INVUL] == 0) { isInvulnerable = true; hasInvulnerabilityPower = false; timer[INVUL] = 60; } } void Moto::invisWalls() { if(timer[INVIS] == 0) { hasInvisWalls = true; hasInvisibilityPower = false; timer[INVIS] = 60; } } void Moto::reset() { if(timer[SPEED] > 0) { timer[SPEED]--; } if(timer[INVUL] > 0) timer[INVUL]--; if(timer[INVIS] > 0) timer[INVIS]--; if(timer[SPEED] == 0) { isFaster = false; } if(timer[INVUL] == 0) { isInvulnerable = false; } if(timer[INVIS] == 0) { hasInvisWalls = false; } } void Moto::activatePower(int index) { if(index == INVIS) invisWalls(); if(index == INVUL) invulnerability(); if(index == SPEED) speedUp(); }
28.4
117
0.480731
[ "render", "shape" ]
13c8931e6f183284455c8d642c238b702ecf63d5
2,823
cpp
C++
src/execution/operator/helper/physical_streaming_limit.cpp
lokax/duckdb
c2581dfebccaebae9468c924c2c722fcf0306944
[ "MIT" ]
null
null
null
src/execution/operator/helper/physical_streaming_limit.cpp
lokax/duckdb
c2581dfebccaebae9468c924c2c722fcf0306944
[ "MIT" ]
1
2022-03-30T09:00:02.000Z
2022-03-30T09:00:02.000Z
src/execution/operator/helper/physical_streaming_limit.cpp
lokax/duckdb
c2581dfebccaebae9468c924c2c722fcf0306944
[ "MIT" ]
null
null
null
#include "duckdb/execution/operator/helper/physical_streaming_limit.hpp" #include "duckdb/execution/operator/helper/physical_limit.hpp" namespace duckdb { PhysicalStreamingLimit::PhysicalStreamingLimit(vector<LogicalType> types, idx_t limit, idx_t offset, unique_ptr<Expression> limit_expression, unique_ptr<Expression> offset_expression, idx_t estimated_cardinality, bool parallel) : PhysicalOperator(PhysicalOperatorType::STREAMING_LIMIT, move(types), estimated_cardinality), limit_value(limit), offset_value(offset), limit_expression(move(limit_expression)), offset_expression(move(offset_expression)), parallel(parallel) { } //===--------------------------------------------------------------------===// // Operator //===--------------------------------------------------------------------===// class StreamingLimitOperatorState : public OperatorState { public: explicit StreamingLimitOperatorState(const PhysicalStreamingLimit &op) { this->limit = op.limit_expression ? DConstants::INVALID_INDEX : op.limit_value; this->offset = op.offset_expression ? DConstants::INVALID_INDEX : op.offset_value; } idx_t limit; idx_t offset; }; class StreamingLimitGlobalState : public GlobalOperatorState { public: StreamingLimitGlobalState() : current_offset(0) { } std::atomic<idx_t> current_offset; }; unique_ptr<OperatorState> PhysicalStreamingLimit::GetOperatorState(ClientContext &context) const { return make_unique<StreamingLimitOperatorState>(*this); } unique_ptr<GlobalOperatorState> PhysicalStreamingLimit::GetGlobalOperatorState(ClientContext &context) const { return make_unique<StreamingLimitGlobalState>(); } OperatorResultType PhysicalStreamingLimit::Execute(ExecutionContext &context, DataChunk &input, DataChunk &chunk, GlobalOperatorState &gstate_p, OperatorState &state_p) const { auto &gstate = (StreamingLimitGlobalState &)gstate_p; auto &state = (StreamingLimitOperatorState &)state_p; auto &limit = state.limit; auto &offset = state.offset; idx_t current_offset = gstate.current_offset.fetch_add(input.size()); idx_t max_element; if (!PhysicalLimit::ComputeOffset(input, limit, offset, current_offset, max_element, limit_expression.get(), offset_expression.get())) { return OperatorResultType::FINISHED; } if (PhysicalLimit::HandleOffset(input, current_offset, offset, limit)) { chunk.Reference(input); } return OperatorResultType::NEED_MORE_INPUT; } bool PhysicalStreamingLimit::IsOrderDependent() const { return !parallel; } bool PhysicalStreamingLimit::ParallelOperator() const { return parallel; } } // namespace duckdb
39.208333
118
0.693234
[ "vector" ]
13ca041f5cd37484e04cb9729db1d80b7dd9c52b
9,530
cc
C++
cc/trees/layer_tree_host_pixeltest_tiles.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
cc/trees/layer_tree_host_pixeltest_tiles.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
cc/trees/layer_tree_host_pixeltest_tiles.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2015 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 <stddef.h> #include "build/build_config.h" #include "cc/layers/content_layer_client.h" #include "cc/layers/picture_layer.h" #include "cc/paint/display_item_list.h" #include "cc/paint/paint_flags.h" #include "cc/paint/paint_op_buffer.h" #include "cc/test/layer_tree_pixel_test.h" #include "cc/test/test_layer_tree_frame_sink.h" #include "components/viz/common/frame_sinks/copy_output_request.h" #include "gpu/command_buffer/client/raster_interface.h" #if !defined(OS_ANDROID) namespace cc { namespace { enum RasterMode { BITMAP, ONE_COPY, GPU, GPU_LOW_BIT_DEPTH, }; struct TilesTestConfig { LayerTreeTest::RendererType renderer_type; RasterMode raster_mode; }; class LayerTreeHostTilesPixelTest : public LayerTreePixelTest, public ::testing::WithParamInterface<TilesTestConfig> { protected: LayerTreeHostTilesPixelTest() : LayerTreePixelTest(renderer_type()) { switch (raster_mode()) { case GPU: case GPU_LOW_BIT_DEPTH: set_gpu_rasterization(); break; default: break; } } RendererType renderer_type() const { return GetParam().renderer_type; } RasterMode raster_mode() const { return GetParam().raster_mode; } void InitializeSettings(LayerTreeSettings* settings) override { LayerTreePixelTest::InitializeSettings(settings); switch (raster_mode()) { case ONE_COPY: settings->use_zero_copy = false; break; case GPU_LOW_BIT_DEPTH: settings->use_rgba_4444 = true; settings->unpremultiply_and_dither_low_bit_depth_tiles = true; break; default: break; } settings->use_partial_raster = use_partial_raster_; } void BeginTest() override { // Don't set up a readback target at the start of the test. PostSetNeedsCommitToMainThread(); } void DoReadback() { Layer* target = readback_target_ ? readback_target_ : layer_tree_host()->root_layer(); target->RequestCopyOfOutput(CreateCopyOutputRequest()); } base::FilePath ref_file_; std::unique_ptr<SkBitmap> result_bitmap_; bool use_partial_raster_ = false; }; class BlueYellowClient : public ContentLayerClient { public: explicit BlueYellowClient(const gfx::Size& size) : size_(size), blue_top_(true) {} gfx::Rect PaintableRegion() override { return gfx::Rect(size_); } scoped_refptr<DisplayItemList> PaintContentsToDisplayList( PaintingControlSetting painting_status) override { auto display_list = base::MakeRefCounted<DisplayItemList>(); display_list->StartPaint(); gfx::Rect top(0, 0, size_.width(), size_.height() / 2); gfx::Rect bottom(0, size_.height() / 2, size_.width(), size_.height() / 2); gfx::Rect blue_rect = blue_top_ ? top : bottom; gfx::Rect yellow_rect = blue_top_ ? bottom : top; PaintFlags flags; flags.setStyle(PaintFlags::kFill_Style); // Use custom colors with 0xF2 rather than the default blue/yellow (which // use 0xFF), as the default won't show dither patterns as it exactly maps // to a 16-bit color. flags.setColor(SkColorSetRGB(0x00, 0x00, 0xF2)); display_list->push<DrawRectOp>(gfx::RectToSkRect(blue_rect), flags); flags.setColor(SkColorSetRGB(0xF2, 0xF2, 0x00)); display_list->push<DrawRectOp>(gfx::RectToSkRect(yellow_rect), flags); display_list->EndPaintOfUnpaired(PaintableRegion()); display_list->Finalize(); return display_list; } bool FillsBoundsCompletely() const override { return true; } size_t GetApproximateUnsharedMemoryUsage() const override { return 0; } void set_blue_top(bool b) { blue_top_ = b; } private: gfx::Size size_; bool blue_top_; }; class LayerTreeHostTilesTestPartialInvalidation : public LayerTreeHostTilesPixelTest { public: LayerTreeHostTilesTestPartialInvalidation() : client_(gfx::Size(200, 200)), picture_layer_(PictureLayer::Create(&client_)) { picture_layer_->SetBounds(gfx::Size(200, 200)); picture_layer_->SetIsDrawable(true); } void DidCommitAndDrawFrame() override { switch (layer_tree_host()->SourceFrameNumber()) { case 1: // We have done one frame, but the resource may not be available for // partial raster yet. Force a second frame. picture_layer_->SetNeedsDisplayRect(gfx::Rect(50, 50, 100, 100)); break; case 2: // We have done two frames, so the layer's content has been rastered // twice and the first frame's resource is available for partial // raster. Now we change the picture behind it to record something // completely different, but we give a smaller invalidation rect. The // layer should only re-raster the stuff in the rect. If it doesn't do // partial raster it would re-raster the whole thing instead. client_.set_blue_top(false); Finish(); picture_layer_->SetNeedsDisplayRect(gfx::Rect(50, 50, 100, 100)); // Add a copy request to see what happened! DoReadback(); break; } } void WillPrepareTilesOnThread(LayerTreeHostImpl* host_impl) override { // Issue a GL finish before preparing tiles to ensure resources become // available for use in a timely manner. Needed for the one-copy path. viz::RasterContextProvider* context_provider = host_impl->layer_tree_frame_sink()->worker_context_provider(); if (!context_provider) return; viz::RasterContextProvider::ScopedRasterContextLock lock(context_provider); lock.RasterInterface()->Finish(); } protected: BlueYellowClient client_; scoped_refptr<PictureLayer> picture_layer_; }; std::vector<TilesTestConfig> const kTestCases = { {LayerTreeTest::RENDERER_SOFTWARE, BITMAP}, #if !defined(GL_NOT_ON_PLATFORM) {LayerTreeTest::RENDERER_GL, ONE_COPY}, {LayerTreeTest::RENDERER_GL, GPU}, {LayerTreeTest::RENDERER_SKIA_GL, ONE_COPY}, {LayerTreeTest::RENDERER_SKIA_GL, GPU}, #endif // !defined(GL_NOT_ON_PLATFORM) #if defined(ENABLE_CC_VULKAN_TESTS) {LayerTreeTest::RENDERER_SKIA_VK, ONE_COPY}, {LayerTreeTest::RENDERER_SKIA_VK, GPU}, #endif // defined(ENABLE_CC_VULKAN_TESTS) }; INSTANTIATE_TEST_SUITE_P(All, LayerTreeHostTilesTestPartialInvalidation, ::testing::ValuesIn(kTestCases)); TEST_P(LayerTreeHostTilesTestPartialInvalidation, PartialRaster) { use_partial_raster_ = true; RunSingleThreadedPixelTest( picture_layer_, base::FilePath(FILE_PATH_LITERAL("blue_yellow_partial_flipped.png"))); } TEST_P(LayerTreeHostTilesTestPartialInvalidation, FullRaster) { RunSingleThreadedPixelTest( picture_layer_, base::FilePath(FILE_PATH_LITERAL("blue_yellow_flipped.png"))); } std::vector<TilesTestConfig> const kTestCasesMultiThread = { #if !defined(GL_NOT_ON_PLATFORM) {LayerTreeTest::RENDERER_GL, ONE_COPY}, {LayerTreeTest::RENDERER_SKIA_GL, ONE_COPY}, #endif // !defined(GL_NOT_ON_PLATFORM) #if defined(ENABLE_CC_VULKAN_TESTS) {LayerTreeTest::RENDERER_SKIA_VK, ONE_COPY}, #endif // defined(ENABLE_CC_VULKAN_TESTS) }; using LayerTreeHostTilesTestPartialInvalidationMultiThread = LayerTreeHostTilesTestPartialInvalidation; INSTANTIATE_TEST_SUITE_P(All, LayerTreeHostTilesTestPartialInvalidationMultiThread, ::testing::ValuesIn(kTestCasesMultiThread)); #if defined(OS_LINUX) && defined(THREAD_SANITIZER) // Flaky on Linux TSAN. https://crbug.com/707711 #define MAYBE_PartialRaster DISABLED_PartialRaster #elif defined(OS_WIN) && defined(ADDRESS_SANITIZER) // Flaky on Windows ASAN https://crbug.com/1045521 #define MAYBE_PartialRaster DISABLED_PartialRaster #else #define MAYBE_PartialRaster PartialRaster #endif TEST_P(LayerTreeHostTilesTestPartialInvalidationMultiThread, MAYBE_PartialRaster) { use_partial_raster_ = true; RunPixelTest( picture_layer_, base::FilePath(FILE_PATH_LITERAL("blue_yellow_partial_flipped.png"))); } TEST_P(LayerTreeHostTilesTestPartialInvalidationMultiThread, FullRaster) { RunPixelTest(picture_layer_, base::FilePath(FILE_PATH_LITERAL("blue_yellow_flipped.png"))); } using LayerTreeHostTilesTestPartialInvalidationLowBitDepth = LayerTreeHostTilesTestPartialInvalidation; // This test doesn't work on Vulkan because on our hardware we can't render to // RGBA4444 format using either SwiftShader or native Vulkan. See // crbug.com/987278 for details #if !defined(GL_NOT_ON_PLATFORM) INSTANTIATE_TEST_SUITE_P( All, LayerTreeHostTilesTestPartialInvalidationLowBitDepth, ::testing::Values( TilesTestConfig{LayerTreeTest::RENDERER_SKIA_GL, GPU_LOW_BIT_DEPTH}, TilesTestConfig{LayerTreeTest::RENDERER_GL, GPU_LOW_BIT_DEPTH})); #endif // !defined(GL_NOT_ON_PLATFORM) TEST_P(LayerTreeHostTilesTestPartialInvalidationLowBitDepth, PartialRaster) { use_partial_raster_ = true; RunSingleThreadedPixelTest(picture_layer_, base::FilePath(FILE_PATH_LITERAL( "blue_yellow_partial_flipped_dither.png"))); } TEST_P(LayerTreeHostTilesTestPartialInvalidationLowBitDepth, FullRaster) { RunSingleThreadedPixelTest( picture_layer_, base::FilePath(FILE_PATH_LITERAL("blue_yellow_flipped_dither.png"))); } } // namespace } // namespace cc #endif // !defined(OS_ANDROID)
33.556338
79
0.730115
[ "render", "vector" ]
13cbce241bc79f9ec955f7ceb1593cc5c18ecb1a
12,136
cpp
C++
lite/isugg.cpp
philomath213/nlp-engine
9c9d694b985a6a266004c32f8866098666a640ca
[ "MIT" ]
null
null
null
lite/isugg.cpp
philomath213/nlp-engine
9c9d694b985a6a266004c32f8866098666a640ca
[ "MIT" ]
null
null
null
lite/isugg.cpp
philomath213/nlp-engine
9c9d694b985a6a266004c32f8866098666a640ca
[ "MIT" ]
null
null
null
/******************************************************************************* Copyright (c) 2001-2010 by Text Analysis International, Inc. All rights reserved. ******************************************************************************** * * NAME: ISUGG.CPP * FILE: lite\isugg.cpp * CR: 10/24/98 AM. * SUBJ: Interpreted/internal suggested rule element class. * *******************************************************************************/ #include "StdAfx.h" #include "machine.h" // 10/25/06 AM. #include "u_out.h" // 01/19/06 AM. #include "lite/lite.h" // 07/07/03 AM. #include "lite/global.h" #include "dlist.h" // 07/07/03 AM. #include "inline.h" // 05/19/99 AM. #include "io.h" #include "lite/iarg.h" // 05/14/03 AM. #include "str.h" // 06/07/99 AM. #include "starr.h" // 05/06/00 AM. #include "node.h" // 07/07/03 AM. #include "tree.h" // 07/07/03 AM. #include "nlppp.h" // 07/07/03 AM. #include "gen.h" // 05/19/00 AM. #include "ielt.h" // 05/19/00 AM. #include "isugg.h" /******************************************** * FN: Special Functions for Class * CR: 10/24/98 AM. ********************************************/ Isugg::Isugg( // Default constructor. _TCHAR *nn, // Element name. Dlist<Ipair> *prs, // Pairs. long num // Line num in pass file. // 08/08/01 AM. ) : Ielement(nn, prs, 0, num) // 08/08/01 AM. { base_ = false; // 11/10/98 AM. unsealed_ = false; // 10/09/99 AM. layers_ = 0; // 05/06/00 AM. // Tracking is in the base class, Ielement. } /*******************************************/ Isugg::~Isugg() { if (layers_) // 05/06/00 AM. delete layers_; // 05/06/00 AM. // Tracking is in the base class, Ielement. } /*******************************************/ /*******************************************/ // Copy constructor. // 07/02/99 AM. /*******************************************/ Isugg::Isugg(Isugg &orig) : Ielement(orig) // Call parent class' copy constructor. { zero(); Isugg::copy(&orig); } /*******************************************/ // Assignment operator overload. // 07/02/99 AM. /*******************************************/ const Isugg &Isugg::operator=(const Isugg &fm) { Isugg *to; to = this; if (&fm == to) { _t_strstream gerrStr; gerrStr << _T("[Can't assign Isugg object to itself.]") << ends; errOut(&gerrStr,false); return *this; } // Let the parent do its assignments. to->Ielement::operator =(fm); to->clear(); // Delete stuff in the object. to->zero(); // Zero out fields of the object. to->copy(&fm); // Copy from the given object. return *this; } /*******************************************/ /*******************************************/ void Isugg::clear() { // 07/02/99 AM. // WARN: DOESN'T CLEAR FOR THE PARENT CLASS. base_ = false; unsealed_ = false; // 10/09/99 AM. delete layers_; // 05/06/00 AM. } void Isugg::zero() { layers_ = 0; // WARN: DOESN'T ZERO FOR THE PARENT CLASS. } void Isugg::copy(const Isugg *orig) { // WARN: DOESN'T COPY THE PARENT CLASS. Isugg *dest; dest = this; dest->base_ = orig->base_; dest->unsealed_ = orig->unsealed_; dest->layers_ = orig->layers_; // 05/06/00 AM. // Note: Doesn't copy strings -- only ptrs to strings. // 05/06/00 AM. } /*******************************************/ _t_ostream &STDOPERATOR<<(_t_ostream &output, Isugg &sugg) // 11/23/98 AM. { bool flag = false; // If something prior was printed. #ifndef UNICODE output << str(sugg.name_); #else char *lpstr8; // 01/28/06 AM. u_to_mbcs((LPCWSTR)str(sugg.name_), CP_UTF8, (LPCTSTR*&)lpstr8);// 01/28/06 AM. output << lpstr8; // 01/28/06 AM. u_delete((LPCTSTR*&)lpstr8); // 01/28/06 AM. #endif output << _T(" ["); if (sugg.base_) { output << _T("base"); flag = true; } if (sugg.unsealed_) // 10/09/99 AM. { if (flag) output << _T(" "); // separator. else flag = true; output << _T("unsealed"); flag = true; } if (sugg.attrs_) { if (flag) output << _T(" "); // separator. else flag = true; output << _T("attrs=(") << *(sugg.attrs_) << _T(")"); } else if (sugg.layers_) // 05/06/00 AM. { if (flag) output << _T(" "); // separator. else flag = true; output << _T("attrs=(") << *(sugg.layers_) << _T(")"); } output << _T("]"); output << _T(" ["); if (sugg.pairs_) output << *(sugg.pairs_); output << _T("]"); return output; } /*******************************************/ _t_ostream &STDOPERATOR<<(_t_ostream &output, Delt<Isugg> &delt) // 11/23/98 AM. { Isugg *sugg; sugg = delt.getData(); output << *sugg; return output; } /*******************************************/ _t_ostream &STDOPERATOR<<(_t_ostream &output, Dlist<Isugg> &list) // 11/23/98 AM. { Delt<Isugg> *delt; delt = list.getFirst(); output << *delt; while (delt = delt->Right()) { output << _T(" ") << *delt; } return output; } /*******************************************/ /*******************************************/ /*******************************************/ /******************************************** * FN: Access Functions * CR: 10/24/98 AM. ********************************************/ bool Isugg::getBase() {return base_;} bool Isugg::getUnsealed() {return unsealed_;} // 10/09/99 AM. Starr *Isugg::getLayers() {return layers_;} // 05/06/00 AM. /******************************************** * FN: Modify Functions * CR: 10/24/98 AM. ********************************************/ void Isugg::setBase(bool x) {base_ = x;} void Isugg::setUnsealed(bool x) {unsealed_ = x;} // 10/09/99 AM. void Isugg::setLayers(Starr *x) {layers_ = x;} // 05/06/00 AM. /******************************************** * FN: General Functions ********************************************/ /******************************************** * FN: INTERN * CR: 11/23/98 AM. * SUBJ: Internalize the pairs data in a suggested element. ********************************************/ void Isugg::intern( bool &info // Not used currently. ) { Isugg *sugg; info = false; sugg = this; // Interning attrs_ list into layers_ list. // 05/06/00 AM. if (sugg->layers_) { _t_strstream gerrStr; gerrStr << _T("[Intern: suggested elt already interned.]") << ends; errOut(&gerrStr,false); return; } Dlist<Ipair> *list; list = sugg->getPairs(); if (!list) { // Set defaults here. //sugg->fillDefaults(); // 10/11/99 AM. sugg->setBase(false); // 10/11/99 AM. sugg->setUnsealed(false); // 10/11/99 AM. return; } Delt<Ipair> *dpair; // For each pair. for (dpair = list->getFirst(); dpair; dpair = dpair->Right()) { // See if it's something we know about. Ipair *pair; pair = dpair->getData(); assert(pair); _TCHAR *key; key = pair->getKey(); Dlist<Iarg> *vals; vals = pair->getVals(); if (!strcmp_i(key, _T("layer")) || !strcmp_i(key, _T("layers")) || !strcmp_i(key, _T("attr")) || !strcmp_i(key, _T("attrs")) ) { // Move layer names from pair. sugg->attrs_ = vals; pair->setVals(0); // So they won't be deleted. // 01/17/99 AM. FIX. } else if (!strcmp_i(key, _T("base"))) { sugg->base_ = true; } else if (!strcmp_i(key, _T("unsealed"))) // 10/09/99 AM. { sugg->unsealed_ = true; // 10/09/99 AM. } else { _t_strstream gerrStr; gerrStr << _T("[Invalid key in rule's suggested element=") << key << _T("]") << ends; errOut(&gerrStr,false); } } // DELETE ALL THE PAIRS! // If they ain't been internalized, they are ignored. Dlist<Ipair>::DeleteDlistAndData(list); sugg->setPairs(0); // Further interning of the layer names. // 05/06/00 AM. if (sugg->attrs_) // 05/06/00 AM. { // Traverse attrs list, installing into a layers array. sugg->setLayers(Iarg::strings_to_starr(sugg->attrs_)); // 05/06/00 AM. // SHOULD REMOVE THE ATTRS LIST HERE. EVERYONE SHOULD // USE THE STRING ARRAY VERSION. // (Do this when everything else is converted. // 05/06/00 AM. //Dlist<Iarg>::DeleteDlistAndData(attrs_); //attrs_ = 0; } // See what hasn't been assigned, and assign it a default value. //sugg->fillDefaults(); // 10/11/99 AM. } /******************************************** * FN: FILLDEFAULTS * CR: 11/23/98 AM. * SUBJ: Fill some default values for a suggested element. * NOTE: 11/22/98 AM. Moved here from postrfa.cpp. ********************************************/ void Isugg::fillDefaults() { //base_ = false; //unsealed_ = false; } /******************************************** * FN: GENSUGG * CR: 05/30/99 AM. * SUBJ: Generate text for a rule's suggested element to a file. * ASS: Not using PAIRS, but rather the internalized values in sugg. ********************************************/ void Isugg::genSugg(Isugg *sugg, _t_ostream &ofile) { if (!sugg) return; Iarg::genName(sugg->getName(), ofile); //ofile << " ["; // 10/11/99 AM. bool found = false; // If any pairs were seen yet. // 10/11/99 AM. if (sugg->getBase()) { if (found) ofile << _T(" "); else ofile << _T(" ["); // 10/11/99 AM. ofile << _T("base"); found = true; } if (sugg->getUnsealed()) // 10/11/99 AM. { if (found) ofile << _T(" "); else ofile << _T(" ["); // 10/11/99 AM. ofile << _T("unsealed"); found = true; } Dlist<Iarg> *dargs; Starr *starr; if (starr = sugg->getLayers()) // Interned attrs. // 05/06/00 AM. { _TCHAR **arr = starr->getArr() - 1; // One BEFORE array. int len = starr->getLength() + 1; // One greater than length. if (found) ofile << _T(" "); else ofile << _T(" ["); ofile << _T("layer=("); while (--len) ofile << *++arr << _T(" "); ofile << _T(")"); found = true; } else if (dargs = sugg->getAttrs()) // Uninterned, for some reason. { // Layering attribute. if (found) ofile << _T(" "); else ofile << _T(" ["); // 10/11/99 AM. Delt<Iarg> *darg; Iarg *arg; ofile << _T("layer=("); for (darg = dargs->getFirst(); darg; darg = darg->Right()) { arg = darg->getData(); ofile << arg->getStr() << _T(" "); } ofile << _T(")"); found = true; } if (found) // 10/11/99 AM. ofile << _T("]"); // 10/11/99 AM. ofile << flush; // 10/11/99 AM. } /******************************************** * FN: SAME * CR: 05/30/99 AM. * SUBJ: If suggested elements are the same in form. ********************************************/ bool Isugg::same(Isugg *sugg1, Isugg *sugg2) { if (!sugg1 && !sugg2) return true; if (!sugg1 || !sugg2) return false; if (sugg1->getBase() != sugg2->getBase()) return false; if (sugg1->getUnsealed() != sugg2->getUnsealed()) // 10/09/99 AM. return false; if (!str_equal(sugg1->getName(), sugg2->getName())) return false; // Need to check both. Perhaps there should be an "interned" flag. if (!Starr::same(sugg1->getLayers(), sugg2->getLayers())) // 05/06/00 AM. return false; // 05/06/00 AM. if (!Iarg::same(sugg1->getAttrs(), sugg2->getAttrs())) return false; return true; } /******************************************** * FN: GEN * CR: 05/19/00 AM. * SUBJ: Gen compiled runtime data for suggested elt. ********************************************/ bool Isugg::gen(_TCHAR *asugg, Gen *gen, int passnum, // Pass number of current rule. // 08/09/02 AM. long ruleline // Line number of current rule. // 08/09/02 AM. ) { //_t_ofstream *fdata = gen->fdata_; _t_ofstream *fdata = gen->passh_; // 04/04/09 AM. _TCHAR a_attrs[MAXSTR]; if (layers_) { _stprintf(a_attrs, _T("attr%d_%d_%d"), gen->id_,gen->recid_, gen->ruleid_); Ielt::genEltstarr(layers_, a_attrs, gen); } else _stprintf(a_attrs, _T("0")); // Now gen a sugg structure. *fdata << _T("const SUGG ") << asugg << _T("={") << _T("_T(\"") << name_ << _T("\"),") << a_attrs << _T(",") << (base_ ? _T("true") : _T("false")) << _T(",") << (unsealed_ ? _T("true") : _T("false")) << ',' << passnum << _T(",") // 08/09/02 AM. << ruleline // 08/09/02 AM. << _T("};"); // 04/04/03 AM. Gen::eol(fdata); // 04/04/03 AM. return true; } /************************* END OF FILE ******************************/
24.127237
82
0.504944
[ "object" ]
13cc19369c87124b02c5a971d5734d2fc5e1d7ec
1,357
cpp
C++
codeforces/cf628 div2/C.cpp
songhn233/ACM_Steps
6f2edeca9bf4fc999a8148bc90b2d8d0e59d48fe
[ "CC0-1.0" ]
1
2020-08-10T21:40:21.000Z
2020-08-10T21:40:21.000Z
codeforces/cf628 div2/C.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
null
null
null
codeforces/cf628 div2/C.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
null
null
null
#include<cstdio> #include<algorithm> #include<cstring> #include<iostream> #include<vector> #include<queue> #include<cmath> #include<map> #include<set> #define ll long long #define F(i,a,b) for(int i=(a);i<=(b);i++) #define mst(a,b) memset((a),(b),sizeof(a)) #define PII pair<int,int> #define rep(i,x,y) for(auto i=(x);i<=(y);++i) #define dep(i,x,y) for(auto i=(x);i>=(y);--i) using namespace std; template<class T>inline void rd(T &x) { x=0; int ch=getchar(),f=0; while(ch<'0'||ch>'9'){if (ch=='-') f=1;ch=getchar();} while (ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();} if(f)x=-x; } const int inf=0x3f3f3f3f; const int maxn=100050; int n,in[maxn]; vector<int> e[maxn]; map<PII,int> mp; PII ans[maxn]; int main() { cin>>n; rep(i,1,n-1) { int x,y;rd(x),rd(y); e[x].push_back(y); e[y].push_back(x); in[x]++,in[y]++; ans[i]=make_pair(x,y); } int t=-1; for(int i=1;i<=n;i++) { if(in[i]>=3) { t=i; break; } } if(t==-1) rep(i,1,n-1) cout<<i-1<<endl; else { rep(i,0,e[t].size()-1) mp[make_pair(t,e[t][i])]=mp[make_pair(e[t][i],t)]=1; int idx=e[t].size(),temp=0; rep(i,1,n-1) { int u=ans[i].first,v=ans[i].second; if(mp[make_pair(u,v)]) { cout<<temp<<endl; temp++; } else cout<<idx<<endl,idx++; } } return 0; }
20.560606
79
0.534267
[ "vector" ]
13d3ba16980cf601094dc966c7c8a753b2105a74
80,594
cpp
C++
Optimize.cpp
kassol/Rs
27ecf29ecb09084c40e005ed8fc16e8e0eb607fd
[ "BSD-3-Clause" ]
1
2017-04-01T08:33:38.000Z
2017-04-01T08:33:38.000Z
Optimize.cpp
kassol/Rs
27ecf29ecb09084c40e005ed8fc16e8e0eb607fd
[ "BSD-3-Clause" ]
null
null
null
Optimize.cpp
kassol/Rs
27ecf29ecb09084c40e005ed8fc16e8e0eb607fd
[ "BSD-3-Clause" ]
1
2020-04-20T16:15:46.000Z
2020-04-20T16:15:46.000Z
#include "stdafx.h" #include "Optimize.h" #include "clipper.hpp" #include <algorithm> #include <io.h> #include <time.h> #define _SnapSame(x1, x2, lfSnap) (0==lfSnap?x1==x2:fabs(x1-x2)<lfSnap) #define _SnapLarge(x1, x2, lfSnap) (x1>x2-lfSnap) #define _SnapLarge2(x1, x2, lfSnap) (x1>x2+lfSnap) using namespace ClipperLib; double CalDistance(double x1, double y1, double x2, double y2) { return (x2-x1)*(x2-x1)+(y2-y1)*(y2-y1); } bool Optimize(CString strAllDomPath, CString strDxfPath, CString strRrlxPath) { clock_t starter = clock(); fstream outtime; outtime.open("C:\\time.txt", ios::out); CString path; CString strExt; std::vector<CString> vecImagePath; const double PRECISION = 10.0; while (1) { int index = strAllDomPath.ReverseFind(';'); if (index == -1) { vecImagePath.push_back(strAllDomPath); break; } else { vecImagePath.push_back(strAllDomPath.Right(strAllDomPath.GetLength()-index-1)); strAllDomPath = strAllDomPath.Left(index); } } auto path_ite = vecImagePath.begin(); std::fstream infile; std::vector<PolygonExt2> polygons; while (path_ite != vecImagePath.end()) { CString image_path = *path_ite; path = image_path.Left(image_path.ReverseFind('\\')+1); strExt = image_path.Right(image_path.GetLength()-image_path.ReverseFind('.')); CString index_name = image_path.Right(image_path.GetLength()-image_path.ReverseFind('\\')-1); index_name = index_name.Left(index_name.ReverseFind('.')); CString rrlx_path = strRrlxPath+index_name+_T(".rrlx"); infile.open(rrlx_path.GetBuffer(0), std::ios::in); int point_count = 0; infile>>point_count; double* px = new double[point_count]; memset(px, 0, sizeof(double)*point_count); double* py = new double[point_count]; memset(py, 0, sizeof(double)*point_count); int temp = 0; for (int i = 0; i < point_count; ++i) { infile>>px[i]>>py[i]>>temp; } polygons.push_back(PolygonExt2(point_count, px, py, index_name)); infile.close(); ++path_ite; } auto polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { double* px = polygon_ite->px_; double* py = polygon_ite->py_; int num = polygon_ite->point_count_; for (auto polygon_ite2 = polygons.begin(); polygon_ite2 < polygons.end(); ++polygon_ite2) { if (polygon_ite2 != polygon_ite) { double* px2 = polygon_ite2->px_; double* py2 = polygon_ite2->py_; int num2 = polygon_ite2->point_count_; for (int n = 0; n < num; ++n) { for (int m = 0; m < num2; ++m) { if (fabs(px[n]-px2[m]) < 0.000001 && fabs(py[n] - py2[m]) < 0.000001) { polygon_ite->np_[n].index_name_n_[polygon_ite->np_[n].shared_by_-1] = polygon_ite2->index_name_; ++(polygon_ite->np_[n].shared_by_); } } } } } ++polygon_ite; } long timer = clock() - starter; outtime<<"统计耗时:"<<timer<<"ms\n"; //判断边界点 polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { double* px = polygon_ite->px_; double* py = polygon_ite->py_; int point_count = polygon_ite->point_count_; for (int i = 0; i < point_count; ++i) { if (polygon_ite->np_[i].shared_by_ == 1) { polygon_ite->np_[i].is_edge_ = true; } else { vector<double> vecx_temp; vector<double> vecy_temp; vecx_temp.push_back(px[(i-1+point_count)%point_count]); vecy_temp.push_back(py[(i-1+point_count)%point_count]); vecx_temp.push_back(px[(i+1)%point_count]); vecy_temp.push_back(py[(i+1)%point_count]); for (int n = 0; n < polygon_ite->np_[i].shared_by_-1; ++n) { auto ite = std::find(polygons.begin(), polygons.end(), PolygonExt2(0, NULL, NULL, polygon_ite->np_[i].index_name_n_[n])); int the_index = 0; for (int j = 0; j < ite->point_count_; ++j) { if (fabs(px[i]-ite->px_[j]) < 1e-5 && fabs(py[i]-ite->py_[j]) < 1e-5) { the_index = j; break; } } bool is_include = false; for (unsigned int j = 0; j < vecx_temp.size(); ++j) { if (fabs(ite->px_[(the_index-1+ite->point_count_)%ite->point_count_]-vecx_temp[j]) < 1e-5 && fabs(ite->py_[(the_index-1+ite->point_count_)%ite->point_count_]-vecy_temp[j]) < 1e-5) { is_include = true; break; } } if (!is_include) { vecx_temp.push_back(ite->px_[(the_index-1+ite->point_count_)%ite->point_count_]); vecy_temp.push_back(ite->py_[(the_index-1+ite->point_count_)%ite->point_count_]); } is_include = false; for (unsigned int j = 0; j < vecx_temp.size(); ++j) { if (fabs(ite->px_[(the_index+1)%ite->point_count_]-vecx_temp[j]) < 1e-5 && fabs(ite->py_[(the_index+1)%ite->point_count_]-vecy_temp[j]) < 1e-5) { is_include = true; break; } } if (!is_include) { vecx_temp.push_back(ite->px_[(the_index+1)%ite->point_count_]); vecy_temp.push_back(ite->py_[(the_index+1)%ite->point_count_]); } } if (vecx_temp.size() > polygon_ite->np_[i].shared_by_) { polygon_ite->np_[i].is_edge_ = true; } vecx_temp.clear(); vecy_temp.clear(); } } ++polygon_ite; } timer = clock()-starter; outtime<<"边界点耗时:"<<timer<<"ms\n"; // if (!EffectPoly(vecImagePath)) // { // return false; // } //读取有效区域 std::vector<PolygonExt2> EffPolygons; path_ite = vecImagePath.begin(); while (path_ite != vecImagePath.end()) { CString index_name = *path_ite; index_name = index_name.Right(index_name.GetLength()-index_name.ReverseFind('\\')-1); index_name = index_name.Left(index_name.ReverseFind('.')); CString ep_name = *path_ite+_T(".ep"); std::fstream infile; infile.open(ep_name.GetBuffer(0), std::ios::in); int point_count = 0; infile>>point_count; double* px = new double[point_count]; double* py = new double[point_count]; for (int i = 0; i < point_count; ++i) { infile>>px[i]>>py[i]; } EffPolygons.push_back(PolygonExt2(point_count, px, py, index_name)); infile.close(); ++path_ite; } //dxf转dem IImageX* pImage = NULL; CoCreateInstance(CLSID_ImageDriverX, NULL, CLSCTX_ALL, IID_IImageX, (void**)&pImage); if (S_FALSE == pImage->Open(vecImagePath.front().AllocSysString(), modeRead)) { pImage->Release(); return false; } double tmp_cellsize = 0, tmp = 0; pImage->GetGrdInfo(&tmp, &tmp, &tmp_cellsize); pImage->Close(); if (strDxfPath.Right(3).CompareNoCase(_T("dxf")) == 0 && !Dxf2Dsm(strDxfPath, tmp_cellsize)) { return false; } CString strDsmPath = strDxfPath.Left(strDxfPath.ReverseFind('.')); strDsmPath += _T(".dem"); //dem转tif if (!Dsm2Tif(strDsmPath)) { return false; } CString strTifPath = strDsmPath.Left(strDsmPath.ReverseFind('.')); strTifPath += _T(".tif"); //根据dsm移三四度点 if (S_FALSE == pImage->Open(strTifPath.AllocSysString(), modeRead)) { pImage->Release(); return false; } double resolution = 0; double lfXOrigin = 0, lfYOrigin = 0; pImage->GetGrdInfo(&lfXOrigin, &lfYOrigin, &resolution); int nWidth = 0, nHeight = 0; pImage->GetCols(&nWidth); pImage->GetRows(&nHeight); double lfXEnd = 0, lfYEnd = 0; lfXEnd = lfXOrigin+nWidth*resolution; lfYEnd = lfYOrigin+nHeight*resolution; double pEdgex[4]; double pEdgey[4]; pEdgex[0] = lfXOrigin; pEdgex[1] = lfXOrigin; pEdgex[2] = lfXEnd; pEdgex[3] = lfXEnd; pEdgey[0] = lfYEnd; pEdgey[1] = lfYOrigin; pEdgey[2] = lfYOrigin; pEdgey[3] = lfYEnd; IImageX* tempImage = NULL; CoCreateInstance(CLSID_ImageDriverX, NULL, CLSCTX_ALL, IID_IImageX, (void**)&tempImage); polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { double* px = polygon_ite->px_; double* py = polygon_ite->py_; int num = polygon_ite->point_count_; CString image_path = path+polygon_ite->index_name_+strExt; if (S_FALSE == tempImage->Open(image_path.AllocSysString(), modeRead)) { pImage->Close(); pImage->Release(); tempImage->Release(); return false; } RectFExt the_rect; int nXSize = 0, nYSize = 0; double lfCellSize = 0; double lfXOrigin = 0, lfYOrigin = 0; tempImage->GetCols(&nXSize); tempImage->GetRows(&nYSize); tempImage->GetGrdInfo(&lfXOrigin, &lfYOrigin, &lfCellSize); tempImage->Close(); the_rect.left = lfXOrigin; the_rect.right = lfXOrigin+nXSize*lfCellSize; the_rect.bottom = lfYOrigin; the_rect.top = lfYOrigin+nYSize*lfCellSize; for (int i = 0; i < num; ++i) { if (polygon_ite->np_[i].shared_by_ > 2) { double geox = px[i]; double geoy = py[i]; float fx = 0, fy = 0; pImage->World2Image(geox, geoy, &fx, &fy); unsigned char height; pImage->ReadImg((int)fx, (int)fy, (int)(fx+1), (int)(fy+1), &height, 1, 1, 1, 0, 0, 1, 1, -1, 0); if (height < 10) { continue; } //获取限定区域 int shared_by = polygon_ite->np_[i].shared_by_; double* limit_poly_x = new double[shared_by]; double* limit_poly_y = new double[shared_by]; memset(limit_poly_x, 0, sizeof(double)*shared_by); memset(limit_poly_y, 0, sizeof(double)*shared_by); for (int limit_index = i-1; limit_index != i; limit_index = (limit_index-1+num)%num) { if (polygon_ite->np_[limit_index].shared_by_ > 2 || polygon_ite->np_[limit_index].is_edge_ == true) { limit_poly_x[0] = px[limit_index]; limit_poly_y[0] = py[limit_index]; } } for (int limit_index = i+1; limit_index != i; limit_index = (limit_index+1)%num) { if (polygon_ite->np_[limit_index].shared_by_ > 2 || polygon_ite->np_[limit_index].is_edge_ == true) { limit_poly_x[1] = px[limit_index]; limit_poly_y[1] = py[limit_index]; } } if (polygon_ite->np_[i].shared_by_ == 3) { auto limit_ite = std::find(polygons.begin(), polygons.end(), PolygonExt2(0, NULL, NULL, polygon_ite->np_[i].index_name_n_[0])); if (limit_ite != polygons.end()) { double* temp_px = limit_ite->px_; double* temp_py = limit_ite->py_; int temp_count = limit_ite->point_count_; for (int count = 0; count < temp_count; ++count) { if (fabs(temp_px[count]-px[i]) < 1e-5 && fabs(temp_py[count]-py[i]) < 1e-5) { int limit_index = 0; for (limit_index = (count-1+temp_count)%temp_count; limit_index != count; limit_index = (limit_index-1+temp_count)%temp_count) { if (limit_ite->np_[limit_index].shared_by_ > 2 || limit_ite->np_[limit_index].is_edge_ == true) { break; } } int limit_index2 = 0; for (limit_index2 = (count+1)%temp_count; limit_index2 != count; limit_index2 = (limit_index2+1)%temp_count) { if (limit_ite->np_[limit_index2].shared_by_ > 2 || limit_ite->np_[limit_index2].is_edge_ == true) { break; } } if (fabs(temp_px[limit_index]-limit_poly_x[0]) < 1e-5 && fabs(temp_py[limit_index]-limit_poly_y[0]) < 1e-5) { limit_poly_x[2] = temp_px[limit_index2]; limit_poly_y[2] = temp_py[limit_index2]; break; } else if (fabs(temp_px[limit_index]-limit_poly_x[1]) < 1e-5 && fabs(temp_py[limit_index]-limit_poly_y[1]) < 1e-5) { limit_poly_x[2] = temp_px[limit_index2]; limit_poly_y[2] = temp_py[limit_index2]; break; } else { if (fabs(temp_px[limit_index2]-limit_poly_x[0]) < 1e-5 && fabs(temp_py[limit_index2]-limit_poly_y[0]) < 1e-5) { limit_poly_x[2] = temp_px[limit_index]; limit_poly_y[2] = temp_py[limit_index]; break; } else if (fabs(temp_px[limit_index2]-limit_poly_x[1]) < 1e-5 && fabs(temp_py[limit_index2]-limit_poly_y[1]) < 1e-5) { limit_poly_x[2] = temp_px[limit_index]; limit_poly_y[2] = temp_py[limit_index]; break; } else { if (limit_poly_x != NULL) { delete []limit_poly_x; delete []limit_poly_y; limit_poly_x = NULL; limit_poly_y = NULL; } break; } } } } } } else if (shared_by == 4) { for (int temp = 0; temp < 2; ++temp) { auto limit_ite = std::find(polygons.begin(), polygons.end(), PolygonExt2(0, NULL, NULL, polygon_ite->np_[i].index_name_n_[temp])); if (limit_ite == polygons.end()) { if (limit_poly_x != NULL) { delete []limit_poly_x; delete []limit_poly_y; limit_poly_x = NULL; limit_poly_y = NULL; } break; } double* temp_px = limit_ite->px_; double* temp_py = limit_ite->py_; int temp_count = limit_ite->point_count_; for (int count = 0; count < temp_count; ++count) { if (fabs(temp_px[count]-px[i]) < 1e-5 && fabs(temp_py[count]-py[i]) < 1e-5) { int limit_index = 0; for (limit_index = (count-1+temp_count)%temp_count; limit_index != count; limit_index = (limit_index-1+temp_count)%temp_count) { if (limit_ite->np_[limit_index].shared_by_ > 2 || limit_ite->np_[limit_index].is_edge_ == true) { break; } } int limit_index2 = 0; for (limit_index2 = (count+1)%temp_count; limit_index2 != count; limit_index2 = (limit_index2+1)%temp_count) { if (limit_ite->np_[limit_index2].shared_by_ > 2 || limit_ite->np_[limit_index2].is_edge_ == true) { break; } } if (fabs(temp_px[limit_index]-limit_poly_x[0]) < 1e-5 && fabs(temp_py[limit_index]-limit_poly_y[0]) < 1e-5) { if (limit_poly_x[2] == 0) { limit_poly_x[2] = temp_px[limit_index2]; limit_poly_y[2] = temp_py[limit_index2]; } else { limit_poly_x[3] = temp_px[limit_index2]; limit_poly_y[3] = temp_py[limit_index2]; } } else if (fabs(temp_px[limit_index]-limit_poly_x[1]) < 1e-5 && fabs(temp_py[limit_index]-limit_poly_y[1]) < 1e-5) { if (limit_poly_x[2] == 0) { limit_poly_x[2] = temp_px[limit_index2]; limit_poly_y[2] = temp_py[limit_index2]; } else { limit_poly_x[3] = temp_px[limit_index2]; limit_poly_y[3] = temp_py[limit_index2]; } } else if (fabs(temp_px[limit_index]-limit_poly_x[2]) < 1e-5 && fabs(temp_py[limit_index]-limit_poly_y[2]) < 1e-5) { limit_poly_x[3] = temp_px[limit_index2]; limit_poly_y[3] = temp_py[limit_index2]; } else { if (limit_poly_x[2] == 0) { limit_poly_x[2] = temp_px[limit_index2]; limit_poly_y[2] = temp_py[limit_index2]; } else { limit_poly_x[3] = temp_px[limit_index2]; limit_poly_y[3] = temp_py[limit_index2]; } } if (fabs(temp_px[limit_index2]-limit_poly_x[0]) < 1e-5 && fabs(temp_py[limit_index2]-limit_poly_y[0]) < 1e-5) { if (limit_poly_x[2] == 0) { limit_poly_x[2] = temp_px[limit_index]; limit_poly_y[2] = temp_py[limit_index]; } else { limit_poly_x[3] = temp_px[limit_index]; limit_poly_y[3] = temp_py[limit_index]; } } else if (fabs(temp_px[limit_index2]-limit_poly_x[1]) < 1e-5 && fabs(temp_py[limit_index2]-limit_poly_y[1]) < 1e-5) { if (limit_poly_x[2] == 0) { limit_poly_x[2] = temp_px[limit_index]; limit_poly_y[2] = temp_py[limit_index]; } else { limit_poly_x[3] = temp_px[limit_index]; limit_poly_y[3] = temp_py[limit_index]; } } else if (fabs(temp_px[limit_index2]-limit_poly_x[2]) < 1e-5 && fabs(temp_py[limit_index2]-limit_poly_y[2]) < 1e-5) { if (fabs(temp_px[limit_index]-limit_poly_x[0]) > 1e-5 && fabs(temp_py[limit_index]-limit_poly_y[0]) > 1e-5 && fabs(temp_px[limit_index]-limit_poly_x[1]) > 1e-5 && fabs(temp_py[limit_index]-limit_poly_y[1]) > 1e-5) { limit_poly_x[3] = temp_px[limit_index]; limit_poly_y[3] = temp_py[limit_index]; } } else { if (fabs(temp_px[limit_index2]-limit_poly_x[0]) > 1e-5 && fabs(temp_py[limit_index2]-limit_poly_y[0]) > 1e-5 && fabs(temp_px[limit_index2]-limit_poly_x[1]) > 1e-5 && fabs(temp_py[limit_index2]-limit_poly_y[1]) > 1e-5) { limit_poly_x[3] = temp_px[limit_index2]; limit_poly_y[3] = temp_py[limit_index2]; } } if (limit_poly_x[2] == 0) { if (limit_poly_x != NULL) { delete []limit_poly_x; delete []limit_poly_y; limit_poly_x = NULL; limit_poly_y = NULL; } break; } else if (limit_poly_x[3] != 0) { break; } } } } } else { if (limit_poly_x != NULL) { delete []limit_poly_x; delete []limit_poly_y; limit_poly_x = NULL; limit_poly_y = NULL; } continue; } if (limit_poly_x == NULL) { continue; } if (shared_by == 4) { double d1 = 0, d2 = 0, d3 = 3, d4 = 0; d1 = (limit_poly_x[2]-limit_poly_x[1])*(limit_poly_y[0]-limit_poly_y[1]) -(limit_poly_x[0]-limit_poly_x[1])*(limit_poly_y[2]-limit_poly_y[1]); d2 = (limit_poly_x[2]-limit_poly_x[1])*(limit_poly_y[3]-limit_poly_y[1]) -(limit_poly_x[3]-limit_poly_x[1])*(limit_poly_y[2]-limit_poly_y[1]); d3 = (limit_poly_x[3]-limit_poly_x[0])*(limit_poly_y[1]-limit_poly_y[0]) -(limit_poly_x[1]-limit_poly_x[0])*(limit_poly_y[3]-limit_poly_y[0]); d4 = (limit_poly_x[3]-limit_poly_x[0])*(limit_poly_y[2]-limit_poly_y[0]) -(limit_poly_x[2]-limit_poly_x[0])*(limit_poly_y[3]-limit_poly_y[0]); if (d1*d2 < 0 && d3*d4 < 0) { double temp = limit_poly_x[2]; limit_poly_x[2] = limit_poly_x[3]; limit_poly_x[3] = temp; temp = limit_poly_y[2]; limit_poly_y[2] = limit_poly_y[3]; limit_poly_y[3] = temp; } }//获取限定区域结束 RectFExt result_result = the_rect; for (int j = 0; j < polygon_ite->np_[i].shared_by_-1; ++j) { image_path = path+polygon_ite->np_[i].index_name_n_[j]+strExt; tempImage->Open(image_path.AllocSysString(), modeRead); RectFExt temp_rect; int nx = 0, ny = 0; double cellsize = 0; double xorigin = 0, yorigin = 0; tempImage->GetCols(&nx); tempImage->GetRows(&ny); tempImage->GetGrdInfo(&xorigin, &yorigin, &cellsize); tempImage->Close(); temp_rect.left = xorigin; temp_rect.right = xorigin+nx*cellsize; temp_rect.bottom = yorigin; temp_rect.top = yorigin+ny*cellsize; result_result = result_result.Intersected(temp_rect); } int blockArea = 128; //获取公共区域的中心 double intersect_center_x = 0, intersect_center_y = 0; intersect_center_x = (result_result.left+result_result.right)/2; intersect_center_y = (result_result.top+result_result.bottom)/2; //限制buffer范围 RectFExt buf_rect; buf_rect.left = px[i]-blockArea; buf_rect.right = px[i]+blockArea; buf_rect.bottom = py[i]-blockArea; buf_rect.top = py[i]+blockArea; buf_rect = buf_rect.Intersected(result_result); if (buf_rect.IsEmpty()) { if (limit_poly_x != NULL) { delete []limit_poly_x; delete []limit_poly_y; limit_poly_x = NULL; limit_poly_y = NULL; } continue; } float buffer_left = 0, buffer_right = 0, buffer_bottom = 0, buffer_top = 0; pImage->World2Image(buf_rect.left, buf_rect.bottom, &buffer_left, &buffer_top); pImage->World2Image(buf_rect.right, buf_rect.top, &buffer_right, &buffer_bottom); float intersect_center_buffer_x = 0, intersect_center_buffer_y = 0; pImage->World2Image(intersect_center_x, intersect_center_y, &intersect_center_buffer_x, &intersect_center_buffer_y); int buffer_height = int(buffer_bottom-buffer_top+0.99999); int buffer_width = int(buffer_right-buffer_left+0.99999); unsigned short* buf = new unsigned short[buffer_height*buffer_width]; memset(buf, 0, buffer_height*buffer_width*sizeof(unsigned short)); pImage->ReadImg(buffer_left, buffer_top, buffer_right, buffer_bottom, (unsigned char*)buf, buffer_width, buffer_height, 1, 0, 0, buffer_width, buffer_height, -1, 0); int start_col = int(fx-buffer_left+0.99999); int start_row = int(fy-buffer_top+0.99999); int end_col = int(intersect_center_buffer_x-buffer_left+0.99999); int end_row = int(intersect_center_buffer_y-buffer_top+0.99999); if (start_col >= buffer_width || start_row >= buffer_height) { delete []buf; buf = NULL; if (limit_poly_x != NULL) { delete []limit_poly_x; delete []limit_poly_y; limit_poly_x = NULL; limit_poly_y = NULL; } continue; } bool isFind = false; int ncount = 0; const int count_limit = 7; //往公共区域中心移点 int xoff = 0, yoff = 0; xoff = end_col-start_col; yoff = end_row-start_row; double xite = 0, yite = 0; if (abs(xoff) > abs(yoff) && xoff != 0) { yite = yoff/(double)abs(xoff); xite = xoff > 0 ? 1 : -1; } else if (abs(yoff) > abs(xoff) && yoff != 0) { xite = xoff/(double)abs(yoff); yite = yoff > 0 ? 1 : -1; } else if (xoff = 0) { xite = 0; yite = yoff >= 0 ? 1 : -1; } else if (yoff = 0) { yite = 0; xite = xite >= 0 ? 1 : -1; } else if (abs(xoff) == abs(yoff)) { xite = xite >= 0 ? 1 : -1; yite = yoff >= 0 ? 1 : -1; } int limit_x = 0, limit_y = 0; if (end_col < start_col) { limit_x = min(end_col, 0); } else if (end_col > start_col) { limit_x = max(end_col, buffer_width); } if (limit_x < 0) { limit_x = 0; } else if (limit_x > buffer_width) { limit_x = buffer_width; } if (end_row < start_row) { limit_y = min(end_row, 0); } else if (end_row > start_row) { limit_y = max(end_row, buffer_height); } if (limit_y < 0) { limit_y = 0; } else if (limit_y > buffer_height) { limit_y = buffer_height; } double findx = start_col, findy = start_row; if (xite == 0) { while ((findy-limit_y)*(findy-yite-limit_y) > 0) { if (buf[int(findy)*buffer_width+int(findx)] > 10) { ncount = 0; } else { ++ncount; if (ncount >= count_limit) { if (-1 == PtInRegionZXEx( geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution, limit_poly_x, limit_poly_y, shared_by, 1e-5)) { break; } isFind = true; auto poly = polygons.begin(); while (poly != polygons.end()) { poly->ResetPoint("", geox, geoy, geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution); ++poly; } break; } } findy += yite; if (findy < 0 || int(findy) >= buffer_width) { break; } } } else if (yite == 0) { while ((findx-limit_x)*(findx-xite-limit_x) > 0) { if (buf[int(findy)*buffer_width+int(findx)] > 10) { ncount = 0; } else { ++ncount; if (ncount >= count_limit) { if (-1 == PtInRegionZXEx( geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution, limit_poly_x, limit_poly_y, shared_by, 1e-5)) { break; } isFind = true; auto poly = polygons.begin(); while (poly != polygons.end()) { poly->ResetPoint("", geox, geoy, geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution); ++poly; } break; } } findx += xite; if (findx < 0 || int(findx) >= buffer_width) { break; } } } else { while ((findx-limit_x)*(findx-xite-limit_x) > 0 && (findy-limit_y)*(findy-yite-limit_y) > 0) { if (buf[int(findy)*buffer_width+int(findx)] != 0) { ncount = 0; } else { ++ncount; if (ncount >= count_limit) { if (-1 == PtInRegionZXEx( geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution, limit_poly_x, limit_poly_y, shared_by, 1e-5)) { break; } isFind = true; auto poly = polygons.begin(); while (poly != polygons.end()) { poly->ResetPoint("", geox, geoy, geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution); ++poly; } break; } } findy += yite; findx += xite; if (findx < 0 || int(findx) >= buffer_width) { break; } if (findy < 0 || int(findy) >= buffer_width) { break; } } } if (!isFind) { yite = -yite; xite = xite; double findx = start_col, findy = start_row; if (xite == 0) { while ((findy-limit_y)*(findy-yite-limit_y) > 0) { if (buf[int(findy)*buffer_width+int(findx)] > 10) { ncount = 0; } else { ++ncount; if (ncount >= count_limit) { if (-1 == PtInRegionZXEx( geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution, limit_poly_x, limit_poly_y, shared_by, 1e-5)) { break; } isFind = true; auto poly = polygons.begin(); while (poly != polygons.end()) { poly->ResetPoint("", geox, geoy, geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution); ++poly; } break; } } findy += yite; if (findy < 0 || int(findy) >= buffer_width) { break; } } } else if (yite == 0) { while ((findx-limit_x)*(findx-xite-limit_x) > 0) { if (buf[int(findy)*buffer_width+int(findx)] > 10) { ncount = 0; } else { ++ncount; if (ncount >= count_limit) { if (-1 == PtInRegionZXEx( geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution, limit_poly_x, limit_poly_y, shared_by, 1e-5)) { break; } isFind = true; auto poly = polygons.begin(); while (poly != polygons.end()) { poly->ResetPoint("", geox, geoy, geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution); ++poly; } break; } } findx += xite; if (findx < 0 || int(findx) >= buffer_width) { break; } } } else { while ((findx-limit_x)*(findx-xite-limit_x) > 0 && (findy-limit_y)*(findy-yite-limit_y) > 0) { if (buf[int(findy)*buffer_width+int(findx)] != 0) { ncount = 0; } else { ++ncount; if (ncount >= count_limit) { if (-1 == PtInRegionZXEx( geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution, limit_poly_x, limit_poly_y, shared_by, 1e-5)) { break; } isFind = true; auto poly = polygons.begin(); while (poly != polygons.end()) { poly->ResetPoint("", geox, geoy, geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution); ++poly; } break; } } findy += yite; findx += xite; if (findx < 0 || int(findx) >= buffer_width) { break; } if (findy < 0 || int(findy) >= buffer_width) { break; } } } } if (!isFind) { yite = yite; xite = -xite; double findx = start_col, findy = start_row; if (xite == 0) { while ((findy-limit_y)*(findy-yite-limit_y) > 0) { if (buf[int(findy)*buffer_width+int(findx)] > 10) { ncount = 0; } else { ++ncount; if (ncount >= count_limit) { if (-1 == PtInRegionZXEx( geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution, limit_poly_x, limit_poly_y, shared_by, 1e-5)) { break; } isFind = true; auto poly = polygons.begin(); while (poly != polygons.end()) { poly->ResetPoint("", geox, geoy, geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution); ++poly; } break; } } findy += yite; if (findy < 0 || int(findy) >= buffer_width) { break; } } } else if (yite == 0) { while ((findx-limit_x)*(findx-xite-limit_x) > 0) { if (buf[int(findy)*buffer_width+int(findx)] > 10) { ncount = 0; } else { ++ncount; if (ncount >= count_limit) { if (-1 == PtInRegionZXEx( geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution, limit_poly_x, limit_poly_y, shared_by, 1e-5)) { break; } isFind = true; auto poly = polygons.begin(); while (poly != polygons.end()) { poly->ResetPoint("", geox, geoy, geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution); ++poly; } break; } } findx += xite; if (findx < 0 || int(findx) >= buffer_width) { break; } } } else { while ((findx-limit_x)*(findx-xite-limit_x) > 0 && (findy-limit_y)*(findy-yite-limit_y) > 0) { if (buf[int(findy)*buffer_width+int(findx)] != 0) { ncount = 0; } else { ++ncount; if (ncount >= count_limit) { if (-1 == PtInRegionZXEx( geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution, limit_poly_x, limit_poly_y, shared_by, 1e-5)) { break; } isFind = true; auto poly = polygons.begin(); while (poly != polygons.end()) { poly->ResetPoint("", geox, geoy, geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution); ++poly; } break; } } findy += yite; findx += xite; if (findx < 0 || int(findx) >= buffer_width) { break; } if (findy < 0 || int(findy) >= buffer_width) { break; } } } } if (!isFind) { yite = -yite; xite = xite; double findx = start_col, findy = start_row; if (xite == 0) { while ((findy-limit_y)*(findy-yite-limit_y) > 0) { if (buf[int(findy)*buffer_width+int(findx)] > 10) { ncount = 0; } else { ++ncount; if (ncount >= count_limit) { if (-1 == PtInRegionZXEx( geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution, limit_poly_x, limit_poly_y, shared_by, 1e-5)) { break; } isFind = true; auto poly = polygons.begin(); while (poly != polygons.end()) { poly->ResetPoint("", geox, geoy, geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution); ++poly; } break; } } findy += yite; if (findy < 0 || int(findy) >= buffer_width) { break; } } } else if (yite == 0) { while ((findx-limit_x)*(findx-xite-limit_x) > 0) { if (buf[int(findy)*buffer_width+int(findx)] > 10) { ncount = 0; } else { ++ncount; if (ncount >= count_limit) { if (-1 == PtInRegionZXEx( geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution, limit_poly_x, limit_poly_y, shared_by, 1e-5)) { break; } isFind = true; auto poly = polygons.begin(); while (poly != polygons.end()) { poly->ResetPoint("", geox, geoy, geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution); ++poly; } break; } } findx += xite; if (findx < 0 || int(findx) >= buffer_width) { break; } } } else { while ((findx-limit_x)*(findx-xite-limit_x) > 0 && (findy-limit_y)*(findy-yite-limit_y) > 0) { if (buf[int(findy)*buffer_width+int(findx)] != 0) { ncount = 0; } else { ++ncount; if (ncount >= count_limit) { if (-1 == PtInRegionZXEx( geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution, limit_poly_x, limit_poly_y, shared_by, 1e-5)) { break; } isFind = true; auto poly = polygons.begin(); while (poly != polygons.end()) { poly->ResetPoint("", geox, geoy, geox+(findx-start_col)*resolution, geoy+(findy-start_row)*resolution); ++poly; } break; } } findy += yite; findx += xite; if (findx < 0 || int(findx) >= buffer_width) { break; } if (findy < 0 || int(findy) >= buffer_width) { break; } } } } delete []buf; buf = NULL; if (limit_poly_x != NULL) { delete []limit_poly_x; delete []limit_poly_y; limit_poly_x = NULL; limit_poly_y = NULL; } } } ++polygon_ite; }//移点结束 //删点 polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { auto ite = polygon_ite->np_.begin(); while (ite != polygon_ite->np_.end()) { if (ite->shared_by_ == 2 && ite->is_edge_ == false) { ite->available_ = false; } ++ite; } ++polygon_ite; } //dp增点 polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { vector<int> available_index; for (int index = 0; index < polygon_ite->point_count_; ++index) { if (polygon_ite->np_[index].available_) { available_index.push_back(index); } } if (available_index.size() <= 2) { vector<int> available_result(available_index); for (unsigned int index = 0; index < available_index.size(); ++index) { if (index != available_index.size()-1) { recurse(polygon_ite->px_, polygon_ite->py_, available_result, available_index[index], available_index[index+1], 128*1.414*0.2, polygon_ite->point_count_); } else { recurse(polygon_ite->px_, polygon_ite->py_, available_result, available_index[index], available_index[0], 128*1.414*0.2, polygon_ite->point_count_); } } for (unsigned int index = 0; index < available_result.size(); ++index) { polygon_ite->np_[available_result[index]].available_ = true; polygon_ite->np_[available_result[index]].is_edge_ = true; } available_result.clear(); } available_index.clear(); ++polygon_ite; } polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { auto ite = polygon_ite->np_.begin(); int index1 = 0; while (ite != polygon_ite->np_.end()) { if (ite->shared_by_ == 2) { auto temp_ite = std::find(polygons.begin(), polygons.end(), PolygonExt2(0, NULL, NULL, ite->index_name_n_[0])); for (int index2 = 0; index2 < temp_ite->point_count_; ++index2) { if (fabs(polygon_ite->px_[index1]-temp_ite->px_[index2]) < 1e-5 && fabs(polygon_ite->py_[index1]-temp_ite->py_[index2]) < 1e-5) { if (temp_ite->np_[index2].available_) { ite->available_ = true; ite->is_edge_ = true; } break; } } } ++index1; ++ite; } ++polygon_ite; } timer = clock()-starter; outtime<<"dp增点耗时:"<<timer<<"ms\n"; //解决删点面积反向 polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { int area = polygon_ite->GetArea(); int area_del = polygon_ite->GetDelArea(); double* px = polygon_ite->px_; double* py = polygon_ite->py_; int point_count = polygon_ite->point_count_; if (area_del == 0) { vector<int> reserve_index; for (int i = 0; i < point_count; ++i) { if (polygon_ite->np_[i].available_) { reserve_index.push_back(i); } if (reserve_index.size() == 2) { break; } } double max = 0; int max_index = 0; for (int i = 0; i < point_count; ++i) { if (polygon_ite->np_[i].available_ == false) { double dis = GetDistance(px[i], py[i], px[reserve_index[0]], py[reserve_index[0]], px[reserve_index[1]], py[reserve_index[1]]); if (max == 0 || max < dis) { max = dis; max_index = i; } } } reserve_index.clear(); polygon_ite->np_[max_index].available_ = true; polygon_ite->np_[max_index].is_edge_ = true; } else if (area*area_del < 0) { for (int i = 0; i < point_count; ++i) { if (polygon_ite->np_[i].available_ == false) { polygon_ite->np_[i].available_ = true; polygon_ite->np_[i].is_edge_ = true; area_del = polygon_ite->GetDelArea(); if (area*area_del > 0) { break; } } } } ++polygon_ite; } //解决删点后自交 polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { bool modified = false; if (polygon_ite->CrossSelf()) { for (int i = 0; i < polygon_ite->point_count_; ++i) { if (polygon_ite->np_[i].available_ == false) { polygon_ite->np_[i].available_ = true; polygon_ite->np_[i].is_edge_ = true; if (polygon_ite->CrossSelf() == false) { modified = true; break; } else { polygon_ite->np_[i].available_ = false; polygon_ite->np_[i].is_edge_ = false; } } } if (modified) { polygon_ite = polygons.begin(); continue; } } ++polygon_ite; } polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { auto ite = polygon_ite->np_.begin(); int index1 = 0; while (ite != polygon_ite->np_.end()) { if (ite->shared_by_ == 2) { auto temp_ite = std::find(polygons.begin(), polygons.end(), PolygonExt2(0, NULL, NULL, ite->index_name_n_[0])); for (int index2 = 0; index2 < temp_ite->point_count_; ++index2) { if (fabs(polygon_ite->px_[index1]-temp_ite->px_[index2]) < 1e-5 && fabs(polygon_ite->py_[index1]-temp_ite->py_[index2]) < 1e-5) { if (temp_ite->np_[index2].available_) { ite->available_ = true; ite->is_edge_ = true; } break; } } } ++index1; ++ite; } ++polygon_ite; } polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { polygon_ite->DeletePoint(); ++polygon_ite; } //解决删点后依然自交 CoCreateInstance(CLSID_ImageDriverX, NULL, CLSCTX_ALL, IID_IImageX, (void**)&tempImage); polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { double* px = polygon_ite->px_; double* py = polygon_ite->py_; int point_count = polygon_ite->point_count_; for (int count = 0; count < point_count; ++count) { if (polygon_ite->np_[count].shared_by_ == 2) { auto polygon_ite2 = polygons.begin(); bool isin = false; while (polygon_ite2 != polygons.end()) { CString strID = polygon_ite2->index_name_; if (strID.CompareNoCase(polygon_ite->np_[count].index_name_n_[0]) != 0 && strID.CompareNoCase(polygon_ite->index_name_) != 0) { isin |= (-1 != PtInRegionZXEx(px[count], py[count], polygon_ite2->px_, polygon_ite2->py_, polygon_ite2->point_count_, 0.00001)); if (isin) { break; } } ++polygon_ite2; } if (isin) { CString strImg = path+polygon_ite->index_name_+strExt; tempImage->Open(strImg.AllocSysString(), modeRead); RectFExt rect1; double lfCellsize; tempImage->GetGrdInfo(&rect1.left, &rect1.bottom, &lfCellsize); int ncols = 0, nrows = 0; tempImage->GetCols(&ncols); tempImage->GetRows(&nrows); rect1.right = rect1.left+ncols*lfCellsize; rect1.top = rect1.bottom+nrows*lfCellsize; tempImage->Close(); RectFExt rect2; strImg = path+polygon_ite->np_[count].index_name_n_[0]+strExt; tempImage->Open(strImg.AllocSysString(), modeRead); tempImage->GetGrdInfo(&rect2.left, &rect2.bottom, &lfCellsize); tempImage->GetCols(&ncols); tempImage->GetRows(&nrows); rect2.right = rect2.left+ncols*lfCellsize; rect2.top = rect2.bottom+nrows*lfCellsize; tempImage->Close(); RectFExt result_rect = rect1.Intersected(rect2); double center_x = (result_rect.left+result_rect.right)/2; double center_y = (result_rect.top+result_rect.bottom)/2; int offsetx = 0, offsety = 0; if (fabs(px[count]-center_x) < fabs(py[count]-center_y)) { if (center_y-py[count] < 0) { offsety = -10; } else { offsety = 10; } offsetx = 0; } else { if (center_x-px[count] < 0) { offsetx = -10; } else { offsetx = 10; } offsety = 0; } double distance = (px[count]-center_x)*(px[count]-center_x)+(py[count]-center_y)*(py[count]-center_y); double temp_distance = 0; do { if (-1 == PtInRegionZXEx(px[count]+offsetx, py[count]+offsety, polygon_ite2->px_, polygon_ite2->py_, polygon_ite2->point_count_, 0.00001)) { break; } offsetx += offsetx; offsety += offsety; temp_distance = (px[count]+offsetx-center_x)*(px[count]+offsetx-center_x)+(py[count]+offsety-center_y)*(py[count]+offsety-center_y); } while (temp_distance < distance); if (-1 == PtInRegionZXEx(px[count]+offsetx, py[count]+offsety, polygon_ite2->px_, polygon_ite2->py_, polygon_ite2->point_count_, 0.00001)) { double px_origin = px[count]; double py_origin = py[count]; polygon_ite2 = polygons.begin(); while (polygon_ite2 != polygons.end()) { polygon_ite2->ResetPoint("", px_origin, py_origin, px_origin+offsetx, py_origin+offsety); ++polygon_ite2; } } } } } ++polygon_ite; } timer = clock()-starter; outtime<<"解决删点错误耗时:"<<timer<<"ms\n"; polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { polygon_ite->Output(strRrlxPath); ++polygon_ite; } //获取dxf中的多边形 CDrawing m_dxffile; std::vector<int> vecPointNum; std::vector<double*> vecX; std::vector<double*> vecY; if (strDxfPath.Right(3).CompareNoCase(_T("dxf")) == 0 && m_dxffile.Create() && m_dxffile.LoadDXFFile(strDxfPath) == TRUE) { ENTITYHEADER EntityHeader; char EntityData[4096]; OBJHANDLE hEntity; hEntity = m_dxffile.FindEntity(FIND_FIRST, &EntityHeader, EntityData, NULL); double lfMinx = 0, lfMiny = 0, lfMaxx = 0, lfMaxy = 0; while (hEntity) { switch(EntityHeader.EntityType) { case ENT_POLYLINE: case ENT_LINE3D: { PENTPOLYLINE pPolyline = (PENTPOLYLINE)EntityData; int nVertexNum = pPolyline->nVertex; if (nVertexNum > 2) { double *pX = new double[pPolyline->nVertex]; double *pY = new double[pPolyline->nVertex]; vecPointNum.push_back(pPolyline->nVertex); memset(pX, 0, pPolyline->nVertex*sizeof(double)); memset(pY, 0, pPolyline->nVertex*sizeof(double)); double minx = 0, miny = 0, maxx = 0, maxy = 0; double *ppX = new double[5]; double *ppY = new double[5]; for (int nIndex = 0; nIndex < pPolyline->nVertex; ++ nIndex) { pX[nIndex] = pPolyline->pVertex[nIndex].Point.x; pY[nIndex] = pPolyline->pVertex[nIndex].Point.y; } vecX.push_back(pX); vecY.push_back(pY); } } } hEntity = m_dxffile.FindEntity(FIND_NEXT, &EntityHeader, EntityData, NULL); } m_dxffile.Destroy(); } else if (strDxfPath.Right(3).CompareNoCase(_T("dxf")) == 0) { pImage->Close(); pImage->Release(); tempImage->Release(); return false; }//获取dxf中的多边形结束 timer = clock()-starter; outtime<<"其他操作耗时:"<<timer<<"ms\n"; if (S_FALSE == pImage->Open(strTifPath.AllocSysString(), modeRead)) { pImage->Release(); return false; } resolution = 0; lfXOrigin = 0, lfYOrigin = 0; pImage->GetGrdInfo(&lfXOrigin, &lfYOrigin, &resolution); nWidth = 0, nHeight = 0; pImage->GetCols(&nWidth); pImage->GetRows(&nHeight); lfXEnd = 0, lfYEnd = 0; lfXEnd = lfXOrigin+nWidth*resolution; lfYEnd = lfYOrigin+nHeight*resolution; pEdgex[0] = lfXOrigin; pEdgex[1] = lfXOrigin; pEdgex[2] = lfXEnd; pEdgex[3] = lfXEnd; pEdgey[0] = lfYEnd; pEdgey[1] = lfYOrigin; pEdgey[2] = lfYOrigin; pEdgey[3] = lfYEnd; IShortPaths* shortpath = NULL; HRESULT hr = CoCreateInstance(CLSID_ShortPaths, NULL, CLSCTX_ALL, IID_IShortPaths, (void**)&shortpath); if (FAILED(hr)) { pImage->Close(); pImage->Release(); tempImage->Release(); return false; } #define NEXT(a) ((a+1==polygon_ite->np_.end()) ? (polygon_ite->np_.begin()) : (a+1)) polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { double* px = polygon_ite->px_; double* py = polygon_ite->py_; int point_count = polygon_ite->point_count_; auto ite = polygon_ite->np_.begin(); int point_index = 0; while (ite != polygon_ite->np_.end()) { if (ite->shared_by_ > 1 && ite->available_) { if ((NEXT(ite))->shared_by_ > 1 && (NEXT(ite))->available_) { double short_start_x = 0, short_start_y = 0, short_end_x = 0, short_end_y = 0; if (-1 != PtInRegionZXEx(px[point_index], py[point_index], pEdgex, pEdgey, 4, 1e-5) && -1 != PtInRegionZXEx(px[(point_index+1)%point_count], py[(point_index+1)%point_count], pEdgex, pEdgey, 4, 1e-5)) { short_start_x = px[point_index]; short_start_y = py[point_index]; short_end_x = px[(point_index+1)%point_count]; short_end_y = py[(point_index+1)%point_count]; } else { double result_x = 0, result_y = 0; if (GetCrossPoint(px[point_index], py[point_index], px[(point_index+1)%point_count], py[(point_index+1)%point_count], pEdgex, pEdgey, 4, result_x, result_y)) { if (-1 != PtInRegionZXEx(px[point_index], py[point_index], pEdgex, pEdgey, 4, 1e-5)) { short_start_x = px[point_index]; short_start_y = py[point_index]; short_end_x = result_x; short_end_y = result_y; } else if (-1 != PtInRegionZXEx(px[(point_index+1)%point_count], py[(point_index+1)%point_count], pEdgex, pEdgey, 4, 1e-5)) { short_start_x = result_x; short_start_y = result_y; short_end_x = px[(point_index+1)%point_count]; short_end_y = py[(point_index+1)%point_count]; } else { ++point_index; ++ite; continue; } } else { ++point_index; ++ite; continue; } } //判断连线本身是否穿过任何建筑物 if (strDxfPath.Right(3).CompareNoCase(_T("dxf")) == 0) { bool is_cross_building = LineCrossPolygon(vecX, vecY, vecPointNum, short_start_x, short_start_y, short_end_x, short_end_y); if (is_cross_building == false) { ++point_index; ++ite; continue; } } //找出另一关联影像 CString strIndexName = ""; for (int name_index = 0; name_index < ite->shared_by_-1; ++name_index) { for (int name_index2 = 0; name_index2 < (NEXT(ite))->shared_by_-1; ++name_index2) { if (ite->index_name_n_[name_index] == (NEXT(ite))->index_name_n_[name_index2]) { strIndexName = ite->index_name_n_[name_index]; break; } } if (strIndexName != "") { break; } } if (strIndexName == "") { ++point_index; ++ite; continue; } //取有效多边形求交 auto poly = std::find(EffPolygons.begin(), EffPolygons.end(), PolygonExt2(0, NULL, NULL, polygon_ite->index_name_)); if (poly == EffPolygons.end()) { ++point_index; ++ite; continue; } Path subj; for (int count = 0; count < poly->point_count_; ++count) { subj<<IntPoint(int(poly->px_[count]*PRECISION), int(poly->py_[count]*PRECISION)); } poly = std::find(EffPolygons.begin(), EffPolygons.end(), PolygonExt2(0, NULL, NULL, strIndexName)); if (poly == EffPolygons.end()) { ++point_index; ++ite; continue; } Path clip; for (int count = 0; count < poly->point_count_; ++count) { clip<<IntPoint(int(poly->px_[count]*PRECISION), int(poly->py_[count]*PRECISION)); } Clipper c; c.AddPath(subj, ptSubject, true); c.AddPath(clip, ptClip, true); Paths effect; c.Execute(ctIntersection, effect); subj.clear(); clip.clear(); c.Clear(); for (int count = 0; count < polygon_ite->point_count_; ++count) { subj<<IntPoint(int(polygon_ite->px_[count]*PRECISION), int(polygon_ite->py_[count]*PRECISION)); } poly = std::find(polygons.begin(), polygons.end(), PolygonExt2(0, NULL, NULL, strIndexName)); if (poly == polygons.end()) { ++point_index; ++ite; continue; } for (int count = 0; count < poly->point_count_; ++count) { clip<<IntPoint(int(poly->px_[count]*PRECISION), int(poly->py_[count]*PRECISION)); } c.AddPath(subj, ptSubject, true); c.AddPath(clip, ptClip, true); Paths temp; c.Execute(ctUnion, temp); c.Clear(); c.AddPaths(effect, ptSubject, true); c.AddPaths(temp, ptClip, true); Paths result = temp; c.Execute(ctIntersection, result); if (result.size() == 0) { ++point_index; ++ite; continue; } int effect_point_count = result[0].size(); double* tempx = new double[effect_point_count]; memset(tempx, 0, sizeof(double)*effect_point_count); double* tempy = new double[effect_point_count]; memset(tempy, 0, sizeof(double)*effect_point_count); for (int i = 0; i < effect_point_count; ++i) { tempx[i] = result[0][i].X/PRECISION; tempy[i] = result[0][i].Y/PRECISION; } result.clear(); //最短路径 double* lpXout = NULL; double* lpYout = NULL; long point_count_out = 0; if (-1 != PtInRegionZXEx(short_start_x, short_start_y, tempx, tempy, effect_point_count, 0.07) || -1 != PtInRegionZXEx(short_end_x, short_end_y, tempx, tempy, effect_point_count, 0.07)) { //返回错误则取图幅范围相交区域走最短路径 CString image_path = path+polygon_ite->index_name_+strExt; tempImage->Open(image_path.AllocSysString(), modeRead); RectFExt the_rect; int nXSize = 0, nYSize = 0; double lfCellSize = 0; double lfXOrigin = 0, lfYOrigin = 0; tempImage->GetCols(&nXSize); tempImage->GetRows(&nYSize); tempImage->GetGrdInfo(&lfXOrigin, &lfYOrigin, &lfCellSize); tempImage->Close(); the_rect.left = lfXOrigin; the_rect.right = lfXOrigin+nXSize*lfCellSize; the_rect.bottom = lfYOrigin; the_rect.top = lfYOrigin+nYSize*lfCellSize; RectFExt rect_result = the_rect; CString strSameIndex = ""; for (int j = 0; j < ite->shared_by_-1; ++j) { for (int k = 0; k < (NEXT(ite))->shared_by_-1; ++k) { if (NEXT(ite)->index_name_n_[k].CompareNoCase(ite->index_name_n_[j]) == 0) { strSameIndex = ite->index_name_n_[j]; break; } } if (strSameIndex != "") { break; } } if (strSameIndex == "") { ++point_index; ++ite; continue; } image_path = path+strSameIndex+strExt; tempImage->Open(image_path.AllocSysString(), modeRead); RectFExt temp_rect; int nx = 0, ny = 0; double cellsize = 0; double xorigin = 0, yorigin = 0; tempImage->GetCols(&nx); tempImage->GetRows(&ny); tempImage->GetGrdInfo(&xorigin, &yorigin, &cellsize); tempImage->Close(); temp_rect.left = xorigin; temp_rect.right = xorigin+nx*cellsize; temp_rect.bottom = yorigin; temp_rect.top = yorigin+ny*cellsize; rect_result = rect_result.Intersected(temp_rect); double rect_x[4]; double rect_y[4]; rect_x[0] = rect_result.left; rect_x[1] = rect_result.left; rect_x[2] = rect_result.right; rect_x[3] = rect_result.right; rect_y[0] = rect_result.top; rect_y[1] = rect_result.bottom; rect_y[2] = rect_result.bottom; rect_y[3] = rect_result.top; double result_x = 0, result_y = 0; if (GetCrossPoint(short_start_x, short_start_y, short_end_x, short_end_y, rect_x, rect_y, 4, result_x, result_y)) { if (-1 != PtInRegionZXEx(short_start_x, short_start_y, rect_x, rect_y, 4, 1e-5)) { short_end_x = result_x; short_end_y = result_y; } else if (-1 != PtInRegionZXEx(short_end_x, short_end_y, rect_x, rect_y, 4, 1e-5)) { short_start_x = result_x; short_start_y = result_y; } else { delete []tempx; tempx = NULL; delete []tempy; tempy = NULL; ++point_index; ++ite; continue; } } else if (-1 != PtInRegionZXEx(short_start_x, short_start_y, rect_x, rect_y, 4, 1e-1) && -1 != PtInRegionZXEx(short_end_x, short_end_y, rect_x, rect_y, 4, 1e-1)) { } else { delete []tempx; tempx = NULL; delete []tempy; tempy = NULL; ++point_index; ++ite; continue; } } shortpath->ShortestPathviaPoly(strDsmPath.AllocSysString(), short_start_x, short_start_y, short_end_x, short_end_y, tempx, tempy, effect_point_count, &lpXout, &lpYout, &point_count_out); delete []tempx; tempx = NULL; delete []tempy; tempy = NULL; if (point_count_out >= 2) { double startx = px[point_index]; double starty = py[point_index]; double endx = px[(point_index+1)%point_count]; double endy = py[(point_index+1)%point_count]; auto temp_ite = polygons.begin(); while (temp_ite != polygons.end()) { temp_ite->InsertPoints(startx, starty, endx, endy, lpXout, lpYout, point_count_out, strIndexName, polygon_ite->index_name_); ++temp_ite; } ite = polygon_ite->np_.begin(); delete []lpXout; lpXout = NULL; delete []lpYout; lpYout = NULL; point_index = 0; px = polygon_ite->px_; py = polygon_ite->py_; point_count = polygon_ite->point_count_; continue; }//插点结束 } } ++point_index; ++ite; } ++polygon_ite; } timer = clock()-starter; outtime<<"最短路径耗时:"<<timer<<"ms\n"; vecPointNum.clear(); auto itex = vecX.begin(); while (itex != vecX.end()) { delete [](*itex); *itex = NULL; ++itex; } vecX.clear(); auto itey = vecY.begin(); while (itey != vecY.end()) { delete [](*itey); *itey = NULL; ++itey; } vecY.clear(); //删除造成相交的点 polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { double* px = polygon_ite->px_; double* py = polygon_ite->py_; int point_count = polygon_ite->point_count_; for (int count = 0; count < point_count; ++count) { if (polygon_ite->np_[count].shared_by_ == 2) { if (polygon_ite->np_[count].available_ == false) { auto polygon_ite2 = polygons.begin(); bool isin = false; while (polygon_ite2 != polygons.end()) { CString strID = polygon_ite2->index_name_; if (strID.CompareNoCase(polygon_ite->np_[count].index_name_n_[0]) != 0 && strID.CompareNoCase(polygon_ite->index_name_) != 0) { isin |= (-1 != PtInRegionZXEx(px[count], py[count], polygon_ite2->px_, polygon_ite2->py_, polygon_ite2->point_count_, 0.00001)); } ++polygon_ite2; } if (!isin) { polygon_ite->np_[count].available_ = true; } } } } ++polygon_ite; } polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { polygon_ite->DeletePoint(); ++polygon_ite; } timer = clock()-starter; outtime<<"第一次删点耗时:"<<timer<<"ms\n"; //第二次删点 while (true) { int cross_count = 0; polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { double* px = polygon_ite->px_; double* py = polygon_ite->py_; int point_count = polygon_ite->point_count_; for (int count = 0; count < point_count; ++count) { if (polygon_ite->np_[count].shared_by_ == 2 && polygon_ite->np_[count].is_edge_ == false) { auto polygon_ite2 = polygons.begin(); bool isin = false; while (polygon_ite2 != polygons.end()) { CString strID = polygon_ite2->index_name_; if (strID.CompareNoCase(polygon_ite->np_[count].index_name_n_[0]) != 0 && strID.CompareNoCase(polygon_ite->index_name_) != 0) { isin |= (-1 != PtInRegionZXEx(px[count], py[count], polygon_ite2->px_, polygon_ite2->py_, polygon_ite2->point_count_, 0.00001)); } ++polygon_ite2; } if (isin) { ++cross_count; polygon_ite->np_[count].available_ = false; } } } ++polygon_ite; } if (cross_count == 0) { break; } polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { polygon_ite->DeletePoint(); ++polygon_ite; } } timer = clock()-starter; outtime<<"第二次删点耗时:"<<timer<<"ms\n"; //删除自交的点 while (true) { int cross_count = 0; bool modified = false; polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { double* px = polygon_ite->px_; double* py = polygon_ite->py_; int point_count = polygon_ite->point_count_; if (point_count == 0) { ++polygon_ite; continue; } int index_front = 0, index_back = (index_front+point_count-1)%point_count; if (polygon_ite->is_cross_self_ == -1 || polygon_ite->is_cross_self_ == 1) { int temp_cross_count = 0; for (; index_front < point_count; ++index_front) { for (index_back = (index_front+point_count-1)%point_count; index_back != (index_front+2)%point_count; index_back = (index_back+point_count-1)%point_count) { if(LineCrossLine(px[index_front], py[index_front], px[(index_front+1)%point_count], py[(index_front+1)%point_count], px[index_back], py[index_back], px[(index_back-1+point_count)%point_count], py[(index_back-1+point_count)%point_count])) { polygon_ite->is_cross_self_ = 1; ++cross_count; ++temp_cross_count; if (polygon_ite->np_[index_front].shared_by_ == 2 && polygon_ite->np_[index_front].is_edge_ == false) { polygon_ite->np_[index_front].available_ = false; modified = true; } if (polygon_ite->np_[(index_front+1)%point_count].shared_by_ == 2 && polygon_ite->np_[(index_front+1)%point_count].is_edge_ == false) { polygon_ite->np_[(index_front+1)%point_count].available_ = false; modified = true; } if (polygon_ite->np_[index_back].shared_by_ == 2 && polygon_ite->np_[index_back].is_edge_ == false) { polygon_ite->np_[index_back].available_ = false; modified = true; } if (polygon_ite->np_[(index_back-1+point_count)%point_count].shared_by_ == 2 && polygon_ite->np_[(index_back-1+point_count)%point_count].is_edge_ == false) { polygon_ite->np_[(index_back-1+point_count)%point_count].available_ = false; modified = true; } } } } if (temp_cross_count == 0) { polygon_ite->is_cross_self_ = 0; } } ++polygon_ite; } if (!modified) { break; } polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { auto ite = polygon_ite->np_.begin(); int index1 = 0; while (ite != polygon_ite->np_.end()) { if (ite->shared_by_ == 2) { auto temp_ite = std::find(polygons.begin(), polygons.end(), PolygonExt2(0, NULL, NULL, ite->index_name_n_[0])); for (int index2 = 0; index2 < temp_ite->point_count_; ++index2) { if (fabs(polygon_ite->px_[index1]-temp_ite->px_[index2]) < 1e-5 && fabs(polygon_ite->py_[index1]-temp_ite->py_[index2]) < 1e-5) { if (temp_ite->np_[index2].available_ == false) { ite->available_ = false; } break; } } } ++index1; ++ite; } ++polygon_ite; } if (cross_count == 0) { break; } polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { polygon_ite->DeletePoint(); ++polygon_ite; } } timer = clock()-starter; outtime<<"解决自交耗时:"<<timer<<"ms\n"; outtime.close(); polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { polygon_ite->Output(strRrlxPath.GetBuffer(0)); ++polygon_ite; } shortpath->Release(); pImage->Close(); pImage->Release(); tempImage->Release(); polygon_ite = polygons.begin(); while (polygon_ite != polygons.end()) { polygon_ite->Free(); ++polygon_ite; } return true; } bool EffectPoly(std::vector<CString>& vecImagePath) { const int BG_COLOR = 255; std::vector<CString>::const_iterator image_path = vecImagePath.begin(); IImageX* pImage = NULL; HRESULT hRes = CoCreateInstance(CLSID_ImageDriverX, NULL, CLSCTX_ALL, IID_IImageX, (void**)&pImage); if (FAILED(hRes)) { return false; } while (image_path != vecImagePath.end()) { CString point_path = (*image_path)+_T(".ep"); std::vector<PointEx> point_left; std::vector<PointEx> point_right; hRes = pImage->Open(image_path->AllocSysString(), modeRead); if (hRes == S_FALSE) { if (pImage) { pImage->Release(); pImage = NULL; } vecImagePath.clear(); return FALSE; } int nXSize = 0, nYSize = 0, nBandNum = 0; double lfXOrigin = 0, lfYOrigin = 0, lfCellSize = 0; int BPB = 0; pImage->GetCols(&nXSize); pImage->GetRows(&nYSize); pImage->GetBandNum(&nBandNum); pImage->GetBPB(&BPB); pImage->GetGrdInfo(&lfXOrigin, &lfYOrigin, &lfCellSize); unsigned char* buffer = new unsigned char[nXSize*nBandNum*BPB]; int scan_count = 50; int interval = nYSize/scan_count; for (int y = 0; y < nYSize; y += interval) { memset(buffer, BG_COLOR, nXSize*nBandNum*BPB); pImage->ReadImg(0, y, nXSize, y+1, buffer, nXSize, 1, nBandNum, 0, 0, nXSize, 1, -1, 0); for (int x = 0; x < nXSize; ++x) { int result = 0; if (BPB == 1) { for (int n = 0; n < nBandNum; ++n) { result += buffer[x*nBandNum+n]; } } else if (BPB == 2) { unsigned short* data = (unsigned short*)buffer; for (int n = 0; n < nBandNum; ++n) { result += data[x*nBandNum+n]; } } if (result != nBandNum*BG_COLOR) { point_left.push_back(PointEx(x, y)); break; } } for(int x = nXSize-1; x >= 0; --x) { int result = 0; if (BPB == 1) { for (int n = 0; n < nBandNum; ++n) { result += buffer[x*nBandNum+n]; } } else if (BPB == 2) { unsigned short* data = (unsigned short*)buffer; for (int n = 0; n < nBandNum; ++n) { result += data[x*nBandNum+n]; } } if (result != nBandNum*BG_COLOR) { point_right.push_back(PointEx(x, y)); break; } } } delete []buffer; buffer = NULL; pImage->Close(); int point_count = point_left.size(); double* px = new double[point_count]; double* py = new double[point_count]; for (int i = 0; i < point_count; ++i) { px[i] = point_left[i].x; py[i] = point_left[i].y; } point_left.clear(); double limit = 2.5; point_left.push_back(PointEx(px[0], py[0])); for (int j = 1, k = 2; k < point_count;) { if(GetDistance(px[j], py[j], point_left.back().x, point_left.back().y, px[k], py[k])-limit < 0.000001) { ++j; ++k; } else { point_left.push_back(PointEx(px[j], py[j])); ++j; ++k; } } point_left.push_back(PointEx(px[point_count-1], py[point_count-1])); delete []px; px = NULL; delete []py; py = NULL; point_count = point_right.size(); px = new double[point_count]; py = new double[point_count]; for (int i = 0; i < point_count; ++i) { px[i] = point_right[i].x; py[i] = point_right[i].y; } point_right.clear(); point_right.push_back(PointEx(px[0], py[0])); for (int j = 1, k = 2; k < point_count;) { if(GetDistance(px[j], py[j], point_right.back().x, point_right.back().y, px[k], py[k])-limit < 0.000001) { ++j; ++k; } else { point_right.push_back(PointEx(px[j], py[j])); ++j; ++k; } } point_right.push_back(PointEx(px[point_count-1], py[point_count-1])); delete []px; px = NULL; delete []py; py = NULL; std::fstream outfile; outfile.open(point_path.GetBuffer(0), std::ios::out); outfile<<std::fixed; outfile<<point_left.size()+point_right.size()<<"\n"; for (unsigned int i = 0; i < point_left.size(); ++i) { outfile<<point_left[i].x*lfCellSize+lfXOrigin<<" "<<point_left[i].y*lfCellSize+lfYOrigin<<"\n"; } for (int i = point_right.size()-1; i >= 0; --i) { outfile<<point_right[i].x*lfCellSize+lfXOrigin<<" "<<point_right[i].y*lfCellSize+lfYOrigin<<"\n"; } outfile.close(); ++image_path; } pImage->Release(); return true; } bool Dxf2Dsm(CString strDxf, double tmp_cellsize) { CString strDsmPath = strDxf.Left(strDxf.ReverseFind('.')); strDsmPath += _T(".dem"); if (_access(strDsmPath, 0) == -1) { CDrawing m_dxffile; if (m_dxffile.Create() && m_dxffile.LoadDXFFile(strDxf) == TRUE) { ENTITYHEADER EntityHeader; char EntityData[4096]; OBJHANDLE hEntity; hEntity = m_dxffile.FindEntity(FIND_FIRST, &EntityHeader, EntityData, NULL); int nPolygonCount = 0; std::vector<int> vecPointNum; std::vector<double*> vecX; std::vector<double*> vecY; std::vector<double*>vecEXx; std::vector<double*>vecExy; double lfMinx = 0, lfMiny = 0, lfMaxx = 0, lfMaxy = 0; while (hEntity) { switch(EntityHeader.EntityType) { case ENT_POLYLINE: case ENT_LINE3D: { PENTPOLYLINE pPolyline = (PENTPOLYLINE)EntityData; int nVertexNum = pPolyline->nVertex; if (nVertexNum > 2) { double *pX = new double[pPolyline->nVertex]; double *pY = new double[pPolyline->nVertex]; vecPointNum.push_back(pPolyline->nVertex); memset(pX, 0, pPolyline->nVertex*sizeof(double)); memset(pY, 0, pPolyline->nVertex*sizeof(double)); double minx = 0, miny = 0, maxx = 0, maxy = 0; double *ppX = new double[5]; double *ppY = new double[5]; for (int nIndex = 0; nIndex < pPolyline->nVertex; ++ nIndex) { pX[nIndex] = pPolyline->pVertex[nIndex].Point.x; pY[nIndex] = pPolyline->pVertex[nIndex].Point.y; if (lfMinx == 0 || lfMinx > pX[nIndex]) { lfMinx = pX[nIndex]; } if (lfMiny == 0 || lfMiny > pY[nIndex]) { lfMiny = pY[nIndex]; } if (lfMaxx == 0 || lfMaxx < pX[nIndex]) { lfMaxx = pX[nIndex]; } if (lfMaxy == 0 || lfMaxy < pY[nIndex]) { lfMaxy = pY[nIndex]; } if (minx == 0 || minx > pX[nIndex]) { minx = pX[nIndex]; } if (miny == 0 || miny > pY[nIndex]) { miny = pY[nIndex]; } if (maxx == 0 || maxx < pX[nIndex]) { maxx = pX[nIndex]; } if (maxy == 0 || maxy < pY[nIndex]) { maxy = pY[nIndex]; } } ppX[0] = minx; ppX[1] = minx; ppX[2] = maxx; ppX[3] = maxx; ppX[4] = minx; ppY[0] = maxy; ppY[1] = miny; ppY[2] = miny; ppY[3] = maxy; ppY[4] = maxy; vecEXx.push_back(ppX); vecExy.push_back(ppY); vecX.push_back(pX); vecY.push_back(pY); ++nPolygonCount; } } } hEntity = m_dxffile.FindEntity(FIND_NEXT, &EntityHeader, EntityData, NULL); } m_dxffile.Destroy(); double cellsize = tmp_cellsize*20; double lfXOrigin = int(lfMinx/cellsize)*cellsize; double lfYOrigin = int(lfMiny/cellsize)*cellsize; double lfXEnd = int(lfMaxx/cellsize+1)*cellsize; double lfYEnd = int(lfMaxy/cellsize+1)*cellsize; int nXSize = int((lfXEnd-lfXOrigin)/cellsize); int nYSize = int((lfYEnd-lfYOrigin)/cellsize); std::fstream out; out<<std::fixed; out.open(strDsmPath.GetBuffer(0), std::ios::out); out<<"NSDTF-DEM\n"; CString tmp; tmp.Format("%.6f\n", cellsize); out<<tmp.GetBuffer(0); out<<"M\n"; out<<"0.000000\n"; out<<"0.000000\n"; out<<lfXOrigin<<"\n"; out<<lfYEnd<<"\n"; out<<cellsize<<"\n"; out<<cellsize<<"\n"; out<<nYSize<<"\n"; out<<nXSize<<"\n"; out<<"1\n"; float high = 100.0; float low = 0.0; float* pbuf = new float[nXSize*nYSize]; memset(pbuf, 0, nXSize*nYSize*sizeof(float)); auto itex = vecX.begin(); auto itey = vecY.begin(); auto itenum = vecPointNum.begin(); auto itexx = vecEXx.begin(); auto iteyy = vecExy.begin(); while (itex != vecX.end()) { int tmp_startx = 0, tmp_starty = 0; int tmp_endx = 0, tmp_endy = 0; tmp_startx = int(((*itexx)[0]-lfXOrigin)/cellsize-1); tmp_starty = int((lfYEnd-(*iteyy)[0])/cellsize-1); if (tmp_startx < 0) { tmp_startx = 0; } if (tmp_starty = 0) { tmp_starty = 0; } tmp_endx = int(((*itexx)[2]-lfXOrigin)/cellsize+1); tmp_endy = int((lfYEnd-(*iteyy)[1])/cellsize+1); if (tmp_endx > nXSize) { tmp_endx = nXSize; } if (tmp_endy > nYSize) { tmp_endy = nYSize; } for (int y = tmp_starty; y < tmp_endy; ++y) { for (int x = tmp_startx; x < tmp_endx; ++x) { if (-1 != PtInRegionZXEx(x*cellsize+lfXOrigin, lfYEnd-y*cellsize, *itex, *itey, *itenum, 1e-2)) { pbuf[y*nXSize+x] = high; } } } ++itex; ++itey; ++itenum; ++itexx; ++iteyy; } for (int y = 0; y < nYSize; ++y) { for (int x = 0; x < nXSize; ++x) { out<<pbuf[y*nXSize+x]<<" "; } out<<"\n"; } delete []pbuf; pbuf = NULL; out<<"\n"; out.close(); itex = vecX.begin(); itey = vecY.begin(); itexx = vecEXx.begin(); iteyy = vecExy.begin(); while(itex != vecX.end()) { delete [](*itex); delete [](*itey); delete [](*itexx); delete [](*iteyy); ++itex; ++itey; ++itexx; ++iteyy; } vecX.clear(); vecY.clear(); vecPointNum.clear(); } else { CString temp = _T("加载dxf失败!"); AfxMessageBox(temp); return false; } } return true; } bool Dsm2Tif(CString strDsmPath) { CString strTifPath = strDsmPath.Left(strDsmPath.ReverseFind('.')); strTifPath += _T(".tif"); if (_access(strTifPath.GetBuffer(0), 0) == -1) { IImageX* pImage = NULL; HRESULT hr = CoCreateInstance(CLSID_ImageDriverX, NULL, CLSCTX_ALL, IID_IImageX, (void**)&pImage); if (FAILED(hr)) { return false; } const int nBlockSize = 128; ifstream infile; float lfXOrigin; float lfYOrigin; float lfXResolution; float lfYResolution; int nXSize; int nYSize; double lfXStart; double lfYStart; infile.open(strDsmPath.GetBuffer(0), ios::in); string tmp; infile>>tmp; double lfZoom = 1; if (tmp == "NSDTF-DEM") { infile>>tmp; infile>>tmp; infile>>tmp; infile>>tmp; infile>>lfXOrigin; infile>>lfYOrigin; infile>>lfXResolution; infile>>lfYResolution; infile>>nYSize; infile>>nXSize; infile>>lfZoom; } else { infile.close(); infile.open(strDsmPath.GetBuffer(0), ios::in); float Keyp[7]; infile>>Keyp[0]; infile>>Keyp[1]; infile>>Keyp[2]; infile>>Keyp[3]; infile>>Keyp[4]; infile>>Keyp[5]; infile>>Keyp[6]; lfXOrigin = Keyp[0]; lfYOrigin = Keyp[1]; lfXResolution = Keyp[3]; lfYResolution = Keyp[4]; nXSize = (int)Keyp[5]; nYSize = (int)Keyp[6]; } lfXStart = lfXOrigin-lfXResolution/2; lfYStart = lfYOrigin+lfYResolution/2-nYSize*lfYResolution; pImage->CreateImg(strTifPath.AllocSysString(), modeCreate, nXSize, nYSize, Pixel_Int16, 1, BIP, lfXStart, lfYStart, lfXResolution); unsigned short* temBuf = new unsigned short[nXSize*nBlockSize]; memset(temBuf, 0, sizeof(unsigned short)*nXSize*nBlockSize); float* fBuf = new float[nXSize*nBlockSize]; memset(fBuf, 0, sizeof(float)*nXSize*nBlockSize); for (int y = 0; y < nYSize;) { if (y+nBlockSize < nYSize) { for (int n = nBlockSize-1; n >= 0; --n) { for (int m = 0; m < nXSize; ++m) { infile>>fBuf[n*nXSize+m]; } } for (int n = 0; n < nBlockSize; ++n) { for (int m = 0; m < nXSize; ++m) { if (fBuf[n*nXSize+m] < 0) { temBuf[n*nXSize+m] = 65535; } else { temBuf[n*nXSize+m] = (unsigned short)(fBuf[n*nXSize+m]/lfZoom); } } } pImage->WriteImg(0, nYSize-y-nBlockSize, nXSize, nYSize-y, (unsigned char*)temBuf, nXSize, nBlockSize, 1, 0, 0, nXSize, nBlockSize, -1, 0); y += nBlockSize; } else { for (int n = nYSize-y-1; n >= 0; --n) { for (int m = 0; m < nXSize; ++m) { infile>>fBuf[n*nXSize+m]; } } for (int n = 0; n < nBlockSize; ++n) { for (int m = 0; m < nXSize; ++m) { if (fBuf[n*nXSize+m] < 0) { temBuf[n*nXSize+m] = 65535; } else { temBuf[n*nXSize+m] = (unsigned short)(fBuf[n*nXSize+m]/lfZoom); } } } pImage->WriteImg(0, 0, nXSize, nYSize-y, (unsigned char*)temBuf, nXSize, nBlockSize, 1, 0, 0, nXSize, nYSize-y, -1, 0); y = nYSize; } } pImage->Close(); pImage->Release(); delete []fBuf; fBuf = NULL; delete []temBuf; temBuf = NULL; } return true; } bool LineCrossPolygon(std::vector<double*>& vecx, std::vector<double*>& vecy, std::vector<int>& point_num, double px1, double py1, double px2, double py2) { auto itex = vecx.begin(); auto itey = vecy.begin(); auto ite_point_count = point_num.begin(); while (itex != vecx.end()) { for (int count = 0; count <*ite_point_count; ++count) { if (LineCrossLine(px1, py1, px2, py2, (*itex)[count], (*itey)[count], (*itex)[(count+1)%(*ite_point_count)], (*itey)[(count+1)%(*ite_point_count)])) { return true; } } ++itex; ++itey; ++ite_point_count; } return false; } bool LineCrossLine(double px1, double py1, double px2, double py2, double px3, double py3, double px4, double py4) { double d1 = 0, d2 = 0, d3 = 0, d4 = 0; d1 = (px2-px1)*(py3-py1)-(px3-px1)*(py2-py1); d2 = (px2-px1)*(py4-py1)-(px4-px1)*(py2-py1); d3 = (px4-px3)*(py1-py3)-(px1-px3)*(py4-py3); d4 = (px4-px3)*(py2-py3)-(px2-px3)*(py4-py3); if (d1*d2 < 0 && d3*d4 < 0) { return true; } return false; } bool GetCrossPoint(double px1, double py1, double px2, double py2, double* px, double* py, int point_num, double& result_x, double& result_y) { for (int count = 0; count < point_num; ++count) { if (LineCrossLine(px1, py1, px2, py2, px[count], py[count], px[(count+1)%point_num], py[(count+1)%point_num])) { if (fabs(px1-px2) < 1e-5) { if (fabs(py1-py[count]) > 1e-5 ||fabs(py2-py[count]) > 1e-5) { result_x = px1; result_y = py[count]; return true; } } else if (fabs(py1-py2) < 1e-5) { if (fabs(px1-px[count]) > 1e-5 || fabs(px2-px[count]) > 1e-5) { result_x = px[count]; result_y = py1; return true; } } else { double k = (py1-py2)/(px1-px2); double b = py1-k*px1; if (fabs(px[count]-px[(count+1)%point_num]) < 1e-5) { result_x = px[count]; result_y = k*result_x+b; return true; } else if (fabs(py[count]-py[(count+1)%point_num]) < 1e-5) { result_y = py[count]; result_x = (result_y-b)/k; return true; } } } } return false; } int PtInRegionZXEx(double x, double y, double *pX, double *pY, int nSum, double lfSnap) { if (nSum <= 0 || NULL == pX || NULL == pY) { return FALSE; } int i0,i1,i2, ret=0; double xmin1, xmax1, ymin1, ymax1; for( int i=0; i<nSum; i++ ) { i0 = i; i1 = (i0+1)%nSum; // ¶¥µãÖØºÏÅÐ¶Ï // if( pX[i0] == x && pY[i0] == y ) if( _SnapSame( pX[i0],x,lfSnap ) && _SnapSame( pY[i0],y,lfSnap ) ) return 0; // ÅжÏÊÇ·ñ´æÔÚÏཻµÄ¿ÉÄÜ if( pX[i0]<pX[i1] ){ xmin1 = pX[i0]; xmax1 = pX[i1]; } else { xmin1 = pX[i1]; xmax1 = pX[i0]; } if( pY[i0]<pY[i1] ){ ymin1 = pY[i0]; ymax1 = pY[i1]; } else { ymin1 = pY[i1]; ymax1 = pY[i0]; } // if( y<ymin1 || y>ymax1 || x>xmax1 )continue; if( _SnapLarge2(ymin1,y,lfSnap) || _SnapLarge2(y,ymax1,lfSnap) || _SnapLarge2(x,xmax1,lfSnap) ) continue; //ÅжÏÊÇ·ñÔÚ±ßÉÏ // ˮƽ±ß½ç´¦Àí£¬Ö»ÐèÒªÅжϵãÊÇ·ñÔڱ߽çÉÏ if( pY[i1] == pY[i0] ) // if( _SnapSame(pY[i1],pY[i0],lfSnap) ) { // if( pY[i0]==y ) if( _SnapSame(pY[i0],y,lfSnap) ) { // if( ( pX[i0]>x && pX[i1]<x ) || // ( pX[i0]<x && pX[i1]>x ) ) if( ( _SnapLarge(pX[i0],x,lfSnap) && _SnapLarge(x,pX[i1],lfSnap) ) || ( _SnapLarge(x,pX[i0],lfSnap) && _SnapLarge(pX[i1],x,lfSnap) ) ) return 0; } } // Ïཻ¼«ÏÞÅжϣºÖ»Óë¶¥µãÏཻ // ÕâÀï²»»áÓеãÔڱ߽çÉϵĿÉÄÜ // if( y==ymin1 || y==ymax1 ) else if( _SnapSame(y,ymin1,lfSnap) || _SnapSame(y,ymax1,lfSnap) ) { if(_SnapSame(y,ymin1,lfSnap) && _SnapSame(y,ymax1,lfSnap)&& (( _SnapLarge(pX[i0],x,lfSnap) && _SnapLarge(x,pX[i1],lfSnap) ) || ( _SnapLarge(x,pX[i0],lfSnap) && _SnapLarge(pX[i1],x,lfSnap) ))) { return 0; } // if( y==pY[i0] && x<pX[i0] ) if( _SnapSame(y,pY[i0],lfSnap) && _SnapLarge(pX[i0],x,lfSnap) ) { // ÅжÏǰһ¸öµãºÍºóÒ»¸öµãÊÇ·ñÔÚÁ½²à£¬ÔÚÁ½²àµÄ»°ret¼Ó1 i2 = i0; while( true ) { i2 = (i2-1+nSum)%nSum; if( pY[i2] == pY[i0] ) { if( i2 == i1 || i2 == i0 )break; continue; } // if( ( pY[i2]<y && pY[i1]>y ) || // ( pY[i2]>y && pY[i1]<y ) ) if( ( _SnapLarge(y,pY[i2],lfSnap) && _SnapLarge(pY[i1],y,lfSnap) ) || ( _SnapLarge(pY[i2],y,lfSnap) && _SnapLarge(y,pY[i1],lfSnap) ) ) { ret ++; } break; } } } // else if( x==xmin1 || x==xmax1 ) else if( _SnapSame(x,xmin1,lfSnap) || _SnapSame(x,xmax1,lfSnap)) { if(_SnapSame(x,xmin1,lfSnap) && _SnapSame(x,xmax1,lfSnap)&& (( _SnapLarge(y,pY[i0],lfSnap) && _SnapLarge(pY[i1],y,lfSnap) ) || ( _SnapLarge(pY[i0],y,lfSnap) && _SnapLarge(y,pY[i1],lfSnap) ))) { return 0; } // if( x==xmin1 ) if( _SnapSame(x,xmin1,lfSnap) ) { ret ++; } } // if( x<xmin1 )ret++; else if( _SnapLarge(xmin1,x,lfSnap) ) ret ++; else { xmax1 = (y-pY[i0])*(pX[i1]-pX[i0])/(pY[i1]-pY[i0])+pX[i0]; // if( x==xmax1 )return 0;//±ß½çÉÏ if( _SnapSame(x,xmax1,lfSnap) )return 0; // if( x<xmax1 )ret++; if( _SnapLarge(xmax1,x,lfSnap) )ret ++; } } return 1==ret%2? 1:-1; }
25.383937
154
0.566581
[ "vector" ]
13dadc80375567af56295f863baded9b6eb46d87
6,515
hpp
C++
include/GlobalNamespace/PlayerSaveData.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/PlayerSaveData.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/PlayerSaveData.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: VersionSaveData #include "GlobalNamespace/VersionSaveData.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: System namespace System { // Forward declaring type: String class String; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x28 #pragma pack(push, 1) // Autogenerated type: PlayerSaveData // [TokenAttribute] Offset: FFFFFFFF class PlayerSaveData : public GlobalNamespace::VersionSaveData { public: // Nested type: GlobalNamespace::PlayerSaveData::GameplayModifiers class GameplayModifiers; // Nested type: GlobalNamespace::PlayerSaveData::PlayerSpecificSettings class PlayerSpecificSettings; // Nested type: GlobalNamespace::PlayerSaveData::PlayerAllOverallStatsData class PlayerAllOverallStatsData; // Nested type: GlobalNamespace::PlayerSaveData::PlayerOverallStatsData class PlayerOverallStatsData; // Nested type: GlobalNamespace::PlayerSaveData::PlayerLevelStatsData class PlayerLevelStatsData; // Nested type: GlobalNamespace::PlayerSaveData::PlayerMissionStatsData class PlayerMissionStatsData; // Nested type: GlobalNamespace::PlayerSaveData::PracticeSettings class PracticeSettings; // Nested type: GlobalNamespace::PlayerSaveData::ColorScheme class ColorScheme; // Nested type: GlobalNamespace::PlayerSaveData::ColorSchemesSettings class ColorSchemesSettings; // Nested type: GlobalNamespace::PlayerSaveData::OverrideEnvironmentSettings class OverrideEnvironmentSettings; // Nested type: GlobalNamespace::PlayerSaveData::GuestPlayer class GuestPlayer; // Nested type: GlobalNamespace::PlayerSaveData::MultiplayerModeSettings class MultiplayerModeSettings; // Nested type: GlobalNamespace::PlayerSaveData::LocalPlayer class LocalPlayer; // public System.Collections.Generic.List`1<PlayerSaveData/LocalPlayer> localPlayers // Size: 0x8 // Offset: 0x18 System::Collections::Generic::List_1<GlobalNamespace::PlayerSaveData::LocalPlayer*>* localPlayers; // Field size check static_assert(sizeof(System::Collections::Generic::List_1<GlobalNamespace::PlayerSaveData::LocalPlayer*>*) == 0x8); // public System.Collections.Generic.List`1<PlayerSaveData/GuestPlayer> guestPlayers // Size: 0x8 // Offset: 0x20 System::Collections::Generic::List_1<GlobalNamespace::PlayerSaveData::GuestPlayer*>* guestPlayers; // Field size check static_assert(sizeof(System::Collections::Generic::List_1<GlobalNamespace::PlayerSaveData::GuestPlayer*>*) == 0x8); // Creating value type constructor for type: PlayerSaveData PlayerSaveData(System::Collections::Generic::List_1<GlobalNamespace::PlayerSaveData::LocalPlayer*>* localPlayers_ = {}, System::Collections::Generic::List_1<GlobalNamespace::PlayerSaveData::GuestPlayer*>* guestPlayers_ = {}) noexcept : localPlayers{localPlayers_}, guestPlayers{guestPlayers_} {} // Deleting conversion operator: operator ::Il2CppString* constexpr operator ::Il2CppString*() const noexcept = delete; // static field const value: static public System.String kCurrentVersion static constexpr const char* kCurrentVersion = "2.0.17"; // Get static field: static public System.String kCurrentVersion static ::Il2CppString* _get_kCurrentVersion(); // Set static field: static public System.String kCurrentVersion static void _set_kCurrentVersion(::Il2CppString* value); // Get instance field: public System.Collections.Generic.List`1<PlayerSaveData/LocalPlayer> localPlayers System::Collections::Generic::List_1<GlobalNamespace::PlayerSaveData::LocalPlayer*>* _get_localPlayers(); // Set instance field: public System.Collections.Generic.List`1<PlayerSaveData/LocalPlayer> localPlayers void _set_localPlayers(System::Collections::Generic::List_1<GlobalNamespace::PlayerSaveData::LocalPlayer*>* value); // Get instance field: public System.Collections.Generic.List`1<PlayerSaveData/GuestPlayer> guestPlayers System::Collections::Generic::List_1<GlobalNamespace::PlayerSaveData::GuestPlayer*>* _get_guestPlayers(); // Set instance field: public System.Collections.Generic.List`1<PlayerSaveData/GuestPlayer> guestPlayers void _set_guestPlayers(System::Collections::Generic::List_1<GlobalNamespace::PlayerSaveData::GuestPlayer*>* value); // public System.Void .ctor() // Offset: 0x1F54120 // Implemented from: VersionSaveData // Base method: System.Void VersionSaveData::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static PlayerSaveData* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::PlayerSaveData::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<PlayerSaveData*, creationType>())); } }; // PlayerSaveData #pragma pack(pop) static check_size<sizeof(PlayerSaveData), 32 + sizeof(System::Collections::Generic::List_1<GlobalNamespace::PlayerSaveData::GuestPlayer*>*)> __GlobalNamespace_PlayerSaveDataSizeCheck; static_assert(sizeof(PlayerSaveData) == 0x28); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::PlayerSaveData*, "", "PlayerSaveData"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::PlayerSaveData::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
56.163793
300
0.750115
[ "object" ]
13e27adafdd0f5fb3226b12fb237b6f9fc3802e3
5,699
cc
C++
src/discord.cc
ca-l-eb/discord-music-bot
7646ff414577181fd7726f42524b71856e0f57fc
[ "BSD-3-Clause" ]
4
2018-04-29T08:58:30.000Z
2020-04-11T08:37:16.000Z
src/discord.cc
ca-l-eb/discord-music-bot
7646ff414577181fd7726f42524b71856e0f57fc
[ "BSD-3-Clause" ]
null
null
null
src/discord.cc
ca-l-eb/discord-music-bot
7646ff414577181fd7726f42524b71856e0f57fc
[ "BSD-3-Clause" ]
2
2020-02-17T19:54:17.000Z
2020-08-07T11:18:02.000Z
#include "discord.h" static discord::snowflake make_snowflake(const std::string &s) { return static_cast<discord::snowflake>(std::stoull(s, nullptr, 10)); } template<typename T> T get_safe(const nlohmann::json &json, const std::string &field, T default_val) { auto find = json.find(field); if (find != json.end()) return find.value(); else return default_val; } template<> std::string get_safe<std::string>(const nlohmann::json &json, const std::string &field, std::string default_val) { auto find = json.find(field); if (find != json.end() && find.value().is_string()) return find.value(); else return default_val; } static std::string empty_string = ""; static std::string zero_string = "0"; bool discord::operator<(const discord::channel &lhs, const discord::channel &rhs) { return lhs.id < rhs.id; } void discord::from_json(const nlohmann::json &json, discord::channel &c) { c.id = make_snowflake(json.at("id").get<std::string>()); c.guild_id = make_snowflake(get_safe(json, "guild_id", zero_string)); c.user_limit = get_safe(json, "user-limit", 0); c.bitrate = get_safe(json, "bitrate", 0); c.type = json.at("type").get<discord::channel::channel_type>(); c.name = json.at("name").get<std::string>(); } bool discord::operator<(const discord::guild &lhs, const discord::guild &rhs) { return lhs.id < rhs.id; } void discord::from_json(const nlohmann::json &json, discord::guild &g) { g.id = make_snowflake(json.at("id").get<std::string>()); g.owner = make_snowflake(get_safe(json, "owner_id", zero_string)); g.name = json.at("name").get<std::string>(); g.region = json.at("region").get<std::string>(); g.unavailable = json.at("unavailable").get<bool>(); g.members = json.at("members").get<std::set<discord::member>>(); g.channels = json.at("channels").get<std::set<discord::channel>>(); g.voice_states = get_safe<std::set<discord::voice_state>>(json, "voice_states", {}); } bool discord::operator<(const discord::member &lhs, const discord::member &rhs) { return lhs.user.id < rhs.user.id; } void discord::from_json(const nlohmann::json &json, discord::member &m) { m.user = json.at("user").get<discord::user>(); m.nick = get_safe(json, "nick", empty_string); } bool discord::operator<(const discord::user &lhs, const discord::user &rhs) { return lhs.id < rhs.id; } void discord::from_json(const nlohmann::json &json, discord::user &u) { u.id = make_snowflake(get_safe(json, "id", zero_string)); u.discriminator = get_safe(json, "discriminator", empty_string); u.name = get_safe(json, "username", empty_string); } bool discord::operator<(const discord::message &lhs, const discord::message &rhs) { return lhs.id < rhs.id; } void discord::from_json(const nlohmann::json &json, discord::message &m) { m.id = make_snowflake(json.at("id").get<std::string>()); m.channel_id = make_snowflake(json.at("channel_id").get<std::string>()); m.author = json.at("author").get<discord::user>(); m.content = json.at("content").get<std::string>(); m.type = json.at("type").get<discord::message::message_type>(); } bool discord::operator<(const discord::voice_state &lhs, const discord::voice_state &rhs) { return lhs.user_id < rhs.user_id; } void discord::from_json(const nlohmann::json &json, discord::voice_state &v) { v.guild_id = make_snowflake(get_safe(json, "guild_id", zero_string)); v.channel_id = make_snowflake(get_safe(json, "channel_id", zero_string)); v.user_id = make_snowflake(json.at("user_id").get<std::string>()); v.session_id = json.at("session_id").get<std::string>(); v.deaf = get_safe(json, "deaf", false); v.mute = get_safe(json, "mute", false); v.self_deaf = get_safe(json, "self_deaf", false); v.self_mute = get_safe(json, "self_mute", false); v.suppress = get_safe(json, "suppress", false); } void discord::from_json(const nlohmann::json &json, discord::payload &p) { p.op = static_cast<discord::gateway_op>(json.at("op").get<int>()); p.data = json.at("d").get<nlohmann::json>(); if (p.op == discord::gateway_op::dispatch) { p.sequence_num = json.at("s").get<int>(); p.event_name = json.at("t").get<std::string>(); } else { p.sequence_num = -1; p.event_name = {}; } } void discord::from_json(const nlohmann::json &json, discord::voice_payload &vp) { vp.op = static_cast<discord::voice_op>(json.at("op").get<int>()); vp.data = json.at("d"); } void discord::from_json(const nlohmann::json &json, discord::voice_ready &vr) { vr.host = json.at("ip").get<std::string>(); vr.ssrc = json.at("ssrc").get<uint32_t>(); vr.port = json.at("port").get<uint16_t>(); } void discord::from_json(const nlohmann::json &json, discord::voice_session &vs) { vs.mode = json.at("mode").get<std::string>(); vs.secret_key = json.at("secret_key").get<std::vector<uint8_t>>(); } void discord::event::from_json(const nlohmann::json &json, discord::event::hello &h) { h.heartbeat_interval = json.at("heartbeat_interval").get<int>(); } void discord::event::from_json(const nlohmann::json &json, discord::event::ready &r) { r.version = json.at("v").get<int>(); r.user = json.at("user").get<discord::user>(); r.session_id = json.at("session_id").get<std::string>(); } void discord::event::from_json(const nlohmann::json &json, discord::event::voice_server_update &v) { v.guild_id = make_snowflake(json.at("guild_id").get<std::string>()); v.token = json.at("token").get<std::string>(); v.endpoint = json.at("endpoint").get<std::string>(); }
33.721893
98
0.653799
[ "vector" ]
13e5e79cc9f94745269814e00462c37103ffdff4
5,179
hpp
C++
lib/generated/definitions/mask/mask_avx2.hpp
db-tu-dresden/TVL
051261d49f993ce5c70629526038a6f7717055ef
[ "Apache-2.0" ]
2
2022-03-21T23:17:32.000Z
2022-03-22T19:56:17.000Z
lib/generated/definitions/mask/mask_avx2.hpp
db-tu-dresden/TVL
051261d49f993ce5c70629526038a6f7717055ef
[ "Apache-2.0" ]
1
2022-03-31T11:56:21.000Z
2022-03-31T11:56:21.000Z
lib/generated/definitions/mask/mask_avx2.hpp
db-tu-dresden/TVL
051261d49f993ce5c70629526038a6f7717055ef
[ "Apache-2.0" ]
1
2022-03-23T08:38:49.000Z
2022-03-23T08:38:49.000Z
/*==========================================================================* * This file is part of the TVL - a template SIMD library. * * * * Copyright 2022 TVL-Team, Database Research Group TU Dresden * * * * 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 lib/generated/definitions/mask/mask_avx2.hpp * @date 30.03.2022 * @brief Mask related primitives. Implementation for avx2 */ #ifndef TUD_D2RG_TVL_LIB_GENERATED_DEFINITIONS_MASK_MASK_AVX2_HPP #define TUD_D2RG_TVL_LIB_GENERATED_DEFINITIONS_MASK_MASK_AVX2_HPP #include "../../declarations/mask.hpp" namespace tvl { namespace details { /** * @brief: Template specialization of implementation for "to_integral". * @details: * Target Extension: avx2. * Data Type: int64_t * Extension Flags: ['avx'] */ template<ImplementationDegreeOfFreedom Idof> struct to_integral_impl<simd<int64_t, avx2>, Idof> { using Vec = simd< int64_t, avx2 >; static constexpr bool native_supported() { return true; } [[nodiscard]] TVL_FORCE_INLINE static typename Vec::base_type apply( typename Vec::mask_type vec_mask ) { return _mm256_movemask_pd( _mm256_castsi256_pd( vec_mask ) ); } }; } // end of namespace details for template specialization of to_integral_impl for avx2 using int64_t. namespace details { /** * @brief: Template specialization of implementation for "get_msb". * @details: * Target Extension: avx2. * Data Type: int64_t * Extension Flags: ['avx'] */ template<ImplementationDegreeOfFreedom Idof> struct get_msb_impl<simd<int64_t, avx2>, Idof> { using Vec = simd< int64_t, avx2 >; static constexpr bool native_supported() { return true; } [[nodiscard]] TVL_FORCE_INLINE static typename Vec::base_type apply( typename Vec::register_type vec ) { return _mm256_movemask_pd( _mm256_castsi256_pd( vec ) ); } }; } // end of namespace details for template specialization of get_msb_impl for avx2 using int64_t. namespace details { /** * @brief: Template specialization of implementation for "to_vector". * @details: * Target Extension: avx2. * Data Type: int64_t * Extension Flags: ['avx'] */ template<ImplementationDegreeOfFreedom Idof> struct to_vector_impl<simd<int64_t, avx2>, Idof> { using Vec = simd< int64_t, avx2 >; static constexpr bool native_supported() { return true; } [[nodiscard]] TVL_FORCE_INLINE static typename Vec::register_type apply( typename Vec::mask_type mask ) { return mask; //mask is a vector already. } }; } // end of namespace details for template specialization of to_vector_impl for avx2 using int64_t. namespace details { /** * @brief: Template specialization of implementation for "mask_reduce". * @details: * Target Extension: avx2. * Data Type: int64_t * Extension Flags: ['avx'] */ template<ImplementationDegreeOfFreedom Idof> struct mask_reduce_impl<simd<int64_t, avx2>, Idof> { using Vec = simd< int64_t, avx2 >; static constexpr bool native_supported() { return true; } [[nodiscard]] TVL_FORCE_INLINE static typename Vec::base_type apply( typename Vec::base_type mask ) { return mask & 0xF; } }; } // end of namespace details for template specialization of mask_reduce_impl for avx2 using int64_t. } // end of namespace tvl #endif //TUD_D2RG_TVL_LIB_GENERATED_DEFINITIONS_MASK_MASK_AVX2_HPP
42.801653
104
0.533308
[ "vector" ]
13e8501f576e2d3d0e32714e65da5687dfcb4db0
1,620
cc
C++
Geometry/TrackerNumberingBuilder/plugins/CmsTrackerPixelPhase2RingBuilder.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
Geometry/TrackerNumberingBuilder/plugins/CmsTrackerPixelPhase2RingBuilder.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
Geometry/TrackerNumberingBuilder/plugins/CmsTrackerPixelPhase2RingBuilder.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "Geometry/TrackerNumberingBuilder/plugins/CmsTrackerPixelPhase2RingBuilder.h" #include "DetectorDescription/Core/interface/DDFilteredView.h" #include "DetectorDescription/DDCMS/interface/DDFilteredView.h" #include "Geometry/TrackerNumberingBuilder/interface/GeometricDet.h" #include "Geometry/TrackerNumberingBuilder/plugins/ExtractStringFromDDD.h" #include "Geometry/TrackerNumberingBuilder/plugins/CmsDetConstruction.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DataFormats/DetId/interface/DetId.h" #include "Geometry/TrackerNumberingBuilder/interface/trackerStablePhiSort.h" #include <vector> template <class FilteredView> void CmsTrackerPixelPhase2RingBuilder<FilteredView>::buildComponent(FilteredView& fv, GeometricDet* g, const std::string& s) { CmsDetConstruction<FilteredView> theCmsDetConstruction; theCmsDetConstruction.buildComponent(fv, g, s); } template <class FilteredView> void CmsTrackerPixelPhase2RingBuilder<FilteredView>::sortNS(FilteredView& fv, GeometricDet* det) { GeometricDet::ConstGeometricDetContainer& comp = det->components(); //increasing phi taking into account the sub-modules trackerStablePhiSort(comp.begin(), comp.end(), CmsTrackerLevelBuilderHelper::getPhi); for (uint32_t i = 0; i < comp.size(); i++) { det->component(i)->setGeographicalID(i + 1); } } template class CmsTrackerPixelPhase2RingBuilder<DDFilteredView>; template class CmsTrackerPixelPhase2RingBuilder<cms::DDFilteredView>;
45
98
0.750617
[ "geometry", "vector" ]
13e8feb1b820d13b9b225ae51b9cb8393c92a6fc
7,592
cpp
C++
export/windows/obj/src/openfl/errors/Error.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/openfl/errors/Error.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/openfl/errors/Error.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
// Generated by Haxe 3.4.7 #include <hxcpp.h> #ifndef INCLUDED_haxe_CallStack #include <haxe/CallStack.h> #endif #ifndef INCLUDED_haxe_StackItem #include <haxe/StackItem.h> #endif #ifndef INCLUDED_openfl_errors_Error #include <openfl/errors/Error.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_7c7ee06d9b3544d2_24_new,"openfl.errors.Error","new",0xefad98b5,"openfl.errors.Error.new","openfl/errors/Error.hx",24,0x5096467b) HX_LOCAL_STACK_FRAME(_hx_pos_7c7ee06d9b3544d2_38_getStackTrace,"openfl.errors.Error","getStackTrace",0x0bedf2e8,"openfl.errors.Error.getStackTrace","openfl/errors/Error.hx",38,0x5096467b) HX_LOCAL_STACK_FRAME(_hx_pos_7c7ee06d9b3544d2_48_toString,"openfl.errors.Error","toString",0x62f5b437,"openfl.errors.Error.toString","openfl/errors/Error.hx",48,0x5096467b) HX_LOCAL_STACK_FRAME(_hx_pos_7c7ee06d9b3544d2_15_boot,"openfl.errors.Error","boot",0xc051063d,"openfl.errors.Error.boot","openfl/errors/Error.hx",15,0x5096467b) namespace openfl{ namespace errors{ void Error_obj::__construct(::String __o_message,hx::Null< int > __o_id){ ::String message = __o_message.Default(HX_HCSTRING("","\x00","\x00","\x00","\x00")); int id = __o_id.Default(0); HX_STACKFRAME(&_hx_pos_7c7ee06d9b3544d2_24_new) HXLINE( 26) this->message = message; HXLINE( 27) this->errorID = id; HXLINE( 28) this->name = HX_("Error",a8,3b,57,06); } Dynamic Error_obj::__CreateEmpty() { return new Error_obj; } void *Error_obj::_hx_vtable = 0; Dynamic Error_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Error_obj > _hx_result = new Error_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool Error_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x1fc85c4d; } ::String Error_obj::getStackTrace(){ HX_STACKFRAME(&_hx_pos_7c7ee06d9b3544d2_38_getStackTrace) HXDLIN( 38) return ::haxe::CallStack_obj::toString(::haxe::CallStack_obj::exceptionStack()); } HX_DEFINE_DYNAMIC_FUNC0(Error_obj,getStackTrace,return ) ::String Error_obj::toString(){ HX_STACKFRAME(&_hx_pos_7c7ee06d9b3544d2_48_toString) HXDLIN( 48) if (hx::IsNotNull( this->message )) { HXLINE( 50) return this->message; } else { HXLINE( 54) return HX_("Error",a8,3b,57,06); } HXLINE( 48) return null(); } HX_DEFINE_DYNAMIC_FUNC0(Error_obj,toString,return ) ::String Error_obj::DEFAULT_TO_STRING; hx::ObjectPtr< Error_obj > Error_obj::__new(::String __o_message,hx::Null< int > __o_id) { hx::ObjectPtr< Error_obj > __this = new Error_obj(); __this->__construct(__o_message,__o_id); return __this; } hx::ObjectPtr< Error_obj > Error_obj::__alloc(hx::Ctx *_hx_ctx,::String __o_message,hx::Null< int > __o_id) { Error_obj *__this = (Error_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(Error_obj), true, "openfl.errors.Error")); *(void **)__this = Error_obj::_hx_vtable; __this->__construct(__o_message,__o_id); return __this; } Error_obj::Error_obj() { } void Error_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(Error); HX_MARK_MEMBER_NAME(errorID,"errorID"); HX_MARK_MEMBER_NAME(message,"message"); HX_MARK_MEMBER_NAME(name,"name"); HX_MARK_END_CLASS(); } void Error_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(errorID,"errorID"); HX_VISIT_MEMBER_NAME(message,"message"); HX_VISIT_MEMBER_NAME(name,"name"); } hx::Val Error_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"name") ) { return hx::Val( name ); } break; case 7: if (HX_FIELD_EQ(inName,"errorID") ) { return hx::Val( errorID ); } if (HX_FIELD_EQ(inName,"message") ) { return hx::Val( message ); } break; case 8: if (HX_FIELD_EQ(inName,"toString") ) { return hx::Val( toString_dyn() ); } break; case 13: if (HX_FIELD_EQ(inName,"getStackTrace") ) { return hx::Val( getStackTrace_dyn() ); } } return super::__Field(inName,inCallProp); } hx::Val Error_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"name") ) { name=inValue.Cast< ::String >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"errorID") ) { errorID=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"message") ) { message=inValue.Cast< ::String >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void Error_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("errorID","\xa3","\x8d","\x0a","\xea")); outFields->push(HX_HCSTRING("message","\xc7","\x35","\x11","\x9a")); outFields->push(HX_HCSTRING("name","\x4b","\x72","\xff","\x48")); super::__GetFields(outFields); }; #if HXCPP_SCRIPTABLE static hx::StorageInfo Error_obj_sMemberStorageInfo[] = { {hx::fsInt,(int)offsetof(Error_obj,errorID),HX_HCSTRING("errorID","\xa3","\x8d","\x0a","\xea")}, {hx::fsString,(int)offsetof(Error_obj,message),HX_HCSTRING("message","\xc7","\x35","\x11","\x9a")}, {hx::fsString,(int)offsetof(Error_obj,name),HX_HCSTRING("name","\x4b","\x72","\xff","\x48")}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo Error_obj_sStaticStorageInfo[] = { {hx::fsString,(void *) &Error_obj::DEFAULT_TO_STRING,HX_HCSTRING("DEFAULT_TO_STRING","\xf7","\x2d","\xdc","\x05")}, { hx::fsUnknown, 0, null()} }; #endif static ::String Error_obj_sMemberFields[] = { HX_HCSTRING("errorID","\xa3","\x8d","\x0a","\xea"), HX_HCSTRING("message","\xc7","\x35","\x11","\x9a"), HX_HCSTRING("name","\x4b","\x72","\xff","\x48"), HX_HCSTRING("getStackTrace","\x53","\x8e","\xb0","\x85"), HX_HCSTRING("toString","\xac","\xd0","\x6e","\x38"), ::String(null()) }; static void Error_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(Error_obj::__mClass,"__mClass"); HX_MARK_MEMBER_NAME(Error_obj::DEFAULT_TO_STRING,"DEFAULT_TO_STRING"); }; #ifdef HXCPP_VISIT_ALLOCS static void Error_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(Error_obj::__mClass,"__mClass"); HX_VISIT_MEMBER_NAME(Error_obj::DEFAULT_TO_STRING,"DEFAULT_TO_STRING"); }; #endif hx::Class Error_obj::__mClass; static ::String Error_obj_sStaticFields[] = { HX_HCSTRING("DEFAULT_TO_STRING","\xf7","\x2d","\xdc","\x05"), ::String(null()) }; void Error_obj::__register() { hx::Object *dummy = new Error_obj; Error_obj::_hx_vtable = *(void **)dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("openfl.errors.Error","\x43","\x1a","\x04","\x80"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = Error_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(Error_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(Error_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< Error_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = Error_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Error_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Error_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } void Error_obj::__boot() { { HX_STACKFRAME(&_hx_pos_7c7ee06d9b3544d2_15_boot) HXDLIN( 15) DEFAULT_TO_STRING = HX_("Error",a8,3b,57,06); } } } // end namespace openfl } // end namespace errors
34.352941
187
0.721022
[ "object" ]
13ec1e9e9cff88821d174cdefd0e8f4c1f639783
1,467
cpp
C++
GraphConnectedComponents.cpp
mraggi/FuzzyLogicEcology
91fbd1a0a97abf41da110fefcc93001ac663cf02
[ "Apache-2.0" ]
3
2017-06-27T21:45:59.000Z
2022-03-02T19:26:32.000Z
GraphConnectedComponents.cpp
mraggi/FuzzyLogicEcology
91fbd1a0a97abf41da110fefcc93001ac663cf02
[ "Apache-2.0" ]
null
null
null
GraphConnectedComponents.cpp
mraggi/FuzzyLogicEcology
91fbd1a0a97abf41da110fefcc93001ac663cf02
[ "Apache-2.0" ]
null
null
null
#include "GraphConnectedComponents.hpp" void DFSConnectedComponentUtil(const Graph& G, std::vector<int>& coloring, vertex_t v, int color) { coloring[v] = color; for (auto u : G.neighbors(v)) { if (coloring[u] == -1) DFSConnectedComponentUtil(G,coloring,u,color); } } int num_connected_components(const Graph& G) { std::vector<int> coloring(G.num_vertices(),-1); coloring[0] = 0; int color = 0; for (vertex_t v = 0; v < G.num_vertices(); ++v) { if (coloring[v] == -1) { DFSConnectedComponentUtil(G,coloring, v, color); ++color; } } return color; } std::vector<int> connected_components_coloring(const Graph& G) { std::vector<int> coloring(G.num_vertices(),-1); int color = 0; for (vertex_t v = 0; v < G.num_vertices(); ++v) { if (coloring[v] == -1) { DFSConnectedComponentUtil(G,coloring, v, color); ++color; } } return coloring; } std::vector<std::vector<vertex_t>> connected_components(const Graph& G) { auto coloring = connected_components_coloring(G); std::vector<std::vector<vertex_t>> cc(*std::max_element(coloring.begin(), coloring.end())+1); for (vertex_t v = 0; v < G.num_vertices(); ++v) { cc[coloring[v]].push_back(v); } return cc; } bool is_connected(const Graph& G) { std::vector<int> coloring(G.num_vertices(),-1); coloring[0] = 0; DFSConnectedComponentUtil(G,coloring, 0, 0); for (vertex_t v = 1; v < G.num_vertices(); ++v) { if (coloring[v] == -1) return false; } return true; }
21.895522
97
0.65985
[ "vector" ]
13f11cc4a297f0af323ba3f4c09cb57d4f8a5b03
9,276
cpp
C++
src/RcppExports.cpp
rmaestre/variableStars
26a0a8288050127fac620ebb62b545004a80b4dc
[ "MIT" ]
1
2018-11-16T23:50:37.000Z
2018-11-16T23:50:37.000Z
src/RcppExports.cpp
rmaestre/variableStars
26a0a8288050127fac620ebb62b545004a80b4dc
[ "MIT" ]
null
null
null
src/RcppExports.cpp
rmaestre/variableStars
26a0a8288050127fac620ebb62b545004a80b4dc
[ "MIT" ]
1
2018-12-19T22:40:08.000Z
2018-12-19T22:40:08.000Z
// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include <RcppArmadillo.h> #include <Rcpp.h> using namespace Rcpp; // seqIntegers NumericVector seqIntegers(int first, int last); RcppExport SEXP _variableStars_seqIntegers(SEXP firstSEXP, SEXP lastSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< int >::type first(firstSEXP); Rcpp::traits::input_parameter< int >::type last(lastSEXP); rcpp_result_gen = Rcpp::wrap(seqIntegers(first, last)); return rcpp_result_gen; END_RCPP } // vectorRev NumericVector vectorRev(NumericVector vector); RcppExport SEXP _variableStars_vectorRev(SEXP vectorSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericVector >::type vector(vectorSEXP); rcpp_result_gen = Rcpp::wrap(vectorRev(vector)); return rcpp_result_gen; END_RCPP } // computeFft arma::cx_vec computeFft(arma::vec v); RcppExport SEXP _variableStars_computeFft(SEXP vSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< arma::vec >::type v(vSEXP); rcpp_result_gen = Rcpp::wrap(computeFft(v)); return rcpp_result_gen; END_RCPP } // calculateSpectrum List calculateSpectrum(arma::vec time, arma::vec x); RcppExport SEXP _variableStars_calculateSpectrum(SEXP timeSEXP, SEXP xSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< arma::vec >::type time(timeSEXP); Rcpp::traits::input_parameter< arma::vec >::type x(xSEXP); rcpp_result_gen = Rcpp::wrap(calculateSpectrum(time, x)); return rcpp_result_gen; END_RCPP } // apodization arma::vec apodization(arma::vec frequences, String filter); RcppExport SEXP _variableStars_apodization(SEXP frequencesSEXP, SEXP filterSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< arma::vec >::type frequences(frequencesSEXP); Rcpp::traits::input_parameter< String >::type filter(filterSEXP); rcpp_result_gen = Rcpp::wrap(apodization(frequences, filter)); return rcpp_result_gen; END_RCPP } // differences arma::vec differences(arma::vec frequences); RcppExport SEXP _variableStars_differences(SEXP frequencesSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< arma::vec >::type frequences(frequencesSEXP); rcpp_result_gen = Rcpp::wrap(differences(frequences)); return rcpp_result_gen; END_RCPP } // diffHistogram List diffHistogram(arma::vec frequences, double dnu); RcppExport SEXP _variableStars_diffHistogram(SEXP frequencesSEXP, SEXP dnuSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< arma::vec >::type frequences(frequencesSEXP); Rcpp::traits::input_parameter< double >::type dnu(dnuSEXP); rcpp_result_gen = Rcpp::wrap(diffHistogram(frequences, dnu)); return rcpp_result_gen; END_RCPP } // apodizationFt List apodizationFt(arma::vec frequences, String filter); RcppExport SEXP _variableStars_apodizationFt(SEXP frequencesSEXP, SEXP filterSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< arma::vec >::type frequences(frequencesSEXP); Rcpp::traits::input_parameter< String >::type filter(filterSEXP); rcpp_result_gen = Rcpp::wrap(apodizationFt(frequences, filter)); return rcpp_result_gen; END_RCPP } // adjacentDifferences arma::vec adjacentDifferences(arma::vec x); RcppExport SEXP _variableStars_adjacentDifferences(SEXP xSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< arma::vec >::type x(xSEXP); rcpp_result_gen = Rcpp::wrap(adjacentDifferences(x)); return rcpp_result_gen; END_RCPP } // findPeaks arma::uvec findPeaks(arma::vec x); RcppExport SEXP _variableStars_findPeaks(SEXP xSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< arma::vec >::type x(xSEXP); rcpp_result_gen = Rcpp::wrap(findPeaks(x)); return rcpp_result_gen; END_RCPP } // calculateRange arma::ivec calculateRange(int nElements, int nFrequencies); RcppExport SEXP _variableStars_calculateRange(SEXP nElementsSEXP, SEXP nFrequenciesSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< int >::type nElements(nElementsSEXP); Rcpp::traits::input_parameter< int >::type nFrequencies(nFrequenciesSEXP); rcpp_result_gen = Rcpp::wrap(calculateRange(nElements, nFrequencies)); return rcpp_result_gen; END_RCPP } // crosscorrelation List crosscorrelation(arma::vec frequencies, String type, bool plot); RcppExport SEXP _variableStars_crosscorrelation(SEXP frequenciesSEXP, SEXP typeSEXP, SEXP plotSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< arma::vec >::type frequencies(frequenciesSEXP); Rcpp::traits::input_parameter< String >::type type(typeSEXP); Rcpp::traits::input_parameter< bool >::type plot(plotSEXP); rcpp_result_gen = Rcpp::wrap(crosscorrelation(frequencies, type, plot)); return rcpp_result_gen; END_RCPP } // echelle List echelle(arma::vec frequencies, arma::vec amplitudes, double dnu); RcppExport SEXP _variableStars_echelle(SEXP frequenciesSEXP, SEXP amplitudesSEXP, SEXP dnuSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< arma::vec >::type frequencies(frequenciesSEXP); Rcpp::traits::input_parameter< arma::vec >::type amplitudes(amplitudesSEXP); Rcpp::traits::input_parameter< double >::type dnu(dnuSEXP); rcpp_result_gen = Rcpp::wrap(echelle(frequencies, amplitudes, dnu)); return rcpp_result_gen; END_RCPP } // process List process(arma::vec frequency, arma::vec amplitude, String filter, double gRegimen, double numFrequencies, double maxDnu, double minDnu, double dnuGuessError, double dnuValue, bool dnuEstimation, bool debug, bool processFirstRangeOnly); RcppExport SEXP _variableStars_process(SEXP frequencySEXP, SEXP amplitudeSEXP, SEXP filterSEXP, SEXP gRegimenSEXP, SEXP numFrequenciesSEXP, SEXP maxDnuSEXP, SEXP minDnuSEXP, SEXP dnuGuessErrorSEXP, SEXP dnuValueSEXP, SEXP dnuEstimationSEXP, SEXP debugSEXP, SEXP processFirstRangeOnlySEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< arma::vec >::type frequency(frequencySEXP); Rcpp::traits::input_parameter< arma::vec >::type amplitude(amplitudeSEXP); Rcpp::traits::input_parameter< String >::type filter(filterSEXP); Rcpp::traits::input_parameter< double >::type gRegimen(gRegimenSEXP); Rcpp::traits::input_parameter< double >::type numFrequencies(numFrequenciesSEXP); Rcpp::traits::input_parameter< double >::type maxDnu(maxDnuSEXP); Rcpp::traits::input_parameter< double >::type minDnu(minDnuSEXP); Rcpp::traits::input_parameter< double >::type dnuGuessError(dnuGuessErrorSEXP); Rcpp::traits::input_parameter< double >::type dnuValue(dnuValueSEXP); Rcpp::traits::input_parameter< bool >::type dnuEstimation(dnuEstimationSEXP); Rcpp::traits::input_parameter< bool >::type debug(debugSEXP); Rcpp::traits::input_parameter< bool >::type processFirstRangeOnly(processFirstRangeOnlySEXP); rcpp_result_gen = Rcpp::wrap(process(frequency, amplitude, filter, gRegimen, numFrequencies, maxDnu, minDnu, dnuGuessError, dnuValue, dnuEstimation, debug, processFirstRangeOnly)); return rcpp_result_gen; END_RCPP } static const R_CallMethodDef CallEntries[] = { {"_variableStars_seqIntegers", (DL_FUNC) &_variableStars_seqIntegers, 2}, {"_variableStars_vectorRev", (DL_FUNC) &_variableStars_vectorRev, 1}, {"_variableStars_computeFft", (DL_FUNC) &_variableStars_computeFft, 1}, {"_variableStars_calculateSpectrum", (DL_FUNC) &_variableStars_calculateSpectrum, 2}, {"_variableStars_apodization", (DL_FUNC) &_variableStars_apodization, 2}, {"_variableStars_differences", (DL_FUNC) &_variableStars_differences, 1}, {"_variableStars_diffHistogram", (DL_FUNC) &_variableStars_diffHistogram, 2}, {"_variableStars_apodizationFt", (DL_FUNC) &_variableStars_apodizationFt, 2}, {"_variableStars_adjacentDifferences", (DL_FUNC) &_variableStars_adjacentDifferences, 1}, {"_variableStars_findPeaks", (DL_FUNC) &_variableStars_findPeaks, 1}, {"_variableStars_calculateRange", (DL_FUNC) &_variableStars_calculateRange, 2}, {"_variableStars_crosscorrelation", (DL_FUNC) &_variableStars_crosscorrelation, 3}, {"_variableStars_echelle", (DL_FUNC) &_variableStars_echelle, 3}, {"_variableStars_process", (DL_FUNC) &_variableStars_process, 12}, {NULL, NULL, 0} }; RcppExport void R_init_variableStars(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); }
44.811594
290
0.770052
[ "vector" ]
13f5a2670163ad3a9d39f4833062fd48f6560bb1
649
cpp
C++
GEC_2/MarioBaseProject/QuestObject.cpp
nerolileung/cgd_year1
211e91c37831a388b1abe1a1cc496716a4e9ca44
[ "MIT" ]
null
null
null
GEC_2/MarioBaseProject/QuestObject.cpp
nerolileung/cgd_year1
211e91c37831a388b1abe1a1cc496716a4e9ca44
[ "MIT" ]
null
null
null
GEC_2/MarioBaseProject/QuestObject.cpp
nerolileung/cgd_year1
211e91c37831a388b1abe1a1cc496716a4e9ca44
[ "MIT" ]
1
2019-12-09T22:41:49.000Z
2019-12-09T22:41:49.000Z
#include "QuestObject.h" QuestObject::QuestObject(SDL_Renderer* renderer, int mapX, int mapY){ mRenderer = renderer; mScreenPosition = Vector2D(-32, -32); mMapPosition = Vector2D(mapX, mapY); } QuestObject::~QuestObject(){ mRenderer = nullptr; delete mTexture; mTexture = nullptr; } void QuestObject::Render() { mTexture->Render(mScreenPosition,SDL_FLIP_NONE); } void QuestObject::SetScreenPosition(int x, int y) { mScreenPosition = Vector2D(x, y); } Rect2D QuestObject::GetCollisionBox() { return Rect2D{(float)mScreenPosition.x,(float)mScreenPosition.y,(float)mTexture->GetWidth(),(float)mTexture->GetHeight()}; }
28.217391
124
0.725732
[ "render" ]
13f5a67d279eceac003fdbf88fee9be79bb0bdab
2,288
cpp
C++
src/utils.cpp
sushobhit27/cppPyUtils
3365ea312b76726e22c774a22f2f5a663f866826
[ "MIT" ]
null
null
null
src/utils.cpp
sushobhit27/cppPyUtils
3365ea312b76726e22c774a22f2f5a663f866826
[ "MIT" ]
null
null
null
src/utils.cpp
sushobhit27/cppPyUtils
3365ea312b76726e22c774a22f2f5a663f866826
[ "MIT" ]
null
null
null
#include "utils.hpp" void check_bounds(size_t beg, size_t end) { if (beg < 0 or end < 0) throw; else if (beg > end) throw; } std::vector<int> range_impl(int start, int end, int step) { std::vector<int> vec; if ((step > 0) && (start > end)) return vec; else if ((step < 0) && (start < end)) return vec; size_t count = abs((start - end)/step); vec.reserve(count + 1); for(int i = start; ;) { if (((step > 0) && (i < end)) || ((step < 0) && (i > end))) { vec.push_back(i); i += step; } else break; } return vec; } std::vector<int> range(int end) { int start = 0; int step = 1; return range_impl(start, end, step); } std::vector<int> range(int start, int end, int step) { return range_impl(start, end, step); } size_t rfind(const std::string &str, const std::string &substr, size_t beg, size_t end) { if (end == std::string::npos) end = str.length() - 1; if (substr.empty()) return std::string::npos; else { while(beg <= end) { size_t found = str.find_last_of(substr[0], end); if (found != std::string::npos) { if (str.substr(found, substr.length()) == substr) return found; else end = found - 1; } else break; } } return std::string::npos; } std::string swapcase(std::string str) { std::string temp = str; for(auto &ch : temp) { int val = static_cast<int>(ch); if (val >= 65 && val <= 90) ch = static_cast<char>(val + 32); else if (val >= 97 && val <= 122) ch = static_cast<char>(val - 32); } return temp; } std::string zfill(const std::string &str, size_t width) { std::string temp; if (str.empty()) return str; if (str.length() >= width || str.length() <= 1) return str; if (str[0] == '-' || str[0] == '+') temp = str[0] + std::string(width - str.length(), '0') + str.substr(1); else temp = std::string(width - str.length(), '0') + str; return temp; } bool startswith(const std::string &substr, const std::string &str, size_t beg, size_t end) { if (str.substr(beg, end).find(substr) == 0) return true; return false; } bool endswith(const std::string &substr, const std::string &str, size_t beg, size_t end) { if (str.substr(beg, end).rfind(substr) + substr.length() == str.substr(beg, end).length()) return true; return false; }
18.754098
91
0.593969
[ "vector" ]
13f5c155a813540e69c2b48fda761739d205f8c1
21,125
cpp
C++
src/compiler/Parser/RQLLexer.cpp
michalwidera/abracadabradb
13d4f66454b3b6af7e8353bd10186409230634e2
[ "MIT" ]
2
2019-12-04T16:51:14.000Z
2020-01-09T15:13:13.000Z
src/compiler/Parser/RQLLexer.cpp
michalwidera/abracadabradb
13d4f66454b3b6af7e8353bd10186409230634e2
[ "MIT" ]
9
2019-12-07T21:21:41.000Z
2020-01-17T16:44:36.000Z
src/compiler/Parser/RQLLexer.cpp
michalwidera/abracadabradb
13d4f66454b3b6af7e8353bd10186409230634e2
[ "MIT" ]
null
null
null
// Generated from RQL.g4 by ANTLR 4.10.1 #include "RQLLexer.h" using namespace antlr4; using namespace antlr4; namespace { struct RQLLexerStaticData final { RQLLexerStaticData(std::vector<std::string> ruleNames, std::vector<std::string> channelNames, std::vector<std::string> modeNames, std::vector<std::string> literalNames, std::vector<std::string> symbolicNames) : ruleNames(std::move(ruleNames)), channelNames(std::move(channelNames)), modeNames(std::move(modeNames)), literalNames(std::move(literalNames)), symbolicNames(std::move(symbolicNames)), vocabulary(this->literalNames, this->symbolicNames) {} RQLLexerStaticData(const RQLLexerStaticData&) = delete; RQLLexerStaticData(RQLLexerStaticData&&) = delete; RQLLexerStaticData& operator=(const RQLLexerStaticData&) = delete; RQLLexerStaticData& operator=(RQLLexerStaticData&&) = delete; std::vector<antlr4::dfa::DFA> decisionToDFA; antlr4::atn::PredictionContextCache sharedContextCache; const std::vector<std::string> ruleNames; const std::vector<std::string> channelNames; const std::vector<std::string> modeNames; const std::vector<std::string> literalNames; const std::vector<std::string> symbolicNames; const antlr4::dfa::Vocabulary vocabulary; antlr4::atn::SerializedATNView serializedATN; std::unique_ptr<antlr4::atn::ATN> atn; }; std::once_flag rqllexerLexerOnceFlag; RQLLexerStaticData *rqllexerLexerStaticData = nullptr; void rqllexerLexerInitialize() { assert(rqllexerLexerStaticData == nullptr); auto staticData = std::make_unique<RQLLexerStaticData>( std::vector<std::string>{ "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", "T__7", "T__8", "T__9", "T__10", "T__11", "T__12", "T__13", "T__14", "T__15", "T__16", "T__17", "T__18", "T__19", "STRING_T", "BYTEARRAY_T", "INTARRAY_T", "BYTE_T", "UNSIGNED_T", "INTEGER_T", "FLOAT_T", "SELECT", "STREAM", "FROM", "DECLARE", "FILE", "STORAGE", "MIN", "MAX", "AVG", "SUMC", "ID", "STRING", "FLOAT", "DECIMAL", "REAL", "EQUAL", "GREATER", "LESS", "EXCLAMATION", "DOUBLE_BAR", "DOT", "UNDERLINE", "AT", "SHARP", "AND", "MOD", "DOLLAR", "COMMA", "SEMI", "COLON", "DOUBLE_COLON", "STAR", "DIVIDE", "PLUS", "MINUS", "BIT_NOT", "BIT_OR", "BIT_XOR", "SPACE", "COMMENT", "LINE_COMMENT", "LETTER", "DEC_DOT_DEC", "HEX_DIGIT", "DEC_DIGIT" }, std::vector<std::string>{ "DEFAULT_TOKEN_CHANNEL", "HIDDEN" }, std::vector<std::string>{ "DEFAULT_MODE" }, std::vector<std::string>{ "", "'['", "']'", "'('", "')'", "'Sqrt'", "'Ceil'", "'Abs'", "'Floor'", "'Sign'", "'Chr'", "'Length'", "'ToNumber'", "'ToTimeStamp'", "'FloatCast'", "'InstCast'", "'Count'", "'Crc'", "'Sum'", "'IsZero'", "'IsNonZero'", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "'='", "'>'", "'<'", "'!'", "'||'", "'.'", "'_'", "'@'", "'#'", "'&'", "'%'", "'$'", "','", "';'", "':'", "'::'", "'*'", "'/'", "'+'", "'-'", "'~'", "'|'", "'^'" }, std::vector<std::string>{ "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "STRING_T", "BYTEARRAY_T", "INTARRAY_T", "BYTE_T", "UNSIGNED_T", "INTEGER_T", "FLOAT_T", "SELECT", "STREAM", "FROM", "DECLARE", "FILE", "STORAGE", "MIN", "MAX", "AVG", "SUMC", "ID", "STRING", "FLOAT", "DECIMAL", "REAL", "EQUAL", "GREATER", "LESS", "EXCLAMATION", "DOUBLE_BAR", "DOT", "UNDERLINE", "AT", "SHARP", "AND", "MOD", "DOLLAR", "COMMA", "SEMI", "COLON", "DOUBLE_COLON", "STAR", "DIVIDE", "PLUS", "MINUS", "BIT_NOT", "BIT_OR", "BIT_XOR", "SPACE", "COMMENT", "LINE_COMMENT" } ); static const int32_t serializedATNSegment[] = { 4,0,68,625,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7, 6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,13,7,13,2,14, 7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,19,2,20,7,20,2,21, 7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2,26,7,26,2,27,7,27,2,28, 7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7,32,2,33,7,33,2,34,7,34,2,35, 7,35,2,36,7,36,2,37,7,37,2,38,7,38,2,39,7,39,2,40,7,40,2,41,7,41,2,42, 7,42,2,43,7,43,2,44,7,44,2,45,7,45,2,46,7,46,2,47,7,47,2,48,7,48,2,49, 7,49,2,50,7,50,2,51,7,51,2,52,7,52,2,53,7,53,2,54,7,54,2,55,7,55,2,56, 7,56,2,57,7,57,2,58,7,58,2,59,7,59,2,60,7,60,2,61,7,61,2,62,7,62,2,63, 7,63,2,64,7,64,2,65,7,65,2,66,7,66,2,67,7,67,2,68,7,68,2,69,7,69,2,70, 7,70,2,71,7,71,1,0,1,0,1,1,1,1,1,2,1,2,1,3,1,3,1,4,1,4,1,4,1,4,1,4,1, 5,1,5,1,5,1,5,1,5,1,6,1,6,1,6,1,6,1,7,1,7,1,7,1,7,1,7,1,7,1,8,1,8,1,8, 1,8,1,8,1,9,1,9,1,9,1,9,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,11,1,11, 1,11,1,11,1,11,1,11,1,11,1,11,1,11,1,12,1,12,1,12,1,12,1,12,1,12,1,12, 1,12,1,12,1,12,1,12,1,12,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13, 1,13,1,14,1,14,1,14,1,14,1,14,1,14,1,14,1,14,1,14,1,15,1,15,1,15,1,15, 1,15,1,15,1,16,1,16,1,16,1,16,1,17,1,17,1,17,1,17,1,18,1,18,1,18,1,18, 1,18,1,18,1,18,1,19,1,19,1,19,1,19,1,19,1,19,1,19,1,19,1,19,1,19,1,20, 1,20,1,20,1,20,1,20,1,20,1,20,1,20,1,20,1,20,1,20,1,20,3,20,273,8,20, 1,21,1,21,1,21,1,21,1,21,1,21,1,21,1,21,1,21,1,21,1,21,1,21,1,21,1,21, 1,21,1,21,1,21,1,21,3,21,293,8,21,1,22,1,22,1,22,1,22,1,22,1,22,1,22, 1,22,1,22,1,22,1,22,1,22,1,22,1,22,1,22,1,22,3,22,311,8,22,1,23,1,23, 1,23,1,23,1,23,1,23,1,23,1,23,3,23,321,8,23,1,24,1,24,1,24,1,24,1,24, 1,24,1,24,1,24,3,24,331,8,24,1,25,1,25,1,25,1,25,1,25,1,25,1,25,1,25, 1,25,1,25,1,25,1,25,1,25,1,25,3,25,347,8,25,1,26,1,26,1,26,1,26,1,26, 1,26,1,26,1,26,1,26,1,26,3,26,359,8,26,1,27,1,27,1,27,1,27,1,27,1,27, 1,27,1,27,1,27,1,27,1,27,1,27,3,27,373,8,27,1,28,1,28,1,28,1,28,1,28, 1,28,1,28,1,28,1,28,1,28,1,28,1,28,3,28,387,8,28,1,29,1,29,1,29,1,29, 1,29,1,29,1,29,1,29,3,29,397,8,29,1,30,1,30,1,30,1,30,1,30,1,30,1,30, 1,30,1,30,1,30,1,30,1,30,1,30,1,30,3,30,413,8,30,1,31,1,31,1,31,1,31, 1,31,1,31,1,31,1,31,3,31,423,8,31,1,32,1,32,1,32,1,32,1,32,1,32,1,32, 1,32,1,32,1,32,1,32,1,32,1,32,1,32,3,32,439,8,32,1,33,1,33,1,33,1,33, 1,33,1,33,3,33,447,8,33,1,34,1,34,1,34,1,34,1,34,1,34,3,34,455,8,34,1, 35,1,35,1,35,1,35,1,35,1,35,3,35,463,8,35,1,36,1,36,1,36,1,36,1,36,1, 36,1,36,1,36,3,36,473,8,36,1,37,1,37,5,37,477,8,37,10,37,12,37,480,9, 37,1,38,1,38,1,38,1,38,5,38,486,8,38,10,38,12,38,489,9,38,1,38,1,38,1, 39,1,39,1,40,4,40,496,8,40,11,40,12,40,497,1,41,1,41,3,41,502,8,41,1, 41,1,41,3,41,506,8,41,1,41,4,41,509,8,41,11,41,12,41,510,1,42,1,42,1, 43,1,43,1,44,1,44,1,45,1,45,1,46,1,46,1,46,1,47,1,47,1,48,1,48,1,49,1, 49,1,50,1,50,1,51,1,51,1,52,1,52,1,53,1,53,1,54,1,54,1,55,1,55,1,56,1, 56,1,57,1,57,1,57,1,58,1,58,1,59,1,59,1,60,1,60,1,61,1,61,1,62,1,62,1, 63,1,63,1,64,1,64,1,65,4,65,562,8,65,11,65,12,65,563,1,65,1,65,1,66,1, 66,1,66,1,66,1,66,5,66,573,8,66,10,66,12,66,576,9,66,1,66,1,66,1,66,1, 66,1,66,1,67,1,67,1,67,1,67,5,67,587,8,67,10,67,12,67,590,9,67,1,67,1, 67,1,68,1,68,1,69,4,69,597,8,69,11,69,12,69,598,1,69,1,69,4,69,603,8, 69,11,69,12,69,604,1,69,4,69,608,8,69,11,69,12,69,609,1,69,1,69,1,69, 1,69,4,69,616,8,69,11,69,12,69,617,3,69,620,8,69,1,70,1,70,1,71,1,71, 1,574,0,72,1,1,3,2,5,3,7,4,9,5,11,6,13,7,15,8,17,9,19,10,21,11,23,12, 25,13,27,14,29,15,31,16,33,17,35,18,37,19,39,20,41,21,43,22,45,23,47, 24,49,25,51,26,53,27,55,28,57,29,59,30,61,31,63,32,65,33,67,34,69,35, 71,36,73,37,75,38,77,39,79,40,81,41,83,42,85,43,87,44,89,45,91,46,93, 47,95,48,97,49,99,50,101,51,103,52,105,53,107,54,109,55,111,56,113,57, 115,58,117,59,119,60,121,61,123,62,125,63,127,64,129,65,131,66,133,67, 135,68,137,0,139,0,141,0,143,0,1,0,9,2,0,65,90,97,122,5,0,36,36,48,57, 65,90,95,95,97,122,1,0,39,39,2,0,43,43,45,45,3,0,9,10,13,13,32,32,2,0, 10,10,13,13,2,0,65,90,95,95,2,0,48,57,65,70,1,0,48,57,654,0,1,1,0,0,0, 0,3,1,0,0,0,0,5,1,0,0,0,0,7,1,0,0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0, 0,0,0,15,1,0,0,0,0,17,1,0,0,0,0,19,1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0, 0,25,1,0,0,0,0,27,1,0,0,0,0,29,1,0,0,0,0,31,1,0,0,0,0,33,1,0,0,0,0,35, 1,0,0,0,0,37,1,0,0,0,0,39,1,0,0,0,0,41,1,0,0,0,0,43,1,0,0,0,0,45,1,0, 0,0,0,47,1,0,0,0,0,49,1,0,0,0,0,51,1,0,0,0,0,53,1,0,0,0,0,55,1,0,0,0, 0,57,1,0,0,0,0,59,1,0,0,0,0,61,1,0,0,0,0,63,1,0,0,0,0,65,1,0,0,0,0,67, 1,0,0,0,0,69,1,0,0,0,0,71,1,0,0,0,0,73,1,0,0,0,0,75,1,0,0,0,0,77,1,0, 0,0,0,79,1,0,0,0,0,81,1,0,0,0,0,83,1,0,0,0,0,85,1,0,0,0,0,87,1,0,0,0, 0,89,1,0,0,0,0,91,1,0,0,0,0,93,1,0,0,0,0,95,1,0,0,0,0,97,1,0,0,0,0,99, 1,0,0,0,0,101,1,0,0,0,0,103,1,0,0,0,0,105,1,0,0,0,0,107,1,0,0,0,0,109, 1,0,0,0,0,111,1,0,0,0,0,113,1,0,0,0,0,115,1,0,0,0,0,117,1,0,0,0,0,119, 1,0,0,0,0,121,1,0,0,0,0,123,1,0,0,0,0,125,1,0,0,0,0,127,1,0,0,0,0,129, 1,0,0,0,0,131,1,0,0,0,0,133,1,0,0,0,0,135,1,0,0,0,1,145,1,0,0,0,3,147, 1,0,0,0,5,149,1,0,0,0,7,151,1,0,0,0,9,153,1,0,0,0,11,158,1,0,0,0,13,163, 1,0,0,0,15,167,1,0,0,0,17,173,1,0,0,0,19,178,1,0,0,0,21,182,1,0,0,0,23, 189,1,0,0,0,25,198,1,0,0,0,27,210,1,0,0,0,29,220,1,0,0,0,31,229,1,0,0, 0,33,235,1,0,0,0,35,239,1,0,0,0,37,243,1,0,0,0,39,250,1,0,0,0,41,272, 1,0,0,0,43,292,1,0,0,0,45,310,1,0,0,0,47,320,1,0,0,0,49,330,1,0,0,0,51, 346,1,0,0,0,53,358,1,0,0,0,55,372,1,0,0,0,57,386,1,0,0,0,59,396,1,0,0, 0,61,412,1,0,0,0,63,422,1,0,0,0,65,438,1,0,0,0,67,446,1,0,0,0,69,454, 1,0,0,0,71,462,1,0,0,0,73,472,1,0,0,0,75,474,1,0,0,0,77,481,1,0,0,0,79, 492,1,0,0,0,81,495,1,0,0,0,83,501,1,0,0,0,85,512,1,0,0,0,87,514,1,0,0, 0,89,516,1,0,0,0,91,518,1,0,0,0,93,520,1,0,0,0,95,523,1,0,0,0,97,525, 1,0,0,0,99,527,1,0,0,0,101,529,1,0,0,0,103,531,1,0,0,0,105,533,1,0,0, 0,107,535,1,0,0,0,109,537,1,0,0,0,111,539,1,0,0,0,113,541,1,0,0,0,115, 543,1,0,0,0,117,546,1,0,0,0,119,548,1,0,0,0,121,550,1,0,0,0,123,552,1, 0,0,0,125,554,1,0,0,0,127,556,1,0,0,0,129,558,1,0,0,0,131,561,1,0,0,0, 133,567,1,0,0,0,135,582,1,0,0,0,137,593,1,0,0,0,139,619,1,0,0,0,141,621, 1,0,0,0,143,623,1,0,0,0,145,146,5,91,0,0,146,2,1,0,0,0,147,148,5,93,0, 0,148,4,1,0,0,0,149,150,5,40,0,0,150,6,1,0,0,0,151,152,5,41,0,0,152,8, 1,0,0,0,153,154,5,83,0,0,154,155,5,113,0,0,155,156,5,114,0,0,156,157, 5,116,0,0,157,10,1,0,0,0,158,159,5,67,0,0,159,160,5,101,0,0,160,161,5, 105,0,0,161,162,5,108,0,0,162,12,1,0,0,0,163,164,5,65,0,0,164,165,5,98, 0,0,165,166,5,115,0,0,166,14,1,0,0,0,167,168,5,70,0,0,168,169,5,108,0, 0,169,170,5,111,0,0,170,171,5,111,0,0,171,172,5,114,0,0,172,16,1,0,0, 0,173,174,5,83,0,0,174,175,5,105,0,0,175,176,5,103,0,0,176,177,5,110, 0,0,177,18,1,0,0,0,178,179,5,67,0,0,179,180,5,104,0,0,180,181,5,114,0, 0,181,20,1,0,0,0,182,183,5,76,0,0,183,184,5,101,0,0,184,185,5,110,0,0, 185,186,5,103,0,0,186,187,5,116,0,0,187,188,5,104,0,0,188,22,1,0,0,0, 189,190,5,84,0,0,190,191,5,111,0,0,191,192,5,78,0,0,192,193,5,117,0,0, 193,194,5,109,0,0,194,195,5,98,0,0,195,196,5,101,0,0,196,197,5,114,0, 0,197,24,1,0,0,0,198,199,5,84,0,0,199,200,5,111,0,0,200,201,5,84,0,0, 201,202,5,105,0,0,202,203,5,109,0,0,203,204,5,101,0,0,204,205,5,83,0, 0,205,206,5,116,0,0,206,207,5,97,0,0,207,208,5,109,0,0,208,209,5,112, 0,0,209,26,1,0,0,0,210,211,5,70,0,0,211,212,5,108,0,0,212,213,5,111,0, 0,213,214,5,97,0,0,214,215,5,116,0,0,215,216,5,67,0,0,216,217,5,97,0, 0,217,218,5,115,0,0,218,219,5,116,0,0,219,28,1,0,0,0,220,221,5,73,0,0, 221,222,5,110,0,0,222,223,5,115,0,0,223,224,5,116,0,0,224,225,5,67,0, 0,225,226,5,97,0,0,226,227,5,115,0,0,227,228,5,116,0,0,228,30,1,0,0,0, 229,230,5,67,0,0,230,231,5,111,0,0,231,232,5,117,0,0,232,233,5,110,0, 0,233,234,5,116,0,0,234,32,1,0,0,0,235,236,5,67,0,0,236,237,5,114,0,0, 237,238,5,99,0,0,238,34,1,0,0,0,239,240,5,83,0,0,240,241,5,117,0,0,241, 242,5,109,0,0,242,36,1,0,0,0,243,244,5,73,0,0,244,245,5,115,0,0,245,246, 5,90,0,0,246,247,5,101,0,0,247,248,5,114,0,0,248,249,5,111,0,0,249,38, 1,0,0,0,250,251,5,73,0,0,251,252,5,115,0,0,252,253,5,78,0,0,253,254,5, 111,0,0,254,255,5,110,0,0,255,256,5,90,0,0,256,257,5,101,0,0,257,258, 5,114,0,0,258,259,5,111,0,0,259,40,1,0,0,0,260,261,5,83,0,0,261,262,5, 84,0,0,262,263,5,82,0,0,263,264,5,73,0,0,264,265,5,78,0,0,265,273,5,71, 0,0,266,267,5,83,0,0,267,268,5,116,0,0,268,269,5,114,0,0,269,270,5,105, 0,0,270,271,5,110,0,0,271,273,5,103,0,0,272,260,1,0,0,0,272,266,1,0,0, 0,273,42,1,0,0,0,274,275,5,66,0,0,275,276,5,89,0,0,276,277,5,84,0,0,277, 278,5,69,0,0,278,279,5,65,0,0,279,280,5,82,0,0,280,281,5,82,0,0,281,282, 5,65,0,0,282,293,5,89,0,0,283,284,5,66,0,0,284,285,5,121,0,0,285,286, 5,116,0,0,286,287,5,101,0,0,287,288,5,97,0,0,288,289,5,114,0,0,289,290, 5,114,0,0,290,291,5,97,0,0,291,293,5,121,0,0,292,274,1,0,0,0,292,283, 1,0,0,0,293,44,1,0,0,0,294,295,5,73,0,0,295,296,5,78,0,0,296,297,5,84, 0,0,297,298,5,65,0,0,298,299,5,82,0,0,299,300,5,82,0,0,300,301,5,65,0, 0,301,311,5,89,0,0,302,303,5,73,0,0,303,304,5,110,0,0,304,305,5,116,0, 0,305,306,5,97,0,0,306,307,5,114,0,0,307,308,5,114,0,0,308,309,5,97,0, 0,309,311,5,121,0,0,310,294,1,0,0,0,310,302,1,0,0,0,311,46,1,0,0,0,312, 313,5,66,0,0,313,314,5,89,0,0,314,315,5,84,0,0,315,321,5,69,0,0,316,317, 5,66,0,0,317,318,5,121,0,0,318,319,5,116,0,0,319,321,5,101,0,0,320,312, 1,0,0,0,320,316,1,0,0,0,321,48,1,0,0,0,322,323,5,85,0,0,323,324,5,73, 0,0,324,325,5,78,0,0,325,331,5,84,0,0,326,327,5,85,0,0,327,328,5,105, 0,0,328,329,5,110,0,0,329,331,5,116,0,0,330,322,1,0,0,0,330,326,1,0,0, 0,331,50,1,0,0,0,332,333,5,73,0,0,333,334,5,78,0,0,334,335,5,84,0,0,335, 336,5,69,0,0,336,337,5,71,0,0,337,338,5,69,0,0,338,347,5,82,0,0,339,340, 5,73,0,0,340,341,5,110,0,0,341,342,5,116,0,0,342,343,5,101,0,0,343,344, 5,103,0,0,344,345,5,101,0,0,345,347,5,114,0,0,346,332,1,0,0,0,346,339, 1,0,0,0,347,52,1,0,0,0,348,349,5,70,0,0,349,350,5,76,0,0,350,351,5,79, 0,0,351,352,5,65,0,0,352,359,5,84,0,0,353,354,5,70,0,0,354,355,5,108, 0,0,355,356,5,111,0,0,356,357,5,97,0,0,357,359,5,116,0,0,358,348,1,0, 0,0,358,353,1,0,0,0,359,54,1,0,0,0,360,361,5,83,0,0,361,362,5,69,0,0, 362,363,5,76,0,0,363,364,5,69,0,0,364,365,5,67,0,0,365,373,5,84,0,0,366, 367,5,115,0,0,367,368,5,101,0,0,368,369,5,108,0,0,369,370,5,101,0,0,370, 371,5,99,0,0,371,373,5,116,0,0,372,360,1,0,0,0,372,366,1,0,0,0,373,56, 1,0,0,0,374,375,5,83,0,0,375,376,5,84,0,0,376,377,5,82,0,0,377,378,5, 69,0,0,378,379,5,65,0,0,379,387,5,77,0,0,380,381,5,115,0,0,381,382,5, 116,0,0,382,383,5,114,0,0,383,384,5,101,0,0,384,385,5,97,0,0,385,387, 5,109,0,0,386,374,1,0,0,0,386,380,1,0,0,0,387,58,1,0,0,0,388,389,5,70, 0,0,389,390,5,82,0,0,390,391,5,79,0,0,391,397,5,77,0,0,392,393,5,102, 0,0,393,394,5,114,0,0,394,395,5,111,0,0,395,397,5,109,0,0,396,388,1,0, 0,0,396,392,1,0,0,0,397,60,1,0,0,0,398,399,5,68,0,0,399,400,5,69,0,0, 400,401,5,67,0,0,401,402,5,76,0,0,402,403,5,65,0,0,403,404,5,82,0,0,404, 413,5,69,0,0,405,406,5,100,0,0,406,407,5,101,0,0,407,408,5,99,0,0,408, 409,5,108,0,0,409,410,5,97,0,0,410,411,5,114,0,0,411,413,5,101,0,0,412, 398,1,0,0,0,412,405,1,0,0,0,413,62,1,0,0,0,414,415,5,70,0,0,415,416,5, 73,0,0,416,417,5,76,0,0,417,423,5,69,0,0,418,419,5,102,0,0,419,420,5, 105,0,0,420,421,5,108,0,0,421,423,5,101,0,0,422,414,1,0,0,0,422,418,1, 0,0,0,423,64,1,0,0,0,424,425,5,83,0,0,425,426,5,84,0,0,426,427,5,79,0, 0,427,428,5,82,0,0,428,429,5,65,0,0,429,430,5,71,0,0,430,439,5,69,0,0, 431,432,5,115,0,0,432,433,5,116,0,0,433,434,5,111,0,0,434,435,5,114,0, 0,435,436,5,97,0,0,436,437,5,103,0,0,437,439,5,101,0,0,438,424,1,0,0, 0,438,431,1,0,0,0,439,66,1,0,0,0,440,441,5,77,0,0,441,442,5,73,0,0,442, 447,5,78,0,0,443,444,5,109,0,0,444,445,5,105,0,0,445,447,5,110,0,0,446, 440,1,0,0,0,446,443,1,0,0,0,447,68,1,0,0,0,448,449,5,77,0,0,449,450,5, 65,0,0,450,455,5,88,0,0,451,452,5,109,0,0,452,453,5,97,0,0,453,455,5, 120,0,0,454,448,1,0,0,0,454,451,1,0,0,0,455,70,1,0,0,0,456,457,5,65,0, 0,457,458,5,86,0,0,458,463,5,71,0,0,459,460,5,97,0,0,460,461,5,118,0, 0,461,463,5,103,0,0,462,456,1,0,0,0,462,459,1,0,0,0,463,72,1,0,0,0,464, 465,5,83,0,0,465,466,5,85,0,0,466,467,5,77,0,0,467,473,5,67,0,0,468,469, 5,115,0,0,469,470,5,117,0,0,470,471,5,109,0,0,471,473,5,99,0,0,472,464, 1,0,0,0,472,468,1,0,0,0,473,74,1,0,0,0,474,478,7,0,0,0,475,477,7,1,0, 0,476,475,1,0,0,0,477,480,1,0,0,0,478,476,1,0,0,0,478,479,1,0,0,0,479, 76,1,0,0,0,480,478,1,0,0,0,481,487,5,39,0,0,482,486,8,2,0,0,483,484,5, 39,0,0,484,486,5,39,0,0,485,482,1,0,0,0,485,483,1,0,0,0,486,489,1,0,0, 0,487,485,1,0,0,0,487,488,1,0,0,0,488,490,1,0,0,0,489,487,1,0,0,0,490, 491,5,39,0,0,491,78,1,0,0,0,492,493,3,139,69,0,493,80,1,0,0,0,494,496, 3,143,71,0,495,494,1,0,0,0,496,497,1,0,0,0,497,495,1,0,0,0,497,498,1, 0,0,0,498,82,1,0,0,0,499,502,3,81,40,0,500,502,3,139,69,0,501,499,1,0, 0,0,501,500,1,0,0,0,502,503,1,0,0,0,503,505,5,69,0,0,504,506,7,3,0,0, 505,504,1,0,0,0,505,506,1,0,0,0,506,508,1,0,0,0,507,509,3,143,71,0,508, 507,1,0,0,0,509,510,1,0,0,0,510,508,1,0,0,0,510,511,1,0,0,0,511,84,1, 0,0,0,512,513,5,61,0,0,513,86,1,0,0,0,514,515,5,62,0,0,515,88,1,0,0,0, 516,517,5,60,0,0,517,90,1,0,0,0,518,519,5,33,0,0,519,92,1,0,0,0,520,521, 5,124,0,0,521,522,5,124,0,0,522,94,1,0,0,0,523,524,5,46,0,0,524,96,1, 0,0,0,525,526,5,95,0,0,526,98,1,0,0,0,527,528,5,64,0,0,528,100,1,0,0, 0,529,530,5,35,0,0,530,102,1,0,0,0,531,532,5,38,0,0,532,104,1,0,0,0,533, 534,5,37,0,0,534,106,1,0,0,0,535,536,5,36,0,0,536,108,1,0,0,0,537,538, 5,44,0,0,538,110,1,0,0,0,539,540,5,59,0,0,540,112,1,0,0,0,541,542,5,58, 0,0,542,114,1,0,0,0,543,544,5,58,0,0,544,545,5,58,0,0,545,116,1,0,0,0, 546,547,5,42,0,0,547,118,1,0,0,0,548,549,5,47,0,0,549,120,1,0,0,0,550, 551,5,43,0,0,551,122,1,0,0,0,552,553,5,45,0,0,553,124,1,0,0,0,554,555, 5,126,0,0,555,126,1,0,0,0,556,557,5,124,0,0,557,128,1,0,0,0,558,559,5, 94,0,0,559,130,1,0,0,0,560,562,7,4,0,0,561,560,1,0,0,0,562,563,1,0,0, 0,563,561,1,0,0,0,563,564,1,0,0,0,564,565,1,0,0,0,565,566,6,65,0,0,566, 132,1,0,0,0,567,568,5,47,0,0,568,569,5,42,0,0,569,574,1,0,0,0,570,573, 3,133,66,0,571,573,9,0,0,0,572,570,1,0,0,0,572,571,1,0,0,0,573,576,1, 0,0,0,574,575,1,0,0,0,574,572,1,0,0,0,575,577,1,0,0,0,576,574,1,0,0,0, 577,578,5,42,0,0,578,579,5,47,0,0,579,580,1,0,0,0,580,581,6,66,1,0,581, 134,1,0,0,0,582,583,5,35,0,0,583,584,5,32,0,0,584,588,1,0,0,0,585,587, 8,5,0,0,586,585,1,0,0,0,587,590,1,0,0,0,588,586,1,0,0,0,588,589,1,0,0, 0,589,591,1,0,0,0,590,588,1,0,0,0,591,592,6,67,1,0,592,136,1,0,0,0,593, 594,7,6,0,0,594,138,1,0,0,0,595,597,3,143,71,0,596,595,1,0,0,0,597,598, 1,0,0,0,598,596,1,0,0,0,598,599,1,0,0,0,599,600,1,0,0,0,600,602,5,46, 0,0,601,603,3,143,71,0,602,601,1,0,0,0,603,604,1,0,0,0,604,602,1,0,0, 0,604,605,1,0,0,0,605,620,1,0,0,0,606,608,3,143,71,0,607,606,1,0,0,0, 608,609,1,0,0,0,609,607,1,0,0,0,609,610,1,0,0,0,610,611,1,0,0,0,611,612, 5,46,0,0,612,620,1,0,0,0,613,615,5,46,0,0,614,616,3,143,71,0,615,614, 1,0,0,0,616,617,1,0,0,0,617,615,1,0,0,0,617,618,1,0,0,0,618,620,1,0,0, 0,619,596,1,0,0,0,619,607,1,0,0,0,619,613,1,0,0,0,620,140,1,0,0,0,621, 622,7,7,0,0,622,142,1,0,0,0,623,624,7,8,0,0,624,144,1,0,0,0,34,0,272, 292,310,320,330,346,358,372,386,396,412,422,438,446,454,462,472,478,485, 487,497,501,505,510,563,572,574,588,598,604,609,617,619,2,6,0,0,0,1,0 }; staticData->serializedATN = antlr4::atn::SerializedATNView(serializedATNSegment, sizeof(serializedATNSegment) / sizeof(serializedATNSegment[0])); antlr4::atn::ATNDeserializer deserializer; staticData->atn = deserializer.deserialize(staticData->serializedATN); const size_t count = staticData->atn->getNumberOfDecisions(); staticData->decisionToDFA.reserve(count); for (size_t i = 0; i < count; i++) { staticData->decisionToDFA.emplace_back(staticData->atn->getDecisionState(i), i); } rqllexerLexerStaticData = staticData.release(); } } RQLLexer::RQLLexer(CharStream *input) : Lexer(input) { RQLLexer::initialize(); _interpreter = new atn::LexerATNSimulator(this, *rqllexerLexerStaticData->atn, rqllexerLexerStaticData->decisionToDFA, rqllexerLexerStaticData->sharedContextCache); } RQLLexer::~RQLLexer() { delete _interpreter; } std::string RQLLexer::getGrammarFileName() const { return "RQL.g4"; } const std::vector<std::string>& RQLLexer::getRuleNames() const { return rqllexerLexerStaticData->ruleNames; } const std::vector<std::string>& RQLLexer::getChannelNames() const { return rqllexerLexerStaticData->channelNames; } const std::vector<std::string>& RQLLexer::getModeNames() const { return rqllexerLexerStaticData->modeNames; } const dfa::Vocabulary& RQLLexer::getVocabulary() const { return rqllexerLexerStaticData->vocabulary; } antlr4::atn::SerializedATNView RQLLexer::getSerializedATN() const { return rqllexerLexerStaticData->serializedATN; } const atn::ATN& RQLLexer::getATN() const { return *rqllexerLexerStaticData->atn; } void RQLLexer::initialize() { std::call_once(rqllexerLexerOnceFlag, rqllexerLexerInitialize); }
59.00838
166
0.6
[ "vector" ]
13f81b62aa66c33332b24756e6fd00af26366cc0
4,726
cpp
C++
src/modules/videoconference/VideoConferenceShared/MicrophoneDevice.cpp
JacobDeuchert/PowerToys
d5a5f858c065a42d5fca46a717b6e538a6c50693
[ "MIT" ]
4
2022-01-10T07:24:48.000Z
2022-02-07T02:08:03.000Z
src/modules/videoconference/VideoConferenceShared/MicrophoneDevice.cpp
JacobDeuchert/PowerToys
d5a5f858c065a42d5fca46a717b6e538a6c50693
[ "MIT" ]
null
null
null
src/modules/videoconference/VideoConferenceShared/MicrophoneDevice.cpp
JacobDeuchert/PowerToys
d5a5f858c065a42d5fca46a717b6e538a6c50693
[ "MIT" ]
1
2022-01-13T04:03:09.000Z
2022-01-13T04:03:09.000Z
#include "MicrophoneDevice.h" #include "Logging.h" #include <Functiondiscoverykeys_devpkey.h> MicrophoneDevice::MicrophoneDevice(wil::com_ptr_nothrow<IMMDevice> device, wil::com_ptr_nothrow<IAudioEndpointVolume> endpoint) : _device{ std::move(device) }, _endpoint{ std::move(endpoint) } { if (!_device || !_endpoint) { throw std::logic_error("MicrophoneDevice was initialized with null objects"); } _device->GetId(&_id); wil::com_ptr_nothrow<IPropertyStore> props; _device->OpenPropertyStore( STGM_READ, &props); if (props) { props->GetValue(PKEY_Device_FriendlyName, &_friendly_name); } else { LOG("MicrophoneDevice::MicrophoneDevice couldn't open property store"); } } MicrophoneDevice::~MicrophoneDevice() { if (_notifier) { _endpoint->UnregisterControlChangeNotify(_notifier.get()); } } bool MicrophoneDevice::active() const noexcept { DWORD state = 0; _device->GetState(&state); return state == DEVICE_STATE_ACTIVE; } void MicrophoneDevice::set_muted(const bool muted) noexcept { _endpoint->SetMute(muted, nullptr); } bool MicrophoneDevice::muted() const noexcept { BOOL muted = FALSE; _endpoint->GetMute(&muted); return muted; } void MicrophoneDevice::toggle_muted() noexcept { set_muted(!muted()); } std::wstring_view MicrophoneDevice::id() const noexcept { return _id ? _id.get() : FALLBACK_ID; } std::wstring_view MicrophoneDevice::name() const noexcept { return _friendly_name.pwszVal ? _friendly_name.pwszVal : FALLBACK_NAME; } void MicrophoneDevice::set_mute_changed_callback(mute_changed_cb_t callback) noexcept { _mute_changed_callback = std::move(callback); _notifier = winrt::make<VolumeNotifier>(this); _endpoint->RegisterControlChangeNotify(_notifier.get()); } std::unique_ptr<MicrophoneDevice> MicrophoneDevice::getDefault() { auto deviceEnumerator = wil::CoCreateInstanceNoThrow<MMDeviceEnumerator, IMMDeviceEnumerator>(); if (!deviceEnumerator) { LOG("MicrophoneDevice::getDefault MMDeviceEnumerator returned null"); return nullptr; } wil::com_ptr_nothrow<IMMDevice> captureDevice; deviceEnumerator->GetDefaultAudioEndpoint(eCapture, eCommunications, &captureDevice); if (!captureDevice) { LOG("MicrophoneDevice::getDefault captureDevice is null"); return nullptr; } wil::com_ptr_nothrow<IAudioEndpointVolume> microphoneEndpoint; captureDevice->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, nullptr, reinterpret_cast<LPVOID*>(&microphoneEndpoint)); if (!microphoneEndpoint) { LOG("MicrophoneDevice::getDefault captureDevice is null"); return nullptr; } return std::make_unique<MicrophoneDevice>(std::move(captureDevice), std::move(microphoneEndpoint)); } std::vector<std::unique_ptr<MicrophoneDevice>> MicrophoneDevice::getAllActive() { std::vector<std::unique_ptr<MicrophoneDevice>> microphoneDevices; auto deviceEnumerator = wil::CoCreateInstanceNoThrow<MMDeviceEnumerator, IMMDeviceEnumerator>(); if (!deviceEnumerator) { LOG("MicrophoneDevice::getAllActive MMDeviceEnumerator returned null"); return microphoneDevices; } wil::com_ptr_nothrow<IMMDeviceCollection> captureDevices; deviceEnumerator->EnumAudioEndpoints(eCapture, DEVICE_STATE_ACTIVE, &captureDevices); if (!captureDevices) { LOG("MicrophoneDevice::getAllActive EnumAudioEndpoints returned null"); return microphoneDevices; } UINT nDevices = 0; captureDevices->GetCount(&nDevices); microphoneDevices.reserve(nDevices); for (UINT i = 0; i < nDevices; ++i) { wil::com_ptr_nothrow<IMMDevice> device; captureDevices->Item(i, &device); if (!device) { continue; } wil::com_ptr_nothrow<IAudioEndpointVolume> microphoneEndpoint; device->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, nullptr, reinterpret_cast<LPVOID*>(&microphoneEndpoint)); if (!microphoneEndpoint) { continue; } microphoneDevices.push_back(std::make_unique<MicrophoneDevice>(std::move(device), std::move(microphoneEndpoint))); } return microphoneDevices; } MicrophoneDevice::VolumeNotifier::VolumeNotifier(MicrophoneDevice* subscribedDevice) : _subscribedDevice{ subscribedDevice } { } HRESULT __stdcall MicrophoneDevice::VolumeNotifier::OnNotify(PAUDIO_VOLUME_NOTIFICATION_DATA data) { if (_subscribedDevice && _subscribedDevice->_mute_changed_callback) _subscribedDevice->_mute_changed_callback(data->bMuted); return S_OK; }
30.490323
139
0.717732
[ "vector" ]
cd0e1e74f59a71eac826179e7d68f968efa1610d
19,024
cpp
C++
Config.cpp
zdco/jiaguomeng
04c5b3477698c530da73648823adae82bcc971e3
[ "Apache-2.0" ]
4
2019-11-13T01:21:04.000Z
2019-12-06T03:11:05.000Z
Config.cpp
zdco/jiaguomeng
04c5b3477698c530da73648823adae82bcc971e3
[ "Apache-2.0" ]
null
null
null
Config.cpp
zdco/jiaguomeng
04c5b3477698c530da73648823adae82bcc971e3
[ "Apache-2.0" ]
1
2019-12-06T03:06:59.000Z
2019-12-06T03:06:59.000Z
#ifdef WIN32 #include "stdafx.h" #endif #include "Config.h" #include "Building.h" Config* Config::m_instance; Config::Config() { } Config::~Config() { ClearBuilding(); } Config* Config::GetInstance() { if (m_instance == 0) { m_instance = new Config; } return m_instance; } void Config::CloseInstance() { if (m_instance) { delete m_instance; } } void Config::ClearBuilding() { for (auto it = m_mapBuilding.begin(); it != m_mapBuilding.end(); it++) { delete it->second; } m_mapBuilding.clear(); } vector<string> Config::SepStr(const string sStr, const string &sSep) { vector<string> vResult; string strTemp = sStr; size_t nPos = strTemp.find(sSep); while (nPos != string::npos) { vResult.push_back(strTemp.substr(0, nPos)); strTemp = strTemp.substr(nPos + sSep.length()); nPos = strTemp.find(sSep); } vResult.push_back(strTemp); return vResult; } string Config::GetUnit(const double &dValue) { ostringstream os; if (dValue > 1e39) os << dValue / 1e39 << "ii"; else if (dValue > 1e36) os << dValue / 1e36 << "hh"; else if (dValue > 1e33) os << dValue / 1e33 << "gg"; else if (dValue > 1e30) os << dValue / 1e30 << "ff"; else if (dValue > 1e27) os << dValue / 1e27 << "ee"; else if (dValue > 1e24) os << dValue / 1e24 << "dd"; else if (dValue > 1e21) os << dValue / 1e21 << "cc"; else if (dValue > 1e18) os << dValue / 1e18 << "bb"; else if (dValue > 1e15) os << dValue / 1e15 << "aa"; else if (dValue > 1e12) os << dValue / 1e12 << "T"; else if (dValue > 1e9) os << dValue / 1e9 << "B"; else if (dValue > 1e6) os << dValue / 1e6 << "M"; else if (dValue > 1e3) os << dValue / 1e3 << "K"; else os << dValue; return os.str(); } vector<vector<string> > Config::ParseConfig(const string &configFile) { vector<vector<string> > vConfig; ifstream ifs(configFile); string sLine; getline(ifs, sLine); //跳过第一行表头 while (getline(ifs, sLine)) { sLine = sLine.substr(0, sLine.find_last_of('\r')); if (!sLine.empty()) { vector<string> vField = SepStr(sLine, ","); vConfig.push_back(vField); } } return vConfig; } void Config::SaveConfig(const string &configFile, const vector<vector<string> > &vConfig) { ofstream ofs(configFile); for (size_t i = 0; i < vConfig.size(); i++) { const vector<string> vField = vConfig[i]; for (size_t j = 0; j < vField.size(); j++) { if (j > 0) { ofs << ","; } ofs << vField[j]; } ofs << endl; } } void Config::Init() { LoadBuildingUpgrade(); LoadBuffStatus(); LoadPhotoBuff(); LoadPolicyBuff(); LoadMissionBuff(); LoadBuildingName(); LoadBuilding(); } void Config::ResetData() { m_setValidBuilding.clear(); for (auto it = m_mapBuilding.begin(); it != m_mapBuilding.end(); it++) { it->second->Reset(); } } void Config::LoadData() { ResetData(); LoadBuildingConfig(); LoadPhotoConfig(); LoadPolicyConfig(); LoadMissionConfig(); LoadJiaguoConfig(); InitBuildingProfit(); } Building* Config::GetBuilding(const string &sBuildingId) { auto it = m_mapBuilding.find(sBuildingId); if (it != m_mapBuilding.end()) { return it->second; } return NULL; } unordered_map<string, Building*> Config::GetCategoryBuilding(const string &sCategory) { unordered_map<string, Building*> mapBuilding; auto it = m_mapCategoryBuilding.find(sCategory); if (it != m_mapCategoryBuilding.end()) { for (size_t i = 0; i < it->second.size(); i++) { const string &sBuildingId = it->second[i]; if (m_setValidBuilding.count(sBuildingId) > 0) { mapBuilding[sBuildingId] = GetBuilding(sBuildingId); } } } return mapBuilding; } void Config::LoadBuildingUpgrade() { vector<vector<string> > vConfig = ParseConfig(BuildingUpgradeData); for (size_t i = 0; i < vConfig.size(); i++) { const vector<string> &vField = vConfig[i]; if (vField.size() >= 2) { int nLevel = atoi(vField[0].c_str()); double dProfit = atof(vField[1].c_str()); // streamsize csize = cout.precision(); // cout.precision(numeric_limits<double>::digits10); // cout << "nLevel:" << nLevel << ",dProfit:" << dProfit << endl; // cout.precision(csize); m_mapLevelProfit[nLevel] = dProfit; } } } void Config::ParseBuffStatus(const string &sEffectId, double dEffectValue, const string &sTargetId, vector<pair<string, double> > &vBuffStatus) { if (sEffectId != "-1") { if (sTargetId == "-1") { vBuffStatus.push_back(make_pair(CategorySupply, dEffectValue)); } else if (sTargetId == "1") { if (sEffectId >= "11" && sEffectId <= "14") { vBuffStatus.push_back(make_pair(CategoryAll, dEffectValue)); } else if (sEffectId >= "21" && sEffectId <= "24") { vBuffStatus.push_back(make_pair(CategoryOnline, dEffectValue)); } else if (sEffectId >= "31" && sEffectId <= "34") { vBuffStatus.push_back(make_pair(CategoryOffline, dEffectValue)); } } else if (sTargetId == "2") { vBuffStatus.push_back(make_pair(CategoryResidence, dEffectValue)); } else if (sTargetId == "3") { vBuffStatus.push_back(make_pair(CategoryBusiness, dEffectValue)); } else if (sTargetId == "4") { vBuffStatus.push_back(make_pair(CategoryIndustrial, dEffectValue)); } else { vBuffStatus.push_back(make_pair(sTargetId, dEffectValue)); } } } void Config::LoadBuffStatus() { vector<vector<string> > vConfig = ParseConfig(BuffStatusData); for (size_t i = 0; i < vConfig.size(); i++) { const vector<string> &vField = vConfig[i]; if (vField.size() >= 13) { string sBuffId = vField[0]; for (int j = 0; j < 3; j++) { string sEffectId = vField[j * 3 + 1]; double dEffectValue = atof(vField[j * 3 + 2].c_str()); string sTargetId = vField[j * 3 + 3]; ParseBuffStatus(sEffectId, dEffectValue, sTargetId, m_mapBuffStatus[sBuffId]); } } } } unordered_map<string, vector<pair<string, double> > > Config::GetBuffStatus() { return m_mapBuffStatus; } void Config::LoadPhotoBuff() { vector<vector<string> > vConfig = ParseConfig(PhotoBuffData); for (size_t i = 0; i < vConfig.size(); i++) { const vector<string> &vField = vConfig[i]; if (vField.size() >= 2) { string sPhotoId = vField[0]; string sBuffId = vField[1]; //cout << "sPhotoId:" << sPhotoId << ",sBuffId:" << sBuffId << endl; m_mapPhotoBuff[sPhotoId] = sBuffId; } } } void Config::LoadPolicyBuff() { vector<vector<string> > vConfig = ParseConfig(PolicyBuffData); for (size_t i = 0; i < vConfig.size(); i++) { const vector<string> &vField = vConfig[i]; if (vField.size() >= 3) { string sPolicyId = vField[1]; string sBuffId = vField[2]; //cout << "sPolicyId:" << sPolicyId << ",sBuffId:" << sBuffId << endl; if (m_mapPolicyBuff.find(sPolicyId) == m_mapPolicyBuff.end()) { m_vPolicyId.push_back(sPolicyId); } m_mapPolicyBuff[sPolicyId].push_back(sBuffId); } } } void Config::LoadMissionBuff() { vector<vector<string> > vConfig = ParseConfig(MissionBuffData); for (size_t i = 0; i < vConfig.size(); i++) { const vector<string> &vField = vConfig[i]; if (vField.size() >= 2) { string sMissionId = vField[0]; string sMissionName = vField[1]; m_mapMissionName[sMissionId] = sMissionName; for (int j = 0; j < 5; j++) { string sBuffId = vField[j + 2]; m_mapMissionBuff[sMissionId].push_back(sBuffId); } } } } unordered_map<string, vector<string> > Config::GetMissionBuff() { return m_mapMissionBuff; } unordered_map<string, string> Config::GetMissionName() { return m_mapMissionName; } void Config::LoadBuildingName() { vector<vector<string> > vConfig = ParseConfig(BuildingNameData); for (size_t i = 0; i < vConfig.size(); i++) { const vector<string> &vField = vConfig[i]; if (vField.size() >= 2) { string sBuildingId = vField[0]; string sName = vField[1]; //cout << "sBuildingId:" << sBuildingId << ",sName:" << sName << endl; Building* building = GetBuilding(sBuildingId); if (building == NULL) { building = new Building(sName); m_mapBuilding[sBuildingId] = building; } } } } void Config::LoadBuilding() { vector<vector<string> > vConfig = ParseConfig(BuildingData); for (size_t i = 0; i < vConfig.size(); i++) { const vector<string> &vField = vConfig[i]; if (vField.size() >= 6) { string sStar = vField[0]; string sBuildingId = vField[1]; string sCategory = vField[2]; //string rarity = vField[3]; double dProfit = atof(vField[4].c_str()); vector<pair<string, double> > vBuff; for (int j = 0; j < 2; j++) { string sBuffId = vField[5 + j]; if (sBuffId != "0") { auto it = m_mapBuffStatus.find(sBuffId); if (it != m_mapBuffStatus.end()) { vBuff.insert(vBuff.end(), it->second.begin(), it->second.end()); } } } //cout << "sStar:" << sStar << ",sBuildingId:" << sBuildingId << ",sCategory:" << sCategory << ",dProfit:" << dProfit << endl; Building* building = GetBuilding(sBuildingId); if (building) { building->AddStarProfit(sStar, dProfit); building->AddStarBuff(sStar, vBuff); m_mapCategoryBuilding[sCategory].push_back(sBuildingId); } } } } void Config::LoadBuildingConfig() { vector<vector<string> > vConfig = ParseConfig(BuildingConfig); for (size_t i = 0; i < vConfig.size(); i++) { const vector<string> &vField = vConfig[i]; if (vField.size() >= 4) { string sBuildingId = vField[0]; string sStar = vField[1]; int nLevel = atoi(vField[2].c_str()); bool bValid = atoi(vField[3].c_str()); Building* building = GetBuilding(sBuildingId); if (bValid && building) { m_setValidBuilding.insert(sBuildingId); building->SetStar(sStar); building->SetLevel(nLevel); } } } } void Config::AddPhotoBuff(const unordered_map<string, Building*> &mapBuilding, const string &sCategory, double dBuff) { for (auto it = mapBuilding.begin(); it != mapBuilding.end(); it++) { it->second->AddPhotoBuff(sCategory, dBuff); } } void Config::AddPhotoBuff(const string &sBuffId) { auto buff_it = m_mapBuffStatus.find(sBuffId); if (buff_it != m_mapBuffStatus.end()) { const vector<pair<string, double> > &vBuff = buff_it->second; for (size_t j = 0; j < vBuff.size(); j++) { const pair<string, double> &buff = vBuff[j]; if (buff.first == CategoryAll || buff.first == CategoryOnline || buff.first == CategoryOffline) { AddPhotoBuff(m_mapBuilding, buff.first, buff.second); } else if (buff.first == CategoryResidence || buff.first == CategoryBusiness || buff.first == CategoryIndustrial) { unordered_map<string, Building*> mapBuilding = GetCategoryBuilding(buff.first); AddPhotoBuff(mapBuilding, CategoryAll, buff.second); } } } } void Config::LoadPhotoConfig() { vector<vector<string> > vConfig = ParseConfig(PhotoConfig); for (size_t i = 0; i < vConfig.size(); i++) { const vector<string> &vField = vConfig[i]; if (vField.size() >= 1) { string sPhotoId = vField[0]; auto it = m_mapPhotoBuff.find(sPhotoId); if (it != m_mapPhotoBuff.end()) { AddPhotoBuff(it->second); } } } } void Config::AddPolicyBuff(const unordered_map<string, Building*> &mapBuilding, const string &sCategory, double dBuff) { for (auto it = mapBuilding.begin(); it != mapBuilding.end(); it++) { it->second->AddPolicyBuff(sCategory, dBuff); } } void Config::AddPolicyBuff(const string &sBuffId) { auto buff_it = m_mapBuffStatus.find(sBuffId); if (buff_it != m_mapBuffStatus.end()) { const vector<pair<string, double> > &vBuff = buff_it->second; for (size_t j = 0; j < vBuff.size(); j++) { const pair<string, double> &buff = vBuff[j]; if (buff.first == CategoryAll || buff.first == CategoryOnline || buff.first == CategoryOffline) { AddPolicyBuff(m_mapBuilding, buff.first, buff.second); } else if (buff.first == CategoryResidence || buff.first == CategoryBusiness || buff.first == CategoryIndustrial) { unordered_map<string, Building*> mapBuilding = GetCategoryBuilding(buff.first); AddPolicyBuff(mapBuilding, CategoryAll, buff.second); } } } } void Config::LoadPolicyConfig() { string sFirstPolicyId; vector<vector<string> > vConfig = ParseConfig(PolicyConfig); for (size_t i = 0; i < vConfig.size(); i++) { const vector<string> &vField = vConfig[i]; if (vField.size() >= 2) { string sPolicyId = vField[0]; int nLevel = atoi(vField[1].c_str()); //cout << "sPolicyId:" << sPolicyId << ",nLevel:" << nLevel << endl; if (sFirstPolicyId.empty()) { sFirstPolicyId = sPolicyId; } if (nLevel > 0) { auto it = m_mapPolicyBuff.find(sPolicyId); if (it != m_mapPolicyBuff.end() && it->second.size() >= nLevel) { string sBuffId = it->second[nLevel - 1]; AddPolicyBuff(sBuffId); } } } } //叠加该阶段之前的所有政策buff for (size_t i = 0; i < m_vPolicyId.size(); i++) { const string sPolicyId = m_vPolicyId[i]; //由于ID排序不规则,使用不等于来判断,相等时终止循环 if (sPolicyId == sFirstPolicyId) { break; } string sBuffId = m_mapPolicyBuff[sPolicyId].back(); AddPolicyBuff(sBuffId); } } void Config::AddMissionBuff(const unordered_map<string, Building*> &mapBuilding, const string &sCategory, double dBuff) { for (auto it = mapBuilding.begin(); it != mapBuilding.end(); it++) { it->second->AddMissionBuff(sCategory, dBuff); } } void Config::AddMissionBuff(const string &sBuffId) { auto buff_it = m_mapBuffStatus.find(sBuffId); if (buff_it != m_mapBuffStatus.end()) { const vector<pair<string, double> > &vBuff = buff_it->second; for (size_t j = 0; j < vBuff.size(); j++) { const pair<string, double> &buff = vBuff[j]; if (buff.first == CategoryAll || buff.first == CategoryOnline || buff.first == CategoryOffline) { AddMissionBuff(m_mapBuilding, buff.first, buff.second); } else if (buff.first == CategoryResidence || buff.first == CategoryBusiness || buff.first == CategoryIndustrial) { unordered_map<string, Building*> mapBuilding = GetCategoryBuilding(buff.first); AddMissionBuff(mapBuilding, CategoryAll, buff.second); } else { Building* building = GetBuilding(buff.first); if (building) { building->AddMissionBuff(CategoryAll, buff.second); } } } } } void Config::LoadMissionConfig() { vector<vector<string> > vConfig = ParseConfig(MissionConfig); for (size_t i = 0; i < vConfig.size(); i++) { const vector<string> &vField = vConfig[i]; if (vField.size() >= 2) { string sMissionId = vField[0]; string sBuffId = vField[1]; //cout << "sMissionId:" << sMissionId << ",sBuffId:" << sBuffId << endl; AddMissionBuff(sBuffId); } } } void Config::LoadJiaguoConfig() { vector<vector<string> > vConfig = ParseConfig(JiaguoConfig); for (size_t i = 0; i < vConfig.size(); i++) { const vector<string> &vField = vConfig[i]; if (vField.size() >= 1) { double dBuff = atoi(vField[0].c_str()) / 100.0f; AddPolicyBuff(m_mapBuilding, CategoryAll, dBuff); } } } void Config::InitBuildingProfit() { for (auto it = m_mapBuilding.begin(); it != m_mapBuilding.end(); it++) { it->second->InitProfit(); } } double Config::GetLevelProfit(int nLevel) { return m_mapLevelProfit[nLevel]; } void Config::SaveBuildingConfig(vector<vector<string> > &vConfig) { vector<string> vHead; vHead.push_back("Id"); vHead.push_back("StarLevel"); vHead.push_back("Level"); vHead.push_back("IsCalc"); vConfig.insert(vConfig.begin(), vHead); SaveConfig(BuildingConfig, vConfig); } void Config::SavePhotoConfig(vector<vector<string> > &vConfig) { vector<string> vHead; vHead.push_back("Id"); vConfig.insert(vConfig.begin(), vHead); SaveConfig(PhotoConfig, vConfig); } void Config::SavePolicyConfig(vector<vector<string> > &vConfig) { vector<string> vHead; vHead.push_back("NameID"); vHead.push_back("Level"); vConfig.insert(vConfig.begin(), vHead); SaveConfig(PolicyConfig, vConfig); } void Config::SaveMissionConfig(vector<vector<string> > &vConfig) { vector<string> vHead; vHead.push_back("NameID"); vHead.push_back("Effect"); vConfig.insert(vConfig.begin(), vHead); SaveConfig(MissionConfig, vConfig); } void Config::SaveJiaguoConfig(vector<vector<string> > &vConfig) { vector<string> vHead; vHead.push_back("Effect"); vConfig.insert(vConfig.begin(), vHead); SaveConfig(JiaguoConfig, vConfig); }
28.267459
143
0.559609
[ "vector" ]
997fc4ab075d0a90a1b0cd818344102b8f4bd61f
7,766
hpp
C++
test/unit/math/rev/functor/ode_test_functors.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/rev/functor/ode_test_functors.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/rev/functor/ode_test_functors.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_TEST_ODE_TEST_FUNCTORS_HPP #define STAN_MATH_TEST_ODE_TEST_FUNCTORS_HPP #include <stan/math/prim/functor/ode_ckrk.hpp> #include <stan/math/prim/functor/ode_rk45.hpp> #include <stan/math/rev/functor/ode_bdf.hpp> #include <stan/math/rev/functor/ode_adams.hpp> #include <stan/math/rev/functor/ode_adjoint.hpp> #include <stan/math/prim/functor/integrate_ode_rk45.hpp> #define STAN_DEF_ODE_SOLVER_FUNCTOR(solver_name, solver_func) \ struct solver_name##_functor { \ const std::string functor_name = #solver_name; \ \ template <typename F, typename T_y0, typename T_t0, typename T_ts, \ typename... Args, stan::require_eigen_vector_t<T_y0>* = nullptr> \ std::vector<Eigen::Matrix<stan::return_type_t<T_y0, T_t0, T_ts, Args...>, \ Eigen::Dynamic, 1>> \ operator()(const F& f, const T_y0& y0, const T_t0& t0, \ const std::vector<T_ts>& ts, std::ostream* msgs, \ const Args&... args) { \ return solver_func(f, y0, t0, ts, msgs, args...); \ } \ \ template <typename F, typename T_y0, typename T_t0, typename T_ts, \ typename... Args, stan::require_eigen_vector_t<T_y0>* = nullptr> \ std::vector<Eigen::Matrix<stan::return_type_t<T_y0, T_t0, T_ts, Args...>, \ Eigen::Dynamic, 1>> \ operator()(const F& f, const T_y0& y0_arg, const T_t0& t0, \ const std::vector<T_ts>& ts, double rtol, double atol, \ size_t max_num_steps, std::ostream* msgs, \ const Args&... args) { \ return solver_func##_tol(f, y0_arg, t0, ts, rtol, atol, max_num_steps, \ msgs, args...); \ } \ }; #define STAN_DEF_STD_ODE_SOLVER_FUNCTOR(solver_name, solver_func) \ struct solver_name##_functor { \ template <typename F, typename T_y0, typename T_param, typename T_t0, \ typename T_ts> \ std::vector<std::vector<stan::return_type_t<T_y0, T_param, T_t0, T_ts>>> \ operator()(const F& f, const std::vector<T_y0>& y0, const T_t0& t0, \ const std::vector<T_ts>& ts, const std::vector<T_param>& theta, \ const std::vector<double>& x, const std::vector<int>& x_int, \ std::ostream* msgs = nullptr, double rtol = 1e-10, \ double atol = 1e-10, size_t max_num_step = 1e8) { \ return solver_func(f, y0, t0, ts, theta, x, x_int, msgs, rtol, atol, \ max_num_step); \ } \ }; STAN_DEF_ODE_SOLVER_FUNCTOR(ode_adams, stan::math::ode_adams); STAN_DEF_ODE_SOLVER_FUNCTOR(ode_ckrk, stan::math::ode_ckrk); STAN_DEF_ODE_SOLVER_FUNCTOR(ode_bdf, stan::math::ode_bdf); STAN_DEF_ODE_SOLVER_FUNCTOR(ode_rk45, stan::math::ode_rk45); STAN_DEF_STD_ODE_SOLVER_FUNCTOR(integrate_ode_adams, stan::math::integrate_ode_adams); STAN_DEF_STD_ODE_SOLVER_FUNCTOR(integrate_ode_bdf, stan::math::integrate_ode_bdf); STAN_DEF_STD_ODE_SOLVER_FUNCTOR(integrate_ode_rk45, stan::math::integrate_ode_rk45); struct ode_adjoint_functor { const std::string functor_name = "ode_adjoint"; template <typename F, typename T_y0, typename T_t0, typename T_ts, typename... Args, stan::require_eigen_vector_t<T_y0>* = nullptr> std::vector<Eigen::Matrix<stan::return_type_t<T_y0, T_t0, T_ts, Args...>, Eigen::Dynamic, 1>> operator()(const F& f, const T_y0& y0, const T_t0& t0, const std::vector<T_ts>& ts, std::ostream* msgs, const Args&... args) { return (*this)(f, y0, t0, ts, 1E-10, 1E-10, 1000000, msgs, args...); } template <typename F, typename T_y0, typename T_t0, typename T_ts, typename... Args, stan::require_eigen_vector_t<T_y0>* = nullptr> std::vector<Eigen::Matrix<stan::return_type_t<T_y0, T_t0, T_ts, Args...>, Eigen::Dynamic, 1>> operator()(const F& f, const T_y0& y0_arg, const T_t0& t0, const std::vector<T_ts>& ts, double relative_tolerance, double absolute_tolerance, size_t max_num_steps, std::ostream* msgs, const Args&... args) { const int N = y0_arg.size(); const double relative_tolerance_forward = relative_tolerance / 8.0; const double relative_tolerance_backward = relative_tolerance / 4.0; const double relative_tolerance_quadrature = relative_tolerance; const Eigen::VectorXd absolute_tolerance_forward = Eigen::VectorXd::Constant(N, absolute_tolerance / 6.0); const Eigen::VectorXd absolute_tolerance_backward = Eigen::VectorXd::Constant(N, absolute_tolerance / 3.0); const double absolute_tolerance_quadrature = absolute_tolerance; const long int num_steps_between_checkpoints = 150; // NOLINT(runtime/int) const int interpolation_polynomial = CV_HERMITE; const int solver_forward = CV_BDF; const int solver_backward = CV_ADAMS; return stan::math::ode_adjoint_tol_ctl( f, y0_arg, t0, ts, relative_tolerance_forward, absolute_tolerance_forward, relative_tolerance_backward, absolute_tolerance_backward, relative_tolerance_quadrature, absolute_tolerance_quadrature, max_num_steps, num_steps_between_checkpoints, interpolation_polynomial, solver_forward, solver_backward, msgs, args...); } template <typename F, typename T_y0, typename T_t0, typename T_ts, typename... T_Args, stan::require_eigen_col_vector_t<T_y0>* = nullptr> std::vector<Eigen::Matrix<stan::return_type_t<T_y0, T_t0, T_ts, T_Args...>, Eigen::Dynamic, 1>> operator()(const F& f, const T_y0& y0, const T_t0& t0, const std::vector<T_ts>& ts, double relative_tolerance_forward, const Eigen::VectorXd& absolute_tolerance_forward, double relative_tolerance_backward, const Eigen::VectorXd& absolute_tolerance_backward, double relative_tolerance_quadrature, double absolute_tolerance_quadrature, long int max_num_steps, // NOLINT(runtime/int) long int num_steps_between_checkpoints, // NOLINT(runtime/int) int interpolation_polynomial, int solver_forward, int solver_backward, std::ostream* msgs, const T_Args&... args) { return stan::math::ode_adjoint_tol_ctl( f, y0, t0, ts, relative_tolerance_forward, absolute_tolerance_forward, relative_tolerance_backward, absolute_tolerance_backward, relative_tolerance_quadrature, absolute_tolerance_quadrature, max_num_steps, num_steps_between_checkpoints, interpolation_polynomial, solver_forward, solver_backward, msgs, args...); } }; #endif
57.525926
80
0.578419
[ "vector" ]
998080d8f1d8d3214cde342844c35abc67e6d0b5
6,325
cpp
C++
android/native-audio-so.cpp
xiushudongfang/native
40848ae4b64907fec31b2562fc977c043133a275
[ "MIT" ]
null
null
null
android/native-audio-so.cpp
xiushudongfang/native
40848ae4b64907fec31b2562fc977c043133a275
[ "MIT" ]
null
null
null
android/native-audio-so.cpp
xiushudongfang/native
40848ae4b64907fec31b2562fc977c043133a275
[ "MIT" ]
null
null
null
// Minimal audio streaming using OpenSL. // // Loosely based on the Android NDK sample code. #include <assert.h> #include <string.h> #include <unistd.h> // for native audio #include <SLES/OpenSLES.h> #include <SLES/OpenSLES_Android.h> #include "../base/logging.h" #include "native-audio-so.h" // This is kinda ugly, but for simplicity I've left these as globals just like in the sample, // as there's not really any use case for this where we have multiple audio devices yet. // engine interfaces static SLObjectItf engineObject; static SLEngineItf engineEngine; static SLObjectItf outputMixObject; // buffer queue player interfaces static SLObjectItf bqPlayerObject = NULL; static SLPlayItf bqPlayerPlay; static SLAndroidSimpleBufferQueueItf bqPlayerBufferQueue; static SLMuteSoloItf bqPlayerMuteSolo; static SLVolumeItf bqPlayerVolume; // Double buffering. static short *buffer[2]; static int curBuffer = 0; static int framesPerBuffer; int sampleRate; static AndroidAudioCallback audioCallback; // This callback handler is called every time a buffer finishes playing. // The documentation available is very unclear about how to best manage buffers. // I've chosen to this approach: Instantly enqueue a buffer that was rendered to the last time, // and then render the next. Hopefully it's okay to spend time in this callback after having enqueued. static void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context) { if (bq != bqPlayerBufferQueue) { ELOG("Wrong bq!"); return; } int renderedFrames = audioCallback(buffer[curBuffer], framesPerBuffer); int sizeInBytes = framesPerBuffer * 2 * sizeof(short); memset(buffer[curBuffer] + renderedFrames * 2, 0, (framesPerBuffer - renderedFrames) * 4); SLresult result = (*bqPlayerBufferQueue)->Enqueue(bqPlayerBufferQueue, buffer[curBuffer], sizeInBytes); // Comment from sample code: // the most likely other result is SL_RESULT_BUFFER_INSUFFICIENT, // which for this code example would indicate a programming error if (result != SL_RESULT_SUCCESS) { ELOG("OpenSL ES: Failed to enqueue! %i %i", renderedFrames, sizeInBytes); } curBuffer ^= 1; // Switch buffer } // create the engine and output mix objects extern "C" bool OpenSLWrap_Init(AndroidAudioCallback cb, int _FramesPerBuffer, int _SampleRate) { audioCallback = cb; framesPerBuffer = _FramesPerBuffer; if (framesPerBuffer == 0) framesPerBuffer = 256; if (framesPerBuffer < 32) framesPerBuffer = 32; sampleRate = _SampleRate; if (sampleRate != 44100 && sampleRate != 48000) { ELOG("Invalid sample rate %i - choosing 44100", sampleRate); sampleRate = 44100; } buffer[0] = new short[framesPerBuffer * 2]; buffer[1] = new short[framesPerBuffer * 2]; SLresult result; // create engine result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == result); result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); assert(SL_RESULT_SUCCESS == result); result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 0, 0, 0); assert(SL_RESULT_SUCCESS == result); result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); SLuint32 sr = SL_SAMPLINGRATE_44_1; if (sampleRate == 48000) { sr = SL_SAMPLINGRATE_48; } SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2}; SLDataFormat_PCM format_pcm = { SL_DATAFORMAT_PCM, 2, sr, SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT, SL_BYTEORDER_LITTLEENDIAN }; SLDataSource audioSrc = {&loc_bufq, &format_pcm}; // configure audio sink SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMixObject}; SLDataSink audioSnk = {&loc_outmix, NULL}; // create audio player const SLInterfaceID ids[2] = {SL_IID_BUFFERQUEUE, SL_IID_VOLUME}; const SLboolean req[2] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; result = (*engineEngine)->CreateAudioPlayer(engineEngine, &bqPlayerObject, &audioSrc, &audioSnk, 2, ids, req); assert(SL_RESULT_SUCCESS == result); result = (*bqPlayerObject)->Realize(bqPlayerObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_PLAY, &bqPlayerPlay); assert(SL_RESULT_SUCCESS == result); result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_BUFFERQUEUE, &bqPlayerBufferQueue); assert(SL_RESULT_SUCCESS == result); result = (*bqPlayerBufferQueue)->RegisterCallback(bqPlayerBufferQueue, bqPlayerCallback, NULL); assert(SL_RESULT_SUCCESS == result); result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_VOLUME, &bqPlayerVolume); assert(SL_RESULT_SUCCESS == result); result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING); assert(SL_RESULT_SUCCESS == result); // Render and enqueue a first buffer. (or should we just play the buffer empty?) curBuffer = 0; audioCallback(buffer[curBuffer], framesPerBuffer); result = (*bqPlayerBufferQueue)->Enqueue(bqPlayerBufferQueue, buffer[curBuffer], sizeof(buffer[curBuffer])); if (SL_RESULT_SUCCESS != result) { return false; } curBuffer ^= 1; return true; } // shut down the native audio system extern "C" void OpenSLWrap_Shutdown() { SLresult result; ILOG("OpenSLWrap_Shutdown - stopping playback"); result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_STOPPED); if (SL_RESULT_SUCCESS != result) { ELOG("SetPlayState failed"); } ILOG("OpenSLWrap_Shutdown - deleting player object"); if (bqPlayerObject != NULL) { (*bqPlayerObject)->Destroy(bqPlayerObject); bqPlayerObject = NULL; bqPlayerPlay = NULL; bqPlayerBufferQueue = NULL; bqPlayerMuteSolo = NULL; bqPlayerVolume = NULL; } ILOG("OpenSLWrap_Shutdown - deleting mix object"); if (outputMixObject != NULL) { (*outputMixObject)->Destroy(outputMixObject); outputMixObject = NULL; } ILOG("OpenSLWrap_Shutdown - deleting engine object"); if (engineObject != NULL) { (*engineObject)->Destroy(engineObject); engineObject = NULL; engineEngine = NULL; } delete [] buffer[0]; delete [] buffer[1]; ILOG("OpenSLWrap_Shutdown - finished"); }
33.643617
111
0.76
[ "render", "object" ]
998748da71991efba199e6ba987557d3e60fe095
4,609
cpp
C++
smoke-android-file/src/main/cpp/test/smoke_jni_test.cpp
mingyuans/smoke
d90270aa2bc9e00d0e497923bb621c4b63464e5f
[ "Apache-2.0" ]
null
null
null
smoke-android-file/src/main/cpp/test/smoke_jni_test.cpp
mingyuans/smoke
d90270aa2bc9e00d0e497923bb621c4b63464e5f
[ "Apache-2.0" ]
null
null
null
smoke-android-file/src/main/cpp/test/smoke_jni_test.cpp
mingyuans/smoke
d90270aa2bc9e00d0e497923bb621c4b63464e5f
[ "Apache-2.0" ]
null
null
null
// // Created by yanxq on 2017/2/18. // #include "smoke_jni_test.h" #include "../smoke_utils/file_util.h" #include "../smoke_jni_log.h" #include "../smoke_appender.h" #include <string> # define ARRAY_LEN(x) ((int) (sizeof(x) / sizeof((x)[0]))) using namespace std; string __package_name="com/mingyuans/smoke"; static bool __jni_is_dir(JNIEnv *env, jobject thiz, jstring _file_path) { const char * file_path = env->GetStringUTFChars(_file_path,0); bool result = fileUtil::is_dir(file_path); env->ReleaseStringUTFChars(_file_path,file_path); return result; } static bool __jni_mk_dir(JNIEnv *jniEnv,jobject thiz, jstring _file_path) { const char * file_path = jniEnv->GetStringUTFChars(_file_path,0); bool result = fileUtil::create_dirs(file_path); jniEnv->ReleaseStringUTFChars(_file_path,file_path); return result; } static bool __jni_delete_dir(JNIEnv *jniEnv, jobject thiz, jstring _file_path) { const char * file_path = jniEnv->GetStringUTFChars(_file_path,0); bool result = fileUtil::delete_dir(file_path); jniEnv->ReleaseStringUTFChars(_file_path,file_path); return result; } static long __jni_last_modify_time(JNIEnv *env, jobject object, jstring _file_path) { const char * file_path = env->GetStringUTFChars(_file_path,0); bool result = fileUtil::last_write_time(file_path); env->ReleaseStringUTFChars(_file_path,file_path); return result; } static jobjectArray __jni_find_dir_files(JNIEnv *env, jobject object,jstring _file_path) { const char *file_path = env->GetStringUTFChars(_file_path,0); std::string **child_files = new std::string*[100]; int count = fileUtil::find_dir_child_files(file_path,100,child_files); jclass stringClazz = env->FindClass("java/lang/String"); jobjectArray result = env->NewObjectArray(count,stringClazz,NULL); for (int i = 0; i < count; ++i) { std::string *child = child_files[i]; jstring child_str = env->NewStringUTF(child->c_str()); env->SetObjectArrayElement(result,i,child_str); delete child; } delete child_files; env->ReleaseStringUTFChars(_file_path,file_path); return result; } static void __jni_make_native_crash() { char *null_array = NULL; char null_char = *null_array; } static void __register_file_util_test(JNIEnv *env) { JNINativeMethod nativeMethods[] = { {"is_directory","(Ljava/lang/String;)Z",(void *)__jni_is_dir}, {"mk_dir","(Ljava/lang/String;)Z",(void *)__jni_mk_dir}, {"delete_dir","(Ljava/lang/String;)Z",(void *)__jni_delete_dir}, {"last_modify_time","(Ljava/lang/String;)J",(void *)__jni_last_modify_time}, {"find_dir_files","(Ljava/lang/String;)[Ljava/lang/String;",(void *)__jni_find_dir_files}, {"make_native_crash","()V",(void *)__jni_make_native_crash}, }; string class_name = __package_name + "/JniFileUtilTest"; jclass file_util_test_class = env->FindClass(class_name.c_str()); if (file_util_test_class != NULL) { env->RegisterNatives(file_util_test_class, nativeMethods, ARRAY_LEN(nativeMethods)); } } static void __test_appender_on(JNIEnv *env, jobject object, jstring dir_, jstring cache_dir_,jstring prefixe_) { const char *dir = env->GetStringUTFChars(dir_,0); const char *cache_dir = env->GetStringUTFChars(cache_dir_,0); const char *name_prefix = env->GetStringUTFChars(prefixe_,0); appender_open(AppenderMode::MODE_ASYNC,dir,cache_dir,name_prefix,"sm"); env->ReleaseStringUTFChars(dir_,dir); env->ReleaseStringUTFChars(cache_dir_,cache_dir); env->ReleaseStringUTFChars(prefixe_,name_prefix); } static void __register_smoke_jni_test(JNIEnv *env) { JNINativeMethod nativeMethods[] = { {"appender_open","(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",(void *)__test_appender_on}, }; string class_name = __package_name + "/SmokeJniTest"; jclass file_util_test_class = env->FindClass(class_name.c_str()); if (file_util_test_class != NULL) { env->RegisterNatives(file_util_test_class, nativeMethods, ARRAY_LEN(nativeMethods)); } } void register_test_methods(JNIEnv *env) { __register_file_util_test(env); __register_smoke_jni_test(env); } JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv* env = NULL; jint result = -1; if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) { return result; } smoke_jni::console_verbose(__FUNCTION__,"jni onLoad"); register_test_methods(env); // 返回jni的版本 return JNI_VERSION_1_4; }
36.007813
117
0.710566
[ "object" ]
998cc90cbbfe4f146a5e0eec3b01a23dd0af3bca
6,966
cxx
C++
smtk/bridge/discrete/operation/vtkMergeOperatorBase.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
smtk/bridge/discrete/operation/vtkMergeOperatorBase.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
4
2016-11-10T15:49:51.000Z
2017-02-06T23:24:16.000Z
smtk/bridge/discrete/operation/vtkMergeOperatorBase.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "vtkMergeOperatorBase.h" #include "vtkDiscreteModel.h" #include "vtkDiscreteModelEdge.h" #include "vtkDiscreteModelFace.h" #include "vtkDiscreteModelRegion.h" #include "vtkDiscreteModelVertex.h" #include <vtkIdTypeArray.h> #include <vtkObjectFactory.h> #include <vtkSmartPointer.h> vtkStandardNewMacro(vtkMergeOperatorBase); vtkCxxSetObjectMacro(vtkMergeOperatorBase, LowerDimensionalIds, vtkIdTypeArray); vtkMergeOperatorBase::vtkMergeOperatorBase() { this->LowerDimensionalIds = vtkIdTypeArray::New(); this->LowerDimensionalIds->SetNumberOfComponents(1); this->LowerDimensionalIds->SetNumberOfTuples(0); this->TargetId = 0; this->IsTargetIdSet = 0; this->SourceId = 0; this->IsSourceIdSet = 0; } vtkMergeOperatorBase::~vtkMergeOperatorBase() { if(this->LowerDimensionalIds) { LowerDimensionalIds->Delete(); } } void vtkMergeOperatorBase::SetTargetId(vtkIdType targetId) { this->IsTargetIdSet = 1; if(targetId != this->TargetId) { this->Modified(); this->TargetId = targetId; } } void vtkMergeOperatorBase::SetSourceId(vtkIdType sourceId) { this->IsSourceIdSet = 1; if(sourceId != this->SourceId) { this->Modified(); this->SourceId = sourceId; } } void vtkMergeOperatorBase::AddLowerDimensionalId(vtkIdType Id) { this->LowerDimensionalIds->InsertNextTupleValue(&Id); } void vtkMergeOperatorBase::RemoveAllLowerDimensionalIds() { this->LowerDimensionalIds->SetNumberOfTuples(0); } vtkDiscreteModelGeometricEntity* vtkMergeOperatorBase::GetTargetModelEntity( vtkDiscreteModel* Model) { if(Model == 0 || this->IsTargetIdSet == 0) { return 0; } vtkDiscreteModelFace* Face = vtkDiscreteModelFace::SafeDownCast( Model->GetModelEntity(vtkModelFaceType, this->TargetId)); if(Face) { return Face; } vtkDiscreteModelRegion* Region = vtkDiscreteModelRegion::SafeDownCast( Model->GetModelEntity(vtkModelRegionType, this->TargetId)); if(Region) { return Region; } vtkDiscreteModelEdge* Edge = vtkDiscreteModelEdge::SafeDownCast( Model->GetModelEntity(vtkModelEdgeType, this->TargetId)); if(Edge) { return Edge; } vtkWarningMacro("Problem getting model entity."); return 0; } vtkDiscreteModelGeometricEntity* vtkMergeOperatorBase::GetSourceModelEntity( vtkDiscreteModel* model) { if(model == 0 || this->IsSourceIdSet == 0) { return 0; } if(vtkDiscreteModelFace* face = vtkDiscreteModelFace::SafeDownCast( model->GetModelEntity(vtkModelFaceType, this->SourceId))) { return face; } if(vtkDiscreteModelRegion* region = vtkDiscreteModelRegion::SafeDownCast( model->GetModelEntity(vtkModelRegionType, this->SourceId))) { return region; } if(vtkDiscreteModelEdge* edge = vtkDiscreteModelEdge::SafeDownCast( model->GetModelEntity(vtkModelEdgeType, this->SourceId))) { return edge; } vtkWarningMacro("Problem getting model entity."); return 0; } bool vtkMergeOperatorBase::AbleToOperate(vtkDiscreteModel* model) { if(!model) { vtkErrorMacro("Passed in a null model."); return 0; } if(this->GetIsTargetIdSet() == 0) { vtkErrorMacro("No target id specified."); return 0; } if(this->GetIsSourceIdSet() == 0) { vtkErrorMacro("No source id set."); return 0; } vtkModelEntity* targetEntity = model->GetModelEntity(this->TargetId); if(vtkDiscreteModelFace::SafeDownCast(targetEntity) == 0 && vtkDiscreteModelRegion::SafeDownCast(targetEntity) == 0 && vtkDiscreteModelEdge::SafeDownCast(targetEntity) == 0 ) { return 0; } int targetEntityType = targetEntity->GetType(); vtkModelEntity* sourceEntity = model->GetModelEntity(this->SourceId); if(targetEntityType != sourceEntity->GetType()) { return 0; } // if we are merging model faces for a 3D model we need to make sure that // all of them have the same regions/materials on both sides if(targetEntityType == vtkModelFaceType) { vtkModelRegion* sides[2] = {0,0}; sides[0] = vtkModelFace::SafeDownCast(targetEntity)->GetModelRegion(0); sides[1] = vtkModelFace::SafeDownCast(targetEntity)->GetModelRegion(1); if(sides[0]!=vtkModelFace::SafeDownCast(sourceEntity)->GetModelRegion(0) && sides[0]!=vtkModelFace::SafeDownCast(sourceEntity)->GetModelRegion(1)) { vtkDebugMacro("Model faces do not share the same regions."); return 0; } if(sides[1]!=vtkModelFace::SafeDownCast(sourceEntity)->GetModelRegion(0) && sides[1]!=vtkModelFace::SafeDownCast(sourceEntity)->GetModelRegion(1)) { vtkDebugMacro("Model faces do not share the same regions."); return 0; } } else if(targetEntityType == vtkModelEdgeType) { if(this->LowerDimensionalIds->GetNumberOfTuples() < 1 || this->LowerDimensionalIds->GetNumberOfTuples() > 2) { vtkDebugMacro("Wrong number of end nodes inputted for merge."); return 0; } vtkModelEdge* sourceEdge = vtkModelEdge::SafeDownCast(sourceEntity); vtkModelEdge* targetEdge = vtkModelEdge::SafeDownCast(targetEntity); for(vtkIdType i=0;i<this->LowerDimensionalIds->GetNumberOfTuples();i++) { vtkModelVertex* sharedVertex = vtkModelVertex::SafeDownCast( model->GetModelEntity(vtkModelVertexType, this->LowerDimensionalIds->GetValue(i))); if(sharedVertex == 0) { return 0; } if(targetEdge->GetAdjacentModelVertex(0) != sharedVertex && targetEdge->GetAdjacentModelVertex(1) != sharedVertex) { return 0; } if(sourceEdge->GetAdjacentModelVertex(0) != sharedVertex && sourceEdge->GetAdjacentModelVertex(1) != sharedVertex) { return 0; } } } return 1; } bool vtkMergeOperatorBase::Operate(vtkDiscreteModel* model) { vtkDiscreteModelGeometricEntity* targetEntity = this->GetTargetModelEntity(model); return targetEntity->Merge(this->GetSourceModelEntity(model), this->LowerDimensionalIds); } void vtkMergeOperatorBase::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "SourceId: " << this->SourceId << endl; os << indent << "IsSourceIdSet: " << this->IsSourceIdSet << endl; os << indent << "LowerDimensionalIds: " << this->LowerDimensionalIds << endl; os << indent << "TargetId: " << this->TargetId << endl; os << indent << "IsTargetIdSet: " << this->IsTargetIdSet << endl; }
30.025862
91
0.68375
[ "model", "3d" ]
998e42ab97d72535ccf3901420ac098e086aa782
5,444
cpp
C++
Big Homework/Game-of-the-Amazons-master/botZoneVersion_RandomMovement.cpp
zyzkevin/Introduction-to-Computing
0838126dda56ee20834dcfe472f9ab9effd8d8b3
[ "MIT" ]
null
null
null
Big Homework/Game-of-the-Amazons-master/botZoneVersion_RandomMovement.cpp
zyzkevin/Introduction-to-Computing
0838126dda56ee20834dcfe472f9ab9effd8d8b3
[ "MIT" ]
null
null
null
Big Homework/Game-of-the-Amazons-master/botZoneVersion_RandomMovement.cpp
zyzkevin/Introduction-to-Computing
0838126dda56ee20834dcfe472f9ab9effd8d8b3
[ "MIT" ]
null
null
null
// // main.cpp // AmazonsProject_Botzone_NewStructure // // Created by 장준우 on 27/12/2018. // Copyright © 2018 Joonwoo Percy Jang. All rights reserved. // #include <iostream> #include <math.h> #include <cmath> #include <cstring> #include <string.h> #include <iomanip> #include <stdlib.h> #include <vector> #include <algorithm> #include <cstdlib> #include <ctime> #define GRIDSIZE 8 #define OBSTACLE 2 #define EMPTY 0 #define grid_black 1 #define grid_white -1 using namespace std; int currBotColor; // Current color of the bot(1 = black ,-1 = white) int dx[] = { -1,-1,-1,0,0,1,1,1 }; int dy[] = { -1,0,1,-1,1,-1,0,1 }; struct Grid{ int xPos; //Variable to indicate the X-coordinate of the grid on the board int yPos; //Variable to indicate the X-coordinate of the grid on the board bool occupied; //variable to indicate if anything is on the grid (blockingstones, stones) int gridState; //OBSTACLE, }; Grid gridInfo[8][8]; bool checkInBoard(int x1, int y1){ if((x1<8 && x1>=0) && (y1<8 && y1>=0)){ return true; } return false; } bool moveStone(int x0, int y0, int x1, int y1, int x2, int y2, int color, bool check_only) { if ((!checkInBoard(x0, y0)) || (!checkInBoard(x1, y1)) || (!checkInBoard(x2, y2))) return false; if (gridInfo[x0][y0].gridState != color || gridInfo[x1][y1].gridState != EMPTY) return false; if ((gridInfo[x2][y2].gridState != 0) && !(x2 == x0 && y2 == y0)) return false; if (!check_only) { gridInfo[x0][y0].gridState = 0; gridInfo[x1][y1].gridState = color; gridInfo[x2][y2].gridState = OBSTACLE; } return true; } int main(){ int x0, y0, x1, y1, x2, y2; // 初始化棋盘 gridInfo[0][(GRIDSIZE - 1) / 3].gridState = gridInfo[(GRIDSIZE - 1) / 3][0].gridState = gridInfo[GRIDSIZE - 1 - ((GRIDSIZE - 1) / 3)][0].gridState = gridInfo[GRIDSIZE - 1][(GRIDSIZE - 1) / 3].gridState = grid_black; gridInfo[0][GRIDSIZE - 1 - ((GRIDSIZE - 1) / 3)].gridState = gridInfo[(GRIDSIZE - 1) / 3][GRIDSIZE - 1].gridState = gridInfo[GRIDSIZE - 1 - ((GRIDSIZE - 1) / 3)][GRIDSIZE - 1].gridState = gridInfo[GRIDSIZE - 1][GRIDSIZE - 1 - ((GRIDSIZE - 1) / 3)].gridState = grid_white; int turnID; cin >> turnID; // 读入到当前回合为止,自己和对手的所有行动,从而把局面恢复到当前回合 currBotColor = grid_white; // 先假设自己是白方 for (int i = 0; i < turnID; i++) { // 根据这些输入输出逐渐恢复状态到当前回合 // 首先是对手行动 cin >> x0 >> y0 >> x1 >> y1 >> x2 >> y2; if (x0 == -1) currBotColor = grid_black; // 第一回合收到坐标是-1, -1,说明我是黑方 else moveStone(x0, y0, x1, y1, x2, y2, -currBotColor, false); // 模拟对方落子 // 然后是自己当时的行动 // 对手行动总比自己行动多一个 if (i < turnID - 1) { cin >> x0 >> y0 >> x1 >> y1 >> x2 >> y2; if (x0 >= 0) moveStone(x0, y0, x1, y1, x2, y2, currBotColor, false); // 模拟己方落子 } } // 做出决策(你只需修改以下部分) // 这里枚举了所有可能的下法,以便之后随机用…… int beginPos[3000][2], possiblePos[3000][2], obstaclePos[3000][2]; int posCount = 0, choice; for (int i = 0; i < GRIDSIZE; ++i) { for (int j = 0; j < GRIDSIZE; ++j) { for (int k = 0; k < 8; ++k) { for (int delta1 = 1; delta1 < GRIDSIZE; delta1++) { int xx = i + dx[k] * delta1; int yy = j + dy[k] * delta1; if (gridInfo[xx][yy].gridState != 0 || !checkInBoard(xx, yy)) break; for (int l = 0; l < 8; ++l) { for (int delta2 = 1; delta2 < GRIDSIZE; delta2++) { int xxx = xx + dx[l] * delta2; int yyy = yy + dy[l] * delta2; if (!checkInBoard(xxx, yyy)) break; if (gridInfo[xxx][yyy].gridState != 0 && !(i == xxx && j == yyy)) break; if (moveStone(i, j, xx, yy, xxx, yyy, currBotColor, true)) { beginPos[posCount][0] = i; beginPos[posCount][1] = j; possiblePos[posCount][0] = xx; possiblePos[posCount][1] = yy; obstaclePos[posCount][0] = xxx; obstaclePos[posCount++][1] = yyy; } } } } } } } int startX, startY, resultX, resultY, obstacleX, obstacleY; if (posCount > 0) { srand(time(0)); choice = rand() % posCount; startX = beginPos[choice][0]; startY = beginPos[choice][1]; resultX = possiblePos[choice][0]; resultY = possiblePos[choice][1]; obstacleX = obstaclePos[choice][0]; obstacleY = obstaclePos[choice][1]; } else { startX = -1; startY = -1; resultX = -1; resultY = -1; obstacleX = -1; obstacleY = -1; } // 决策结束,输出结果(你只需修改以上部分) cout << startX << ' ' << startY << ' ' << resultX << ' ' << resultY << ' ' << obstacleX << ' ' << obstacleY << endl; return 0; }
31.651163
120
0.484386
[ "vector" ]
99908fe6d3e5a5494731e1eb3002e0aa305912ee
4,163
cpp
C++
src/orocos_kinematics_dynamics/orocos_kdl/examples/trajectory_example.cpp
matchRos/simulation_multirobots
286c5add84d521ad371b2c8961dea872c34e7da2
[ "BSD-2-Clause" ]
742
2017-07-05T02:49:36.000Z
2022-03-30T12:55:43.000Z
src/orocos_kinematics_dynamics/orocos_kdl/examples/trajectory_example.cpp
matchRos/simulation_multirobots
286c5add84d521ad371b2c8961dea872c34e7da2
[ "BSD-2-Clause" ]
73
2017-07-06T12:50:51.000Z
2022-03-07T08:07:07.000Z
src/orocos_kinematics_dynamics/orocos_kdl/examples/trajectory_example.cpp
matchRos/simulation_multirobots
286c5add84d521ad371b2c8961dea872c34e7da2
[ "BSD-2-Clause" ]
425
2017-07-04T22:03:29.000Z
2022-03-29T06:59:06.000Z
/** * \file path_example.cpp * An example to demonstrate the use of trajectory generation * functions. * * There are is a matlab/octave file in the examples directory to visualise the results * of this example program. (visualize_trajectory.m) * */ #include <frames.hpp> #include <frames_io.hpp> #include <trajectory.hpp> #include <trajectory_segment.hpp> #include <trajectory_stationary.hpp> #include <trajectory_composite.hpp> #include <trajectory_composite.hpp> #include <velocityprofile_trap.hpp> #include <path_roundedcomposite.hpp> #include <rotational_interpolation_sa.hpp> #include <utilities/error.h> #include <trajectory_composite.hpp> int main(int argc,char* argv[]) { using namespace KDL; // Create the trajectory: // use try/catch to catch any exceptions thrown. // NOTE: exceptions will become obsolete in a future version. try { // Path_RoundedComposite defines the geometric path along // which the robot will move. // Path_RoundedComposite* path = new Path_RoundedComposite(0.2,0.01,new RotationalInterpolation_SingleAxis()); // The routines are now robust against segments that are parallel. // When the routines are parallel, no rounding is needed, and no attempt is made // add constructing a rounding arc. // (It is still not possible when the segments are on top of each other) // Note that you can only rotate in a deterministic way over an angle less then M_PI! // With an angle == M_PI, you cannot predict over which side will be rotated. // With an angle > M_PI, the routine will rotate over 2*M_PI-angle. // If you need to rotate over a larger angle, you need to introduce intermediate points. // So, there is a common use case for using parallel segments. path->Add(Frame(Rotation::RPY(M_PI,0,0), Vector(-1,0,0))); path->Add(Frame(Rotation::RPY(M_PI/2,0,0), Vector(-0.5,0,0))); path->Add(Frame(Rotation::RPY(0,0,0), Vector(0,0,0))); path->Add(Frame(Rotation::RPY(0.7,0.7,0.7), Vector(1,1,1))); path->Add(Frame(Rotation::RPY(0,0.7,0), Vector(1.5,0.3,0))); path->Add(Frame(Rotation::RPY(0.7,0.7,0), Vector(1,1,0))); // always call Finish() at the end, otherwise the last segment will not be added. path->Finish(); // Trajectory defines a motion of the robot along a path. // This defines a trapezoidal velocity profile. VelocityProfile* velpref = new VelocityProfile_Trap(0.5,0.1); velpref->SetProfile(0,path->PathLength()); Trajectory* traject = new Trajectory_Segment(path, velpref); Trajectory_Composite* ctraject = new Trajectory_Composite(); ctraject->Add(traject); ctraject->Add(new Trajectory_Stationary(1.0,Frame(Rotation::RPY(0.7,0.7,0), Vector(1,1,0)))); // use the trajectory double dt=0.1; std::ofstream of("./trajectory.dat"); for (double t=0.0; t <= traject->Duration(); t+= dt) { Frame current_pose; current_pose = traject->Pos(t); for (int i=0;i<4;++i) for (int j=0;j<4;++j) of << current_pose(i,j) << "\t"; of << "\n"; // also velocities and accelerations are available ! //traject->Vel(t); //traject->Acc(t); } of.close(); // you can get some meta-info on the path: for (int segmentnr=0; segmentnr < path->GetNrOfSegments(); segmentnr++) { double starts,ends; Path::IdentifierType pathtype; if (segmentnr==0) { starts = 0.0; } else { starts = path->GetLengthToEndOfSegment(segmentnr-1); } ends = path->GetLengthToEndOfSegment(segmentnr); pathtype = path->GetSegment(segmentnr)->getIdentifier(); std::cout << "segment " << segmentnr << " runs from s="<<starts << " to s=" <<ends; switch(pathtype) { case Path::ID_CIRCLE: std::cout << " circle"; break; case Path::ID_LINE: std::cout << " line "; break; default: std::cout << " unknown "; break; } std::cout << std::endl; } std::cout << " trajectory written to the ./trajectory.dat file " << std::endl; delete ctraject; } catch(Error& error) { std::cout <<"I encountered this error : " << error.Description() << std::endl; std::cout << "with the following type " << error.GetType() << std::endl; } }
35.279661
109
0.673793
[ "vector" ]
99928fbeab43e92c36c36f416c7476102de528c4
4,828
cpp
C++
code/auto-compile.cpp
LiuTianyouOnLuogu/auto-compiler
8f9d603cbfd3752e83c6ad4af675b2329c1df2a6
[ "WTFPL" ]
1
2021-02-14T08:15:26.000Z
2021-02-14T08:15:26.000Z
code/auto-compile.cpp
LiuTianyouOnLuogu/auto-compiler
8f9d603cbfd3752e83c6ad4af675b2329c1df2a6
[ "WTFPL" ]
3
2021-02-17T06:07:01.000Z
2021-03-25T10:57:40.000Z
code/auto-compile.cpp
LiuTianyouOnLuogu/auto-compiler
8f9d603cbfd3752e83c6ad4af675b2329c1df2a6
[ "WTFPL" ]
null
null
null
#include "language/language.hpp" #ifdef __cplusplus extern "C"{ #endif #include "../Iniparser/iniparser.h" #ifdef __cplusplus } #endif #include "functions/functions.hpp" #include <iostream> #include <cstring> #include <thread> #include <list> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> #include <unistd.h> using namespace std; struct threadPlus{ int number; thread* t; threadPlus(int no, thread* _t){ number = no; t = _t; } }; list<threadPlus> threadPool; //线程池 list<string> Serial; //串行“指令集” int main_pid = 0; //主线程pid bool debug = false; //debug标志 char buffer[10240]; //全局buffer int system(string command){ pid_t pid; int status; if(command.empty()){ return 1; } if((pid = fork()) < 0){ status = -1; }else if(pid == 0){ execl("/bin/sh", "sh", "-c", command.c_str(), (char*)0); _exit(127); }else{ while(waitpid(pid, &status, 0) < 0){ if(errno != EINTR){ status = -1; break; } } } if(errno != 0 && debug == true){ clog << "system(): errno = " << errno << endl; } return status; } void CE(int sig){ cerr << "An Unexpeted Error Happened." << endl; system("cat error.log"); //system("rm /tmp/*.o"); exit(EXIT_FAILURE); } void subthread(const char* cmd, pid_t pid, bool t = false){ int test = 0; start: int status = system(cmd); if(status != 0){ if(t){ test++; if(status < 5) goto start; } kill(pid, SIGUSR1); //如果失败,发送失败信号 } } string itoa(int number){ snprintf(buffer, 10240, "%d", number); return buffer; } int main(int argc, char** argv){ signal(SIGCHLD, SIG_DFL); signal(SIGUSR1, CE); main_pid = getpid(); system("echo > error.log"); //清空日志 string objs; string filename = "ac.ini"; dictionary* ini = NULL; string link_cmd = "gcc "; int number = 0; FILE* pwd_s = popen("pwd", "r"); string self = argv[0]; //命令行自身表示 string pwd; fgets(&pwd[0], 1024, pwd_s); pclose(pwd_s); if(argc == 2 && !strcmp(argv[1], "--debug")){ debug = true; goto start; //跳入正常的处理 }else if(argc == 2 && !strcmp(argv[1], "--help")){ return system("cat ../README.md"); }else if(argc == 2){ filename = argv[1]; //指定ac.ini文件 }else if(argc==1){ start:; ini = iniparser_load(filename.c_str()); if(ini == NULL){ cerr << "Error: Can NOT read config file!" << endl; return EXIT_FAILURE; } for(int i = 0; i < iniparser_getnsec(ini); i++){ string name = iniparser_getsecname(ini, i); if(name == "main") continue; string cmd; char pid[1024]; snprintf(buffer, 10240, "%d", i); snprintf(pid, 10240, "%d", getpid()); cmd = pwd + "submission " + filename + " " + buffer + " 2>> error.log"; //clog << "Command: " << cmd << endl; std::string object = name.substr(0, name.find(".")); objs += "/tmp/" + object + ".o "; if(!strcmp(iniparser_getstring(ini, (name + ":serial").c_str(), NULLSTR), "true")){ Serial.push_back(cmd); continue; } threadPool.push_back(threadPlus(number++, 0)); threadPool.back().t = new thread(subthread, cmd.c_str(), main_pid, false); clog << "[" << threadPool.back().t->get_id() << "]" << "Compiling " + name + "..." << endl; if(threadPool.back().t->joinable()) threadPool.back().t->detach(); //有时线程执行过快,无法脱离 } while(!threadPool.empty()){ //测试:多线程处理 if(threadPool.back().t->joinable()) { threadPool.front().t->join(); //加入主线程 clog << "[" << threadPool.back().t->get_id() << "]" << "Joining the main thread..." << endl; } threadPool.pop_front(); } while(!Serial.empty()){ //处理串行任务 clog << "Serial: " << Serial.front().c_str() << endl; subthread(Serial.front().c_str(), main_pid); Serial.pop_front(); } clog << "Linking objects..." << endl; link_cmd += objs + " "; link_cmd += (string("-o ") + iniparser_getstring(ini, "main:name", NULLSTR)) + " "; link_cmd += parser(iniparser_getstring(ini, "main:library", NULLSTR), "-l", " "); link_cmd += " 2>> error.log"; subthread(link_cmd.c_str(), main_pid, true); if(!debug) remove("error.log"); //system("rm /tmp/*.o"); iniparser_freedict(ini); return EXIT_SUCCESS; }else{ cerr << "Error: Invaild command line!" << endl; return EXIT_FAILURE; } }
30.175
108
0.521748
[ "object" ]
99a0253897118474477d06617840d78762772d04
6,933
hpp
C++
DT3Core/Types/Math/Box.hpp
9heart/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
3
2018-10-05T15:03:27.000Z
2019-03-19T11:01:56.000Z
DT3Core/Types/Math/Box.hpp
pakoito/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
null
null
null
DT3Core/Types/Math/Box.hpp
pakoito/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
3
2016-01-14T07:51:52.000Z
2021-08-21T08:02:51.000Z
#ifndef DT3_BOX #define DT3_BOX //============================================================================== /// /// File: Box.hpp /// /// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved. /// /// This file is subject to the terms and conditions defined in /// file 'LICENSE.txt', which is part of this source code package. /// //============================================================================== #include "DT3Core/Types/Base/BaseInclude.hpp" #include "DT3Core/Types/Math/Rectangle.hpp" #include "DT3Core/Types/Math/Vector3.hpp" //============================================================================== //============================================================================== namespace DT3 { //============================================================================== /// Forward declarations //============================================================================== class Stream; //============================================================================== /// Class //============================================================================== class Box: public Rectangle { public: DEFINE_TYPE_SIMPLE(Box,Rectangle) Box (void); Box (const Box &rhs); Box ( const DTfloat mx, const DTfloat px, const DTfloat my, const DTfloat py, const DTfloat mz, const DTfloat pz ); Box & operator = (const Box &rhs); ~Box (void); public: DTboolean operator == (const Box& rhs) const; DTboolean operator != (const Box& rhs) const; /// Sets the size of the box given the extents along all 3 axes. /// \param minus_x Minimum Coordinate along the X axis /// \param plus_x Maximum Coordinate along the X axis /// \param minus_y Minimum Coordinate along the Y axis /// \param plus_y Maximum Coordinate along the Y axis /// \param minus_z Minimum Coordinate along the Z axis /// \param plus_z Maximum Coordinate along the Z axis void set ( const DTfloat minus_x, const DTfloat plus_x, const DTfloat minus_y, const DTfloat plus_y, const DTfloat minus_z, const DTfloat plus_z ); /// Sets the extents of the box along the Z axis. /// \param minus_z Minimum Coordinate along the Z axis /// \param plus_z Maximum Coordinate along the Z axis void set_Z_extents (const DTfloat minus_z, const DTfloat plus_z) { _minus_z = minus_z; _plus_z = plus_z; } DEFINE_ACCESSORS(minus_z, set_minus_z, DTfloat, _minus_z) DEFINE_ACCESSORS(plus_z, set_plus_z, DTfloat, _plus_z) /// Invalidates the box void clear (void); /// Returns wether the box is still clear /// \return is box DTboolean is_clear (void) { return _minus_x >= _plus_x || _minus_y >= _plus_y || _minus_z >= _plus_z; } /// Offset the rectangle /// \param offset offset for the rectangle void offset (const Vector3 &offset); // // Info // /// Returns the area of the rectangle /// \return area DTfloat volume (void) const { return area() * depth(); } /// Returns the width of the rectangle /// \return width DTfloat depth (void) const { return _plus_z - _minus_z; } /// Returns the center of the rectangle /// \return center Vector3 center (void) const { return Vector3( 0.5F*(_minus_x + _plus_x), 0.5F*(_minus_y + _plus_y), 0.5F*(_minus_z + _plus_z) ); } // // Computation // /// Calculate the union of two boxes /// \param a box 1 /// \param b box 2 /// \return union of boxes static Box calc_union (const Box &a, const Box &b); /// Calculate the union of two boxes /// \param a box 1 /// \param b vector 2 /// \return union of boxes static Box calc_union (const Box &a, const Vector3 &b); /// Calculate the intersection of two boxes /// \param a box 1 /// \param b box 2 /// \return intersection of boxes static Box calc_intersection (const Box &a, const Box &b); // // Query // /// Check for overlap beteen two rectangles /// \param other Other rectangle /// \return is touching DTboolean is_touching (const Box &other); /// Check for overlap beteen two rectangles /// \param pt point /// \return is touching DTboolean is_touching (const Vector3 &pt) const; /// Is this box touching an extruded sphere? /// \param start point /// \param end point /// \param radius radius /// \return is touching ray DTboolean is_touching (const Vector3 &from, const Vector3 &to, const DTfloat r); /// Is this box touching a ray? /// \param start point /// \param end point /// \return is touching ray DTboolean is_touching (const Vector3 &from, const Vector3 &to); /// Returns the distance from the rectangle to the point /// \param pt point /// \return distance DTfloat distance_to_point (const Vector3 &pt) const; /// Returns the closest point in the rectangle /// \param pt point /// \return closest point const Vector3 closest_point (const Vector3 &pt) const; private: DTfloat _minus_z; /// Minus position on Z axis DTfloat _plus_z; /// Plus position on Z axis }; //============================================================================== /// Streaming operators //============================================================================== Stream& operator <<(Stream &s, const Box &v); Stream& operator >>(Stream &s, Box &v); //============================================================================== //============================================================================== } // DT3 #endif
38.731844
149
0.440646
[ "vector" ]
99a10bfd0c74f3fe334744e1093bc140ce343833
10,265
cc
C++
bench/qu8-vadd.cc
dedsec-9/XNNPACK
9eb52c7eb56a45ca9b250eb13c112d8adbd63999
[ "BSD-3-Clause" ]
1,125
2019-10-03T18:51:05.000Z
2022-03-30T14:01:11.000Z
bench/qu8-vadd.cc
dedsec-9/XNNPACK
9eb52c7eb56a45ca9b250eb13c112d8adbd63999
[ "BSD-3-Clause" ]
150
2019-10-07T19:55:21.000Z
2022-03-25T12:53:31.000Z
bench/qu8-vadd.cc
dedsec-9/XNNPACK
9eb52c7eb56a45ca9b250eb13c112d8adbd63999
[ "BSD-3-Clause" ]
207
2019-10-05T00:39:00.000Z
2022-03-28T08:32:22.000Z
// Copyright 2021 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <algorithm> #include <cmath> #include <functional> #include <random> #include <vector> #include <benchmark/benchmark.h> #include "bench/utils.h" #include <xnnpack/AlignedAllocator.h> #include <xnnpack/common.h> #include <xnnpack/params.h> #include <xnnpack/params-init.h> #include <xnnpack/vaddsub.h> static void qu8_vadd( benchmark::State& state, xnn_qu8_vaddsub_minmax_ukernel_function vadd, xnn_init_qu8_addsub_minmax_params_fn init_params, benchmark::utils::IsaCheckFunction isa_check = nullptr) { if (isa_check && !isa_check(state)) { return; } const size_t num_elements = state.range(0); std::random_device random_device; auto rng = std::mt19937(random_device()); auto u8rng = std::bind( std::uniform_int_distribution<uint32_t>(std::numeric_limits<uint8_t>::min(), std::numeric_limits<uint8_t>::max()), std::ref(rng)); std::vector<uint8_t, AlignedAllocator<uint8_t, 64>> a(num_elements); std::vector<uint8_t, AlignedAllocator<uint8_t, 64>> b(num_elements); std::vector<uint8_t, AlignedAllocator<uint8_t, 64>> sum(num_elements); std::generate(a.begin(), a.end(), std::ref(u8rng)); std::generate(b.begin(), b.end(), std::ref(u8rng)); union xnn_qu8_addsub_minmax_params params; init_params(&params, 127 /* a zero point */, 127 /* b zero point */, 127 /* output zero point */, 0.5f /* a-output scale */, 0.75f /* b-output scale */, std::numeric_limits<uint8_t>::min() + 1, std::numeric_limits<uint8_t>::max() - 1); for (auto _ : state) { vadd(num_elements * sizeof(uint8_t), a.data(), b.data(), sum.data(), &params); } const uint64_t cpu_frequency = benchmark::utils::GetCurrentCpuFrequency(); if (cpu_frequency != 0) { state.counters["cpufreq"] = cpu_frequency; } const size_t num_elements_per_iteration = num_elements; state.counters["num_elements"] = benchmark::Counter(uint64_t(state.iterations()) * num_elements_per_iteration, benchmark::Counter::kIsRate); const size_t bytes_per_iteration = 3 * num_elements * sizeof(int8_t); state.counters["bytes"] = benchmark::Counter(uint64_t(state.iterations()) * bytes_per_iteration, benchmark::Counter::kIsRate); } #if XNN_ARCH_ARM || XNN_ARCH_ARM64 BENCHMARK_CAPTURE(qu8_vadd, neon_ld64_x8, xnn_qu8_vadd_minmax_ukernel__neon_ld64_x8, xnn_init_qu8_add_minmax_neon_params, benchmark::utils::CheckNEON) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, neon_ld64_x16, xnn_qu8_vadd_minmax_ukernel__neon_ld64_x16, xnn_init_qu8_add_minmax_neon_params, benchmark::utils::CheckNEON) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, neon_ld64_x32, xnn_qu8_vadd_minmax_ukernel__neon_ld64_x32, xnn_init_qu8_add_minmax_neon_params, benchmark::utils::CheckNEON) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, neon_ld128_x16, xnn_qu8_vadd_minmax_ukernel__neon_ld128_x16, xnn_init_qu8_add_minmax_neon_params, benchmark::utils::CheckNEON) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); #endif // XNN_ARCH_ARM || XNN_ARCH_ARM64 #if XNN_ARCH_X86 || XNN_ARCH_X86_64 BENCHMARK_CAPTURE(qu8_vadd, avx512skx_mul32_ld128_x16, xnn_qu8_vadd_minmax_ukernel__avx512skx_mul32_ld128_x16, xnn_init_qu8_add_minmax_avx512_params, benchmark::utils::CheckAVX512SKX) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, avx512skx_mul32_ld128_x32, xnn_qu8_vadd_minmax_ukernel__avx512skx_mul32_ld128_x32, xnn_init_qu8_add_minmax_avx512_params, benchmark::utils::CheckAVX512SKX) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, avx2_mul32_ld64_x8, xnn_qu8_vadd_minmax_ukernel__avx2_mul32_ld64_x8, xnn_init_qu8_add_minmax_avx2_params, benchmark::utils::CheckAVX2) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, avx2_mul32_ld64_x16, xnn_qu8_vadd_minmax_ukernel__avx2_mul32_ld64_x16, xnn_init_qu8_add_minmax_avx2_params, benchmark::utils::CheckAVX2) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, xop_mul32_ld32_x8, xnn_qu8_vadd_minmax_ukernel__xop_mul32_ld32_x8, xnn_init_qu8_add_minmax_sse4_params, benchmark::utils::CheckXOP) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, xop_mul32_ld32_x16, xnn_qu8_vadd_minmax_ukernel__xop_mul32_ld32_x16, xnn_init_qu8_add_minmax_sse4_params, benchmark::utils::CheckXOP) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, avx_mul16_ld64_x8, xnn_qu8_vadd_minmax_ukernel__avx_mul16_ld64_x8, xnn_init_qu8_add_minmax_sse2_params, benchmark::utils::CheckAVX) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, avx_mul16_ld64_x16, xnn_qu8_vadd_minmax_ukernel__avx_mul16_ld64_x16, xnn_init_qu8_add_minmax_sse2_params, benchmark::utils::CheckAVX) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, avx_mul32_ld32_x8, xnn_qu8_vadd_minmax_ukernel__avx_mul32_ld32_x8, xnn_init_qu8_add_minmax_sse4_params, benchmark::utils::CheckAVX) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, avx_mul32_ld32_x16, xnn_qu8_vadd_minmax_ukernel__avx_mul32_ld32_x16, xnn_init_qu8_add_minmax_sse4_params, benchmark::utils::CheckAVX) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, sse41_mul16_ld64_x8, xnn_qu8_vadd_minmax_ukernel__sse41_mul16_ld64_x8, xnn_init_qu8_add_minmax_sse2_params, benchmark::utils::CheckSSE41) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, sse41_mul16_ld64_x16, xnn_qu8_vadd_minmax_ukernel__sse41_mul16_ld64_x16, xnn_init_qu8_add_minmax_sse2_params, benchmark::utils::CheckSSE41) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, sse41_mul32_ld32_x8, xnn_qu8_vadd_minmax_ukernel__sse41_mul32_ld32_x8, xnn_init_qu8_add_minmax_sse4_params, benchmark::utils::CheckSSE41) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, sse41_mul32_ld32_x16, xnn_qu8_vadd_minmax_ukernel__sse41_mul32_ld32_x16, xnn_init_qu8_add_minmax_sse4_params, benchmark::utils::CheckSSE41) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, sse2_mul16_ld64_x8, xnn_qu8_vadd_minmax_ukernel__sse2_mul16_ld64_x8, xnn_init_qu8_add_minmax_sse2_params) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, sse2_mul16_ld64_x16, xnn_qu8_vadd_minmax_ukernel__sse2_mul16_ld64_x16, xnn_init_qu8_add_minmax_sse2_params) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); #endif // XNN_ARCH_X86 || XNN_ARCH_X86_64 #if XNN_ARCH_WASMSIMD BENCHMARK_CAPTURE(qu8_vadd, wasmsimd_x8, xnn_qu8_vadd_minmax_ukernel__wasmsimd_x8, xnn_init_qu8_add_minmax_wasmsimd_params) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, wasmsimd_x16, xnn_qu8_vadd_minmax_ukernel__wasmsimd_x16, xnn_init_qu8_add_minmax_wasmsimd_params) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); #endif // XNN_ARCH_WASMSIMD BENCHMARK_CAPTURE(qu8_vadd, scalar_x1, xnn_qu8_vadd_minmax_ukernel__scalar_x1, xnn_init_qu8_add_minmax_scalar_params) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, scalar_x2, xnn_qu8_vadd_minmax_ukernel__scalar_x2, xnn_init_qu8_add_minmax_scalar_params) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); BENCHMARK_CAPTURE(qu8_vadd, scalar_x4, xnn_qu8_vadd_minmax_ukernel__scalar_x4, xnn_init_qu8_add_minmax_scalar_params) ->Apply(benchmark::utils::BinaryElementwiseParameters<uint8_t, uint8_t>) ->UseRealTime(); #ifndef XNNPACK_BENCHMARK_NO_MAIN BENCHMARK_MAIN(); #endif
44.055794
118
0.696152
[ "vector" ]
99a213781c5abcca31c58c639159c233bb4ef8b0
33,294
cpp
C++
src/Application/JavascriptModule/qscript_Ray.cpp
Joosua/tundra
c170c597d9af73a5ef08ea8ef4566665addc6664
[ "Apache-2.0" ]
31
2015-01-12T15:20:29.000Z
2022-02-03T10:04:17.000Z
src/Application/JavascriptModule/qscript_Ray.cpp
Joosua/tundra
c170c597d9af73a5ef08ea8ef4566665addc6664
[ "Apache-2.0" ]
2
2015-02-04T12:58:05.000Z
2016-01-04T15:46:48.000Z
src/Application/JavascriptModule/qscript_Ray.cpp
Joosua/tundra
c170c597d9af73a5ef08ea8ef4566665addc6664
[ "Apache-2.0" ]
20
2015-03-04T02:31:33.000Z
2022-02-13T18:12:55.000Z
#include "QtScriptBindingsHelpers.h" void ToExistingScriptValue_Ray(QScriptEngine *engine, const Ray &value, QScriptValue obj) { obj.setProperty("pos", qScriptValueFromValue(engine, value.pos), QScriptValue::Undeletable); obj.setProperty("dir", qScriptValueFromValue(engine, value.dir), QScriptValue::Undeletable); } static QScriptValue Ray_Ray(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 0) { printf("Error! Invalid number of arguments passed to function Ray_Ray in file %s, line %d!\nExpected 0, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray ret; memset(&ret, 0, sizeof ret); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Ray_float3_float3(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 2) { printf("Error! Invalid number of arguments passed to function Ray_Ray_float3_float3 in file %s, line %d!\nExpected 2, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } float3 pos = qscriptvalue_cast<float3>(context->argument(0)); float3 dir = qscriptvalue_cast<float3>(context->argument(1)); Ray ret(pos, dir); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Ray_Line(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Ray_Line in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Line line = qscriptvalue_cast<Line>(context->argument(0)); Ray ret(line); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Ray_LineSegment(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Ray_LineSegment in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } LineSegment lineSegment = qscriptvalue_cast<LineSegment>(context->argument(0)); Ray ret(lineSegment); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_IsFinite_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 0) { printf("Error! Invalid number of arguments passed to function Ray_IsFinite_const in file %s, line %d!\nExpected 0, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); bool ret = This.IsFinite(); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_GetPoint_float_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_GetPoint_float_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); float distance = qscriptvalue_cast<float>(context->argument(0)); float3 ret = This.GetPoint(distance); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Translate_float3(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Translate_float3 in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); float3 offset = qscriptvalue_cast<float3>(context->argument(0)); This.Translate(offset); ToExistingScriptValue_Ray(engine, This, context->thisObject()); return QScriptValue(); } static QScriptValue Ray_Transform_float3x3(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Transform_float3x3 in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); float3x3 transform = qscriptvalue_cast<float3x3>(context->argument(0)); This.Transform(transform); ToExistingScriptValue_Ray(engine, This, context->thisObject()); return QScriptValue(); } static QScriptValue Ray_Transform_float3x4(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Transform_float3x4 in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); float3x4 transform = qscriptvalue_cast<float3x4>(context->argument(0)); This.Transform(transform); ToExistingScriptValue_Ray(engine, This, context->thisObject()); return QScriptValue(); } static QScriptValue Ray_Transform_float4x4(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Transform_float4x4 in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); float4x4 transform = qscriptvalue_cast<float4x4>(context->argument(0)); This.Transform(transform); ToExistingScriptValue_Ray(engine, This, context->thisObject()); return QScriptValue(); } static QScriptValue Ray_Transform_Quat(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Transform_Quat in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); Quat transform = qscriptvalue_cast<Quat>(context->argument(0)); This.Transform(transform); ToExistingScriptValue_Ray(engine, This, context->thisObject()); return QScriptValue(); } static QScriptValue Ray_Contains_float3_float_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 2) { printf("Error! Invalid number of arguments passed to function Ray_Contains_float3_float_const in file %s, line %d!\nExpected 2, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); float3 point = qscriptvalue_cast<float3>(context->argument(0)); float distanceThreshold = qscriptvalue_cast<float>(context->argument(1)); bool ret = This.Contains(point, distanceThreshold); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Contains_LineSegment_float_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 2) { printf("Error! Invalid number of arguments passed to function Ray_Contains_LineSegment_float_const in file %s, line %d!\nExpected 2, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); LineSegment lineSegment = qscriptvalue_cast<LineSegment>(context->argument(0)); float distanceThreshold = qscriptvalue_cast<float>(context->argument(1)); bool ret = This.Contains(lineSegment, distanceThreshold); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Equals_Ray_float_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 2) { printf("Error! Invalid number of arguments passed to function Ray_Equals_Ray_float_const in file %s, line %d!\nExpected 2, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); Ray otherRay = qscriptvalue_cast<Ray>(context->argument(0)); float epsilon = qscriptvalue_cast<float>(context->argument(1)); bool ret = This.Equals(otherRay, epsilon); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Distance_float3_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Distance_float3_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); float3 point = qscriptvalue_cast<float3>(context->argument(0)); float ret = This.Distance(point); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Distance_Ray_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Distance_Ray_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); Ray other = qscriptvalue_cast<Ray>(context->argument(0)); float ret = This.Distance(other); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Distance_Line_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Distance_Line_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); Line other = qscriptvalue_cast<Line>(context->argument(0)); float ret = This.Distance(other); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Distance_LineSegment_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Distance_LineSegment_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); LineSegment other = qscriptvalue_cast<LineSegment>(context->argument(0)); float ret = This.Distance(other); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Distance_Sphere_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Distance_Sphere_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); Sphere sphere = qscriptvalue_cast<Sphere>(context->argument(0)); float ret = This.Distance(sphere); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Distance_Capsule_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Distance_Capsule_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); Capsule capsule = qscriptvalue_cast<Capsule>(context->argument(0)); float ret = This.Distance(capsule); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Intersects_Triangle_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Intersects_Triangle_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); Triangle triangle = qscriptvalue_cast<Triangle>(context->argument(0)); bool ret = This.Intersects(triangle); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Intersects_Plane_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Intersects_Plane_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); Plane plane = qscriptvalue_cast<Plane>(context->argument(0)); bool ret = This.Intersects(plane); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Intersects_Sphere_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Intersects_Sphere_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); Sphere s = qscriptvalue_cast<Sphere>(context->argument(0)); bool ret = This.Intersects(s); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Intersects_AABB_float_float_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 3) { printf("Error! Invalid number of arguments passed to function Ray_Intersects_AABB_float_float_const in file %s, line %d!\nExpected 3, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); AABB aabb = qscriptvalue_cast<AABB>(context->argument(0)); float dNear = qscriptvalue_cast<float>(context->argument(1)); float dFar = qscriptvalue_cast<float>(context->argument(2)); bool ret = This.Intersects(aabb, dNear, dFar); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Intersects_AABB_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Intersects_AABB_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); AABB aabb = qscriptvalue_cast<AABB>(context->argument(0)); bool ret = This.Intersects(aabb); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Intersects_OBB_float_float_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 3) { printf("Error! Invalid number of arguments passed to function Ray_Intersects_OBB_float_float_const in file %s, line %d!\nExpected 3, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); OBB obb = qscriptvalue_cast<OBB>(context->argument(0)); float dNear = qscriptvalue_cast<float>(context->argument(1)); float dFar = qscriptvalue_cast<float>(context->argument(2)); bool ret = This.Intersects(obb, dNear, dFar); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Intersects_OBB_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Intersects_OBB_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); OBB obb = qscriptvalue_cast<OBB>(context->argument(0)); bool ret = This.Intersects(obb); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Intersects_Capsule_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Intersects_Capsule_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); Capsule capsule = qscriptvalue_cast<Capsule>(context->argument(0)); bool ret = This.Intersects(capsule); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Intersects_Polygon_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Intersects_Polygon_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); Polygon polygon = qscriptvalue_cast<Polygon>(context->argument(0)); bool ret = This.Intersects(polygon); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Intersects_Frustum_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Intersects_Frustum_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); Frustum frustum = qscriptvalue_cast<Frustum>(context->argument(0)); bool ret = This.Intersects(frustum); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_Intersects_Polyhedron_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_Intersects_Polyhedron_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); Polyhedron polyhedron = qscriptvalue_cast<Polyhedron>(context->argument(0)); bool ret = This.Intersects(polyhedron); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_IntersectsDisc_Circle_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_IntersectsDisc_Circle_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); Circle disc = qscriptvalue_cast<Circle>(context->argument(0)); bool ret = This.IntersectsDisc(disc); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_ToLine_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 0) { printf("Error! Invalid number of arguments passed to function Ray_ToLine_const in file %s, line %d!\nExpected 0, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); Line ret = This.ToLine(); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_ToLineSegment_float_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { printf("Error! Invalid number of arguments passed to function Ray_ToLineSegment_float_const in file %s, line %d!\nExpected 1, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); float d = qscriptvalue_cast<float>(context->argument(0)); LineSegment ret = This.ToLineSegment(d); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_ProjectToAxis_float3_float_float_const(QScriptContext *context, QScriptEngine * /*engine*/) { if (context->argumentCount() != 3) { printf("Error! Invalid number of arguments passed to function Ray_ProjectToAxis_float3_float_float_const in file %s, line %d!\nExpected 3, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); float3 direction = qscriptvalue_cast<float3>(context->argument(0)); float outMin = qscriptvalue_cast<float>(context->argument(1)); float outMax = qscriptvalue_cast<float>(context->argument(2)); This.ProjectToAxis(direction, outMin, outMax); return QScriptValue(); } static QScriptValue Ray_ToLineSegment_float_float_const(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 2) { printf("Error! Invalid number of arguments passed to function Ray_ToLineSegment_float_float_const in file %s, line %d!\nExpected 2, but got %d!\n", __FILE__, __LINE__, context->argumentCount()); PrintCallStack(context->backtrace()); return QScriptValue(); } Ray This = qscriptvalue_cast<Ray>(context->thisObject()); float dStart = qscriptvalue_cast<float>(context->argument(0)); float dEnd = qscriptvalue_cast<float>(context->argument(1)); LineSegment ret = This.ToLineSegment(dStart, dEnd); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_toString_const(QScriptContext *context, QScriptEngine *engine) { Ray This; if (context->argumentCount() > 0) This = qscriptvalue_cast<Ray>(context->argument(0)); // Qt oddity (bug?): Sometimes the built-in toString() function doesn't give us this from thisObject, but as the first argument. else This = qscriptvalue_cast<Ray>(context->thisObject()); QString ret = This.toString(); return qScriptValueFromValue(engine, ret); } static QScriptValue Ray_ctor(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() == 0) return Ray_Ray(context, engine); if (context->argumentCount() == 2 && QSVIsOfType<float3>(context->argument(0)) && QSVIsOfType<float3>(context->argument(1))) return Ray_Ray_float3_float3(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<Line>(context->argument(0))) return Ray_Ray_Line(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<LineSegment>(context->argument(0))) return Ray_Ray_LineSegment(context, engine); printf("Ray_ctor failed to choose the right function to call! Did you use 'var x = Ray();' instead of 'var x = new Ray();'?\n"); PrintCallStack(context->backtrace()); return QScriptValue(); } static QScriptValue Ray_Transform_selector(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() == 1 && QSVIsOfType<float3x3>(context->argument(0))) return Ray_Transform_float3x3(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<float3x4>(context->argument(0))) return Ray_Transform_float3x4(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<float4x4>(context->argument(0))) return Ray_Transform_float4x4(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<Quat>(context->argument(0))) return Ray_Transform_Quat(context, engine); printf("Ray_Transform_selector failed to choose the right function to call in file %s, line %d!\n", __FILE__, __LINE__); PrintCallStack(context->backtrace()); return QScriptValue(); } static QScriptValue Ray_Contains_selector(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() == 2 && QSVIsOfType<float3>(context->argument(0)) && QSVIsOfType<float>(context->argument(1))) return Ray_Contains_float3_float_const(context, engine); if (context->argumentCount() == 2 && QSVIsOfType<LineSegment>(context->argument(0)) && QSVIsOfType<float>(context->argument(1))) return Ray_Contains_LineSegment_float_const(context, engine); printf("Ray_Contains_selector failed to choose the right function to call in file %s, line %d!\n", __FILE__, __LINE__); PrintCallStack(context->backtrace()); return QScriptValue(); } static QScriptValue Ray_Distance_selector(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() == 1 && QSVIsOfType<float3>(context->argument(0))) return Ray_Distance_float3_const(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<Ray>(context->argument(0))) return Ray_Distance_Ray_const(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<Line>(context->argument(0))) return Ray_Distance_Line_const(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<LineSegment>(context->argument(0))) return Ray_Distance_LineSegment_const(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<Sphere>(context->argument(0))) return Ray_Distance_Sphere_const(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<Capsule>(context->argument(0))) return Ray_Distance_Capsule_const(context, engine); printf("Ray_Distance_selector failed to choose the right function to call in file %s, line %d!\n", __FILE__, __LINE__); PrintCallStack(context->backtrace()); return QScriptValue(); } static QScriptValue Ray_Intersects_selector(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() == 1 && QSVIsOfType<Triangle>(context->argument(0))) return Ray_Intersects_Triangle_const(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<Plane>(context->argument(0))) return Ray_Intersects_Plane_const(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<Sphere>(context->argument(0))) return Ray_Intersects_Sphere_const(context, engine); if (context->argumentCount() == 3 && QSVIsOfType<AABB>(context->argument(0)) && QSVIsOfType<float>(context->argument(1)) && QSVIsOfType<float>(context->argument(2))) return Ray_Intersects_AABB_float_float_const(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<AABB>(context->argument(0))) return Ray_Intersects_AABB_const(context, engine); if (context->argumentCount() == 3 && QSVIsOfType<OBB>(context->argument(0)) && QSVIsOfType<float>(context->argument(1)) && QSVIsOfType<float>(context->argument(2))) return Ray_Intersects_OBB_float_float_const(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<OBB>(context->argument(0))) return Ray_Intersects_OBB_const(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<Capsule>(context->argument(0))) return Ray_Intersects_Capsule_const(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<Polygon>(context->argument(0))) return Ray_Intersects_Polygon_const(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<Frustum>(context->argument(0))) return Ray_Intersects_Frustum_const(context, engine); if (context->argumentCount() == 1 && QSVIsOfType<Polyhedron>(context->argument(0))) return Ray_Intersects_Polyhedron_const(context, engine); printf("Ray_Intersects_selector failed to choose the right function to call in file %s, line %d!\n", __FILE__, __LINE__); PrintCallStack(context->backtrace()); return QScriptValue(); } static QScriptValue Ray_ToLineSegment_selector(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() == 1 && QSVIsOfType<float>(context->argument(0))) return Ray_ToLineSegment_float_const(context, engine); if (context->argumentCount() == 2 && QSVIsOfType<float>(context->argument(0)) && QSVIsOfType<float>(context->argument(1))) return Ray_ToLineSegment_float_float_const(context, engine); printf("Ray_ToLineSegment_selector failed to choose the right function to call in file %s, line %d!\n", __FILE__, __LINE__); PrintCallStack(context->backtrace()); return QScriptValue(); } void FromScriptValue_Ray(const QScriptValue &obj, Ray &value) { value.pos = qScriptValueToValue<float3>(obj.property("pos")); value.dir = qScriptValueToValue<float3>(obj.property("dir")); } QScriptValue ToScriptValue_Ray(QScriptEngine *engine, const Ray &value) { QScriptValue obj = engine->newVariant(QVariant::fromValue(value)); // The contents of this variant are NOT used. The real data lies in the data() pointer of this QScriptValue. This only exists to enable overload resolution to work for QObject slots. ToExistingScriptValue_Ray(engine, value, obj); return obj; } QScriptValue ToScriptValue_const_Ray(QScriptEngine *engine, const Ray &value) { QScriptValue obj = engine->newVariant(QVariant::fromValue(value)); // The contents of this variant are NOT used. The real data lies in the data() pointer of this QScriptValue. This only exists to enable overload resolution to work for QObject slots. obj.setPrototype(engine->defaultPrototype(qMetaTypeId<Ray>())); obj.setProperty("pos", ToScriptValue_const_float3(engine, value.pos), QScriptValue::Undeletable | QScriptValue::ReadOnly); obj.setProperty("dir", ToScriptValue_const_float3(engine, value.dir), QScriptValue::Undeletable | QScriptValue::ReadOnly); return obj; } QScriptValue register_Ray_prototype(QScriptEngine *engine) { QScriptValue proto = engine->newObject(); proto.setProperty("IsFinite", engine->newFunction(Ray_IsFinite_const, 0), QScriptValue::Undeletable | QScriptValue::ReadOnly); proto.setProperty("GetPoint", engine->newFunction(Ray_GetPoint_float_const, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly); proto.setProperty("Translate", engine->newFunction(Ray_Translate_float3, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly); proto.setProperty("Transform", engine->newFunction(Ray_Transform_selector, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly); proto.setProperty("Contains", engine->newFunction(Ray_Contains_selector, 2), QScriptValue::Undeletable | QScriptValue::ReadOnly); proto.setProperty("Equals", engine->newFunction(Ray_Equals_Ray_float_const, 2), QScriptValue::Undeletable | QScriptValue::ReadOnly); proto.setProperty("Distance", engine->newFunction(Ray_Distance_selector, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly); proto.setProperty("Intersects", engine->newFunction(Ray_Intersects_selector, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly); proto.setProperty("Intersects", engine->newFunction(Ray_Intersects_selector, 3), QScriptValue::Undeletable | QScriptValue::ReadOnly); proto.setProperty("IntersectsDisc", engine->newFunction(Ray_IntersectsDisc_Circle_const, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly); proto.setProperty("ToLine", engine->newFunction(Ray_ToLine_const, 0), QScriptValue::Undeletable | QScriptValue::ReadOnly); proto.setProperty("ToLineSegment", engine->newFunction(Ray_ToLineSegment_selector, 1), QScriptValue::Undeletable | QScriptValue::ReadOnly); proto.setProperty("ProjectToAxis", engine->newFunction(Ray_ProjectToAxis_float3_float_float_const, 3), QScriptValue::Undeletable | QScriptValue::ReadOnly); proto.setProperty("ToLineSegment", engine->newFunction(Ray_ToLineSegment_selector, 2), QScriptValue::Undeletable | QScriptValue::ReadOnly); proto.setProperty("toString", engine->newFunction(Ray_toString_const, 0), QScriptValue::Undeletable | QScriptValue::ReadOnly); proto.setProperty("metaTypeId", engine->toScriptValue<qint32>((qint32)qMetaTypeId<Ray>())); engine->setDefaultPrototype(qMetaTypeId<Ray>(), proto); engine->setDefaultPrototype(qMetaTypeId<Ray*>(), proto); qScriptRegisterMetaType(engine, ToScriptValue_Ray, FromScriptValue_Ray, proto); QScriptValue ctor = engine->newFunction(Ray_ctor, proto, 2); engine->globalObject().setProperty("Ray", ctor, QScriptValue::Undeletable | QScriptValue::ReadOnly); return ctor; }
67.808554
305
0.748153
[ "transform" ]
99a65296d015413aa25615de2d0e28fd0d2b6b36
268,367
cpp
C++
openrave/plugins/ikfastsolvers/ik_katana5d_trans.cpp
jdsika/TUM_HOly
a2ac55fa1751a3a8038cf61d29b95005f36d6264
[ "MIT" ]
2
2015-11-13T16:40:57.000Z
2017-09-15T15:37:19.000Z
openrave/plugins/ikfastsolvers/ik_katana5d_trans.cpp
jdsika/holy
a2ac55fa1751a3a8038cf61d29b95005f36d6264
[ "MIT" ]
1
2016-06-13T01:29:51.000Z
2016-06-14T00:38:27.000Z
openrave/plugins/ikfastsolvers/ik_katana5d_trans.cpp
jdsika/holy
a2ac55fa1751a3a8038cf61d29b95005f36d6264
[ "MIT" ]
null
null
null
#define IKFAST_NAMESPACE ik_katana5d_trans #include "plugindefs.h" /// autogenerated analytical inverse kinematics code from ikfast program part of OpenRAVE /// \author Rosen Diankov /// /// 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. /// /// ikfast version 0x10000048 generated on 2014-10-08 15:52:02.140958 /// To compile with gcc: /// gcc -lstdc++ ik.cpp /// To compile without any main function as a shared object (might need -llapack): /// gcc -fPIC -lstdc++ -DIKFAST_NO_MAIN -DIKFAST_CLIBRARY -shared -Wl,-soname,libik.so -o libik.so ik.cpp #define IKFAST_HAS_LIBRARY #include "ikfast.h" // found inside share/openrave-X.Y/python/ikfast.h using namespace ikfast; // check if the included ikfast version matches what this file was compiled with #define IKFAST_COMPILE_ASSERT(x) extern int __dummy[(int)x] IKFAST_COMPILE_ASSERT(IKFAST_VERSION==0x10000048); #include <cmath> #include <vector> #include <limits> #include <algorithm> #include <complex> #ifndef IKFAST_ASSERT #include <stdexcept> #include <sstream> #include <iostream> #ifdef _MSC_VER #ifndef __PRETTY_FUNCTION__ #define __PRETTY_FUNCTION__ __FUNCDNAME__ #endif #endif #ifndef __PRETTY_FUNCTION__ #define __PRETTY_FUNCTION__ __func__ #endif #define IKFAST_ASSERT(b) { if( !(b) ) { std::stringstream ss; ss << "ikfast exception: " << __FILE__ << ":" << __LINE__ << ": " <<__PRETTY_FUNCTION__ << ": Assertion '" << #b << "' failed"; throw std::runtime_error(ss.str()); } } #endif #if defined(_MSC_VER) #define IKFAST_ALIGNED16(x) __declspec(align(16)) x #else #define IKFAST_ALIGNED16(x) x __attribute((aligned(16))) #endif #define IK2PI ((IkReal)6.28318530717959) #define IKPI ((IkReal)3.14159265358979) #define IKPI_2 ((IkReal)1.57079632679490) #ifdef _MSC_VER #ifndef isnan #define isnan _isnan #endif #ifndef isinf #define isinf _isinf #endif //#ifndef isfinite //#define isfinite _isfinite //#endif #endif // _MSC_VER // lapack routines extern "C" { void dgetrf_ (const int* m, const int* n, double* a, const int* lda, int* ipiv, int* info); void zgetrf_ (const int* m, const int* n, std::complex<double>* a, const int* lda, int* ipiv, int* info); void dgetri_(const int* n, const double* a, const int* lda, int* ipiv, double* work, const int* lwork, int* info); void dgesv_ (const int* n, const int* nrhs, double* a, const int* lda, int* ipiv, double* b, const int* ldb, int* info); void dgetrs_(const char *trans, const int *n, const int *nrhs, double *a, const int *lda, int *ipiv, double *b, const int *ldb, int *info); void dgeev_(const char *jobvl, const char *jobvr, const int *n, double *a, const int *lda, double *wr, double *wi,double *vl, const int *ldvl, double *vr, const int *ldvr, double *work, const int *lwork, int *info); } using namespace std; // necessary to get std math routines #ifdef IKFAST_NAMESPACE namespace IKFAST_NAMESPACE { #endif inline float IKabs(float f) { return fabsf(f); } inline double IKabs(double f) { return fabs(f); } inline float IKsqr(float f) { return f*f; } inline double IKsqr(double f) { return f*f; } inline float IKlog(float f) { return logf(f); } inline double IKlog(double f) { return log(f); } // allows asin and acos to exceed 1 #ifndef IKFAST_SINCOS_THRESH #define IKFAST_SINCOS_THRESH ((IkReal)2e-6) #endif // used to check input to atan2 for degenerate cases #ifndef IKFAST_ATAN2_MAGTHRESH #define IKFAST_ATAN2_MAGTHRESH ((IkReal)2e-6) #endif // minimum distance of separate solutions #ifndef IKFAST_SOLUTION_THRESH #define IKFAST_SOLUTION_THRESH ((IkReal)1e-6) #endif // there are checkpoints in ikfast that are evaluated to make sure they are 0. This threshold speicfies by how much they can deviate #ifndef IKFAST_EVALCOND_THRESH #define IKFAST_EVALCOND_THRESH ((IkReal)0.000005) #endif inline float IKasin(float f) { IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver if( f <= -1 ) return float(-IKPI_2); else if( f >= 1 ) return float(IKPI_2); return asinf(f); } inline double IKasin(double f) { IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver if( f <= -1 ) return -IKPI_2; else if( f >= 1 ) return IKPI_2; return asin(f); } // return positive value in [0,y) inline float IKfmod(float x, float y) { while(x < 0) { x += y; } return fmodf(x,y); } // return positive value in [0,y) inline double IKfmod(double x, double y) { while(x < 0) { x += y; } return fmod(x,y); } inline float IKacos(float f) { IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver if( f <= -1 ) return float(IKPI); else if( f >= 1 ) return float(0); return acosf(f); } inline double IKacos(double f) { IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver if( f <= -1 ) return IKPI; else if( f >= 1 ) return 0; return acos(f); } inline float IKsin(float f) { return sinf(f); } inline double IKsin(double f) { return sin(f); } inline float IKcos(float f) { return cosf(f); } inline double IKcos(double f) { return cos(f); } inline float IKtan(float f) { return tanf(f); } inline double IKtan(double f) { return tan(f); } inline float IKsqrt(float f) { if( f <= 0.0f ) return 0.0f; return sqrtf(f); } inline double IKsqrt(double f) { if( f <= 0.0 ) return 0.0; return sqrt(f); } inline float IKatan2Simple(float fy, float fx) { return atan2f(fy,fx); } inline float IKatan2(float fy, float fx) { if( isnan(fy) ) { IKFAST_ASSERT(!isnan(fx)); // if both are nan, probably wrong value will be returned return float(IKPI_2); } else if( isnan(fx) ) { return 0; } return atan2f(fy,fx); } inline double IKatan2Simple(double fy, double fx) { return atan2(fy,fx); } inline double IKatan2(double fy, double fx) { if( isnan(fy) ) { IKFAST_ASSERT(!isnan(fx)); // if both are nan, probably wrong value will be returned return IKPI_2; } else if( isnan(fx) ) { return 0; } return atan2(fy,fx); } template <typename T> struct CheckValue { T value; bool valid; }; template <typename T> inline CheckValue<T> IKatan2WithCheck(T fy, T fx, T epsilon) { CheckValue<T> ret; ret.valid = false; ret.value = 0; if( !isnan(fy) && !isnan(fx) ) { if( IKabs(fy) >= IKFAST_ATAN2_MAGTHRESH || IKabs(fx) > IKFAST_ATAN2_MAGTHRESH ) { ret.value = IKatan2Simple(fy,fx); ret.valid = true; } } return ret; } inline float IKsign(float f) { if( f > 0 ) { return float(1); } else if( f < 0 ) { return float(-1); } return 0; } inline double IKsign(double f) { if( f > 0 ) { return 1.0; } else if( f < 0 ) { return -1.0; } return 0; } template <typename T> inline CheckValue<T> IKPowWithIntegerCheck(T f, int n) { CheckValue<T> ret; ret.valid = true; if( n == 0 ) { ret.value = 1.0; return ret; } else if( n == 1 ) { ret.value = f; return ret; } else if( n < 0 ) { if( f == 0 ) { ret.valid = false; ret.value = (T)1.0e30; return ret; } if( n == -1 ) { ret.value = T(1.0)/f; return ret; } } int num = n > 0 ? n : -n; if( num == 2 ) { ret.value = f*f; } else if( num == 3 ) { ret.value = f*f*f; } else { ret.value = 1.0; while(num>0) { if( num & 1 ) { ret.value *= f; } num >>= 1; f *= f; } } if( n < 0 ) { ret.value = T(1.0)/ret.value; } return ret; } /// solves the forward kinematics equations. /// \param pfree is an array specifying the free joints of the chain. IKFAST_API void ComputeFk(const IkReal* j, IkReal* eetrans, IkReal* eerot) { IkReal x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16; x0=IKcos(j[0]); x1=IKsin(j[1]); x2=IKcos(j[1]); x3=IKsin(j[2]); x4=IKcos(j[2]); x5=IKsin(j[3]); x6=IKsin(j[0]); x7=IKcos(j[3]); x8=((0.139)*x0); x9=((0.273)*x0); x10=((0.273)*x6); x11=((0.139)*x6); x12=((0.19)*x1); x13=(x2*x3); x14=(x1*x3); x15=(x1*x4); x16=(x2*x4); eetrans[0]=(((x0*x12))+((x5*(((((-1.0)*x16*x9))+((x14*x9))))))+((x13*x8))+((x7*((((x13*x9))+((x15*x9))))))+((x15*x8))); IkReal x17=((1.0)*x10); IkReal x18=((1.0)*x11); eetrans[1]=((((-1.0)*x12*x6))+((x5*(((((-1.0)*x14*x17))+((x10*x16))))))+(((-1.0)*x13*x18))+(((-1.0)*x15*x18))+((x7*(((((-1.0)*x13*x17))+(((-1.0)*x15*x17))))))); eetrans[2]=((0.2015)+((x7*(((((-0.273)*x14))+(((0.273)*x16))))))+(((-0.139)*x14))+((x5*(((((0.273)*x15))+(((0.273)*x13))))))+(((0.19)*x2))+(((0.139)*x16))); } IKFAST_API int GetNumFreeParameters() { return 2; } IKFAST_API int* GetFreeParameters() { static int freeparams[] = {3, 4}; return freeparams; } IKFAST_API int GetNumJoints() { return 5; } IKFAST_API int GetIkRealSize() { return sizeof(IkReal); } IKFAST_API int GetIkType() { return 0x33000003; } class IKSolver { public: IkReal j0,cj0,sj0,htj0,j0mul,j1,cj1,sj1,htj1,j1mul,j2,cj2,sj2,htj2,j2mul,j3,cj3,sj3,htj3,j4,cj4,sj4,htj4,new_px,px,npx,new_py,py,npy,new_pz,pz,npz,pp; unsigned char _ij0[2], _nj0,_ij1[2], _nj1,_ij2[2], _nj2,_ij3[2], _nj3,_ij4[2], _nj4; IkReal j100, cj100, sj100; unsigned char _ij100[2], _nj100; bool ComputeIk(const IkReal* eetrans, const IkReal* eerot, const IkReal* pfree, IkSolutionListBase<IkReal>& solutions) { j0=numeric_limits<IkReal>::quiet_NaN(); _ij0[0] = -1; _ij0[1] = -1; _nj0 = -1; j1=numeric_limits<IkReal>::quiet_NaN(); _ij1[0] = -1; _ij1[1] = -1; _nj1 = -1; j2=numeric_limits<IkReal>::quiet_NaN(); _ij2[0] = -1; _ij2[1] = -1; _nj2 = -1; _ij3[0] = -1; _ij3[1] = -1; _nj3 = 0; _ij4[0] = -1; _ij4[1] = -1; _nj4 = 0; for(int dummyiter = 0; dummyiter < 1; ++dummyiter) { solutions.Clear(); j3=pfree[0]; cj3=cos(pfree[0]); sj3=sin(pfree[0]); j4=pfree[1]; cj4=cos(pfree[1]); sj4=sin(pfree[1]); px = eetrans[0]; py = eetrans[1]; pz = eetrans[2]; new_px=px; new_py=((-1.0)*py); new_pz=((0.2015)+(((-1.0)*pz))); px = new_px; py = new_py; pz = new_pz; pp=((px*px)+(py*py)+(pz*pz)); { IkReal j0eval[1]; j0eval[0]=((IKabs(px))+(IKabs(py))); if( IKabs(j0eval[0]) < 0.0000010000000000 ) { { IkReal j2eval[2]; j2eval[0]=((IKabs(sj3))+(((9.63948332369385)*(IKabs(((0.05282)+(((0.10374)*cj3)))))))); j2eval[1]=((1.0)+(((3.92805755395683)*cj3))+(((3.85740903679934)*(sj3*sj3)))+(((3.85740903679934)*(cj3*cj3)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 ) { { IkReal evalcond[2]; bool bgotonextstatement = true; do { evalcond[0]=((IKabs(px))+(IKabs(py))); evalcond[1]=0; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j2eval[2]; px=0; py=0; pp=pz*pz; j2eval[0]=((IKabs(sj3))+(((9.63948332369385)*(IKabs(((0.05282)+(((0.10374)*cj3)))))))); j2eval[1]=((1.0)+(((3.92805755395683)*cj3))+(((3.85740903679934)*(sj3*sj3)))+(((3.85740903679934)*(cj3*cj3)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 ) { { IkReal j1eval[1]; px=0; py=0; pp=pz*pz; j1eval[0]=pz; if( IKabs(j1eval[0]) < 0.0000010000000000 ) { continue; // no branches [j0, j1, j2] } else { { IkReal j1array[2], cj1array[2], sj1array[2]; bool j1valid[2]={false}; _nj1 = 2; CheckValue<IkReal> x19=IKPowWithIntegerCheck(pz,-1); if(!x19.valid){ continue; } cj1array[0]=((2.63157894736842)*(x19.value)*(((0.05775)+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))))); if( cj1array[0] >= -1-IKFAST_SINCOS_THRESH && cj1array[0] <= 1+IKFAST_SINCOS_THRESH ) { j1valid[0] = j1valid[1] = true; j1array[0] = IKacos(cj1array[0]); sj1array[0] = IKsin(j1array[0]); cj1array[1] = cj1array[0]; j1array[1] = -j1array[0]; sj1array[1] = -sj1array[0]; } else if( isnan(cj1array[0]) ) { // probably any value will work j1valid[0] = true; cj1array[0] = 1; sj1array[0] = 0; j1array[0] = 0; } for(int ij1 = 0; ij1 < 2; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 2; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal j2eval[3]; px=0; py=0; pp=pz*pz; IkReal x20=((273000.0)*pz); IkReal x21=((139000.0)*pz); j2eval[0]=((-1.23659314306796)+(((-1.0)*cj3))); j2eval[1]=((IKabs(((26410.0)+((sj1*sj3*x20))+((cj1*x21))+(((51870.0)*cj3))+((cj1*cj3*x20)))))+(IKabs(((((-1.0)*cj3*sj1*x20))+((cj1*sj3*x20))+(((51870.0)*sj3))+(((-1.0)*sj1*x21)))))); j2eval[2]=IKsign(((-93850.0)+(((-75894.0)*cj3)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 || IKabs(j2eval[2]) < 0.0000010000000000 ) { { IkReal j2eval[3]; px=0; py=0; pp=pz*pz; IkReal x22=pz*pz; IkReal x23=(pz*sj1); IkReal x24=((13650000.0)*x22); j2eval[0]=((1.23659314306796)+cj3); j2eval[1]=IKsign(((1783150.0)+(((1441986.0)*cj3)))); j2eval[2]=((IKabs(((-903152.5)+(((-5187000.0)*sj3*x23))+(((-2301280.8)*cj3))+(((6950000.0)*x22))+((cj3*x24))+(((-1035953.1)*(cj3*cj3))))))+(IKabs(((((-1773817.5)*sj3))+(((5187000.0)*cj3*x23))+((sj3*x24))+(((-1035953.1)*cj3*sj3))+(((2641000.0)*x23)))))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 || IKabs(j2eval[2]) < 0.0000010000000000 ) { { IkReal j2eval[1]; px=0; py=0; pp=pz*pz; j2eval[0]=((((-1.23659314306796)*cj1))+(((-1.0)*cj1*cj3))); if( IKabs(j2eval[0]) < 0.0000010000000000 ) { { IkReal evalcond[2]; bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j1)))), 6.28318530717959))); evalcond[1]=((0.05775)+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j2eval[3]; px=0; py=0; pp=pz*pz; sj1=1.0; cj1=0; j1=1.5707963267949; IkReal x25=((273000.0)*pz); j2eval[0]=((-1.23659314306796)+(((-1.0)*cj3))); j2eval[1]=((IKabs(((26410.0)+((sj3*x25))+(((51870.0)*cj3)))))+(IKabs(((((51870.0)*sj3))+(((-139000.0)*pz))+(((-1.0)*cj3*x25)))))); j2eval[2]=IKsign(((-93850.0)+(((-75894.0)*cj3)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 || IKabs(j2eval[2]) < 0.0000010000000000 ) { { IkReal j2eval[3]; px=0; py=0; pp=pz*pz; sj1=1.0; cj1=0; j1=1.5707963267949; IkReal x26=pz*pz; IkReal x27=cj3*cj3; IkReal x28=(cj3*x26); j2eval[0]=((3.46268674455821)+(((26.6463004583164)*x26))+(((-3.97184425371572)*x27))+(((52.3341009001465)*x28))+(((-1.0)*cj3))); j2eval[1]=((IKabs(((-501790.0)+(((-5187000.0)*pz*sj3))+(((-985530.0)*cj3)))))+(IKabs(((((68345323.7410072)*(pz*pz*pz)))+(((-985530.0)*sj3))+(((-1305942.44604317)*pz)))))); j2eval[2]=IKsign(((1234525.0)+(((18658273.381295)*x28))+(((-1416051.0)*x27))+(((-356522.287769784)*cj3))+(((9500000.0)*x26)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 || IKabs(j2eval[2]) < 0.0000010000000000 ) { continue; // no branches [j0, j2] } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x29=pz*pz; CheckValue<IkReal> x30=IKPowWithIntegerCheck(IKsign(((1234525.0)+(((-1416051.0)*(cj3*cj3)))+(((-356522.287769784)*cj3))+(((18658273.381295)*cj3*x29))+(((9500000.0)*x29)))),-1); if(!x30.valid){ continue; } CheckValue<IkReal> x31 = IKatan2WithCheck(IkReal(((((68345323.7410072)*(pz*pz*pz)))+(((-985530.0)*sj3))+(((-1305942.44604317)*pz)))),((-501790.0)+(((-5187000.0)*pz*sj3))+(((-985530.0)*cj3))),IKFAST_ATAN2_MAGTHRESH); if(!x31.valid){ continue; } j2array[0]=((-1.5707963267949)+(((1.5707963267949)*(x30.value)))+(x31.value)); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[3]; IkReal x32=IKcos(j2); IkReal x33=IKsin(j2); IkReal x34=((0.273)*cj3); IkReal x35=(sj3*x33); evalcond[0]=((-0.19)+(((-1.0)*x32*x34))+(((-0.273)*x35))+(((-0.139)*x32))); evalcond[1]=((0.0722)+(((1.36690647482014)*x32*(pz*pz)))+(((0.10374)*x35))+(((-0.0261188489208633)*x32))); evalcond[2]=((((0.139)*x33))+(((-0.273)*sj3*x32))+(((-1.0)*pz))+((x33*x34))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x36=((273000.0)*pz); CheckValue<IkReal> x37=IKPowWithIntegerCheck(IKsign(((-93850.0)+(((-75894.0)*cj3)))),-1); if(!x37.valid){ continue; } CheckValue<IkReal> x38 = IKatan2WithCheck(IkReal(((((51870.0)*sj3))+(((-139000.0)*pz))+(((-1.0)*cj3*x36)))),((26410.0)+(((51870.0)*cj3))+((sj3*x36))),IKFAST_ATAN2_MAGTHRESH); if(!x38.valid){ continue; } j2array[0]=((-1.5707963267949)+(((1.5707963267949)*(x37.value)))+(x38.value)); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[3]; IkReal x39=IKcos(j2); IkReal x40=IKsin(j2); IkReal x41=((0.273)*cj3); IkReal x42=(sj3*x40); evalcond[0]=((-0.19)+(((-1.0)*x39*x41))+(((-0.139)*x39))+(((-0.273)*x42))); evalcond[1]=((0.0722)+(((1.36690647482014)*x39*(pz*pz)))+(((0.10374)*x42))+(((-0.0261188489208633)*x39))); evalcond[2]=((((0.139)*x40))+((x40*x41))+(((-0.273)*sj3*x39))+(((-1.0)*pz))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j1)))), 6.28318530717959))); evalcond[1]=((0.05775)+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j2eval[3]; px=0; py=0; pp=pz*pz; sj1=-1.0; cj1=0; j1=-1.5707963267949; IkReal x43=((273000.0)*pz); j2eval[0]=((-1.23659314306796)+(((-1.0)*cj3))); j2eval[1]=((IKabs((((cj3*x43))+(((51870.0)*sj3))+(((139000.0)*pz)))))+(IKabs(((26410.0)+(((51870.0)*cj3))+(((-1.0)*sj3*x43)))))); j2eval[2]=IKsign(((-93850.0)+(((-75894.0)*cj3)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 || IKabs(j2eval[2]) < 0.0000010000000000 ) { { IkReal j2eval[3]; px=0; py=0; pp=pz*pz; sj1=-1.0; cj1=0; j1=-1.5707963267949; IkReal x44=pz*pz; IkReal x45=cj3*cj3; IkReal x46=(cj3*x44); j2eval[0]=((-3.46268674455821)+cj3+(((-26.6463004583164)*x44))+(((-52.3341009001465)*x46))+(((3.97184425371572)*x45))); j2eval[1]=((IKabs(((((68345323.7410072)*(pz*pz*pz)))+(((985530.0)*sj3))+(((-1305942.44604317)*pz)))))+(IKabs(((501790.0)+(((-5187000.0)*pz*sj3))+(((985530.0)*cj3)))))); j2eval[2]=IKsign(((-1234525.0)+(((356522.287769784)*cj3))+(((1416051.0)*x45))+(((-9500000.0)*x44))+(((-18658273.381295)*x46)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 || IKabs(j2eval[2]) < 0.0000010000000000 ) { continue; // no branches [j0, j2] } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x47=pz*pz; CheckValue<IkReal> x48 = IKatan2WithCheck(IkReal(((((68345323.7410072)*(pz*pz*pz)))+(((985530.0)*sj3))+(((-1305942.44604317)*pz)))),((501790.0)+(((-5187000.0)*pz*sj3))+(((985530.0)*cj3))),IKFAST_ATAN2_MAGTHRESH); if(!x48.valid){ continue; } CheckValue<IkReal> x49=IKPowWithIntegerCheck(IKsign(((-1234525.0)+(((356522.287769784)*cj3))+(((1416051.0)*(cj3*cj3)))+(((-9500000.0)*x47))+(((-18658273.381295)*cj3*x47)))),-1); if(!x49.valid){ continue; } j2array[0]=((-1.5707963267949)+(x48.value)+(((1.5707963267949)*(x49.value)))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[3]; IkReal x50=IKcos(j2); IkReal x51=IKsin(j2); IkReal x52=((0.273)*cj3); IkReal x53=(sj3*x51); evalcond[0]=((-0.19)+(((-0.139)*x50))+(((-0.273)*x53))+(((-1.0)*x50*x52))); evalcond[1]=((((0.139)*x51))+pz+((x51*x52))+(((-0.273)*sj3*x50))); evalcond[2]=((0.0722)+(((1.36690647482014)*x50*(pz*pz)))+(((0.10374)*x53))+(((-0.0261188489208633)*x50))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x54=((273000.0)*pz); CheckValue<IkReal> x55 = IKatan2WithCheck(IkReal(((((51870.0)*sj3))+(((139000.0)*pz))+((cj3*x54)))),((26410.0)+(((51870.0)*cj3))+(((-1.0)*sj3*x54))),IKFAST_ATAN2_MAGTHRESH); if(!x55.valid){ continue; } CheckValue<IkReal> x56=IKPowWithIntegerCheck(IKsign(((-93850.0)+(((-75894.0)*cj3)))),-1); if(!x56.valid){ continue; } j2array[0]=((-1.5707963267949)+(x55.value)+(((1.5707963267949)*(x56.value)))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[3]; IkReal x57=IKcos(j2); IkReal x58=IKsin(j2); IkReal x59=((0.273)*cj3); IkReal x60=(sj3*x58); evalcond[0]=((-0.19)+(((-0.139)*x57))+(((-0.273)*x60))+(((-1.0)*x57*x59))); evalcond[1]=(((x58*x59))+(((0.139)*x58))+pz+(((-0.273)*sj3*x57))); evalcond[2]=((0.0722)+(((1.36690647482014)*x57*(pz*pz)))+(((-0.0261188489208633)*x57))+(((0.10374)*x60))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0, j2] } } while(0); if( bgotonextstatement ) { } } } } } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x61=cj1*cj1; IkReal x62=(cj1*cj3); IkReal x63=(cj1*sj3); IkReal x64=(pz*sj1); IkReal x65=(pz*x61); CheckValue<IkReal> x66=IKPowWithIntegerCheck(((((-75.894)*x62))+(((-93.85)*cj1))),-1); if(!x66.valid){ continue; } CheckValue<IkReal> x67=IKPowWithIntegerCheck(((((9385.0)*cj1))+(((7589.4)*x62))),-1); if(!x67.valid){ continue; } if( IKabs(((x66.value)*(((((273.0)*sj3*x65))+(((-139.0)*cj1*x64))+(((51.87)*x63))+(((-273.0)*x62*x64)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((x67.value)*(((((-27300.0)*cj3*x65))+(((-5187.0)*x62))+(((-27300.0)*x63*x64))+(((-13900.0)*x65))+(((-2641.0)*cj1)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((x66.value)*(((((273.0)*sj3*x65))+(((-139.0)*cj1*x64))+(((51.87)*x63))+(((-273.0)*x62*x64))))))+IKsqr(((x67.value)*(((((-27300.0)*cj3*x65))+(((-5187.0)*x62))+(((-27300.0)*x63*x64))+(((-13900.0)*x65))+(((-2641.0)*cj1))))))-1) <= IKFAST_SINCOS_THRESH ) continue; j2array[0]=IKatan2(((x66.value)*(((((273.0)*sj3*x65))+(((-139.0)*cj1*x64))+(((51.87)*x63))+(((-273.0)*x62*x64))))), ((x67.value)*(((((-27300.0)*cj3*x65))+(((-5187.0)*x62))+(((-27300.0)*x63*x64))+(((-13900.0)*x65))+(((-2641.0)*cj1)))))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[5]; IkReal x68=IKsin(j2); IkReal x69=IKcos(j2); IkReal x70=(sj1*sj3); IkReal x71=((1.0)*pz); IkReal x72=(cj3*x69); IkReal x73=((0.273)*x68); IkReal x74=((0.139)*x68); IkReal x75=((0.139)*x69); IkReal x76=((0.273)*sj3*x69); evalcond[0]=((((-1.0)*x76))+(((-1.0)*sj1*x71))+x74+((cj3*x73))); evalcond[1]=((-0.19)+(((-0.273)*x72))+(((-1.0)*x75))+(((-1.0)*sj3*x73))+(((-1.0)*cj1*x71))); evalcond[2]=((0.12995)+(((0.10374)*sj3*x68))+(((0.10374)*x72))+(((0.075894)*cj3))+(((0.05282)*x69))+(((-1.0)*pz*x71))); evalcond[3]=((((0.19)*sj1))+((cj1*cj3*x73))+(((0.273)*sj1*x72))+((sj1*x75))+((x70*x73))+((cj1*x74))+(((-1.0)*cj1*x76))); evalcond[4]=((((-0.273)*cj1*x72))+(((-0.273)*x69*x70))+(((-1.0)*x71))+(((-0.19)*cj1))+((cj3*sj1*x73))+((sj1*x74))+(((-1.0)*cj1*sj3*x73))+(((-1.0)*cj1*x75))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x77=pz*pz; IkReal x78=(pz*sj1); IkReal x79=((13650000.0)*x77); CheckValue<IkReal> x80 = IKatan2WithCheck(IkReal(((((-1773817.5)*sj3))+(((-1035953.1)*cj3*sj3))+((sj3*x79))+(((5187000.0)*cj3*x78))+(((2641000.0)*x78)))),((-903152.5)+(((-5187000.0)*sj3*x78))+(((-2301280.8)*cj3))+(((6950000.0)*x77))+((cj3*x79))+(((-1035953.1)*(cj3*cj3)))),IKFAST_ATAN2_MAGTHRESH); if(!x80.valid){ continue; } CheckValue<IkReal> x81=IKPowWithIntegerCheck(IKsign(((1783150.0)+(((1441986.0)*cj3)))),-1); if(!x81.valid){ continue; } j2array[0]=((-1.5707963267949)+(x80.value)+(((1.5707963267949)*(x81.value)))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[5]; IkReal x82=IKsin(j2); IkReal x83=IKcos(j2); IkReal x84=(sj1*sj3); IkReal x85=((1.0)*pz); IkReal x86=(cj3*x83); IkReal x87=((0.273)*x82); IkReal x88=((0.139)*x82); IkReal x89=((0.139)*x83); IkReal x90=((0.273)*sj3*x83); evalcond[0]=((((-1.0)*sj1*x85))+((cj3*x87))+x88+(((-1.0)*x90))); evalcond[1]=((-0.19)+(((-0.273)*x86))+(((-1.0)*sj3*x87))+(((-1.0)*cj1*x85))+(((-1.0)*x89))); evalcond[2]=((0.12995)+(((0.10374)*x86))+(((0.10374)*sj3*x82))+(((0.075894)*cj3))+(((0.05282)*x83))+(((-1.0)*pz*x85))); evalcond[3]=(((x84*x87))+(((0.19)*sj1))+((sj1*x89))+(((0.273)*sj1*x86))+(((-1.0)*cj1*x90))+((cj1*x88))+((cj1*cj3*x87))); evalcond[4]=(((cj3*sj1*x87))+(((-0.273)*x83*x84))+(((-0.19)*cj1))+((sj1*x88))+(((-1.0)*cj1*x89))+(((-1.0)*x85))+(((-0.273)*cj1*x86))+(((-1.0)*cj1*sj3*x87))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x91=((273000.0)*pz); IkReal x92=((139000.0)*pz); CheckValue<IkReal> x93 = IKatan2WithCheck(IkReal(((((-1.0)*sj1*x92))+(((51870.0)*sj3))+(((-1.0)*cj3*sj1*x91))+((cj1*sj3*x91)))),((26410.0)+(((51870.0)*cj3))+((sj1*sj3*x91))+((cj1*x92))+((cj1*cj3*x91))),IKFAST_ATAN2_MAGTHRESH); if(!x93.valid){ continue; } CheckValue<IkReal> x94=IKPowWithIntegerCheck(IKsign(((-93850.0)+(((-75894.0)*cj3)))),-1); if(!x94.valid){ continue; } j2array[0]=((-1.5707963267949)+(x93.value)+(((1.5707963267949)*(x94.value)))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[5]; IkReal x95=IKsin(j2); IkReal x96=IKcos(j2); IkReal x97=(sj1*sj3); IkReal x98=((1.0)*pz); IkReal x99=(cj3*x96); IkReal x100=((0.273)*x95); IkReal x101=((0.139)*x95); IkReal x102=((0.139)*x96); IkReal x103=((0.273)*sj3*x96); evalcond[0]=((((-1.0)*sj1*x98))+((cj3*x100))+(((-1.0)*x103))+x101); evalcond[1]=((-0.19)+(((-1.0)*sj3*x100))+(((-0.273)*x99))+(((-1.0)*x102))+(((-1.0)*cj1*x98))); evalcond[2]=((0.12995)+(((-1.0)*pz*x98))+(((0.10374)*x99))+(((0.10374)*sj3*x95))+(((0.075894)*cj3))+(((0.05282)*x96))); evalcond[3]=(((sj1*x102))+((x100*x97))+(((-1.0)*cj1*x103))+((cj1*x101))+((cj1*cj3*x100))+(((0.19)*sj1))+(((0.273)*sj1*x99))); evalcond[4]=((((-0.273)*cj1*x99))+((sj1*x101))+(((-1.0)*cj1*x102))+(((-0.273)*x96*x97))+(((-0.19)*cj1))+((cj3*sj1*x100))+(((-1.0)*x98))+(((-1.0)*cj1*sj3*x100))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } } } } else { { IkReal j2array[2], cj2array[2], sj2array[2]; bool j2valid[2]={false}; _nj2 = 2; IkReal x104=((0.05282)+(((0.10374)*cj3))); CheckValue<IkReal> x107 = IKatan2WithCheck(IkReal(x104),((0.10374)*sj3),IKFAST_ATAN2_MAGTHRESH); if(!x107.valid){ continue; } IkReal x105=((1.0)*(x107.value)); if((((x104*x104)+(((0.0107619876)*(sj3*sj3))))) < -0.00001) continue; CheckValue<IkReal> x108=IKPowWithIntegerCheck(IKabs(IKsqrt(((x104*x104)+(((0.0107619876)*(sj3*sj3)))))),-1); if(!x108.valid){ continue; } if( (((x108.value)*(((0.12995)+(((0.075894)*cj3))+(((-1.0)*(pz*pz))))))) < -1-IKFAST_SINCOS_THRESH || (((x108.value)*(((0.12995)+(((0.075894)*cj3))+(((-1.0)*(pz*pz))))))) > 1+IKFAST_SINCOS_THRESH ) continue; IkReal x106=IKasin(((x108.value)*(((0.12995)+(((0.075894)*cj3))+(((-1.0)*(pz*pz))))))); j2array[0]=((((-1.0)*x105))+(((-1.0)*x106))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); j2array[1]=((3.14159265358979)+(((-1.0)*x105))+x106); sj2array[1]=IKsin(j2array[1]); cj2array[1]=IKcos(j2array[1]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; if( j2array[1] > IKPI ) { j2array[1]-=IK2PI; } else if( j2array[1] < -IKPI ) { j2array[1]+=IK2PI; } j2valid[1] = true; for(int ij2 = 0; ij2 < 2; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 2; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal j1eval[3]; px=0; py=0; pp=pz*pz; IkReal x109=((0.273)*sj2); IkReal x110=((0.273)*cj2); j1eval[0]=pz; j1eval[1]=((IKabs((((cj3*x109))+(((0.139)*sj2))+(((-1.0)*sj3*x110)))))+(IKabs(((-0.19)+(((-1.0)*sj3*x109))+(((-1.0)*cj3*x110))+(((-0.139)*cj2)))))); j1eval[2]=IKsign(pz); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 || IKabs(j1eval[2]) < 0.0000010000000000 ) { { IkReal j1eval[1]; px=0; py=0; pp=pz*pz; j1eval[0]=pz; if( IKabs(j1eval[0]) < 0.0000010000000000 ) { { IkReal j1eval[2]; px=0; py=0; pp=pz*pz; IkReal x111=((1.96402877697842)*pz); j1eval[0]=((((1.36690647482014)*pz))+((cj2*pz))+((cj2*cj3*x111))+((sj2*sj3*x111))); j1eval[1]=pz; if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 ) { { IkReal evalcond[5]; bool bgotonextstatement = true; do { IkReal x112=((0.075894)*cj3); IkReal x113=((0.273)*cj3); IkReal x114=(sj2*sj3); evalcond[0]=IKabs(pz); evalcond[1]=((0.12995)+(((0.10374)*x114))+x112+(((0.05282)*cj2))+(((0.10374)*cj2*cj3))); evalcond[2]=((-0.19)+(((-0.273)*x114))+(((-1.0)*cj2*x113))+(((-0.139)*cj2))); evalcond[3]=(((sj2*x113))+(((0.139)*sj2))+(((-0.273)*cj2*sj3))); evalcond[4]=((0.05775)+x112); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j1eval[1]; px=0; py=0; pp=0; pz=0; IkReal x115=((0.273)*sj3); j1eval[0]=((IKabs(((((-1.0)*cj2*x115))+(((-0.0687338129496403)*sj2)))))+(IKabs(((-0.19)+(((0.0687338129496403)*cj2))+(((-1.0)*sj2*x115)))))); if( IKabs(j1eval[0]) < 0.0000010000000000 ) { { IkReal j1eval[1]; px=0; py=0; pp=0; pz=0; IkReal x116=((0.273)*sj3); j1eval[0]=((IKabs(((((-1.0)*cj2*x116))+(((-0.0687338129496403)*sj2)))))+(IKabs(((0.19)+(((-0.0687338129496403)*cj2))+((sj2*x116)))))); if( IKabs(j1eval[0]) < 0.0000010000000000 ) { continue; // no branches [j0, j1] } else { { IkReal j1array[2], cj1array[2], sj1array[2]; bool j1valid[2]={false}; _nj1 = 2; IkReal x117=((0.273)*sj3); CheckValue<IkReal> x119 = IKatan2WithCheck(IkReal(((((-1.0)*cj2*x117))+(((-0.0687338129496403)*sj2)))),((0.19)+(((-0.0687338129496403)*cj2))+((sj2*x117))),IKFAST_ATAN2_MAGTHRESH); if(!x119.valid){ continue; } IkReal x118=x119.value; j1array[0]=((-1.0)*x118); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); j1array[1]=((3.14159265358979)+(((-1.0)*x118))); sj1array[1]=IKsin(j1array[1]); cj1array[1]=IKcos(j1array[1]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; if( j1array[1] > IKPI ) { j1array[1]-=IK2PI; } else if( j1array[1] < -IKPI ) { j1array[1]+=IK2PI; } j1valid[1] = true; for(int ij1 = 0; ij1 < 2; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 2; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[1]; IkReal x120=IKcos(j1); IkReal x121=IKsin(j1); IkReal x122=((0.273)*sj3); evalcond[0]=((((0.0687338129496403)*cj2*x120))+(((-1.0)*cj2*x121*x122))+(((-0.0687338129496403)*sj2*x121))+(((-0.19)*x120))+(((-1.0)*sj2*x120*x122))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } else { { IkReal j1array[2], cj1array[2], sj1array[2]; bool j1valid[2]={false}; _nj1 = 2; IkReal x123=((0.273)*sj3); CheckValue<IkReal> x125 = IKatan2WithCheck(IkReal(((-0.19)+(((-1.0)*sj2*x123))+(((0.0687338129496403)*cj2)))),((((-1.0)*cj2*x123))+(((-0.0687338129496403)*sj2))),IKFAST_ATAN2_MAGTHRESH); if(!x125.valid){ continue; } IkReal x124=x125.value; j1array[0]=((-1.0)*x124); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); j1array[1]=((3.14159265358979)+(((-1.0)*x124))); sj1array[1]=IKsin(j1array[1]); cj1array[1]=IKcos(j1array[1]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; if( j1array[1] > IKPI ) { j1array[1]-=IK2PI; } else if( j1array[1] < -IKPI ) { j1array[1]+=IK2PI; } j1valid[1] = true; for(int ij1 = 0; ij1 < 2; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 2; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[1]; IkReal x126=IKsin(j1); IkReal x127=IKcos(j1); IkReal x128=((0.273)*sj3); evalcond[0]=(((sj2*x126*x128))+(((-0.0687338129496403)*sj2*x127))+(((-0.0687338129496403)*cj2*x126))+(((-1.0)*cj2*x127*x128))+(((0.19)*x126))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0, j1] } } while(0); if( bgotonextstatement ) { } } } } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x129=pz*pz; IkReal x130=(cj3*sj2); IkReal x131=(cj2*cj3); IkReal x132=((5.187)*pz); IkReal x133=(cj2*sj3); IkReal x134=((13.65)*x129); CheckValue<IkReal> x135=IKPowWithIntegerCheck(((((2.641)*cj2*pz))+((x131*x132))+((sj2*sj3*x132))+(((3.61)*pz))),-1); if(!x135.valid){ continue; } CheckValue<IkReal> x136=IKPowWithIntegerCheck(pz,-1); if(!x136.valid){ continue; } if( IKabs(((x135.value)*(((((-1.3157508)*x130))+(((-1.0)*x133*x134))+((x130*x134))+(((-0.4013625)*sj2))+(((-1.0359531)*cj3*x130))+(((0.7882875)*x133))+(((1.0359531)*sj3*x131))+(((6.95)*sj2*x129)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((0.0526315789473684)*(x136.value)*(((2.8875)+(((3.7947)*cj3))+(((-50.0)*x129)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((x135.value)*(((((-1.3157508)*x130))+(((-1.0)*x133*x134))+((x130*x134))+(((-0.4013625)*sj2))+(((-1.0359531)*cj3*x130))+(((0.7882875)*x133))+(((1.0359531)*sj3*x131))+(((6.95)*sj2*x129))))))+IKsqr(((0.0526315789473684)*(x136.value)*(((2.8875)+(((3.7947)*cj3))+(((-50.0)*x129))))))-1) <= IKFAST_SINCOS_THRESH ) continue; j1array[0]=IKatan2(((x135.value)*(((((-1.3157508)*x130))+(((-1.0)*x133*x134))+((x130*x134))+(((-0.4013625)*sj2))+(((-1.0359531)*cj3*x130))+(((0.7882875)*x133))+(((1.0359531)*sj3*x131))+(((6.95)*sj2*x129))))), ((0.0526315789473684)*(x136.value)*(((2.8875)+(((3.7947)*cj3))+(((-50.0)*x129)))))); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x137=IKcos(j1); IkReal x138=IKsin(j1); IkReal x139=((0.273)*sj2); IkReal x140=((1.0)*pz); IkReal x141=((0.273)*cj3); IkReal x142=((0.273)*cj2); IkReal x143=((0.139)*cj2); IkReal x144=((0.139)*sj2); IkReal x145=(sj2*x138); IkReal x146=(cj3*x137); IkReal x147=(cj2*x138); IkReal x148=(sj3*x137); evalcond[0]=((0.05775)+(((-1.0)*pz*x140))+(((0.075894)*cj3))+(((-0.38)*pz*x137))); evalcond[1]=((((-1.0)*x138*x140))+((cj3*x139))+x144+(((-1.0)*sj3*x142))); evalcond[2]=((-0.19)+(((-1.0)*x143))+(((-1.0)*x137*x140))+(((-1.0)*sj3*x139))+(((-1.0)*cj2*x141))); evalcond[3]=((((-1.0)*x142*x148))+((x137*x144))+((sj3*x138*x139))+((x138*x143))+((x141*x147))+(((0.19)*x138))+((x139*x146))); evalcond[4]=((((-1.0)*x140))+(((-1.0)*x137*x143))+((x138*x144))+(((-1.0)*x139*x148))+(((-1.0)*sj3*x138*x142))+(((-0.19)*x137))+(((-1.0)*cj2*x137*x141))+((cj3*x138*x139))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; CheckValue<IkReal> x150=IKPowWithIntegerCheck(pz,-1); if(!x150.valid){ continue; } IkReal x149=x150.value; CheckValue<IkReal> x151=IKPowWithIntegerCheck(x149,-2); if(!x151.valid){ continue; } if( IKabs((x149*(((((0.139)*sj2))+(((0.273)*cj3*sj2))+(((-0.273)*cj2*sj3)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((0.0526315789473684)*x149*(((2.8875)+(((-50.0)*(x151.value)))+(((3.7947)*cj3)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((x149*(((((0.139)*sj2))+(((0.273)*cj3*sj2))+(((-0.273)*cj2*sj3))))))+IKsqr(((0.0526315789473684)*x149*(((2.8875)+(((-50.0)*(x151.value)))+(((3.7947)*cj3))))))-1) <= IKFAST_SINCOS_THRESH ) continue; j1array[0]=IKatan2((x149*(((((0.139)*sj2))+(((0.273)*cj3*sj2))+(((-0.273)*cj2*sj3))))), ((0.0526315789473684)*x149*(((2.8875)+(((-50.0)*(x151.value)))+(((3.7947)*cj3)))))); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x152=IKcos(j1); IkReal x153=IKsin(j1); IkReal x154=((0.273)*sj2); IkReal x155=((1.0)*pz); IkReal x156=((0.273)*cj3); IkReal x157=((0.273)*cj2); IkReal x158=((0.139)*cj2); IkReal x159=((0.139)*sj2); IkReal x160=(sj2*x153); IkReal x161=(cj3*x152); IkReal x162=(cj2*x153); IkReal x163=(sj3*x152); evalcond[0]=((0.05775)+(((-1.0)*pz*x155))+(((-0.38)*pz*x152))+(((0.075894)*cj3))); evalcond[1]=((((-1.0)*x153*x155))+((cj3*x154))+x159+(((-1.0)*sj3*x157))); evalcond[2]=((-0.19)+(((-1.0)*x158))+(((-1.0)*x152*x155))+(((-1.0)*cj2*x156))+(((-1.0)*sj3*x154))); evalcond[3]=(((x153*x158))+(((-1.0)*x157*x163))+((x152*x159))+((sj3*x153*x154))+((x156*x162))+((x154*x161))+(((0.19)*x153))); evalcond[4]=(((x153*x159))+(((-1.0)*x154*x163))+(((-1.0)*x155))+(((-0.19)*x152))+(((-1.0)*sj3*x153*x157))+((cj3*x153*x154))+(((-1.0)*x152*x158))+(((-1.0)*cj2*x152*x156))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x164=((0.273)*sj2); IkReal x165=((0.273)*cj2); CheckValue<IkReal> x166 = IKatan2WithCheck(IkReal(((((0.139)*sj2))+((cj3*x164))+(((-1.0)*sj3*x165)))),((-0.19)+(((-1.0)*cj3*x165))+(((-1.0)*sj3*x164))+(((-0.139)*cj2))),IKFAST_ATAN2_MAGTHRESH); if(!x166.valid){ continue; } CheckValue<IkReal> x167=IKPowWithIntegerCheck(IKsign(pz),-1); if(!x167.valid){ continue; } j1array[0]=((-1.5707963267949)+(x166.value)+(((1.5707963267949)*(x167.value)))); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x168=IKcos(j1); IkReal x169=IKsin(j1); IkReal x170=((0.273)*sj2); IkReal x171=((1.0)*pz); IkReal x172=((0.273)*cj3); IkReal x173=((0.273)*cj2); IkReal x174=((0.139)*cj2); IkReal x175=((0.139)*sj2); IkReal x176=(sj2*x169); IkReal x177=(cj3*x168); IkReal x178=(cj2*x169); IkReal x179=(sj3*x168); evalcond[0]=((0.05775)+(((-0.38)*pz*x168))+(((-1.0)*pz*x171))+(((0.075894)*cj3))); evalcond[1]=(((cj3*x170))+x175+(((-1.0)*x169*x171))+(((-1.0)*sj3*x173))); evalcond[2]=((-0.19)+(((-1.0)*x174))+(((-1.0)*cj2*x172))+(((-1.0)*x168*x171))+(((-1.0)*sj3*x170))); evalcond[3]=((((0.19)*x169))+((x168*x175))+((x169*x174))+((x172*x178))+((x170*x177))+((sj3*x169*x170))+(((-1.0)*x173*x179))); evalcond[4]=((((-1.0)*x171))+(((-1.0)*sj3*x169*x173))+((x169*x175))+(((-0.19)*x168))+(((-1.0)*cj2*x168*x172))+(((-1.0)*x170*x179))+((cj3*x169*x170))+(((-1.0)*x168*x174))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0, j1, j2] } } while(0); if( bgotonextstatement ) { } } } } else { { IkReal j2array[2], cj2array[2], sj2array[2]; bool j2valid[2]={false}; _nj2 = 2; IkReal x180=((0.05282)+(((0.10374)*cj3))); CheckValue<IkReal> x183 = IKatan2WithCheck(IkReal(x180),((0.10374)*sj3),IKFAST_ATAN2_MAGTHRESH); if(!x183.valid){ continue; } IkReal x181=((1.0)*(x183.value)); if((((((0.0107619876)*(sj3*sj3)))+(x180*x180))) < -0.00001) continue; CheckValue<IkReal> x184=IKPowWithIntegerCheck(IKabs(IKsqrt(((((0.0107619876)*(sj3*sj3)))+(x180*x180)))),-1); if(!x184.valid){ continue; } if( (((x184.value)*(((0.12995)+(((-1.0)*(px*px)))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py))))))) < -1-IKFAST_SINCOS_THRESH || (((x184.value)*(((0.12995)+(((-1.0)*(px*px)))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py))))))) > 1+IKFAST_SINCOS_THRESH ) continue; IkReal x182=IKasin(((x184.value)*(((0.12995)+(((-1.0)*(px*px)))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py))))))); j2array[0]=((((-1.0)*x181))+(((-1.0)*x182))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); j2array[1]=((3.14159265358979)+(((-1.0)*x181))+x182); sj2array[1]=IKsin(j2array[1]); cj2array[1]=IKcos(j2array[1]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; if( j2array[1] > IKPI ) { j2array[1]-=IK2PI; } else if( j2array[1] < -IKPI ) { j2array[1]+=IK2PI; } j2valid[1] = true; for(int ij2 = 0; ij2 < 2; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 2; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal j0eval[1]; j0eval[0]=((IKabs(px))+(IKabs(py))); if( IKabs(j0eval[0]) < 0.0000010000000000 ) { { IkReal j1eval[2]; IkReal x185=sj2*sj2; IkReal x186=cj2*cj2; IkReal x187=sj3*sj3; IkReal x188=cj3*cj3; IkReal x189=((3.92805755395683)*cj3); IkReal x190=(sj2*sj3); IkReal x191=(cj2*cj3); IkReal x192=((3.85740903679934)*x186); IkReal x193=((3.85740903679934)*x185); j1eval[0]=((IKabs(((-0.19)+(((-0.273)*x191))+(((-0.273)*x190))+(((-0.139)*cj2)))))+(IKabs(((((0.139)*sj2))+(((0.273)*cj3*sj2))+(((-0.273)*cj2*sj3)))))); j1eval[1]=((1.86843331090523)+(((2.73381294964029)*cj2))+((x186*x189))+((x187*x193))+((x187*x192))+(((5.36928730396977)*x190))+(((5.36928730396977)*x191))+((x188*x193))+((x188*x192))+((x185*x189))+x185+x186); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 ) { { IkReal evalcond[3]; bool bgotonextstatement = true; do { evalcond[0]=((IKabs(px))+(IKabs(py))); evalcond[1]=0; evalcond[2]=((0.12995)+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((0.05282)*cj2))+(((0.10374)*cj2*cj3))+(((0.10374)*sj2*sj3))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j1eval[3]; px=0; py=0; pp=pz*pz; IkReal x194=((0.273)*sj2); IkReal x195=((0.273)*cj2); j1eval[0]=pz; j1eval[1]=((IKabs(((-0.19)+(((-1.0)*sj3*x194))+(((-1.0)*cj3*x195))+(((-0.139)*cj2)))))+(IKabs(((((0.139)*sj2))+((cj3*x194))+(((-1.0)*sj3*x195)))))); j1eval[2]=IKsign(pz); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 || IKabs(j1eval[2]) < 0.0000010000000000 ) { { IkReal j1eval[1]; px=0; py=0; pp=pz*pz; j1eval[0]=pz; if( IKabs(j1eval[0]) < 0.0000010000000000 ) { { IkReal j1eval[2]; px=0; py=0; pp=pz*pz; IkReal x196=((1.96402877697842)*pz); j1eval[0]=((((1.36690647482014)*pz))+((sj2*sj3*x196))+((cj2*cj3*x196))+((cj2*pz))); j1eval[1]=pz; if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 ) { { IkReal evalcond[4]; bool bgotonextstatement = true; do { IkReal x197=((0.273)*sj2); IkReal x198=((0.273)*cj2); evalcond[0]=IKabs(pz); evalcond[1]=((-0.19)+(((-1.0)*sj3*x197))+(((-1.0)*cj3*x198))+(((-0.139)*cj2))); evalcond[2]=((((0.139)*sj2))+((cj3*x197))+(((-1.0)*sj3*x198))); evalcond[3]=((0.05775)+(((0.075894)*cj3))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j1eval[1]; px=0; py=0; pp=0; pz=0; IkReal x199=((0.273)*sj3); j1eval[0]=((IKabs(((((-0.0687338129496403)*sj2))+(((-1.0)*cj2*x199)))))+(IKabs(((-0.19)+(((0.0687338129496403)*cj2))+(((-1.0)*sj2*x199)))))); if( IKabs(j1eval[0]) < 0.0000010000000000 ) { { IkReal j1eval[1]; px=0; py=0; pp=0; pz=0; IkReal x200=((0.273)*sj3); j1eval[0]=((IKabs(((0.19)+(((-0.0687338129496403)*cj2))+((sj2*x200)))))+(IKabs(((((-1.0)*cj2*x200))+(((-0.0687338129496403)*sj2)))))); if( IKabs(j1eval[0]) < 0.0000010000000000 ) { continue; // no branches [j0, j1] } else { { IkReal j1array[2], cj1array[2], sj1array[2]; bool j1valid[2]={false}; _nj1 = 2; IkReal x201=((0.273)*sj3); CheckValue<IkReal> x203 = IKatan2WithCheck(IkReal(((((-1.0)*cj2*x201))+(((-0.0687338129496403)*sj2)))),((0.19)+(((-0.0687338129496403)*cj2))+((sj2*x201))),IKFAST_ATAN2_MAGTHRESH); if(!x203.valid){ continue; } IkReal x202=x203.value; j1array[0]=((-1.0)*x202); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); j1array[1]=((3.14159265358979)+(((-1.0)*x202))); sj1array[1]=IKsin(j1array[1]); cj1array[1]=IKcos(j1array[1]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; if( j1array[1] > IKPI ) { j1array[1]-=IK2PI; } else if( j1array[1] < -IKPI ) { j1array[1]+=IK2PI; } j1valid[1] = true; for(int ij1 = 0; ij1 < 2; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 2; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[1]; IkReal x204=IKcos(j1); IkReal x205=IKsin(j1); IkReal x206=((0.273)*sj3); evalcond[0]=((((0.0687338129496403)*cj2*x204))+(((-0.0687338129496403)*sj2*x205))+(((-1.0)*sj2*x204*x206))+(((-1.0)*cj2*x205*x206))+(((-0.19)*x204))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } else { { IkReal j1array[2], cj1array[2], sj1array[2]; bool j1valid[2]={false}; _nj1 = 2; IkReal x207=((0.273)*sj3); CheckValue<IkReal> x209 = IKatan2WithCheck(IkReal(((-0.19)+(((0.0687338129496403)*cj2))+(((-1.0)*sj2*x207)))),((((-1.0)*cj2*x207))+(((-0.0687338129496403)*sj2))),IKFAST_ATAN2_MAGTHRESH); if(!x209.valid){ continue; } IkReal x208=x209.value; j1array[0]=((-1.0)*x208); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); j1array[1]=((3.14159265358979)+(((-1.0)*x208))); sj1array[1]=IKsin(j1array[1]); cj1array[1]=IKcos(j1array[1]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; if( j1array[1] > IKPI ) { j1array[1]-=IK2PI; } else if( j1array[1] < -IKPI ) { j1array[1]+=IK2PI; } j1valid[1] = true; for(int ij1 = 0; ij1 < 2; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 2; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[1]; IkReal x210=IKsin(j1); IkReal x211=IKcos(j1); IkReal x212=((0.273)*sj3); evalcond[0]=((((-0.0687338129496403)*cj2*x210))+(((-1.0)*cj2*x211*x212))+((sj2*x210*x212))+(((-0.0687338129496403)*sj2*x211))+(((0.19)*x210))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0, j1] } } while(0); if( bgotonextstatement ) { } } } } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x213=pz*pz; IkReal x214=(cj3*sj2); IkReal x215=(cj2*cj3); IkReal x216=((5.187)*pz); IkReal x217=(cj2*sj3); IkReal x218=((13.65)*x213); CheckValue<IkReal> x219=IKPowWithIntegerCheck(((((2.641)*cj2*pz))+((sj2*sj3*x216))+((x215*x216))+(((3.61)*pz))),-1); if(!x219.valid){ continue; } CheckValue<IkReal> x220=IKPowWithIntegerCheck(pz,-1); if(!x220.valid){ continue; } if( IKabs(((x219.value)*(((((0.7882875)*x217))+((x214*x218))+(((6.95)*sj2*x213))+(((1.0359531)*sj3*x215))+(((-1.3157508)*x214))+(((-1.0)*x217*x218))+(((-1.0359531)*cj3*x214))+(((-0.4013625)*sj2)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((0.0526315789473684)*(x220.value)*(((2.8875)+(((3.7947)*cj3))+(((-50.0)*x213)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((x219.value)*(((((0.7882875)*x217))+((x214*x218))+(((6.95)*sj2*x213))+(((1.0359531)*sj3*x215))+(((-1.3157508)*x214))+(((-1.0)*x217*x218))+(((-1.0359531)*cj3*x214))+(((-0.4013625)*sj2))))))+IKsqr(((0.0526315789473684)*(x220.value)*(((2.8875)+(((3.7947)*cj3))+(((-50.0)*x213))))))-1) <= IKFAST_SINCOS_THRESH ) continue; j1array[0]=IKatan2(((x219.value)*(((((0.7882875)*x217))+((x214*x218))+(((6.95)*sj2*x213))+(((1.0359531)*sj3*x215))+(((-1.3157508)*x214))+(((-1.0)*x217*x218))+(((-1.0359531)*cj3*x214))+(((-0.4013625)*sj2))))), ((0.0526315789473684)*(x220.value)*(((2.8875)+(((3.7947)*cj3))+(((-50.0)*x213)))))); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x221=IKcos(j1); IkReal x222=IKsin(j1); IkReal x223=((0.273)*sj2); IkReal x224=((1.0)*pz); IkReal x225=((0.273)*cj3); IkReal x226=((0.273)*cj2); IkReal x227=((0.139)*cj2); IkReal x228=((0.139)*sj2); IkReal x229=(sj2*x222); IkReal x230=(cj3*x221); IkReal x231=(cj2*x222); IkReal x232=(sj3*x221); evalcond[0]=((0.05775)+(((-1.0)*pz*x224))+(((0.075894)*cj3))+(((-0.38)*pz*x221))); evalcond[1]=(((cj3*x223))+(((-1.0)*x222*x224))+x228+(((-1.0)*sj3*x226))); evalcond[2]=((-0.19)+(((-1.0)*sj3*x223))+(((-1.0)*cj2*x225))+(((-1.0)*x221*x224))+(((-1.0)*x227))); evalcond[3]=(((x222*x227))+((sj3*x222*x223))+(((0.19)*x222))+((x225*x231))+(((-1.0)*x226*x232))+((x221*x228))+((x223*x230))); evalcond[4]=(((cj3*x222*x223))+(((-0.19)*x221))+(((-1.0)*cj2*x221*x225))+((x222*x228))+(((-1.0)*sj3*x222*x226))+(((-1.0)*x223*x232))+(((-1.0)*x221*x227))+(((-1.0)*x224))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; CheckValue<IkReal> x234=IKPowWithIntegerCheck(pz,-1); if(!x234.valid){ continue; } IkReal x233=x234.value; CheckValue<IkReal> x235=IKPowWithIntegerCheck(x233,-2); if(!x235.valid){ continue; } if( IKabs((x233*(((((0.139)*sj2))+(((0.273)*cj3*sj2))+(((-0.273)*cj2*sj3)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((0.0526315789473684)*x233*(((2.8875)+(((3.7947)*cj3))+(((-50.0)*(x235.value))))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((x233*(((((0.139)*sj2))+(((0.273)*cj3*sj2))+(((-0.273)*cj2*sj3))))))+IKsqr(((0.0526315789473684)*x233*(((2.8875)+(((3.7947)*cj3))+(((-50.0)*(x235.value)))))))-1) <= IKFAST_SINCOS_THRESH ) continue; j1array[0]=IKatan2((x233*(((((0.139)*sj2))+(((0.273)*cj3*sj2))+(((-0.273)*cj2*sj3))))), ((0.0526315789473684)*x233*(((2.8875)+(((3.7947)*cj3))+(((-50.0)*(x235.value))))))); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x236=IKcos(j1); IkReal x237=IKsin(j1); IkReal x238=((0.273)*sj2); IkReal x239=((1.0)*pz); IkReal x240=((0.273)*cj3); IkReal x241=((0.273)*cj2); IkReal x242=((0.139)*cj2); IkReal x243=((0.139)*sj2); IkReal x244=(sj2*x237); IkReal x245=(cj3*x236); IkReal x246=(cj2*x237); IkReal x247=(sj3*x236); evalcond[0]=((0.05775)+(((-1.0)*pz*x239))+(((0.075894)*cj3))+(((-0.38)*pz*x236))); evalcond[1]=(((cj3*x238))+(((-1.0)*sj3*x241))+x243+(((-1.0)*x237*x239))); evalcond[2]=((-0.19)+(((-1.0)*cj2*x240))+(((-1.0)*x236*x239))+(((-1.0)*x242))+(((-1.0)*sj3*x238))); evalcond[3]=(((x240*x246))+((sj3*x237*x238))+((x237*x242))+((x238*x245))+(((0.19)*x237))+((x236*x243))+(((-1.0)*x241*x247))); evalcond[4]=(((cj3*x237*x238))+(((-1.0)*cj2*x236*x240))+((x237*x243))+(((-1.0)*x236*x242))+(((-1.0)*x239))+(((-1.0)*x238*x247))+(((-1.0)*sj3*x237*x241))+(((-0.19)*x236))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x248=((0.273)*sj2); IkReal x249=((0.273)*cj2); CheckValue<IkReal> x250 = IKatan2WithCheck(IkReal(((((-1.0)*sj3*x249))+(((0.139)*sj2))+((cj3*x248)))),((-0.19)+(((-1.0)*sj3*x248))+(((-1.0)*cj3*x249))+(((-0.139)*cj2))),IKFAST_ATAN2_MAGTHRESH); if(!x250.valid){ continue; } CheckValue<IkReal> x251=IKPowWithIntegerCheck(IKsign(pz),-1); if(!x251.valid){ continue; } j1array[0]=((-1.5707963267949)+(x250.value)+(((1.5707963267949)*(x251.value)))); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x252=IKcos(j1); IkReal x253=IKsin(j1); IkReal x254=((0.273)*sj2); IkReal x255=((1.0)*pz); IkReal x256=((0.273)*cj3); IkReal x257=((0.273)*cj2); IkReal x258=((0.139)*cj2); IkReal x259=((0.139)*sj2); IkReal x260=(sj2*x253); IkReal x261=(cj3*x252); IkReal x262=(cj2*x253); IkReal x263=(sj3*x252); evalcond[0]=((0.05775)+(((-1.0)*pz*x255))+(((0.075894)*cj3))+(((-0.38)*pz*x252))); evalcond[1]=(((cj3*x254))+x259+(((-1.0)*sj3*x257))+(((-1.0)*x253*x255))); evalcond[2]=((-0.19)+(((-1.0)*x252*x255))+(((-1.0)*sj3*x254))+(((-1.0)*cj2*x256))+(((-1.0)*x258))); evalcond[3]=((((0.19)*x253))+((sj3*x253*x254))+((x254*x261))+((x253*x258))+((x256*x262))+((x252*x259))+(((-1.0)*x257*x263))); evalcond[4]=((((-1.0)*x252*x258))+(((-0.19)*x252))+((cj3*x253*x254))+((x253*x259))+(((-1.0)*cj2*x252*x256))+(((-1.0)*sj3*x253*x257))+(((-1.0)*x254*x263))+(((-1.0)*x255))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0, j1] } } while(0); if( bgotonextstatement ) { } } } } else { { IkReal j1array[2], cj1array[2], sj1array[2]; bool j1valid[2]={false}; _nj1 = 2; IkReal x264=((0.273)*cj3); IkReal x265=((0.273)*sj3); IkReal x266=((((0.139)*sj2))+((sj2*x264))+(((-1.0)*cj2*x265))); IkReal x267=((-0.19)+(((-1.0)*sj2*x265))+(((-1.0)*cj2*x264))+(((-0.139)*cj2))); CheckValue<IkReal> x270 = IKatan2WithCheck(IkReal(x267),x266,IKFAST_ATAN2_MAGTHRESH); if(!x270.valid){ continue; } IkReal x268=((1.0)*(x270.value)); if((((x266*x266)+(x267*x267))) < -0.00001) continue; CheckValue<IkReal> x271=IKPowWithIntegerCheck(IKabs(IKsqrt(((x266*x266)+(x267*x267)))),-1); if(!x271.valid){ continue; } if( ((pz*(x271.value))) < -1-IKFAST_SINCOS_THRESH || ((pz*(x271.value))) > 1+IKFAST_SINCOS_THRESH ) continue; IkReal x269=IKasin((pz*(x271.value))); j1array[0]=(x269+(((-1.0)*x268))); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); j1array[1]=((3.14159265358979)+(((-1.0)*x269))+(((-1.0)*x268))); sj1array[1]=IKsin(j1array[1]); cj1array[1]=IKcos(j1array[1]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; if( j1array[1] > IKPI ) { j1array[1]-=IK2PI; } else if( j1array[1] < -IKPI ) { j1array[1]+=IK2PI; } j1valid[1] = true; for(int ij1 = 0; ij1 < 2; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 2; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal j0eval[3]; IkReal x272=((139.0)*sj2); IkReal x273=((1000.0)*pz*sj1); IkReal x274=((273.0)*cj2*sj3); IkReal x275=((273.0)*cj3*sj2); IkReal x276=(((cj1*(px*px)))+((cj1*(py*py)))); j0eval[0]=x276; j0eval[1]=((IKabs((((py*x272))+((py*x275))+(((-1.0)*py*x273))+(((-1.0)*py*x274)))))+(IKabs((((px*x272))+((px*x275))+(((-1.0)*px*x273))+(((-1.0)*px*x274)))))); j0eval[2]=IKsign(x276); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { { IkReal j0eval[3]; IkReal x277=(cj2*py); IkReal x278=((273.0)*px); IkReal x279=(sj2*sj3); IkReal x280=((1000.0)*cj1*pz); IkReal x281=(((sj1*(py*py)))+((sj1*(px*px)))); j0eval[0]=x281; j0eval[1]=IKsign(x281); j0eval[2]=((IKabs(((((139.0)*cj2*px))+(((190.0)*px))+((cj2*cj3*x278))+((x278*x279))+((px*x280)))))+(IKabs(((((190.0)*py))+(((139.0)*x277))+(((273.0)*py*x279))+(((273.0)*cj3*x277))+((py*x280)))))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { { IkReal j0eval[3]; IkReal x282=px*px; IkReal x283=py*py; IkReal x284=pz*pz; IkReal x285=((37947.0)*cj3); IkReal x286=((500000.0)*px); IkReal x287=((500000.0)*py); IkReal x288=(sj1*x282); IkReal x289=(sj1*x283); IkReal x290=((190000.0)*cj1*pz); j0eval[0]=(x289+x288); j0eval[1]=IKsign(((((19.0)*x288))+(((19.0)*x289)))); j0eval[2]=((IKabs((((x284*x286))+(((-1.0)*px*x285))+((px*x290))+(((-28875.0)*px))+((x283*x286))+((x286*(px*px))))))+(IKabs((((x284*x287))+((x287*(py*py)))+((py*x290))+(((-1.0)*py*x285))+(((-28875.0)*py))+((x282*x287)))))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { { IkReal evalcond[8]; bool bgotonextstatement = true; do { IkReal x291=((0.075894)*cj3); IkReal x292=(cj2*cj3); IkReal x293=(sj2*sj3); IkReal x294=((1.0)*(px*px)); IkReal x295=((1.0)*(py*py)); IkReal x296=((1.0)*(pz*pz)); IkReal x297=(x294+x295+x296); IkReal x298=((-0.19)+(((-1.0)*pz))+(((-0.273)*x292))+(((-0.273)*x293))+(((-0.139)*cj2))); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j1))), 6.28318530717959))); evalcond[1]=((0.12995)+(((0.10374)*x292))+(((0.10374)*x293))+(((-1.0)*x297))+x291+(((0.05282)*cj2))); evalcond[2]=x298; evalcond[3]=((0.05775)+(((-0.38)*pz))+(((-1.0)*x297))+x291); evalcond[4]=x298; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[3]; sj1=0; cj1=1.0; j1=0; IkReal x299=(px*sj2); IkReal x300=((273.0)*cj3); IkReal x301=(py*sj2); IkReal x302=((273.0)*cj2*sj3); IkReal x303=((px*px)+(py*py)); j0eval[0]=x303; j0eval[1]=IKsign(x303); j0eval[2]=((IKabs(((((-1.0)*px*x302))+((x299*x300))+(((139.0)*x299)))))+(IKabs(((((139.0)*x301))+(((-1.0)*py*x302))+((x300*x301)))))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { { IkReal evalcond[4]; bool bgotonextstatement = true; do { IkReal x304=x266; evalcond[0]=((px*px)+(py*py)); evalcond[1]=0; evalcond[2]=x304; evalcond[3]=x304; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0array[4], cj0array[4], sj0array[4]; bool j0valid[4]={false}; _nj0 = 4; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=1.5707963267949; sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); j0array[2]=3.14159265358979; sj0array[2]=IKsin(j0array[2]); cj0array[2]=IKcos(j0array[2]); j0array[3]=-1.5707963267949; sj0array[3]=IKsin(j0array[3]); cj0array[3]=IKcos(j0array[3]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; if( j0array[2] > IKPI ) { j0array[2]-=IK2PI; } else if( j0array[2] < -IKPI ) { j0array[2]+=IK2PI; } j0valid[2] = true; if( j0array[3] > IKPI ) { j0array[3]-=IK2PI; } else if( j0array[3] < -IKPI ) { j0array[3]+=IK2PI; } j0valid[3] = true; for(int ij0 = 0; ij0 < 4; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 4; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x305=x266; evalcond[0]=((IKabs(px))+(IKabs(py))); evalcond[1]=0; evalcond[2]=x305; evalcond[3]=x305; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0array[4], cj0array[4], sj0array[4]; bool j0valid[4]={false}; _nj0 = 4; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=1.5707963267949; sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); j0array[2]=3.14159265358979; sj0array[2]=IKsin(j0array[2]); cj0array[2]=IKcos(j0array[2]); j0array[3]=-1.5707963267949; sj0array[3]=IKsin(j0array[3]); cj0array[3]=IKcos(j0array[3]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; if( j0array[2] > IKPI ) { j0array[2]-=IK2PI; } else if( j0array[2] < -IKPI ) { j0array[2]+=IK2PI; } j0valid[2] = true; if( j0array[3] > IKPI ) { j0array[3]-=IK2PI; } else if( j0array[3] < -IKPI ) { j0array[3]+=IK2PI; } j0valid[3] = true; for(int ij0 = 0; ij0 < 4; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 4; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(((-3.14159265358979)+(IKfmod(((3.14159265358979)+j3), 6.28318530717959)))))+(IKabs(((-3.14159265358979)+(IKfmod(((3.14159265358979)+j2), 6.28318530717959)))))); if( IKabs(evalcond[0]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[1]; sj1=0; cj1=1.0; j1=0; j3=0; sj3=0; cj3=1.0; j2=0; sj2=0; cj2=1.0; j0eval[0]=((IKabs(px))+(IKabs(py))); if( IKabs(j0eval[0]) < 0.0000010000000000 ) { { IkReal evalcond[2]; bool bgotonextstatement = true; do { evalcond[0]=((IKabs(px))+(IKabs(py))); evalcond[1]=0; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0array[4], cj0array[4], sj0array[4]; bool j0valid[4]={false}; _nj0 = 4; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=1.5707963267949; sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); j0array[2]=3.14159265358979; sj0array[2]=IKsin(j0array[2]); cj0array[2]=IKcos(j0array[2]); j0array[3]=-1.5707963267949; sj0array[3]=IKsin(j0array[3]); cj0array[3]=IKcos(j0array[3]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; if( j0array[2] > IKPI ) { j0array[2]-=IK2PI; } else if( j0array[2] < -IKPI ) { j0array[2]+=IK2PI; } j0valid[2] = true; if( j0array[3] > IKPI ) { j0array[3]-=IK2PI; } else if( j0array[3] < -IKPI ) { j0array[3]+=IK2PI; } j0valid[3] = true; for(int ij0 = 0; ij0 < 4; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 4; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0] } } while(0); if( bgotonextstatement ) { } } } } else { { IkReal j0array[2], cj0array[2], sj0array[2]; bool j0valid[2]={false}; _nj0 = 2; CheckValue<IkReal> x307 = IKatan2WithCheck(IkReal(py),((-1.0)*px),IKFAST_ATAN2_MAGTHRESH); if(!x307.valid){ continue; } IkReal x306=x307.value; j0array[0]=((-1.0)*x306); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=((3.14159265358979)+(((-1.0)*x306))); sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; for(int ij0 = 0; ij0 < 2; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 2; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[1]; evalcond[0]=((((-1.0)*py*(IKsin(j0))))+(((-1.0)*px*(IKcos(j0))))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(((-3.14159265358979)+(IKfmod(j2, 6.28318530717959)))))+(IKabs(((-3.14159265358979)+(IKfmod(((3.14159265358979)+j3), 6.28318530717959)))))); if( IKabs(evalcond[0]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[1]; sj1=0; cj1=1.0; j1=0; j3=0; sj3=0; cj3=1.0; j2=3.14159265358979; sj2=0; cj2=-1.0; j0eval[0]=((IKabs(px))+(IKabs(py))); if( IKabs(j0eval[0]) < 0.0000010000000000 ) { { IkReal evalcond[2]; bool bgotonextstatement = true; do { evalcond[0]=((IKabs(px))+(IKabs(py))); evalcond[1]=0; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0array[4], cj0array[4], sj0array[4]; bool j0valid[4]={false}; _nj0 = 4; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=1.5707963267949; sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); j0array[2]=3.14159265358979; sj0array[2]=IKsin(j0array[2]); cj0array[2]=IKcos(j0array[2]); j0array[3]=-1.5707963267949; sj0array[3]=IKsin(j0array[3]); cj0array[3]=IKcos(j0array[3]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; if( j0array[2] > IKPI ) { j0array[2]-=IK2PI; } else if( j0array[2] < -IKPI ) { j0array[2]+=IK2PI; } j0valid[2] = true; if( j0array[3] > IKPI ) { j0array[3]-=IK2PI; } else if( j0array[3] < -IKPI ) { j0array[3]+=IK2PI; } j0valid[3] = true; for(int ij0 = 0; ij0 < 4; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 4; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0] } } while(0); if( bgotonextstatement ) { } } } } else { { IkReal j0array[2], cj0array[2], sj0array[2]; bool j0valid[2]={false}; _nj0 = 2; CheckValue<IkReal> x309 = IKatan2WithCheck(IkReal(py),((-1.0)*px),IKFAST_ATAN2_MAGTHRESH); if(!x309.valid){ continue; } IkReal x308=x309.value; j0array[0]=((-1.0)*x308); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=((3.14159265358979)+(((-1.0)*x308))); sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; for(int ij0 = 0; ij0 < 2; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 2; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[1]; evalcond[0]=((((-1.0)*py*(IKsin(j0))))+(((-1.0)*px*(IKcos(j0))))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(((-3.14159265358979)+(IKfmod(j3, 6.28318530717959)))))+(IKabs(((-3.14159265358979)+(IKfmod(((3.14159265358979)+j2), 6.28318530717959)))))); if( IKabs(evalcond[0]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[1]; sj1=0; cj1=1.0; j1=0; j3=3.14159265358979; sj3=0; cj3=-1.0; j2=0; sj2=0; cj2=1.0; j0eval[0]=((IKabs(px))+(IKabs(py))); if( IKabs(j0eval[0]) < 0.0000010000000000 ) { { IkReal evalcond[2]; bool bgotonextstatement = true; do { evalcond[0]=((IKabs(px))+(IKabs(py))); evalcond[1]=0; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0array[4], cj0array[4], sj0array[4]; bool j0valid[4]={false}; _nj0 = 4; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=1.5707963267949; sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); j0array[2]=3.14159265358979; sj0array[2]=IKsin(j0array[2]); cj0array[2]=IKcos(j0array[2]); j0array[3]=-1.5707963267949; sj0array[3]=IKsin(j0array[3]); cj0array[3]=IKcos(j0array[3]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; if( j0array[2] > IKPI ) { j0array[2]-=IK2PI; } else if( j0array[2] < -IKPI ) { j0array[2]+=IK2PI; } j0valid[2] = true; if( j0array[3] > IKPI ) { j0array[3]-=IK2PI; } else if( j0array[3] < -IKPI ) { j0array[3]+=IK2PI; } j0valid[3] = true; for(int ij0 = 0; ij0 < 4; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 4; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0] } } while(0); if( bgotonextstatement ) { } } } } else { { IkReal j0array[2], cj0array[2], sj0array[2]; bool j0valid[2]={false}; _nj0 = 2; CheckValue<IkReal> x311 = IKatan2WithCheck(IkReal(py),((-1.0)*px),IKFAST_ATAN2_MAGTHRESH); if(!x311.valid){ continue; } IkReal x310=x311.value; j0array[0]=((-1.0)*x310); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=((3.14159265358979)+(((-1.0)*x310))); sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; for(int ij0 = 0; ij0 < 2; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 2; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[1]; evalcond[0]=((((-1.0)*py*(IKsin(j0))))+(((-1.0)*px*(IKcos(j0))))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(((-3.14159265358979)+(IKfmod(j3, 6.28318530717959)))))+(IKabs(((-3.14159265358979)+(IKfmod(j2, 6.28318530717959)))))); if( IKabs(evalcond[0]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[1]; sj1=0; cj1=1.0; j1=0; j3=3.14159265358979; sj3=0; cj3=-1.0; j2=3.14159265358979; sj2=0; cj2=-1.0; j0eval[0]=((IKabs(px))+(IKabs(py))); if( IKabs(j0eval[0]) < 0.0000010000000000 ) { { IkReal evalcond[2]; bool bgotonextstatement = true; do { evalcond[0]=((IKabs(px))+(IKabs(py))); evalcond[1]=0; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0array[4], cj0array[4], sj0array[4]; bool j0valid[4]={false}; _nj0 = 4; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=1.5707963267949; sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); j0array[2]=3.14159265358979; sj0array[2]=IKsin(j0array[2]); cj0array[2]=IKcos(j0array[2]); j0array[3]=-1.5707963267949; sj0array[3]=IKsin(j0array[3]); cj0array[3]=IKcos(j0array[3]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; if( j0array[2] > IKPI ) { j0array[2]-=IK2PI; } else if( j0array[2] < -IKPI ) { j0array[2]+=IK2PI; } j0valid[2] = true; if( j0array[3] > IKPI ) { j0array[3]-=IK2PI; } else if( j0array[3] < -IKPI ) { j0array[3]+=IK2PI; } j0valid[3] = true; for(int ij0 = 0; ij0 < 4; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 4; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0] } } while(0); if( bgotonextstatement ) { } } } } else { { IkReal j0array[2], cj0array[2], sj0array[2]; bool j0valid[2]={false}; _nj0 = 2; CheckValue<IkReal> x313 = IKatan2WithCheck(IkReal(py),((-1.0)*px),IKFAST_ATAN2_MAGTHRESH); if(!x313.valid){ continue; } IkReal x312=x313.value; j0array[0]=((-1.0)*x312); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=((3.14159265358979)+(((-1.0)*x312))); sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; for(int ij0 = 0; ij0 < 2; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 2; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[1]; evalcond[0]=((((-1.0)*py*(IKsin(j0))))+(((-1.0)*px*(IKcos(j0))))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0] } } while(0); if( bgotonextstatement ) { } } } } } } } } } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x314=(px*sj2); IkReal x315=((0.273)*cj3); IkReal x316=(py*sj2); IkReal x317=((0.273)*cj2*sj3); CheckValue<IkReal> x318 = IKatan2WithCheck(IkReal(((((0.139)*x316))+((x315*x316))+(((-1.0)*py*x317)))),((((0.139)*x314))+((x314*x315))+(((-1.0)*px*x317))),IKFAST_ATAN2_MAGTHRESH); if(!x318.valid){ continue; } CheckValue<IkReal> x319=IKPowWithIntegerCheck(IKsign(((px*px)+(py*py))),-1); if(!x319.valid){ continue; } j0array[0]=((-1.5707963267949)+(x318.value)+(((1.5707963267949)*(x319.value)))); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[2]; IkReal x320=IKcos(j0); IkReal x321=IKsin(j0); IkReal x322=((1.0)*px); evalcond[0]=((((-1.0)*x321*x322))+((py*x320))); evalcond[1]=((((-1.0)*py*x321))+(((0.139)*sj2))+(((-1.0)*x320*x322))+(((0.273)*cj3*sj2))+(((-0.273)*cj2*sj3))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x323=((0.075894)*cj3); IkReal x324=((0.139)*cj2); IkReal x325=(cj2*cj3); IkReal x326=(sj2*sj3); IkReal x327=((0.273)*x325); IkReal x328=((0.273)*x326); IkReal x329=(x324+x327+x328); IkReal x330=((((1.0)*(px*px)))+(((1.0)*(py*py)))+(((1.0)*(pz*pz)))); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j1)))), 6.28318530717959))); evalcond[1]=((0.12995)+x323+(((0.10374)*x325))+(((0.10374)*x326))+(((-1.0)*x330))+(((0.05282)*cj2))); evalcond[2]=((-0.19)+(((-1.0)*x329))+pz); evalcond[3]=((0.05775)+(((0.38)*pz))+x323+(((-1.0)*x330))); evalcond[4]=((0.19)+x329+(((-1.0)*pz))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[3]; sj1=0; cj1=-1.0; j1=3.14159265358979; IkReal x331=(px*sj2); IkReal x332=((273.0)*cj3); IkReal x333=(py*sj2); IkReal x334=((273.0)*cj2*sj3); IkReal x335=((((-1.0)*(px*px)))+(((-1.0)*(py*py)))); j0eval[0]=x335; j0eval[1]=IKsign(x335); j0eval[2]=((IKabs(((((139.0)*x331))+(((-1.0)*px*x334))+((x331*x332)))))+(IKabs(((((139.0)*x333))+((x332*x333))+(((-1.0)*py*x334)))))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { { IkReal evalcond[4]; bool bgotonextstatement = true; do { IkReal x336=((0.273)*cj2*sj3); IkReal x337=((((0.139)*sj2))+(((0.273)*cj3*sj2))); evalcond[0]=((IKabs(px))+(IKabs(py))); evalcond[1]=0; evalcond[2]=(x337+(((-1.0)*x336))); evalcond[3]=(x336+(((-1.0)*x337))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0array[4], cj0array[4], sj0array[4]; bool j0valid[4]={false}; _nj0 = 4; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=1.5707963267949; sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); j0array[2]=3.14159265358979; sj0array[2]=IKsin(j0array[2]); cj0array[2]=IKcos(j0array[2]); j0array[3]=-1.5707963267949; sj0array[3]=IKsin(j0array[3]); cj0array[3]=IKcos(j0array[3]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; if( j0array[2] > IKPI ) { j0array[2]-=IK2PI; } else if( j0array[2] < -IKPI ) { j0array[2]+=IK2PI; } j0valid[2] = true; if( j0array[3] > IKPI ) { j0array[3]-=IK2PI; } else if( j0array[3] < -IKPI ) { j0array[3]+=IK2PI; } j0valid[3] = true; for(int ij0 = 0; ij0 < 4; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 4; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(((-3.14159265358979)+(IKfmod(((3.14159265358979)+j3), 6.28318530717959)))))+(IKabs(((-3.14159265358979)+(IKfmod(((3.14159265358979)+j2), 6.28318530717959)))))); if( IKabs(evalcond[0]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[1]; sj1=0; cj1=-1.0; j1=3.14159265358979; j3=0; sj3=0; cj3=1.0; j2=0; sj2=0; cj2=1.0; j0eval[0]=((IKabs(px))+(IKabs(py))); if( IKabs(j0eval[0]) < 0.0000010000000000 ) { { IkReal evalcond[2]; bool bgotonextstatement = true; do { evalcond[0]=((IKabs(px))+(IKabs(py))); evalcond[1]=0; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0array[4], cj0array[4], sj0array[4]; bool j0valid[4]={false}; _nj0 = 4; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=1.5707963267949; sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); j0array[2]=3.14159265358979; sj0array[2]=IKsin(j0array[2]); cj0array[2]=IKcos(j0array[2]); j0array[3]=-1.5707963267949; sj0array[3]=IKsin(j0array[3]); cj0array[3]=IKcos(j0array[3]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; if( j0array[2] > IKPI ) { j0array[2]-=IK2PI; } else if( j0array[2] < -IKPI ) { j0array[2]+=IK2PI; } j0valid[2] = true; if( j0array[3] > IKPI ) { j0array[3]-=IK2PI; } else if( j0array[3] < -IKPI ) { j0array[3]+=IK2PI; } j0valid[3] = true; for(int ij0 = 0; ij0 < 4; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 4; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0] } } while(0); if( bgotonextstatement ) { } } } } else { { IkReal j0array[2], cj0array[2], sj0array[2]; bool j0valid[2]={false}; _nj0 = 2; CheckValue<IkReal> x339 = IKatan2WithCheck(IkReal(px),py,IKFAST_ATAN2_MAGTHRESH); if(!x339.valid){ continue; } IkReal x338=x339.value; j0array[0]=((-1.0)*x338); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=((3.14159265358979)+(((-1.0)*x338))); sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; for(int ij0 = 0; ij0 < 2; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 2; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[1]; evalcond[0]=((((-1.0)*px*(IKsin(j0))))+((py*(IKcos(j0))))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(((-3.14159265358979)+(IKfmod(j2, 6.28318530717959)))))+(IKabs(((-3.14159265358979)+(IKfmod(((3.14159265358979)+j3), 6.28318530717959)))))); if( IKabs(evalcond[0]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[1]; sj1=0; cj1=-1.0; j1=3.14159265358979; j3=0; sj3=0; cj3=1.0; j2=3.14159265358979; sj2=0; cj2=-1.0; j0eval[0]=((IKabs(px))+(IKabs(py))); if( IKabs(j0eval[0]) < 0.0000010000000000 ) { { IkReal evalcond[2]; bool bgotonextstatement = true; do { evalcond[0]=((IKabs(px))+(IKabs(py))); evalcond[1]=0; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0array[4], cj0array[4], sj0array[4]; bool j0valid[4]={false}; _nj0 = 4; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=1.5707963267949; sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); j0array[2]=3.14159265358979; sj0array[2]=IKsin(j0array[2]); cj0array[2]=IKcos(j0array[2]); j0array[3]=-1.5707963267949; sj0array[3]=IKsin(j0array[3]); cj0array[3]=IKcos(j0array[3]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; if( j0array[2] > IKPI ) { j0array[2]-=IK2PI; } else if( j0array[2] < -IKPI ) { j0array[2]+=IK2PI; } j0valid[2] = true; if( j0array[3] > IKPI ) { j0array[3]-=IK2PI; } else if( j0array[3] < -IKPI ) { j0array[3]+=IK2PI; } j0valid[3] = true; for(int ij0 = 0; ij0 < 4; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 4; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0] } } while(0); if( bgotonextstatement ) { } } } } else { { IkReal j0array[2], cj0array[2], sj0array[2]; bool j0valid[2]={false}; _nj0 = 2; CheckValue<IkReal> x341 = IKatan2WithCheck(IkReal(px),py,IKFAST_ATAN2_MAGTHRESH); if(!x341.valid){ continue; } IkReal x340=x341.value; j0array[0]=((-1.0)*x340); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=((3.14159265358979)+(((-1.0)*x340))); sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; for(int ij0 = 0; ij0 < 2; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 2; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[1]; evalcond[0]=((((-1.0)*px*(IKsin(j0))))+((py*(IKcos(j0))))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(((-3.14159265358979)+(IKfmod(j3, 6.28318530717959)))))+(IKabs(((-3.14159265358979)+(IKfmod(((3.14159265358979)+j2), 6.28318530717959)))))); if( IKabs(evalcond[0]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[1]; sj1=0; cj1=-1.0; j1=3.14159265358979; j3=3.14159265358979; sj3=0; cj3=-1.0; j2=0; sj2=0; cj2=1.0; j0eval[0]=((IKabs(px))+(IKabs(py))); if( IKabs(j0eval[0]) < 0.0000010000000000 ) { { IkReal evalcond[2]; bool bgotonextstatement = true; do { evalcond[0]=((IKabs(px))+(IKabs(py))); evalcond[1]=0; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0array[4], cj0array[4], sj0array[4]; bool j0valid[4]={false}; _nj0 = 4; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=1.5707963267949; sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); j0array[2]=3.14159265358979; sj0array[2]=IKsin(j0array[2]); cj0array[2]=IKcos(j0array[2]); j0array[3]=-1.5707963267949; sj0array[3]=IKsin(j0array[3]); cj0array[3]=IKcos(j0array[3]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; if( j0array[2] > IKPI ) { j0array[2]-=IK2PI; } else if( j0array[2] < -IKPI ) { j0array[2]+=IK2PI; } j0valid[2] = true; if( j0array[3] > IKPI ) { j0array[3]-=IK2PI; } else if( j0array[3] < -IKPI ) { j0array[3]+=IK2PI; } j0valid[3] = true; for(int ij0 = 0; ij0 < 4; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 4; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0] } } while(0); if( bgotonextstatement ) { } } } } else { { IkReal j0array[2], cj0array[2], sj0array[2]; bool j0valid[2]={false}; _nj0 = 2; CheckValue<IkReal> x343 = IKatan2WithCheck(IkReal(px),py,IKFAST_ATAN2_MAGTHRESH); if(!x343.valid){ continue; } IkReal x342=x343.value; j0array[0]=((-1.0)*x342); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=((3.14159265358979)+(((-1.0)*x342))); sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; for(int ij0 = 0; ij0 < 2; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 2; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[1]; evalcond[0]=((((-1.0)*px*(IKsin(j0))))+((py*(IKcos(j0))))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(((-3.14159265358979)+(IKfmod(j3, 6.28318530717959)))))+(IKabs(((-3.14159265358979)+(IKfmod(j2, 6.28318530717959)))))); if( IKabs(evalcond[0]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[1]; sj1=0; cj1=-1.0; j1=3.14159265358979; j3=3.14159265358979; sj3=0; cj3=-1.0; j2=3.14159265358979; sj2=0; cj2=-1.0; j0eval[0]=((IKabs(px))+(IKabs(py))); if( IKabs(j0eval[0]) < 0.0000010000000000 ) { { IkReal evalcond[2]; bool bgotonextstatement = true; do { evalcond[0]=((IKabs(px))+(IKabs(py))); evalcond[1]=0; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0array[4], cj0array[4], sj0array[4]; bool j0valid[4]={false}; _nj0 = 4; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=1.5707963267949; sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); j0array[2]=3.14159265358979; sj0array[2]=IKsin(j0array[2]); cj0array[2]=IKcos(j0array[2]); j0array[3]=-1.5707963267949; sj0array[3]=IKsin(j0array[3]); cj0array[3]=IKcos(j0array[3]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; if( j0array[2] > IKPI ) { j0array[2]-=IK2PI; } else if( j0array[2] < -IKPI ) { j0array[2]+=IK2PI; } j0valid[2] = true; if( j0array[3] > IKPI ) { j0array[3]-=IK2PI; } else if( j0array[3] < -IKPI ) { j0array[3]+=IK2PI; } j0valid[3] = true; for(int ij0 = 0; ij0 < 4; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 4; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0] } } while(0); if( bgotonextstatement ) { } } } } else { { IkReal j0array[2], cj0array[2], sj0array[2]; bool j0valid[2]={false}; _nj0 = 2; CheckValue<IkReal> x345 = IKatan2WithCheck(IkReal(px),py,IKFAST_ATAN2_MAGTHRESH); if(!x345.valid){ continue; } IkReal x344=x345.value; j0array[0]=((-1.0)*x344); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=((3.14159265358979)+(((-1.0)*x344))); sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; for(int ij0 = 0; ij0 < 2; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 2; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[1]; evalcond[0]=((((-1.0)*px*(IKsin(j0))))+((py*(IKcos(j0))))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0] } } while(0); if( bgotonextstatement ) { } } } } } } } } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x346=(px*sj2); IkReal x347=((0.273)*cj3); IkReal x348=(py*sj2); IkReal x349=((0.273)*cj2*sj3); CheckValue<IkReal> x350=IKPowWithIntegerCheck(IKsign(((((-1.0)*(px*px)))+(((-1.0)*(py*py))))),-1); if(!x350.valid){ continue; } CheckValue<IkReal> x351 = IKatan2WithCheck(IkReal((((x347*x348))+(((0.139)*x348))+(((-1.0)*py*x349)))),((((-1.0)*px*x349))+((x346*x347))+(((0.139)*x346))),IKFAST_ATAN2_MAGTHRESH); if(!x351.valid){ continue; } j0array[0]=((-1.5707963267949)+(((1.5707963267949)*(x350.value)))+(x351.value)); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[2]; IkReal x352=IKsin(j0); IkReal x353=IKcos(j0); evalcond[0]=(((py*x353))+(((-1.0)*px*x352))); evalcond[1]=(((px*x353))+(((0.139)*sj2))+((py*x352))+(((0.273)*cj3*sj2))+(((-0.273)*cj2*sj3))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x354=((((0.139)*sj2))+(((-1.0)*pz))+(((0.273)*cj3*sj2))+(((-0.273)*cj2*sj3))); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j1)))), 6.28318530717959))); evalcond[1]=((0.12995)+(((-1.0)*(px*px)))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((0.05282)*cj2))+(((0.10374)*cj2*cj3))+(((-1.0)*(py*py)))+(((0.10374)*sj2*sj3))); evalcond[2]=x354; evalcond[3]=x354; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[3]; sj1=1.0; cj1=0; j1=1.5707963267949; IkReal x355=(cj2*py); IkReal x356=((273.0)*cj3); IkReal x357=(cj2*px); IkReal x358=((273.0)*sj2*sj3); IkReal x359=((((-1.0)*(px*px)))+(((-1.0)*(py*py)))); j0eval[0]=x359; j0eval[1]=IKsign(x359); j0eval[2]=((IKabs(((((-139.0)*x355))+(((-190.0)*py))+(((-1.0)*py*x358))+(((-1.0)*x355*x356)))))+(IKabs(((((-139.0)*x357))+(((-190.0)*px))+(((-1.0)*px*x358))+(((-1.0)*x356*x357)))))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { { IkReal j0eval[3]; sj1=1.0; cj1=0; j1=1.5707963267949; IkReal x360=py*py; IkReal x361=px*px; IkReal x362=pz*pz; IkReal x363=((500000.0)*px); IkReal x364=((500000.0)*py); IkReal x365=((37947.0)*cj3); j0eval[0]=((((-1.0)*x360))+(((-1.0)*x361))); j0eval[1]=IKsign(((((-19.0)*x360))+(((-19.0)*x361)))); j0eval[2]=((IKabs(((((-1.0)*x362*x363))+(((-1.0)*x360*x363))+(((28875.0)*px))+((px*x365))+(((-1.0)*x363*(px*px))))))+(IKabs(((((-1.0)*x362*x364))+(((-1.0)*x361*x364))+(((28875.0)*py))+((py*x365))+(((-1.0)*x364*(py*py))))))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { { IkReal evalcond[5]; bool bgotonextstatement = true; do { IkReal x366=((0.139)*cj2); IkReal x367=((0.273)*cj2*cj3); IkReal x368=((0.273)*sj2*sj3); IkReal x369=(x368+x366+x367); evalcond[0]=((IKabs(px))+(IKabs(py))); evalcond[1]=0; evalcond[2]=((-0.19)+(((-1.0)*x369))); evalcond[3]=((0.05775)+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))); evalcond[4]=((0.19)+x369); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0array[4], cj0array[4], sj0array[4]; bool j0valid[4]={false}; _nj0 = 4; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=1.5707963267949; sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); j0array[2]=3.14159265358979; sj0array[2]=IKsin(j0array[2]); cj0array[2]=IKcos(j0array[2]); j0array[3]=-1.5707963267949; sj0array[3]=IKsin(j0array[3]); cj0array[3]=IKcos(j0array[3]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; if( j0array[2] > IKPI ) { j0array[2]-=IK2PI; } else if( j0array[2] < -IKPI ) { j0array[2]+=IK2PI; } j0valid[2] = true; if( j0array[3] > IKPI ) { j0array[3]-=IK2PI; } else if( j0array[3] < -IKPI ) { j0array[3]+=IK2PI; } j0valid[3] = true; for(int ij0 = 0; ij0 < 4; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 4; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0] } } while(0); if( bgotonextstatement ) { } } } } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x370=pz*pz; IkReal x371=py*py; IkReal x372=px*px; IkReal x373=((50.0)*px); IkReal x374=((50.0)*py); IkReal x375=((3.7947)*cj3); CheckValue<IkReal> x376=IKPowWithIntegerCheck(IKsign(((((-19.0)*x371))+(((-19.0)*x372)))),-1); if(!x376.valid){ continue; } CheckValue<IkReal> x377 = IKatan2WithCheck(IkReal(((((-1.0)*x370*x374))+(((-1.0)*x372*x374))+((py*x375))+(((-1.0)*x374*(py*py)))+(((2.8875)*py)))),((((-1.0)*x373*(px*px)))+(((-1.0)*x370*x373))+((px*x375))+(((-1.0)*x371*x373))+(((2.8875)*px))),IKFAST_ATAN2_MAGTHRESH); if(!x377.valid){ continue; } j0array[0]=((-1.5707963267949)+(((1.5707963267949)*(x376.value)))+(x377.value)); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[3]; IkReal x378=IKsin(j0); IkReal x379=IKcos(j0); IkReal x380=(px*x379); IkReal x381=(py*x378); evalcond[0]=(((py*x379))+(((-1.0)*px*x378))); evalcond[1]=((-0.19)+(((-0.273)*sj2*sj3))+x380+x381+(((-0.273)*cj2*cj3))+(((-0.139)*cj2))); evalcond[2]=((0.05775)+(((-1.0)*(px*px)))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((0.38)*x381))+(((0.38)*x380))+(((-1.0)*(py*py)))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x382=(cj2*px); IkReal x383=((0.273)*cj3); IkReal x384=(cj2*py); IkReal x385=((0.273)*sj2*sj3); CheckValue<IkReal> x386=IKPowWithIntegerCheck(IKsign(((((-1.0)*(px*px)))+(((-1.0)*(py*py))))),-1); if(!x386.valid){ continue; } CheckValue<IkReal> x387 = IKatan2WithCheck(IkReal(((((-1.0)*py*x385))+(((-0.139)*x384))+(((-0.19)*py))+(((-1.0)*x383*x384)))),((((-0.139)*x382))+(((-0.19)*px))+(((-1.0)*px*x385))+(((-1.0)*x382*x383))),IKFAST_ATAN2_MAGTHRESH); if(!x387.valid){ continue; } j0array[0]=((-1.5707963267949)+(((1.5707963267949)*(x386.value)))+(x387.value)); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[3]; IkReal x388=IKsin(j0); IkReal x389=IKcos(j0); IkReal x390=(px*x389); IkReal x391=(py*x388); evalcond[0]=((((-1.0)*px*x388))+((py*x389))); evalcond[1]=((-0.19)+(((-0.273)*sj2*sj3))+x391+x390+(((-0.273)*cj2*cj3))+(((-0.139)*cj2))); evalcond[2]=((0.05775)+(((-1.0)*(px*px)))+(((0.38)*x390))+(((0.38)*x391))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py)))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x392=((0.139)*sj2); IkReal x393=((0.273)*cj2*sj3); IkReal x394=((0.273)*cj3*sj2); IkReal x395=(x394+x392); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j1)))), 6.28318530717959))); evalcond[1]=((0.12995)+(((-1.0)*(px*px)))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((0.05282)*cj2))+(((0.10374)*cj2*cj3))+(((-1.0)*(py*py)))+(((0.10374)*sj2*sj3))); evalcond[2]=((((-1.0)*x393))+x395+pz); evalcond[3]=((((-1.0)*x395))+x393+(((-1.0)*pz))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[3]; sj1=-1.0; cj1=0; j1=-1.5707963267949; IkReal x396=(cj2*py); IkReal x397=((273.0)*px); IkReal x398=(sj2*sj3); IkReal x399=((px*px)+(py*py)); j0eval[0]=x399; j0eval[1]=IKsign(x399); j0eval[2]=((IKabs(((((-139.0)*x396))+(((-273.0)*py*x398))+(((-190.0)*py))+(((-273.0)*cj3*x396)))))+(IKabs(((((-190.0)*px))+(((-1.0)*cj2*cj3*x397))+(((-1.0)*x397*x398))+(((-139.0)*cj2*px)))))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { { IkReal j0eval[3]; sj1=-1.0; cj1=0; j1=-1.5707963267949; IkReal x400=py*py; IkReal x401=px*px; IkReal x402=pz*pz; IkReal x403=((500000.0)*px); IkReal x404=((500000.0)*py); IkReal x405=((37947.0)*cj3); j0eval[0]=(x401+x400); j0eval[1]=IKsign(((((19.0)*x400))+(((19.0)*x401)))); j0eval[2]=((IKabs((((py*x405))+(((28875.0)*py))+(((-1.0)*x402*x404))+(((-1.0)*x401*x404))+(((-1.0)*x404*(py*py))))))+(IKabs(((((-1.0)*x403*(px*px)))+(((28875.0)*px))+((px*x405))+(((-1.0)*x402*x403))+(((-1.0)*x400*x403)))))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { { IkReal evalcond[5]; bool bgotonextstatement = true; do { IkReal x406=x267; evalcond[0]=((px*px)+(py*py)); evalcond[1]=0; evalcond[2]=x406; evalcond[3]=((0.05775)+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))); evalcond[4]=x406; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0array[4], cj0array[4], sj0array[4]; bool j0valid[4]={false}; _nj0 = 4; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=1.5707963267949; sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); j0array[2]=3.14159265358979; sj0array[2]=IKsin(j0array[2]); cj0array[2]=IKcos(j0array[2]); j0array[3]=-1.5707963267949; sj0array[3]=IKsin(j0array[3]); cj0array[3]=IKcos(j0array[3]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; if( j0array[2] > IKPI ) { j0array[2]-=IK2PI; } else if( j0array[2] < -IKPI ) { j0array[2]+=IK2PI; } j0valid[2] = true; if( j0array[3] > IKPI ) { j0array[3]-=IK2PI; } else if( j0array[3] < -IKPI ) { j0array[3]+=IK2PI; } j0valid[3] = true; for(int ij0 = 0; ij0 < 4; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 4; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x407=x267; evalcond[0]=((IKabs(px))+(IKabs(py))); evalcond[1]=0; evalcond[2]=x407; evalcond[3]=((0.05775)+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))); evalcond[4]=x407; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0array[4], cj0array[4], sj0array[4]; bool j0valid[4]={false}; _nj0 = 4; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=1.5707963267949; sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); j0array[2]=3.14159265358979; sj0array[2]=IKsin(j0array[2]); cj0array[2]=IKcos(j0array[2]); j0array[3]=-1.5707963267949; sj0array[3]=IKsin(j0array[3]); cj0array[3]=IKcos(j0array[3]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; if( j0array[2] > IKPI ) { j0array[2]-=IK2PI; } else if( j0array[2] < -IKPI ) { j0array[2]+=IK2PI; } j0valid[2] = true; if( j0array[3] > IKPI ) { j0array[3]-=IK2PI; } else if( j0array[3] < -IKPI ) { j0array[3]+=IK2PI; } j0valid[3] = true; for(int ij0 = 0; ij0 < 4; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 4; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0] } } while(0); if( bgotonextstatement ) { } } } } } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x408=pz*pz; IkReal x409=py*py; IkReal x410=px*px; IkReal x411=((50.0)*px); IkReal x412=((50.0)*py); IkReal x413=((3.7947)*cj3); CheckValue<IkReal> x414 = IKatan2WithCheck(IkReal((((py*x413))+(((-1.0)*x412*(py*py)))+(((-1.0)*x410*x412))+(((2.8875)*py))+(((-1.0)*x408*x412)))),((((-1.0)*x411*(px*px)))+((px*x413))+(((2.8875)*px))+(((-1.0)*x408*x411))+(((-1.0)*x409*x411))),IKFAST_ATAN2_MAGTHRESH); if(!x414.valid){ continue; } CheckValue<IkReal> x415=IKPowWithIntegerCheck(IKsign(((((19.0)*x410))+(((19.0)*x409)))),-1); if(!x415.valid){ continue; } j0array[0]=((-1.5707963267949)+(x414.value)+(((1.5707963267949)*(x415.value)))); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[3]; IkReal x416=IKcos(j0); IkReal x417=IKsin(j0); IkReal x418=(px*x416); IkReal x419=(py*x417); evalcond[0]=(((py*x416))+(((-1.0)*px*x417))); evalcond[1]=((-0.19)+(((-0.273)*sj2*sj3))+(((-0.273)*cj2*cj3))+(((-0.139)*cj2))+(((-1.0)*x418))+(((-1.0)*x419))); evalcond[2]=((0.05775)+(((-1.0)*(px*px)))+(((-0.38)*x418))+(((-0.38)*x419))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py)))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x420=((0.139)*cj2); IkReal x421=((0.273)*sj2*sj3); IkReal x422=((0.273)*cj2*cj3); CheckValue<IkReal> x423=IKPowWithIntegerCheck(IKsign(((px*px)+(py*py))),-1); if(!x423.valid){ continue; } CheckValue<IkReal> x424 = IKatan2WithCheck(IkReal(((((-0.19)*py))+(((-1.0)*py*x421))+(((-1.0)*py*x420))+(((-1.0)*py*x422)))),((((-1.0)*px*x422))+(((-1.0)*px*x420))+(((-1.0)*px*x421))+(((-0.19)*px))),IKFAST_ATAN2_MAGTHRESH); if(!x424.valid){ continue; } j0array[0]=((-1.5707963267949)+(((1.5707963267949)*(x423.value)))+(x424.value)); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[3]; IkReal x425=IKcos(j0); IkReal x426=IKsin(j0); IkReal x427=(px*x425); IkReal x428=(py*x426); evalcond[0]=((((-1.0)*px*x426))+((py*x425))); evalcond[1]=((-0.19)+(((-0.273)*sj2*sj3))+(((-1.0)*x427))+(((-1.0)*x428))+(((-0.273)*cj2*cj3))+(((-0.139)*cj2))); evalcond[2]=((0.05775)+(((-1.0)*(px*px)))+(((-0.38)*x428))+(((-0.38)*x427))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py)))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x429=((0.075894)*cj3); IkReal x430=(sj1*sj2); IkReal x431=(cj2*cj3); IkReal x432=(cj1*pz); IkReal x433=((0.273)*sj3); IkReal x434=((1.0)*pz); IkReal x435=((0.273)*cj3); IkReal x436=((0.139)*cj2); IkReal x437=((0.139)*sj2); IkReal x438=(pz*x434); IkReal x439=(sj2*x433); evalcond[0]=((IKabs(px))+(IKabs(py))); evalcond[1]=0; evalcond[2]=((0.12995)+(((-1.0)*x438))+(((0.10374)*x431))+x429+(((0.05282)*cj2))+(((0.10374)*sj2*sj3))); evalcond[3]=((-0.19)+(((-0.273)*x431))+(((-1.0)*x436))+(((-1.0)*x439))+(((-1.0)*x432))); evalcond[4]=((((-1.0)*sj1*x434))+(((-1.0)*cj2*x433))+x437+((sj2*x435))); evalcond[5]=((0.05775)+(((-1.0)*x438))+(((-0.38)*x432))+x429); evalcond[6]=((((-1.0)*x434))+(((-0.273)*cj1*x431))+(((-0.19)*cj1))+(((-1.0)*cj1*x439))+(((-1.0)*cj1*x436))+((x430*x435))+(((0.139)*x430))+(((-1.0)*cj2*sj1*x433))); evalcond[7]=(((cj1*x437))+(((0.19)*sj1))+((x430*x433))+((cj1*sj2*x435))+(((0.273)*sj1*x431))+(((-1.0)*cj1*cj2*x433))+((sj1*x436))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0array[4], cj0array[4], sj0array[4]; bool j0valid[4]={false}; _nj0 = 4; j0array[0]=0; sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=1.5707963267949; sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); j0array[2]=3.14159265358979; sj0array[2]=IKsin(j0array[2]); cj0array[2]=IKcos(j0array[2]); j0array[3]=-1.5707963267949; sj0array[3]=IKsin(j0array[3]); cj0array[3]=IKcos(j0array[3]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; if( j0array[2] > IKPI ) { j0array[2]-=IK2PI; } else if( j0array[2] < -IKPI ) { j0array[2]+=IK2PI; } j0valid[2] = true; if( j0array[3] > IKPI ) { j0array[3]-=IK2PI; } else if( j0array[3] < -IKPI ) { j0array[3]+=IK2PI; } j0valid[3] = true; for(int ij0 = 0; ij0 < 4; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 4; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0] } } while(0); if( bgotonextstatement ) { } } } } } } } } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x440=px*px; IkReal x441=py*py; IkReal x442=pz*pz; IkReal x443=((50.0)*px); IkReal x444=((50.0)*py); IkReal x445=((19.0)*sj1); IkReal x446=((3.7947)*cj3); IkReal x447=((19.0)*cj1*pz); CheckValue<IkReal> x448=IKPowWithIntegerCheck(IKsign((((x440*x445))+((x441*x445)))),-1); if(!x448.valid){ continue; } CheckValue<IkReal> x449 = IKatan2WithCheck(IkReal(((((-2.8875)*py))+((x444*(py*py)))+((py*x447))+((x440*x444))+(((-1.0)*py*x446))+((x442*x444)))),((((-2.8875)*px))+((px*x447))+((x441*x443))+((x442*x443))+((x443*(px*px)))+(((-1.0)*px*x446))),IKFAST_ATAN2_MAGTHRESH); if(!x449.valid){ continue; } j0array[0]=((-1.5707963267949)+(((1.5707963267949)*(x448.value)))+(x449.value)); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[5]; IkReal x450=IKcos(j0); IkReal x451=IKsin(j0); IkReal x452=((1.0)*px); IkReal x453=(cj1*pz); IkReal x454=((0.273)*cj3); IkReal x455=((0.139)*cj2); IkReal x456=((0.139)*sj2); IkReal x457=((0.273)*sj2*sj3); IkReal x458=((0.273)*cj2*sj3); IkReal x459=(py*sj1*x451); IkReal x460=((1.0)*py*x451); IkReal x461=(px*sj1*x450); evalcond[0]=((((-1.0)*x451*x452))+((py*x450))); evalcond[1]=((-0.19)+(((-1.0)*x453))+(((-1.0)*x455))+(((-1.0)*x457))+x459+x461+(((-1.0)*cj2*x454))); evalcond[2]=(((sj2*x454))+(((-1.0)*cj1*x450*x452))+(((-1.0)*x458))+(((-1.0)*cj1*x460))+x456+(((-1.0)*pz*sj1))); evalcond[3]=((0.05775)+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*px*x452))+(((-1.0)*(py*py)))+(((0.38)*x461))+(((-0.38)*x453))+(((0.38)*x459))); evalcond[4]=(((cj1*x456))+(((0.19)*sj1))+(((-1.0)*x460))+(((-1.0)*cj1*x458))+((sj1*x455))+((sj1*x457))+(((-1.0)*x450*x452))+((cj1*sj2*x454))+((cj2*sj1*x454))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x462=((0.139)*cj2); IkReal x463=(cj1*pz); IkReal x464=((0.273)*sj2*sj3); IkReal x465=((0.273)*cj2*cj3); CheckValue<IkReal> x466=IKPowWithIntegerCheck(IKsign((((sj1*(py*py)))+((sj1*(px*px))))),-1); if(!x466.valid){ continue; } CheckValue<IkReal> x467 = IKatan2WithCheck(IkReal(((((0.19)*py))+((py*x465))+((py*x463))+((py*x462))+((py*x464)))),((((0.19)*px))+((px*x462))+((px*x463))+((px*x465))+((px*x464))),IKFAST_ATAN2_MAGTHRESH); if(!x467.valid){ continue; } j0array[0]=((-1.5707963267949)+(((1.5707963267949)*(x466.value)))+(x467.value)); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[5]; IkReal x468=IKcos(j0); IkReal x469=IKsin(j0); IkReal x470=((1.0)*px); IkReal x471=(cj1*pz); IkReal x472=((0.273)*cj3); IkReal x473=((0.139)*cj2); IkReal x474=((0.139)*sj2); IkReal x475=((0.273)*sj2*sj3); IkReal x476=((0.273)*cj2*sj3); IkReal x477=(py*sj1*x469); IkReal x478=((1.0)*py*x469); IkReal x479=(px*sj1*x468); evalcond[0]=((((-1.0)*x469*x470))+((py*x468))); evalcond[1]=((-0.19)+(((-1.0)*x475))+(((-1.0)*x473))+(((-1.0)*x471))+x477+x479+(((-1.0)*cj2*x472))); evalcond[2]=((((-1.0)*x476))+(((-1.0)*cj1*x468*x470))+(((-1.0)*cj1*x478))+x474+(((-1.0)*pz*sj1))+((sj2*x472))); evalcond[3]=((0.05775)+(((-1.0)*px*x470))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-0.38)*x471))+(((-1.0)*(py*py)))+(((0.38)*x479))+(((0.38)*x477))); evalcond[4]=(((cj1*sj2*x472))+(((-1.0)*x468*x470))+((cj2*sj1*x472))+(((0.19)*sj1))+(((-1.0)*x478))+((cj1*x474))+(((-1.0)*cj1*x476))+((sj1*x473))+((sj1*x475))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x480=(px*sj2); IkReal x481=((0.273)*cj3); IkReal x482=(py*sj2); IkReal x483=((1.0)*pz*sj1); IkReal x484=((0.273)*cj2*sj3); CheckValue<IkReal> x485=IKPowWithIntegerCheck(IKsign((((cj1*(px*px)))+((cj1*(py*py))))),-1); if(!x485.valid){ continue; } CheckValue<IkReal> x486 = IKatan2WithCheck(IkReal(((((0.139)*x482))+((x481*x482))+(((-1.0)*py*x483))+(((-1.0)*py*x484)))),((((0.139)*x480))+(((-1.0)*px*x484))+(((-1.0)*px*x483))+((x480*x481))),IKFAST_ATAN2_MAGTHRESH); if(!x486.valid){ continue; } j0array[0]=((-1.5707963267949)+(((1.5707963267949)*(x485.value)))+(x486.value)); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[5]; IkReal x487=IKcos(j0); IkReal x488=IKsin(j0); IkReal x489=((1.0)*px); IkReal x490=(cj1*pz); IkReal x491=((0.273)*cj3); IkReal x492=((0.139)*cj2); IkReal x493=((0.139)*sj2); IkReal x494=((0.273)*sj2*sj3); IkReal x495=((0.273)*cj2*sj3); IkReal x496=(py*sj1*x488); IkReal x497=((1.0)*py*x488); IkReal x498=(px*sj1*x487); evalcond[0]=(((py*x487))+(((-1.0)*x488*x489))); evalcond[1]=((-0.19)+(((-1.0)*x492))+(((-1.0)*x494))+(((-1.0)*cj2*x491))+(((-1.0)*x490))+x498+x496); evalcond[2]=((((-1.0)*x495))+(((-1.0)*cj1*x497))+x493+(((-1.0)*cj1*x487*x489))+(((-1.0)*pz*sj1))+((sj2*x491))); evalcond[3]=((0.05775)+(((-0.38)*x490))+(((0.38)*x496))+(((0.38)*x498))+(((-1.0)*px*x489))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py)))); evalcond[4]=((((-1.0)*x497))+(((-1.0)*cj1*x495))+(((0.19)*sj1))+((cj1*sj2*x491))+((sj1*x494))+((sj1*x492))+(((-1.0)*x487*x489))+((cj1*x493))+((cj2*sj1*x491))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } } else { { IkReal j0array[2], cj0array[2], sj0array[2]; bool j0valid[2]={false}; _nj0 = 2; CheckValue<IkReal> x500 = IKatan2WithCheck(IkReal(py),((-1.0)*px),IKFAST_ATAN2_MAGTHRESH); if(!x500.valid){ continue; } IkReal x499=x500.value; j0array[0]=((-1.0)*x499); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=((3.14159265358979)+(((-1.0)*x499))); sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; for(int ij0 = 0; ij0 < 2; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 2; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal j1eval[2]; IkReal x501=py*py; IkReal x502=cj0*cj0; IkReal x503=(((x501*x502))+(((-1.0)*x502*(px*px)))+(((-1.0)*(pz*pz)))+(((-2.0)*cj0*px*py*sj0))+(((-1.0)*x501))); j1eval[0]=x503; j1eval[1]=IKsign(x503); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 ) { { IkReal j1eval[2]; IkReal x504=(cj0*px); IkReal x505=((0.139)*sj2); IkReal x506=(cj2*pz); IkReal x507=(py*sj0); IkReal x508=((1.96402877697842)*sj2); IkReal x509=(pz*sj3); IkReal x510=((1.0)*sj2); IkReal x511=((0.273)*sj2); IkReal x512=((0.273)*cj2*sj3); IkReal x513=((1.96402877697842)*cj2*sj3); j1eval[0]=(((x507*x513))+(((-1.0)*cj3*x504*x508))+(((-1.0)*x508*x509))+(((-1.0)*x504*x510))+((x504*x513))+(((-1.0)*cj3*x507*x508))+(((-1.36690647482014)*pz))+(((-1.0)*x506))+(((-1.96402877697842)*cj3*x506))+(((-1.0)*x507*x510))); j1eval[1]=IKsign((((x507*x512))+(((-1.0)*x505*x507))+(((-0.273)*cj3*x506))+((x504*x512))+(((-0.139)*x506))+(((-0.19)*pz))+(((-1.0)*cj3*x504*x511))+(((-1.0)*cj3*x507*x511))+(((-1.0)*x504*x505))+(((-1.0)*x509*x511)))); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 ) { { IkReal j1eval[2]; IkReal x514=((0.273)*cj3); IkReal x515=(pz*sj2); IkReal x516=((1.96402877697842)*cj3); IkReal x517=(py*sj0); IkReal x518=((1.96402877697842)*sj3); IkReal x519=(cj2*pz); IkReal x520=(cj0*px); IkReal x521=((0.273)*sj3); IkReal x522=(cj2*x520); IkReal x523=(sj2*sj3*x517); j1eval[0]=((((-1.36690647482014)*x517))+(((-1.0)*cj2*x517))+(((-1.36690647482014)*x520))+(((-1.0)*cj2*x516*x517))+(((-1.0)*x522))+(((-1.0)*x518*x519))+(((-1.0)*sj2*x517*x518))+x515+(((-1.0)*x516*x522))+((x515*x516))+(((-1.0)*sj2*x518*x520))); j1eval[1]=IKsign(((((-0.19)*x517))+(((-0.139)*x522))+(((-0.139)*cj2*x517))+((x514*x515))+(((-1.0)*sj2*x517*x521))+(((-1.0)*cj2*x514*x517))+(((0.139)*x515))+(((-1.0)*sj2*x520*x521))+(((-0.19)*x520))+(((-1.0)*x519*x521))+(((-1.0)*x514*x522)))); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 ) { continue; // no branches [j1] } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x524=cj2*cj2; IkReal x525=cj3*cj3; IkReal x526=((0.273)*cj3); IkReal x527=(cj0*px); IkReal x528=(py*sj0); IkReal x529=(pz*sj2); IkReal x530=((0.139)*cj2); IkReal x531=((0.075894)*cj3); IkReal x532=(cj2*sj2); IkReal x533=(cj2*sj3); IkReal x534=(cj3*sj3); IkReal x535=((0.075894)*sj3); IkReal x536=((0.273)*sj2*sj3); IkReal x537=((0.149058)*x525); CheckValue<IkReal> x538=IKPowWithIntegerCheck(IKsign(((((-1.0)*x527*x530))+(((-1.0)*x527*x536))+(((-0.273)*pz*x533))+(((0.139)*x529))+((x526*x529))+(((-1.0)*x528*x530))+(((-1.0)*x528*x536))+(((-1.0)*cj2*x526*x527))+(((-1.0)*cj2*x526*x528))+(((-0.19)*x527))+(((-0.19)*x528)))),-1); if(!x538.valid){ continue; } CheckValue<IkReal> x539 = IKatan2WithCheck(IkReal(((-0.110629)+(((-1.0)*x532*x535))+(((-0.10374)*sj2*sj3))+(((-1.0)*x524*x531))+(((-1.0)*x524*x537))+(((0.074529)*x525))+(((0.055208)*x524))+(((-0.149058)*x532*x534))+(pz*pz)+(((-0.05282)*cj2))+(((-0.10374)*cj2*cj3)))),((((-1.0)*x532*x537))+((pz*x528))+((pz*x527))+(((-0.02641)*sj2))+(((-0.05187)*cj3*sj2))+(((-1.0)*x531*x532))+(((0.055208)*x532))+(((-0.074529)*x534))+(((0.05187)*x533))+((x524*x535))+(((0.149058)*x524*x534))+(((-0.037947)*sj3))),IKFAST_ATAN2_MAGTHRESH); if(!x539.valid){ continue; } j1array[0]=((-1.5707963267949)+(((1.5707963267949)*(x538.value)))+(x539.value)); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x540=IKsin(j1); IkReal x541=IKcos(j1); IkReal x542=((0.273)*sj3); IkReal x543=(cj0*px); IkReal x544=((0.273)*cj3); IkReal x545=(py*sj0); IkReal x546=((1.0)*pz); IkReal x547=((0.139)*sj2); IkReal x548=(sj2*x540); IkReal x549=((1.0)*x541); IkReal x550=(cj2*x541); IkReal x551=(cj2*x540); IkReal x552=((0.38)*x540); IkReal x553=(sj2*x541); evalcond[0]=((-0.19)+(((-1.0)*x541*x546))+(((-1.0)*sj2*x542))+(((-1.0)*cj2*x544))+((x540*x543))+((x540*x545))+(((-0.139)*cj2))); evalcond[1]=((((-1.0)*x545*x549))+(((-1.0)*cj2*x542))+((sj2*x544))+(((-1.0)*x540*x546))+x547+(((-1.0)*x543*x549))); evalcond[2]=((0.05775)+(((-1.0)*(px*px)))+(((-0.38)*pz*x541))+(((-1.0)*pz*x546))+(((0.075894)*cj3))+((x543*x552))+(((-1.0)*(py*py)))+((x545*x552))); evalcond[3]=((((-0.139)*x550))+((x544*x548))+(((-1.0)*x544*x550))+((x540*x547))+(((-1.0)*x546))+(((-0.19)*x541))+(((-1.0)*x542*x553))+(((-1.0)*x542*x551))); evalcond[4]=((((0.19)*x540))+((x541*x547))+(((-1.0)*x543))+(((-1.0)*x545))+((x542*x548))+((x544*x553))+((x544*x551))+(((0.139)*x551))+(((-1.0)*x542*x550))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x554=cj2*cj2; IkReal x555=cj3*cj3; IkReal x556=(cj3*sj3); IkReal x557=(cj2*sj2); IkReal x558=((0.075894)*cj3); IkReal x559=(cj2*pz); IkReal x560=(cj2*sj3); IkReal x561=((0.273)*sj2); IkReal x562=(cj0*px); IkReal x563=((1.0)*pz); IkReal x564=(py*sj0); IkReal x565=((0.139)*sj2); IkReal x566=((0.075894)*x554); IkReal x567=((0.149058)*x555); CheckValue<IkReal> x568=IKPowWithIntegerCheck(IKsign(((((-1.0)*x564*x565))+(((-1.0)*cj3*x561*x564))+(((-1.0)*cj3*x561*x562))+(((-0.139)*x559))+(((0.273)*x560*x564))+(((0.273)*x560*x562))+(((-1.0)*pz*sj3*x561))+(((-0.19)*pz))+(((-1.0)*x562*x565))+(((-0.273)*cj3*x559)))),-1); if(!x568.valid){ continue; } CheckValue<IkReal> x569 = IKatan2WithCheck(IkReal((((sj3*x566))+(((-0.02641)*sj2))+(((-0.05187)*cj3*sj2))+(((0.05187)*x560))+(((0.055208)*x557))+(((-1.0)*x562*x563))+(((0.149058)*x554*x556))+(((-1.0)*x557*x567))+(((-0.074529)*x556))+(((-1.0)*x563*x564))+(((-1.0)*x557*x558))+(((-0.037947)*sj3)))),((-0.019321)+(((0.149058)*x556*x557))+((x554*x558))+(((0.075894)*sj3*x557))+(pz*pz)+(((-1.0)*x558))+(((-0.074529)*x555))+(((-0.055208)*x554))+((x554*x567))),IKFAST_ATAN2_MAGTHRESH); if(!x569.valid){ continue; } j1array[0]=((-1.5707963267949)+(((1.5707963267949)*(x568.value)))+(x569.value)); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x570=IKsin(j1); IkReal x571=IKcos(j1); IkReal x572=((0.273)*sj3); IkReal x573=(cj0*px); IkReal x574=((0.273)*cj3); IkReal x575=(py*sj0); IkReal x576=((1.0)*pz); IkReal x577=((0.139)*sj2); IkReal x578=(sj2*x570); IkReal x579=((1.0)*x571); IkReal x580=(cj2*x571); IkReal x581=(cj2*x570); IkReal x582=((0.38)*x570); IkReal x583=(sj2*x571); evalcond[0]=((-0.19)+(((-1.0)*cj2*x574))+(((-1.0)*sj2*x572))+(((-1.0)*x571*x576))+(((-0.139)*cj2))+((x570*x573))+((x570*x575))); evalcond[1]=((((-1.0)*cj2*x572))+(((-1.0)*x573*x579))+(((-1.0)*x570*x576))+(((-1.0)*x575*x579))+((sj2*x574))+x577); evalcond[2]=((0.05775)+(((-1.0)*(px*px)))+(((-0.38)*pz*x571))+((x575*x582))+((x573*x582))+(((-1.0)*pz*x576))+(((0.075894)*cj3))+(((-1.0)*(py*py)))); evalcond[3]=((((-0.139)*x580))+(((-1.0)*x572*x581))+(((-1.0)*x572*x583))+((x574*x578))+(((-1.0)*x576))+(((-1.0)*x574*x580))+((x570*x577))+(((-0.19)*x571))); evalcond[4]=(((x571*x577))+(((-1.0)*x572*x580))+(((0.139)*x581))+((x574*x581))+((x574*x583))+(((-1.0)*x573))+(((-1.0)*x575))+(((0.19)*x570))+((x572*x578))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x584=py*py; IkReal x585=cj0*cj0; IkReal x586=((0.273)*cj3); IkReal x587=(py*sj0); IkReal x588=((0.273)*sj3); IkReal x589=(pz*sj2); IkReal x590=((0.139)*cj2); IkReal x591=(cj0*px); IkReal x592=(cj2*pz); IkReal x593=((0.139)*sj2); IkReal x594=(cj2*x591); CheckValue<IkReal> x595=IKPowWithIntegerCheck(IKsign((((x584*x585))+(((-1.0)*x584))+(((-1.0)*(pz*pz)))+(((-2.0)*x587*x591))+(((-1.0)*x585*(px*px))))),-1); if(!x595.valid){ continue; } CheckValue<IkReal> x596 = IKatan2WithCheck(IkReal(((((-0.139)*x589))+(((-1.0)*x587*x590))+(((-1.0)*x586*x594))+(((-1.0)*x586*x589))+(((-1.0)*x590*x591))+(((-1.0)*sj2*x588*x591))+(((-0.19)*x591))+((x588*x592))+(((-1.0)*cj2*x586*x587))+(((-1.0)*sj2*x587*x588))+(((-0.19)*x587)))),(((cj2*x587*x588))+(((0.19)*pz))+(((-1.0)*x587*x593))+((pz*x590))+((x588*x589))+(((-1.0)*sj2*x586*x591))+(((-1.0)*sj2*x586*x587))+((x588*x594))+(((-1.0)*x591*x593))+((x586*x592))),IKFAST_ATAN2_MAGTHRESH); if(!x596.valid){ continue; } j1array[0]=((-1.5707963267949)+(((1.5707963267949)*(x595.value)))+(x596.value)); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x597=IKsin(j1); IkReal x598=IKcos(j1); IkReal x599=((0.273)*sj3); IkReal x600=(cj0*px); IkReal x601=((0.273)*cj3); IkReal x602=(py*sj0); IkReal x603=((1.0)*pz); IkReal x604=((0.139)*sj2); IkReal x605=(sj2*x597); IkReal x606=((1.0)*x598); IkReal x607=(cj2*x598); IkReal x608=(cj2*x597); IkReal x609=((0.38)*x597); IkReal x610=(sj2*x598); evalcond[0]=((-0.19)+(((-1.0)*cj2*x601))+((x597*x602))+((x597*x600))+(((-1.0)*sj2*x599))+(((-1.0)*x598*x603))+(((-0.139)*cj2))); evalcond[1]=((((-1.0)*x602*x606))+(((-1.0)*x597*x603))+(((-1.0)*cj2*x599))+(((-1.0)*x600*x606))+x604+((sj2*x601))); evalcond[2]=((0.05775)+(((-1.0)*(px*px)))+(((-0.38)*pz*x598))+((x600*x609))+(((0.075894)*cj3))+((x602*x609))+(((-1.0)*pz*x603))+(((-1.0)*(py*py)))); evalcond[3]=(((x601*x605))+(((-0.139)*x607))+(((-1.0)*x599*x610))+((x597*x604))+(((-1.0)*x599*x608))+(((-0.19)*x598))+(((-1.0)*x603))+(((-1.0)*x601*x607))); evalcond[4]=(((x601*x608))+((x601*x610))+(((-1.0)*x600))+(((-1.0)*x602))+(((0.139)*x608))+(((-1.0)*x599*x607))+(((0.19)*x597))+((x599*x605))+((x598*x604))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } } } } } } else { { IkReal j0array[2], cj0array[2], sj0array[2]; bool j0valid[2]={false}; _nj0 = 2; CheckValue<IkReal> x612 = IKatan2WithCheck(IkReal(py),((-1.0)*px),IKFAST_ATAN2_MAGTHRESH); if(!x612.valid){ continue; } IkReal x611=x612.value; j0array[0]=((-1.0)*x611); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=((3.14159265358979)+(((-1.0)*x611))); sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; for(int ij0 = 0; ij0 < 2; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 2; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal j2eval[2]; j2eval[0]=((IKabs(sj3))+(((9.63948332369385)*(IKabs(((0.05282)+(((0.10374)*cj3)))))))); j2eval[1]=((1.0)+(((3.92805755395683)*cj3))+(((3.85740903679934)*(sj3*sj3)))+(((3.85740903679934)*(cj3*cj3)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 ) { { IkReal j1eval[2]; IkReal x613=(py*sj0); IkReal x614=(cj0*px); j1eval[0]=((x614*x614)+(x613*x613)+(((2.0)*x613*x614))+(pz*pz)); j1eval[1]=((((2.63157894736842)*(IKabs(((((0.38)*x614))+(((0.38)*x613)))))))+(IKabs(pz))); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 ) { continue; // no branches [j1, j2] } else { { IkReal j1array[2], cj1array[2], sj1array[2]; bool j1valid[2]={false}; _nj1 = 2; IkReal x615=pz*pz; IkReal x616=((((0.38)*cj0*px))+(((0.38)*py*sj0))); CheckValue<IkReal> x619 = IKatan2WithCheck(IkReal(((-0.38)*pz)),x616,IKFAST_ATAN2_MAGTHRESH); if(!x619.valid){ continue; } IkReal x617=((1.0)*(x619.value)); if((((x616*x616)+(((0.1444)*x615)))) < -0.00001) continue; CheckValue<IkReal> x620=IKPowWithIntegerCheck(IKabs(IKsqrt(((x616*x616)+(((0.1444)*x615))))),-1); if(!x620.valid){ continue; } if( (((x620.value)*(((0.05775)+(((-1.0)*(px*px)))+(((-1.0)*x615))+(((0.075894)*cj3))+(((-1.0)*(py*py))))))) < -1-IKFAST_SINCOS_THRESH || (((x620.value)*(((0.05775)+(((-1.0)*(px*px)))+(((-1.0)*x615))+(((0.075894)*cj3))+(((-1.0)*(py*py))))))) > 1+IKFAST_SINCOS_THRESH ) continue; IkReal x618=IKasin(((x620.value)*(((0.05775)+(((-1.0)*(px*px)))+(((-1.0)*x615))+(((0.075894)*cj3))+(((-1.0)*(py*py))))))); j1array[0]=((((-1.0)*x618))+(((-1.0)*x617))); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); j1array[1]=((3.14159265358979)+(((-1.0)*x617))+x618); sj1array[1]=IKsin(j1array[1]); cj1array[1]=IKcos(j1array[1]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; if( j1array[1] > IKPI ) { j1array[1]-=IK2PI; } else if( j1array[1] < -IKPI ) { j1array[1]+=IK2PI; } j1valid[1] = true; for(int ij1 = 0; ij1 < 2; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 2; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal j2eval[2]; j2eval[0]=((-1.23659314306796)+(((-1.0)*cj3))); j2eval[1]=IKsign(((-93850.0)+(((-75894.0)*cj3)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 ) { { IkReal j2eval[2]; IkReal x621=(cj1*cj3); j2eval[0]=(x621+(((1.23659314306796)*cj1))); j2eval[1]=IKsign(((((75.894)*x621))+(((93.85)*cj1)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 ) { { IkReal j2eval[2]; IkReal x622=(cj3*sj1); j2eval[0]=((((-1.23659314306796)*sj1))+(((-1.0)*x622))); j2eval[1]=IKsign(((((-93.85)*sj1))+(((-75.894)*x622)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 ) { { IkReal evalcond[3]; bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j1))), 6.28318530717959))); evalcond[1]=((((-1.0)*px*sj0))+((cj0*py))); evalcond[2]=((0.05775)+(((-0.38)*pz))+(((-1.0)*(px*px)))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py)))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j2eval[3]; sj1=0; cj1=1.0; j1=0; IkReal x623=(cj0*px); IkReal x624=((273000.0)*sj3); IkReal x625=(py*sj0); IkReal x626=((273000.0)*cj3); j2eval[0]=((-1.23659314306796)+(((-1.0)*cj3))); j2eval[1]=((IKabs((((pz*x624))+(((-1.0)*x623*x626))+(((51870.0)*sj3))+(((-1.0)*x625*x626))+(((-139000.0)*x623))+(((-139000.0)*x625)))))+(IKabs(((26410.0)+((pz*x626))+(((51870.0)*cj3))+((x624*x625))+(((139000.0)*pz))+((x623*x624)))))); j2eval[2]=IKsign(((-93850.0)+(((-75894.0)*cj3)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 || IKabs(j2eval[2]) < 0.0000010000000000 ) { { IkReal j2eval[2]; sj1=0; cj1=1.0; j1=0; j2eval[0]=((-1.23659314306796)+(((-1.0)*cj3))); j2eval[1]=IKsign(((-1783150.0)+(((-1441986.0)*cj3)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 ) { continue; // no branches [j2] } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x627=px*px; IkReal x628=py*py; IkReal x629=pz*pz; IkReal x630=((13650000.0)*sj3); IkReal x631=((13650000.0)*cj3); IkReal x632=(py*sj0); IkReal x633=((5187000.0)*cj0*px); CheckValue<IkReal> x634 = IKatan2WithCheck(IkReal(((((1035953.1)*cj3*sj3))+(((-1.0)*x629*x630))+(((-5187000.0)*cj3*x632))+(((-1.0)*x628*x630))+(((-2641000.0)*x632))+(((-1.0)*x627*x630))+(((1773817.5)*sj3))+(((-2641000.0)*cj0*px))+(((-1.0)*cj3*x633)))),((903152.5)+(((-1.0)*x629*x631))+(((5187000.0)*sj3*x632))+(((-1.0)*x628*x631))+((sj3*x633))+(((-6950000.0)*x627))+(((-6950000.0)*x629))+(((-6950000.0)*x628))+(((2301280.8)*cj3))+(((-1.0)*x627*x631))+(((1035953.1)*(cj3*cj3)))),IKFAST_ATAN2_MAGTHRESH); if(!x634.valid){ continue; } CheckValue<IkReal> x635=IKPowWithIntegerCheck(IKsign(((-1783150.0)+(((-1441986.0)*cj3)))),-1); if(!x635.valid){ continue; } j2array[0]=((-1.5707963267949)+(x634.value)+(((1.5707963267949)*(x635.value)))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[3]; IkReal x636=IKcos(j2); IkReal x637=IKsin(j2); IkReal x638=((0.273)*cj3); IkReal x639=(sj3*x637); evalcond[0]=((-0.19)+(((-0.273)*x639))+(((-1.0)*pz))+(((-1.0)*x636*x638))+(((-0.139)*x636))); evalcond[1]=((((0.139)*x637))+(((-0.273)*sj3*x636))+(((-1.0)*py*sj0))+(((-1.0)*cj0*px))+((x637*x638))); evalcond[2]=((0.12995)+(((0.10374)*x639))+(((-1.0)*(px*px)))+(((0.10374)*cj3*x636))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((0.05282)*x636))+(((-1.0)*(py*py)))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x640=(cj0*px); IkReal x641=((273000.0)*sj3); IkReal x642=(py*sj0); IkReal x643=((273000.0)*cj3); CheckValue<IkReal> x644 = IKatan2WithCheck(IkReal(((((-1.0)*x642*x643))+(((-1.0)*x640*x643))+(((51870.0)*sj3))+((pz*x641))+(((-139000.0)*x640))+(((-139000.0)*x642)))),((26410.0)+((x640*x641))+((pz*x643))+((x641*x642))+(((51870.0)*cj3))+(((139000.0)*pz))),IKFAST_ATAN2_MAGTHRESH); if(!x644.valid){ continue; } CheckValue<IkReal> x645=IKPowWithIntegerCheck(IKsign(((-93850.0)+(((-75894.0)*cj3)))),-1); if(!x645.valid){ continue; } j2array[0]=((-1.5707963267949)+(x644.value)+(((1.5707963267949)*(x645.value)))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[3]; IkReal x646=IKcos(j2); IkReal x647=IKsin(j2); IkReal x648=((0.273)*cj3); IkReal x649=(sj3*x647); evalcond[0]=((-0.19)+(((-1.0)*x646*x648))+(((-1.0)*pz))+(((-0.139)*x646))+(((-0.273)*x649))); evalcond[1]=((((0.139)*x647))+(((-1.0)*py*sj0))+(((-0.273)*sj3*x646))+(((-1.0)*cj0*px))+((x647*x648))); evalcond[2]=((0.12995)+(((-1.0)*(px*px)))+(((0.05282)*x646))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((0.10374)*x649))+(((-1.0)*(py*py)))+(((0.10374)*cj3*x646))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j1)))), 6.28318530717959))); evalcond[1]=((((-1.0)*px*sj0))+((cj0*py))); evalcond[2]=((0.05775)+(((-1.0)*(px*px)))+(((0.38)*pz))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py)))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j2eval[3]; sj1=0; cj1=-1.0; j1=3.14159265358979; IkReal x650=(cj0*px); IkReal x651=((273000.0)*sj3); IkReal x652=(py*sj0); IkReal x653=((273000.0)*cj3); j2eval[0]=((-1.23659314306796)+(((-1.0)*cj3))); j2eval[1]=((IKabs(((((139000.0)*x652))+(((139000.0)*x650))+((x652*x653))+(((51870.0)*sj3))+(((-1.0)*pz*x651))+((x650*x653)))))+(IKabs(((26410.0)+(((-1.0)*x651*x652))+(((-139000.0)*pz))+(((51870.0)*cj3))+(((-1.0)*pz*x653))+(((-1.0)*x650*x651)))))); j2eval[2]=IKsign(((-93850.0)+(((-75894.0)*cj3)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 || IKabs(j2eval[2]) < 0.0000010000000000 ) { { IkReal j2eval[2]; sj1=0; cj1=-1.0; j1=3.14159265358979; j2eval[0]=((-1.23659314306796)+(((-1.0)*cj3))); j2eval[1]=IKsign(((-1783150.0)+(((-1441986.0)*cj3)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 ) { continue; // no branches [j2] } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x654=px*px; IkReal x655=py*py; IkReal x656=pz*pz; IkReal x657=((13650000.0)*sj3); IkReal x658=(py*sj0); IkReal x659=((5187000.0)*cj3); IkReal x660=((13650000.0)*cj3); IkReal x661=(cj0*px); IkReal x662=((5187000.0)*sj3); IkReal x663=((13650000.0)*x656); CheckValue<IkReal> x664 = IKatan2WithCheck(IkReal(((((1035953.1)*cj3*sj3))+(((2641000.0)*x661))+(((-1.0)*x655*x657))+(((-1.0)*x656*x657))+(((2641000.0)*x658))+((x659*x661))+(((1773817.5)*sj3))+((x658*x659))+(((-1.0)*x654*x657)))),((903152.5)+(((-1.0)*x654*x660))+(((-6950000.0)*x654))+(((-6950000.0)*x656))+(((-6950000.0)*x655))+(((-1.0)*x661*x662))+(((-1.0)*x658*x662))+(((2301280.8)*cj3))+(((-1.0)*x656*x660))+(((-1.0)*x655*x660))+(((1035953.1)*(cj3*cj3)))),IKFAST_ATAN2_MAGTHRESH); if(!x664.valid){ continue; } CheckValue<IkReal> x665=IKPowWithIntegerCheck(IKsign(((-1783150.0)+(((-1441986.0)*cj3)))),-1); if(!x665.valid){ continue; } j2array[0]=((-1.5707963267949)+(x664.value)+(((1.5707963267949)*(x665.value)))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[3]; IkReal x666=IKcos(j2); IkReal x667=IKsin(j2); IkReal x668=((0.273)*cj3); IkReal x669=(sj3*x667); evalcond[0]=((-0.19)+(((-0.139)*x666))+pz+(((-1.0)*x666*x668))+(((-0.273)*x669))); evalcond[1]=(((x667*x668))+(((0.139)*x667))+(((-0.273)*sj3*x666))+((cj0*px))+((py*sj0))); evalcond[2]=((0.12995)+(((-1.0)*(px*px)))+(((0.10374)*x669))+(((0.05282)*x666))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((0.10374)*cj3*x666))+(((-1.0)*(py*py)))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x670=(cj0*px); IkReal x671=((273000.0)*sj3); IkReal x672=(py*sj0); IkReal x673=((273000.0)*cj3); CheckValue<IkReal> x674=IKPowWithIntegerCheck(IKsign(((-93850.0)+(((-75894.0)*cj3)))),-1); if(!x674.valid){ continue; } CheckValue<IkReal> x675 = IKatan2WithCheck(IkReal((((x672*x673))+((x670*x673))+(((51870.0)*sj3))+(((-1.0)*pz*x671))+(((139000.0)*x672))+(((139000.0)*x670)))),((26410.0)+(((-139000.0)*pz))+(((-1.0)*pz*x673))+(((-1.0)*x670*x671))+(((51870.0)*cj3))+(((-1.0)*x671*x672))),IKFAST_ATAN2_MAGTHRESH); if(!x675.valid){ continue; } j2array[0]=((-1.5707963267949)+(((1.5707963267949)*(x674.value)))+(x675.value)); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[3]; IkReal x676=IKcos(j2); IkReal x677=IKsin(j2); IkReal x678=((0.273)*cj3); IkReal x679=(sj3*x677); evalcond[0]=((-0.19)+(((-0.139)*x676))+(((-0.273)*x679))+pz+(((-1.0)*x676*x678))); evalcond[1]=((((-0.273)*sj3*x676))+((x677*x678))+(((0.139)*x677))+((cj0*px))+((py*sj0))); evalcond[2]=((0.12995)+(((-1.0)*(px*px)))+(((0.10374)*x679))+(((0.05282)*x676))+(((0.10374)*cj3*x676))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py)))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j1)))), 6.28318530717959))); evalcond[1]=((((-1.0)*px*sj0))+((cj0*py))); evalcond[2]=((0.05775)+(((-1.0)*(px*px)))+(((0.38)*cj0*px))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py)))+(((0.38)*py*sj0))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j2eval[3]; sj1=1.0; cj1=0; j1=1.5707963267949; IkReal x680=(cj0*px); IkReal x681=((273000.0)*sj3); IkReal x682=(py*sj0); IkReal x683=((273000.0)*cj3); j2eval[0]=((-1.23659314306796)+(((-1.0)*cj3))); j2eval[1]=((IKabs(((26410.0)+(((-1.0)*x680*x683))+(((51870.0)*cj3))+(((-1.0)*x682*x683))+((pz*x681))+(((-139000.0)*x680))+(((-139000.0)*x682)))))+(IKabs(((((-1.0)*x681*x682))+(((-1.0)*x680*x681))+(((51870.0)*sj3))+(((-139000.0)*pz))+(((-1.0)*pz*x683)))))); j2eval[2]=IKsign(((-93850.0)+(((-75894.0)*cj3)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 || IKabs(j2eval[2]) < 0.0000010000000000 ) { { IkReal j2eval[2]; sj1=1.0; cj1=0; j1=1.5707963267949; j2eval[0]=((1.23659314306796)+cj3); j2eval[1]=IKsign(((1783150.0)+(((1441986.0)*cj3)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 ) { continue; // no branches [j2] } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x684=px*px; IkReal x685=py*py; IkReal x686=pz*pz; IkReal x687=((13650000.0)*sj3); IkReal x688=((13650000.0)*cj3); IkReal x689=((5187000.0)*pz); CheckValue<IkReal> x690 = IKatan2WithCheck(IkReal(((((2641000.0)*pz))+((x686*x687))+(((-1773817.5)*sj3))+((x685*x687))+(((-1035953.1)*cj3*sj3))+((x684*x687))+((cj3*x689)))),((-903152.5)+((x686*x688))+((x685*x688))+(((-2301280.8)*cj3))+(((6950000.0)*x684))+(((6950000.0)*x685))+(((6950000.0)*x686))+(((-1.0)*sj3*x689))+((x684*x688))+(((-1035953.1)*(cj3*cj3)))),IKFAST_ATAN2_MAGTHRESH); if(!x690.valid){ continue; } CheckValue<IkReal> x691=IKPowWithIntegerCheck(IKsign(((1783150.0)+(((1441986.0)*cj3)))),-1); if(!x691.valid){ continue; } j2array[0]=((-1.5707963267949)+(x690.value)+(((1.5707963267949)*(x691.value)))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[3]; IkReal x692=IKsin(j2); IkReal x693=IKcos(j2); IkReal x694=((0.273)*cj3); IkReal x695=(sj3*x692); evalcond[0]=((((0.139)*x692))+((x692*x694))+(((-1.0)*pz))+(((-0.273)*sj3*x693))); evalcond[1]=((-0.19)+(((-1.0)*x693*x694))+(((-0.139)*x693))+(((-0.273)*x695))+((cj0*px))+((py*sj0))); evalcond[2]=((0.12995)+(((-1.0)*(px*px)))+(((0.10374)*cj3*x693))+(((0.05282)*x693))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((0.10374)*x695))+(((-1.0)*(py*py)))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x696=(cj0*px); IkReal x697=((273000.0)*sj3); IkReal x698=(py*sj0); IkReal x699=((273000.0)*cj3); CheckValue<IkReal> x700 = IKatan2WithCheck(IkReal(((((-1.0)*x696*x697))+(((-1.0)*x697*x698))+(((51870.0)*sj3))+(((-139000.0)*pz))+(((-1.0)*pz*x699)))),((26410.0)+(((-139000.0)*x698))+(((-139000.0)*x696))+(((-1.0)*x696*x699))+((pz*x697))+(((51870.0)*cj3))+(((-1.0)*x698*x699))),IKFAST_ATAN2_MAGTHRESH); if(!x700.valid){ continue; } CheckValue<IkReal> x701=IKPowWithIntegerCheck(IKsign(((-93850.0)+(((-75894.0)*cj3)))),-1); if(!x701.valid){ continue; } j2array[0]=((-1.5707963267949)+(x700.value)+(((1.5707963267949)*(x701.value)))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[3]; IkReal x702=IKsin(j2); IkReal x703=IKcos(j2); IkReal x704=((0.273)*cj3); IkReal x705=(sj3*x702); evalcond[0]=(((x702*x704))+(((-1.0)*pz))+(((0.139)*x702))+(((-0.273)*sj3*x703))); evalcond[1]=((-0.19)+(((-0.139)*x703))+(((-1.0)*x703*x704))+(((-0.273)*x705))+((cj0*px))+((py*sj0))); evalcond[2]=((0.12995)+(((0.10374)*cj3*x703))+(((-1.0)*(px*px)))+(((0.05282)*x703))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py)))+(((0.10374)*x705))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j1)))), 6.28318530717959))); evalcond[1]=((((-1.0)*px*sj0))+((cj0*py))); evalcond[2]=((0.05775)+(((-1.0)*(px*px)))+(((-0.38)*py*sj0))+(((-0.38)*cj0*px))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py)))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j2eval[3]; sj1=-1.0; cj1=0; j1=-1.5707963267949; IkReal x706=(cj0*px); IkReal x707=((273000.0)*sj3); IkReal x708=(py*sj0); IkReal x709=((273000.0)*cj3); j2eval[0]=((1.23659314306796)+cj3); j2eval[1]=IKsign(((93850.0)+(((75894.0)*cj3)))); j2eval[2]=((IKabs(((((-1.0)*pz*x709))+(((-1.0)*x706*x707))+(((-1.0)*x707*x708))+(((-139000.0)*pz))+(((-51870.0)*sj3)))))+(IKabs(((-26410.0)+(((-1.0)*x706*x709))+(((-139000.0)*x706))+(((-139000.0)*x708))+(((-1.0)*x708*x709))+((pz*x707))+(((-51870.0)*cj3)))))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 || IKabs(j2eval[2]) < 0.0000010000000000 ) { { IkReal j2eval[2]; sj1=-1.0; cj1=0; j1=-1.5707963267949; j2eval[0]=((-1.23659314306796)+(((-1.0)*cj3))); j2eval[1]=IKsign(((-1783150.0)+(((-1441986.0)*cj3)))); if( IKabs(j2eval[0]) < 0.0000010000000000 || IKabs(j2eval[1]) < 0.0000010000000000 ) { continue; // no branches [j2] } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x710=px*px; IkReal x711=py*py; IkReal x712=pz*pz; IkReal x713=((13650000.0)*sj3); IkReal x714=((13650000.0)*cj3); IkReal x715=((5187000.0)*pz); CheckValue<IkReal> x716 = IKatan2WithCheck(IkReal(((((1035953.1)*cj3*sj3))+(((2641000.0)*pz))+(((-1.0)*x711*x713))+(((-1.0)*x710*x713))+(((1773817.5)*sj3))+(((-1.0)*x712*x713))+((cj3*x715)))),((903152.5)+(((-1.0)*x711*x714))+(((-1.0)*x710*x714))+(((2301280.8)*cj3))+(((-1.0)*x712*x714))+(((1035953.1)*(cj3*cj3)))+(((-6950000.0)*x711))+(((-6950000.0)*x710))+(((-6950000.0)*x712))+(((-1.0)*sj3*x715))),IKFAST_ATAN2_MAGTHRESH); if(!x716.valid){ continue; } CheckValue<IkReal> x717=IKPowWithIntegerCheck(IKsign(((-1783150.0)+(((-1441986.0)*cj3)))),-1); if(!x717.valid){ continue; } j2array[0]=((-1.5707963267949)+(x716.value)+(((1.5707963267949)*(x717.value)))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[3]; IkReal x718=IKsin(j2); IkReal x719=IKcos(j2); IkReal x720=((0.273)*cj3); IkReal x721=(sj3*x718); evalcond[0]=((((0.139)*x718))+pz+((x718*x720))+(((-0.273)*sj3*x719))); evalcond[1]=((-0.19)+(((-0.139)*x719))+(((-1.0)*py*sj0))+(((-1.0)*x719*x720))+(((-1.0)*cj0*px))+(((-0.273)*x721))); evalcond[2]=((0.12995)+(((0.05282)*x719))+(((-1.0)*(px*px)))+(((0.10374)*cj3*x719))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py)))+(((0.10374)*x721))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x722=(cj0*px); IkReal x723=((273000.0)*sj3); IkReal x724=(py*sj0); IkReal x725=((273000.0)*cj3); CheckValue<IkReal> x726=IKPowWithIntegerCheck(IKsign(((93850.0)+(((75894.0)*cj3)))),-1); if(!x726.valid){ continue; } CheckValue<IkReal> x727 = IKatan2WithCheck(IkReal(((((-1.0)*x723*x724))+(((-1.0)*x722*x723))+(((-139000.0)*pz))+(((-51870.0)*sj3))+(((-1.0)*pz*x725)))),((-26410.0)+(((-1.0)*x724*x725))+(((-1.0)*x722*x725))+(((-139000.0)*x724))+(((-139000.0)*x722))+((pz*x723))+(((-51870.0)*cj3))),IKFAST_ATAN2_MAGTHRESH); if(!x727.valid){ continue; } j2array[0]=((-1.5707963267949)+(((1.5707963267949)*(x726.value)))+(x727.value)); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[3]; IkReal x728=IKsin(j2); IkReal x729=IKcos(j2); IkReal x730=((0.273)*cj3); IkReal x731=(sj3*x728); evalcond[0]=(((x728*x730))+(((0.139)*x728))+pz+(((-0.273)*sj3*x729))); evalcond[1]=((-0.19)+(((-0.139)*x729))+(((-1.0)*py*sj0))+(((-0.273)*x731))+(((-1.0)*cj0*px))+(((-1.0)*x729*x730))); evalcond[2]=((0.12995)+(((-1.0)*(px*px)))+(((0.10374)*cj3*x729))+(((0.05282)*x729))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((0.10374)*x731))+(((-1.0)*(py*py)))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j2] } } while(0); if( bgotonextstatement ) { } } } } } } } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x732=cj1*cj1; IkReal x733=(cj0*px); IkReal x734=((139.0)*pz); IkReal x735=(cj3*sj1); IkReal x736=((273.0)*sj3); IkReal x737=((273.0)*cj3); IkReal x738=((273.0)*cj1); IkReal x739=(cj1*sj1); IkReal x740=((273.0)*py*sj0); IkReal x741=((139.0)*py*sj0); IkReal x742=(pz*x732); CheckValue<IkReal> x743 = IKatan2WithCheck(IkReal(((((-139.0)*x733*x739))+(((51.87)*sj1*sj3))+(((-1.0)*py*sj0*x736))+(((-1.0)*x733*x735*x738))+((x732*x733*x736))+(((-1.0)*x733*x736))+((pz*x736*x739))+(((-1.0)*x734))+(((-1.0)*py*sj0*x735*x738))+((x737*x742))+(((-1.0)*x739*x741))+(((-1.0)*pz*x737))+((py*sj0*x732*x736))+((x732*x734)))),((((-139.0)*x733))+((py*sj0*x736*x739))+(((-1.0)*py*sj0*x737))+((x733*x736*x739))+((x734*x739))+((x732*x733*x737))+(((-1.0)*x733*x737))+((pz*x735*x738))+(((26.41)*sj1))+((x732*x741))+((pz*x736))+(((139.0)*x732*x733))+(((-1.0)*x741))+((py*sj0*x732*x737))+(((51.87)*x735))+(((-1.0)*x736*x742))),IKFAST_ATAN2_MAGTHRESH); if(!x743.valid){ continue; } CheckValue<IkReal> x744=IKPowWithIntegerCheck(IKsign(((((-93.85)*sj1))+(((-75.894)*x735)))),-1); if(!x744.valid){ continue; } j2array[0]=((-1.5707963267949)+(x743.value)+(((1.5707963267949)*(x744.value)))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[5]; IkReal x745=IKcos(j2); IkReal x746=IKsin(j2); IkReal x747=(cj0*px); IkReal x748=(py*sj0); IkReal x749=((1.0)*pz); IkReal x750=((0.273)*cj1); IkReal x751=((1.0)*cj1); IkReal x752=((0.273)*sj1); IkReal x753=(cj3*x745); IkReal x754=((0.139)*x746); IkReal x755=((0.139)*x745); IkReal x756=(sj3*x746); IkReal x757=((0.273)*cj3*x746); IkReal x758=((0.273)*sj3*x745); evalcond[0]=((-0.19)+((sj1*x748))+((sj1*x747))+(((-0.273)*x756))+(((-0.273)*x753))+(((-1.0)*cj1*x749))+(((-1.0)*x755))); evalcond[1]=((((-1.0)*sj1*x749))+(((-1.0)*x747*x751))+x754+x757+(((-1.0)*x748*x751))+(((-1.0)*x758))); evalcond[2]=((0.12995)+(((0.05282)*x745))+(((-1.0)*(px*px)))+(((-1.0)*pz*x749))+(((0.075894)*cj3))+(((0.10374)*x753))+(((0.10374)*x756))+(((-1.0)*(py*py)))); evalcond[3]=((((-1.0)*x750*x753))+(((-1.0)*x750*x756))+(((-0.19)*cj1))+((sj1*x754))+(((-1.0)*sj3*x745*x752))+(((-1.0)*cj1*x755))+((cj3*x746*x752))+(((-1.0)*x749))); evalcond[4]=(((cj1*x754))+((x752*x753))+((x752*x756))+(((0.19)*sj1))+((sj1*x755))+(((-1.0)*sj3*x745*x750))+(((-1.0)*x747))+(((-1.0)*x748))+((cj3*x746*x750))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x759=cj1*cj1; IkReal x760=(cj0*px); IkReal x761=(py*sj0); IkReal x762=(cj3*pz); IkReal x763=((51.87)*cj1); IkReal x764=(pz*sj3); IkReal x765=((273.0)*cj1*sj1); IkReal x766=((273.0)*x759); IkReal x767=((139.0)*cj1*sj1); IkReal x768=((139.0)*x759); CheckValue<IkReal> x769=IKPowWithIntegerCheck(IKsign(((((93.85)*cj1))+(((75.894)*cj1*cj3)))),-1); if(!x769.valid){ continue; } CheckValue<IkReal> x770 = IKatan2WithCheck(IkReal((((sj3*x761*x765))+((x760*x768))+((sj3*x760*x765))+((x761*x768))+(((-1.0)*x764*x766))+((cj3*x760*x766))+((cj3*x761*x766))+((x762*x765))+((pz*x767))+(((-1.0)*sj3*x763)))),((((-1.0)*x762*x766))+(((-1.0)*sj3*x761*x766))+(((-26.41)*cj1))+(((-1.0)*cj3*x763))+(((-1.0)*sj3*x760*x766))+((x760*x767))+((x761*x767))+(((-1.0)*x764*x765))+((cj3*x760*x765))+((cj3*x761*x765))+(((-1.0)*pz*x768))),IKFAST_ATAN2_MAGTHRESH); if(!x770.valid){ continue; } j2array[0]=((-1.5707963267949)+(((1.5707963267949)*(x769.value)))+(x770.value)); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[5]; IkReal x771=IKcos(j2); IkReal x772=IKsin(j2); IkReal x773=(cj0*px); IkReal x774=(py*sj0); IkReal x775=((1.0)*pz); IkReal x776=((0.273)*cj1); IkReal x777=((1.0)*cj1); IkReal x778=((0.273)*sj1); IkReal x779=(cj3*x771); IkReal x780=((0.139)*x772); IkReal x781=((0.139)*x771); IkReal x782=(sj3*x772); IkReal x783=((0.273)*cj3*x772); IkReal x784=((0.273)*sj3*x771); evalcond[0]=((-0.19)+(((-1.0)*x781))+((sj1*x774))+((sj1*x773))+(((-0.273)*x782))+(((-0.273)*x779))+(((-1.0)*cj1*x775))); evalcond[1]=((((-1.0)*x774*x777))+(((-1.0)*x784))+x783+x780+(((-1.0)*x773*x777))+(((-1.0)*sj1*x775))); evalcond[2]=((0.12995)+(((-1.0)*(px*px)))+(((0.10374)*x782))+(((0.10374)*x779))+(((-1.0)*pz*x775))+(((0.075894)*cj3))+(((-1.0)*(py*py)))+(((0.05282)*x771))); evalcond[3]=(((cj3*x772*x778))+(((-0.19)*cj1))+((sj1*x780))+(((-1.0)*x776*x782))+(((-1.0)*cj1*x781))+(((-1.0)*x776*x779))+(((-1.0)*x775))+(((-1.0)*sj3*x771*x778))); evalcond[4]=(((cj3*x772*x776))+((cj1*x780))+(((0.19)*sj1))+((sj1*x781))+((x778*x779))+((x778*x782))+(((-1.0)*x773))+(((-1.0)*x774))+(((-1.0)*sj3*x771*x776))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j2array[1], cj2array[1], sj2array[1]; bool j2valid[1]={false}; _nj2 = 1; IkReal x785=((139000.0)*cj1); IkReal x786=(py*sj0); IkReal x787=(cj0*px); IkReal x788=((273000.0)*cj3); IkReal x789=((139000.0)*sj1); IkReal x790=((273000.0)*cj1*sj3); IkReal x791=((273000.0)*sj1*sj3); CheckValue<IkReal> x792 = IKatan2WithCheck(IkReal(((((-1.0)*pz*sj1*x788))+(((-1.0)*cj1*x787*x788))+(((-1.0)*cj1*x786*x788))+(((51870.0)*sj3))+((pz*x790))+(((-1.0)*x787*x791))+(((-1.0)*x786*x791))+(((-1.0)*x785*x787))+(((-1.0)*x785*x786))+(((-1.0)*pz*x789)))),((26410.0)+(((-1.0)*sj1*x786*x788))+((x786*x790))+((x787*x790))+((pz*x791))+((pz*x785))+(((-1.0)*sj1*x787*x788))+(((51870.0)*cj3))+(((-1.0)*x787*x789))+(((-1.0)*x786*x789))+((cj1*pz*x788))),IKFAST_ATAN2_MAGTHRESH); if(!x792.valid){ continue; } CheckValue<IkReal> x793=IKPowWithIntegerCheck(IKsign(((-93850.0)+(((-75894.0)*cj3)))),-1); if(!x793.valid){ continue; } j2array[0]=((-1.5707963267949)+(x792.value)+(((1.5707963267949)*(x793.value)))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; for(int ij2 = 0; ij2 < 1; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 1; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal evalcond[5]; IkReal x794=IKcos(j2); IkReal x795=IKsin(j2); IkReal x796=(cj0*px); IkReal x797=(py*sj0); IkReal x798=((1.0)*pz); IkReal x799=((0.273)*cj1); IkReal x800=((1.0)*cj1); IkReal x801=((0.273)*sj1); IkReal x802=(cj3*x794); IkReal x803=((0.139)*x795); IkReal x804=((0.139)*x794); IkReal x805=(sj3*x795); IkReal x806=((0.273)*cj3*x795); IkReal x807=((0.273)*sj3*x794); evalcond[0]=((-0.19)+(((-0.273)*x802))+(((-0.273)*x805))+((sj1*x796))+((sj1*x797))+(((-1.0)*cj1*x798))+(((-1.0)*x804))); evalcond[1]=((((-1.0)*x796*x800))+(((-1.0)*x797*x800))+x806+x803+(((-1.0)*x807))+(((-1.0)*sj1*x798))); evalcond[2]=((0.12995)+(((-1.0)*(px*px)))+(((0.10374)*x802))+(((0.10374)*x805))+(((0.05282)*x794))+(((0.075894)*cj3))+(((-1.0)*pz*x798))+(((-1.0)*(py*py)))); evalcond[3]=(((cj3*x795*x801))+(((-1.0)*x798))+(((-1.0)*sj3*x794*x801))+(((-1.0)*x799*x802))+(((-1.0)*x799*x805))+(((-0.19)*cj1))+(((-1.0)*cj1*x804))+((sj1*x803))); evalcond[4]=((((0.19)*sj1))+((cj1*x803))+((x801*x805))+((x801*x802))+((sj1*x804))+(((-1.0)*sj3*x794*x799))+(((-1.0)*x796))+(((-1.0)*x797))+((cj3*x795*x799))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } } else { { IkReal j2array[2], cj2array[2], sj2array[2]; bool j2valid[2]={false}; _nj2 = 2; IkReal x808=((0.05282)+(((0.10374)*cj3))); CheckValue<IkReal> x811 = IKatan2WithCheck(IkReal(x808),((0.10374)*sj3),IKFAST_ATAN2_MAGTHRESH); if(!x811.valid){ continue; } IkReal x809=((1.0)*(x811.value)); if((((x808*x808)+(((0.0107619876)*(sj3*sj3))))) < -0.00001) continue; CheckValue<IkReal> x812=IKPowWithIntegerCheck(IKabs(IKsqrt(((x808*x808)+(((0.0107619876)*(sj3*sj3)))))),-1); if(!x812.valid){ continue; } if( (((x812.value)*(((0.12995)+(((-1.0)*(px*px)))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py))))))) < -1-IKFAST_SINCOS_THRESH || (((x812.value)*(((0.12995)+(((-1.0)*(px*px)))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py))))))) > 1+IKFAST_SINCOS_THRESH ) continue; IkReal x810=IKasin(((x812.value)*(((0.12995)+(((-1.0)*(px*px)))+(((0.075894)*cj3))+(((-1.0)*(pz*pz)))+(((-1.0)*(py*py))))))); j2array[0]=((((-1.0)*x810))+(((-1.0)*x809))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); j2array[1]=((3.14159265358979)+x810+(((-1.0)*x809))); sj2array[1]=IKsin(j2array[1]); cj2array[1]=IKcos(j2array[1]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; if( j2array[1] > IKPI ) { j2array[1]-=IK2PI; } else if( j2array[1] < -IKPI ) { j2array[1]+=IK2PI; } j2valid[1] = true; for(int ij2 = 0; ij2 < 2; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 2; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal j1eval[2]; IkReal x813=py*py; IkReal x814=cj0*cj0; IkReal x815=((((-1.0)*x814*(px*px)))+((x813*x814))+(((-1.0)*x813))+(((-1.0)*(pz*pz)))+(((-2.0)*cj0*px*py*sj0))); j1eval[0]=x815; j1eval[1]=IKsign(x815); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 ) { { IkReal j1eval[2]; IkReal x816=(cj0*px); IkReal x817=((0.139)*sj2); IkReal x818=(cj2*pz); IkReal x819=(py*sj0); IkReal x820=((1.96402877697842)*sj2); IkReal x821=(pz*sj3); IkReal x822=((1.0)*sj2); IkReal x823=((0.273)*sj2); IkReal x824=((0.273)*cj2*sj3); IkReal x825=((1.96402877697842)*cj2*sj3); j1eval[0]=((((-1.0)*x816*x822))+(((-1.96402877697842)*cj3*x818))+(((-1.0)*cj3*x816*x820))+(((-1.0)*x819*x822))+((x819*x825))+((x816*x825))+(((-1.0)*x818))+(((-1.0)*x820*x821))+(((-1.36690647482014)*pz))+(((-1.0)*cj3*x819*x820))); j1eval[1]=IKsign(((((-1.0)*cj3*x816*x823))+(((-1.0)*x816*x817))+(((-1.0)*x817*x819))+((x819*x824))+(((-0.19)*pz))+((x816*x824))+(((-1.0)*x821*x823))+(((-0.139)*x818))+(((-1.0)*cj3*x819*x823))+(((-0.273)*cj3*x818)))); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 ) { { IkReal j1eval[2]; IkReal x826=((0.273)*cj3); IkReal x827=(pz*sj2); IkReal x828=((1.96402877697842)*cj3); IkReal x829=(py*sj0); IkReal x830=((1.96402877697842)*sj3); IkReal x831=(cj2*pz); IkReal x832=(cj0*px); IkReal x833=((0.273)*sj3); IkReal x834=(cj2*x832); IkReal x835=(sj2*sj3*x829); j1eval[0]=((((-1.0)*cj2*x829))+(((-1.0)*sj2*x830*x832))+(((-1.0)*sj2*x829*x830))+(((-1.0)*x828*x834))+(((-1.36690647482014)*x832))+(((-1.0)*x830*x831))+(((-1.36690647482014)*x829))+(((-1.0)*x834))+(((-1.0)*cj2*x828*x829))+x827+((x827*x828))); j1eval[1]=IKsign(((((-1.0)*sj2*x829*x833))+(((-1.0)*sj2*x832*x833))+(((-1.0)*x826*x834))+(((-1.0)*cj2*x826*x829))+(((-0.139)*x834))+(((-0.19)*x829))+(((0.139)*x827))+(((-0.19)*x832))+(((-0.139)*cj2*x829))+((x826*x827))+(((-1.0)*x831*x833)))); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 ) { continue; // no branches [j1] } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x836=cj2*cj2; IkReal x837=cj3*cj3; IkReal x838=((0.273)*cj3); IkReal x839=(cj0*px); IkReal x840=(py*sj0); IkReal x841=(pz*sj2); IkReal x842=((0.139)*cj2); IkReal x843=((0.075894)*cj3); IkReal x844=(cj2*sj2); IkReal x845=(cj2*sj3); IkReal x846=(cj3*sj3); IkReal x847=((0.075894)*sj3); IkReal x848=((0.273)*sj2*sj3); IkReal x849=((0.149058)*x837); CheckValue<IkReal> x850 = IKatan2WithCheck(IkReal(((-0.110629)+(((-0.10374)*sj2*sj3))+(((-0.149058)*x844*x846))+(((-1.0)*x836*x849))+(((-1.0)*x836*x843))+(((0.074529)*x837))+(pz*pz)+(((0.055208)*x836))+(((-1.0)*x844*x847))+(((-0.05282)*cj2))+(((-0.10374)*cj2*cj3)))),((((-0.02641)*sj2))+(((-0.074529)*x846))+(((-0.05187)*cj3*sj2))+((pz*x839))+(((0.055208)*x844))+((pz*x840))+(((-1.0)*x843*x844))+((x836*x847))+(((0.149058)*x836*x846))+(((-1.0)*x844*x849))+(((0.05187)*x845))+(((-0.037947)*sj3))),IKFAST_ATAN2_MAGTHRESH); if(!x850.valid){ continue; } CheckValue<IkReal> x851=IKPowWithIntegerCheck(IKsign((((x838*x841))+(((-1.0)*x840*x842))+(((-1.0)*x840*x848))+(((-1.0)*cj2*x838*x840))+(((-0.273)*pz*x845))+(((-1.0)*cj2*x838*x839))+(((-0.19)*x840))+(((-1.0)*x839*x848))+(((-1.0)*x839*x842))+(((-0.19)*x839))+(((0.139)*x841)))),-1); if(!x851.valid){ continue; } j1array[0]=((-1.5707963267949)+(x850.value)+(((1.5707963267949)*(x851.value)))); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x852=IKsin(j1); IkReal x853=IKcos(j1); IkReal x854=((0.273)*sj3); IkReal x855=(cj0*px); IkReal x856=((0.273)*cj3); IkReal x857=(py*sj0); IkReal x858=((1.0)*pz); IkReal x859=((0.139)*sj2); IkReal x860=(sj2*x852); IkReal x861=((1.0)*x853); IkReal x862=(cj2*x853); IkReal x863=(cj2*x852); IkReal x864=((0.38)*x852); IkReal x865=(sj2*x853); evalcond[0]=((-0.19)+(((-1.0)*x853*x858))+(((-1.0)*cj2*x856))+(((-1.0)*sj2*x854))+((x852*x857))+((x852*x855))+(((-0.139)*cj2))); evalcond[1]=(((sj2*x856))+(((-1.0)*x852*x858))+(((-1.0)*cj2*x854))+x859+(((-1.0)*x857*x861))+(((-1.0)*x855*x861))); evalcond[2]=((0.05775)+(((-1.0)*(px*px)))+((x855*x864))+(((-0.38)*pz*x853))+(((0.075894)*cj3))+(((-1.0)*pz*x858))+(((-1.0)*(py*py)))+((x857*x864))); evalcond[3]=((((-0.139)*x862))+(((-1.0)*x854*x865))+(((-1.0)*x854*x863))+(((-1.0)*x858))+(((-0.19)*x853))+((x856*x860))+(((-1.0)*x856*x862))+((x852*x859))); evalcond[4]=((((-1.0)*x854*x862))+(((-1.0)*x855))+(((-1.0)*x857))+(((0.139)*x863))+((x856*x865))+((x856*x863))+(((0.19)*x852))+((x853*x859))+((x854*x860))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x866=cj2*cj2; IkReal x867=cj3*cj3; IkReal x868=(cj3*sj3); IkReal x869=(cj2*sj2); IkReal x870=((0.075894)*cj3); IkReal x871=(cj2*pz); IkReal x872=(cj2*sj3); IkReal x873=((0.273)*sj2); IkReal x874=(cj0*px); IkReal x875=((1.0)*pz); IkReal x876=(py*sj0); IkReal x877=((0.139)*sj2); IkReal x878=((0.075894)*x866); IkReal x879=((0.149058)*x867); CheckValue<IkReal> x880=IKPowWithIntegerCheck(IKsign(((((-0.139)*x871))+(((-1.0)*x876*x877))+(((-0.19)*pz))+(((-0.273)*cj3*x871))+(((-1.0)*pz*sj3*x873))+(((-1.0)*cj3*x873*x876))+(((-1.0)*cj3*x873*x874))+(((-1.0)*x874*x877))+(((0.273)*x872*x874))+(((0.273)*x872*x876)))),-1); if(!x880.valid){ continue; } CheckValue<IkReal> x881 = IKatan2WithCheck(IkReal(((((0.05187)*x872))+(((-0.02641)*sj2))+((sj3*x878))+(((-0.05187)*cj3*sj2))+(((0.055208)*x869))+(((-1.0)*x869*x870))+(((-1.0)*x869*x879))+(((-0.074529)*x868))+(((0.149058)*x866*x868))+(((-1.0)*x875*x876))+(((-1.0)*x874*x875))+(((-0.037947)*sj3)))),((-0.019321)+(((-0.055208)*x866))+(((0.149058)*x868*x869))+((x866*x879))+((x866*x870))+(pz*pz)+(((-0.074529)*x867))+(((0.075894)*sj3*x869))+(((-1.0)*x870))),IKFAST_ATAN2_MAGTHRESH); if(!x881.valid){ continue; } j1array[0]=((-1.5707963267949)+(((1.5707963267949)*(x880.value)))+(x881.value)); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x882=IKsin(j1); IkReal x883=IKcos(j1); IkReal x884=((0.273)*sj3); IkReal x885=(cj0*px); IkReal x886=((0.273)*cj3); IkReal x887=(py*sj0); IkReal x888=((1.0)*pz); IkReal x889=((0.139)*sj2); IkReal x890=(sj2*x882); IkReal x891=((1.0)*x883); IkReal x892=(cj2*x883); IkReal x893=(cj2*x882); IkReal x894=((0.38)*x882); IkReal x895=(sj2*x883); evalcond[0]=((-0.19)+(((-1.0)*x883*x888))+(((-1.0)*cj2*x886))+((x882*x885))+((x882*x887))+(((-1.0)*sj2*x884))+(((-0.139)*cj2))); evalcond[1]=((((-1.0)*cj2*x884))+(((-1.0)*x882*x888))+((sj2*x886))+(((-1.0)*x885*x891))+x889+(((-1.0)*x887*x891))); evalcond[2]=((0.05775)+(((-1.0)*(px*px)))+(((-1.0)*pz*x888))+(((0.075894)*cj3))+((x885*x894))+(((-1.0)*(py*py)))+(((-0.38)*pz*x883))+((x887*x894))); evalcond[3]=(((x886*x890))+(((-1.0)*x884*x893))+(((-1.0)*x884*x895))+((x882*x889))+(((-1.0)*x888))+(((-0.19)*x883))+(((-0.139)*x892))+(((-1.0)*x886*x892))); evalcond[4]=(((x886*x895))+((x886*x893))+(((-1.0)*x884*x892))+((x884*x890))+(((0.19)*x882))+((x883*x889))+(((-1.0)*x885))+(((-1.0)*x887))+(((0.139)*x893))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x896=py*py; IkReal x897=cj0*cj0; IkReal x898=((0.273)*cj3); IkReal x899=(py*sj0); IkReal x900=((0.273)*sj3); IkReal x901=(pz*sj2); IkReal x902=((0.139)*cj2); IkReal x903=(cj0*px); IkReal x904=(cj2*pz); IkReal x905=((0.139)*sj2); IkReal x906=(cj2*x903); CheckValue<IkReal> x907=IKPowWithIntegerCheck(IKsign(((((-2.0)*x899*x903))+((x896*x897))+(((-1.0)*x897*(px*px)))+(((-1.0)*x896))+(((-1.0)*(pz*pz))))),-1); if(!x907.valid){ continue; } CheckValue<IkReal> x908 = IKatan2WithCheck(IkReal(((((-1.0)*sj2*x900*x903))+(((-1.0)*x902*x903))+(((-0.19)*x903))+((x900*x904))+(((-1.0)*x898*x906))+(((-1.0)*x898*x901))+(((-0.19)*x899))+(((-0.139)*x901))+(((-1.0)*sj2*x899*x900))+(((-1.0)*x899*x902))+(((-1.0)*cj2*x898*x899)))),((((-1.0)*x903*x905))+(((-1.0)*sj2*x898*x903))+(((0.19)*pz))+((x900*x901))+((x900*x906))+((cj2*x899*x900))+(((-1.0)*sj2*x898*x899))+((pz*x902))+((x898*x904))+(((-1.0)*x899*x905))),IKFAST_ATAN2_MAGTHRESH); if(!x908.valid){ continue; } j1array[0]=((-1.5707963267949)+(((1.5707963267949)*(x907.value)))+(x908.value)); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x909=IKsin(j1); IkReal x910=IKcos(j1); IkReal x911=((0.273)*sj3); IkReal x912=(cj0*px); IkReal x913=((0.273)*cj3); IkReal x914=(py*sj0); IkReal x915=((1.0)*pz); IkReal x916=((0.139)*sj2); IkReal x917=(sj2*x909); IkReal x918=((1.0)*x910); IkReal x919=(cj2*x910); IkReal x920=(cj2*x909); IkReal x921=((0.38)*x909); IkReal x922=(sj2*x910); evalcond[0]=((-0.19)+((x909*x914))+((x909*x912))+(((-1.0)*x910*x915))+(((-1.0)*sj2*x911))+(((-0.139)*cj2))+(((-1.0)*cj2*x913))); evalcond[1]=(((sj2*x913))+(((-1.0)*x912*x918))+(((-1.0)*x914*x918))+x916+(((-1.0)*x909*x915))+(((-1.0)*cj2*x911))); evalcond[2]=((0.05775)+(((-1.0)*(px*px)))+(((-1.0)*pz*x915))+((x914*x921))+(((0.075894)*cj3))+(((-0.38)*pz*x910))+(((-1.0)*(py*py)))+((x912*x921))); evalcond[3]=((((-1.0)*x913*x919))+((x909*x916))+(((-1.0)*x915))+(((-0.19)*x910))+(((-0.139)*x919))+((x913*x917))+(((-1.0)*x911*x920))+(((-1.0)*x911*x922))); evalcond[4]=(((x910*x916))+(((0.139)*x920))+((x911*x917))+(((-1.0)*x914))+(((-1.0)*x912))+(((-1.0)*x911*x919))+(((0.19)*x909))+((x913*x922))+((x913*x920))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(5); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } } } } } } return solutions.GetNumSolutions()>0; } }; /// solves the inverse kinematics equations. /// \param pfree is an array specifying the free joints of the chain. IKFAST_API bool ComputeIk(const IkReal* eetrans, const IkReal* eerot, const IkReal* pfree, IkSolutionListBase<IkReal>& solutions) { IKSolver solver; return solver.ComputeIk(eetrans,eerot,pfree,solutions); } IKFAST_API bool ComputeIk2(const IkReal* eetrans, const IkReal* eerot, const IkReal* pfree, IkSolutionListBase<IkReal>& solutions, void* pOpenRAVEManip) { IKSolver solver; return solver.ComputeIk(eetrans,eerot,pfree,solutions); } IKFAST_API const char* GetKinematicsHash() { return "69feda14a9ec6d01480eccb137edee22"; } IKFAST_API const char* GetIkFastVersion() { return "0x10000048"; } #ifdef IKFAST_NAMESPACE } // end namespace #endif #ifndef IKFAST_NO_MAIN #include <stdio.h> #include <stdlib.h> #ifdef IKFAST_NAMESPACE using namespace IKFAST_NAMESPACE; #endif int main(int argc, char** argv) { if( argc != 12+GetNumFreeParameters()+1 ) { printf("\nUsage: ./ik r00 r01 r02 t0 r10 r11 r12 t1 r20 r21 r22 t2 free0 ...\n\n" "Returns the ik solutions given the transformation of the end effector specified by\n" "a 3x3 rotation R (rXX), and a 3x1 translation (tX).\n" "There are %d free parameters that have to be specified.\n\n",GetNumFreeParameters()); return 1; } IkSolutionList<IkReal> solutions; std::vector<IkReal> vfree(GetNumFreeParameters()); IkReal eerot[9],eetrans[3]; eerot[0] = atof(argv[1]); eerot[1] = atof(argv[2]); eerot[2] = atof(argv[3]); eetrans[0] = atof(argv[4]); eerot[3] = atof(argv[5]); eerot[4] = atof(argv[6]); eerot[5] = atof(argv[7]); eetrans[1] = atof(argv[8]); eerot[6] = atof(argv[9]); eerot[7] = atof(argv[10]); eerot[8] = atof(argv[11]); eetrans[2] = atof(argv[12]); for(std::size_t i = 0; i < vfree.size(); ++i) vfree[i] = atof(argv[13+i]); bool bSuccess = ComputeIk(eetrans, eerot, vfree.size() > 0 ? &vfree[0] : NULL, solutions); if( !bSuccess ) { fprintf(stderr,"Failed to get ik solution\n"); return -1; } printf("Found %d ik solutions:\n", (int)solutions.GetNumSolutions()); std::vector<IkReal> solvalues(GetNumJoints()); for(std::size_t i = 0; i < solutions.GetNumSolutions(); ++i) { const IkSolutionBase<IkReal>& sol = solutions.GetSolution(i); printf("sol%d (free=%d): ", (int)i, (int)sol.GetFree().size()); std::vector<IkReal> vsolfree(sol.GetFree().size()); sol.GetSolution(&solvalues[0],vsolfree.size()>0?&vsolfree[0]:NULL); for( std::size_t j = 0; j < solvalues.size(); ++j) printf("%.15f, ", solvalues[j]); printf("\n"); } return 0; } #endif #include "plugindefs.h" namespace IKFAST_NAMESPACE { IkSolverBasePtr CreateIkSolver(EnvironmentBasePtr penv, std::istream& sinput, const std::vector<dReal>& vfreeinc) { boost::shared_ptr<ikfast::IkFastFunctions<IkReal> > ikfunctions(new ikfast::IkFastFunctions<IkReal>()); ikfunctions->_ComputeIk = IKFAST_NAMESPACE::ComputeIk; ikfunctions->_ComputeFk = IKFAST_NAMESPACE::ComputeFk; ikfunctions->_GetNumFreeParameters = IKFAST_NAMESPACE::GetNumFreeParameters; ikfunctions->_GetFreeParameters = IKFAST_NAMESPACE::GetFreeParameters; ikfunctions->_GetNumJoints = IKFAST_NAMESPACE::GetNumJoints; ikfunctions->_GetIkRealSize = IKFAST_NAMESPACE::GetIkRealSize; ikfunctions->_GetIkFastVersion = IKFAST_NAMESPACE::GetIkFastVersion; ikfunctions->_GetIkType = IKFAST_NAMESPACE::GetIkType; ikfunctions->_GetKinematicsHash = IKFAST_NAMESPACE::GetKinematicsHash; return CreateIkFastSolver(penv,sinput,ikfunctions,vfreeinc); } } // end namespace
27.581398
666
0.631091
[ "object", "vector" ]
99b0e6142939bf844b2417d7799565952d8bfa60
12,898
cc
C++
tutorial/05_physical_regions/physical_regions.cc
karasevb/legion
f3f4e7d987768598b554ffca65d730f697956dc8
[ "Apache-2.0" ]
null
null
null
tutorial/05_physical_regions/physical_regions.cc
karasevb/legion
f3f4e7d987768598b554ffca65d730f697956dc8
[ "Apache-2.0" ]
null
null
null
tutorial/05_physical_regions/physical_regions.cc
karasevb/legion
f3f4e7d987768598b554ffca65d730f697956dc8
[ "Apache-2.0" ]
1
2021-01-07T22:07:18.000Z
2021-01-07T22:07:18.000Z
/* Copyright 2020 Stanford University * * 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 <cstdio> #include <cassert> #include <cstdlib> #include "legion.h" using namespace Legion; /* * In this section we use a sequential * implementation of daxpy to show how * to create physical instances of logical * regions. In later sections we will * show how to extend this daxpy example * so that it will run with sub-tasks * and also run in parallel. */ enum TaskIDs { TOP_LEVEL_TASK_ID, }; enum FieldIDs { FID_X, FID_Y, FID_Z, }; void top_level_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { int num_elements = 1024; // See if we have any command line arguments to parse { const InputArgs &command_args = Runtime::get_input_args(); for (int i = 1; i < command_args.argc; i++) { if (!strcmp(command_args.argv[i],"-n")) num_elements = atoi(command_args.argv[++i]); } } printf("Running daxpy for %d elements...\n", num_elements); // We'll create two logical regions with a common index space // for storing our inputs and outputs. The input region will // have two fields for storing the 'x' and 'y' fields of the // daxpy computation, and the output region will have a single // field 'z' for storing the result. Rect<1> elem_rect(0,num_elements-1); IndexSpace is = runtime->create_index_space(ctx, elem_rect); FieldSpace input_fs = runtime->create_field_space(ctx); { FieldAllocator allocator = runtime->create_field_allocator(ctx, input_fs); allocator.allocate_field(sizeof(double),FID_X); allocator.allocate_field(sizeof(double),FID_Y); } FieldSpace output_fs = runtime->create_field_space(ctx); { FieldAllocator allocator = runtime->create_field_allocator(ctx, output_fs); allocator.allocate_field(sizeof(double),FID_Z); } LogicalRegion input_lr = runtime->create_logical_region(ctx, is, input_fs); LogicalRegion output_lr = runtime->create_logical_region(ctx, is, output_fs); // Use fill_field to set an initial value for the fields in the input // logical region. runtime->fill_field<double>(ctx, input_lr, input_lr, FID_X, 0.0); runtime->fill_field<double>(ctx, input_lr, input_lr, FID_Y, 0.0); // Now that we have our logical regions we want to instantiate physical // instances of these regions which we can use for storing data. One way // of creating a physical instance of a logical region is via an inline // mapping operation. (We'll discuss the other way of creating physical // instances in the next example.) Inline mappings map a physical instance // of logical region inside of this task's context. This will give the // task an up-to-date copy of the data stored in these logical regions. // In this particular daxpy example, the data has yet to be initialized so // really this just creates un-initialized physical regions for the // application to use. // // To perform an inline mapping we use an InlineLauncher object which is // similar to other launcher objects shown earlier. The argument passed // to this launcher is a 'RegionRequirement' which is used to specify which // logical region we should be mapping as well as with what privileges // and coherence. In this example we are mapping the input_lr logical // region with READ-WRITE privilege and EXCLUSIVE coherence. We'll see // examples of other privileges in later examples. If you're interested // in learning about relaxed coherence modes we refer you to our OOPSLA paper. // The last argument in the RegionRequirement is the logical region for // which the enclosing task has privileges which in this case is the // same input_lr logical region. We'll discuss restrictions on privileges // more in the next example. RegionRequirement req(input_lr, READ_WRITE, EXCLUSIVE, input_lr); // We also need to specify which fields we plan to access in our // RegionRequirement. To do this we invoke the 'add_field' method // on the RegionRequirement. req.add_field(FID_X); req.add_field(FID_Y); InlineLauncher input_launcher(req); // Once we have set up our launcher, we as the runtime to map a physical // region instance of our requested logical region with the given // privileges and coherence. This returns a PhysicalRegion object // which is handle to the physical instance which contains data // for the logical region. In keeping with Legion's deferred execution // model the 'map_region' call is asynchronous. This allows the // application to issue many of these operations in flight and to // perform other useful work while waiting for the region to be ready. // // One common criticism about Legion applications is that there exists // a dichotomy between logical and physical regions. Programmers // are explicitly required to keep track of both kinds of regions and // know when and how to use them. If you feel this way as well, we // encourage you to try out our Legion compiler in which this // dichotomy does not exist. There are simply regions and the compiler // automatically manages the logical and physical nature of them // in a way that is analogous to how compilers manage the mapping // between variables and architectural registers. This runtime API // is designed to be expressive for all Legion programs and is not // necessarily designed for programmer productivity. PhysicalRegion input_region = runtime->map_region(ctx, input_launcher); // The application can either poll a physical region to see when it // contains valid data for the logical region using the 'is_valid' // method or it can explicitly wait using the 'wait_until_valid' // method. Just like waiting on a future, if the region is not ready // this task is pre-empted and other tasks may run while waiting // for the region to be ready. Note that an application does not // need to explicitly wait for the physical region to be ready before // using it, but any call to get an accessor (described next) on // physical region that does not yet have valid data will implicitly // call 'wait_until_valid' to guarantee correct execution by ensuring // the application only can access the physical instance once the // data is valid. input_region.wait_until_valid(); // To actually access data within a physical region, an application // must create a RegionAccessor. RegionAccessors provide a level // of indirection between a physical instance and the application // which is necessary for supporting general task code that is // independent of data layout. RegionAccessors are templated on // the kind of accessor that they are and the type of element they // are accessing. Here we illustrate only Generic accessors. // Generic accessors are the simplest accessors to use and have // the ability to dynamically verify that all accesses they perform // are correct. However, they are also very slow. Therefore // they should NEVER be used in production code. In general, we // encourage application developers to write two versions of any // function: one using Generic accessors that can be used to check // correctness, and then a faster version using higher performance // accessors (discussed in a later example). // // Note that each accessor must specify which field it is // accessing and then check that the types match with the // field that is being accessed. This provides a combination // of dynamic and static checking which ensures that the // correct data is being accessed. const FieldAccessor<READ_WRITE,double,1> acc_x(input_region, FID_X); const FieldAccessor<READ_WRITE,double,1> acc_y(input_region, FID_Y); // We initialize our regions with some random data. To iterate // over all the points in each of the regions we use an iterator // which can be used to enumerate all the points within an array. // The points in the array (the 'p' field in the iterator) are // used to access different locations in each of the physical // instances. for (PointInRectIterator<1> pir(elem_rect); pir(); pir++) { acc_x[*pir] = drand48(); acc_y[*pir] = drand48(); } // Now we map our output region so we can do the actual computation. // We use another inline launcher with a different RegionRequirement // that specifies our privilege to be WRITE-DISCARD. WRITE-DISCARD // says that we can discard any data presently residing the region // because we are going to overwrite it. InlineLauncher output_launcher(RegionRequirement(output_lr, WRITE_DISCARD, EXCLUSIVE, output_lr)); output_launcher.requirement.add_field(FID_Z); // Map the region PhysicalRegion output_region = runtime->map_region(ctx, output_launcher); // Note that this accessor invokes the implicit 'wait_until_valid' // call described earlier. const double alpha = drand48(); { const FieldAccessor<WRITE_DISCARD,double,1> acc_z(output_region, FID_Z); printf("Running daxpy computation with alpha %.8g...", alpha); // Iterate over our points and perform the daxpy computation. Note // we can use the same iterator because both the input and output // regions were created using the same index space. for (PointInRectIterator<1> pir(elem_rect); pir(); pir++) acc_z[*pir] = alpha * acc_x[*pir] + acc_y[*pir]; } printf("Done!\n"); // In some cases it may be necessary to unmap regions and then // remap them. We'll give a compelling example of this in the // next example. In this case we'll remap the output region // with READ-ONLY privileges to check the output result. // We really could have done this directly since WRITE-DISCARD // privileges are equivalent to READ-WRITE privileges in terms // of allowing reads and writes, but we'll explicitly unmap // and then remap. Unmapping is done with the unmap call. // After this call the physical region no longer contains valid // data and all accessors from the physical region are invalidated. runtime->unmap_region(ctx, output_region); // We can then remap the region. Note if we wanted to remap // with the same privileges we could have used the 'remap_region' // call. However, we want different privileges so we update // the launcher and then remap the region. The 'remap_region' // call also guarantees that we would get the same physical // instance. By calling 'map_region' again, we have no such // guarantee. We may get the same physical instance or a new // one. The orthogonality of correctness from mapping decisions // ensures that we will access the same data regardless. output_launcher.requirement.privilege = READ_ONLY; output_region = runtime->map_region(ctx, output_launcher); // Since we may have received a new physical instance we need // to update our accessor as well. Again this implicitly calls // 'wait_until_valid' to ensure we have valid data. const FieldAccessor<READ_ONLY,double,1> acc_z(output_region, FID_Z); printf("Checking results..."); bool all_passed = true; // Check our results are the same for (PointInRectIterator<1> pir(elem_rect); pir(); pir++) { double expected = alpha * acc_x[*pir] + acc_y[*pir]; double received = acc_z[*pir]; // Probably shouldn't check for floating point equivalence but // the order of operations are the same should they should // be bitwise equal. if (expected != received) all_passed = false; } if (all_passed) printf("SUCCESS!\n"); else printf("FAILURE!\n"); // Clean up all our data structures. runtime->destroy_logical_region(ctx, input_lr); runtime->destroy_logical_region(ctx, output_lr); runtime->destroy_field_space(ctx, input_fs); runtime->destroy_field_space(ctx, output_fs); runtime->destroy_index_space(ctx, is); } int main(int argc, char **argv) { Runtime::set_top_level_task_id(TOP_LEVEL_TASK_ID); { TaskVariantRegistrar registrar(TOP_LEVEL_TASK_ID, "top_level"); registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); Runtime::preregister_task_variant<top_level_task>(registrar, "top_level"); } return Runtime::start(argc, argv); }
45.575972
80
0.730889
[ "object", "vector", "model" ]
99b3e04eed266d0ada0f206a9a23930e7d20c361
2,281
cpp
C++
Dev/Cpp/EditorCommon/GUI/Misc.cpp
Shockblast/Effekseer
bac86c0fc965f04a0f57c5863d37a9c2d5c3be97
[ "Apache-2.0", "BSD-3-Clause" ]
1
2021-12-21T07:03:42.000Z
2021-12-21T07:03:42.000Z
Dev/Cpp/EditorCommon/GUI/Misc.cpp
Shockblast/Effekseer
bac86c0fc965f04a0f57c5863d37a9c2d5c3be97
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Dev/Cpp/EditorCommon/GUI/Misc.cpp
Shockblast/Effekseer
bac86c0fc965f04a0f57c5863d37a9c2d5c3be97
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
#include "Misc.h" #include "JapaneseFont.h" #include <cmath> #include <fstream> #include <imgui.h> #include <iostream> #include <sstream> #include <string> #include <vector> #include "../Common/StringHelper.h" namespace Effekseer { namespace Editor { void AddFontFromFileTTF(const char* fontFilepath, const char* commonCharacterTablePath, const char* characterTableName, float size_pixels, float dpi_scale) { ImGuiIO& io = ImGui::GetIO(); size_pixels = std::roundf(size_pixels * dpi_scale); const auto tableName = std::string(characterTableName); if (tableName == "japanese") { io.Fonts->AddFontFromFileTTF(fontFilepath, size_pixels, nullptr, glyphRangesJapanese); } else if (tableName == "chinese") { io.Fonts->AddFontFromFileTTF(fontFilepath, size_pixels, nullptr, io.Fonts->GetGlyphRangesChineseFull()); } else if (tableName == "korean") { io.Fonts->AddFontFromFileTTF(fontFilepath, size_pixels, nullptr, io.Fonts->GetGlyphRangesKorean()); } else if (tableName == "thai") { io.Fonts->AddFontFromFileTTF(fontFilepath, size_pixels, nullptr, io.Fonts->GetGlyphRangesThai()); } else { io.Fonts->AddFontFromFileTTF(fontFilepath, size_pixels, nullptr, io.Fonts->GetGlyphRangesDefault()); } { static std::vector<ImWchar> ranges; ranges.clear(); std::ifstream f(commonCharacterTablePath); if (f.is_open()) { auto str = std::string((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); auto str16 = Tool::StringHelper::ConvertUtf8ToUtf16(str); for (const auto c : str16) { ranges.emplace_back(c); ranges.emplace_back(c); } ranges.emplace_back(0); ImFontConfig config; config.MergeMode = true; io.Fonts->AddFontFromFileTTF(fontFilepath, size_pixels, &config, ranges.data()); } } io.Fonts->Build(); } std::string GetLanguageKey(SystemLanguage language) { if (language == SystemLanguage::Japanese) { return "ja"; } else if (language == SystemLanguage::English) { return "en"; } // Fallback return "en"; } SystemLanguage GetSystemLanguage(const std::string& key) { if (key == "ja") { return SystemLanguage::Japanese; } else if (key == "en") { return SystemLanguage::English; } return SystemLanguage::Unknown; } } // namespace Editor } // namespace Effekseer
22.362745
155
0.712845
[ "vector" ]
99b80c5faf3d8e6ff172a10854cc96da24bdd072
6,272
cpp
C++
exec/tests/electroTwoWall/particleGen.cpp
ckim103/FHDeX
9182d7589db7e7ee318ca2a0f343c378d9c120a0
[ "BSD-3-Clause-LBNL" ]
null
null
null
exec/tests/electroTwoWall/particleGen.cpp
ckim103/FHDeX
9182d7589db7e7ee318ca2a0f343c378d9c120a0
[ "BSD-3-Clause-LBNL" ]
null
null
null
exec/tests/electroTwoWall/particleGen.cpp
ckim103/FHDeX
9182d7589db7e7ee318ca2a0f343c378d9c120a0
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "INS_functions.H" #include "common_functions.H" #include "FhdParticleContainer.H" //#include <AMReX.H> //#include <AMReX_AmrParGDB.H> //#include <AMReX_ParmParse.H> //#include <AMReX_Particles.H> //#include <AMReX_NeighborParticles.H> //#include <common_functions.H> //#include <common_namespace.H> //#include <ib_functions_F.H> //#include <iostream> void FhdParticleContainer::InitParticles(species* particleInfo, const Real* dxp) { const int lev = 0; const Geometry& geom = Geom(lev); const Real* dx = geom.CellSize(); const Real* plo = geom.ProbLo(); const Real* phi = geom.ProbHi(); int qcount = 0; double cosTheta, sinTheta, cosPhi, sinPhi,sep, th; int pcount = 0; int ll =0; //double initTemp = 0; //double pc = 0; for (MFIter mfi = MakeMFIter(lev, true); mfi.isValid(); ++mfi) { const Box& tile_box = mfi.tilebox(); const RealBox tile_realbox{tile_box, geom.CellSize(), geom.ProbLo()}; const int grid_id = mfi.index(); const int tile_id = mfi.LocalTileIndex(); auto& particle_tile = GetParticles(lev)[std::make_pair(grid_id,tile_id)]; //Assuming tile=box for now, i.e. no tiling. IntVect smallEnd = tile_box.smallEnd(); IntVect bigEnd = tile_box.bigEnd(); if(ParallelDescriptor::MyProc() == 0 && mfi.LocalTileIndex() == 0) { for(int i_spec=0; i_spec < nspecies; i_spec++) { std::cout << "Rank " << ParallelDescriptor::MyProc() << " generating " << particleInfo[i_spec].total << " of species " << i_spec << ".\n"; for (int i_part=0; i_part<particleInfo[i_spec].total;i_part++) { ParticleType p; p.id() = ParticleType::NextID(); p.cpu() = ParallelDescriptor::MyProc(); p.idata(FHD_intData::sorted) = 0; p.pos(0) = prob_lo[0] + prob_hi[0]/2.0 + (1.5-3*ll)*dxp[0]; p.pos(1) = prob_lo[1] + 0.25*(prob_hi[1]-prob_lo[1]); #if (BL_SPACEDIM == 3) p.pos(2) = prob_lo[2] + 0.25*(prob_hi[2]-prob_lo[2]); #endif ll++; p.rdata(FHD_realData::q) = particleInfo[i_spec].q; //Print() << "Pos: " << p.pos(0) << ", " << p.pos(1) << ", " << p.pos(2) << ", " << p.rdata(FHD_realData::q) << "\n" ; //original position stored for MSD calculations p.rdata(FHD_realData::ox) = p.pos(0); p.rdata(FHD_realData::oy) = p.pos(1); #if (BL_SPACEDIM == 3) p.rdata(FHD_realData::oz) = p.pos(2); #endif //p.rdata(FHD_realData::vx) = sqrt(particleInfo.R*particleInfo.T)*get_particle_normal_func(); //p.rdata(FHD_realData::vy) = sqrt(particleInfo.R*particleInfo.T)*get_particle_normal_func(); //p.rdata(FHD_realData::vz) = sqrt(particleInfo.R*particleInfo.T)*get_particle_normal_func(); p.rdata(FHD_realData::pred_posx) = 0; p.rdata(FHD_realData::pred_posy) = 0; p.rdata(FHD_realData::pred_posz) = 0; p.rdata(FHD_realData::pred_velx) = 0; p.rdata(FHD_realData::pred_vely) = 0; p.rdata(FHD_realData::pred_velz) = 0; p.rdata(FHD_realData::pred_forcex) = 0; p.rdata(FHD_realData::pred_forcey) = 0; p.rdata(FHD_realData::pred_forcez) = 0; p.rdata(FHD_realData::fx) = 0; p.rdata(FHD_realData::fy) = 0; p.rdata(FHD_realData::fz) = 0; p.rdata(FHD_realData::vx) = 0; p.rdata(FHD_realData::vy) = 0; p.rdata(FHD_realData::vz) = 0; p.rdata(FHD_realData::ux) = 0; p.rdata(FHD_realData::uy) = 0; p.rdata(FHD_realData::uz) = 0; p.rdata(FHD_realData::ax) = 0; p.rdata(FHD_realData::ay) = 0; p.rdata(FHD_realData::az) = 0; p.rdata(FHD_realData::fx) = 0; p.rdata(FHD_realData::fy) = 0; p.rdata(FHD_realData::fz) = 0; p.rdata(FHD_realData::travelTime) = 0; p.rdata(FHD_realData::diffAv) = 0; p.rdata(FHD_realData::stepCount) = 0; p.rdata(FHD_realData::travelTime) = 0; p.rdata(FHD_realData::diffAv) = 0; p.rdata(FHD_realData::stepCount) = 0; p.rdata(FHD_realData::mass) = particleInfo[i_spec].m; //mass p.rdata(FHD_realData::R) = particleInfo[i_spec].R; //R p.rdata(FHD_realData::radius) = particleInfo[i_spec].d/2.0; //radius p.rdata(FHD_realData::accelFactor) = -6*3.14159265359*p.rdata(FHD_realData::radius)/p.rdata(FHD_realData::mass); //acceleration factor (replace with amrex c++ constant for pi...) p.rdata(FHD_realData::dragFactor) = 6*3.14159265359*p.rdata(FHD_realData::radius); //drag factor //p.rdata(FHD_realData::dragFactor) = 0; //drag factor //p.rdata(FHD_realData::dragFactor) = 6*3.14159265359*dx[0]*1.322; //drag factor p.rdata(FHD_realData::wetDiff) = particleInfo[i_spec].wetDiff; p.rdata(FHD_realData::dryDiff) = particleInfo[i_spec].dryDiff; p.rdata(FHD_realData::totalDiff) = particleInfo[i_spec].totalDiff; p.rdata(FHD_realData::sigma) = particleInfo[i_spec].sigma; p.rdata(FHD_realData::eepsilon) = particleInfo[i_spec].eepsilon; p.idata(FHD_intData::species) = i_spec +1; p.rdata(FHD_realData::potential) = 0; // set distance for which we do direct, short range coulomb force calculation // in p3m to be 6.5*dx_poisson_grid p.rdata(FHD_realData::p3m_radius) = (pkernel_es + 0.5)*dxp[0]; particle_tile.push_back(p); pcount++; } } } } std::cout << "Rank " << ParallelDescriptor::MyProc() << " generated " << ll << " particles.\n"; Redistribute(); UpdateCellVectors(); ReBin(); clearNeighbors(); fillNeighbors(); }
38.243902
194
0.55389
[ "geometry" ]
99bc6edbc3b27a977ac6e1389d17d5439a5578bd
7,614
cpp
C++
third_party/WebKit/Source/bindings/core/v8/ScriptModule.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/bindings/core/v8/ScriptModule.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/bindings/core/v8/ScriptModule.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 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 "bindings/core/v8/ScriptModule.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/V8BindingForCore.h" #include "core/dom/Modulator.h" #include "core/dom/ScriptModuleResolver.h" #include "core/probe/CoreProbes.h" namespace blink { const char* ScriptModuleStateToString(ScriptModuleState state) { switch (state) { case ScriptModuleState::kUninstantiated: return "uninstantiated"; case ScriptModuleState::kInstantiating: return "instatinating"; case ScriptModuleState::kInstantiated: return "instantiated"; case ScriptModuleState::kEvaluating: return "evaluating"; case ScriptModuleState::kEvaluated: return "evaluated"; case ScriptModuleState::kErrored: return "errored"; } NOTREACHED(); return ""; } ScriptModule::ScriptModule() { // We ensure module-related code is not executed without the flag. // https://crbug.com/715376 CHECK(RuntimeEnabledFeatures::ModuleScriptsEnabled()); } ScriptModule::ScriptModule(WTF::HashTableDeletedValueType) : module_(WTF::kHashTableDeletedValue) { // We ensure module-related code is not executed without the flag. // https://crbug.com/715376 CHECK(RuntimeEnabledFeatures::ModuleScriptsEnabled()); } ScriptModule::ScriptModule(v8::Isolate* isolate, v8::Local<v8::Module> module) : module_(SharedPersistent<v8::Module>::Create(module, isolate)), identity_hash_(static_cast<unsigned>(module->GetIdentityHash())) { // We ensure module-related code is not executed without the flag. // https://crbug.com/715376 CHECK(RuntimeEnabledFeatures::ModuleScriptsEnabled()); DCHECK(!module_->IsEmpty()); } ScriptModule::~ScriptModule() {} ScriptModule ScriptModule::Compile(v8::Isolate* isolate, const String& source, const String& file_name, AccessControlStatus access_control_status, const TextPosition& start_position, ExceptionState& exception_state) { // We ensure module-related code is not executed without the flag. // https://crbug.com/715376 CHECK(RuntimeEnabledFeatures::ModuleScriptsEnabled()); v8::TryCatch try_catch(isolate); v8::Local<v8::Module> module; if (!V8ScriptRunner::CompileModule(isolate, source, file_name, access_control_status, start_position) .ToLocal(&module)) { DCHECK(try_catch.HasCaught()); exception_state.RethrowV8Exception(try_catch.Exception()); return ScriptModule(); } DCHECK(!try_catch.HasCaught()); return ScriptModule(isolate, module); } ScriptValue ScriptModule::Instantiate(ScriptState* script_state) { v8::Isolate* isolate = script_state->GetIsolate(); v8::TryCatch try_catch(isolate); try_catch.SetVerbose(true); DCHECK(!IsNull()); v8::Local<v8::Context> context = script_state->GetContext(); bool success; if (!NewLocal(script_state->GetIsolate()) ->InstantiateModule(context, &ResolveModuleCallback) .To(&success) || !success) { DCHECK(try_catch.HasCaught()); return ScriptValue(script_state, try_catch.Exception()); } DCHECK(!try_catch.HasCaught()); return ScriptValue(); } void ScriptModule::Evaluate(ScriptState* script_state) const { v8::Isolate* isolate = script_state->GetIsolate(); // Isolate exceptions that occur when executing the code. These exceptions // should not interfere with javascript code we might evaluate from C++ when // returning from here. v8::TryCatch try_catch(isolate); try_catch.SetVerbose(true); probe::ExecuteScript probe(ExecutionContext::From(script_state)); // TODO(kouhei): We currently don't have a code-path which use return value of // EvaluateModule. Stop ignoring result once we have such path. v8::Local<v8::Value> result; if (!V8ScriptRunner::EvaluateModule(module_->NewLocal(isolate), script_state->GetContext(), isolate) .ToLocal(&result)) { return; } } void ScriptModule::ReportException(ScriptState* script_state, v8::Local<v8::Value> exception, const String& file_name, const TextPosition& start_position) { // We ensure module-related code is not executed without the flag. // https://crbug.com/715376 CHECK(RuntimeEnabledFeatures::ModuleScriptsEnabled()); v8::Isolate* isolate = script_state->GetIsolate(); v8::TryCatch try_catch(isolate); try_catch.SetVerbose(true); V8ScriptRunner::ReportExceptionForModule(isolate, exception, file_name, start_position); } Vector<String> ScriptModule::ModuleRequests(ScriptState* script_state) { if (IsNull()) return Vector<String>(); v8::Local<v8::Module> module = module_->NewLocal(script_state->GetIsolate()); Vector<String> ret; int length = module->GetModuleRequestsLength(); ret.ReserveInitialCapacity(length); for (int i = 0; i < length; ++i) { v8::Local<v8::String> v8_name = module->GetModuleRequest(i); ret.push_back(ToCoreString(v8_name)); } return ret; } Vector<TextPosition> ScriptModule::ModuleRequestPositions( ScriptState* script_state) { if (IsNull()) return Vector<TextPosition>(); v8::Local<v8::Module> module = module_->NewLocal(script_state->GetIsolate()); Vector<TextPosition> ret; int length = module->GetModuleRequestsLength(); ret.ReserveInitialCapacity(length); for (int i = 0; i < length; ++i) { v8::Location v8_loc = module->GetModuleRequestLocation(i); ret.emplace_back(OrdinalNumber::FromZeroBasedInt(v8_loc.GetLineNumber()), OrdinalNumber::FromZeroBasedInt(v8_loc.GetColumnNumber())); } return ret; } ScriptModuleState ScriptModule::Status(ScriptState* script_state) { DCHECK(!IsNull()); v8::Local<v8::Module> module = module_->NewLocal(script_state->GetIsolate()); return module->GetStatus(); } v8::Local<v8::Value> ScriptModule::ErrorCompletion(ScriptState* script_state) { DCHECK(!IsNull()); DCHECK_EQ(ScriptModuleState::kErrored, Status(script_state)); v8::Local<v8::Module> module = module_->NewLocal(script_state->GetIsolate()); return module->GetException(); } v8::MaybeLocal<v8::Module> ScriptModule::ResolveModuleCallback( v8::Local<v8::Context> context, v8::Local<v8::String> specifier, v8::Local<v8::Module> referrer) { // We ensure module-related code is not executed without the flag. // https://crbug.com/715376 CHECK(RuntimeEnabledFeatures::ModuleScriptsEnabled()); v8::Isolate* isolate = context->GetIsolate(); Modulator* modulator = Modulator::From(ScriptState::From(context)); DCHECK(modulator); ScriptModule referrer_record(isolate, referrer); ExceptionState exception_state(isolate, ExceptionState::kExecutionContext, "ScriptModule", "resolveModuleCallback"); ScriptModule resolved = modulator->GetScriptModuleResolver()->Resolve( ToCoreStringWithNullCheck(specifier), referrer_record, exception_state); if (resolved.IsNull()) { DCHECK(exception_state.HadException()); return v8::MaybeLocal<v8::Module>(); } DCHECK(!exception_state.HadException()); return v8::MaybeLocal<v8::Module>(resolved.module_->NewLocal(isolate)); } } // namespace blink
35.413953
80
0.693853
[ "vector" ]
99c0b0d59c82dc8c5fe4c28cd207cea19aefd0a9
15,546
cc
C++
mindspore/lite/src/train/train_export.cc
Vincent34/mindspore
a39a60878a46e7e9cb02db788c0bca478f2fa6e5
[ "Apache-2.0" ]
1
2021-07-03T06:52:20.000Z
2021-07-03T06:52:20.000Z
mindspore/lite/src/train/train_export.cc
Vincent34/mindspore
a39a60878a46e7e9cb02db788c0bca478f2fa6e5
[ "Apache-2.0" ]
null
null
null
mindspore/lite/src/train/train_export.cc
Vincent34/mindspore
a39a60878a46e7e9cb02db788c0bca478f2fa6e5
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies 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. */ #define _STUB #include "src/train/train_export.h" #include <unistd.h> #include <sys/stat.h> #include <fstream> #include <utility> #include <functional> #include <map> #include <set> #include "schema/inner/model_generated.h" #include "src/train/train_utils.h" #include "src/common/quant_utils.h" #include "tools/common/storage.h" namespace mindspore { namespace lite { std::vector<uint8_t> TrainExport::CreateData(const lite::Tensor *tensor) { uint8_t *tensor_data = reinterpret_cast<uint8_t *>(tensor->data_c()); auto size = tensor->Size(); std::vector<uint8_t> data(tensor_data, tensor_data + size); return data; } bool TrainExport::NeedQuantization(const lite::Tensor *t) { return ((quant_type_ == QT_WEIGHT && t->shape().size() > 1) || ((quant_type_ == QT_DEFAULT) && (t->quant_params().size() > 0) && (t->quant_params().at(0).inited))); } schema::QuantType TrainExport::GetNodeQuantType(const kernel::LiteKernel *kernel) { if (std::any_of(kernel->in_tensors().cbegin(), kernel->in_tensors().cend(), [](const lite::Tensor *t) { return (t->IsConst() && (t->quant_params().size() > 0) && (t->quant_params().at(0).inited)); })) { return schema::QuantType_QUANT_WEIGHT; } return schema::QuantType_QUANT_NONE; } void TrainExport::TagQuantizedNodes() { if (quant_type_ == QT_WEIGHT) { for (auto &node : meta_graph_->nodes) { if (node->quantType != schema::QuantType_QUANT_WEIGHT) { for (auto t_idx : node->inputIndex) { if ((meta_graph_->allTensors.at(t_idx)->nodeType == NodeType_ValueNode) && (meta_graph_->allTensors.at(t_idx)->quantParams.size() > 0)) { node->quantType = schema::QuantType_QUANT_WEIGHT; } } } } } } int TrainExport::QuantTensorData(schema::TensorT *dest_tensor, const lite::Tensor *src_tensor) { int channels = 1; int bit_num = 8; if (src_tensor->quant_params().size() > 0) { channels = src_tensor->quant_params().size(); bit_num = src_tensor->quant_params().at(0).bitNum; } if (channels < 1) { MS_LOG(ERROR) << "Quant Params is empty"; return RET_ERROR; } int quant_max = QuantMax(bit_num, kNumberTypeInt8); int quant_min = QuantMin(bit_num, kNumberTypeInt8); std::vector<int8_t> data(src_tensor->ElementsNum()); std::vector<schema::QuantParamT> quant_params; STATUS ret = RET_OK; if (channels == kPerTensor) { ret = DoPerLayerQuant<int8_t>(reinterpret_cast<float *>(src_tensor->data_c()), src_tensor->ElementsNum(), &(quant_params), quant_max, quant_min, bit_num, false, &data); } else { bool channel_at_first = (src_tensor->shape().at(0) == channels); ret = DoPerChannelQuant<int8_t>(reinterpret_cast<float *>(src_tensor->data_c()), src_tensor->ElementsNum(), schema::QuantType_WeightQuant, &(quant_params), quant_max, quant_min, bit_num, false, &data, channels, channel_at_first); } if (ret == RET_QUANT_CONTINUE) { MS_LOG(DEBUG) << "No Need to quant per channel"; return RET_OK; } if (ret == RET_ERROR) { MS_LOG(ERROR) << "QuantTensorData error, channels = " << channels; return ret; } if (quant_params.empty()) { MS_LOG(ERROR) << "quant_params empty"; return RET_ERROR; } dest_tensor->data = std::vector<uint8_t>(data.data(), data.data() + data.size()); dest_tensor->dataType = kNumberTypeInt8; dest_tensor->quantParams.clear(); for (auto quant_param : quant_params) { dest_tensor->quantParams.emplace_back(std::make_unique<schema::QuantParamT>(quant_param)); } return RET_OK; } std::unique_ptr<schema::TensorT> TrainExport::CreateTensor(const mindspore::lite::Tensor *tensor, schema::Tensor *scTensor) { auto tensorT = std::make_unique<schema::TensorT>(); tensorT->nodeType = scTensor->nodeType(); tensorT->dims = tensor->shape(); tensorT->format = static_cast<schema::Format>(tensor->format()); tensorT->name = tensor->tensor_name(); tensorT->refCount = 0; tensorT->offset = 0; tensorT->dataType = tensor->data_type(); tensorT->enableHuffmanCode = false; if ((tensorT->nodeType == NodeType_ValueNode) && (scTensor->data() != nullptr) && (scTensor->data()->size() > 0)) { if (NeedQuantization(tensor)) { QuantTensorData(tensorT.get(), tensor); } else { tensorT->data = CreateData(tensor); } } tensorT->quantClusters = tensor->quant_clusters(); return tensorT; } Model::Node *TrainExport::FindNode(const mindspore::kernel::LiteKernel *kernel, const Model *model) { auto nodes = model->all_nodes_; auto it = std::find_if(nodes.begin(), nodes.end(), [&kernel](mindspore::lite::Model::Node *n) { return (kernel->name() == n->name_); }); if (it == nodes.end()) { return nullptr; } return *it; } int TrainExport::CreateAndAddCNode(const mindspore::kernel::LiteKernel *kernel, std::vector<uint32_t> inputIndex, std::vector<uint32_t> outputIndex, const Model *model) { auto cnode = CreateCNode(kernel, inputIndex, outputIndex, model); if (cnode == nullptr) { MS_LOG(ERROR) << "failed to create cnode"; return RET_ERROR; } meta_graph_->nodes.emplace_back(std::move(cnode)); if (!meta_graph_->subGraph.empty()) { meta_graph_->subGraph[0]->nodeIndices.push_back(meta_graph_->nodes.size() - 1); } return RET_OK; } std::unique_ptr<schema::CNodeT> TrainExport::CreateCNode(const mindspore::kernel::LiteKernel *kernel, std::vector<uint32_t> inputIndex, std::vector<uint32_t> outputIndex, const Model *model) { auto cnodeT = std::make_unique<schema::CNodeT>(); if (cnodeT == nullptr) { MS_LOG(ERROR) << " cannot allocate node"; return nullptr; } cnodeT->inputIndex = inputIndex; cnodeT->outputIndex = outputIndex; cnodeT->name = kernel->name(); cnodeT->quantType = GetNodeQuantType(kernel); // find kernel in model auto *node = FindNode(kernel, model); if (node == nullptr) { MS_LOG(ERROR) << "cannot find kernel " + kernel->name() + " in model"; return nullptr; } auto primitive = reinterpret_cast<schema::Primitive *>(const_cast<void *>(node->primitive_)); cnodeT->primitive = std::unique_ptr<schema::PrimitiveT>(primitive->UnPack()); return cnodeT; } int TrainExport::LoadModel(void *buf, size_t buf_size) { flatbuffers::Verifier verify((const uint8_t *)buf, buf_size); if (!schema::VerifyMetaGraphBuffer(verify)) { MS_LOG(ERROR) << "model flatbuffer verify fail"; return RET_ERROR; } meta_graph_ = schema::GetMetaGraph(buf)->UnPack(); meta_graph_->outputIndex.clear(); if (!meta_graph_->subGraph.empty()) { meta_graph_->subGraph[0]->outputIndices.clear(); } return RET_OK; } std::unique_ptr<schema::TensorT> TrainExport::CreateTransformTensor(size_t id) { auto &scTensor = meta_graph_->allTensors.at(id); auto tensorT = std::make_unique<schema::TensorT>(); if (tensorT == nullptr) { MS_LOG(ERROR) << "Could not create tensor "; return nullptr; } tensorT->nodeType = scTensor->nodeType; tensorT->dataType = scTensor->dataType; std::vector<int32_t> dims; std::vector<int32_t> val = {0, 2, 3, 1}; if (scTensor->dims.size() == 4) { for (size_t i = 0; i < val.size(); i++) { dims.push_back(scTensor->dims.at(val[i])); } tensorT->dims = dims; } else { tensorT->dims = scTensor->dims; } tensorT->format = schema::Format_NHWC; tensorT->name = scTensor->name + "_post"; tensorT->refCount = 0; tensorT->offset = 0; tensorT->enableHuffmanCode = false; return tensorT; } std::unique_ptr<schema::TensorT> TrainExport::CreateTransformConst(size_t last_id) { auto tensorT = std::make_unique<schema::TensorT>(); if (tensorT == nullptr) { MS_LOG(ERROR) << "Could not create tensor "; return nullptr; } tensorT->nodeType = lite::NodeType_ValueNode; tensorT->dataType = TypeId::kNumberTypeInt32; tensorT->dims = {4}; tensorT->format = schema::Format_NCHW; tensorT->name = "const-" + std::to_string(last_id); tensorT->refCount = 0; tensorT->offset = 0; tensorT->enableHuffmanCode = false; int32_t val[] = {0, 2, 3, 1}; uint8_t *valp = reinterpret_cast<uint8_t *>(val); tensorT->data = std::vector<uint8_t>(valp, valp + sizeof(val)); return tensorT; } std::unique_ptr<schema::CNodeT> TrainExport::CreateTransformNode(std::vector<uint32_t> inputIndex, std::vector<uint32_t> outputIndex, size_t id) { auto cnodeT = std::make_unique<schema::CNodeT>(); if (cnodeT == nullptr) { MS_LOG(ERROR) << "cannot allocate node"; return nullptr; } cnodeT->inputIndex = inputIndex; cnodeT->outputIndex = outputIndex; cnodeT->name = "transpose-" + std::to_string(id); cnodeT->quantType = schema::QuantType_QUANT_NONE; cnodeT->primitive = std::make_unique<schema::PrimitiveT>(); cnodeT->primitive->value.type = schema::PrimitiveType_Transpose; return cnodeT; } int TrainExport::AddTransformNode() { std::unordered_map<size_t, size_t> reconnect; size_t last_id = meta_graph_->allTensors.size(); size_t last_node = meta_graph_->nodes.size(); for (auto it : connect_) { auto tensorConst = CreateTransformConst(last_id); if (tensorConst == nullptr) { MS_LOG(ERROR) << "error in create tensor"; return RET_ERROR; } meta_graph_->allTensors.emplace_back(std::move(tensorConst)); // last_id if (!meta_graph_->subGraph.empty()) { meta_graph_->subGraph[0]->tensorIndices.push_back(meta_graph_->allTensors.size() - 1); } auto tensorT = CreateTransformTensor(it.second); if (tensorT == nullptr) { MS_LOG(ERROR) << "error in create tensor"; return RET_ERROR; } meta_graph_->allTensors.emplace_back(std::move(tensorT)); // last_id + 1 if (!meta_graph_->subGraph.empty()) { meta_graph_->subGraph[0]->tensorIndices.push_back(meta_graph_->allTensors.size() - 1); } std::vector<uint32_t> in_idx = {static_cast<uint32_t>(it.second), static_cast<uint32_t>(last_id)}; std::vector<uint32_t> out_idx = {static_cast<uint32_t>(last_id + 1)}; reconnect[it.first] = last_id + 1; auto cnode = CreateTransformNode(in_idx, out_idx, last_node); if (cnode == nullptr) { MS_LOG(ERROR) << "error in node creation"; return RET_ERROR; } meta_graph_->nodes.emplace_back(std::move(cnode)); if (!meta_graph_->subGraph.empty()) { meta_graph_->subGraph[0]->nodeIndices.push_back(meta_graph_->nodes.size() - 1); } } connect_ = reconnect; return RET_OK; } void TrainExport::PrepareRemap(int offset) { for (auto it : connect_) { remap_[it.first + offset] = it.second; } } int TrainExport::ExportNet(const std::vector<mindspore::kernel::LiteKernel *> &kernels, const std::vector<mindspore::lite::Tensor *> &tensors, const std::vector<std::string> &output_names, const Model *model, QuantizationType quant_type) { std::vector<size_t> map_index; std::set<size_t> out_set; int offset = meta_graph_->allTensors.size(); int tensor_idx = offset; quant_type_ = quant_type; if (meta_graph_ == nullptr) { int status = ExportInit(model->name_, model->version_); if (status != RET_OK) { return status; } } PrepareRemap(offset); for (const auto kernel : kernels) { std::vector<uint32_t> in_idx, out_idx; for (const auto tensor : kernel->in_tensors()) { size_t id = TSFindTensor(tensors, tensor) + offset; if (id == tensors.size()) { MS_LOG(ERROR) << "cannot find tensor " + tensor->ToString() + " in model"; return RET_ERROR; } auto it = remap_.find(id); if (it == remap_.end()) { remap_[id] = tensor_idx; in_idx.push_back(tensor_idx); map_index.push_back(id); tensor_idx++; } else { in_idx.push_back(it->second); } } for (const auto tensor : kernel->out_tensors()) { size_t id = TSFindTensor(tensors, tensor) + offset; if (id == tensors.size()) { MS_LOG(ERROR) << "cannot find tensor " + tensor->ToString() + " in model"; return RET_ERROR; } auto it = remap_.find(id); if (it == remap_.end()) { remap_[id] = tensor_idx; map_index.push_back(id); out_idx.push_back(tensor_idx); out_set.insert(tensor_idx); tensor_idx++; } else { out_idx.push_back(it->second); out_set.insert(it->second); } } auto ret = CreateAndAddCNode(kernel, in_idx, out_idx, model); if (ret != RET_OK) { MS_LOG(ERROR) << "failed to create cnode"; return ret; } } for (auto id : map_index) { size_t pid = id - offset; mindspore::lite::Tensor *tensor = tensors.at(pid); schema::Tensor *scTensor = model->all_tensors_.at(pid); auto tensorT = CreateTensor(tensor, scTensor); if (tensorT == nullptr) { MS_LOG(ERROR) << "error in tensor creation"; return RET_ERROR; } if (out_set.find(remap_[id]) == out_set.end()) { if (IsInputTensor(*tensorT)) { meta_graph_->inputIndex.push_back(remap_[id]); if (!meta_graph_->subGraph.empty()) { meta_graph_->subGraph[0]->inputIndices.push_back(remap_[id]); } } } // find output tensor if (std::find(output_names.begin(), output_names.end(), tensor->tensor_name()) != output_names.end()) { meta_graph_->outputIndex.push_back(remap_[id]); if (!meta_graph_->subGraph.empty()) { meta_graph_->subGraph[0]->outputIndices.push_back(remap_[id]); } } meta_graph_->allTensors.emplace_back(std::move(tensorT)); if (!meta_graph_->subGraph.empty()) { meta_graph_->subGraph[0]->tensorIndices.push_back(meta_graph_->allTensors.size() - 1); } } TagQuantizedNodes(); // do another loop to mark QUANT_WEIGHT_NODES return RET_OK; } int TrainExport::ExportInit(const std::string model_name, std::string version) { meta_graph_ = new (std::nothrow) schema::MetaGraphT(); if (meta_graph_ == nullptr) { MS_LOG(ERROR) << "cannot allocate meta_graph"; return RET_ERROR; } meta_graph_->fmkType = 3; meta_graph_->name = model_name; meta_graph_->version = version; return RET_OK; } int TrainExport::SaveToFile() { return Storage::Save(*meta_graph_, file_name_); } int TrainExport::IsInputTensor(const schema::TensorT &t) { int total_dims = std::accumulate(t.dims.begin(), t.dims.end(), 1, std::multiplies<int>()); return ((t.data.size() == 0) && (total_dims != 0)); } TrainExport::~TrainExport() { delete meta_graph_; } } // namespace lite } // namespace mindspore
36.492958
117
0.649235
[ "shape", "vector", "model" ]
99c1d0193fea9785e7c458c8d7b17bb9259ca117
5,578
hpp
C++
src/midend/KLT/include/KLT/Core/looptree.hpp
ouankou/rose
76f2a004bd6d8036bc24be2c566a14e33ba4f825
[ "BSD-3-Clause" ]
488
2015-01-09T08:54:48.000Z
2022-03-30T07:15:46.000Z
src/midend/KLT/include/KLT/Core/looptree.hpp
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
174
2015-01-28T18:41:32.000Z
2022-03-31T16:51:05.000Z
src/midend/KLT/include/KLT/Core/looptree.hpp
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
146
2015-04-27T02:48:34.000Z
2022-03-04T07:32:53.000Z
#ifndef __KLT_LOOPTREE_HPP__ #define __KLT_LOOPTREE_HPP__ #include <cstddef> #include <vector> #include <map> #include <set> #include <iostream> #include <string> class SgNode; class SgProject; class SgExpression; class SgStatement; class SgForStatement; class SgVariableSymbol; namespace KLT { namespace Descriptor { struct loop_t; struct tile_t; } namespace LoopTree { struct loop_t; enum kind_e { e_block, e_cond, e_loop, e_tile, e_stmt, e_ignored, e_unknown }; class extraction_context_t { public: typedef ::KLT::LoopTree::loop_t loop_t; typedef SgVariableSymbol vsym_t; typedef std::vector<vsym_t *> vsym_list_t; typedef std::set<vsym_t *> vsym_set_t; typedef std::map<SgForStatement *, size_t> loop_map_t; private: loop_map_t & loop_map; const vsym_set_t & data; size_t loop_cnt; private: vsym_set_t parameters; vsym_set_t iterators; vsym_set_t locals; public: extraction_context_t(loop_map_t & loop_map_, const vsym_set_t & data_); void addParameter(vsym_t * vsym); void addIterator (vsym_t * vsym); void addLocal (vsym_t * vsym); void processVarRefs(SgNode * node); size_t nextLoopID(); void registerLoop(SgForStatement *, loop_t *); const vsym_set_t & getParameters() const; }; struct loop_t; struct tile_t; struct node_t { kind_e kind; node_t * parent; node_t(kind_e kind_); virtual ~node_t(); static node_t * extract(SgStatement * stmt, extraction_context_t & ctx); virtual node_t * finalize() = 0; std::string getGraphVizLabel() const; virtual void toGraphViz(std::ostream & out, std::string indent) const = 0; virtual void collectLoops(std::vector<Descriptor::loop_t *> & loops, std::map<const loop_t *, Descriptor::loop_t *> & loop_translation_map) const = 0; virtual void collectTiles(std::vector<Descriptor::tile_t *> & tiles, const std::map<const loop_t *, Descriptor::loop_t *> & loop_translation_map) const = 0; }; struct block_t : public node_t { std::vector<node_t *> children; block_t(); virtual ~block_t(); static block_t * extract(SgStatement * stmt, extraction_context_t & ctx); virtual node_t * finalize(); virtual void toGraphViz(std::ostream & out, std::string indent) const; virtual void collectLoops(std::vector<Descriptor::loop_t *> & loops, std::map<const loop_t *, Descriptor::loop_t *> & loop_translation_map) const; virtual void collectTiles(std::vector<Descriptor::tile_t *> & tiles, const std::map<const loop_t *, Descriptor::loop_t *> & loop_translation_map) const; }; struct cond_t : public node_t { SgExpression * condition; node_t * branch_true; node_t * branch_false; cond_t(SgExpression * cond = NULL); virtual ~cond_t(); static cond_t * extract(SgStatement * stmt, extraction_context_t & ctx); virtual node_t * finalize(); virtual void toGraphViz(std::ostream & out, std::string indent) const; virtual void collectLoops(std::vector<Descriptor::loop_t *> & loops, std::map<const loop_t *, Descriptor::loop_t *> & loop_translation_map) const; virtual void collectTiles(std::vector<Descriptor::tile_t *> & tiles, const std::map<const loop_t *, Descriptor::loop_t *> & loop_translation_map) const; }; struct loop_t : public node_t { size_t id; // for ('iterator' = 'lower_bound'; 'iterator' <= 'upper_bound'; 'iterator' += 'stride') SgVariableSymbol * iterator; SgExpression * lower_bound; SgExpression * upper_bound; SgExpression * stride; node_t * body; loop_t( size_t id_, SgVariableSymbol * it = NULL, SgExpression * lb = NULL, SgExpression * ub = NULL, SgExpression * stride_ = NULL ); virtual ~loop_t(); static loop_t * extract(SgStatement * stmt, extraction_context_t & ctx); virtual node_t * finalize(); virtual void toGraphViz(std::ostream & out, std::string indent) const; virtual void collectLoops(std::vector<Descriptor::loop_t *> & loops, std::map<const loop_t *, Descriptor::loop_t *> & loop_translation_map) const; virtual void collectTiles(std::vector<Descriptor::tile_t *> & tiles, const std::map<const loop_t *, Descriptor::loop_t *> & loop_translation_map) const; }; struct stmt_t : public node_t { SgStatement * statement; stmt_t(SgStatement * stmt = NULL); virtual ~stmt_t(); static stmt_t * extract(SgStatement * stmt, extraction_context_t & ctx); virtual node_t * finalize(); virtual void toGraphViz(std::ostream & out, std::string indent) const; virtual void collectLoops(std::vector<Descriptor::loop_t *> & loops, std::map<const loop_t *, Descriptor::loop_t *> & loop_translation_map) const; virtual void collectTiles(std::vector<Descriptor::tile_t *> & tiles, const std::map<const loop_t *, Descriptor::loop_t *> & loop_translation_map) const; }; struct tile_t : public node_t { size_t id; unsigned long kind; size_t order; SgExpression * param; loop_t * loop; size_t tile_id; // ID in the loop tile_t * next_tile; node_t * next_node; tile_t(size_t id_, unsigned long kind_, size_t order_, SgExpression * param_, loop_t * loop_, size_t tile_id_); virtual ~tile_t(); virtual node_t * finalize(); virtual void toGraphViz(std::ostream & out, std::string indent) const; virtual void collectLoops(std::vector<Descriptor::loop_t *> & loops, std::map<const loop_t *, Descriptor::loop_t *> & loop_translation_map) const; virtual void collectTiles(std::vector<Descriptor::tile_t *> & tiles, const std::map<const loop_t *, Descriptor::loop_t *> & loop_translation_map) const; }; } } #endif /* __KLT_LOOPTREE_HPP__ */
27.613861
158
0.714055
[ "vector" ]
99c9302f02df467d82395bc4ed0a9e219d904f20
5,146
cpp
C++
Tools/CacheSimulator/CacheSetConstructor.cpp
ronichoudhury/mtvx
379cfbfd7a55440e6862526c1817dfad5c6ce171
[ "Apache-2.0" ]
2
2018-07-30T17:02:50.000Z
2020-06-12T03:01:21.000Z
Tools/CacheSimulator/CacheSetConstructor.cpp
waxlamp/mtvx
379cfbfd7a55440e6862526c1817dfad5c6ce171
[ "Apache-2.0" ]
null
null
null
Tools/CacheSimulator/CacheSetConstructor.cpp
waxlamp/mtvx
379cfbfd7a55440e6862526c1817dfad5c6ce171
[ "Apache-2.0" ]
null
null
null
// Copyright 2011 A.N.M. Imroz Choudhury // // CacheConstructor.cpp // MTV headers. #include <Core/Util/Boost.h> #include <Tools/CacheSimulator/CacheConstructor.h> #include <Tools/CacheSimulator/CacheSetConstructor.h> using Daly::CacheConstructor; using Daly::CacheSetConstructor; // TinyXML headers. #define TIXML_USE_STL #include <tinyxml.h> // System headers. #include <map> CacheSetConstructor::CacheSetConstructor(const std::string& filename, const std::string& bsfile, unsigned numstreams){ // Create an XML document object. TiXmlDocument doc(filename.c_str()); if(!doc.LoadFile()){ *this << "error: could not open file '" << filename << "' for reading."; return; } // Parse the file. // // Begin by checking the name of the root element. TiXmlElement *root = doc.RootElement(); if(std::string(root->Value()) != "CacheSet"){ *this << "error: XML document '" << filename << "' does not contain a root CacheSet element."; return; } // Get the blocksize attribute. const char *text = root->Attribute("blocksize"); if(!text){ *this << "error: CacheSet element does not contain 'blocksize' attribute."; return; } unsigned blocksize = lexical_cast<unsigned>(text); //std::cout << "blocksize = " << blocksize << std::endl; // Find the SharedCacheLevels element and make sure it appears at most // once. TiXmlElement *shared_element = root->FirstChildElement("SharedCacheLevels"); if(shared_element and shared_element->NextSiblingElement("SharedCacheLevels")){ *this << "error: multiple SharedCacheLevels elements in file '" << filename << "'."; return; } // Process it if it's there. std::map<std::string, CacheLevel::ptr> shared_levels; if(shared_element){ // The shared element consists of several CacheLevel elements. for(TiXmlElement *e = shared_element->FirstChildElement("CacheLevel"); e; e = e->NextSiblingElement("CacheLevel")){ // Name attribute. const char *text = e->Attribute("name"); if(!text){ *this << "error: CacheLevel element missing 'name' attribute."; return; } std::string name(text); //std::cout << "Shared Cache Level: name = " << name << std::endl; // Block count attribute. text = e->Attribute("num_blocks"); if(!text){ *this << "error: CacheLevel element missing 'num_blocks' attribute."; return; } unsigned num_blocks = lexical_cast<unsigned>(text); //std::cout << "num_blocks = " << num_blocks << std::endl; // Associativity attribute. text = e->Attribute("associativity"); if(!text){ *this << "error: CacheLevel element missing 'associativity' attribute."; return; } unsigned associativity = lexical_cast<unsigned>(text); //std::cout << "associativity = " << associativity << std::endl; // Write policy attribute. text = e->Attribute("write_policy"); WritePolicy policy; if(!text){ *this << "error: CacheLevel element missing 'write_policy' attribute."; return; } if(std::string(text) == "WriteThrough"){ policy = WriteThrough; } else if(std::string(text) == "WriteBack"){ policy = WriteBack; } else{ *this << "error: CacheLevel's write_policy is '" << text << "'; must be either 'WriteThrough' or 'WriteBack'."; return; } //std::cout << "write_policy = " << text << std::endl; // Construct a cache level object and store it in the shared // map. shared_levels[name] = CacheLevel::ptr(new CacheLevel(blocksize*num_blocks, blocksize, associativity, policy)); } } // Get the containing path for the XML file (relative or absolute). const boost::filesystem::path filepath(filename); // const std::string location = boost::filesystem::path(filename).parent_path().string(); const std::string location = filepath.parent_path().string(); // Create a cache object for each Cache element appearing in the // file. ModtimeTable::ptr modtime = boost::make_shared<ModtimeTable>(); for(TiXmlElement *e = root->FirstChildElement("Cache"); e; e = e->NextSiblingElement("Cache")){ const char *text = e->Attribute("filename"); if(!text){ *this << "error: Cache element has no 'filename' attribute."; return; } std::string cache_file(text); // If the filename is not absolute, prepend the containing path of // the original file to its name. // // boost::filesystem::path p(text); // if(!p.is_absolute()){ if(cache_file.length() > 0 and cache_file[0] != '/'){ cache_file = location + "/" + cache_file; } //std::cout << "cache, filename = " << cache_file << std::endl; // Create a cache and store its pointer in the return list. CacheConstructor c(cache_file, shared_levels); // TODO(choudhury): error checking on cache construction. // Use a shared modtime table for all the caches in the set. Cache::ptr cachep = c.constructCache(TraceReader::ptr(), modtime); if(cachep){ cacheset.push_back(cachep); } } }
33.855263
119
0.643995
[ "object" ]
99caf14801da3c06ae5a04115cea1915d6a21e3f
33,754
cpp
C++
src/CifUtils.cpp
PDB-REDO/libcifpp
f97e742daa7c1cfd0670ad00d3aef004708a3461
[ "BSD-2-Clause" ]
7
2021-01-12T07:00:04.000Z
2022-03-11T08:44:14.000Z
src/CifUtils.cpp
PDB-REDO/libcifpp
f97e742daa7c1cfd0670ad00d3aef004708a3461
[ "BSD-2-Clause" ]
12
2021-03-11T17:53:45.000Z
2022-02-09T15:06:04.000Z
src/CifUtils.cpp
PDB-REDO/libcifpp
f97e742daa7c1cfd0670ad00d3aef004708a3461
[ "BSD-2-Clause" ]
7
2021-02-08T00:45:31.000Z
2021-12-06T22:37:22.000Z
/*- * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2020 NKI/AVL, Netherlands Cancer Institute * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <atomic> #include <chrono> #include <cmath> #include <cstdio> #include <filesystem> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <mutex> #include <regex> #include <sstream> #include <thread> #include <tuple> #if defined(_MSC_VER) #define TERM_WIDTH 80 #else #include <sys/ioctl.h> #include <termios.h> #endif #include <boost/algorithm/string.hpp> #include "cif++/CifUtils.hpp" namespace ba = boost::algorithm; namespace fs = std::filesystem; // -------------------------------------------------------------------- namespace cif { extern int VERBOSE; // -------------------------------------------------------------------- std::string get_version_nr() { const std::regex rxVersionNr1(R"(build-(\d+)-g[0-9a-f]{7}(-dirty)?)"), rxVersionNr2(R"(libcifpp-version: (\d+\.\d+\.\d+))"); #include "revision.hpp" struct membuf : public std::streambuf { membuf(char *data, size_t length) { this->setg(data, data, data + length); } } buffer(const_cast<char *>(kRevision), sizeof(kRevision)); std::istream is(&buffer); std::string line, result; while (getline(is, line)) { std::smatch m; if (std::regex_match(line, m, rxVersionNr1)) { result = m[1]; if (m[2].matched) result += '*'; break; } // always the first, replace with more specific if followed by the other info if (std::regex_match(line, m, rxVersionNr2)) result = m[1]; } return result; } // -------------------------------------------------------------------- // This really makes a difference, having our own tolower routines const uint8_t kCharToLowerMap[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff}; // -------------------------------------------------------------------- bool iequals(const std::string &a, const std::string &b) { bool result = a.length() == b.length(); for (auto ai = a.begin(), bi = b.begin(); result and ai != a.end() and bi != b.end(); ++ai, ++bi) result = tolower(*ai) == tolower(*bi); return result; } bool iequals(const char *a, const char *b) { bool result = true; for (; result and *a and *b; ++a, ++b) result = tolower(*a) == tolower(*b); return result and *a == *b; } int icompare(const std::string &a, const std::string &b) { int d = 0; auto ai = a.begin(), bi = b.begin(); for (; d == 0 and ai != a.end() and bi != b.end(); ++ai, ++bi) d = tolower(*ai) - tolower(*bi); if (d == 0) { if (ai != a.end()) d = 1; else if (bi != b.end()) d = -1; } return d; } int icompare(const char *a, const char *b) { int d = 0; for (; d == 0 and *a != 0 and *b != 0; ++a, ++b) d = tolower(*a) - tolower(*b); if (d == 0) { if (*a != 0) d = 1; else if (*b != 0) d = -1; } return d; } void toLower(std::string &s) { for (auto &c : s) c = tolower(c); } std::string toLowerCopy(const std::string &s) { std::string result(s); for (auto &c : result) c = tolower(c); return result; } // -------------------------------------------------------------------- std::tuple<std::string, std::string> splitTagName(const std::string &tag) { if (tag.empty()) throw std::runtime_error("empty tag"); if (tag[0] != '_') throw std::runtime_error("tag does not start with underscore"); auto s = tag.find('.'); if (s == std::string::npos) throw std::runtime_error("tag does not contain dot"); return std::tuple<std::string, std::string>{ tag.substr(1, s - 1), tag.substr(s + 1)}; } // -------------------------------------------------------------------- std::string cifIdForNumber(int number) { std::string result; if (number >= 26 * 26 * 26) result = 'L' + std::to_string(number); else { if (number >= 26 * 26) { int v = number / (26 * 26); result += char('A' - 1 + v); number %= (26 * 26); } if (number >= 26) { int v = number / 26; result += char('A' - 1 + v); number %= 26; } result += char('A' + number); } assert(not result.empty()); return result; } // -------------------------------------------------------------------- // Simplified line breaking code taken from a decent text editor. // In this case, simplified means it only supports ASCII. enum LineBreakClass { kLBC_OpenPunctuation, kLBC_ClosePunctuation, kLBC_CloseParenthesis, kLBC_Quotation, kLBC_NonBreaking, kLBC_Nonstarter, kLBC_Exlamation, kLBC_SymbolAllowingBreakAfter, kLBC_InfixNumericSeparator, kLBC_PrefixNumeric, kLBC_PostfixNumeric, kLBC_Numeric, kLBC_Alphabetic, kLBC_Ideographic, kLBC_Inseperable, kLBC_Hyphen, kLBC_BreakAfter, kLBC_BreakBefor, kLBC_BreakOpportunityBeforeAndAfter, kLBC_ZeroWidthSpace, kLBC_CombiningMark, kLBC_WordJoiner, kLBC_HangulLVSyllable, kLBC_HangulLVTSyllable, kLBC_HangulLJamo, kLBC_HangulVJamo, kLBC_HangulTJamo, kLBC_MandatoryBreak, kLBC_CarriageReturn, kLBC_LineFeed, kLBC_NextLine, kLBC_Surrogate, kLBC_Space, kLBC_ContigentBreakOpportunity, kLBC_Ambiguous, kLBC_ComplexContext, kLBC_Unknown }; const LineBreakClass kASCII_LBTable[128] = { kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_BreakAfter, kLBC_LineFeed, kLBC_MandatoryBreak, kLBC_MandatoryBreak, kLBC_CarriageReturn, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_CombiningMark, kLBC_Space, kLBC_Exlamation, kLBC_Quotation, kLBC_Alphabetic, kLBC_PrefixNumeric, kLBC_PostfixNumeric, kLBC_Alphabetic, kLBC_Quotation, kLBC_OpenPunctuation, kLBC_CloseParenthesis, kLBC_Alphabetic, kLBC_PrefixNumeric, // comma treated differently here, it is not a numeric separator in PDB kLBC_SymbolAllowingBreakAfter /* kLBC_InfixNumericSeparator */, kLBC_Hyphen, kLBC_InfixNumericSeparator, kLBC_SymbolAllowingBreakAfter, kLBC_Numeric, kLBC_Numeric, kLBC_Numeric, kLBC_Numeric, kLBC_Numeric, kLBC_Numeric, kLBC_Numeric, kLBC_Numeric, kLBC_Numeric, kLBC_Numeric, kLBC_InfixNumericSeparator, kLBC_InfixNumericSeparator, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Exlamation, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_OpenPunctuation, kLBC_PrefixNumeric, kLBC_CloseParenthesis, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_Alphabetic, kLBC_OpenPunctuation, kLBC_BreakAfter, kLBC_ClosePunctuation, kLBC_Alphabetic, kLBC_CombiningMark}; std::string::const_iterator nextLineBreak(std::string::const_iterator text, std::string::const_iterator end) { if (text == end) return text; enum breakAction { DBK = 0, // direct break (blank in table) IBK, // indirect break (% in table) PBK, // prohibited break (^ in table) CIB, // combining indirect break CPB // combining prohibited break }; const breakAction brkTable[27][27] = { // OP CL CP QU GL NS EX SY IS PR PO NU AL ID IN HY BA BB B2 ZW CM WJ H2 H3 JL JV JT /* OP */ {PBK, PBK, PBK, PBK, PBK, PBK, PBK, PBK, PBK, PBK, PBK, PBK, PBK, PBK, PBK, PBK, PBK, PBK, PBK, PBK, CPB, PBK, PBK, PBK, PBK, PBK, PBK}, /* CL */ {DBK, PBK, PBK, IBK, IBK, PBK, PBK, PBK, PBK, IBK, IBK, DBK, DBK, DBK, DBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, DBK}, /* CP */ {DBK, PBK, PBK, IBK, IBK, PBK, PBK, PBK, PBK, IBK, IBK, IBK, IBK, DBK, DBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, DBK}, /* QU */ {PBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, PBK, CIB, PBK, IBK, IBK, IBK, IBK, IBK}, /* GL */ {IBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, PBK, CIB, PBK, IBK, IBK, IBK, IBK, IBK}, /* NS */ {DBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, DBK, DBK, DBK, DBK, DBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, DBK}, /* EX */ {DBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, DBK, DBK, DBK, DBK, DBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, DBK}, /* SY */ {DBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, DBK, IBK, DBK, DBK, DBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, DBK}, /* IS */ {DBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, DBK, IBK, IBK, DBK, DBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, DBK}, /* PR */ {IBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, DBK, IBK, IBK, IBK, DBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, IBK, IBK, IBK, IBK, IBK}, /* PO */ {IBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, DBK, IBK, IBK, DBK, DBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, DBK}, /* NU */ {DBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, IBK, IBK, IBK, IBK, DBK, IBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, DBK}, /* AL */ {DBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, DBK, IBK, IBK, DBK, IBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, DBK}, /* ID */ {DBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, IBK, DBK, DBK, DBK, IBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, DBK}, /* IN */ {DBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, DBK, DBK, DBK, DBK, IBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, DBK}, /* HY */ {DBK, PBK, PBK, IBK, DBK, IBK, PBK, PBK, PBK, DBK, DBK, IBK, DBK, DBK, DBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, DBK}, /* BA */ {DBK, PBK, PBK, IBK, DBK, IBK, PBK, PBK, PBK, DBK, DBK, DBK, DBK, DBK, DBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, DBK}, /* BB */ {IBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, PBK, CIB, PBK, IBK, IBK, IBK, IBK, IBK}, /* B2 */ {DBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, DBK, DBK, DBK, DBK, DBK, IBK, IBK, DBK, PBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, DBK}, /* ZW */ {DBK, DBK, DBK, DBK, DBK, DBK, DBK, DBK, DBK, DBK, DBK, DBK, DBK, DBK, DBK, DBK, DBK, DBK, DBK, PBK, DBK, DBK, DBK, DBK, DBK, DBK, DBK}, /* CM */ {DBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, DBK, IBK, IBK, DBK, IBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, DBK}, /* WJ */ {IBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, IBK, PBK, CIB, PBK, IBK, IBK, IBK, IBK, IBK}, /* H2 */ {DBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, IBK, DBK, DBK, DBK, IBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, IBK, IBK}, /* H3 */ {DBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, IBK, DBK, DBK, DBK, IBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, IBK}, /* JL */ {DBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, IBK, DBK, DBK, DBK, IBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, IBK, IBK, IBK, IBK, DBK}, /* JV */ {DBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, IBK, DBK, DBK, DBK, IBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, IBK, IBK}, /* JT */ {DBK, PBK, PBK, IBK, IBK, IBK, PBK, PBK, PBK, DBK, IBK, DBK, DBK, DBK, IBK, IBK, IBK, DBK, DBK, PBK, CIB, PBK, DBK, DBK, DBK, DBK, IBK}, }; uint8_t ch = static_cast<uint8_t>(*text); LineBreakClass cls; if (ch == '\n') cls = kLBC_MandatoryBreak; else if (ch < 128) { cls = kASCII_LBTable[ch]; if (cls > kLBC_MandatoryBreak and cls != kLBC_Space) // duh... cls = kLBC_Alphabetic; } else cls = kLBC_Unknown; if (cls == kLBC_Space) cls = kLBC_WordJoiner; LineBreakClass ncls = cls; while (++text != end and cls != kLBC_MandatoryBreak) { ch = *text; LineBreakClass lcls = ncls; if (ch == '\n') { ++text; break; } ncls = kASCII_LBTable[ch]; if (ncls == kLBC_Space) continue; breakAction brk = brkTable[cls][ncls]; if (brk == DBK or (brk == IBK and lcls == kLBC_Space)) break; cls = ncls; } return text; } std::vector<std::string> wrapLine(const std::string &text, size_t width) { std::vector<std::string> result; std::vector<size_t> offsets = {0}; auto b = text.begin(); while (b != text.end()) { auto e = nextLineBreak(b, text.end()); offsets.push_back(e - text.begin()); b = e; } size_t count = offsets.size() - 1; std::vector<size_t> minima(count + 1, 1000000); minima[0] = 0; std::vector<size_t> breaks(count + 1, 0); for (size_t i = 0; i < count; ++i) { size_t j = i + 1; while (j <= count) { size_t w = offsets[j] - offsets[i]; if (w > width) break; while (w > 0 and isspace(text[offsets[i] + w - 1])) --w; size_t cost = minima[i]; if (j < count) // last line may be shorter cost += (width - w) * (width - w); if (cost < minima[j]) { minima[j] = cost; breaks[j] = i; } ++j; } } size_t j = count; while (j > 0) { size_t i = breaks[j]; result.push_back(text.substr(offsets[i], offsets[j] - offsets[i])); j = i; } reverse(result.begin(), result.end()); return result; } std::vector<std::string> wordWrap(const std::string &text, size_t width) { std::vector<std::string> paragraphs; ba::split(paragraphs, text, ba::is_any_of("\n")); std::vector<std::string> result; for (auto &p : paragraphs) { if (p.empty()) { result.push_back(""); continue; } auto lines = wrapLine(p, width); result.insert(result.end(), lines.begin(), lines.end()); } return result; } // -------------------------------------------------------------------- #ifdef _MSC_VER } #include <Windows.h> #include <libloaderapi.h> #include <wincon.h> #include <codecvt> namespace cif { uint32_t get_terminal_width() { return TERM_WIDTH; } std::string GetExecutablePath() { WCHAR buffer[4096]; DWORD n = ::GetModuleFileNameW(nullptr, buffer, sizeof(buffer) / sizeof(WCHAR)); if (n == 0) throw std::runtime_error("could not get exe path"); std::wstring ws(buffer); // convert from utf16 to utf8 std::wstring_convert<std::codecvt_utf8<wchar_t>> conv1; std::string u8str = conv1.to_bytes(ws); return u8str; } #else uint32_t get_terminal_width() { uint32_t result = 80; if (isatty(STDOUT_FILENO)) { struct winsize w; ioctl(0, TIOCGWINSZ, &w); result = w.ws_col; } return result; } std::string get_executable_path() { using namespace std::literals; char path[PATH_MAX] = ""; if (readlink("/proc/self/exe", path, sizeof(path)) == -1) throw std::runtime_error("could not get exe path "s + strerror(errno)); return {path}; } #endif // -------------------------------------------------------------------- struct ProgressImpl { ProgressImpl(int64_t inMax, const std::string &inAction) : mMax(inMax) , mConsumed(0) , mAction(inAction) , mMessage(inAction) , mThread(std::bind(&ProgressImpl::Run, this)) { } void Run(); void Stop() { mStop = true; if (mThread.joinable()) mThread.join(); } void PrintProgress(); void PrintDone(); int64_t mMax; std::atomic<int64_t> mConsumed; int64_t mLastConsumed = 0; int mSpinnerIndex = 0; std::string mAction, mMessage; std::mutex mMutex; std::thread mThread; std::chrono::time_point<std::chrono::system_clock> mStart = std::chrono::system_clock::now(); bool mStop = false; }; void ProgressImpl::Run() { bool printedAny = false; try { for (;;) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::unique_lock lock(mMutex); if (mStop or mConsumed == mMax) break; auto elapsed = std::chrono::system_clock::now() - mStart; if (elapsed < std::chrono::seconds(5)) continue; PrintProgress(); printedAny = true; } } catch (...) { } if (printedAny) PrintDone(); } void ProgressImpl::PrintProgress() { // const char* kBlocks[] = { // " ", // 0 // u8"\u258F", // 1 // u8"\u258E", // 2 // u8"\u258D", // 3 // u8"\u258C", // 4 // u8"\u258B", // 5 // u8"\u258A", // 6 // u8"\u2589", // 7 // u8"\u2588", // 8 // }; const char *kBlocks[] = { " ", // 0 " ", // 1 " ", // 2 "-", // 3 "-", // 4 "-", // 5 "=", // 6 "=", // 7 "=", // 8 }; uint32_t width = get_terminal_width(); std::string msg; msg.reserve(width + 1); if (mMessage.length() <= 20) { msg = mMessage; if (msg.length() < 20) msg.append(20 - msg.length(), ' '); } else msg = mMessage.substr(0, 17) + "..."; msg += " |"; int64_t consumed = mConsumed; float progress = static_cast<float>(consumed) / mMax; int pi = static_cast<int>(std::ceil(progress * 33 * 8)); // int tw = width - 28; // int twd = static_cast<int>(tw * progress + 0.5f); // msg.append(twd, '='); // msg.append(tw - twd, ' '); for (int i = 0; i < 33; ++i) { if (pi <= 0) msg += kBlocks[0]; else if (pi >= 8) msg += kBlocks[8]; else msg += kBlocks[pi]; pi -= 8; } msg.append("| "); // const char kSpinner[] = { '|', '/', '-', '\\' }; const char kSpinner[] = {' ', '.', 'o', 'O', '0', 'O', 'o', '.'}; const size_t kSpinnerCount = sizeof(kSpinner); if (mLastConsumed < consumed) { mLastConsumed = consumed; mSpinnerIndex = (mSpinnerIndex + 1) % kSpinnerCount; } const char spinner[2] = {kSpinner[mSpinnerIndex], 0}; msg.append(spinner); // int perc = static_cast<int>(100 * progress); // if (perc < 100) // msg += ' '; // if (perc < 10) // msg += ' '; // msg += to_string(perc); // msg += '%'; std::cout << '\r' << msg; std::cout.flush(); } namespace { std::ostream &operator<<(std::ostream &os, const std::chrono::duration<double> &t) { uint64_t s = static_cast<uint64_t>(std::trunc(t.count())); if (s > 24 * 60 * 60) { auto days = s / (24 * 60 * 60); os << days << "d "; s %= 24 * 60 * 60; } if (s > 60 * 60) { auto hours = s / (60 * 60); os << hours << "h "; s %= 60 * 60; } if (s > 60) { auto minutes = s / 60; os << minutes << "m "; s %= 60; } double ss = s + 1e-6 * (t.count() - s); os << std::fixed << std::setprecision(1) << ss << 's'; return os; } } // namespace void ProgressImpl::PrintDone() { std::chrono::duration<double> elapsed = std::chrono::system_clock::now() - mStart; std::ostringstream msgstr; msgstr << mAction << " done in " << elapsed << " cpu / %ws wall"; auto msg = msgstr.str(); uint32_t width = get_terminal_width(); if (msg.length() < width) msg += std::string(width - msg.length(), ' '); std::cout << '\r' << msg << std::endl; } Progress::Progress(int64_t inMax, const std::string &inAction) : mImpl(nullptr) { if (isatty(STDOUT_FILENO)) mImpl = new ProgressImpl(inMax, inAction); } Progress::~Progress() { if (mImpl != nullptr) mImpl->Stop(); delete mImpl; } void Progress::consumed(int64_t inConsumed) { if (mImpl != nullptr and (mImpl->mConsumed += inConsumed) >= mImpl->mMax) { mImpl->Stop(); } } void Progress::progress(int64_t inProgress) { if (mImpl != nullptr and (mImpl->mConsumed = inProgress) >= mImpl->mMax) { mImpl->Stop(); } } void Progress::message(const std::string &inMessage) { if (mImpl != nullptr) { std::unique_lock lock(mImpl->mMutex); mImpl->mMessage = inMessage; } } } // namespace cif // -------------------------------------------------------------------- // // Try to find a named resource. Can be either a local file with this name, // a file located in our cache directory or a resource linked in with mrc. // // We have a special, private version of mrsrc here. To be able to create // shared libraries and still be able to link when there's no mrc used. namespace mrsrc { /// \brief Internal data structure as generated by mrc struct rsrc_imp { unsigned int m_next; unsigned int m_child; unsigned int m_name; unsigned int m_size; unsigned int m_data; }; } // namespace mrsrc #if _MSC_VER extern "C" const mrsrc::rsrc_imp* gResourceIndexDefault[1] = {}; extern "C" const char* gResourceDataDefault[1] = {}; extern "C" const char* gResourceNameDefault[1] = {}; extern "C" const mrsrc::rsrc_imp gResourceIndex[]; extern "C" const char gResourceData[]; extern "C" const char gResourceName[]; #pragma comment(linker, "/alternatename:gResourceIndex=gResourceIndexDefault") #pragma comment(linker, "/alternatename:gResourceData=gResourceDataDefault") #pragma comment(linker, "/alternatename:gResourceName=gResourceNameDefault") #else extern const __attribute__((weak)) mrsrc::rsrc_imp gResourceIndex[]; extern const __attribute__((weak)) char gResourceData[]; extern const __attribute__((weak)) char gResourceName[]; const mrsrc::rsrc_imp gResourceIndex[1] = {}; const char gResourceData[1] = {}; const char gResourceName[1] = {}; #endif namespace mrsrc { class rsrc_data { public: static rsrc_data &instance() { static rsrc_data s_instance; return s_instance; } const rsrc_imp *index() const { return m_index; } const char *data(unsigned int offset) const { return m_data + offset; } const char *name(unsigned int offset) const { return m_name + offset; } private: rsrc_data() { if (gResourceIndex and (gResourceIndex[0].m_child > 0 or gResourceIndex[0].m_size > 0) and gResourceIndex and gResourceName) { m_index = gResourceIndex; m_data = gResourceData; m_name = gResourceName; } } rsrc_imp m_dummy = {}; const rsrc_imp *m_index = &m_dummy; const char *m_data = ""; const char *m_name = ""; }; /// \brief Class mrsrc::rsrc contains a pointer to the data in the /// resource, as well as offering an iterator interface to its /// children. class rsrc { public: rsrc() : m_impl(rsrc_data::instance().index()) { } rsrc(const rsrc &other) : m_impl(other.m_impl) { } rsrc &operator=(const rsrc &other) { m_impl = other.m_impl; return *this; } rsrc(std::filesystem::path path); std::string name() const { return rsrc_data::instance().name(m_impl->m_name); } const char *data() const { return rsrc_data::instance().data(m_impl->m_data); } unsigned long size() const { return m_impl->m_size; } explicit operator bool() const { return m_impl != NULL and m_impl->m_size > 0; } template <typename RSRC> class iterator_t { public: using iterator_category = std::input_iterator_tag; using value_type = RSRC; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; iterator_t(const rsrc_imp *cur) : m_cur(cur) { } iterator_t(const iterator_t &i) : m_cur(i.m_cur) { } iterator_t &operator=(const iterator_t &i) { m_cur = i.m_cur; return *this; } reference operator*() { return m_cur; } pointer operator->() { return &m_cur; } iterator_t &operator++() { if (m_cur.m_impl->m_next) m_cur.m_impl = rsrc_data::instance().index() + m_cur.m_impl->m_next; else m_cur.m_impl = nullptr; return *this; } iterator_t operator++(int) { auto tmp(*this); this->operator++(); return tmp; } bool operator==(const iterator_t &rhs) const { return m_cur.m_impl == rhs.m_cur.m_impl; } bool operator!=(const iterator_t &rhs) const { return m_cur.m_impl != rhs.m_cur.m_impl; } private: value_type m_cur; }; using iterator = iterator_t<rsrc>; iterator begin() const { const rsrc_imp *impl = nullptr; if (m_impl and m_impl->m_child) impl = rsrc_data::instance().index() + m_impl->m_child; return iterator(impl); } iterator end() const { return iterator(nullptr); } private: rsrc(const rsrc_imp *imp) : m_impl(imp) { } const rsrc_imp *m_impl; }; inline rsrc::rsrc(std::filesystem::path p) { m_impl = rsrc_data::instance().index(); // using std::filesytem::path would have been natural here of course... auto pb = p.begin(); auto pe = p.end(); while (m_impl != nullptr and pb != pe) { auto name = *pb++; const rsrc_imp *impl = nullptr; for (rsrc child : *this) { if (child.name() == name) { impl = child.m_impl; break; } } m_impl = impl; } if (pb != pe) // not found m_impl = nullptr; } // -------------------------------------------------------------------- template <typename CharT, typename Traits> class basic_streambuf : public std::basic_streambuf<CharT, Traits> { public: typedef CharT char_type; typedef Traits traits_type; typedef typename traits_type::int_type int_type; typedef typename traits_type::pos_type pos_type; typedef typename traits_type::off_type off_type; /// \brief constructor taking a \a path to the resource in memory basic_streambuf(const std::string &path) : m_rsrc(path) { init(); } /// \brief constructor taking a \a rsrc basic_streambuf(const rsrc &rsrc) : m_rsrc(rsrc) { init(); } basic_streambuf(const basic_streambuf &) = delete; basic_streambuf(basic_streambuf &&rhs) : basic_streambuf(rhs.m_rsrc) { } basic_streambuf &operator=(const basic_streambuf &) = delete; basic_streambuf &operator=(basic_streambuf &&rhs) { swap(rhs); return *this; } void swap(basic_streambuf &rhs) { std::swap(m_begin, rhs.m_begin); std::swap(m_end, rhs.m_end); std::swap(m_current, rhs.m_current); } private: void init() { m_begin = reinterpret_cast<const char_type *>(m_rsrc.data()); m_end = reinterpret_cast<const char_type *>(m_rsrc.data() + m_rsrc.size()); m_current = m_begin; } int_type underflow() { if (m_current == m_end) return traits_type::eof(); return traits_type::to_int_type(*m_current); } int_type uflow() { if (m_current == m_end) return traits_type::eof(); return traits_type::to_int_type(*m_current++); } int_type pbackfail(int_type ch) { if (m_current == m_begin or (ch != traits_type::eof() and ch != m_current[-1])) return traits_type::eof(); return traits_type::to_int_type(*--m_current); } std::streamsize showmanyc() { assert(std::less_equal<const char *>()(m_current, m_end)); return m_end - m_current; } pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which) { switch (dir) { case std::ios_base::beg: m_current = m_begin + off; break; case std::ios_base::end: m_current = m_end + off; break; case std::ios_base::cur: m_current += off; break; default: break; } if (m_current < m_begin) m_current = m_begin; if (m_current > m_end) m_current = m_end; return m_current - m_begin; } pos_type seekpos(pos_type pos, std::ios_base::openmode which) { m_current = m_begin + pos; if (m_current < m_begin) m_current = m_begin; if (m_current > m_end) m_current = m_end; return m_current - m_begin; } private: rsrc m_rsrc; const char_type *m_begin; const char_type *m_end; const char_type *m_current; }; using streambuf = basic_streambuf<char, std::char_traits<char>>; // -------------------------------------------------------------------- // class mrsrc::istream template <typename CharT, typename Traits> class basic_istream : public std::basic_istream<CharT, Traits> { public: typedef CharT char_type; typedef Traits traits_type; typedef typename traits_type::int_type int_type; typedef typename traits_type::pos_type pos_type; typedef typename traits_type::off_type off_type; private: using __streambuf_type = basic_streambuf<CharT, Traits>; using __istream_type = std::basic_istream<CharT, Traits>; __streambuf_type m_buffer; public: basic_istream(const std::string &path) : __istream_type(&m_buffer) , m_buffer(path) { this->init(&m_buffer); } basic_istream(rsrc &resource) : __istream_type(&m_buffer) , m_buffer(resource) { this->init(&m_buffer); } basic_istream(const basic_istream &) = delete; basic_istream(basic_istream &&rhs) : __istream_type(std::move(rhs)) , m_buffer(std::move(rhs.m_buffer)) { __istream_type::set_rdbuf(&m_buffer); } basic_istream &operator=(const basic_istream &) = delete; basic_istream &operator=(basic_istream &&rhs) { __istream_type::operator=(std::move(rhs)); m_buffer = std::move(rhs.m_buffer); return *this; } void swap(basic_istream &rhs) { __istream_type::swap(rhs); m_buffer.swap(rhs.m_buffer); } __streambuf_type *rdbuf() const { return const_cast<__streambuf_type *>(&m_buffer); } }; using istream = basic_istream<char, std::char_traits<char>>; } // namespace mrsrc // -------------------------------------------------------------------- namespace cif { // -------------------------------------------------------------------- std::map<std::string,std::filesystem::path> gLocalResources; std::filesystem::path gDataDir; void addDataDirectory(std::filesystem::path dataDir) { if (VERBOSE and not fs::exists(dataDir)) std::cerr << "The specified data directory " << dataDir << " does not exist" << std::endl; gDataDir = dataDir; } void addFileResource(const std::string &name, std::filesystem::path dataFile) { if (not fs::exists(dataFile)) throw std::runtime_error("Attempt to add a file resource for " + name + " that does not exist: " + dataFile.string()); gLocalResources[name] = dataFile; } std::unique_ptr<std::istream> loadResource(std::filesystem::path name) { std::unique_ptr<std::istream> result; fs::path p = name; if (gLocalResources.count(name.string())) { std::unique_ptr<std::ifstream> file(new std::ifstream(gLocalResources[name.string()], std::ios::binary)); if (file->is_open()) result.reset(file.release()); } if (not result and not fs::exists(p) and not gDataDir.empty()) p = gDataDir / name; #if defined(CACHE_DIR) if (not result and not fs::exists(p)) { auto p2 = fs::path(CACHE_DIR) / p; if (fs::exists(p2)) swap(p, p2); } #endif #if defined(DATA_DIR) if (not result and not fs::exists(p)) { auto p2 = fs::path(DATA_DIR) / p; if (fs::exists(p2)) swap(p, p2); } #endif if (not result and fs::exists(p)) { std::unique_ptr<std::ifstream> file(new std::ifstream(p, std::ios::binary)); if (file->is_open()) result.reset(file.release()); } if (not result and gResourceData) { mrsrc::rsrc rsrc(name); if (rsrc) result.reset(new mrsrc::istream(rsrc)); } return result; } } // namespace cif
25.884969
161
0.638354
[ "vector" ]
99cc01402ff25221b1107d1570e7dca179c71297
3,382
cpp
C++
cpp/test/PacketLoggerTest.cpp
simpleton/profilo
91ef4ba1a8316bad2b3080210316dfef4761e180
[ "Apache-2.0" ]
null
null
null
cpp/test/PacketLoggerTest.cpp
simpleton/profilo
91ef4ba1a8316bad2b3080210316dfef4761e180
[ "Apache-2.0" ]
null
null
null
cpp/test/PacketLoggerTest.cpp
simpleton/profilo
91ef4ba1a8316bad2b3080210316dfef4761e180
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2004-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <vector> #include <profilo/logger/lfrb/LockFreeRingBuffer.h> #include <profilo/PacketLogger.h> #include <profilo/writer/PacketReassembler.h> #include <gtest/gtest.h> namespace facebook { namespace profilo { using namespace logger; using namespace writer; const size_t kItemSize = sizeof(uint16_t); const size_t kItems = 512; TEST(Logger, testPacketizedWrite) { std::vector<uint16_t> data(kItems); for (size_t i = 0; i < data.size(); ++i) { data[i] = i; } PacketBuffer buffer(1000); PacketLogger logger([&]() -> PacketBuffer& { return buffer; }); // // Try different sized writes from 1 to data.size(). // Assert that the data in each case is correct and that the // PacketReassembler sees exactly one payload. // for (size_t i = 1; i <= data.size(); ++i) { PacketBuffer::Cursor cursor = buffer.currentHead(); logger.write(data.data(), i * kItemSize); size_t calls = 0; PacketReassembler reassembler([&](const void* read_data, size_t size) { EXPECT_EQ(size, i * kItemSize) << "read must be the same size as write"; const uint16_t* idata = reinterpret_cast<const uint16_t*>(read_data); for (size_t j = 0; j < size / kItemSize; ++j) { EXPECT_EQ(j, idata[j]) << "data must be the same"; } ++calls; }); Packet packet; while (buffer.tryRead(packet, cursor)) { reassembler.process(packet); cursor.moveForward(); } EXPECT_EQ(calls, 1) << "must read exactly one payload"; } } TEST(Logger, testPacketizedWriteBackwards) { std::vector<uint16_t> data(kItems); for (size_t i = 0; i < data.size(); ++i) { data[i] = i; } // // Try different sized writes from 1 to data.size(). // Assert that the data in each case is correct and that the // PacketReassembler sees exactly one payload. // for (size_t i = 1; i <= data.size(); ++i) { PacketBuffer buffer(1000); PacketLogger logger([&]() -> PacketBuffer& { return buffer; }); logger.write(data.data(), i * kItemSize); size_t calls = 0; PacketReassembler reassembler([&](const void* read_data, size_t size) { EXPECT_EQ(size, i * kItemSize) << "read must be the same size as write"; const uint16_t* idata = reinterpret_cast<const uint16_t*>(read_data); for (size_t j = 0; j < size / kItemSize; ++j) { EXPECT_EQ(j, idata[j]) << "data must be the same"; } ++calls; }); auto cursor = buffer.currentHead(); cursor.moveBackward(); Packet packet; while (buffer.tryRead(packet, cursor)) { reassembler.processBackwards(packet); if (!cursor.moveBackward()) { break; } } EXPECT_EQ(calls, 1) << "must read exactly one payload"; } } } } // facebook::profilo
27.721311
78
0.651094
[ "vector" ]
99d1b25d39b7e2a6ad532915a30239479baa355b
1,828
cpp
C++
aws-cpp-sdk-robomaker/source/model/DeploymentApplicationConfig.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-robomaker/source/model/DeploymentApplicationConfig.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-robomaker/source/model/DeploymentApplicationConfig.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/robomaker/model/DeploymentApplicationConfig.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace RoboMaker { namespace Model { DeploymentApplicationConfig::DeploymentApplicationConfig() : m_applicationHasBeenSet(false), m_applicationVersionHasBeenSet(false), m_launchConfigHasBeenSet(false) { } DeploymentApplicationConfig::DeploymentApplicationConfig(JsonView jsonValue) : m_applicationHasBeenSet(false), m_applicationVersionHasBeenSet(false), m_launchConfigHasBeenSet(false) { *this = jsonValue; } DeploymentApplicationConfig& DeploymentApplicationConfig::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("application")) { m_application = jsonValue.GetString("application"); m_applicationHasBeenSet = true; } if(jsonValue.ValueExists("applicationVersion")) { m_applicationVersion = jsonValue.GetString("applicationVersion"); m_applicationVersionHasBeenSet = true; } if(jsonValue.ValueExists("launchConfig")) { m_launchConfig = jsonValue.GetObject("launchConfig"); m_launchConfigHasBeenSet = true; } return *this; } JsonValue DeploymentApplicationConfig::Jsonize() const { JsonValue payload; if(m_applicationHasBeenSet) { payload.WithString("application", m_application); } if(m_applicationVersionHasBeenSet) { payload.WithString("applicationVersion", m_applicationVersion); } if(m_launchConfigHasBeenSet) { payload.WithObject("launchConfig", m_launchConfig.Jsonize()); } return payload; } } // namespace Model } // namespace RoboMaker } // namespace Aws
20.311111
88
0.753282
[ "model" ]
99d1d7c8fe59b4bb0996ebcf0e84242b9e52e393
7,331
cpp
C++
src/hqn_gui_controller.cpp
Bindernews/HeadlessQuickNes
394cc533c74b079bf8b143b25d4e4f6c75232469
[ "MIT" ]
5
2016-04-19T20:45:28.000Z
2018-11-25T03:07:30.000Z
src/hqn_gui_controller.cpp
Bindernews/HappyQuickNes
394cc533c74b079bf8b143b25d4e4f6c75232469
[ "MIT" ]
null
null
null
src/hqn_gui_controller.cpp
Bindernews/HappyQuickNes
394cc533c74b079bf8b143b25d4e4f6c75232469
[ "MIT" ]
null
null
null
#include "hqn_gui_controller.h" #include "hqn_util.h" #include <algorithm> #include <cstring> #include <SDL.h> #define DEFAULT_WIDTH 256 #define DEFAULT_HEIGHT 240 namespace hqn { const char *DEFAULT_WINDOW_TITLE = "HeadlessQuickNES"; const SDL_Rect NES_BLIT_RECT = { 0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT }; // Determine the letterboxing required to display something on screen. // The original code is basically magic. // aspectW/H and windowW/H are the aspect ratio and window size, they are // inputs. The view* parameters are the outputs and correspond to the // calculated area in the window where the view should be. void determineLetterbox(double aspectW, double aspectH, double windowW, double windowH, int &viewX, int &viewY, int &viewW, int &viewH) { double scale = std::min(windowW / aspectW, windowH / aspectH); viewW = (int)(aspectW * scale); viewH = (int)(aspectH * scale); viewX = (int)(windowW - viewW) / 2; viewY = (int)(windowH - viewH) / 2; } /* -- Returns: scale, scissorX, scissorY, scissorW, scissorH, offsetX, offsetY function xl.calculateViewport(sizes, winW, winH, scaleInterval, screenFlex ) local gameW,gameH = sizes.w, sizes.h local screenW,screenH = winW + screenFlex, winH + screenFlex local scale = math.min(screenW / gameW, screenH / gameH) scale = math.floor(scale * scaleInterval) / scaleInterval local scissorW, scissorH = gameW * scale, gameH * scale local scissorX, scissorY = (winW - scissorW) / 2, (winH - scissorH) / 2 local offsetX, offsetY = scissorX / scale, scissorY / scale return scale, scissorX, scissorY, scissorW, scissorH, offsetX, offsetY end */ GUIController::GUIController(HQNState &state) :m_state(state) { m_tex = nullptr; m_texOverlay = nullptr; m_renderer = nullptr; m_window = nullptr; m_overlay = nullptr; m_closeOp = CLOSE_QUIT; m_isFullscreen = false; } GUIController::~GUIController() { if (m_tex) SDL_DestroyTexture(m_tex); if (m_texOverlay) SDL_DestroyTexture(m_texOverlay); if (m_renderer) SDL_DestroyRenderer(m_renderer); if (m_window) SDL_DestroyWindow(m_window); m_state.setListener(nullptr); } GUIController *GUIController::create(HQNState &state) { GUIController *self = new GUIController(state); if (!self->init()) { delete self; return nullptr; } else { return self; } } bool GUIController::init() { // create the window if (!(m_window = SDL_CreateWindow(DEFAULT_WINDOW_TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, DEFAULT_WIDTH, DEFAULT_HEIGHT, 0))) return false; if (!(m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED))) return false; if (!(m_tex = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, 256, 256))) return false; // Set the clear color now rather than later SDL_SetRenderDrawColor(m_renderer, 0, 0, 0, 255); // Default the scale to 1 if (!setScale(1)) return false; return true; } bool GUIController::setScale(int scale) { if (scale < 1 || scale > 5) return false; if (m_isFullscreen) setFullscreen(false, false); // reset to windowed and don't bother changing the overlay int winW = DEFAULT_WIDTH * scale; int winH = DEFAULT_HEIGHT * scale; // Change the window size SDL_SetWindowSize(m_window, winW, winH); if (!onResize(winW, winH, true)) return false; // update the overlay destination m_overlayDest = { 0, 0, winW, winH }; m_nesDest = { 0, 0, winW, winH }; // Update internal scale variable m_scale = scale; return true; } int GUIController::getScale() const { return m_scale; } void GUIController::setFullscreen(bool full, bool adjustOverlay) { m_isFullscreen = full; SDL_SetWindowFullscreen(m_window, full ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0); int w, h; SDL_GetWindowSize(m_window, &w, &h); onResize((size_t)w, (size_t)h, adjustOverlay); } bool GUIController::isFullscreen() const { return m_isFullscreen; } bool GUIController::onResize(size_t w, size_t h, bool adjustOverlay) { // first calculate letterboxing int viewX, viewY, viewW, viewH; determineLetterbox(DEFAULT_WIDTH, DEFAULT_HEIGHT, w, h, viewX, viewY, viewW, viewH); // make sure images are put in the right places m_overlayDest = { viewX, viewY, viewW, viewH }; m_nesDest = { viewX, viewY, viewW, viewH }; if (adjustOverlay && !resizeOverlay(viewW, viewH)) return false; return true; } bool GUIController::resizeOverlay(size_t w, size_t h) { // destroy the overlay and corresponding texture if (m_overlay) { // first check if the overlay is already the correct size if (m_overlay->getWidth() == (int)w && m_overlay->getHeight() == (int)h) return true; else delete m_overlay; } if (m_texOverlay) SDL_DestroyTexture(m_texOverlay); // Now re-create them m_overlay = new Surface(w, h); if (!(m_texOverlay = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, w, h))) return false; SDL_SetTextureBlendMode(m_texOverlay, SDL_BLENDMODE_BLEND); return true; } void GUIController::update(bool readNES) { void *nesPixels = nullptr; void *overlayPixels = nullptr; int pitch = 0; // Update the overlay if (SDL_LockTexture(m_texOverlay, nullptr, &overlayPixels, &pitch) < 0) return; memcpy(overlayPixels, m_overlay->getPixels(), m_overlay->getDataSize()); SDL_UnlockTexture(m_texOverlay); // Only update the NES image if we have to if (readNES) { if (SDL_LockTexture(m_tex, nullptr, &nesPixels, &pitch) < 0) return; m_state.blit((int32_t*)nesPixels, HQNState::NES_VIDEO_PALETTE, 0, 0, 0, 0); SDL_UnlockTexture(m_tex); } // render to screen SDL_RenderClear(m_renderer); SDL_RenderCopy(m_renderer, m_tex, &NES_BLIT_RECT, &m_nesDest); SDL_RenderCopy(m_renderer, m_texOverlay, nullptr, &m_overlayDest); SDL_RenderPresent(m_renderer); // Process any outstanding events processEvents(); } void GUIController::onAdvanceFrame(HQNState *state) { update(true); } void GUIController::setTitle(const char *title) { SDL_SetWindowTitle(m_window, title); } void GUIController::setCloseOperation(CloseOperation closeop) { m_closeOp = closeop; } GUIController::CloseOperation GUIController::getCloseOperation() const { return m_closeOp; } void GUIController::processEvents() { bool quit = false; SDL_Event event; while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: quit = true; break; } } if (quit) { if (m_closeOp & CLOSE_QUIT) { exit(0); } if (m_closeOp & CLOSE_DELETE) { m_state.setListener(nullptr); delete this; } } } void GUIController::onLoadROM(HQNState *state, const char *filename) {} // unimportant void GUIController::onLoadState(HQNState *state) {} // also unimportant }
27.664151
95
0.665803
[ "render" ]
99d5c3136f8bddd796f5b87c881a3a865e3b31a4
319
cpp
C++
Metaclass/main.cpp
vmille/ConceptExpressions
9e846b515ea1536713e30210a61fe0583dbdf9c5
[ "MIT" ]
null
null
null
Metaclass/main.cpp
vmille/ConceptExpressions
9e846b515ea1536713e30210a61fe0583dbdf9c5
[ "MIT" ]
null
null
null
Metaclass/main.cpp
vmille/ConceptExpressions
9e846b515ea1536713e30210a61fe0583dbdf9c5
[ "MIT" ]
1
2022-03-13T18:08:33.000Z
2022-03-13T18:08:33.000Z
// // Created by mille on 19-Nov-18. // #include <iostream> int main() { // double a = 2.0; // double b = 7.0; // Vector X{1.0, 2.0, 3.0, 4.0}; // Vector Y{5.0, 6.0, 7.0, 8.0}; // Vector Z{9.0, 10.0, 11.0, 12.0}; // double res = sum(-X+a*Y+b*Z); // std::cout << "Result : " << res << std::endl; }
21.266667
51
0.473354
[ "vector" ]
99df07b44e097667ba802e4b2106c5c7460e737c
6,056
cpp
C++
pwiz_aux/sfcap/peptideSieve/digest.cpp
austinkeller/pwiz
aa8e575cb40fd5e97cc7d922e4d8da44c9277cca
[ "Apache-2.0" ]
11
2015-01-08T08:33:44.000Z
2019-07-12T06:14:54.000Z
pwiz_aux/sfcap/peptideSieve/digest.cpp
austinkeller/pwiz
aa8e575cb40fd5e97cc7d922e4d8da44c9277cca
[ "Apache-2.0" ]
61
2015-05-27T11:20:11.000Z
2019-12-20T15:06:21.000Z
pwiz_aux/sfcap/peptideSieve/digest.cpp
austinkeller/pwiz
aa8e575cb40fd5e97cc7d922e4d8da44c9277cca
[ "Apache-2.0" ]
4
2016-02-03T09:41:16.000Z
2021-08-01T18:42:36.000Z
// // Original Author: Parag Mallick // // Copyright 2009 Spielberg Family Center for Applied Proteomics // Cedars Sinai Medical Center, Los Angeles, California 90048 // // 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 "digest.hpp" double Digest::computeMass(string peptide){ double mass = 0; if (peptide.length () > 0) { mass = massMap_['o']+ 2 * massMap_['h']; //simply compute normal, not [H+] //yes - I should be doing all this with iterators - but I'll do that in the next version for(size_t i=1;i<peptide.length()-1;i++){ if(isalpha(peptide[i])){ mass += massMap_[peptide[i]]; } else{ mass += massMap_['X']; } } } return mass; } void Digest::createPeptides(){ std::transform(sequence_.begin(), sequence_.end(), sequence_.begin(), (int(*)(int)) toupper); size_t length = sequence_.length(); if(sequence_[length-1] != '*'){ sequence_.push_back('*'); // WCH: added to reflect the true length length++; } string peptide; for(size_t start=0;start<length;start++){ if((start == 0) || (sequence_[start] == 'K' && sequence_[start+1] != 'P') || (sequence_[start] == 'R' && sequence_[start+1] != 'P')) { //WCH: Original code: don't know why double is used //double numMisCleavages = -1; int numMisCleavages = 0; // WCH for(size_t end=start+1;((end<length) && (((int)(end-start)) < config_._maxSeqLength));end++){ if((sequence_[end] == 'K') || (sequence_[end] == 'R') || (sequence_[end] == '*')){ if(end < length){ if(sequence_[end+1] != 'P'){ peptide = sequence_.substr(start,((int)(end-start))+2); } else { //WCH: this should not be considered as a cleavage // continue to find the next cleavage continue; } } else{ peptide = sequence_.substr(start,((int)(end-start))+2); } double mass; if (start == 0) { // WCH: we should include N-term residue! mass = computeMass(string(" ").append(peptide)); } else { mass = computeMass(peptide); } if((mass > config_._minMass) && (mass<config_._maxMass) && (((int)(end-start)) > config_._minSeqLength) ){ // cout<<peptide<<endl; peptides_.push_back(peptide); massVector_.push_back(mass); } numMisCleavages++; // WCH: shifted from outer loop as it is more efficient // to check number of cleavage after we have updated it // PM: OK - nice change. if(numMisCleavages > config_._numAllowedMisCleavages){ break; } } } /*for(size_t end=start;((end<length) && (((int)(end-start)) < config_._maxSeqLength));end++){*/ } } } void Digest::initMassMap(){ bool useAvgMass = false; if (useAvgMass == true) /*avg masses*/ { massMap_['h']= 1.00794; /* hydrogen */ massMap_['o']= 15.9994; /* oxygen */ massMap_['c']= 12.0107; /* carbon */ massMap_['n']= 14.00674; /* nitrogen */ massMap_['p']= 30.973761; /* phosporus */ massMap_['s']= 32.066; /* sulphur */ massMap_['G']= 57.05192; massMap_['A']= 71.07880; massMap_['S']= 87.07820; massMap_['P']= 97.11668; massMap_['V']= 99.13256; massMap_['T']=101.10508; massMap_['C']=103.13880; massMap_['L']=113.15944; massMap_['I']=113.15944; massMap_['X']=113.15944; massMap_['N']=114.10384; massMap_['O']=114.14720; massMap_['B']=114.59622; massMap_['D']=115.08860; massMap_['Q']=128.13072; massMap_['K']=128.17408; massMap_['Z']=128.62310; massMap_['E']=129.11548; massMap_['M']=131.19256; massMap_['H']=137.14108; massMap_['F']=147.17656; massMap_['R']=156.18748; massMap_['Y']=163.17596; massMap_['W']=186.21320; } else /* monoisotopic masses */ { massMap_['h']= 1.0078250; massMap_['o']= 15.9949146; massMap_['c']= 12.0000000; massMap_['n']= 14.0030740; massMap_['p']= 30.9737633; massMap_['s']= 31.9720718; massMap_['G']= 57.0214636; massMap_['A']= 71.0371136; massMap_['S']= 87.0320282; massMap_['P']= 97.0527636; massMap_['V']= 99.0684136; massMap_['T']=101.0476782; massMap_['C']=103.0091854; massMap_['L']=113.0840636; massMap_['I']=113.0840636; massMap_['X']=113.0840636; massMap_['N']=114.0429272; massMap_['O']=114.0793126; massMap_['B']=114.5349350; massMap_['D']=115.0269428; massMap_['Q']=128.0585772; massMap_['A']= 71.0371136; massMap_['S']= 87.0320282; massMap_['P']= 97.0527636; massMap_['V']= 99.0684136; massMap_['T']=101.0476782; massMap_['C']=103.0091854; massMap_['L']=113.0840636; massMap_['I']=113.0840636; massMap_['N']=114.0429272; massMap_['O']=114.0793126; massMap_['B']=114.5349350; massMap_['D']=115.0269428; massMap_['Q']=128.0585772; massMap_['K']=128.0949626; massMap_['Z']=128.5505850; massMap_['E']=129.0425928; massMap_['M']=131.0404854; massMap_['H']=137.0589116; massMap_['F']=147.0684136; massMap_['R']=156.1011106; massMap_['Y']=163.0633282; massMap_['W']=186.0793126; } }
32.212766
103
0.560766
[ "transform" ]
99e207e1c5ef196fbd0102e48b8e0dffcc10a507
835
cpp
C++
gui-2048/src/helper.cpp
ShreyanshJoshi/2048
38276aa5a0cde4d94f952621e8780c163f1ab7f3
[ "MIT" ]
null
null
null
gui-2048/src/helper.cpp
ShreyanshJoshi/2048
38276aa5a0cde4d94f952621e8780c163f1ab7f3
[ "MIT" ]
null
null
null
gui-2048/src/helper.cpp
ShreyanshJoshi/2048
38276aa5a0cde4d94f952621e8780c163f1ab7f3
[ "MIT" ]
null
null
null
/** * @file helper.cpp * @author Shreyansh Joshi * @brief File containing implementation of the helper functions (functions that are of no practical use in themselves * and just help the core functions). * */ #include "base.h" #include <bits/stdc++.h> void load_vector(vector<vector<int>>&v, int board[Y_DIM][X_DIM]) { for(int i=0;i<Y_DIM;i++) { vector<int>w; for(int j=0;j<X_DIM;j++) w.push_back(board[i][j]); v.push_back(w); } } pair<int,int> get_loc(int board[Y_DIM][X_DIM]) { vector<int>v; for(int i=0;i<Y_DIM;i++) for(int j=0;j<X_DIM;j++) if(board[i][j]==0) v.push_back(X_DIM*i+j); if(v.size()==0) { pair<int,int>p = {-1,-1}; return p; } int temp = rand(); temp = temp % v.size(); int row = v[temp]/X_DIM; int col = v[temp]%X_DIM; pair<int,int>p = {row,col}; return p; }
20.875
118
0.613174
[ "vector" ]
99e6c64d5c82f4f4b64020ffdb179323fdd61838
1,387
cpp
C++
C++ STL(Standard Template Library)/Sort.cpp
MrinmoiHossain/Algorithms
d29a10316219f320b0116ef3b412457a1c1aea26
[ "MIT" ]
2
2017-06-29T14:04:14.000Z
2020-03-21T12:48:21.000Z
C++ STL(Standard Template Library)/Sort.cpp
MrinmoiHossain/Algorithms
d29a10316219f320b0116ef3b412457a1c1aea26
[ "MIT" ]
null
null
null
C++ STL(Standard Template Library)/Sort.cpp
MrinmoiHossain/Algorithms
d29a10316219f320b0116ef3b412457a1c1aea26
[ "MIT" ]
2
2020-03-31T15:45:19.000Z
2021-09-15T15:51:06.000Z
#include <iostream> #include <cstdlib> //using for rand() #include <vector> //using for vector #include <algorithm> //using for sort() using namespace std; struct Point{ double x, y; }point[3]; bool cmp(Point A, Point B) { if(A.x != B.x) return A.x < B.x; return A.y < B.y; } int main(void) { int arr[7] = {3, 2, 7, 1, 4, 6, 5}; //Declare Array for sorting //sort(Start Index Number, Before Last Index Number) sort(arr, arr + 5); //Sort from 0 to 5 for(int i = 0; i < 7; i++) cout << arr[i] << endl; cout << endl; vector<int> a; for(int i = 1; i <= 7; i++) a.push_back(rand() % 100); sort(a.begin(), a.end()); //Sort a vector for(int i = 0; i < a.size(); i++) cout << a[i] << endl; cout << endl; //Structure for Sorting for(int i = 0; i < 3; i++){ point[i].x = 14.0 - 1.3 * i; point[i].y = 13.0 - 1.5 * i; } cout << "Unsorted Structure" << endl; for(int i = 0; i < 3; i++) cout << point[i].x << " " << point[i].y << endl; cout << "Sorted Structure" << endl; sort(point, point + 3, cmp); //Sorting a Structure, here cmp is function for(int i = 0; i < 3; i++) cout << point[i].x << " " << point[i].y << endl; cout << endl; return 0; }
27.196078
87
0.474405
[ "vector" ]
99ea0c685e1fe081cb2975e321edcc1c5c4156f8
6,320
cpp
C++
code/GUI-version/code/warehouse.cpp
chengwenwu/warehouse-management-system
d5ffd62c4f33ae0695846eaefbc593331fe93be5
[ "Unlicense" ]
25
2019-04-05T05:01:07.000Z
2022-02-12T00:48:56.000Z
code/GUI-version/code/warehouse.cpp
chengwenwu/warehouse-management-system
d5ffd62c4f33ae0695846eaefbc593331fe93be5
[ "Unlicense" ]
null
null
null
code/GUI-version/code/warehouse.cpp
chengwenwu/warehouse-management-system
d5ffd62c4f33ae0695846eaefbc593331fe93be5
[ "Unlicense" ]
6
2019-04-05T05:24:01.000Z
2021-08-15T10:36:16.000Z
#include "warehouse.h" #include <QMessageBox> #include <QSqlDatabase> #include <QSqlQuery> #include <QVariant> Warehouse::Warehouse() { this->goods.clear(); if(!db.creatDataBase()) { QMessageBox message(QMessageBox::Warning, "waring", "Creat Database failed!", QMessageBox::Ok); if(message.exec() == QMessageBox::Ok) exit(-1); } this->readGoodsFromDataBase(); } Warehouse::~Warehouse() { } void Warehouse::empty()//用来将仓库中的货物清零 { QSqlQuery query; query.exec("delete from goods"); this->goods.clear(); QString str = "Warehouse is empty!"; throw str; } bool Warehouse::inputCheck(string &id, QString &name, string &count) { QString text = ""; if(id.length() > 100 || id.length() == 0) { text = "Id is wrong, please input again!\n"; } if(name.length() > 100 || name.length() == 0) { text = "Name is wrong, please input again!\n"; } if(count.length() >= 10) { text += "number is wrong, please input again!\n"; } int coun; for (coun = 0; coun < count.length(); coun++) { if (!isdigit(count[coun])) { text += "Goods number should only include number!\n"; break; } } for (coun = 0; coun < id.length(); coun++) { if (!isdigit(id[coun])) { text += "id should only include number!\n"; break; } } if(text != "") { throw text; } return true; } bool Warehouse::add_goods(string id, QString name, string count) { try { if(!inputCheck(id, name, count)) { return false; } int id_temp = stringToNum(id); int number = stringToNum(count); vector<Goods>::iterator it; for (it = goods.begin(); it != goods.end();it++) { if (it->getId() == id_temp) { if(it->getName() != name) { QString str = "Id and name mismatch\n"; throw str; } //存到数据库中 db.writeAnItemToDataBase(id_temp,name,it->getCount() + number); it->setCount(it->getCount() + number); QString str = "Goods have been stored!"; throw str; } } //若已存在要入库的商品,则只需增加其数量 if (it == goods.end()) { add_to_list(id_temp, name, number); return true; } //若目前仓库中没有该商品,则将其加入商品列表 } catch (QString str1) { throw str1; } } bool Warehouse::add_to_list(int id, QString name, int count) //在列表中加入新的商品,该函数在函数add_goods(string name, int count)内部调用 { try { if (this->goods.size() < ALL)//仓库未满直接存储 { Goods good; good.setId(id); good.setName(name); good.setCount(count); //存进数据库 db.writeAnItemToDataBase(id,name,count); this->goods.push_back(good); QString str = "Goods have been stored!"; throw str; } else { QString str = "save failed\n warehouse is full!"; throw str; } //当储存位置已经满了的时候,显示“仓库已满” } catch (QString str1) { throw str1; } } bool Warehouse::delete_goods(string id,string count) //出货 { QString null = "null"; if(!inputCheck(id, null, count)) { return false; } int id_temp = stringToNum(id); int number = stringToNum(count); vector<Goods>::iterator it; for (it = goods.begin(); it != goods.end(); it++) { if (it->getId() == id_temp) { if ((it->getCount() - number) < 0) { QString str = "Goods is not enough!"; throw str; } //出货数量大于库存时,拒绝请求 else if ((it->getCount() -number) == 0) { db.writeAnItemToDataBase(id_temp,it->getName(),-1); this->goods.erase(it); QString str = "OK!\nAll this Goods have been delete!"; throw str; //return true; } //出货数量刚好等于库存时,出货,并将该商品从列中移除 else if ((it->getCount() - number) > 0) { //存进数据库中 db.writeAnItemToDataBase(id_temp,it->getName(),it->getCount() - number); it->setCount(it->getCount() - number); QString str = "OK!"; throw str; } return true; } } if (it == goods.end()) { QString str = "Error\n Goods not exists"; throw str; } //若目前仓库中没有该商品,提示未找到 } void Warehouse::show_goods() //显示目前仓库中所有商品及其数量 { QString text = "Id Name number\n"; if(goods.size() == 0) { QMessageBox massagebox(QMessageBox::Warning,"waring", "warehouse is empty", QMessageBox::Ok,NULL); massagebox.exec(); return ; } vector<Goods>::iterator it; for (it = goods.begin(); it != goods.end(); it++) { QString id =QString::number(it->getId()); QString count = QString::number(it->getCount()); text = text+id+" "+ it->getName()+" "+count+"\n"; } throw text; } void Warehouse::find_goods(QString id, QString name) //在所有商品中进行查找目标商品 { QString text = "Id Name number\n"; vector<Goods>::iterator it; for (it = goods.begin(); it != goods.end(); it++) { if (it->getName() == name || QString::number(it->getId()) == id) { QString id_r = QString::number(it->getId()); QString name_r = it->getName(); QString num_r = QString::number(it->getCount()); text += (id_r +" "+name_r+" "+num_r+"\n"); } } throw text; } void Warehouse::readGoodsFromDataBase() { QSqlQuery query; query.exec("SELECT id, name, number FROM goods"); while (query.next()) { int id_in = query.value(0).toInt(); QString name_in = query.value(1).toString(); int number_in = query.value(2).toInt(); Goods good; good.setId(id_in); good.setName(name_in); good.setCount(number_in); this->goods.push_back(good); } }
26.115702
106
0.501582
[ "vector" ]
99ed75bcb214b6d96903fe02451cdaba314de0a9
5,989
cpp
C++
libsolidity/interface/GasEstimator.cpp
miohtama/solidity
9e36bdda8a9552f1885e0a63a85db588623b39b2
[ "MIT" ]
null
null
null
libsolidity/interface/GasEstimator.cpp
miohtama/solidity
9e36bdda8a9552f1885e0a63a85db588623b39b2
[ "MIT" ]
null
null
null
libsolidity/interface/GasEstimator.cpp
miohtama/solidity
9e36bdda8a9552f1885e0a63a85db588623b39b2
[ "MIT" ]
1
2016-09-22T14:08:24.000Z
2016-09-22T14:08:24.000Z
/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2015 * Gas consumption estimator working alongside the AST. */ #include "GasEstimator.h" #include <map> #include <functional> #include <memory> #include <libdevcore/SHA3.h> #include <libevmasm/ControlFlowGraph.h> #include <libevmasm/KnownState.h> #include <libevmasm/PathGasMeter.h> #include <libsolidity/ast/AST.h> #include <libsolidity/ast/ASTVisitor.h> #include <libsolidity/codegen/CompilerUtils.h> using namespace std; using namespace dev; using namespace dev::eth; using namespace dev::solidity; GasEstimator::ASTGasConsumptionSelfAccumulated GasEstimator::structuralEstimation( AssemblyItems const& _items, vector<ASTNode const*> const& _ast ) { solAssert(std::count(_ast.begin(), _ast.end(), nullptr) == 0, ""); map<SourceLocation, GasConsumption> particularCosts; ControlFlowGraph cfg(_items); for (BasicBlock const& block: cfg.optimisedBlocks()) { assertThrow(!!block.startState, OptimizerException, ""); GasMeter meter(block.startState->copy()); auto const end = _items.begin() + block.end; for (auto iter = _items.begin() + block.begin; iter != end; ++iter) particularCosts[iter->location()] += meter.estimateMax(*iter); } set<ASTNode const*> finestNodes = finestNodesAtLocation(_ast); ASTGasConsumptionSelfAccumulated gasCosts; auto onNode = [&](ASTNode const& _node) { if (!finestNodes.count(&_node)) return true; gasCosts[&_node][0] = gasCosts[&_node][1] = particularCosts[_node.location()]; return true; }; auto onEdge = [&](ASTNode const& _parent, ASTNode const& _child) { gasCosts[&_parent][1] += gasCosts[&_child][1]; }; ASTReduce folder(onNode, onEdge); for (ASTNode const* ast: _ast) ast->accept(folder); return gasCosts; } map<ASTNode const*, GasMeter::GasConsumption> GasEstimator::breakToStatementLevel( ASTGasConsumptionSelfAccumulated const& _gasCosts, vector<ASTNode const*> const& _roots ) { solAssert(std::count(_roots.begin(), _roots.end(), nullptr) == 0, ""); // first pass: statementDepth[node] is the distance from the deepend statement to node // in direction of the tree root (or undefined if not possible) map<ASTNode const*, int> statementDepth; auto onNodeFirstPass = [&](ASTNode const& _node) { if (dynamic_cast<Statement const*>(&_node)) statementDepth[&_node] = 0; return true; }; auto onEdgeFirstPass = [&](ASTNode const& _parent, ASTNode const& _child) { if (statementDepth.count(&_child)) statementDepth[&_parent] = max(statementDepth[&_parent], statementDepth[&_child] + 1); }; ASTReduce firstPass(onNodeFirstPass, onEdgeFirstPass); for (ASTNode const* node: _roots) node->accept(firstPass); // we use the location of a node if // - its statement depth is 0 or // - its statement depth is undefined but the parent's statement depth is at least 1 map<ASTNode const*, GasConsumption> gasCosts; auto onNodeSecondPass = [&](ASTNode const& _node) { return statementDepth.count(&_node); }; auto onEdgeSecondPass = [&](ASTNode const& _parent, ASTNode const& _child) { bool useNode = false; if (statementDepth.count(&_child)) useNode = statementDepth[&_child] == 0; else useNode = statementDepth.count(&_parent) && statementDepth.at(&_parent) > 0; if (useNode) gasCosts[&_child] = _gasCosts.at(&_child)[1]; }; ASTReduce secondPass(onNodeSecondPass, onEdgeSecondPass); for (ASTNode const* node: _roots) node->accept(secondPass); // gasCosts should only contain non-overlapping locations return gasCosts; } GasEstimator::GasConsumption GasEstimator::functionalEstimation( AssemblyItems const& _items, string const& _signature ) { auto state = make_shared<KnownState>(); if (!_signature.empty()) { ExpressionClasses& classes = state->expressionClasses(); using Id = ExpressionClasses::Id; using Ids = vector<Id>; Id hashValue = classes.find(u256(FixedHash<4>::Arith(FixedHash<4>(dev::sha3(_signature))))); Id calldata = classes.find(Instruction::CALLDATALOAD, Ids{classes.find(u256(0))}); classes.forceEqual(hashValue, Instruction::DIV, Ids{ calldata, classes.find(u256(1) << (8 * 28)) }); } PathGasMeter meter(_items); return meter.estimateMax(0, state); } GasEstimator::GasConsumption GasEstimator::functionalEstimation( AssemblyItems const& _items, size_t const& _offset, FunctionDefinition const& _function ) { auto state = make_shared<KnownState>(); unsigned parametersSize = CompilerUtils::sizeOnStack(_function.parameters()); if (parametersSize > 16) return GasConsumption::infinite(); // Store an invalid return value on the stack, so that the path estimator breaks upon reaching // the return jump. AssemblyItem invalidTag(PushTag, u256(-0x10)); state->feedItem(invalidTag, true); if (parametersSize > 0) state->feedItem(swapInstruction(parametersSize)); return PathGasMeter(_items).estimateMax(_offset, state); } set<ASTNode const*> GasEstimator::finestNodesAtLocation( vector<ASTNode const*> const& _roots ) { map<SourceLocation, ASTNode const*> locations; set<ASTNode const*> nodes; SimpleASTVisitor visitor(function<bool(ASTNode const&)>(), [&](ASTNode const& _n) { if (!locations.count(_n.location())) { locations[_n.location()] = &_n; nodes.insert(&_n); } }); for (ASTNode const* root: _roots) root->accept(visitor); return nodes; }
31.192708
95
0.73468
[ "vector" ]
99eeb36c8858b7a416bfe1875c4e21d62814028e
811
cpp
C++
303. Range Sum Query - Immutable.cpp
NeoYY/Leetcode-Solution
0f067973d3c296ac7f2fa85a89dbdd5295b0b037
[ "MIT" ]
null
null
null
303. Range Sum Query - Immutable.cpp
NeoYY/Leetcode-Solution
0f067973d3c296ac7f2fa85a89dbdd5295b0b037
[ "MIT" ]
null
null
null
303. Range Sum Query - Immutable.cpp
NeoYY/Leetcode-Solution
0f067973d3c296ac7f2fa85a89dbdd5295b0b037
[ "MIT" ]
null
null
null
/* Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note: You may assume that the array does not change. There are many calls to sumRange function. Solution is using dp */ class NumArray { public: NumArray(vector<int>& nums) { dp.resize( nums.size() + 1, 0 ); for ( int i = 1; i <= nums.size(); ++i ) { dp[i] = dp[i - 1] + nums[i - 1]; } } int sumRange(int i, int j) { return dp[j + 1] - dp[i]; } private: vector<int> dp; }; /** * Your NumArray object will be instantiated and called as such: * NumArray* obj = new NumArray(nums); * int param_1 = obj->sumRange(i,j); */
20.794872
101
0.5709
[ "object", "vector" ]
99f20449f0dda5c993ecae3644ad504c791452cd
14,444
hpp
C++
octotiger/unitiger/cell_geometry.hpp
cclauss/octotiger
73c3f2e5366e2c0b2d46a1f252b13f3b2f9b9171
[ "BSL-1.0" ]
null
null
null
octotiger/unitiger/cell_geometry.hpp
cclauss/octotiger
73c3f2e5366e2c0b2d46a1f252b13f3b2f9b9171
[ "BSL-1.0" ]
null
null
null
octotiger/unitiger/cell_geometry.hpp
cclauss/octotiger
73c3f2e5366e2c0b2d46a1f252b13f3b2f9b9171
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2019 AUTHORS // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef OCTOTIGER_UNITIGER_CELL_GEOMETRY_HPP_ #define OCTOTIGER_UNITIGER_CELL_GEOMETRY_HPP_ #include <mutex> #include "octotiger/unitiger/util.hpp" template<int NDIM, int INX> struct cell_geometry { static constexpr int H_BW = OCTOTIGER_BW; static constexpr int H_NX = (2 * H_BW + INX); static constexpr int H_NX_X = cell_geometry::H_NX; static constexpr int H_NX_Y = NDIM > 1 ? cell_geometry::H_NX : 1; static constexpr int H_NX_Z = NDIM > 2 ? cell_geometry::H_NX : 1; static constexpr int H_NX_XM2 = cell_geometry::H_NX - 2; static constexpr int H_NX_YM2 = NDIM > 1 ? cell_geometry::H_NX - 2 : 1; static constexpr int H_NX_ZM2 = NDIM > 2 ? cell_geometry::H_NX - 2 : 1; static constexpr int H_NX_XM3 = cell_geometry::H_NX - 3; static constexpr int H_NX_YM3 = NDIM > 1 ? cell_geometry::H_NX - 3 : 1; static constexpr int H_NX_ZM3 = NDIM > 2 ? cell_geometry::H_NX - 3 : 1; static constexpr int H_NX_XM4 = cell_geometry::H_NX - 4; static constexpr int H_NX_YM4 = NDIM > 1 ? cell_geometry::H_NX - 4 : 1; static constexpr int H_NX_ZM4 = NDIM > 2 ? cell_geometry::H_NX - 4 : 1; static constexpr int H_NX_XM6 = cell_geometry::H_NX - 6; static constexpr int H_NX_YM6 = NDIM > 1 ? cell_geometry::H_NX - 6 : 1; static constexpr int H_NX_ZM6 = NDIM > 2 ? cell_geometry::H_NX - 6 : 1; static constexpr int H_NX_XM8 = cell_geometry::H_NX - 8; static constexpr int H_NX_YM8 = NDIM > 1 ? cell_geometry::H_NX - 8 : 1; static constexpr int H_NX_ZM8 = NDIM > 2 ? cell_geometry::H_NX - 8 : 1; static constexpr int H_DNX = NDIM == 3 ? cell_geometry::H_NX * cell_geometry::H_NX : (NDIM == 2 ? cell_geometry::H_NX : 1); static constexpr int H_DNY = NDIM == 3 ? cell_geometry::H_NX : 1; static constexpr int H_DNZ = 1; static constexpr int H_N3 = std::pow(cell_geometry::H_NX, NDIM); static constexpr int H_DN0 = 0; static constexpr int NDIR = std::pow(3, NDIM); static constexpr int NANGMOM = NDIM == 1 ? 0 : std::pow(3, NDIM - 2); static constexpr int NFACEDIR = std::pow(3, NDIM - 1); static constexpr int H_DN[3] = { H_DNX, H_DNY, H_DNZ }; static constexpr int group_count() { return ngroups_[NDIM - 1]; } static int group_size(int gi) { return group_size_[NDIM - 1][gi]; } static std::pair<int, int> group_pair(int gi, int ni) { return groups3d_[NDIM - 1][gi][ni]; } private: static constexpr int ngroups_[3] = { 0, 1, 4 }; static constexpr int group_size_[3][4] = { { }, { 4 }, { 8, 4, 4, 4 } }; static constexpr std::pair<int, int> groups3d_[3][4][8] = { { { } }, { { /**/{ -H_DNX - H_DNY, 8 }, /**/{ -H_DNX, 2 }, /**/{ -H_DNY, 6 }, /**/{ -H_DN0, 0 } } }, /**/{ { /* 0 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 */ /**/{ (-H_DNX - H_DNY - H_DNZ), 26 }, /**/{ (-H_DNY - H_DNZ), 24 }, /**/{ (-H_DNX - H_DNZ), 20 }, /**/{ (-H_DNX - H_DNY), 8 }, /**/{ -H_DNX, 2 }, /**/{ -H_DNY, 6 }, /**/{ -H_DNZ, 18 }, /**/{ -H_DN0, 0 } }, { /**/{ (-H_DNX - H_DNY), 17 }, /**/{ -H_DNX, 11 }, /**/{ -H_DNY, 15 }, /**/{ -H_DN0, 9 }, }, { /**/{ (-H_DNX - H_DNZ), 23 }, /**/{ -H_DNX, 5 }, /**/{ -H_DNZ, 21 }, /**/{ -H_DN0, 3 }, }, { /**/{ (-H_DNZ - H_DNY), 25 }, /**/{ -H_DNY, 7 }, /**/{ -H_DNZ, 19 }, /**/{ -H_DN0, 1 } } } }; static constexpr bool is_lower_face[3][3][27] = { { 1, 0, 0 }, /**/{ { 1, 0, 0, 1, 0, 0, 1, 0, 0 }, { 1, 1, 1, 0, 0, 0, 0, 0, 0 } }, { /**/{ 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0 }, /**/{ 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 }, /**/{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } } }; static constexpr int levi_civitas[3][3][3][3] = { { { { } } }, { { { 0, 1 }, { -1, 0 } } }, { { { 0, 0, 0 }, { 0, 0, 1 }, { 0, -1, 0 } }, { { 0, 0, -1 }, { 0, 0, 0 }, { 1, 0, 0 } }, { { 0, 1, 0 }, { -1, 0, 0 }, { 0, 0, 0 } } } }; static constexpr int lower_face_members[3][3][9] = { { { 0 } }, { { 3, 0, 6 }, { 1, 0, 2 } }, { { 12, 0, 3, 6, 9, 15, 18, 21, 24 }, { 10, 0, 1, 2, 9, 11, 18, 19, 20 }, { 4, 0, 1, 2, 3, 5, 6, 7, 8 } } }; static constexpr safe_real quad_weights[3][9] = { { 1.0 }, { 2.0 / 3.0, 1.0 / 6.0, 1.0 / 6.0 }, { 16. / 36., 1. / 36., 4. / 36., 1. / 36., 4. / 36., 4. / 36., 1. / 36., 4. / 36., 1. / 36. } }; static constexpr safe_real vol_weights[3][27] = { /**/{ 1. / 6., 4. / 6., 1. / 6. }, /**/{ 1. / 36., 4. / 36., 1. / 36., 4. / 36., 16. / 36., 4. / 36., 1. / 36., 4. / 36., 1. / 36. }, /**/{ 1. / 216., 4. / 216., 1. / 216., 4. / 216., 16. / 216., 4. / 216., 1. / 216., 4. / 216., 1. / 216., /****/4. / 216., 16. / 216., 4. / 216., 16. / 216., 64. / 216., 16. / 216., 4. / 216., 16. / 216., 4. / 216., /****/1. / 216., 4. / 216., 1. / 216., 4. / 216., 16. / 216., 4. / 216., 1. / 216., 4. / 216., 1. / 216. } }; static constexpr int face_locs[3][27][3] = { /**/{ { -1 }, { 0 }, { 1 } }, /**/{ /**/{ -1, -1 }, { +0, -1 }, { +1, -1 }, /**/{ -1, +0 }, { +0, +0 }, { +1, +0 }, /**/{ -1, +1 }, { +0, +1 }, { +1, +1 } }, /**/{ /**/{ -1, -1, -1 }, { +0, -1, -1 }, { +1, -1, -1 }, /**/{ -1, +0, -1 }, { +0, +0, -1 }, { 1, +0, -1 }, /**/{ -1, +1, -1 }, { +0, +1, -1 }, { +1, +1, -1 }, /**/{ -1, -1, +0 }, { +0, -1, +0 }, { +1, -1, +0 }, /**/{ -1, +0, +0 }, { +0, +0, +0 }, { +1, +0, +0 }, /**/{ -1, +1, +0 }, { +0, +1, +0 }, { +1, +1, +0 }, /**/{ -1, -1, +1 }, { +0, -1, +1 }, { +1, -1, +1 }, /**/{ -1, +0, +1 }, { +0, +0, +1 }, { +1, +0, +1 }, /**/{ -1, +1, +1 }, { +0, +1, +1 }, { +1, +1, +1 } } }; static constexpr int directions[3][27] = { { /**/-H_DNX, +H_DN0, +H_DNX /**/ }, { /**/-H_DNX - H_DNY, +H_DN0 - H_DNY, +H_DNX - H_DNY,/**/ /**/-H_DNX + H_DN0, +H_DN0 + H_DN0, +H_DNX + H_DN0,/**/ /**/-H_DNX + H_DNY, +H_DN0 + H_DNY, +H_DNX + H_DNY, /**/ }, { /**/-H_DNX - H_DNY - H_DNZ, +H_DN0 - H_DNY - H_DNZ, +H_DNX - H_DNY - H_DNZ,/**/ /**/-H_DNX + H_DN0 - H_DNZ, +H_DN0 + H_DN0 - H_DNZ, +H_DNX + H_DN0 - H_DNZ,/**/ /**/-H_DNX + H_DNY - H_DNZ, +H_DN0 + H_DNY - H_DNZ, +H_DNX + H_DNY - H_DNZ,/**/ /**/-H_DNX - H_DNY + H_DN0, +H_DN0 - H_DNY + H_DN0, +H_DNX - H_DNY + H_DN0,/**/ /**/-H_DNX + H_DN0 + H_DN0, +H_DN0 + H_DN0 + H_DN0, +H_DNX + H_DN0 + H_DN0,/**/ /**/-H_DNX + H_DNY + H_DN0, +H_DN0 + H_DNY + H_DN0, +H_DNX + H_DNY + H_DN0,/**/ /**/-H_DNX - H_DNY + H_DNZ, +H_DN0 - H_DNY + H_DNZ, +H_DNX - H_DNY + H_DNZ,/**/ /**/-H_DNX + H_DN0 + H_DNZ, +H_DN0 + H_DN0 + H_DNZ, +H_DNX + H_DN0 + H_DNZ,/**/ /**/-H_DNX + H_DNY + H_DNZ, +H_DN0 + H_DNY + H_DNZ, +H_DNX + H_DNY + H_DNZ/**/ } }; static std::array<std::array<std::vector<int>, NDIR>, H_BW> all_indices; static void verify_3d_constdefs() { for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { for (int k = -1; k < 2; k++) { const int index = (i + 1) + 3 * (j + 1) + 9 * (k + 1); safe_real sum = H_DN[0] * i; sum += H_DN[1] * j; sum += H_DN[2] * k; if (directions[2][index] != sum) { printf("directions failed verification at %i %i %i\n", i, j, k); abort(); } bool cond = false; cond = cond || (face_locs[2][index][0] != i); cond = cond || (face_locs[2][index][1] != j); cond = cond || (face_locs[2][index][2] != k); if (cond) { printf("xlocs failed verification at %i %i %i %i\n", index, i, j, k); for (int dim = 0; dim < NDIM; dim++) { printf("%i ", face_locs[2][index][dim]); } printf("\n"); abort(); } } } } bool fail = false; /* corners */ int gi = 0; for (int n = 0; n < group_size_[2][0]; n++) { const auto pair = group_pair(gi, n); const int x = pair.second % 3; const int y = (pair.second / 3) % 3; const int z = pair.second / 9; const int index = -((x / 2) * H_DNX + (y / 2) * H_DNY + (z / 2) * H_DNZ); if (index != pair.first) { fail = true; } } gi = 1; for (int n = 0; n < group_size_[2][1]; n++) { const auto pair = group_pair(gi, n); const int x = pair.second % 3; const int y = (pair.second / 3) % 3; const int z = pair.second / 9; const int index = -((x / 2) * H_DNX + (y / 2) * H_DNY); if (index != pair.first) { fail = true; } } gi = 2; for (int n = 0; n < group_size_[2][2]; n++) { const auto pair = group_pair(gi, n); const int x = pair.second % 3; const int y = (pair.second / 3) % 3; const int z = pair.second / 9; const int index = -((x / 2) * H_DNX + (z / 2) * H_DNZ); if (index != pair.first) { fail = true; } } gi = 3; for (int n = 0; n < group_size_[2][2]; n++) { const auto pair = group_pair(gi, n); const int x = pair.second % 3; const int y = (pair.second / 3) % 3; const int z = pair.second / 9; const int index = -((y / 2) * H_DNY + (z / 2) * H_DNZ); if (index != pair.first) { fail = true; } } if (fail) { printf("Corners/edges indexes failed\n"); abort(); } // printf("3D geometry constdefs passed verification\n"); } public: cell_geometry() { static std::once_flag flag; std::call_once(flag, []() { printf( "Initializing cell_geometry %i %i %i\n", NDIM, INX, cell_geometry::H_NX); verify_3d_constdefs(); for (int bw = 1; bw <= H_BW; bw++) { for (int d = 0; d < NDIR; d++) { all_indices[bw - 1][d] = find_indices(bw, cell_geometry::H_NX - bw, d); } } }); } inline const auto& get_indexes(int bw, int d) const { return all_indices[bw - 1][d]; } inline static constexpr auto levi_civita() { return levi_civitas[NDIM - 1]; } inline static constexpr auto direction() { return directions[NDIM - 1]; } inline static constexpr auto xloc() { return face_locs[NDIM - 1]; } inline static constexpr auto is_lface(int dim, int d) { return is_lower_face[NDIM - 1][dim][d]; } inline static constexpr auto volume_weight() { return vol_weights[NDIM - 1]; } inline static constexpr auto face_weight() { return quad_weights[NDIM - 1]; } inline static constexpr auto face_pts() { return lower_face_members[NDIM - 1]; } inline constexpr int flip(const int d) const { return NDIR - 1 - d; } static inline int flip_dim(const int d, int flip_dim) { std::array<int, NDIM> dims; int k = d; for (int dim = 0; dim < NDIM; dim++) { dims[dim] = k % 3; k /= 3; } k = 0; dims[flip_dim] = 2 - dims[flip_dim]; for (int dim = 0; dim < NDIM; dim++) { k *= 3; k += dims[NDIM - 1 - dim]; } return k; } static auto to_index(int j, int k, int l) { if /*constexpr*/(NDIM == 1) { return j; } else if /*constexpr*/(NDIM == 2) { return (j * cell_geometry::H_NX + k); } else { return (j * cell_geometry::H_NX + k) * cell_geometry::H_NX + l; } } static inline std::vector<int> find_indices(int lb, int ub, int d = NDIR / 2) { std::vector<int> I; std::array<int, NDIM> lbs; std::array<int, NDIM> ubs; for (int dim = 0; dim < NDIM; dim++) { ubs[dim] = xloc()[d][dim] == -1 ? (ub + 1) : ub; lbs[dim] = xloc()[d][dim] == +1 ? (lb - 1) : lb; } for (int i = 0; i < H_N3; i++) { bool interior = true; const auto dims = index_to_dims<NDIM, cell_geometry::H_NX>(i); for (int dim = 0; dim < NDIM; dim++) { int this_i = dims[dim]; if (this_i < lbs[dim] || this_i >= ubs[dim]) { interior = false; break; } } if (interior) { I.push_back(i); } } return I; } }; template<int NDIM, int INX> std::array<std::array<std::vector<int>, cell_geometry<NDIM, INX>::NDIR>, cell_geometry<NDIM, INX>::H_BW> cell_geometry<NDIM, INX>::all_indices; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::ngroups_[3]; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::group_size_[3][4]; template<int NDIM, int INX> constexpr std::pair<int, int> cell_geometry<NDIM, INX>::groups3d_[3][4][8]; template<int NDIM, int INX> constexpr bool cell_geometry<NDIM, INX>::is_lower_face[3][3][27]; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::levi_civitas[3][3][3][3]; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::lower_face_members[3][3][9]; template<int NDIM, int INX> constexpr safe_real cell_geometry<NDIM, INX>::quad_weights[3][9]; template<int NDIM, int INX> constexpr safe_real cell_geometry<NDIM, INX>::vol_weights[3][27]; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::face_locs[3][27][3]; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::directions[3][27]; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_DN[3]; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_BW; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_NX; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_NX_X; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_NX_Y; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_NX_Z; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_NX_XM2; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_NX_YM2; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_NX_ZM2; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_NX_XM4; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_NX_YM4; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_NX_ZM4; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_NX_XM6; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_NX_YM6; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_NX_ZM6; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_DNX; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_DNY; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_DNZ; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_N3; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::H_DN0; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::NDIR; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::NANGMOM; template<int NDIM, int INX> constexpr int cell_geometry<NDIM, INX>::NFACEDIR; #endif /* OCTOTIGER_UNITIGER_CELL_GEOMETRY_HPP_ */
31.537118
156
0.567017
[ "geometry", "vector", "3d" ]
99fef9343178695e96681ee41791cd6aa2129621
10,657
cpp
C++
Source/Game/imgui_impl_gl3.cpp
igorsegallafa/UrhoMMO
fd389d9722f32b0dc90dff746138213471503820
[ "MIT" ]
8
2020-02-06T13:14:13.000Z
2020-11-03T06:26:04.000Z
Source/Game/imgui_impl_gl3.cpp
igorsegallafa/UrhoMMO
fd389d9722f32b0dc90dff746138213471503820
[ "MIT" ]
null
null
null
Source/Game/imgui_impl_gl3.cpp
igorsegallafa/UrhoMMO
fd389d9722f32b0dc90dff746138213471503820
[ "MIT" ]
6
2019-06-19T00:24:16.000Z
2020-12-08T05:03:59.000Z
// ImGui GLFW binding with OpenGL3 + shaders // In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown(). // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui #include "PrecompiledHeader.h" #include "ImGui/imgui.h" #include "imgui_hook.h" #include "imgui_impl_gl3.h" #include <Urho3D/Graphics/Graphics.h> #include <Urho3D/Graphics/GraphicsImpl.h> #include <Urho3D/Graphics/Texture2D.h> #include <Urho3D/Core/Context.h> // Data static Urho3D::SharedPtr<Urho3D::Texture2D> g_FontTexture; static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0; static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0; static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0; Urho3D::Texture2D* ImGui_Impl_GetFontTexture() { return g_FontTexture.Get(); } // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) // If text or lines are blurry when integrating ImGui in your engine: // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) void ImGui_Impl_RenderDrawLists(ImDrawData* draw_data) { // Backup GL state GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src); GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst); GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb); GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha); GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); GLboolean last_enable_blend = glIsEnabled(GL_BLEND); GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glActiveTexture(GL_TEXTURE0); // Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays) ImGuiIO& io = ImGui::GetIO(); int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x); int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y); if (fb_width == 0 || fb_height == 0) return; draw_data->ScaleClipRects(io.DisplayFramebufferScale); // Setup viewport, orthographic projection matrix glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); const float ortho_projection[4][4] = { { 2.0f / io.DisplaySize.x, 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f / -io.DisplaySize.y, 0.0f, 0.0f }, { 0.0f, 0.0f, -1.0f, 0.0f }, { -1.0f, 1.0f, 0.0f, 1.0f }, }; glUseProgram(g_ShaderHandle); glUniform1i(g_AttribLocationTex, 0); glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); glBindVertexArray(g_VaoHandle); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawIdx* idx_buffer_offset = 0; glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid*)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle); glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid*)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW); for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++) { if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { auto texture = static_cast<Urho3D::Texture2D*>(pcmd->TextureId); glBindTexture(GL_TEXTURE_2D, texture->GetGPUObjectName()); texture->UpdateParameters(); glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); } idx_buffer_offset += pcmd->ElemCount; } } // Restore modified GL state glUseProgram(last_program); glBindTexture(GL_TEXTURE_2D, last_texture); glBindVertexArray(last_vertex_array); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); glBlendFunc(last_blend_src, last_blend_dst); if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND); if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); } bool ImGui_ImplGlfwGL3_CreateFontsTexture(Urho3D::Context* context) { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader. // Upload texture to graphics system GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); g_FontTexture = Urho3D::MakeShared<Urho3D::Texture2D>(context); g_FontTexture->SetNumLevels(1); g_FontTexture->SetSize(width, height, Urho3D::Graphics::GetRGBAFormat()); g_FontTexture->SetData(0, 0, 0, width, height, pixels); g_FontTexture->SetFilterMode(Urho3D::FILTER_BILINEAR); // Store our identifier io.Fonts->TexID = (void*)g_FontTexture.Get(); io.Fonts->ClearTexData(); // Restore state glBindTexture(GL_TEXTURE_2D, last_texture); return true; } bool ImGui_Impl_CreateDeviceObjects(Urho3D::Context* context) { // Backup GL state GLint last_texture, last_array_buffer, last_vertex_array; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); const GLchar *vertex_shader = "#version 330\n" "uniform mat4 ProjMtx;\n" "in vec2 Position;\n" "in vec2 UV;\n" "in vec4 Color;\n" "out vec2 Frag_UV;\n" "out vec4 Frag_Color;\n" "void main()\n" "{\n" " Frag_UV = UV;\n" " Frag_Color = Color;\n" " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; const GLchar* fragment_shader = "#version 330\n" "uniform sampler2D Texture;\n" "in vec2 Frag_UV;\n" "in vec4 Frag_Color;\n" "out vec4 Out_Color;\n" "void main()\n" "{\n" " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n" "}\n"; g_ShaderHandle = glCreateProgram(); g_VertHandle = glCreateShader(GL_VERTEX_SHADER); g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(g_VertHandle, 1, &vertex_shader, 0); glShaderSource(g_FragHandle, 1, &fragment_shader, 0); glCompileShader(g_VertHandle); glCompileShader(g_FragHandle); glAttachShader(g_ShaderHandle, g_VertHandle); glAttachShader(g_ShaderHandle, g_FragHandle); glLinkProgram(g_ShaderHandle); g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture"); g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx"); g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position"); g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV"); g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color"); glGenBuffers(1, &g_VboHandle); glGenBuffers(1, &g_ElementsHandle); glGenVertexArrays(1, &g_VaoHandle); glBindVertexArray(g_VaoHandle); glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); glEnableVertexAttribArray(g_AttribLocationPosition); glEnableVertexAttribArray(g_AttribLocationUV); glEnableVertexAttribArray(g_AttribLocationColor); #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos)); glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv)); glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col)); #undef OFFSETOF ImGui_ImplGlfwGL3_CreateFontsTexture(context); // Restore modified GL state glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindVertexArray(last_vertex_array); return true; } void ImGui_Impl_InvalidateDeviceObjects() { if (g_VaoHandle) glDeleteVertexArrays(1, &g_VaoHandle); if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle); if (g_ElementsHandle) glDeleteBuffers(1, &g_ElementsHandle); g_VaoHandle = g_VboHandle = g_ElementsHandle = 0; glDetachShader(g_ShaderHandle, g_VertHandle); glDeleteShader(g_VertHandle); g_VertHandle = 0; glDetachShader(g_ShaderHandle, g_FragHandle); glDeleteShader(g_FragHandle); g_FragHandle = 0; glDeleteProgram(g_ShaderHandle); g_ShaderHandle = 0; if (g_FontTexture) { auto object = g_FontTexture->GetGPUObjectName(); glDeleteTextures(1, &object); ImGui::GetIO().Fonts->TexID = 0; g_FontTexture.Reset(); } } void ImGui_Impl_Shutdown() { ImGui_Impl_InvalidateDeviceObjects(); }
40.06391
171
0.764286
[ "render", "object" ]
8204821a59e073117971f0d7202bf4315136c849
1,871
cpp
C++
CK2ToEU3/Source/CK2World/Opinion/Repository.cpp
beerhall/paradoxGameConverters
96b6f91ebc413795afd63f40f6ecf4ca83fa9460
[ "MIT" ]
114
2015-06-07T20:27:45.000Z
2020-08-16T05:05:56.000Z
CK2ToEU3/Source/CK2World/Opinion/Repository.cpp
iamdafu/paradoxGameConverters
674364a22917155642ade923e5dfbe38a5fa9610
[ "MIT" ]
553
2015-07-20T23:58:26.000Z
2019-06-13T21:45:56.000Z
CK2ToEU3/Source/CK2World/Opinion/Repository.cpp
iamdafu/paradoxGameConverters
674364a22917155642ade923e5dfbe38a5fa9610
[ "MIT" ]
106
2015-07-27T00:21:16.000Z
2020-06-10T10:13:13.000Z
/*Copyright (c) 2016 The Paradox Game Converters Project 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 "CK2World/Opinion/Repository.h" void ck2::opinion::Repository::initOpinions(IObject* root) { if (root == NULL) { return; } std::vector<IObject*> opinions = root->getLeaves(); for (std::vector<IObject*>::iterator itr = opinions.begin(); itr != opinions.end(); ++itr) { std::string name = (*itr)->getKey(); std::vector<IObject*> opinionObjs = (*itr)->getValue("opinion"); int value = 0; if (opinionObjs.size() > 0) { value = atoi(opinionObjs[0]->getLeaf().c_str()); } if (!name.empty() && value != 0) { opinionVals[name] = value; } } } int ck2::opinion::Repository::getBaseValue(std::string opinion) { std::map<std::string,int>::const_iterator itr = opinionVals.find(opinion); if (itr == opinionVals.end()) return 0; return itr->second; }
34.648148
91
0.73597
[ "vector" ]
820546c4c5b71cc233f734d03ef805dd04d7d706
4,281
cpp
C++
Classes/HelloWorldScene.cpp
yadurajiv/sample-multilingual
22a2936d65cc7caf8f342cbce0f0752f00dc0251
[ "MIT" ]
null
null
null
Classes/HelloWorldScene.cpp
yadurajiv/sample-multilingual
22a2936d65cc7caf8f342cbce0f0752f00dc0251
[ "MIT" ]
null
null
null
Classes/HelloWorldScene.cpp
yadurajiv/sample-multilingual
22a2936d65cc7caf8f342cbce0f0752f00dc0251
[ "MIT" ]
null
null
null
/* Copyright 2017 Yadu Rajiv */ #include "HelloWorldScene.h" #include "editor-support/cocostudio/CocoStudio.h" #include "ui/CocosGUI.h" #include "GameResources.h" USING_NS_CC; using namespace cocostudio::timeline; Scene* HelloWorld::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = HelloWorld::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool HelloWorld::init() { // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label auto label = Label::createWithTTF(GameResources::getInstance()->getUIString("hello"), GameResources::getInstance()->getFont(), 24); // position the label on the center of the screen label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, 1); auto help = cocos2d::ui::Text::create(GameResources::getInstance()->getUIString("help"), GameResources::getInstance()->getFont(), 24); help->setPosition(Vec2(origin.x + visibleSize.width / 2, 100)); this->addChild(help, 2); // add "HelloWorld" splash screen" auto sprite = Sprite::create("HelloWorld.png"); // position the sprite on the center of the screen sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0); auto listener = EventListenerKeyboard::create(); listener->onKeyReleased = CC_CALLBACK_2(HelloWorld::onKeyReleased, this); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); return true; } void HelloWorld::onKeyReleased(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event) { if (keyCode == cocos2d::EventKeyboard::KeyCode::KEY_BACK || keyCode == cocos2d::EventKeyboard::KeyCode::KEY_SPACE) { // set new language and reload strings if (GameResources::getInstance()->getUILanguage() == "en") { GameResources::getInstance()->setUILanguage("hi"); } else if (GameResources::getInstance()->getUILanguage() == "hi") { GameResources::getInstance()->setUILanguage("ml"); } else if (GameResources::getInstance()->getUILanguage() == "ml") { GameResources::getInstance()->setUILanguage("en"); } auto scene = HelloWorld::createScene(); Director::getInstance()->replaceScene(TransitionSlideInL::create(0.5f, scene)); } } void HelloWorld::menuCloseCallback(cocos2d::Ref* pSender) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.", "Alert"); return; #endif Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif }
34.804878
138
0.635366
[ "object" ]
82154ede0cfd0973cb5e6dcd4003d16b25d7479d
30,237
cpp
C++
maxon_epos2/src/epos_communication.cpp
andy-Chien/swerve_drive
b959f5e6a09638e612eac43d843dfbea31bf605b
[ "MIT" ]
null
null
null
maxon_epos2/src/epos_communication.cpp
andy-Chien/swerve_drive
b959f5e6a09638e612eac43d843dfbea31bf605b
[ "MIT" ]
null
null
null
maxon_epos2/src/epos_communication.cpp
andy-Chien/swerve_drive
b959f5e6a09638e612eac43d843dfbea31bf605b
[ "MIT" ]
null
null
null
//============================================================================ // Name : EposCommunication.cpp // Author : Julian Stiefel // Version : 1.0.0 // Created on : 26.04.2018 // Copyright : BSD 3-Clause // Description : Class providing the communication functions for Maxon EPOS2. // Install EPOS2 Linux Library from Maxon first! //============================================================================ #include <cmath> #include "maxon_epos2/epos_communication.hpp" namespace maxon_epos2 { EposCommunication::EposCommunication() { g_pKeyHandle = 0; //set adress to zero g_pSubKeyHandle = 0; g_usNodeId = 1; g_baudrate = 0; swerve_gear_ratio = 1; } EposCommunication::~EposCommunication() { } void EposCommunication::LogError(std::string functionName, int p_lResult, unsigned int p_ulErrorCode, unsigned short p_usNodeId = 0) { std::cerr << g_programName << ": " << functionName << " failed (result=" << p_lResult <<", ID = " << p_usNodeId << ", errorCode=0x" << std::hex << p_ulErrorCode << ")"<< std::endl; } void EposCommunication::LogInfo(std::string message) { std::cout << message << std::endl; } void EposCommunication::SeparatorLine() { const int lineLength = 65; for(int i=0; i<lineLength; i++) { std::cout << "-"; } std::cout << std::endl; } void EposCommunication::PrintHeader() { SeparatorLine(); LogInfo("Initializing EPOS2 Communication Library"); SeparatorLine(); } void EposCommunication::PrintSettings() { std::stringstream msg; msg << "default settings:" << std::endl; msg << "main node id = " << g_usNodeId << std::endl; msg << "device name = '" << g_deviceName << "'" << std::endl; msg << "protocal stack name = '" << g_protocolStackName << "'" << std::endl; msg << "interface name = '" << g_interfaceName << "'" << std::endl; msg << "port name = '" << g_portName << "'"<< std::endl; msg << "baudrate = " << g_baudrate << std::endl; msg << "node id list = " << g_nodeIdList; LogInfo(msg.str()); SeparatorLine(); } void EposCommunication::SetDefaultParameters(std::vector<int> nodeIdList, int motors) { /* Options: * node id: default 1 (not ROS node!) * device name: EPOS2, EPOS4, default: EPOS4 * protocol stack name: MAXON_RS232, CANopen, MAXON SERIAL V2, default: MAXON SERIAL V2 * interface name: RS232, USB, CAN_ixx_usb 0, CAN_kvaser_usb 0,... default: USB * port name: COM1, USB0, CAN0,... default: USB0 * baudrate: 115200, 1000000,... default: 1000000 */ //USB g_usNodeId = nodeIdList[0]; g_deviceName = "EPOS2"; g_protocolStackName = "MAXON SERIAL V2"; g_interfaceName = "USB"; g_baudrate = 1000000; g_subProtocolStackName = "CANopen"; // g_usSubNodeId = 2; g_motors = motors; g_nodeIdList = (unsigned short*) std::calloc(g_motors, sizeof(unsigned short)); for(int i = 0; i < g_motors; i++) g_nodeIdList[i] = nodeIdList[i]; //get the port name: int lStartOfSelection = 1; int lMaxStrSize = 255; char* pPortNameSel = new char[lMaxStrSize]; int lEndOfSelection = 0; unsigned int ulErrorCode = 0; VCS_GetPortNameSelection((char*)g_deviceName.c_str(), (char*)g_protocolStackName.c_str(), (char*)g_interfaceName.c_str(), lStartOfSelection, pPortNameSel, lMaxStrSize, &lEndOfSelection, &ulErrorCode); g_portName = pPortNameSel; ROS_INFO_STREAM("Port Name: " << g_portName); } int EposCommunication::SetPositionProfile(HANDLE p_DeviceHandle, unsigned short p_usNodeId, unsigned int* p_pErrorCode, unsigned int profile_velocity = 500, unsigned int profile_acceleration = 1000, unsigned int profile_deceleration = 1000) { //to use set variables below first! int lResult = MMC_SUCCESS; int vel_rpm = radsToRpm(profile_velocity); if(vel_rpm == 0) return lResult; if(VCS_SetPositionProfile(p_DeviceHandle, p_usNodeId, vel_rpm, radsToRpm(profile_acceleration), radsToRpm(profile_deceleration), p_pErrorCode) == MMC_FAILED) { LogError("VCS_SetPositionProfile", lResult, *p_pErrorCode); lResult = MMC_FAILED; } return lResult; } int EposCommunication::SetHomingParameter(unsigned int* p_pErrorCode) { //to use set variables below first! int lResult = MMC_SUCCESS; unsigned int homing_acceleration = 20; unsigned int speed_switch = 50; unsigned int speed_index = 50; int home_offset = 0; unsigned short current_threshold = 0; int home_position = 0; if(VCS_SetHomingParameter(g_pKeyHandle, g_usNodeId, homing_acceleration, speed_switch, speed_index, home_offset, current_threshold, home_position, p_pErrorCode) == MMC_FAILED) { lResult = MMC_FAILED; LogError("VCS_SetHomingParameter", lResult, *p_pErrorCode); } return lResult; } int EposCommunication::SetSensor(unsigned int* p_pErrorCode) { int lResult = MMC_SUCCESS; if(VCS_SetSensorType(g_pKeyHandle, g_usNodeId, 1, p_pErrorCode) == MMC_FAILED) { LogError("VCS_SetSensorType", lResult, *p_pErrorCode); lResult = MMC_FAILED; } if(VCS_SetIncEncoderParameter(g_pKeyHandle, g_usNodeId, 256, 0, p_pErrorCode) == MMC_FAILED) { LogError("VCS_SetIncEncoderParameter", lResult, *p_pErrorCode); lResult = MMC_FAILED; } return lResult; } int EposCommunication::OpenDevice(unsigned int* p_pErrorCode) { int lResult = MMC_FAILED; char* pDeviceName = new char[255]; char* pProtocolStackName = new char[255]; char* pInterfaceName = new char[255]; char* pPortName = new char[255]; strcpy(pDeviceName, g_deviceName.c_str()); strcpy(pProtocolStackName, g_protocolStackName.c_str()); strcpy(pInterfaceName, g_interfaceName.c_str()); strcpy(pPortName, g_portName.c_str()); LogInfo("Open device..."); LogInfo(pInterfaceName); g_pKeyHandle = VCS_OpenDevice(pDeviceName, pProtocolStackName, pInterfaceName, pPortName, p_pErrorCode); if(g_pKeyHandle!=0 && *p_pErrorCode == 0) { unsigned int lBaudrate = 0; unsigned int lTimeout = 0; if(VCS_GetProtocolStackSettings(g_pKeyHandle, &lBaudrate, &lTimeout, p_pErrorCode)!=MMC_FAILED) { if(VCS_SetProtocolStackSettings(g_pKeyHandle, g_baudrate, lTimeout, p_pErrorCode)!=MMC_FAILED) { if(VCS_GetProtocolStackSettings(g_pKeyHandle, &lBaudrate, &lTimeout, p_pErrorCode)!=MMC_FAILED) { if(g_baudrate==(int)lBaudrate) { lResult = MMC_SUCCESS; } } } } } else { g_pKeyHandle = 0; ROS_ERROR("Opening device failed."); } delete []pDeviceName; delete []pProtocolStackName; delete []pInterfaceName; delete []pPortName; return lResult; } int EposCommunication::OpenSubDevice(unsigned int* p_pErrorCode) { int lResult = MMC_FAILED; char* pDeviceName = new char[255]; char* pProtocolStackName = new char[255]; strcpy(pDeviceName, g_deviceName.c_str()); strcpy(pProtocolStackName, g_subProtocolStackName.c_str()); LogInfo("Open device..."); g_pSubKeyHandle = VCS_OpenSubDevice(g_pKeyHandle, pDeviceName, pProtocolStackName, p_pErrorCode); if(g_pSubKeyHandle!=0 && *p_pErrorCode == 0) { unsigned int lBaudrate = 0; unsigned int lTimeout = 0; if(VCS_GetProtocolStackSettings(g_pSubKeyHandle, &lBaudrate, &lTimeout, p_pErrorCode)!=MMC_FAILED) { if(VCS_SetProtocolStackSettings(g_pSubKeyHandle, g_baudrate, lTimeout, p_pErrorCode)!=MMC_FAILED) { if(VCS_GetProtocolStackSettings(g_pSubKeyHandle, &lBaudrate, &lTimeout, p_pErrorCode)!=MMC_FAILED) { if(g_baudrate==(int)lBaudrate) { lResult = MMC_SUCCESS; } } } } } else { g_pKeyHandle = 0; ROS_ERROR("Opening sub device failed."); } delete []pDeviceName; delete []pProtocolStackName; return lResult; } int EposCommunication::CloseDevice(unsigned int* p_pErrorCode) { int lResult = MMC_SUCCESS; *p_pErrorCode = 0; if(VCS_CloseAllSubDevices(g_pSubKeyHandle, p_pErrorCode) == MMC_FAILED) { lResult = MMC_FAILED; LogError("VCS_CloseAllSubDevices FAILED", lResult, *p_pErrorCode); } if(VCS_CloseDevice(g_pKeyHandle, p_pErrorCode) == MMC_FAILED) { lResult = MMC_FAILED; LogError("VCS_CloseDevice FAILED", lResult, *p_pErrorCode); } if(VCS_CloseAllDevices(p_pErrorCode) == MMC_FAILED) { lResult = MMC_FAILED; LogError("VCS_CloseAllDevices FAILED", lResult, *p_pErrorCode); } return lResult; } int EposCommunication::PrepareEpos(HANDLE p_DeviceHandle, unsigned short p_usNodeId, unsigned int* p_pErrorCode) { int lResult = MMC_SUCCESS; BOOL oIsFault = 0; //0 is not in fault state if(VCS_GetFaultState(p_DeviceHandle, p_usNodeId, &oIsFault, p_pErrorCode ) == MMC_FAILED) { LogError("VCS_GetFaultState", lResult, *p_pErrorCode); lResult = MMC_FAILED; } ROS_INFO_STREAM("Debug 1: FaultState:" << oIsFault); if(lResult == MMC_SUCCESS) { if(oIsFault) { std::stringstream msg; msg << "clear fault, node = '" << g_usNodeId << "'"; LogInfo(msg.str()); if(VCS_ClearFault(p_DeviceHandle, p_usNodeId, p_pErrorCode) == MMC_FAILED) { LogError("VCS_ClearFault", lResult, *p_pErrorCode); lResult = MMC_FAILED; } } if(lResult == MMC_SUCCESS) { BOOL oIsEnabled = 0; if(VCS_GetEnableState(p_DeviceHandle, p_usNodeId, &oIsEnabled, p_pErrorCode) == MMC_FAILED) { LogError("VCS_GetEnableState", lResult, *p_pErrorCode); lResult = MMC_FAILED; } if(!oIsEnabled) { if(VCS_SetEnableState(p_DeviceHandle, p_usNodeId, p_pErrorCode) == MMC_FAILED) { LogError("VCS_SetEnableState", lResult, *p_pErrorCode); lResult = MMC_FAILED; } else{ VCS_GetEnableState(p_DeviceHandle, p_usNodeId, &oIsEnabled, p_pErrorCode); ROS_INFO_STREAM("SetEnableState should be 1:" << oIsEnabled); } } } } return lResult; } // int EposCommunication::PositionMode(HANDLE p_DeviceHandle, unsigned short p_usNodeId, unsigned int* p_pErrorCode) // { // int lResult = MMC_SUCCESS; // lResult = ActivateProfilePositionMode(p_DeviceHandle, p_usNodeId, p_pErrorCode); // if(lResult != MMC_SUCCESS) // { // LogError("ActivateProfilePositionMode", lResult, *p_pErrorCode); // } // return lResult; // } int EposCommunication::HomingMode(unsigned short p_usNodeId, unsigned int* p_pErrorCode) { int lResult = MMC_SUCCESS; HANDLE p_DeviceHandle = (p_usNodeId == g_usNodeId) ? g_pKeyHandle : g_pSubKeyHandle; lResult = ActivateHomingMode(p_DeviceHandle, p_usNodeId, p_pErrorCode); if(lResult != MMC_SUCCESS) { LogError("ActivateHomingMode", lResult, *p_pErrorCode); } return lResult; } int EposCommunication::ActivateProfilePositionMode(HANDLE p_DeviceHandle, unsigned short p_usNodeId, unsigned int* p_pErrorCode) { int lResult = MMC_SUCCESS; std::stringstream msg; msg << "set profile position mode, node = " << p_usNodeId; LogInfo(msg.str()); if(VCS_ActivateProfilePositionMode(p_DeviceHandle, p_usNodeId, p_pErrorCode) == MMC_FAILED) { LogError("VCS_ActivateProfilePositionMode", lResult, *p_pErrorCode); lResult = MMC_FAILED; } else { ROS_INFO("VCS_ActivateProfilePositionMode successfull."); } return lResult; } int EposCommunication::ActivatePositionMode(HANDLE p_DeviceHandle, unsigned short p_usNodeId, unsigned int* p_pErrorCode) { int lResult = MMC_SUCCESS; std::stringstream msg; msg << "set position mode, node = " << p_usNodeId; LogInfo(msg.str()); if(VCS_ActivatePositionMode(p_DeviceHandle, p_usNodeId, p_pErrorCode) == MMC_FAILED) { LogError("VCS_ActivatePositionMode", lResult, *p_pErrorCode); lResult = MMC_FAILED; } else { ROS_INFO("VCS_ActivatePositionMode successfull."); } return lResult; } int EposCommunication::ActivateVelocityMode(HANDLE p_DeviceHandle, unsigned short p_usNodeId, unsigned int* p_pErrorCode) { int lResult = MMC_SUCCESS; std::stringstream msg; msg << "set velocity mode, node = " << p_usNodeId; LogInfo(msg.str()); if(VCS_ActivateVelocityMode(p_DeviceHandle, p_usNodeId, p_pErrorCode) == MMC_FAILED) { LogError("VCS_ActivateVelocityMode", lResult, *p_pErrorCode); lResult = MMC_FAILED; } else { ROS_INFO("VCS_ActivateVelocityMode successfull."); } return lResult; } int EposCommunication::ActivateHomingMode(HANDLE p_DeviceHandle, unsigned short p_usNodeId, unsigned int* p_pErrorCode) { int lResult = MMC_SUCCESS; std::stringstream msg; msg << "set homing mode, node = " << p_usNodeId; LogInfo(msg.str()); if(VCS_ActivateHomingMode(p_DeviceHandle, p_usNodeId, p_pErrorCode) == MMC_FAILED) { LogError("VCS_ActivateHomingMode", lResult, *p_pErrorCode); lResult = MMC_FAILED; } return lResult; } int EposCommunication::FindHome(unsigned short p_usNodeId, signed char homing_method, unsigned int* p_pErrorCode) { int lResult = MMC_SUCCESS; HANDLE p_DeviceHandle = (p_usNodeId == g_usNodeId) ? g_pKeyHandle : g_pSubKeyHandle; if(VCS_FindHome(p_DeviceHandle, p_usNodeId, homing_method, p_pErrorCode) == MMC_FAILED) { LogError("VCS_ActivateHomingMode", lResult, *p_pErrorCode); lResult = MMC_FAILED; } return lResult; } int EposCommunication::HomingSuccess(unsigned short p_usNodeId, unsigned int* p_pErrorCode) { int lResult = MMC_SUCCESS; unsigned int timeout = 6000000; //timeout in ms, should be shorter after testing HANDLE p_DeviceHandle = (p_usNodeId == g_usNodeId) ? g_pKeyHandle : g_pSubKeyHandle; // if(VCS_WaitForHomingAttained(p_DeviceHandle, p_usNodeId, timeout, p_pErrorCode) == MMC_FAILED) // { // LogError("VCS_WaitForHomingAttained", lResult, *p_pErrorCode); // lResult = MMC_FAILED; // } int pHomingAttained; int pHomingError; if(VCS_GetHomingState(p_DeviceHandle, p_usNodeId, &pHomingAttained, &pHomingError, p_pErrorCode) == MMC_FAILED) { LogError("VCS_GetHomingState", lResult, *p_pErrorCode); lResult = MMC_FAILED; } return pHomingAttained; } int EposCommunication::SetPosition(HANDLE p_DeviceHandle, unsigned short p_usNodeId, long position_setpoint, unsigned int* p_pErrorCode) { int lResult = MMC_SUCCESS; bool absolute = true; if(VCS_MoveToPosition(p_DeviceHandle, p_usNodeId, position_setpoint, absolute, 1, p_pErrorCode) == MMC_FAILED) { LogError("VCS_MoveToPosition", lResult, *p_pErrorCode); lResult = MMC_FAILED; std::cout<<"Fuck Fail_1"<<std::endl; } else{ // ROS_INFO("Movement executed."); } return lResult; } int EposCommunication::PrintAvailablePorts(char* p_pInterfaceNameSel) { int lResult = MMC_FAILED; int lStartOfSelection = 1; int lMaxStrSize = 255; char* pPortNameSel = new char[lMaxStrSize]; int lEndOfSelection = 0; unsigned int ulErrorCode = 0; do { if(!VCS_GetPortNameSelection((char*)g_deviceName.c_str(), (char*)g_protocolStackName.c_str(), p_pInterfaceNameSel, lStartOfSelection, pPortNameSel, lMaxStrSize, &lEndOfSelection, &ulErrorCode)) { lResult = MMC_FAILED; LogError("GetPortNameSelection", lResult, ulErrorCode); break; } else { lResult = MMC_SUCCESS; printf(" port = %s\n", pPortNameSel); } lStartOfSelection = 0; } while(lEndOfSelection == 0); return lResult; } int EposCommunication::PrintAvailableInterfaces() { int lResult = MMC_FAILED; int lStartOfSelection = 1; int lMaxStrSize = 255; char* pInterfaceNameSel = new char[lMaxStrSize]; int lEndOfSelection = 0; unsigned int ulErrorCode = 0; do { if(!VCS_GetInterfaceNameSelection((char*)g_deviceName.c_str(), (char*)g_protocolStackName.c_str(), lStartOfSelection, pInterfaceNameSel, lMaxStrSize, &lEndOfSelection, &ulErrorCode)) { lResult = MMC_FAILED; LogError("GetInterfaceNameSelection", lResult, ulErrorCode); break; } else { lResult = MMC_SUCCESS; printf("interface = %s\n", pInterfaceNameSel); PrintAvailablePorts(pInterfaceNameSel); } lStartOfSelection = 0; } while(lEndOfSelection == 0); SeparatorLine(); delete[] pInterfaceNameSel; return lResult; } int EposCommunication::PrintDeviceVersion() { int lResult = MMC_FAILED; unsigned short usHardwareVersion = 0; unsigned short usSoftwareVersion = 0; unsigned short usApplicationNumber = 0; unsigned short usApplicationVersion = 0; unsigned int ulErrorCode = 0; if(VCS_GetVersion(g_pKeyHandle, g_usNodeId, &usHardwareVersion, &usSoftwareVersion, &usApplicationNumber, &usApplicationVersion, &ulErrorCode)) { printf("%s Hardware Version = 0x%04x\n Software Version = 0x%04x\n Application Number = 0x%04x\n Application Version = 0x%04x\n", g_deviceName.c_str(), usHardwareVersion, usSoftwareVersion, usApplicationNumber, usApplicationVersion); lResult = MMC_SUCCESS; } return lResult; } int EposCommunication::PrintAvailableProtocols() { int lResult = MMC_FAILED; int lStartOfSelection = 1; int lMaxStrSize = 255; char* pProtocolNameSel = new char[lMaxStrSize]; int lEndOfSelection = 0; unsigned int ulErrorCode = 0; do { if(!VCS_GetProtocolStackNameSelection((char*)g_deviceName.c_str(), lStartOfSelection, pProtocolNameSel, lMaxStrSize, &lEndOfSelection, &ulErrorCode)) { lResult = MMC_FAILED; LogError("GetProtocolStackNameSelection", lResult, ulErrorCode); break; } else { lResult = MMC_SUCCESS; printf("protocol stack name = %s\n", pProtocolNameSel); } lStartOfSelection = 0; } while(lEndOfSelection == 0); SeparatorLine(); delete[] pProtocolNameSel; return lResult; } int EposCommunication::GetPosition(int* pPositionIsCounts, unsigned int* p_pErrorCode) { int lResult = MMC_SUCCESS; if(VCS_GetPositionIs(g_pKeyHandle, g_usNodeId, pPositionIsCounts, p_pErrorCode) == MMC_FAILED) { LogError("VCS_GetPositionIs", lResult, *p_pErrorCode); lResult = MMC_FAILED; } return lResult; } int EposCommunication::GetVelocity(int* pVelocityIsCounts, unsigned int* p_pErrorCode) { int lResult = MMC_SUCCESS; if(VCS_GetVelocityIs(g_pKeyHandle, g_usNodeId, pVelocityIsCounts, p_pErrorCode) == MMC_FAILED) { LogError("VCS_GetVelocityIs", lResult, *p_pErrorCode); lResult = MMC_FAILED; } return lResult; } //public functions: int EposCommunication::initialization(std::vector<int> nodeIdList, int motors){ int lResult = MMC_SUCCESS; unsigned int ulErrorCode = 0; //Print Header: PrintHeader(); //Set Default Parameters: SetDefaultParameters(nodeIdList, motors); //Print Settings: PrintSettings(); //Open device: if((lResult = OpenDevice(&ulErrorCode))==MMC_FAILED) { LogError("OpenDevice", lResult, ulErrorCode); deviceOpenedCheckStatus = MMC_FAILED; } else { deviceOpenedCheckStatus = MMC_SUCCESS; //used to forbid other functions as getPosition and getVelocity if device is not opened } //Prepare EPOS controller: if((lResult = PrepareEpos(g_pKeyHandle, g_usNodeId, &ulErrorCode))==MMC_FAILED) { LogError("PrepareEpos", lResult, ulErrorCode); } if(g_motors > 1) { if((lResult = OpenSubDevice(&ulErrorCode))==MMC_FAILED) { LogError("OpenSubDevice", lResult, ulErrorCode); deviceOpenedCheckStatus = MMC_FAILED; } else { deviceOpenedCheckStatus = MMC_SUCCESS; //used to forbid other functions as getPosition and getVelocity if device is not opened } for(int i = 1; i < g_motors; i++) { if((lResult = PrepareEpos(g_pSubKeyHandle, g_nodeIdList[i], &ulErrorCode))==MMC_FAILED) { LogError("PrepareSubEpos ID = ", lResult, ulErrorCode , g_nodeIdList[i]); } } } unsigned int MaxAcceleration = 10000; if((lResult = VCS_GetMaxFollowingError(g_pKeyHandle, g_usNodeId, &pMaxFollowingError, &ulErrorCode))==MMC_FAILED) { LogError("VCS_GetMaxFollowingError", lResult, ulErrorCode); } if((lResult = VCS_GetMaxProfileVelocity(g_pKeyHandle, g_usNodeId, &pMaxProfileVelocity, &ulErrorCode))==MMC_FAILED) { LogError("VCS_GetMaxProfileVelocity", lResult, ulErrorCode); } if((lResult = VCS_SetMaxProfileVelocity(g_pKeyHandle, g_usNodeId, pMaxProfileVelocity, &ulErrorCode))==MMC_FAILED) { LogError("VCS_SetMaxProfileVelocity", lResult, ulErrorCode); } if((lResult = VCS_SetMaxAcceleration(g_pKeyHandle, g_usNodeId, MaxAcceleration, &ulErrorCode))==MMC_FAILED) { LogError("VCS_SetMaxAcceleration", lResult, ulErrorCode); } if((lResult = VCS_GetMaxAcceleration(g_pKeyHandle, g_usNodeId, &pMaxAcceleration, &ulErrorCode))==MMC_FAILED) { LogError("VCS_GetMaxAcceleration", lResult, ulErrorCode); } for(int i = 1; i < g_motors; i++) { if((lResult = VCS_GetMaxFollowingError(g_pSubKeyHandle, g_nodeIdList[i], &pMaxFollowingError, &ulErrorCode))==MMC_FAILED) { LogError("VCS_GetMaxFollowingError", lResult, ulErrorCode, g_nodeIdList[i]); } if((lResult = VCS_GetMaxProfileVelocity(g_pSubKeyHandle, g_nodeIdList[i], &pMaxProfileVelocity, &ulErrorCode))==MMC_FAILED) { LogError("VCS_GetMaxProfileVelocity", lResult, ulErrorCode, g_nodeIdList[i]); } if((lResult = VCS_SetMaxAcceleration(g_pSubKeyHandle, g_nodeIdList[i], MaxAcceleration, &ulErrorCode))==MMC_FAILED) { LogError("VCS_SetMaxAcceleration", lResult, ulErrorCode, g_nodeIdList[i]); } if((lResult = VCS_GetMaxAcceleration(g_pSubKeyHandle, g_nodeIdList[i], &pMaxAcceleration, &ulErrorCode))==MMC_FAILED) { LogError("VCS_GetMaxAcceleration", lResult, ulErrorCode, g_nodeIdList[i]); } std::cout<<"ID: "<<g_nodeIdList[i]<<", pMaxFollowingError: "<<pMaxFollowingError<<", pMaxProfileVelocity: "<<pMaxProfileVelocity<<", pMaxAcceleration: "<<pMaxAcceleration<<std::endl; } LogInfo("Initialization successful"); return lResult; } int EposCommunication::setHomingParameter(unsigned short p_usNodeId, unsigned int p_Velocity) { //to use set variables below first! p_Velocity = (p_Velocity > pMaxProfileVelocity) ? pMaxProfileVelocity : p_Velocity; int lResult = MMC_SUCCESS; unsigned int *ulErrorCode = 0; unsigned int homing_acceleration = pMaxAcceleration; unsigned int speed_switch = p_Velocity; unsigned int speed_index = p_Velocity; int home_offset = 0; unsigned short current_threshold = 0; int home_position = 0; HANDLE p_DeviceHandle = (p_usNodeId == g_usNodeId) ? g_pKeyHandle : g_pSubKeyHandle; if(VCS_SetHomingParameter(p_DeviceHandle, p_usNodeId, homing_acceleration, speed_switch, speed_index, home_offset, current_threshold, home_position, ulErrorCode) == MMC_FAILED) { lResult = MMC_FAILED; LogError("VCS_SetHomingParameter", lResult, *ulErrorCode); } return lResult; } int EposCommunication::homing(unsigned short p_usNodeId, bool refind) { int lResult = MMC_FAILED; unsigned int ulErrorCode = 0; signed char homing_method; if(refind) homing_method = HM_HOME_SWITCH_NEGATIVE_SPEED; else homing_method = HM_HOME_SWITCH_NEGATIVE_SPEED; //Start homing mode: if((lResult = HomingMode(p_usNodeId, &ulErrorCode))==MMC_FAILED) { LogError("HomingMode", lResult, ulErrorCode); } //Find home: if((lResult = FindHome(p_usNodeId, homing_method, &ulErrorCode))==MMC_FAILED) { LogError("FindHome", lResult, ulErrorCode); } return lResult; } int EposCommunication::homingSuccess(unsigned short p_usNodeId) { int lResult = MMC_FAILED; unsigned int ulErrorCode = 0; // if((lResult = HomingSuccess(p_usNodeId, &ulErrorCode))==MMC_FAILED) // { // LogError("HomingSuccess", lResult, ulErrorCode); // } return HomingSuccess(p_usNodeId, &ulErrorCode); } int EposCommunication::startPositionMode(std::vector<int> id_list) { int lResult = MMC_FAILED; unsigned int ulErrorCode = 0; for (std::vector<int>::iterator it = id_list.begin() ; it != id_list.end(); ++it) { HANDLE p_DeviceHandle = (*it == g_usNodeId) ? g_pKeyHandle : g_pSubKeyHandle; if((lResult = ActivatePositionMode(p_DeviceHandle, *it, &ulErrorCode))==MMC_FAILED) { LogError("ActivatePositionMode", lResult, ulErrorCode, *it); } } return lResult; } int EposCommunication::startVolicityMode(std::vector<int> id_list) { int lResult = MMC_FAILED; unsigned int ulErrorCode = 0; for (std::vector<int>::iterator it = id_list.begin() ; it != id_list.end(); ++it) { HANDLE p_DeviceHandle = (*it == g_usNodeId) ? g_pKeyHandle : g_pSubKeyHandle; if((lResult = ActivateVelocityMode(p_DeviceHandle, *it, &ulErrorCode))==MMC_FAILED) { LogError("ActivateVelocityMode Sub", lResult, ulErrorCode, *it); } } return lResult; } int EposCommunication::setPositionProfile(unsigned short p_usNodeId, double profile_velocity, double profile_acceleration = 1000, double profile_deceleration = 1000) { unsigned int ulErrorCode = 0; int lResult = MMC_SUCCESS; HANDLE p_DeviceHandle = (p_usNodeId == g_usNodeId) ? g_pKeyHandle : g_pSubKeyHandle; int vel_rpm = radsToRpm(profile_velocity); if(vel_rpm == 0) return lResult; if(VCS_SetPositionProfile(p_DeviceHandle, p_usNodeId, vel_rpm, radsToRpm(profile_acceleration), radsToRpm(profile_deceleration), &ulErrorCode) == MMC_FAILED) { lResult = MMC_FAILED; LogError("VCS_SetPositionProfile", lResult, ulErrorCode, p_usNodeId); std::cout<< "radsToRpm(profile_velocity) = "<< radsToRpm(profile_velocity)<<std::endl; } return lResult; } bool EposCommunication::deviceOpenedCheck() { return deviceOpenedCheckStatus; } int EposCommunication::setPosition(unsigned short p_usNodeId, double position_setpoint){ //Set position, call this function in service callback: int lResult = MMC_SUCCESS; unsigned int ulErrorCode = 0; HANDLE p_DeviceHandle = (p_usNodeId == g_usNodeId) ? g_pKeyHandle : g_pSubKeyHandle; //Safety check setpoint and homing: if(position_setpoint <= M_PI && position_setpoint >= -1 * M_PI) { bool absolute = true; if(VCS_MoveToPosition(p_DeviceHandle, p_usNodeId, radsToCounts(position_setpoint), absolute, 1, &ulErrorCode) == MMC_FAILED) { lResult = MMC_FAILED; LogError("VCS_MoveToPosition", lResult, ulErrorCode, p_usNodeId); } else{ // ROS_INFO("Movement executed."); } } return lResult; } int EposCommunication::setPositionMust(unsigned short p_usNodeId, double& position_setpoint) { int lResult = MMC_SUCCESS; unsigned int ulErrorCode = 0; HANDLE p_DeviceHandle = (p_usNodeId == g_usNodeId) ? g_pKeyHandle : g_pSubKeyHandle; if(VCS_SetPositionMust(p_DeviceHandle, p_usNodeId, radsToCounts(position_setpoint), &ulErrorCode) == MMC_FAILED) { LogError("VCS_SetPositionMust", lResult, ulErrorCode, p_usNodeId); std::cout<<"position_setpoint: "<<position_setpoint<<", to counts: "<<radsToCounts(position_setpoint)<<std::endl; lResult = MMC_FAILED; } else{ // ROS_INFO("Movement executed."); } return lResult; } int EposCommunication::setVelocityMust(unsigned short p_usNodeId, double& velocity_setpoint) { int lResult = MMC_SUCCESS; unsigned int ulErrorCode = 0; HANDLE p_DeviceHandle = (p_usNodeId == g_usNodeId) ? g_pKeyHandle : g_pSubKeyHandle; long velocity_cmd = (fabs(radsToRpm(velocity_setpoint)) > pMaxProfileVelocity) ? ((velocity_setpoint > 0) - (velocity_setpoint < 0)) * pMaxProfileVelocity : radsToRpm(velocity_setpoint); if(VCS_SetVelocityMust(p_DeviceHandle, p_usNodeId, radsToRpm(velocity_setpoint), &ulErrorCode) == MMC_FAILED) { LogError("VCS_SetVelocityMust", lResult, ulErrorCode, p_usNodeId); std::cout<<"velocity_setpoint: "<<velocity_setpoint<<", to counts: "<<radsToRpm(velocity_setpoint)<<std::endl; lResult = MMC_FAILED; } else{ // ROS_INFO("Movement executed."); } return lResult; } int EposCommunication::getPosition(unsigned short p_usNodeId, double* pPositionIs) { unsigned int ulErrorCode = 0; int pPositionIsCounts = 0; HANDLE p_DeviceHandle = (p_usNodeId == g_usNodeId) ? g_pKeyHandle : g_pSubKeyHandle; // if((lResult = GetPosition(&pPositionIsCounts, &ulErrorCode))==MMC_FAILED) // { // LogError("getPosition", lResult, ulErrorCode); // return lResult; // } int lResult = MMC_SUCCESS; if(VCS_GetPositionIs(p_DeviceHandle, p_usNodeId, &pPositionIsCounts, &ulErrorCode) == MMC_FAILED) { lResult = MMC_FAILED; LogError("VCS_GetPositionIs", lResult, ulErrorCode, p_usNodeId); } *pPositionIs = countsToRads(pPositionIsCounts); //only for Debugging //ROS_INFO_STREAM("!!! pPositionIs: " << *pPositionIs << " pPositionIsCounts: " << pPositionIsCounts); return lResult; } int EposCommunication::getVelocity(unsigned short p_usNodeId, double* pVelocityIs) { unsigned int ulErrorCode = 0; int pVelocityIsCounts; HANDLE p_DeviceHandle = (p_usNodeId == g_usNodeId) ? g_pKeyHandle : g_pSubKeyHandle; // if((lResult = GetVelocity(&pVelocityIsCounts, &ulErrorCode))==MMC_FAILED) // { // LogError("getVelocity", lResult, ulErrorCode); // return lResult; // } int lResult = MMC_SUCCESS; if(VCS_GetVelocityIs(p_DeviceHandle, p_usNodeId, &pVelocityIsCounts, &ulErrorCode) == MMC_FAILED) { lResult = MMC_FAILED; LogError("VCS_GetVelocityIs", lResult, ulErrorCode, p_usNodeId); } *pVelocityIs = rpmToRads(pVelocityIsCounts); return lResult; } void EposCommunication::resetHomePoseition(unsigned short p_usNodeId) { int moto_pos = 0; unsigned int ulErrorCode = 0; int lResult = MMC_SUCCESS; HANDLE p_DeviceHandle = (p_usNodeId == g_usNodeId) ? g_pKeyHandle : g_pSubKeyHandle; lResult = VCS_GetPositionIs(p_DeviceHandle, p_usNodeId, &moto_pos, &ulErrorCode); lResult = VCS_SetPositionMust(p_DeviceHandle, p_usNodeId, moto_pos, &ulErrorCode); lResult = VCS_ActivateHomingMode(p_DeviceHandle, p_usNodeId, &ulErrorCode); int home_pos; if(moto_pos > 0) home_pos = moto_pos - radsToCounts(2 * M_PI / swerve_gear_ratio); else home_pos = radsToCounts(2 * M_PI / swerve_gear_ratio) - moto_pos; lResult = VCS_DefinePosition(p_DeviceHandle, p_usNodeId, home_pos, &ulErrorCode); lResult = VCS_ActivatePositionMode(p_DeviceHandle, p_usNodeId, &ulErrorCode); if(lResult == MMC_FAILED) LogError("resetHomePoseition Failed", lResult, ulErrorCode, p_usNodeId); return; } int EposCommunication::closeDevice(){ //Close device: int lResult = MMC_FAILED; unsigned int ulErrorCode = 0; if((lResult = CloseDevice(&ulErrorCode))==MMC_FAILED) { LogError("CloseDevice", lResult, ulErrorCode); return lResult; } return lResult; } double EposCommunication::countsToRads(const int& counts){ double mm = 2 * M_PI * (counts) / 2048. / (103275.0/3211.0); return mm; } int EposCommunication::radsToCounts(const double& mm){ int counts = mm * 2048 * (103275.0/3211.0) / (2 * M_PI); // ROS_INFO_STREAM("counts: " << counts); return counts; } int EposCommunication::radsToRpm(const double& rads) { int rpm; rpm = rads * (103275.0/3211.0) * 60 / (2 * M_PI); return rpm; } double EposCommunication::rpmToRads(const int& rpm) { double rads; rads = (rpm) / (103275.0/3211.0) / 60. * (2 * M_PI); return rads; } /* workflow: * initialize, setPosition, closeDevice */ } /* namespace */
29.186293
201
0.732811
[ "vector" ]
821891c8132e7a13ee7afa2b3be63448700ceaad
32,580
cc
C++
src/shard.cc
manopapad/legate.numpy
896f4fd9b32db445da6cdabf7b78d523fca96936
[ "Apache-2.0" ]
null
null
null
src/shard.cc
manopapad/legate.numpy
896f4fd9b32db445da6cdabf7b78d523fca96936
[ "Apache-2.0" ]
null
null
null
src/shard.cc
manopapad/legate.numpy
896f4fd9b32db445da6cdabf7b78d523fca96936
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "shard.h" #include <cmath> #define MAX(x, y) (((x) > (y)) ? (x) : (y)) using namespace Legion; namespace legate { namespace numpy { /*static*/ NumPyShardingFunctor* NumPyShardingFunctor::sharding_functors[NUMPY_SHARD_LAST]; struct Comparator2D { public: bool operator()(const std::pair<Point<2>, size_t>& left, const std::pair<Point<2>, size_t>& right) const { if (left.first[0] < right.first[0]) return true; else if (left.first[0] > right.first[0]) return false; else if (left.first[1] < right.first[1]) return true; else if (left.first[1] > right.first[1]) return false; else return (left.second < right.second); } }; // This is a little ugly, but it will allow us to memoize some common // computations in a way that doesn't require locks __thread std::map<std::pair<Point<2>, size_t>, std::pair<Point<2>, Point<2>>, Comparator2D>* chunks2d = NULL; static inline Point<2> compute_chunks_2d(const Point<2> bounds, size_t shards, Point<2>& pieces) { const std::pair<Point<2>, size_t> key(bounds, shards); // First check to see if we already did this computation if (chunks2d != NULL) { std::map<std::pair<Point<2>, size_t>, std::pair<Point<2>, Point<2>>, Comparator2D>:: const_iterator finder = chunks2d->find(key); if (finder != chunks2d->end()) { pieces = finder->second.first; return finder->second.second; } } else { // We're going to need this eventually chunks2d = new std::map<std::pair<Point<2>, size_t>, std::pair<Point<2>, Point<2>>, Comparator2D>(); } // Didn't find it so we have to compute it const bool swap = (bounds[0] > bounds[1]); double nx = swap ? (double)bounds[1] : (double)bounds[0]; double ny = swap ? (double)bounds[0] : (double)bounds[1]; double n = sqrt(shards * nx / ny); // need to constrain n to be an integer with shards % n == 0 // try rounding n both up and down int n1 = floor(n + 1.e-12); n1 = MAX(n1, 1); while (shards % n1 != 0) --n1; int n2 = ceil(n - 1.e-12); n2 = MAX(n2, 1); while (shards % n2 != 0) ++n2; // pick whichever of n1 and n2 gives blocks closest to square, // i.e. gives the shortest long side double longside1 = MAX(nx / n1, ny / (shards / n1)); double longside2 = MAX(nx / n2, ny / (shards / n2)); size_t shardx = (longside1 <= longside2 ? n1 : n2); size_t shardy = shards / shardx; pieces = Point<2>(swap ? shardy : shardx, swap ? shardx : shardy); // Now we can compute the chunk size for each dimension Point<2> chunks = (bounds + pieces - Point<2>::ONES()) / pieces; chunks[0] = MAX(chunks[0], coord_t{1}); chunks[1] = MAX(chunks[1], coord_t{1}); // Save the result (*chunks2d)[key] = std::pair<Point<2>, Point<2>>(pieces, chunks); return chunks; } NumPyShardingFunctor::NumPyShardingFunctor(NumPyShardingCode c) : code(c) {} NumPyShardingFunctor_1D::NumPyShardingFunctor_1D(NumPyShardingCode c) : NumPyShardingFunctor(c) {} ShardID NumPyShardingFunctor_1D::shard(const DomainPoint& p, const Domain& launch_space, const size_t total_shards) { // This one is easy, just chunk it const Point<1> point = p; const Rect<1> space = launch_space; switch (code) { case NUMPY_SHARD_TILE_1D: { const size_t size = (space.hi[0] - space.lo[0]) + 1; const size_t chunk = (size + total_shards - 1) / total_shards; return (point[0] - space.lo[0]) / chunk; } default: assert(false); // not handling any other cases currently } // Appease the compiler return 0; } unsigned NumPyShardingFunctor_1D::localize(const DomainPoint& p, const Domain& launch_space, const size_t total_shards, const ShardID local_shard) { // This one is easy, just chunk it const Point<1> point = p; const Rect<1> space = launch_space; switch (code) { case NUMPY_SHARD_TILE_1D: { const size_t size = (space.hi[0] - space.lo[0]) + 1; const coord_t chunk = (size + total_shards - 1) / total_shards; const coord_t start = local_shard * chunk + space.lo[0]; assert(point[0] >= start); assert(point[0] < (start + chunk)); return (point[0] - start); } default: assert(false); // not handling any other cases currently } // Appease the compiler return 0; } NumPyShardingFunctor_2D::NumPyShardingFunctor_2D(NumPyShardingCode c) : NumPyShardingFunctor(c) {} ShardID NumPyShardingFunctor_2D::shard(const DomainPoint& p, const Domain& launch_space, const size_t total_shards) { const Point<2> point = p; const Rect<2> space = launch_space; const Point<2> bounds = (space.hi - space.lo) + Point<2>::ONES(); Point<2> pieces; const Point<2> chunks = compute_chunks_2d(bounds, total_shards, pieces); const coord_t x = (point[0] - space.lo[0]) / chunks[0]; const coord_t y = (point[1] - space.lo[1]) / chunks[1]; switch (code) { case NUMPY_SHARD_TILE_2D: { // Now linearlize chunk coordinates onto shards return (y * pieces[0] + x); } case NUMPY_SHARD_TILE_2D_YX: { // Linearize in the opposite way return (x * pieces[1] + y); } default: assert(false); // not handling any other cases currently } // Appease the compiler return 0; } unsigned NumPyShardingFunctor_2D::localize(const DomainPoint& p, const Domain& launch_space, const size_t total_shards, const ShardID local_shard) { const Point<2> point = p; const Rect<2> space = launch_space; const Point<2> bounds = (space.hi - space.lo) + Point<2>::ONES(); Point<2> pieces; const Point<2> chunks = compute_chunks_2d(bounds, total_shards, pieces); switch (code) { case NUMPY_SHARD_TILE_2D: { const size_t shard_x = local_shard % pieces[0]; const size_t shard_y = local_shard / pieces[0]; const coord_t start_x = shard_x * chunks[0] + space.lo[0]; const coord_t start_y = shard_y * chunks[1] + space.lo[1]; assert(point[0] >= start_x); assert(point[0] < (start_x + chunks[0])); assert(point[1] >= start_y); assert(point[1] < (start_y + chunks[1])); return (point[1] - start_y) * chunks[0] + (point[0] - start_x); } case NUMPY_SHARD_TILE_2D_YX: { const size_t shard_y = local_shard % pieces[1]; const size_t shard_x = local_shard / pieces[1]; const coord_t start_x = shard_x * chunks[0] + space.lo[0]; const coord_t start_y = shard_y * chunks[1] + space.lo[1]; assert(point[0] >= start_x); assert(point[0] < (start_x + chunks[0])); assert(point[1] >= start_y); assert(point[1] < (start_y + chunks[1])); // Linearize in the opposite way return (point[0] - start_x) * chunks[1] + (point[1] - start_y); } default: assert(false); // not handling any other cases currently } // Appease the compiler return 0; } NumPyShardingFunctor_2D_1D::NumPyShardingFunctor_2D_1D(NumPyShardingCode c) : NumPyShardingFunctor(c) { } ShardID NumPyShardingFunctor_2D_1D::shard(const DomainPoint& p, const Domain& launch_space, const size_t total_shards) { #if 0 const Point<2> point = p; const Rect<2> space = launch_space; #endif switch (code) { default: assert(false); // not handling any other cases currently } // Appease the compiler return 0; } unsigned NumPyShardingFunctor_2D_1D::localize(const DomainPoint& p, const Domain& launch_space, const size_t total_shards, const ShardID local_shard) { #if 0 const Point<2> point = p; const Rect<2> space = launch_space; #endif switch (code) { default: assert(false); // not handling any other cases currently } // Appease the compiler return 0; } NumPyShardingFunctor_3D::NumPyShardingFunctor_3D(NumPyShardingCode c) : NumPyShardingFunctor(c) {} ShardID NumPyShardingFunctor_3D::shard(const DomainPoint& p, const Domain& launch_space, const size_t total_shards) { // TODO: make this properly block things // For now linearize and compute const Point<3> point = p; const Rect<3> space = launch_space; coord_t pitch = 1; coord_t linear_point = 0; for (int i = 2; i >= 0; i--) { linear_point += point[i] * pitch; pitch *= ((space.hi[i] - space.lo[i]) + 1); } return linear_point % total_shards; } unsigned NumPyShardingFunctor_3D::localize(const DomainPoint& p, const Domain& launch_space, const size_t total_shards, const ShardID local_shard) { // TODO: make this properly block things // For now linearize and compute const Point<3> point = p; const Rect<3> space = launch_space; coord_t pitch = 1; coord_t linear_point = 0; for (int i = 2; i >= 0; i--) { linear_point += point[i] * pitch; pitch *= ((space.hi[i] - space.lo[i]) + 1); } return linear_point / total_shards; } NumPyShardingFunctor_3D_2D::NumPyShardingFunctor_3D_2D(NumPyShardingCode c) : NumPyShardingFunctor(c) { } ShardID NumPyShardingFunctor_3D_2D::shard(const DomainPoint& p, const Domain& launch_space, const size_t total_shards) { const Point<3> point = p; const Rect<3> space = launch_space; switch (code) { case NUMPY_SHARD_TILE_3D_2D_XY: { const Point<2> bounds((space.hi[0] - space.lo[0]) + 1, (space.hi[1] - space.lo[1]) + 1); Point<2> pieces; const Point<2> chunks = compute_chunks_2d(bounds, total_shards, pieces); const coord_t x = (point[0] - space.lo[0]) / chunks[0]; const coord_t y = (point[1] - space.lo[1]) / chunks[1]; // Now linearlize chunk coordinates onto shards return (y * pieces[0] + x); } case NUMPY_SHARD_TILE_3D_2D_XZ: { const Point<2> bounds((space.hi[0] - space.lo[0]) + 1, (space.hi[2] - space.lo[2]) + 1); Point<2> pieces; const Point<2> chunks = compute_chunks_2d(bounds, total_shards, pieces); const coord_t x = (point[0] - space.lo[0]) / chunks[0]; const coord_t y = (point[2] - space.lo[2]) / chunks[1]; // Now linearlize chunk coordinates onto shards return (y * pieces[0] + x); } case NUMPY_SHARD_TILE_3D_2D_YZ: { const Point<2> bounds((space.hi[1] - space.lo[1]) + 1, (space.hi[2] - space.lo[2]) + 1); Point<2> pieces; const Point<2> chunks = compute_chunks_2d(bounds, total_shards, pieces); const coord_t x = (point[1] - space.lo[1]) / chunks[0]; const coord_t y = (point[2] - space.lo[2]) / chunks[1]; // Now linearlize chunk coordinates onto shards return (y * pieces[0] + x); } default: assert(false); } // Appease the compiler return 0; } unsigned NumPyShardingFunctor_3D_2D::localize(const DomainPoint& p, const Domain& launch_space, const size_t total_shards, const ShardID local_shard) { const Point<3> point = p; const Rect<3> space = launch_space; switch (code) { case NUMPY_SHARD_TILE_3D_2D_XY: { const Point<2> bounds((space.hi[0] - space.lo[0]) + 1, (space.hi[1] - space.lo[1]) + 1); Point<2> pieces; const Point<2> chunks = compute_chunks_2d(bounds, total_shards, pieces); const size_t shard_x = local_shard % pieces[0]; const size_t shard_y = local_shard / pieces[0]; const coord_t start_x = shard_x * chunks[0] + space.lo[0]; const coord_t start_y = shard_y * chunks[1] + space.lo[1]; assert(point[0] >= start_x); assert(point[0] < (start_x + chunks[0])); assert(point[1] >= start_y); assert(point[1] < (start_y + chunks[1])); return (point[1] - start_y) * chunks[0] + (point[0] - start_x); } case NUMPY_SHARD_TILE_3D_2D_XZ: { const Point<2> bounds((space.hi[0] - space.lo[0]) + 1, (space.hi[2] - space.lo[2]) + 1); Point<2> pieces; const Point<2> chunks = compute_chunks_2d(bounds, total_shards, pieces); const size_t shard_x = local_shard % pieces[0]; const size_t shard_y = local_shard / pieces[0]; const coord_t start_x = shard_x * chunks[0] + space.lo[0]; const coord_t start_y = shard_y * chunks[1] + space.lo[2]; assert(point[0] >= start_x); assert(point[0] < (start_x + chunks[0])); assert(point[2] >= start_y); assert(point[2] < (start_y + chunks[1])); return (point[2] - start_y) * chunks[0] + (point[0] - start_x); } case NUMPY_SHARD_TILE_3D_2D_YZ: { const Point<2> bounds((space.hi[1] - space.lo[1]) + 1, (space.hi[2] - space.lo[2]) + 1); Point<2> pieces; const Point<2> chunks = compute_chunks_2d(bounds, total_shards, pieces); const size_t shard_x = local_shard % pieces[0]; const size_t shard_y = local_shard / pieces[0]; const coord_t start_x = shard_x * chunks[0] + space.lo[1]; const coord_t start_y = shard_y * chunks[1] + space.lo[2]; assert(point[1] >= start_x); assert(point[1] < (start_x + chunks[0])); assert(point[2] >= start_y); assert(point[2] < (start_y + chunks[1])); return (point[2] - start_y) * chunks[0] + (point[1] - start_x); } default: assert(false); } // Appease the compiler return 0; } template <int DIM, int RADIX> NumPyShardingFunctor_Radix2D<DIM, RADIX>::NumPyShardingFunctor_Radix2D(NumPyShardingCode c) : NumPyShardingFunctor(c) { assert(RADIX > 0); } template <int DIM, int RADIX> ShardID NumPyShardingFunctor_Radix2D<DIM, RADIX>::shard(const DomainPoint& p, const Domain& launch_space, const size_t total_shards) { // Tile-shard based on non-reduced dimension const Point<2> point = p; const Rect<2> space = launch_space; const size_t size = space.hi[1 - DIM] - space.lo[1 - DIM] + 1; const size_t chunk = (size + total_shards - 1) / total_shards; return (point[1 - DIM] - space.lo[1 - DIM]) / chunk; } template <int DIM, int RADIX> unsigned NumPyShardingFunctor_Radix2D<DIM, RADIX>::localize(const DomainPoint& p, const Domain& launch_space, const size_t total_shards, const ShardID local_shard) { // Tile-shard based on non-reduced dimension const Point<2> point = p; const Rect<2> space = launch_space; const size_t size = space.hi[1 - DIM] - space.lo[1 - DIM] + 1; const coord_t chunk = (size + total_shards - 1) / total_shards; const coord_t start = local_shard * chunk + space.lo[1 - DIM]; assert(point[1 - DIM] >= start); assert(point[1 - DIM] < (start + chunk)); return point[1 - DIM] - start; } template <int DIM, int RADIX> NumPyShardingFunctor_Radix3D<DIM, RADIX>::NumPyShardingFunctor_Radix3D(NumPyShardingCode c) : NumPyShardingFunctor(c) { assert(RADIX > 0); } template <int DIM, int RADIX> ShardID NumPyShardingFunctor_Radix3D<DIM, RADIX>::shard(const DomainPoint& p, const Domain& launch_space, const size_t total_shards) { const Point<3> point = p; const Rect<3> space = launch_space; // See if this is an inner product case or not if ((space.lo[(DIM + 1) % 3] == space.hi[(DIM + 1) % 3]) && (space.lo[(DIM + 2) % 3] == space.hi[(DIM + 2) % 3])) { // Inner-product case const coord_t num_pieces = (space.hi[DIM] - space.lo[DIM]) + 1; const coord_t chunk = (num_pieces + total_shards - 1) / total_shards; return point[DIM] / chunk; } else { // Normal case const coord_t collapsed_size = (space.hi[DIM] - space.lo[DIM]) + 1; const coord_t one_size = (space.hi[(DIM + 1) % 3] - space.lo[(DIM + 1) % 3]) + 1; const coord_t two_size = (space.hi[(DIM + 2) % 3] - space.lo[(DIM + 2) % 3]) + 1; // One of the two other sizes should be the same as the collapsing one assert((one_size == collapsed_size) || (two_size == collapsed_size)); // Figure out which dimension is partitioned the same as the collapsing dim const Point<2> bounds((DIM == 1) ? two_size : one_size, (DIM == 1) ? one_size : two_size); Point<2> pieces; const Point<2> chunks = compute_chunks_2d(bounds, total_shards, pieces); if (DIM == 0) { if (one_size == collapsed_size) { const coord_t x = point[0] * RADIX / chunks[0]; const coord_t y = point[1] / chunks[0]; const coord_t z = point[2] / chunks[1]; return z * pieces[0] + x + (y % RADIX); } else { const coord_t x = point[0] * RADIX / chunks[1]; const coord_t y = point[1] / chunks[0]; const coord_t z = point[2] / chunks[1]; return (x + (z % RADIX)) * pieces[0] + y; } } else if (DIM == 1) { if (one_size == collapsed_size) { const coord_t x = point[0] / chunks[0]; const coord_t y = point[1] * RADIX / chunks[0]; const coord_t z = point[2] / chunks[1]; return z * pieces[0] + y + (x % RADIX); } else { const coord_t x = point[0] / chunks[0]; const coord_t y = point[1] * RADIX / chunks[1]; const coord_t z = point[2] / chunks[1]; return (y + (z % RADIX)) * pieces[0] + x; } } else if (DIM == 2) { if (one_size == collapsed_size) { const coord_t x = point[0] / chunks[0]; const coord_t y = point[1] / chunks[1]; const coord_t z = point[2] * RADIX / chunks[0]; return y * pieces[0] + z + (x % RADIX); } else { const coord_t x = point[0] / chunks[0]; const coord_t y = point[1] / chunks[1]; const coord_t z = point[2] * RADIX / chunks[1]; return (z + (y % RADIX)) * pieces[0] + x; } } } // Should never get here assert(false); return 0; } template <int DIM, int RADIX> unsigned NumPyShardingFunctor_Radix3D<DIM, RADIX>::localize(const DomainPoint& p, const Domain& launch_space, const size_t total_shards, const ShardID local_shard) { const Point<3> point = p; const Rect<3> space = launch_space; // See if this is an inner product case or not if ((space.lo[(DIM + 1) % 3] == space.hi[(DIM + 1) % 3]) && (space.lo[(DIM + 2) % 3] == space.hi[(DIM + 2) % 3])) { // Inner product case const coord_t num_pieces = (space.hi[DIM] - space.lo[DIM]) + 1; const coord_t chunk = (num_pieces + total_shards - 1) / total_shards; assert((local_shard * chunk) <= point[DIM]); assert(point[DIM] < ((local_shard + 1) * chunk)); // Compute the offset within our local shard return (point[DIM] - local_shard * chunk); } else { // Normal case const coord_t collapsed_size = (space.hi[DIM] - space.lo[DIM]) + 1; const coord_t one_size = (space.hi[(DIM + 1) % 3] - space.lo[(DIM + 1) % 3]) + 1; const coord_t two_size = (space.hi[(DIM + 2) % 3] - space.lo[(DIM + 2) % 3]) + 1; // One of the two other sizes should be the same as the collapsing one // MZ: commenting out this assert for test correctness, but this needs to be looked at further // assert((one_size == collapsed_size) || (two_size == collapsed_size)); // Figure out which dimension is partitioned the same as the collapsing dim const Point<2> bounds((DIM == 1) ? two_size : one_size, (DIM == 1) ? one_size : two_size); Point<2> pieces; const Point<2> chunks = compute_chunks_2d(bounds, total_shards, pieces); if (DIM == 0) { if (one_size == collapsed_size) { const coord_t x = (point[0] * RADIX) % chunks[0]; const coord_t y = point[1] % chunks[0]; const coord_t z = point[2] % chunks[1]; return z * chunks[0] + x + (y % RADIX); } else { const coord_t x = (point[0] * RADIX) % chunks[1]; const coord_t y = point[1] % chunks[0]; const coord_t z = point[2] % chunks[1]; return (x + (z % RADIX)) * chunks[0] + y; } } else if (DIM == 1) { if (one_size == collapsed_size) { const coord_t x = point[0] % chunks[0]; const coord_t y = (point[1] * RADIX) % chunks[0]; const coord_t z = point[2] / chunks[1]; return z * chunks[0] + y + (x % RADIX); } else { const coord_t x = point[0] % chunks[0]; const coord_t y = (point[1] * RADIX) % chunks[1]; const coord_t z = point[2] % chunks[1]; return (y + (z % RADIX)) * chunks[0] + x; } } else if (DIM == 2) { if (one_size == collapsed_size) { const coord_t x = point[0] % chunks[0]; const coord_t y = point[1] % chunks[1]; const coord_t z = (point[2] * RADIX) % chunks[0]; return y * chunks[0] + z + (x % RADIX); } else { const coord_t x = point[0] % chunks[0]; const coord_t y = point[1] % chunks[1]; const coord_t z = (point[2] * RADIX) % chunks[1]; return (z + (y % RADIX)) * chunks[0] + x; } } } // Should never get here assert(false); return 0; } template <int M, typename BASE> NumPyTransformShardingFunctor<M, BASE>::NumPyTransformShardingFunctor(NumPyShardingCode code, const long* data, unsigned n) : BASE(code), N(n), transform((long*)malloc(M * (N + 1) * sizeof(long))) { memcpy(transform, data, M * (N + 1) * sizeof(long)); } template <int M, typename BASE> NumPyTransformShardingFunctor<M, BASE>::~NumPyTransformShardingFunctor(void) { free(transform); } template <int M, typename BASE> ShardID NumPyTransformShardingFunctor<M, BASE>::shard(const DomainPoint& p, const Domain& launch_space, const size_t total_shards) { assert(p.get_dim() == N); assert(launch_space.get_dim() == M); DomainPoint point; point.dim = M; for (unsigned i = 0; i < M; i++) { point.point_data[i] = transform[i * (N + 1) + N]; // offset for (unsigned j = 0; j < N; j++) point.point_data[i] += transform[i * (N + 1) + j] * p.point_data[j]; } return BASE::shard(point, launch_space, total_shards); } template <int M, typename BASE> unsigned NumPyTransformShardingFunctor<M, BASE>::localize(const DomainPoint& p, const Domain& launch_space, size_t total_shards, const ShardID local_shard) { assert(p.get_dim() == N); assert(launch_space.get_dim() == M); DomainPoint point; point.dim = M; for (unsigned i = 0; i < M; i++) { point.point_data[i] = transform[i * (N + 1) + N]; // offset for (unsigned j = 0; j < N; j++) point.point_data[i] += transform[i * (N + 1) + j] * p.point_data[j]; } return BASE::localize(point, launch_space, total_shards, local_shard); } // Some template help for unrolling template <int X, int P> struct Pow { enum { result = X * Pow<X, P - 1>::result }; }; template <int X> struct Pow<X, 0> { enum { result = 1 }; }; template <int X> struct Pow<X, 1> { enum { result = X }; }; template <typename T> static void register_functor(Runtime* runtime, ShardingID offset, NumPyShardingCode code) { T* functor = new T(code); runtime->register_sharding_functor( (ShardingID)(offset + code), functor, true /*silence warnings*/); // Save this is in the mapper sharding functors array assert(code < NUMPY_SHARD_LAST); NumPyShardingFunctor::sharding_functors[code] = functor; } /*static*/ void NumPyShardingFunctor::register_sharding_functors(Runtime* runtime, ShardingID offset) { register_functor<NumPyShardingFunctor_1D>(runtime, offset, NUMPY_SHARD_TILE_1D); register_functor<NumPyShardingFunctor_2D>(runtime, offset, NUMPY_SHARD_TILE_2D); register_functor<NumPyShardingFunctor_3D>(runtime, offset, NUMPY_SHARD_TILE_3D); register_functor<NumPyShardingFunctor_2D>(runtime, offset, NUMPY_SHARD_TILE_2D_YX); register_functor<NumPyShardingFunctor_3D_2D>(runtime, offset, NUMPY_SHARD_TILE_3D_2D_XY); register_functor<NumPyShardingFunctor_3D_2D>(runtime, offset, NUMPY_SHARD_TILE_3D_2D_XZ); register_functor<NumPyShardingFunctor_3D_2D>(runtime, offset, NUMPY_SHARD_TILE_3D_2D_YZ); register_functor<NumPyShardingFunctor_Radix2D<0, Pow<NUMPY_RADIX, 1>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_X_1); register_functor<NumPyShardingFunctor_Radix2D<0, Pow<NUMPY_RADIX, 2>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_X_2); register_functor<NumPyShardingFunctor_Radix2D<0, Pow<NUMPY_RADIX, 3>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_X_3); register_functor<NumPyShardingFunctor_Radix2D<0, Pow<NUMPY_RADIX, 4>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_X_4); register_functor<NumPyShardingFunctor_Radix2D<0, Pow<NUMPY_RADIX, 5>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_X_5); register_functor<NumPyShardingFunctor_Radix2D<0, Pow<NUMPY_RADIX, 6>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_X_6); register_functor<NumPyShardingFunctor_Radix2D<0, Pow<NUMPY_RADIX, 7>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_X_7); register_functor<NumPyShardingFunctor_Radix2D<0, Pow<NUMPY_RADIX, 8>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_X_8); register_functor<NumPyShardingFunctor_Radix2D<1, Pow<NUMPY_RADIX, 1>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_Y_1); register_functor<NumPyShardingFunctor_Radix2D<1, Pow<NUMPY_RADIX, 2>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_Y_2); register_functor<NumPyShardingFunctor_Radix2D<1, Pow<NUMPY_RADIX, 3>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_Y_3); register_functor<NumPyShardingFunctor_Radix2D<1, Pow<NUMPY_RADIX, 4>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_Y_4); register_functor<NumPyShardingFunctor_Radix2D<1, Pow<NUMPY_RADIX, 5>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_Y_5); register_functor<NumPyShardingFunctor_Radix2D<1, Pow<NUMPY_RADIX, 6>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_Y_6); register_functor<NumPyShardingFunctor_Radix2D<1, Pow<NUMPY_RADIX, 7>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_Y_7); register_functor<NumPyShardingFunctor_Radix2D<1, Pow<NUMPY_RADIX, 8>::result>>( runtime, offset, NUMPY_SHARD_RADIX_2D_Y_8); register_functor<NumPyShardingFunctor_Radix3D<0, Pow<NUMPY_RADIX, 1>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_X_1); register_functor<NumPyShardingFunctor_Radix3D<0, Pow<NUMPY_RADIX, 2>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_X_2); register_functor<NumPyShardingFunctor_Radix3D<0, Pow<NUMPY_RADIX, 3>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_X_3); register_functor<NumPyShardingFunctor_Radix3D<0, Pow<NUMPY_RADIX, 4>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_X_4); register_functor<NumPyShardingFunctor_Radix3D<0, Pow<NUMPY_RADIX, 5>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_X_5); register_functor<NumPyShardingFunctor_Radix3D<0, Pow<NUMPY_RADIX, 6>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_X_6); register_functor<NumPyShardingFunctor_Radix3D<0, Pow<NUMPY_RADIX, 7>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_X_7); register_functor<NumPyShardingFunctor_Radix3D<0, Pow<NUMPY_RADIX, 8>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_X_8); register_functor<NumPyShardingFunctor_Radix3D<1, Pow<NUMPY_RADIX, 1>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Y_1); register_functor<NumPyShardingFunctor_Radix3D<1, Pow<NUMPY_RADIX, 2>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Y_2); register_functor<NumPyShardingFunctor_Radix3D<1, Pow<NUMPY_RADIX, 3>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Y_3); register_functor<NumPyShardingFunctor_Radix3D<1, Pow<NUMPY_RADIX, 4>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Y_4); register_functor<NumPyShardingFunctor_Radix3D<1, Pow<NUMPY_RADIX, 5>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Y_5); register_functor<NumPyShardingFunctor_Radix3D<1, Pow<NUMPY_RADIX, 6>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Y_6); register_functor<NumPyShardingFunctor_Radix3D<1, Pow<NUMPY_RADIX, 7>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Y_7); register_functor<NumPyShardingFunctor_Radix3D<1, Pow<NUMPY_RADIX, 8>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Y_8); register_functor<NumPyShardingFunctor_Radix3D<2, Pow<NUMPY_RADIX, 1>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Z_1); register_functor<NumPyShardingFunctor_Radix3D<2, Pow<NUMPY_RADIX, 2>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Z_2); register_functor<NumPyShardingFunctor_Radix3D<2, Pow<NUMPY_RADIX, 3>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Z_3); register_functor<NumPyShardingFunctor_Radix3D<2, Pow<NUMPY_RADIX, 4>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Z_4); register_functor<NumPyShardingFunctor_Radix3D<2, Pow<NUMPY_RADIX, 5>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Z_5); register_functor<NumPyShardingFunctor_Radix3D<2, Pow<NUMPY_RADIX, 6>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Z_6); register_functor<NumPyShardingFunctor_Radix3D<2, Pow<NUMPY_RADIX, 7>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Z_7); register_functor<NumPyShardingFunctor_Radix3D<2, Pow<NUMPY_RADIX, 8>::result>>( runtime, offset, NUMPY_SHARD_RADIX_3D_Z_8); } } // namespace numpy } // namespace legate extern "C" { void legate_numpy_create_transform_sharding_functor( unsigned first, unsigned offset, unsigned M, unsigned N, const long* transform) { legate::numpy::NumPyShardingFunctor* functor = NULL; switch (M) { case 1: { functor = new legate::numpy::NumPyTransformShardingFunctor<1, legate::numpy::NumPyShardingFunctor_1D>( NUMPY_SHARD_TILE_1D, transform, N); break; } case 2: { functor = new legate::numpy::NumPyTransformShardingFunctor<2, legate::numpy::NumPyShardingFunctor_2D>( NUMPY_SHARD_TILE_2D, transform, N); break; } case 3: { functor = new legate::numpy::NumPyTransformShardingFunctor<3, legate::numpy::NumPyShardingFunctor_3D>( NUMPY_SHARD_TILE_3D, transform, N); break; } default: assert(false); // should never get here } Runtime* runtime = Runtime::get_runtime(); runtime->register_sharding_functor(first + offset, functor, true /*silence warnings*/); // Also record this as a sharding functor for the mappers legate::numpy::NumPyShardingFunctor::sharding_functors[offset] = functor; } }
41.715749
100
0.62388
[ "transform" ]
8227d58e6ab5947c5343acadbb5a16f2022ddca0
11,272
hh
C++
python/src/database.hh
bvmeggelen/routino
b6bcc47be6ba4a90353a5b140ca9996aaa17d2b8
[ "X11", "MIT" ]
1
2016-02-12T20:26:31.000Z
2016-02-12T20:26:31.000Z
python/src/database.hh
bvmeggelen/routino
b6bcc47be6ba4a90353a5b140ca9996aaa17d2b8
[ "X11", "MIT" ]
2
2019-01-16T10:00:19.000Z
2019-02-03T10:53:32.000Z
python/src/database.hh
bvmeggelen/routino
b6bcc47be6ba4a90353a5b140ca9996aaa17d2b8
[ "X11", "MIT" ]
null
null
null
/*************************************** Header file for interface between Routino database and Python. Part of the Routino routing software. ******************/ /****************** This file Copyright 2018 Andrew M. Bishop This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ***************************************/ #ifndef DATABASE_H #define DATABASE_H /*+ To stop multiple inclusions. +*/ #include <vector> extern "C" { #include "types.h" #include "routino.h" } /* Constants that are not automatically picked up from types.h */ const nodeflags_t Nodeflag_Super = NODE_SUPER; const nodeflags_t Nodeflag_U_Turn = NODE_UTURN; const nodeflags_t Nodeflag_Mini_Roundabout = NODE_MINIRNDBT; const nodeflags_t Nodeflag_Turn_Restrict = NODE_TURNRSTRCT; const nodeflags_t Nodeflag_Turn_Restrict2 = NODE_TURNRSTRCT2; const distance_t Segmentflag_Area = SEGMENT_AREA; const distance_t Segmentflag_Oneway_1to2 = ONEWAY_1TO2; const distance_t Segmentflag_Oneway_2to1 = ONEWAY_2TO1; const distance_t Segmentflag_Super = SEGMENT_SUPER; const distance_t Segmentflag_Normal = SEGMENT_NORMAL; /* Classes (much easier to use them than C for doing this with swig) */ class PythonDatabase; class PythonNode; class PythonSegment; class PythonWay; class PythonRelation; template <class T> class PythonDatabaseIter; template <class T> class PythonNodeIter; /* The database as seen by Python */ PythonDatabase *LoadDatabase(const char *dirname, const char *prefix); PythonDatabase *LoadDatabase(const char *dirname); class PythonDatabase { public: PythonDatabase(const char *_dirname,const char *_prefix, Routino_Database* database); /*+ A constructor +*/ ~PythonDatabase(); /*+ A destructor to unload the database. +*/ PythonNode *GetNode(index_t item); /*+ Get a single node from the database. +*/ PythonSegment *GetSegment(index_t item); /*+ Get a single segment from the database. +*/ PythonWay *GetWay(index_t item); /*+ Get a single way from the database. +*/ PythonRelation *GetRelation(index_t item); /*+ Get a single relation from the database. +*/ PythonDatabaseIter<PythonNode> *Nodes(); /*+ Create a node iterator to get all the nodes from the database. +*/ PythonDatabaseIter<PythonSegment> *Segments(); /*+ Create a segment iterator to get all the segments from the database. +*/ PythonDatabaseIter<PythonWay> *Ways(); /*+ Create a way iterator to get all the ways from the database. +*/ PythonDatabaseIter<PythonRelation> *Relations(); /*+ Create a relation iterator to get all the relations from the database. +*/ index_t nnodes; /*+ The number of nodes in the database. +*/ index_t nsegments; /*+ The number of segments in the database. +*/ index_t nways; /*+ The number of ways in the database. +*/ index_t nrelations; /*+ The number of relations in the database. +*/ char *__str__(); /*+ Convert the Python database to a string. +*/ friend class PythonNode; friend class PythonSegment; friend class PythonWay; friend class PythonRelation; private: char *dirname; /*+ A copy of the database directory name. +*/ char *prefix; /*+ A copy of the database prefix. +*/ Routino_Database *database; /*+ The database opened using the libroutino function. +*/ }; /* A node as seen by Python - copied from ../src/nodes.h and then modified */ class PythonNode { public: PythonNode(PythonDatabase* _pydatabase) { pydatabase = _pydatabase; } /*+ A constructor passed the database. +*/ index_t id; /*+ The index of this node. +*/ index_t firstsegment; /*+ The index of the first segment. +*/ PythonNodeIter<PythonSegment> *Segments(); double latitude; /*+ The node latitude in degrees. +*/ double longitude; /*+ The node longitude in degrees. +*/ transports_t allow; /*+ The types of transport that are allowed through the node. +*/ nodeflags_t flags; /*+ Flags containing extra information (e.g. super-node, turn restriction). +*/ char *__str__(); /*+ Convert the Python node to a string. +*/ private: friend class PythonNodeIter<PythonSegment>; PythonDatabase *pydatabase; /*+ A pointer to the database that this node came from. +*/ std::vector<index_t> segments; /*+ The list of segments for this node, only filled in after calling Segments(). +*/ PythonSegment *get_segment(index_t item); /*+ Get a single segment from the node. +*/ void fill_segments(); /*+ Fill in the list of segments. +*/ }; /* A segment as seen by Python - copied from ../src/segments.h and then modified */ class PythonSegment { public: PythonSegment(PythonDatabase* _pydatabase) { pydatabase = _pydatabase; } /*+ A constructor passed the database. +*/ index_t id; /*+ The index of this segment. +*/ index_t node1; /*+ The index of the starting node. +*/ index_t node2; /*+ The index of the finishing node. +*/ PythonNode *Node1() { return pydatabase->GetNode(node1); } PythonNode *Node2() { return pydatabase->GetNode(node2); } index_t next2; /*+ The index of the next segment sharing node2. +*/ index_t way; /*+ The index of the way associated with the segment. +*/ PythonWay *Way() { return pydatabase->GetWay(way); } double distance; /*+ The distance between the nodes. +*/ distance_t flags; /*+ The flags associated with the segment. +*/ char *__str__(); /*+ Convert the Python segment to a string. +*/ private: PythonDatabase *pydatabase; /*+ A pointer to the database that this segment came from. +*/ }; /* A way as seen by Python - copied from ../src/ways.h and then modified */ class PythonWay { public: PythonWay(PythonDatabase* _pydatabase) { pydatabase = _pydatabase; } /*+ A constructor passed the database. +*/ index_t id; /*+ The index of this way. +*/ char *name; /*+ The offset of the name of the way in the names array. +*/ transports_t allow; /*+ The type of traffic allowed on the way. +*/ highway_t type; /*+ The highway type of the way. +*/ properties_t props; /*+ The properties of the way. +*/ double speed; /*+ The defined maximum speed limit of the way. +*/ double weight; /*+ The defined maximum weight of traffic on the way. +*/ double height; /*+ The defined maximum height of traffic on the way. +*/ double width; /*+ The defined maximum width of traffic on the way. +*/ double length; /*+ The defined maximum length of traffic on the way. +*/ char *__str__(); /*+ Convert the Python way to a string. +*/ private: PythonDatabase *pydatabase; /*+ A pointer to the database that this segment came from. +*/ }; /* A relation as seen by Python - copied from ../src/relations.h and then modified */ class PythonRelation { public: PythonRelation(PythonDatabase* _pydatabase) { pydatabase = _pydatabase; } /*+ A constructor passed the database. +*/ index_t id; /*+ The index of this relation. +*/ index_t from_seg; /*+ The segment that the path comes from. +*/ index_t via_node; /*+ The node that the path goes via. +*/ index_t to_seg; /*+ The segment that the path goes to. +*/ PythonSegment *FromSegment() { return pydatabase->GetSegment(from_seg); } PythonNode *ViaNode() { return pydatabase->GetNode(via_node); } PythonSegment *ToSegment() { return pydatabase->GetSegment(to_seg); } index_t from_way; /*+ The way that the path comes from. +*/ index_t to_way; /*+ The way that the path goes to. +*/ PythonWay *FromWay() { return pydatabase->GetWay(from_way); } PythonWay *ToWay() { return pydatabase->GetWay(to_way); } index_t from_node; /*+ The node that the path comes from. +*/ index_t to_node; /*+ The node that the path goes to. +*/ PythonNode *FromNode() { return pydatabase->GetNode(from_node); } PythonNode *ToNode() { return pydatabase->GetNode(to_node); } transports_t except_transport; /*+ The types of transports that that this relation does not apply to. +*/ char *__str__(); /*+ Convert the Python relation to a string. +*/ private: PythonDatabase *pydatabase; /*+ A pointer to the database that this segment came from. +*/ }; /* A generic node/segment/way/relation iterator */ template <class T> class PythonDatabaseIter { public: PythonDatabaseIter(PythonDatabase* _pydatabase, index_t _number) { pydatabase = _pydatabase; number = _number; } /*+ A constructor passed the database. +*/ index_t __len__() { return number; } /*+ When used as a list return the length of it. +*/ T *__getitem__(index_t index); /*+ When used as a list get a particular item from it. +*/ PythonDatabaseIter *__iter__() { return this; } /*+ When used as an iterator return itself. +*/ T *__next__() { if( next < number ) return __getitem__(next++); else return NULL; } /*+ When used as an iterator return the next item. +*/ private: index_t next=0; /*+ The next node/segment/way/relation to be returned. +*/ index_t number; /*+ The number of nodes/segments/ways/relations in total. +*/ PythonDatabase *pydatabase; /*+ A pointer to the database that this node/segment/way/relation came from. +*/ }; /* A segment iterator for nodes */ template <class T> class PythonNodeIter { public: PythonNodeIter(PythonNode *_pynode, index_t _number) { pynode = _pynode; number = _number; } /*+ A constructor passed the node. +*/ index_t __len__() { return number; } /*+ When used as a list return the length of it. +*/ T *__getitem__(index_t index); /*+ When used as a list get a particular item from it. +*/ PythonNodeIter *__iter__() { return this; } /*+ When used as an iterator return itself. +*/ T *__next__() { if( next < number ) return __getitem__(next++); else return NULL; } /*+ When used as an iterator return the next item. +*/ private: index_t next=0; /*+ The next segment to be returned. +*/ index_t number; /*+ The number of segments in total. +*/ PythonNode *pynode; /*+ A pointer to the node that these segments come from. +*/ }; #endif /* DATABASE_H */
38.868966
156
0.652147
[ "vector" ]
8228a76b66f79dbd403667d5630d59d00128feff
4,080
cpp
C++
src/wallet/test/hdwallet_test_fixture.cpp
dmuralov/particl-core
ac4dc00b7cd6293329ff4bf3acaa65636238910a
[ "MIT" ]
null
null
null
src/wallet/test/hdwallet_test_fixture.cpp
dmuralov/particl-core
ac4dc00b7cd6293329ff4bf3acaa65636238910a
[ "MIT" ]
null
null
null
src/wallet/test/hdwallet_test_fixture.cpp
dmuralov/particl-core
ac4dc00b7cd6293329ff4bf3acaa65636238910a
[ "MIT" ]
null
null
null
// Copyright (c) 2017-2021 The Particl Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <wallet/test/hdwallet_test_fixture.h> #include <rpc/server.h> #include <wallet/db.h> #include <wallet/hdwallet.h> #include <wallet/rpcwallet.h> #include <wallet/coincontrol.h> #include <validation.h> #include <util/system.h> #include <blind.h> #include <miner.h> #include <pos/miner.h> #include <timedata.h> #include <boost/test/unit_test.hpp> HDWalletTestingSetup::HDWalletTestingSetup(const std::string &chainName): TestingSetup(chainName, { "-balancesindex" }, true /* fFalconMode */) { ECC_Start_Stealth(); ECC_Start_Blinding(); pwalletMain = std::make_shared<CHDWallet>(m_chain.get(), "", CreateMockWalletDatabase()); WalletContext& wallet_context = *m_wallet_client->context(); AddWallet(wallet_context, pwalletMain); pwalletMain->LoadWallet(); m_chain_notifications_handler = m_chain->handleNotifications({ pwalletMain.get(), [](CHDWallet*) {} }); m_wallet_client->registerRpcs(); } HDWalletTestingSetup::~HDWalletTestingSetup() { WalletContext& wallet_context = *m_wallet_client->context(); RemoveWallet(wallet_context, pwalletMain, std::nullopt); pwalletMain->Finalise(); pwalletMain.reset(); falcon::mapStakeSeen.clear(); falcon::listStakeSeen.clear(); ECC_Stop_Stealth(); ECC_Stop_Blinding(); } void StakeNBlocks(CHDWallet *pwallet, size_t nBlocks) { ChainstateManager *pchainman{nullptr}; if (pwallet->HaveChain()) { pchainman = pwallet->chain().getChainman(); } if (!pchainman) { LogPrintf("Error: Chainstate manager not found.\n"); return; } size_t nStaked = 0; size_t k, nTries = 10000; for (k = 0; k < nTries; ++k) { int nBestHeight = WITH_LOCK(cs_main, return pchainman->ActiveChain().Height()); int64_t nSearchTime = GetAdjustedTime() & ~Params().GetStakeTimestampMask(nBestHeight+1); if (nSearchTime <= pwallet->nLastCoinStakeSearchTime) { std::this_thread::sleep_for(std::chrono::milliseconds(250)); continue; } std::unique_ptr<CBlockTemplate> pblocktemplate = pwallet->CreateNewBlock(); BOOST_REQUIRE(pblocktemplate.get()); if (pwallet->SignBlock(pblocktemplate.get(), nBestHeight+1, nSearchTime)) { CBlock *pblock = &pblocktemplate->block; if (CheckStake(*pchainman, pblock)) { nStaked++; } } if (nStaked >= nBlocks) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(250)); } BOOST_REQUIRE(k < nTries); SyncWithValidationInterfaceQueue(); } uint256 AddTxn(CHDWallet *pwallet, CTxDestination &dest, OutputTypes input_type, OutputTypes output_type, CAmount amount, CAmount exploit_amount, std::string expect_error) { uint256 txid; BOOST_REQUIRE(IsValidDestination(dest)); { LOCK(pwallet->cs_wallet); std::string sError; std::vector<CTempRecipient> vecSend; vecSend.emplace_back(output_type, amount, dest); CTransactionRef tx_new; CWalletTx wtx(pwallet, tx_new); CTransactionRecord rtx; CAmount nFee; CCoinControl coinControl; coinControl.m_debug_exploit_anon = exploit_amount; int rv = input_type == OUTPUT_RINGCT ? pwallet->AddAnonInputs(wtx, rtx, vecSend, true, 3, 1, nFee, &coinControl, sError) : input_type == OUTPUT_CT ? pwallet->AddBlindedInputs(wtx, rtx, vecSend, true, nFee, &coinControl, sError) : pwallet->AddStandardInputs(wtx, rtx, vecSend, true, nFee, &coinControl, sError); BOOST_REQUIRE(rv == 0); rv = wtx.SubmitMemoryPoolAndRelay(sError, true); if (expect_error.empty()) { BOOST_REQUIRE(rv == 1); } else { BOOST_CHECK(sError == expect_error); BOOST_REQUIRE(rv == 0); } txid = wtx.GetHash(); } SyncWithValidationInterfaceQueue(); return txid; }
31.384615
171
0.675245
[ "vector" ]
822a22713be477c8cc43e57aa6f1c1a809677baf
1,047
cpp
C++
src/tests/test_sphere.cpp
masonium/twinkle
853ae84ebd1fd8dcd3dda47eb3fb1c2cf0b8f0c6
[ "MIT" ]
2
2016-09-20T06:01:03.000Z
2020-12-03T23:22:19.000Z
src/tests/test_sphere.cpp
masonium/twinkle
853ae84ebd1fd8dcd3dda47eb3fb1c2cf0b8f0c6
[ "MIT" ]
null
null
null
src/tests/test_sphere.cpp
masonium/twinkle
853ae84ebd1fd8dcd3dda47eb3fb1c2cf0b8f0c6
[ "MIT" ]
null
null
null
#include "tests/test_util.h" #include "geometry/sphere.h" #include "textures.h" #include "kdscene.h" namespace { class SingleSphereFixture { public: SingleSphereFixture() : sphere(make_shared<Sphere>(Vec3{0.0, 0.0, 0.0}, 1.0)), mat(make_shared<RoughColorMaterial>(0, spectrum{1.0})), shape(make_shared<Shape>(sphere.get(), mat.get())), ray{Vec3{5.0, 0.0, 0.0}, Vec3{-2.0, 0.0, 0.0}} { scene.add(shape.get()); scene.prepare(); } KDScene scene; shared_ptr<Sphere> sphere; shared_ptr<Material> mat; shared_ptr<Shape> shape; Ray ray; }; TEST_FIXTURE(SingleSphereFixture, scene_test) { auto isect = scene.intersect(ray); CHECK(isect.is()); } TEST_FIXTURE(SingleSphereFixture, sphere) { auto isect = scene.intersect(ray); CHECK(isect.is()); if (isect.is()) { CHECK_CLOSE(isect.get().t(), 2.0, EPS); CHECK_CLOSE(sphere->intersect(ray).get(), 2.0, EPS); } } }
22.276596
83
0.576886
[ "geometry", "shape" ]
822c1c43d57183f941046057ba2904412ffc4f4e
10,279
cpp
C++
Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerializationResult.cpp
CStudios15/o3de
9dc85000a3ec1a6c6633d718f5c455ab11a46818
[ "Apache-2.0", "MIT" ]
8
2021-08-31T02:14:19.000Z
2021-12-28T19:20:59.000Z
Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerializationResult.cpp
CStudios15/o3de
9dc85000a3ec1a6c6633d718f5c455ab11a46818
[ "Apache-2.0", "MIT" ]
8
2021-07-12T13:55:00.000Z
2021-10-04T14:53:21.000Z
Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerializationResult.cpp
CStudios15/o3de
9dc85000a3ec1a6c6633d718f5c455ab11a46818
[ "Apache-2.0", "MIT" ]
1
2021-09-16T05:06:18.000Z
2021-09-16T05:06:18.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 <AzCore/Serialization/Json/JsonSerializationResult.h> #include <AzCore/Serialization/Json/JsonSerialization.h> #include <AzCore/std/algorithm.h> namespace AZ { namespace JsonSerializationResult { namespace Internal { template<typename StringType> void AppendToString(AZ::JsonSerializationResult::ResultCode code, StringType& target, AZStd::string_view path) { if (code.GetTask() == static_cast<Tasks>(0)) { target.append("The result code wasn't initialized"); return; } target.append("The operation "); switch (code.GetProcessing()) { case Processing::Halted: target.append("has halted during "); break; case Processing::Altered: target.append("has taken an alternative approach for "); break; case Processing::PartialAlter: target.append("has taken a partially alternative approach for "); break; case Processing::Completed: target.append("has completed "); break; default: target.append("has unknown processing status for "); break; } switch (code.GetTask()) { case Tasks::RetrieveInfo: target.append("a retrieve info operation "); break; case Tasks::CreateDefault: target.append("a create default operation "); break; case Tasks::Convert: target.append("a convert operation "); break; case Tasks::ReadField: target.append("a read field operation "); break; case Tasks::WriteValue: target.append("a write value operation "); break; case Tasks::Merge: target.append("a merge operation "); break; case Tasks::CreatePatch: target.append("a create patch operation "); break; case Tasks::Import: target.append("an import operation"); break; default: target.append("an unknown operation "); break; } if (!path.empty()) { target.append("for '"); target.append(path.begin(), path.end()); target.append("' "); } switch (code.GetOutcome()) { case Outcomes::Success: target.append("which resulted in success"); break; case Outcomes::DefaultsUsed: target.append("by using only default values"); break; case Outcomes::PartialDefaults: target.append("by using one or more default values"); break; case Outcomes::Skipped: target.append("because a field or value was skipped"); break; case Outcomes::PartialSkip: target.append("because one or more fields or values were skipped"); break; case Outcomes::Unavailable: target.append("because the target was unavailable"); break; case Outcomes::Unsupported: target.append("because the action was unsupported"); break; case Outcomes::TypeMismatch: target.append("because the source and target are unrelated types"); break; case Outcomes::TestFailed: target.append("because a test against a value failed"); break; case Outcomes::Missing: target.append("because a required field or value was missing"); break; case Outcomes::Invalid: target.append("because a field or element has an invalid value"); break; case Outcomes::Unknown: target.append("because information was missing"); break; case Outcomes::Catastrophic: target.append("because a catastrophic issue was encountered"); break; default: break; } } } // namespace JsonSerializationResultInternal ResultCode::ResultCode(Tasks task) : m_code(0) { m_options.m_task = task; } ResultCode::ResultCode(uint32_t code) : m_code(code) {} ResultCode::ResultCode(Tasks task, Outcomes outcome) { m_options.m_task = task; switch (outcome) { case Outcomes::Success: // fall through case Outcomes::Skipped: // fall through case Outcomes::PartialSkip: // fall through case Outcomes::DefaultsUsed: // fall through case Outcomes::PartialDefaults: m_options.m_processing = Processing::Completed; break; case Outcomes::Unavailable: // fall through case Outcomes::Unsupported: m_options.m_processing = Processing::Altered; break; case Outcomes::TypeMismatch: // fall through case Outcomes::TestFailed: // fall through case Outcomes::Missing: // fall through case Outcomes::Invalid: // fall through case Outcomes::Unknown: // fall through case Outcomes::Catastrophic: // fall through default: m_options.m_processing = Processing::Halted; break; } m_options.m_outcome = outcome; } bool ResultCode::HasDoneWork() const { return m_options.m_outcome != static_cast<Outcomes>(0); } ResultCode& ResultCode::Combine(ResultCode other) { *this = Combine(*this, other); return *this; } ResultCode& ResultCode::Combine(const Result& other) { *this = Combine(*this, other.GetResultCode()); return *this; } ResultCode ResultCode::Combine(ResultCode lhs, ResultCode rhs) { ResultCode result = ResultCode(AZStd::max(lhs.m_code, rhs.m_code)); if ((lhs.m_options.m_outcome == Outcomes::Success && rhs.m_options.m_outcome == Outcomes::DefaultsUsed) || (lhs.m_options.m_outcome == Outcomes::DefaultsUsed && rhs.m_options.m_outcome == Outcomes::Success)) { result.m_options.m_outcome = Outcomes::PartialDefaults; } else if ((lhs.m_options.m_outcome == Outcomes::Success && rhs.m_options.m_outcome == Outcomes::Skipped) || (lhs.m_options.m_outcome == Outcomes::Skipped && rhs.m_options.m_outcome == Outcomes::Success)) { result.m_options.m_outcome = Outcomes::PartialSkip; } if ((lhs.m_options.m_processing == Processing::Completed && rhs.m_options.m_processing == Processing::Altered) || (lhs.m_options.m_processing == Processing::Altered && rhs.m_options.m_processing == Processing::Completed)) { result.m_options.m_processing = Processing::PartialAlter; } return result; } Tasks ResultCode::GetTask() const { return m_options.m_task; } Processing ResultCode::GetProcessing() const { return m_options.m_processing == static_cast<Processing>(0) ? Processing::Completed : m_options.m_processing; } Outcomes ResultCode::GetOutcome() const { return m_options.m_outcome == static_cast<Outcomes>(0) ? Outcomes::DefaultsUsed : m_options.m_outcome; } void ResultCode::AppendToString(AZ::OSString& target, AZStd::string_view path) const { Internal::AppendToString(*this, target, path); } void ResultCode::AppendToString(AZStd::string& target, AZStd::string_view path) const { Internal::AppendToString(*this, target, path); } AZStd::string ResultCode::ToString(AZStd::string_view path) const { AZStd::string result; AppendToString(result, path); return result; } AZ::OSString ResultCode::ToOSString(AZStd::string_view path) const { AZ::OSString result; AppendToString(result, path); return result; } Result::Result(const JsonIssueCallback& callback, AZStd::string_view message, ResultCode result, AZStd::string_view path) : m_result(callback(message, result, path)) {} Result::Result(const JsonIssueCallback& callback, AZStd::string_view message, Tasks task, Outcomes outcome, AZStd::string_view path) : m_result(callback(message, ResultCode(task, outcome), path)) {} Result::operator ResultCode() const { return m_result; } ResultCode Result::GetResultCode() const { return m_result; } } // namespace JsonSerializationResult } // namespace AZ
37.378182
140
0.516393
[ "3d" ]
436295c47143643ae4e2102faff6c5d77efc8239
2,551
cpp
C++
aws-cpp-sdk-route53/source/model/ListTrafficPolicyVersionsResult.cpp
ambasta/aws-sdk-cpp
c81192e00b572b76d175d84dff77185bd17ae1ac
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-route53/source/model/ListTrafficPolicyVersionsResult.cpp
ambasta/aws-sdk-cpp
c81192e00b572b76d175d84dff77185bd17ae1ac
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-route53/source/model/ListTrafficPolicyVersionsResult.cpp
ambasta/aws-sdk-cpp
c81192e00b572b76d175d84dff77185bd17ae1ac
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/route53/model/ListTrafficPolicyVersionsResult.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <utility> using namespace Aws::Route53::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils; using namespace Aws; ListTrafficPolicyVersionsResult::ListTrafficPolicyVersionsResult() : m_isTruncated(false) { } ListTrafficPolicyVersionsResult::ListTrafficPolicyVersionsResult(const AmazonWebServiceResult<XmlDocument>& result) : m_isTruncated(false) { *this = result; } ListTrafficPolicyVersionsResult& ListTrafficPolicyVersionsResult::operator =(const AmazonWebServiceResult<XmlDocument>& result) { const XmlDocument& xmlDocument = result.GetPayload(); XmlNode resultNode = xmlDocument.GetRootElement(); if(!resultNode.IsNull()) { XmlNode trafficPoliciesNode = resultNode.FirstChild("TrafficPolicies"); if(!trafficPoliciesNode.IsNull()) { XmlNode trafficPoliciesMember = trafficPoliciesNode.FirstChild("TrafficPolicy"); while(!trafficPoliciesMember.IsNull()) { m_trafficPolicies.push_back(trafficPoliciesMember); trafficPoliciesMember = trafficPoliciesMember.NextNode("TrafficPolicy"); } } XmlNode isTruncatedNode = resultNode.FirstChild("IsTruncated"); if(!isTruncatedNode.IsNull()) { m_isTruncated = StringUtils::ConvertToBool(StringUtils::Trim(isTruncatedNode.GetText().c_str()).c_str()); } XmlNode trafficPolicyVersionMarkerNode = resultNode.FirstChild("TrafficPolicyVersionMarker"); if(!trafficPolicyVersionMarkerNode.IsNull()) { m_trafficPolicyVersionMarker = StringUtils::Trim(trafficPolicyVersionMarkerNode.GetText().c_str()); } XmlNode maxItemsNode = resultNode.FirstChild("MaxItems"); if(!maxItemsNode.IsNull()) { m_maxItems = StringUtils::Trim(maxItemsNode.GetText().c_str()); } } return *this; }
34.013333
127
0.75147
[ "model" ]
436366786e4a71d60d5a1109e595b5faf107b498
9,823
cpp
C++
tests/src/test_TensorRestriction.cpp
kmorel/MGARD
a7c44d57fda76a5c3e6fa38702ca8c8c12150b83
[ "Apache-2.0" ]
19
2019-03-08T15:21:36.000Z
2022-02-11T04:02:50.000Z
tests/src/test_TensorRestriction.cpp
kmorel/MGARD
a7c44d57fda76a5c3e6fa38702ca8c8c12150b83
[ "Apache-2.0" ]
100
2019-01-14T15:34:09.000Z
2022-03-29T13:39:30.000Z
tests/src/test_TensorRestriction.cpp
kmorel/MGARD
a7c44d57fda76a5c3e6fa38702ca8c8c12150b83
[ "Apache-2.0" ]
22
2018-11-16T01:13:57.000Z
2022-03-14T23:53:28.000Z
#include "catch2/catch_approx.hpp" #include "catch2/catch_test_macros.hpp" #include <array> #include <numeric> #include "testing_random.hpp" #include "testing_utilities.hpp" #include "TensorMassMatrix.hpp" #include "TensorMeshHierarchy.hpp" #include "TensorMeshHierarchyIteration.hpp" #include "TensorProlongation.hpp" #include "TensorRestriction.hpp" #include "shuffle.hpp" #include "utilities.hpp" TEST_CASE("constituent restrictions", "[TensorRestriction]") { SECTION("1D and default spacing") { const mgard::TensorMeshHierarchy<1, float> hierarchy({9}); const std::size_t ndof = 9; const std::array<float, ndof> u_ = {9, 2, 4, -4, 7, 5, -2, 5, 6}; std::array<float, ndof> v_; std::array<float, ndof> buffer_; float const *const u = u_.data(); float *const v = v_.data(); float *const buffer = buffer_.data(); const std::size_t dimension = 0; const std::array<std::array<float, ndof>, 3> expecteds = { {{10, 2, 3, -4, 7.5, 5, 3, 5, 8.5}, {11, 2, 4, -4, 8, 5, -2, 5, 5}, {12.5, 2, 4, -4, 7, 5, -2, 5, 9.5}}}; for (std::size_t l = 3; l > 0; --l) { const std::size_t i = 3 - l; const std::array<float, ndof> &expected = expecteds.at(i); const mgard::ConstituentRestriction<1, float> R(hierarchy, l, dimension); mgard::shuffle(hierarchy, u, v); R({0}, v); mgard::unshuffle(hierarchy, v, buffer); TrialTracker tracker; for (std::size_t i = 0; i < ndof; ++i) { tracker += buffer_.at(i) == expected.at(i); } REQUIRE(tracker); } } SECTION("1D and custom spacing and nondyadic") { const std::vector<double> xs = {0.0, 0.1, 0.9, 1.0}; const mgard::TensorMeshHierarchy<1, double> hierarchy({4}, {xs}); const std::size_t ndof = 4; const std::array<double, ndof> u_ = {5, 2, 2, 4}; std::array<double, ndof> v_; std::array<double, ndof> buffer_; double const *const u = u_.data(); double *const v = v_.data(); double *const buffer = buffer_.data(); const std::size_t dimension = 0; const std::array<std::array<double, ndof>, 2> expecteds = { {{5, 20. / 9, 2, 52. / 9}, {6.8, 2, 2, 4.2}}}; for (std::size_t l = 2; l > 0; --l) { const mgard::ConstituentRestriction<1, double> R(hierarchy, l, dimension); mgard::shuffle(hierarchy, u, v); R({0}, v); mgard::unshuffle(hierarchy, v, buffer); TrialTracker tracker; const std::array<double, ndof> &expected = expecteds.at(2 - l); for (std::size_t i = 0; i < ndof; ++i) { tracker += buffer_.at(i) == Catch::Approx(expected.at(i)); } REQUIRE(tracker); } } SECTION("2D and custom spacing") { const mgard::TensorMeshHierarchy<2, double> hierarchy( {3, 3}, {{{0, 0.75, 1}, {0, 0.25, 1}}}); const std::size_t ndof = 3 * 3; const std::array<double, ndof> u_ = {-9, -5, 1, 9, 3, 2, 9, 5, 6}; std::array<double, ndof> v_; std::array<double, ndof> buffer_; double const *const u = u_.data(); double *const v = v_.data(); double *const buffer = buffer_.data(); { const std::size_t l = 1; const std::size_t dimension = 0; const mgard::ConstituentRestriction<2, double> R(hierarchy, l, dimension); const std::array<std::array<std::size_t, 2>, 3> multiindices = { {{0, 0}, {0, 1}}}; const std::array<std::array<double, ndof>, 2> expecteds = {{ {-6.75, -5, 1, 9, 3, 2, 15.75, 5, 6}, {-9, -4.25, 1, 9, 3, 2, 9, 7.25, 6}, }}; for (std::size_t i = 0; i < 2; ++i) { const std::array<std::size_t, 2> &multiindex = multiindices.at(i); const std::array<double, ndof> &expected = expecteds.at(i); mgard::shuffle(hierarchy, u, v); R(multiindex, v); mgard::unshuffle(hierarchy, v, buffer); TrialTracker tracker; for (std::size_t j = 0; j < ndof; ++j) { tracker += buffer_.at(j) == Catch::Approx(expected.at(j)); } REQUIRE(tracker); } } { const std::size_t l = 1; const std::size_t dimension = 1; const mgard::ConstituentRestriction<2, double> R(hierarchy, l, dimension); const std::array<std::array<std::size_t, 2>, 3> multiindices = { {{1, 0}, {2, 0}}}; const std::array<std::array<double, ndof>, 2> expecteds = {{ {-9, -5, 1, 11.25, 3, 2.75, 9, 5, 6}, {-9, -5, 1, 9, 3, 2, 12.75, 5, 7.25}, }}; for (std::size_t i = 0; i < 2; ++i) { const std::array<std::size_t, 2> &multiindex = multiindices.at(i); const std::array<double, ndof> &expected = expecteds.at(i); mgard::shuffle(hierarchy, u, v); R(multiindex, v); mgard::unshuffle(hierarchy, v, buffer); TrialTracker tracker; for (std::size_t j = 0; j < ndof; ++j) { tracker += buffer_.at(j) == Catch::Approx(expected.at(j)); } REQUIRE(tracker); } } { bool thrown = false; try { const mgard::ConstituentRestriction<2, double> R(hierarchy, 0, 0); } catch (...) { // The constructor will throw a `std::invalid_argument` exception, but // (as of this writing) the attempt to initialize `coarse_indices` // throws first. thrown = true; } REQUIRE(thrown); } } } namespace { // Prolongate a function on the coarse mesh to the fine mesh, project back down // to the coarse mesh, and compare. template <std::size_t N, typename Real> void test_tensor_projection_identity(std::default_random_engine &generator, const std::array<std::size_t, N> shape) { std::uniform_real_distribution<Real> node_spacing_distribution(1, 1.5); std::uniform_real_distribution<Real> polynomial_coefficient_distribution( -0.5, 1.25); const mgard::TensorMeshHierarchy<N, Real> hierarchy = hierarchy_with_random_spacing(generator, node_spacing_distribution, shape); const std::size_t ndof = hierarchy.ndof(); std::vector<Real> u_(ndof); Real *const u = u_.data(); for (std::size_t l = hierarchy.L; l > 0; --l) { const MultilinearPolynomial<Real, N> p(generator, polynomial_coefficient_distribution); for (const mgard::TensorNode<N> node : mgard::ShuffledTensorNodeRange(hierarchy, l)) { hierarchy.at(u, node.multiindex) = hierarchy.date_of_birth(node.multiindex) == l ? 0 : p(coordinates(hierarchy, node)); } const mgard::TensorProlongationAddition<N, Real> PA(hierarchy, l); const mgard::TensorRestriction<N, Real> R(hierarchy, l); const mgard::TensorMassMatrixInverse<N, Real> m_inv(hierarchy, l - 1); const mgard::TensorMassMatrix<N, Real> M(hierarchy, l); PA(u); M(u); R(u); m_inv(u); TrialTracker tracker; for (const mgard::TensorNode<N> node : mgard::ShuffledTensorNodeRange(hierarchy, l - 1)) { // Encountered a handful of small errors. tracker += hierarchy.at(u, node.multiindex) == Catch::Approx(p(coordinates(hierarchy, node))).epsilon(0.001); } REQUIRE(tracker); } } } // namespace TEST_CASE("tensor product restrictions", "[TensorRestriction]") { { const mgard::TensorMeshHierarchy<2, double> hierarchy( {3, 3}, {{{0, 0.5, 1}, {-1, -0.5, 1}}}); const std::size_t ndof = 3 * 3; const std::array<double, ndof> u_ = {6, 0, 7, -6, -10, 8, -6, 3, 9}; std::array<double, ndof> v_; std::array<double, ndof> buffer_; double const *const u = u_.data(); double *const v = v_.data(); double *const buffer = buffer_.data(); const std::size_t l = 1; const mgard::TensorRestriction<2, double> R(hierarchy, l); const std::array<double, ndof> expected = {-0.75, -5, 9.75, -13.5, -10, 5.5, -10.5, -2, 12.5}; mgard::shuffle(hierarchy, u, v); R(v); mgard::unshuffle(hierarchy, v, buffer); REQUIRE(buffer_ == expected); } std::default_random_engine generator(445624); SECTION("dyadic") { test_tensor_projection_identity<1, float>(generator, {129}); test_tensor_projection_identity<2, double>(generator, {65, 65}); test_tensor_projection_identity<3, float>(generator, {33, 9, 33}); test_tensor_projection_identity<4, double>(generator, {9, 9, 17, 17}); } SECTION("nondyadic") { test_tensor_projection_identity<1, float>(generator, {105}); test_tensor_projection_identity<2, double>(generator, {45, 65}); test_tensor_projection_identity<3, float>(generator, {36, 10, 27}); test_tensor_projection_identity<4, double>(generator, {9, 19, 6, 8}); } } TEST_CASE("restrictions on 'flat' meshes", "[TensorRestriction]") { const std::size_t ndof = 90; const std::size_t l = 2; std::vector<float> u_(ndof); std::vector<float> expected_(ndof); std::vector<float> obtained_(ndof); float *const u = u_.data(); float *const expected = expected_.data(); float *const obtained = obtained_.data(); std::iota(u, u + ndof, 0); { const mgard::TensorMeshHierarchy<2, float> hierarchy({10, 9}); const mgard::TensorRestriction<2, float> R(hierarchy, l); std::copy(u, u + ndof, expected); R(expected); } { const mgard::TensorMeshHierarchy<4, float> hierarchy({10, 1, 1, 9}); const mgard::TensorRestriction<4, float> R(hierarchy, l); std::copy(u, u + ndof, obtained); R(obtained); REQUIRE(obtained_ == expected_); } { const mgard::TensorMeshHierarchy<5, float> hierarchy({1, 1, 1, 10, 9}); const mgard::TensorRestriction<5, float> R(hierarchy, l); std::copy(u, u + ndof, obtained); R(obtained); REQUIRE(obtained_ == expected_); } }
35.850365
80
0.595236
[ "mesh", "shape", "vector" ]
436434c79c610c55be1cef3728179647628d6ad5
18,027
cpp
C++
project/scratch.cpp
idungoofed/advanced_cv
5399ad7b1a0e20e8eb9eb6e7ae1e5502be2db9f3
[ "MIT" ]
null
null
null
project/scratch.cpp
idungoofed/advanced_cv
5399ad7b1a0e20e8eb9eb6e7ae1e5502be2db9f3
[ "MIT" ]
null
null
null
project/scratch.cpp
idungoofed/advanced_cv
5399ad7b1a0e20e8eb9eb6e7ae1e5502be2db9f3
[ "MIT" ]
null
null
null
// // Created by Ben Brown on 4/5/18. // /** * Ben Brown : beb5277 * Mark Philip : msp3430 * Advanced Computer Vision Project * Reads in a warped image with crosses and performs a Hough transform to locate * the corners of the image * * Ellipse detection: https://www.sciencedirect.com/science/article/pii/S0031320314001976 */ #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> //#include <opencv2/videoio/videoio.hpp> //#include <opencv2/video/video.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/features2d.hpp> //#include <map> #include <iostream> //#include <fstream> #include <opencv/cv.hpp> using namespace cv; using namespace std; struct LineStruct { Point2f startpt; Point2f endpt; }; //Mat firstFrame; //String window = "Image Display"; //int lineError = 5; int binarizeThreshold = 70; //int pointDistError = 3; const int minCircleArea = 10; //Returns corners in order: TL, TR, BR, BL vector<KeyPoint> getCornersV2(Mat image) { /* FLOW * init: four arrays: one for each corner * detect blobs * for each blob: * convert to hsv * if color is close to one of the presets: * if in the same quadrant: * append to correct array * find most extreme blob in each array -> corner_points */ Mat grayscaleMat; cvtColor(image, grayscaleMat,CV_BGR2GRAY); SimpleBlobDetector::Params params; params.filterByColor = false; params.filterByArea = true; params.minArea = minCircleArea; params.filterByCircularity = true; params.minCircularity = .8; params.filterByConvexity = true; params.minConvexity = .9; params.filterByInertia = true; params.minInertiaRatio = .5; Ptr<SimpleBlobDetector> detector = SimpleBlobDetector::create(params); std::vector<KeyPoint> keypoints; detector->detect(grayscaleMat, keypoints); for (const auto& item : keypoints) { cout << item.pt << ": " << item.size << endl; /* * convert to hsv * if color is close to one of the presets: * if in the same quadrant: * append to correct array */ } return keypoints; /* // Change thresholds params.minThreshold = 10; params.maxThreshold = 200; // Filter by Area. params.filterByArea = true; params.minArea = 1500; // Filter by Circularity params.filterByCircularity = true; params.minCircularity = 0.1; // Filter by Convexity params.filterByConvexity = true; params.minConvexity = 0.87; // Filter by Inertia params.filterByInertia = true; params.minInertiaRatio = 0.01; */ } //Returns corners in order: TL, TR, BR, BL vector<Point2f> getCorners(Mat image) { vector<Point2f> crossLocations; vector<LineStruct> horizLines; vector<LineStruct> vertLines; Mat grayscaleMat; cvtColor(image, grayscaleMat, COLOR_BGR2GRAY); /* // first find edges Mat cannyEdges; Canny(grayscaleMat, cannyEdges, 10, 50, 3); imshow("Canny Edges", cannyEdges); */ // binarize Mat binarizedImg; threshold(grayscaleMat, binarizedImg, binarizeThreshold, 255, CV_THRESH_BINARY); imshow("Binarized", binarizedImg); // now use edges to find lines vector<Vec4i> houghLines; HoughLinesP(binarizedImg, houghLines, 1, CV_PI/180, 30, 5, 2); cout << "Lines found: " << houghLines.size() << endl; // mat for displaying found lines Mat foundLines = Mat(image.rows, image.cols, CV_8UC3, Scalar(0, 0, 0)); // hashmap for keeping track of found points for (const auto& foundLine : houghLines) { Point pt1 = Point(foundLine[0], foundLine[1]); Point pt2 = Point(foundLine[2], foundLine[3]); line(foundLines, pt1, pt2, Scalar(0, 0, 255)); cout << "Pt1: " << pt1 << ", Pt2: " << pt2 << endl; } /* for (size_t idx = 0; idx < houghLines.size(); idx++) { Point pt1 = Point(houghLines[idx][0], houghLines[idx][1]); Point pt2 = Point(houghLines[idx][2], houghLines[idx][3]); line(foundLines, pt1, pt2, Scalar(0, 0, 255)); cout << "Pt1: " << pt1 << ", Pt2: " << pt2 << endl; } */ imshow("Found Lines", foundLines); // TODO: cluster points with a distance of < pointDistError away /* // original attempt with crosses vector<Vec2f> houghLines; HoughLines(cannyEdges, houghLines, 1, CV_PI/180, 30, 0, 0); cout << houghLines.size() << "\n"; for( size_t i = 0; i < houghLines.size(); i++ ) { float rho = houghLines[i][0], theta = houghLines[i][1]; cout << theta << endl; // find vertical lines if (0-lineError < int(theta)%180 < 0+lineError) {// || 85 < theta < 95) { cout << "found vert line" << endl; Point pt1, pt2; double a = cos(theta), b = sin(theta); double x0 = a*rho, y0 = b*rho; LineStruct ls; ls.startpt = Point( cvRound(x0 + 1000*(-b)), cvRound(y0 + 1000*(a)) ); ls.endpt = Point( cvRound(x0 - 1000*(-b)), cvRound(y0 - 1000*(a)) ); vertLines.push_back(ls); } //find horizontal lines else if (90-lineError < theta < 90+lineError) { cout << "found horiz line" << endl; Point pt1, pt2; double a = cos(theta), b = sin(theta); double x0 = a*rho, y0 = b*rho; LineStruct ls; ls.startpt = Point( cvRound(x0 + 1000*(-b)), cvRound(y0 + 1000*(a)) ); ls.endpt = Point( cvRound(x0 - 1000*(-b)), cvRound(y0 - 1000*(a)) ); cout << ls.startpt << endl; cout << ls.endpt << endl; horizLines.push_back(ls); } // ignore all other lines } // draw the found lines just for visualization for (size_t idx = 0; idx < vertLines.size(); idx++) { line(image, vertLines[idx].startpt, vertLines[idx].endpt, Scalar(0, 0, 255)); } for (size_t idx = 0; idx < horizLines.size(); idx++) { line(image, horizLines[idx].startpt, horizLines[idx].endpt, Scalar(0, 0, 255)); } imshow("Found Lines", image); // find intersections between lines //imshow("Found Corners", image); */ return crossLocations; } int main(int argc, char** argv) { Mat testImage(Size(400, 400), CV_8UC3); int edgeMargin = 25; int crossWidth = 20; int crossThickness = 2; Scalar crossColor = Scalar(0, 0, 255); //Create corners (centers of crosses) Point topLeft(edgeMargin, edgeMargin); Point topRight(testImage.rows - edgeMargin, edgeMargin); Point bottomRight(testImage.rows - edgeMargin, testImage.cols - edgeMargin); Point bottomLeft(edgeMargin, testImage.cols - edgeMargin); vector<Point2f> points; //Clockwise: TL, TR, BR, BL cout << "Points:" << endl; cout << "\tTL: " << topLeft << endl; cout << "\tTR: " << topRight << endl; cout << "\tBL: " << bottomLeft << endl; cout << "\tBR: " << bottomRight << endl; // draw colored circles on the points circle(testImage, topLeft, crossWidth, Scalar(0,0,255), -1); // hsv(0, 100, 100) circle(testImage, topRight, crossWidth, Scalar(0,255,127), -1); // hsv(90, 100, 100) circle(testImage, bottomLeft, crossWidth, Scalar(255,255,0), -1); // hsv(180, 100, 100) circle(testImage, bottomRight, crossWidth, Scalar(255,0,127), -1); // hsv(270, 100, 100) // display the original image imshow("Original Image", testImage); destroyAllWindows(); vector<KeyPoint> keypoints = getCornersV2(testImage); for (const auto& kp : keypoints) { circle(testImage, kp.pt, int(kp.size)/4, Scalar(255, 255, 255), -1); } imshow("Found Circles", testImage); waitKey(0); /* // draw borders line(testImage, topLeft, topRight, crossColor, crossThickness); line(testImage, topLeft, bottomLeft, crossColor, crossThickness); line(testImage, topRight, bottomRight, crossColor, crossThickness); line(testImage, bottomLeft, bottomRight, crossColor, crossThickness); */ /* points.push_back(topLeft); points.push_back(topRight); points.push_back(bottomRight); points.push_back(bottomLeft); for (int point=0; point<4; point++) { Point thePoint = points[point]; line(testImage, Point(thePoint.x - crossWidth, thePoint.y), Point(thePoint.x + crossWidth, thePoint.y), crossColor, crossThickness ); line(testImage, Point(thePoint.x, thePoint.y - crossWidth), Point(thePoint.x, thePoint.y + crossWidth), crossColor, crossThickness ); } */ /* // display the original image imshow("Original Image", testImage); waitKey(0); // find the (red) corners vector<Point2f> calculatedCorners = getCorners(testImage); // draw circles around the corners that were detected for (int point=0; point<calculatedCorners.size(); point++) { circle(testImage, calculatedCorners[point], 5, Scalar(0,255,0), -1); } imshow("Found Corners", testImage); */ /* waitKey(0); VideoCapture cap(0); if (!cap.isOpened()) { cout << "Error opening webcam" << endl; return EXIT_FAILURE; } Mat webcam; const char *webcam_window = "Webcam"; namedWindow(webcam_window, CV_WINDOW_NORMAL); setWindowProperty(webcam_window, CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN); for (;;) { Mat frame; cap >> frame; imshow(webcam_window, frame); if (waitKey(30) >= 0) { imwrite("./webcam_output.png", frame); break; } } */ return EXIT_SUCCESS; } //////////////////////////////////////////////////////////////////////////////////// // // Created by Ben Brown on 4/5/18. // /** * Ben Brown : beb5277 * Mark Philip : msp3430 * Advanced Computer Vision Project * Reads in a warped image with crosses and performs a Hough transform to locate * the corners of the image * * Ellipse detection: https://www.sciencedirect.com/science/article/pii/S0031320314001976 */ #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/features2d.hpp> #include <opencv/cv.hpp> #include <iostream> using namespace cv; using namespace std; // params for blob detection const bool filterByColor = false; const bool filterByArea = true; const float minCircleArea = 10; const bool filterByCircularity = true; const float minCircularity = 0.3; const bool filterByConvexity = true; const float minConvexity = .5; const bool filterByInertia = true; const float minInertiaRatio = .5; // edge circle colors const Scalar tl_color(0,0,255); // hsv(0, 255, 255) const Scalar tl_hsv(0,255,255); const Scalar tr_color(0,255,127); // hsv(45, 255, 255) const Scalar tr_hsv(45,255,255); const Scalar bl_color(255,255,0); // hsv(90, 255, 255) const Scalar bl_hsv(90,255,255); const Scalar br_color(255,0,127); // hsv(135, 255, 255) const Scalar br_hsv(135,255,255); // acceptable error const int hue_error = 15; const int saturation_error = 10; // constants for readability const int H_VAL = 0; const int S_VAL = 1; /* * Gets average rgb value of the given mat (extracted blob) and returns its hsv value */ Scalar bgrToHSV(Mat bgr) { //imshow("pt", bgr); //waitKey(0); //destroyWindow("pt"); Scalar avg = mean(bgr); Mat bgr_one(1,1, CV_8UC3, avg); cout << "AVG: " << avg << endl; cout << "BGR: " << bgr_one << endl; Mat hsv_one; cvtColor(bgr_one, hsv_one, CV_BGR2HSV); Scalar hsv = hsv_one.at<Vec3b>(Point(0, 0)); cout << "HSV: " << hsv << endl; return hsv; } int getQuadrant(Point pt, Size imgSize) { Point mdpt(imgSize.width/2, imgSize.height/2); bool pt_left = mdpt.x - pt.x > 0; bool pt_up = mdpt.y - pt.y > 0; return pt_left ? (pt_up ? 2 : 3) : (pt_up ? 1 : 4); } bool checkColor(Scalar candidate, Scalar original) { //return true; double upper_bound = original[H_VAL] + hue_error; double lower_bound = original[H_VAL] - hue_error; if (lower_bound < 0) { lower_bound+= 180; if (lower_bound < candidate[H_VAL] || candidate[H_VAL] < upper_bound) { return true; } else { return false; } } else { if (lower_bound < candidate[H_VAL] < upper_bound) { return true; } else { return false; } } } //Returns corners in order: TL, TR, BR, BL vector<KeyPoint> getCorners(Mat image) { /* FLOW * init: four arrays: one for each corner * detect blobs * for each blob: * convert to hsv * if color is close to one of the presets: * if in the same quadrant: * append to correct array * find most extreme blob in each array -> corner_points */ Mat grayscaleMat; cvtColor(image, grayscaleMat,CV_BGR2GRAY); SimpleBlobDetector::Params params; params.filterByColor = filterByColor; params.filterByArea = filterByArea; params.minArea = minCircleArea; params.filterByCircularity = filterByCircularity; params.minCircularity = minCircularity; params.filterByConvexity = filterByConvexity; params.minConvexity = minConvexity; params.filterByInertia = filterByInertia; params.minInertiaRatio = minInertiaRatio; vector<KeyPoint> keypoints, tl_list, tr_list, bl_list, br_list; Ptr<SimpleBlobDetector> detector = SimpleBlobDetector::create(params); detector->detect(grayscaleMat, keypoints); for (const auto& item : keypoints) { cout << item.pt << ": " << item.size << endl; Rect extractedBlob((int)round(item.pt.x - item.size/4), (int)round(item.pt.y - item.size/4), (int)round(item.size/2), (int)round(item.size/2)); Mat forConversion = Mat(image, extractedBlob); Scalar hsv = bgrToHSV(forConversion); int quadrant = getQuadrant(item.pt, image.size()); cout << "Quadrant: " << quadrant << endl; switch (quadrant) { case 1: if (checkColor(hsv, tr_hsv)) { cout << "Added " << item.pt << " to TR" << endl; tr_list.push_back(item); } break; case 2: if (checkColor(hsv, tl_hsv)) { cout << "Added " << item.pt << " to TL" << endl; tl_list.push_back(item); } break; case 3: if (checkColor(hsv, bl_hsv)) { cout << "Added " << item.pt << " to BL" << endl; bl_list.push_back(item); } break; case 4: if (checkColor(hsv, br_hsv)) { cout << "Added " << item.pt << " to BR" << endl; br_list.push_back(item); } break; default: cout << "Error: Quadrant error" << endl; break; } cout << endl; } // ToDo: find corner-est of each list, remove all others if (not (tl_list.empty() || tr_list.empty() || br_list.empty() || bl_list.empty()) ) { return vector<KeyPoint>{tl_list[0], tr_list[0], br_list[0], bl_list[0]}; } else { return vector<KeyPoint>{}; } } int main(int argc, char** argv) { /* Mat testImage(Size(400, 400), CV_8UC3, Scalar(255, 255, 255)); int edgeMargin = 25; int radius = 20; Scalar crossColor = Scalar(0, 0, 255); //Create corners (centers of circles) Point topLeft(edgeMargin, edgeMargin); Point topRight(testImage.rows - edgeMargin, edgeMargin); Point bottomRight(testImage.rows - edgeMargin, testImage.cols - edgeMargin); Point bottomLeft(edgeMargin, testImage.cols - edgeMargin); vector<Point2f> points; //Clockwise: TL, TR, BR, BL cout << "Points:" << endl; cout << "\tTL: " << topLeft << ", " << tl_color << endl; cout << "\tTR: " << topRight << ", " << tr_color << endl; cout << "\tBL: " << bottomLeft << ", " << bl_color << endl; cout << "\tBR: " << bottomRight << ", " << br_color << endl << endl; // draw colored circles on the points circle(testImage, topLeft, radius, tl_color, -1); circle(testImage, topRight, radius, tr_color, -1); circle(testImage, bottomLeft, radius, bl_color, -1); circle(testImage, bottomRight, radius, br_color, -1); */ Mat testImage = imread("./test_pics/webcam_output.png"); // display the original image imshow("Original Image", testImage); // find the blobs vector<KeyPoint> keypoints = getCorners(testImage); cout << "Found " << keypoints.size() << " keypoints" << endl; for (const auto& kp : keypoints) { circle(testImage, kp.pt, int(kp.size)/4, Scalar(255, 255, 255), -1); } // display imshow("Found Circles", testImage); waitKey(0); // code for capturing a pic /* destroyAllWindows(); namedWindow("x", CV_WINDOW_NORMAL); imshow("x", testImage); VideoCapture cap(0); if (!cap.isOpened()) { cout << "Error opening webcam" << endl; return EXIT_FAILURE; } Mat webcam; const char *webcam_window = "Webcam"; namedWindow(webcam_window, CV_WINDOW_NORMAL); setWindowProperty(webcam_window, CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN); for (;;) { Mat frame; cap >> frame; imshow(webcam_window, frame); if ((char)waitKey(30) == 'q') { imwrite("./webcam_output.png", frame); break; } } */ return EXIT_SUCCESS; }
29.40783
92
0.595163
[ "vector", "transform" ]
4366c03a4d63e0c3b1a9718ef1c6c97e31f09529
13,041
cpp
C++
vdf/WebUI.cpp
vineyard2020/vine_talk
f2e8b29e46618e64e11139f7701a8297d433c651
[ "Apache-2.0" ]
1
2021-04-06T13:45:52.000Z
2021-04-06T13:45:52.000Z
vdf/WebUI.cpp
vineyard2020/vine_talk
f2e8b29e46618e64e11139f7701a8297d433c651
[ "Apache-2.0" ]
null
null
null
vdf/WebUI.cpp
vineyard2020/vine_talk
f2e8b29e46618e64e11139f7701a8297d433c651
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018 Foundation for Research and Technology - Hellas * * 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 [1] [1] * * 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. * * Links: * ------ * [1] http://www.apache.org/licenses/LICENSE-2.0 [1] */ #include "WebUI.h" #include "Misc.h" #include <vine_pipe.h> #include <conf.h> #include <Poco/URI.h> #include <iostream> #include <fstream> #include <random> #include "Pallete.h" using namespace Poco; using namespace Poco::Net; #define ID_OUT {for(int cnt = 0 ; cnt < id_lvl ; cnt++)out << '\t';}out extern vine_pipe_s *vpipe; const char * normalize(const char * label,size_t size) { static char buff[1024]; snprintf(buff,sizeof(buff),"<tr><th>%s</th><td>%s</td></tr>\n",label,autoRange(size,bytes_to_orders,1024).c_str()); return buff; } int bar_count = 0; char hostname[1024]; #ifdef BREAKS_ENABLE void addBarSlice(std::ostream & os,int bar_count,int id,unsigned long long value,std::string title) { os << "<div id='slice"<<bar_count<< "_" << id <<"' title='" << title << "' class=slice1 style = 'flex-grow:" << value << ";background-color:#" << Pallete::get(id,15) << ";'></div>\n"; } std::string generateBreakBar(std::ostream & out,utils_breakdown_stats_s * breakdown) { int samples = breakdown->samples; std::ostringstream bar; std::ostringstream heads; std::ostringstream percs; std::ostringstream raw_vals; std::ostringstream total_bar; std::ostringstream head_str; std::vector<std::string> head_vec; bar << "<div class=bar>\n"; total_bar << "<div class=tot_bar>\n"; heads << "<tr><th style='border: none;'></th><th class='btn1' onClick=\"toggleSlice(this,'slice" <<bar_count<< "_" << 0 << "')\" style='background-color:#" << Pallete::get(0,15) << "'>"; char * s = breakdown->heads; int parts = 0; while(*s) { if(*s == ',') { heads << "</th><th class='btn1' onClick=\"toggleSlice(this,'slice" <<bar_count<< "_" << parts+1 << "')\" style='background-color:#" << Pallete::get(parts+1,15) << "'>"; parts++; head_vec.push_back(head_str.str()); head_str.str(""); head_str.clear(); } else { if(*s == '_') { heads << ' '; head_str << ' '; } else { heads << *s; head_str << *s; } } s++; } addBarSlice(total_bar,bar_count,parts,breakdown->part[BREAKDOWN_PARTS],"Total"); total_bar << "</div>\n"; if(breakdown->part[BREAKDOWN_PARTS]) { heads << "Total</th><th class=invisible></th><th onClick=\"toggleSlice(this,'slice" <<bar_count<< "_" << parts+1 << "')\" style='background-color:#" << Pallete::get(parts+1,15) << "'> Interarival</th></tr>\n"; heads << "<tr><th>Time</th>"; percs << "<tr><th>Percent</th>"; raw_vals << "<tr><th>Time(ns)</th>"; for(int part = 0 ; part < parts ; part++) { float perc = (100.0*breakdown->part[part])/breakdown->part[BREAKDOWN_PARTS]; heads << "<td>" << autoRange(breakdown->part[part]/(float)samples,ns_to_secs,1000) << "</td>"; percs << "<td>" << ((int)(1000*perc))/1000.0 << " <div class=u>%</div></td>"; addBarSlice(bar,bar_count,part,breakdown->part[part],head_vec[part]); raw_vals << "<td>" << breakdown->part[part] << "<div class=u>ns</div></td>"; } addBarSlice(bar,bar_count,parts+1,breakdown->part[BREAKDOWN_PARTS+1],"Interarival"); percs << "<td>" << 100 << "%</td><td class=invisible></td>"; raw_vals << "<td>" << breakdown->part[BREAKDOWN_PARTS] << "<div class=u>ns</div></td><td class=invisible></td>"; heads << "<td>" << autoRange(breakdown->part[BREAKDOWN_PARTS]/(float)samples,ns_to_secs,1000) << "</td><td class=invisible></td>"; percs << "<td>" << (100.0*breakdown->part[BREAKDOWN_PARTS+1])/breakdown->part[BREAKDOWN_PARTS] << "%</td></tr>\n"; raw_vals << "<td>" << breakdown->part[BREAKDOWN_PARTS+1] << "<div class=u>ns</div></td></tr>\n"; heads << "<td>" << autoRange(breakdown->part[BREAKDOWN_PARTS+1]/(float)samples,ns_to_secs,1000) << "</td></tr>\n"; } bar << "</div>\n"; bar_count++; return bar.str()+total_bar.str()+"<table style='align-self: center;'>\n"+heads.str()+percs.str()+raw_vals.str()+"</table>\n"; } #endif struct allocation { void * name; size_t start; size_t end; size_t size; int partition; }; std::ostream & operator<<(std::ostream & os, const struct allocation & alloc) { } void inspector(void * start, void * end, size_t size, void* arg) { std::vector<allocation> * alloc_vec = (std::vector<allocation> *)arg; allocation alloc = {start,(size_t)start,(size_t)end,size}; alloc_vec->push_back(alloc); } void WebUI :: handleRequest(HTTPServerRequest & request,HTTPServerResponse & response) { int id_lvl = 0; int type; utils_list_s *list; utils_list_node_s *itr; vine_object_s *obj; response.setStatus(HTTPResponse::HTTP_OK); response.setContentType("text/html"); URI uri(request.getURI()); std::ostream& out = response.send(); if(!args["embed"]) { ID_OUT << "<!DOCTYPE html>\n"; ID_OUT << "<html>\n"; id_lvl++; ID_OUT << "<head>\n"; id_lvl++; ID_OUT << "<title>VineWatch</title>\n"; if(uri.getPath() == "/reset") { void * temp; std::istringstream iss(uri.getQuery()); iss >> std::hex >> temp; if(temp) utils_breakdown_init_stats((utils_breakdown_stats_s*)temp); ID_OUT << "<meta http-equiv=\"refresh\" content=\"0; url=/\" />"; } ID_OUT << "<link href=\"https://fonts.googleapis.com/css?family=Roboto\" rel=\"stylesheet\">\n"; id_lvl--; ID_OUT << "</head>\n"; ID_OUT << "<body>\n"; id_lvl++; } std::string src_path = __FILE__; src_path.resize(src_path.size()-9); ID_OUT << "<style>"; ID_OUT << "\n" << std::ifstream(src_path+"style.css").rdbuf(); ID_OUT << "</style>\n"; ID_OUT << "<script>"; ID_OUT << "\n" << std::ifstream(src_path+"script.js").rdbuf(); ID_OUT << "</script>\n"; ID_OUT << "<div class=version>" << VINE_TALK_GIT_REV << "</div>\n"; ID_OUT << std::ifstream(src_path+"logo.svg").rdbuf(); if(!args["noalloc"]) { arch_alloc_stats_s stats = arch_alloc_stats(&(vpipe->allocator)); ID_OUT << "<h2 onClick=blockTogle('alloc_block')>Allocations</h2>\n"; ID_OUT << "<div class=block name=alloc_block>\n"; id_lvl++; ID_OUT << "<div class=hgroup>\n"; id_lvl++; ID_OUT << "<div class=hgroup>\n"; id_lvl++; ID_OUT << "<table>\n"; id_lvl++; ID_OUT << _TR(_TH("All Partitions","colspan=2")) << std::endl; ID_OUT << "<tr><th>Base</th><td>" << vpipe << "</td></tr>\n"; ID_OUT <<_TR(_TH("Partitions")+_TD(_S(stats.mspaces))); ID_OUT << normalize("Space",stats.total_bytes); ID_OUT << normalize("Used",stats.used_bytes); ID_OUT << normalize("Free",stats.total_bytes-stats.used_bytes); #ifdef ALLOC_STATS ID_OUT <<_TR(_TH("Failed allocations")+_TD(_S(stats.allocs[0]))); ID_OUT <<_TR(_TH("Good allocations")+_TD(_S(stats.allocs[1]))); ID_OUT <<_TR(_TH("Total Alloc")+_TD(_S(stats.allocs[0]+stats.allocs[1]))); ID_OUT <<_TR(_TH("Total Free")+_TD(_S(stats.frees))); #endif id_lvl--; ID_OUT << "</table>\n"; id_lvl--; ID_OUT << "</div>\n"; stats.mspaces = 0; std::vector<allocation> allocs; std::map<int,std::vector<allocation>> alloc_map; arch_alloc_inspect(&(vpipe->allocator),inspector,&allocs); size_t base = (size_t)((&(vpipe->allocator))+1); for(auto alloc : allocs) { alloc.start -= base; alloc.end -= base; alloc.partition = alloc.start/(512*1024*1024); alloc_map[alloc.partition].push_back(alloc); } allocs.clear(); ID_OUT << "<div class='hgroup greedy'>\n"; id_lvl++; int part = 0; do { stats = arch_alloc_mspace_stats(&(vpipe->allocator),stats.mspaces); if(stats.mspaces) { ID_OUT << "<div class='vgroup bg" << part%2 << "'>\n"; id_lvl++; ID_OUT << "<table>\n"; id_lvl++; //ID_OUT << "<tr><th colspan=2>Partition:" << stats.mspaces << "</th></tr>\n"; ID_OUT << _TR(_TH("Partition:"+_S(stats.mspaces),"colspan=2")) << std::endl; ID_OUT <<normalize("Space",stats.total_bytes); ID_OUT <<normalize("Used",stats.used_bytes); ID_OUT <<normalize("Free",stats.total_bytes-stats.used_bytes); ID_OUT << "</table>\n"; id_lvl--; ID_OUT << "<table>\n"; id_lvl++; ID_OUT << _TR(_TH("Allocations ["+_S(alloc_map[part].size())+"]","colspan=3")) << std::endl; ID_OUT << _TR(_TH("Start")+_TH("End")+_TH("Used")) << std::endl; for(allocation itr : alloc_map[part]) { ID_OUT << "<tr onmouseover=\"highlight_same(this)\" name=\"alloc" << itr.name << "\">"; ID_OUT << _TD(_S(itr.start)) + _TD(_S(itr.end)) + _TD(_S(itr.size)); ID_OUT << "</tr>" << std::endl; } id_lvl--; ID_OUT << "</table>\n"; id_lvl--; ID_OUT << "</div>\n"; } part++; } while(stats.mspaces); id_lvl--; ID_OUT << "</div>\n"; id_lvl--; ID_OUT << "</div>\n"; id_lvl--; ID_OUT << "</div>\n"; } if(!args["noobj"]) { ID_OUT << "<h2 onClick=blockTogle('obj_block')>Objects</h2>\n"; ID_OUT << "<div class=block name=obj_block>\n"; id_lvl++; const char * typestr[VINE_TYPE_COUNT] = { "Phys Accel", "Virt Accel", "Vine Procs", "Vine Datas", "Vine Tasks" }; ID_OUT << "<div class=hgroup>\n"; id_lvl++; for(type = 0 ; type < VINE_TYPE_COUNT ; type++) { list = vine_object_list_lock(&(vpipe->objs),(vine_object_type_e)type); ID_OUT << "<div class='bg" << type%2 << "'>\n"; id_lvl++; ID_OUT << "<table>\n"; id_lvl++; ID_OUT << _TR(_TH(std::string(typestr[type])+"["+_S(list->length)+"]","colspan=5")) << std::endl; ID_OUT << _TR(_TH("Address")+_TH("Name")+_TH("Refs")+_TH("Type")+_TH("Extra")) << std::endl; if(list->length) { utils_list_for_each(*list,itr) { obj = (vine_object_s*)itr->owner; ID_OUT << "<tr onmouseover=\"highlight_same(this)\" name=\"alloc"<< obj << "\"><td>" << obj << "</td>"<< _TD(obj->name) << _TD(_S(vine_object_refs(obj))); switch(type) { case VINE_TYPE_PHYS_ACCEL: ID_OUT << _TD(vine_accel_type_to_str(((vine_accel_s*)obj)->type)) << _TD("Rev:"+_S(vine_accel_get_revision(((vine_accel_s*)obj)))); break; case VINE_TYPE_VIRT_ACCEL: ID_OUT << _TD(vine_accel_type_to_str(((vine_vaccel_s*)obj)->type)) << _TD("Queue:"+_S(utils_queue_used_slots(vine_vaccel_queue((vine_vaccel_s*)obj)))); break; case VINE_TYPE_PROC: ID_OUT << _TD(vine_accel_type_to_str(((vine_proc_s*)obj)->type)) << _TD(""); break; case VINE_TYPE_DATA: ID_OUT << _TD(_S(((vine_data_s*)obj)->size)) << _TD(""); break; case VINE_TYPE_TASK: { vine_task_msg_s * task = (vine_task_msg_s*)obj; ID_OUT << _TD(vine_accel_type_to_str(((vine_proc_s*)((task)->proc))->type)) << _TD(((vine_object_s*)((task)->proc))->name); } break; default: ID_OUT << _TD("Unknown") << _TD(""); break; } ID_OUT << "<tr>\n"; } } else { ID_OUT << _TR(_TD(std::string("No ")+typestr[type],"colspan=5")) << std::endl; } id_lvl--; ID_OUT << "</table>\n"; vine_object_list_unlock(&(vpipe->objs),(vine_object_type_e)type); id_lvl++; ID_OUT << "</div>\n"; } id_lvl--; ID_OUT << "</div>\n"; id_lvl--; ID_OUT << "</div>\n"; } #ifdef BREAKS_ENABLE if(!args["nobreak"]) { bool had_breaks = false; ID_OUT << "<h2 onClick=blockTogle('brk_block')>Breakdowns</h2>\n"; ID_OUT << "<div class=block name=brk_block>\n"; id_lvl++; vine_proc_s* proc; list = vine_object_list_lock(&(vpipe->objs),VINE_TYPE_PROC); utils_list_for_each(*list,itr) { obj = (vine_object_s*)itr->owner; proc = (vine_proc_s*)obj; int samples = proc->breakdown.samples; if(samples) { ID_OUT << "<h2>" << vine_accel_type_to_str(proc->type) << "::" << obj->name << "(" << samples << " samples,task average)@" << hostname << ":</h2>\n"; ID_OUT << "<a href='reset?" << (void*)&(proc->breakdown) << "'>Reset breakdown</a>\n"; out << generateBreakBar(out,&(proc->breakdown)); had_breaks = true; } } vine_object_list_unlock(&(vpipe->objs),VINE_TYPE_PROC); if(!had_breaks) { ID_OUT << "No breakdowns collected, run something first!\n"; } id_lvl--; ID_OUT << "</div>\n"; } if(!args["notelemetry"]) { ID_OUT << "<h2 onClick=blockTogle('tlm_block')>Telemetry</h2>\n"; ID_OUT << "<div class=block name=tlm_block>\n"; id_lvl++; collector->rawDump(out); id_lvl--; ID_OUT << "</div>\n"; } #endif if(!args["embed"]) { id_lvl--; ID_OUT << "</body>\n"; id_lvl--; ID_OUT << "</html>\n"; } out.flush(); } WebUI :: WebUI(std::map<std::string,bool> & args,Collector * collector) : collector(collector), args(args) { gethostname(hostname,1024); }
29.571429
211
0.614523
[ "vector" ]
43679af25d8358b38a857abef7cd4b7736db1656
2,752
cc
C++
src/logger.cc
archilleu/base
f56aafcbb75ae65ff6c485142ad29e029ba910c6
[ "Unlicense" ]
null
null
null
src/logger.cc
archilleu/base
f56aafcbb75ae65ff6c485142ad29e029ba910c6
[ "Unlicense" ]
null
null
null
src/logger.cc
archilleu/base
f56aafcbb75ae65ff6c485142ad29e029ba910c6
[ "Unlicense" ]
null
null
null
//--------------------------------------------------------------------------- #include <cstdarg> #include "logger.h" #include "logger_sink.h" //--------------------------------------------------------------------------- namespace base { //--------------------------------------------------------------------------- std::shared_ptr<Logger> Logger::stdout_logger_mt() { SinkPtr ptr = std::make_shared<ConsoleSinkMT>(); return std::make_shared<Logger>(ptr); } //--------------------------------------------------------------------------- std::shared_ptr<Logger> Logger::stdout_logger_st() { SinkPtr ptr = std::make_shared<ConsoleSinkST>(); return std::make_shared<Logger>(ptr); } //--------------------------------------------------------------------------- std::shared_ptr<Logger> Logger::file_logger_mt(const std::string& path, bool daily) { SinkPtr ptr = std::make_shared<FileSinkMT>(path, daily); return std::make_shared<Logger>(ptr); } //--------------------------------------------------------------------------- std::shared_ptr<Logger> Logger::file_logger_st(const std::string& path, bool daily) { SinkPtr ptr = std::make_shared<FileSinkST>(path, daily); return std::make_shared<Logger>(ptr); } //--------------------------------------------------------------------------- std::shared_ptr<Logger> Logger::file_stdout_logger_mt(const std::string& path, bool daily) { std::vector<SinkPtr> vec_ptr; vec_ptr.push_back(std::make_shared<ConsoleSinkMT>()); vec_ptr.push_back(std::make_shared<FileSinkMT>(path, daily)); return std::make_shared<Logger>(vec_ptr); } //--------------------------------------------------------------------------- std::shared_ptr<Logger> Logger::file_stdout_logger_st(const std::string& path, bool daily) { std::vector<SinkPtr> vec_ptr; vec_ptr.push_back(std::make_shared<ConsoleSinkST>()); vec_ptr.push_back(std::make_shared<FileSinkST>(path, daily)); return std::make_shared<Logger>(vec_ptr); } //--------------------------------------------------------------------------- void Logger::Flush() { for(const auto& v: slots_) v->flush(); return; } //--------------------------------------------------------------------------- void Logger::WriteToSinks(const char* msg, Level lv) { for(const auto& v : slots_) { try { v->log(lv, msg); } catch(const std::fstream::failure& e) { free(const_cast<char*>(msg)); throw e; } } if(ShouldFlush(lv)) Flush(); return; } //--------------------------------------------------------------------------- }//namespace base //---------------------------------------------------------------------------
33.560976
90
0.4375
[ "vector" ]
4367c7b499ad970c9f27d847714c87baf03b9da2
1,412
cpp
C++
2/AC/ejercicio2-9.cpp
xKuZz/trabajosugr
5dd0cf416ccf5dfe5961713a85581d95cd14aa74
[ "MIT" ]
3
2019-10-23T06:06:43.000Z
2021-05-23T17:20:25.000Z
2/AC/ejercicio2-9.cpp
xKuZz/trabajosugr
5dd0cf416ccf5dfe5961713a85581d95cd14aa74
[ "MIT" ]
null
null
null
2/AC/ejercicio2-9.cpp
xKuZz/trabajosugr
5dd0cf416ccf5dfe5961713a85581d95cd14aa74
[ "MIT" ]
1
2017-12-18T22:16:47.000Z
2017-12-18T22:16:47.000Z
#include <iostream> using namespace std; //#define PRINT_MATRIX int main(int argc, char** argv) { if (argc != 2) { cerr << "ERROR: Incluir N como unico argumento."; return -1; } int N = atoi(argv[1]); // Reserva de memoria dinámica double** M1 = new double*[N]; double** M2 = new double*[N]; double* v = new double [N]; for (int i = 0; i < N; ++i) { M1[i] = new double[N]; M2[i] = new double[N]; } double t_antes, t_despues; #pragma omp parallel { // Inicialización de variables #pragma omp for for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) { M1[i][j] = (N + i) * 0.1 + (N-j) * 0.1; M2[i][j] = 0; } #pragma omp for for (int i = 0; i < N; ++i) v[i] = i+1; #pragma omp single t_antes = omp_get_wtime(); // Multiplicación de matriz por vector #pragma omp for for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) { for (int k = 0; k < N; ++k) #pragma omp single t_despues = omp_get_wtime(); } #ifdef PRINT_MATRIX for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) cout << M2[i][j] << '\t'; cout << endl; } #endif // Liberación de memoria dinámica for (int i = 0; i < N; ++i) { delete[] M1[i]; delete[] M2[i]; } delete[] M1; }
21.723077
54
0.469547
[ "vector" ]
436879a61f402ea9aab8afa35ebfe6ff2e24a55c
4,404
cpp
C++
src/backend/graph_compiler/core/src/compiler/ir/easy_build.cpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
src/backend/graph_compiler/core/src/compiler/ir/easy_build.cpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
src/backend/graph_compiler/core/src/compiler/ir/easy_build.cpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2020-2022 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "easy_build.hpp" #include <utility> #include <compiler/config/context.hpp> namespace sc { namespace builder { for_range_simulator_t range(const std::string &name, for_loop &out, expr min, expr extent, expr step, for_type type) { return for_range_simulator_t(builder::get_current_builder(), &out, name, std::move(min), std::move(extent), std::move(step), type); } for_range_simulator_t range_nobind(const std::string &name, expr min, expr extent, expr step, for_type type) { return for_range_simulator_t(builder::get_current_builder(), nullptr, name, std::move(min), std::move(extent), std::move(step), type); } for_range_simulator_t range( for_loop &out, expr min, expr extent, expr step, for_type type) { return for_range_simulator_t(builder::get_current_builder(), &out, "!!!unamed", std::move(min), std::move(extent), std::move(step), type); } for_range_simulator_t range(expr min, expr extent, expr step, for_type type) { return for_range_simulator_t(builder::get_current_builder(), nullptr, "!!!unamed", std::move(min), std::move(extent), std::move(step), type); } func_simulator_t _make_func_simulator(const std::string &name, func_t *outfunc, sc_data_type_t dtype, std::vector<std::vector<expr>> &&args) { std::vector<expr> flattened; for (auto &a : args) { for (auto &arg : a) { flattened.emplace_back(std::move(arg)); } } return func_simulator_t(name, outfunc, dtype, std::move(flattened)); } std::vector<expr> _make_arg( const char *name, sc_data_type_t dtype, const std::vector<int> &args) { expr ret; if (args.empty()) { ret = builder::make_var(dtype, name); } else { std::vector<expr> dims; dims.reserve(args.size()); for (auto i : args) { dims.emplace_back(i); } ret = builder::make_tensor(name, dims, dtype); } return std::vector<expr> {ret}; } std::vector<expr> _make_arg(const char *name, sc_data_type_t dtype, std::initializer_list<unsigned long> args) { // NOLINT, // We must use unsigned long here to let g++ and MSVC to correctly let UL // number literals find correct overload version of function. expr ret; if (args.size() == 0) { ret = builder::make_var(dtype, name); } else { std::vector<expr> dims; dims.reserve(args.size()); for (auto i : args) { dims.emplace_back(i); } ret = builder::make_tensor(name, dims, dtype); } return std::vector<expr> {ret}; } std::vector<expr> _make_arg( const char *name, sc_data_type_t dtype, const std::vector<expr> &args) { expr ret; if (args.empty()) { ret = builder::make_var(dtype, name); } else { ret = builder::make_tensor(name, args, dtype); } return std::vector<expr> {ret}; } std::vector<expr> _make_arg(const char *name, sc_data_type_t dtype, std::initializer_list<int> args) { return _make_arg(name, dtype, std::vector<int>(args)); } std::vector<expr> _make_arg(const char *name, sc_data_type_t dtype) { return std::vector<expr> {builder::make_var(dtype, name)}; } func_t _decl_func(const std::string &name, sc_data_type_t dtype, std::vector<std::vector<expr>> &&args) { std::vector<expr> flattened; for (auto &a : args) { for (auto &arg : a) { flattened.emplace_back(std::move(arg)); } } return builder::make_func(name, flattened, stmt(), dtype); } } // namespace builder } // namespace sc
34.952381
81
0.622616
[ "vector" ]
436a35dc172e9044c3b7fce4b40fa6e018576d0d
18,000
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/SystemConfig.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/SystemConfig.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/SystemConfig.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos 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. //========================================================================= #include "elastos/droid/server/SystemConfig.h" #include <elastos/droid/os/Process.h> #include <elastos/droid/utility/Xml.h> #include <elastos/droid/internal/utility/XmlUtils.h> #include <elastos/droid/internal/utility/ArrayUtils.h> #include <elastos/utility/logging/Logger.h> #include <elastos/utility/logging/Slogger.h> #include <elastos/core/AutoLock.h> #include <elastos/core/AutoLock.h> using Elastos::Core::AutoLock; using Elastos::Droid::Content::Pm::CFeatureInfo; using Elastos::Droid::Content::Pm::CSignature; using Elastos::Droid::Os::Process; using Elastos::Droid::Os::IEnvironment; using Elastos::Droid::Os::CEnvironment; using Elastos::Droid::Os::ISystemProperties; using Elastos::Droid::Os::CSystemProperties; using Elastos::Droid::Utility::Xml; using Elastos::Droid::Internal::Utility::XmlUtils; using Elastos::Droid::Internal::Utility::ArrayUtils; using Elastos::IO::CFile; using Elastos::IO::ICloseable; using Elastos::IO::IReader; using Elastos::IO::IFileReader; using Elastos::IO::CFileReader; using Elastos::Utility::CHashMap; using Elastos::Utility::Logging::Logger; using Elastos::Utility::Logging::Slogger; namespace Elastos { namespace Droid { namespace Server { const String SystemConfig::TAG("SystemConfig"); Object SystemConfig::sLock; AutoPtr<SystemConfig> SystemConfig::sInstance; AutoPtr<SystemConfig> SystemConfig::GetInstance() { AutoLock syncLock(sLock); if (sInstance == NULL) { sInstance = new SystemConfig(); } return sInstance; } AutoPtr<ArrayOf<Int32> > SystemConfig::GetGlobalGids() { return mGlobalGids; } AutoPtr< HashMap<Int32, AutoPtr<HashSet<String> > > > SystemConfig::GetSystemPermissions() { return mSystemPermissions; } AutoPtr<HashMap<String, String> > SystemConfig::GetSharedLibraries() { return mSharedLibraries; } AutoPtr<HashMap<String, AutoPtr<IFeatureInfo> > > SystemConfig::GetAvailableFeatures() { return mAvailableFeatures; } AutoPtr<HashMap<String, AutoPtr<SystemConfig::PermissionEntry> > > SystemConfig::GetPermissions() { return mPermissions; } AutoPtr<HashSet<String> > SystemConfig::GetAllowInPowerSave() { return mAllowInPowerSave; } AutoPtr<HashSet<String> > SystemConfig::GetFixedImeApps() { return mFixedImeApps; } AutoPtr<HashMap<AutoPtr<ISignature>, AutoPtr<HashSet<String> > > > SystemConfig::GetSignatureAllowances() { return mSignatureAllowances; } SystemConfig::SystemConfig() { mSystemPermissions = new HashMap<Int32, AutoPtr<HashSet<String> > >(); mSharedLibraries = new HashMap<String, String>(); mAvailableFeatures = new HashMap<String, AutoPtr<IFeatureInfo> >(); mPermissions = new HashMap<String, AutoPtr<PermissionEntry> >(); mAllowInPowerSave = new HashSet<String>(); mFixedImeApps = new HashSet<String>(); mSignatureAllowances = new HashMap<AutoPtr<ISignature>, AutoPtr<HashSet<String> > >(); AutoPtr<IEnvironment> environment; CEnvironment::AcquireSingleton((IEnvironment**)&environment); AutoPtr<IFile> rootDir, oemDir; environment->GetRootDirectory((IFile**)&rootDir); environment->GetOemDirectory((IFile**)&oemDir); // Read configuration from system AutoPtr< ArrayOf<String> > segments = ArrayOf<String>::Alloc(2); segments->Set(0, String("etc")); segments->Set(1, String("sysconfig")); AutoPtr<IFile> path; environment->BuildPath(rootDir, segments, (IFile**)&path); ReadPermissions(path, FALSE); // Read configuration from the old permissions dir path = NULL; segments->Set(1, String("permissions")); environment->BuildPath(rootDir, segments, (IFile**)&path); ReadPermissions(path, FALSE); // Only read features from OEM config path = NULL; segments->Set(1, String("sysconfig")); environment->BuildPath(oemDir, segments, (IFile**)&path); ReadPermissions(path, TRUE); path = NULL; segments->Set(1, String("permissions")); environment->BuildPath(oemDir, segments, (IFile**)&path); ReadPermissions(path, TRUE); } ECode SystemConfig::ReadPermissions( /* [in] */ IFile* libraryDir, /* [in] */ Boolean onlyFeatures) { Boolean exists, isDir; libraryDir->Exists(&exists); libraryDir->IsDirectory(&isDir); // Read permissions from given directory. if (!exists || !isDir) { if (!onlyFeatures) { Logger::W(TAG, "No directory %s, skipping", TO_CSTR(libraryDir)); } return NOERROR; } Boolean canRead; libraryDir->CanRead(&canRead); if (!canRead) { Logger::W(TAG, "Directory %s cannot be read", TO_CSTR(libraryDir)); return NOERROR; } // Iterate over the files in the directory and scan .xml files AutoPtr<ArrayOf<IFile*> > files; libraryDir->ListFiles((ArrayOf<IFile*>**)&files); if (files != NULL) { IFile* f; String path; for (Int32 i = 0; i < files->GetLength(); ++i) { f = (*files)[i]; f->GetPath(&path); // We'll read platform.xml last if (path.EndWith("etc/permissions/platform.xml")) { continue; } if (!path.EndWith(".xml")) { Logger::I(TAG, "Non-xml file %s in %s directory, ignoring", TO_CSTR(f), TO_CSTR(libraryDir)); continue; } f->CanRead(&canRead); if (!canRead) { Logger::W(TAG, "Permissions library file %s cannot be read", TO_CSTR(f)); continue; } ReadPermissionsFromXml(f, onlyFeatures); } } // Read permissions from .../etc/permissions/platform.xml last so it will take precedence AutoPtr<IEnvironment> environment; CEnvironment::AcquireSingleton((IEnvironment**)&environment); AutoPtr<IFile> rootDir; environment->GetRootDirectory((IFile**)&rootDir); AutoPtr<IFile> permFile; CFile::New(rootDir, String("etc/permissions/platform.xml"), (IFile**)&permFile); return ReadPermissionsFromXml(permFile, onlyFeatures); } ECode SystemConfig::ReadPermissionsFromXml( /* [in] */ IFile* permFile, /* [in] */ Boolean onlyFeatures) { AutoPtr<IFileReader> permReader; ECode ec = CFileReader::New(permFile, (IFileReader**)&permReader); if (ec == (ECode)E_FILE_NOT_FOUND_EXCEPTION){ Logger::W(TAG, "Couldn't find or open permissions file %s", TO_CSTR(permFile)); return NOERROR; } Int32 type, eventType; Int32 uid; String name, gidStr, perm, nullStr, uidStr, fname, pos, pkgname; HashMap<Int32, AutoPtr<HashSet<String> > >::Iterator it; HashMap<AutoPtr<ISignature>, AutoPtr<HashSet<String> > >::Iterator itSA; AutoPtr<HashSet<String> > perms; const String sname("name"); const String spackage("package"); AutoPtr<IXmlPullParser> parser; ec = Xml::NewPullParser((IXmlPullParser**)&parser); FAIL_GOTO(ec, _Exit_) ec = parser->SetInput(IReader::Probe(permReader)); FAIL_GOTO(ec, _Exit_) ec = parser->Next(&type); FAIL_GOTO(ec, _Exit_) while (type != IXmlPullParser::START_TAG && type != IXmlPullParser::END_DOCUMENT) { ec = parser->Next(&type); FAIL_GOTO(ec, _Exit_) } if (type != IXmlPullParser::START_TAG) { Logger::E(TAG, "No start tag found"); ec = E_XML_PULL_PARSER_EXCEPTION; FAIL_GOTO(ec, _Exit_) } parser->GetName(&name); if (!name.Equals("permissions") && !name.Equals("config")) { Logger::E(TAG, "Unexpected start tag: found %s, expected 'permissions' or 'config'", name.string()); ec = E_XML_PULL_PARSER_EXCEPTION; FAIL_GOTO(ec, _Exit_) } while (TRUE) { FAIL_GOTO(XmlUtils::NextElement(parser), _Exit_) FAIL_GOTO(parser->GetEventType(&eventType), _Exit_) if (eventType == IXmlPullParser::END_DOCUMENT) { break; } FAIL_GOTO(parser->GetName(&name), _Exit_) if (name.Equals("group") && !onlyFeatures) { FAIL_GOTO(parser->GetAttributeValue(nullStr, String("gid"), &gidStr), _Exit_) if (!gidStr.IsNull()) { Int32 gid = Process::GetGidForName(gidStr); AutoPtr<ArrayOf<Int32> > ids = mGlobalGids; mGlobalGids = ArrayUtils::AppendInt32(ids, gid); } else { parser->GetPositionDescription(&pos); Logger::W(TAG, "<group> without gid at %s", pos.string()); } XmlUtils::SkipCurrentTag(parser); continue; } else if (name.Equals("permission") && !onlyFeatures) { FAIL_GOTO(parser->GetAttributeValue(nullStr, sname, &perm), _Exit_) if (perm.IsNull()) { parser->GetPositionDescription(&pos); Logger::W(TAG, "<permission> without name at %s", pos.string()); XmlUtils::SkipCurrentTag(parser); continue; } ReadPermission(parser, perm); } else if (name.Equals("assign-permission") && !onlyFeatures) { FAIL_GOTO(parser->GetAttributeValue(nullStr, sname, &perm), _Exit_) if (perm == NULL) { parser->GetPositionDescription(&pos); Logger::W(TAG, "<assign-permission> without name at %s", pos.string()); XmlUtils::SkipCurrentTag(parser); continue; } FAIL_GOTO(parser->GetAttributeValue(nullStr, String("uid"), &uidStr), _Exit_) if (uidStr == NULL) { parser->GetPositionDescription(&pos); Logger::W(TAG, "<assign-permission> without uid at %s", pos.string()); XmlUtils::SkipCurrentTag(parser); continue; } uid = Process::GetUidForName(uidStr); if (uid < 0) { parser->GetPositionDescription(&pos); Logger::W(TAG, "<assign-permission> with unknown uid \"%s\" at ", uidStr.string(), pos.string()); XmlUtils::SkipCurrentTag(parser); continue; } perms = NULL; it = mSystemPermissions->Find(uid); if (it != mSystemPermissions->End()) { perms = it->mSecond; } if (perms == NULL) { perms = new HashSet<String>(); (*mSystemPermissions)[uid] = perms; } perms->Insert(perm); XmlUtils::SkipCurrentTag(parser); } else if (name.Equals("allow-permission")) { parser->GetAttributeValue(nullStr, String("name"), &perm); if (perm.IsNull()) { parser->GetPositionDescription(&pos); Slogger::W(TAG, "<allow-permission> without name at %s", pos.string()); XmlUtils::SkipCurrentTag(parser); continue; } String signature; parser->GetAttributeValue(nullStr, String("signature"), &signature); if (signature.IsNull()) { parser->GetPositionDescription(&pos); Slogger::W(TAG, "<allow-permission> without signature at %s", pos.string()); XmlUtils::SkipCurrentTag(parser); continue; } AutoPtr<ISignature> sig; CSignature::New(signature, (ISignature**)&sig); if (sig != NULL) { perms = NULL; itSA = mSignatureAllowances->Find(sig); if (itSA != mSignatureAllowances->End()) { perms = itSA->mSecond; } if (perms == NULL) { perms = new HashSet<String>(); (*mSignatureAllowances)[sig] = perms; } perms->Insert(perm); } else { parser->GetPositionDescription(&pos); Slogger::W(TAG, "<allow-permission> with bad signature at %s", pos.string()); } XmlUtils::SkipCurrentTag(parser); } else if (name.Equals("library") && !onlyFeatures) { String lname, lfile; FAIL_GOTO(parser->GetAttributeValue(nullStr, sname, &lname), _Exit_) FAIL_GOTO(parser->GetAttributeValue(nullStr, String("file"), &lfile), _Exit_) if (lname == NULL) { parser->GetPositionDescription(&pos); Logger::W(TAG, "<library> without name at %s", pos.string()); } else if (lfile == NULL) { parser->GetPositionDescription(&pos); Logger::W(TAG, "<library> without file at %s", pos.string()); } else { //Log.i(TAG, "Got library " + lname + " in " + lfile); (*mSharedLibraries)[lname] = lfile; } XmlUtils::SkipCurrentTag(parser); continue; } else if (name.Equals("feature")) { FAIL_GOTO(parser->GetAttributeValue(nullStr, sname, &fname), _Exit_) if (fname.IsNull()) { parser->GetPositionDescription(&pos); Logger::W(TAG, "<feature> without name at %s", pos.string()); } else if (IsLowRamDevice() && fname.Equals("android.software.managed_users")) { Slogger::W(TAG, "Feature not supported on low memory device %s", fname.string()); } else { //Log.i(TAG, "Got feature " + fname); AutoPtr<IFeatureInfo> fi; CFeatureInfo::New((IFeatureInfo**)&fi); fi->SetName(fname); (*mAvailableFeatures)[fname] = fi; } XmlUtils::SkipCurrentTag(parser); continue; } else if (name.Equals("allow-in-power-save")) { FAIL_GOTO(parser->GetAttributeValue(nullStr, spackage, &pkgname), _Exit_) if (pkgname.IsNull()) { parser->GetPositionDescription(&pos); Logger::W(TAG, "<allow-in-power-save> without package at %s", pos.string()); } else { mAllowInPowerSave->Insert(pkgname); } XmlUtils::SkipCurrentTag(parser); continue; } else if (name.Equals("fixed-ime-app")) { FAIL_GOTO(parser->GetAttributeValue(nullStr, spackage, &pkgname), _Exit_) if (pkgname.IsNull()) { parser->GetPositionDescription(&pos); Logger::W(TAG, "<fixed-ime-app> without package at %s", pos.string()); } else { mFixedImeApps->Insert(pkgname); } XmlUtils::SkipCurrentTag(parser); continue; } else { XmlUtils::SkipCurrentTag(parser); continue; } } ICloseable::Probe(permReader)->Close(); _Exit_: if (ec == (ECode)E_XML_PULL_PARSER_EXCEPTION) { Logger::W(TAG, "Got execption parsing permissions. E_XML_PULL_PARSER_EXCEPTION"); } else if (ec == (ECode)E_IO_EXCEPTION) { Logger::W(TAG, "Got execption parsing permissions. E_IO_EXCEPTION"); } return ec; } ECode SystemConfig::ReadPermission( /* [in] */ IXmlPullParser* parser, /* [in] */ const String& name) { AutoPtr<PermissionEntry> perm; HashMap<String, AutoPtr<PermissionEntry> >::Iterator it = mPermissions->Find(name); if (it != mPermissions->End()) { perm = it->mSecond; } if (perm == NULL) { perm = new PermissionEntry(name); (*mPermissions)[name] = perm; } Int32 outerDepth, depth, type; String tagName, gidStr, nullStr; parser->GetDepth(&outerDepth); parser->Next(&type); while (type != IXmlPullParser::END_DOCUMENT && (type != IXmlPullParser::END_TAG || (parser->GetDepth(&depth), depth) > outerDepth)) { if (type == IXmlPullParser::END_TAG || type == IXmlPullParser::TEXT) { parser->Next(&type); continue; } parser->GetName(&tagName); if (tagName.Equals("group")) { parser->GetAttributeValue(nullStr, String("gid"), &gidStr); if (!gidStr.IsNull()) { Int32 gid = Process::GetGidForName(gidStr); AutoPtr<ArrayOf<Int32> > tmp = perm->mGids; perm->mGids = ArrayUtils::AppendInt32(tmp, gid); } else { String pos; parser->GetPositionDescription(&pos); Logger::W(TAG, "<group> without gid at %s", pos.string()); } } XmlUtils::SkipCurrentTag(parser); parser->Next(&type); } return NOERROR; } Boolean SystemConfig::IsLowRamDevice() { AutoPtr<ISystemProperties> sp; CSystemProperties::AcquireSingleton((ISystemProperties**)&sp); String str; sp->Get(String("ro.config.low_ram"), String("false"), &str); return str.Equals("true"); } } // namespace Server } // namepsace Droid } // namespace Elastos
34.351145
108
0.584111
[ "object" ]
436e3bed17a19d49a0f8c85d2eae5cd79d7fd9c8
1,822
cpp
C++
src/caffe/layers/cudnn_tanh_layer.cpp
Amanda-Barbara/nvcaffe
5155a708b235a818ce300aa3f9fc235ece9a35fb
[ "BSD-2-Clause" ]
758
2015-03-08T20:54:38.000Z
2022-01-11T03:14:51.000Z
src/caffe/layers/cudnn_tanh_layer.cpp
Matsuko9/caffe
17e347e42e664b87d80f63bfbbb89bec5e559242
[ "BSD-2-Clause" ]
493
2015-04-28T00:08:53.000Z
2021-08-04T07:26:54.000Z
src/caffe/layers/cudnn_tanh_layer.cpp
Matsuko9/caffe
17e347e42e664b87d80f63bfbbb89bec5e559242
[ "BSD-2-Clause" ]
389
2015-03-05T12:11:44.000Z
2022-03-13T21:49:42.000Z
#ifdef USE_CUDNN #include <vector> #include "caffe/layers/cudnn_tanh_layer.hpp" namespace caffe { template <typename Ftype, typename Btype> void CuDNNTanHLayer<Ftype, Btype>::LayerSetUp(const vector<Blob*>& bottom, const vector<Blob*>& top) { TanHLayer<Ftype, Btype>::LayerSetUp(bottom, top); // initialize cuDNN cudnn::createTensor4dDesc<Ftype>(&fwd_bottom_desc_); cudnn::createTensor4dDesc<Ftype>(&fwd_top_desc_); cudnn::createTensor4dDesc<Btype>(&bwd_bottom_desc_); cudnn::createTensor4dDesc<Btype>(&bwd_top_desc_); cudnnCreateActivationDescriptor(&activ_desc_); cudnnSetActivationDescriptor(activ_desc_, CUDNN_ACTIVATION_TANH, CUDNN_NOT_PROPAGATE_NAN, 0.0); handles_setup_ = true; } template <typename Ftype, typename Btype> void CuDNNTanHLayer<Ftype, Btype>::Reshape(const vector<Blob*>& bottom, const vector<Blob*>& top) { TanHLayer<Ftype, Btype>::Reshape(bottom, top); const int N = bottom[0]->num(); const int K = bottom[0]->channels(); const int H = bottom[0]->height(); const int W = bottom[0]->width(); cudnn::setTensor4dDesc<Ftype>(&fwd_bottom_desc_, N, K, H, W); cudnn::setTensor4dDesc<Ftype>(&fwd_top_desc_, N, K, H, W); cudnn::setTensor4dDesc<Btype>(&bwd_bottom_desc_, N, K, H, W); cudnn::setTensor4dDesc<Btype>(&bwd_top_desc_, N, K, H, W); } template <typename Ftype, typename Btype> CuDNNTanHLayer<Ftype, Btype>::~CuDNNTanHLayer() { // Check that handles have been setup before destroying. if (!handles_setup_) { return; } cudnnDestroyActivationDescriptor(this->activ_desc_); cudnnDestroyTensorDescriptor(fwd_bottom_desc_); cudnnDestroyTensorDescriptor(fwd_top_desc_); cudnnDestroyTensorDescriptor(bwd_bottom_desc_); cudnnDestroyTensorDescriptor(bwd_top_desc_); } INSTANTIATE_CLASS_FB(CuDNNTanHLayer); } // namespace caffe #endif
34.377358
74
0.751372
[ "vector" ]
437393f1ab72f29549181ae85de569d5e504bfbe
590
cpp
C++
CCC/wdawdawdaw.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
1
2017-10-01T00:51:39.000Z
2017-10-01T00:51:39.000Z
CCC/wdawdawdaw.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
null
null
null
CCC/wdawdawdaw.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> using namespace std; int N,P; vector<pair<int,int> > planets; int main() { cin >> N >> P; int fuel; for (int i=0;i<N;i++) { int val,cost; cin >> val >> cost; if (P-1==i) fuel = val; else if (val>=cost) planets.push_back(make_pair(cost,val)); } sort(planets.begin(),planets.end()); int cnt = 1; for (int i=0;i<planets.size();i++) { if (planets[i].first>fuel) break; else { cnt++; fuel += planets[i].second-planets[i].first; } } cout << fuel << endl << cnt << endl; }
18.4375
62
0.561017
[ "vector" ]
4374c487a3e3cd0a7e52a8bcff30a7931fae4621
1,292
hpp
C++
src/Camera.hpp
prise-3d/vpbrt
d0aca0fe6dc76f0079efcec049b0be04c9cd174b
[ "MIT" ]
6
2021-09-23T03:10:31.000Z
2021-12-16T11:35:44.000Z
src/Camera.hpp
prise-3d/vpbrt
d0aca0fe6dc76f0079efcec049b0be04c9cd174b
[ "MIT" ]
null
null
null
src/Camera.hpp
prise-3d/vpbrt
d0aca0fe6dc76f0079efcec049b0be04c9cd174b
[ "MIT" ]
2
2021-09-23T03:10:34.000Z
2021-12-01T22:34:51.000Z
#ifndef _CAMERA_HPP #define _CAMERA_HPP #include <iostream> using namespace std; #include "./Geometry/transform.h" class Camera { public: Transform mla; // matrice lookat de pbrt float o[4]; // position de la caméra float v[4]; // point visé par la caméra float up[4]; // vecteur up de la caméra float vdir[4]; // vecteur direction de visée float fov; // dimensions de l'image int xresolution; int yresolution; float ratio; // ratio de l'image = xresolution/yresolution // dimensions intiales de le fenêtre d'affichage int largeur, hauteur; // pas incrémentaux des déplacements float dtheta; float dtrans; Camera(); ~Camera(); void initialize(const Transform &m); void translate(const float *t); void rotateLeft(); void rotateRight(); void rotateUp(); void rotateDown(); void increaseFov(); void decreaseFov(); friend ostream& operator<<(ostream& out, const Camera& cam); static void crossProduct(float* n, float *v1, float *v2); private: void mulMatVec(float m[16], float v[4]); void rotate(float a, float b, float c, float ang, float v[4]); static const float DTHETA; static const float DTRANS; static const float DFOV; static const int DEFAULT_SCREEN_WIDTH; static const int DEFAULT_SCREEN_HEIGHT; }; #endif
22.666667
64
0.705108
[ "geometry", "transform" ]
437540990d9806c30b6c9298548065001877920e
2,416
cpp
C++
ycsb/wrappers/ycsbwrappers.cpp
shenweihai1/veribetrkv-linear
0e63dc1cc2a24f0ab460e8a905924560e5991644
[ "MIT" ]
null
null
null
ycsb/wrappers/ycsbwrappers.cpp
shenweihai1/veribetrkv-linear
0e63dc1cc2a24f0ab460e8a905924560e5991644
[ "MIT" ]
null
null
null
ycsb/wrappers/ycsbwrappers.cpp
shenweihai1/veribetrkv-linear
0e63dc1cc2a24f0ab460e8a905924560e5991644
[ "MIT" ]
null
null
null
#include "ycsbwrappers.h" #include <iostream> #include <string> #include "core_workload.h" #include "utils.h" utils::Properties ycsbcwrappers::props_from(std::string filename) { utils::Properties props; std::ifstream input(filename); props.Load(input); return props; } ycsbc::CoreWorkload* ycsbcwrappers::new_workload(utils::Properties& props) { ycsbc::CoreWorkload* wl = new ycsbc::CoreWorkload; wl->Init(props); return wl; } const ycsbcwrappers::TxRead ycsbcwrappers::TransactionRead(ycsbc::CoreWorkload&workload) { const std::string table = workload.NextTable(); const std::string key = workload.NextTransactionKey(); if (!workload.read_all_fields()) { std::vector<std::string>* fields = new std::vector<std::string>; fields->push_back("field" + workload.NextFieldName()); return TxRead(table, key, fields); } else { return TxRead(table, key, NULL); } } const ycsbcwrappers::TxInsert ycsbcwrappers::TransactionInsert(ycsbc::CoreWorkload&workload, bool load) { const std::string &table = workload.NextTable(); const std::string &key = load ? workload.NextSequenceKey() : workload.NextTransactionKey(); std::vector<ycsbc::DB::KVPair>* values = new std::vector<ycsbc::DB::KVPair>(); values->reserve(16); workload.BuildValues(*values); return TxInsert(table, key, values); } const ycsbcwrappers::TxUpdate ycsbcwrappers::TransactionUpdate(ycsbc::CoreWorkload&workload) { const std::string &table = workload.NextTable(); const std::string &key = workload.NextTransactionKey(); std::vector<ycsbc::DB::KVPair>* values = new std::vector<ycsbc::DB::KVPair>(); values->reserve(16); if (workload.write_all_fields()) { workload.BuildValues(*values); } else { workload.BuildUpdate(*values); } return TxUpdate(table, key, values); } const ycsbcwrappers::TxScan ycsbcwrappers::TransactionScan(ycsbc::CoreWorkload&workload) { const std::string &table = workload.NextTable(); const std::string &key = workload.NextSequenceKey(); int len = workload.NextScanLength(); if (!workload.read_all_fields()) { std::vector<std::string>* fields = new std::vector<std::string>; fields->push_back("field" + workload.NextFieldName()); return TxScan(table, key, len, fields); } else { return TxScan(table, key, len, NULL); } }
35.529412
105
0.683361
[ "vector" ]
43775526686a8f6107a31fac7afe99d65242451a
10,415
cc
C++
engines/ep/tests/module_tests/collections/collections_kvstore_test.cc
gsauere/kv_engine
233945fe4ddb033c2292e51f5845ab630c33276f
[ "BSD-3-Clause" ]
null
null
null
engines/ep/tests/module_tests/collections/collections_kvstore_test.cc
gsauere/kv_engine
233945fe4ddb033c2292e51f5845ab630c33276f
[ "BSD-3-Clause" ]
null
null
null
engines/ep/tests/module_tests/collections/collections_kvstore_test.cc
gsauere/kv_engine
233945fe4ddb033c2292e51f5845ab630c33276f
[ "BSD-3-Clause" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2019 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "checkpoint_manager.h" #include "configuration.h" #include "ep_vb.h" #include "failover-table.h" #include "item.h" #include "kvstore.h" #include "kvstore_config.h" #include "stats.h" #include "tests/module_tests/collections/test_manifest.h" #include "tests/module_tests/kvstore_test.h" /// Dummy callback to replace the flusher callback so we can create VBuckets class DummyCB : public Callback<Vbid> { public: DummyCB() { } void callback(Vbid& dummy) { } }; struct WriteCallback { void operator()(TransactionContext&, KVStore::MutationSetResultState) { } }; struct DeleteCallback { void operator()(TransactionContext&, KVStore::MutationStatus) { } }; class CollectionsKVStoreTest : public KVStoreParamTest { public: CollectionsKVStoreTest() : vbucket(Vbid(0), vbucket_state_active, global_stats, checkpoint_config, /*kvshard*/ nullptr, /*lastSeqno*/ 0, /*lastSnapStart*/ 0, /*lastSnapEnd*/ 0, /*table*/ nullptr, std::make_shared<DummyCB>(), /*newSeqnoCb*/ nullptr, NoopSyncWriteCompleteCb, NoopSeqnoAckCb, config, EvictionPolicy::Value, std::make_unique<Collections::VB::Manifest>()) { } void getEventsFromCheckpoint(std::vector<queued_item>& events) { std::vector<queued_item> items; vbucket.checkpointManager->getAllItemsForPersistence(items); for (const auto& qi : items) { if (qi->getOperation() == queue_op::system_event) { events.push_back(qi); } } ASSERT_FALSE(events.empty()) << "getEventsFromCheckpoint: no events in " << vbucket.getId(); } void applyEvents(const CollectionsManifest& cm) { manifest.wlock().update(vbucket, {cm}); std::vector<queued_item> events; getEventsFromCheckpoint(events); for (auto& ev : events) { if (ev->isDeleted()) { kvstore->delSystemEvent(*ev, dc); } else { kvstore->setSystemEvent(*ev, wc); } } } void checkUid(const Collections::KVStore::Manifest& md, const CollectionsManifest& cm) { EXPECT_EQ(cm.getUid(), md.manifestUid); } void checkCollections( const Collections::KVStore::Manifest& md, const CollectionsManifest& cm, size_t expectedMatches, std::vector<CollectionID> expectedDropped = {}) const { EXPECT_EQ(expectedMatches, md.collections.size()); auto expected = cm.getCreateEventVector(); EXPECT_EQ(expectedMatches, expected.size()); size_t matched = 0; // No ordering expectations from KVStore, so compare all for (const auto& e : expected) { for (const auto& c : md.collections) { if (c.metaData == e) { matched++; if (expectedMatches == matched) { break; // done } } } } EXPECT_EQ(expectedMatches, matched); auto dropped = kvstore->getDroppedCollections(Vbid(0)); if (!expectedDropped.empty()) { EXPECT_TRUE(md.droppedCollectionsExist); matched = 0; EXPECT_EQ(expectedDropped.size(), dropped.size()); for (const auto cid : expectedDropped) { auto p = [cid](const Collections::KVStore::DroppedCollection& dropped) { return dropped.collectionId == cid; }; auto found = std::find_if(dropped.begin(), dropped.end(), p); if (found != dropped.end()) { matched++; if (expectedDropped.size() == matched) { break; // done } } } EXPECT_EQ(expectedDropped.size(), matched); } else { EXPECT_FALSE(md.droppedCollectionsExist); EXPECT_TRUE(dropped.empty()); } } void checkScopes(const Collections::KVStore::Manifest& md, const CollectionsManifest& cm, int expectedMatches) const { auto expectedScopes = cm.getScopeIdVector(); EXPECT_EQ(expectedMatches, expectedScopes.size()); EXPECT_EQ(expectedMatches, md.scopes.size()); int matched = 0; for (const auto sid : expectedScopes) { auto found = std::find(md.scopes.begin(), md.scopes.end(), sid); if (found != md.scopes.end()) { matched++; if (expectedMatches == matched) { break; // done } } } EXPECT_EQ(expectedMatches, matched); } void applyAndCheck(const CollectionsManifest& cm, int expectedCollections, int expectedScopes, std::vector<CollectionID> expectedDropped = {}) { kvstore->begin(std::make_unique<TransactionContext>()); applyEvents(cm); kvstore->commit(flush); auto md = kvstore->getCollectionsManifest(Vbid(0)); checkUid(md, cm); checkCollections(md, cm, expectedCollections, expectedDropped); checkScopes(md, cm, expectedScopes); }; protected: EPStats global_stats; CheckpointConfig checkpoint_config; Configuration config; EPVBucket vbucket; WriteCallback wc; DeleteCallback dc; }; TEST_P(CollectionsKVStoreTest, initial_meta) { // Ask the kvstore for the initial meta auto md = kvstore->getCollectionsManifest(Vbid(0)); // Expect 1 collection and 1 scope EXPECT_EQ(1, md.collections.size()); EXPECT_EQ(1, md.scopes.size()); // It's the default collection and the default scope EXPECT_EQ(0, md.collections[0].startSeqno); EXPECT_EQ("_default", md.collections[0].metaData.name); EXPECT_EQ(CollectionID::Default, md.collections[0].metaData.cid); EXPECT_EQ(ScopeID::Default, md.collections[0].metaData.sid); EXPECT_FALSE(md.collections[0].metaData.maxTtl.is_initialized()); EXPECT_EQ(ScopeID::Default, md.scopes[0]); EXPECT_EQ(0, md.manifestUid); } TEST_P(CollectionsKVStoreTest, one_update) { CollectionsManifest cm; cm.add(CollectionEntry::vegetable); applyAndCheck(cm, 2, 1); } TEST_P(CollectionsKVStoreTest, two_updates) { CollectionsManifest cm; cm.add(CollectionEntry::vegetable).add(CollectionEntry::fruit); applyAndCheck(cm, 3, 1); } TEST_P(CollectionsKVStoreTest, updates_with_scopes) { CollectionsManifest cm; cm.add(ScopeEntry::shop1) .add(CollectionEntry::vegetable, ScopeEntry::shop1); cm.add(ScopeEntry::shop2).add(CollectionEntry::fruit, ScopeEntry::shop2); applyAndCheck(cm, 3, 3); } TEST_P(CollectionsKVStoreTest, updates_between_commits) { CollectionsManifest cm; cm.add(ScopeEntry::shop1) .add(CollectionEntry::vegetable, ScopeEntry::shop1); applyAndCheck(cm, 2, 2); cm.add(ScopeEntry::shop2).add(CollectionEntry::fruit, ScopeEntry::shop2); applyAndCheck(cm, 3, 3); cm.add(CollectionEntry::meat, ScopeEntry::shop2); applyAndCheck(cm, 4, 3); } TEST_P(CollectionsKVStoreTest, updates_and_drops_between_commits) { CollectionsManifest cm; cm.add(ScopeEntry::shop1) .add(CollectionEntry::vegetable, ScopeEntry::shop1); applyAndCheck(cm, 2, 2); cm.add(ScopeEntry::shop2).add(CollectionEntry::fruit, ScopeEntry::shop2); applyAndCheck(cm, 3, 3); cm.add(CollectionEntry::meat, ScopeEntry::shop2); applyAndCheck(cm, 4, 3); cm.remove(CollectionEntry::fruit, ScopeEntry::shop2); applyAndCheck(cm, 3, 3, {CollectionUid::fruit}); cm.remove(CollectionEntry::meat, ScopeEntry::shop2); applyAndCheck(cm, 2, 3, {CollectionUid::fruit, CollectionUid::meat}); cm.remove(CollectionEntry::vegetable, ScopeEntry::shop1); applyAndCheck(cm, 1, 3, {CollectionUid::fruit, CollectionUid::meat, CollectionUid::vegetable}); cm.remove(CollectionEntry::defaultC); applyAndCheck(cm, 0, 3, {CollectionUid::fruit, CollectionUid::meat, CollectionUid::vegetable, CollectionUid::defaultC}); } // Recreate a dropped collection not ideal whilst it still exists TEST_P(CollectionsKVStoreTest, add_of_dropped) { CollectionsManifest cm; cm.add(CollectionEntry::vegetable); applyAndCheck(cm, 2, 1); cm.remove(CollectionEntry::vegetable); applyAndCheck(cm, 1, 1, {CollectionUid::vegetable}); cm.add(CollectionEntry::vegetable); try { applyAndCheck(cm, 1, 1); FAIL() << "Expected an exception"; } catch (const std::exception& e) { EXPECT_STREQ( "CouchKVStore::updateOpenCollections found a new collection in " "dropped list, cid:0xa", e.what()); } } static std::string kvstoreTestParams[] = {"couchdb"}; INSTANTIATE_TEST_CASE_P(CollectionsKVStoreTests, CollectionsKVStoreTest, ::testing::ValuesIn(kvstoreTestParams), [](const ::testing::TestParamInfo<std::string>& info) { return info.param; });
34.372937
80
0.595103
[ "vector" ]
4379c034a7fca53e05c91f6f9ec585a9b9f6b67e
7,071
cpp
C++
Reis/graphics/image/SpriteSheet.cpp
marcelomesmo/Raiz
19ddd256b71faa8e042637513f67142ffc2eb281
[ "Zlib" ]
2
2020-06-17T18:27:43.000Z
2020-06-17T19:42:53.000Z
Reis/graphics/image/SpriteSheet.cpp
marcelomesmo/Raiz
19ddd256b71faa8e042637513f67142ffc2eb281
[ "Zlib" ]
null
null
null
Reis/graphics/image/SpriteSheet.cpp
marcelomesmo/Raiz
19ddd256b71faa8e042637513f67142ffc2eb281
[ "Zlib" ]
null
null
null
#include "SpriteSheet.h" SpriteSheet::SpriteSheet(std::string path, int sprite_width, int sprite_height, Color* transparent) { create(path, sprite_width, sprite_height); } SpriteSheet::SpriteSheet() { } SpriteSheet::~SpriteSheet() { free(); } void SpriteSheet::free() { //Free texture if it exists if (image != NULL) { SDL_DestroyTexture(image); image = NULL; width = 0; height = 0; //Free pointers for (SDL_Rect* s : spriteClips) { delete s; s = NULL; } } } /* * ************************************* * Creating Sprite Sheet * ************************************* */ // Load Sprite Sheets using Sprites with the same size (in width and height) bool SpriteSheet::create(std::string path, int sprite_width, int sprite_height, Color* transparent) { // Create a Sprite with specified image path if(!initImage(path, transparent)) return false; /* For SpriteSheets with Sprites that have the same size (in width and height): sheet width ---> sheet width ---> ________________ ex: 32x32 ___________________ | 1 2 3 | | imgs | 0,0 32,0 64,0 | | | 4 5 6 | | sheet height | 0,32 32,32 64,32 | | sheet height |_7____8___imgs_| v |_0,64_32,64_64,64_| v imgs on a sheet img pos on sheet */ this->lines = 0; // Check all lines in the sprite sheet for (int j = 0; j < this->height; j += sprite_height) { this->columns = 0; // Check all columns in the sprite sheet for (int i = 0; i < this->width; i += sprite_width) { // Get Clip for Sprite in the current position SDL_Rect* clip = new SDL_Rect(); clip->x = i; clip->y = j; clip->w = sprite_width; clip->h = sprite_height; //clip = {i, j, sprite_width, sprite_height}; spriteClips.push_back(clip); this->columns++; } this->lines++; } // Get how many Sprites we have in the Sprite Sheet (include empty spaces) this->size = spriteClips.size(); isXmlLoaded = false; return true; } // Load Sprite Sheets using a XML metadata for the Sprites // Support: MuSSEXmlParser. bool SpriteSheet::create(std::string path, std::string musse_xml_path) { // Open parser and load xml if (!parsed_xml.parseXmlFile(musse_xml_path.c_str())) { std::cout << "ERROR: [SS::MUSSE::create] Couldn't open file [" << musse_xml_path << "]" << std::endl; return false; } // Create a Spritesheet with specified image path and color key if (!initImage(path, parsed_xml.getColorKey())) { std::cout << "ERROR: [SS::MUSSE::create] Couldn't create sprite sheet with path [" << path << "]" << std::endl; return false; } isXmlLoaded = true; return true; } /* * ************************************* * Getting Sprites * ************************************* */ /* Get a sprite (or clip) at a particular cell on the sprite sheet int sheetPosX - the X position of the cell on the SpriteSheet int sheetPosY - the Y position of the cell on the SpriteSheet sheet pos X ---> _____________________ | 0,0 1,0 2,0 3,0 | | 0 1 2 3 | 0,1 1,1 2,1 3,1 | | sheet pos Y 4 5 6 7 |_0,2__1,2__2,2__3,2_| v 8 9 10 11 imgs on a sheet sheet ordered count */ SDL_Rect* SpriteSheet::getClip(int sheetPosX, int sheetPosY) { int count = getSpriteCountByPos(sheetPosX, sheetPosY); if (count < 0 || (unsigned)count > spriteClips.size() - 1) { printf("ERROR: [SS::getClip] Invalid sprite frame position %i \n", count); return spriteClips[0]; } return spriteClips[count]; } SDL_Rect* SpriteSheet::getClip(int count) { if (count < 0 || (unsigned)count > spriteClips.size() - 1) { printf("ERROR: [SS::getClip] Invalid sprite frame position %i \n", count); return spriteClips[0]; } return spriteClips[count]; } std::vector<Sprite_Xml> SpriteSheet::getAnimation(std::string name) { return parsed_xml.getSpritesData(name); } bool SpriteSheet::hasAnimation(std::string name) { // Check if Sprite Sheet has been read from Xml if (!isXmlLoaded) { std::cout << "ERROR: [SS::hasAnim] Sprite Sheet ain't loaded from Xml.\n"; return false; } if (!parsed_xml.hasAnimation(name)) { std::cout << "ERROR: [SS::hasAnim] There is no Animation with name "<< name << ".\n"; return false; } return true; } int SpriteSheet::getSpriteCountByPos(int sheetPosX, int sheetPosY) { return sheetPosX + (sheetPosY * columns); } int SpriteSheet::getSpriteCount() { return this->size; } int SpriteSheet::getHorizontalCount() { return this->lines; } int SpriteSheet::getVerticalCount() { return this->columns; } int SpriteSheet::getWidth() { return width; } int SpriteSheet::getHeight() { return height; } SDL_Texture* SpriteSheet::getImage() { return image; } bool SpriteSheet::initImage(std::string path, Color* transparent) { //Get rid of preexisting texture free(); //The final texture SDL_Texture* newTexture = NULL; //Load image at specified path SDL_Surface* loadedSurface = IMG_Load(path.c_str()); if (loadedSurface == NULL) { printf("ERROR: [SS::initImage] Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError()); } else { //Convert surface to display format SDL_Surface* formattedSurface = SDL_ConvertSurfaceFormat(loadedSurface, SDL_PIXELFORMAT_RGBA8888, NULL); if (formattedSurface == NULL) { printf("ERROR: [SS::initImage] Unable to convert loaded surface to display format! %s\n", SDL_GetError()); } else { //Create blank streamable texture newTexture = SDL_CreateTexture(Graphics::renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, formattedSurface->w, formattedSurface->h); if (newTexture == NULL) { printf("ERROR: [SS::initImage] Unable to create blank texture! SDL Error: %s\n", SDL_GetError()); } else { //Enable blending on texture SDL_SetTextureBlendMode(newTexture, SDL_BLENDMODE_BLEND); //Lock texture for manipulation SDL_LockTexture(newTexture, &formattedSurface->clip_rect, &pixels, &pitch); //Copy loaded/formatted surface pixels memcpy(pixels, formattedSurface->pixels, formattedSurface->pitch * formattedSurface->h); //Get image dimensions width = formattedSurface->w; height = formattedSurface->h; //Get pixel data in editable format Uint32* pixs = (Uint32*)pixels; int pixelCount = (pitch / 4) * height; //Map colors SDL_Color colorTransparency = ColorManager::getColor(transparent); Uint32 colorKey = SDL_MapRGB(formattedSurface->format, colorTransparency.r, colorTransparency.g, colorTransparency.b); Uint32 transparency = SDL_MapRGBA(formattedSurface->format, 0x00, 0xFF, 0xFF, 0x00); //Color key pixels for (int i = 0; i < pixelCount; ++i) { if (pixs[i] == colorKey) { pixs[i] = transparency; } } //Unlock texture to update SDL_UnlockTexture(newTexture); pixels = NULL; } //Get rid of old formatted surface SDL_FreeSurface(formattedSurface); } //Get rid of old loaded surface SDL_FreeSurface(loadedSurface); } //Return success image = newTexture; return image != NULL; }
28.512097
151
0.662424
[ "vector" ]
437fb01d05db76f509f4a73e5bc06c9de0ab8308
7,563
cc
C++
flexirf/src/GIRFAxisParam.cc
cosimoNigro/flexIRF
3ae91dc677b94c6e8264c35be4733a7feeebef31
[ "Apache-2.0" ]
2
2016-08-24T12:13:31.000Z
2020-08-07T20:33:13.000Z
flexirf/src/GIRFAxisParam.cc
cosimoNigro/flexIRF
3ae91dc677b94c6e8264c35be4733a7feeebef31
[ "Apache-2.0" ]
8
2016-03-02T15:23:40.000Z
2016-05-31T12:29:37.000Z
flexirf/src/GIRFAxisParam.cc
cosimoNigro/flexIRF
3ae91dc677b94c6e8264c35be4733a7feeebef31
[ "Apache-2.0" ]
4
2016-03-03T15:02:25.000Z
2020-08-07T13:03:54.000Z
/* ======================================================================== *\ ! ! Author(s): Javier Rico 12/2013 <mailto:jrico@ifae.es> ! ! Copyright: CTA Software Development, 2013 ! \* ======================================================================== */ ////////////////////////////////////////////////////////////////////////////// // // GIRFAxisParam // // Class to represent axes describing the organization of data // in the GIRF object // The axis represents a parameterization // ////////////////////////////////////////////////////////////////////////////// #include <iostream> #include "GIRFAxisParam.h" #include "string.h" using namespace std; //////////////////////////////////////////////////////////////// // // Construct empty axis object // flexIRF::GIRFAxisParam::GIRFAxisParam() : GIRFAxis(), fAxisParameterizationFilled(0){ SetAxisType(kParam); } //////////////////////////////////////////////////////////////// // // Construct axis object with predefined data // flexIRF::GIRFAxisParam::GIRFAxisParam(VarType varType, ScaleType scaleType) : GIRFAxis(varType), fAxisParameterizationFilled(0){ SetAxisType(kParam); SetScale(scaleType); } //////////////////////////////////////////////////////////////// // // Construct axis object with predefined vectors (using arrays) // flexIRF::GIRFAxisParam::GIRFAxisParam(VarType varType, AxisParameterization axisParam, ScaleType scaleType) : GIRFAxis(varType) { SetAxisType(kParam); fAxisParam = axisParam; SetScale(scaleType); // Check if the axis is properly parameterized CheckAxisParameterizationFilled(); } //////////////////////////////////////////////////////////////// // // Construct axis object directly reading from HDU // flexIRF::GIRFAxisParam::GIRFAxisParam(fitsfile* fptr, int* status) { SetAxisType(kParam); long int nRows; int nCol, anynull; float nullfloat = 0.0F; char card[FLEN_CARD]; /* Standard string lengths defined in fitsio.h */ char *longcard; float validRangeLow, validRangeHigh; int numVars; fits_get_num_rows(fptr, &nRows, status); fits_get_num_cols(fptr, &nCol, status); float farray[nRows]; //TODO: For now, just get one column. In the future maybe Axis should have several columns (low/high bin edges) fits_read_col(fptr, TFLOAT, 1, 1, 1, nRows, &nullfloat, &farray, &anynull, status); fits_read_key_str(fptr, "NUMVARS", card, NULL, status); numVars = atoi(card); fits_read_key_longstr(fptr, "FORMULA", &longcard, NULL, status); SetFormula((string) longcard, numVars); fits_read_key_str(fptr, "VARTYPE", card, NULL, status); SetVarType((VarType) atoi(card)); fits_read_key_str(fptr, "VRANGE_L", card, NULL, status); fAxisParam.validRangeLow = atof(card); fits_read_key_str(fptr, "VRANGE_H", card, NULL, status); fAxisParam.validRangeHigh = atof(card); // SetValidRange(); fits_read_key_str(fptr, "SCALE", card, NULL, status); SetScale((string) card); //TODO: Read everything from fits file. CheckAxisParameterizationFilled(); } //////////////////////////////////////////////////////////////// // // Check if axis contains AxisRange // bool flexIRF::GIRFAxisParam::ContainsRange(AxisRange axisRange) { //TODO: Modify as soon as I add the range of validity!!! if (!fAxisParameterizationFilled) return 0; if (axisRange.varType != GetVarType()) return 0; //Sanity check else { if (axisRange.lowRange >= GetRangeMin() && axisRange.highRange <= GetRangeMax()){ return 1; } else return 0; } } void flexIRF::GIRFAxisParam::SetAxisParam(AxisParameterization axisParam){ fAxisParam = axisParam; // Check if the axis is properly parameterized CheckAxisParameterizationFilled(); } //////////////////////////////////////////////////////////////// // // Set the parametrized formula of the axis. // void flexIRF::GIRFAxisParam::SetFormula(string formula, std::vector<float>::size_type numParameters) { fAxisParam.formula = formula; // Fill vector with arrays fAxisParam.numParameters = numParameters; CheckAxisParameterizationFilled(); } //////////////////////////////////////////////////////////////// // // Set the valid range of the parameterization. // void flexIRF::GIRFAxisParam::SetValidRange(float validRangeLow, float validRangeHigh) { fAxisParam.validRangeLow = validRangeLow; fAxisParam.validRangeHigh = validRangeHigh; CheckAxisParameterizationFilled(); } //////////////////////////////////////////////////////////////// // // Write the axis to the specified file pointer // int const flexIRF::GIRFAxisParam::Write(fitsfile* fptr, int& axisID, int* status) { // fill the data array float* axisdata; if (!CheckAxisExists(fptr, axisID, status)) { // write the axis header and data WriteAxis(fptr, 0, axisdata, axisID, status); } return *status; } //////////////////////////////////////////////////////////////// // // Check if the Axis already exists within the fits file // bool const flexIRF::GIRFAxisParam::CheckAxisExists(fitsfile* fptr, int& axisID, int* status) { int currenthdu = fptr->HDUposition; char card[FLEN_CARD]; /* Standard string lengths defined in fitsio.h */ int single = 0, hdutype = BINARY_TBL, hdunum, nkeys, ii; fits_get_num_hdus(fptr, &hdunum, status); for (int hdupos = 1; hdupos <= hdunum; hdupos++) /* Main loop through each extension */ { fits_movabs_hdu(fptr, hdupos, &hdutype, status); if (hdutype == BINARY_TBL) { if (!fits_read_key_str(fptr, "HDUCLAS2", card, NULL, status)) { if (!strcmp(card, "AXIS")) { if (!fits_read_key_str(fptr, "VARTYPE", card, NULL, status)) { if ((ushort) atoi(card) == (ushort) this->GetVarType()) { if (!fits_read_key_str(fptr, "HDUCLAS3", card, NULL, status)) { if (!strcmp(card, "PARAM") && this->GetAxisType() == kParam) { GIRFAxisParam* IRFAxis = new GIRFAxisParam( fptr, status); if ((*IRFAxis) == (*this)) { if (!fits_read_key_str(fptr, "HDUCLAS4", card, NULL, status)) { axisID = (ushort) atoi(card); return TRUE; } } } } } } } } } if (*status == KEY_NO_EXIST) *status = 0; if (*status) break; } fits_movabs_hdu(fptr, currenthdu + 1, NULL, status); return FALSE; } //////////////////////////////////////////////////////////////// // // Check that the vector describe consistently the axis // int flexIRF::GIRFAxisParam::CheckAxisConsistency() { int status = GIRFAxis::CheckAxisConsistency(); if (!fAxisParameterizationFilled) status++; //TODO: Check if the function contains the correct number of constants and variables.?? return status; } //////////////////////////////////////////////////////////////// // // Print the content of the parameterized axis. // void const flexIRF::GIRFAxisParam::Print() { cout << "GIRFAxisParam:" << endl; cout << "formula = " << fAxisParam.formula << endl; cout << "numParameters = " << fAxisParam.numParameters << endl; cout << "valid Range = { " << fAxisParam.validRangeLow << ", " << fAxisParam.validRangeHigh << "}" << endl; //TODO: print constants } //////////////////////////////////////////////////////////////// // // Check if the parameterized axis is filled propperly // bool flexIRF::GIRFAxisParam::CheckAxisParameterizationFilled(){ if (fAxisParam.validRangeLow < fAxisParam.validRangeHigh && fAxisParam.validRangeLow != fAxisParam.validRangeHigh){ if (!fAxisParam.formula.empty()){ fAxisParameterizationFilled=1; return 1; } } return 0; }
26.914591
116
0.595399
[ "object", "vector" ]