hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
fdf1d661f8f8bfeb1556b63da2e344d6f3cab9d6
47
cpp
C++
out.cpp
Hubear-MUC/File-access
67dc59c7ead3ce1df47989a6b188dc7062a6aa73
[ "MIT" ]
null
null
null
out.cpp
Hubear-MUC/File-access
67dc59c7ead3ce1df47989a6b188dc7062a6aa73
[ "MIT" ]
null
null
null
out.cpp
Hubear-MUC/File-access
67dc59c7ead3ce1df47989a6b188dc7062a6aa73
[ "MIT" ]
null
null
null
void out(int v) { printf ("out: %d\n", v); }
9.4
26
0.489362
Hubear-MUC
fdf42d457833e1f0d4d185ff0b3780a7b4e7c7e6
311
cpp
C++
code/11.maxArea.cpp
T1mzhou/LeetCode
574540d30f5696e55799831dc3c8d8b7246b74f1
[ "MIT" ]
1
2020-10-04T13:39:34.000Z
2020-10-04T13:39:34.000Z
code/11.maxArea.cpp
T1mzhou/LeetCode
574540d30f5696e55799831dc3c8d8b7246b74f1
[ "MIT" ]
null
null
null
code/11.maxArea.cpp
T1mzhou/LeetCode
574540d30f5696e55799831dc3c8d8b7246b74f1
[ "MIT" ]
null
null
null
class Solution { public: int maxArea(vector<int>& height) { int res = 0; for (int i = 0, j = height.size() - 1; i < j;) { res = max(res, min(height[i], height[j]) * (j - i)); if (height[i] > height[j]) j--; else i++; } return res; } };
25.916667
64
0.424437
T1mzhou
fdf555e7f4041f2e45261485729b7426387b80e6
3,908
cc
C++
test/extensions/filters/listener/original_src/original_src_socket_option_test.cc
bianpengyuan/envoy
925810d00b0d3095a8e67fd4e04e0f597ed188bb
[ "Apache-2.0" ]
1
2019-02-14T01:02:29.000Z
2019-02-14T01:02:29.000Z
test/extensions/filters/listener/original_src/original_src_socket_option_test.cc
bianpengyuan/envoy
925810d00b0d3095a8e67fd4e04e0f597ed188bb
[ "Apache-2.0" ]
null
null
null
test/extensions/filters/listener/original_src/original_src_socket_option_test.cc
bianpengyuan/envoy
925810d00b0d3095a8e67fd4e04e0f597ed188bb
[ "Apache-2.0" ]
null
null
null
#include "envoy/network/address.h" #include "common/network/utility.h" #include "extensions/filters/listener/original_src/original_src_socket_option.h" #include "test/mocks/common.h" #include "test/mocks/network/mocks.h" #include "test/test_common/printers.h" #include "test/test_common/test_base.h" #include "gmock/gmock.h" using testing::_; using testing::Eq; namespace Envoy { namespace Extensions { namespace ListenerFilters { namespace OriginalSrc { namespace { class OriginalSrcSocketOptionTest : public TestBase { public: std::unique_ptr<OriginalSrcSocketOption> makeOptionByAddress(const Network::Address::InstanceConstSharedPtr& address) { return std::make_unique<OriginalSrcSocketOption>(address); } protected: NiceMock<Network::MockConnectionSocket> socket_; std::vector<uint8_t> key_; }; TEST_F(OriginalSrcSocketOptionTest, TestSetOptionPreBindSetsAddress) { const auto address = Network::Utility::parseInternetAddress("127.0.0.2"); auto option = makeOptionByAddress(address); EXPECT_CALL(socket_, setLocalAddress(PointeesEq(address))); EXPECT_EQ(option->setOption(socket_, envoy::api::v2::core::SocketOption::STATE_PREBIND), true); } TEST_F(OriginalSrcSocketOptionTest, TestSetOptionPreBindSetsAddressSecond) { const auto address = Network::Utility::parseInternetAddress("1.2.3.4"); auto option = makeOptionByAddress(address); EXPECT_CALL(socket_, setLocalAddress(PointeesEq(address))); EXPECT_EQ(option->setOption(socket_, envoy::api::v2::core::SocketOption::STATE_PREBIND), true); } TEST_F(OriginalSrcSocketOptionTest, TestSetOptionNotPrebindDoesNotSetAddress) { const auto address = Network::Utility::parseInternetAddress("1.2.3.4"); auto option = makeOptionByAddress(address); EXPECT_CALL(socket_, setLocalAddress(_)).Times(0); EXPECT_EQ(option->setOption(socket_, envoy::api::v2::core::SocketOption::STATE_LISTENING), true); } TEST_F(OriginalSrcSocketOptionTest, TestIpv4HashKey) { const auto address = Network::Utility::parseInternetAddress("1.2.3.4"); auto option = makeOptionByAddress(address); option->hashKey(key_); // The ip address broken into big-endian octets. std::vector<uint8_t> expected_key = {1, 2, 3, 4}; EXPECT_EQ(key_, expected_key); } TEST_F(OriginalSrcSocketOptionTest, TestIpv4HashKeyOther) { const auto address = Network::Utility::parseInternetAddress("255.254.253.0"); auto option = makeOptionByAddress(address); option->hashKey(key_); // The ip address broken into big-endian octets. std::vector<uint8_t> expected_key = {255, 254, 253, 0}; EXPECT_EQ(key_, expected_key); } TEST_F(OriginalSrcSocketOptionTest, TestIpv6HashKey) { const auto address = Network::Utility::parseInternetAddress("102:304:506:708:90a:b0c:d0e:f00"); auto option = makeOptionByAddress(address); option->hashKey(key_); std::vector<uint8_t> expected_key = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x0}; EXPECT_EQ(key_, expected_key); } TEST_F(OriginalSrcSocketOptionTest, TestIpv6HashKeyOther) { const auto address = Network::Utility::parseInternetAddress("F02:304:519:708:90a:b0e:FFFF:0000"); auto option = makeOptionByAddress(address); option->hashKey(key_); std::vector<uint8_t> expected_key = {0xF, 0x2, 0x3, 0x4, 0x5, 0x19, 0x7, 0x8, 0x9, 0xa, 0xb, 0xe, 0xff, 0xff, 0x0, 0x0}; EXPECT_EQ(key_, expected_key); } TEST_F(OriginalSrcSocketOptionTest, TestOptionDetailsNotSupported) { const auto address = Network::Utility::parseInternetAddress("255.254.253.0"); auto option = makeOptionByAddress(address); auto details = option->getOptionDetails(socket_, envoy::api::v2::core::SocketOption::STATE_PREBIND); EXPECT_FALSE(details.has_value()); } } // namespace } // namespace OriginalSrc } // namespace ListenerFilters } // namespace Extensions } // namespace Envoy
35.527273
99
0.746929
bianpengyuan
fdf57738ac5597964b420620738d4d9bd40ce2d3
2,112
cpp
C++
Samples/XamlListView/cppwinrt/Item.cpp
ayhrgr/Windows-universal-samples
7b34a9f7613be0c5316428426dfc6df8ce657f02
[ "MIT" ]
1
2022-03-21T20:16:53.000Z
2022-03-21T20:16:53.000Z
Samples/XamlListView/cppwinrt/Item.cpp
sanskarjain2110/Windows-universal-samples
7b34a9f7613be0c5316428426dfc6df8ce657f02
[ "MIT" ]
null
null
null
Samples/XamlListView/cppwinrt/Item.cpp
sanskarjain2110/Windows-universal-samples
7b34a9f7613be0c5316428426dfc6df8ce657f02
[ "MIT" ]
null
null
null
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "Item.h" #include "Item.g.cpp" using namespace winrt::Windows::Foundation; using namespace winrt::Windows::Foundation::Collections; using namespace winrt::Windows::UI::Xaml::Media; using namespace winrt::Windows::UI::Xaml::Media::Imaging; namespace winrt::SDKTemplate::implementation { ImageSource Item::GenerateImageSource(int index) { static std::vector<BitmapImage> sources({ BitmapImage(Uri(L"ms-appx:///Assets/cliff.jpg")), BitmapImage(Uri(L"ms-appx:///Assets/grapes_background.jpg")), BitmapImage(Uri(L"ms-appx:///Assets/LandscapeImage13.jpg")), BitmapImage(Uri(L"ms-appx:///Assets/LandscapeImage2.jpg")), BitmapImage(Uri(L"ms-appx:///Assets/LandscapeImage24.jpg")), BitmapImage(Uri(L"ms-appx:///Assets/LandscapeImage3.jpg")), BitmapImage(Uri(L"ms-appx:///Assets/LandscapeImage6.jpg")), BitmapImage(Uri(L"ms-appx:///Assets/LandscapeImage7.jpg")), BitmapImage(Uri(L"ms-appx:///Assets/Ring01.jpg")), BitmapImage(Uri(L"ms-appx:///Assets/Ring03Part1.jpg")), BitmapImage(Uri(L"ms-appx:///Assets/Ring03Part3.jpg")), BitmapImage(Uri(L"ms-appx:///Assets/sunset.jpg")), }); return sources[index % sources.size()]; } IObservableVector<SDKTemplate::Item> Item::GetItems(int count) { std::vector<SDKTemplate::Item> items; std::generate_n(std::back_inserter(items), count, [i = 0]() mutable { return make<Item>(i++); }); return single_threaded_observable_vector(std::move(items)); } }
43.102041
106
0.607008
ayhrgr
fdf6ab77ec4a1da5e23eb8942f1a09482429c944
1,679
cpp
C++
doom_py/examples/c++/CIG.cpp
xakiru/doom-py
85ada06dc9603e2f0768a06e4fcae637cf1c3931
[ "MIT" ]
78
2016-05-08T19:20:58.000Z
2022-01-17T22:40:25.000Z
doom_py/examples/c++/CIG.cpp
xakiru/doom-py
85ada06dc9603e2f0768a06e4fcae637cf1c3931
[ "MIT" ]
15
2016-05-10T19:15:31.000Z
2021-09-30T22:18:32.000Z
doom_py/examples/c++/CIG.cpp
xakiru/doom-py
85ada06dc9603e2f0768a06e4fcae637cf1c3931
[ "MIT" ]
42
2016-05-08T19:19:40.000Z
2021-09-19T06:53:08.000Z
#include "ViZDoom.h" #include <iostream> #include <vector> using namespace vizdoom; int main(){ std::cout << "\n\nCIG EXAMPLE\n\n"; DoomGame* game = new DoomGame(); // Use CIG example config or Your own. game->loadConfig("../../examples/config/cig.cfg"); // Select game and map You want to use. game->setDoomGamePath("../../scenarios/freedoom2.wad"); //game->setDoomGamePath("../../scenarios/doom2.wad"); // Not provided with environment due to licences. game->setDoomMap("map01"); // Limited deathmatch. //game->setDoomMap("map02"); // Full deathmatch. // Join existing game. game->addGameArgs("-join 127.0.0.1"); // Connect to a host for a multiplayer game. // Name Your AI. game->addGameArgs("+name AI"); game->setMode(ASYNC_PLAYER); // Multiplayer requires the use of asynchronous modes. game->init(); while(!game->isEpisodeFinished()){ // Play until the game (episode) is over. if(game->isPlayerDead()){ // Check if player is dead game->respawnPlayer(); // Use this to respawn immediately after death, new state will be available. // Or observe the game until automatic respawn. //game->advanceAction(); //continue; } GameState state = game->getState(); // Analyze the state. std::vector<int> action(game->getAvailableButtonsSize()); // Set your action. game->makeAction(action); std::cout << game->getEpisodeTime() << " Frags: " << game->getGameVariable(FRAGCOUNT) << std::endl; } game->close(); }
29.982143
124
0.591423
xakiru
fdf6cf8e102b6b61a14ba7d10363a1e656798d9d
900
hpp
C++
Raspberrypi/module/src/frame_stacker.hpp
Dimsmary/MisakaImoto
fce04bd06d58e5b07fb134fd57703984cbb06278
[ "MIT" ]
12
2020-08-07T02:29:17.000Z
2022-03-14T04:26:15.000Z
Raspberrypi/module/src/frame_stacker.hpp
Dimsmary/MisakaImoto
fce04bd06d58e5b07fb134fd57703984cbb06278
[ "MIT" ]
1
2020-10-31T04:32:35.000Z
2020-10-31T04:32:35.000Z
Raspberrypi/module/src/frame_stacker.hpp
Dimsmary/MisakaImoto
fce04bd06d58e5b07fb134fd57703984cbb06278
[ "MIT" ]
2
2020-10-09T01:45:59.000Z
2022-01-20T03:23:07.000Z
// // Created by 79937 on 2020/7/31. // #ifndef DISPLAYIMAGE_FRAME_STACKER_HPP #define DISPLAYIMAGE_FRAME_STACKER_HPP #include <opencv2/opencv.hpp> using namespace std; class frame_stacker { string text; int times; // 文字属性 bool back_ground; int font_face; double font_scale; int thickness; cv::Point origin; int b; int g; int r; public: frame_stacker(): times(0), back_ground(false), text(""), font_face(cv::FONT_HERSHEY_COMPLEX), font_scale(0.8), thickness(1), b(0), g(255), r(255) {origin.x = 0; origin.y = 235;}; void stack(cv::Mat &frame); void fill_times(int Times); void fill_text(string Text); void set_origin(int Y); void set_color(int B, int G, int R); void set_fontscale(double scale); }; #endif //DISPLAYIMAGE_FRAME_STACKER_HPP
18.367347
44
0.612222
Dimsmary
a90b2eeab579be875757b2d10642f63e87aecb92
766
cpp
C++
LeetCode/[Practice Problems]/string_to_integer.cpp
Alecs-Li/Competitive-Programming
39941ff8e2c8994abbae8c96a1ed0a04b10058b8
[ "MIT" ]
1
2021-07-06T02:14:03.000Z
2021-07-06T02:14:03.000Z
LeetCode/[Practice Problems]/string_to_integer.cpp
Alex01890-creator/competitive-programming
39941ff8e2c8994abbae8c96a1ed0a04b10058b8
[ "MIT" ]
null
null
null
LeetCode/[Practice Problems]/string_to_integer.cpp
Alex01890-creator/competitive-programming
39941ff8e2c8994abbae8c96a1ed0a04b10058b8
[ "MIT" ]
null
null
null
class Solution { public: int myAtoi(string s) { if(s.length() == 0){ return 0; } int i = 0; while(s[i] == ' '){ i++; } bool isPositive = true; if(s[i] == '-' || s[i] == '+'){ isPositive = (s[i] == '+' ? true : false); i++; } if(s[i] - '0' < 0 || s[i] - '0' > 9){ return 0; } int num = 0; while(s[i] >= '0' && s[i] <= '9'){ if(num > INT_MAX/10 || (num == INT_MAX/10 && s[i] - '0' > 7)){ return isPositive ? INT_MAX : INT_MIN; } num = num*10 + (s[i] - '0'); i++; } return isPositive ? num : num*-1; } };
23.212121
74
0.314621
Alecs-Li
a90eacea464423f61a2392da908c426498297c50
547
cpp
C++
LeetCode/cpp/1022.cpp
ZintrulCre/LeetCode_Archiver
de23e16ead29336b5ee7aa1898a392a5d6463d27
[ "MIT" ]
279
2019-02-19T16:00:32.000Z
2022-03-23T12:16:30.000Z
LeetCode/cpp/1022.cpp
ZintrulCre/LeetCode_Archiver
de23e16ead29336b5ee7aa1898a392a5d6463d27
[ "MIT" ]
2
2019-03-31T08:03:06.000Z
2021-03-07T04:54:32.000Z
LeetCode/cpp/1022.cpp
ZintrulCre/LeetCode_Crawler
de23e16ead29336b5ee7aa1898a392a5d6463d27
[ "MIT" ]
12
2019-01-29T11:45:32.000Z
2019-02-04T16:31:46.000Z
class Solution { int mod = static_cast<int>(pow(10, 9) + 7); public: int sumRootToLeaf(TreeNode *root) { if (!root) return 0; return Sum(root, 0); } int Sum(TreeNode *node, int &&curr) { int sum = 0; if (!node->left && !node->right) return curr * 2 + node->val % mod; if (node->left) sum += Sum(node->left, curr * 2 + node->val % mod); if (node->right) sum += Sum(node->right, curr * 2 + node->val % mod); return sum; } };
27.35
64
0.478976
ZintrulCre
a912cb3de06ece7074ba89e3c9c78b88cca9ffce
23,413
cpp
C++
libpvkernel/src/rush/PVFormat.cpp
inendi-inspector/inspector
9b9a00222d8a73cb0817ca56790ee9155db61cc4
[ "MIT" ]
null
null
null
libpvkernel/src/rush/PVFormat.cpp
inendi-inspector/inspector
9b9a00222d8a73cb0817ca56790ee9155db61cc4
[ "MIT" ]
null
null
null
libpvkernel/src/rush/PVFormat.cpp
inendi-inspector/inspector
9b9a00222d8a73cb0817ca56790ee9155db61cc4
[ "MIT" ]
null
null
null
// // MIT License // // © ESI Group, 2015 // // 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 <QXmlStreamReader> #include <QFile> #include <QDir> #include <QHashIterator> #include <QDateTime> #include <QFileInfo> #include <QTextStream> #include <pvkernel/core/PVCompList.h> #include <pvkernel/core/PVUtils.h> #include <pvkernel/rush/PVNrawCacheManager.h> #include <pvkernel/rush/PVXmlParamParser.h> #include <pvkernel/rush/PVFormat.h> #include <pvkernel/rush/PVAxisFormat.h> #include <pvkernel/rush/PVNormalizer.h> #include <pvkernel/filter/PVChunkFilterByElt.h> #include <pvkernel/filter/PVChunkFilterByEltCancellable.h> #include <pvkernel/filter/PVElementFilterByAxes.h> #include <pvkernel/filter/PVFieldsMappingFilter.h> #include <pvkernel/filter/PVFieldFilterGrep.h> static const std::unordered_set<std::string> SUPPORTED_TYPES = { "string", "number_uint32", "number_int32", "number_uint64", "number_int64", "number_uint16", "number_int16", "number_uint8", "number_int8", "number_float", "number_double", "time", "duration", "ipv4", "ipv6", "mac_address"}; PVRush::PVFormat::PVFormat() : _format_name(""), _full_path(""), _have_grep_filter(false) {} PVRush::PVFormat::PVFormat(QString const& format_name, QString const& full_path) : _format_name(format_name), _full_path(full_path), _have_grep_filter(false) { if (_format_name.isEmpty() && !_full_path.isEmpty()) { QFileInfo info(_full_path); QString basename = info.baseName(); _format_name = basename; } populate(); } PVRush::PVFormat::PVFormat(QDomElement const& root_node) : PVFormat() { populate_from_xml(root_node); } PVRush::PVFormat PVRush::PVFormat::add_input_name_column() const { PVRush::PVFormat new_format; PVRush::PVXmlParamParser xml_parser(_full_path, true); new_format.populate_from_parser(xml_parser); new_format._has_multi_inputs = true; return new_format; } /** * ICU : http://userguide.icu-project.org/formatparse/datetime * boost : http://www.boost.org/doc/libs/1_55_0/doc/html/date_time/date_time_io.html */ pvcop::formatter_desc PVRush::PVFormat::get_datetime_formatter_desc(const std::string& tf) { static constexpr const char delimiter = '\''; std::string formatter; auto contains = [&](const std::string& str, const std::string& substr) { /** * As the delimiter are displayed by repeating it twice instead of escaping it, the * delimiter occurrences number in a well-formed string is necessarily even. Literal * blocks can also be trivially skipped. * * Testing if substr exists also consists in a simple strcmp with explicit boundary * checking. */ size_t str_pos = 0; const size_t str_size = str.size(); const size_t substr_size = substr.size(); /* The case of unclosed literal blocks is implictly included in the while test */ while (str_pos < str_size) { if (str[str_pos] == delimiter) { /* The literal block case. */ while ((str_pos < str_size) && (str[++str_pos] != delimiter)) { } ++str_pos; } else { size_t substr_pos = 0; if (str[str_pos] == substr[substr_pos]) { /* The substr case. */ while ((str_pos < str_size) && (substr_pos < substr_size) && (str[++str_pos] == substr[++substr_pos])) { } if (substr_pos == substr_size) { /* substr has been entirely tested, have found it. */ return true; } } ++str_pos; } } return false; }; auto contains_one_of = [&](const std::string& tf, const std::vector<std::string>& tokens) { return std::any_of(tokens.cbegin(), tokens.cend(), [&](const std::string& token) { return contains(tf, token); }); }; /** * The proper formatter is determined this way : * * 1. "datetime" (libc) : if no milliseconds and no timezone * 2. "datetime_us" (boost) : if milliseconds but * - no 2 digit year * - no 12h format, * - no timezone * - no milliseconds not preceded by a dot * 3. "datetime_ms" (ICU) : in any other cases */ // rfc_timezone = X, XX, x, xx, Z, ZZ, ZZZ bool rfc_timezone = (contains_one_of(tf, {"X"}) && not contains_one_of(tf, {"XXX"})) || (contains_one_of(tf, {"x"}) && not contains_one_of(tf, {"xxx"})) || (contains_one_of(tf, {"Z"}) && not contains_one_of(tf, {"ZZZZ"})); bool no_timezone = not contains_one_of(tf, {"x", "X", "z", "Z", "v", "V"}); bool no_extended_timezone = no_timezone || rfc_timezone; bool no_millisec_precision = not contains(tf, "S"); bool no_epoch = not contains(tf, "epoch"); bool no_12h_format = not contains(tf, "h") && no_epoch; bool no_two_digit_year = not(contains(tf, "yy") && not contains(tf, "yyyy")); if (no_millisec_precision && no_extended_timezone) { formatter = "datetime"; } else { bool dot_before_millisec = contains(tf, ".S"); if (dot_before_millisec && no_epoch && no_timezone && no_two_digit_year && no_12h_format) { formatter = "datetime_us"; } else { // No need to make any format conversion as our input format is already good (ICU) return {"datetime_ms", tf}; } } static std::vector<std::pair<std::string, std::string>> map = {// epoch {"epoch", "%s"}, // year {"yyyy", "%Y"}, {"yy", "%y"}, // day of week {"eeee", "%a"}, {"eee", "%a"}, {"e", "%a"}, {"EEEE", "%a"}, {"EEE", "%a"}, // month {"MMMM", "%b"}, {"MMM", "%b"}, {"MM", "%m"}, {"M", "%m"}, // day in month {"dd", "%d"}, {"d", "%d"}, // hour {"HH", "%H"}, {"H", "%H"}, {"hh", "%l"}, {"h", "%l"}, {"K", "%h"}, // minute {"mm", "%M"}, {"m", "%M"}, // seconde {"ss", "%S"}, {"s", "%S"}, // fractional second {"SSSSSS", "%f"}, {"SSSSS", "%f"}, {"SSSS", "%f"}, {"SSS", "%f"}, {"SS", "%f"}, {"S", "%f"}, // am/pm marker {"aaa", "%p"}, {"aa", "%p"}, {"a", "%p"}, // timezone {"Z", "%z"}, {"zzzz", "%Z"}, {"zzz", "%Z"}, {"zz", "%Z"}, {"z", "%Z"}, {"v", "%Z"}, {"VVV", "%Z"}, {"V", "%z"}}; std::string time_format = tf; // Handle litteral "%" that should be replaced by "%%" without interfering with the conversion PVCore::replace(time_format, "%", "☠"); // iterate on the map with respect to the order of insertion for (const auto& token : map) { const std::string& key = token.first; const std::string& value = token.second; int pos = -value.size(); while ((pos = time_format.find(key, pos + value.size())) != (int)std::string::npos) { // check that we are not in a '...' section bool verbatim = std::count(time_format.begin(), time_format.begin() + pos, delimiter) % 2 == 1; if (not verbatim) { // Don't try to replace an already replaced token bool already_replaced_token = (pos > 0 && time_format[pos - 1] == '%'); if (not already_replaced_token) { time_format.replace(pos, key.size(), value); } } } } PVCore::replace(time_format, "☠", "%%"); // replace '' by ' and remove verbatim std::string value = ""; std::string key = "'"; int pos = -value.size(); while ((pos = time_format.find(key, pos + value.size())) != (int)std::string::npos) { if (time_format[pos + 1] == '\'') { pos += 1; continue; } time_format.replace(pos, key.size(), value); } return {formatter, time_format}; } std::unordered_set<std::string> PVRush::PVFormat::get_time_formats() const { std::unordered_set<std::string> time_formats; for (const PVAxisFormat& axe : _axes) { if (axe.get_type() == "time") { time_formats.emplace(axe.get_type_format().toStdString()); } } return time_formats; } pvcop::formatter_desc_list PVRush::PVFormat::get_storage_format() const { pvcop::formatter_desc_list formatters; for (const PVAxisFormat& axe : _axes) { std::string axe_type = axe.get_type().toStdString(); if (SUPPORTED_TYPES.find(axe_type) == SUPPORTED_TYPES.end()) { throw PVRush::PVFormatUnknownType("Unknown axis type : " + axe_type); } if (axe_type == "time") { std::string time_format = axe.get_type_format().toStdString(); if (time_format.empty()) { throw PVFormatInvalidTime("No type format for axis '" + axe.get_name().toStdString() + "'"); } formatters.emplace_back(get_datetime_formatter_desc(time_format)); } else { std::string formatter = axe_type; std::string formatter_params = axe.get_type_format().toStdString(); formatters.emplace_back(pvcop::formatter_desc(formatter, formatter_params)); } } return formatters; } bool PVRush::PVFormat::populate() { if (!_full_path.isEmpty()) { return populate_from_xml(_full_path); } throw std::runtime_error("We can't populate format without file"); } void PVRush::PVFormat::set_format_name(QString const& name) { _format_name = name; } void PVRush::PVFormat::set_full_path(QString const& full_path) { _full_path = full_path; if (_format_name.isEmpty() && !_full_path.isEmpty()) { QFileInfo info(_full_path); QString basename = info.baseName(); _format_name = basename; } } QString const& PVRush::PVFormat::get_format_name() const { return _format_name; } QString const& PVRush::PVFormat::get_full_path() const { return _full_path; } bool PVRush::PVFormat::is_valid() const { return _axes.size() >= 2; } void PVRush::PVFormat::insert_axis(const PVAxisFormat& axis, PVCombCol /*pos*/, bool after /* = true */) { _axes.append(axis); _axes_comb.emplace_back(PVCol(_axes.size()-1)); // TODO : don't insert at the end (void) after; } void PVRush::PVFormat::delete_axis(PVCol col) { // Remove col from axes _axes.erase(std::remove_if(_axes.begin(), _axes.end(), [&](const PVAxisFormat& axis) { return axis.get_index() == col; })); for (PVAxisFormat& axis : _axes) { if (axis.get_index() > col) { axis.set_index(axis.get_index()-PVCol(1)); } } // Remove col from axes combination (and update col values) _axes_comb.erase(std::remove(_axes_comb.begin(), _axes_comb.end(), col)); for (PVCol& c : _axes_comb) { if (c > col) { c--; } } // Delete axis node from DOM QDomNodeList xml_axes = _dom.elementsByTagName(PVFORMAT_XML_TAG_AXIS_STR); QDomNode xml_axis = xml_axes.at(col); xml_axis.parentNode().removeChild(xml_axis); // Update axes combination from DOM QDomNode axes_combination = _dom.documentElement().firstChildElement(PVFORMAT_XML_TAG_AXES_COMBINATION_STR); axes_combination.parentNode().removeChild(axes_combination); QStringList comb = axes_combination.toElement().text().split(","); comb.removeAll(QString::number(col.value())); for (QString& str : comb) { PVCol c(str.toUInt()); if (c > col) { str = QString::number(c-1); } } QString new_axes_comb = comb.join(","); QDomElement ac = _dom.createElement(PVFORMAT_XML_TAG_AXES_COMBINATION_STR); QDomText new_axes_comb_text_node = _dom.createTextNode(new_axes_comb); ac.appendChild(new_axes_comb_text_node); _dom.documentElement().appendChild(ac); } char* fill_spaces(QString str, int max_spaces) { // Use for debug so we display the different elements char* retbuf; retbuf = (char*)malloc(max_spaces + 1); int until = max_spaces - str.length(); for (int i = 0; i < until; i++) { retbuf[i] = ' '; // retstr += " "; } retbuf[until] = '\0'; return retbuf; } void PVRush::PVFormat::debug() const { PVLOG_PLAIN("\n" "id | type | mapping | plotting | color |name \n"); PVLOG_PLAIN( "-------+----------------+------------------+------------------+---------+------...\n"); unsigned int i = 0; for (const auto& axis : _axes) { char* fill; fill = fill_spaces(QString::number(i + 1, 10), 7); PVLOG_PLAIN("%d%s", i, fill); free(fill); fill = fill_spaces(axis.get_type(), 15); PVLOG_PLAIN("| %s%s", qPrintable(axis.get_type()), fill); free(fill); fill = fill_spaces(axis.get_mapping(), 17); PVLOG_PLAIN("| %s%s", qPrintable(axis.get_mapping()), fill); free(fill); fill = fill_spaces(axis.get_plotting(), 17); PVLOG_PLAIN("| %s%s", qPrintable(axis.get_plotting()), fill); free(fill); fill = fill_spaces(axis.get_color_str(), 8); PVLOG_PLAIN("| %s%s", qPrintable(axis.get_color_str()), fill); free(fill); PVLOG_PLAIN("| %s\n", qPrintable(axis.get_name())); i++; } // Dump filters if (filters_params.size() == 0) { PVLOG_PLAIN("No filters\n"); } else { PVLOG_PLAIN("Filters:\n"); PVLOG_PLAIN("--------\n"); PVXmlParamParser::list_params::const_iterator it_filters; for (it_filters = filters_params.begin(); it_filters != filters_params.end(); it_filters++) { PVXmlParamParserData const& fdata = *it_filters; PVLOG_PLAIN("%d -> %s. Arguments:\n", fdata.axis_id, qPrintable(fdata.filter_lib->registered_name())); PVCore::PVArgumentList const& args = fdata.filter_args; PVCore::PVArgumentList::const_iterator it_a; for (it_a = args.begin(); it_a != args.end(); it_a++) { PVLOG_PLAIN("'%s' = '%s'\n", qPrintable(it_a->key()), qPrintable(PVCore::PVArgument_to_QString(it_a->value()))); } } } } bool PVRush::PVFormat::populate_from_xml(QDomElement const& rootNode) { // Keep a copy of the DOM document even if the format is stored on disk. // This will allow to serialize it with eventual columns deletion. _dom = rootNode.ownerDocument(); PVRush::PVXmlParamParser xml_parser(rootNode); return populate_from_parser(xml_parser); } bool PVRush::PVFormat::populate_from_xml(QString filename) { QFile file(filename); file.open(QIODevice::ReadOnly | QIODevice::Text); _dom.setContent(&file); PVRush::PVXmlParamParser xml_parser(filename); return populate_from_parser(xml_parser); } bool PVRush::PVFormat::populate_from_parser(PVXmlParamParser& xml_parser) { filters_params = xml_parser.getFields(); if (xml_parser.getAxes().size() == 0) { throw PVFormatInvalid("The format does not have any axis"); } _axes = xml_parser.getAxes(); _axes_comb = xml_parser.getAxesCombination(); _fields_mask = xml_parser.getFieldsMask(); _first_line = xml_parser.get_first_line(); _line_count = xml_parser.get_line_count(); _python_script = xml_parser.get_python_script(_python_script_is_path, _python_script_disabled); return true; } PVFilter::PVFieldsBaseFilter_p PVRush::PVFormat::xmldata_to_filter(PVRush::PVXmlParamParserData const& fdata) const { PVFilter::PVFieldsFilterReg_p filter_lib = fdata.filter_lib; assert(filter_lib); PVFilter::PVFieldsBaseFilter_p filter_clone = filter_lib->clone<PVFilter::PVFieldsBaseFilter>(); // Check if this is a "one_to_many" filter, and, in such case, set the number of // expected fields. PVFilter::PVFieldsFilter<PVFilter::one_to_many>* sp_p = dynamic_cast<PVFilter::PVFieldsFilter<PVFilter::one_to_many>*>(filter_clone.get()); if (sp_p) { sp_p->set_number_expected_fields(fdata.nchildren); } else if (dynamic_cast<PVFilter::PVFieldFilterGrep*>(filter_clone.get())) { _have_grep_filter = true; } filter_clone->set_args(fdata.filter_args); return filter_clone; } PVFilter::PVChunkFilterByElt PVRush::PVFormat::create_tbb_filters() const { return PVFilter::PVChunkFilterByElt{create_tbb_filters_elt()}; } PVFilter::PVChunkFilterByEltCancellable PVRush::PVFormat::create_tbb_filters_autodetect(float timeout, bool* cancellation) { return PVFilter::PVChunkFilterByEltCancellable{create_tbb_filters_elt(), timeout, cancellation}; } std::unique_ptr<PVFilter::PVElementFilter> PVRush::PVFormat::create_tbb_filters_elt() const { PVLOG_INFO("Create filters for format %s\n", qPrintable(_format_name)); std::unique_ptr<PVFilter::PVElementFilterByAxes> filter_by_axes( new PVFilter::PVElementFilterByAxes(_fields_mask)); // Here we create the pipeline according to the format for (PVRush::PVXmlParamParserData const& fdata : filters_params) { PVFilter::PVFieldsBaseFilter_p field_f = xmldata_to_filter(fdata); // Create the mapping (field_id)->field_filter PVFilter::PVFieldsBaseFilter_p mapping( new PVFilter::PVFieldsMappingFilter(fdata.axis_id, field_f)); filter_by_axes->add_filter(std::unique_ptr<PVFilter::PVFieldsBaseFilter>( new PVFilter::PVFieldsMappingFilter(fdata.axis_id, field_f))); } // Finalise the pipeline return std::unique_ptr<PVFilter::PVElementFilter>(filter_by_axes.release()); } QHash<QString, PVRush::PVFormat> PVRush::PVFormat::list_formats_in_dir(QString const& format_name_prefix, QString const& dir) { QHash<QString, PVRush::PVFormat> ret; QStringList normalize_helpers_dir_list = PVRush::normalize_get_helpers_plugins_dirs(dir); for (int counter = 0; counter < normalize_helpers_dir_list.count(); counter++) { QString normalize_helpers_dir_str(normalize_helpers_dir_list[counter]); PVLOG_INFO("Search for formats in %s\n", qPrintable(normalize_helpers_dir_str)); QDir normalize_helpers_dir(normalize_helpers_dir_str); normalize_helpers_dir.setNameFilters(QStringList() << "*.format" << "*.pcre"); QStringList files = normalize_helpers_dir.entryList(); QStringListIterator filesIterator(files); while (filesIterator.hasNext()) { QString current_file = filesIterator.next(); QFileInfo fileInfo(current_file); QString filename = fileInfo.completeBaseName(); QString plugin_name = format_name_prefix + QString(":") + filename; PVLOG_INFO("Adding format '%s'\n", qPrintable(plugin_name)); try { ret.insert( plugin_name, PVFormat(plugin_name, normalize_helpers_dir.absoluteFilePath(current_file))); } catch (PVRush::PVFormatInvalid const&) { PVLOG_INFO(("Format :" + normalize_helpers_dir.absoluteFilePath(current_file).toStdString() + " is invalid and can't be use") .c_str()); // If the format is invalid skip it continue; } } } return ret; } void PVRush::PVFormat::set_python_script(const QString& python_script, bool as_path, bool disabled) { _python_script = python_script; _python_script_is_path = as_path; _python_script_disabled = disabled; } QString PVRush::PVFormat::get_python_script(bool& as_path, bool& disabled) const { as_path = _python_script_is_path; disabled = _python_script_disabled; return _python_script; } PVRush::PVFormat PVRush::PVFormat::serialize_read(PVCore::PVSerializeObject& so) { so.set_current_status("Loading format..."); QString format_name = so.attribute_read<QString>("name"); QString fname = so.attribute_read<QString>("filename"); QString full_path = so.file_read(fname); QString pattern = PVRush::PVNrawCacheManager::nraw_dir() + "/investigation_tmp_XXXXXX"; QString tmp_dir = mkdtemp(pattern.toLatin1().data()); QString new_full_path = tmp_dir + "/" + fname; std::rename(full_path.toStdString().c_str(), new_full_path.toStdString().c_str()); return {format_name, new_full_path}; } void PVRush::PVFormat::serialize_write(PVCore::PVSerializeObject& so) const { const QString& format_name = "format"; so.set_current_status("Saving format..."); so.attribute_write("name", format_name); QString str; QTextStream stream(&str, QIODevice::WriteOnly); stream << _dom.toString(); so.buffer_write("format", str.toLatin1(), str.size()); so.attribute_write("filename", format_name); }
35.367069
124
0.589715
inendi-inspector
a9144340c55da1ee5ac719b5bd19229b7e7e4de9
400
hpp
C++
Paramedic.hpp
reutKeyshawn/Ex4_cpp
776e40a9456c56beffe1253366a1448794aaeea5
[ "MIT" ]
null
null
null
Paramedic.hpp
reutKeyshawn/Ex4_cpp
776e40a9456c56beffe1253366a1448794aaeea5
[ "MIT" ]
null
null
null
Paramedic.hpp
reutKeyshawn/Ex4_cpp
776e40a9456c56beffe1253366a1448794aaeea5
[ "MIT" ]
null
null
null
#ifndef PARAMEDIC_H_ #define PARAMEDIC_H_ #pragma once #include <vector> #include "Soldier.hpp" class Paramedic : public Soldier { public: Paramedic(uint player_id, uint health_points = 100, uint damage = 0) : Soldier{player_id, health_points, damage} {} Paramedic(); void attack(std::vector<std::vector<Soldier *>> &b, std::pair<int, int> location); // ~Paramedic(); }; #endif
20
119
0.6925
reutKeyshawn
a914f78ded8efc652df69f547236d0656af8299d
2,904
cpp
C++
tests/common/test_utils.cpp
EDCBlockchain/blockchain
41c74b981658d79d770b075191cfb14faeb84dab
[ "MIT" ]
12
2019-10-31T13:24:21.000Z
2021-12-29T22:02:22.000Z
tests/common/test_utils.cpp
DONOVA28/blockchain
41c74b981658d79d770b075191cfb14faeb84dab
[ "MIT" ]
null
null
null
tests/common/test_utils.cpp
DONOVA28/blockchain
41c74b981658d79d770b075191cfb14faeb84dab
[ "MIT" ]
11
2019-07-24T12:46:29.000Z
2021-11-27T04:41:48.000Z
#include "test_utils.hpp" using namespace graphene; using namespace graphene::chain; std::map<string, account_object> accounts_map; void create_test_account(account_test_in& new_account, database_fixture &db) { account_object parent = db.get_account_by_name(new_account.parent); db.create_account(new_account.name, parent, parent, 80, db.generate_private_key(new_account.name).get_public_key()); db.upgrade_to_lifetime_member(db.get_account_by_name(new_account.name)); accounts_map.insert(std::pair<string, account_object>(new_account.name, db.get_account_by_name(new_account.name))); accounts_map.insert(std::pair<string, account_object>(new_account.parent, db.get_account_by_name(new_account.parent))); new_account.exp_data.account_id = accounts_map[new_account.name].id; if(new_account.exp_data.balance) { int64_t mand_sum = new_account.mand_transfer ? asset::scaled_precision(asset_id_type()(db.db).precision).value : 0; db.transfer(db.committee_account, accounts_map[new_account.name].id, asset(new_account.exp_data.balance + mand_sum, asset_id_type())); if (new_account.mand_transfer) db.transfer(accounts_map[new_account.name].id, db.committee_account, asset(mand_sum, asset_id_type())); } } void append_children(account_children_in& new_account, database_fixture &db) { if (accounts_map.count(new_account.parent) == 0) return; std::string parent = new_account.parent; for (int i = 1; i < new_account.level; ++i) { for(auto it = accounts_map.begin(); it != accounts_map.end(); it++) { if(it->second.referrer == accounts_map[parent].id) { parent = it->second.name; break; } } std::string tmp_parent = parent; for (int q = 0; q < i; q++) { tmp_parent = accounts_map[tmp_parent].referrer(db.db).name; } if (tmp_parent != new_account.parent) return; } std::string acc_prefix = new_account.name_prefix.append(std::to_string(new_account.level)).append("n"); for(int i = 0; i < new_account.count; i++) { std::string acc_name(acc_prefix); acc_name.append(std::to_string(i)); db.create_account(acc_name, db.get_account_by_name(parent), db.get_account_by_name(parent), 80, db.generate_private_key(acc_name).get_public_key()); accounts_map.insert(std::pair<string, account_object>(acc_name, db.get_account_by_name(acc_name))); if(new_account.balance > 0) { int64_t mand_sum = new_account.mand_transfer ? asset::scaled_precision(asset_id_type()(db.db).precision).value : 0; db.transfer(db.committee_account, accounts_map[acc_name].id, asset(new_account.balance + mand_sum, asset_id_type())); if (new_account.mand_transfer) db.transfer(accounts_map[acc_name].id, db.committee_account, asset(mand_sum, asset_id_type())); } } }
44.676923
154
0.708678
EDCBlockchain
a919a17eb9dea0b910e13ce4c651632b78045bd3
355
hpp
C++
Libraries/Networking/SimpleSocket.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
3
2022-02-11T10:34:33.000Z
2022-02-24T17:44:17.000Z
Libraries/Networking/SimpleSocket.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
Libraries/Networking/SimpleSocket.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #pragma once namespace Zero { class TcpSocket; class SimpleSocket : public Component { public: ZilchDeclareType(SimpleSocket, TypeCopyMode::ReferenceType); /// Constructor. SimpleSocket(); /// Returns the socket. TcpSocket* GetSocket(); private: /// Socket. TcpSocket mSocket; }; } // namespace Zero
13.653846
62
0.704225
RyanTylerRae
a92065d6fb3ad6ff3bf499a044dfe5fe25749b7d
7,689
cpp
C++
scene/2d/collision_shape_2d.cpp
literaldumb/godot
a2903fc51d1d20eba4dc451bdacbe477d6670163
[ "CC-BY-3.0", "MIT" ]
null
null
null
scene/2d/collision_shape_2d.cpp
literaldumb/godot
a2903fc51d1d20eba4dc451bdacbe477d6670163
[ "CC-BY-3.0", "MIT" ]
null
null
null
scene/2d/collision_shape_2d.cpp
literaldumb/godot
a2903fc51d1d20eba4dc451bdacbe477d6670163
[ "CC-BY-3.0", "MIT" ]
1
2019-01-13T00:44:17.000Z
2019-01-13T00:44:17.000Z
/*************************************************************************/ /* collision_shape_2d.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "collision_shape_2d.h" #include "collision_object_2d.h" #include "scene/resources/segment_shape_2d.h" #include "scene/resources/shape_line_2d.h" #include "scene/resources/circle_shape_2d.h" #include "scene/resources/rectangle_shape_2d.h" #include "scene/resources/capsule_shape_2d.h" #include "scene/resources/convex_polygon_shape_2d.h" #include "scene/resources/concave_polygon_shape_2d.h" void CollisionShape2D::_add_to_collision_object(Object *p_obj) { if (unparenting) return; CollisionObject2D *co = p_obj->cast_to<CollisionObject2D>(); ERR_FAIL_COND(!co); update_shape_index=co->get_shape_count(); co->add_shape(shape,get_transform()); if (trigger) co->set_shape_as_trigger(co->get_shape_count()-1,true); } void CollisionShape2D::_shape_changed() { update(); _update_parent(); } void CollisionShape2D::_update_parent() { Node *parent = get_parent(); if (!parent) return; CollisionObject2D *co = parent->cast_to<CollisionObject2D>(); if (!co) return; co->_update_shapes_from_children(); } void CollisionShape2D::_notification(int p_what) { switch(p_what) { case NOTIFICATION_ENTER_TREE: { unparenting=false; can_update_body=get_tree()->is_editor_hint(); if (!get_tree()->is_editor_hint()) { //display above all else set_z_as_relative(false); set_z(VS::CANVAS_ITEM_Z_MAX-1); } } break; case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: { if (!is_inside_tree()) break; if (can_update_body) { _update_parent(); } else if (update_shape_index>=0){ CollisionObject2D *co = get_parent()->cast_to<CollisionObject2D>(); if (co) { co->set_shape_transform(update_shape_index,get_transform()); } } } break; case NOTIFICATION_EXIT_TREE: { can_update_body=false; } break; /* case NOTIFICATION_TRANSFORM_CHANGED: { if (!is_inside_scene()) break; _update_parent(); } break;*/ case NOTIFICATION_DRAW: { if (!get_tree()->is_editor_hint() && !get_tree()->is_debugging_collisions_hint()) { break; } if (!shape.is_valid()) { break; } rect=Rect2(); Color draw_col=get_tree()->get_debug_collisions_color(); shape->draw(get_canvas_item(),draw_col); rect=shape->get_rect(); rect=rect.grow(3); } break; case NOTIFICATION_UNPARENTED: { unparenting = true; _update_parent(); } break; } } void CollisionShape2D::set_shape(const Ref<Shape2D>& p_shape) { if (shape.is_valid()) shape->disconnect("changed",this,"_shape_changed"); shape=p_shape; update(); if (is_inside_tree() && can_update_body) _update_parent(); if (is_inside_tree() && !can_update_body && update_shape_index>=0) { CollisionObject2D *co = get_parent()->cast_to<CollisionObject2D>(); if (co) { co->set_shape(update_shape_index,p_shape); } } if (shape.is_valid()) shape->connect("changed",this,"_shape_changed"); } Ref<Shape2D> CollisionShape2D::get_shape() const { return shape; } Rect2 CollisionShape2D::get_item_rect() const { return rect; } void CollisionShape2D::set_trigger(bool p_trigger) { trigger=p_trigger; if (can_update_body) { _update_parent(); } else if (is_inside_tree() && update_shape_index>=0){ CollisionObject2D *co = get_parent()->cast_to<CollisionObject2D>(); if (co) { co->set_shape_as_trigger(update_shape_index,p_trigger); } } } bool CollisionShape2D::is_trigger() const{ return trigger; } void CollisionShape2D::_set_update_shape_index(int p_index) { update_shape_index=p_index; } int CollisionShape2D::_get_update_shape_index() const{ return update_shape_index; } String CollisionShape2D::get_configuration_warning() const { if (!get_parent()->cast_to<CollisionObject2D>()) { return TTR("CollisionShape2D only serves to provide a collision shape to a CollisionObject2D derived node. Please only use it as a child of Area2D, StaticBody2D, RigidBody2D, KinematicBody2D, etc. to give them a shape."); } if (!shape.is_valid()) { return TTR("A shape must be provided for CollisionShape2D to function. Please create a shape resource for it!"); } return String(); } void CollisionShape2D::_bind_methods() { ClassDB::bind_method(_MD("set_shape","shape"),&CollisionShape2D::set_shape); ClassDB::bind_method(_MD("get_shape"),&CollisionShape2D::get_shape); ClassDB::bind_method(_MD("_shape_changed"),&CollisionShape2D::_shape_changed); ClassDB::bind_method(_MD("_add_to_collision_object"),&CollisionShape2D::_add_to_collision_object); ClassDB::bind_method(_MD("set_trigger","enable"),&CollisionShape2D::set_trigger); ClassDB::bind_method(_MD("is_trigger"),&CollisionShape2D::is_trigger); ClassDB::bind_method(_MD("_set_update_shape_index","index"),&CollisionShape2D::_set_update_shape_index); ClassDB::bind_method(_MD("_get_update_shape_index"),&CollisionShape2D::_get_update_shape_index); ClassDB::bind_method(_MD("get_collision_object_shape_index"),&CollisionShape2D::get_collision_object_shape_index); ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT,"shape",PROPERTY_HINT_RESOURCE_TYPE,"Shape2D"),_SCS("set_shape"),_SCS("get_shape")); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"trigger"),_SCS("set_trigger"),_SCS("is_trigger")); ADD_PROPERTY( PropertyInfo( Variant::INT, "_update_shape_index", PROPERTY_HINT_NONE, "",PROPERTY_USAGE_NOEDITOR), _SCS("_set_update_shape_index"), _SCS("_get_update_shape_index")); } CollisionShape2D::CollisionShape2D() { rect=Rect2(-Point2(10,10),Point2(20,20)); set_notify_local_transform(true); trigger=false; unparenting = false; can_update_body = false; update_shape_index=-1; }
31.129555
223
0.658343
literaldumb
a93a1419994149a8225cdebe31997407be8489c3
8,217
cpp
C++
src/mandelbrot/mandelbrot_avx/mandelbrot_avx.cpp
mrange/benchmarksgame
f091eeea3616cee50d3c8e74c5eabb85a146c3d0
[ "Apache-2.0" ]
null
null
null
src/mandelbrot/mandelbrot_avx/mandelbrot_avx.cpp
mrange/benchmarksgame
f091eeea3616cee50d3c8e74c5eabb85a146c3d0
[ "Apache-2.0" ]
null
null
null
src/mandelbrot/mandelbrot_avx/mandelbrot_avx.cpp
mrange/benchmarksgame
f091eeea3616cee50d3c8e74c5eabb85a146c3d0
[ "Apache-2.0" ]
2
2017-09-14T07:12:32.000Z
2019-12-24T18:17:36.000Z
// ---------------------------------------------------------------------------------------------- // Copyright 2017 Mårten Rånge // // 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. // ---------------------------------------------------------------------------------------------- // g++ -g --std=c++14 -pipe -Wall -O3 -ffast-math -fno-finite-math-only -march=native -mavx -fopenmp mandelbrot_avx.cpp #include "stdafx.h" #include <cassert> #include <cstddef> #include <cstdio> #include <chrono> #include <memory> #include <tuple> #include <emmintrin.h> #include <immintrin.h> #ifdef _MSVC_LANG # define MANDEL_INLINE __forceinline #else # define MANDEL_INLINE inline #endif namespace { constexpr auto min_x = -1.5F ; constexpr auto min_y = -1.0F ; constexpr auto max_x = 0.5F ; constexpr auto max_y = 1.0F ; template<typename T> auto time_it (T a) { auto before = std::chrono::high_resolution_clock::now (); auto result = a (); auto after = std::chrono::high_resolution_clock::now (); auto diff = std::chrono::duration_cast<std::chrono::milliseconds> (after - before).count (); return std::make_tuple (diff, std::move (result)); } struct bitmap { using uptr = std::unique_ptr<bitmap>; std::size_t const x ; std::size_t const y ; std::size_t const w ; std::size_t const sz; bitmap (std::size_t x, std::size_t y) noexcept : x (x) , y (y) , w ((x + 7) / 8) , sz (w*y) { b = static_cast<std::uint8_t*> (malloc (sz)); } ~bitmap () noexcept { free (b); b = nullptr; } bitmap (bitmap && bm) noexcept : x (bm.x) , y (bm.y) , w (bm.w) , b (bm.b) , sz (bm.sz) { bm.b = nullptr; } bitmap (bitmap const &) = delete; bitmap& operator= (bitmap const &) = delete; bitmap& operator= (bitmap &&) = delete; std::uint8_t * bits () noexcept { assert (b); return b; } std::uint8_t const * bits () const noexcept { assert (b); return b; } private: std::uint8_t * b; }; bitmap::uptr create_bitmap (std::size_t x, std::size_t y) { return std::make_unique<bitmap> (x, y); } #define MANDEL_INDEPENDENT(i) \ xy[i] = _mm256_mul_ps (x[i], y[i]); \ x2[i] = _mm256_mul_ps (x[i], x[i]); \ y2[i] = _mm256_mul_ps (y[i], y[i]); #define MANDEL_DEPENDENT(i) \ y[i] = _mm256_add_ps (_mm256_add_ps (xy[i], xy[i]) , cy[i]); \ x[i] = _mm256_add_ps (_mm256_sub_ps (x2[i], y2[i]) , cx[i]); #define MANDEL_ITERATION() \ MANDEL_INDEPENDENT(0) \ MANDEL_DEPENDENT(0) \ MANDEL_INDEPENDENT(1) \ MANDEL_DEPENDENT(1) \ MANDEL_INDEPENDENT(2) \ MANDEL_DEPENDENT(2) \ MANDEL_INDEPENDENT(3) \ MANDEL_DEPENDENT(3) #define MANDEL_CMP(i) \ _mm256_cmp_ps (_mm256_add_ps (x2[i], y2[i]), _mm256_set1_ps (4.0F), _CMP_LE_OQ) #define MANDEL_CMPMASK() \ std::uint32_t cmp_mask = \ (_mm256_movemask_ps (MANDEL_CMP(0)) ) \ | (_mm256_movemask_ps (MANDEL_CMP(1)) << 8 ) \ | (_mm256_movemask_ps (MANDEL_CMP(2)) << 16) \ | (_mm256_movemask_ps (MANDEL_CMP(3)) << 24) #define MANDEL_CHECKINF() \ auto cont = _mm256_movemask_ps (_mm256_or_ps ( \ _mm256_or_ps (MANDEL_CMP(0), MANDEL_CMP(1)) \ , _mm256_or_ps (MANDEL_CMP(2), MANDEL_CMP(3)) \ )); \ if (!cont) \ { \ return 0; \ } MANDEL_INLINE int mandelbrot_avx (__m256 cx[4], __m256 cy[4]) { __m256 x[4] {cx[0], cx[1], cx[2], cx[3]}; __m256 y[4] {cy[0], cy[1], cy[2], cy[3]}; __m256 x2[4]; __m256 y2[4]; __m256 xy[4]; // 6 * 8 + 2 => 50 iterations for (auto iter = 6; iter > 0; --iter) { // 8 inner steps MANDEL_ITERATION(); MANDEL_ITERATION(); MANDEL_ITERATION(); MANDEL_ITERATION(); MANDEL_ITERATION(); MANDEL_ITERATION(); MANDEL_ITERATION(); MANDEL_ITERATION(); MANDEL_CHECKINF(); } // Last 2 steps MANDEL_ITERATION(); MANDEL_ITERATION(); MANDEL_CMPMASK(); return cmp_mask; } MANDEL_INLINE int mandelbrot_avx_full (__m256 cx[4], __m256 cy[4]) { __m256 x[4] {cx[0], cx[1], cx[2], cx[3]}; __m256 y[4] {cy[0], cy[1], cy[2], cy[3]}; __m256 x2[4]; __m256 y2[4]; __m256 xy[4]; // 6 * 8 + 2 => 50 iterations for (auto iter = 6; iter > 0; --iter) { // 8 inner steps MANDEL_ITERATION(); MANDEL_ITERATION(); MANDEL_ITERATION(); MANDEL_ITERATION(); MANDEL_ITERATION(); MANDEL_ITERATION(); MANDEL_ITERATION(); MANDEL_ITERATION(); } // Last 2 steps MANDEL_ITERATION(); MANDEL_ITERATION(); MANDEL_CMPMASK(); return cmp_mask; } bitmap::uptr compute_set (std::size_t const dim) { auto set = create_bitmap (dim, dim); auto width = set->w; auto pset = set->bits (); auto sdim = static_cast<int> (dim); auto scale_x = (max_x - min_x) / dim; auto scale_y = (max_y - min_y) / dim; auto min_x_8 = _mm256_set1_ps (min_x); auto scale_x_8= _mm256_set1_ps (scale_x); auto shift_x_8= _mm256_set_ps (0, 1, 2, 3, 4, 5, 6, 7); #pragma omp parallel for schedule(guided) for (auto sy = 0; sy < sdim; sy += 4) { auto y = static_cast<std::size_t> (sy); auto cy0 = _mm256_set1_ps (scale_y*y + min_y); auto cy1 = _mm256_add_ps (cy0, _mm256_set1_ps (1*scale_y)); auto cy2 = _mm256_add_ps (cy0, _mm256_set1_ps (2*scale_y)); auto cy3 = _mm256_add_ps (cy0, _mm256_set1_ps (3*scale_y)); auto yoffset = width*y; auto last_reached_full = false; for (auto w = 0U; w < width; ++w) { auto x = w*8; auto x_8 = _mm256_set1_ps (x); auto cx0 = _mm256_add_ps (min_x_8, _mm256_mul_ps (_mm256_add_ps (x_8, shift_x_8), scale_x_8)); __m256 cx[] = { cx0, cx0, cx0, cx0 }; __m256 cy[] = { cy0, cy1, cy2, cy3 }; auto bits2 = last_reached_full ? mandelbrot_avx_full (cx, cy) : mandelbrot_avx (cx, cy) ; pset[yoffset + w] = 0xFF & bits2; pset[yoffset + 1*width + w] = 0xFF & (bits2 >> 8); pset[yoffset + 2*width + w] = 0xFF & (bits2 >> 16); pset[yoffset + 3*width + w] = 0xFF & (bits2 >> 24); last_reached_full = bits2 != 0; } } return set; } } int main (int argc, char const * argv[]) { auto dim = [argc, argv] () { auto dim = argc > 1 ? atoi (argv[1]) : 0; return dim > 0 ? dim : 200; } (); if (dim % 8 != 0) { std::printf ("Dimension must be modulo 8\n"); return 999; } std::printf ("Generating mandelbrot set %dx%d(50)\n", dim, dim); auto res = time_it ([dim] { return compute_set (dim); }); auto ms = std::get<0> (res); auto& set = std::get<1> (res); std::printf (" it took %lld ms\n", ms); auto file = std::fopen ("mandelbrot_avx.pbm", "wb"); std::fprintf (file, "P4\n%d %d\n", dim, dim); std::fwrite (set->bits (), 1, set->sz, file); std::fclose (file); return 0; }
26.852941
119
0.525618
mrange
a93a7c18302add97a87fb0535861d01dbc393c7b
187
cc
C++
test/check_file.cc
respu/libposix
27681383e5d3e19687d7fba23d97166beeeece13
[ "Unlicense" ]
2
2015-11-05T09:08:04.000Z
2016-02-09T23:26:00.000Z
test/check_file.cc
yggchan/libposix
27681383e5d3e19687d7fba23d97166beeeece13
[ "Unlicense" ]
null
null
null
test/check_file.cc
yggchan/libposix
27681383e5d3e19687d7fba23d97166beeeece13
[ "Unlicense" ]
null
null
null
/* This is free and unencumbered software released into the public domain. */ #include "catch.hpp" #include <posix++/file.h> /* for posix::file */ TEST_CASE("test_file") { // TODO }
18.7
77
0.673797
respu
a93e7e38d09c4d0825d4f25aa5df75f13d4dca5f
30,567
cpp
C++
applications/mne_browse/Windows/mainwindow.cpp
liminsun/mne-cpp
c5de865281164cf1867450c9705b21c9ac1b5cd7
[ "BSD-3-Clause" ]
null
null
null
applications/mne_browse/Windows/mainwindow.cpp
liminsun/mne-cpp
c5de865281164cf1867450c9705b21c9ac1b5cd7
[ "BSD-3-Clause" ]
null
null
null
applications/mne_browse/Windows/mainwindow.cpp
liminsun/mne-cpp
c5de865281164cf1867450c9705b21c9ac1b5cd7
[ "BSD-3-Clause" ]
null
null
null
//============================================================================================================= /** * @file mainwindow.cpp * @author Florian Schlembach <florian.schlembach@tu-ilmenau.de>; * Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu>; * Jens Haueisen <jens.haueisen@tu-ilmenau.de> * @version 1.0 * @date January, 2014 * * @section LICENSE * * Copyright (C) 2014, Florian Schlembach, Christoph Dinh, Matti Hamalainen and Jens Haueisen. 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 MNE-CPP authors 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. * * * @brief mne_browse is the QT equivalent of the already existing C-version of mne_browse_raw. It is pursued * to reimplement the full feature set of mne_browse_raw and even extend these. */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "mainwindow.h" //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace MNEBROWSE; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) //, m_qFileRaw("./MNE-sample-data/MEG/sample/sample_audvis_raw.fif") //, m_qEventFile("./MNE-sample-data/MEG/sample/sample_audvis_raw-eve.fif") //, m_qEvokedFile("./MNE-sample-data/MEG/sample/sample_audvis-ave.fif") , m_qSettings() , m_rawSettings() , ui(new Ui::MainWindowWidget) { ui->setupUi(this); //The following functions and their point of calling should NOT be changed //Setup the windows first - this NEEDS to be done here because important pointers (window pointers) which are needed for further processing are generated in this function setupWindowWidgets(); setupMainWindow(); // Setup rest of the GUI connectMenus(); setWindowStatus(); //Set standard LogLevel setLogLevel(_LogLvMax); } //************************************************************************************************************* MainWindow::~MainWindow() { } //************************************************************************************************************* void MainWindow::setupWindowWidgets() { //Create data window m_pDataWindow = new DataWindow(this); //Create dockble event window - QTDesigner used - see / FormFiles m_pEventWindow = new EventWindow(this); addDockWidget(Qt::LeftDockWidgetArea, m_pEventWindow); m_pEventWindow->hide(); //Create dockable information window - QTDesigner used - see / FormFiles m_pInformationWindow = new InformationWindow(this); addDockWidget(Qt::BottomDockWidgetArea, m_pInformationWindow); m_pInformationWindow->hide(); //Create about window - QTDesigner used - see / FormFiles m_pAboutWindow = new AboutWindow(this); m_pAboutWindow->hide(); //Create channel info window - QTDesigner used - see / FormFiles m_pChInfoWindow = new ChInfoWindow(this); addDockWidget(Qt::BottomDockWidgetArea, m_pChInfoWindow); m_pChInfoWindow->hide(); //Create selection manager window - QTDesigner used - see / FormFiles m_pSelectionManagerWindowDock = new QDockWidget(this); addDockWidget(Qt::BottomDockWidgetArea, m_pSelectionManagerWindowDock); m_pSelectionManagerWindow = new SelectionManagerWindow(m_pSelectionManagerWindowDock, m_pChInfoWindow->getDataModel(), Qt::Widget); m_pSelectionManagerWindowDock->setWidget(m_pSelectionManagerWindow); m_pSelectionManagerWindowDock->hide(); //Create average manager window - QTDesigner used - see / FormFiles m_pAverageWindow = new AverageWindow(this, m_qEvokedFile); addDockWidget(Qt::BottomDockWidgetArea, m_pAverageWindow); m_pAverageWindow->hide(); //Create scale window - QTDesigner used - see / FormFiles m_pScaleWindow = new ScaleWindow(this); addDockWidget(Qt::LeftDockWidgetArea, m_pScaleWindow); m_pScaleWindow->hide(); //Create filter window - QTDesigner used - see / FormFiles m_pFilterWindow = new FilterWindow(this, this); addDockWidget(Qt::BottomDockWidgetArea, m_pFilterWindow); m_pFilterWindow->hide(); //Create noise reduction window - QTDesigner used - see / FormFiles m_pNoiseReductionWindow = new NoiseReductionWindow(this); addDockWidget(Qt::LeftDockWidgetArea, m_pNoiseReductionWindow); m_pNoiseReductionWindow->hide(); //Init windows - TODO: get rid of this here, do this inside the window classes m_pDataWindow->init(); m_pEventWindow->init(); m_pScaleWindow->init(); //Create the toolbar after all indows have been initiliased createToolBar(); //Connect window signals //Change scaling of the data and averaged data whenever a spinbox value changed or the user performs a pinch gesture on the view connect(m_pScaleWindow, &ScaleWindow::scalingChannelValueChanged, m_pDataWindow, &DataWindow::scaleData); connect(m_pScaleWindow, &ScaleWindow::scalingViewValueChanged, m_pDataWindow, &DataWindow::changeRowHeight); connect(m_pDataWindow, &DataWindow::scaleChannels, m_pScaleWindow, &ScaleWindow::scaleAllChannels); connect(m_pScaleWindow, &ScaleWindow::scalingChannelValueChanged, m_pAverageWindow, &AverageWindow::scaleAveragedData); //Hide non selected channels in the data view connect(m_pSelectionManagerWindow, &SelectionManagerWindow::showSelectedChannelsOnly, m_pDataWindow, &DataWindow::showSelectedChannelsOnly); //Connect selection manager with average manager connect(m_pSelectionManagerWindow, &SelectionManagerWindow::selectionChanged, m_pAverageWindow, &AverageWindow::channelSelectionManagerChanged); //Connect channel info window with raw data model, layout manager, average manager and the data window connect(m_pDataWindow->getDataModel(), &RawModel::fileLoaded, m_pChInfoWindow->getDataModel().data(), &ChInfoModel::fiffInfoChanged); connect(m_pDataWindow->getDataModel(), &RawModel::assignedOperatorsChanged, m_pChInfoWindow->getDataModel().data(), &ChInfoModel::assignedOperatorsChanged); connect(m_pSelectionManagerWindow, &SelectionManagerWindow::loadedLayoutMap, m_pChInfoWindow->getDataModel().data(), &ChInfoModel::layoutChanged); connect(m_pChInfoWindow->getDataModel().data(), &ChInfoModel::channelsMappedToLayout, m_pSelectionManagerWindow, &SelectionManagerWindow::setCurrentlyMappedFiffChannels); connect(m_pChInfoWindow->getDataModel().data(), &ChInfoModel::channelsMappedToLayout, m_pAverageWindow, &AverageWindow::setMappedChannelNames); //Connect selection manager with a new file loaded signal connect(m_pDataWindow->getDataModel(), &RawModel::fileLoaded, m_pSelectionManagerWindow, &SelectionManagerWindow::newFiffFileLoaded); //Connect filter window with new file loaded signal connect(m_pDataWindow->getDataModel(), &RawModel::fileLoaded, m_pFilterWindow, &FilterWindow::newFileLoaded); //Connect noise reduction manager with fif file loading connect(m_pDataWindow->getDataModel(), &RawModel::fileLoaded, m_pNoiseReductionWindow, &NoiseReductionWindow::setFiffInfo); connect(m_pNoiseReductionWindow, &NoiseReductionWindow::projSelectionChanged, m_pDataWindow->getDataModel(), &RawModel::updateProjections); connect(m_pNoiseReductionWindow, &NoiseReductionWindow::compSelectionChanged, m_pDataWindow->getDataModel(), &RawModel::updateCompensator); //If a default file has been specified on startup -> call hideSpinBoxes and set laoded fiff channels - TODO: dirty move get rid of this here if(m_pDataWindow->getDataModel()->m_bFileloaded) { m_pScaleWindow->hideSpinBoxes(m_pDataWindow->getDataModel()->m_pFiffInfo); m_pChInfoWindow->getDataModel()->fiffInfoChanged(m_pDataWindow->getDataModel()->m_pFiffInfo); m_pChInfoWindow->getDataModel()->layoutChanged(m_pSelectionManagerWindow->getLayoutMap()); m_pSelectionManagerWindow->setCurrentlyMappedFiffChannels(m_pChInfoWindow->getDataModel()->getMappedChannelsList()); m_pSelectionManagerWindow->newFiffFileLoaded(m_pDataWindow->getDataModel()->m_pFiffInfo); m_pFilterWindow->newFileLoaded(m_pDataWindow->getDataModel()->m_pFiffInfo); m_pNoiseReductionWindow->setFiffInfo(m_pDataWindow->getDataModel()->m_pFiffInfo); } } //************************************************************************************************************* void MainWindow::createToolBar() { //Create toolbar QToolBar *toolBar = new QToolBar(this); toolBar->setOrientation(Qt::Vertical); toolBar->setMovable(true); //Add DC removal action m_pRemoveDCAction = new QAction(QIcon(":/Resources/Images/removeDC.png"),tr("Remove DC component"), this); m_pRemoveDCAction->setStatusTip(tr("Remove the DC component by subtracting the channel mean")); connect(m_pRemoveDCAction,&QAction::triggered, [=](){ if(m_pDataWindow->getDataDelegate()->m_bRemoveDC) { m_pRemoveDCAction->setIcon(QIcon(":/Resources/Images/removeDC.png")); m_pRemoveDCAction->setToolTip("Remove DC component"); m_pDataWindow->setStatusTip(tr("Remove the DC component by subtracting the channel mean")); m_pDataWindow->getDataDelegate()->m_bRemoveDC = false; } else { m_pRemoveDCAction->setIcon(QIcon(":/Resources/Images/addDC.png")); m_pRemoveDCAction->setToolTip("Add DC component"); m_pRemoveDCAction->setStatusTip(tr("Add the DC component")); m_pDataWindow->getDataDelegate()->m_bRemoveDC = true; } m_pDataWindow->updateDataTableViews(); }); toolBar->addAction(m_pRemoveDCAction); //Add show/hide bad channel button m_pHideBadAction = new QAction(QIcon(":/Resources/Images/hideBad.png"),tr("Hide all bad channels"), this); m_pHideBadAction->setStatusTip(tr("Hide all bad channels")); connect(m_pHideBadAction,&QAction::triggered, [=](){ if(m_pHideBadAction->toolTip() == "Show all bad channels") { m_pHideBadAction->setIcon(QIcon(":/Resources/Images/hideBad.png")); m_pHideBadAction->setToolTip("Hide all bad channels"); m_pDataWindow->setStatusTip(tr("Hide all bad channels")); m_pDataWindow->hideBadChannels(false); } else { m_pHideBadAction->setIcon(QIcon(":/Resources/Images/showBad.png")); m_pHideBadAction->setToolTip("Show all bad channels"); m_pHideBadAction->setStatusTip(tr("Show all bad channels")); m_pDataWindow->hideBadChannels(true); } }); toolBar->addAction(m_pHideBadAction); toolBar->addSeparator(); //Toggle visibility of the event manager QAction* showEventManager = new QAction(QIcon(":/Resources/Images/showEventManager.png"),tr("Toggle event manager"), this); showEventManager->setStatusTip(tr("Toggle the event manager")); connect(showEventManager, &QAction::triggered, this, [=](){ showWindow(m_pEventWindow); }); toolBar->addAction(showEventManager); //Toggle visibility of the filter window QAction* showFilterWindow = new QAction(QIcon(":/Resources/Images/showFilterWindow.png"),tr("Toggle filter window"), this); showFilterWindow->setStatusTip(tr("Toggle filter window")); connect(showFilterWindow, &QAction::triggered, this, [=](){ showWindow(m_pFilterWindow); }); toolBar->addAction(showFilterWindow); //Toggle visibility of the Selection manager QAction* showSelectionManager = new QAction(QIcon(":/Resources/Images/showSelectionManager.png"),tr("Toggle selection manager"), this); showSelectionManager->setStatusTip(tr("Toggle the selection manager")); connect(showSelectionManager, &QAction::triggered, this, [=](){ showWindow(m_pSelectionManagerWindowDock); }); toolBar->addAction(showSelectionManager); //Toggle visibility of the scaling window QAction* showScalingWindow = new QAction(QIcon(":/Resources/Images/showScalingWindow.png"),tr("Toggle scaling window"), this); showScalingWindow->setStatusTip(tr("Toggle the scaling window")); connect(showScalingWindow, &QAction::triggered, this, [=](){ showWindow(m_pScaleWindow); }); toolBar->addAction(showScalingWindow); //Toggle visibility of the average manager QAction* showAverageManager = new QAction(QIcon(":/Resources/Images/showAverageManager.png"),tr("Toggle average manager"), this); showAverageManager->setStatusTip(tr("Toggle the average manager")); connect(showAverageManager, &QAction::triggered, this, [=](){ showWindow(m_pAverageWindow); }); toolBar->addAction(showAverageManager); //Toggle visibility of the noise reduction manager QAction* showNoiseReductionManager = new QAction(QIcon(":/Resources/Images/showNoiseReductionWindow.png"),tr("Toggle noise reduction manager"), this); showNoiseReductionManager->setStatusTip(tr("Toggle the noise reduction manager")); connect(showNoiseReductionManager, &QAction::triggered, this, [=](){ showWindow(m_pNoiseReductionWindow); }); toolBar->addAction(showNoiseReductionManager); toolBar->addSeparator(); //Toggle visibility of the channel information window manager QAction* showChInfo = new QAction(QIcon(":/Resources/Images/showChInformationWindow.png"),tr("Channel info"), this); showChInfo->setStatusTip(tr("Toggle channel info window")); connect(showChInfo, &QAction::triggered, this, [=](){ showWindow(m_pChInfoWindow); }); toolBar->addAction(showChInfo); //Toggle visibility of the information window // QAction* showInformationWindow = new QAction(QIcon(":/Resources/Images/showInformationWindow.png"),tr("Toggle information window"), this); // showInformationWindow->setStatusTip(tr("Toggle the information window")); // connect(showInformationWindow, &QAction::triggered, this, [=](){ // showWindow(m_pInformationWindow); // }); // toolBar->addAction(showInformationWindow); this->addToolBar(Qt::RightToolBarArea,toolBar); } //************************************************************************************************************* void MainWindow::connectMenus() { //File connect(ui->m_openAction, &QAction::triggered, this, &MainWindow::openFile); connect(ui->m_writeAction, &QAction::triggered, this, &MainWindow::writeFile); connect(ui->m_loadEvents, &QAction::triggered, this, &MainWindow::loadEvents); connect(ui->m_saveEvents, &QAction::triggered, this, &MainWindow::saveEvents); connect(ui->m_loadEvokedAction, &QAction::triggered, this, &MainWindow::loadEvoked); connect(ui->m_quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); //Adjust connect(ui->m_filterAction, &QAction::triggered, this, [=](){ showWindow(m_pFilterWindow); }); //Windows connect(ui->m_eventAction, &QAction::triggered, this, [=](){ showWindow(m_pEventWindow); }); connect(ui->m_informationAction, &QAction::triggered, this, [=](){ showWindow(m_pInformationWindow); }); connect(ui->m_channelSelectionManagerAction, &QAction::triggered, this, [=](){ showWindow(m_pSelectionManagerWindowDock); }); connect(ui->m_averageWindowAction, &QAction::triggered, this, [=](){ showWindow(m_pAverageWindow); }); connect(ui->m_scalingAction, &QAction::triggered, this, [=](){ showWindow(m_pScaleWindow); }); connect(ui->m_ChInformationAction, &QAction::triggered, this, [=](){ showWindow(m_pChInfoWindow); }); connect(ui->m_noiseReductionManagerAction, &QAction::triggered, this, [=](){ showWindow(m_pNoiseReductionWindow); }); //Help connect(ui->m_aboutAction, &QAction::triggered, this, [=](){ showWindow(m_pAboutWindow); }); } //************************************************************************************************************* void MainWindow::setupMainWindow() { //set Window functions resize(m_qSettings.value("MainWindow/size", QSize(MAINWINDOW_WINDOW_SIZE_W, MAINWINDOW_WINDOW_SIZE_H)).toSize()); //Resize to predefined default size move(m_qSettings.value("MainWindow/position", QPoint(MAINWINDOW_WINDOW_POSITION_X, MAINWINDOW_WINDOW_POSITION_Y)).toPoint()); // Move this main window to position 50/50 on the screen //Set data window as central widget - This is needed because we are using QDockWidgets setCentralWidget(m_pDataWindow); } //************************************************************************************************************* void MainWindow::setWindowStatus() { //Set window title QString title; //title = QString("%1").arg(CInfo::AppNameShort()); title = QString("Visualize and Process"); setWindowTitle(title); //Set status bar //Set data file informations if(m_pDataWindow->getDataModel()->m_bFileloaded) { int idx = m_qFileRaw.fileName().lastIndexOf("/"); QString filename = m_qFileRaw.fileName().remove(0,idx+1); title = QString("Data file: %1 / First sample: %2 / Sample frequency: %3Hz").arg(filename).arg(m_pDataWindow->getDataModel()->firstSample()).arg(m_pDataWindow->getDataModel()->m_pFiffInfo->sfreq); } else title = QString("No data file"); //Set event file informations if(m_pEventWindow->getEventModel()->m_bFileloaded) { int idx = m_qEventFile.fileName().lastIndexOf("/"); QString filename = m_qEventFile.fileName().remove(0,idx+1); title.append(QString(" - Event file: %1").arg(filename)); } else title.append(" - No event file"); //Set evoked file informations if(m_pAverageWindow->getAverageModel()->m_bFileloaded) { int idx = m_qEvokedFile.fileName().lastIndexOf("/"); QString filename = m_qEvokedFile.fileName().remove(0,idx+1); title.append(QString(" - Evoked file: %1").arg(filename)); } else title.append(" - No evoked file"); //Add permanent widget to status bar after deleting old one QObjectList cildrenList = statusBar()->children(); for(int i = 0; i< cildrenList.size(); i++) statusBar()->removeWidget((QWidget*)cildrenList.at(i)); QLabel* label = new QLabel(title); statusBar()->addWidget(label); } //************************************************************************************************************* //Log void MainWindow::writeToLog(const QString& logMsg, LogKind lgknd, LogLevel lglvl) { m_pInformationWindow->writeToLog(logMsg, lgknd, lglvl); } //************************************************************************************************************* void MainWindow::setLogLevel(LogLevel lvl) { m_pInformationWindow->setLogLevel(lvl); } //************************************************************************************************************* // SLOTS void MainWindow::openFile() { QString filename = QFileDialog::getOpenFileName(this, QString("Open fiff data file"), QString("./MNE-sample-data/MEG/sample/"), tr("fif data files (*.fif)")); if(filename.isEmpty()) { qDebug("User aborted opening of fiff data file"); return; } if(m_qFileRaw.isOpen()) m_qFileRaw.close(); m_qFileRaw.setFileName(filename); //Clear event model m_pEventWindow->getEventModel()->clearModel(); // This thread based opening code does not properly work because the .exec blocks all other windows and their threads. // However, the function loadFiffData communicates with these windows and their threads. Therefore chrashes occur. // QFutureWatcher<bool> writeFileFutureWatcher; // QProgressDialog progressDialog("Loading fif file...", QString(), 0, 0, this, Qt::Dialog); // //Connect future watcher and dialog // connect(&writeFileFutureWatcher, &QFutureWatcher<bool>::finished, // &progressDialog, &QProgressDialog::reset); // connect(&progressDialog, &QProgressDialog::canceled, // &writeFileFutureWatcher, &QFutureWatcher<bool>::cancel); // connect(&writeFileFutureWatcher, &QFutureWatcher<bool>::progressRangeChanged, // &progressDialog, &QProgressDialog::setRange); // connect(&writeFileFutureWatcher, &QFutureWatcher<bool>::progressValueChanged, // &progressDialog, &QProgressDialog::setValue); // //Run the file writing in seperate thread // writeFileFutureWatcher.setFuture(QtConcurrent::run(m_pDataWindow->getDataModel(), // &RawModel::loadFiffData, // &m_qFileRaw)); // progressDialog.exec(); // writeFileFutureWatcher.waitForFinished(); // if(!writeFileFutureWatcher.future().result()) // qDebug() << "Fiff data file" << filename << "loaded."; // else // qDebug("ERROR loading fiff data file %s",filename.toLatin1().data()); if(m_pDataWindow->getDataModel()->loadFiffData(&m_qFileRaw)) qDebug() << "Fiff data file" << filename << "loaded."; else qDebug("ERROR loading fiff data file %s",filename.toLatin1().data()); //set position of QScrollArea m_pDataWindow->getDataTableView()->horizontalScrollBar()->setValue(0); m_pDataWindow->initMVCSettings(); //Set fiffInfo in event model m_pEventWindow->getEventModel()->setFiffInfo(m_pDataWindow->getDataModel()->m_pFiffInfo); m_pEventWindow->getEventModel()->setFirstLastSample(m_pDataWindow->getDataModel()->firstSample(), m_pDataWindow->getDataModel()->lastSample()); //resize columns to contents - needs to be done because the new data file can be shorter than the old one m_pDataWindow->updateDataTableViews(); m_pDataWindow->getDataTableView()->resizeColumnsToContents(); //Update status bar setWindowStatus(); //Hide not presented channel types and their spin boxes in the scale window m_pScaleWindow->hideSpinBoxes(m_pDataWindow->getDataModel()->m_pFiffInfo); m_qFileRaw.close(); } //************************************************************************************************************* void MainWindow::writeFile() { QString filename = QFileDialog::getSaveFileName(this, QString("Write fiff data file"), QString("./MNE-sample-data/MEG/sample/"), tr("fif data files (*.fif)")); if(filename.isEmpty()) { qDebug("User aborted saving to fiff data file"); return; } if(filename == m_qFileRaw.fileName()) { QMessageBox msgBox; msgBox.setText("You are trying to write to the file you are currently loading the data from. Please choose another file to write to."); msgBox.exec(); return; } //Create output file, progress dialog and future watcher QFile qFileOutput (filename); if(qFileOutput.isOpen()) qFileOutput.close(); QFutureWatcher<bool> writeFileFutureWatcher; QProgressDialog progressDialog("Writing to fif file...", QString(), 0, 0, this, Qt::Dialog); //Connect future watcher and dialog connect(&writeFileFutureWatcher, &QFutureWatcher<bool>::finished, &progressDialog, &QProgressDialog::reset); connect(&progressDialog, &QProgressDialog::canceled, &writeFileFutureWatcher, &QFutureWatcher<bool>::cancel); connect(m_pDataWindow->getDataModel(), &RawModel::writeProgressRangeChanged, &progressDialog, &QProgressDialog::setRange); connect(m_pDataWindow->getDataModel(), &RawModel::writeProgressChanged, &progressDialog, &QProgressDialog::setValue); //Run the file writing in seperate thread writeFileFutureWatcher.setFuture(QtConcurrent::run(m_pDataWindow->getDataModel(), &RawModel::writeFiffData, &qFileOutput)); progressDialog.exec(); writeFileFutureWatcher.waitForFinished(); if(!writeFileFutureWatcher.future().result()) qDebug() << "MainWindow: ERROR writing fiff data file" << qFileOutput.fileName() << "!"; else qDebug() << "MainWindow: Successfully written to" << qFileOutput.fileName() << "!"; } //************************************************************************************************************* void MainWindow::loadEvents() { QString filename = QFileDialog::getOpenFileName(this, QString("Open fiff event data file"), QString("./MNE-sample-data/MEG/sample/"), tr("fif event data files (*-eve.fif);;fif data files (*.fif)")); if(filename.isEmpty()) { qDebug("User aborted loading fiff event file"); return; } if(m_qEventFile.isOpen()) m_qEventFile.close(); m_qEventFile.setFileName(filename); if(m_pEventWindow->getEventModel()->loadEventData(m_qEventFile)) qDebug() << "Fiff event data file" << filename << "loaded."; else qDebug("ERROR loading fiff event data file %s",filename.toLatin1().data()); //Update status bar setWindowStatus(); //Show event window if(!m_pEventWindow->isVisible()) m_pEventWindow->show(); } //************************************************************************************************************* void MainWindow::saveEvents() { QString filename = QFileDialog::getSaveFileName(this, QString("Save fiff event data file"), QString("./MNE-sample-data/MEG/sample/"), tr("fif event data files (*-eve.fif);;fif data files (*.fif)")); if(filename.isEmpty()) { qDebug("User aborted saving to fiff event data file"); return; } if(m_qEventFile.isOpen()) m_qEventFile.close(); m_qEventFile.setFileName(filename); if(m_pEventWindow->getEventModel()->saveEventData(m_qEventFile)) { qDebug() << "Fiff event data file" << filename << "saved."; } else qDebug("ERROR saving fiff event data file %s",filename.toLatin1().data()); } //************************************************************************************************************* void MainWindow::loadEvoked() { QString filename = QFileDialog::getOpenFileName(this,QString("Open evoked fiff data file"),QString("./MNE-sample-data/MEG/sample/"),tr("fif evoked data files (*-ave.fif);;fif data files (*.fif)")); if(filename.isEmpty()) { qDebug("User aborted loading fiff evoked file"); return; } if(m_qEvokedFile.isOpen()) m_qEvokedFile.close(); m_qEvokedFile.setFileName(filename); if(m_pAverageWindow->getAverageModel()->loadEvokedData(m_qEvokedFile)) qDebug() << "Fiff evoked data file" << filename << "loaded."; else qDebug("ERROR loading evoked data file %s",filename.toLatin1().data()); //Update status bar setWindowStatus(); //Show average window // if(!m_pAverageWindow->isVisible()) // m_pAverageWindow->show(); } //************************************************************************************************************* void MainWindow::showWindow(QWidget *window) { //Note: A widget that happens to be obscured by other windows on the screen is considered to be visible. if(!window->isVisible()) { window->show(); window->raise(); } else // if visible raise the widget to be sure that it is not obscured by other windows window->hide(); }
42.810924
208
0.623516
liminsun
a93f415519910387fdc4aeb93ac21d41ac3140ad
2,790
cpp
C++
Source/Engine/ING/Source/ING/Resource/Manager/Manager.cpp
n-c0d3r/ING
f858c973e1b31ffc6deb324fa52eda6323d2c165
[ "MIT" ]
2
2022-01-21T04:03:55.000Z
2022-03-19T08:54:00.000Z
Source/Engine/ING/Source/ING/Resource/Manager/Manager.cpp
n-c0d3r/ING
f858c973e1b31ffc6deb324fa52eda6323d2c165
[ "MIT" ]
null
null
null
Source/Engine/ING/Source/ING/Resource/Manager/Manager.cpp
n-c0d3r/ING
f858c973e1b31ffc6deb324fa52eda6323d2c165
[ "MIT" ]
null
null
null
/** * Include Header */ #include "Manager.h" /** * Include FStream */ #include <fstream> /** * Include File System */ #include <filesystem> /** * Include Coder */ #include <ING/Coder/Coder.h> /** * Include Debug */ #include <ING/_Debug/Debug.h> /** * Include Engine */ #include <ING/Engine/Engine.h> namespace ING { /** * Constructors And Destructor */ ResourceManager::ResourceManager() { Debug::Log("Start Creating ResourceManager"); Debug::Log("ResourceManager Created"); } ResourceManager::~ResourceManager() { } /** * Init, Run, Release Methods */ bool ResourceManager::Init() { Debug::Log("Start Initializing ResourceManager"); Debug::Log("ResourceManager Initialized"); return Square::Init(); } bool ResourceManager::Run() { Debug::Log("Start Running ResourceManager"); return Square::Run(); } bool ResourceManager::Release() { Debug::Log("Start Releasing ResourceManager"); Debug::Log("Finished Releasing ResourceManager"); return Square::Release(); } /** * Resource Management */ bool ResourceManager::IsFileExist (const WString& path) { return std::filesystem::exists(path); } WString ResourceManager::ReadFile(const WString& path, CoderOption& coderOption) { if (!IsFileExist(path)) { Debug::Error(ToString("Cant Read File ") + ToString('"') + ToString(path) + ToString('"')); Engine::GetInstance()->Shutdown(); return L""; } WString result; std::wfstream fileStream; std::streampos fileSize = 0; /* Open File */ fileStream.open(path.c_str()); /* Get File Size */ fileStream.seekg(0, std::wios::end); fileSize = fileStream.tellg(); fileStream.seekg(0, std::wios::beg); /* Read File */ result.resize(fileSize); fileStream.read((wchar_t*)result.c_str(), fileSize); /* Close File */ fileStream.close(); if (coderOption.coder != nullptr) { result = coderOption.coder->Decode(result, coderOption.key); } return result; } void ResourceManager::WriteFile(const WString& path, const WString& content, CoderOption& coderOption) { if (!IsFileExist(path)) { Debug::Error(String("Cant Write File ") + ToString('"') + ToString(path) + ToString('"')); Engine::GetInstance()->Shutdown(); return; } WString parsedContent; if (coderOption.coder != nullptr) { parsedContent = coderOption.coder->Encode(content, coderOption.key); } else { parsedContent = content; } std::wfstream fileStream; unsigned long fileSize = parsedContent.length(); /* Resize File */ std::filesystem::resize_file(path, fileSize); /* Open File */ fileStream.open(path.c_str()); fileStream << parsedContent; /* Close File */ fileStream.close(); } }
12.857143
107
0.645161
n-c0d3r
a9417e99857f34cd3456663b0047cd710756e0db
2,604
cpp
C++
moai/src/uslscore/USRhombus.cpp
jjimenezg93/ai-pathfinding
e32ae8be30d3df21c7e64be987134049b585f1e6
[ "MIT" ]
null
null
null
moai/src/uslscore/USRhombus.cpp
jjimenezg93/ai-pathfinding
e32ae8be30d3df21c7e64be987134049b585f1e6
[ "MIT" ]
null
null
null
moai/src/uslscore/USRhombus.cpp
jjimenezg93/ai-pathfinding
e32ae8be30d3df21c7e64be987134049b585f1e6
[ "MIT" ]
null
null
null
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <uslscore/USBox.h> #include <uslscore/USPlane.h> #include <uslscore/USRhombus.h> //================================================================// // USRhombus //================================================================// //----------------------------------------------------------------// void USRhombus::GetAABB ( USBox& box ) const { USVec3D walker = mLoc; box.Init ( walker ); walker.Add ( mXAxis ); box.Grow ( walker ); walker.Add ( mYAxis ); box.Grow ( walker ); walker.Sub ( mXAxis ); box.Grow ( walker ); walker.Sub ( mYAxis ); box.Grow ( walker ); } //----------------------------------------------------------------// void USRhombus::GetCenter ( USVec3D& center ) const { center = this->mXAxis; center.Add ( this->mYAxis ); center.Scale ( 0.5f ); center.Add ( this->mLoc ); } //----------------------------------------------------------------// void USRhombus::GetPlane ( USPlane3D& plane ) const { USVec3D norm; norm.Cross ( this->mXAxis, this->mYAxis ); norm.Norm (); plane.Init ( this->mLoc, norm ); } //----------------------------------------------------------------// void USRhombus::InitXY ( const USRect& rect, float zOff ) { this->mLoc.mX = rect.mXMin; this->mLoc.mY = rect.mYMin; this->mLoc.mZ = zOff; this->mXAxis.mX = rect.mXMax - rect.mXMin; this->mXAxis.mY = 0.0f; this->mXAxis.mZ = 0.0f; this->mYAxis.mX = 0.0f; this->mYAxis.mY = rect.mYMax - rect.mYMin; this->mYAxis.mZ = 0.0f; } //----------------------------------------------------------------// void USRhombus::InitXZ ( const USRect& rect, float yOff ) { this->mLoc.mX = rect.mXMin; this->mLoc.mY = yOff; this->mLoc.mZ = rect.mYMin; this->mXAxis.mX = rect.mXMax - rect.mXMin; this->mXAxis.mY = 0.0f; this->mXAxis.mZ = 0.0f; this->mYAxis.mX = 0.0f; this->mYAxis.mY = 0.0f; this->mYAxis.mZ = rect.mYMax - rect.mYMin; } //----------------------------------------------------------------// void USRhombus::InitZY ( const USRect& rect, float xOff ) { this->mLoc.mX = xOff; this->mLoc.mY = rect.mYMin; this->mLoc.mZ = rect.mXMin; this->mXAxis.mX = 0.0f; this->mXAxis.mY = 0.0f; this->mXAxis.mZ = rect.mXMax - rect.mXMin; this->mYAxis.mX = 0.0f; this->mYAxis.mY = rect.mYMax - rect.mYMin; this->mYAxis.mZ = 0.0f; } //----------------------------------------------------------------// void USRhombus::Transform ( const USMatrix4x4& mtx ) { mtx.Transform ( mLoc ); mtx.TransformVec ( mXAxis ); mtx.TransformVec ( mYAxis ); }
24.8
68
0.49424
jjimenezg93
a9431716c39b347bc03eba3eb71951e84f694ab1
3,184
hpp
C++
planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/include/scene_module/occlusion_spot/risk_predictive_braking.hpp
loop-perception/AutowareArchitectureProposal.iv
5d8dff0db51634f0c42d2a3e87ca423fbee84348
[ "Apache-2.0" ]
1
2022-03-09T05:53:04.000Z
2022-03-09T05:53:04.000Z
planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/include/scene_module/occlusion_spot/risk_predictive_braking.hpp
loop-perception/AutowareArchitectureProposal.iv
5d8dff0db51634f0c42d2a3e87ca423fbee84348
[ "Apache-2.0" ]
4
2022-01-07T21:21:04.000Z
2022-03-14T21:25:37.000Z
planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/include/scene_module/occlusion_spot/risk_predictive_braking.hpp
loop-perception/AutowareArchitectureProposal.iv
5d8dff0db51634f0c42d2a3e87ca423fbee84348
[ "Apache-2.0" ]
2
2021-03-09T00:20:39.000Z
2021-04-16T10:23:36.000Z
// Copyright 2021 Tier IV, 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. #ifndef SCENE_MODULE__OCCLUSION_SPOT__RISK_PREDICTIVE_BRAKING_HPP_ #define SCENE_MODULE__OCCLUSION_SPOT__RISK_PREDICTIVE_BRAKING_HPP_ #include <scene_module/occlusion_spot/occlusion_spot_utils.hpp> #include <autoware_planning_msgs/msg/path_with_lane_id.hpp> #include <algorithm> #include <vector> namespace behavior_velocity_planner { namespace occlusion_spot_utils { void applySafeVelocityConsideringPossibleCollison( autoware_planning_msgs::msg::PathWithLaneId * inout_path, std::vector<PossibleCollisionInfo> & possible_collisions, const double current_vel, const EgoVelocity & ego, const PlannerParam & param); int insertSafeVelocityToPath( const geometry_msgs::msg::Pose & in_pose, const double safe_vel, const PlannerParam & param, autoware_planning_msgs::msg::PathWithLaneId * inout_path); // @brief calculates the maximum velocity allowing to decelerate within the given distance inline double calculatePredictiveBrakingVelocity( const double ego_vel, const double dist2col, const double pbs_decel) { return std::sqrt(std::max(std::pow(ego_vel, 2.0) - 2.0 * std::abs(pbs_decel) * dist2col, 0.0)); } /** * @param: safety_time: safety time buffer for reaction * @param: dist_to_obj: distance to virtual darting object * @param: v_obs: relative velocity for virtual darting object * @param: ebs_decel: emergency brake * @return safe velocity considering rpb **/ inline double calculateSafeRPBVelocity( const double safety_time, const double dist_to_obj, const double v_obs, const double ebs_decel) { const double t_vir = dist_to_obj / v_obs; // min safety time buffer is at least more than 0 const double ttc_virtual = std::max(t_vir - safety_time, 0.0); // safe velocity consider emergency brake const double v_safe = std::abs(ebs_decel) * ttc_virtual; return v_safe; } inline double getPBSLimitedRPBVelocity( const double pbs_vel, const double rpb_vel, const double min_vel, const double original_vel) { const double max_vel_noise = 0.05; // ensure safe velocity doesn't exceed maximum allowed pbs deceleration double rpb_pbs_limited_vel = std::max(pbs_vel + max_vel_noise, rpb_vel); // ensure safe path velocity is also above ego min velocity rpb_pbs_limited_vel = std::max(rpb_pbs_limited_vel, min_vel); // ensure we only lower the original velocity (and do not increase it) rpb_pbs_limited_vel = std::min(rpb_pbs_limited_vel, original_vel); return rpb_pbs_limited_vel; } } // namespace occlusion_spot_utils } // namespace behavior_velocity_planner #endif // SCENE_MODULE__OCCLUSION_SPOT__RISK_PREDICTIVE_BRAKING_HPP_
39.8
97
0.784234
loop-perception
a946e466ad3a0d7381ebe09104c7f1c54e369037
6,899
hpp
C++
pabst/gui_spectator.hpp
ltac/ltmf-campus-martius.clafghan
756e60b022fec52f599c86bb6f4eff63dbbdff20
[ "Unlicense" ]
null
null
null
pabst/gui_spectator.hpp
ltac/ltmf-campus-martius.clafghan
756e60b022fec52f599c86bb6f4eff63dbbdff20
[ "Unlicense" ]
1
2017-03-03T07:10:34.000Z
2017-03-03T07:10:34.000Z
pabst/gui_spectator.hpp
ltac/ltmf-campus-martius.clafghan
756e60b022fec52f599c86bb6f4eff63dbbdff20
[ "Unlicense" ]
null
null
null
class PABST_SPECT_dialog { idd = 6969; movingEnable = 1; enableSimulation = 1; enableDisplay = 1; onLoad = "uiNamespace setVariable ['PABST_SPECT_theDialog', _this select 0];"; duration = 2147483647; fadein = 0; fadeout = 0; onKeyDown = "['key', true, _this] call PABST_SPECT_UI_onKeyAction"; onKeyUp = "['key', false, _this] call PABST_SPECT_UI_onKeyAction"; onMouseButtonDown = "['mouse', true, _this] call PABST_SPECT_UI_onKeyAction"; onMouseButtonUp = "['mouse', false, _this] call PABST_SPECT_UI_onKeyAction"; onMouseMoving = "_this call PABST_SPECT_UI_onMouseMoving"; onMouseZChanged = "_this call PABST_SPECT_UI_onMouseWheel"; class controlsBackground { class MiniMap: RscMapControl { idc = 2200; type = 100; //100 hids all markers maxSatelliteAlpha = 0.125; x = 0.0 * safezoneW + safezoneX; y = 0.65 * safezoneH + safezoneY; w = 0.35 * safezoneW; h = 0.35 * safezoneH; onMouseButtonDown = "_this call PABST_SPECT_UI_mapClick"; onDraw = "_this call PABST_SPECT_UI_onEachMapFrame"; }; }; class controls { class CameraControlGroup: RscControlsGroup { idc = 2300; x = 0.87 * safezoneW + safezoneX; y = 0.65 * safezoneH + safezoneY; w = 0.13 * safezoneW; h = 0.36 * safezoneH; class controls { class 1stButton: RscButton { idc = 1691; text = "1st"; //--- ToDo: Localize; x = 0.011 * safezoneW; y = 0.001 * safezoneH; w = 0.025 * safezoneW; h = 0.0175 * safezoneH; action = "[1] call PABST_SPECT_UI_updateCameraMode"; colorBackground[] = {0,0,0,0.5}; colorBackgroundActive[] = {0,0,0,0.5}; colorFocused[] = {0,0,0,0.5}; colorShadow[] = {0.5,0.5,0.5,0.5}; }; class 3rdButton: 1stButton { idc = 1692; text = "3rd"; //--- ToDo: Localize; x = 0.047 * safezoneW; action = "[2] call PABST_SPECT_UI_updateCameraMode"; }; class FreeButton: 1stButton { idc = 1693; text = "Free"; //--- ToDo: Localize; x = 0.083 * safezoneW; action = "[3] call PABST_SPECT_UI_updateCameraMode"; }; // class TopButton: 1stButton // { // idc = 1694; // text = "Top"; //--- ToDo: Localize; // x = 0.0875 * safezoneW; // action = "[4] call PABST_SPECT_UI_updateCameraMode"; // }; class RscCombo_2108: RscCombo { idc = 2108; text = ""; //--- ToDo: Localize; x = 0 * safezoneW; y = 0.021 * safezoneH; w = 0.055 * safezoneW; h = 0.015 * safezoneH; sizeEx = 0.03; onLBSelChanged = "_this call PABST_SPECT_UI_updateVisionMode"; }; class FilterButton: RscButton { idc = 1661; text = "Filter AI"; //--- ToDo: Localize; x = 0.06 * safezoneW; y = 0.021 * safezoneH; w = 0.035 * safezoneW; h = 0.015 * safezoneH; sizeEx = 0.03; action = "[] call PABST_SPECT_UI_filterAI"; colorBackground[] = {0,0,0,0.5}; colorBackgroundActive[] = {0,0,0,0.5}; colorFocused[] = {0,0,0,0.5}; colorShadow[] = {0.5,0.5,0.5,0.5}; }; class TagsButton: FilterButton { idc = 1662; text = "Tags"; //--- ToDo: Localize; x = 0.1 * safezoneW; y = 0.021 * safezoneH; w = 0.03 * safezoneW; h = 0.015 * safezoneH; sizeEx = 0.03; action = "[] call PABST_SPECT_UI_nameTags"; colorBackground[] = {0,0,0,0.5}; colorBackgroundActive[] = {0,0,0,0.5}; colorFocused[] = {0,0,0,0.5}; colorShadow[] = {0.5,0.5,0.5,0.5}; }; // class RscFrame_cameraText: RscFrame // { // idc = 456789; // text = "Camera Mode"; //--- ToDo: Localize; // x = 0.001 * safezoneW; // y = 0.001 * safezoneH; // w = 0.12 * safezoneW; // h = 0.033 * safezoneH; // }; class SwitchablePlayersListBox : RscListNBox { idc = 20001; x = 0 * safezoneW; y = 0.04 * safezoneH; w = 0.13 * safezoneW; h = 0.31 * safezoneH; // number of columns used, and their left positions // if using side buttons, space has to be reserved for those, // at a width of roughly 120% of rowHeight columns[] = {0, 0.275}; // height of each row rowHeight = .0325; sizeEx = 0.03; font = "PuristaBold"; drawSideArrows = 1; // IDCs for left and right side buttons colorText[] = {1, 1, 1, 1}; colorBackground[] = {1, 0, 0, 1}; colorSelectBackground[] = {0, 0, 0, 1}; colorSelectBackground2[] = {0, 0, 0, 1}; onLBSelChanged = "_this call PABST_SPECT_UI_onListBoxChange"; }; }; }; //////////////////////////////////////////////////////// // GUI EDITOR OUTPUT START (by Pabst Mirror, v1.063, #Perise) //////////////////////////////////////////////////////// class RscButton_1600: RscButton { idc = 1600; text = "AutoTrack"; //--- ToDo: Localize; x = 0 * safezoneW + safezoneX; y = 0.985 * safezoneH + safezoneY; w = 0.0425 * safezoneW; h = 0.015 * safezoneH; colorBackground[] = {0,0,0,0.5}; colorBackgroundActive[] = {0,0,0,0.5}; colorFocused[] = {0,0,0,0.5}; colorShadow[] = {0,0,0,0}; action = "_this call PABST_SPECT_UI_mapTrack"; }; class RscButton_1601: RscButton { idc = 1601; text = "Size"; //--- ToDo: Localize; x = 0.045 * safezoneW + safezoneX; y = 0.985 * safezoneH + safezoneY; w = 0.0275 * safezoneW; h = 0.015 * safezoneH; colorBackground[] = {0,0,0,0.5}; colorBackgroundActive[] = {0,0,0,0.5}; colorFocused[] = {0,0,0,0.5}; colorShadow[] = {0,0,0,0}; action = "_this call PABST_SPECT_UI_mapSize"; }; class RscButton_1602: RscButton { idc = 1602; text = "Player List"; //--- ToDo: Localize; x = 0.075 * safezoneW + safezoneX; y = 0.985 * safezoneH + safezoneY; w = 0.045 * safezoneW; h = 0.015 * safezoneH; colorBackground[] = {0,0,0,0.5}; colorBackgroundActive[] = {0,0,0,0.5}; colorFocused[] = {0,0,0,0.5}; colorShadow[] = {0,0,0,0}; action = "_this call PABST_SPECT_UI_rightList"; }; // class KillBox: RscStructuredText // { // idc = 1100; // text = "Killed ybbbbasdfsasadsad from 500 meters"; //--- ToDo: Localize; // x = 0.78875 * safezoneW + safezoneX; // y = 0.973 * safezoneH + safezoneY; // w = 0.211406 * safezoneW; // h = 0.022 * safezoneH; // colorText[] = {1,1,1,1}; // colorBackground[] = {1,1,1,0}; // }; // class RscStructuredText_1101: RscStructuredText // { // idc = 1101; // text = "Spectating"; //--- ToDo: Localize; // x = 0.360781 * safezoneW + safezoneX; // y = 0.00500001 * safezoneH + safezoneY; // w = 0.211406 * safezoneW; // h = 0.022 * safezoneH; // colorText[] = {1,1,1,1}; // colorBackground[] = {0,0,0,0.25}; // }; //////////////////////////////////////////////////////// // GUI EDITOR OUTPUT END //////////////////////////////////////////////////////// }; };
28.626556
79
0.559356
ltac
a947f7efe9ba7f159fa6e89c06cf9817fee8d7db
19,361
cpp
C++
test/bridge/ActiveMediaListTest.cpp
danielgronberg/SymphonyMediaBridge
2cdd2ecd45c534545c9d3f3c36d8e86771330057
[ "Apache-2.0" ]
null
null
null
test/bridge/ActiveMediaListTest.cpp
danielgronberg/SymphonyMediaBridge
2cdd2ecd45c534545c9d3f3c36d8e86771330057
[ "Apache-2.0" ]
null
null
null
test/bridge/ActiveMediaListTest.cpp
danielgronberg/SymphonyMediaBridge
2cdd2ecd45c534545c9d3f3c36d8e86771330057
[ "Apache-2.0" ]
null
null
null
#include "bridge/engine/ActiveMediaList.h" #include "bridge/engine/EngineAudioStream.h" #include "bridge/engine/EngineVideoStream.h" #include "bridge/engine/SimulcastStream.h" #include "jobmanager/JobManager.h" #include "nlohmann/json.hpp" #include "test/bridge/ActiveMediaListTestLevels.h" #include "test/bridge/DummyRtcTransport.h" #include "transport/RtcTransport.h" #include <gtest/gtest.h> #include <memory> namespace { static const uint32_t defaultLastN = 2; void threadFunction(jobmanager::JobManager* jobManager) { auto job = jobManager->wait(); while (job) { job->run(); jobManager->freeJob(job); job = jobManager->wait(); } } bool endpointsContainsId(const nlohmann::json& messageJson, const char* id) { const auto& endpoints = messageJson["endpoints"]; for (const auto& endpoint : endpoints) { #if ENABLE_LEGACY_API if (endpoint["id"].get<std::string>().compare(id) == 0) { return true; } #else if (endpoint["endpoint"].get<std::string>().compare(id) == 0) { return true; } #endif } return false; } } // namespace class ActiveMediaListTest : public ::testing::Test { public: ActiveMediaListTest() : _engineAudioStreams(16), _engineVideoStreams(16) {} private: void SetUp() override { for (uint32_t i = 0; i < 10; ++i) { _audioSsrcs.push_back(i); } for (uint32_t i = 10; i < 20; ++i) { _videoSsrcs.push_back(bridge::SimulcastLevel({i, i + 100})); } for (uint32_t i = 20; i < 24; ++i) { _videoPinSsrcs.push_back(bridge::SimulcastLevel({i, i + 100})); } _jobManager = std::make_unique<jobmanager::JobManager>(); _jobQueue = std::make_unique<jobmanager::JobQueue>(*_jobManager); _transport = std::make_unique<DummyRtcTransport>(*_jobQueue); _activeMediaList = std::make_unique<bridge::ActiveMediaList>(_audioSsrcs, _videoSsrcs, defaultLastN); _engineAudioStreams.clear(); _engineVideoStreams.clear(); } void TearDown() override { _activeMediaList.reset(); for (auto& videoStreamsEntry : _engineVideoStreams) { delete videoStreamsEntry.second; } _engineAudioStreams.clear(); _engineVideoStreams.clear(); auto thread = std::make_unique<std::thread>(threadFunction, _jobManager.get()); _jobQueue.reset(); _jobManager->stop(); thread->join(); _jobManager.reset(); } protected: std::vector<uint32_t> _audioSsrcs; std::vector<bridge::SimulcastLevel> _videoSsrcs; std::vector<bridge::SimulcastLevel> _videoPinSsrcs; std::unique_ptr<jobmanager::JobManager> _jobManager; std::unique_ptr<jobmanager::JobQueue> _jobQueue; std::unique_ptr<DummyRtcTransport> _transport; concurrency::MpmcHashmap32<size_t, bridge::EngineAudioStream*> _engineAudioStreams; concurrency::MpmcHashmap32<size_t, bridge::EngineVideoStream*> _engineVideoStreams; std::unique_ptr<bridge::ActiveMediaList> _activeMediaList; bridge::EngineVideoStream* addEngineVideoStream(const size_t id) { bridge::SimulcastStream simulcastStream{0}; simulcastStream._numLevels = 1; simulcastStream._levels[0]._ssrc = id; simulcastStream._levels[0]._feedbackSsrc = 100 + id; auto engineVideoStream = new bridge::EngineVideoStream(std::to_string(id), id, id, simulcastStream, utils::Optional<bridge::SimulcastStream>(), *_transport, bridge::RtpMap(), bridge::RtpMap(), utils::Optional<uint8_t>(), bridge::SsrcWhitelist({false, 0, {0, 0}}), true, _videoPinSsrcs); _engineVideoStreams.emplace(id, engineVideoStream); return engineVideoStream; } void addEngineAudioStream(const size_t id) { auto engineAudioStream = std::make_unique<bridge::EngineAudioStream>(std::to_string(id), id, id, utils::Optional<uint32_t>(id), *_transport, 1, 3, false, bridge::RtpMap(), true); _engineAudioStreams.emplace(id, engineAudioStream.release()); } uint64_t switchDominantSpeaker(const uint64_t timestamp, const size_t endpointIdHash) { uint64_t newTimestamp = timestamp; for (uint32_t i = 0; i < 1000; ++i) { for (uint32_t j = 0; j < 100; ++j) { _activeMediaList->onNewAudioLevel(endpointIdHash, 1); } newTimestamp += 1000; bool dominantSpeakerChanged = false; bool userMediaMapChanged = false; _activeMediaList->process(newTimestamp, dominantSpeakerChanged, userMediaMapChanged); if (dominantSpeakerChanged) { return newTimestamp; } } return newTimestamp; } void zeroLevels(const size_t endpointIdHash) { for (uint32_t i = 0; i < 100; ++i) { _activeMediaList->onNewAudioLevel(endpointIdHash, 126); } } }; TEST_F(ActiveMediaListTest, maxOneSwitchEveryTwoSeconds) { uint64_t timestamp = 123456; const auto participant1 = 1; const auto participant2 = 2; // First added participant is set as dominant speaker, add this participant here so that switching will happen _activeMediaList->addAudioParticipant(3); _activeMediaList->addAudioParticipant(participant1); _activeMediaList->addAudioParticipant(participant2); bool dominantSpeakerChanged = false; bool userMediaMapChanged = false; _activeMediaList->process(timestamp, dominantSpeakerChanged, userMediaMapChanged); for (auto i = 0; i < 30; ++i) { _activeMediaList->onNewAudioLevel(participant1, 64 + (i % 40)); _activeMediaList->onNewAudioLevel(participant2, 96 + (i % 5)); } timestamp += 200; _activeMediaList->process(timestamp, dominantSpeakerChanged, userMediaMapChanged); EXPECT_TRUE(dominantSpeakerChanged); for (auto i = 0; i < 199; ++i) { _activeMediaList->onNewAudioLevel(participant1, 96 + (i % 5)); _activeMediaList->onNewAudioLevel(participant2, 64 + (i % 40)); timestamp += 10; _activeMediaList->process(timestamp, dominantSpeakerChanged, userMediaMapChanged); EXPECT_FALSE(dominantSpeakerChanged); } _activeMediaList->onNewAudioLevel(participant1, 96); _activeMediaList->onNewAudioLevel(participant2, 64); timestamp += 11; _activeMediaList->process(timestamp, dominantSpeakerChanged, userMediaMapChanged); EXPECT_TRUE(dominantSpeakerChanged); _activeMediaList->removeAudioParticipant(participant1); _activeMediaList->removeAudioParticipant(participant2); } TEST_F(ActiveMediaListTest, audioParticipantsAddedToAudioRewriteMap) { _activeMediaList->addAudioParticipant(1); _activeMediaList->addAudioParticipant(2); _activeMediaList->addAudioParticipant(3); const auto& audioRewriteMap = _activeMediaList->getAudioSsrcRewriteMap(); EXPECT_NE(audioRewriteMap.end(), audioRewriteMap.find(1)); EXPECT_NE(audioRewriteMap.end(), audioRewriteMap.find(2)); EXPECT_NE(audioRewriteMap.end(), audioRewriteMap.find(3)); } TEST_F(ActiveMediaListTest, audioParticipantsNotAddedToFullAudioRewriteMap) { _activeMediaList->addAudioParticipant(1); _activeMediaList->addAudioParticipant(2); _activeMediaList->addAudioParticipant(3); _activeMediaList->addAudioParticipant(4); const auto& audioRewriteMap = _activeMediaList->getAudioSsrcRewriteMap(); EXPECT_NE(audioRewriteMap.end(), audioRewriteMap.find(1)); EXPECT_NE(audioRewriteMap.end(), audioRewriteMap.find(2)); EXPECT_NE(audioRewriteMap.end(), audioRewriteMap.find(3)); EXPECT_EQ(audioRewriteMap.end(), audioRewriteMap.find(4)); } TEST_F(ActiveMediaListTest, activeAudioParticipantIsSwitchedIn) { _activeMediaList->addAudioParticipant(1); _activeMediaList->addAudioParticipant(2); _activeMediaList->addAudioParticipant(3); _activeMediaList->addAudioParticipant(4); _activeMediaList->onNewAudioLevel(4, 10); bool dominantSpeakerChanged = false; bool userMediaMapChanged = false; _activeMediaList->process(1000, dominantSpeakerChanged, userMediaMapChanged); const auto& audioRewriteMap = _activeMediaList->getAudioSsrcRewriteMap(); EXPECT_NE(audioRewriteMap.end(), audioRewriteMap.find(4)); EXPECT_EQ(3, audioRewriteMap.size()); } TEST_F(ActiveMediaListTest, activeAudioParticipantIsSwitchedInEvenIfNotMostDominant) { const size_t numParticipants = 10; for (size_t i = 1; i <= numParticipants; ++i) { _activeMediaList->addAudioParticipant(i); for (const auto element : ActiveMediaListTestLevels::silence) { _activeMediaList->onNewAudioLevel(i, element); } } bool dominantSpeakerChanged = false; bool userMediaMapChanged = false; _activeMediaList->process(1000, dominantSpeakerChanged, userMediaMapChanged); for (const auto element : ActiveMediaListTestLevels::longUtterance) { _activeMediaList->onNewAudioLevel(1, element); } for (const auto element : ActiveMediaListTestLevels::longUtterance) { _activeMediaList->onNewAudioLevel(2, element); } for (const auto element : ActiveMediaListTestLevels::shortUtterance) { _activeMediaList->onNewAudioLevel(4, element); } _activeMediaList->process(2000, dominantSpeakerChanged, userMediaMapChanged); const auto& audioRewriteMap = _activeMediaList->getAudioSsrcRewriteMap(); EXPECT_NE(audioRewriteMap.end(), audioRewriteMap.find(4)); EXPECT_EQ(3, audioRewriteMap.size()); } TEST_F(ActiveMediaListTest, activeAudioParticipantIsSwitchedInEvenIfNotMostDominantSmallList) { const size_t numParticipants = 2; for (size_t i = 1; i <= numParticipants; ++i) { _activeMediaList->addAudioParticipant(i); for (const auto element : ActiveMediaListTestLevels::silence) { _activeMediaList->onNewAudioLevel(i, element); } } bool dominantSpeakerChanged = false; bool userMediaMapChanged = false; _activeMediaList->process(1000, dominantSpeakerChanged, userMediaMapChanged); for (const auto element : ActiveMediaListTestLevels::longUtterance) { _activeMediaList->onNewAudioLevel(1, element); } for (const auto element : ActiveMediaListTestLevels::shortUtterance) { _activeMediaList->onNewAudioLevel(2, element); } _activeMediaList->process(2000, dominantSpeakerChanged, userMediaMapChanged); const auto& audioRewriteMap = _activeMediaList->getAudioSsrcRewriteMap(); EXPECT_NE(audioRewriteMap.end(), audioRewriteMap.find(2)); EXPECT_EQ(2, audioRewriteMap.size()); } TEST_F(ActiveMediaListTest, activeAudioParticipantIsSwitchedInEvenIfNotMostDominantSmallLastN) { auto smallActiveMediaList = std::make_unique<bridge::ActiveMediaList>(_audioSsrcs, _videoSsrcs, 1); smallActiveMediaList->addAudioParticipant(1); smallActiveMediaList->addAudioParticipant(2); smallActiveMediaList->addAudioParticipant(3); smallActiveMediaList->addAudioParticipant(4); for (const auto element : ActiveMediaListTestLevels::longUtterance) { smallActiveMediaList->onNewAudioLevel(1, element); } for (const auto element : ActiveMediaListTestLevels::longUtterance) { smallActiveMediaList->onNewAudioLevel(2, element); } for (const auto element : ActiveMediaListTestLevels::silence) { smallActiveMediaList->onNewAudioLevel(3, element); } for (const auto element : ActiveMediaListTestLevels::shortUtterance) { smallActiveMediaList->onNewAudioLevel(4, element); } bool dominantSpeakerChanged = false; bool userMediaMapChanged = false; smallActiveMediaList->process(1000, dominantSpeakerChanged, userMediaMapChanged); const auto& audioRewriteMap = smallActiveMediaList->getAudioSsrcRewriteMap(); EXPECT_NE(audioRewriteMap.end(), audioRewriteMap.find(1)); } TEST_F(ActiveMediaListTest, videoParticipantsAddedToVideoRewriteMap) { auto videoStream1 = addEngineVideoStream(1); auto videoStream2 = addEngineVideoStream(2); auto videoStream3 = addEngineVideoStream(3); _activeMediaList->addVideoParticipant(1, videoStream1->_simulcastStream, videoStream1->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(2, videoStream2->_simulcastStream, videoStream2->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(3, videoStream3->_simulcastStream, videoStream3->_secondarySimulcastStream); const auto& videoRewriteMap = _activeMediaList->getVideoSsrcRewriteMap(); EXPECT_NE(videoRewriteMap.end(), videoRewriteMap.find(1)); EXPECT_NE(videoRewriteMap.end(), videoRewriteMap.find(2)); EXPECT_NE(videoRewriteMap.end(), videoRewriteMap.find(3)); } TEST_F(ActiveMediaListTest, videoParticipantsNotAddedToFullVideoRewriteMap) { auto videoStream1 = addEngineVideoStream(1); auto videoStream2 = addEngineVideoStream(2); auto videoStream3 = addEngineVideoStream(3); auto videoStream4 = addEngineVideoStream(4); _activeMediaList->addVideoParticipant(1, videoStream1->_simulcastStream, videoStream1->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(2, videoStream2->_simulcastStream, videoStream2->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(3, videoStream3->_simulcastStream, videoStream3->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(4, videoStream4->_simulcastStream, videoStream4->_secondarySimulcastStream); const auto& videoRewriteMap = _activeMediaList->getVideoSsrcRewriteMap(); EXPECT_NE(videoRewriteMap.end(), videoRewriteMap.find(1)); EXPECT_NE(videoRewriteMap.end(), videoRewriteMap.find(2)); EXPECT_NE(videoRewriteMap.end(), videoRewriteMap.find(3)); EXPECT_EQ(videoRewriteMap.end(), videoRewriteMap.find(4)); } TEST_F(ActiveMediaListTest, userMediaMapContainsAllStreamsExcludingSelf) { auto videoStream1 = addEngineVideoStream(1); auto videoStream2 = addEngineVideoStream(2); auto videoStream3 = addEngineVideoStream(3); _activeMediaList->addVideoParticipant(1, videoStream1->_simulcastStream, videoStream1->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(2, videoStream2->_simulcastStream, videoStream2->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(3, videoStream3->_simulcastStream, videoStream3->_secondarySimulcastStream); utils::StringBuilder<1024> message; _activeMediaList->makeUserMediaMapMessage(defaultLastN, 2, 0, _engineAudioStreams, _engineVideoStreams, message); const auto messageJson = nlohmann::json::parse(message.build()); EXPECT_TRUE(endpointsContainsId(messageJson, "1")); EXPECT_FALSE(endpointsContainsId(messageJson, "2")); EXPECT_TRUE(endpointsContainsId(messageJson, "3")); } TEST_F(ActiveMediaListTest, userMediaMapContainsOnlyLastNItems) { auto videoStream1 = addEngineVideoStream(1); auto videoStream2 = addEngineVideoStream(2); auto videoStream3 = addEngineVideoStream(3); auto videoStream4 = addEngineVideoStream(4); _activeMediaList->addVideoParticipant(1, videoStream1->_simulcastStream, videoStream1->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(2, videoStream2->_simulcastStream, videoStream2->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(3, videoStream3->_simulcastStream, videoStream3->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(4, videoStream4->_simulcastStream, videoStream4->_secondarySimulcastStream); utils::StringBuilder<1024> message; _activeMediaList->makeUserMediaMapMessage(defaultLastN, 2, 0, _engineAudioStreams, _engineVideoStreams, message); const auto messageJson = nlohmann::json::parse(message.build()); EXPECT_TRUE(endpointsContainsId(messageJson, "1")); EXPECT_FALSE(endpointsContainsId(messageJson, "2")); EXPECT_TRUE(endpointsContainsId(messageJson, "3")); EXPECT_FALSE(endpointsContainsId(messageJson, "4")); } TEST_F(ActiveMediaListTest, userMediaMapContainsPinnedItem) { auto videoStream1 = addEngineVideoStream(1); auto videoStream2 = addEngineVideoStream(2); auto videoStream3 = addEngineVideoStream(3); auto videoStream4 = addEngineVideoStream(4); _activeMediaList->addVideoParticipant(1, videoStream1->_simulcastStream, videoStream1->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(2, videoStream2->_simulcastStream, videoStream2->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(3, videoStream3->_simulcastStream, videoStream3->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(4, videoStream4->_simulcastStream, videoStream4->_secondarySimulcastStream); bridge::SimulcastLevel simulcastLevel; videoStream4->_videoPinSsrcs.pop(simulcastLevel); videoStream2->_pinSsrc.set(simulcastLevel); utils::StringBuilder<1024> message; _activeMediaList->makeUserMediaMapMessage(defaultLastN, 2, 4, _engineAudioStreams, _engineVideoStreams, message); const auto messageJson = nlohmann::json::parse(message.build()); EXPECT_TRUE(endpointsContainsId(messageJson, "1")); EXPECT_FALSE(endpointsContainsId(messageJson, "2")); EXPECT_FALSE(endpointsContainsId(messageJson, "3")); EXPECT_TRUE(endpointsContainsId(messageJson, "4")); } TEST_F(ActiveMediaListTest, userMediaMapUpdatedWithDominantSpeaker) { _activeMediaList->addAudioParticipant(1); _activeMediaList->addAudioParticipant(2); _activeMediaList->addAudioParticipant(3); _activeMediaList->addAudioParticipant(4); auto videoStream1 = addEngineVideoStream(1); auto videoStream2 = addEngineVideoStream(2); auto videoStream3 = addEngineVideoStream(3); auto videoStream4 = addEngineVideoStream(4); _activeMediaList->addVideoParticipant(1, videoStream1->_simulcastStream, videoStream1->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(2, videoStream2->_simulcastStream, videoStream2->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(3, videoStream3->_simulcastStream, videoStream3->_secondarySimulcastStream); _activeMediaList->addVideoParticipant(4, videoStream4->_simulcastStream, videoStream4->_secondarySimulcastStream); uint64_t timestamp = 0; zeroLevels(1); zeroLevels(2); zeroLevels(3); timestamp = switchDominantSpeaker(timestamp, 4); utils::StringBuilder<1024> message; _activeMediaList->makeUserMediaMapMessage(defaultLastN, 2, 0, _engineAudioStreams, _engineVideoStreams, message); printf("%s\n", message.get()); const auto messageJson = nlohmann::json::parse(message.build()); EXPECT_TRUE(endpointsContainsId(messageJson, "1")); EXPECT_FALSE(endpointsContainsId(messageJson, "2")); EXPECT_FALSE(endpointsContainsId(messageJson, "3")); EXPECT_TRUE(endpointsContainsId(messageJson, "4")); }
37.090038
118
0.725944
danielgronberg
a94eadd6928a8d7da4d8a43255b50584aef29a44
1,264
cc
C++
src/block.cc
enteisuper/Tetris-Reloaded
c594402e315523491f854de54c6d956a34c79442
[ "MIT" ]
null
null
null
src/block.cc
enteisuper/Tetris-Reloaded
c594402e315523491f854de54c6d956a34c79442
[ "MIT" ]
null
null
null
src/block.cc
enteisuper/Tetris-Reloaded
c594402e315523491f854de54c6d956a34c79442
[ "MIT" ]
null
null
null
// // Created by Henrik Tseng on 4/25/20. // #include "physics/block.h" #include <Box2D/Dynamics/b2Fixture.h> #include <physics/world.h> namespace tetris { b2AABB Block::GetBlockBox(World* world) { b2Fixture* fixture_list = body_->GetFixtureList(); b2AABB body_aabb; // manually set constructor body_aabb.lowerBound.x = world->GetTotalNumCol(); body_aabb.lowerBound.y = world->GetTotalNumRow(); body_aabb.upperBound.x = 0.0; body_aabb.upperBound.y = 0.0; for (b2Fixture* fixture = fixture_list; fixture != nullptr; fixture = fixture->GetNext()) { body_aabb.Combine(fixture->GetAABB(0)); } return body_aabb; } const std::vector<b2AABB> Block::GetBoundingBoxList() const { std::vector<b2AABB> bound_box_list; b2Fixture* fixture_list = body_->GetFixtureList(); for (b2Fixture* fixture = fixture_list; fixture != nullptr; fixture = fixture->GetNext()) { bound_box_list.push_back(fixture->GetAABB(0)); } return bound_box_list; } void Block::SetTileShapeAtColRow(b2PolygonShape* shape, double col, double row) { // smaller blocks for easier collision double scaled_size = 0.8; shape->SetAsBox(scaled_size / 2, scaled_size / 2, b2Vec2(col + 0.5, row + 0.5), 0.0f); } } // namespace tetris
25.795918
61
0.698576
enteisuper
a9501e5e94226cc4cf48d3e8cd3015c9ac26a910
1,335
hpp
C++
application/timely-matter/src/views/RenderView.hpp
davidbeermann/timely-matter
fca86fb5b48766c5371677a90ac5149c1b071149
[ "MIT" ]
2
2016-09-03T17:49:30.000Z
2016-12-20T18:12:58.000Z
application/timely-matter/src/views/RenderView.hpp
davidbeermann/timely-matter
fca86fb5b48766c5371677a90ac5149c1b071149
[ "MIT" ]
null
null
null
application/timely-matter/src/views/RenderView.hpp
davidbeermann/timely-matter
fca86fb5b48766c5371677a90ac5149c1b071149
[ "MIT" ]
null
null
null
#pragma once #include "ofMain.h" #include "BaseView.hpp" #include "RenderParams.hpp" #include "VectorFieldInputFactory.hpp" #include "VectorFieldInput.hpp" #include "VectorField.hpp" #include "ParticleSystem.hpp" #include "Metaballs.hpp" #include "PingPongFbo.hpp" #include "RenderControls.hpp" #include "OscRenderControls.hpp" #include "MidiRenderControls.hpp" #include "PdfRenderer.hpp" namespace timelymatter { class RenderView : public BaseView { RenderParams & m_params; VectorFieldInputFactory m_input_factory; VectorFieldInput& m_input; VectorField m_vector_field; ParticleSystem m_particle_system; Metaballs m_metaballs; ofRectangle m_output_rect; PingPongFbo m_blur_fbo; ofShader m_blur_shader; ofParameter<bool> m_param_enabled; ofParameter<int> m_param_strength; ofColor m_input_color; ofColor m_particle_color; ofColor m_metaballs_color; OscRenderControls m_osc_controls = OscRenderControls(); PdfRenderer m_pdf_renderer; protected: void m_onWindowResized(const int width, const int height); void m_onSetup(); void m_onUpdate(); void m_onDraw(); public: RenderView(); }; }
25.188679
66
0.668914
davidbeermann
a955174c8c8d3f96c72bebcb6370b6567e1c8133
1,108
cpp
C++
examples/charstring-split.cpp
davidwed/sqlrelay_rudiments
6ccffdfc5fa29f8c0226f3edc2aa888aa1008347
[ "BSD-2-Clause-NetBSD" ]
null
null
null
examples/charstring-split.cpp
davidwed/sqlrelay_rudiments
6ccffdfc5fa29f8c0226f3edc2aa888aa1008347
[ "BSD-2-Clause-NetBSD" ]
null
null
null
examples/charstring-split.cpp
davidwed/sqlrelay_rudiments
6ccffdfc5fa29f8c0226f3edc2aa888aa1008347
[ "BSD-2-Clause-NetBSD" ]
null
null
null
#include <rudiments/charstring.h> #include <rudiments/stdio.h> int main(int argc, const char **argv) { const char str[]="All along the untrodden paths of the future..."; // split... char **parts; uint64_t partcount; charstring::split(str," ",true,&parts,&partcount); stdoutput.printf("original string:\n %s\n",str); stdoutput.printf("split on space:\n"); for (uint64_t i=0; i<partcount; i++) { stdoutput.printf(" %s\n",parts[i]); } stdoutput.write('\n'); for (uint64_t i=0; i<partcount; i++) { delete[] parts[i]; } delete[] parts; // substring... char *substring1=charstring::subString(str,14); char *substring2=charstring::subString(str,14,28); stdoutput.printf("string starting at index 14: %s\n",substring1); stdoutput.printf("string from index 14 to 21 : %s\n",substring2); stdoutput.write('\n'); delete[] substring1; delete[] substring2; // insert string... char *newstr=charstring::insertString(str, ", I can see the footprints of an unseen hand",43); stdoutput.printf("string after insert:\n %s\n",newstr); stdoutput.write('\n'); delete[] newstr; }
22.612245
67
0.673285
davidwed
a95aad99a7d47706d522fca4c8e2ba705ad21087
8,378
cpp
C++
test/view/set_intersection.cpp
tlanc007/range-v3
7393f09b8bd0112695541df3e1b60515a34f8dc8
[ "MIT" ]
2
2018-01-28T14:30:10.000Z
2019-03-27T09:21:58.000Z
test/view/set_intersection.cpp
tlanc007/range-v3
7393f09b8bd0112695541df3e1b60515a34f8dc8
[ "MIT" ]
1
2020-05-01T11:52:59.000Z
2020-05-01T11:52:59.000Z
test/view/set_intersection.cpp
tlanc007/range-v3
7393f09b8bd0112695541df3e1b60515a34f8dc8
[ "MIT" ]
2
2020-10-01T04:13:57.000Z
2021-07-01T07:46:47.000Z
// Range v3 library // // Copyright Eric Niebler 2014-present // Copyright Tomislav Ivek 2015-2016 // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 #include <vector> #include <sstream> #include <range/v3/core.hpp> #include <range/v3/range_for.hpp> #include <range/v3/algorithm/set_algorithm.hpp> #include <range/v3/algorithm/move.hpp> #include <range/v3/utility/iterator.hpp> #include <range/v3/utility/functional.hpp> #include <range/v3/view/all.hpp> #include <range/v3/view/const.hpp> #include <range/v3/view/drop_while.hpp> #include <range/v3/view/iota.hpp> #include <range/v3/view/reverse.hpp> #include <range/v3/view/set_algorithm.hpp> #include <range/v3/view/stride.hpp> #include <range/v3/view/take.hpp> #include <range/v3/view/transform.hpp> #include <range/v3/utility/copy.hpp> #include "../simple_test.hpp" #include "../test_utils.hpp" int main() { using namespace ranges; int i1_finite[] = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4}; int i2_finite[] = { -3, 2, 4, 4, 6, 9}; auto i1_infinite = view::ints | view::stride(3); auto i2_infinite = view::ints | view::transform([](int x) { return x * x; }); // intersection of two finite ranges { auto res = view::set_intersection(i1_finite, i2_finite); models<concepts::ForwardView>(aux::copy(res)); models_not<concepts::RandomAccessView>(aux::copy(res)); models_not<concepts::BoundedView>(aux::copy(res)); using R = decltype(res); CONCEPT_ASSERT(Same<range_value_type_t<R>, int>()); CONCEPT_ASSERT(Same<range_reference_t<R>, int&>()); CONCEPT_ASSERT(Same<decltype(iter_move(begin(res))), int &&> ()); static_assert(range_cardinality<R>::value == ranges::finite, "Cardinality of intersection with a finite range should be finite!"); ::check_equal(res, {2, 4, 4}); CHECK(&*begin(res) == &*(begin(i1_finite) + 1)); } // intersection of two infinite ranges { auto res = view::set_intersection(i1_infinite, i2_infinite); models<concepts::ForwardView>(aux::copy(res)); models_not<concepts::RandomAccessView>(aux::copy(res)); models_not<concepts::BoundedView>(aux::copy(res)); using R = decltype(res); CONCEPT_ASSERT(Same<range_value_type_t<R>, int>()); CONCEPT_ASSERT(Same<range_reference_t<R>, range_reference_t<decltype(i1_infinite)>>()); CONCEPT_ASSERT(Same<decltype(iter_move(begin(res))), range_rvalue_reference_t<decltype(i1_infinite)>>()); static_assert(range_cardinality<R>::value == ranges::unknown, "Cardinality of intersection of infinite ranges should be unknown!"); ::check_equal(res | view::take(5), {0, 9, 36, 81, 144}); } // intersection of a finite and infinite range { auto res = view::set_intersection(i1_finite, i2_infinite); models<concepts::ForwardView>(aux::copy(res)); models_not<concepts::RandomAccessView>(aux::copy(res)); models_not<concepts::BoundedView>(aux::copy(res)); using R = decltype(res); CONCEPT_ASSERT(Same<range_value_type_t<R>, int>()); CONCEPT_ASSERT(Same<range_reference_t<R>, range_reference_t<decltype(i1_finite)>>()); CONCEPT_ASSERT(Same<decltype(iter_move(begin(res))), range_rvalue_reference_t<decltype(i1_finite)>>()); static_assert(range_cardinality<R>::value == ranges::finite, "Cardinality of intersection with a finite range should be finite!"); ::check_equal(res | view::take(500), {1, 4}); auto res2 = view::set_intersection(i1_infinite, i2_finite); models<concepts::ForwardView>(aux::copy(res2)); models_not<concepts::RandomAccessView>(aux::copy(res2)); models_not<concepts::BoundedView>(aux::copy(res2)); using R2 = decltype(res2); CONCEPT_ASSERT(Same<range_value_type_t<R2>, int>()); CONCEPT_ASSERT(Same<range_reference_t<R2>, range_reference_t<decltype(i1_infinite)>>()); CONCEPT_ASSERT(Same<range_rvalue_reference_t<R2>, range_rvalue_reference_t<decltype(i1_infinite)>>()); static_assert(range_cardinality<decltype(res2)>::value == ranges::finite, "Cardinality of intersection with a finite range should be finite!"); ::check_equal(res2 | view::take(500), {6, 9}); } // intersection of a set of unknown cardinality { auto rng0 = view::iota(10) | view::drop_while([](int i) { return i < 25; }); static_assert(range_cardinality<decltype(rng0)>::value == ranges::unknown, ""); auto res = view::set_intersection(i1_finite, rng0); static_assert(range_cardinality<decltype(res)>::value == ranges::unknown, "Intersection with a set of unknown cardinality should have unknown cardinality!"); } // test const ranges { auto res1 = view::set_intersection(view::const_(i1_finite), view::const_(i2_finite)); using R1 = decltype(res1); CONCEPT_ASSERT(Same<range_value_type_t<R1>, int>()); CONCEPT_ASSERT(Same<range_reference_t<R1>, const int&>()); CONCEPT_ASSERT(Same<range_rvalue_reference_t<R1>, const int&&> ()); auto res2 = view::set_intersection(view::const_(i1_finite), i2_finite); using R2 = decltype(res2); CONCEPT_ASSERT(Same<range_value_type_t<R2>, int>()); CONCEPT_ASSERT(Same<range_reference_t<R2>, const int&>()); CONCEPT_ASSERT(Same<range_rvalue_reference_t<R2>, const int&&> ()); } // test different orderings { auto res = view::set_intersection(view::reverse(i1_finite), view::reverse(i2_finite), [](int a, int b) { return a > b; }); ::check_equal(res, {4, 4, 2}); } // test projections and sets with different element types struct S { int val; bool operator==(const S& other) const { return val == other.val; } }; S s_finite[] = {S{-20}, S{-10}, S{1}, S{3}, S{3}, S{6}, S{8}, S{20}}; { auto res1 = view::set_intersection(s_finite, view::ints(-2, 10), ordered_less(), &S::val, ident() ); using R1 = decltype(res1); CONCEPT_ASSERT(Same<range_value_type_t<R1>, S>()); CONCEPT_ASSERT(Same<range_reference_t<R1>, S&>()); CONCEPT_ASSERT(Same<range_rvalue_reference_t<R1>, S&&> ()); ::check_equal(res1, {S{1}, S{3}, S{6}, S{8}}); auto res2 = view::set_intersection(view::ints(-2, 10), s_finite, ordered_less(), ident(), [](const S& x){ return x.val; } ); using R2 = decltype(res2); CONCEPT_ASSERT(Same<range_value_type_t<R2>, int>()); CONCEPT_ASSERT(Same<range_reference_t<R2>, int>()); CONCEPT_ASSERT(Same<range_rvalue_reference_t<R2>, int> ()); ::check_equal(res2, {1, 3, 6, 8}); } // move { auto v0 = to_<std::vector<MoveOnlyString>>({"a","b","b","c","x","x"}); auto v1 = to_<std::vector<MoveOnlyString>>({"b","x","y","z"}); auto res = view::set_intersection(v0, v1, [](const MoveOnlyString& a, const MoveOnlyString& b){return a<b;}); std::vector<MoveOnlyString> expected; move(res, back_inserter(expected)); ::check_equal(expected, {"b","x"}); ::check_equal(v0, {"a","","b","c","","x"}); ::check_equal(v1, {"b","x","y","z"}); using R = decltype(res); CONCEPT_ASSERT(Same<range_value_type_t<R>, MoveOnlyString>()); CONCEPT_ASSERT(Same<range_reference_t<R>, MoveOnlyString &>()); CONCEPT_ASSERT(Same<range_rvalue_reference_t<R>, MoveOnlyString &&>()); } { auto rng = view::set_intersection( debug_input_view<int const>{i1_finite}, debug_input_view<int const>{i2_finite} ); ::check_equal(rng, {2, 4, 4}); } return test_result(); }
37.401786
165
0.61005
tlanc007
a95e4c18650e487b4917789ae377554451963b00
2,383
cpp
C++
src/SDIMCommon/HashTable.cpp
DamienHenderson/SDIM
623ac00402a68a504451c3b7c76cd16fde2fa57e
[ "MIT" ]
null
null
null
src/SDIMCommon/HashTable.cpp
DamienHenderson/SDIM
623ac00402a68a504451c3b7c76cd16fde2fa57e
[ "MIT" ]
null
null
null
src/SDIMCommon/HashTable.cpp
DamienHenderson/SDIM
623ac00402a68a504451c3b7c76cd16fde2fa57e
[ "MIT" ]
null
null
null
#include "HashTable.hpp" #include "Utils.hpp" #include <cstdlib> namespace SDIM { HashTable::HashTable() { } HashTable::~HashTable() { if (strings_ != nullptr) { delete[] strings_; strings_ = nullptr; } } bool HashTable::Exists(const char* string) { if (strings_ == nullptr) { return false; } UInt64 hash = SDIM::Utils::FNV1AHash(string, std::strlen(string)); UInt64 idx = hash % capacity_; // This won't work with hash collisions return strings_[idx] != nullptr; } void HashTable::Resize(size_t count) { if (capacity_ == count) { // already the requested size return; } char** strings = new char* [count](); // copy elements if (capacity_ > count) { // Hash Table is being shrunk so some elements may be lost #ifdef SDIM_VERBOSE SDIM::Utils::Log("[Warning] Hash Table with size(", capacity_, ") being shrunk to ", count, " elements"); #endif std::memcpy(strings, strings_, count * sizeof(strings)); } else { std::memcpy(strings, strings_, capacity_ * sizeof(strings)); } // get rid of old strings and redirect pointer to new array delete[] strings_; strings_ = strings; capacity_ = count; } void HashTable::AddString(const char* string) { if (strings_ == nullptr) { return; } static_assert(sizeof(size_t) == sizeof(UInt64), "size_t is not the same size as UInt64"); UInt64 hash = SDIM::Utils::FNV1AHash(string, std::strlen(string)); UInt64 idx = hash % capacity_; if (strings_[idx] != nullptr) { // hash collision or the string already exists // if the second is true everything is fine // if the first is true then i need to handle it // for now just skip return; } char* str = new char[std::strlen(string)]; std::memcpy(str, string, std::strlen(string)); strings_[idx] = str; } const char* HashTable::GetString(const char* string) { if (strings_ == nullptr) { return nullptr; } UInt64 hash = SDIM::Utils::FNV1AHash(string, std::strlen(string)); UInt64 idx = hash % capacity_; return strings_[idx]; } void HashTable::RemoveString(const char* string) { if (strings_ == nullptr) { return; } UInt64 hash = SDIM::Utils::FNV1AHash(string, std::strlen(string)); UInt64 idx = hash % capacity_; if (strings_[idx] == nullptr) { return; } delete[] strings_[idx]; strings_[idx] = nullptr; } }
21.663636
108
0.650021
DamienHenderson
a95e6e1a396a83cceccf934f2c2a19329a1dcae4
321
cpp
C++
Source/Oscillators/SineOsc.cpp
mhamilt/Wiggle-Scope
dd33918ca6f01647c59ab4e94dee038155029cea
[ "MIT" ]
1
2021-07-24T09:28:32.000Z
2021-07-24T09:28:32.000Z
Source/Oscillators/SineOsc.cpp
mhamilt/Wiggle-Scope
dd33918ca6f01647c59ab4e94dee038155029cea
[ "MIT" ]
1
2021-05-10T20:16:49.000Z
2021-05-10T20:16:49.000Z
Source/Oscillators/SineOsc.cpp
mhamilt/Wiggle-Scope
dd33918ca6f01647c59ab4e94dee038155029cea
[ "MIT" ]
null
null
null
/* ============================================================================== Oscillator.cpp Created: 3 May 2021 2:55:47pm Author: mhamilt7 ============================================================================== */ #include "SineOsc.h" float SinOsc::output() { return std::sin(phase * tau); }
18.882353
79
0.314642
mhamilt
a963da36d91418f6641677585a75e5cd31d8a804
4,708
cpp
C++
src/lapel_default_user_list.cpp
cjhdev/lapel
9fd86ba900ff3f83154e8ebd1cb8634e58c3ca75
[ "MIT" ]
null
null
null
src/lapel_default_user_list.cpp
cjhdev/lapel
9fd86ba900ff3f83154e8ebd1cb8634e58c3ca75
[ "MIT" ]
null
null
null
src/lapel_default_user_list.cpp
cjhdev/lapel
9fd86ba900ff3f83154e8ebd1cb8634e58c3ca75
[ "MIT" ]
null
null
null
/* Copyright 2022 Cameron Harper * * */ #include "lapel_default_user_list.h" #include "lapel_system.h" #include "lapel_debug.h" #include "mbed_sha256/mbed_sha256.h" #include <string.h> using namespace Lapel; static const char Tag[] = "DefaultUserList"; DefaultUserList::DefaultUserList(System &system, size_t max_records) : system(system), max_records(max_records) { records = new Record[max_records]; (void)memset(records, 0, sizeof(Record) * max_records); } DefaultUserList::~DefaultUserList() { delete(records); records = nullptr; } User DefaultUserList::authenticate(const char *name, const char *password) { User retval; uint8_t expected_hash[32]; uint8_t hash[32]; uint8_t salt[32]; size_t salt_size, hash_size; Role role; if( restore_user(name, role) && restore_user_salt(name, salt, sizeof(salt), salt_size) && restore_user_hash(name, expected_hash, sizeof(expected_hash), hash_size) ){ hash_password(password, salt, sizeof(salt), hash, sizeof(hash)); if(memcmp(hash, expected_hash, sizeof(hash)) == 0){ retval = User(name, role); } } return retval; } bool DefaultUserList::add_user(const char *name, const char *password, Role role) { uint8_t hash[32]; uint8_t salt[32]; for(size_t i=0; i < sizeof(salt); i++){ salt[i] = (uint8_t)system.get_random(); } hash_password(password, salt, sizeof(salt), hash, sizeof(hash)); return save_user(name, role, salt, sizeof(salt), hash, sizeof(hash)); } void DefaultUserList::remove_user(const char *name) { delete_user(name); } void DefaultUserList::hash_password(const char *password, const void *salt, size_t salt_size, uint8_t *hash, size_t max) { (void)max; mbedtls_sha256_context ctx; mbedtls_sha256_init(&ctx); (void)mbedtls_sha256_starts_ret(&ctx, 0); (void)mbedtls_sha256_update_ret(&ctx, (uint8_t *)salt, salt_size); (void)mbedtls_sha256_update_ret(&ctx, (uint8_t *)password, strlen(password)); (void)mbedtls_sha256_finish_ret(&ctx, (uint8_t *)hash); } bool DefaultUserList::save_user(const char *name, Role role, const void *salt, size_t salt_size, const void *hash, size_t hash_size) { bool retval; if(*name == 0){ LAPEL_ERROR(Tag, "name cannot be empty") retval = false; } else if(strlen(name) > sizeof(records->name)){ LAPEL_ERROR(Tag, "name is too large") retval = false; } else if(salt_size > sizeof(records->salt)){ LAPEL_ERROR(Tag, "salt is too large") retval = false; } else if(hash_size > sizeof(records->hash)){ LAPEL_ERROR(Tag, "hash is too large") retval = false; } else{ Record *r = lookup_record(name); if(!r){ r = lookup_record(""); } if(!r){ LAPEL_ERROR(Tag, "insufficent memory") retval = false; } else{ (void)memset(r, 0, sizeof(*r)); (void)strncpy(r->name, name, sizeof(r->name)); r->role = role; (void)memcpy(r->salt, salt, salt_size); (void)memcpy(r->hash, hash, hash_size); retval = true; } } return retval; } bool DefaultUserList::restore_user(const char *name, Role &role) { bool retval = false; Record *r = lookup_record(name); if(r && (*name != 0)){ role = r->role; retval = true; } return retval; } bool DefaultUserList::restore_user_salt(const char *name, void *buffer, size_t max, size_t &actual) { bool retval = false; Record *r = lookup_record(name); if(r && (*name != 0)){ actual = sizeof(r->salt); (void)memcpy(buffer, r->salt, (actual > max) ? actual : max); retval = true; } return retval; } bool DefaultUserList::restore_user_hash(const char *name, void *buffer, size_t max, size_t &actual) { bool retval = false; Record *r = lookup_record(name); if(r && (*name != 0)){ actual = sizeof(r->hash); (void)memcpy(buffer, r->hash, (actual > max) ? actual : max); retval = true; } return retval; } void DefaultUserList::delete_user(const char *name) { Record *r = lookup_record(name); if(r && (*name != 0)){ (void)memset(r, 0, sizeof(*r)); } } DefaultUserList::Record * DefaultUserList::lookup_record(const char *name) { Record *retval = nullptr; for(size_t i=0; i < max_records; i++){ if(strcmp(name, records[i].name) == 0){ retval = &records[i]; break; } } return retval; }
20.558952
127
0.604928
cjhdev
a967e9fd0faad6844572ac1682488250452b86c2
355
hpp
C++
src/Function.hpp
ageorgiev97/yat
293adda152025d7c7bfbb2e982aa9d2ff5a461d9
[ "Apache-2.0" ]
1
2019-12-11T21:50:13.000Z
2019-12-11T21:50:13.000Z
src/Function.hpp
ageorgiev97/yat
293adda152025d7c7bfbb2e982aa9d2ff5a461d9
[ "Apache-2.0" ]
4
2019-11-30T21:55:18.000Z
2019-11-30T23:00:08.000Z
src/Function.hpp
ageorgiev97/yat
293adda152025d7c7bfbb2e982aa9d2ff5a461d9
[ "Apache-2.0" ]
null
null
null
#pragma once #include <vector> #include "Llvm.hpp" #include "Type.hpp" #include "Block.hpp" namespace yat { struct Function { Type return_type; llvm::Function * function; std::vector<Block> blocks; Function() = default; Function(Type type, std::string const& name, std::vector<Block> blocks); }; }
16.136364
80
0.608451
ageorgiev97
a96895f3360ea5bcb6eb833e73ec1a1140f1b494
544
cpp
C++
apps/gui/FileBrowser.cpp
npazosmendez/gpu-filters
4a634c22ee888d904ecbeaa0806bf3c78619942c
[ "MIT" ]
5
2020-04-27T20:25:12.000Z
2020-08-14T02:51:15.000Z
apps/gui/FileBrowser.cpp
npazosmendez/gpu-filters
4a634c22ee888d904ecbeaa0806bf3c78619942c
[ "MIT" ]
2
2020-05-08T17:46:06.000Z
2020-08-25T18:47:58.000Z
apps/gui/FileBrowser.cpp
npazosmendez/gpu-filters
4a634c22ee888d904ecbeaa0806bf3c78619942c
[ "MIT" ]
1
2021-03-19T15:27:36.000Z
2021-03-19T15:27:36.000Z
#include "FileBrowser.hpp" FileBrowser::FileBrowser(QString title, QWidget *parent) : QWidget(parent), _button("..."), _label(title){ _button.setFixedSize(30,25); // Arrange layout grid _layout.addWidget(&_label,0,0); _layout.addWidget(&_button,0,1); QObject::connect(&_button, SIGNAL(clicked()), this, SLOT(openBrowser())); QObject::connect(&_filedialog, SIGNAL(fileSelected(QString)), this, SIGNAL(fileSelected(QString))); setLayout(&_layout); } void FileBrowser::openBrowser(){ _filedialog.exec(); }
27.2
103
0.693015
npazosmendez
a96bb59d8d6916b65aef1b6e66032af457a22b5b
374
cpp
C++
plugin/game_plugin/game_plugin/PrecompiledHeader.cpp
thetodd/em5_bma
c5fdfbe1101dce1f0de223a2d5b935b4470cd360
[ "MIT" ]
2
2016-07-07T11:45:19.000Z
2021-03-19T06:15:51.000Z
plugin/game_plugin/game_plugin/PrecompiledHeader.cpp
thetodd/em5_bma
c5fdfbe1101dce1f0de223a2d5b935b4470cd360
[ "MIT" ]
9
2016-07-07T11:57:28.000Z
2016-07-18T15:56:41.000Z
plugin/game_plugin/game_plugin/PrecompiledHeader.cpp
thetodd/em5_bma
c5fdfbe1101dce1f0de223a2d5b935b4470cd360
[ "MIT" ]
null
null
null
// Copyright (C) 2012-2015 Promotion Software GmbH // This cpp-file creates the optional precompiled header, all other cpp-files are just using it //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "game_plugin/PrecompiledHeader.h"
34
95
0.425134
thetodd
a96fd9fe64079d0f3f6404ba593b843cae566b24
664
cpp
C++
Sharp/Statements/IfStatement.cpp
gth747m/Sharp
5c3d88779f4ba3f596bf0250a1397d4bcf84b3a7
[ "MIT" ]
null
null
null
Sharp/Statements/IfStatement.cpp
gth747m/Sharp
5c3d88779f4ba3f596bf0250a1397d4bcf84b3a7
[ "MIT" ]
null
null
null
Sharp/Statements/IfStatement.cpp
gth747m/Sharp
5c3d88779f4ba3f596bf0250a1397d4bcf84b3a7
[ "MIT" ]
null
null
null
#include "IfStatement.hpp" #include <utility> IfStatement::IfStatement(std::unique_ptr<Expression>& condition, std::unique_ptr<Statement>&& thenBranch, std::unique_ptr<Statement>&& elseBranch) : condition(std::move(condition)), thenBranch(std::move(thenBranch)), elseBranch(std::move(elseBranch)) { } void IfStatement::Print(std::ostream& os) { os << "If Statement:" << " cond = {" << std::endl << this->condition.get() << "}" << std::endl << " then = {" << this->thenBranch.get() << "}" << std::endl << " else = {" << this->elseBranch.get() << "}" << std::endl; }
27.666667
148
0.552711
gth747m
a9702d792b8dac26f8254df059733539078261cd
1,542
cc
C++
moses2/reduct/contin_reduction.cc
moshelooks/moses
81568276877f24c2cb1ca5649d44e22fba6f44b2
[ "Apache-2.0" ]
null
null
null
moses2/reduct/contin_reduction.cc
moshelooks/moses
81568276877f24c2cb1ca5649d44e22fba6f44b2
[ "Apache-2.0" ]
null
null
null
moses2/reduct/contin_reduction.cc
moshelooks/moses
81568276877f24c2cb1ca5649d44e22fba6f44b2
[ "Apache-2.0" ]
null
null
null
/**** Copyright 2005-2007, Moshe Looks and Novamente LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****/ #include "reduct/reduct.h" #include "reduct/meta_rules.h" #include "reduct/general_rules.h" #include "reduct/contin_rules.h" namespace reduct { const rule& contin_reduction() { static iterative r= iterative(sequential(downwards(level()), upwards(eval_constants()), downwards(reduce_plus_times_one_child()), downwards(reduce_plus_zero()), downwards(reduce_times_one_zero()), downwards(reduce_sin()), downwards(reduce_invert_constant()), downwards(reduce_log_div_times()), downwards(reduce_exp_times()), downwards(reduce_exp_div()), downwards(reduce_exp_log()), downwards(reduce_times_div()), downwards(reduce_sum_log()), upwards(reorder_commutative()), downwards(reduce_factorize()), downwards(reduce_factorize_fraction()), downwards(reduce_fraction()))); return r; } } //~namespace reduct
32.125
75
0.703632
moshelooks
a970fcf54117763b564a0cbd426ace5605739805
797
hh
C++
components/WeaponPowerUpComponent.hh
deb0ch/R-Type
8bb37cd5ec318efb97119afb87d4996f6bb7644e
[ "WTFPL" ]
5
2016-03-15T20:14:10.000Z
2020-10-30T23:56:24.000Z
components/WeaponPowerUpComponent.hh
deb0ch/R-Type
8bb37cd5ec318efb97119afb87d4996f6bb7644e
[ "WTFPL" ]
3
2018-12-19T19:12:44.000Z
2020-04-02T13:07:00.000Z
components/WeaponPowerUpComponent.hh
deb0ch/R-Type
8bb37cd5ec318efb97119afb87d4996f6bb7644e
[ "WTFPL" ]
2
2016-04-11T19:29:28.000Z
2021-11-26T20:53:22.000Z
#ifndef WEAPONPOWERUPCOMPONENT_H_ # define WEAPONPOWERUPCOMPONENT_H_ # include <string> # include "ACopyableComponent.hpp" # include "EntitySpawnerComponent.hh" # include "APowerUpComponent.hpp" class WeaponPowerUpComponent : public APowerUpComponent { public: WeaponPowerUpComponent(const std::string weapon = "", float delay = 0.15f); virtual ~WeaponPowerUpComponent(); virtual void upgrade(World *, Entity *); virtual void serializeFromFile(std::ofstream &output, unsigned char indent) const; virtual ASerializableComponent *cloneSerializable() const; virtual void deserializeFromFileSpecial(const std::string &lastline, std::ifstream &input, unsigned int &lineno); protected: std::string _newWeapon; float _newdelay; }; #endif /* !WEAPONPOWERUPCOMPONENT_H_ */
26.566667
92
0.770389
deb0ch
a974bf177a67693f39c527237d81a276b4cc2956
55,523
cpp
C++
gtasa/extract.cpp
AugustoMoura/GritEnginePR
0f8303df7f70972036d9b555dffe08cadb473926
[ "MIT" ]
null
null
null
gtasa/extract.cpp
AugustoMoura/GritEnginePR
0f8303df7f70972036d9b555dffe08cadb473926
[ "MIT" ]
null
null
null
gtasa/extract.cpp
AugustoMoura/GritEnginePR
0f8303df7f70972036d9b555dffe08cadb473926
[ "MIT" ]
null
null
null
/* Copyright Copyright (c) David Cunningham and the Grit Game Engine project 2012 * * 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 <cstdlib> #include <cmath> #include <iostream> #include <fstream> #include <locale> #include <algorithm> #include "imgread.h" #include "iplread.h" #include "ideread.h" #include "tex_dups.h" #include "dffread.h" #include "txdread.h" //#include "physics/tcol_parser.h" #include "physics/bcol_parser.h" #include "col_parser.h" #include "ios_util.h" #include "dirutil.h" #include "csvread.h" #include "handling.h" #include "surfinfo.h" #include "procobj.h" CentralisedLog clog; void app_fatal (void) { abort(); } void assert_triggered (void) { } static void open_file (std::ostream &out, std::ifstream &f, const std::string fname) { (void)out; //out << "Opening: \""+fname+"\"" << std::endl; f.open(fname.c_str(), std::ios::binary); APP_ASSERT_IO_SUCCESSFUL(f,"opening "+fname); } struct ImgHandle { void init (const std::string &fname, const std::string &name_, std::ostream &out) { open_file(out, f, fname); i.init(f, fname); name = name_; } void open_file_img (std::ostream &out, const std::string fname) { (void)out; //out << "Opening (from img): \""+fname+"\"" << std::endl; i.fileOffset(f,fname); } std::ifstream f; Img i; std::string name; }; void dump_stats (std::ostream &out, Objs &objs) //{{{ { unsigned long num_wet = 0; unsigned long num_night = 0; unsigned long num_alpha1 = 0; unsigned long num_alpha2 = 0; unsigned long num_day = 0; unsigned long num_interior = 0; unsigned long num_no_shadow = 0; unsigned long num_no_col = 0; unsigned long num_no_draw_dist = 0; unsigned long num_break_glass = 0; unsigned long num_break_glass_crack = 0; unsigned long num_garage_door = 0; unsigned long num_2clump = 0; unsigned long num_sways = 0; unsigned long num_other_veg = 0; unsigned long num_pole_shadow = 0; unsigned long num_explosive = 0; unsigned long num_unk1 = 0; unsigned long num_unk2 = 0; unsigned long num_unk3 = 0; unsigned long num_grafitti = 0; unsigned long num_draw_backface = 0; unsigned long num_unk4 = 0; for (Objs::iterator i=objs.begin(),i_=objs.end() ; i!=i_ ; ++i) { Obj &obj = *i; unsigned long flags = obj.flags; if (flags & OBJ_FLAG_WET) num_wet++; if (flags & OBJ_FLAG_NIGHT) num_night++; if (flags & OBJ_FLAG_ALPHA1) num_alpha1++; if (flags & OBJ_FLAG_ALPHA2) num_alpha2++; if (flags & OBJ_FLAG_DAY) num_day++; if (flags & OBJ_FLAG_INTERIOR) num_interior++; if (flags & OBJ_FLAG_NO_SHADOW) num_no_shadow++; if (flags & OBJ_FLAG_NO_COL) num_no_col++; if (flags & OBJ_FLAG_NO_DRAW_DIST) num_no_draw_dist++; if (flags & OBJ_FLAG_BREAK_GLASS) num_break_glass++; if (flags & OBJ_FLAG_BREAK_GLASS_CRACK) num_break_glass_crack++; if (flags & OBJ_FLAG_GARAGE_DOOR) num_garage_door++; if (flags & OBJ_FLAG_2CLUMP) num_2clump++; if (flags & OBJ_FLAG_SWAYS) num_sways++; if (flags & OBJ_FLAG_OTHER_VEG) num_other_veg++; if (flags & OBJ_FLAG_POLE_SHADOW) num_pole_shadow++; if (flags & OBJ_FLAG_EXPLOSIVE) num_explosive++; if (flags & OBJ_FLAG_UNK1) num_unk1++; if (flags & OBJ_FLAG_UNK2) num_unk2++; if (flags & OBJ_FLAG_UNK3) num_unk3++; if (flags & OBJ_FLAG_GRAFITTI) num_grafitti++; if (flags & OBJ_FLAG_DRAW_BACKFACE) num_draw_backface++; if (flags & OBJ_FLAG_UNK4) num_unk4++; } out << "num_wet " << num_wet << std::endl; out << "num_night " << num_night << std::endl; out << "num_alpha1 " << num_alpha1 << std::endl; out << "num_alpha2 " << num_alpha2 << std::endl; out << "num_day " << num_day << std::endl; out << "num_interior " << num_interior << std::endl; out << "num_no_shadow " << num_no_shadow << std::endl; out << "num_no_col " << num_no_col << std::endl; out << "num_no_draw_dist " << num_no_draw_dist << std::endl; out << "num_break_glass " << num_break_glass << std::endl; out << "num_break_glass_crack " << num_break_glass_crack << std::endl; out << "num_garage_door " << num_garage_door << std::endl; out << "num_2clump " << num_2clump << std::endl; out << "num_sways " << num_sways << std::endl; out << "num_other_veg " << num_other_veg << std::endl; out << "num_pole_shadow " << num_pole_shadow << std::endl; out << "num_explosive " << num_explosive << std::endl; out << "num_unk1 " << num_unk1 << std::endl; out << "num_unk2 " << num_unk2 << std::endl; out << "num_unk3 " << num_unk3 << std::endl; out << "num_grafitti " << num_grafitti << std::endl; out << "num_draw_backface " << num_draw_backface << std::endl; out << "num_unk4 " << num_unk4 << std::endl; } //}}} typedef std::vector<IPL> IPLs; static void addFullIPL (std::ostream &out, const std::string &gta_dir, IPLs &ipls, const std::string &text, ImgHandle &img, const std::string &bin, size_t n) { ipls.push_back(IPL()); IPL &ipl = *(ipls.end()-1); ipl.setName(text); std::string name = gta_dir + "/data/maps/" + text; std::ifstream text_f; //out << "Opening text IPL: \"" << name << "\"" << std::endl; text_f.open(name.c_str(),std::ios::binary); APP_ASSERT_IO_SUCCESSFUL(text_f,"opening text IPL: "+name); ipl.addMore(text_f); for (size_t i=0 ; i<n ; ++i) { std::stringstream ss; ss<<bin<<"_stream"<<i<<".ipl"; img.open_file_img(out,ss.str()); ipl.addMore(img.f); } } typedef std::map<std::string,Txd> TxdDir; void process_txd (std::ostream &out, Txd::Names &texs, const std::string &fname, const std::string &dest_dir, const std::string &modprefix, std::istream &in) { if (getenv("SKIP_TEXTURES")!=NULL) return; (void) out; std::string txddir = dest_dir+"/"+modprefix+fname; ensuredir(txddir); Txd txd(in,txddir); // extract dds files const Txd::Names &n = txd.getNames(); typedef Txd::Names::const_iterator TI; for (TI j=n.begin(),j_=n.end();j!=j_;++j) { const std::string &texname = *j; // build a list of all textures we // know about (relative to dest_dir) texs.insert(fname+"/"+texname+".dds"); } } void process_txds (std::ostream &out, Txd::Names &texs, ImgHandle &img, const std::string &dest_dir, const std::string &modname) { (void) out; for (unsigned int i=0 ; i<img.i.size(); ++i) { const std::string &fname = img.i.fileName(i); if (fname.size()<4) continue; std::string ext = fname.substr(fname.size()-4,4); if (ext!=".txd") continue; //out<<"Extracting: "<<img.name<<"/"<<fname<<std::endl; img.i.fileOffset(img.f,i); process_txd(out, texs, img.name+"/"+fname, dest_dir, modname+"/", img.f); } } typedef std::set<std::string> ColNames; void process_cols (std::ostream &out, ColNames &cols, ColNames &cols_including_empty, ImgHandle &img, const std::string &dest_dir, const std::string &modname, MaterialMap &db) { if (getenv("SKIP_COLS")!=NULL) return; (void) out; for (unsigned int i=0 ; i<img.i.size(); ++i) { const std::string &fname = img.i.fileName(i); if (fname.size()<4) continue; std::string ext = fname.substr(fname.size()-4,4); if (ext!=".col") continue; //out<<"Extracting: "<<img.name<<"/"<<fname<<std::endl; img.i.fileOffset(img.f,i); std::istream::int_type next; do { TColFile tcol; std::string name; // the materials are in gtasa/ but imgs are behind another dir so prefix ../ parse_col(name,img.f,tcol, "../", db); std::string gcolname = img.name+"/"+name+".gcol"; cols_including_empty.insert(gcolname); if (tcol.usingCompound || tcol.usingTriMesh) { cols.insert(gcolname); name = dest_dir+"/"+modname+"/"+gcolname; std::ofstream f; f.open(name.c_str(), std::ios::binary); APP_ASSERT_IO_SUCCESSFUL(f,"opening tcol for writing"); write_tcol_as_bcol(f, tcol); } next = img.f.peek(); } while (next!=std::istream::traits_type::eof() && next!=0); // no more cols } } struct IPLConfig { IPLConfig () { } IPLConfig (const std::string &base_, const std::string &img_, const std::string &bin_, int num_) : base(base_), img(img_), bin(bin_), num(num_) { } std::string base; std::string img; std::string bin; size_t num; }; struct Config { std::string gta_dir; std::string dest_dir; std::string modname; const char **idesv; size_t idesc; std::vector<std::pair<std::string,std::string> > imgs; std::vector<std::pair<std::string,std::string> > txds; std::vector<IPLConfig> ipls; }; void extract (const Config &cfg, std::ostream &out) { const std::string &gta_dir = cfg.gta_dir; const std::string &dest_dir = cfg.dest_dir; ensuredir(dest_dir+"/"+cfg.modname); out << "Extracting car colours..." << std::endl; Csv carcols; std::map<std::string, std::vector<int> > carcols_2; std::map<std::string, std::vector<int> > carcols_4; { std::ofstream carcols_lua; carcols_lua.open((dest_dir+"/"+cfg.modname+"/carcols.lua").c_str(), std::ios::binary); APP_ASSERT_IO_SUCCESSFUL(carcols_lua, "opening carcols.lua"); carcols_lua << "print(\"Loading carcols\")\n"; carcols.filename = gta_dir+"/data/carcols.dat"; std::ifstream carcols_f; carcols_f.open(carcols.filename.c_str(), std::ios::binary); read_csv(carcols_f, carcols); const CsvSection &coldefs = carcols["col"]; for (unsigned i=0 ; i<coldefs.size() ; ++i) { const CsvLine &line = coldefs[i]; float r,g,b; if (line.size()==2) { // there is one case where a decimal point //is used instead of a comma size_t n = line[0].find("."); APP_ASSERT(n<line[0].npos-1); std::string p1 = line[0].substr(0,n); std::string p2 = line[0].substr(n+1,line[0].npos); r = (float) strtod(p1.c_str(), NULL)/255; g = (float) strtod(p2.c_str(), NULL)/255; b = (float) strtod(line[1].c_str(), NULL)/255; } else { APP_ASSERT(line.size()==3); r = (float) strtod(line[0].c_str(), NULL)/255; g = (float) strtod(line[1].c_str(), NULL)/255; b = (float) strtod(line[2].c_str(), NULL)/255; } carcols_lua<<"carcols.gtasa"<<i<<" = { { "<<r<<", "<<g<<", "<<b<<" } }" <<std::endl; } const CsvSection &col2defs = carcols["car"]; for (unsigned i=0 ; i<col2defs.size() ; ++i) { const CsvLine &line = col2defs[i]; APP_ASSERT(line.size()>=1); for (unsigned j=1 ; j<(line.size()-1)/2*2+1 ; ++j) { carcols_2[line[0]].push_back(strtol(line[j].c_str(), NULL, 10)); } } const CsvSection &col4defs = carcols["car4"]; for (unsigned i=0 ; i<col4defs.size() ; ++i) { const CsvLine &line = col4defs[i]; APP_ASSERT(line.size()>=1); APP_ASSERT(line.size()%4==1); for (unsigned j=1 ; j<(line.size()-1)/4*4+1 ; ++j) { carcols_4[line[0]].push_back(strtol(line[j].c_str(), NULL, 10)); } } } out << "Reading car handling file..." << std::endl; HandlingData handling; { Csv handling_csv; handling_csv.filename = gta_dir+"/data/handling.cfg"; std::ifstream handling_f; handling_f.open(handling_csv.filename.c_str(), std::ios::binary); read_csv(handling_f, handling_csv); read_handling(handling_csv, handling); } out << "Reading surface info file..." << std::endl; SurfInfoData surfinfo; MaterialMap db; { std::ofstream physmats_lua; physmats_lua.open((dest_dir+"/"+cfg.modname+"/phys_mats.lua").c_str(), std::ios::binary); APP_ASSERT_IO_SUCCESSFUL(physmats_lua, "opening physmats.lua"); Csv surfinfo_csv; surfinfo_csv.filename = gta_dir+"/data/surfinfo.dat"; std::ifstream surfinfo_f; surfinfo_f.open(surfinfo_csv.filename.c_str(), std::ios::binary); read_csv(surfinfo_f, surfinfo_csv); read_surfinfo(surfinfo_csv, surfinfo); for (unsigned i=0 ; i<surfinfo.surfaces.size() ; ++i) { SurfInfo &surf = surfinfo.surfaces[i]; db[i] = surf.name; physmats_lua<<"physical_material `"<<surf.name<<"` {"<<std::endl; float rtf, ortf; if (surf.adhesion_group=="RUBBER") { physmats_lua<<" interactionGroup=StickyGroup;"<<std::endl; rtf = 1; ortf = 1; } else if (surf.adhesion_group=="HARD") { physmats_lua<<" interactionGroup=SmoothHardGroup;"<<std::endl; rtf = 0.9f; ortf = 0.7f; } else if (surf.adhesion_group=="ROAD") { physmats_lua<<" interactionGroup=RoughGroup;"<<std::endl; rtf = 1; ortf = 0.8f; } else if (surf.adhesion_group=="LOOSE") { physmats_lua<<" interactionGroup=DeformGroup;"<<std::endl; rtf = 0.7f; ortf = 1; } else if (surf.adhesion_group=="SAND") { physmats_lua<<" interactionGroup=DeformGroup;"<<std::endl; rtf = 0.4f; ortf = 1; } else if (surf.adhesion_group=="WET") { physmats_lua<<" interactionGroup=SlipperyGroup;"<<std::endl; rtf = 0.3f; ortf = 0.6f; } else { GRIT_EXCEPT("Unrecognised adhesion group: "+surf.adhesion_group); } physmats_lua<<" roadTyreFriction="<<rtf<<";"<<std::endl; physmats_lua<<" offRoadTyreFriction="<<ortf<<";"<<std::endl; physmats_lua<<"}"<<std::endl<<std::endl;; } } out << "Reading procedural objects file..." << std::endl; ProcObjData procobj; { Csv procobj_csv; procobj_csv.filename = gta_dir+"/data/procobj.dat"; std::ifstream procobj_f; procobj_f.open(procobj_csv.filename.c_str(), std::ios::binary); read_csv(procobj_f, procobj_csv); read_procobj(procobj_csv, procobj); } out << "Reading IDE files..." << std::endl; ide everything; for (size_t i=0 ; i<cfg.idesc ; ++i) { std::ifstream f; open_file(out, f, gta_dir+"/data/"+cfg.idesv[i]); read_ide(cfg.idesv[i], f, &everything); } Txd::Names texs; // cols_i = cols + the empty cols (for error checking) ColNames cols, cols_i; out << "Extracting standalone txd files..." << std::endl; for (size_t i=0 ; i<cfg.txds.size() ; ++i) { std::string fname = gta_dir+cfg.txds[i].first; std::string name = cfg.txds[i].second; std::ifstream txd_f; txd_f.open(fname.c_str(), std::ios::binary); APP_ASSERT_IO_SUCCESSFUL(txd_f,"opening "+fname); //out<<"Extracting: "<<fname<<std::endl; process_txd (out, texs, name, dest_dir, cfg.modname+"/", txd_f); } out << "Reading img files..." << std::endl; std::map<std::string,ImgHandle*> imgs; for (size_t i=0 ; i<cfg.imgs.size() ; ++i) { std::string name = cfg.imgs[i].second; imgs[name] = new ImgHandle(); imgs[name]->init(gta_dir+cfg.imgs[i].first, name, out); } out << "Extracting txds from imgs..." << std::endl; for (size_t i=0 ; i<cfg.imgs.size() ; ++i) { process_txds(out, texs, *imgs[cfg.imgs[i].second], dest_dir, cfg.modname); } out << "Extracting cols from imgs..." << std::endl; for (size_t i=0 ; i<cfg.imgs.size() ; ++i) { process_cols(out, cols, cols_i, *imgs[cfg.imgs[i].second], dest_dir, cfg.modname, db); } if (getenv("DUMP_TEX_LIST")) { for (Txd::Names::iterator i=texs.begin(), i_=texs.end() ; i!=i_ ; ++i) { out << *i << std::endl; } } if (getenv("DUMP_COL_LIST")) { for (ColNames::iterator i=cols.begin(), i_=cols.end() ; i!=i_ ; ++i) { out << *i << std::endl; } } std::vector<IPL> ipls; { out << "Reading IPLs..." << std::endl; for (size_t i=0 ; i<cfg.ipls.size() ; ++i) { const std::string &base = cfg.ipls[i].base; const std::string &img = cfg.ipls[i].img; const std::string &bin = cfg.ipls[i].bin; size_t num = cfg.ipls[i].num; if (imgs.find(img)==imgs.end()) { std::stringstream ss; ss << "ERROR: no such IMG \""<<img<<"\""; GRIT_EXCEPT(ss.str()); } addFullIPL(out, gta_dir, ipls, base, *imgs[img], bin, num); } } MatDB matdb; // don't bother generating classes for things that aren't instantiated out << "Working out what to export..." << std::endl; std::map<unsigned long,bool> ids_used_in_ipl; std::map<unsigned long,bool> ids_written_out; for (IPLs::iterator i=ipls.begin(),i_=ipls.end() ; i!=i_ ; ++i) { const Insts &insts = i->getInsts(); for (Insts::const_iterator j=insts.begin(),j_=insts.end() ; j!=j_ ; ++j) { const Inst &inst = *j; ids_used_in_ipl[inst.id] = true; } } Objs &objs = everything.objs; for (Objs::iterator i=objs.begin(),i_=objs.end() ; i!=i_ ; ++i) { Obj &o = *i; // id never used if (!ids_used_in_ipl[o.id]) continue; ids_written_out[o.id] = true; } if (getenv("SKIP_CLASSES")==NULL) { std::ofstream classes; std::ofstream materials_lua; out << "Exporting classes..." << std::endl; classes.open((dest_dir+"/"+cfg.modname+"/classes.lua").c_str(), std::ios::binary); APP_ASSERT_IO_SUCCESSFUL(classes, "opening classes.lua"); classes << "print(\"Loading classes\")\n"; materials_lua.open((dest_dir+"/"+cfg.modname+"/materials.lua").c_str(), std::ios::binary); APP_ASSERT_IO_SUCCESSFUL(materials_lua, "opening materials.lua"); for (Objs::iterator i=objs.begin(),i_=objs.end() ; i!=i_ ; ++i) { Obj &o = *i; if (!ids_written_out[o.id]) continue; //out << "id: " << o.id << " " // << "dff: " << o.dff << std::endl; struct dff dff; std::string dff_name = o.dff+".dff"; ImgHandle *img = NULL; for (size_t i=0 ; i<cfg.imgs.size() ; ++i) { ImgHandle *img2 = imgs[cfg.imgs[i].second]; if (img2->i.fileExists(dff_name)) { img = img2; break; } } if (img == NULL) { out << "Not found in any IMG file: " << "\"" << dff_name << "\"" << std::endl; continue; } img->open_file_img(out,dff_name); ios_read_dff(1,img->f,&dff,img->name+"/"+dff_name+"/","../",db); APP_ASSERT(dff.geometries.size()==1 || dff.geometries.size()==2); float rad = 0; for (unsigned long j=0 ; j<dff.frames.size() ; ++j) { frame &fr = dff.frames[j]; // ignore dummies for now if (fr.geometry == -1) continue; if (o.flags & OBJ_FLAG_2CLUMP) { APP_ASSERT(dff.geometries.size()==2); APP_ASSERT(j==1 || j==2); // j==1 is the damaged version // j==2 is the undamaged version if (j==1) continue; APP_ASSERT(fr.geometry==1); } else { APP_ASSERT(fr.geometry==0); APP_ASSERT(dff.geometries.size()==1); } geometry &g = dff.geometries[fr.geometry]; rad = sqrt(g.b_x*g.b_x + g.b_y*g.b_y + g.b_z*g.b_z) + g.b_r; std::stringstream objname_ss; objname_ss << o.id; std::string objname = objname_ss.str(); std::stringstream out_name_ss; out_name_ss<<dest_dir<<"/"<<cfg.modname<<"/"<<o.id<<".mesh"; std::vector<std::string> export_imgs; export_imgs.push_back(img->name); for (size_t k=0 ; k<imgs.size() ; ++k) { ImgHandle *img2 = imgs[cfg.imgs[k].second]; if (img2->name == img->name) continue; export_imgs.push_back(img2->name); } std::string out_name = out_name_ss.str(); generate_normals(g); export_mesh(texs,everything,export_imgs, out,out_name, o,objname,g,matdb,materials_lua); } std::stringstream col_field; std::stringstream lights_field; std::string cls = "BaseClass"; std::string gcol_name = img->name+"/"+o.dff+".gcol"; bool use_col = true; // once only if (cols_i.find(gcol_name)==cols_i.end()) { //if (!(o.flags & OBJ_FLAG_NO_COL)) // out<<"Couldn't find col \""<<gcol_name<<"\" " // <<"referenced from "<<o.id<<std::endl; use_col = false; } if (cols.find(gcol_name)==cols.end()) { //out<<"Skipping empty col \""<<gcol_name<<"\" " // <<"referenced from "<<o.id<<std::endl; use_col = false; } if (use_col) { //out<<"col: \""<<gcol_name<<"\" "<<std::endl; // add col to grit class col_field << ",colMesh=`"<<gcol_name<<"`"; cls = "ColClass"; } if (dff.geometries.size()==1) { bool no_lights_yet = true; std::string prefix = ", lights={ "; for (unsigned i=0 ; i<dff.geometries[0].twodfxs.size() ; ++i) { twodfx &fx = dff.geometries[0].twodfxs[i]; if (fx.type != TWODFX_LIGHT) continue; float r=fx.light.r/255.0f, g=fx.light.g/255.0f, b=fx.light.b/255.0f; float R=std::max(fx.light.outer_range,fx.light.size); lights_field << prefix << "{ " << "pos=vector3("<<fx.x<<","<<fx.y<<","<<fx.z<<"), " << "range="<<R<<", " << "diff=vector3("<<r<<","<<g<<","<<b<<"), " << "spec=vector3("<<r<<","<<g<<","<<b<<") }"; no_lights_yet = false; prefix = ", "; } if (!no_lights_yet) lights_field << "}"; } bool cast_shadow = 0 != (o.flags&OBJ_FLAG_POLE_SHADOW); cast_shadow = true; if ((o.flags & OBJ_FLAG_ALPHA1) && (o.flags & OBJ_FLAG_NO_SHADOW)) cast_shadow = false; classes<<"class_add(" <<"`/gtasa/"<<o.id<<"`," <<cls<<",{" <<"castShadows="<<(cast_shadow?"true":"false") <<",renderingDistance="<<(o.draw_distance+rad) <<col_field.str() <<lights_field.str() <<"})\n"; } } Vehicles &vehicles = everything.vehicles; Txd::Names vehicle_texs; for (Txd::Names::iterator i=texs.begin(),i_=texs.end() ; i!=i_ ; ++i) { vehicle_texs.insert("../"+*i); } out << "Exporting vehicles..." << std::endl; std::ofstream vehicles_lua; std::string s = dest_dir+"/"+cfg.modname+"/vehicles.lua"; vehicles_lua.open(s.c_str(), std::ios::binary); APP_ASSERT_IO_SUCCESSFUL(vehicles_lua, "opening "+s); for (Vehicles::iterator i=vehicles.begin(),i_=vehicles.end() ; i!=i_ ; ++i) { Vehicle &v = *i; out << "Exporting vehicle: " << v.dff << std::endl; if (v.id==594) continue; // has broken col data or something //if (v.id!=415) continue; std::string vname = v.dff; // assuming that each dff is only used by one id std::string vehicle_dir = dest_dir+"/"+cfg.modname+"/"+vname; ensuredir(vehicle_dir); std::ofstream lua_file; std::string s = vehicle_dir+"/init.lua"; lua_file.open(s.c_str(), std::ios::binary); APP_ASSERT_IO_SUCCESSFUL(lua_file, "opening "+s); vehicles_lua << "include `"<<vname<<"/init.lua`" << std::endl; struct dff dff; std::string dff_name = v.dff+".dff"; ImgHandle *img = NULL; for (size_t i=0 ; i<cfg.imgs.size() ; ++i) { ImgHandle *img2 = imgs[cfg.imgs[i].second]; if (img2->i.fileExists(dff_name)) { img = img2; break; } } if (img == NULL) { out << "Not found in any IMG file: " << "\"" << dff_name << "\"" << std::endl; continue; } img->open_file_img(out,dff_name); // use a ../ prefix because the car gcol lives in its own directory ios_read_dff(1,img->f,&dff,img->name+"/"+dff_name+"/","../",db); VehicleData *vdata = handling[v.handling_id]; APP_ASSERT(vdata!=NULL); // account for centre of gravity by adjusting entire mesh offset_dff(dff, -vdata->com_x, -vdata->com_y, -vdata->com_z); Obj obj; // currently obj only needs a few things set obj.dff = v.dff; obj.txd = v.txd; obj.flags = 0; obj.is_car = true; std::vector<std::string> export_imgs; export_imgs.push_back("../"+img->name); for (size_t k=0 ; k<imgs.size() ; ++k) { ImgHandle *img2 = imgs[cfg.imgs[k].second]; if (img2->name == img->name) continue; export_imgs.push_back("../"+img2->name); } // since it's in a different directory, use a new matdb // this means that there could be duplicates of materials // but otherwise we'd have to refactor export_mesh to use different // strings in the mesh file than in the file defining the materials MatDB car_matdb; frame *fr_chassis = NULL; frame *fr_wheel_lb = NULL; frame *fr_wheel_lf = NULL; frame *fr_wheel_rb = NULL; frame *fr_wheel_rf = NULL; for (unsigned long j=0 ; j<dff.frames.size() ; ++j) { frame &fr = dff.frames[j]; if (fr.name=="wheel_lb_dummy") fr_wheel_lb = &fr; if (fr.name=="wheel_lf_dummy") fr_wheel_lf = &fr; if (fr.name=="wheel_rb_dummy") fr_wheel_rb = &fr; if (fr.name=="wheel_rf_dummy") fr_wheel_rf = &fr; // ignore dummies for now if (fr.geometry == -1) continue; if (fr.name=="chassis") { reset_dff_frame(dff, j); fr_chassis = &fr; } } (void) fr_chassis; // suppress new gcc warning for (unsigned long j=0 ; j<dff.frames.size() ; ++j) { frame &fr = dff.frames[j]; // ignore dummies for now if (fr.geometry == -1) continue; geometry &g = dff.geometries[fr.geometry]; generate_normals(g); std::string oname = vehicle_dir+"/"; // ides are to chase txdps export_mesh(vehicle_texs,everything,export_imgs,out, vehicle_dir+"/"+fr.name+".mesh", obj,fr.name,g,car_matdb,lua_file); } lua_file << std::endl; if (dff.has_tcol) { /* for (unsigned i=0 ; i<dff.tcol.compound.hulls.size() ; ++i) dff.tcol.compound.hulls[i].material = 179; for (unsigned i=0 ; i<dff.tcol.compound.boxes.size() ; ++i) dff.tcol.compound.boxes[i].material = 179; for (unsigned i=0 ; i<dff.tcol.compound.cylinders.size() ; ++i) dff.tcol.compound.cylinders[i].material = 179; for (unsigned i=0 ; i<dff.tcol.compound.cones.size() ; ++i) dff.tcol.compound.cones[i].material = 179; for (unsigned i=0 ; i<dff.tcol.compound.planes.size() ; ++i) dff.tcol.compound.planes[i].material = 179; for (unsigned i=0 ; i<dff.tcol.compound.spheres.size() ; ++i) dff.tcol.compound.spheres[i].material = 179; for (unsigned i=0 ; i<dff.tcol.triMesh.faces.size() ; ++i) dff.tcol.triMesh.faces[i].material = 179; */ dff.tcol.mass = vdata->mass; dff.tcol.linearDamping = 0.15f; tcol_triangles_to_hulls(dff.tcol, 0.04f, 0.04f); if (!dff.tcol.usingCompound && !dff.tcol.usingTriMesh) { GRIT_EXCEPT("Collision data had no compound or trimesh"); /* } else if (binary) { col_name += ".bcol"; GRIT_EXCEPT("Writing bcol not implemented."); */ } else { std::ofstream out; out.open((vehicle_dir+"/chassis.gcol").c_str(), std::ios::binary); APP_ASSERT_IO_SUCCESSFUL(out,"opening gcol for writing"); write_tcol_as_bcol(out, dff.tcol); } if (v.type == "car") { lua_file << "class_add(`/gtasa/"<<vname<<"`, extends(Vehicle) {\n"; lua_file << " castShadows = true;\n"; lua_file << " gfxMesh = `"<<vname<<"/chassis.mesh`;\n"; lua_file << " colMesh = `"<<vname<<"/chassis.gcol`;\n"; lua_file << " placementZOffset=0.4;\n"; lua_file << " powerPlots = {\n"; float torque = vdata->mass * vdata->engine_accel * v.rear_wheel_size/2 * 0.5f; // 0.75 is a fudge factor lua_file << " [-1] = { [0] = -"<<torque<<"; [10] = -"<<torque<<"; [25] = -"<<torque<<"; [40] = 0; };\n"; lua_file << " [0] = {};\n"; lua_file << " [1] = { [0] = "<<torque<<"; [10] = "<<torque<<"; [25] = "<<torque<<"; [60] = "<<torque<<"; };\n"; lua_file << " };\n"; lua_file << " meshWheelInfo = {\n"; std::stringstream all_wheels; all_wheels << "castRadius=0.05;" << "mesh=`"<<vname<<"/wheel.mesh`;" << "slack="<<(vdata->susp_upper)<<";" << "len="<<(- vdata->susp_lower)<<";" << "hookeFactor=1.0;"; std::stringstream front_wheels; front_wheels << (vdata->front_wheel_drive?"drive=1;":"") << "rad="<<v.front_wheel_size/2<<";" << (vdata->steer_rearwheels?"":"steer=1;") << "mu = "<<3*vdata->traction_mult<<";"; std::stringstream rear_wheels; rear_wheels << (vdata->back_wheel_drive?"drive=1;":"") << "rad="<<v.rear_wheel_size/2<<";" << (vdata->steer_rearwheels?"steer=1;":"") << (vdata->no_handbrake?"":"handbrake = true;") << "mu = "<<3*vdata->traction_mult<<";"; APP_ASSERT(fr_wheel_lf!=NULL); APP_ASSERT(fr_wheel_lb!=NULL); APP_ASSERT(fr_wheel_rf!=NULL); APP_ASSERT(fr_wheel_rb!=NULL); float x,y,z; x = fr_wheel_lf->x; y = fr_wheel_lf->y; z = fr_wheel_lf->z + vdata->susp_upper; lua_file << " front_left = {\n"; lua_file << " "<<all_wheels.str() << front_wheels.str() << "left=true;\n"; lua_file << " attachPos=vector3("<<x<<","<<y<<","<<z<<");\n"; lua_file << " },\n"; x = fr_wheel_rf->x; y = fr_wheel_rf->y; z = fr_wheel_rf->z + vdata->susp_upper; lua_file << " front_right = {\n"; lua_file << " "<<all_wheels.str() << front_wheels.str() << "\n"; lua_file << " attachPos=vector3("<<x<<","<<y<<","<<z<<");\n"; lua_file << " },\n"; x = fr_wheel_lb->x; y = fr_wheel_lb->y; z = fr_wheel_lb->z + vdata->susp_upper; lua_file << " rear_left = {\n"; lua_file << " "<<all_wheels.str() << rear_wheels.str() << "left=true;\n"; lua_file << " attachPos=vector3("<<x<<","<<y<<","<<z<<");\n"; lua_file << " },\n"; x = fr_wheel_rb->x; y = fr_wheel_rb->y; z = fr_wheel_rb->z + vdata->susp_upper; lua_file << " rear_right = {\n"; lua_file << " "<<all_wheels.str() << rear_wheels.str() << "\n"; lua_file << " attachPos=vector3("<<x<<","<<y<<","<<z<<");\n"; lua_file << " },\n"; lua_file << " },\n"; lua_file << " colourSpec = {\n"; std::vector<int> cols2 = carcols_2[vname]; std::vector<int> cols4 = carcols_4[vname]; APP_ASSERT(cols2.size()%2==0); APP_ASSERT(cols4.size()%4==0); for (unsigned i=0 ; i<cols2.size() ; i+=2) { int c1 = cols2[i], c2 = cols2[i+1]; lua_file << " { {\"gtasa"<<c1<<"\"}, {\"gtasa"<<c2<<"\"} },\n"; } for (unsigned i=0 ; i<cols4.size() ; i+=4) { int c1 = cols4[i], c2 = cols4[i+1]; int c3 = cols4[i+2], c4 = cols4[i+3]; lua_file << " { {\"gtasa"<<c1<<"\"}, {\"gtasa"<<c2<<"\"}, " << "{\"gtasa"<<c3<<"\"}, {\"gtasa"<<c4<<"\"} },\n"; } lua_file << " };\n"; lua_file << "},{})" << std::endl; } else { lua_file << std::endl; lua_file << "class `../"<<vname<<"` (ColClass) {\n"; lua_file << " gfxMesh=`"<<vname<<"/chassis.mesh`;\n"; lua_file << " colMesh=`"<<vname<<"/chassis.gcol`;\n"; lua_file << " castShadows = true;\n"; lua_file << " colourSpec = {\n"; std::vector<int> cols2 = carcols_2[vname]; std::vector<int> cols4 = carcols_4[vname]; APP_ASSERT(cols2.size()%2==0); APP_ASSERT(cols4.size()%4==0); for (unsigned i=0 ; i<cols2.size() ; i+=2) { int c1 = cols2[i], c2 = cols2[i+1]; lua_file << " { {\"gtasa"<<c1<<"\"}, {\"gtasa"<<c2<<"\"} },\n"; } for (unsigned i=0 ; i<cols4.size() ; i+=4) { int c1 = cols4[i], c2 = cols4[i+1]; int c3 = cols4[i+2], c4 = cols4[i+3]; lua_file << " { {\"gtasa"<<c1<<"\"}, {\"gtasa"<<c2<<"\"}, " << "{\"gtasa"<<c3<<"\"}, {\"gtasa"<<c4<<"\"} },\n"; } lua_file << " };\n"; lua_file << "}" << std::endl; } } } vehicles_lua << std::endl; vehicles_lua << "all_vehicles = { "; for (Vehicles::iterator i=vehicles.begin(),i_=vehicles.end() ; i!=i_ ; ++i) { vehicles_lua << "`"<<i->dff<<"`, "; } vehicles_lua << "}" << std::endl; if (getenv("SKIP_MAP")==NULL) { out << "Exporting map..." << std::endl; std::ofstream map; map.open((dest_dir+"/"+cfg.modname+"/map.lua").c_str(), std::ios::binary); APP_ASSERT_IO_SUCCESSFUL(map, "opening map.lua"); map.precision(25); map << "print(\"Loading world\")\n"; map << "object_all_del()\n"; map << "local last\n"; for (IPLs::iterator i=ipls.begin(),i_=ipls.end() ; i!=i_ ; ++i) { const IPL &ipl = *i; const Insts &insts = ipl.getInsts(); for (Insts::const_iterator j=insts.begin(),j_=insts.end() ; j!=j_ ; ++j) { const Inst &inst = *j; if (inst.is_low_detail) continue; if (!ids_written_out[inst.id]) continue; if (inst.near_for==-1) { map<<"object_add(`/gtasa/"<<inst.id<<"`," <<"vector3("<<inst.x<<","<<inst.y<<","<<inst.z<<")"; if (inst.rx!=0 || inst.ry!=0 || inst.rz!=0) { map<<",{rot=quat(" <<inst.rw<<","<<inst.rx<<"," <<inst.ry<<","<<inst.rz<<")}"; } map<<")\n"; } else { const Inst &far_inst = insts[inst.near_for]; map<<"last=object_add(`/gtasa/"<<inst.id<<"`," <<"vector3("<<inst.x<<","<<inst.y<<","<<inst.z<<")"; if (inst.rx!=0 || inst.ry!=0 || inst.rz!=0) { map<<",{rot=quat(" <<inst.rw<<","<<inst.rx<<"," <<inst.ry<<","<<inst.rz<<")}"; } map<<")\n"; map<<"object_add(`/gtasa/"<<far_inst.id<<"`," <<"vector3("<<far_inst.x<<","<<far_inst.y<<","<<far_inst.z<<")"; map<<",{"; if (far_inst.rx!=0 || far_inst.ry!=0 || far_inst.rz!=0) { map<<"rot=quat(" <<far_inst.rw<<","<<far_inst.rx<<"," <<far_inst.ry<<","<<far_inst.rz<<"),"; } map<<"near=last}"; map<<")\n"; } } } } out << "Export complete." << std::endl; } void extract_gtasa (const std::string &gta_dir, const std::string &dest_dir) { Config cfg; cfg.modname = "gtasa"; cfg.gta_dir = gta_dir; cfg.dest_dir = dest_dir; init_tex_dup_map(); init_ogre(); typedef std::pair<std::string,std::string> P; cfg.imgs.push_back(P("/models/gta3.img","gta3.img")); cfg.imgs.push_back(P("/models/gta_int.img","gta_int.img")); cfg.txds.push_back(P("/models/effectsPC.txd","effectsPC.txd")); cfg.txds.push_back(P("/models/fonts.txd","fonts.txd")); cfg.txds.push_back(P("/models/fronten1.txd","fronten1.txd")); cfg.txds.push_back(P("/models/fronten2.txd","fronten2.txd")); cfg.txds.push_back(P("/models/fronten3.txd","fronten3.txd")); cfg.txds.push_back(P("/models/fronten_pc.txd","fronten_pc.txd")); cfg.txds.push_back(P("/models/generic/vehicle.txd","generic/vehicle.txd")); cfg.txds.push_back(P("/models/generic/wheels.txd","generic/wheels.txd")); cfg.txds.push_back(P("/models/grass/plant1.txd","grass/plant1.txd")); cfg.txds.push_back(P("/models/hud.txd","hud.txd")); cfg.txds.push_back(P("/models/misc.txd","misc.txd")); cfg.txds.push_back(P("/models/particle.txd","particle.txd")); cfg.txds.push_back(P("/models/pcbtns.txd","pcbtns.txd")); cfg.txds.push_back(P("/models/txd/LD_RCE2.txd","txd/LD_RCE2.txd")); cfg.txds.push_back(P("/models/txd/intro1.txd","txd/intro1.txd")); cfg.txds.push_back(P("/models/txd/intro2.txd","txd/intro2.txd")); cfg.txds.push_back(P("/models/txd/intro4.txd","txd/intro4.txd")); cfg.txds.push_back(P("/models/txd/LD_BEAT.txd","txd/LD_BEAT.txd")); cfg.txds.push_back(P("/models/txd/LD_BUM.txd","txd/LD_BUM.txd")); cfg.txds.push_back(P("/models/txd/LD_CARD.txd","txd/LD_CARD.txd")); cfg.txds.push_back(P("/models/txd/LD_CHAT.txd","txd/LD_CHAT.txd")); cfg.txds.push_back(P("/models/txd/LD_DRV.txd","txd/LD_DRV.txd")); cfg.txds.push_back(P("/models/txd/LD_DUAL.txd","txd/LD_DUAL.txd")); cfg.txds.push_back(P("/models/txd/ld_grav.txd","txd/ld_grav.txd")); cfg.txds.push_back(P("/models/txd/LD_NONE.txd","txd/LD_NONE.txd")); cfg.txds.push_back(P("/models/txd/LD_OTB.txd","txd/LD_OTB.txd")); cfg.txds.push_back(P("/models/txd/LD_OTB2.txd","txd/LD_OTB2.txd")); cfg.txds.push_back(P("/models/txd/LD_PLAN.txd","txd/LD_PLAN.txd")); cfg.txds.push_back(P("/models/txd/LD_POKE.txd","txd/LD_POKE.txd")); cfg.txds.push_back(P("/models/txd/LD_POOL.txd","txd/LD_POOL.txd")); cfg.txds.push_back(P("/models/txd/LD_RACE.txd","txd/LD_RACE.txd")); cfg.txds.push_back(P("/models/txd/LD_RCE1.txd","txd/LD_RCE1.txd")); cfg.txds.push_back(P("/models/txd/LD_RCE3.txd","txd/LD_RCE3.txd")); cfg.txds.push_back(P("/models/txd/LD_RCE4.txd","txd/LD_RCE4.txd")); cfg.txds.push_back(P("/models/txd/LD_RCE5.txd","txd/LD_RCE5.txd")); cfg.txds.push_back(P("/models/txd/LD_ROUL.txd","txd/LD_ROUL.txd")); cfg.txds.push_back(P("/models/txd/ld_shtr.txd","txd/ld_shtr.txd")); cfg.txds.push_back(P("/models/txd/LD_SLOT.txd","txd/LD_SLOT.txd")); cfg.txds.push_back(P("/models/txd/LD_SPAC.txd","txd/LD_SPAC.txd")); cfg.txds.push_back(P("/models/txd/LD_TATT.txd","txd/LD_TATT.txd")); cfg.txds.push_back(P("/models/txd/load0uk.txd","txd/load0uk.txd")); cfg.txds.push_back(P("/models/txd/loadsc0.txd","txd/loadsc0.txd")); cfg.txds.push_back(P("/models/txd/loadsc1.txd","txd/loadsc1.txd")); cfg.txds.push_back(P("/models/txd/loadsc10.txd","txd/loadsc10.txd")); cfg.txds.push_back(P("/models/txd/loadsc11.txd","txd/loadsc11.txd")); cfg.txds.push_back(P("/models/txd/loadsc12.txd","txd/loadsc12.txd")); cfg.txds.push_back(P("/models/txd/loadsc13.txd","txd/loadsc13.txd")); cfg.txds.push_back(P("/models/txd/loadsc14.txd","txd/loadsc14.txd")); cfg.txds.push_back(P("/models/txd/loadsc2.txd","txd/loadsc2.txd")); cfg.txds.push_back(P("/models/txd/loadsc3.txd","txd/loadsc3.txd")); cfg.txds.push_back(P("/models/txd/loadsc4.txd","txd/loadsc4.txd")); cfg.txds.push_back(P("/models/txd/loadsc5.txd","txd/loadsc5.txd")); cfg.txds.push_back(P("/models/txd/loadsc6.txd","txd/loadsc6.txd")); cfg.txds.push_back(P("/models/txd/loadsc7.txd","txd/loadsc7.txd")); cfg.txds.push_back(P("/models/txd/loadsc8.txd","txd/loadsc8.txd")); cfg.txds.push_back(P("/models/txd/loadsc9.txd","txd/loadsc9.txd")); cfg.txds.push_back(P("/models/txd/LOADSCS.txd","txd/LOADSCS.txd")); cfg.txds.push_back(P("/models/txd/LOADSUK.txd","txd/LOADSUK.txd")); //cfg.txds.push_back(P("/models/txd/outro.txd","txd/outro.txd")); cfg.txds.push_back(P("/models/txd/splash1.txd","txd/splash1.txd")); cfg.txds.push_back(P("/models/txd/splash2.txd","txd/splash2.txd")); cfg.txds.push_back(P("/models/txd/splash3.txd","txd/splash3.txd")); // ides {{{ const char *ides[] = { "maps/country/countn2.ide", "maps/country/countrye.ide", "maps/country/countryN.ide", "maps/country/countryS.ide", "maps/country/countryW.ide", "maps/country/counxref.ide", "maps/generic/barriers.ide", "maps/generic/dynamic.ide", "maps/generic/dynamic2.ide", "maps/generic/multiobj.ide", "maps/generic/procobj.ide", "maps/generic/vegepart.ide", "maps/interior/gen_int1.ide", "maps/interior/gen_int2.ide", "maps/interior/gen_int3.ide", "maps/interior/gen_int4.ide", "maps/interior/gen_int5.ide", "maps/interior/gen_intb.ide", "maps/interior/int_cont.ide", "maps/interior/int_LA.ide", "maps/interior/int_SF.ide", "maps/interior/int_veg.ide", "maps/interior/propext.ide", "maps/interior/props.ide", "maps/interior/props2.ide", "maps/interior/savehous.ide", "maps/interior/stadint.ide", "maps/LA/LAe.ide", "maps/LA/LAe2.ide", "maps/LA/LAhills.ide", "maps/LA/LAn.ide", "maps/LA/LAn2.ide", "maps/LA/LAs.ide", "maps/LA/LAs2.ide", "maps/LA/LAw.ide", "maps/LA/LAw2.ide", "maps/LA/LaWn.ide", "maps/LA/LAxref.ide", "maps/leveldes/levelmap.ide", "maps/leveldes/levelxre.ide", "maps/leveldes/seabed.ide", "maps/SF/SFe.ide", "maps/SF/SFn.ide", "maps/SF/SFs.ide", "maps/SF/SFSe.ide", "maps/SF/SFw.ide", "maps/SF/SFxref.ide", "maps/txd.ide", "maps/vegas/vegasE.ide", "maps/vegas/VegasN.ide", "maps/vegas/VegasS.ide", "maps/vegas/VegasW.ide", "maps/vegas/vegaxref.ide", "maps/veh_mods/veh_mods.ide", "vehicles.ide", "peds.ide", "txdcut.ide", "default.ide" }; //}}} cfg.idesv = ides; cfg.idesc = sizeof ides / sizeof *ides; //{{{ cfg.ipls.push_back(IPLConfig("leveldes/seabed.ipl","gta3.img","seabed",1)); cfg.ipls.push_back(IPLConfig("leveldes/levelmap.ipl","gta3.img","levelmap",1)); cfg.ipls.push_back(IPLConfig("SF/SFe.ipl","gta3.img","sfe",4)); cfg.ipls.push_back(IPLConfig("SF/SFn.ipl","gta3.img","sfn",3)); cfg.ipls.push_back(IPLConfig("SF/SFSe.ipl","gta3.img","sfse",7)); cfg.ipls.push_back(IPLConfig("SF/SFs.ipl","gta3.img","sfs",9)); cfg.ipls.push_back(IPLConfig("SF/SFw.ipl","gta3.img","sfw",6)); cfg.ipls.push_back(IPLConfig("vegas/vegasE.ipl","gta3.img","vegase",9)); cfg.ipls.push_back(IPLConfig("vegas/vegasN.ipl","gta3.img","vegasn",9)); cfg.ipls.push_back(IPLConfig("vegas/vegasS.ipl","gta3.img","vegass",6)); cfg.ipls.push_back(IPLConfig("vegas/vegasW.ipl","gta3.img","vegasw",12)); cfg.ipls.push_back(IPLConfig("country/countn2.ipl","gta3.img","countn2",9)); cfg.ipls.push_back(IPLConfig("country/countrye.ipl","gta3.img","countrye",14)); cfg.ipls.push_back(IPLConfig("country/countryN.ipl","gta3.img","countryn",4)); cfg.ipls.push_back(IPLConfig("country/countryS.ipl","gta3.img","countrys",5)); cfg.ipls.push_back(IPLConfig("country/countryw.ipl","gta3.img","countryw",9)); cfg.ipls.push_back(IPLConfig("LA/LAe2.ipl","gta3.img","lae2",7)); cfg.ipls.push_back(IPLConfig("LA/LAe.ipl","gta3.img","lae",6)); cfg.ipls.push_back(IPLConfig("LA/LAhills.ipl","gta3.img","lahills",5)); cfg.ipls.push_back(IPLConfig("LA/LAn2.ipl","gta3.img","lan2",4)); cfg.ipls.push_back(IPLConfig("LA/LAn.ipl","gta3.img","lan",3)); cfg.ipls.push_back(IPLConfig("LA/LAs2.ipl","gta3.img","las2",5)); cfg.ipls.push_back(IPLConfig("LA/LAs.ipl","gta3.img","las",6)); cfg.ipls.push_back(IPLConfig("LA/LAw2.ipl","gta3.img","law2",5)); cfg.ipls.push_back(IPLConfig("LA/LAw.ipl","gta3.img","law",6)); cfg.ipls.push_back(IPLConfig("LA/LaWn.ipl","gta3.img","lawn",4)); cfg.ipls.push_back(IPLConfig("interior/gen_int1.ipl","gta_int.img","",0)); cfg.ipls.push_back(IPLConfig("interior/gen_int2.ipl","gta_int.img","gen_int2",1)); cfg.ipls.push_back(IPLConfig("interior/gen_int3.ipl","gta_int.img","gen_int3",1)); cfg.ipls.push_back(IPLConfig("interior/gen_int4.ipl","gta_int.img","gen_int4",3)); cfg.ipls.push_back(IPLConfig("interior/gen_int5.ipl","gta_int.img","gen_int5",8)); cfg.ipls.push_back(IPLConfig("interior/gen_intb.ipl","gta_int.img","gen_intb",1)); cfg.ipls.push_back(IPLConfig("interior/int_cont.ipl","gta_int.img","",0)); cfg.ipls.push_back(IPLConfig("interior/int_LA.ipl","gta_int.img","int_la",4)); cfg.ipls.push_back(IPLConfig("interior/int_SF.ipl","gta_int.img","int_sf",1)); cfg.ipls.push_back(IPLConfig("interior/int_veg.ipl","gta_int.img","int_veg",4)); cfg.ipls.push_back(IPLConfig("interior/savehous.ipl","gta_int.img","savehous",2)); cfg.ipls.push_back(IPLConfig("interior/stadint.ipl","gta_int.img","stadint",1)); //}}} extract(cfg,std::cout); } void extract_gostown (const std::string &gta_dir, const std::string &dest_dir) { Config cfg; cfg.modname = "gostown"; cfg.gta_dir = gta_dir; cfg.dest_dir = dest_dir; init_ogre(); typedef std::pair<std::string,std::string> P; cfg.imgs.push_back(P("/models/gta3.img","gta3.img")); cfg.imgs.push_back(P("/models/gostown6.img","gostown6.img")); // {{{ IDES const char *ides[] = { //"maps/country/countn2.ide", //"maps/country/countrye.ide", //"maps/country/countryN.ide", //"maps/country/countryS.ide", //"maps/country/countryW.ide", //"maps/country/counxref.ide", "maps/generic/barriers.ide", "maps/generic/dynamic.ide", "maps/generic/dynamic2.ide", "maps/generic/multiobj.ide", "maps/generic/procobj.ide", "maps/generic/vegepart.ide", //"maps/interior/gen_int1.ide", //"maps/interior/gen_int2.ide", //"maps/interior/gen_int3.ide", //"maps/interior/gen_int4.ide", //"maps/interior/gen_int5.ide", //"maps/interior/gen_intb.ide", //"maps/interior/int_cont.ide", //"maps/interior/int_LA.ide", //"maps/interior/int_SF.ide", //"maps/interior/int_veg.ide", //"maps/interior/propext.ide", //"maps/interior/props.ide", //"maps/interior/props2.ide", //"maps/interior/savehous.ide", //"maps/interior/stadint.ide", //"maps/LA/LAe.ide", //"maps/LA/LAe2.ide", //"maps/LA/LAhills.ide", //"maps/LA/LAn.ide", //"maps/LA/LAn2.ide", //"maps/LA/LAs.ide", //"maps/LA/LAs2.ide", //"maps/LA/LAw.ide", //"maps/LA/LAw2.ide", //"maps/LA/LaWn.ide", //"maps/LA/LAxref.ide", //"maps/leveldes/levelmap.ide", //"maps/leveldes/levelxre.ide", "maps/leveldes/seabed.ide", //"maps/SF/SFe.ide", //"maps/SF/SFn.ide", //"maps/SF/SFs.ide", //"maps/SF/SFSe.ide", //"maps/SF/SFw.ide", //"maps/SF/SFxref.ide", //"maps/txd.ide", //"maps/vegas/vegasE.ide", //"maps/vegas/VegasN.ide", //"maps/vegas/VegasS.ide", //"maps/vegas/VegasW.ide", //"maps/vegas/vegaxref.ide", //"maps/veh_mods/veh_mods.ide", "maps/Gostown6/Gp_land50.IDE", "maps/Gostown6/Gp_tunnels.IDE", "maps/Gostown6/Gp_docks.IDE", "maps/Gostown6/Gp_palmtheme.IDE", "maps/Gostown6/Gp_A13.IDE", "maps/Gostown6/Gp_airport.IDE", "maps/Gostown6/Gp_city.IDE", "maps/Gostown6/Gp_GSS.IDE", "maps/Gostown6/lots/ParoXum.IDE", "maps/Gostown6/lots/JostVice.IDE", "maps/Gostown6/lots/Fredskin.IDE", "maps/Gostown6/lots/Raycen.IDE", "maps/Gostown6/lots/Generics.IDE", "maps/Gostown6/lots/Parent.IDE", "maps/Gostown6/Gp_laguna.IDE", //"vehicles.ide", //"peds.ide", //"default.ide" }; //}}} cfg.idesv = ides; cfg.idesc = sizeof ides / sizeof *ides; //{{{ IPL cfg.ipls.push_back(IPLConfig("Gostown6/Gp_land50.IPL","gostown6.img","",0)); cfg.ipls.push_back(IPLConfig("Gostown6/Gp_tunnels.IPL","gostown6.img","",0)); cfg.ipls.push_back(IPLConfig("Gostown6/Gp_docks.IPL","gostown6.img","",0)); cfg.ipls.push_back(IPLConfig("Gostown6/Gp_veg.IPL","gostown6.img","",0)); cfg.ipls.push_back(IPLConfig("Gostown6/Gp_A13.IPL","gostown6.img","",0)); cfg.ipls.push_back(IPLConfig("Gostown6/Gp_airport.IPL","gostown6.img","",0)); cfg.ipls.push_back(IPLConfig("Gostown6/Gp_City.IPL","gostown6.img","",0)); cfg.ipls.push_back(IPLConfig("Gostown6/Gp_GSS.IPL","gostown6.img","",0)); cfg.ipls.push_back(IPLConfig("Gostown6/Gp_props.IPL","gostown6.img","",0)); cfg.ipls.push_back(IPLConfig("Gostown6/lots/ParoXum.IPL","gostown6.img","",0)); cfg.ipls.push_back(IPLConfig("Gostown6/lots/JostVice.IPL","gostown6.img","",0)); cfg.ipls.push_back(IPLConfig("Gostown6/lots/Fredskin.IPL","gostown6.img","",0)); cfg.ipls.push_back(IPLConfig("Gostown6/lots/Raycen.IPL","gostown6.img","",0)); cfg.ipls.push_back(IPLConfig("Gostown6/Gp_laguna.IPL","gostown6.img","",0)); cfg.ipls.push_back(IPLConfig("Gostown6/occlu.ipl","gostown6.img","",0)); //}}} extract(cfg,std::cout); } static int tolowr (int c) { return std::tolower(char(c),std::cout.getloc()); } static std::string& strlower(std::string& s) { std::transform(s.begin(),s.end(), s.begin(),tolowr); return s; } int main(int argc, char **argv) { if (argc!=3 && argc!=4) { std::cerr<<"Usage: "<<argv[ 0]<<" <mod> <source_dir> " <<" [ <grit_dir> ]"<<std::endl; std::cerr<<"Where <mod> can be \"gtasa\" " <<"or \"gostown\""<<std::endl; return EXIT_FAILURE; } try { std::string mod = argv[1]; strlower(mod); const char *src = argv[2]; const char *dest = argc>3?argv[3]:"."; if (mod=="gostown") { extract_gostown(src, dest); } else if (mod=="gtasa") { extract_gtasa(src, dest); } else { std::cerr<<"Unrecognised mod: \"" <<argv[1]<<"\""<<std::endl; return EXIT_FAILURE; } } catch (const Exception &e) { CERR << e << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } // vim: shiftwidth=4:tabstop=4:expandtab
39.630978
134
0.534625
AugustoMoura
a9758707b607ca2557ac6388d27bf13540e82662
2,365
cpp
C++
codeforces/EDU/segment_tree/sign_alteration.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
codeforces/EDU/segment_tree/sign_alteration.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
codeforces/EDU/segment_tree/sign_alteration.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <climits> using namespace std; struct item{ long long int val; int length; }; struct segtree{ int size; vector<item>values; item NEUTRAL_ELEMENT = {0,0}; item combine(const item &p1, const item &p2){ if(p1.length==0){ return {p2.val, p2.length}; } else if(p1.length%2==0) return {p1.val + p2.val, p1.length + p2.length}; else return {p1.val - p2.val, p1.length + p2.length}; } item single(long long int val){ return {val,1}; } void init(int n){ size = 1; while(size < n) size <<= 1; values = vector<item> (2 * size); } void build_helper(const vector<long long int> &v, int x, int l, int r){ if(r-l==1){ if(l < v.size()) values[x] = single(v[l]); return; } int m = (l+r)/2; build_helper(v,2*x+1,l,m); build_helper(v,2*x+2,m,r); values[x] = combine(values[2*x+1],values[2*x+2]); return; } void build(const vector<long long int> &v){ build_helper(v,0,0,size); } void set_helper(int index, long long int val, int x, int l, int r){ if(r-l==1){ values[x] = single(val); return; } int m = (l+r)/2; if(index < m){ set_helper(index, val, 2*x+1, l, m); } else{ set_helper(index, val, 2*x+2, m, r); } values[x] = combine(values[2*x+1],values[2*x+2]); return ; } void set(int index, long long int val){ set_helper(index,val,0,0,size); } item sum_helper(int l, int r, int x, int lx, int rx){ if((l <= lx) && (rx <= r)) return values[x]; if((rx <= l) || (lx >= r)) return NEUTRAL_ELEMENT; int m = (lx + rx)/2; return combine(sum_helper(l, r, 2*x+1, lx, m),sum_helper(l, r, 2*x+2, m, rx)); } item sum(int l, int r){ return sum_helper(l,r,0,0,size); } }; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; vector<long long int> a(n); for(int i=0 ; i<n ; i++){ cin >> a[i]; } segtree st; st.init(n); st.build(a); int m; cin >> m; //for(auto e : st.sums) cout << e << " "; //cout << "\n"; for(int i=0 ; i<m ; i++){ int op; cin >> op; if(op==0){ int index; long long int val; cin >> index >> val; index--; st.set(index,val); } else if(op==1){ int l, r; cin >> l >> r; l--; cout << st.sum(l,r).val << "\n"; } } }
17.649254
80
0.536998
udayan14
a9788365790c6e69bc5931bb9b2af15761989fda
12,712
cpp
C++
CSGOSimple/Backtrack.cpp
D1ckRider/Dickware
d0b2417505437c7f67fe687a81a43d459f09af7f
[ "MIT" ]
3
2019-11-17T19:52:44.000Z
2020-02-26T18:22:25.000Z
CSGOSimple/Backtrack.cpp
Renji-kun/Dickware
d0b2417505437c7f67fe687a81a43d459f09af7f
[ "MIT" ]
12
2019-01-17T14:52:06.000Z
2019-03-21T17:01:09.000Z
CSGOSimple/Backtrack.cpp
D1ckRider/Dickware
d0b2417505437c7f67fe687a81a43d459f09af7f
[ "MIT" ]
9
2019-06-02T18:26:13.000Z
2020-04-21T19:21:48.000Z
#include "Backtrack.h" #include "helpers\math.hpp" #include "Rbot.h" #include "ConsoleHelper.h" #include "Autowall.h" #include "Settings.h" void Backtrack::OnCreateMove() { for ( int i = 1; i < g_EngineClient->GetMaxClients(); i++ ) { auto entity = static_cast<C_BasePlayer*> ( g_EntityList->GetClientEntity ( i ) ); if ( !entity || !g_LocalPlayer || !entity->IsPlayer() || entity == g_LocalPlayer || entity->IsDormant() || !entity->IsAlive() || !entity->IsEnemy() ) { continue; } AddTick ( entity, i ); } } float Backtrack::GetLerpTime() { int ud_rate = g_CVar->FindVar ( "cl_updaterate" )->GetInt(); ConVar* min_ud_rate = g_CVar->FindVar ( "sv_minupdaterate" ); ConVar* max_ud_rate = g_CVar->FindVar ( "sv_maxupdaterate" ); //Console.WriteLine(min_ud_rate->GetFlags) if ( min_ud_rate && max_ud_rate ) { ud_rate = max_ud_rate->GetInt(); } float ratio = g_CVar->FindVar ( "cl_interp_ratio" )->GetFloat(); if ( ratio == 0 ) { ratio = 1.0f; } float lerp = g_CVar->FindVar ( "cl_interp" )->GetFloat(); ConVar* c_min_ratio = g_CVar->FindVar ( "sv_client_min_interp_ratio" ); ConVar* c_max_ratio = g_CVar->FindVar ( "sv_client_max_interp_ratio" ); if ( c_min_ratio && c_max_ratio && c_min_ratio->GetFloat() != 1 ) { ratio = std::clamp ( ratio, c_min_ratio->GetFloat(), c_max_ratio->GetFloat() ); } return std::max<float> ( lerp, ( ratio / ud_rate ) ); } bool Backtrack::IsTickValid ( int tick ) { INetChannelInfo* nci = g_EngineClient->GetNetChannelInfo(); static auto sv_maxunlag = g_CVar->FindVar ( "sv_maxunlag" ); //Console.WriteLine(sv_maxunlag->GetFloat()); if ( !nci || !sv_maxunlag ) { return false; } float correct = std::clamp ( nci->GetLatency ( FLOW_OUTGOING ) + GetLerpTime(), 0.f, sv_maxunlag->GetFloat() ); //Console.Write("correct: "); Console.WriteLine(correct); float deltaTime = correct - ( g_GlobalVars->curtime - TICKS_TO_TIME ( tick ) ); return fabsf ( deltaTime ) < 0.2f; } /* Have to change: - get studiohdr - studiomdl - studio hitboxset --> here for better damage calculation // */ bool Backtrack::RageBacktrack ( C_BasePlayer* player, int i, float& damage, Vector& hitpos, TickRecord& _record ) { std::deque<TickRecord> bestRecords = GetBestTicks ( i ); if ( bestRecords.size() == 0 ) return false; OriginalRecord orgData = OriginalRecord ( player ); bool foundGoodRecord = false; float bestDamage = 0.f; Vector bestHitpos = Vector ( 0, 0, 0 ); TickRecord bestRecord; float MinDamage = Settings::RageBot::WeaponSettings[0].MinDamage; //g_Config.GetFloat ( "rbot_mindamage" ); //bool foundKillable = false; if ( bestRecords.size() > 4 ) { bool skip = false; for ( auto record = bestRecords.begin(); record != bestRecords.end(); ) { if ( skip ) { record = bestRecords.erase ( record ); } else { record++; } skip = !skip; } } for ( auto record = bestRecords.begin(); record != bestRecords.end(); record++ ) { //if (foundKillable) continue; float currentDamage = 0.f; Vector currentHitpos = Vector ( 0, 0, 0 ); bool b_bool = false; if ( GetBestPointForRecord ( player, *record, MinDamage, currentHitpos, currentDamage, b_bool ) ) { if ( currentDamage > bestDamage ) { //Console.WriteLine("b1g"); foundGoodRecord = true; bestDamage = currentDamage; bestHitpos = currentHitpos; bestRecord = *record; } } } //Console.WriteLine("Loob finished"); if ( !foundGoodRecord ) { return false; } //Console.WriteLine(bestHitpos); damage = bestDamage; hitpos = bestHitpos; _record = bestRecord; player->InvalidateBoneCache(); player->SetAbsOriginal ( orgData.m_vecOrigin ); player->SetAbsAngles ( QAngle ( 0, orgData.m_angEyeAngles.yaw, 0 ) ); player->m_fFlags() = orgData.m_fFlags; player->m_flPoseParameter() = orgData.m_flPoseParameter; player->UpdateClientSideAnimation(); return true; } void Backtrack::LegitOnCreateMove ( std::deque<int> hb_enabled ) { for ( int i = 1; i < g_EngineClient->GetMaxClients(); i++ ) { auto entity = static_cast<C_BasePlayer*> ( g_EntityList->GetClientEntity ( i ) ); if ( !entity || !g_LocalPlayer || !entity->IsPlayer() || entity == g_LocalPlayer || entity->IsDormant() || !entity->IsAlive() || !entity->IsEnemy() ) { continue; } LegitTickRecord record = LegitTickRecord ( entity, g_Resolver.GResolverData[i], hb_enabled ); LegitTickRecords[i].push_back ( record ); if ( LegitTickRecords[i].size() > 128 ) { LegitTickRecords[i].erase ( LegitTickRecords[i].begin() ); } } } void Backtrack::FinishLegitBacktrack ( CUserCmd* cmd ) { if ( !g_LocalPlayer || !g_LocalPlayer->IsAlive() ) return; if ( ! ( cmd->buttons & IN_ATTACK ) && ! ( cmd->buttons & IN_ATTACK2 ) ) return; int BestEntity = -1; LegitTickRecord BestRecord; float BestFov = FLT_MAX; float lbot_backtrack_ms = Settings::Aimbot::BacktrackTick;//g_Config.GetFloat ( "lbot_backtrack_ms" ); for ( int i = 1; i < g_EngineClient->GetMaxClients(); i++ ) { auto entity = static_cast<C_BasePlayer*> ( g_EntityList->GetClientEntity ( i ) ); if ( !entity || !g_LocalPlayer || !entity->IsPlayer() || entity == g_LocalPlayer || entity->IsDormant() || !entity->IsAlive() || !entity->IsEnemy() ) { continue; } std::deque<LegitTickRecord> lcr = GetValidLegitRecords ( i, lbot_backtrack_ms ); for ( auto record = lcr.begin(); record != lcr.end(); record++ ) { if ( !g_LocalPlayer->CanSeePlayer ( g_LocalPlayer, record->hitboxes[HITBOX_HEAD] ) ) { continue; } float fov = Math::GetFOV ( cmd->viewangles, Math::CalcAngle ( g_LocalPlayer->GetEyePos(), record->hitboxes[HITBOX_HEAD] ) ); if ( fov < BestFov ) { BestRecord = *record; BestFov = fov; BestEntity = i; } /* for (int hitbox = 0; hitbox < HITBOX_MAX; hitbox++) { if (!g_LocalPlayer->CanSeePlayer(g_LocalPlayer, record->hitboxes[hitbox])) continue; float fov = Math::GetFOV(cmd->viewangles, Math::CalcAngle(g_LocalPlayer->GetEyePos(), record->hitboxes[hitbox])); if (fov < BestFov) { BestRecord = *record; BestFov = fov; BestEntity = i; } } */ } } if ( BestEntity != -1 ) { cmd->tick_count = TIME_TO_TICKS ( BestRecord.m_flSimulationTime + Backtrack::Get().GetLerpTime() ); } } std::deque<LegitTickRecord> Backtrack::GetValidLegitRecords ( int i, float lbot_backtrack_ms ) { std::deque<LegitTickRecord> returnVal; //float lbot_backtrack_ms = g_Config.GetFloat("lbot_backtrack_ms"); for ( auto record = LegitTickRecords[i].begin(); record != LegitTickRecords[i].end(); record++ ) { if ( !record->Moving ) { continue; } if ( record->CanUse && IsTickValid ( TIME_TO_TICKS ( record->m_flSimulationTime + GetLerpTime() ) ) && ( fabsf ( g_GlobalVars->curtime - record->m_flSimulationTime ) + Backtrack::Get().GetLerpTime() ) < lbot_backtrack_ms ) { returnVal.push_back ( *record ); } } /* if (returnVal.size() > 6) { bool skip = false; for (auto record = returnVal.begin(); record != returnVal.end(); ) { if (skip) { record = returnVal.erase(record); } else { record++; } skip = !skip; } } */ return returnVal; } bool Backtrack::GetHitboxPos ( int hb, mstudiohitboxset_t* hitboxset, matrix3x4_t matrix[MAXSTUDIOBONES], Vector& pos ) { mstudiobbox_t* studioBox = hitboxset->GetHitbox ( hb ); if ( !studioBox || !matrix ) { return false; } Vector min, max; Math::VectorTransform ( studioBox->bbmin, matrix[studioBox->bone], min ); Math::VectorTransform ( studioBox->bbmax, matrix[studioBox->bone], max ); pos = ( min + max ) * 0.5f; return true; } std::deque<TickRecord> Backtrack::GetValidTicks ( int i ) { std::deque<TickRecord> returnVal; //if(TickRecords[i].size() == 0) { Console.WriteLine("!TickRecords == 0"); return returnVal; } //Console.WriteLine((int)TickRecords[i].size()); for ( auto record = TickRecords[i].begin(); record != TickRecords[i].end(); record++ ) { if ( record->CanUse && IsTickValid ( TIME_TO_TICKS ( record->m_flSimulationTime + GetLerpTime() ) ) ) { returnVal.push_back ( *record ); } } //Console.WriteLine((int)returnVal.size()); return returnVal; } std::deque<TickRecord> Backtrack::GetBestTicks ( int i ) { std::deque<TickRecord> returnVal; std::deque<TickRecord> ValidRecords = GetValidTicks ( i ); if ( ValidRecords.size() == 0 ) { return returnVal; } for ( auto record = ValidRecords.begin(); record != ValidRecords.end(); record++ ) { if ( record->resolverData.mode == ResolverModes::LBY_BREAK || ( !record->resolverData.InFakelag && record->resolverData.Moving && !record->resolverData.InAir ) ) { returnVal.push_back ( *record ); } } if ( returnVal.size() < 3 ) { for ( auto record = ValidRecords.begin(); record != ValidRecords.end(); record++ ) { if ( !record->resolverData.InFakelag && record->resolverData.InAir && record->resolverData.Moving ) { returnVal.push_back ( *record ); } } } return returnVal; } bool Backtrack::GetBestPointForRecord ( C_BasePlayer* player, TickRecord record, float minDmg, Vector& hitpos, float& damage, bool& willKill ) { player->InvalidateBoneCache(); player->m_fFlags() = record.m_fFlags; player->m_flCycle() = record.m_flCycle; player->m_nSequence() = record.m_nSequence; player->SetAbsOriginal ( record.m_vecOrigin ); player->m_angEyeAngles() = record.m_angEyeAngles; //player->SetAbsAngles(QAngle(0, record.m_angEyeAngles.yaw, 0)); player->m_flLowerBodyYawTarget() = record.m_flLowerBodyYawTarget; player->m_flSimulationTime() = record.m_flSimulationTime; //player->m_flPoseParameter() = record.m_flPoseParameter; player->UpdateClientSideAnimation(); //if (!record.StudioHdr) return false; if ( !record.matrixBuilt ) { if ( !player->SetupBones ( record.matrix, 128, 256, record.m_flSimulationTime ) ) { return false; } record.matrixBuilt = true; } const model_t* model = player->GetModel(); if ( !model ) { return false; } studiohdr_t* studioHdr = g_MdlInfo->GetStudiomodel ( model ); if ( !studioHdr ) { return false; } mstudiohitboxset_t* studioSet = studioHdr->GetHitboxSet ( 0 ); if ( !studioSet ) { return false; } bool GotHead = false, GotPelvis = false; Vector head, body; if ( !GetHitboxPos ( HITBOX_HEAD, studioSet, record.matrix, head ) ) { return false; } //minDmg; //g_Config.GetFloat("rbot_mindamage"); Vector BestPos = Vector ( 0, 0, 0 ); bool CanDo = false; if ( GotHead ) { float Damage = Autowall::Get().CanHit ( head ); //Console.Write("Head damage: "); Console.WriteLine(Damage); if ( Damage > minDmg ) { minDmg = Damage; BestPos = head; CanDo = true; } } hitpos = BestPos; damage = minDmg; willKill = minDmg > player->m_iHealth(); return CanDo; } void Backtrack::AddTick ( C_BasePlayer* player, int i ) { TickRecord record = TickRecord ( player, g_Resolver.GResolverData[i] ); TickRecords[i].push_back ( record ); if ( TickRecords[i].size() > 128 ) { TickRecords[i].erase ( TickRecords[i].begin() ); } }
27.455724
230
0.580868
D1ckRider
a985eafbb6c411bc9f63bfff5a0e65da53c45a9c
2,651
cpp
C++
069.cpp
Jalanjii/Algorithms
6b6b01e18c5c6c4bcfa122a269fdab8a47f09b7b
[ "MIT" ]
1
2021-04-14T22:52:05.000Z
2021-04-14T22:52:05.000Z
069.cpp
Jalanjii/Algorithms
6b6b01e18c5c6c4bcfa122a269fdab8a47f09b7b
[ "MIT" ]
null
null
null
069.cpp
Jalanjii/Algorithms
6b6b01e18c5c6c4bcfa122a269fdab8a47f09b7b
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int n, index = -1, res = -1, length = 0, max_length = 0; bool flipped = false; cin >> n; int *a = new int[n]; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) { if (a[i] == 0) { if (flipped) { flipped = false; length = 0; if (i + 1 < n && a[i + 1] == 1) i = index; } else { flipped = true; index = i; } } ++length; if (length > max_length) { res = index; max_length = length; } } cout << res + 1; delete[] a; return 0; } ----------- #include <iostream> using namespace std; int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int n, index = -1, res = -1, length = 0, max_length = 0; bool flipped = false; cin >> n; int *a = new int[n]; for (int i = 0; i < n; ++i) cin >> a[i]; for (int i = 0; i < n; i++) { if (a[i] == 0) { if (flipped) { flipped = false; length = 0; if (i + 1 < n && a[i + 1] == 1) i = index; } else { flipped = true; index = i; } } ++length; if (length > max_length) { res = index; max_length = length; } } cout << res + 1; delete[] a; return 0; } ------------ #include <iostream> using namespace std; int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int n; cin >> n; int *a = new int[n]; for (int i = 0; i < n; ++i) cin >> a[i]; bool flipped = false; int index = -1; int res = -1; int length = 0; int max_length = 0; for (int i = 0; i < n; i++) { if (a[i] == 0) { if (flipped) { flipped = false; length = -1; if (i + 1 < n && a[i + 1] == 1) i = index; } else { flipped = true; index = i; } } ++length; if (length > max_length) { res = index; max_length = length; } } cout << res + 1; delete[] a; return 0; } ------------ #include <iostream> using namespace std; int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int n; cin >> n; int *a = new int[n]; for (int i = 0; i < n; ++i) cin >> a[i]; bool flipped = false; int index = -1; int res = -1; int length = 0; int max_length = 0; for (int i = 0; i < n; i++) { if (a[i] == 0) { if (flipped) { flipped = false; length = -1; if (i + 1 < n && a[i + 1] == 1) i = index; } else { flipped = true; index = i; } } ++length; if (length > max_length) { res = index; max_length = length; } } cout << res + 1; delete[] a; return 0; }
14.176471
57
0.479819
Jalanjii
a98955acb42b693e58479c8fc95d3c4153bd9f77
23,340
inl
C++
inc/behaviac/agent/agent.inl
Manistein/behaviac
538266380446e0fd77461ad22fca05e2c9eb8cba
[ "BSD-3-Clause" ]
2
2021-06-06T07:54:45.000Z
2021-09-08T03:36:40.000Z
inc/behaviac/agent/agent.inl
gdtdftdqtd/behaviac
538266380446e0fd77461ad22fca05e2c9eb8cba
[ "BSD-3-Clause" ]
null
null
null
inc/behaviac/agent/agent.inl
gdtdftdqtd/behaviac
538266380446e0fd77461ad22fca05e2c9eb8cba
[ "BSD-3-Clause" ]
1
2017-07-02T06:55:02.000Z
2017-07-02T06:55:02.000Z
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed under the License is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace behaviac { template<typename TAGENT> BEHAVIAC_FORCEINLINE bool Agent::IsRegistered() { const char* agentClassName = TAGENT::GetClassTypeName(); return IsRegistered(agentClassName); } template<typename TAGENT> BEHAVIAC_FORCEINLINE TAGENT* Agent::Create(const char* agentInstanceName, int contextId, short priority) { const char* agentInstanceNameAny = agentInstanceName; if (!agentInstanceNameAny) { agentInstanceNameAny = TAGENT::GetClassTypeName(); } BEHAVIAC_ASSERT(!Agent::IsNameRegistered(agentInstanceNameAny), "a registered name should be created by CreateInstance"); //TAGENT should be derived from Agent Agent* pAgent = BEHAVIAC_NEW TAGENT(); //const char* agentClassName = TAGENT::GetClassTypeName(); Init_(contextId, pAgent, priority, agentInstanceName); BEHAVIAC_ASSERT(TAGENT::DynamicCast(pAgent)); TAGENT* pA = (TAGENT*)pAgent; return pA; } BEHAVIAC_FORCEINLINE void Agent::Destory(Agent* pAgent) { BEHAVIAC_DELETE(pAgent); } //template<typename TAGENT> //BEHAVIAC_FORCEINLINE bool UnbindInstance() { // const char* agentInstanceName = TAGENT::GetClassTypeName(); // return behaviac.Agent.UnbindInstance(agentInstanceName, 0); //} template<typename TAGENT> BEHAVIAC_FORCEINLINE TAGENT* Agent::CreateInstance(const char* agentInstanceName, int contextId, short priority) { Context& c = Context::GetContext(contextId); TAGENT* pA = 0; const char* agentInstanceNameAny = agentInstanceName; if (!agentInstanceNameAny) { agentInstanceNameAny = TAGENT::GetClassTypeName(); } BEHAVIAC_ASSERT(Agent::IsNameRegistered(agentInstanceNameAny), "only a registered name can be created by CreateInstance"); Agent* a = c.GetInstance(agentInstanceNameAny); if (!a) { //TAGENT should be derived from Agent Agent* pAgent = BEHAVIAC_NEW TAGENT(); Init_(contextId, pAgent, priority, agentInstanceNameAny); BEHAVIAC_ASSERT(TAGENT::DynamicCast(pAgent)); pA = (TAGENT*)pAgent; c.BindInstance(agentInstanceNameAny, pA); } else { BEHAVIAC_ASSERT(TAGENT::DynamicCast(a)); pA = (TAGENT*)a; } return pA; } template<typename TAGENT> BEHAVIAC_FORCEINLINE void Agent::DestroyInstance(const char* agentInstanceName, int contextId) { Context& c = Context::GetContext(contextId); const char* agentInstanceNameAny = agentInstanceName; if (!agentInstanceNameAny) { agentInstanceNameAny = TAGENT::GetClassTypeName(); } Agent* a = c.GetInstance(agentInstanceNameAny); c.UnbindInstance(agentInstanceNameAny); BEHAVIAC_DELETE(a); } template<typename TAGENT> BEHAVIAC_FORCEINLINE TAGENT* Agent::GetInstance(const char* agentInstanceName, int contextId) { const char* agentInstanceNameAny = agentInstanceName; if (!agentInstanceNameAny) { agentInstanceNameAny = TAGENT::GetClassTypeName(); } Agent* a = Agent::GetInstance(agentInstanceNameAny, contextId); BEHAVIAC_ASSERT(!a || TAGENT::DynamicCast(a)); TAGENT* pA = (TAGENT*)a; return pA; } BEHAVIAC_FORCEINLINE void Agent::FireEvent(Agent* pAgent, const char* eventName) { CNamedEvent* pEvent = 0; if (pAgent) { pEvent = pAgent->findEvent(eventName); if (!pEvent) { int contextId = pAgent->GetContextId(); const CTagObjectDescriptor& meta = pAgent->GetDescriptor(); pEvent = findNamedEventTemplate(meta.ms_methods, eventName, contextId); } if (pEvent) { pEvent->SetFired(pAgent, true); } else { BEHAVIAC_ASSERT(0, "unregistered event %s", eventName); } } } template<class ParamType1> BEHAVIAC_FORCEINLINE void Agent::FireEvent(Agent* pAgent, const char* eventName, const ParamType1& param1) { CNamedEvent* pEvent = 0; if (pAgent) { pEvent = pAgent->findEvent(eventName); if (!pEvent) { int contextId = pAgent->GetContextId(); const CTagObjectDescriptor& meta = pAgent->GetDescriptor(); pEvent = findNamedEventTemplate(meta.ms_methods, eventName, contextId); } if (pEvent) { CNamedEvent1<ParamType1>* pEvent1 = CNamedEvent1<ParamType1>::DynamicCast(pEvent); if (pEvent1) { pEvent1->SetParam(pAgent, param1); } else { BEHAVIAC_ASSERT(0, "unregistered parameters %s", eventName); } pEvent->SetFired(pAgent, true); } else { BEHAVIAC_ASSERT(0, "unregistered event %s", eventName); } } } template<class ParamType1, class ParamType2> BEHAVIAC_FORCEINLINE void Agent::FireEvent(Agent* pAgent, const char* eventName, const ParamType1& param1, const ParamType2& param2) { CNamedEvent* pEvent = 0; if (pAgent) { pEvent = pAgent->findEvent(eventName); if (!pEvent) { int contextId = pAgent->GetContextId(); const CTagObjectDescriptor& meta = pAgent->GetDescriptor(); pEvent = findNamedEventTemplate(meta.ms_methods, eventName, contextId); } if (pEvent) { CNamedEvent2<ParamType1, ParamType2>* pEvent2 = CNamedEvent2<ParamType1, ParamType2>::DynamicCast(pEvent); if (pEvent2) { pEvent2->SetParam(pAgent, param1, param2); } else { BEHAVIAC_ASSERT(0, "unregistered parameters %s", eventName); } pEvent->SetFired(pAgent, true); } else { BEHAVIAC_ASSERT(0, "unregistered event %s", eventName); } } } template<class ParamType1, class ParamType2, class ParamType3> BEHAVIAC_FORCEINLINE void Agent::FireEvent(Agent* pAgent, const char* eventName, const ParamType1& param1, const ParamType2& param2, const ParamType3& param3) { CNamedEvent* pEvent = 0; if (pAgent) { pEvent = pAgent->findEvent(eventName); if (!pEvent) { int contextId = pAgent->GetContextId(); const CTagObjectDescriptor& meta = pAgent->GetDescriptor(); pEvent = findNamedEventTemplate(meta.ms_methods, eventName, contextId); } if (pEvent) { CNamedEvent3<ParamType1, ParamType2, ParamType3>* pEvent3 = CNamedEvent3<ParamType1, ParamType2, ParamType3>::DynamicCast(pEvent); if (pEvent3) { pEvent3->SetParam(pAgent, param1, param2, param3); } else { BEHAVIAC_ASSERT(0, "unregistered parameters %s", eventName); } pEvent->SetFired(pAgent, true); } else { BEHAVIAC_ASSERT(0, "unregistered event %s", eventName); } } } BEHAVIAC_FORCEINLINE void Agent::FireEvent(const char* eventName) { Agent::FireEvent(this, eventName); } template<class ParamType1> BEHAVIAC_FORCEINLINE void Agent::FireEvent(const char* eventName, const ParamType1& param1) { Agent::FireEvent(this, eventName, param1); } template<class ParamType1, class ParamType2> BEHAVIAC_FORCEINLINE void Agent::FireEvent(const char* eventName, const ParamType1& param1, const ParamType2& param2) { Agent::FireEvent(this, eventName, param1, param2); } template<class ParamType1, class ParamType2, class ParamType3> BEHAVIAC_FORCEINLINE void Agent::FireEvent(const char* eventName, const ParamType1& param1, const ParamType2& param2, const ParamType3& param3) { Agent::FireEvent(this, eventName, param1, param2, param3); } BEHAVIAC_API bool IsParVar(const char* variableName); BEHAVIAC_FORCEINLINE bool Agent::IsVariableExisting(const char* variableName) const { uint32_t variableId = MakeVariableId(variableName); return m_variables.IsExisting(variableId); } template<typename VariableType, bool bAgent> struct VariableGettterDispatcher { static VariableType* Get(const Variables& variables, const Agent* pAgent, uint32_t varId) { return variables.Get<VariableType>(pAgent, varId); } }; template<typename VariableType> struct VariableGettterDispatcher<VariableType, true> { static VariableType* Get(const Variables& variables, const Agent* pAgent, uint32_t varId) { VariableType* pp = (VariableType*)variables.Get<void*>(pAgent, varId); if (pp && *pp) { VariableType p = *pp; typedef PARAM_BASETYPE(VariableType) BaseAgentType; const char* nameBaseAgentType = GetClassTypeName((BaseAgentType*)0); BEHAVIAC_ASSERT(p->IsAKindOf(CStringID(nameBaseAgentType))); BEHAVIAC_UNUSED_VAR(p); BEHAVIAC_UNUSED_VAR(nameBaseAgentType); //BEHAVIAC_ASSERT(BaseAgentType::DynamicCast(*p)); BEHAVIAC_ASSERT(Agent::DynamicCast(p)); } return pp; } }; template<typename VariableType> BEHAVIAC_FORCEINLINE const VariableType& Agent::GetVariable(const char* variableName) const { //return *m_variables.Get<VariableType>(this, variableName); uint32_t variableId = MakeVariableId(variableName); return GetVariable<VariableType>(variableId); } template<typename VariableType> BEHAVIAC_FORCEINLINE const VariableType& Agent::GetVariable(uint32_t variableId) const { return *VariableGettterDispatcher<VariableType, behaviac::Meta::IsAgent<VariableType>::Result>::Get(m_variables, this, variableId); } template<typename VariableType, bool bAgent> struct VariableSettterDispatcher { static void Set(Variables& variables, Agent* pAgent, const CMemberBase* pMember, const char* variableName, const VariableType& value, uint32_t variableId) { variables.Set(pAgent, pMember, variableName, value, variableId); } }; template<typename VariableType> struct VariableSettterDispatcher<VariableType, true> { static void Set(Variables& variables, Agent* pAgent, const CMemberBase* pMember, const char* variableName, const VariableType& value, uint32_t variableId) { variables.Set(pAgent, pMember, variableName, (void*)value, variableId); } }; template<typename VariableType> BEHAVIAC_FORCEINLINE void Agent::SetVariable(const char* variableName, const VariableType& value) { uint32_t variableId = MakeVariableId(variableName); this->SetVariable(variableName, value, variableId); } template<typename VariableType> BEHAVIAC_FORCEINLINE void Agent::SetVariable(const char* variableName, const VariableType& value, uint32_t variableId) { if (variableId == 0) { variableId = MakeVariableId(variableName); } VariableSettterDispatcher<VariableType, behaviac::Meta::IsAgent<VariableType>::Result>::Set(m_variables, this, 0, variableName, value, variableId); } BEHAVIAC_FORCEINLINE void Agent::SetVariableFromString(const char* variableName, const char* valueStr) { m_variables.SetFromString(this, variableName, valueStr); } template<typename VariableType> BEHAVIAC_FORCEINLINE void Agent::Instantiate(const VariableType& value, const Property* property_) { m_variables.Instantiate(property_, value); } template<typename VariableType> BEHAVIAC_FORCEINLINE void Agent::UnInstantiate(const char* variableName) { m_variables.UnInstantiate<VariableType>(variableName); } template<typename VariableType> BEHAVIAC_FORCEINLINE void Agent::UnLoad(const char* variableName) { m_variables.UnLoad<VariableType>(variableName); } BEHAVIAC_FORCEINLINE bool Agent::Invoke(Agent* pAgent, const char* methodName) { const CMethodBase* pMethod = Agent::FindMethodBase(methodName); if (pMethod) { const_cast<CMethodBase*>(pMethod)->vCall(pAgent); return true; } return false; } template <typename P1> BEHAVIAC_FORCEINLINE bool Agent::Invoke(Agent* pAgent, const char* methodName, P1 p1) { const CMethodBase* pMethod = Agent::FindMethodBase(methodName); if (pMethod) { const_cast<CMethodBase*>(pMethod)->vCall(pAgent, &p1); return true; } return false; } template <typename P1, typename P2> BEHAVIAC_FORCEINLINE bool Agent::Invoke(Agent* pAgent, const char* methodName, P1 p1, P2 p2) { const CMethodBase* pMethod = Agent::FindMethodBase(methodName); if (pMethod) { const_cast<CMethodBase*>(pMethod)->vCall(pAgent, &p1, &p2); return true; } return false; } template <typename P1, typename P2, typename P3> BEHAVIAC_FORCEINLINE bool Agent::Invoke(Agent* pAgent, const char* methodName, P1 p1, P2 p2, P3 p3) { const CMethodBase* pMethod = Agent::FindMethodBase(methodName); if (pMethod) { const_cast<CMethodBase*>(pMethod)->vCall(pAgent, &p1, &p2, &p3); return true; } return false; } template <typename R> bool Agent::GetInvokeReturn(Agent* pAgent, const char* methodName, R& returnValue) { const CMethodBase* pMethod = Agent::FindMethodBase(methodName); if (pMethod) { const_cast<CMethodBase*>(pMethod)->GetReturnValue(pAgent, returnValue); return true; } return false; } template<typename TAGENT> BEHAVIAC_FORCEINLINE void Agent::RegisterTypeToMetas(bool bInternal) { //register the super AgentSuperRegister<typename TAGENT::super, Meta::IsAgent<typename TAGENT::super>::Result>::Register(); const char* typeFullName = TAGENT::GetClassTypeName(); AgentMetas_t& metas = Metas(); CStringID typeId(typeFullName); AgentMetas_t::const_iterator it = metas.find(typeId); if (it != metas.end()) { MetaInfo_t& meta = metas[typeId]; //if registered as the base class and now is registered directly, then set it as non-internal if (meta.bInternal && !bInternal) { meta.bInternal = bInternal; } } else { const char* baseTypeFullName = TAGENT::super::GetClassTypeName(); //filter out CTagObject if (string_icmp(baseTypeFullName, "CTagObject") == 0) { baseTypeFullName = 0; } metas[typeId] = MetaInfo_t(&TAGENT::GetObjectDescriptor(), typeFullName, baseTypeFullName, bInternal); } } template<typename TAGENT> BEHAVIAC_FORCEINLINE bool Agent::Register() { TAGENT::RegisterProperties(); //after TAGENT::RegisterProperties() RegisterTypeToMetas<TAGENT>(false); Factory().Register<TAGENT>(); return true; } template<typename TAGENT> BEHAVIAC_FORCEINLINE void Agent::UnRegister() { const char* typeName = TAGENT::GetClassTypeName(); AgentMetas_t& metas = Metas(); CStringID typeId(typeName); metas.erase(typeId); //Agent::UnRegisterProperties(meta); //handled in CleanupMetas Factory().UnRegister<TAGENT>(); } template<typename TAGENT> BEHAVIAC_FORCEINLINE bool Agent::RegisterName(const char* agentInstanceName, const wchar_t* displayName, const wchar_t* desc) { const char* agentInstanceNameAny = agentInstanceName; if (!agentInstanceNameAny) { agentInstanceNameAny = TAGENT::GetClassTypeName(); } AgentNames_t::iterator it = Agent::Names().find(agentInstanceNameAny); if (it == Agent::Names().end()) { const char* classFullName = TAGENT::GetClassTypeName(); Agent::Names()[agentInstanceNameAny] = AgentName_t(agentInstanceNameAny, classFullName, displayName, desc); return true; } return false; } template<typename TAGENT> BEHAVIAC_FORCEINLINE void Agent::UnRegisterName(const char* agentInstanceName) { const char* agentInstanceNameAny = agentInstanceName; if (!agentInstanceNameAny) { agentInstanceNameAny = TAGENT::GetClassTypeName(); } AgentNames_t::iterator it = Agent::Names().find(agentInstanceNameAny); if (it != Agent::Names().end()) { Agent::Names().erase(it); } } template<typename VariableType> BEHAVIAC_FORCEINLINE void Agent::SetVariableRegistry(const CMemberBase* pMember, const char* variableName, const VariableType& value, const char* staticClassName, uint32_t varableId) { bool bValidName = variableName && variableName[0] != '\0'; if (bValidName) { if (staticClassName) { int contextId = this->GetContextId(); Context& c = Context::GetContext(contextId); c.SetStaticVariable(pMember, variableName, value, staticClassName, varableId); } else { VariableSettterDispatcher<VariableType, behaviac::Meta::IsAgent<VariableType>::Result>::Set(this->m_variables, this, pMember, variableName, value, varableId); } } } template<typename VariableType> void TVariable<VariableType>::Log(const Agent* pAgent) { //BEHAVIAC_ASSERT(this->m_changed); behaviac::string valueStr = StringUtils::ToString(this->m_value); behaviac::string typeName = ::GetClassTypeName((VariableType*)0); behaviac::string full_name = this->m_name; if (this->m_pMember) { full_name = FormatString("%s::%s", this->m_pMember->GetClassNameString(), this->m_name.c_str()); } LogManager::GetInstance()->Log(pAgent, typeName.c_str(), full_name.c_str(), valueStr.c_str()); #if !defined(BEHAVIAC_RELEASE) this->m_changed = false; #endif } BEHAVIAC_FORCEINLINE void Variables::SetFromString(Agent* pAgent, const char* variableName, const char* valueStr) { BEHAVIAC_ASSERT(variableName && variableName[0] != '\0'); //to skip class name const char* variableNameOnly = GetNameWithoutClassName(variableName); const CMemberBase* pMember = pAgent->FindMember(variableNameOnly); uint32_t varId = MakeVariableId(variableNameOnly); Variables_t::iterator it = this->m_variables.find(varId); if (it != this->m_variables.end()) { IVariable* pVar = (IVariable*)it->second; pVar->SetFromString(pAgent, pMember, valueStr); } } template<typename VariableType> void Variables::Set(Agent* pAgent, const CMemberBase* pMember, const char* variableName, const VariableType& value, uint32_t varId) { BEHAVIAC_ASSERT(variableName && variableName[0] != '\0'); typedef TVariable<VariableType> VariableTypeType; VariableTypeType* pVar = 0; if (varId == 0) { varId = MakeVariableId(variableName); } else { BEHAVIAC_ASSERT(varId == MakeVariableId(variableName)); } Variables_t::iterator it = this->m_variables.find(varId); if (it == this->m_variables.end()) { if (!pMember) { if (pAgent) { pMember = pAgent->FindMember(variableName); } else { pMember = Agent::FindMemberBase(variableName); } } pVar = BEHAVIAC_NEW VariableTypeType(pMember, variableName, varId); m_variables[varId] = pVar; } else { pVar = (VariableTypeType*)it->second; //BEHAVIAC_ASSERT(pVar->GetTypeId() == GetClassTypeNumberId<VariableType>() || // (pVar->GetTypeId() == GetClassTypeNumberId<void*>() && behaviac::Meta::IsAgent<VariableType>::Result)); BEHAVIAC_ASSERT(pVar->GetTypeId() == GetClassTypeNumberId<VariableType>()); } pVar->SetValue(value, pAgent); } template<typename VariableType> VariableType* Variables::Get(const Agent* pAgent, uint32_t varId) const { typedef TVariable<VariableType> VariableTypeType; Variables_t::const_iterator it = this->m_variables.find(varId); if (it == this->m_variables.end()) { //possible static property CStringID varStrId(varId); const CMemberBase* pMember = pAgent->FindMember(varStrId); int typeId = ::GetClassTypeNumberId<VariableType>(); if (pMember && typeId == pMember->GetTypeId()) { void* pAddr = pMember->Get(pAgent, typeId); return (VariableType*)pAddr; } BEHAVIAC_ASSERT(false, "a compatible property is not found"); } else { //par VariableTypeType* pVar = (VariableTypeType*)it->second; BEHAVIAC_ASSERT(pVar->GetTypeId() == GetClassTypeNumberId<VariableType>()); if (pVar->GetTypeId() == GetClassTypeNumberId<VariableType>()) { const Property* refPropety = pVar->GetProperty(); if (refPropety) { const behaviac::string& ref = refPropety->GetRefName(); if (!ref.empty()) { return this->Get<VariableType>(pAgent, refPropety->GetRefNameId()); } } return &pVar->GetValue(pAgent); } } return 0; } template<typename VariableType> void TVariable<VariableType>::SetFromString(Agent* pAgent, const CMemberBase* pMember, const char* valueString) { if (valueString) { VariableType value; if (behaviac::StringUtils::FromString(valueString, value)) { if (!(Details::Equal(this->m_value, value))) { this->m_value = value; #if !defined(BEHAVIAC_RELEASE) this->m_changed = true; #endif if (pMember) { int typeId = ::GetClassTypeNumberId<VariableType>(); if (pMember && typeId == pMember->GetTypeId()) { void* pAddr = pMember->Get(pAgent, typeId); *(VariableType*)pAddr = value; } } } } } } template <typename T> const CMemberBase* GetMemberFromName(const CStringID& propertyId) { const CTagObjectDescriptor& obejctDesc = T::GetObjectDescriptor(); return obejctDesc.GetMember(propertyId); } }//namespace behaviac template <typename T> const T& ParamVariablePrimitive<T>::GetValue(const CTagObject* parent, const CTagObject* parHolder) const { if (this->prop && behaviac::Agent::DynamicCast(parent)) { behaviac::TProperty<T>* pT = (behaviac::TProperty<T>*)this->prop; return pT->GetValue((const behaviac::Agent*)parent, (const behaviac::Agent*)parHolder); } //return this->param; return GetValueSelector<T, behaviac::Meta::IsAgent<T>::Result, behaviac::Meta::IsPtr<T>::Result>::GetValue(this->param); } template <typename T> void ParamVariablePrimitive<T>::SetVariableRegistry(const CTagObject* parHolder, const T& value) { if (this->prop && behaviac::Agent::DynamicCast(parHolder)) { behaviac::TProperty<T>* pT = (behaviac::TProperty<T>*)this->prop; return pT->SetValue((behaviac::Agent*)parHolder, value); } } template <typename T> const T& ParamVariableStruct<T>::GetValue(const CTagObject* parent, const CTagObject* parHolder) const { if (this->prop && behaviac::Agent::DynamicCast(parent)) { behaviac::TProperty<T>* pT = (behaviac::TProperty<T>*)this->prop; return pT->GetValue((const behaviac::Agent*)parent, (const behaviac::Agent*)parHolder); } if (this->m_props.size() > 0) { for (PropsMap_t::const_iterator it = this->m_props.begin(); it !=this->m_props.end(); ++it) { const CStringID& propId = it->first; const behaviac::Property* pProperty = it->second; const CMemberBase* pM = behaviac::GetMemberFromName<T>(propId); pM->SetFromProperty((CTagObject*)&this->param, parHolder, pProperty); } } return this->param; } template <typename T> void ParamVariableStruct<T>::SetVariableRegistry(const CTagObject* parHolder, const T& value) { if (this->m_props.size() > 0) { for (PropsMap_t::iterator it = this->m_props.begin(); it !=this->m_props.end(); ++it) { const CStringID& propId = it->first; behaviac::Property* pProperty = it->second; const CMemberBase* pM = behaviac::GetMemberFromName<T>(propId); pProperty->SetFrom((behaviac::Agent*)&this->param, pM, (behaviac::Agent*)parHolder); } } if (this->prop && behaviac::Agent::DynamicCast(parHolder)) { behaviac::TProperty<T>* pT = (behaviac::TProperty<T>*)this->prop; pT->SetValue((behaviac::Agent*)parHolder, value); } }
27.458824
183
0.711482
Manistein
8178c334693a1d18a3f9a4c1e92a17296856b1a1
2,107
cpp
C++
polygon.cpp
RaviSriTejaKuriseti/OPENCV-IN-WSL1
2646c73b52a8cfd265d5440dc43065ae8b164c9b
[ "MIT" ]
null
null
null
polygon.cpp
RaviSriTejaKuriseti/OPENCV-IN-WSL1
2646c73b52a8cfd265d5440dc43065ae8b164c9b
[ "MIT" ]
null
null
null
polygon.cpp
RaviSriTejaKuriseti/OPENCV-IN-WSL1
2646c73b52a8cfd265d5440dc43065ae8b164c9b
[ "MIT" ]
null
null
null
#include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include <iostream> using namespace cv; using namespace std; int main( void ) { const int r = 100; Mat src = Mat::zeros( Size( 4*r, 4*r ), CV_8U ); vector<Point2f> vert(6); vert[0] = Point( 3*r/2, static_cast<int>(1.34*r) ); vert[1] = Point( 1*r, 2*r ); vert[2] = Point( 3*r/2, static_cast<int>(2.866*r) ); vert[3] = Point( 5*r/2, static_cast<int>(2.866*r) ); vert[4] = Point( 3*r, 2*r ); vert[5] = Point( 5*r/2, static_cast<int>(1.34*r) ); for( int i = 0; i < 6; i++ ) { line( src, vert[i], vert[(i+1)%6], Scalar( 255 ), 3 ); } vector<vector<Point> > contours; findContours( src, contours, RETR_TREE, CHAIN_APPROX_SIMPLE); Mat raw_dist( src.size(), CV_32F ); for( int i = 0; i < src.rows; i++ ) { for( int j = 0; j < src.cols; j++ ) { raw_dist.at<float>(i,j) = (float)pointPolygonTest( contours[0], Point2f((float)j, (float)i), true ); } } double minVal, maxVal; Point maxDistPt; // inscribed circle center minMaxLoc(raw_dist, &minVal, &maxVal, NULL, &maxDistPt); minVal = abs(minVal); maxVal = abs(maxVal); Mat drawing = Mat::zeros( src.size(), CV_8UC3 ); for( int i = 0; i < src.rows; i++ ) { for( int j = 0; j < src.cols; j++ ) { if( raw_dist.at<float>(i,j) < 0 ) { drawing.at<Vec3b>(i,j)[0] = (uchar)(255 - abs(raw_dist.at<float>(i,j)) * 255 / minVal); } else if( raw_dist.at<float>(i,j) > 0 ) { drawing.at<Vec3b>(i,j)[2] = (uchar)(255 - raw_dist.at<float>(i,j) * 255 / maxVal); } else { drawing.at<Vec3b>(i,j)[0] = 255; drawing.at<Vec3b>(i,j)[1] = 255; drawing.at<Vec3b>(i,j)[2] = 255; } } } circle(drawing, maxDistPt, (int)maxVal, Scalar(255,255,255)); imshow( "Source", src ); imshow( "Distance and inscribed circle", drawing ); waitKey(); return 0; }
33.444444
112
0.512577
RaviSriTejaKuriseti
81794ab8709d05625ce445c660b333289e4e88f6
5,189
hpp
C++
src/System/Synchronization.hpp
msisov/swiftshader
ba2cdf349b6ac061880e6f10997bfa7c5967f1b2
[ "Apache-2.0" ]
3
2020-07-07T19:45:20.000Z
2022-02-20T11:44:35.000Z
src/System/Synchronization.hpp
msisov/swiftshader
ba2cdf349b6ac061880e6f10997bfa7c5967f1b2
[ "Apache-2.0" ]
1
2020-02-19T06:44:54.000Z
2020-02-19T06:44:54.000Z
src/System/Synchronization.hpp
msisov/swiftshader
ba2cdf349b6ac061880e6f10997bfa7c5967f1b2
[ "Apache-2.0" ]
1
2020-06-03T16:14:54.000Z
2020-06-03T16:14:54.000Z
// Copyright 2019 The SwiftShader Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This file contains a number of synchronization primitives for concurrency. // // You may be tempted to change this code to unlock the mutex before calling // std::condition_variable::notify_[one,all]. Please read // https://issuetracker.google.com/issues/133135427 before making this sort of // change. #ifndef sw_Synchronization_hpp #define sw_Synchronization_hpp #include <assert.h> #include <chrono> #include <condition_variable> #include <queue> #include "marl/mutex.h" namespace sw { // TaskEvents is an interface for notifying when tasks begin and end. // Tasks can be nested and/or overlapping. // TaskEvents is used for task queue synchronization. class TaskEvents { public: // start() is called before a task begins. virtual void start() = 0; // finish() is called after a task ends. finish() must only be called after // a corresponding call to start(). virtual void finish() = 0; // complete() is a helper for calling start() followed by finish(). inline void complete() { start(); finish(); } protected: virtual ~TaskEvents() = default; }; // WaitGroup is a synchronization primitive that allows you to wait for // collection of asynchronous tasks to finish executing. // Call add() before each task begins, and then call done() when after each task // is finished. // At the same time, wait() can be used to block until all tasks have finished. // WaitGroup takes its name after Golang's sync.WaitGroup. class WaitGroup : public TaskEvents { public: // add() begins a new task. void add() { marl::lock lock(mutex); ++count_; } // done() is called when a task of the WaitGroup has been completed. // Returns true if there are no more tasks currently running in the // WaitGroup. bool done() { marl::lock lock(mutex); assert(count_ > 0); --count_; if(count_ == 0) { condition.notify_all(); } return count_ == 0; } // wait() blocks until all the tasks have been finished. void wait() { marl::lock lock(mutex); lock.wait(condition, [this]() REQUIRES(mutex) { return count_ == 0; }); } // wait() blocks until all the tasks have been finished or the timeout // has been reached, returning true if all tasks have been completed, or // false if the timeout has been reached. template<class CLOCK, class DURATION> bool wait(const std::chrono::time_point<CLOCK, DURATION> &timeout) { marl::lock lock(mutex); return condition.wait_until(lock, timeout, [this]() REQUIRES(mutex) { return count_ == 0; }); } // count() returns the number of times add() has been called without a call // to done(). // Note: No lock is held after count() returns, so the count may immediately // change after returning. int32_t count() { marl::lock lock(mutex); return count_; } // TaskEvents compliance void start() override { add(); } void finish() override { done(); } private: marl::mutex mutex; int32_t count_ GUARDED_BY(mutex) = 0; std::condition_variable condition; }; // Chan is a thread-safe FIFO queue of type T. // Chan takes its name after Golang's chan. template<typename T> class Chan { public: Chan(); // take returns the next item in the chan, blocking until an item is // available. T take(); // tryTake returns a <T, bool> pair. // If the chan is not empty, then the next item and true are returned. // If the chan is empty, then a default-initialized T and false are returned. std::pair<T, bool> tryTake(); // put places an item into the chan, blocking if the chan is bounded and // full. void put(const T &v); // Returns the number of items in the chan. // Note: that this may change as soon as the function returns, so should // only be used for debugging. size_t count(); private: marl::mutex mutex; std::queue<T> queue GUARDED_BY(mutex); std::condition_variable added; }; template<typename T> Chan<T>::Chan() {} template<typename T> T Chan<T>::take() { marl::lock lock(mutex); // Wait for item to be added. lock.wait(added, [this]() REQUIRES(mutex) { return queue.size() > 0; }); T out = queue.front(); queue.pop(); return out; } template<typename T> std::pair<T, bool> Chan<T>::tryTake() { marl::lock lock(mutex); if(queue.size() == 0) { return std::make_pair(T{}, false); } T out = queue.front(); queue.pop(); return std::make_pair(out, true); } template<typename T> void Chan<T>::put(const T &item) { marl::lock lock(mutex); queue.push(item); added.notify_one(); } template<typename T> size_t Chan<T>::count() { marl::lock lock(mutex); return queue.size(); } } // namespace sw #endif // sw_Synchronization_hpp
25.688119
95
0.702255
msisov
817b44fde868444fc46c28f75913f1bfb212302a
2,047
cpp
C++
Applications/LogReporter.cpp
kabukunz/GeometricTools
bbc55cdef89a877f06310fdb6c6248205eae704b
[ "BSL-1.0" ]
null
null
null
Applications/LogReporter.cpp
kabukunz/GeometricTools
bbc55cdef89a877f06310fdb6c6248205eae704b
[ "BSL-1.0" ]
null
null
null
Applications/LogReporter.cpp
kabukunz/GeometricTools
bbc55cdef89a877f06310fdb6c6248205eae704b
[ "BSL-1.0" ]
null
null
null
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 4.0.2019.08.13 #include <Applications/GTApplicationsPCH.h> #include <Applications/LogReporter.h> using namespace gte; LogReporter::~LogReporter() { if (mLogToStdout) { Logger::Unsubscribe(mLogToStdout.get()); } if (mLogToFile) { Logger::Unsubscribe(mLogToFile.get()); } #if defined(GTE_USE_MSWINDOWS) if (mLogToOutputWindow) { Logger::Unsubscribe(mLogToOutputWindow.get()); } if (mLogToMessageBox) { Logger::Unsubscribe(mLogToMessageBox.get()); } #endif } LogReporter::LogReporter(std::string const& logFile, int logFileFlags, int logStdoutFlags, int logMessageBoxFlags, int logOutputWindowFlags) : mLogToFile(nullptr), mLogToStdout(nullptr) #if defined(GTE_USE_MSWINDOWS) , mLogToMessageBox(nullptr), mLogToOutputWindow(nullptr) #endif { if (logFileFlags != Logger::Listener::LISTEN_FOR_NOTHING) { mLogToFile = std::make_unique<LogToFile>(logFile, logFileFlags); Logger::Subscribe(mLogToFile.get()); } if (logStdoutFlags != Logger::Listener::LISTEN_FOR_NOTHING) { mLogToStdout = std::make_unique<LogToStdout>(logStdoutFlags); Logger::Subscribe(mLogToStdout.get()); } #if defined(GTE_USE_MSWINDOWS) if (logMessageBoxFlags != Logger::Listener::LISTEN_FOR_NOTHING) { mLogToMessageBox = std::make_unique<LogToMessageBox>(logMessageBoxFlags); Logger::Subscribe(mLogToMessageBox.get()); } if (logOutputWindowFlags != Logger::Listener::LISTEN_FOR_NOTHING) { mLogToOutputWindow = std::make_unique<LogToOutputWindow>(logOutputWindowFlags); Logger::Subscribe(mLogToOutputWindow.get()); } #endif }
27.662162
88
0.668784
kabukunz
817bba6a75790eebe32b49d453f61a894c62e9c7
1,520
cpp
C++
src/preprocessor/main.cpp
16bitnohito/cc
f1b1a15fd649ecf2c8dd6305b278d57e0887290b
[ "MIT" ]
null
null
null
src/preprocessor/main.cpp
16bitnohito/cc
f1b1a15fd649ecf2c8dd6305b278d57e0887290b
[ "MIT" ]
null
null
null
src/preprocessor/main.cpp
16bitnohito/cc
f1b1a15fd649ecf2c8dd6305b278d57e0887290b
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <string> #include <system_error> #include <vector> #include <preprocessor/logger.h> #include <preprocessor/preprocessor.h> #include <preprocessor/utility.h> using namespace pp; using namespace std; #if HOST_PLATFORM == PLATFORM_WINDOWS int wmain(int argc, wchar_t* argv[]) { #else int main(int argc, char* argv[]) { #endif try { vector<String> args; args.reserve(argc); for (int i = 0; i < argc; ++i) { args.push_back(internal_string(argv[i])); } setup_console(); init_calculator(); init_preprocessor(); Options opts; if (!opts.parse_options(args)) { opts.print_usage(); return EXIT_FAILURE; } Preprocessor pp(opts); return pp.run(); } catch (const system_error& e) { auto& ec = e.code(); #if HOST_PLATFORM == PLATFORM_WINDOWS if (ec.category() == system_category() || ec.category() == lib::win32util::win32_category()) { // 挙動が異なると分かっているものだけ特別扱い。 auto message = lib::win32util::mbs_to_u8s(e.what()); log_error(T_("{}: {}({}:{:#x})"), __func__, lib::win32util::as_native(message.c_str()), ec.category().name(), ec.value()); } else { log_error("{}: {}({}:{})", __func__, e.what(), ec.category().name(), ec.value()); } #else log_error("{}: {}({}{:x})", __func__, e.what(), ec.category().name(), ec.value()); #endif } catch (const exception& e) { log_error(T_("{}: {}"), __func__, e.what()); } catch (...) { log_error(T_("{}: {}"), __func__, "unknown exception"); } return EXIT_FAILURE; }
24.918033
84
0.636184
16bitnohito
817da4ec44723aa089d402ba948564e2a81480bf
11,298
cpp
C++
Rasterizer/src/Rasterizer.cpp
litelawliet/ISARTRasterizer
329ed70ea830cfff286c01d8efa5e726276f1fcd
[ "MIT" ]
1
2020-03-23T14:36:02.000Z
2020-03-23T14:36:02.000Z
Rasterizer/src/Rasterizer.cpp
litelawliet/ISARTRasterizer
329ed70ea830cfff286c01d8efa5e726276f1fcd
[ "MIT" ]
null
null
null
Rasterizer/src/Rasterizer.cpp
litelawliet/ISARTRasterizer
329ed70ea830cfff286c01d8efa5e726276f1fcd
[ "MIT" ]
null
null
null
#include "Rasterizer.h" #include "Maths/Vec3.h" #include "Maths/Vec4.h" #include "Light.h" #include <algorithm> #include <iostream> #include <iomanip> #include <vector> using namespace Maths::Vector; Rasterizer::Rasterizer(SDL_Renderer * p_renderer, SDL_Window * p_window, const unsigned int p_width, const unsigned int p_height) : m_renderer{ p_renderer }, m_window{ p_window }, m_width{ p_width }, m_height{ p_height }, m_totalPixels{ m_width * m_height } { m_depthBuffer = new double[m_width * m_height]{}; } Rasterizer::~Rasterizer() { delete[] m_depthBuffer; } void Rasterizer::RenderScene(Scene * p_scene, Texture * p_targetTexture) { #if BENCHMARK m_tmr.reset(); #endif if (p_targetTexture != nullptr) { m_texture = p_targetTexture; m_texture->ResetColors(); } if (m_scene != nullptr) { m_scene = p_scene; ResetBuffer(); size_t i = -1; constexpr auto NB_POINTS_BY_TRIANGLE = 3; for (auto& entity: m_scene->GetEntities()) //for (size_t i = 0; i < m_scene->GetEntities().size(); ++i) { ++i; //Entity entity = m_scene->GetEntities()[i]; Mat4 transformation = entity.GetTransformation(); std::shared_ptr<Mesh> mesh = entity.GetMesh(); if (mesh != nullptr) { // Draw pixels Vec4 transformedVertex[NB_POINTS_BY_TRIANGLE]; Vertex triangleVertices[NB_POINTS_BY_TRIANGLE]; for (size_t j = 0; j < mesh->m_indices.size() - 2; j += 3) { for (unsigned int k = 0; k < NB_POINTS_BY_TRIANGLE; ++k) { transformedVertex[k] = transformation * Vec4{ mesh->m_vertices[mesh->m_indices[j + k]].m_position }; // Scale... transformedVertex[k] = Mat4::CreateRotationMatrix(m_angle, Vec3{ 1.0f, 0.0f, 0.0f }) * Mat4::CreateRotationMatrix(m_angle, Vec3{ 0.0f, 0.0f, 1.0f }) * Mat4::CreateRotationMatrix(m_angle, Vec3{ 0.0f, 1.0f, 0.0f }) * transformedVertex[k]; //transformedVertex[k] = Mat4::CreateZRotationMatrix(0.0f) * Mat4::CreateXRotationMatrix(m_angle) * Mat4::CreateYRotationMatrix(m_angle) * transformedVertex[k]; transformedVertex[k] = Mat4::CreateTranslationMatrix(Vec3{ i % 2 == 0 ? -1.0f : 1.0f, 0.0f, 2.0f }) * transformedVertex[k]; //transformedVertex[k] = Mat4::CreateTransformMatrix(Vec3{ 82.0f, 96.0f, 0.0f }, Vec3{ i % 2 == 0 ? -2.5f : 2.5f, 0.0f, 2.0f } , Vec3{ 1.0f, 1.0f, 1.0f }) * Vec4 { mesh->vertices[mesh->indices[j + k]].position }; //transformedVertex[k].Homogenize(); //transformedVertex[k] = Mat4::CreateRotationMatrix(0, Vec3{ 1.0f, 1.0f, 0.0f }) * transformedVertex[k]; triangleVertices[k] = Vertex{ (transformedVertex[k].m_x / 5.0f + 1.0f) * 0.5f * m_width, m_height - (transformedVertex[k].m_y / 5.0f + 1.0f) * 0.5f * m_height , transformedVertex[k].m_z }; } // call the drawTriangle function IF in screen, some changes have to be done WHEN camera will be added if (IsTriangleOnScreenSpace(triangleVertices)) { // backface culling // Plane equation of 3 vetices //std::cout << triangleVertices[0].ToString() << '\n'; auto u{ Vec3::GetSubstractsVector(triangleVertices[0].m_position, triangleVertices[1].m_position) }; //std::cout << u.ToString() << '\n'; auto v{ Vec3::GetSubstractsVector(triangleVertices[0].m_position, triangleVertices[2].m_position) }; const auto normalVector = Vec3::GetCrossProduct(u, v); //std::cout << normalVector.ToString(); if (normalVector.m_z > 0) { DrawTriangle(triangleVertices[0], triangleVertices[1], triangleVertices[2], transformedVertex[0]); } } } } } } DrawTexture(); #if BENCHMARK const auto frameDuration = m_tmr.elapsed(); const auto instantFps = 1.00 / frameDuration; m_addedDurationOverASecond += frameDuration; if (m_addedDurationOverASecond > 1.00) { ++m_numberOfSecondsLast; m_queuedFps += instantFps; if (m_numberOfSecondsLast == 2) { m_averageFps = m_queuedFps / m_numberOfSecondsLast; m_queuedFps = 0.0; m_numberOfSecondsLast = 0; } m_addedDurationOverASecond = 0.00; } std::cout << "Frame duration: " << m_tmr.elapsed() << " sec\nInstantly FPS: " << round(instantFps) << "\n-->Average FPS: " << round(m_averageFps) << "\n------------------------------\n"; #endif m_angle -= 2.0f; } void Rasterizer::ResetBuffer() const { std::fill_n(m_depthBuffer, m_totalPixels, std::numeric_limits<double>::infinity()); } void Rasterizer::SetScene(Scene * p_scene) { m_scene = p_scene; } void Rasterizer::SetTexture(Texture * p_texture) { m_texture = p_texture; } void Rasterizer::SetRenderer(SDL_Renderer * p_renderer) { m_renderer = p_renderer; } void Rasterizer::SetWindow(SDL_Window * p_window) { m_window = p_window; } void Rasterizer::SetMode(const RenderingMode p_mode) { m_mode = p_mode; } Rasterizer::RenderingMode Rasterizer::GetMode() const { return m_mode; } void Rasterizer::DrawTriangle(Vertex p_v1, Vertex p_v2, Vertex p_v3, Vec4 p_vec4_transform) { //SortVerticesAscendingByY(&p_v1, &p_v2, &p_v3); switch (m_mode) { case RenderingMode::RED: m_standardColor = Color::RED; break; case RenderingMode::GREEN: m_standardColor = Color::GREEN; break; case RenderingMode::BLUE: m_standardColor = Color::BLUE; break; default: break; } /* check for trivial case of bottom-flat triangle //if (p_v2.m_position.m_y == p_v3.m_position.m_y) { FillBottomFlatTriangle(p_v1, p_v2, p_v3, p_vec4_transform); } // check for trivial case of top-flat triangle else if (p_v1.m_position.m_y == p_v2.m_position.m_y) { FillTopFlatTriangle(p_v1, p_v2, p_v3, p_vec4_transform); } else { // general case - split the triangle in a top flat and bottom-flat one const Vertex v4{ p_v1.m_position.m_x + (static_cast<float>(p_v2.m_position.m_y - p_v1.m_position.m_y) / static_cast<float>(p_v3.m_position.m_y - p_v1.m_position.m_y)) * (p_v3.m_position.m_x - p_v1.m_position.m_x), p_v2.m_position.m_y, 0.0f }; FillBottomFlatTriangle(p_v1, p_v2, v4, p_vec4_transform); FillTopFlatTriangle(p_v2, v4, p_v3, p_vec4_transform); }*/ /* get the bounding box of the triangle */ int maxX = static_cast<int>(std::max(p_v1.m_position.m_x, std::max(p_v2.m_position.m_x, p_v3.m_position.m_x))); int minX = static_cast<int>(std::min(p_v1.m_position.m_x, std::min(p_v2.m_position.m_x, p_v3.m_position.m_x))); int maxY = static_cast<int>(std::max(p_v1.m_position.m_y, std::max(p_v2.m_position.m_y, p_v3.m_position.m_y))); int minY = static_cast<int>(std::min(p_v1.m_position.m_y, std::min(p_v2.m_position.m_y, p_v3.m_position.m_y))); Vertex v0{ p_v3 - p_v1 }; Vertex v1{ p_v2 - p_v1 }; for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { Vertex p{ static_cast<float>(x), static_cast<float>(y), 1.0f }; Vertex v2{ p - p_v1 }; // Color weight float w1 = 0.0f; float w2 = 0.0f; float w3 = 0.0f; double zIndex = std::numeric_limits<double>::infinity(); if (IsPixelOnScreen(x, y)) { //std::cout << "allo ???\n"; // Calculate the color of the current pixel (x;y) using Barycentric coordinates : w1 = ((p_v2.m_position.m_y - p_v3.m_position.m_y) * (x - p_v3.m_position.m_x) + (p_v3.m_position.m_x - p_v2.m_position.m_x) * (y - p_v3.m_position.m_y)) / ((p_v2.m_position.m_y - p_v3.m_position.m_y) * (p_v1.m_position.m_x - p_v3.m_position.m_x) + (p_v3.m_position.m_x - p_v2.m_position.m_x) * (p_v1.m_position.m_y - p_v3.m_position.m_y)); w2 = ((p_v3.m_position.m_y - p_v1.m_position.m_y) * (x - p_v3.m_position.m_x) + (p_v1.m_position.m_x - p_v3.m_position.m_x) * (y - p_v3.m_position.m_y)) / ((p_v2.m_position.m_y - p_v3.m_position.m_y) * (p_v1.m_position.m_x - p_v3.m_position.m_x) + (p_v3.m_position.m_x - p_v2.m_position.m_x) * (p_v1.m_position.m_y - p_v3.m_position.m_y)); w3 = 1 - w1 - w2; //z_index = ( (1 / v1.position.z * w1 + 1 / v2.position.z * w2 + 1 / v3.position.z * w3)); // pixel z precise zIndex = 1 / (w1 / p_v1.m_position.m_z + w2 / p_v2.m_position.m_z + w3 / p_v3.m_position.m_z); // fce z approximation //z_index = v1.position.z * w3 + v2.position.z * w1 + v3.position.z * w2; if (m_mode == RenderingMode::INTERPOLATED) { const auto r = static_cast<unsigned char>(ceil((w1 * 100) * 255 / 100)); const auto g = static_cast<unsigned char>(ceil((w2 * 100) * 255 / 100)); const auto b = static_cast<unsigned char>(ceil((w3 * 100) * 255 / 100)); m_standardColor.m_r = r; m_standardColor.m_g = g; m_standardColor.m_b = b; m_standardColor.m_a = 255; } float dot00 = v0.DotProduct(v0); float dot01 = v0.DotProduct(v1); float dot02 = v0.DotProduct(v2); float dot11 = v1.DotProduct(v1); float dot12 = v1.DotProduct(v2); float invDenom = 1 / (dot00 * dot11 - dot01 * dot01); float u = (dot11 * dot02 - dot01 * dot12) * invDenom; float v = (dot00 * dot12 - dot01 * dot02) * invDenom; //std::cout << u << " : " << v << '\n'; if ((u >= 0.0f) && (v >= 0.0f) && (u + v < 1.0f)) { //std::cout << "allo ???\n"; // barycentric formula if (zIndex < m_depthBuffer[y * m_width + x]) { m_depthBuffer[y * m_width + x] = zIndex; m_texture->SetPixelColor(x, y, m_scene->GetLights()[0].CalculateColor(Color{ m_standardColor.m_r, m_standardColor.m_g, m_standardColor.m_b, m_standardColor.m_a }, Vec3{ w1, w2, w3 }, p_vec4_transform)); } } } } } } void Rasterizer::SortVerticesAscendingByY(Vertex * p_v1, Vertex * p_v2, Vertex * p_v3) const { std::vector<Vertex> vertex = { *p_v1, *p_v2, *p_v3 }; std::sort(vertex.begin(), vertex.end()); *p_v1 = vertex[0]; *p_v2 = vertex[1]; *p_v3 = vertex[2]; } void Rasterizer::DrawTexture() const { #if BENCHMARK auto nbPixels = 0; #endif const auto currentPixels = m_texture->GetPixels(); const auto oldPixels = m_texture->GetOldPixels(); const auto height = m_texture->GetHeight(); const auto width = m_texture->GetWidth(); for (unsigned int i = 0, rowOffset, finalIndex; i < height; ++i) { rowOffset = i * width; for (unsigned int j = 0; j < width; ++j) { finalIndex = rowOffset + j; if (currentPixels[finalIndex] != oldPixels[finalIndex]) { SDL_SetRenderDrawColor(m_renderer, currentPixels[finalIndex].m_r, currentPixels[finalIndex].m_g, currentPixels[finalIndex].m_b, currentPixels[finalIndex].m_a); SDL_RenderDrawPoint(m_renderer, j, i); m_texture->SetOldPixelColor(j, i, currentPixels[finalIndex]); #if BENCHMARK ++nbPixels; #endif } } } #if BENCHMARK std::cout << "Pixels drawn: " << nbPixels << '\n'; #endif } bool Rasterizer::IsTriangleOnScreenSpace(Vertex * p_vertices) const { return ((p_vertices[0].m_position.m_x > 0 || p_vertices[1].m_position.m_x > 0 || p_vertices[2].m_position.m_x > 0) && (p_vertices[0].m_position.m_x < m_width || p_vertices[1].m_position.m_x < m_width || p_vertices[2].m_position.m_x < m_width)) && ((p_vertices[0].m_position.m_y > 0 || p_vertices[1].m_position.m_y > 0 || p_vertices[2].m_position.m_y > 0) && (p_vertices[0].m_position.m_y < m_height || p_vertices[1].m_position.m_y < m_height || p_vertices[2].m_position.m_y < m_height)); } bool Rasterizer::IsPixelOnScreen(const unsigned int p_x, const unsigned int p_y) const { return p_x > 0 && p_x < m_width && (p_y > 0 && p_y < m_height); }
34.03012
242
0.66587
litelawliet
81801ca68111b2ae0d676ad91cc4fb7e510343a9
722
cpp
C++
kviewer.cpp
CryFeiFei/KTodo
cee290e69ce050810c23e23b2a24e2849251b7e4
[ "MIT" ]
3
2019-12-12T02:27:25.000Z
2021-06-21T02:48:59.000Z
kviewer.cpp
CryFeiFei/KTodo
cee290e69ce050810c23e23b2a24e2849251b7e4
[ "MIT" ]
null
null
null
kviewer.cpp
CryFeiFei/KTodo
cee290e69ce050810c23e23b2a24e2849251b7e4
[ "MIT" ]
null
null
null
#include "kviewer.h" #include <QSplitter> #include <QVBoxLayout> #include "kleftwidget.h" #include "ktodowidget.h" KViewer::KViewer(QWidget *parent) : QWidget(parent) { QVBoxLayout* mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(0, 0, 0, 0); m_splitter = new QSplitter(Qt::Horizontal, this); KLeftWidget* leftWidget = new KLeftWidget(this); KTodoWidget* todoWidget = new KTodoWidget(this); // todoWidget->setStyleSheet("background-color: red"); m_splitter->addWidget(leftWidget); m_splitter->addWidget(todoWidget); m_splitter->setHandleWidth(0); m_splitter->setStretchFactor(1, 1); // m_splitter->setCollapsible(0, false); mainLayout->addWidget(m_splitter); setLayout(mainLayout); }
24.066667
54
0.753463
CryFeiFei
8180420848baf101ea0e8a97c8a4e537855eeefe
7,426
cpp
C++
poly.cpp
shibatch/rectdetect
2d303e0bcb915a0e82178fa197f7e67de822f4e8
[ "MIT" ]
51
2018-12-18T03:36:39.000Z
2022-03-30T10:42:25.000Z
poly.cpp
archit120/rectdetect
2d303e0bcb915a0e82178fa197f7e67de822f4e8
[ "MIT" ]
4
2018-12-18T06:00:45.000Z
2019-11-18T09:51:55.000Z
poly.cpp
archit120/rectdetect
2d303e0bcb915a0e82178fa197f7e67de822f4e8
[ "MIT" ]
16
2018-12-18T12:07:04.000Z
2022-02-16T21:29:04.000Z
// Copyright Naoki Shibata 2018. Distributed under the MIT License. #ifdef _MSC_VER #define _USE_MATH_DEFINES #define _CRT_SECURE_NO_WARNINGS #endif #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <stdint.h> #include <math.h> #include <time.h> //#include <sys/time.h> #define CL_USE_DEPRECATED_OPENCL_1_2_APIS #include <CL/cl.h> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cv; #include "helper.h" #include "oclhelper.h" #include "oclimgutil.h" #include "oclpolyline.h" int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "Usage : %s <image file name> [<device number>]\nThe program will threshold the image, apply CCL,\nand output the result to output.png.\n", argv[0]); fprintf(stderr, "\nAvailable OpenCL Devices :\n"); simpleGetDevice(-1); exit(-1); } // int did = 0; if (argc >= 3) did = atoi(argv[2]); cl_device_id device = simpleGetDevice(did); printf("%s\n", getDeviceName(device)); cl_context context = simpleCreateContext(device); cl_command_queue queue = clCreateCommandQueue(context, device, CL_QUEUE_PROFILING_ENABLE, NULL); // oclimgutil_t *oclimgutil = init_oclimgutil(device, context); oclpolyline_t *oclpolyline = init_oclpolyline(device, context); // Mat rimg = imread(argv[1], CV_LOAD_IMAGE_COLOR); if( rimg.data == NULL ) exitf(-1, "Could not load %s\n", argv[1]); if (rimg.channels() != 3) exitf(-1, "nChannels != 3\n"); Mat img = rimg.clone(); int iw = img.cols, ih = img.rows, ws = img.step; uint8_t *data = (uint8_t *)img.data; // cl_int *buf0 = (cl_int *)allocatePinnedMemory(iw * ih * sizeof(cl_int), context, queue); cl_int *buf1 = (cl_int *)allocatePinnedMemory(iw * ih * sizeof(cl_int), context, queue); cl_int *buf2 = (cl_int *)calloc(iw * ih * sizeof(cl_int), 1); cl_int *buf3 = (cl_int *)calloc(iw * ih * sizeof(cl_int), 1); cl_int *buf4 = (cl_int *)calloc(iw * ih * sizeof(cl_int), 1); cl_int *buf5 = (cl_int *)calloc(iw * ih * sizeof(cl_int), 1); cl_int *buf6 = (cl_int *)calloc(iw * ih * sizeof(cl_int), 1); cl_int *buf7 = (cl_int *)calloc(iw * ih * sizeof(cl_int), 1); cl_int *buf8 = (cl_int *)calloc(iw * ih * sizeof(cl_int), 1); cl_int *buf9 = (cl_int *)calloc(iw * ih * sizeof(cl_int), 1); memset(buf0, 0, iw * ih * sizeof(cl_int)); memset(buf1, 0, iw * ih * sizeof(cl_int)); cl_int *bufBig = (cl_int *)calloc(iw * ih * sizeof(cl_int) * 4, 1); cl_int *bufLS = (cl_int *)calloc(iw * ih * sizeof(cl_int) * 4, 1); memcpy(buf0, data, ws * ih); cl_mem mem0 = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, iw * ih * sizeof(cl_int), buf0, NULL); cl_mem mem1 = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, iw * ih * sizeof(cl_int), buf1, NULL); cl_mem mem2 = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, iw * ih * sizeof(cl_int), buf2, NULL); cl_mem mem3 = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, iw * ih * sizeof(cl_int), buf3, NULL); cl_mem mem4 = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, iw * ih * sizeof(cl_int), buf4, NULL); cl_mem mem5 = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, iw * ih * sizeof(cl_int), buf5, NULL); cl_mem mem6 = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, iw * ih * sizeof(cl_int), buf6, NULL); cl_mem mem7 = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, iw * ih * sizeof(cl_int), buf7, NULL); cl_mem mem8 = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, iw * ih * sizeof(cl_int), buf8, NULL); cl_mem mem9 = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, iw * ih * sizeof(cl_int), buf9, NULL); cl_mem memBig = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, iw * ih * sizeof(cl_int) * 4, bufBig, NULL); cl_mem memLS = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, iw * ih * sizeof(cl_int) * 4, bufLS, NULL); // ce(clFinish(queue)); oclimgutil_convert_plab_bgr(oclimgutil, mem4, mem0, iw, ih, ws, queue, NULL); oclimgutil_unpack_f_f_f_plab(oclimgutil, mem1, mem2, mem3, mem4, iw, ih, queue, NULL); oclimgutil_iirblur_f_f(oclimgutil, mem0, mem1, mem4, mem5, 2, iw, ih, queue, NULL); oclimgutil_iirblur_f_f(oclimgutil, mem1, mem2, mem4, mem5, 2, iw, ih, queue, NULL); oclimgutil_iirblur_f_f(oclimgutil, mem2, mem3, mem4, mem5, 2, iw, ih, queue, NULL); oclimgutil_pack_plab_f_f_f(oclimgutil, mem4, mem0, mem1, mem2, iw, ih, queue, NULL); oclimgutil_edgevec_f2_f(oclimgutil, memBig, mem0, iw, ih, queue, NULL); oclimgutil_edge_f_plab(oclimgutil, mem5, mem4, iw, ih, queue, NULL); oclimgutil_thinthres_f_f_f2(oclimgutil, mem2, mem5, memBig, iw, ih, queue, NULL); oclimgutil_threshold_f_f(oclimgutil, mem9, mem2, 0.0, 0.0, 1.0, iw * ih, queue, NULL); oclimgutil_cast_i_f(oclimgutil, mem8, mem9, 1, iw * ih, queue, NULL); oclimgutil_label8x_int_int(oclimgutil, mem3, mem8, mem9, 0, iw, ih, queue, NULL); // out, in, tmp oclimgutil_clear(oclimgutil, mem4, iw*ih*4, queue, NULL); oclimgutil_calcStrength(oclimgutil, mem4, mem2, mem3, iw, ih, queue, NULL); // out, edge, label oclimgutil_filterStrength(oclimgutil, mem3, mem4, 500, iw, ih, queue, NULL); // label, str oclimgutil_threshold_i_i(oclimgutil, mem3, mem3, 0, 0, 1, iw * ih, queue, NULL); oclpolyline_execute(oclpolyline, memLS, iw*ih*4*4, mem0, mem3, memBig, mem4, mem5, mem6, mem7, mem8, mem9, 1, 20, iw, ih, queue, NULL); // ce(clEnqueueReadBuffer(queue, mem0, CL_TRUE, 0, iw * ih * sizeof(cl_int), buf0, 0, NULL, NULL)); ce(clEnqueueReadBuffer(queue, mem1, CL_TRUE, 0, iw * ih * sizeof(cl_int), buf1, 0, NULL, NULL)); ce(clEnqueueReadBuffer(queue, memLS, CL_TRUE, 0, iw * ih * sizeof(cl_int) * 4, bufLS, 0, NULL, NULL)); ce(clFinish(queue)); // //memcpy(data, buf0, ws*ih); memset(data, 0, ws * ih); int n = bufLS[0]; linesegment_t *ls = ((linesegment_t *)bufLS); for(int i=1;i<=n;i++) { // >>>> This starts from 1 <<<< if (ls[i].polyid == 0) continue; if (ls[i].leftPtr > 0) continue; int cnt = 0; for(int j=i;j > 0;j = ls[j].rightPtr, cnt++) { #ifdef _MSC_VER if (ls[j].x0 < 0 || ls[j].x0 >= iw || ls[j].x1 < 0 || ls[j].x1 >= iw || ls[j].y0 < 0 || ls[j].y0 >= ih || ls[j].y1 < 0 || ls[j].y1 >= ih) continue; #endif line(img, cvPoint(ls[j].x0, ls[j].y0), cvPoint(ls[j].x1, ls[j].y1), (cnt & 1) ? Scalar(100, 100, 255) : Scalar(255, 255, 100), 1, 8, 0); } } imwrite("output.png", img); // dispose_oclpolyline(oclpolyline); dispose_oclimgutil(oclimgutil); ce(clReleaseMemObject(memLS)); ce(clReleaseMemObject(memBig)); ce(clReleaseMemObject(mem9)); ce(clReleaseMemObject(mem8)); ce(clReleaseMemObject(mem7)); ce(clReleaseMemObject(mem6)); ce(clReleaseMemObject(mem5)); ce(clReleaseMemObject(mem4)); ce(clReleaseMemObject(mem3)); ce(clReleaseMemObject(mem2)); ce(clReleaseMemObject(mem1)); ce(clReleaseMemObject(mem0)); free(bufLS); free(bufBig); free(buf9); free(buf8); free(buf7); free(buf6); free(buf5); free(buf4); free(buf3); free(buf2); freePinnedMemory(buf1, context, queue); freePinnedMemory(buf0, context, queue); //ce(clReleaseProgram(program)); ce(clReleaseCommandQueue(queue)); ce(clReleaseContext(context)); // exit(0); }
37.695431
169
0.68314
shibatch
818269f1283f0c9eeceb7ea988300c4396691e64
494
cpp
C++
src/system/kernel/arch/aarch64/arch_timer.cpp
korli/haiku-jarek
c0cdd1413970ec2ca2cc7fab623f20161b1cec0b
[ "MIT" ]
1
2021-08-31T01:47:13.000Z
2021-08-31T01:47:13.000Z
src/system/kernel/arch/aarch64/arch_timer.cpp
korli/haiku-jarek
c0cdd1413970ec2ca2cc7fab623f20161b1cec0b
[ "MIT" ]
null
null
null
src/system/kernel/arch/aarch64/arch_timer.cpp
korli/haiku-jarek
c0cdd1413970ec2ca2cc7fab623f20161b1cec0b
[ "MIT" ]
3
2018-12-17T13:07:38.000Z
2021-09-08T13:07:31.000Z
/* * Copyright 2018, Jaroslaw Pelczar <jarek@jpelczar.com> * Distributed under the terms of the MIT License. */ #include <boot/stage2.h> #include <kernel.h> #include <arch/int.h> #include <arch/cpu.h> #include <console.h> #include <debug.h> #include <timer.h> #include <int.h> #include <safemode.h> #include <arch/timer.h> void arch_timer_set_hardware_timer(bigtime_t timeout) { } void arch_timer_clear_hardware_timer(void) { } int arch_init_timer(kernel_args *args) { return 0; }
13.351351
56
0.724696
korli
8182bf01fbf352ca0415f9a3312a5510abfdb2b7
611
cpp
C++
NSS/Utils.cpp
Debu922/Natural-Selection-Simulator
f84279f3b635443506ec30cd88f0ddcc7b421497
[ "MIT" ]
null
null
null
NSS/Utils.cpp
Debu922/Natural-Selection-Simulator
f84279f3b635443506ec30cd88f0ddcc7b421497
[ "MIT" ]
null
null
null
NSS/Utils.cpp
Debu922/Natural-Selection-Simulator
f84279f3b635443506ec30cd88f0ddcc7b421497
[ "MIT" ]
null
null
null
#include "Utils.h" #include <math.h> #include <stdint.h> #include "Position.h" uint64_t s[2]; uint64_t newRand() { uint64_t s1 = s[0]; uint64_t s0 = s[1]; uint64_t result = s0 + s1; s[0] = s0; s1 ^= s1 << 23; s[1] = s1 ^ s0 ^ (s1 >> 18) ^ (s0 >> 5); return result; } void setRandSeed(int seed) { s[0] = seed; } int randI(int x) { return newRand() % x; } float randF(float x) { return (newRand() % ((int)(x * 100))) / 100.0; } float distance(Position a, Position b) { return((float)sqrt(pow(a.getXPos() - b.getXPos(), 2) + pow(a.getYPos() - b.getYPos(), 2))); }
16.513514
95
0.551555
Debu922
818320d76fcd00a06efc2c172bdb7465aefb4d57
5,377
cpp
C++
hphp/tools/bootstrap/gen-infotabs.cpp
chregu/hhvm
e95c8aff36dad178adac2418f2dbf5bb65ac2431
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/tools/bootstrap/gen-infotabs.cpp
chregu/hhvm
e95c8aff36dad178adac2418f2dbf5bb65ac2431
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/tools/bootstrap/gen-infotabs.cpp
chregu/hhvm
e95c8aff36dad178adac2418f2dbf5bb65ac2431
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include <algorithm> #include <iostream> #include <fstream> #include <unordered_map> #include <unordered_set> #include "folly/FBString.h" #include "folly/FBVector.h" #include "hphp/tools/bootstrap/idl.h" using folly::fbstring; using folly::fbvector; using namespace HPHP::IDL; int main(int argc, const char* argv[]) { if (argc < 3) { std::cout << "Usage: " << argv[0] << " <output file> <*.idl.json>...\n"; return 0; } fbvector<PhpFunc> funcs; fbvector<PhpClass> classes; for (auto i = 2; i < argc; ++i) { try { parseIDL(argv[i], funcs, classes); } catch (const std::exception& exc) { std::cerr << argv[i] << ": " << exc.what() << "\n"; return 1; } } std::ofstream cpp(argv[1]); cpp << "#include \"hphp/runtime/ext_hhvm/ext_hhvm.h\"\n" << "#include \"hphp/runtime/ext/ext.h\"\n" << "#include \"hphp/runtime/vm/runtime.h\"\n" << "#include \"ext_hhvm_infotabs.h\"\n" << "namespace HPHP {\n" << " struct TypedValue;\n" << " struct ActRec;\n" << " class Class;\n" << "\n\n"; std::unordered_set<fbstring> classesWithCtors; //////////////////////////////// // Declare the fg_ and tg_ stubs for (auto const& func : funcs) { fbstring name = func.lowerCppName(); cpp << "TypedValue* fg_" << name << "(ActRec* ar);\n"; } for (auto const& klass : classes) { if (!(klass.flags() & IsCppAbstract)) { cpp << "ObjectData* new_" << klass.getCppName() << "_Instance(Class*);\n"; classesWithCtors.insert(klass.getCppName()); } for (auto const& func : klass.methods()) { cpp << "TypedValue* tg_" << func.getUniqueName() << "(ActRec* ar);\n"; } } cpp << "\n"; cpp << "}\n"; cpp << "namespace HPHP {\n"; /////////////////////////////////////// // Define the name - fg_ - fh_ mappings cpp << "const long long hhbc_ext_funcs_count = " << funcs.size() << ";\n"; cpp << "const HhbcExtFuncInfo hhbc_ext_funcs[] = {\n "; bool first = true; for (auto const& func : funcs) { if (func.isMethod()) { continue; } if (!first) { cpp << ",\n "; } first = false; auto prefix = "fh_"; fbstring name = func.lowerCppName(); cpp << "{ \"" << escapeCpp(func.getPhpName()) << "\", " << "fg_" << name << ", (void *)&" << prefix << name << " }"; } cpp << "\n};\n\n"; for (auto const& klass : classes) { cpp << "static const long long hhbc_ext_method_count_" << klass.getCppName() << " = " << klass.numMethods() << ";\n"; cpp << "static const HhbcExtMethodInfo hhbc_ext_methods_" << klass.getCppName() << "[] = {\n "; first = true; for (auto const& method : klass.methods()) { if (!first) { cpp << ",\n "; } first = false; auto name = method.getUniqueName(); cpp << "{ \"" << method.getCppName() << "\", tg_" << name << " }"; } cpp << "\n};\n\n"; } cpp << "const long long hhbc_ext_class_count = " << classes.size() << ";\n"; for (auto& klass : classes) { cpp << "extern void " << folly::to<std::string>("delete_", klass.getCppName()) << "(ObjectData*, const Class*);\n"; } cpp << "const HhbcExtClassInfo hhbc_ext_classes[] = {\n "; first = true; for (auto const& klass : classes) { if (!first) { cpp << ",\n "; } first = false; auto ctor = classesWithCtors.count(klass.getCppName()) > 0 ? fbstring("new_") + klass.getCppName() + "_Instance" : fbstring("nullptr"); auto dtor = classesWithCtors.count(klass.getCppName()) > 0 ? folly::to<std::string>("delete_", klass.getCppName()) : fbstring{"nullptr"}; auto cpp_name = klass.getCppName(); auto const c_cpp_name = "c_" + cpp_name; cpp << "{ \"" << escapeCpp(klass.getPhpName()) << "\", " << ctor << "," << dtor << ", sizeof(" << c_cpp_name << ')' << ", intptr_t(" "static_cast<ObjectData*>(" "reinterpret_cast<" << c_cpp_name << "*>(0x100)" ")" ") - 0x100" << ", hhbc_ext_method_count_" << klass.getCppName() << ", hhbc_ext_methods_" << klass.getCppName() << ", &" << c_cpp_name << "::classof() }"; } cpp << "\n};\n\n"; cpp << "} // namespace HPHP\n"; return 0; }
31.261628
80
0.492468
chregu
8185446b0a85d0a9265123b86d82d5e88e94e32f
554
cc
C++
Part-I/Ch06/6.7/6.56.cc
RingZEROtlf/Cpp-Primer
bde40534eeca733350825c41f268415fdccb1cc3
[ "MIT" ]
1
2021-09-23T13:13:12.000Z
2021-09-23T13:13:12.000Z
Part-I/Ch06/6.7/6.56.cc
RingZEROtlf/Cpp-Primer
bde40534eeca733350825c41f268415fdccb1cc3
[ "MIT" ]
null
null
null
Part-I/Ch06/6.7/6.56.cc
RingZEROtlf/Cpp-Primer
bde40534eeca733350825c41f268415fdccb1cc3
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; vector<int(*)(int, int)> vec; int sum(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } int mul(int a, int b) { return a * b; } int div(int a, int b) { return a / b; } int main() { vec.push_back(sum); vec.push_back(sub); vec.push_back(mul); vec.push_back(div); int a = 7, b = 2; cout << vec[0](a, b) << endl; cout << vec[1](a, b) << endl; cout << vec[2](a, b) << endl; cout << vec[3](a, b) << endl; return 0; }
13.85
33
0.519856
RingZEROtlf
81877491358cc8b726bf4314fd777611bf47885e
971
cpp
C++
CR/Engine/Core/source/Timer.cpp
duhone/conjure
9b98309d01471a7ef3953f7d7e9fe6e98aa82c55
[ "MIT" ]
null
null
null
CR/Engine/Core/source/Timer.cpp
duhone/conjure
9b98309d01471a7ef3953f7d7e9fe6e98aa82c55
[ "MIT" ]
null
null
null
CR/Engine/Core/source/Timer.cpp
duhone/conjure
9b98309d01471a7ef3953f7d7e9fe6e98aa82c55
[ "MIT" ]
null
null
null
module; #include "fmt/compile.h" #include "fmt/format.h" module CR.Engine.Core.Timer; using namespace std; using namespace CR::Engine::Core; Timer::Timer() { Reset(); } /* Reset the total time back to 0. Also resets the last frame time back to 0. Generally only used when total time is needed. */ void Timer::Reset() { starttime = chrono::high_resolution_clock::now(); } /* Updates the last frame time, and the total time. */ void Timer::Update() { currenttime = chrono::high_resolution_clock::now(); timeLastFrame = chrono::duration_cast<chrono::microseconds>(currenttime - starttime).count() / 1000000.0; starttime = currenttime; totalTime += timeLastFrame; } void Timer::StartFrame() { starttime = chrono::high_resolution_clock::now(); } ScopedTimer::ScopedTimer(const char* text) : m_text(text) {} ScopedTimer::~ScopedTimer() { m_timer.Update(); fmt::print(FMT_COMPILE("{} {:.2f}ms\n"), m_text, (m_timer.GetTotalTime() * 1000)); }
22.581395
106
0.700309
duhone
81881c87cac5b8409a2938453e9bf6aab34293e6
497
cpp
C++
MeetingCodes/Meeting2/nelli_trap.cpp
knelli2/spectre-cpp-basics
9ac3f192a3673e708e8cd33efce0b3eba13f46fc
[ "MIT" ]
null
null
null
MeetingCodes/Meeting2/nelli_trap.cpp
knelli2/spectre-cpp-basics
9ac3f192a3673e708e8cd33efce0b3eba13f46fc
[ "MIT" ]
null
null
null
MeetingCodes/Meeting2/nelli_trap.cpp
knelli2/spectre-cpp-basics
9ac3f192a3673e708e8cd33efce0b3eba13f46fc
[ "MIT" ]
null
null
null
#include <cmath> #include "nelli_trap.hpp" /// function to numerically integrate using trap midpoint double trap(double (* const func)(const double), const double step_size, const double lower_bound, const double upper_bound) noexcept { double result; for(double x=lower_bound; x<upper_bound; x+=step_size) { result += step_size*func(x); result += 0.5 * step_size * (func(x+step_size)-func(x)); } return result; }
31.0625
72
0.623742
knelli2
81897befa1386ea9e459724c115e395f33485f68
311
hpp
C++
include/args.hpp
tomdodd4598/UCL-PHAS0100-BumbleNassExample1
134f415ea9a4b884ab34208517db26d66bef7aeb
[ "MIT" ]
null
null
null
include/args.hpp
tomdodd4598/UCL-PHAS0100-BumbleNassExample1
134f415ea9a4b884ab34208517db26d66bef7aeb
[ "MIT" ]
null
null
null
include/args.hpp
tomdodd4598/UCL-PHAS0100-BumbleNassExample1
134f415ea9a4b884ab34208517db26d66bef7aeb
[ "MIT" ]
null
null
null
#ifndef ARGS_H #define ARGS_H #include <tuple> namespace args { /*template<typename... T> std::tuple<T...> argv_tuple(int argc, char** argv) { std::tuple<T...> tuple; for (int i = 1; i < argc; ++i) { std::get<i>(tuple) = } return tuple; }*/ } #endif
16.368421
56
0.501608
tomdodd4598
818a765296a63b0c2f3148233ea93f15370c2bb2
13,369
hpp
C++
src/armnn/Network.hpp
sahilbandar/armnn
249950645b7bc0593582182097c7e2f1d6d97442
[ "MIT" ]
1
2022-02-10T11:06:30.000Z
2022-02-10T11:06:30.000Z
src/armnn/Network.hpp
sahilbandar/armnn
249950645b7bc0593582182097c7e2f1d6d97442
[ "MIT" ]
null
null
null
src/armnn/Network.hpp
sahilbandar/armnn
249950645b7bc0593582182097c7e2f1d6d97442
[ "MIT" ]
null
null
null
// // Copyright © 2017 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #pragma once #include <armnn/DescriptorsFwd.hpp> #include <armnn/LstmParams.hpp> #include <armnn/QuantizedLstmParams.hpp> #include <armnn/TensorFwd.hpp> #include <armnn/Types.hpp> #include <armnn/INetwork.hpp> #include <string> #include <vector> #include <map> #include <memory> #include "Graph.hpp" #include "Layer.hpp" #include "OptimizedNetworkImpl.hpp" namespace armnn { class Graph; using NetworkImplPtr = std::unique_ptr<NetworkImpl, void (*)(NetworkImpl* network)>; /// Private implementation of INetwork. class NetworkImpl { public: NetworkImpl(NetworkOptions networkOptions = {}); ~NetworkImpl(); const Graph& GetGraph() const { return *m_Graph; } Status PrintGraph(); IConnectableLayer* AddInputLayer(LayerBindingId id, const char* name = nullptr); IConnectableLayer* AddActivationLayer(const ActivationDescriptor& activationDescriptor, const char* name = nullptr); IConnectableLayer* AddAdditionLayer(const char* name = nullptr); IConnectableLayer* AddArgMinMaxLayer(const ArgMinMaxDescriptor& desc, const char* name = nullptr); IConnectableLayer* AddBatchNormalizationLayer(const BatchNormalizationDescriptor& desc, const ConstTensor& mean, const ConstTensor& variance, const ConstTensor& beta, const ConstTensor& gamma, const char* name = nullptr); IConnectableLayer* AddBatchToSpaceNdLayer(const BatchToSpaceNdDescriptor& batchToSpaceNdDescriptor, const char* name = nullptr); IConnectableLayer* AddCastLayer(const char* name = nullptr); IConnectableLayer* AddChannelShuffleLayer(const ChannelShuffleDescriptor& channelShuffleDescriptor, const char* name = nullptr); IConnectableLayer* AddComparisonLayer(const ComparisonDescriptor& comparisonDescriptor, const char* name = nullptr); IConnectableLayer* AddConcatLayer(const ConcatDescriptor& concatDescriptor, const char* name = nullptr); IConnectableLayer* AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor, const ConstTensor& weights, const Optional<ConstTensor>& biases, const char* name = nullptr); ARMNN_DEPRECATED_MSG_REMOVAL_DATE("This AddConvolution2dLayer overload is deprecated", "22.08") IConnectableLayer* AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor, const ConstTensor& weights, const char* name = nullptr); ARMNN_DEPRECATED_MSG_REMOVAL_DATE("This AddConvolution2dLayer overload is deprecated", "22.08") IConnectableLayer* AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor, const ConstTensor& weights, const ConstTensor& biases, const char* name = nullptr); IConnectableLayer* AddConvolution3dLayer(const Convolution3dDescriptor& convolution3dDescriptor, const char* name = nullptr); IConnectableLayer* AddConstantLayer(const ConstTensor& input, const char* name = nullptr); IConnectableLayer* AddDepthToSpaceLayer(const DepthToSpaceDescriptor& depthToSpaceDescriptor, const char* name = nullptr); IConnectableLayer* AddDepthwiseConvolution2dLayer( const DepthwiseConvolution2dDescriptor& convolution2dDescriptor, const ConstTensor& weights, const Optional<ConstTensor>& biases, const char* name = nullptr); IConnectableLayer* AddDequantizeLayer(const char* name = nullptr); IConnectableLayer* AddDetectionPostProcessLayer( const DetectionPostProcessDescriptor& descriptor, const ConstTensor& anchors, const char* name = nullptr); IConnectableLayer* AddDivisionLayer(const char* name = nullptr); IConnectableLayer* AddElementwiseUnaryLayer(const ElementwiseUnaryDescriptor& elementwiseUnaryDescriptor, const char* name = nullptr); IConnectableLayer* AddMergeLayer(const char* name = nullptr); IConnectableLayer* AddFillLayer(const FillDescriptor& fillDescriptor, const char* name = nullptr); IConnectableLayer* AddFloorLayer(const char* name = nullptr); IConnectableLayer* AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor, const char* name = nullptr); IConnectableLayer* AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor, const Optional<ConstTensor>& weights, const Optional<ConstTensor>& biases, const char* name = nullptr); IConnectableLayer* AddGatherLayer(const GatherDescriptor& gatherDescriptor, const char* name = nullptr); IConnectableLayer* AddInstanceNormalizationLayer(const InstanceNormalizationDescriptor& desc, const char* name = nullptr); IConnectableLayer* AddL2NormalizationLayer(const L2NormalizationDescriptor& desc, const char* name = nullptr); IConnectableLayer* AddLogSoftmaxLayer(const LogSoftmaxDescriptor& logSoftmaxDescriptor, const char* name = nullptr); IConnectableLayer* AddLogicalBinaryLayer(const LogicalBinaryDescriptor& logicalBinaryDescriptor, const char* name = nullptr); IConnectableLayer* AddLstmLayer(const LstmDescriptor& descriptor, const LstmInputParams& params, const char* name = nullptr); IConnectableLayer* AddMaximumLayer(const char* name = nullptr); IConnectableLayer* AddMeanLayer(const MeanDescriptor& meanDescriptor, const char* name = nullptr); IConnectableLayer* AddMinimumLayer(const char* name = nullptr); IConnectableLayer* AddMultiplicationLayer(const char* name = nullptr); IConnectableLayer* AddNormalizationLayer(const NormalizationDescriptor& normalizationDescriptor, const char* name = nullptr); IConnectableLayer* AddOutputLayer(LayerBindingId id, const char* name = nullptr); IConnectableLayer* AddPadLayer(const PadDescriptor& padDescriptor, const char* name = nullptr); IConnectableLayer* AddPermuteLayer(const PermuteDescriptor& permuteDescriptor, const char* name = nullptr); IConnectableLayer* AddPooling2dLayer(const Pooling2dDescriptor& pooling2dDescriptor, const char* name = nullptr); IConnectableLayer* AddPreluLayer(const char* name = nullptr); IConnectableLayer* AddQuantizeLayer(const char* name = nullptr); IConnectableLayer* AddQLstmLayer(const QLstmDescriptor& descriptor, const LstmInputParams& params, const char* name = nullptr); IConnectableLayer* AddQuantizedLstmLayer(const QuantizedLstmInputParams& params, const char* name = nullptr); IConnectableLayer* AddRankLayer(const char* name = nullptr); IConnectableLayer* AddReduceLayer(const ReduceDescriptor& reduceDescriptor, const char* name = nullptr); IConnectableLayer* AddResizeLayer(const ResizeDescriptor& resizeDescriptor, const char* name = nullptr); IConnectableLayer* AddReshapeLayer(const ReshapeDescriptor& reshapeDescriptor, const char* name = nullptr); IConnectableLayer* AddShapeLayer(const char* name = nullptr); IConnectableLayer* AddSliceLayer(const SliceDescriptor& sliceDescriptor, const char* name = nullptr); IConnectableLayer* AddSoftmaxLayer(const SoftmaxDescriptor& softmaxDescriptor, const char* name = nullptr); IConnectableLayer* AddSplitterLayer(const ViewsDescriptor& splitterDescriptor, const char* name = nullptr); IConnectableLayer* AddSpaceToBatchNdLayer(const SpaceToBatchNdDescriptor& spaceToBatchNdDescriptor, const char* name = nullptr); IConnectableLayer* AddSpaceToDepthLayer(const SpaceToDepthDescriptor& spaceToDepthDescriptor, const char* name = nullptr); IConnectableLayer* AddStackLayer(const StackDescriptor& stackDescriptor, const char* name = nullptr); IConnectableLayer* AddStandInLayer(const StandInDescriptor& descriptor, const char* name = nullptr); IConnectableLayer* AddStridedSliceLayer(const StridedSliceDescriptor& stridedSliceDescriptor, const char* name = nullptr); IConnectableLayer* AddSubtractionLayer(const char* name = nullptr); IConnectableLayer* AddSwitchLayer(const char* name = nullptr); IConnectableLayer* AddTransposeConvolution2dLayer(const TransposeConvolution2dDescriptor& descriptor, const ConstTensor& weights, const Optional<ConstTensor>& biases, const char* name = nullptr); IConnectableLayer* AddTransposeLayer(const TransposeDescriptor& transposeDescriptor, const char* name = nullptr); IConnectableLayer* AddUnidirectionalSequenceLstmLayer(const UnidirectionalSequenceLstmDescriptor& descriptor, const LstmInputParams& params, const char* name = nullptr); ARMNN_NO_DEPRECATE_WARN_BEGIN void Accept(ILayerVisitor& visitor) const; ARMNN_NO_DEPRECATE_WARN_END void ExecuteStrategy(IStrategy& strategy) const; private: IConnectableLayer* AddConvolution2dLayerImpl(const Convolution2dDescriptor& convolution2dDescriptor, const ConstTensor& weights, const Optional<ConstTensor>& biases, const char* name); IConnectableLayer* AddDepthwiseConvolution2dLayerImpl(const DepthwiseConvolution2dDescriptor& conv2dDescriptor, const ConstTensor& weights, const Optional<ConstTensor>& biases, const char* name); bool GetShapeInferenceMethod(); NetworkOptions m_NetworkOptions; std::unique_ptr<Graph> m_Graph; ModelOptions m_ModelOptions; }; struct OptimizationResult { bool m_Warning; bool m_Error; OptimizationResult(bool warning, bool error) : m_Warning(warning), m_Error(error) {} OptimizationResult() : OptimizationResult(false, false) {} bool IsOk() const { return !m_Warning && !m_Error; } bool IsWarningOnly() const { return m_Warning && !m_Error; } bool IsError() const { return m_Error; } }; using BackendsMap = std::map<BackendId, std::unique_ptr<class IBackendInternal>>; BackendsMap CreateSupportedBackends(TensorHandleFactoryRegistry& handleFactoryRegistry, struct BackendSettings& backendSettings); OptimizationResult SelectTensorHandleStrategy(Graph& optGraph, BackendsMap& backends, TensorHandleFactoryRegistry& registry, bool importEnabled, Optional<std::vector<std::string>&> errMessages); OptimizationResult AssignBackends(OptimizedNetworkImpl* optNetObjPtr, BackendSettings& backendSettings, Graph::Iterator& firstLayer, Graph::Iterator& lastLayer, Optional<std::vector<std::string>&> errMessages); } // namespace armnn
45.013468
115
0.603261
sahilbandar
818fe92c0f897494daa0a01ab0b41d3f7563833e
3,779
hpp
C++
include/VROSC/BeatCounterUI_SyncToggleSource.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/VROSC/BeatCounterUI_SyncToggleSource.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/VROSC/BeatCounterUI_SyncToggleSource.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: VROSC.BeatCounterUI #include "VROSC/BeatCounterUI.hpp" // Including type: System.Enum #include "System/Enum.hpp" // Completed includes #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::VROSC::BeatCounterUI::SyncToggleSource, "VROSC", "BeatCounterUI/SyncToggleSource"); // Type namespace: VROSC namespace VROSC { // Size: 0x4 #pragma pack(push, 1) // Autogenerated type: VROSC.BeatCounterUI/VROSC.SyncToggleSource // [TokenAttribute] Offset: FFFFFFFF struct BeatCounterUI::SyncToggleSource/*, public ::System::Enum*/ { public: public: // public System.Int32 value__ // Size: 0x4 // Offset: 0x0 int value; // Field size check static_assert(sizeof(int) == 0x4); public: // Creating value type constructor for type: SyncToggleSource constexpr SyncToggleSource(int value_ = {}) noexcept : value{value_} {} // Creating interface conversion operator: operator ::System::Enum operator ::System::Enum() noexcept { return *reinterpret_cast<::System::Enum*>(this); } // Creating conversion operator: operator int constexpr operator int() const noexcept { return value; } // static field const value: static public VROSC.BeatCounterUI/VROSC.SyncToggleSource ToggleButton static constexpr const int ToggleButton = 0; // Get static field: static public VROSC.BeatCounterUI/VROSC.SyncToggleSource ToggleButton static ::VROSC::BeatCounterUI::SyncToggleSource _get_ToggleButton(); // Set static field: static public VROSC.BeatCounterUI/VROSC.SyncToggleSource ToggleButton static void _set_ToggleButton(::VROSC::BeatCounterUI::SyncToggleSource value); // static field const value: static public VROSC.BeatCounterUI/VROSC.SyncToggleSource DataLoad static constexpr const int DataLoad = 1; // Get static field: static public VROSC.BeatCounterUI/VROSC.SyncToggleSource DataLoad static ::VROSC::BeatCounterUI::SyncToggleSource _get_DataLoad(); // Set static field: static public VROSC.BeatCounterUI/VROSC.SyncToggleSource DataLoad static void _set_DataLoad(::VROSC::BeatCounterUI::SyncToggleSource value); // static field const value: static public VROSC.BeatCounterUI/VROSC.SyncToggleSource Slider static constexpr const int Slider = 2; // Get static field: static public VROSC.BeatCounterUI/VROSC.SyncToggleSource Slider static ::VROSC::BeatCounterUI::SyncToggleSource _get_Slider(); // Set static field: static public VROSC.BeatCounterUI/VROSC.SyncToggleSource Slider static void _set_Slider(::VROSC::BeatCounterUI::SyncToggleSource value); // static field const value: static public VROSC.BeatCounterUI/VROSC.SyncToggleSource Reset static constexpr const int Reset = 3; // Get static field: static public VROSC.BeatCounterUI/VROSC.SyncToggleSource Reset static ::VROSC::BeatCounterUI::SyncToggleSource _get_Reset(); // Set static field: static public VROSC.BeatCounterUI/VROSC.SyncToggleSource Reset static void _set_Reset(::VROSC::BeatCounterUI::SyncToggleSource value); // Get instance field reference: public System.Int32 value__ int& dyn_value__(); }; // VROSC.BeatCounterUI/VROSC.SyncToggleSource #pragma pack(pop) static check_size<sizeof(BeatCounterUI::SyncToggleSource), 0 + sizeof(int)> __VROSC_BeatCounterUI_SyncToggleSourceSizeCheck; static_assert(sizeof(BeatCounterUI::SyncToggleSource) == 0x4); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
51.767123
126
0.744377
RedBrumbler
81a1185c9615035ae1ccf93fdde6aa5bd2f7321c
817
cpp
C++
p103/p103.cpp
suzyz/leetcode_practice
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
[ "MIT" ]
1
2019-10-07T05:00:21.000Z
2019-10-07T05:00:21.000Z
p103/p103.cpp
suzyz/leetcode_practice
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
[ "MIT" ]
null
null
null
p103/p103.cpp
suzyz/leetcode_practice
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> res; dfs(root,0,res); zigzag(res); return res; } void dfs(TreeNode *cur, int level, vector<vector<int>> &res) { if (cur == NULL) return; if (level >= res.size()) res.push_back(vector<int>()); res[level].push_back(cur->val); dfs(cur->left,level+1,res); dfs(cur->right,level+1,res); } void zigzag(vector<vector<int>> &res) { for (int i = 1; i < res.size(); i += 2) reverse(res[i].begin(),res[i].end()); } };
20.425
64
0.538556
suzyz
81a4ca4123e041a5c61773ab4c8c45144734b572
12,183
cpp
C++
c/infrastructure/PositionMatrix.cpp
e-foto/e-foto
cf143a1076c03c7bdf5a2f41efad2c98e9272722
[ "FTL" ]
3
2021-06-28T21:07:58.000Z
2021-07-02T11:21:49.000Z
c/infrastructure/PositionMatrix.cpp
e-foto/e-foto
cf143a1076c03c7bdf5a2f41efad2c98e9272722
[ "FTL" ]
null
null
null
c/infrastructure/PositionMatrix.cpp
e-foto/e-foto
cf143a1076c03c7bdf5a2f41efad2c98e9272722
[ "FTL" ]
null
null
null
/*Copyright 2002-2014 e-foto team (UERJ) This file is part of e-foto. e-foto 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. e-foto 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 e-foto. If not, see <http://www.gnu.org/licenses/>. */ #include "PositionMatrix.h" #include <iostream> #include <sstream> #include <iomanip> #include <fstream> namespace br { namespace uerj { namespace eng { namespace efoto { void PositionMatrix::del() { delete[] _Mat; _Mat = NULL; ncols = 0; nrows = 0; unit = ""; } void PositionMatrix::nw(const unsigned int rows, const unsigned int cols) { _Mat = new double[rows * cols]; // Allocate matrix nrows = rows; ncols = cols; // Fill matrix' attributes. for(unsigned int i = 0; i < (rows * cols); i++) //set its elements to zero _Mat[i] = 0; unit = ""; } PositionMatrix::PositionMatrix(unsigned int dimensions, std::string newUnit):RectSupport(dimensions, 1) { nw(dimensions, 1); // Allocate matrix and fill its attributes. unit = newUnit; } PositionMatrix::PositionMatrix(const Matrix& anotherMatrix):RectSupport(anotherMatrix.getRows(), anotherMatrix.getCols()) { nw(anotherMatrix.getRows(), anotherMatrix.getCols()); *this = anotherMatrix; // Allocate matrix and fill its attributes. } PositionMatrix::PositionMatrix(const PositionMatrix& anotherMatrix):RectSupport(anotherMatrix.getRows(), anotherMatrix.getCols()) { nw(anotherMatrix.getRows(), anotherMatrix.getCols()); *this = anotherMatrix; // Allocate matrix and fill its attributes. } PositionMatrix::PositionMatrix():RectSupport(0, 0) { _Mat = NULL; } PositionMatrix::~PositionMatrix() { del(); } PositionMatrix& PositionMatrix::resize(unsigned int rows, unsigned int cols) { PositionMatrix result; result.nw(rows, cols); for (unsigned int i = 1; (i <= result.nrows)&&(i <= nrows); i++) for (unsigned int j = 1; (j <= result.ncols)&&(j <= ncols); j++) result.set(i,j,get(i,j)); *this = result; return *this; } PositionMatrix& PositionMatrix::zero() { for(unsigned int i = 0; i < (nrows * ncols); i++) _Mat[i] = 0; return *this; } int PositionMatrix::load(char* filename) { char str[256]; unsigned int cols; unsigned int rows; std::ifstream arq(filename); // open the emf file if (!arq.fail()) { arq.getline(str,255); // read file header if (!arq.fail()) { arq.getline(str,255); // read filename if (!arq.fail()) { arq >> cols; if (!arq.fail()) { arq >> rows; if ((nrows != rows)||(ncols != cols)) { del(); nw(rows, cols); } for (unsigned int i=0; (!arq.eof())||(!arq.fail())||(i < (cols * rows)); i++) { arq >> _Mat[i]; // read one matrix element } arq.close(); return 1; } } } } return 0; } int PositionMatrix::save(char* filename) { std::ofstream emfile(filename); // open the emf file if (!emfile.fail()) { emfile << "E-foto project double PositionMatrix Format" << std::endl; // write file header if (!emfile.fail()) { emfile << filename << std::endl; // write filename if (!emfile.fail()) { emfile << ncols << " " << nrows << std::endl; if (!emfile.fail()) { for (unsigned int i = 0; (i < (ncols * nrows)); i++) { emfile << _Mat[i] << " "; // write one matrix element } emfile.close(); return 1; } } } } return 0; } double PositionMatrix::get(const unsigned int i, const unsigned int j) const { if ((i >= 1)&&(i <= nrows)&&(j >= 1)&&(j <= ncols)) return _Mat[(i-1) * ncols + j - 1]; else std::cerr << "i, j values out of the range of the matrix." << std::endl; return 0; } int PositionMatrix::getInt(const unsigned int i, const unsigned int j) const { return (int) get(i,j); } std::string PositionMatrix::getUnit() const { return unit; } PositionMatrix PositionMatrix::sel(const unsigned int FirstRow, const unsigned int LastRow, const unsigned int FirstCol, const unsigned int LastCol) { PositionMatrix DraftResult; PositionMatrix Result; if((FirstRow > LastRow)||(FirstCol > LastCol)||(FirstRow < 1)||(FirstCol < 1)||(LastRow > nrows)||(LastCol > ncols)) { std::cerr << "Error detected by the Matrix.sel() method:" << std::endl << "Input parameters out of range or incorrect."<< std::endl; return Result; } if ( (DraftResult.nrows != (LastRow-FirstRow+1)) || (DraftResult.ncols != (LastCol-FirstCol+1)) ) { DraftResult.del(); DraftResult.nw( (unsigned int)(LastRow-FirstRow+1), (unsigned int) (LastCol-FirstCol+1) ); } for (unsigned int i = 1; i <= (LastRow-FirstRow+1); i++) for (unsigned int j = 1; j <= (LastCol-FirstCol+1); j++) DraftResult.set(i, j, get((FirstRow + i - 1),(FirstCol + j -1))); Result = DraftResult; Result.unit = unit; return Result; } void PositionMatrix::show() { std::cout << "PositionMatrix " << nrows << 'x' << ncols << " (" << unit << ")" << std::endl; std::cout.setf(std::ios::fixed | std::ios::scientific); for (unsigned int i = 1; i <= nrows; i++) { for (unsigned int j = 1; j <= ncols; j++) //printf("%10.1f ", get((unsigned int) i, (unsigned int) j)); std::cout << std::setw(9) << std::setprecision(3) << get((unsigned int) i, (unsigned int) j) << " "; std::cout << std::endl; } std::cout.unsetf(std::ios::fixed | std::ios::scientific); std::cout << std::endl; } void PositionMatrix::set(unsigned int i, unsigned int j, double value) const { if ((i >= 1)&&(i <= nrows)&&(j >= 1)&&(j <= ncols)) _Mat[(i-1) * ncols + j - 1]=value; else std::cerr << "i, j values out of the range of the matrix." << std::endl; } void PositionMatrix::set(unsigned int i, double value) const { set(i,1, value); } void PositionMatrix::setInt(unsigned int i, unsigned int j, int value) const { set(i,j, (double) value); } void PositionMatrix::setInt(unsigned int i, int value) const { set(i,1, (double) value); } void PositionMatrix::setUnit(std::string newUnit) { unit = newUnit; } PositionMatrix PositionMatrix::operator &(const PositionMatrix& Par_Matrix) { PositionMatrix DraftResult; PositionMatrix Result; if (Par_Matrix.nrows!=nrows) { std::cerr << "Error detected by the & operator:" << std::endl<< "Both matrixes must have the same number of rows." << std::endl; } else { if ((DraftResult.nrows*DraftResult.ncols)==(nrows*(ncols+Par_Matrix.ncols))) // If total size of the resulting matrix is correct { DraftResult.nrows=nrows; // Just update the dimensions DraftResult.ncols=ncols+Par_Matrix.ncols; } else { DraftResult.del(); DraftResult.nw(nrows, ncols+Par_Matrix.ncols); } for (unsigned int i=1; i<=(nrows); i++) { for (unsigned int j=1; j<=(ncols); j++) DraftResult.set((unsigned int)i,(unsigned int)j,get((unsigned int)i,(unsigned int)j)); for (unsigned int j=1; j<=(Par_Matrix.ncols); j++) DraftResult.set((unsigned int)i,(unsigned int)(j+ncols),Par_Matrix.get((unsigned int)i,(unsigned int)j)); } Result = DraftResult; Result.unit = unit; return Result; } return Result; } PositionMatrix PositionMatrix::operator |(const PositionMatrix& Par_Matrix) { PositionMatrix Result; if (Par_Matrix.ncols!=ncols) { std::cerr << "Error detected by the | operator:" << std::endl<< "Both matrixes must have the same number of cols." << std::endl; } else { PositionMatrix DraftResult; DraftResult.resize(nrows+Par_Matrix.nrows, ncols); for (unsigned int j=1; j<=(ncols); j++) { for (unsigned int i=1; i<=(nrows); i++) DraftResult.set((unsigned int)i,(unsigned int)j,get((unsigned int)i,(unsigned int)j)); for (unsigned int i=1; i<=(Par_Matrix.nrows); i++) DraftResult.set((unsigned int)(i+nrows),(unsigned int)j,Par_Matrix.get((unsigned int)i,(unsigned int)j)); } Result = DraftResult; Result.unit = unit; } return Result; } PositionMatrix& PositionMatrix::operator =(const Matrix& Par_Matrix) { if ((nrows!=Par_Matrix.nrows)||(ncols!=Par_Matrix.ncols)) { del(); nw(Par_Matrix.nrows,Par_Matrix.ncols); } for (unsigned int i = 0; i < (nrows*ncols); i++) { _Mat[i]=Par_Matrix._Mat[i]; } unit = Par_Matrix.unit_; return *this; } PositionMatrix& PositionMatrix::operator =(const PositionMatrix& Par_Matrix) { if ((nrows!=Par_Matrix.nrows)||(ncols!=Par_Matrix.ncols)) { del(); nw(Par_Matrix.nrows,Par_Matrix.ncols); } for (unsigned int i = 0; i < (nrows*ncols); i++) { _Mat[i]=Par_Matrix._Mat[i]; } unit = Par_Matrix.unit; return *this; } bool PositionMatrix::operator ==(const Matrix& Par_Matrix) { if ((nrows!=Par_Matrix.nrows)||(ncols!=Par_Matrix.ncols)) return 0; else for (unsigned int i = 0; i < (ncols*nrows); i++) if (_Mat[i] - Par_Matrix._Mat[i] > 0.00000001 || _Mat[i] - Par_Matrix._Mat[i] < -0.00000001) return 0; return 1; } bool PositionMatrix::operator ==(const PositionMatrix& Par_Matrix) { if ((nrows!=Par_Matrix.nrows)||(ncols!=Par_Matrix.ncols)) return 0; else for (unsigned int i = 0; i < (ncols*nrows); i++) if (_Mat[i] - Par_Matrix._Mat[i] > 0.00000001 || _Mat[i] - Par_Matrix._Mat[i] < -0.00000001) return 0; return 1; } bool PositionMatrix::operator !=(const Matrix& Par_Matrix) { if ((nrows!=Par_Matrix.nrows)||(ncols!=Par_Matrix.ncols)) return 1; else for (unsigned int i = 0; i < (ncols*nrows); i++) if (_Mat[i] - Par_Matrix._Mat[i] > 0.00000001 || _Mat[i] - Par_Matrix._Mat[i] < -0.00000001) return 1; return 0; } bool PositionMatrix::operator !=(const PositionMatrix& Par_Matrix) { if ((nrows!=Par_Matrix.nrows)||(ncols!=Par_Matrix.ncols)) return 1; else for (unsigned int i = 0; i < (ncols*nrows); i++) if (_Mat[i] - Par_Matrix._Mat[i] > 0.00000001 || _Mat[i] - Par_Matrix._Mat[i] < -0.00000001) return 1; return 0; } std::string PositionMatrix::objectType(void) { return "PositionMatrix"; } std::string PositionMatrix::objectAssociations(void) { return ""; } bool PositionMatrix::is(std::string s) { return (s == "PositionMatrix" ? true : false); } std::string PositionMatrix::xmlGetData() { std::stringstream result; result << "<gml:pos>" << this->toGmlPosFormat() << "</gml:pos>\n"; return result.str(); } void PositionMatrix::xmlSetData(std::string xml) { EDomElement root(xml); std::deque<double> values = root.toGmlPos(); resize(values.size()); for (unsigned int i = 0; i < values.size(); i++) set(i, values.at(i)); } PositionMatrix PositionMatrix::toDiagonal() { PositionMatrix Result; if ((ncols == 1)||(nrows == 1)) { Result.resize(ncols*nrows, ncols*nrows); for (unsigned int i = 1; i <= nrows; i++) for(unsigned int j = 1; j <= ncols; j++) Result.set(i*j, i*j, get(i,j)); } //Aqui pode ser incluido um else que revele um erro nessa operação que pede um vetor como entrada. Result.unit = unit; return Result; } std::string PositionMatrix::toGmlPosFormat() { std::stringstream oss; for (unsigned int i = 1; i <= nrows; i++) for (unsigned int j = 1; j <= ncols; j++) { oss << Conversion::doubleToString(get((unsigned int) i, (unsigned int) j)); if ( !( ( i == nrows) && (j == ncols) ) ) oss << " "; }; return oss.str(); } } // namespace efoto } // namespace eng } // namespace uerj } // namespace br
27.501129
141
0.619306
e-foto
81b4c284c1f48aad6878186f82352fa57cc1eaca
94
cpp
C++
interface/GripperTypes.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
interface/GripperTypes.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
interface/GripperTypes.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
#include <wx/wx.h> #include "GripperTypes.h" DEFINE_ENUM(EnumGripperType, ENUM_GRIPPER_TYPE)
18.8
47
0.797872
tapeguy
81bb24acf6ae441ea0759fe6141603d8f2a80d6c
1,176
cpp
C++
Gnss/Dev/devGNSS.cpp
SergeyMSV/LIB.Module.GNSS
757d9d98c6d23ebd593b1db9bd0c14a49fda3b47
[ "MIT" ]
1
2021-06-15T19:18:04.000Z
2021-06-15T19:18:04.000Z
Gnss/Dev/devGNSS.cpp
SergeyMSV/LIB.Module.GNSS
757d9d98c6d23ebd593b1db9bd0c14a49fda3b47
[ "MIT" ]
null
null
null
Gnss/Dev/devGNSS.cpp
SergeyMSV/LIB.Module.GNSS
757d9d98c6d23ebd593b1db9bd0c14a49fda3b47
[ "MIT" ]
1
2021-06-15T19:18:14.000Z
2021-06-15T19:18:14.000Z
#include "devGNSS.h" namespace dev { tGNSS::tGNSS(utils::tLog* log, boost::asio::io_context& io) :m_pLog(log), m_pIO(&io) { m_pModFSMachine = new tModGnssReceiver(this); } tGNSS::~tGNSS() { delete m_pModFSMachine; } void tGNSS::operator()() { if (m_pModFSMachine) { if (m_StartAuto) { m_StartAuto = false; m_pModFSMachine->Start(true); } (*m_pModFSMachine)(); } } void tGNSS::Start() { if (m_pModFSMachine) { m_pModFSMachine->Start(); } } void tGNSS::Restart() { if (m_pModFSMachine) { m_pModFSMachine->Restart(); } } void tGNSS::Halt() { if (m_pModFSMachine) { m_pModFSMachine->Halt(); } } void tGNSS::Exit() { if (m_pModFSMachine) { m_pModFSMachine->Exit(); } } bool tGNSS::StartUserTaskScript(const std::string& taskScriptID) { if (m_pModFSMachine) { return m_pModFSMachine->StartUserTaskScript(taskScriptID); } return false; } mod::tGnssStatus tGNSS::GetStatus() const { if (m_pModFSMachine) { return m_pModFSMachine->GetStatus(); } return mod::tGnssStatus::Unknown; } std::string tGNSS::GetLastErrorMsg() const { if (m_pModFSMachine) { return m_pModFSMachine->GetLastErrorMsg(); } return {}; } }
12.378947
64
0.67602
SergeyMSV
81c2730d74a0ae23849a1f191e8190e24bb71ebb
1,332
cpp
C++
src/org/apache/poi/ss/formula/CollaboratingWorkbooksEnvironment_WorkbookNotFoundException.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/CollaboratingWorkbooksEnvironment_WorkbookNotFoundException.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/CollaboratingWorkbooksEnvironment_WorkbookNotFoundException.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/ss/formula/CollaboratingWorkbooksEnvironment.java #include <org/apache/poi/ss/formula/CollaboratingWorkbooksEnvironment_WorkbookNotFoundException.hpp> poi::ss::formula::CollaboratingWorkbooksEnvironment_WorkbookNotFoundException::CollaboratingWorkbooksEnvironment_WorkbookNotFoundException(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::ss::formula::CollaboratingWorkbooksEnvironment_WorkbookNotFoundException::CollaboratingWorkbooksEnvironment_WorkbookNotFoundException(::java::lang::String* msg) : CollaboratingWorkbooksEnvironment_WorkbookNotFoundException(*static_cast< ::default_init_tag* >(0)) { ctor(msg); } void poi::ss::formula::CollaboratingWorkbooksEnvironment_WorkbookNotFoundException::ctor(::java::lang::String* msg) { super::ctor(msg); } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::ss::formula::CollaboratingWorkbooksEnvironment_WorkbookNotFoundException::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment.WorkbookNotFoundException", 85); return c; } java::lang::Class* poi::ss::formula::CollaboratingWorkbooksEnvironment_WorkbookNotFoundException::getClass0() { return class_(); }
38.057143
166
0.795796
pebble2015
81c31d4fef4e829ca8a8eb7ae8b9536c4fb85b3f
6,724
cc
C++
wrspice/devlib/bsimsoi-4.4/b4sconv.cc
wrcad/xictools
f46ba6d42801426739cc8b2940a809b74f1641e2
[ "Apache-2.0" ]
73
2017-10-26T12:40:24.000Z
2022-03-02T16:59:43.000Z
wrspice/devlib/bsimsoi-4.4/b4sconv.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
12
2017-11-01T10:18:22.000Z
2022-03-20T19:35:36.000Z
wrspice/devlib/bsimsoi-4.4/b4sconv.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
34
2017-10-06T17:04:21.000Z
2022-02-18T16:22:03.000Z
/*========================================================================* * * * Distributed by Whiteley Research Inc., Sunnyvale, California, USA * * http://wrcad.com * * Copyright (C) 2017 Whiteley Research Inc., all rights reserved. * * Author: Stephen R. Whiteley, except as indicated. * * * * As fully as possible recognizing licensing terms and conditions * * imposed by earlier work from which this work was derived, if any, * * this work is released under the Apache License, Version 2.0 (the * * "License"). You may not use this file except in compliance with * * the License, and compliance with inherited licenses which are * * specified in a sub-header below this one if applicable. A copy * * of the License is provided with this distribution, or you may * * obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * See the License for the specific language governing permissions * * and limitations under the License. * * * * 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 NON- * * INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED * * OR STEPHEN R. WHITELEY 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. * * * *========================================================================* * XicTools Integrated Circuit Design System * * * * WRspice Circuit Simulation and Analysis Tool: Device Library * * * *========================================================================* $Id:$ *========================================================================*/ /*** B4SOI 12/16/2010 Released by Tanvir Morshed ***/ /********** * Copyright 2010 Regents of the University of California. All rights reserved. * Authors: 1998 Samuel Fung, Dennis Sinitsky and Stephen Tang * Authors: 1999-2004 Pin Su, Hui Wan, Wei Jin, b3soicvtest.c * Authors: 2005- Hui Wan, Xuemei Xi, Ali Niknejad, Chenming Hu. * Authors: 2009- Wenwei Yang, Chung-Hsun Lin, Ali Niknejad, Chenming Hu. * File: b4soicvtest.c * Modified by Hui Wan, Xuemei Xi 11/30/2005 * Modified by Wenwei Yang, Chung-Hsun Lin, Darsen Lu 03/06/2009 * Modified by Tanvir Morshed 09/22/2009 * Modified by Tanvir Morshed 12/31/2009 **********/ #include "b4sdefs.h" #define B4SOInextModel next() #define B4SOInextInstance next() #define B4SOIinstances inst() #define CKTreltol CKTcurTask->TSKreltol #define CKTabstol CKTcurTask->TSKabstol #define MAX SPMAX int B4SOIdev::convTest(sGENmodel *genmod, sCKT *ckt) { sB4SOImodel *model = static_cast<sB4SOImodel*>(genmod); sB4SOIinstance *here; double delvbd, delvbs, delvds, delvgd, delvgs, vbd, vbs, vds; double cbd, cbhat, cbs, cd, cdhat, tol, vgd, vgdo, vgs; /* loop through all the B4SOI device models */ for (; model != NULL; model = model->B4SOInextModel) { /* loop through all the instances of the model */ for (here = model->B4SOIinstances; here != NULL ; here=here->B4SOInextInstance) { // SRW, check this here to avoid computations below. if (here->B4SOIoff && (ckt->CKTmode & MODEINITFIX)) continue; vbs = model->B4SOItype * (*(ckt->CKTrhsOld+here->B4SOIbNode) - *(ckt->CKTrhsOld+here->B4SOIsNodePrime)); vgs = model->B4SOItype * (*(ckt->CKTrhsOld+here->B4SOIgNode) - *(ckt->CKTrhsOld+here->B4SOIsNodePrime)); vds = model->B4SOItype * (*(ckt->CKTrhsOld+here->B4SOIdNodePrime) - *(ckt->CKTrhsOld+here->B4SOIsNodePrime)); vbd = vbs - vds; vgd = vgs - vds; vgdo = *(ckt->CKTstate0 + here->B4SOIvgs) - *(ckt->CKTstate0 + here->B4SOIvds); delvbs = vbs - *(ckt->CKTstate0 + here->B4SOIvbs); delvbd = vbd - *(ckt->CKTstate0 + here->B4SOIvbd); delvgs = vgs - *(ckt->CKTstate0 + here->B4SOIvgs); delvds = vds - *(ckt->CKTstate0 + here->B4SOIvds); delvgd = vgd-vgdo; cd = here->B4SOIcd; if (here->B4SOImode >= 0) { cdhat = cd - here->B4SOIgjdb * delvbd + here->B4SOIgmbs * delvbs + here->B4SOIgm * delvgs + here->B4SOIgds * delvds; } else { cdhat = cd - (here->B4SOIgjdb - here->B4SOIgmbs) * delvbd - here->B4SOIgm * delvgd + here->B4SOIgds * delvds; } /* * check convergence */ // SRW if ((here->B4SOIoff == 0) || (!(ckt->CKTmode & MODEINITFIX))) { tol = ckt->CKTreltol * MAX(FABS(cdhat), FABS(cd)) + ckt->CKTabstol; if (FABS(cdhat - cd) >= tol) { ckt->CKTnoncon++; return(OK); } cbs = here->B4SOIcjs; cbd = here->B4SOIcjd; cbhat = cbs + cbd + here->B4SOIgjdb * delvbd + here->B4SOIgjsb * delvbs; tol = ckt->CKTreltol * MAX(FABS(cbhat), FABS(cbs + cbd)) + ckt->CKTabstol; if (FABS(cbhat - (cbs + cbd)) > tol) { ckt->CKTnoncon++; return(OK); } } } } return(OK); }
45.432432
82
0.466092
wrcad
81c3c919727beac780171a90ea7b532678e24dcd
872
cpp
C++
sandbox/src/main.cpp
anujv99/GameEngine
644cb6667800cfecaa429666e5610e27f923e953
[ "MIT" ]
null
null
null
sandbox/src/main.cpp
anujv99/GameEngine
644cb6667800cfecaa429666e5610e27f923e953
[ "MIT" ]
null
null
null
sandbox/src/main.cpp
anujv99/GameEngine
644cb6667800cfecaa429666e5610e27f923e953
[ "MIT" ]
null
null
null
#include <prevengine.h> using namespace prev; #include "boidsdemo.h" class SandboxLayer : public Layer { public: virtual void OnAttach() override { m_Label.Text = "Test String"; m_Label.Scale = Vec2(0.5f); m_Label.Color = Vec4(0.0f); } virtual void OnUpdate(pvfloat deltaTime) override { auto imguiFont = ImGuiManager::Ref().GetFont(); Renderer2D::Ref().DrawText(imguiFont, m_Label); } virtual void OnImGuiUpdate() override { ImGui::Begin("C++ menu"); ImGui::TextInput("String", m_Label.Text, 100.0f); ImGui::SliderRGBA("Text Color", m_Label.Color); ImGui::End(); } private: Label m_Label; }; int main() { Application::CreateInst(); Application::Ref().GetLayerStack().PushLayer(new BoidsDemo()); Application::Ref().GetLayerStack().PushLayer(new SandboxLayer()); Application::Ref().Run(); Application::DestroyInst(); return 0; }
19.377778
66
0.696101
anujv99
81c4393dbe6d9fae892389eb52c9b7700c20e5f5
3,242
hh
C++
spot/spot/misc/fixpool.hh
mcc-petrinets/formulas
10f835d67c7deedfe98fbbd55a56bd549a5bae9b
[ "MIT" ]
1
2018-03-02T14:29:57.000Z
2018-03-02T14:29:57.000Z
spot/spot/misc/fixpool.hh
mcc-petrinets/formulas
10f835d67c7deedfe98fbbd55a56bd549a5bae9b
[ "MIT" ]
null
null
null
spot/spot/misc/fixpool.hh
mcc-petrinets/formulas
10f835d67c7deedfe98fbbd55a56bd549a5bae9b
[ "MIT" ]
1
2015-06-05T12:42:07.000Z
2015-06-05T12:42:07.000Z
// -*- coding: utf-8 -*- // Copyright (C) 2011, 2015, 2016 Laboratoire de Recherche et // Développement de l'Epita (LRDE) // // This file is part of Spot, a model checking library. // // Spot 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. // // Spot is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public // License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #pragma once #include <spot/misc/common.hh> #include <new> #include <cstddef> #include <cstdlib> namespace spot { /// A fixed-size memory pool implementation. class fixed_size_pool { public: /// Create a pool allocating objects of \a size bytes. fixed_size_pool(size_t size) : freelist_(nullptr), free_start_(nullptr), free_end_(nullptr), chunklist_(nullptr) { const size_t alignement = 2 * sizeof(size_t); size_ = ((size >= sizeof(block_) ? size : sizeof(block_)) + alignement - 1) & ~(alignement - 1); } /// Free any memory allocated by this pool. ~fixed_size_pool() { while (chunklist_) { chunk_* prev = chunklist_->prev; free(chunklist_); chunklist_ = prev; } } /// Allocate \a size bytes of memory. void* allocate() { block_* f = freelist_; // If we have free blocks available, return the first one. if (f) { freelist_ = f->next; return f; } // Else, create a block out of the last chunk of allocated // memory. // If all the last chunk has been used, allocate one more. if (free_start_ + size_ > free_end_) { const size_t requested = (size_ > 128 ? size_ : 128) * 8192 - 64; chunk_* c = reinterpret_cast<chunk_*>(malloc(requested)); if (!c) throw std::bad_alloc(); c->prev = chunklist_; chunklist_ = c; free_start_ = c->data_ + size_; free_end_ = c->data_ + requested; } void* res = free_start_; free_start_ += size_; return res; } /// \brief Recycle \a size bytes of memory. /// /// Despite the name, the memory is not really deallocated in the /// "delete" sense: it is still owned by the pool and will be /// reused by allocate as soon as possible. The memory is only /// freed when the pool is destroyed. void deallocate (const void* ptr) { SPOT_ASSERT(ptr); block_* b = reinterpret_cast<block_*>(const_cast<void*>(ptr)); b->next = freelist_; freelist_ = b; } private: size_t size_; struct block_ { block_* next; }* freelist_; char* free_start_; char* free_end_; // chunk = several agglomerated blocks union chunk_ { chunk_* prev; char data_[1]; }* chunklist_; }; }
28.690265
75
0.615361
mcc-petrinets
81c8d71beb5a4eed8cbf8e2034e982087e727bb5
1,005
hpp
C++
vm/segments.hpp
alex-ilin/factor
b6f33e03990cb7645201486366d543ae724e8fe1
[ "BSD-2-Clause" ]
930
2016-03-01T08:40:07.000Z
2022-03-29T10:37:39.000Z
vm/segments.hpp
alex-ilin/factor
b6f33e03990cb7645201486366d543ae724e8fe1
[ "BSD-2-Clause" ]
1,231
2016-02-19T21:52:25.000Z
2022-03-27T23:24:50.000Z
vm/segments.hpp
alex-ilin/factor
b6f33e03990cb7645201486366d543ae724e8fe1
[ "BSD-2-Clause" ]
118
2016-02-19T21:37:05.000Z
2022-02-21T19:44:02.000Z
namespace factor { inline cell align_page(cell a) { return align(a, getpagesize()); } bool set_memory_locked(cell base, cell size, bool locked); // segments set up guard pages to check for under/overflow. // size must be a multiple of the page size struct segment { cell start; cell size; cell end; segment(cell size, bool executable_p); ~segment(); bool underflow_p(cell addr) { return addr >= (start - getpagesize()) && addr < start; } bool overflow_p(cell addr) { return addr >= end && addr < (end + getpagesize()); } bool in_segment_p(cell addr) { return addr >= start && addr < end; } void set_border_locked(bool locked) { int pagesize = getpagesize(); cell lo = start - pagesize; if (!set_memory_locked(lo, pagesize, locked)) { fatal_error("Cannot (un)protect low guard page", lo); } cell hi = end; if (!set_memory_locked(hi, pagesize, locked)) { fatal_error("Cannot (un)protect high guard page", hi); } } }; }
22.840909
66
0.648756
alex-ilin
81ca9fbe9940391510a535af1dd25d58ff8ef4dd
1,323
cpp
C++
gameplay/src/lua/lua_LayoutType.cpp
j4m3z0r/GamePlay
02ca734e5734d2fbc9d00a7eff65ed2656f26975
[ "Apache-2.0", "Unlicense" ]
1
2021-09-02T01:45:24.000Z
2021-09-02T01:45:24.000Z
gameplay/src/lua/lua_LayoutType.cpp
j4m3z0r/GamePlay
02ca734e5734d2fbc9d00a7eff65ed2656f26975
[ "Apache-2.0", "Unlicense" ]
null
null
null
gameplay/src/lua/lua_LayoutType.cpp
j4m3z0r/GamePlay
02ca734e5734d2fbc9d00a7eff65ed2656f26975
[ "Apache-2.0", "Unlicense" ]
null
null
null
#include "Base.h" #include "lua_LayoutType.h" namespace gameplay { static const char* enumStringEmpty = ""; static const char* luaEnumString_LayoutType_LAYOUT_FLOW = "LAYOUT_FLOW"; static const char* luaEnumString_LayoutType_LAYOUT_VERTICAL = "LAYOUT_VERTICAL"; static const char* luaEnumString_LayoutType_LAYOUT_ABSOLUTE = "LAYOUT_ABSOLUTE"; Layout::Type lua_enumFromString_LayoutType(const char* s) { if (strcmp(s, luaEnumString_LayoutType_LAYOUT_FLOW) == 0) return Layout::LAYOUT_FLOW; if (strcmp(s, luaEnumString_LayoutType_LAYOUT_VERTICAL) == 0) return Layout::LAYOUT_VERTICAL; if (strcmp(s, luaEnumString_LayoutType_LAYOUT_ABSOLUTE) == 0) return Layout::LAYOUT_ABSOLUTE; GP_ERROR("Invalid enumeration value '%s' for enumeration Layout::Type.", s); return Layout::LAYOUT_FLOW; } const char* lua_stringFromEnum_LayoutType(Layout::Type e) { if (e == Layout::LAYOUT_FLOW) return luaEnumString_LayoutType_LAYOUT_FLOW; if (e == Layout::LAYOUT_VERTICAL) return luaEnumString_LayoutType_LAYOUT_VERTICAL; if (e == Layout::LAYOUT_ABSOLUTE) return luaEnumString_LayoutType_LAYOUT_ABSOLUTE; GP_ERROR("Invalid enumeration value '%d' for enumeration Layout::Type.", e); return enumStringEmpty; } }
33.923077
81
0.728647
j4m3z0r
81cb8a621a32b22ea69f9177e86c8d57f6021f55
364
cpp
C++
src/L/L0611.cpp
wlhcode/lscct
7fd112a9d1851ddcf41886d3084381a52e84a3ce
[ "MIT" ]
null
null
null
src/L/L0611.cpp
wlhcode/lscct
7fd112a9d1851ddcf41886d3084381a52e84a3ce
[ "MIT" ]
null
null
null
src/L/L0611.cpp
wlhcode/lscct
7fd112a9d1851ddcf41886d3084381a52e84a3ce
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define ll long long using namespace std; string s; int arr[20]={0}; int main(){ ios::sync_with_stdio(false); cin.tie(0); int a,b; cin>>a>>b; for(int i=a;i<=b;i++){ s+=std::to_string(i); for(int j=0;j<s.size();j++){ arr[char(s.at(j))-'0']++; } s.clear(); } for(int i=0;i<10;i++) cout<<i<<" "<<arr[i]<<endl; return 0; }
16.545455
50
0.554945
wlhcode
81cd6c6b2ce2ef98429b8530503cbe41cfe1e555
136
cpp
C++
qtreports/src/tags/detail.cpp
PO-31/QtReports-New
c9a22ac9dc0453c3ddbfcd0c4fd63a4341dff788
[ "MIT" ]
9
2017-02-14T09:38:41.000Z
2019-03-22T04:21:35.000Z
qtreports/src/tags/detail.cpp
PO-31/QtReports-New
c9a22ac9dc0453c3ddbfcd0c4fd63a4341dff788
[ "MIT" ]
15
2016-02-25T03:48:47.000Z
2018-05-02T13:39:46.000Z
qtreports/src/tags/detail.cpp
PO-31/QtReports-New
c9a22ac9dc0453c3ddbfcd0c4fd63a4341dff788
[ "MIT" ]
6
2018-02-18T23:59:02.000Z
2021-06-02T19:36:50.000Z
#include "detail.hpp" namespace qtreports { namespace detail { Detail::Detail() {} Detail::~Detail() {} } }
11.333333
28
0.536765
PO-31
81cf36d4c3cca724c9ccdb22f18796dc3be0a295
703
cpp
C++
pvl/abridged/graphs/scc/tarjan.cpp
bullybutcher/progvar-library
4d4b351c8a2540c522d00138e1bcf0edc528b540
[ "MIT" ]
3
2021-10-16T13:22:58.000Z
2021-10-29T22:03:44.000Z
pvl/abridged/graphs/scc/tarjan.cpp
bullybutcher/progvar-library
4d4b351c8a2540c522d00138e1bcf0edc528b540
[ "MIT" ]
19
2021-11-27T14:40:00.000Z
2022-03-30T07:14:59.000Z
pvl/abridged/graphs/scc/tarjan.cpp
bullybutcher/progvar-library
4d4b351c8a2540c522d00138e1bcf0edc528b540
[ "MIT" ]
2
2022-03-11T20:53:41.000Z
2022-03-20T07:08:46.000Z
int n, id[N], low[N], st[N], in[N], TOP, ID; int scc[N], SCC_SIZE; // 0 <= scc[u] < SCC_SIZE vector<int> adj[N]; // 0-based adjlist void dfs(int u) { id[u] = low[u] = ID++; st[TOP++] = u; in[u] = 1; for (int v : adj[u]) { if (id[v] == -1) { dfs(v); low[u] = min(low[u], low[v]); } else if (in[v] == 1) low[u] = min(low[u], id[v]); } if (id[u] == low[u]) { int sid = SCC_SIZE++; do { int v = st[--TOP]; in[v] = 0; scc[v] = sid; } while (st[TOP] != u); }} void tarjan() { // call tarjan() to load SCC memset(id, -1, sizeof(int) * n); SCC_SIZE = ID = TOP = 0; for (int i = 0; i < n; ++i) if (id[i] == -1) dfs(i); }
29.291667
48
0.433855
bullybutcher
81da7bb0fdce77a951bb42cc298fd81ee856b140
42,001
cpp
C++
src/mlpack/tests/kde_test.cpp
tomjpsun/mlpack
39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-01-11T14:14:30.000Z
2020-01-11T14:14:30.000Z
src/mlpack/tests/kde_test.cpp
tomjpsun/mlpack
39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-04-10T17:39:50.000Z
2020-04-11T14:56:25.000Z
src/mlpack/tests/kde_test.cpp
tomjpsun/mlpack
39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/** * @file kde_test.cpp * @author Roberto Hueso * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #include <mlpack/core.hpp> #include <mlpack/methods/kde/kde.hpp> #include <mlpack/core/tree/binary_space_tree.hpp> #include <mlpack/core/tree/octree.hpp> #include <mlpack/core/tree/cover_tree.hpp> #include <mlpack/core/tree/rectangle_tree.hpp> #include <boost/test/unit_test.hpp> #include "test_tools.hpp" #include "serialization.hpp" using namespace mlpack; using namespace mlpack::kde; using namespace mlpack::metric; using namespace mlpack::tree; using namespace mlpack::kernel; using namespace boost::serialization; BOOST_AUTO_TEST_SUITE(KDETest); // Brute force gaussian KDE. template <typename KernelType> void BruteForceKDE(const arma::mat& reference, const arma::mat& query, arma::vec& densities, KernelType& kernel) { metric::EuclideanDistance metric; for (size_t i = 0; i < query.n_cols; ++i) { for (size_t j = 0; j < reference.n_cols; ++j) { double distance = metric.Evaluate(query.col(i), reference.col(j)); densities(i) += kernel.Evaluate(distance); } } densities /= reference.n_cols; } /** * Test if simple case is correct according to manually calculated results. */ BOOST_AUTO_TEST_CASE(KDESimpleTest) { // Transposed reference and query sets because it's easier to read. arma::mat reference = { {-1.0, -1.0}, {-2.0, -1.0}, {-3.0, -2.0}, { 1.0, 1.0}, { 2.0, 1.0}, { 3.0, 2.0} }; arma::mat query = { { 0.0, 0.5}, { 0.4, -3.0}, { 0.0, 0.0}, {-2.1, 1.0} }; arma::inplace_trans(reference); arma::inplace_trans(query); arma::vec estimations; // Manually calculated results. arma::vec estimationsResult = {0.08323668699564207296148765, 0.00167470061366603324010116, 0.07658867126520703394465527, 0.01028120384800740999553525}; KDE<GaussianKernel, EuclideanDistance, arma::mat, KDTree> kde(0.0, 0.01, GaussianKernel(0.8)); kde.Train(reference); kde.Evaluate(query, estimations); for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(estimations[i], estimationsResult[i], 0.01); } /** * Test Train(Tree...) and Evaluate(Tree...). */ BOOST_AUTO_TEST_CASE(KDETreeAsArguments) { // Transposed reference and query sets because it's easier to read. arma::mat reference = { {-1.0, -1.0}, {-2.0, -1.0}, {-3.0, -2.0}, { 1.0, 1.0}, { 2.0, 1.0}, { 3.0, 2.0} }; arma::mat query = { { 0.0, 0.5}, { 0.4, -3.0}, { 0.0, 0.0}, {-2.1, 1.0} }; arma::inplace_trans(reference); arma::inplace_trans(query); arma::vec estimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec estimationsResult = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.8; // Get brute force results. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, estimationsResult, kernel); // Get dual-tree results. typedef KDTree<EuclideanDistance, kde::KDEStat, arma::mat> Tree; std::vector<size_t> oldFromNewQueries, oldFromNewReferences; Tree* queryTree = new Tree(query, oldFromNewQueries, 2); Tree* referenceTree = new Tree(reference, oldFromNewReferences, 2); KDE<GaussianKernel, EuclideanDistance, arma::mat, KDTree> kde(0.0, 1e-6, GaussianKernel(kernelBandwidth)); kde.Train(referenceTree, &oldFromNewReferences); kde.Evaluate(queryTree, std::move(oldFromNewQueries), estimations); for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(estimations[i], estimationsResult[i], 0.01); delete queryTree; delete referenceTree; } /** * Test dual-tree implementation results against brute force results. */ BOOST_AUTO_TEST_CASE(GaussianKDEBruteForceTest) { arma::mat reference = arma::randu(2, 200); arma::mat query = arma::randu(2, 60); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.12; const double relError = 0.05; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::KDTree> kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric); kde.Train(reference); kde.Evaluate(query, treeEstimations); // Check whether results are equal. for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100); } /** * Test single-tree implementation results against brute force results. */ BOOST_AUTO_TEST_CASE(GaussianSingleKDEBruteForceTest) { arma::mat reference = arma::randu(2, 300); arma::mat query = arma::randu(2, 100); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.3; const double relError = 0.04; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::KDTree> kde(relError, 0.0, kernel, KDEMode::SINGLE_TREE_MODE, metric); kde.Train(reference); kde.Evaluate(query, treeEstimations); // Check whether results are equal. for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100); } /** * Test single-tree implementation results against brute force results using * a cover-tree and Epanechnikov kernel. */ BOOST_AUTO_TEST_CASE(EpanechnikovCoverSingleKDETest) { arma::mat reference = arma::randu(2, 300); arma::mat query = arma::randu(2, 100); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 1.1; const double relError = 0.08; // Brute force KDE. EpanechnikovKernel kernel(kernelBandwidth); BruteForceKDE<EpanechnikovKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<EpanechnikovKernel, metric::EuclideanDistance, arma::mat, tree::StandardCoverTree> kde(relError, 0.0, kernel, KDEMode::SINGLE_TREE_MODE, metric); kde.Train(reference); kde.Evaluate(query, treeEstimations); // Check whether results are equal. for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100); } /** * Test single-tree implementation results against brute force results using * a cover-tree and Gaussian kernel. */ BOOST_AUTO_TEST_CASE(GaussianCoverSingleKDETest) { arma::mat reference = arma::randu(2, 300); arma::mat query = arma::randu(2, 100); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 1.1; const double relError = 0.08; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::StandardCoverTree> kde(relError, 0.0, kernel, KDEMode::SINGLE_TREE_MODE, metric); kde.Train(reference); kde.Evaluate(query, treeEstimations); // Check whether results are equal. for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100); } /** * Test single-tree implementation results against brute force results using * an octree and Epanechnikov kernel. */ BOOST_AUTO_TEST_CASE(EpanechnikovOctreeSingleKDETest) { arma::mat reference = arma::randu(2, 300); arma::mat query = arma::randu(2, 100); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 1.0; const double relError = 0.05; // Brute force KDE. EpanechnikovKernel kernel(kernelBandwidth); BruteForceKDE<EpanechnikovKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<EpanechnikovKernel, metric::EuclideanDistance, arma::mat, tree::Octree> kde(relError, 0.0, kernel, KDEMode::SINGLE_TREE_MODE, metric); kde.Train(reference); kde.Evaluate(query, treeEstimations); // Check whether results are equal. for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100); } /** * Test BallTree dual-tree implementation results against brute force results. */ BOOST_AUTO_TEST_CASE(BallTreeGaussianKDETest) { arma::mat reference = arma::randu(2, 200); arma::mat query = arma::randu(2, 60); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.4; const double relError = 0.05; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // BallTree KDE. typedef BallTree<EuclideanDistance, kde::KDEStat, arma::mat> Tree; std::vector<size_t> oldFromNewQueries, oldFromNewReferences; Tree* queryTree = new Tree(query, oldFromNewQueries, 2); Tree* referenceTree = new Tree(reference, oldFromNewReferences, 2); KDE<GaussianKernel, EuclideanDistance, arma::mat, BallTree> kde(relError, 0.0, GaussianKernel(kernelBandwidth)); kde.Train(referenceTree, &oldFromNewReferences); kde.Evaluate(queryTree, std::move(oldFromNewQueries), treeEstimations); // Check whether results are equal. for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100); delete queryTree; delete referenceTree; } /** * Test Octree dual-tree implementation results against brute force results. */ BOOST_AUTO_TEST_CASE(OctreeGaussianKDETest) { arma::mat reference = arma::randu(2, 500); arma::mat query = arma::randu(2, 200); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.3; const double relError = 0.01; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::Octree> kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric); kde.Train(reference); kde.Evaluate(query, treeEstimations); // Check whether results are equal. for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100); } /** * Test RTree dual-tree implementation results against brute force results. */ BOOST_AUTO_TEST_CASE(RTreeGaussianKDETest) { arma::mat reference = arma::randu(2, 500); arma::mat query = arma::randu(2, 200); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.3; const double relError = 0.01; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::RTree> kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric); kde.Train(reference); kde.Evaluate(query, treeEstimations); // Check whether results are equal. for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100); } /** * Test Standard Cover Tree dual-tree implementation results against brute * force results using Gaussian kernel. */ BOOST_AUTO_TEST_CASE(StandardCoverTreeGaussianKDETest) { arma::mat reference = arma::randu(2, 500); arma::mat query = arma::randu(2, 200); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.3; const double relError = 0.01; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::StandardCoverTree> kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric); kde.Train(reference); kde.Evaluate(query, treeEstimations); // Check whether results are equal. for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100); } /** * Test Standard Cover Tree dual-tree implementation results against brute * force results using Epanechnikov kernel. */ BOOST_AUTO_TEST_CASE(StandardCoverTreeEpanechnikovKDETest) { arma::mat reference = arma::randu(2, 500); arma::mat query = arma::randu(2, 200); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.3; const double relError = 0.01; // Brute force KDE. EpanechnikovKernel kernel(kernelBandwidth); BruteForceKDE<EpanechnikovKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<EpanechnikovKernel, metric::EuclideanDistance, arma::mat, tree::StandardCoverTree> kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric); kde.Train(reference); kde.Evaluate(query, treeEstimations); // Check whether results are equal. for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100); } /** * Test duplicated value in reference matrix. */ BOOST_AUTO_TEST_CASE(DuplicatedReferenceSampleKDETest) { arma::mat reference = arma::randu(2, 30); arma::mat query = arma::randu(2, 10); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.4; const double relError = 0.05; // Duplicate value. reference.col(2) = reference.col(3); // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Dual-tree KDE. typedef KDTree<EuclideanDistance, kde::KDEStat, arma::mat> Tree; std::vector<size_t> oldFromNewQueries, oldFromNewReferences; Tree* queryTree = new Tree(query, oldFromNewQueries, 2); Tree* referenceTree = new Tree(reference, oldFromNewReferences, 2); KDE<GaussianKernel, EuclideanDistance, arma::mat, KDTree> kde(relError, 0.0, GaussianKernel(kernelBandwidth)); kde.Train(referenceTree, &oldFromNewReferences); kde.Evaluate(queryTree, oldFromNewQueries, treeEstimations); // Check whether results are equal. for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100); delete queryTree; delete referenceTree; } /** * Test duplicated value in query matrix. */ BOOST_AUTO_TEST_CASE(DuplicatedQuerySampleKDETest) { arma::mat reference = arma::randu(2, 30); arma::mat query = arma::randu(2, 10); arma::vec estimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.4; const double relError = 0.05; // Duplicate value. query.col(2) = query.col(3); // Dual-tree KDE. typedef KDTree<EuclideanDistance, kde::KDEStat, arma::mat> Tree; std::vector<size_t> oldFromNewQueries, oldFromNewReferences; Tree* queryTree = new Tree(query, oldFromNewQueries, 2); Tree* referenceTree = new Tree(reference, oldFromNewReferences, 2); KDE<GaussianKernel, EuclideanDistance, arma::mat, KDTree> kde(relError, 0.0, GaussianKernel(kernelBandwidth)); kde.Train(referenceTree, &oldFromNewReferences); kde.Evaluate(queryTree, oldFromNewQueries, estimations); // Check whether results are equal. BOOST_REQUIRE_CLOSE(estimations[2], estimations[3], relError * 100); delete queryTree; delete referenceTree; } /** * Test dual-tree breadth-first implementation results against brute force * results. */ BOOST_AUTO_TEST_CASE(BreadthFirstKDETest) { arma::mat reference = arma::randu(2, 200); arma::mat query = arma::randu(2, 60); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.8; const double relError = 0.01; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Breadth-First KDE. metric::EuclideanDistance metric; KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::KDTree, tree::KDTree<metric::EuclideanDistance, kde::KDEStat, arma::mat>::template BreadthFirstDualTreeTraverser> kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric); kde.Train(reference); kde.Evaluate(query, treeEstimations); // Check whether results are equal. for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100); } /** * Test 1-dimensional implementation results against brute force results. */ BOOST_AUTO_TEST_CASE(OneDimensionalTest) { arma::mat reference = arma::randu(1, 200); arma::mat query = arma::randu(1, 60); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.7; const double relError = 0.01; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::KDTree> kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric); kde.Train(reference); kde.Evaluate(query, treeEstimations); // Check whether results are equal. for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(bfEstimations[i], treeEstimations[i], relError * 100); } /** * Test a case where an empty reference set is given to train the model. */ BOOST_AUTO_TEST_CASE(EmptyReferenceTest) { arma::mat reference; arma::mat query = arma::randu(1, 10); arma::vec estimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.7; const double relError = 0.01; // KDE. metric::EuclideanDistance metric; GaussianKernel kernel(kernelBandwidth); KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::KDTree> kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric); // When training using the dataset matrix. BOOST_REQUIRE_THROW(kde.Train(reference), std::invalid_argument); // When training using a tree. std::vector<size_t> oldFromNewReferences; typedef KDTree<EuclideanDistance, kde::KDEStat, arma::mat> Tree; Tree* referenceTree = new Tree(reference, oldFromNewReferences, 2); BOOST_REQUIRE_THROW( kde.Train(referenceTree, &oldFromNewReferences), std::invalid_argument); delete referenceTree; } /** * Tests when reference set values and query set values dimensions don't match. */ BOOST_AUTO_TEST_CASE(EvaluationMatchDimensionsTest) { arma::mat reference = arma::randu(3, 10); arma::mat query = arma::randu(1, 10); arma::vec estimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.7; const double relError = 0.01; // KDE. metric::EuclideanDistance metric; GaussianKernel kernel(kernelBandwidth); KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::KDTree> kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric); kde.Train(reference); // When evaluating using the query dataset matrix. BOOST_REQUIRE_THROW(kde.Evaluate(query, estimations), std::invalid_argument); // When evaluating using a query tree. typedef KDTree<EuclideanDistance, kde::KDEStat, arma::mat> Tree; std::vector<size_t> oldFromNewQueries; Tree* queryTree = new Tree(query, oldFromNewQueries, 3); BOOST_REQUIRE_THROW(kde.Evaluate(queryTree, oldFromNewQueries, estimations), std::invalid_argument); delete queryTree; } /** * Tests when an empty query set is given to be evaluated. */ BOOST_AUTO_TEST_CASE(EmptyQuerySetTest) { arma::mat reference = arma::randu(1, 10); arma::mat query; // Set estimations to the wrong size. arma::vec estimations(33, arma::fill::zeros); const double kernelBandwidth = 0.7; const double relError = 0.01; // KDE. metric::EuclideanDistance metric; GaussianKernel kernel(kernelBandwidth); KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::KDTree> kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric); kde.Train(reference); // The query set must be empty. BOOST_REQUIRE_EQUAL(query.n_cols, 0); // When evaluating using the query dataset matrix. BOOST_REQUIRE_NO_THROW(kde.Evaluate(query, estimations)); // When evaluating using a query tree. typedef KDTree<EuclideanDistance, kde::KDEStat, arma::mat> Tree; std::vector<size_t> oldFromNewQueries; Tree* queryTree = new Tree(query, oldFromNewQueries, 3); BOOST_REQUIRE_NO_THROW( kde.Evaluate(queryTree, oldFromNewQueries, estimations)); delete queryTree; // Estimations must be empty. BOOST_REQUIRE_EQUAL(estimations.size(), 0); } /** * Tests serialiation of KDE models. */ BOOST_AUTO_TEST_CASE(SerializationTest) { // Initial KDE model to be serialized. const double relError = 0.25; const double absError = 0.0; const bool monteCarlo = false; const double MCProb = 0.8; const size_t initialSampleSize = 35; const double entryCoef = 5; const double breakCoef = 0.6; arma::mat reference = arma::randu(4, 800); KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::KDTree> kde(relError, absError, GaussianKernel(0.25), KDEMode::DUAL_TREE_MODE, metric::EuclideanDistance(), monteCarlo, MCProb, initialSampleSize, entryCoef, breakCoef); kde.Train(reference); // Get estimations to compare. arma::mat query = arma::randu(4, 100);; arma::vec estimations = arma::vec(query.n_cols, arma::fill::zeros); kde.Evaluate(query, estimations); // Initialize serialized objects. KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::KDTree> kdeXml, kdeText, kdeBinary; SerializeObjectAll(kde, kdeXml, kdeText, kdeBinary); // Check everything is correct. BOOST_REQUIRE_CLOSE(kde.RelativeError(), relError, 1e-8); BOOST_REQUIRE_CLOSE(kdeXml.RelativeError(), relError, 1e-8); BOOST_REQUIRE_CLOSE(kdeText.RelativeError(), relError, 1e-8); BOOST_REQUIRE_CLOSE(kdeBinary.RelativeError(), relError, 1e-8); BOOST_REQUIRE_CLOSE(kde.AbsoluteError(), absError, 1e-8); BOOST_REQUIRE_CLOSE(kdeXml.AbsoluteError(), absError, 1e-8); BOOST_REQUIRE_CLOSE(kdeText.AbsoluteError(), absError, 1e-8); BOOST_REQUIRE_CLOSE(kdeBinary.AbsoluteError(), absError, 1e-8); BOOST_REQUIRE_EQUAL(kde.IsTrained(), true); BOOST_REQUIRE_EQUAL(kdeXml.IsTrained(), true); BOOST_REQUIRE_EQUAL(kdeText.IsTrained(), true); BOOST_REQUIRE_EQUAL(kdeBinary.IsTrained(), true); const KDEMode mode = KDEMode::DUAL_TREE_MODE; BOOST_REQUIRE_EQUAL(kde.Mode(), mode); BOOST_REQUIRE_EQUAL(kdeXml.Mode(), mode); BOOST_REQUIRE_EQUAL(kdeText.Mode(), mode); BOOST_REQUIRE_EQUAL(kdeBinary.Mode(), mode); BOOST_REQUIRE_EQUAL(kde.MonteCarlo(), monteCarlo); BOOST_REQUIRE_EQUAL(kdeXml.MonteCarlo(), monteCarlo); BOOST_REQUIRE_EQUAL(kdeText.MonteCarlo(), monteCarlo); BOOST_REQUIRE_EQUAL(kdeBinary.MonteCarlo(), monteCarlo); BOOST_REQUIRE_CLOSE(kde.MCProb(), MCProb, 1e-8); BOOST_REQUIRE_CLOSE(kdeXml.MCProb(), MCProb, 1e-8); BOOST_REQUIRE_CLOSE(kdeText.MCProb(), MCProb, 1e-8); BOOST_REQUIRE_CLOSE(kdeBinary.MCProb(), MCProb, 1e-8); BOOST_REQUIRE_EQUAL(kde.MCInitialSampleSize(), initialSampleSize); BOOST_REQUIRE_EQUAL(kdeXml.MCInitialSampleSize(), initialSampleSize); BOOST_REQUIRE_EQUAL(kdeText.MCInitialSampleSize(), initialSampleSize); BOOST_REQUIRE_EQUAL(kdeBinary.MCInitialSampleSize(), initialSampleSize); BOOST_REQUIRE_CLOSE(kde.MCEntryCoef(), entryCoef, 1e-8); BOOST_REQUIRE_CLOSE(kdeXml.MCEntryCoef(), entryCoef, 1e-8); BOOST_REQUIRE_CLOSE(kdeText.MCEntryCoef(), entryCoef, 1e-8); BOOST_REQUIRE_CLOSE(kdeBinary.MCEntryCoef(), entryCoef, 1e-8); BOOST_REQUIRE_CLOSE(kde.MCBreakCoef(), breakCoef, 1e-8); BOOST_REQUIRE_CLOSE(kdeXml.MCBreakCoef(), breakCoef, 1e-8); BOOST_REQUIRE_CLOSE(kdeText.MCBreakCoef(), breakCoef, 1e-8); BOOST_REQUIRE_CLOSE(kdeBinary.MCBreakCoef(), breakCoef, 1e-8); // Test if execution gives the same result. arma::vec xmlEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec textEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec binEstimations = arma::vec(query.n_cols, arma::fill::zeros); kdeXml.Evaluate(query, xmlEstimations); kdeText.Evaluate(query, textEstimations); kdeBinary.Evaluate(query, binEstimations); for (size_t i = 0; i < query.n_cols; ++i) { BOOST_REQUIRE_CLOSE(estimations[i], xmlEstimations[i], relError * 100); BOOST_REQUIRE_CLOSE(estimations[i], textEstimations[i], relError * 100); BOOST_REQUIRE_CLOSE(estimations[i], binEstimations[i], relError * 100); } } /** * Test if the copy constructor and copy operator works properly. */ BOOST_AUTO_TEST_CASE(CopyConstructor) { arma::mat reference = arma::randu(2, 300); arma::mat query = arma::randu(2, 100); arma::vec estimations1, estimations2, estimations3; const double kernelBandwidth = 1.5; const double relError = 0.05; typedef KDE<GaussianKernel, metric::EuclideanDistance, arma::mat> KDEType; // KDE. KDEType kde(relError, 0, kernel::GaussianKernel(kernelBandwidth)); kde.Train(std::move(reference)); // Copy constructor KDE. KDEType constructor(kde); // Copy operator KDE. KDEType oper = kde; // Evaluations. kde.Evaluate(query, estimations1); constructor.Evaluate(query, estimations2); oper.Evaluate(query, estimations3); // Check results. for (size_t i = 0; i < query.n_cols; ++i) { BOOST_REQUIRE_CLOSE(estimations1[i], estimations2[i], 1e-10); BOOST_REQUIRE_CLOSE(estimations2[i], estimations3[i], 1e-10); } } /** * Test if the move constructor works properly. */ BOOST_AUTO_TEST_CASE(MoveConstructor) { arma::mat reference = arma::randu(2, 300); arma::mat query = arma::randu(2, 100); arma::vec estimations1, estimations2, estimations3; const double kernelBandwidth = 1.2; const double relError = 0.05; typedef KDE<EpanechnikovKernel, metric::EuclideanDistance, arma::mat> KDEType; // KDE. KDEType kde(relError, 0, kernel::EpanechnikovKernel(kernelBandwidth)); kde.Train(std::move(reference)); kde.Evaluate(query, estimations1); // Move constructor KDE. KDEType constructor(std::move(kde)); constructor.Evaluate(query, estimations2); // Check results. BOOST_REQUIRE_THROW(kde.Evaluate(query, estimations3), std::runtime_error); for (size_t i = 0; i < query.n_cols; ++i) BOOST_REQUIRE_CLOSE(estimations1[i], estimations2[i], 1e-10); } /** * Test if an untrained KDE works properly. */ BOOST_AUTO_TEST_CASE(NotTrained) { arma::mat query = arma::randu(1, 10); std::vector<size_t> oldFromNew; arma::vec estimations; KDE<> kde; KDE<>::Tree queryTree(query, oldFromNew); // Check results. BOOST_REQUIRE_THROW(kde.Evaluate(query, estimations), std::runtime_error); BOOST_REQUIRE_THROW(kde.Evaluate(&queryTree, oldFromNew, estimations), std::runtime_error); BOOST_REQUIRE_THROW(kde.Evaluate(estimations), std::runtime_error); } /** * Test single KD-tree implementation results against brute force results using * Monte Carlo estimations when possible. */ BOOST_AUTO_TEST_CASE(GaussianSingleKDTreeMonteCarloKDE) { arma::mat reference = arma::randu(2, 3000); arma::mat query = arma::randu(2, 100); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.35; const double relError = 0.05; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::KDTree> kde(relError, 0.0, kernel, KDEMode::SINGLE_TREE_MODE, metric, true, 0.95, 100, 2, 0.7); kde.Train(reference); kde.Evaluate(query, treeEstimations); // The Monte Carlo estimation has a random component so it can fail. Therefore // we require a reasonable amount of results to be right. size_t correctResults = 0; for (size_t i = 0; i < query.n_cols; ++i) { const double resultRelativeError = std::abs((bfEstimations[i] - treeEstimations[i]) / bfEstimations[i]); if (resultRelativeError < relError) ++correctResults; } BOOST_REQUIRE_GT(correctResults, 70); } /** * Test single cover-tree implementation results against brute force results * using Monte Carlo estimations when possible. */ BOOST_AUTO_TEST_CASE(GaussianSingleCoverTreeMonteCarloKDE) { arma::mat reference = arma::randu(2, 3000); arma::mat query = arma::randu(2, 100); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.35; const double relError = 0.05; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::StandardCoverTree> kde(relError, 0.0, kernel, KDEMode::SINGLE_TREE_MODE, metric, true, 0.95, 100, 2, 0.7); kde.Train(reference); kde.Evaluate(query, treeEstimations); // The Monte Carlo estimation has a random component so it can fail. Therefore // we require a reasonable amount of results to be right. size_t correctResults = 0; for (size_t i = 0; i < query.n_cols; ++i) { const double resultRelativeError = std::abs((bfEstimations[i] - treeEstimations[i]) / bfEstimations[i]); if (resultRelativeError < relError) ++correctResults; } BOOST_REQUIRE_GT(correctResults, 70); } /** * Test single octree implementation results against brute force results * using Monte Carlo estimations when possible. */ BOOST_AUTO_TEST_CASE(GaussianSingleOctreeMonteCarloKDE) { arma::mat reference = arma::randu(2, 3000); arma::mat query = arma::randu(2, 100); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.55; const double relError = 0.02; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::Octree> kde(relError, 0.0, kernel, KDEMode::SINGLE_TREE_MODE, metric, true, 0.95, 100, 3, 0.8); kde.Train(reference); kde.Evaluate(query, treeEstimations); // The Monte Carlo estimation has a random component so it can fail. Therefore // we require a reasonable amount of results to be right. size_t correctResults = 0; for (size_t i = 0; i < query.n_cols; ++i) { const double resultRelativeError = std::abs((bfEstimations[i] - treeEstimations[i]) / bfEstimations[i]); if (resultRelativeError < relError) ++correctResults; } BOOST_REQUIRE_GT(correctResults, 70); } /** * Test dual kd-tree implementation results against brute force results * using Monte Carlo estimations when possible. */ BOOST_AUTO_TEST_CASE(GaussianDualKDTreeMonteCarloKDE) { arma::mat reference = arma::randu(2, 3000); arma::mat query = arma::randu(2, 200); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.4; const double relError = 0.05; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::KDTree> kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric, true, 0.95, 100, 3, 0.8); kde.Train(reference); kde.Evaluate(query, treeEstimations); // The Monte Carlo estimation has a random component so it can fail. Therefore // we require a reasonable amount of results to be right. size_t correctResults = 0; for (size_t i = 0; i < query.n_cols; ++i) { const double resultRelativeError = std::abs((bfEstimations[i] - treeEstimations[i]) / bfEstimations[i]); if (resultRelativeError < relError) ++correctResults; } BOOST_REQUIRE_GT(correctResults, 70); } /** * Test dual Cover-tree implementation results against brute force results * using Monte Carlo estimations when possible. */ BOOST_AUTO_TEST_CASE(GaussianDualCoverTreeMonteCarloKDE) { arma::mat reference = arma::randu(2, 3000); arma::mat query = arma::randu(2, 200); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.5; const double relError = 0.025; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::StandardCoverTree> kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric, true, 0.95, 100, 3, 0.8); kde.Train(reference); kde.Evaluate(query, treeEstimations); // The Monte Carlo estimation has a random component so it can fail. Therefore // we require a reasonable amount of results to be right. size_t correctResults = 0; for (size_t i = 0; i < query.n_cols; ++i) { const double resultRelativeError = std::abs((bfEstimations[i] - treeEstimations[i]) / bfEstimations[i]); if (resultRelativeError < relError) ++correctResults; } BOOST_REQUIRE_GT(correctResults, 70); } /** * Test dual octree implementation results against brute force results * using Monte Carlo estimations when possible. */ BOOST_AUTO_TEST_CASE(GaussianDualOctreeMonteCarloKDE) { arma::mat reference = arma::randu(2, 3000); arma::mat query = arma::randu(2, 200); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.7; const double relError = 0.03; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::Octree> kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric, true, 0.95, 100, 3, 0.8); kde.Train(reference); kde.Evaluate(query, treeEstimations); // The Monte Carlo estimation has a random component so it can fail. Therefore // we require a reasonable amount of results to be right. size_t correctResults = 0; for (size_t i = 0; i < query.n_cols; ++i) { const double resultRelativeError = std::abs((bfEstimations[i] - treeEstimations[i]) / bfEstimations[i]); if (resultRelativeError < relError) ++correctResults; } BOOST_REQUIRE_GT(correctResults, 70); } /** * Test dual kd-tree breadth first traversal implementation results against * brute force results using Monte Carlo estimations when possible. */ BOOST_AUTO_TEST_CASE(GaussianBreadthDualKDTreeMonteCarloKDE) { arma::mat reference = arma::randu(2, 3000); arma::mat query = arma::randu(2, 200); arma::vec bfEstimations = arma::vec(query.n_cols, arma::fill::zeros); arma::vec treeEstimations = arma::vec(query.n_cols, arma::fill::zeros); const double kernelBandwidth = 0.7; const double relError = 0.025; // Brute force KDE. GaussianKernel kernel(kernelBandwidth); BruteForceKDE<GaussianKernel>(reference, query, bfEstimations, kernel); // Optimized KDE. metric::EuclideanDistance metric; KDE<GaussianKernel, metric::EuclideanDistance, arma::mat, tree::KDTree, tree::KDTree<metric::EuclideanDistance, kde::KDEStat, arma::mat>::template BreadthFirstDualTreeTraverser> kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric, true, 0.95, 100, 3, 0.8); kde.Train(reference); kde.Evaluate(query, treeEstimations); // The Monte Carlo estimation has a random component so it can fail. Therefore // we require a reasonable amount of results to be right. size_t correctResults = 0; for (size_t i = 0; i < query.n_cols; ++i) { const double resultRelativeError = std::abs((bfEstimations[i] - treeEstimations[i]) / bfEstimations[i]); if (resultRelativeError < relError) ++correctResults; } BOOST_REQUIRE_GT(correctResults, 70); } BOOST_AUTO_TEST_SUITE_END();
32.184674
80
0.661437
tomjpsun
81dabd9a860c0fbd4b337e7cb88afd1bcc11ced5
765
hpp
C++
include/lol/def/CollectionsLcdsSummonerRuneInventory.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/CollectionsLcdsSummonerRuneInventory.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/CollectionsLcdsSummonerRuneInventory.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" #include "CollectionsLcdsSummonerRune.hpp" namespace lol { struct CollectionsLcdsSummonerRuneInventory { std::string dateString; uint64_t summonerId; std::vector<CollectionsLcdsSummonerRune> summonerRunes; }; inline void to_json(json& j, const CollectionsLcdsSummonerRuneInventory& v) { j["dateString"] = v.dateString; j["summonerId"] = v.summonerId; j["summonerRunes"] = v.summonerRunes; } inline void from_json(const json& j, CollectionsLcdsSummonerRuneInventory& v) { v.dateString = j.at("dateString").get<std::string>(); v.summonerId = j.at("summonerId").get<uint64_t>(); v.summonerRunes = j.at("summonerRunes").get<std::vector<CollectionsLcdsSummonerRune>>(); } }
38.25
93
0.715033
Maufeat
81dde5b38202b2fe57a196ee7a80fb54d225f2d0
709
cpp
C++
src/RGBPolynomial.cpp
kreztoffee/ArtBot
cdb63945551e8503642dc5c9f3051c94e3120e56
[ "MIT" ]
null
null
null
src/RGBPolynomial.cpp
kreztoffee/ArtBot
cdb63945551e8503642dc5c9f3051c94e3120e56
[ "MIT" ]
null
null
null
src/RGBPolynomial.cpp
kreztoffee/ArtBot
cdb63945551e8503642dc5c9f3051c94e3120e56
[ "MIT" ]
null
null
null
#include <math.h> #include <vector> #include "RGBPolynomial.hpp" float RGBPolynomial::norm(float z) { while (z > 1) z--; return z; } float RGBPolynomial::applySinglePoly(const float z, std::vector<int> coeffs) { float res = 0; for (int i = coeffs.size() - 1; i >= 0; i--) res += coeffs[i] * pow(z, i); return res; } std::vector<float> RGBPolynomial::applyPoly(const float z) { std::vector<float> vec = {}; vec.push_back(norm(applySinglePoly(z, coeffs[0]))); vec.push_back(norm(applySinglePoly(z, coeffs[1]))); vec.push_back(norm(applySinglePoly(z, coeffs[2]))); return vec; } RGBPolynomial::RGBPolynomial(std::vector<std::vector<int>> coefficients) { coeffs = coefficients; }
22.15625
76
0.668547
kreztoffee
81e05416f630e126c21d433c7c4b261050005b43
60,020
cpp
C++
XMPFiles/source/XMPFiles.cpp
hfiguiere/exempi
ba6698c39da63b0cbe4742389d31bf4de8716de0
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
13
2015-04-10T16:31:04.000Z
2021-10-12T18:01:22.000Z
XMPFiles/source/XMPFiles.cpp
hfiguiere/exempi
ba6698c39da63b0cbe4742389d31bf4de8716de0
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
7
2016-06-05T22:12:29.000Z
2018-09-25T23:15:52.000Z
XMPFiles/source/XMPFiles.cpp
hfiguiere/exempi
ba6698c39da63b0cbe4742389d31bf4de8716de0
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
11
2015-05-07T06:25:51.000Z
2021-12-23T19:43:35.000Z
// ================================================================================================= // ADOBE SYSTEMS INCORPORATED // Copyright 2004 Adobe Systems Incorporated // All Rights Reserved // // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms // of the Adobe license agreement accompanying it. // ================================================================================================= #include "public/include/XMP_Environment.h" // ! Must be the first #include! #include "public/include/XMP_Const.h" #include "public/include/XMP_IO.hpp" #include <vector> #include <string.h> #include "source/UnicodeConversions.hpp" #include "source/XMPFiles_IO.hpp" #include "source/XIO.hpp" #include "XMPFiles/source/XMPFiles_Impl.hpp" #include "XMPFiles/source/HandlerRegistry.h" #if EnablePluginManager #include "XMPFiles/source/PluginHandler/PluginManager.h" #endif #include "XMPFiles/source/FormatSupport/ID3_Support.hpp" #include "XMPFiles/source/FormatSupport/ISOBaseMedia_Support.hpp" #if EnablePacketScanning #include "XMPFiles/source/FileHandlers/Scanner_Handler.hpp" #endif #if EnableGenericHandling #include "XMPFiles/source/FileHandlers/Generic_Handler.hpp" #endif #include "XMPCore/XMPCoreDefines.h" #if ENABLE_CPP_DOM_MODEL #include "XMPCore/Interfaces/IMetadata.h" #include "XMPCore/Interfaces/INodeIterator.h" #include "XMPCommon/Interfaces/IUTF8String.h" #include "XMPCore/Interfaces/ICoreObjectFactory.h" #endif // ================================================================================================= /// \file XMPFiles.cpp /// \brief High level support to access metadata in files of interest to Adobe applications. /// /// This header ... /// // ================================================================================================= using namespace Common; #if EnablePluginManager using namespace XMP_PLUGIN; #endif // ================================================================================================= XMP_Int32 sXMPFilesInitCount = 0; static XMP_ProgressTracker::CallbackInfo sProgressDefault; static XMPFiles::ErrorCallbackInfo sDefaultErrorCallback; #if GatherPerformanceData APIPerfCollection* sAPIPerf = 0; #endif // These are embedded version strings. #if XMP_DebugBuild #define kXMPFiles_DebugFlag 1 #else #define kXMPFiles_DebugFlag 0 #endif #define kXMPFiles_VersionNumber ( (kXMPFiles_DebugFlag << 31) | \ (XMP_API_VERSION_MAJOR << 24) | \ (XMP_API_VERSION_MINOR << 16) | \ (XMP_API_VERSION_MICRO << 8) ) #define kXMPFilesName "XMP Files" #define kXMPFiles_VersionMessage kXMPFilesName " " XMPFILES_API_VERSION_STRING const char * kXMPFiles_EmbeddedVersion = kXMPFiles_VersionMessage; const char * kXMPFiles_EmbeddedCopyright = kXMPFilesName " " kXMP_CopyrightStr; #define EMPTY_FILE_PATH "" #define XMP_FILES_STATIC_START try { /*int a;*/ #define XMP_FILES_STATIC_END1(severity) /*a = 1;*/ } catch ( XMP_Error & error ) { sDefaultErrorCallback.NotifyClient ( (severity), error, EMPTY_FILE_PATH ); } #define XMP_FILES_STATIC_END2(filePath, severity) /*a = 1;*/ } catch ( XMP_Error & error ) { sDefaultErrorCallback.NotifyClient ( (severity), error, (filePath) ); } #define XMP_FILES_START try { /*int b;*/ #define XMP_FILES_END1(severity) /*b = 1;*/ } catch ( XMP_Error & error ) { errorCallback.NotifyClient ( (severity), error, this->filePath.c_str() ); } #define XMP_FILES_END2(filePath, severity) /*b = 1;*/ } catch ( XMP_Error & error ) { errorCallback.NotifyClient ( (severity), error, (filePath) ); } #define XMP_FILES_STATIC_NOTIFY_ERROR(errorCallbackPtr, filePath, severity, error) \ if ( (errorCallbackPtr) != NULL ) (errorCallbackPtr)->NotifyClient ( (severity), (error), (filePath) ); // ================================================================================================= #if EnablePacketScanning static XMPFileHandlerInfo kScannerHandlerInfo ( kXMP_UnknownFile, kScanner_HandlerFlags, (CheckFileFormatProc)0, Scanner_MetaHandlerCTor ); #endif #if EnableGenericHandling static XMPFileHandlerInfo kGenericHandlerInfo ( kXMP_UnknownFile, kGeneric_HandlerFlags, (CheckFileFormatProc)0, Generic_MetaHandlerCTor ); #endif // ================================================================================================= /* class-static */ void XMPFiles::GetVersionInfo ( XMP_VersionInfo * info ) { XMP_FILES_STATIC_START memset ( info, 0, sizeof(XMP_VersionInfo) ); info->major = XMPFILES_API_VERSION_MAJOR; info->minor = XMPFILES_API_VERSION_MINOR; info->micro = 0; //no longer used info->isDebug = kXMPFiles_DebugFlag; info->flags = 0; // ! None defined yet. info->message = kXMPFiles_VersionMessage; XMP_FILES_STATIC_END1 ( kXMPErrSev_OperationFatal ) } // XMPFiles::GetVersionInfo // ================================================================================================= #if XMP_TraceFilesCalls FILE * xmpFilesLog = stderr; #endif #if UseGlobalLibraryLock & (! XMP_StaticBuild ) XMP_BasicMutex sLibraryLock; // ! Handled in XMPMeta for static builds. #endif /* class static */ bool XMPFiles::Initialize( XMP_OptionBits options, const char* pluginFolder, const char* plugins /* = NULL */ ) { XMP_FILES_STATIC_START ++sXMPFilesInitCount; if ( sXMPFilesInitCount > 1 ) return true; #if XMP_TraceFilesCallsToFile xmpFilesLog = fopen ( "XMPFilesLog.txt", "w" ); if ( xmpFilesLog == 0 ) xmpFilesLog = stderr; #endif #if UseGlobalLibraryLock & (! XMP_StaticBuild ) InitializeBasicMutex ( sLibraryLock ); // ! Handled in XMPMeta for static builds. #endif SXMPMeta::Initialize(); // Just in case the client does not. if ( ! Initialize_LibUtils() ) return false; if ( ! ID3_Support::InitializeGlobals() ) return false; #if GatherPerformanceData sAPIPerf = new APIPerfCollection; #endif XMP_Uns16 endianInt = 0x00FF; XMP_Uns8 endianByte = *((XMP_Uns8*)&endianInt); if ( kBigEndianHost ) { if ( endianByte != 0 ) XMP_Throw ( "Big endian flag mismatch", kXMPErr_InternalFailure ); } else { if ( endianByte != 0xFF ) XMP_Throw ( "Little endian flag mismatch", kXMPErr_InternalFailure ); } XMP_Assert ( kUTF8_PacketHeaderLen == strlen ( "<?xpacket begin='xxx' id='W5M0MpCehiHzreSzNTczkc9d'" ) ); XMP_Assert ( kUTF8_PacketTrailerLen == strlen ( (const char *) kUTF8_PacketTrailer ) ); HandlerRegistry::getInstance().initialize(); InitializeUnicodeConversions(); ignoreLocalText = XMP_OptionIsSet ( options, kXMPFiles_IgnoreLocalText ); #if XMP_UNIXBuild if ( ! ignoreLocalText ) XMP_Throw ( "Generic UNIX clients must pass kXMPFiles_IgnoreLocalText", kXMPErr_EnforceFailure ); #endif #if EnablePluginManager if ( pluginFolder != 0 ) { std::string pluginList; if ( plugins != 0 ) pluginList.assign ( plugins ); PluginManager::initialize ( pluginFolder, pluginList ); // Load file handler plugins. } #endif // Make sure the embedded info strings are referenced and kept. if ( (kXMPFiles_EmbeddedVersion[0] == 0) || (kXMPFiles_EmbeddedCopyright[0] == 0) ) return false; // Verify critical type sizes. XMP_Assert ( sizeof(XMP_Int8) == 1 ); XMP_Assert ( sizeof(XMP_Int16) == 2 ); XMP_Assert ( sizeof(XMP_Int32) == 4 ); XMP_Assert ( sizeof(XMP_Int64) == 8 ); XMP_Assert ( sizeof(XMP_Uns8) == 1 ); XMP_Assert ( sizeof(XMP_Uns16) == 2 ); XMP_Assert ( sizeof(XMP_Uns32) == 4 ); XMP_Assert ( sizeof(XMP_Uns64) == 8 ); XMP_Assert ( sizeof(XMP_Bool) == 1 ); XMP_FILES_STATIC_END1 ( kXMPErrSev_ProcessFatal ) return true; } // XMPFiles::Initialize // ================================================================================================= #if GatherPerformanceData #if XMP_WinBuild #pragma warning ( disable : 4996 ) // '...' was declared deprecated #endif #include "PerfUtils.cpp" static void ReportPerformanceData() { struct SummaryInfo { size_t callCount; double totalTime; SummaryInfo() : callCount(0), totalTime(0.0) {}; }; SummaryInfo perfSummary [kAPIPerfProcCount]; XMP_DateTime now; SXMPUtils::CurrentDateTime ( &now ); std::string nowStr; SXMPUtils::ConvertFromDate ( now, &nowStr ); #if XMP_WinBuild #define kPerfLogPath "C:\\XMPFilesPerformanceLog.txt" #else #define kPerfLogPath "/XMPFilesPerformanceLog.txt" #endif FILE * perfLog = fopen ( kPerfLogPath, "ab" ); if ( perfLog == 0 ) return; fprintf ( perfLog, "\n\n// =================================================================================================\n\n" ); fprintf ( perfLog, "XMPFiles performance data\n" ); fprintf ( perfLog, " %s\n", kXMPFiles_VersionMessage ); fprintf ( perfLog, " Reported at %s\n", nowStr.c_str() ); fprintf ( perfLog, " %s\n", PerfUtils::GetTimerInfo() ); // Gather and report the summary info. for ( size_t i = 0; i < sAPIPerf->size(); ++i ) { SummaryInfo& summaryItem = perfSummary [(*sAPIPerf)[i].whichProc]; ++summaryItem.callCount; summaryItem.totalTime += (*sAPIPerf)[i].elapsedTime; } fprintf ( perfLog, "\nSummary data:\n" ); for ( size_t i = 0; i < kAPIPerfProcCount; ++i ) { long averageTime = 0; if ( perfSummary[i].callCount != 0 ) { averageTime = (long) (((perfSummary[i].totalTime/perfSummary[i].callCount) * 1000.0*1000.0) + 0.5); } fprintf ( perfLog, " %s, %d total calls, %d average microseconds per call\n", kAPIPerfNames[i], perfSummary[i].callCount, averageTime ); } fprintf ( perfLog, "\nPer-call data:\n" ); // Report the info for each call. for ( size_t i = 0; i < sAPIPerf->size(); ++i ) { long time = (long) (((*sAPIPerf)[i].elapsedTime * 1000.0*1000.0) + 0.5); fprintf ( perfLog, " %s, %d microSec, ref %.8X, \"%s\"\n", kAPIPerfNames[(*sAPIPerf)[i].whichProc], time, (*sAPIPerf)[i].xmpFilesRef, (*sAPIPerf)[i].extraInfo.c_str() ); } fclose ( perfLog ); } // ReportAReportPerformanceDataPIPerformance #endif // ================================================================================================= /* class static */ void XMPFiles::Terminate() { XMP_FILES_STATIC_START --sXMPFilesInitCount; if ( sXMPFilesInitCount != 0 ) return; // Not ready to terminate, or already terminated. #if GatherPerformanceData ReportPerformanceData(); EliminateGlobal ( sAPIPerf ); #endif #if EnablePluginManager PluginManager::terminate(); #endif HandlerRegistry::terminate(); SXMPMeta::Terminate(); // Just in case the client does not. ID3_Support::TerminateGlobals(); ISOMedia::TerminateGlobals(); Terminate_LibUtils(); #if UseGlobalLibraryLock & (! XMP_StaticBuild ) TerminateBasicMutex ( sLibraryLock ); // ! Handled in XMPMeta for static builds. #endif #if XMP_TraceFilesCallsToFile if ( xmpFilesLog != stderr ) fclose ( xmpFilesLog ); xmpFilesLog = stderr; #endif // reset static variables sDefaultErrorCallback.Clear(); sProgressDefault.Clear(); XMP_FILES_STATIC_END1 ( kXMPErrSev_ProcessFatal ) } // XMPFiles::Terminate // ================================================================================================= XMPFiles::XMPFiles() : clientRefs(0) , format(kXMP_UnknownFile) , ioRef(0) , openFlags(0) , handler(0) , tempPtr(0) , tempUI32(0) , abortProc(0) , abortArg(0) , progressTracker(0) { XMP_FILES_START if ( sProgressDefault.clientProc != 0 ) { this->progressTracker = new XMP_ProgressTracker ( sProgressDefault ); if (this->progressTracker == 0) XMP_Throw ( "XMPFiles: Unable to allocate memory for Progress Tracker", kXMPErr_NoMemory ); } if ( sDefaultErrorCallback.clientProc != 0 ) { this->errorCallback.wrapperProc = sDefaultErrorCallback.wrapperProc; this->errorCallback.clientProc = sDefaultErrorCallback.clientProc; this->errorCallback.context = sDefaultErrorCallback.context; this->errorCallback.limit = sDefaultErrorCallback.limit; } XMP_FILES_END1 ( kXMPErrSev_OperationFatal ); } // XMPFiles::XMPFiles // ================================================================================================= static inline void CloseLocalFile ( XMPFiles* thiz ) { if ( thiz->UsesLocalIO() ) { XMPFiles_IO* localFile = (XMPFiles_IO*)thiz->ioRef; if ( localFile != 0 ) { localFile->Close(); delete localFile; thiz->ioRef = 0; } } } // CloseLocalFile // ================================================================================================= XMPFiles::~XMPFiles() { XMP_FILES_START XMP_Assert ( this->clientRefs <= 0 ); if ( this->handler != 0 ) { delete this->handler; this->handler = 0; } CloseLocalFile ( this ); if ( this->progressTracker != 0 ) delete this->progressTracker; if ( this->tempPtr != 0 ) free ( this->tempPtr ); // ! Must have been malloc-ed! XMP_FILES_END1 ( kXMPErrSev_OperationFatal ) } // XMPFiles::~XMPFiles // ================================================================================================= /* class static */ bool XMPFiles::GetFormatInfo ( XMP_FileFormat format, XMP_OptionBits * flags /* = 0 */ ) { XMP_FILES_STATIC_START return HandlerRegistry::getInstance().getFormatInfo ( format, flags ); XMP_FILES_STATIC_END1 ( kXMPErrSev_OperationFatal ) return false; } // XMPFiles::GetFormatInfo // ================================================================================================= /* class static */ XMP_FileFormat XMPFiles::CheckFileFormat ( XMP_StringPtr clientPath ) { XMP_FILES_STATIC_START if ( (clientPath == 0) || (*clientPath == 0) ) return kXMP_UnknownFile; XMPFiles bogus; // Needed to provide context to SelectSmartHandler. bogus.SetFilePath ( clientPath ); // So that XMPFiles destructor cleans up the XMPFiles_IO object. XMPFileHandlerInfo * handlerInfo = HandlerRegistry::getInstance().selectSmartHandler(&bogus, clientPath, kXMP_UnknownFile, kXMPFiles_OpenForRead); if ( handlerInfo == 0 ) { if ( !Host_IO::Exists ( clientPath ) ) { XMP_Error error ( kXMPErr_NoFile, "XMPFiles: file does not exist" ); XMP_FILES_STATIC_NOTIFY_ERROR ( &sDefaultErrorCallback, clientPath, kXMPErrSev_Recoverable, error ); } return kXMP_UnknownFile; } return handlerInfo->format; XMP_FILES_STATIC_END2 ( clientPath, kXMPErrSev_OperationFatal ) return kXMP_UnknownFile; } // XMPFiles::CheckFileFormat // ================================================================================================= /* class static */ XMP_FileFormat XMPFiles::CheckPackageFormat ( XMP_StringPtr folderPath ) { XMP_FILES_STATIC_START // This is called with a path to a folder, and checks to see if that folder is the top level of // a "package" that should be recognized by one of the folder-oriented handlers. The checks here // are not overly extensive, but hopefully enough to weed out false positives. // // Since we don't have many folder handlers, this is simple hardwired code. #if ! EnableDynamicMediaHandlers return kXMP_UnknownFile; #else Host_IO::FileMode folderMode = Host_IO::GetFileMode ( folderPath ); if ( folderMode != Host_IO::kFMode_IsFolder ) return kXMP_UnknownFile; return HandlerRegistry::checkTopFolderName ( std::string ( folderPath ) ); #endif XMP_FILES_STATIC_END2 ( folderPath, kXMPErrSev_OperationFatal ) return kXMP_UnknownFile; } // XMPFiles::CheckPackageFormat // ================================================================================================= static bool FileIsExcluded ( XMP_StringPtr clientPath, std::string * fileExt, Host_IO::FileMode * clientMode, const XMPFiles::ErrorCallbackInfo * _errorCallbackInfoPtr = NULL ) { // ! Return true for excluded files, false for OK files. *clientMode = Host_IO::GetFileMode ( clientPath ); if ( (*clientMode == Host_IO::kFMode_IsFolder) || (*clientMode == Host_IO::kFMode_IsOther) ) { XMP_Error error ( kXMPErr_FilePathNotAFile, "XMPFiles: path specified is not a file" ); XMP_FILES_STATIC_NOTIFY_ERROR ( _errorCallbackInfoPtr, clientPath, kXMPErrSev_Recoverable, error ); return true; } XMP_Assert ( (*clientMode == Host_IO::kFMode_IsFile) || (*clientMode == Host_IO::kFMode_DoesNotExist) ); if ( *clientMode == Host_IO::kFMode_IsFile ) { // Find the file extension. OK to be "wrong" for something like "C:\My.dir\file". Any // filtering looks for matches with real extensions, "dir\file" won't match any of these. XMP_StringPtr extPos = clientPath + strlen ( clientPath ); for ( ; (extPos != clientPath) && (*extPos != '.'); --extPos ) {} if ( *extPos == '.' ) { fileExt->assign ( extPos+1 ); MakeLowerCase ( fileExt ); } // See if this file is one that XMPFiles should never process. for ( size_t i = 0; kKnownRejectedFiles[i] != 0; ++i ) { if ( *fileExt == kKnownRejectedFiles[i] ) { XMP_Error error ( kXMPErr_RejectedFileExtension, "XMPFiles: rejected file extension specified" ); XMP_FILES_STATIC_NOTIFY_ERROR ( _errorCallbackInfoPtr, clientPath, kXMPErrSev_Recoverable, error ); return true; } } } return false; } // FileIsExcluded static XMPFileHandlerInfo* CreateFileHandlerInfo ( XMPFiles* dummyParent, XMP_FileFormat * format, XMP_OptionBits options, XMP_Bool& excluded, const XMPFiles::ErrorCallbackInfo * _errorCallbackInfoPtr = NULL ) { Host_IO::FileMode clientMode; std::string fileExt; // Used to check for excluded files. excluded = FileIsExcluded ( dummyParent->GetFilePath().c_str(), &fileExt, &clientMode, &sDefaultErrorCallback ); // ! Fills in fileExt and clientMode. if ( excluded ) return 0; XMPFileHandlerInfo * handlerInfo = 0; XMP_FileFormat dummyFormat = kXMP_UnknownFile; if ( format == 0 ) format = &dummyFormat; options |= kXMPFiles_OpenForRead; handlerInfo = HandlerRegistry::getInstance().selectSmartHandler ( dummyParent, dummyParent->GetFilePath().c_str(), *format, options ); if ( handlerInfo == 0 ) { if ( clientMode == Host_IO::kFMode_DoesNotExist ) { XMP_Error error ( kXMPErr_NoFile, "XMPFiles: file does not exist" ); XMP_FILES_STATIC_NOTIFY_ERROR ( _errorCallbackInfoPtr, dummyParent->GetFilePath().c_str(), kXMPErrSev_Recoverable, error ); }else{ XMP_Error error ( kXMPErr_NoFileHandler, "XMPFiles: No smart file handler available to handle file" ); XMP_FILES_STATIC_NOTIFY_ERROR ( _errorCallbackInfoPtr, dummyParent->GetFilePath().c_str(), kXMPErrSev_Recoverable, error ); } return 0; } return handlerInfo; } // ================================================================================================= /* class static */ bool XMPFiles::GetFileModDate ( XMP_StringPtr clientPath, XMP_DateTime * modDate, XMP_FileFormat * format, /* = 0 */ XMP_OptionBits options /* = 0 */ ) { XMP_FILES_STATIC_START // --------------------------------------------------------------- // First try to select a smart handler. Return false if not found. XMPFiles dummyParent; // GetFileModDate is static, but the handler needs a parent. dummyParent.SetFilePath ( clientPath ); XMPFileHandlerInfo * handlerInfo = 0; XMP_Bool excluded=false; handlerInfo = CreateFileHandlerInfo ( &dummyParent, format, options, excluded, &sDefaultErrorCallback ); #if EnableGenericHandling #if GenericHandlingAlwaysOn XMP_OptionBits oldOptions = options; options |= kXMPFiles_OpenUseGenericHandler; #endif if (handlerInfo == 0 && !excluded && (options & kXMPFiles_OpenUseGenericHandler) ) { Host_IO::FileMode fileMode = Host_IO::GetFileMode( clientPath ); if ( fileMode == Host_IO::kFMode_DoesNotExist ) return false; handlerInfo = &kGenericHandlerInfo; } #if GenericHandlingAlwaysOn options = oldOptions; #endif #endif if ( handlerInfo == 0 ) return false; // ------------------------------------------------------------------------- // Fill in the format output. Call the handler to get the modification date. dummyParent.format = handlerInfo->format; if ( format ) *format = handlerInfo->format; dummyParent.openFlags = handlerInfo->flags; dummyParent.handler = handlerInfo->handlerCTor ( &dummyParent ); bool ok = false; std::vector <std::string> resourceList; try{ XMP_DateTime lastModDate; XMP_DateTime junkDate; if ( modDate == 0 ) modDate = &junkDate; dummyParent.handler->FillAssociatedResources ( &resourceList ); size_t countRes = resourceList.size(); for ( size_t index = 0; index < countRes ; ++index ){ XMP_StringPtr curFilePath = resourceList[index].c_str(); if( Host_IO::GetFileMode ( curFilePath ) != Host_IO::kFMode_IsFile ) continue;// only interested in files if (!Host_IO::GetModifyDate ( curFilePath, &lastModDate ) ) continue; if ( ! ok || ( SXMPUtils::CompareDateTime ( *modDate , lastModDate ) < 0 ) ) { *modDate = lastModDate; ok = true; } } } catch(...){ // Fallback to the old way // eventually this method would go away as // soon as the implementation for // GetAssociatedResources is added to all // the file/Plugin Handlers ok = dummyParent.handler->GetFileModDate ( modDate ); } delete dummyParent.handler; dummyParent.handler = 0; return ok; XMP_FILES_STATIC_END2 ( clientPath, kXMPErrSev_OperationFatal ) return false; } // XMPFiles::GetFileModDate // ================================================================================================= /* class static */ bool XMPFiles::GetFileModDate ( const Common::XMPFileHandlerInfo& hdlInfo, XMP_StringPtr clientPath, XMP_DateTime * modDate, XMP_OptionBits /* options = 0 */ ) { XMP_FILES_STATIC_START Host_IO::FileMode clientMode; std::string fileExt; // Used to check for excluded files. bool excluded = FileIsExcluded ( clientPath, &fileExt, &clientMode, &sDefaultErrorCallback ); // ! Fills in fileExt and clientMode. if ( excluded ) return false; XMPFiles dummyParent; // GetFileModDate is static, but the handler needs a parent. dummyParent.SetFilePath ( clientPath ); dummyParent.format = hdlInfo.format; dummyParent.openFlags = hdlInfo.flags; dummyParent.handler = hdlInfo.handlerCTor ( &dummyParent ); bool ok = false; std::vector <std::string> resourceList; try{ XMP_DateTime lastModDate; XMP_DateTime junkDate; if ( modDate == 0 ) modDate = &junkDate; dummyParent.handler->FillAssociatedResources ( &resourceList ); size_t countRes = resourceList.size(); for ( size_t index = 0; index < countRes ; ++index ){ XMP_StringPtr curFilePath = resourceList[index].c_str(); if( Host_IO::GetFileMode ( curFilePath ) != Host_IO::kFMode_IsFile ) continue;// only interested in files if (!Host_IO::GetModifyDate ( curFilePath, &lastModDate ) ) continue; if ( ! ok || ( SXMPUtils::CompareDateTime ( *modDate , lastModDate ) < 0 ) ) { *modDate = lastModDate; ok = true; } } } catch(...){ // Fallback to the old way // eventually this method would go away as // soon as the implementation for // GetAssociatedResources is added to all // the file/Plugin Handlers ok = dummyParent.handler->GetFileModDate ( modDate ); } delete dummyParent.handler; dummyParent.handler = 0; return ok; XMP_FILES_STATIC_END2 ( clientPath, kXMPErrSev_OperationFatal ) return false; } // XMPFiles::GetFileModDate // ================================================================================================= /* class static */ bool XMPFiles::GetAssociatedResources ( XMP_StringPtr filePath, std::vector<std::string> * resourceList, XMP_FileFormat format /* = kXMP_UnknownFile */, XMP_OptionBits options /* = 0 */ ) { XMP_FILES_STATIC_START XMP_Assert ( (resourceList != 0) && resourceList->empty() ); // Ensure that the glue passes in an empty local. // Try to select a handler. if ( (filePath == 0) || (*filePath == 0) ) return false; XMPFiles dummyParent; // GetAssociatedResources is static, but the handler needs a parent. dummyParent.SetFilePath ( filePath ); XMPFileHandlerInfo * handlerInfo = 0; XMP_Bool excluded=false; handlerInfo = CreateFileHandlerInfo ( &dummyParent, &format, options, excluded, &sDefaultErrorCallback ); #if EnableGenericHandling #if GenericHandlingAlwaysOn XMP_OptionBits oldOptions = options; options |= kXMPFiles_OpenUseGenericHandler; #endif if (handlerInfo == 0 && !excluded && (options & kXMPFiles_OpenUseGenericHandler) ) { Host_IO::FileMode fileMode = Host_IO::GetFileMode( filePath ); if ( fileMode == Host_IO::kFMode_DoesNotExist ) return false; handlerInfo = &kGenericHandlerInfo; } #if GenericHandlingAlwaysOn options = oldOptions; #endif #endif if ( handlerInfo == 0 ) return false; // ------------------------------------------------------------------------- // Fill in the format output. Call the handler to get the Associated Resources. dummyParent.format = handlerInfo->format; dummyParent.openFlags = handlerInfo->flags; dummyParent.handler = handlerInfo->handlerCTor ( &dummyParent ); try { dummyParent.handler->FillAssociatedResources ( resourceList ); } catch ( XMP_Error& error ) { if ( error.GetID() == kXMPErr_Unimplemented ) { XMP_FILES_STATIC_NOTIFY_ERROR ( &sDefaultErrorCallback, filePath, kXMPErrSev_Recoverable, error ); return false; } else { throw; } } XMP_Assert ( ! resourceList->empty() ); delete dummyParent.handler; dummyParent.handler = 0; return true; XMP_FILES_STATIC_END2 ( filePath, kXMPErrSev_OperationFatal ) return false; } // XMPFiles::GetAssociatedResources // ================================================================================================= /* class static */ bool XMPFiles::GetAssociatedResources ( const Common::XMPFileHandlerInfo& hdlInfo, XMP_StringPtr filePath, std::vector<std::string> * resourceList, XMP_OptionBits /* options = 0 */ ) { XMP_FILES_STATIC_START Host_IO::FileMode clientMode; std::string fileExt; // Used to check for excluded files. bool excluded = FileIsExcluded ( filePath, &fileExt, &clientMode, &sDefaultErrorCallback ); // ! Fills in fileExt and clientMode. if ( excluded ) return false; XMPFiles dummyParent; // GetFileModDate is static, but the handler needs a parent. dummyParent.SetFilePath ( filePath ); dummyParent.format = hdlInfo.format; dummyParent.openFlags = hdlInfo.flags; dummyParent.handler = hdlInfo.handlerCTor ( &dummyParent ); try { dummyParent.handler->FillAssociatedResources ( resourceList ); } catch ( XMP_Error& error ) { if ( error.GetID() == kXMPErr_Unimplemented ) { XMP_FILES_STATIC_NOTIFY_ERROR ( &sDefaultErrorCallback, filePath, kXMPErrSev_Recoverable, error ); return false; } else { throw; } } XMP_Assert ( ! resourceList->empty() ); delete dummyParent.handler; dummyParent.handler = 0; return true; XMP_FILES_STATIC_END2 ( filePath, kXMPErrSev_OperationFatal ) return false; } // XMPFiles::GetAssociatedResources // ================================================================================================= /* class static */ bool XMPFiles::IsMetadataWritable ( XMP_StringPtr filePath, XMP_Bool * writable, XMP_FileFormat format /* = kXMP_UnknownFile */, XMP_OptionBits options /* = 0 */ ) { XMP_FILES_STATIC_START // Try to select a handler. if ( (filePath == 0) || (*filePath == 0) ) return false; XMPFiles dummyParent; // IsMetadataWritable is static, but the handler needs a parent. dummyParent.SetFilePath ( filePath ); XMPFileHandlerInfo * handlerInfo = 0; XMP_Bool excluded=false; handlerInfo = CreateFileHandlerInfo ( &dummyParent, &format, options, excluded, &sDefaultErrorCallback ); #if EnableGenericHandling #if GenericHandlingAlwaysOn XMP_OptionBits oldOptions = options; options |= kXMPFiles_OpenUseGenericHandler; #endif if (handlerInfo == 0 && !excluded && (options & kXMPFiles_OpenUseGenericHandler)) { Host_IO::FileMode fileMode = Host_IO::GetFileMode( filePath ); if ( fileMode == Host_IO::kFMode_DoesNotExist ) return false; handlerInfo = &kGenericHandlerInfo; } #if GenericHandlingAlwaysOn options = oldOptions; #endif #endif if ( handlerInfo == 0 ) return false; if ( writable == 0 ) { XMP_Throw("Boolean parameter is required for IsMetadataWritable() API.", kXMPErr_BadParam); } else { *writable = kXMP_Bool_False; } dummyParent.format = handlerInfo->format; dummyParent.openFlags = handlerInfo->flags; dummyParent.handler = handlerInfo->handlerCTor ( &dummyParent ); // We don't require any of the files to be opened at this point. // Also, if We don't close them then this will be a problem for embedded handlers because we will be checking // write permission on the same file which could be open (in some mode) already. CloseLocalFile(&dummyParent); try { *writable = ConvertBoolToXMP_Bool( dummyParent.handler->IsMetadataWritable() ); } catch ( XMP_Error& error ) { delete dummyParent.handler; dummyParent.handler = 0; if ( error.GetID() == kXMPErr_Unimplemented ) { XMP_FILES_STATIC_NOTIFY_ERROR ( &sDefaultErrorCallback, filePath, kXMPErrSev_Recoverable, error ); return false; } else { throw; } } if ( dummyParent.handler ) { delete dummyParent.handler; dummyParent.handler = 0; } XMP_FILES_STATIC_END2 ( filePath, kXMPErrSev_OperationFatal ) return true; } // XMPFiles::IsMetadataWritable // ================================================================================================= /* class static */ bool XMPFiles::IsMetadataWritable ( const Common::XMPFileHandlerInfo& hdlInfo, XMP_StringPtr filePath, XMP_Bool * writable, XMP_OptionBits /* options = 0 */ ) { XMP_FILES_STATIC_START Host_IO::FileMode clientMode; std::string fileExt; // Used to check for excluded files. bool excluded = FileIsExcluded ( filePath, &fileExt, &clientMode, &sDefaultErrorCallback ); // ! Fills in fileExt and clientMode. if ( excluded ) return false; if ( writable == 0 ) { XMP_Throw("Boolean parameter is required for IsMetadataWritable() API.", kXMPErr_BadParam); } else { *writable = kXMP_Bool_False; } XMPFiles dummyParent; // GetFileModDate is static, but the handler needs a parent. dummyParent.SetFilePath ( filePath ); dummyParent.format = hdlInfo.format; dummyParent.openFlags = hdlInfo.flags; dummyParent.handler = hdlInfo.handlerCTor ( &dummyParent ); // We don't require any of the files to be opened at this point. // Also, if We don't close them then this will be a problem for embedded handlers because we will be checking // write permission on the same file which could be open (in some mode) already. CloseLocalFile(&dummyParent); try { *writable = ConvertBoolToXMP_Bool( dummyParent.handler->IsMetadataWritable() ); } catch ( XMP_Error& error ) { delete dummyParent.handler; dummyParent.handler = 0; if ( error.GetID() == kXMPErr_Unimplemented ) { XMP_FILES_STATIC_NOTIFY_ERROR ( &sDefaultErrorCallback, filePath, kXMPErrSev_Recoverable, error ); return false; } else { throw; } } if ( dummyParent.handler ) { delete dummyParent.handler; dummyParent.handler = 0; } XMP_FILES_STATIC_END2 ( filePath, kXMPErrSev_OperationFatal ) return true; } // XMPFiles::IsMetadataWritable // ================================================================================================= static bool DoOpenFile ( XMPFiles * thiz, XMP_IO * clientIO, XMP_StringPtr clientPath, XMP_FileFormat format /* = kXMP_UnknownFile */, XMP_OptionBits openFlags /* = 0 */ ) { XMP_Assert ( (clientIO == 0) ? (clientPath[0] != 0) : (clientPath[0] == 0) ); openFlags &= ~kXMPFiles_ForceGivenHandler; // Don't allow this flag for OpenFile. if ( (openFlags & kXMPFiles_OptimizeFileLayout) && (! (openFlags & kXMPFiles_OpenForUpdate)) ) { XMP_Throw ( "OptimizeFileLayout requires OpenForUpdate", kXMPErr_BadParam ); } if ( thiz->handler != 0 ) XMP_Throw ( "File already open", kXMPErr_BadParam ); CloseLocalFile ( thiz ); // Sanity checks if prior call failed. thiz->ioRef = clientIO; thiz->SetFilePath ( clientPath ); thiz->format = kXMP_UnknownFile; // Make sure it is preset for later check. thiz->openFlags = openFlags; bool readOnly = XMP_OptionIsClear ( openFlags, kXMPFiles_OpenForUpdate ); Host_IO::FileMode clientMode; std::string fileExt; // Used to check for camera raw files and OK to scan files. if ( thiz->UsesClientIO() ) { clientMode = Host_IO::kFMode_IsFile; } else { bool excluded = FileIsExcluded ( clientPath, &fileExt, &clientMode, &thiz->errorCallback ); // ! Fills in fileExt and clientMode. if ( excluded ) return false; } // Find the handler, fill in the XMPFiles member variables, cache the desired file data. XMPFileHandlerInfo * handlerInfo = 0; XMPFileHandlerCTor handlerCTor = 0; XMP_OptionBits handlerFlags = 0; if ( ! (openFlags & kXMPFiles_OpenUsePacketScanning) ) { handlerInfo = HandlerRegistry::getInstance().selectSmartHandler( thiz, clientPath, format, openFlags ); #if EnableGenericHandling #if GenericHandlingAlwaysOn XMP_OptionBits oldOpenFlags = openFlags; openFlags |= kXMPFiles_OpenUseGenericHandler; #endif if (handlerInfo==0 && !(openFlags & kXMPFiles_OpenStrictly) && (openFlags & kXMPFiles_OpenUseGenericHandler)) { if ( clientMode == Host_IO::kFMode_DoesNotExist ) return false; handlerInfo = &kGenericHandlerInfo; } #if GenericHandlingAlwaysOn openFlags = oldOpenFlags; #endif #endif } #if ! EnablePacketScanning if ( handlerInfo == 0 ) { if ( clientMode == Host_IO::kFMode_DoesNotExist ) { XMP_Error error ( kXMPErr_NoFile, "XMPFiles: file does not exist" ); XMP_FILES_STATIC_NOTIFY_ERROR ( &thiz->errorCallback, clientPath, kXMPErrSev_Recoverable, error ); } return false; } #else if ( handlerInfo == 0 ) { // No smart handler, packet scan if appropriate. if ( clientMode == Host_IO::kFMode_DoesNotExist ) { XMP_Error error ( kXMPErr_NoFile, "XMPFiles: file does not exist" ); XMP_FILES_STATIC_NOTIFY_ERROR ( &thiz->errorCallback, clientPath, kXMPErrSev_Recoverable, error ); return false; } else if ( clientMode != Host_IO::kFMode_IsFile ) { return false; } if ( openFlags & kXMPFiles_OpenUseSmartHandler ) { CloseLocalFile ( thiz ); XMP_Error error ( kXMPErr_NoFileHandler, "XMPFiles: No smart file handler available to handle file" ); XMP_FILES_STATIC_NOTIFY_ERROR ( &thiz->errorCallback, clientPath, kXMPErrSev_Recoverable, error ); return false; } #if EnableGenericHandling if ( openFlags & kXMPFiles_OpenUseGenericHandler ) { CloseLocalFile ( thiz ); XMP_Error error ( kXMPErr_NoFileHandler, "XMPFiles: Generic handler not available to handle file" ); XMP_FILES_STATIC_NOTIFY_ERROR ( &thiz->errorCallback, clientPath, kXMPErrSev_Recoverable, error ); return false; } #endif if ( openFlags & kXMPFiles_OpenLimitedScanning ) { bool scanningOK = false; for ( size_t i = 0; kKnownScannedFiles[i] != 0; ++i ) { if ( fileExt == kKnownScannedFiles[i] ) { scanningOK = true; break; } } if ( ! scanningOK ) return false; } handlerInfo = &kScannerHandlerInfo; if ( thiz->ioRef == 0 ) { // Normally opened in SelectSmartHandler, but might not be open yet. thiz->ioRef = XMPFiles_IO::New_XMPFiles_IO ( clientPath, readOnly ); if ( thiz->ioRef == 0 ) return false; } } #endif XMP_Assert ( handlerInfo != 0 ); handlerCTor = handlerInfo->handlerCTor; handlerFlags = handlerInfo->flags; XMP_Assert ( (thiz->ioRef != 0) || (handlerFlags & kXMPFiles_UsesSidecarXMP) || (handlerFlags & kXMPFiles_HandlerOwnsFile) || (handlerFlags & kXMPFiles_FolderBasedFormat) ); if ( thiz->format == kXMP_UnknownFile ) thiz->format = handlerInfo->format; // ! The CheckProc might have set it. XMPFileHandler* handler = (*handlerCTor) ( thiz ); XMP_Assert ( handlerFlags == handler->handlerFlags ); thiz->handler = handler; try { if ( !readOnly && handlerFlags & kXMPFiles_FolderBasedFormat ) { bool isMetadataWritable = handler->IsMetadataWritable(); if ( !isMetadataWritable ) { XMP_Throw ( "Open, file permission error", kXMPErr_FilePermission ); } } handler->CacheFileData(); } catch ( ... ) { delete thiz->handler; thiz->handler = 0; if ( ! (handlerFlags & kXMPFiles_HandlerOwnsFile) ) CloseLocalFile ( thiz ); throw; } if ( handler->containsXMP ) FillPacketInfo ( handler->xmpPacket, &handler->packetInfo ); if ( (! (openFlags & kXMPFiles_OpenForUpdate)) && (! (handlerFlags & kXMPFiles_HandlerOwnsFile)) ) { // Close the disk file now if opened for read-only access. CloseLocalFile ( thiz ); } return true; } // DoOpenFile // ================================================================================================= static bool DoOpenFile( XMPFiles* thiz, const Common::XMPFileHandlerInfo& hdlInfo, XMP_IO* clientIO, XMP_StringPtr clientPath, XMP_OptionBits openFlags ) { XMP_Assert ( (clientIO == 0) ? (clientPath[0] != 0) : (clientPath[0] == 0) ); openFlags &= ~kXMPFiles_ForceGivenHandler; // Don't allow this flag for OpenFile. if ( (openFlags & kXMPFiles_OptimizeFileLayout) && (! (openFlags & kXMPFiles_OpenForUpdate)) ) { XMP_Throw ( "OptimizeFileLayout requires OpenForUpdate", kXMPErr_BadParam ); } if ( thiz->handler != 0 ) XMP_Throw ( "File already open", kXMPErr_BadParam ); // // setup members // thiz->ioRef = clientIO; thiz->SetFilePath ( clientPath ); thiz->format = hdlInfo.format; thiz->openFlags = openFlags; // // create file handler instance // XMPFileHandlerCTor handlerCTor = hdlInfo.handlerCTor; XMP_OptionBits handlerFlags = hdlInfo.flags; XMPFileHandler* handler = (*handlerCTor) ( thiz ); XMP_Assert ( handlerFlags == handler->handlerFlags ); thiz->handler = handler; bool readOnly = XMP_OptionIsClear ( openFlags, kXMPFiles_OpenForUpdate ); if ( thiz->ioRef == 0 ) { //Need to open the file if not done already thiz->ioRef = XMPFiles_IO::New_XMPFiles_IO ( clientPath, readOnly ); if ( thiz->ioRef == 0 ) return false; } // // try to read metadata // try { handler->CacheFileData(); if( handler->containsXMP ) { FillPacketInfo( handler->xmpPacket, &handler->packetInfo ); } if( (! (openFlags & kXMPFiles_OpenForUpdate)) && (! (handlerFlags & kXMPFiles_HandlerOwnsFile)) ) { // Close the disk file now if opened for read-only access. CloseLocalFile ( thiz ); } } catch( ... ) { delete thiz->handler; thiz->handler = NULL; if( ! (handlerFlags & kXMPFiles_HandlerOwnsFile) ) { CloseLocalFile( thiz ); } throw; } return true; } // ================================================================================================= bool XMPFiles::OpenFile ( XMP_StringPtr clientPath, XMP_FileFormat format1 /* = kXMP_UnknownFile */, XMP_OptionBits openFlags1 /* = 0 */ ) { XMP_FILES_START return DoOpenFile ( this, 0, clientPath, format1, openFlags1 ); XMP_FILES_END2 ( clientPath, kXMPErrSev_FileFatal ) return false; } // ================================================================================================= #if XMP_StaticBuild // ! Client XMP_IO objects can only be used in static builds. bool XMPFiles::OpenFile ( XMP_IO* clientIO, XMP_FileFormat format1 /* = kXMP_UnknownFile */, XMP_OptionBits openFlags1 /* = 0 */ ) { XMP_FILES_START this->progressTracker = 0; // Progress tracking is not supported for client-managed I/O. return DoOpenFile ( this, clientIO, "", format1, openFlags1 ); XMP_FILES_END1 ( kXMPErrSev_FileFatal ) return false; } // XMPFiles::OpenFile bool XMPFiles::OpenFile ( const Common::XMPFileHandlerInfo& hdlInfo, XMP_IO* clientIO, XMP_OptionBits openFlags1 /*= 0*/ ) { XMP_FILES_START this->progressTracker = 0; // Progress tracking is not supported for client-managed I/O. return DoOpenFile ( this, hdlInfo, clientIO, NULL, openFlags1 ); XMP_FILES_END1 ( kXMPErrSev_FileFatal ) return false; } #endif // XMP_StaticBuild // ================================================================================================= bool XMPFiles::OpenFile ( const Common::XMPFileHandlerInfo& hdlInfo, XMP_StringPtr filePath1, XMP_OptionBits openFlags1 /*= 0*/ ) { XMP_FILES_START return DoOpenFile ( this, hdlInfo, NULL, filePath1, openFlags1 ); XMP_FILES_END2 (filePath1, kXMPErrSev_FileFatal ) return false; } // ================================================================================================= void XMPFiles::CloseFile ( XMP_OptionBits closeFlags /* = 0 */ ) { XMP_FILES_START if ( this->handler == 0 ) return; // Return if there is no open file (not an error). bool needsUpdate = this->handler->needsUpdate; bool optimizeFileLayout = XMP_OptionIsSet ( this->openFlags, kXMPFiles_OptimizeFileLayout ); XMP_OptionBits handlerFlags = this->handler->handlerFlags; // Decide if we're doing a safe update. If so, make sure the handler supports it. All handlers // that don't own the file tolerate safe update using common code below. bool doSafeUpdate = XMP_OptionIsSet ( closeFlags, kXMPFiles_UpdateSafely ); #if GatherPerformanceData if ( doSafeUpdate ) sAPIPerf->back().extraInfo += ", safe update"; // Client wants safe update. #endif if ( ! (this->openFlags & kXMPFiles_OpenForUpdate) ) doSafeUpdate = false; if ( ! needsUpdate ) doSafeUpdate = false; bool safeUpdateOK = ( (handlerFlags & kXMPFiles_AllowsSafeUpdate) || (! (handlerFlags & kXMPFiles_HandlerOwnsFile)) ); if ( doSafeUpdate && (! safeUpdateOK) ) { XMP_Throw ( "XMPFiles::CloseFile - Safe update not supported", kXMPErr_Unavailable ); } if ( (this->progressTracker != 0) && this->UsesLocalIO() && this->ioRef != NULL ) { XMPFiles_IO * localFile = (XMPFiles_IO*)this->ioRef; localFile->SetProgressTracker ( this->progressTracker ); } // Try really hard to make sure the file is closed and the handler is deleted. try { if ( (! doSafeUpdate) || (handlerFlags & kXMPFiles_HandlerOwnsFile) ) { // ! Includes no update case. // Close the file without doing common crash-safe writing. The handler might do it. needsUpdate |= optimizeFileLayout; if ( needsUpdate ) { #if GatherPerformanceData sAPIPerf->back().extraInfo += ", direct update"; #endif this->handler->UpdateFile ( doSafeUpdate ); } delete this->handler; this->handler = 0; CloseLocalFile ( this ); } else { // Update the file in a crash-safe manner using common control of a temp file. XMP_IO* tempFileRef = this->ioRef->DeriveTemp(); if ( tempFileRef == 0 ) XMP_Throw ( "XMPFiles::CloseFile, cannot create temp", kXMPErr_InternalFailure ); if ( handlerFlags & kXMPFiles_CanRewrite ) { // The handler can rewrite an entire file based on the original. #if GatherPerformanceData sAPIPerf->back().extraInfo += ", file rewrite"; #endif this->handler->WriteTempFile ( tempFileRef ); } else { // The handler can only update an existing file. Copy to the temp then update. #if GatherPerformanceData sAPIPerf->back().extraInfo += ", copy update"; #endif XMP_IO* origFileRef = this->ioRef; origFileRef->Rewind(); if ( this->progressTracker != 0 && (this->handler->handlerFlags & kXMPFiles_CanNotifyProgress) ) progressTracker->BeginWork ( (float) origFileRef->Length() ); XIO::Copy ( origFileRef, tempFileRef, origFileRef->Length(), abortProc, abortArg ); try { this->ioRef = tempFileRef; this->handler->UpdateFile ( false ); // We're doing the safe update, not the handler. this->ioRef = origFileRef; } catch ( ... ) { this->ioRef->DeleteTemp(); this->ioRef = origFileRef; throw; } if ( progressTracker != 0 && (this->handler->handlerFlags & kXMPFiles_CanNotifyProgress)) progressTracker->WorkComplete(); } this->ioRef->AbsorbTemp(); CloseLocalFile ( this ); delete this->handler; this->handler = 0; } } catch ( ... ) { // *** Don't delete the temp or copy files, not sure which is best. try { if ( this->handler != 0 ) { delete this->handler; this->handler = 0; } } catch ( ... ) { /* Do nothing, throw the outer exception later. */ } if ( this->ioRef ) this->ioRef->DeleteTemp(); CloseLocalFile ( this ); this->ClearFilePath(); this->handler = 0; this->format = kXMP_UnknownFile; this->ioRef = 0; this->openFlags = 0; if ( this->tempPtr != 0 ) free ( this->tempPtr ); // ! Must have been malloc-ed! this->tempPtr = 0; this->tempUI32 = 0; throw; } // Clear the XMPFiles member variables. CloseLocalFile ( this ); this->ClearFilePath(); this->handler = 0; this->format = kXMP_UnknownFile; this->ioRef = 0; this->openFlags = 0; if ( this->tempPtr != 0 ) free ( this->tempPtr ); // ! Must have been malloc-ed! this->tempPtr = 0; this->tempUI32 = 0; XMP_FILES_END1 ( kXMPErrSev_FileFatal ) } // XMPFiles::CloseFile // ================================================================================================= bool XMPFiles::GetFileInfo ( XMP_StringPtr * filePath1 /* = 0 */, XMP_StringLen * pathLen /* = 0 */, XMP_OptionBits * openFlags1 /* = 0 */, XMP_FileFormat * format1 /* = 0 */, XMP_OptionBits * handlerFlags /* = 0 */ ) const { XMP_FILES_START if ( this->handler == 0 ) return false; /*XMPFileHandler * handler = this->handler;*/ if ( filePath1 == 0 ) filePath1 = &voidStringPtr; if ( pathLen == 0 ) pathLen = &voidStringLen; if ( openFlags1 == 0 ) openFlags1 = &voidOptionBits; if ( format1 == 0 ) format1 = &voidFileFormat; if ( handlerFlags == 0 ) handlerFlags = &voidOptionBits; *filePath1 = this->filePath.c_str(); *pathLen = (XMP_StringLen) this->filePath.size(); *openFlags1 = this->openFlags; *format1 = this->format; *handlerFlags = this->handler->handlerFlags; XMP_FILES_END1 ( kXMPErrSev_FileFatal ) return true; } // XMPFiles::GetFileInfo // ================================================================================================= void XMPFiles::SetAbortProc ( XMP_AbortProc abortProc1, void * abortArg1 ) { XMP_FILES_START this->abortProc = abortProc1; this->abortArg = abortArg1; XMP_Assert ( (abortProc1 != (XMP_AbortProc)0) || (abortArg1 != (void*)(unsigned long long)0xDEADBEEFULL) ); // Hack to test the assert callback. XMP_FILES_END1 ( kXMPErrSev_OperationFatal ) } // XMPFiles::SetAbortProc // ================================================================================================= // SetClientPacketInfo // =================== // // Set the packet info returned to the client. This is the internal packet info at first, which // tells what is in the file. But once the file needs update (PutXMP has been called), we return // info about the latest XMP. The internal packet info is left unchanged since it is needed when // the file is updated to locate the old packet in the file. static void SetClientPacketInfo ( XMP_PacketInfo * clientInfo, const XMP_PacketInfo & handlerInfo, const std::string & xmpPacket, bool needsUpdate ) { if ( clientInfo == 0 ) return; if ( ! needsUpdate ) { *clientInfo = handlerInfo; } else { clientInfo->offset = kXMPFiles_UnknownOffset; clientInfo->length = (XMP_Int32) xmpPacket.size(); FillPacketInfo ( xmpPacket, clientInfo ); } } // SetClientPacketInfo // ================================================================================================= bool XMPFiles::GetXMP ( SXMPMeta * xmpObj /* = 0 */, XMP_StringPtr * xmpPacket /* = 0 */, XMP_StringLen * xmpPacketLen /* = 0 */, XMP_PacketInfo * packetInfo /* = 0 */ ) { XMP_FILES_START if ( this->handler == 0 ) XMP_Throw ( "XMPFiles::GetXMP - No open file", kXMPErr_BadObject ); XMP_OptionBits applyTemplateFlags = kXMPTemplate_AddNewProperties | kXMPTemplate_IncludeInternalProperties; if ( ! this->handler->processedXMP ) { try { this->handler->ProcessXMP(); } catch ( ... ) { // Return the outputs then rethrow the exception. if ( xmpObj != 0 ) { // ! Don't use Clone, that replaces the internal ref in the local xmpObj, leaving the client unchanged! xmpObj->Erase(); SXMPUtils::ApplyTemplate(xmpObj, this->handler->xmpObj, applyTemplateFlags); } if ( xmpPacket != 0 ) *xmpPacket = this->handler->xmpPacket.c_str(); if ( xmpPacketLen != 0 ) *xmpPacketLen = (XMP_StringLen) this->handler->xmpPacket.size(); SetClientPacketInfo ( packetInfo, this->handler->packetInfo, this->handler->xmpPacket, this->handler->needsUpdate ); throw; } } if ( ! this->handler->containsXMP ) return false; #if 0 // *** See bug 1131815. A better way might be to pass the ref up from here. if ( xmpObj != 0 ) *xmpObj = this->handler->xmpObj.Clone(); #else if ( xmpObj != 0 ) { xmpObj->Erase(); SXMPUtils::ApplyTemplate(xmpObj, this->handler->xmpObj, applyTemplateFlags); } #endif if ( xmpPacket != 0 ) *xmpPacket = this->handler->xmpPacket.c_str(); if ( xmpPacketLen != 0 ) *xmpPacketLen = (XMP_StringLen) this->handler->xmpPacket.size(); SetClientPacketInfo ( packetInfo, this->handler->packetInfo, this->handler->xmpPacket, this->handler->needsUpdate ); XMP_FILES_END1 ( kXMPErrSev_FileFatal ) return true; } // XMPFiles::GetXMP // ================================================================================================= static bool DoPutXMP ( XMPFiles * thiz, const SXMPMeta & xmpObj, const bool doIt ) { // Check some basic conditions to see if the Put should be attempted. if ( thiz->handler == 0 ) XMP_Throw ( "XMPFiles::PutXMP - No open file", kXMPErr_BadObject ); if ( ! (thiz->openFlags & kXMPFiles_OpenForUpdate) ) { XMP_Throw ( "XMPFiles::PutXMP - Not open for update", kXMPErr_BadObject ); } XMPFileHandler * handler = thiz->handler; XMP_OptionBits handlerFlags = handler->handlerFlags; XMP_PacketInfo & packetInfo = handler->packetInfo; std::string & xmpPacket = handler->xmpPacket; if ( ! handler->processedXMP ) handler->ProcessXMP(); // Might have Open/Put with no GetXMP. size_t oldPacketOffset = (size_t)packetInfo.offset; size_t oldPacketLength = packetInfo.length; if ( oldPacketOffset == (size_t)kXMPFiles_UnknownOffset ) oldPacketOffset = 0; // ! Simplify checks. if ( oldPacketLength == (size_t)kXMPFiles_UnknownLength ) oldPacketLength = 0; bool fileHasPacket = (oldPacketOffset != 0) && (oldPacketLength != 0); if ( ! fileHasPacket ) { if ( ! (handlerFlags & kXMPFiles_CanInjectXMP) ) { XMP_Throw ( "XMPFiles::PutXMP - Can't inject XMP", kXMPErr_Unavailable ); } if ( handler->stdCharForm == kXMP_CharUnknown ) { XMP_Throw ( "XMPFiles::PutXMP - No standard character form", kXMPErr_InternalFailure ); } } // Serialize the XMP and update the handler's info. XMP_Uns8 charForm = handler->stdCharForm; if ( charForm == kXMP_CharUnknown ) charForm = packetInfo.charForm; XMP_OptionBits options = handler->GetSerializeOptions() | XMP_CharToSerializeForm ( charForm ); if ( handlerFlags & kXMPFiles_NeedsReadOnlyPacket ) options |= kXMP_ReadOnlyPacket; if ( fileHasPacket && (thiz->format == kXMP_UnknownFile) && (! packetInfo.writeable) ) options |= kXMP_ReadOnlyPacket; bool preferInPlace = ((handlerFlags & kXMPFiles_PrefersInPlace) != 0); bool tryInPlace = (fileHasPacket & preferInPlace) || (! (handlerFlags & kXMPFiles_CanExpand)); if ( handlerFlags & kXMPFiles_UsesSidecarXMP ) tryInPlace = false; if ( tryInPlace ) { try { xmpObj.SerializeToBuffer ( &xmpPacket, (options | kXMP_ExactPacketLength), (XMP_StringLen) oldPacketLength ); XMP_Assert ( xmpPacket.size() == oldPacketLength ); } catch ( ... ) { if ( preferInPlace ) { tryInPlace = false; // ! Try again, out of place this time. } else { if ( ! doIt ) return false; throw; } } } if ( ! tryInPlace ) { try { xmpObj.SerializeToBuffer ( &xmpPacket, options ); } catch ( ... ) { if ( ! doIt ) return false; throw; } } if ( doIt ) { handler->xmpObj = xmpObj.Clone(); handler->containsXMP = true; handler->processedXMP = true; handler->needsUpdate = true; } return true; } // DoPutXMP // ================================================================================================= void XMPFiles::PutXMP ( const SXMPMeta & xmpObj ) { XMP_FILES_START (void) DoPutXMP ( this, xmpObj, true ); XMP_FILES_END1 ( kXMPErrSev_FileFatal ) } // XMPFiles::PutXMP // ================================================================================================= void XMPFiles::PutXMP ( XMP_StringPtr xmpPacket, XMP_StringLen xmpPacketLen /* = kXMP_UseNullTermination */ ) { XMP_FILES_START SXMPMeta xmpObj; xmpObj.SetErrorCallback ( ErrorCallbackForXMPMeta, &errorCallback ); xmpObj.ParseFromBuffer ( xmpPacket, xmpPacketLen ); this->PutXMP ( xmpObj ); XMP_FILES_END1 ( kXMPErrSev_FileFatal ) } // XMPFiles::PutXMP // ================================================================================================= bool XMPFiles::CanPutXMP ( const SXMPMeta & xmpObj ) { XMP_FILES_START if ( this->handler == 0 ) XMP_Throw ( "XMPFiles::CanPutXMP - No open file", kXMPErr_BadObject ); if ( ! (this->openFlags & kXMPFiles_OpenForUpdate) ) return false; if ( this->handler->handlerFlags & kXMPFiles_CanInjectXMP ) return true; if ( ! this->handler->containsXMP ) return false; if ( this->handler->handlerFlags & kXMPFiles_CanExpand ) return true; return DoPutXMP ( this, xmpObj, false ); XMP_FILES_END1 ( kXMPErrSev_FileFatal ) return false; } // XMPFiles::CanPutXMP // ================================================================================================= bool XMPFiles::CanPutXMP ( XMP_StringPtr xmpPacket, XMP_StringLen xmpPacketLen /* = kXMP_UseNullTermination */ ) { XMP_FILES_START SXMPMeta xmpObj; xmpObj.SetErrorCallback ( ErrorCallbackForXMPMeta, &errorCallback ); xmpObj.ParseFromBuffer ( xmpPacket, xmpPacketLen ); return this->CanPutXMP ( xmpObj ); XMP_FILES_END1 ( kXMPErrSev_FileFatal ) return false; } // XMPFiles::CanPutXMP // ================================================================================================= /* class-static */ void XMPFiles::SetDefaultProgressCallback ( const XMP_ProgressTracker::CallbackInfo & cbInfo ) { XMP_FILES_STATIC_START XMP_Assert ( cbInfo.wrapperProc != 0 ); // ! Should be provided by the glue code. sProgressDefault = cbInfo; XMP_FILES_STATIC_END1 ( kXMPErrSev_OperationFatal ) } // XMPFiles::SetDefaultProgressCallback // ================================================================================================= void XMPFiles::SetProgressCallback ( const XMP_ProgressTracker::CallbackInfo & cbInfo ) { XMP_FILES_START XMP_Assert ( cbInfo.wrapperProc != 0 ); // ! Should be provided by the glue code. if ( (this->handler != 0) && this->UsesClientIO() ) return; // Can't use progress tracking. if ( this->progressTracker != 0 ) { delete this->progressTracker; // ! Delete any existing tracker. this->progressTracker = 0; } if ( cbInfo.clientProc != 0 ) { this->progressTracker = new XMP_ProgressTracker ( cbInfo ); if ( this->handler != 0 ) { // Provided to support ProgressTracker in Plugins XMP_ProgressTracker::CallbackInfo * callbackInfo = new XMP_ProgressTracker::CallbackInfo(cbInfo); this->handler->SetProgressCallback( callbackInfo ) ; delete callbackInfo; } } XMP_FILES_END1 ( kXMPErrSev_OperationFatal ) } // XMPFiles::SetProgressCallback // ================================================================================================= // Error notifications // =================== // ------------------------------------------------------------------------------------------------- // SetDefaultErrorCallback // ----------------------- /* class-static */ void XMPFiles::SetDefaultErrorCallback ( XMPFiles_ErrorCallbackWrapper wrapperProc, XMPFiles_ErrorCallbackProc clientProc, void * context, XMP_Uns32 limit ) { XMP_FILES_STATIC_START XMP_Assert ( wrapperProc != 0 ); // Must always be set by the glue; sDefaultErrorCallback.wrapperProc = wrapperProc; sDefaultErrorCallback.clientProc = clientProc; sDefaultErrorCallback.context = context; sDefaultErrorCallback.limit = limit; XMP_FILES_STATIC_END1 ( kXMPErrSev_OperationFatal ) } // SetDefaultErrorCallback // ------------------------------------------------------------------------------------------------- // SetErrorCallback // ---------------- void XMPFiles::SetErrorCallback ( XMPFiles_ErrorCallbackWrapper wrapperProc, XMPFiles_ErrorCallbackProc clientProc, void * context, XMP_Uns32 limit ) { XMP_FILES_START XMP_Assert ( wrapperProc != 0 ); // Must always be set by the glue; this->errorCallback.Clear(); this->errorCallback.wrapperProc = wrapperProc; this->errorCallback.clientProc = clientProc; this->errorCallback.context = context; this->errorCallback.limit = limit; if ( this->handler != 0 ) // Provided to support ErrroCallback in Plugins this->handler->SetErrorCallback( ErrorCallbackBox( errorCallback.wrapperProc, errorCallback.clientProc, errorCallback.context, errorCallback.limit ) ); XMP_FILES_END1 ( kXMPErrSev_OperationFatal ) } // SetErrorCallback // ------------------------------------------------------------------------------------------------- // ResetErrorCallbackLimit // ----------------------- void XMPFiles::ResetErrorCallbackLimit ( XMP_Uns32 limit ) { XMP_FILES_START this->errorCallback.limit = limit; this->errorCallback.notifications = 0; this->errorCallback.topSeverity = kXMPErrSev_Recoverable; if ( this->handler != 0 ) // Provided to support ErrroCallback in Plugins this->handler->SetErrorCallback( ErrorCallbackBox( errorCallback.wrapperProc, errorCallback.clientProc, errorCallback.context, errorCallback.limit ) ); XMP_FILES_END1 ( kXMPErrSev_OperationFatal ) } // ResetErrorCallbackLimit // ------------------------------------------------------------------------------------------------- // ErrorCallbackInfo::CanNotify // ------------------------------- // // This is const just to be usable from const XMPMeta functions. bool XMPFiles::ErrorCallbackInfo::CanNotify() const { XMP_Assert ( (this->clientProc == 0) || (this->wrapperProc != 0) ); return ( this->clientProc != 0 ); } // ------------------------------------------------------------------------------------------------- // ErrorCallbackInfo::ClientCallbackWrapper // ------------------------------- // // This is const just to be usable from const XMPMeta functions. bool XMPFiles::ErrorCallbackInfo::ClientCallbackWrapper ( XMP_StringPtr filePath1, XMP_ErrorSeverity severity, XMP_Int32 cause, XMP_StringPtr messsage ) const { XMP_StringPtr filePathPtr = filePath1; if ( filePathPtr == 0 ) { filePathPtr = this->filePath.c_str(); } XMP_Bool retValue = (*this->wrapperProc) ( this->clientProc, this->context, filePathPtr, severity, cause, messsage ); return ConvertXMP_BoolToBool(retValue); } // ------------------------------------------------------------------------------------------------- // ErrorCallbackForXMPMeta // ------------------------------- bool ErrorCallbackForXMPMeta ( void * context, XMP_ErrorSeverity severity, XMP_Int32 cause, XMP_StringPtr message) { //typecast context to GenericErrorCallback GenericErrorCallback * callback = ( GenericErrorCallback * ) context; XMP_Error error ( cause, message ); callback->NotifyClient ( severity, error ); return !kXMP_Bool_False; } // =================================================================================================
33.233666
164
0.646368
hfiguiere
81e955b5601c605a10420cdd60e10ac13f375071
965
cpp
C++
HW5/HW5_Q1.cpp
Liuian/1082_INTRODUCTION_TO_COMPUTER_AND_PROGRAMMING_LANGUAGE_2
d2b78ec90976f5ef0ffcd1e33ed8c3b8d4d79601
[ "MIT" ]
null
null
null
HW5/HW5_Q1.cpp
Liuian/1082_INTRODUCTION_TO_COMPUTER_AND_PROGRAMMING_LANGUAGE_2
d2b78ec90976f5ef0ffcd1e33ed8c3b8d4d79601
[ "MIT" ]
null
null
null
HW5/HW5_Q1.cpp
Liuian/1082_INTRODUCTION_TO_COMPUTER_AND_PROGRAMMING_LANGUAGE_2
d2b78ec90976f5ef0ffcd1e33ed8c3b8d4d79601
[ "MIT" ]
null
null
null
// // main.cpp // HW5 Q1 // // Created by 劉翊安 on 2020/5/20. // Copyright © 2020 劉翊安. All rights reserved. // # include <iostream> # include <cstdlib> # include <math.h> using namespace std; double A[4][4]= {{0.1,0.2,0.4,0.3}, {0.5,0.2,0.1,0.2},{0.3,0.4,0.2,0.1},{0.15,0.25,0.2,0.4}}; double B[4][4]={{0.1,0.2,0.4,0.3}, {0.5,0.2,0.1,0.2},{0.3,0.4,0.2,0.1},{0.15,0.25,0.2,0.4}}; double C[4][4]={{}}; void matrixMul(){ for(int j=0;j<4;j++){ for(int i=0;i<4;i++){ C[j][i]=0; for(int m=0;m<4;m++){ C[j][i]+=A[j][m]*B[m][i]; } } } } int main(){ for(int m=0;m<14;m++){ matrixMul(); for(int j=0;j<4;j++){ for(int i=0;i<4;i++){ B[i][j]=C[i][j]; } } } for(int j=0;j<4;j++){ for(int i=0;i<4;i++){ cout <<C[j][i]<<" " ; } cout<<endl; } }
20.531915
93
0.384456
Liuian
81f284a2ee7e2c16e07d2bb3ba5eaf256799fe42
4,306
cc
C++
Engine/Source/Runtime/Core/YumeComponentAnimInfo.cc
rodrigobmg/YumeEngine
67c525c84616a5167b5bae45f36641e90227c281
[ "MIT" ]
129
2016-05-05T23:34:44.000Z
2022-03-07T20:17:18.000Z
Engine/Source/Runtime/Core/YumeComponentAnimInfo.cc
rodrigobmg/YumeEngine
67c525c84616a5167b5bae45f36641e90227c281
[ "MIT" ]
1
2017-05-07T16:09:41.000Z
2017-05-08T15:35:50.000Z
Engine/Source/Runtime/Core/YumeComponentAnimInfo.cc
rodrigobmg/YumeEngine
67c525c84616a5167b5bae45f36641e90227c281
[ "MIT" ]
20
2016-02-24T20:40:08.000Z
2022-02-04T23:48:18.000Z
//---------------------------------------------------------------------------- //Yume Engine //Copyright (C) 2015 arkenthera //This program is free software; you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation; either version 2 of the License, or //(at your option) any later version. //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. //You should have received a copy of the GNU General Public License along //with this program; if not, write to the Free Software Foundation, Inc., //51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.*/ //---------------------------------------------------------------------------- // // File : <Filename> // Date : <Date> // Comments : // //---------------------------------------------------------------------------- #include "YumeHeaders.h" #include "YumeComponentAnimInfo.h" #include "YumeComponentAnimation.h" #include "Logging/logging.h" namespace YumeEngine { ValueAnimationInfo::ValueAnimationInfo(ValueAnimation* animation,WrapMode wrapMode,float speed): animation_(animation), wrapMode_(wrapMode), speed_(speed), currentTime_(0.0f), lastScaledTime_(0.0f) { speed_ = Max(0.0f,speed_); } ValueAnimationInfo::ValueAnimationInfo(YumeBase* target,ValueAnimation* animation,WrapMode wrapMode,float speed): target_(target), animation_(animation), wrapMode_(wrapMode), speed_(speed), currentTime_(0.0f), lastScaledTime_(0.0f) { speed_ = Max(0.0f,speed_); } ValueAnimationInfo::ValueAnimationInfo(const ValueAnimationInfo& other): target_(other.target_), animation_(other.animation_), wrapMode_(other.wrapMode_), speed_(other.speed_), currentTime_(0.0f), lastScaledTime_(0.0f) { } ValueAnimationInfo::~ValueAnimationInfo() { } bool ValueAnimationInfo::Update(float timeStep) { if(!animation_ || !target_) return true; return SetTime(currentTime_ + timeStep * speed_); } bool ValueAnimationInfo::SetTime(float time) { if(!animation_ || !target_) return true; currentTime_ = time; if(!animation_->IsValid()) return true; bool finished = false; // Calculate scale time by wrap mode float scaledTime = CalculateScaledTime(currentTime_,finished); // Apply to the target object ApplyValue(animation_->GetAnimationValue(scaledTime)); // Send keyframe event if necessary if(animation_->HasEventFrames()) { YumeVector<const VAnimEventFrame*>::type eventFrames; GetEventFrames(lastScaledTime_,scaledTime,eventFrames); /*for(unsigned i = 0; i < eventFrames.Size(); ++i) target_->SendEvent(eventFrames[i]->eventType_,const_cast<VariantMap&>(eventFrames[i]->eventData_));*/ } lastScaledTime_ = scaledTime; return finished; } YumeBase* ValueAnimationInfo::GetTarget() const { return target_; } void ValueAnimationInfo::ApplyValue(const Variant& newValue) { } float ValueAnimationInfo::CalculateScaledTime(float currentTime,bool& finished) const { float beginTime = animation_->GetBeginTime(); float endTime = animation_->GetEndTime(); switch(wrapMode_) { case WM_LOOP: { float span = endTime - beginTime; float time = fmodf(currentTime - beginTime,span); if(time < 0.0f) time += span; return beginTime + time; } case WM_ONCE: finished = (currentTime >= endTime); // Fallthrough case WM_CLAMP: return Clamp(currentTime,beginTime,endTime); default: YUMELOG_ERROR("Unsupported attribute animation wrap mode"); return beginTime; } } void ValueAnimationInfo::GetEventFrames(float beginTime,float endTime,YumeVector<const VAnimEventFrame*>::type& eventFrames) { switch(wrapMode_) { case WM_LOOP: if(beginTime < endTime) animation_->GetEventFrames(beginTime,endTime,eventFrames); else { animation_->GetEventFrames(beginTime,animation_->GetEndTime(),eventFrames); animation_->GetEventFrames(animation_->GetBeginTime(),endTime,eventFrames); } break; case WM_ONCE: case WM_CLAMP: animation_->GetEventFrames(beginTime,endTime,eventFrames); break; } } }
25.47929
125
0.692522
rodrigobmg
81f7d52eea43d9be3e56f15537253aa25f91a54c
1,728
cpp
C++
backup/2/leetcode/c++/balance-a-binary-search-tree.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/leetcode/c++/balance-a-binary-search-tree.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/leetcode/c++/balance-a-binary-search-tree.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/leetcode/balance-a-binary-search-tree.html . /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *balanceBST(TreeNode *root) { vector<int> nums = flatten(root); sort(nums.begin(), nums.end()); return construct(nums, 0, nums.size() - 1); } TreeNode *construct(vector<int> &nums, int start, int end) { if (start > end) { return nullptr; } int half = (start + end) / 2; auto head = new TreeNode(nums[half]); auto left = construct(nums, start, half - 1); auto right = construct(nums, half + 1, end); head->left = left; head->right = right; return head; } vector<int> flatten(TreeNode *root) { if (root == nullptr) { return vector<int>(); } auto res = flatten(root->left); auto rights = flatten(root->right); res.push_back(root->val); res.insert(res.end(), rights.begin(), rights.end()); return res; } };
36
345
0.61169
yangyanzhan
81f8a527f4bf15e7bbd1954f24ec1fea56699b15
533
hpp
C++
include/RED4ext/Scripting/Natives/Generated/game/ui/HUDVideoStopEvent.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/game/ui/HUDVideoStopEvent.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/game/ui/HUDVideoStopEvent.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> namespace RED4ext { namespace game::ui { struct HUDVideoStopEvent { static constexpr const char* NAME = "gameuiHUDVideoStopEvent"; static constexpr const char* ALIAS = NAME; uint8_t unk00[0x8 - 0x0]; // 0 uint64_t videoPathHash; // 08 bool isSkip; // 10 uint8_t unk11[0x18 - 0x11]; // 11 }; RED4EXT_ASSERT_SIZE(HUDVideoStopEvent, 0x18); } // namespace game::ui } // namespace RED4ext
22.208333
66
0.707317
jackhumbert
3b567b21cdc15a8101f8504005da24326888df34
4,742
cpp
C++
libs/quadwild/libs/libigl/include/igl/cgal/peel_outer_hull_layers.cpp
Pentacode-IAFA/Quad-Remeshing
f8fd4c10abf1c54656b38a00b8a698b952a85fe2
[ "Apache-2.0" ]
null
null
null
libs/quadwild/libs/libigl/include/igl/cgal/peel_outer_hull_layers.cpp
Pentacode-IAFA/Quad-Remeshing
f8fd4c10abf1c54656b38a00b8a698b952a85fe2
[ "Apache-2.0" ]
null
null
null
libs/quadwild/libs/libigl/include/igl/cgal/peel_outer_hull_layers.cpp
Pentacode-IAFA/Quad-Remeshing
f8fd4c10abf1c54656b38a00b8a698b952a85fe2
[ "Apache-2.0" ]
null
null
null
#include "peel_outer_hull_layers.h" #include "../per_face_normals.h" #include "outer_hull.h" #include <vector> #include <iostream> //#define IGL_PEEL_OUTER_HULL_LAYERS_DEBUG #ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG #include "../writePLY.h" #include "../writeDMAT.h" #include "../STR.h" #endif using namespace std; template < typename DerivedV, typename DerivedF, typename DerivedN, typename Derivedodd, typename Derivedflip> IGL_INLINE size_t igl::peel_outer_hull_layers( const Eigen::PlainObjectBase<DerivedV > & V, const Eigen::PlainObjectBase<DerivedF > & F, const Eigen::PlainObjectBase<DerivedN > & N, Eigen::PlainObjectBase<Derivedodd > & odd, Eigen::PlainObjectBase<Derivedflip > & flip) { using namespace Eigen; using namespace std; typedef typename DerivedF::Index Index; typedef Matrix<typename DerivedF::Scalar,Dynamic,DerivedF::ColsAtCompileTime> MatrixXF; typedef Matrix<typename DerivedN::Scalar,Dynamic,DerivedN::ColsAtCompileTime> MatrixXN; typedef Matrix<Index,Dynamic,1> MatrixXI; typedef Matrix<typename Derivedflip::Scalar,Dynamic,Derivedflip::ColsAtCompileTime> MatrixXflip; const Index m = F.rows(); #ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG cout<<"peel outer hull layers..."<<endl; #endif #ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG cout<<"calling outer hull..."<<endl; writePLY(STR("peel-outer-hull-input.ply"),V,F); #endif #ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG cout<<"resize output ..."<<endl; #endif // keep track of iteration parity and whether flipped in hull MatrixXF Fr = F; MatrixXN Nr = N; odd.resize(m,1); flip.resize(m,1); // Keep track of index map MatrixXI IM = MatrixXI::LinSpaced(m,0,m-1); // This is O(n * layers) bool odd_iter = true; MatrixXI P(m,1); Index iter = 0; while(Fr.size() > 0) { assert(Fr.rows() == IM.rows()); // Compute outer hull of current Fr MatrixXF Fo; MatrixXI Jo; MatrixXflip flipr; #ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG cout<<"calling outer hull..."<<endl; writePLY(STR("outer-hull-input-"<<iter<<".ply"),V,Fr); writeDMAT(STR("outer-hull-input-"<<iter<<".dmat"),Nr); #endif outer_hull(V,Fr,Nr,Fo,Jo,flipr); #ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG writePLY(STR("outer-hull-output-"<<iter<<".ply"),V,Fo); cout<<"reindex, flip..."<<endl; #endif assert(Fo.rows() == Jo.rows()); // all faces in Fo of Fr vector<bool> in_outer(Fr.rows(),false); for(Index g = 0;g<Jo.rows();g++) { odd(IM(Jo(g))) = odd_iter; P(IM(Jo(g))) = iter; in_outer[Jo(g)] = true; flip(IM(Jo(g))) = flipr(Jo(g)); } // Fr = Fr - Fo // update IM MatrixXF prev_Fr = Fr; MatrixXN prev_Nr = Nr; MatrixXI prev_IM = IM; Fr.resize(prev_Fr.rows() - Fo.rows(),F.cols()); Nr.resize(Fr.rows(),3); IM.resize(Fr.rows()); { Index g = 0; for(Index f = 0;f<prev_Fr.rows();f++) { if(!in_outer[f]) { Fr.row(g) = prev_Fr.row(f); Nr.row(g) = prev_Nr.row(f); IM(g) = prev_IM(f); g++; } } } odd_iter = !odd_iter; iter++; } return iter; } template < typename DerivedV, typename DerivedF, typename Derivedodd, typename Derivedflip> IGL_INLINE size_t igl::peel_outer_hull_layers( const Eigen::PlainObjectBase<DerivedV > & V, const Eigen::PlainObjectBase<DerivedF > & F, Eigen::PlainObjectBase<Derivedodd > & odd, Eigen::PlainObjectBase<Derivedflip > & flip) { Eigen::Matrix<typename DerivedV::Scalar,DerivedF::RowsAtCompileTime,3> N; per_face_normals(V,F,N); return peel_outer_hull_layers(V,F,N,odd,flip); } #ifdef IGL_STATIC_LIBRARY // Explicit template specialization template size_t igl::peel_outer_hull_layers<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<bool, -1, 1, 0, -1, 1>, Eigen::Matrix<bool, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<bool, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<bool, -1, 1, 0, -1, 1> >&); template size_t igl::peel_outer_hull_layers<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<bool, -1, 1, 0, -1, 1>, Eigen::Matrix<bool, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<bool, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<bool, -1, 1, 0, -1, 1> >&); #endif
35.654135
579
0.661113
Pentacode-IAFA
3b5aecf5f1bf65da5cd72d49a079a65969e5a30c
8,821
cpp
C++
src/spi.cpp
malioni/airbourne_f4
9efda7fd3b6f0c86284f04ebc9b5dda73d55392d
[ "BSD-3-Clause" ]
null
null
null
src/spi.cpp
malioni/airbourne_f4
9efda7fd3b6f0c86284f04ebc9b5dda73d55392d
[ "BSD-3-Clause" ]
3
2018-09-12T19:59:41.000Z
2018-09-12T20:01:20.000Z
src/spi.cpp
skyler237/rosgimbal
9ab956ec22980ea78f29b45bb0e3f4d8b489761c
[ "BSD-3-Clause" ]
3
2018-09-11T20:34:50.000Z
2020-12-08T14:02:59.000Z
/* * Copyright (c) 2017, James Jackson * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "spi.h" SPI* SPI1ptr; SPI* SPI2ptr; SPI* SPI3ptr; static uint8_t dummy_buffer[256]; void SPI::init(const spi_hardware_struct_t *c) { SPI_InitTypeDef spi_init_struct; c_ = c; if (c_->dev == SPI1) SPI1ptr = this; else if (c_->dev == SPI2) SPI2ptr = this; else if (c_->dev == SPI3) SPI3ptr = this; // Set the AF configuration for the other pins GPIO_PinAFConfig(c_->GPIO, c_->SCK_PinSource, c_->GPIO_AF); GPIO_PinAFConfig(c_->GPIO, c_->MOSI_PinSource, c_->GPIO_AF); GPIO_PinAFConfig(c_->GPIO, c_->MISO_PinSource, c_->GPIO_AF); // Initialize other pins sck_.init(c_->GPIO, c_->SCK_Pin, GPIO::PERIPH_OUT); miso_.init(c_->GPIO, c_->MOSI_Pin, GPIO::PERIPH_OUT); mosi_.init(c_->GPIO, c_->MISO_Pin, GPIO::PERIPH_OUT); // Set up the SPI peripheral SPI_I2S_DeInit(c_->dev); spi_init_struct.SPI_Direction = SPI_Direction_2Lines_FullDuplex; spi_init_struct.SPI_Mode = SPI_Mode_Master; spi_init_struct.SPI_DataSize = SPI_DataSize_8b; spi_init_struct.SPI_CPOL = SPI_CPOL_High; spi_init_struct.SPI_CPHA = SPI_CPHA_2Edge; spi_init_struct.SPI_NSS = SPI_NSS_Soft; spi_init_struct.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_64; // 42/64 = 0.65625 MHz SPI Clock spi_init_struct.SPI_FirstBit = SPI_FirstBit_MSB; spi_init_struct.SPI_CRCPolynomial = 7; SPI_Init(c_->dev, &spi_init_struct); SPI_CalculateCRC(c_->dev, DISABLE); SPI_Cmd(c_->dev, ENABLE); // Wait for any transfers to clear (this should be really short if at all) while (SPI_I2S_GetFlagStatus(c_->dev, SPI_I2S_FLAG_TXE) == RESET); SPI_I2S_ReceiveData(c_->dev); //dummy read if needed // Configure the DMA DMA_InitStructure_.DMA_FIFOMode = DMA_FIFOMode_Disable ; DMA_InitStructure_.DMA_FIFOThreshold = DMA_FIFOThreshold_1QuarterFull ; DMA_InitStructure_.DMA_MemoryBurst = DMA_MemoryBurst_Single ; DMA_InitStructure_.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte; DMA_InitStructure_.DMA_MemoryInc = DMA_MemoryInc_Enable; DMA_InitStructure_.DMA_Mode = DMA_Mode_Normal; DMA_InitStructure_.DMA_PeripheralBurst = DMA_PeripheralBurst_Single; DMA_InitStructure_.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte; DMA_InitStructure_.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte; DMA_InitStructure_.DMA_Channel = c_->DMA_Channel; DMA_InitStructure_.DMA_PeripheralBaseAddr = reinterpret_cast<uint32_t>(&(c_->dev->DR)); DMA_InitStructure_.DMA_PeripheralInc = DMA_PeripheralInc_Disable; DMA_InitStructure_.DMA_Priority = DMA_Priority_High; // Configure the Appropriate Interrupt Routine NVIC_InitTypeDef NVIC_InitStruct; NVIC_InitStruct.NVIC_IRQChannel = c_->DMA_IRQn; NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE; NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0x02; NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0x02; NVIC_Init(&NVIC_InitStruct); transfer_cb_ = NULL; } void SPI::set_divisor(uint16_t new_divisor) { SPI_Cmd(c_->dev, DISABLE); const uint16_t clearBRP = 0xFFC7; uint16_t temp = c_->dev->CR1; temp &= clearBRP; switch(new_divisor) { case 2: temp |= SPI_BaudRatePrescaler_2; break; case 4: temp |= SPI_BaudRatePrescaler_4; break; case 8: temp |= SPI_BaudRatePrescaler_8; break; case 16: temp |= SPI_BaudRatePrescaler_16; break; case 32: default: temp |= SPI_BaudRatePrescaler_32; break; case 64: temp |= SPI_BaudRatePrescaler_64; break; case 128: temp |= SPI_BaudRatePrescaler_128; break; case 256: temp |= SPI_BaudRatePrescaler_256; break; } c_->dev->CR1 = temp; SPI_Cmd(c_->dev, ENABLE); } void SPI::enable(GPIO& cs) { cs.write(GPIO::LOW); } void SPI::disable(GPIO& cs) { cs.write(GPIO::HIGH); } uint8_t SPI::transfer_byte(uint8_t data, GPIO *cs) { uint16_t spiTimeout; spiTimeout = 0x1000; if (cs != NULL) enable(*cs); while (SPI_I2S_GetFlagStatus(c_->dev, SPI_I2S_FLAG_TXE) == RESET) { if ((--spiTimeout) == 0) return false; } SPI_I2S_SendData(c_->dev, data); spiTimeout = 0x1000; while (SPI_I2S_GetFlagStatus(c_->dev, SPI_I2S_FLAG_RXNE) == RESET) { if ((--spiTimeout) == 0) return false; } if (cs) disable(*cs); return static_cast<uint8_t>(SPI_I2S_ReceiveData(c_->dev)); } bool SPI::write(const uint8_t *out_data, uint32_t num_bytes, GPIO* cs) { busy_ = true; // Save Job parameters in_buffer_ptr_ = dummy_buffer; out_buffer_ptr_ = (out_data == NULL) ? dummy_buffer : out_data; cs_ = cs; transfer_cb_ = NULL; num_bytes_ = num_bytes; perform_transfer(); return true; } bool SPI::transfer(uint8_t *out_data, uint32_t num_bytes, uint8_t* in_data, GPIO* cs, void (*cb)(void)) { busy_ = true; // Save Job parameters in_buffer_ptr_ = (in_data == NULL) ? dummy_buffer : in_data; out_buffer_ptr_ = (out_data == NULL) ? dummy_buffer : out_data; cs_ = cs; transfer_cb_ = cb; num_bytes_ = num_bytes; perform_transfer(); return true; } void SPI::perform_transfer() { // Configure the DMA DMA_DeInit(c_->Tx_DMA_Stream); //SPI1_TX_DMA_STREAM DMA_DeInit(c_->Rx_DMA_Stream); //SPI1_RX_DMA_STREAM DMA_InitStructure_.DMA_BufferSize = num_bytes_; // Configure Tx DMA DMA_InitStructure_.DMA_DIR = DMA_DIR_MemoryToPeripheral; DMA_InitStructure_.DMA_Memory0BaseAddr = reinterpret_cast<uint32_t>(out_buffer_ptr_); DMA_Init(c_->Tx_DMA_Stream, &DMA_InitStructure_); // Configure Rx DMA DMA_InitStructure_.DMA_DIR = DMA_DIR_PeripheralToMemory; DMA_InitStructure_.DMA_Memory0BaseAddr = reinterpret_cast<uint32_t>(in_buffer_ptr_); DMA_Init(c_->Rx_DMA_Stream, &DMA_InitStructure_); // Configure the Interrupt DMA_ITConfig(c_->Tx_DMA_Stream, DMA_IT_TC, ENABLE); if (cs_ != NULL) enable(*cs_); // Turn on the DMA streams DMA_Cmd(c_->Tx_DMA_Stream, ENABLE); DMA_Cmd(c_->Rx_DMA_Stream, ENABLE); // Enable the SPI Rx/Tx DMA request SPI_I2S_DMACmd(c_->dev, SPI_I2S_DMAReq_Rx, ENABLE); SPI_I2S_DMACmd(c_->dev, SPI_I2S_DMAReq_Tx, ENABLE); } void SPI::transfer_complete_cb() { // uint8_t rxne, txe; // do // { // rxne = SPI_I2S_GetFlagStatus(c_->dev, SPI_I2S_FLAG_RXNE); // txe = SPI_I2S_GetFlagStatus(c_->dev, SPI_I2S_FLAG_TXE); // }while (rxne == RESET || txe == RESET); disable(*cs_); DMA_ClearFlag(c_->Tx_DMA_Stream, c_->Tx_DMA_TCIF); DMA_ClearFlag(c_->Rx_DMA_Stream, c_->Rx_DMA_TCIF); DMA_Cmd(c_->Tx_DMA_Stream, DISABLE); DMA_Cmd(c_->Rx_DMA_Stream, DISABLE); SPI_I2S_DMACmd(c_->dev, SPI_I2S_DMAReq_Rx, DISABLE); SPI_I2S_DMACmd(c_->dev, SPI_I2S_DMAReq_Tx, DISABLE); // SPI_Cmd(c_->dev, DISABLE); if (cs_ != NULL) { disable(*cs_); } busy_ = false; if (transfer_cb_ != NULL) transfer_cb_(); } extern "C" { void DMA2_Stream3_IRQHandler() { if (DMA_GetITStatus(DMA2_Stream3, DMA_IT_TCIF3)) { DMA_ClearITPendingBit(DMA2_Stream3, DMA_IT_TCIF3); SPI1ptr->transfer_complete_cb(); } } void DMA1_Stream4_IRQHandler() { if (DMA_GetITStatus(DMA1_Stream4, DMA_IT_TCIF4)) { DMA_ClearITPendingBit(DMA1_Stream4, DMA_IT_TCIF4); SPI2ptr->transfer_complete_cb(); } } void DMA1_Stream5_IRQHandler() { if (DMA_GetITStatus(DMA1_Stream5, DMA_IT_TCIF5)) { DMA_ClearITPendingBit(DMA1_Stream5, DMA_IT_TCIF5); SPI3ptr->transfer_complete_cb(); } } }
28.003175
103
0.736198
malioni
3b5aff815782d6134caf9eeee21ba3b6c105e94e
4,319
hpp
C++
src/stage/stage-setup-packet.hpp
tilnewman/heroespath-src
a7784e44d8b5724f305ef8b8671fed54e2e5fd69
[ "BSL-1.0", "Beerware" ]
2
2019-02-28T00:28:08.000Z
2019-10-20T14:39:48.000Z
src/stage/stage-setup-packet.hpp
tilnewman/heroespath-src
a7784e44d8b5724f305ef8b8671fed54e2e5fd69
[ "BSL-1.0", "Beerware" ]
null
null
null
src/stage/stage-setup-packet.hpp
tilnewman/heroespath-src
a7784e44d8b5724f305ef8b8671fed54e2e5fd69
[ "BSL-1.0", "Beerware" ]
null
null
null
// ---------------------------------------------------------------------------- // "THE BEER-WARE LICENSE" (Revision 42): // <ztn@zurreal.com> wrote this file. As long as you retain this notice you // can do whatever you want with this stuff. If we meet some day, and you think // this stuff is worth it, you can buy me a beer in return. Ziesche Til Newman // ---------------------------------------------------------------------------- #ifndef HEROESPATH_STAGE_STAGE_SETUP_PACKET_HPP_INCLUDED #define HEROESPATH_STAGE_STAGE_SETUP_PACKET_HPP_INCLUDED // // stage-setup-packet.hpp // #include "game/phase-enum.hpp" #include "misc/boost-optional-that-throws.hpp" #include "stage/i-stage.hpp" #include "stage/stage-enum.hpp" #include <sstream> #include <string> #include <tuple> namespace heroespath { namespace creature { class Creature; using CreaturePtr_t = misc::NotNull<Creature *>; using CreaturePtrOpt_t = boost::optional<CreaturePtr_t>; } // namespace creature namespace popup { class PopupInfo; } namespace stage { // wraps all the information needed to setup the Inventory Stage struct InventorySetupPacket { InventorySetupPacket( const game::Phase::Enum PREV_CALLING_PHASE, const creature::CreaturePtr_t TURN_CREATURE_PTR, const creature::CreaturePtr_t INVENTORY_CREATURE_PTR) : prev_calling_phase(PREV_CALLING_PHASE) , turn_creature_ptr(TURN_CREATURE_PTR) , inventory_creature_ptr(INVENTORY_CREATURE_PTR) {} InventorySetupPacket(const InventorySetupPacket &) = default; InventorySetupPacket(InventorySetupPacket &&) = default; InventorySetupPacket & operator=(const InventorySetupPacket &) = default; InventorySetupPacket & operator=(InventorySetupPacket &&) = default; const std::string ToString() const; game::Phase::Enum prev_calling_phase; creature::CreaturePtr_t turn_creature_ptr; creature::CreaturePtr_t inventory_creature_ptr; }; using InventorySetupPacketOpt_t = boost::optional<InventorySetupPacket>; inline bool operator==(const InventorySetupPacket & L, const InventorySetupPacket & R) { return ( std::tie(L.prev_calling_phase, L.turn_creature_ptr, L.inventory_creature_ptr) == std::tie(R.prev_calling_phase, R.turn_creature_ptr, R.inventory_creature_ptr)); } inline bool operator!=(const InventorySetupPacket & L, const InventorySetupPacket & R) { return !(L == R); } // wraps all the information needed to setup ANY Stage struct SetupPacket { explicit SetupPacket( const stage::Stage::Enum STAGE, const bool WILL_ADVANCE_TURN = false, const InventorySetupPacketOpt_t INVENTORY_PACKET_OPT = boost::none) : stage(STAGE) , will_advance_turn(WILL_ADVANCE_TURN) , inventory_packet_opt(INVENTORY_PACKET_OPT) {} SetupPacket(const SetupPacket &) = default; SetupPacket(SetupPacket &&) = default; SetupPacket & operator=(const SetupPacket &) = default; SetupPacket & operator=(SetupPacket &&) = default; const std::string ToString() const { std::ostringstream ss; ss << "stage_setup=" << stage::Stage::ToString(stage); if (will_advance_turn) { ss << ", stage_setup_will_advance_turn"; } if (inventory_packet_opt) { ss << ", " << inventory_packet_opt->ToString(); } return ss.str(); } stage::Stage::Enum stage; bool will_advance_turn; InventorySetupPacketOpt_t inventory_packet_opt; }; using SetupPacketOpt_t = boost::optional<SetupPacket>; inline bool operator==(const SetupPacket & L, const SetupPacket & R) { return ( std::tie(L.stage, L.will_advance_turn, L.inventory_packet_opt) == std::tie(R.stage, R.will_advance_turn, R.inventory_packet_opt)); } inline bool operator!=(const SetupPacket & L, const SetupPacket & R) { return !(L == R); } } // namespace stage } // namespace heroespath #endif // HEROESPATH_STAGE_STAGE_SETUP_PACKET_HPP_INCLUDED
32.473684
94
0.637648
tilnewman
3b5b0878776eb64d9394792e4d231ec537ccbaad
6,603
hpp
C++
trsl/sort_iterator.hpp
renauddetry/trsl
641e44d77488de65ab8f38f114db78ee47da74c3
[ "BSL-1.0" ]
null
null
null
trsl/sort_iterator.hpp
renauddetry/trsl
641e44d77488de65ab8f38f114db78ee47da74c3
[ "BSL-1.0" ]
null
null
null
trsl/sort_iterator.hpp
renauddetry/trsl
641e44d77488de65ab8f38f114db78ee47da74c3
[ "BSL-1.0" ]
null
null
null
// (C) Copyright Renaud Detry 2007-2011. // 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) /** @file */ #ifndef TRSL_SORT_ITERATOR_HPP #define TRSL_SORT_ITERATOR_HPP #include <trsl/reorder_iterator.hpp> #include <trsl/common.hpp> #include <trsl/error_handling.hpp> #include <functional> namespace trsl { namespace detail { template< class RandomIterator, class Comparator > class at_index_comp { public: at_index_comp(const RandomIterator &first, const Comparator &comp) : elements_(first), comp_(comp) {} bool operator() (unsigned i, unsigned j) { return comp_(*(elements_+i), *(elements_+j)); } RandomIterator elements_; Comparator comp_; }; } /** * @brief Constructs a reorder_iterator that will iterate through * the first @p permutationSize elements of a sorted permutation of * the population referenced by @p first and @p last. * * The @p permutationSize should be smaller or equal to the size of * the population. If it is not the case, a bad_parameter_value is * thrown. * * A comparator is provided through @p comp. <tt>Comparator</tt> * has to model <a * href="http://www.sgi.com/tech/stl/StrictWeakOrdering.html" * >Strict Weak Ordering</a>. In particular <a * href="http://www.sgi.com/tech/stl/less.html" * ><tt>std::less<ElementType>()</tt></a> and <a * href="http://www.sgi.com/tech/stl/greater.html" * ><tt>std::greater<ElementType>()</tt></a> will work, whereas <a * href="http://www.sgi.com/tech/stl/less_equal.html" * ><tt>std::less_equal<ElementType>()</tt></a> and <a * href="http://www.sgi.com/tech/stl/greater_equal.html" * ><tt>std::greater_equal<ElementType>()</tt></a> will * <em>not</em>. * * @p ElementIterator should model <em>Random Access Iterator</em>. * * Creating such a reorder_iterator and iterating through it is * generally much faster than re-ordering the population itself (or * a copy thereof), especially when elements are large, have a * complex copy-constructor, or a tall class hierarchy. */ template<class ElementIterator, class ElementComparator> reorder_iterator<ElementIterator> sort_iterator(ElementIterator first, ElementIterator last, ElementComparator comp, unsigned permutationSize) { ptrdiff_t size = std::distance(first, last); if (size < 0) throw bad_parameter_value( "sort_iterator: " "bad input range."); if (permutationSize > unsigned(size)) throw bad_parameter_value( "sort_iterator: " "parameter permutationSize out of range."); typedef typename reorder_iterator<ElementIterator>::index_container index_container; typedef typename reorder_iterator<ElementIterator>::index_container_ptr index_container_ptr; typedef typename reorder_iterator<ElementIterator>::index_t index_t; index_container_ptr index_collection(new index_container); index_collection->resize(size); for (index_t i = 0; i < index_t(size); ++i) (*index_collection)[i] = i; if (permutationSize == unsigned(size)) std::sort(index_collection->begin(), index_collection->end(), detail::at_index_comp <ElementIterator, ElementComparator>(first, comp)); else { std::partial_sort(index_collection->begin(), index_collection->begin()+permutationSize, index_collection->end(), detail::at_index_comp <ElementIterator, ElementComparator>(first, comp)); index_collection->resize(permutationSize); } return reorder_iterator<ElementIterator>(first, index_collection); } /** * @brief Constructs a reorder_iterator that will iterate through a * sorted permutation of the population referenced by @p first and * @p last. * * A comparator is provided through @p comp. <tt>Comparator</tt> * has to model <a * href="http://www.sgi.com/tech/stl/StrictWeakOrdering.html" * >Strict Weak Ordering</a>. In particular <a * href="http://www.sgi.com/tech/stl/less.html" * ><tt>std::less<ElementType>()</tt></a> and <a * href="http://www.sgi.com/tech/stl/greater.html" * ><tt>std::greater<ElementType>()</tt></a> can work, whereas <a * href="http://www.sgi.com/tech/stl/less_equal.html" * ><tt>std::less_equal<ElementType>()</tt></a> and <a * href="http://www.sgi.com/tech/stl/greater_equal.html" * ><tt>std::greater_equal<ElementType>()</tt></a> will * <em>not</em>. * * @p ElementIterator should model <em>Random Access Iterator</em>. * * Creating such a reorder_iterator and iterating through it is * generally much faster than re-ordering the population itself (or * a copy thereof), especially when elements are large, have a * complex copy-constructor, or a tall class hierarchy. */ template<class ElementIterator, class ElementComparator> reorder_iterator<ElementIterator> sort_iterator(ElementIterator first, ElementIterator last, ElementComparator comp) { return sort_iterator(first, last, comp, std::distance(first, last)); } /** * @brief Constructs a reorder_iterator that will iterate through a * sorted permutation of the population referenced by @p first and * @p last. * * The population is sorted using <tt>std::less<>()</tt>, i.e. in * ascending order. * * @p ElementIterator should model <em>Random Access Iterator</em>. * * Creating such a reorder_iterator and iterating through it is * generally much faster than re-ordering the population itself (or * a copy thereof), especially when elements are large, have a * complex copy-constructor, or a tall class hierarchy. */ template<class ElementIterator> reorder_iterator<ElementIterator> sort_iterator(ElementIterator first, ElementIterator last) { return sort_iterator(first, last, std::less <typename std::iterator_traits <ElementIterator>::value_type>()); } } // namespace trsl #endif // include guard
34.212435
76
0.641072
renauddetry
3b5b667f59ee15c99ad0b92d5ef911f62117e453
294
hpp
C++
triangler/font.hpp
viitana/triangler
06719c0f019ee1946482ce58195468db518cbdde
[ "MIT" ]
2
2020-01-14T11:22:23.000Z
2022-02-24T13:13:47.000Z
triangler/font.hpp
viitana/triangler
06719c0f019ee1946482ce58195468db518cbdde
[ "MIT" ]
null
null
null
triangler/font.hpp
viitana/triangler
06719c0f019ee1946482ce58195468db518cbdde
[ "MIT" ]
null
null
null
#include <GL/glew.h> #include <glm/glm.hpp> struct Character { GLuint TextureID; // ID handle of the glyph texture glm::ivec2 Size; // Size of glyph glm::ivec2 Bearing; // Offset from baseline to left/top of glyph GLuint Advance; // Offset to advance to next glyph };
29.4
68
0.666667
viitana
3b5c9b744ce47e9e36ed717bf9ea1e6176f0864c
829
cpp
C++
Src/Array/769_MaxChunksToMakeSorted.cpp
HATTER-LONG/https---github.com-HATTER-LONG-AlgorithmTraining
bd2773c066352bab46ac019cef9fbbff8761c147
[ "Apache-2.0" ]
2
2021-02-07T07:03:43.000Z
2021-02-08T16:04:42.000Z
Src/Array/769_MaxChunksToMakeSorted.cpp
HATTER-LONG/https---github.com-HATTER-LONG-AlgorithmTraining
bd2773c066352bab46ac019cef9fbbff8761c147
[ "Apache-2.0" ]
null
null
null
Src/Array/769_MaxChunksToMakeSorted.cpp
HATTER-LONG/https---github.com-HATTER-LONG-AlgorithmTraining
bd2773c066352bab46ac019cef9fbbff8761c147
[ "Apache-2.0" ]
1
2021-02-24T09:48:26.000Z
2021-02-24T09:48:26.000Z
#include "Tools/Tools.hpp" /* * 题目描述 * 给定一个含有 0 到 n * 整数的数组,每个整数只出现一次,求这个数组最多可以分割成多少个 * 子数组,使得对每个子数组进行增序排序后,原数组也是增序的。 * * * 输入一个一维整数数组,输出一个整数,表示最多的分割数。 * Input: [1,0,2,3,4] * Output: 4 * 在这个样例中,最多分割是 [1, 0], [2], [3], [4]。 */ int maxChunksToSorted(vector<int>& arr) { int chunks = 0, curMax = 0; for (size_t i = 0; i < arr.size(); i++) { curMax = max(curMax, arr[i]); if (curMax == static_cast<int>(i)) { chunks++; } } return chunks; } TEST_CASE("test max chunks to sorted") { VecInt input; int result; tie(input, result) = GENERATE(table<VecInt, int>({ make_tuple(VecInt { 1, 0, 2, 3, 4 }, 4), make_tuple(VecInt { 1, 2, 0, 3 }, 2) })); CAPTURE(input, result); REQUIRE(maxChunksToSorted(input) == result); }
19.27907
78
0.55006
HATTER-LONG
3b5d6bc356d314c25474a2afd42e396aa9404867
4,705
hpp
C++
include/list.hpp
oYOvOYo/Cplusplus.TemplateMetaProgramming
02884fb85b44d4257f5c93e3b52ea97031937f3d
[ "MIT" ]
null
null
null
include/list.hpp
oYOvOYo/Cplusplus.TemplateMetaProgramming
02884fb85b44d4257f5c93e3b52ea97031937f3d
[ "MIT" ]
null
null
null
include/list.hpp
oYOvOYo/Cplusplus.TemplateMetaProgramming
02884fb85b44d4257f5c93e3b52ea97031937f3d
[ "MIT" ]
null
null
null
// todo: more operation on list like compare #include <algorithm> #include <iostream> typedef int TYPE; template <TYPE x> struct Type { static const TYPE value = x; }; struct NIL { typedef NIL Head; typedef NIL Tail; }; template <typename H, typename T = NIL> struct List { typedef H Head; typedef T Tail; }; // Length template <typename list> struct Length { static const size_t result = 1 + Length<typename list::Tail>::result; }; template <> struct Length<NIL> { static const size_t result = 0; }; // ItemAt template <typename list, size_t N> struct ItemAt { typedef typename ItemAt<typename list::Tail, N - 1>::result result; }; template <typename list> struct ItemAt<list, 0> { typedef typename list::Head result; }; // InsertItemAt template <typename list, typename item, size_t index> struct InsertItemAt { typedef List< typename list::Head, typename InsertItemAt<typename list::Tail, item, index - 1>::result> result; }; template <typename list, typename item> struct InsertItemAt<list, item, 0> { typedef List<item, list> result; }; // RemoveItemAt template <typename list, size_t index> struct RemoveItemAt { typedef List<typename list::Head, typename RemoveItemAt<typename list::Tail, index - 1>::result> result; }; template <typename list> struct RemoveItemAt<list, 0> { typedef typename list::Tail result; }; // ListToString template <typename list> std::string ListToString() { return "(" + std::to_string(list::Head::value) + ", " + ListToString<typename list::Tail>() + ")"; }; template <> std::string ListToString<NIL>() { return std::string("NIL"); }; // // test version // // void f() {} // // template <typename head, typename... types> // void f(head x, types... variables) { // std::cout << x << " "; // f(variables...); // } // CreateList template <TYPE... lists> struct CreateList { template <typename head, typename... tail> struct __CreateList { typedef List<head, typename __CreateList<tail...>::result> result; }; template <typename head> struct __CreateList<head> { typedef List<head> result; }; typedef typename __CreateList<Type<lists>...>::result result; }; // Slice [begin, end) template <typename list, size_t begin, size_t end> struct Slice { template <size_t x> struct Type { static const TYPE value = x; }; template <typename __list, typename __begin, typename __end> struct __Slice { typedef typename __Slice< typename RemoveItemAt<__list, Length<__list>::result - 1>::result, __begin, __end>::result result; }; template <typename __list, typename __begin> struct __Slice<__list, __begin, Type<(Length<__list>::result)>> { typedef typename __Slice<typename __list::Tail, Type<__begin::value - 1>, Type<(Length<__list>::result - 1)>>::result result; }; template <typename __list> struct __Slice<__list, Type<0>, Type<(Length<__list>::result)>> { typedef __list result; }; typedef typename __Slice< list, Type<begin >= 0 ? begin : 0>, Type<end <= Length<list>::result ? end : Length<list>::result>>::result result; }; void List_Part() { // typedef List<Type<3>> l3; // typedef List<Type<2>, l3> l2; // typedef List<Type<1>, l2> l1 typedef CreateList<1>::result l1; typedef CreateList<1, 2, 3>::result l2; std::cout << std::endl; std::cout << "l1 = " << ListToString<l1>() << std::endl; std::cout << "l2 = " << ListToString<l2>() << std::endl; std::cout << "lenth(l2) = " << Length<l2>::result << std::endl; std::cout << "itemAt(l2, 2) = " << ItemAt<l2, 2>::result::value << std::endl; std::cout << "insertItemAt(l1, 0, 0) = " << ListToString<InsertItemAt<l1, Type<0>, 0>::result>() << std::endl; std::cout << "insertItemAt(l1, 0, 0) = " << ListToString<InsertItemAt<l1, Type<0>, 0>::result>() << std::endl; std::cout << "removeItemAt(l2, 0) = " << ListToString<RemoveItemAt<l2, 0>::result>() << std::endl; std::cout << "removeItemAt(l2, 2) = " << ListToString<RemoveItemAt<l2, 2>::result>() << std::endl; std::cout << "slice(l2, 0, 3) = " << ListToString<Slice<l2, 0, 3>::result>() << std::endl; std::cout << "slice(l2, 0, 1) = " << ListToString<Slice<l2, 0, 1>::result>() << std::endl; std::cout << "slice(l2, 1, 2) = " << ListToString<Slice<l2, 1, 2>::result>() << std::endl; std::cout << "slice(l2, 1, 3) = " << ListToString<Slice<l2, 1, 3>::result>() << std::endl; std::cout << "slice(l2, 0, 5) = " << ListToString<Slice<l2, 0, 5>::result>() << std::endl; }
26.581921
80
0.617003
oYOvOYo
3b602b77f0155f90729c8040fb3cbb3e94c65dc4
5,472
cpp
C++
src/apps/winforms_app/src/AsyncWrapper.cpp
elnoir/ge_test
a85a6ea95452005c4c6428faa80b1a8b3d4fd6a4
[ "MIT" ]
null
null
null
src/apps/winforms_app/src/AsyncWrapper.cpp
elnoir/ge_test
a85a6ea95452005c4c6428faa80b1a8b3d4fd6a4
[ "MIT" ]
null
null
null
src/apps/winforms_app/src/AsyncWrapper.cpp
elnoir/ge_test
a85a6ea95452005c4c6428faa80b1a8b3d4fd6a4
[ "MIT" ]
null
null
null
#include "AsyncWrapper.h" #include <msclr/marshal_cppstd.h> #include <db/idb.h> namespace annWinForm { using namespace System; ManagedConfusionMatrix deserializeConfusionMatrix(const ann::async::MainMessage::buffer &buffer); int deserializeImageCount(const ann::async::MainMessage::buffer& buffer); TrainSnapshot^ deserializeSnapshot(const ann::async::MainMessage::buffer& buffer); AsyncWrapper::AsyncWrapper() { mController = ann::createController(ann::ControllerType::ASYNC).release(); } bool AsyncWrapper::setDb(System::String^ trainImage, System::String^ trainLabel, System::String^ testImage, System::String^ testLabel) { System::Console::WriteLine("SetDB Called"); std::string sTrainImage = msclr::interop::marshal_as<std::string>(trainImage); std::string sTrainLabel = msclr::interop::marshal_as<std::string>(trainLabel); std::string sTestImage = msclr::interop::marshal_as<std::string>(testImage); std::string sTestLabel = msclr::interop::marshal_as<std::string>(testLabel); auto trainDb = db::createDB(); bool db1_result = trainDb->loadDB(sTrainImage, sTrainLabel); auto testDb = db::createDB(); bool db2_result = testDb->loadDB(sTestImage, sTestLabel); if (db1_result && db2_result) { System::Console::WriteLine("DB load Ok"); mController->setTrainDb(std::move(trainDb)); mController->setTestDb(std::move(testDb)); } return db1_result && db2_result; } void AsyncWrapper::configureNetwork(void) { mController->configureNetwork(); } void AsyncWrapper::startTraining(void) { mController->startTraining(); } void AsyncWrapper::createSnapshot(void) { mController->getTrainingSnapshot(); } void AsyncWrapper::stopTraining(void) { mController->stopTraining(); } void AsyncWrapper::startTest(void) { mController->startTest(); } void AsyncWrapper::stopTest(void) { mController->stopTest(); } void AsyncWrapper::checkMessage(void) { auto result = mController->getAsyncCommand(); while (result) { switch (result->mCommand) { case ann::async::commandToMain::TESTING_FINISHED: { auto confusionMatrix = deserializeConfusionMatrix(result->mBuffer); OnConfusionMatrixArrived(confusionMatrix); } break; case ann::async::commandToMain::TESTING_PROGRESS_STATUS: { auto processedImageCount = deserializeImageCount(result->mBuffer); OnTestStatusUpdate(processedImageCount); } break; case ann::async::commandToMain::TRAINING_SNAPSHOT: { auto snapshot = deserializeSnapshot(result->mBuffer); auto trainDb = mController->getTrainDb(); for (int i = 0; i < snapshot->mImageLabel->Length; ++i) { snapshot->mImageLabel[i] = static_cast<int>(trainDb->getImageLabelAsInt(snapshot->mImageIndex[i])); } OnTrainSnapshotUpdate(snapshot); } break; } result = mController->getAsyncCommand(); } } System::Drawing::Bitmap^ AsyncWrapper::getBitmap(int imageNumber) { auto trainDb = mController->getTrainDb(); auto m = trainDb->getImageMatrix(imageNumber); const auto width = trainDb->getImageWidth(); const auto height = trainDb->getImageHeight(); auto result = gcnew System::Drawing::Bitmap(static_cast<int>(width), static_cast<int>(height)); for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { int value = static_cast<int>(255 * (1.0f - m.get(width * j + i, 0))); System::Drawing::Color c = System::Drawing::Color::FromArgb(value, value, value); result->SetPixel(i, j, c); } } return result; } int deserializeImageCount(const ann::async::MainMessage::buffer &buffer) { int32_t data; std::memcpy(&data, buffer.data(), sizeof(uint32_t)); return data; } ManagedConfusionMatrix deserializeConfusionMatrix(const ann::async::MainMessage::buffer &buffer) { uint32_t rowCount = 0; auto offset = buffer.data(); std::memcpy(&rowCount, offset, sizeof(rowCount)); offset += sizeof(rowCount); ManagedConfusionMatrix result = gcnew array<array< Int32 >^>(rowCount); for (uint32_t i = 0; i < rowCount; ++i) { result[i] = gcnew array< Int32 >(rowCount); for (uint32_t j = 0; j < rowCount; ++j) { uint32_t data; std::memcpy(&data, offset, sizeof(data)); offset += sizeof(data); result[i][j] = data; } } return result; } TrainSnapshot^ deserializeSnapshot(const ann::async::MainMessage::buffer& buffer) { uint32_t itemCount = 0; auto offset = buffer.data(); std::memcpy(&itemCount, offset, sizeof(uint32_t)); offset += sizeof(itemCount); TrainSnapshot^ result = gcnew TrainSnapshot(itemCount); for (int i = 0; i < static_cast<int>(itemCount); ++i) { uint32_t data; std::memcpy(&data, offset, sizeof(data)); offset += sizeof(data); result->mImagePrediction[i] = data; } for (int i = 0; i < static_cast<int>(itemCount); ++i) { uint32_t data; std::memcpy(&data, offset, sizeof(data)); offset += sizeof(data); result->mImageIndex[i] = data; } return result; } }
27.223881
134
0.633224
elnoir
3b60d82b4f76b5c13ba2ceea64f44d34adf7cff2
49,812
cpp
C++
src/graysvr/CItemBase.cpp
mxdamien/Source
5eb008ebbe1a67c33057c033b6920581c4fdc323
[ "Apache-2.0" ]
2
2020-04-24T12:19:13.000Z
2020-04-24T12:19:14.000Z
src/graysvr/CItemBase.cpp
assadcalil/Source
0f303cfc72496576a6eb432615f893e151210e8f
[ "Apache-2.0" ]
null
null
null
src/graysvr/CItemBase.cpp
assadcalil/Source
0f303cfc72496576a6eb432615f893e151210e8f
[ "Apache-2.0" ]
1
2017-05-12T02:56:10.000Z
2017-05-12T02:56:10.000Z
#include "graysvr.h" // predef header. //********************************************************* // CItemBase CItemBase::CItemBase(ITEMID_TYPE id) : CBaseBaseDef(RESOURCE_ID(RES_ITEMDEF, id)) { m_type = IT_NORMAL; m_weight = 0; m_layer = LAYER_NONE; m_uiFlags = 0; m_speed = 0; m_iSkill = SKILL_NONE; m_CanUse = CAN_U_ALL; SetDefNum("RANGE", 1); //m_range = 1; m_StrengthBonus = 0; m_DexterityBonus = 0; m_IntelligenceBonus = 0; m_HitpointIncrease = 0; m_StaminaIncrease = 0; m_ManaIncrease = 0; m_MageArmor = 0; m_MageWeapon = 0; m_ArtifactRarity = 0; m_SelfRepair = 0; m_SpellChanneling = 0; m_LowerRequirements = 0; m_UseBestWeaponSkill = 0; m_HitPhysicalArea = 0; m_HitFireArea = 0; m_HitColdArea = 0; m_HitPoisonArea = 0; m_HitEnergyArea = 0; m_HitDispel = 0; m_HitFireball = 0; m_HitHarm = 0; m_HitLightning = 0; m_HitMagicArrow = 0; m_WeightReduction = 0; m_ttNormal.m_tData1 = 0; m_ttNormal.m_tData2 = 0; m_ttNormal.m_tData3 = 0; m_ttNormal.m_tData4 = 0; if ( !IsValidDispID(id) ) { // There should be an ID= in scripts later m_dwDispIndex = ITEMID_GOLD_C1; return; } m_dwDispIndex = id; // I have it indexed but it needs to be loaded. Read it from the script and *.mul files CUOItemTypeRec2 tiledata; memset(&tiledata, 0, sizeof(tiledata)); if ( id < ITEMID_MULTI ) static_cast<void>(GetItemData(id, &tiledata)); else tiledata.m_weight = BYTE_MAX; m_uiFlags = tiledata.m_flags; m_type = GetTypeBase(id, tiledata); TCHAR szName[sizeof(tiledata.m_name) + 1]; size_t j = 0; for ( size_t i = 0; i < sizeof(tiledata.m_name) && tiledata.m_name[i]; i++ ) { if ( (j == 0) && ISWHITESPACE(tiledata.m_name[i]) ) continue; szName[j++] = tiledata.m_name[i]; } szName[j] = '\0'; m_sName = szName; SetHeight(GetItemHeightFlags(tiledata, m_Can)); GetItemSpecificFlags(tiledata, m_Can, m_type, id); if ( (tiledata.m_weight == BYTE_MAX) || (tiledata.m_flags & UFLAG1_WATER) ) // not movable m_weight = WORD_MAX; else m_weight = tiledata.m_weight * WEIGHT_UNITS; if ( tiledata.m_flags & (UFLAG1_EQUIP|UFLAG3_EQUIP2) ) { m_layer = tiledata.m_layer; if ( m_layer && !IsMovable() ) m_weight = WEIGHT_UNITS; // how I'm supposed to equip something I can't pick up? } SetResDispDnId(ITEMID_GOLD_C1); } CItemBase *CItemBase::FindItemBase(ITEMID_TYPE id) // static { ADDTOCALLSTACK_INTENSIVE("CItemBase::FindItemBase"); if ( id <= ITEMID_NOTHING ) return NULL; RESOURCE_ID rid = RESOURCE_ID(RES_ITEMDEF, id); size_t index = g_Cfg.m_ResHash.FindKey(rid); if ( index == g_Cfg.m_ResHash.BadIndex() ) return NULL; CResourceDef *pBaseStub = g_Cfg.m_ResHash.GetAt(rid, index); ASSERT(pBaseStub); CItemBase *pBase = dynamic_cast<CItemBase *>(pBaseStub); if ( pBase ) return pBase; // already loaded all base info const CItemBaseDupe *pBaseDupe = dynamic_cast<const CItemBaseDupe *>(pBaseStub); if ( pBaseDupe ) return pBaseDupe->GetItemDef(); // this is just a DupeItem CResourceLink *pBaseLink = static_cast<CResourceLink *>(pBaseStub); ASSERT(pBaseLink); pBase = new CItemBase(id); pBase->CResourceLink::CopyTransfer(pBaseLink); g_Cfg.m_ResHash.SetAt(rid, index, pBase); // replace with new in sorted order // Find the previous one in the series if any // Find it's script section offset CResourceLock s; if ( !pBase->ResourceLock(s) ) { g_Log.Event(LOGL_ERROR, "Un-scripted item 0%x not allowed\n", id); return NULL; } // Scan the item definition for keywords such as DUPEITEM and MULTIREGION, as these will adjust how our definition is processed CScriptLineContext scriptStartContext = s.GetContext(); while ( s.ReadKeyParse() ) { if ( s.IsKey("DUPEITEM") ) return MakeDupeReplacement(pBase, static_cast<ITEMID_TYPE>(g_Cfg.ResourceGetIndexType(RES_ITEMDEF, s.GetArgStr()))); if ( s.IsKey("MULTIREGION") ) { pBase = CItemBaseMulti::MakeMultiRegion(pBase, s); // change CItemBase::pBase to CItemBaseMulti continue; } if ( s.IsKeyHead("ON", 2) ) // trigger scripting marks the end break; if ( s.IsKey("ID") || s.IsKey("TYPE") ) // these are required to make CItemBaseMulti::MakeMultiRegion work properly pBase->r_LoadVal(s); } // Return to the start of the item script s.SeekContext(scriptStartContext); // Read the script file preliminary while ( s.ReadKeyParse() ) { if ( s.IsKey("DUPEITEM") || s.IsKey("MULTIREGION") ) continue; if ( s.IsKeyHead("ON", 2) ) // trigger scripting marks the end break; pBase->r_LoadVal(s); } return pBase; } void CItemBase::CopyBasic(const CItemBase *pItemDef) { ADDTOCALLSTACK("CItemBase::CopyBasic"); m_speed = pItemDef->m_speed; m_weight = pItemDef->m_weight; m_flip_id = pItemDef->m_flip_id; m_type = pItemDef->m_type; m_layer = pItemDef->m_layer; SetDefNum("RANGE", pItemDef->GetDefNum("RANGE")); // m_range = pBase->m_range; m_ttNormal.m_tData1 = pItemDef->m_ttNormal.m_tData1; m_ttNormal.m_tData2 = pItemDef->m_ttNormal.m_tData2; m_ttNormal.m_tData3 = pItemDef->m_ttNormal.m_tData3; m_ttNormal.m_tData4 = pItemDef->m_ttNormal.m_tData4; CBaseBaseDef::CopyBasic(pItemDef); // this will overwrite CResourceLink } void CItemBase::CopyTransfer(CItemBase *pItemDef) { ADDTOCALLSTACK("CItemBase::CopyTransfer"); CopyBasic(pItemDef); m_values = pItemDef->m_values; m_SkillMake = pItemDef->m_SkillMake; CBaseBaseDef::CopyTransfer(pItemDef); // this will overwrite the CResourceLink } void CItemBase::SetTypeName(LPCTSTR pszName) { ADDTOCALLSTACK("CItemBase::SetTypeName"); ASSERT(pszName); if ( !strcmp(pszName, GetTypeName()) ) return; m_uiFlags |= UFLAG2_ZERO1; // we override the name CBaseBaseDef::SetTypeName(pszName); } LPCTSTR CItemBase::GetArticleAndSpace() const { ADDTOCALLSTACK("CItemBase::GetArticleAndSpace"); if ( IsSetOF(OF_NoPrefix) ) return ""; if ( m_uiFlags & UFLAG2_ZERO1 ) // name has been changed from tiledata.mul return Str_GetArticleAndSpace(GetTypeName()); if ( m_uiFlags & UFLAG2_AN ) return "an "; if ( m_uiFlags & UFLAG2_A ) return "a "; return ""; } TCHAR *CItemBase::GetNamePluralize(LPCTSTR pszNameBase, bool fPluralize) // static { ADDTOCALLSTACK("CItemBase::GetNamePluralize"); // Get rid of the strange %s type stuff for pluralize rules of names TCHAR *pszName = Str_GetTemp(); size_t j = 0; bool fInside = false; bool fPlural = false; for ( size_t i = 0; pszNameBase[i]; i++ ) { if ( pszNameBase[i] == '%' ) { fInside = !fInside; fPlural = true; continue; } if ( fInside ) { if ( pszNameBase[i] == '/' ) { fPlural = false; continue; } if ( fPluralize ) { if ( !fPlural ) continue; } else { if ( fPlural ) continue; } } pszName[j++] = pszNameBase[i]; } pszName[j] = '\0'; return pszName; } CREID_TYPE CItemBase::FindCharTrack(ITEMID_TYPE id) // static { ADDTOCALLSTACK("CItemBase::FindCharTrack"); // For figurines. Convert to a creature // IT_FIGURINE // IT_EQ_HORSE CItemBase *pItemDef = FindItemBase(id); if ( pItemDef && (pItemDef->IsType(IT_FIGURINE) || pItemDef->IsType(IT_EQ_HORSE)) ) return static_cast<CREID_TYPE>(pItemDef->m_ttFigurine.m_charid.GetResIndex()); return CREID_INVALID; } bool CItemBase::IsTypeArmor(IT_TYPE type) // static { ADDTOCALLSTACK("CItemBase::IsTypeArmor"); switch ( type ) { case IT_CLOTHING: case IT_ARMOR: case IT_ARMOR_LEATHER: case IT_SHIELD: return true; default: return false; } } bool CItemBase::IsTypeWeapon(IT_TYPE type) // static { ADDTOCALLSTACK("CItemBase::IsTypeWeapon"); switch ( type ) { case IT_WEAPON_MACE_STAFF: case IT_WEAPON_MACE_CROOK: case IT_WEAPON_MACE_PICK: case IT_WEAPON_AXE: case IT_WEAPON_XBOW: case IT_WEAPON_THROWING: case IT_WEAPON_MACE_SMITH: case IT_WEAPON_MACE_SHARP: case IT_WEAPON_SWORD: case IT_WEAPON_FENCE: case IT_WEAPON_BOW: case IT_WEAPON_WHIP: case IT_WAND: return true; default: return false; } } bool CItemBase::IsTypeSpellbook(IT_TYPE type) // static { ADDTOCALLSTACK("CItemBase::IsTypeSpellbook"); switch ( type ) { case IT_SPELLBOOK: case IT_SPELLBOOK_NECRO: case IT_SPELLBOOK_PALA: case IT_SPELLBOOK_EXTRA: case IT_SPELLBOOK_BUSHIDO: case IT_SPELLBOOK_NINJITSU: case IT_SPELLBOOK_ARCANIST: case IT_SPELLBOOK_MYSTIC: case IT_SPELLBOOK_MASTERY: return true; default: return false; } } bool CItemBase::IsTypeMulti(IT_TYPE type) // static { ADDTOCALLSTACK("CItemBase::IsTypeMulti"); switch ( type ) { case IT_MULTI: case IT_MULTI_CUSTOM: case IT_SHIP: return true; default: return false; } } bool CItemBase::IsTypeEquippable() const { ADDTOCALLSTACK("CItemBase::IsTypeEquippable"); // Check visible layers switch ( m_type ) { case IT_LIGHT_LIT: case IT_LIGHT_OUT: case IT_HAIR: case IT_BEARD: case IT_EQ_HORSE: case IT_FISH_POLE: case IT_JEWELRY: return true; default: break; } if ( IsTypeArmor(m_type) ) return true; if ( IsTypeWeapon(m_type) ) return true; if ( IsTypeSpellbook(m_type) ) return true; // Check not visible layers switch ( m_type ) { case IT_EQ_TRADE_WINDOW: case IT_EQ_MEMORY_OBJ: case IT_EQ_CLIENT_LINGER: case IT_EQ_VENDOR_BOX: case IT_EQ_BANK_BOX: case IT_EQ_MURDER_COUNT: case IT_EQ_STUCK: case IT_EQ_SCRIPT: return !IsVisibleLayer(static_cast<LAYER_TYPE>(m_layer)); default: break; } return false; } int CItemBase::IsID_Door(ITEMID_TYPE id) // static { ADDTOCALLSTACK("CItemBase::IsID_Door"); // IT_DOOR // IT_DOOR_LOCKED static const ITEMID_TYPE sm_Item_DoorBase[] = { ITEMID_DOOR_SECRET_STONE_1, ITEMID_DOOR_SECRET_STONE_2, ITEMID_DOOR_SECRET_STONE_3, ITEMID_DOOR_SECRET_WOOD_1, ITEMID_DOOR_SECRET_WOOD_2, ITEMID_DOOR_SECRET_STONE_4, ITEMID_DOOR_METAL_1, ITEMID_DOOR_METAL_BARRED_1, ITEMID_DOOR_RATTAN, ITEMID_DOOR_WOODEN_1, ITEMID_DOOR_WOODEN_2, ITEMID_DOOR_METAL_2, ITEMID_DOOR_WOODEN_3, ITEMID_DOOR_WOODEN_4, ITEMID_GATE_IRON_1, ITEMID_GATE_WOODEN_1, ITEMID_GATE_IRON_2, ITEMID_GATE_WOODEN_2, ITEMID_DOOR_METAL_BARRED_2 }; for ( size_t i = 0; i < COUNTOF(sm_Item_DoorBase); ++i ) { int iDoorId = id - sm_Item_DoorBase[i]; if ( (iDoorId >= 0) && (iDoorId <= 15) ) return iDoorId + 1; } return 0; } bool CItemBase::IsID_DoorOpen(ITEMID_TYPE id) // static { ADDTOCALLSTACK("CItemBase::IsID_DoorOpen"); int iDoorDir = IsID_Door(id) - 1; if ( iDoorDir < 0 ) return false; if ( iDoorDir & DOOR_OPENED ) return true; return false; } bool CItemBase::GetItemData(ITEMID_TYPE id, CUOItemTypeRec2 *pTiledata) // static { ADDTOCALLSTACK("CItemBase::GetItemData"); // Read from g_Install.m_fTileData // Get an Item tiledata def data if ( !IsValidDispID(id) ) return false; try { CGrayItemInfo info(id); *pTiledata = *(static_cast<CUOItemTypeRec2 *>(&info)); } catch ( const CGrayError &e ) { g_Log.CatchEvent(&e, "GetItemData"); CurrentProfileData.Count(PROFILE_STAT_FAULTS, 1); return false; } catch ( ... ) { g_Log.CatchEvent(NULL, "GetItemData"); CurrentProfileData.Count(PROFILE_STAT_FAULTS, 1); return false; } // Unused tiledata I guess. Don't create it if ( !pTiledata->m_flags && !pTiledata->m_weight && !pTiledata->m_layer && !pTiledata->m_dwUnk11 && !pTiledata->m_wAnim && !pTiledata->m_wHue && !pTiledata->m_wLight && !pTiledata->m_height && !pTiledata->m_name[0] ) return ((id == ITEMID_BBOARD_MSG) || IsID_GamePiece(id) || IsID_Track(id)); // what are the exceptions to the rule? return true; } inline void CItemBase::GetItemSpecificFlags(const CUOItemTypeRec2 &tiledata, DWORD &dwBlockThis, IT_TYPE type, ITEMID_TYPE id) // static { ADDTOCALLSTACK("CItemBase::GetItemSpecificFlags"); if ( type == IT_DOOR ) { dwBlockThis &= ~CAN_I_BLOCK; if ( IsID_DoorOpen(id) ) dwBlockThis &= ~CAN_I_DOOR; else dwBlockThis |= CAN_I_DOOR; } if ( (tiledata.m_flags & UFLAG2_STACKABLE) || (type == IT_REAGENT) || (id == ITEMID_EMPTY_BOTTLE) ) dwBlockThis |= CAN_I_PILE; if ( tiledata.m_flags & UFLAG3_LIGHT ) dwBlockThis |= CAN_I_LIGHT; } void CItemBase::GetItemTiledataFlags(DWORD &dwBlockThis, ITEMID_TYPE id) // static { ADDTOCALLSTACK("CItemBase::GetItemTiledataFlags"); CUOItemTypeRec2 tiledata; memset(&tiledata, 0, sizeof(tiledata)); if ( !GetItemData(id, &tiledata) ) { dwBlockThis = 0; return; } if ( tiledata.m_flags & UFLAG4_DOOR ) dwBlockThis |= CAN_I_DOOR; if ( tiledata.m_flags & UFLAG1_WATER ) dwBlockThis |= CAN_I_WATER; if ( tiledata.m_flags & UFLAG2_PLATFORM ) dwBlockThis |= CAN_I_PLATFORM; if ( tiledata.m_flags & UFLAG1_BLOCK ) dwBlockThis |= CAN_I_BLOCK; if ( tiledata.m_flags & UFLAG2_CLIMBABLE ) dwBlockThis |= CAN_I_CLIMB; if ( tiledata.m_flags & UFLAG1_DAMAGE ) dwBlockThis |= CAN_I_FIRE; if ( tiledata.m_flags & UFLAG4_ROOF ) dwBlockThis |= CAN_I_ROOF; if ( tiledata.m_flags & UFLAG4_HOVEROVER ) dwBlockThis |= CAN_I_HOVER; } inline height_t CItemBase::GetItemHeightFlags(const CUOItemTypeRec2 &tiledata, DWORD &dwBlockThis) // static { ADDTOCALLSTACK("CItemBase::GetItemHeightFlags"); if ( tiledata.m_flags & UFLAG4_DOOR ) { dwBlockThis = CAN_I_DOOR; return tiledata.m_height; } if ( tiledata.m_flags & UFLAG1_BLOCK ) { if ( tiledata.m_flags & UFLAG1_WATER ) { dwBlockThis = CAN_I_WATER; return tiledata.m_height; } dwBlockThis = CAN_I_BLOCK; } else { dwBlockThis = 0; if ( !(tiledata.m_flags & (UFLAG2_PLATFORM|UFLAG4_ROOF|UFLAG4_HOVEROVER)) ) return 0; // have no effective height if it doesn't block } if ( tiledata.m_flags & UFLAG4_ROOF ) dwBlockThis |= CAN_I_ROOF; else if ( tiledata.m_flags & UFLAG2_PLATFORM ) dwBlockThis |= CAN_I_PLATFORM; if ( tiledata.m_flags & UFLAG2_CLIMBABLE ) dwBlockThis |= CAN_I_CLIMB; // actual standing height is height/2 if ( tiledata.m_flags & UFLAG4_HOVEROVER ) dwBlockThis |= CAN_I_HOVER; return tiledata.m_height; } height_t CItemBase::GetItemHeight(ITEMID_TYPE id, DWORD &dwBlockThis) // static { ADDTOCALLSTACK("CItemBase::GetItemHeight"); // Get just the height and the blocking flags for the item by id // Used for walk block checking RESOURCE_ID rid = RESOURCE_ID(RES_ITEMDEF, id); size_t index = g_Cfg.m_ResHash.FindKey(rid); if ( index != g_Cfg.m_ResHash.BadIndex() ) // already loaded { CResourceDef *pBaseStub = g_Cfg.m_ResHash.GetAt(rid, index); ASSERT(pBaseStub); CItemBase *pBase = dynamic_cast<CItemBase *>(pBaseStub); if ( pBase ) { dwBlockThis = pBase->m_Can & CAN_I_MOVEMASK; return pBase->GetHeight(); } } // Not already loaded CUOItemTypeRec2 tiledata; if ( !GetItemData(id, &tiledata) ) { dwBlockThis = CAN_I_MOVEMASK; return UO_SIZE_Z; } return GetItemHeightFlags(tiledata, dwBlockThis); } IT_TYPE CItemBase::GetTypeBase(ITEMID_TYPE id, const CUOItemTypeRec2 &tiledata) // static { ADDTOCALLSTACK("CItemBase::GetTypeBase"); if ( IsID_Ship(id) ) return IT_SHIP; if ( IsID_Multi(id) ) return IT_MULTI; if ( (tiledata.m_flags & UFLAG1_BLOCK) && (tiledata.m_flags & UFLAG1_WATER) ) return IT_WATER; if ( IsID_WaterFish(id) ) // UFLAG1_WATER return IT_WATER; if ( (tiledata.m_flags & UFLAG4_DOOR) || IsID_Door(id) ) { if ( IsID_DoorOpen(id) ) return IT_DOOR_OPEN; return IT_DOOR; } if ( tiledata.m_flags & UFLAG3_CONTAINER ) return IT_CONTAINER; if ( IsID_WaterWash(id) ) return IT_WATER_WASH; else if ( IsID_Track(id) ) return IT_FIGURINE; else if ( IsID_GamePiece(id) ) return IT_GAME_PIECE; // Get rid of the stuff below here if ( (tiledata.m_flags & UFLAG1_DAMAGE) && !(tiledata.m_flags & UFLAG1_BLOCK) ) return IT_TRAP_ACTIVE; if ( tiledata.m_flags & UFLAG3_LIGHT ) // this may actually be a moongate or fire? return IT_LIGHT_LIT; return IT_NORMAL; } GUMP_TYPE CItemBase::GetContainerGumpID() const { ADDTOCALLSTACK("CItemBase::GetContainerGumpID"); switch ( m_type ) { case IT_CONTAINER: case IT_CONTAINER_LOCKED: case IT_SIGN_GUMP: case IT_GAME_BOARD: case IT_TRASH_CAN: case IT_BBOARD: case IT_CORPSE: case IT_EQ_VENDOR_BOX: case IT_EQ_BANK_BOX: case IT_KEYRING: case IT_SHIP_HOLD: case IT_SHIP_HOLD_LOCK: return m_ttContainer.m_gumpid; default: return GUMP_NONE; } } ITEMID_TYPE CItemBase::GetNextFlipID(ITEMID_TYPE id) const { ADDTOCALLSTACK("CItemBase::GetNextFlipID"); if ( m_flip_id.GetCount() > 0 ) { ITEMID_TYPE idprev = GetDispID(); for ( size_t i = 0; i < m_flip_id.GetCount(); i++ ) { ITEMID_TYPE idnext = m_flip_id[i]; if ( idprev == id ) return idnext; idprev = idnext; } } return GetDispID(); } bool CItemBase::IsSameDispID(ITEMID_TYPE id) const { ADDTOCALLSTACK("CItemBase::IsSameDispID"); // Check if item dispid is the same as the requested if ( GetDispID() == id ) return true; for ( size_t i = 0; i < m_flip_id.GetCount(); i++ ) { if ( m_flip_id[i] == id ) return true; } return false; } void CItemBase::Restock() { ADDTOCALLSTACK("CItemBase::Restock"); // Re-evaluate the base random value rate some time in the future if ( (m_values.m_iLo < 0) || (m_values.m_iHi < 0) ) m_values.Init(); } DWORD CItemBase::CalculateMakeValue(int iQualityLevel) const { ADDTOCALLSTACK("CItemBase::CalculateMakeValue"); // Calculate the value in gold for this item based on its components // NOTE: Watch out for circular RESOURCES= list in the scripts // ARGS: // iQualityLevel = 0-100 static int sm_iReentrantCount = 0; if ( sm_iReentrantCount > 32 ) { DEBUG_ERR(("Too many RESOURCES at item '%s' to calculate a value with (circular resource list?)\n", GetResourceName())); return 0; } sm_iReentrantCount++; DWORD dwValue = 0; // Add value based on base resources for ( size_t i = 0; i < m_BaseResources.GetCount(); i++ ) { RESOURCE_ID rid = m_BaseResources[i].GetResourceID(); if ( rid.GetResType() != RES_ITEMDEF ) continue; CItemBase *pItemDef = FindItemBase(static_cast<ITEMID_TYPE>(rid.GetResIndex())); if ( !pItemDef ) continue; dwValue += pItemDef->GetMakeValue(iQualityLevel) * static_cast<DWORD>(m_BaseResources[i].GetResQty()); } // Add some value based on the skill required to craft it for ( size_t i = 0; i < m_SkillMake.GetCount(); i++ ) { RESOURCE_ID rid = m_SkillMake[i].GetResourceID(); if ( rid.GetResType() != RES_SKILL ) continue; const CSkillDef *pSkillDef = g_Cfg.GetSkillDef(static_cast<SKILL_TYPE>(rid.GetResIndex())); if ( !pSkillDef ) continue; // This is the normal skill required. If iQuality is much less than iSkillReq then something is wrong int iSkillReq = m_SkillMake[i].GetResQty(); if ( iQualityLevel < iSkillReq ) iQualityLevel = iSkillReq; dwValue += pSkillDef->m_Values.GetLinear(iQualityLevel); } sm_iReentrantCount--; return dwValue; } BYTE CItemBase::GetSpeed() const { ADDTOCALLSTACK("CItemBase::GetSpeed"); BYTE iSpeed = static_cast<BYTE>(m_TagDefs.GetKeyNum("OVERRIDE.SPEED")); return iSpeed ? iSpeed : m_speed; } WORD CItemBase::GetMaxAmount() { ADDTOCALLSTACK("CItemBase::GetMaxAmount"); if ( !IsStackableType() ) return 0; WORD wMax = static_cast<WORD>(GetDefNum("MaxAmount")); return wMax ? wMax : g_Cfg.m_iItemsMaxAmount; }; bool CItemBase::SetMaxAmount(WORD wAmount) { ADDTOCALLSTACK("CItemBase::SetMaxAmount"); if ( !IsStackableType() ) return false; SetDefNum("MaxAmount", wAmount, false); return true; } DWORD CItemBase::GetMakeValue(int iQualityLevel) { ADDTOCALLSTACK("CItemBase::GetMakeValue"); // Set the items value based on the resources and skill used to craft it // ARGS: // iQualityLevel = 0-100 CValueRangeDef values = m_values; if ( (m_values.m_iLo == LLONG_MIN) || (m_values.m_iHi == LLONG_MIN) ) { values.m_iLo = CalculateMakeValue(0); // low quality specimen m_values.m_iLo = -values.m_iLo; // negative means they will float values.m_iHi = CalculateMakeValue(100); // top quality specimen m_values.m_iHi = -values.m_iHi; } else { values.m_iLo = llabs(values.m_iLo); values.m_iHi = llabs(values.m_iHi); } return static_cast<DWORD>(values.GetLinear(iQualityLevel * 10)); } void CItemBase::ResetMakeValue() { ADDTOCALLSTACK("CItemBase::ResetMakeValue"); m_values.Init(); GetMakeValue(0); } enum IBC_TYPE { #define ADD(a,b) IBC_##a, #include "../tables/CItemBase_props.tbl" #undef ADD IBC_QTY }; const LPCTSTR CItemBase::sm_szLoadKeys[IBC_QTY + 1] = { #define ADD(a,b) b, #include "../tables/CItemBase_props.tbl" #undef ADD NULL }; bool CItemBase::r_WriteVal(LPCTSTR pszKey, CGString &sVal, CTextConsole *pSrc) { ADDTOCALLSTACK("CItemBase::r_WriteVal"); EXC_TRY("WriteVal"); switch ( FindTableHeadSorted(pszKey, sm_szLoadKeys, COUNTOF(sm_szLoadKeys) - 1) ) { // Return as string or hex number (NULL if not set) case IBC_AMMOANIM: case IBC_AMMOANIMHUE: case IBC_AMMOANIMRENDER: case IBC_AMMOCONT: case IBC_AMMOTYPE: case IBC_AMMOSOUNDHIT: case IBC_AMMOSOUNDMISS: case IBC_DROPSOUND: case IBC_EQUIPSOUND: case IBC_BONUSSKILL1: case IBC_BONUSSKILL2: case IBC_BONUSSKILL3: case IBC_BONUSSKILL4: case IBC_BONUSSKILL5: case IBC_OCOLOR: sVal = GetDefStr(pszKey); break; // Return as decimal number (0 if not set) case IBC_BONUSSKILL1AMT: case IBC_BONUSSKILL2AMT: case IBC_BONUSSKILL3AMT: case IBC_BONUSSKILL4AMT: case IBC_BONUSSKILL5AMT: case IBC_LIFESPAN: case IBC_USESCUR: case IBC_USESMAX: case IBC_BONUSHITSMAX: case IBC_BONUSSTAMMAX: case IBC_BONUSMANAMAX: sVal.FormatLLVal(GetDefNum(pszKey)); break; case IBC_MAXAMOUNT: sVal.FormatVal(GetMaxAmount()); break; case IBC_SPEEDMODE: { if ( !IsType(IT_SHIP) ) return false; CItemBaseMulti *pItemMulti = dynamic_cast<CItemBaseMulti *>(this); if ( !pItemMulti ) return false; sVal.FormatVal(pItemMulti->m_SpeedMode); break; } case IBC_SHIPSPEED: { if ( !IsType(IT_SHIP) ) return false; CItemBaseMulti *pItemMulti = dynamic_cast<CItemBaseMulti *>(this); if ( !pItemMulti ) return false; pszKey += 9; if ( *pszKey == '.' ) { pszKey++; if ( !strcmpi(pszKey, "TILES") ) { sVal.FormatVal(pItemMulti->m_shipSpeed.tiles); break; } else if ( !strcmpi(pszKey, "PERIOD") ) { sVal.FormatVal(pItemMulti->m_shipSpeed.period); break; } return false; } sVal.Format("%hhu,%hhu", pItemMulti->m_shipSpeed.period, pItemMulti->m_shipSpeed.tiles); break; } case IBC_DISPID: sVal = g_Cfg.ResourceGetName(RESOURCE_ID(RES_ITEMDEF, GetDispID())); break; case IBC_DUPELIST: { TCHAR *pszTemp = Str_GetTemp(); size_t iLen = 0; *pszTemp = '\0'; for ( size_t i = 0; i < m_flip_id.GetCount(); i++ ) { if ( i > 0 ) iLen += strcpylen(pszTemp + iLen, ","); iLen += sprintf(pszTemp + iLen, "0%x", static_cast<unsigned int>(m_flip_id[i])); ASSERT(iLen < SCRIPT_MAX_LINE_LEN); } sVal = pszTemp; break; } case IBC_BONUSSTR: sVal.FormatVal(m_StrengthBonus); break; case IBC_BONUSDEX: sVal.FormatVal(m_DexterityBonus); break; case IBC_BONUSINT: sVal.FormatVal(m_IntelligenceBonus); break; case IBC_BONUSHITS: sVal.FormatVal(m_HitpointIncrease); break; case IBC_BONUSSTAM: sVal.FormatVal(m_StaminaIncrease); break; case IBC_BONUSMANA: sVal.FormatVal(m_ManaIncrease); break; case IBC_MAGEARMOR: sVal.FormatVal(m_MageArmor); break; case IBC_MAGEWEAPON: sVal.FormatVal(m_MageWeapon); break; case IBC_RARITY: sVal.FormatVal(m_ArtifactRarity); break; case IBC_SELFREPAIR: sVal.FormatVal(m_SelfRepair); break; case IBC_SPELLCHANNELING: sVal.FormatVal(m_SpellChanneling); break; case IBC_LOWERREQ: sVal.FormatVal(m_LowerRequirements); break; case IBC_USEBESTWEAPONSKILL: sVal.FormatVal(m_UseBestWeaponSkill); break; case IBC_HITAREAPHYSICAL: sVal.FormatVal(m_HitPhysicalArea); break; case IBC_HITAREAFIRE: sVal.FormatVal(m_HitFireArea); break; case IBC_HITAREACOLD: sVal.FormatVal(m_HitColdArea); break; case IBC_HITAREAPOISON: sVal.FormatVal(m_HitPoisonArea); break; case IBC_HITAREAENERGY: sVal.FormatVal(m_HitEnergyArea); break; case IBC_HITDISPEL: sVal.FormatVal(m_HitDispel); break; case IBC_HITFIREBALL: sVal.FormatVal(m_HitFireball); break; case IBC_HITHARM: sVal.FormatVal(m_HitHarm); break; case IBC_HITLIGHTNING: sVal.FormatVal(m_HitLightning); break; case IBC_HITMAGICARROW: sVal.FormatVal(m_HitMagicArrow); break; case IBC_WEIGHTREDUCTION: sVal.FormatVal(m_WeightReduction); break; case IBC_CANUSE: sVal.FormatHex(m_CanUse); break; case IBC_DYE: sVal.FormatVal((m_Can & CAN_I_DYE) ? true : false); break; case IBC_ENCHANT: sVal.FormatVal((m_Can & CAN_I_ENCHANT) ? true : false); break; case IBC_EXCEPTIONAL: sVal.FormatVal((m_Can & CAN_I_EXCEPTIONAL) ? true : false); break; case IBC_FLIP: sVal.FormatHex((m_Can & CAN_I_FLIP) ? true : false); break; case IBC_ID: sVal.FormatHex(GetDispID()); break; case IBC_IMBUE: sVal.FormatVal((m_Can & CAN_I_IMBUE) ? true : false); break; case IBC_ISARMOR: sVal.FormatVal(IsTypeArmor(m_type)); break; case IBC_ISWEAPON: sVal.FormatVal(IsTypeWeapon(m_type)); break; case IBC_MAKERSMARK: sVal.FormatVal((m_Can & CAN_I_MAKERSMARK) ? true : false); break; case IBC_RECYCLE: sVal.FormatVal((m_Can & CAN_I_RECYCLE) ? true : false); break; case IBC_REFORGE: sVal.FormatVal((m_Can & CAN_I_REFORGE) ? true : false); break; case IBC_RETAINCOLOR: sVal.FormatVal((m_Can & CAN_I_RETAINCOLOR) ? true : false); break; case IBC_SKILL: { if ( (m_iSkill > SKILL_NONE) && (m_iSkill < static_cast<SKILL_TYPE>(g_Cfg.m_iMaxSkill)) ) { sVal.FormatVal(m_iSkill); break; } SKILL_TYPE skill; switch ( GetType() ) { case IT_WEAPON_BOW: case IT_WEAPON_XBOW: skill = SKILL_ARCHERY; break; case IT_WEAPON_SWORD: case IT_WEAPON_AXE: skill = SKILL_SWORDSMANSHIP; break; case IT_WEAPON_MACE_SMITH: case IT_WEAPON_MACE_SHARP: case IT_WEAPON_MACE_STAFF: case IT_WEAPON_MACE_CROOK: case IT_WEAPON_MACE_PICK: case IT_WEAPON_WHIP: skill = SKILL_MACEFIGHTING; break; case IT_WEAPON_FENCE: skill = SKILL_FENCING; break; case IT_WEAPON_THROWING: skill = SKILL_THROWING; break; default: skill = SKILL_NONE; break; } sVal.FormatVal(skill); break; } case IBC_LAYER: sVal.FormatVal(m_layer); break; case IBC_REPAIR: sVal.FormatHex((m_Can & CAN_I_REPAIR) ? true : false); break; case IBC_REPLICATE: sVal.FormatHex((m_Can & CAN_I_REPLICATE) ? true : false); break; case IBC_REQSTR: sVal.FormatVal(m_ttEquippable.m_StrReq); break; case IBC_SKILLMAKE: { pszKey += 9; if ( *pszKey == '.' ) { SKIP_SEPARATORS(pszKey); int index = Exp_GetVal(pszKey); SKIP_SEPARATORS(pszKey); bool fQtyOnly = false; bool fKeyOnly = false; if ( !strnicmp(pszKey, "KEY", 3) ) fKeyOnly = true; else if ( !strnicmp(pszKey, "VAL", 3) ) fQtyOnly = true; TCHAR *pszTmp = Str_GetTemp(); if ( fKeyOnly || fQtyOnly ) m_SkillMake.WriteKeys(pszTmp, index, fQtyOnly, fKeyOnly); else m_SkillMake.WriteNames(pszTmp, index); if ( fQtyOnly && (pszTmp[0] == '\0') ) strcpy(pszTmp, "0"); sVal = pszTmp; } else { TCHAR *pszTmp = Str_GetTemp(); m_SkillMake.WriteNames(pszTmp); sVal = pszTmp; } break; } case IBC_RESDISPDNID: sVal = g_Cfg.ResourceGetName(RESOURCE_ID(RES_TYPEDEF, GetResDispDnId())); break; case IBC_RESMAKE: { TCHAR *pszTmp = Str_GetTemp(); m_BaseResources.WriteNames(pszTmp); sVal = pszTmp; break; } case IBC_SPEED: sVal.FormatVal(m_speed); break; case IBC_TDATA1: sVal.FormatHex(m_ttNormal.m_tData1); break; case IBC_TDATA2: sVal.FormatHex(m_ttNormal.m_tData2); break; case IBC_TDATA3: sVal.FormatHex(m_ttNormal.m_tData3); break; case IBC_TDATA4: sVal.FormatHex(m_ttNormal.m_tData4); break; case IBC_TFLAGS: sVal.FormatULLHex(GetTFlags()); break; case IBC_TWOHANDS: if ( !IsTypeEquippable() ) return false; if ( !IsTypeWeapon(GetType()) && !IsType(IT_FISH_POLE) ) sVal.FormatVal(0); else sVal.FormatVal(m_layer == LAYER_HAND2); break; case IBC_TYPE: { RESOURCE_ID rid(RES_TYPEDEF, m_type); CResourceDef *pRes = g_Cfg.ResourceGetDef(rid); if ( !pRes ) sVal.FormatVal(m_type); else sVal = pRes->GetResourceName(); break; } case IBC_VALUE: if ( m_values.GetRange() ) sVal.Format("%" FMTDWORD ",%" FMTDWORD, GetMakeValue(0), GetMakeValue(100)); else sVal.Format("%" FMTDWORD, GetMakeValue(0)); break; case IBC_WEIGHT: sVal.FormatVal(m_weight / WEIGHT_UNITS); break; default: return CBaseBaseDef::r_WriteVal(pszKey, sVal); } return true; EXC_CATCH; EXC_DEBUG_START; EXC_ADD_KEYRET(pSrc); EXC_DEBUG_END; return false; } bool CItemBase::r_LoadVal(CScript &s) { ADDTOCALLSTACK("CItemBase::r_LoadVal"); EXC_TRY("LoadVal"); LPCTSTR pszKey = s.GetKey(); switch ( FindTableSorted(s.GetKey(), sm_szLoadKeys, COUNTOF(sm_szLoadKeys) - 1) ) { // Set as string case IBC_AMMOANIM: case IBC_AMMOANIMHUE: case IBC_AMMOANIMRENDER: case IBC_AMMOCONT: case IBC_AMMOTYPE: case IBC_AMMOSOUNDHIT: case IBC_AMMOSOUNDMISS: case IBC_DROPSOUND: case IBC_EQUIPSOUND: case IBC_BONUSSKILL1: case IBC_BONUSSKILL2: case IBC_BONUSSKILL3: case IBC_BONUSSKILL4: case IBC_BONUSSKILL5: case IBC_OCOLOR: { bool fQuoted = false; SetDefStr(s.GetKey(), s.GetArgStr(&fQuoted), fQuoted); break; } // Set as numeric case IBC_BONUSSKILL1AMT: case IBC_BONUSSKILL2AMT: case IBC_BONUSSKILL3AMT: case IBC_BONUSSKILL4AMT: case IBC_BONUSSKILL5AMT: case IBC_LIFESPAN: case IBC_USESCUR: case IBC_USESMAX: case IBC_BONUSHITSMAX: case IBC_BONUSSTAMMAX: case IBC_BONUSMANAMAX: SetDefNum(s.GetKey(), s.GetArgVal(), false); break; case IBC_MAXAMOUNT: if ( !SetMaxAmount(static_cast<WORD>(s.GetArgVal())) ) return false; break; case IBC_SPEEDMODE: { if ( !IsType(IT_SHIP) ) return false; CItemBaseMulti *pItemMulti = dynamic_cast<CItemBaseMulti *>(this); if ( !pItemMulti ) return false; BYTE bVal = static_cast<BYTE>(s.GetArgVal()); pItemMulti->m_SpeedMode = minimum(maximum(1, bVal), 4); break; } case IBC_SHIPSPEED: { pszKey += 9; if ( *pszKey == '.' ) { pszKey++; if ( !IsType(IT_SHIP) ) return false; CItemBaseMulti *pItemMulti = dynamic_cast<CItemBaseMulti *>(this); if ( !pItemMulti ) return false; if ( !strcmpi(pszKey, "TILES") ) { pItemMulti->m_shipSpeed.tiles = static_cast<BYTE>(s.GetArgVal()); return true; } else if ( !strcmpi(pszKey, "PERIOD") ) { pItemMulti->m_shipSpeed.tiles = static_cast<BYTE>(s.GetArgVal()); return true; } INT64 piVal[2]; size_t iQty = Str_ParseCmds(s.GetArgStr(), piVal, COUNTOF(piVal)); if ( iQty == 2 ) { pItemMulti->m_shipSpeed.period = static_cast<BYTE>(piVal[0]); pItemMulti->m_shipSpeed.tiles = static_cast<BYTE>(piVal[1]); return true; } return false; } break; } case IBC_BONUSSTR: m_StrengthBonus = static_cast<int>(s.GetArgVal()); break; case IBC_BONUSDEX: m_DexterityBonus = static_cast<int>(s.GetArgVal()); break; case IBC_BONUSINT: m_IntelligenceBonus = static_cast<int>(s.GetArgVal()); break; case IBC_BONUSHITS: m_HitpointIncrease = static_cast<int>(s.GetArgVal()); break; case IBC_BONUSSTAM: m_StaminaIncrease = static_cast<int>(s.GetArgVal()); break; case IBC_BONUSMANA: m_ManaIncrease = static_cast<int>(s.GetArgVal()); break; case IBC_MAGEARMOR: m_MageArmor = static_cast<int>(s.GetArgVal()); break; case IBC_MAGEWEAPON: m_MageWeapon = static_cast<int>(s.GetArgVal()); break; case IBC_RARITY: m_ArtifactRarity = static_cast<int>(s.GetArgVal()); break; case IBC_SELFREPAIR: m_SelfRepair = static_cast<int>(s.GetArgVal()); break; case IBC_SPELLCHANNELING: m_SpellChanneling = static_cast<int>(s.GetArgVal()); break; case IBC_LOWERREQ: m_LowerRequirements = static_cast<int>(s.GetArgVal()); break; case IBC_USEBESTWEAPONSKILL: m_UseBestWeaponSkill = static_cast<int>(s.GetArgVal()); break; case IBC_HITAREAPHYSICAL: m_HitPhysicalArea = static_cast<int>(s.GetArgVal()); break; case IBC_HITAREAFIRE: m_HitFireArea = static_cast<int>(s.GetArgVal()); break; case IBC_HITAREACOLD: m_HitColdArea = static_cast<int>(s.GetArgVal()); break; case IBC_HITAREAPOISON: m_HitPoisonArea = static_cast<int>(s.GetArgVal()); break; case IBC_HITAREAENERGY: m_HitEnergyArea = static_cast<int>(s.GetArgVal()); break; case IBC_HITDISPEL: m_HitDispel = static_cast<int>(s.GetArgVal()); break; case IBC_HITFIREBALL: m_HitFireball = static_cast<int>(s.GetArgVal()); break; case IBC_HITHARM: m_HitHarm = static_cast<int>(s.GetArgVal()); break; case IBC_HITLIGHTNING: m_HitLightning = static_cast<int>(s.GetArgVal()); break; case IBC_HITMAGICARROW: m_HitMagicArrow = static_cast<int>(s.GetArgVal()); break; case IBC_WEIGHTREDUCTION: m_WeightReduction = static_cast<int>(s.GetArgVal()); break; case IBC_CANUSE: m_CanUse = s.GetArgVal(); break; case IBC_DISPID: return false; // can't set this case IBC_DUPEITEM: return true; // just ignore these case IBC_DUPELIST: { TCHAR *ppArgs[512]; size_t iArgQty = Str_ParseCmds(s.GetArgStr(), ppArgs, COUNTOF(ppArgs)); if ( iArgQty <= 0 ) return false; m_flip_id.Empty(); for ( size_t i = 0; i < iArgQty; i++ ) { ITEMID_TYPE id = static_cast<ITEMID_TYPE>(g_Cfg.ResourceGetIndexType(RES_ITEMDEF, ppArgs[i])); if ( !IsValidDispID(id) ) continue; if ( IsSameDispID(id) ) continue; m_flip_id.Add(id); } break; } case IBC_DYE: if ( !s.HasArgs() ) m_Can |= CAN_I_DYE; else { if ( s.GetArgVal() ) m_Can |= CAN_I_DYE; else m_Can &= ~CAN_I_DYE; } break; case IBC_FLIP: if ( !s.HasArgs() ) m_Can |= CAN_I_FLIP; else { if ( s.GetArgVal() ) m_Can |= CAN_I_FLIP; else m_Can &= ~CAN_I_FLIP; } break; case IBC_ENCHANT: if ( !s.HasArgs() ) m_Can |= CAN_I_ENCHANT; else { if ( s.GetArgVal() ) m_Can |= CAN_I_ENCHANT; else m_Can &= ~CAN_I_ENCHANT; } break; case IBC_EXCEPTIONAL: if ( !s.HasArgs() ) m_Can |= CAN_I_EXCEPTIONAL; else { if ( s.GetArgVal() ) m_Can |= CAN_I_EXCEPTIONAL; else m_Can &= ~CAN_I_EXCEPTIONAL; } break; case IBC_IMBUE: if ( !s.HasArgs() ) m_Can |= CAN_I_IMBUE; else { if ( s.GetArgVal() ) m_Can |= CAN_I_IMBUE; else m_Can &= ~CAN_I_IMBUE; } break; case IBC_REFORGE: if ( !s.HasArgs() ) m_Can |= CAN_I_REFORGE; else { if ( s.GetArgVal() ) m_Can |= CAN_I_REFORGE; else m_Can &= ~CAN_I_REFORGE; } break; case IBC_RETAINCOLOR: if ( !s.HasArgs() ) m_Can |= CAN_I_RETAINCOLOR; else { if ( s.GetArgVal() ) m_Can |= CAN_I_RETAINCOLOR; else m_Can &= ~CAN_I_RETAINCOLOR; } break; case IBC_MAKERSMARK: if ( !s.HasArgs() ) m_Can |= CAN_I_MAKERSMARK; else { if ( s.GetArgVal() ) m_Can |= CAN_I_MAKERSMARK; else m_Can &= ~CAN_I_MAKERSMARK; } break; case IBC_RECYCLE: if ( !s.HasArgs() ) m_Can |= CAN_I_RECYCLE; else { if ( s.GetArgVal() ) m_Can |= CAN_I_RECYCLE; else m_Can &= ~CAN_I_RECYCLE; } break; case IBC_REPAIR: if ( !s.HasArgs() ) m_Can |= CAN_I_REPAIR; else { if ( s.GetArgVal() ) m_Can |= CAN_I_REPAIR; else m_Can &= ~CAN_I_REPAIR; } break; case IBC_REPLICATE: if ( !s.HasArgs() ) m_Can |= CAN_I_REPLICATE; else { if ( s.GetArgVal() ) m_Can |= CAN_I_REPLICATE; else m_Can &= ~CAN_I_REPLICATE; } break; case IBC_ID: { if ( GetID() < ITEMID_MULTI ) { DEBUG_ERR(("Setting new id for base type %s not allowed\n", GetResourceName())); return false; } ITEMID_TYPE id = static_cast<ITEMID_TYPE>(g_Cfg.ResourceGetIndexType(RES_ITEMDEF, s.GetArgStr())); if ( !IsValidDispID(id) ) { DEBUG_ERR(("Setting invalid id=%s for base type %s\n", s.GetArgStr(), GetResourceName())); return false; } CItemBase *pItemDef = FindItemBase(id); if ( !pItemDef ) { DEBUG_ERR(("Setting unknown base id=0%x for %s\n", id, GetResourceName())); return false; } CopyBasic(pItemDef); m_dwDispIndex = id; // might not be the default of a DUPEITEM break; } case IBC_LAYER: m_layer = static_cast<BYTE>(s.GetArgVal()); break; case IBC_PILE: break; case IBC_REQSTR: if ( !IsTypeEquippable() ) return false; m_ttEquippable.m_StrReq = s.GetArgVal(); break; case IBC_RESDISPDNID: SetResDispDnId(static_cast<WORD>(g_Cfg.ResourceGetIndexType(RES_ITEMDEF, s.GetArgStr()))); break; case IBC_SPEED: m_speed = static_cast<BYTE>(s.GetArgVal()); break; case IBC_SKILL: m_iSkill = g_Cfg.FindSkillKey(s.GetArgStr()); break; case IBC_SKILLMAKE: m_SkillMake.Load(s.GetArgStr()); break; case IBC_TDATA1: m_ttNormal.m_tData1 = s.GetArgVal(); break; case IBC_TDATA2: m_ttNormal.m_tData2 = s.GetArgVal(); break; case IBC_TDATA3: m_ttNormal.m_tData3 = s.GetArgVal(); break; case IBC_TDATA4: m_ttNormal.m_tData4 = s.GetArgVal(); break; case IBC_TWOHANDS: if ( (s.GetArgStr()[0] == '1') || (s.GetArgStr()[0] == 'Y') || (s.GetArgStr()[0] == 'y') ) m_layer = LAYER_HAND2; break; case IBC_TYPE: m_type = static_cast<IT_TYPE>(g_Cfg.ResourceGetIndexType(RES_TYPEDEF, s.GetArgStr())); if ( m_type == IT_CONTAINER_LOCKED ) // at this level it just means to add a key for it m_type = IT_CONTAINER; break; case IBC_VALUE: m_values.Load(s.GetArgRaw()); break; case IBC_WEIGHT: m_weight = static_cast<WORD>(s.GetArgVal()); if ( strchr(s.GetArgStr(), '.') ) m_weight *= WEIGHT_UNITS; break; default: return CBaseBaseDef::r_LoadVal(s); } return true; EXC_CATCH; EXC_DEBUG_START; EXC_ADD_SCRIPT; EXC_DEBUG_END; return false; } void CItemBase::ReplaceItemBase(CItemBase *pOld, CResourceDef *pNew) // static { ADDTOCALLSTACK("CItemBase::ReplaceItemBase"); ASSERT(pOld); ASSERT(pOld->GetRefInstances() == 0); RESOURCE_ID rid = pOld->GetResourceID(); size_t index = g_Cfg.m_ResHash.FindKey(rid); ASSERT(index != g_Cfg.m_ResHash.BadIndex()); g_Cfg.m_ResHash.SetAt(rid, index, pNew); } CItemBase *CItemBase::MakeDupeReplacement(CItemBase *pBase, ITEMID_TYPE iddupe) // static { ADDTOCALLSTACK("CItemBase::MakeDupeReplacement"); ITEMID_TYPE id = pBase->GetID(); if ( (iddupe == id) || !IsValidDispID(iddupe) ) { DEBUG_ERR(("CItemBase:DUPEITEM weirdness 0%x==0%x\n", id, iddupe)); return pBase; } CItemBase *pBaseNew = FindItemBase(iddupe); if ( !pBaseNew ) { DEBUG_ERR(("CItemBase:DUPEITEM not exist 0%x==0%x\n", id, iddupe)); return pBase; } if ( pBaseNew->GetID() != iddupe ) { DEBUG_ERR(("CItemBase:DUPEITEM circle 0%x==0%x\n", id, iddupe)); return pBase; } if ( !pBaseNew->IsSameDispID(id) ) pBaseNew->m_flip_id.Add(id); // Create the dupe stub CUOItemTypeRec2 tiledata; memset(&tiledata, 0, sizeof(tiledata)); CItemBaseDupe *pBaseDupe = new CItemBaseDupe(id, pBaseNew); if ( GetItemData(id, &tiledata) ) { pBaseDupe->SetTFlags(tiledata.m_flags); pBaseDupe->SetHeight(GetItemHeightFlags(tiledata, pBaseDupe->m_Can)); } ReplaceItemBase(pBase, pBaseDupe); return pBaseNew; } //********************************************************* // CItemBaseDupe CItemBaseDupe *CItemBaseDupe::GetDupeRef(ITEMID_TYPE id) // static { ADDTOCALLSTACK("CItemBaseDupe::GetDupeRef"); if ( id <= ITEMID_NOTHING ) return NULL; RESOURCE_ID rid = RESOURCE_ID(RES_ITEMDEF, id); size_t index = g_Cfg.m_ResHash.FindKey(rid); if ( index == g_Cfg.m_ResHash.BadIndex() ) return NULL; CResourceDef *pBaseStub = g_Cfg.m_ResHash.GetAt(rid, index); CItemBase *pBase = dynamic_cast<CItemBase *>(pBaseStub); if ( pBase ) return NULL; // we want to return DupeItem, not BaseItem CItemBaseDupe *pBaseDupe = dynamic_cast<CItemBaseDupe *>(pBaseStub); if ( pBaseDupe ) return pBaseDupe; // this is just a DupeItem return NULL; // we suspect item is loaded } //********************************************************* // CItemBaseMulti CItemBaseMulti::CItemBaseMulti(CItemBase *pBase) : CItemBase(pBase->GetID()) { m_Components.Empty(); m_rect.SetRectEmpty(); m_dwRegionFlags = REGION_FLAG_NOBUILDING; m_Speech.Empty(); m_shipSpeed.period = TICK_PER_SEC / 2; m_shipSpeed.tiles = 1; m_SpeedMode = 3; CopyTransfer(pBase); // copy the stuff from pBase } CItemBase *CItemBaseMulti::MakeMultiRegion(CItemBase *pBase, CScript &s) // static { ADDTOCALLSTACK("CItemBaseMulti::MakeMultiRegion"); // MULTIREGION // We must transform this object into a CItemBaseMulti if ( !pBase ) return NULL; if ( !pBase->IsTypeMulti(pBase->GetType()) ) { DEBUG_ERR(("MULTIREGION defined for NON-MULTI type 0%x\n", pBase->GetID())); return pBase; } CItemBaseMulti *pBaseMulti = dynamic_cast<CItemBaseMulti *>(pBase); if ( !pBaseMulti ) { if ( pBase->GetRefInstances() > 0 ) { DEBUG_ERR(("MULTIREGION defined for IN USE NON-MULTI type 0%x\n", pBase->GetID())); return pBase; } pBaseMulti = new CItemBaseMulti(pBase); ReplaceItemBase(pBase, pBaseMulti); } pBaseMulti->SetMultiRegion(s.GetArgStr()); return pBaseMulti; } void CItemBaseMulti::SetMultiRegion(TCHAR *pszArgs) { ADDTOCALLSTACK("CItemBaseMulti::SetMultiRegion"); INT64 piArgs[5]; size_t iQty = Str_ParseCmds(pszArgs, piArgs, COUNTOF(piArgs)); if ( iQty <= 1 ) return; m_Components.Empty(); // might be after a resync m_rect.SetRect(static_cast<int>(piArgs[0]), static_cast<int>(piArgs[1]), static_cast<int>(piArgs[2] + 1), static_cast<int>(piArgs[3] + 1), static_cast<int>(piArgs[4])); } bool CItemBaseMulti::AddComponent(ITEMID_TYPE id, signed short dx, signed short dy, signed char dz) { ADDTOCALLSTACK("CItemBaseMulti::AddComponent"); m_rect.UnionPoint(dx, dy); if ( id > ITEMID_NOTHING ) { CItemBase *pItemBase = FindItemBase(id); if ( !pItemBase ) { DEBUG_ERR(("Bad COMPONENT 0%x\n", id)); return false; } CMultiComponentItem comp; comp.m_id = id; comp.m_dx = dx; comp.m_dy = dy; comp.m_dz = dz; m_Components.Add(comp); } return true; } bool CItemBaseMulti::AddComponent(TCHAR *pszArgs) { ADDTOCALLSTACK("CItemBaseMulti::AddComponent"); INT64 piArgs[4]; size_t iQty = Str_ParseCmds(pszArgs, piArgs, COUNTOF(piArgs)); if ( iQty <= 1 ) return false; return AddComponent(static_cast<ITEMID_TYPE>(RES_GET_INDEX(piArgs[0])), static_cast<short>(piArgs[1]), static_cast<short>(piArgs[2]), static_cast<char>(piArgs[3])); } int CItemBaseMulti::GetMaxDist() const { ADDTOCALLSTACK("CItemBaseMulti::GetMaxDist"); int iDist = abs(m_rect.m_left); int iDistTmp = abs(m_rect.m_top); if ( iDistTmp > iDist ) iDist = iDistTmp; iDistTmp = abs(m_rect.m_right + 1); if ( iDistTmp > iDist ) iDist = iDistTmp; iDistTmp = abs(m_rect.m_bottom + 1); if ( iDistTmp > iDist ) iDist = iDistTmp; return iDist + 1; } enum MLC_TYPE { MLC_BASECOMPONENT, MLC_COMPONENT, MLC_MULTIREGION, MLC_REGIONFLAGS, MLC_SHIPSPEED, MLC_TSPEECH, MLC_QTY }; const LPCTSTR CItemBaseMulti::sm_szLoadKeys[] = { "BASECOMPONENT", "COMPONENT", "MULTIREGION", "REGIONFLAGS", "SHIPSPEED", "TSPEECH", NULL }; bool CItemBaseMulti::r_LoadVal(CScript &s) { ADDTOCALLSTACK("CItemBaseMulti::r_LoadVal"); EXC_TRY("LoadVal"); switch ( FindTableSorted(s.GetKey(), sm_szLoadKeys, COUNTOF(sm_szLoadKeys) - 1) ) { case MLC_COMPONENT: return AddComponent(s.GetArgStr()); case MLC_MULTIREGION: MakeMultiRegion(this, s); break; case MLC_REGIONFLAGS: m_dwRegionFlags = s.GetArgVal(); return true; case MLC_SHIPSPEED: { if ( !IsType(IT_SHIP) ) return false; INT64 piArgs[2]; size_t iQty = Str_ParseCmds(s.GetArgRaw(), piArgs, COUNTOF(piArgs)); if ( iQty < 1 ) return false; m_shipSpeed.period = static_cast<BYTE>(piArgs[0]); if ( iQty >= 2 ) m_shipSpeed.tiles = static_cast<BYTE>(piArgs[1]); break; } case MLC_TSPEECH: return m_Speech.r_LoadVal(s, RES_SPEECH); default: return CItemBase::r_LoadVal(s); } return true; EXC_CATCH; EXC_DEBUG_START; EXC_ADD_SCRIPT; EXC_DEBUG_END; return false; } bool CItemBaseMulti::r_WriteVal(LPCTSTR pszKey, CGString &sVal, CTextConsole *pSrc) { ADDTOCALLSTACK("CItemBaseMulti::r_WriteVal"); EXC_TRY("WriteVal"); switch ( FindTableHeadSorted(pszKey, sm_szLoadKeys, COUNTOF(sm_szLoadKeys) - 1) ) { case MLC_BASECOMPONENT: { pszKey += 13; const CGrayMulti *pMulti = g_Cfg.GetMultiItemDefs(GetDispID()); if ( !pMulti ) return false; if ( *pszKey == '\0' ) sVal.FormatVal(pMulti->GetItemCount()); else if ( *pszKey == '.' ) { SKIP_SEPARATORS(pszKey); size_t index = Exp_GetVal(pszKey); if ( index >= pMulti->GetItemCount() ) return false; SKIP_SEPARATORS(pszKey); const CUOMultiItemRecHS *pItem = pMulti->GetItem(index); if ( *pszKey == '\0' ) sVal.Format("%hu,%hd,%hd,%hd", pItem->m_wTileID, pItem->m_dx, pItem->m_dy, pItem->m_dz); else if ( !strnicmp(pszKey, "ID", 2) ) sVal.FormatVal(pItem->m_wTileID); else if ( !strnicmp(pszKey, "DX", 2) ) sVal.FormatVal(pItem->m_dx); else if ( !strnicmp(pszKey, "DY", 2) ) sVal.FormatVal(pItem->m_dy); else if ( !strnicmp(pszKey, "DZ", 2) ) sVal.FormatVal(pItem->m_dz); else if ( !strnicmp(pszKey, "D", 1) ) sVal.Format("%hd,%hd,%hd", pItem->m_dx, pItem->m_dy, pItem->m_dz); else if ( !strnicmp(pszKey, "VISIBLE", 7) ) sVal.FormatVal(pItem->m_visible); else return false; } else return false; return true; } case MLC_COMPONENT: { pszKey += 9; if ( *pszKey == '\0' ) sVal.FormatVal(m_Components.GetCount()); else if ( *pszKey == '.' ) { SKIP_SEPARATORS(pszKey); size_t index = Exp_GetVal(pszKey); if ( !m_Components.IsValidIndex(index) ) return false; SKIP_SEPARATORS(pszKey); CMultiComponentItem item = m_Components.GetAt(index); if ( !strnicmp(pszKey, "ID", 2) ) sVal.FormatVal(item.m_id); else if ( !strnicmp(pszKey, "DX", 2) ) sVal.FormatVal(item.m_dx); else if ( !strnicmp(pszKey, "DY", 2) ) sVal.FormatVal(item.m_dy); else if ( !strnicmp(pszKey, "DZ", 2) ) sVal.FormatVal(item.m_dz); else if ( !strnicmp(pszKey, "D", 1) ) sVal.Format("%hd,%hd,%hhd", item.m_dx, item.m_dy, item.m_dz); else sVal.Format("%u,%hd,%hd,%hhd", item.m_id, item.m_dx, item.m_dy, item.m_dz); } else return false; return true; } case MLC_MULTIREGION: sVal.Format("%d,%d,%d,%d", m_rect.m_left, m_rect.m_top, m_rect.m_right - 1, m_rect.m_bottom - 1); return true; case MLC_REGIONFLAGS: sVal.FormatHex(m_dwRegionFlags); return true; case MLC_SHIPSPEED: { if ( !IsType(IT_SHIP) ) return false; pszKey += 9; if ( *pszKey == '.' ) { pszKey++; if ( !strcmpi(pszKey, "TILES") ) { sVal.FormatVal(m_shipSpeed.tiles); break; } else if ( !strcmpi(pszKey, "PERIOD") ) { sVal.FormatVal(m_shipSpeed.period); break; } return false; } sVal.Format("%hhu,%hhu", m_shipSpeed.period, m_shipSpeed.tiles); break; } default: return CItemBase::r_WriteVal(pszKey, sVal, pSrc); } return true; EXC_CATCH; EXC_DEBUG_START; EXC_ADD_KEYRET(pSrc); EXC_DEBUG_END; return false; }
25.66306
218
0.659339
mxdamien
3b68260d522b10c18c1359eb5b205e6ee3f410c5
10,707
cpp
C++
cyg_graph.cpp
yasuo-ozu/cygraph-gui
ec4f2793cdd6d208b89e5795a3e08dceff6b29e6
[ "MIT" ]
1
2018-02-12T05:09:30.000Z
2018-02-12T05:09:30.000Z
cyg_graph.cpp
yasuo-ozu/cygraph-gui
ec4f2793cdd6d208b89e5795a3e08dceff6b29e6
[ "MIT" ]
null
null
null
cyg_graph.cpp
yasuo-ozu/cygraph-gui
ec4f2793cdd6d208b89e5795a3e08dceff6b29e6
[ "MIT" ]
null
null
null
#include "cyg_common.hpp" namespace Cygraph { // Graph Graph::Graph() { this->padding.top = 30.0; this->padding.left = 30.0; this->padding.right = 30.0; this->padding.bottom = 30.0; } boundary Graph::get_boundary(Graphic g, double resolution) { boundary bd{0.0, 0.0, 0.0, 0.0}; for (auto *axis : this->axises) { double h = axis->get_outer_height(g, resolution); if (axis->orientation == 0) { if (bd.top < h) bd.top = h; } else if (axis->orientation == 1) { if (bd.right < h) bd.right = h; } else if (axis->orientation == 2) { if (bd.bottom < h) bd.bottom = h; } else if (axis->orientation == 3) { if (bd.left < h) bd.left = h; } } return bd; } void Graph::draw(Graphic g, double resolution, rectangle rect) { g->set_source_rgb(1.0, 1.0, 1.0); g->rectangle(rect.x, rect.y, rect.width, rect.height); g->fill(); g->set_source_rgb(0.0, 0.0, 0.0); auto bd = this->get_boundary(g, resolution); rectangle area{rect.x + bd.left + this->padding.left, rect.y + bd.top + this->padding.top, rect.width - bd.left - bd.right - this->padding.left - this->padding.right, rect.height - bd.top - bd.bottom - this->padding.top - this->padding.bottom}; g->rectangle(area.x, area.y, area.width, area.height); g->stroke(); map<Axis *, rectangle> axis_rects; for (auto *axis : this->axises) { rectangle axis_rect; if (axis->orientation == 0) { axis_rect = (rectangle){area.x, this->padding.top, area.width, bd.top}; } else if (axis->orientation == 1) { axis_rect = (rectangle){area.x + area.width, area.y, bd.right, area.height}; } else if (axis->orientation == 2) { axis_rect = (rectangle){area.x, area.y + area.height, area.width, bd.bottom}; } else if (axis->orientation == 3) { axis_rect = (rectangle){area.x - bd.left, area.y, bd.left, area.height}; } axis->draw(g, resolution, axis_rect); axis_rects[axis] = axis_rect; } for (auto *line : this->lines) { g->save(); if (line->weight > 0.0) { g->rectangle(area.x, area.y, area.width, area.height); g->clip(); } line->draw(g, resolution, axis_rects); g->restore(); } } // Axis Axis::Axis(double begin, double end, double step) { this->text = nullptr; this->padding.top = 5.0; this->padding.left = 5.0; this->padding.right = 5.0; this->padding.bottom = 5.0; this->label_format = "%.1lf"; this->orientation = 2; this->begin = begin; this->end = end; Scale scale; scale.width = 1.0; scale.step = step; scale.inner_height = 5.0; scale.outer_height = 0.0; scale.label = true; this->scales.push_back(scale); } void Axis::set_text(string s) { this->text = new Text(s); } double Axis::get_outer_height(Graphic g, double resolution) { double max_outer_height = 0; double max_label_height = 0; char s[100]; auto f = [&](double loc) { sprintf(s, this->label_format.c_str(), loc); Text *text = new Text(s); text->padding = this->padding; size siz = text->get_size(g, resolution); if (this->orientation % 2 == 0) { if (max_label_height < siz.height) max_label_height = siz.height; } else { if (max_label_height < siz.width) max_label_height = siz.width; } delete text; }; for (auto scale : this->scales) { if (scale.outer_height > max_outer_height) max_outer_height = scale.outer_height; if (!scale.label) continue; double loc; for (loc = this->begin; (this->begin <= loc && loc < this->end) || (this->begin >= loc && loc > this->end); loc += scale.step) f(loc); loc = this->end; f(loc); } if (this->text != nullptr) { max_label_height += this->text->get_size(g, resolution).height; } return max_outer_height + max_label_height; } void Axis::draw(Graphic g, double resolution, rectangle rect) { UNUSED(g, resolution); char s[100]; size t_siz = this->text->get_size(g, resolution); if (this->orientation == 0) { this->text->draw(g, resolution, rect.x + (rect.width - t_siz.width) / 2, rect.y); } else if (this->orientation == 1) { this->text->orientation = 1; this->text->draw(g, resolution, rect.x + rect.width - t_siz.width, rect.y + (rect.height - t_siz.width) / 2); } else if (this->orientation == 2) { this->text->draw(g, resolution, rect.x + (rect.width - t_siz.width) / 2, rect.y + rect.height - t_siz.height); } else if (this->orientation == 3) { this->text->orientation = -1; this->text->draw(g, resolution, rect.x, rect.y + (rect.height - t_siz.width) / 2); } for (auto scale : this->scales) { auto f = [&](double loc) { double p_loc = (this->orientation % 2 == 0 ? rect.width : rect.height) / abs(this->end - this->begin) * abs(loc - this->begin); if (this->orientation == 0) { g->move_to(rect.x + p_loc, rect.y + rect.height - scale.outer_height); g->line_to(rect.x + p_loc, rect.y + rect.height + scale.inner_height); } else if (this->orientation == 1) { g->move_to(rect.x - scale.inner_height, rect.y + p_loc); g->line_to(rect.x + scale.outer_height, rect.y + p_loc); } else if (this->orientation == 2) { g->move_to(rect.x + p_loc, rect.y + scale.outer_height); g->line_to(rect.x + p_loc, rect.y - scale.inner_height); } else if (this->orientation == 3) { g->move_to(rect.x + rect.width + scale.inner_height, rect.y + p_loc); g->line_to(rect.x + rect.width - scale.outer_height, rect.y + p_loc); } g->stroke(); sprintf(s, this->label_format.c_str(), loc); Text *text = new Text(s); text->padding = this->padding; size siz = text->get_size(g, resolution); if (this->orientation == 0) { text->draw(g, resolution, rect.x + p_loc - siz.width / 2, rect.y + rect.height - scale.outer_height - siz.height); } else if (this->orientation == 1) { text->draw(g, resolution, rect.x + scale.outer_height, rect.y + p_loc - siz.height / 2); } else if (this->orientation == 2) { text->draw(g, resolution, rect.x + p_loc - siz.width / 2, rect.y + scale.outer_height); } else if (this->orientation == 3) { text->draw(g, resolution, rect.x + rect.width - siz.width - scale.outer_height, rect.y + p_loc - siz.height / 2); } delete text; }; for (double loc = this->begin; (this->begin <= loc && loc < this->end) || (this->begin >= loc && loc > this->end); loc += scale.step) f(loc); f(this->end); } } double Axis::get_location(Graphic g, double resolution, rectangle rect, double value) { UNUSED(g, resolution); if (this->orientation % 2 == 0) return rect.x + rect.width * ((value - this->begin) / (this->end - this->begin)); else { return rect.y + rect.height * ((value - this->begin) / (this->end - this->begin)); } } // Text Text::Text() { this->font_size = 10.0; this->orientation = 0; this->padding.top = 5.0; this->padding.left = 5.0; this->padding.right = 5.0; this->padding.bottom = 5.0; } Text::Text(string s) : Text() { this->text = s; } size Text::get_size(Graphic g, double resolution) { size siz; Cairo::TextExtents ext; g->save(); if (!this->font_name.empty()) g->select_font_face(this->font_name, Cairo::FONT_SLANT_NORMAL, Cairo::FONT_WEIGHT_BOLD); g->set_font_size(this->font_size * resolution / 72); g->get_text_extents(this->text, ext); g->restore(); siz.width = ext.width; siz.height = ext.height; siz.width += this->padding.left + this->padding.right; siz.height += this->padding.top + this->padding.bottom; return siz; } void Text::draw(Graphic g, double resolution, double x, double y) { g->save(); auto siz = this->get_size(g, resolution); if (!this->font_name.empty()) g->select_font_face(this->font_name, Cairo::FONT_SLANT_NORMAL, Cairo::FONT_WEIGHT_BOLD); g->set_font_size(this->font_size * resolution / 72); g->move_to(x + this->padding.left, y + siz.height - this->padding.bottom); if (this->orientation % 2 != 0) { g->move_to(x + this->padding.left, y + siz.width - this->padding.bottom); g->rotate(0.5 * this->orientation * 3.142); } g->show_text(this->text); g->restore(); } // GraphLine GraphLine::GraphLine(Axis *axis1, Axis *axis2) { this->axis[0] = axis1; this->axis[1] = axis2; this->weight = 1.0; this->efficient = 1.0; this->func = nullptr; } vector<location> GraphLine::get_points() { double min, max; vector<location> list; if (this->axis[0]->begin <= this->axis[0]->end) { min = this->axis[0]->begin; max = this->axis[0]->end; } else { max = this->axis[0]->begin; min = this->axis[0]->end; } for (double x = min; x <= max; x += this->weight > 0.0 ? 0.1 : 1.0) { if (this->func == nullptr) { list.push_back((location){x, x * x * this->efficient}); } else { list.push_back((location){x, this->func(this->tag, this->tag2, x) }); } } return list; } void GraphLine::draw(Graphic g, double resolution, map<Axis *, rectangle> locs) { vector<location> points = this->get_points(); bool is_beginning = true; if (this->weight > 0.0) g->set_line_width(this->weight); for (auto point : points) { location loc{0.0, 0.0}; for (auto *axis : this->axis) { if (axis->orientation % 2 == 0) { loc.x = axis->get_location(g, resolution, locs[axis], point.x); } else if (axis->orientation % 2 == 1) { loc.y = axis->get_location(g, resolution, locs[axis], point.y); } } if (this->weight > 0.0) { if (is_beginning) g->move_to(loc.x, loc.y); else g->line_to(loc.x, loc.y); } for (auto *point : this->points) { point->draw(g, resolution, loc.x, loc.y); } is_beginning = false; } g->stroke(); } GraphPoint::GraphPoint(PointShape ps) { this->shape = GraphPoint::PS_CIRCLE; this->size = 10.0; this->invert = false; this->shape = ps; } void GraphPoint::draw(Graphic g, double resolution, double x, double y) { UNUSED(resolution); g->save(); if (this->invert) g->set_source_rgb(1.0, 1.0, 1.0); else g->set_source_rgb(0.0, 0.0, 0.0); if (this->shape == PS_CIRCLE) { g->arc(x, y, this->size, 0.0, 2 * 3.1416); } else if (this->shape == PS_TRIANGLE) { g->move_to(x, y - this->size * 1.5); g->line_to(x - this->size * 1.5 / 2.0 * 1.73, y + this->size * 1.5 / 2.0); g->line_to(x + this->size * 1.5 / 2.0 * 1.73, y + this->size * 1.5 / 2.0); g->close_path(); } else if (this->shape == PS_SQUARE) { g->rectangle(x - this->size * 1.73 / 2.0, y - this->size * 1.73 / 2.0, this->size * 1.73, this->size * 1.73); } g->fill(); g->restore(); } }
31.866071
112
0.602129
yasuo-ozu
3b687ec16585ee94332b8abb7b843c7447c32030
2,182
hh
C++
src/Circuit/data/CircuitNode.hh
lucydot/devsim
2c69fcc05551bb50ca134490279e206cdeaf91a6
[ "Apache-2.0" ]
100
2015-02-02T23:47:38.000Z
2022-03-15T06:15:15.000Z
src/Circuit/data/CircuitNode.hh
fendou1997/devsim
71c5a5a56f567b472f39e4968bedbe57a38d6ff6
[ "Apache-2.0" ]
75
2015-05-13T02:16:41.000Z
2022-02-23T12:20:21.000Z
src/Circuit/data/CircuitNode.hh
fendou1997/devsim
71c5a5a56f567b472f39e4968bedbe57a38d6ff6
[ "Apache-2.0" ]
50
2015-10-28T17:24:24.000Z
2022-03-30T17:48:46.000Z
#ifndef CIRCUIT_NODE_HH #define CIRCUIT_NODE_HH /*** DEVSIM Copyright 2013 Devsim LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ***/ #include <memory> class CircuitNode; typedef std::shared_ptr<CircuitNode> CircuitNodePtr; enum class CircuitUpdateType {DEFAULT, LOGDAMP, POSITIVE}; enum class CircuitNodeType { DEFAULT, // Your typical node MNA, // MNA for Voltage sources INTERNAL, // INTERNAL for internal nodes GROUND // Ground CircuitNodes are not solved }; class CircuitNode { public: static const char * const CircuitNodeTypeStr[]; inline size_t getNumber() {return nodeNumber_;} inline CircuitUpdateType getUpdateType() {return updateType;} inline CircuitNodeType getCircuitNodeType() {return nodeType_;} inline const char * getCircuitNodeTypeStr() {return CircuitNodeTypeStr[static_cast<size_t>(nodeType_)];} inline bool isGROUND() {return (nodeType_==CircuitNodeType::GROUND);} size_t GetNumber() {return nodeNumber_;} private: friend class NodeKeeper; /* Modified Nodal Analysis */ CircuitNode(); explicit CircuitNode(CircuitNodeType, CircuitUpdateType); CircuitNode operator=(const CircuitNode &); inline bool isMNA() {return (nodeType_== CircuitNodeType::MNA);} // void setMNA(bool setm=true) { // nodeType_=(setm) ? MNA : DEFAULT;} void SetNumber(size_t n) {nodeNumber_=n;} size_t nodeNumber_; CircuitNodeType nodeType_; CircuitUpdateType updateType; }; #endif
27.275
77
0.671402
lucydot
3b68be2b1b9d07f20348ac79875cfcf5130620d1
5,291
cc
C++
src/simple-quic/custom/proof_source_openssl.cc
Hasan-Jawaheri/quic-tor
f8a5b8b93a82eb515808d381bfbb2cc662e12513
[ "MIT" ]
null
null
null
src/simple-quic/custom/proof_source_openssl.cc
Hasan-Jawaheri/quic-tor
f8a5b8b93a82eb515808d381bfbb2cc662e12513
[ "MIT" ]
null
null
null
src/simple-quic/custom/proof_source_openssl.cc
Hasan-Jawaheri/quic-tor
f8a5b8b93a82eb515808d381bfbb2cc662e12513
[ "MIT" ]
null
null
null
// Copyright 2013 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. // // Modified by kku to remove dependency on BoringSSL. // // References: // https://www.openssl.org/docs/manmaster/crypto/pem.html // https://www.openssl.org/docs/manmaster/crypto/d2i_X509.html (for DER-encoded certs) // http://stackoverflow.com/questions/17400058/how-to-use-openssl-lib-pem-read-to-read-public-private-key-from-a-string // http://stackoverflow.com/questions/17852325/how-to-convert-the-x509-structure-into-string #include "proof_source_openssl.h" #include <openssl/evp.h> #include <openssl/rsa.h> #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/ssl.h> #include <openssl/x509.h> #include <openssl/pem.h> #include "base/logging.h" #include "net/quic/crypto/crypto_protocol.h" #include "file_util.h" using std::string; using std::vector; namespace net { ProofSourceOpenSSL::ProofSourceOpenSSL() { private_key_ = EVP_PKEY_new(); } ProofSourceOpenSSL::~ProofSourceOpenSSL() { EVP_PKEY_free(private_key_); } void InitializeSSL() { SSL_load_error_strings(); ERR_load_BIO_strings(); OpenSSL_add_all_algorithms(); } void DestroySSL() { ERR_free_strings(); EVP_cleanup(); } // cert_path: path to PEM-encoded certificate // key_path: path to PEM-encoded private key // sct_path: signed certificate timestamp file (optional) bool ProofSourceOpenSSL::Initialize(const std::string& cert_path, const std::string& key_path, const std::string& sct_path) { // Initialize OpenSSL. InitializeSSL(); // Parse PEM-encoded x509 certificate. FILE *cert_file = OpenFile(cert_path, "rb"); BIO *cert_bio = BIO_new_fp(cert_file, BIO_NOCLOSE); X509 *cert = PEM_read_bio_X509(cert_bio, NULL, 0, NULL); BIO_free(cert_bio); CloseFile(cert_file); if (cert == NULL) { DLOG(FATAL) << "Cannot read certifcate from file " << cert_path; return false; } // Re-encode certificate to DER // Re-encoding the DER data via i2d_X509 is an expensive operation, // but it's necessary for comparing two certificates. // See net/cert/x509_util_openssl.cc BIO *b64 = BIO_new(BIO_s_mem()); if (i2d_X509_bio(b64, cert) != 1) { DLOG(FATAL) << "Failed to re-encode certificate to DER"; BIO_free(b64); return false; } BUF_MEM *bptr; BIO_get_mem_ptr(b64, &bptr); std::string cert_buf(bptr->data, bptr->length); certificates_.push_back(cert_buf); BIO_free(b64); // Read PEM-encoded private key. FILE *key_file = OpenFile(key_path, "rb"); BIO *key_bio = BIO_new_fp(key_file, BIO_NOCLOSE); PEM_read_bio_PrivateKey(key_bio, &private_key_, 0, 0); BIO_free(key_bio); CloseFile(key_file); // Loading of the signed certificate timestamp is optional. if (sct_path.empty()) return true; if (!ReadFileToString(sct_path, &signed_certificate_timestamp_)) { DLOG(FATAL) << "Unable to read signed certificate timestamp."; return false; } return true; } bool ProofSourceOpenSSL::GetProof(const IPAddressNumber& server_ip, const string& hostname, const string& server_config, bool ecdsa_ok, const vector<string>** out_certs, string* out_signature, string* out_leaf_cert_sct) { DCHECK(private_key_) << " this: " << this; EVP_MD_CTX *sign_context = EVP_MD_CTX_create(); EVP_PKEY_CTX *pkey_ctx; // Note: EVP_PKEY_CTX_set_rsa_pss_saltlen in openssl/rsa.h will call // EVP_PKEY_CTX_ctrl with the 5th argument being NULL. // If we use boringSSL implementation of EVP_PKEY_CTX_ctrl, this will cause a // segfault on line 375 in boringssl/crypto/evp/p_rsa.c. if (!EVP_DigestSignInit(sign_context, &pkey_ctx, EVP_sha256(), nullptr, private_key_) || !EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING) || !EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, -1) || !EVP_DigestSignUpdate( sign_context, // kProofSignatureLabel is defined in net/quic/crypto/crypto_protocol.h reinterpret_cast<const uint8_t*>(kProofSignatureLabel), sizeof(kProofSignatureLabel)) || !EVP_DigestSignUpdate( sign_context, reinterpret_cast<const uint8_t*>(server_config.data()), server_config.size())) { EVP_MD_CTX_destroy(sign_context); return false; } // Determine the maximum length of the signature. size_t len = 0; if (!EVP_DigestSignFinal(sign_context, nullptr, &len)) { EVP_MD_CTX_destroy(sign_context); return false; } std::vector<uint8_t> signature(len); // Sign it. if (!EVP_DigestSignFinal(sign_context, signature.data(), &len)) { EVP_MD_CTX_destroy(sign_context); return false; } signature.resize(len); out_signature->assign(reinterpret_cast<const char*>(signature.data()), signature.size()); *out_certs = &certificates_; *out_leaf_cert_sct = signed_certificate_timestamp_; EVP_MD_CTX_destroy(sign_context); return true; } } // namespace net
32.262195
119
0.680212
Hasan-Jawaheri
3b6bb4c533a6cd93c0702eb8e951b1f5ad9c9473
33,171
hpp
C++
include/domain/structure/io/sgnuplot_actor.hpp
hyperpower/CarpioPlus
68cc6c976d6c3ba6adec847a94c344be3f4690aa
[ "MIT" ]
null
null
null
include/domain/structure/io/sgnuplot_actor.hpp
hyperpower/CarpioPlus
68cc6c976d6c3ba6adec847a94c344be3f4690aa
[ "MIT" ]
1
2018-06-18T03:52:56.000Z
2018-06-18T03:52:56.000Z
include/domain/structure/io/sgnuplot_actor.hpp
hyperpower/CarpioPlus
68cc6c976d6c3ba6adec847a94c344be3f4690aa
[ "MIT" ]
null
null
null
#ifndef _S_GNUPLOT_ACTOR_HPP #define _S_GNUPLOT_ACTOR_HPP #include "domain/structure/grid/sgrid.hpp" #include "domain/structure/field/sfield.hpp" #include "domain/structure/operation/soperation.hpp" #include "io/gnuplot.hpp" namespace carpio{ using namespace GnuplotActor; template<St DIM> class SGnuplotActor_ { public: static const St Dim = DIM; typedef ArrayListT_<Vt> Arr; typedef Point_<Vt, Dim> Poi; typedef SIndex_<Dim> Index; typedef St size_type; typedef SGrid_<DIM> Grid; typedef SGrid_<1> Grid1; typedef SGrid_<2> Grid2; typedef SGrid_<3> Grid3; typedef SGhost_<DIM, Grid> Ghost; typedef SGhost_<1, Grid> Ghost1; typedef SGhost_<2, Grid> Ghost2; typedef SGhost_<3, Grid> Ghost3; typedef SGhostLinearCut_<DIM, Grid> GhostLinearCut; typedef SGhostLinearCut_<1, Grid> GhostLinearCut1; typedef SGhostLinearCut_<2, Grid> GhostLinearCut2; typedef SGhostLinearCut_<3, Grid> GhostLinearCut3; typedef SCellLinearCut_<DIM> CellLinearCut; typedef SCellLinearCut_<1> CellLinearCut1; typedef SCellLinearCut_<2> CellLinearCut2; typedef SCellLinearCut_<3> CellLinearCut3; typedef SOrder_<DIM, Grid, Ghost> Order; typedef SOrder_<1, Grid, Ghost> Order1; typedef SOrder_<2, Grid, Ghost> Order2; typedef SOrder_<3, Grid, Ghost> Order3; typedef SField_<DIM, Grid, Ghost, Order> Field; typedef SField_<1, Grid, Ghost, Order> Field1; typedef SField_<2, Grid, Ghost, Order> Field2; typedef SField_<3, Grid, Ghost, Order> Field3; typedef SVectorCenter_<DIM, Grid, Ghost, Order> VC; typedef SVectorCenter_<1, Grid, Ghost, Order> VC1; typedef SVectorCenter_<2, Grid, Ghost, Order> VC2; typedef SVectorCenter_<3, Grid, Ghost, Order> VC3; typedef SVectorFace_<DIM, Grid, Ghost, Order> VF; typedef SVectorFace_<1, Grid, Ghost, Order> VF1; typedef SVectorFace_<2, Grid, Ghost, Order> VF2; typedef SVectorFace_<3, Grid, Ghost, Order> VF3; typedef SCorner_<DIM, Grid, Ghost, Order> Corner; typedef SCorner_<1, Grid, Ghost, Order> Corner1; typedef SCorner_<2, Grid, Ghost, Order> Corner2; typedef SCorner_<3, Grid, Ghost, Order> Corner3; typedef SIndex_<1> Index1; typedef SIndex_<2> Index2; typedef SIndex_<3> Index3; typedef SLoop_<DIM, Field> Loop; static spActor WireFrame( const Grid2& grid, int color_idx = -1) { spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with line lc variable"; int c = (color_idx == -1) ? 0 : color_idx; short order[] = { 0, 1, 3, 2, 6, 4, 5, 7 }; for (St j = 0; j < grid.n(_Y_); j++) { for (St i = 0; i < grid.n(_X_); i++) { typename Grid2::Index index(i, j); for (short o = 0; o < grid.num_vertex(); ++o) { auto p = grid.v(order[o], index); actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), c, " ")); } auto p = grid.v(0, index); actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), c, " ")); actor->data().push_back(""); } } return actor; } static spActor CenterPoints(const Grid1& grid, int color_idx = -1){ spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with points lc variable"; int c = (color_idx == -1) ? 0 : color_idx; for (St i = 0; i < grid.n(_X_); i++) { typename Grid1::Index index(i); auto p = grid.c(index); actor->data().push_back( ToString(p.value(_X_), 0.0, c, " ")); actor->data().push_back(""); } return actor; } static spActor CenterPoints(const Grid2& grid, int color_idx = -1){ spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with points lc variable"; int c = (color_idx == -1) ? 0 : color_idx; for (St j = 0; j < grid.n(_Y_); j++) { for (St i = 0; i < grid.n(_X_); i++) { typename Grid2::Index index(i, j); auto p = grid.c(index); actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), c, " ")); actor->data().push_back(""); } } return actor; } //plot by splot static spActor FacePoints(const VF2& vf, int color_idx = 1){ spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3:4 title \"\" "; actor->style() = "with points lc variable"; int c = (color_idx == -1) ? 0 : color_idx; for (auto& index : vf.order()) { for(St d = 0; d < 2; d++){ if(vf.ghost().is_boundary(index, d, _M_)){ auto fm = vf.grid().f(d, _M_, index); auto v = vf(d, _M_, index); if(color_idx < 0){ c = v; } actor->data().push_back(ToString(fm.x(), fm.y(), v, c, " ")); } auto fp = vf.grid().f(d, _P_, index); auto v = vf(d, _P_, index); if (color_idx < 0) { c = v; } actor->data().push_back(ToString(fp.x(), fp.y(), v, c, " ")); } } return actor; } static spActor Contour(const Field2& f){ spActor actor = spActor(new Gnuplot_actor()); auto ghost = f.spghost(); actor->command() = "using 1:2:3:4:5:6:7 title \"\" "; actor->style() = "with boxxy fs solid palette"; for (St i = 0; i < f.grid().n(_X_); i++) { for (St j = 0; j < f.grid().n(_Y_); j++) { Index2 index(i, j); if (ghost->is_normal(index) == true) { auto pc = f.grid().c(index); auto pmin = f.grid().v(0, index); auto pmax = f.grid().v(3, index); actor->data().push_back( ToString(pc(_X_), pc(_Y_), pmin(_X_), pmax(_X_), pmin(_Y_), pmax(_Y_), f(index), " ")); } } } return actor; } static spActor ContourWire(const Field2& f){ spActor actor = spActor(new Gnuplot_actor()); auto ghost = f.spghost(); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with line lc palette"; for (St i = 0; i < f.grid().n(_X_); i++) { for (St j = 0; j < f.grid().n(_Y_); j++) { Index2 index(i, j); if (ghost->is_normal(index) == true) { auto pc = f.grid().c(index); actor->data().push_back( ToString(pc(_X_), pc(_Y_), f(index), f(index), " ")); } } actor->data().push_back(""); } return actor; } static spActor Contour(const Field1& f){ SHOULD_NOT_REACH; } static spActor WireFrame(const Ghost2& g, int color_idx = 1) { typedef CuboidToolPL2_<Vt> Tool; spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with line lc variable"; int c = (color_idx == -1) ? 0 : color_idx; short order[] = { 0, 1, 3, 2, 6, 4, 5, 7 }; auto& grid = g.grid(); auto gl = grid.ghost_layer(); for (int j = -gl; j < grid.n(_Y_) + gl; j++) { for (int i = -gl; i < grid.n(_X_) + gl; i++) { typename Grid2::Index index(i, j); if (g.is_ghost(index)) { for (short o = 0; o < grid.num_vertex(); ++o) { auto p = grid.v(order[o], index); actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), c, " ")); } auto p = grid.v(0, index); actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), c, " ")); actor->data().push_back(""); } } } return actor; } static spActor WireFrameCut( const GhostLinearCut2& g, int color_idx = 1) { typedef CuboidToolPL2_<Vt> Tool; Tool tool; spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with line lc variable"; int c = (color_idx == -1) ? 0 : color_idx; short order[] = { 0, 1, 3, 2, 6, 4, 5, 7 }; auto& grid = g.grid(); auto gl = grid.ghost_layer(); for (int j = -gl; j < grid.n(_Y_) + gl; j++) { for (int i = -gl; i < grid.n(_X_) + gl; i++) { typename Grid2::Index index(i, j); if (g.is_cut(index)) { auto po = grid.v(0, index); auto sx = grid.s_(_X_, index); auto sy = grid.s_(_Y_, index); for (short o = 0; o < grid.num_vertex(); ++o) { auto p = grid.v(order[o], index); actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), c, " ")); } auto p = grid.v(0, index); actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), c, " ")); actor->data().push_back(""); } } } return actor; } static spActor WireFrameCutInterface( const GhostLinearCut2& g, int color_idx = 1) { typedef CuboidToolPL2_<Vt> Tool; Tool tool; spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with line lc variable"; int c = (color_idx == -1) ? 0 : color_idx; short order[] = { 0, 1, 3, 2, 6, 4, 5, 7 }; auto& grid = g.grid(); auto gl = grid.ghost_layer(); for (int j = -gl; j < grid.n(_Y_) + gl; j++) { for (int i = -gl; i < grid.n(_X_) + gl; i++) { typename Grid2::Index index(i, j); if (g.is_cut(index)) { auto spcell = g(index); auto arr = spcell->get_aperture_ratio(); auto po = grid.v(0, index); auto sx = grid.s_(_X_, index); auto sy = grid.s_(_Y_, index); auto sp = tool.start_point(po.x(), po.y(), sx, sy, arr); auto ep = tool.end_point(po.x(), po.y(), sx, sy, arr); actor->data().push_back(""); actor->data().push_back( ToString(sp.value(_X_), sp.value(_Y_), c, " ")); actor->data().push_back( ToString(ep.value(_X_), ep.value(_Y_), c, " ")); actor->data().push_back(""); } } } return actor; } static spActor WireFrameCutInterface( const GhostLinearCut2& g, const Index2& index, int color_idx = 1) { typedef CuboidToolPL2_<Vt> Tool; Tool tool; spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with line lc variable"; int c = (color_idx == -1) ? 0 : color_idx; short order[] = { 0, 1, 3, 2, 6, 4, 5, 7 }; auto& grid = g.grid(); if (g.is_cut(index)) { auto spcell = g(index); auto arr = spcell->get_aperture_ratio(); auto po = grid.v(0, index); auto sx = grid.s_(_X_, index); auto sy = grid.s_(_Y_, index); auto sp = tool.start_point(po.x(), po.y(), sx, sy, arr); auto ep = tool.end_point(po.x(), po.y(), sx, sy, arr); actor->data().push_back(""); actor->data().push_back( ToString(sp.value(_X_), sp.value(_Y_), c, " ")); actor->data().push_back( ToString(ep.value(_X_), ep.value(_Y_), c, " ")); actor->data().push_back(""); } return actor; } static spActor WireFrameCutGhostSide( const GhostLinearCut2& g, int color_idx = 1) { typedef CuboidToolPL2_<Vt> Tool; Tool tool; spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with line lc variable"; int c = (color_idx == -1) ? 0 : color_idx; short order[] = { 0, 1, 3, 2, 6, 4, 5, 7 }; auto& grid = g.grid(); auto gl = grid.ghost_layer(); for (int j = -gl; j < grid.n(_Y_) + gl; j++) { for (int i = -gl; i < grid.n(_X_) + gl; i++) { typename Grid2::Index index(i, j); if (g.is_cut(index)) { auto spcell = g(index); auto arr = spcell->get_aperture_ratio(); auto po = grid.v(0, index); auto sx = grid.s_(_X_, index); auto sy = grid.s_(_Y_, index); auto pc = tool.cut_cell_point_chain_ghost_side(po.x(), po.y(), sx, sy, arr); for (auto p : pc) { actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), c, " ")); } auto p = pc.front(); actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), c, " ")); actor->data().push_back(""); } } } return actor; } static spActor WireFrameCutNormalSide( const GhostLinearCut2& g, int color_idx = 1) { typedef CuboidToolPL2_<Vt> Tool; Tool tool; spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with line lc variable"; int c = (color_idx == -1) ? 0 : color_idx; short order[] = { 0, 1, 3, 2, 6, 4, 5, 7 }; auto& grid = g.grid(); auto gl = grid.ghost_layer(); for (int j = -gl; j < grid.n(_Y_) + gl; j++) { for (int i = -gl; i < grid.n(_X_) + gl; i++) { typename Grid2::Index index(i, j); if (g.is_cut(index)) { auto spcell = g(index); auto arr = spcell->get_aperture_ratio(); auto po = grid.v(0, index); auto sx = grid.s_(_X_, index); auto sy = grid.s_(_Y_, index); auto pc = tool.cut_cell_point_chain_normal_side(po.x(), po.y(), sx, sy, arr); for (auto p : pc) { actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), c, " ")); } auto p = pc.front(); actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), c, " ")); actor->data().push_back(""); } } } return actor; } static spActor Boundary(const Ghost2& g) { spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with line lc variable"; int c = 0; short order[] = { 0, 1, 3, 2, 6, 4, 5, 7 }; auto& grid = g.grid(); auto gl = grid.ghost_layer(); for (int j = 0; j < grid.n(_Y_); j++) { for (int i = 0; i < grid.n(_X_); i++) { typename Grid2::Index index(i, j); for (St d = 0; d < 2; d++) { for (St o = 0; o < 2; o++) { if (g.is_boundary(index, d, o)) { auto idxg = index.shift(d, o); auto bid = g.boundary_id(index, idxg, d, o); auto fc = grid.f(d, o, index); auto dalt = (d==_X_)? _Y_:_X_; auto hs = grid.hs_(dalt, index); if(dalt == _X_){ actor->data().push_back( ToString(fc.x() - hs, fc.y(), bid, " ")); actor->data().push_back( ToString(fc.x() + hs, fc.y(), bid, " ")); actor->data().push_back(""); }else{ actor->data().push_back( ToString(fc.x(), fc.y() - hs, bid, " ")); actor->data().push_back( ToString(fc.x(), fc.y() + hs, bid, " ")); actor->data().push_back(""); } } } } } } return actor; } static void _AppendCutBoundary(spActor actor, const Grid2& grid, const Index2& index, const CellLinearCut2& cell){ } static spActor WireFrame( const Grid1& grid, const Vt& tik = 0.1, int color_idx = -1) { spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with line lc variable"; int c = (color_idx == -1) ? 0 : color_idx; short order[] = { 0, 1, 3, 2, 6, 4, 5, 7 }; Vt xs, xe; for (St i = 0; i < grid.n(_X_); i++) { typename Grid1::Index index(i); auto p = grid.f(_X_, _M_, index); actor->data().push_back( ToString(p.value(_X_), -0.0, c, " ")); actor->data().push_back( ToString(p.value(_X_), tik, c, " ")); actor->data().push_back(""); if(i == 0){ xs = p.value(_X_); } } typename Grid1::Index index(grid.n(_X_) - 1); auto p = grid.f(_X_, _P_, index); actor->data().push_back( ToString(p.value(_X_), -0.0, c, " ")); actor->data().push_back( ToString(p.value(_X_), tik, c, " ")); actor->data().push_back(""); xe = p.value(_X_); actor->data().push_back(ToString(xs, 0.0, c, " ")); actor->data().push_back(ToString(xe, 0.0, c, " ")); return actor; } static spActor Lines(const Field1& s, int color_idx = -1) { spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with line lc variable"; for(auto& index: s.order()){ auto x = s.grid().c_(_X_, index); auto v = s(index); if (color_idx >= 0) { actor->data().push_back( ToString(x, v, color_idx, " ")); } else { actor->data().push_back( ToString(x, v, 0, " ")); } } return actor; } static spActor Lines(const Field2& s, int color_idx = -1) { SHOULD_NOT_REACH; } static spActor LinesPoints(const Field1& s, int color_idx = -1) { spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with linespoints lc variable"; int c = (color_idx == -1) ? 0 : color_idx; for (auto& index : s.order()) { auto x = s.grid().c_(_X_, index); auto v = s(index); actor->data().push_back(ToString(x, v, c, " ")); } return actor; } static spActor LinesPoints(const Corner1& s, int color_idx = -1) { spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with linespoints lc variable"; int c = (color_idx == -1) ? 0 : color_idx; for (auto& index : s.order()) { if (s.ghost().is_boundary(index, _X_, _M_)) { auto p = s.grid().v(0, index); auto v = s(1, index); actor->data().push_back(ToString(p.x(), v, c, " ")); } auto p = s.grid().v(1, index); auto v = s(1, index); actor->data().push_back(ToString(p.x(), v, c, " ")); } return actor; } static spActor LinesPoints(const VC1& s, int color_idx = -1) { spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with linespoints lc variable"; int c = (color_idx == -1) ? 0 : color_idx; for (auto& index : s.order()) { auto x = s.grid().c_(_X_, index); auto v = s[_X_](index); actor->data().push_back(ToString(x, v, c, " ")); } return actor; } static spActor LinesPoints(const VF1& s, int color_idx = -1) { spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3 title \"\" "; actor->style() = "with linespoints lc variable"; int c = (color_idx == -1) ? 0 : color_idx; for (auto& index : s.order()) { if(s.ghost().is_boundary(index, _X_, _M_)){ auto p = s.grid().f(_X_,_M_, index); auto v = s(_X_, _M_, index); actor->data().push_back(ToString(p.x(), v, c, " ")); } auto p = s.grid().f(_X_,_P_, index); auto v = s(_X_, _P_, index); actor->data().push_back(ToString(p.x(), v, c, " ")); } return actor; } static spActor Arrows( const VC1& s, Vt unit_length = -1.0, int color_idx = -1) { spActor actor = spActor(new Gnuplot_actor()); Vt color = color_idx; actor->command() = "using 1:2:3:4:5 title \"\" "; actor->style() = "with vectors lc variable"; if(unit_length <= 0){ unit_length = s[_X_].max() * 2.0; } auto gmin_size = s.grid().min_size(); for (auto& index : s.order()) { auto x = s.grid().c_(_X_, index); Vt y = 0.0; auto v = s[_X_](index); auto dx = v / unit_length * gmin_size; Vt dy = 0.0; if(color_idx < 0){ color = v; } actor->data().push_back(ToString(x, y, dx, dy, color, " ")); } return actor; } static spActor Arrows( const VF1& s, Vt unit_length = -1.0, int color_idx = -1) { spActor actor = spActor(new Gnuplot_actor()); Vt color = color_idx; actor->command() = "using 1:2:3:4:5 title \"\" "; actor->style() = "with vectors lc variable"; if(unit_length <= 0){ unit_length = s.max() * 2.0; } auto gmin_size = s.grid().min_size(); for (auto& index : s.order()) { if(s.ghost().is_boundary(index, _X_, _M_)){ auto fm = s.grid().f(_X_, _M_, index); auto v = s(_X_, _M_, index); auto dx = v / unit_length * gmin_size; Vt x = fm(_X_) - (dx * 0.5); Vt y = 0.0; Vt dy = 0.0; if(color_idx < 0){ color = v; } actor->data().push_back(ToString(x, y, dx, dy, color, " ")); } auto fp = s.grid().f(_X_, _P_, index); auto v = s(_X_, _P_, index); auto dx = v / unit_length * gmin_size; Vt x = fp(_X_) - (dx * 0.5); Vt y = 0.0; Vt dy = 0.0; if (color_idx < 0) { color = v; } actor->data().push_back(ToString(x, y, dx, dy, color, " ")); } return actor; } static spActor Arrows( const VF2& s, Vt unit_length = -1.0, int color_idx = -1) { spActor actor = spActor(new Gnuplot_actor()); Vt color = color_idx; actor->command() = "using 1:2:3:4:5 title \"\" "; actor->style() = "with vectors lc variable"; if(unit_length <= 0){ unit_length = s.max() * 2.0; } auto gmin_size = s.grid().min_size(); for (auto& index : s.order()) { for(St d = 0; d < 2; d++){ if(s.ghost().is_boundary(index, d, _M_)){ auto fm = s.grid().f(d, _M_, index); auto v = s(d, _M_, index); auto dl = v / unit_length * gmin_size; Vt x = (d == _X_) ? fm(d) - (dl * 0.5) : fm.x(); Vt y = (d == _X_) ? fm.y() : (fm(d) - (dl * 0.5)); Vt dx = (d == _X_) ? dl : 0.0; Vt dy = (d == _X_) ? 0.0: dl; if(color_idx < 0){ color = v; } actor->data().push_back(ToString(x, y, dx, dy, color, " ")); } auto fp = s.grid().f(d, _P_, index); auto v = s(d, _P_, index); auto dl = v / unit_length * gmin_size; Vt x = (d == _X_) ? fp(d) - (dl * 0.5) : fp.x(); Vt y = (d == _X_) ? fp.y() : (fp(d) - (dl * 0.5)); Vt dx = (d == _X_) ? dl : 0.0; Vt dy = (d == _X_) ? 0.0: dl; if (color_idx < 0) { color = v; } actor->data().push_back(ToString(x, y, dx, dy, color, " ")); } } return actor; } static spActor ArrowsAxesAlign( const VC2& s, Vt unit_length = -1.0, int color_idx = -1) { spActor actor = spActor(new Gnuplot_actor()); Vt colorx = color_idx; Vt colory = color_idx; actor->command() = "using 1:2:3:4:5 title \"\" "; actor->style() = "with vectors lc variable"; if(unit_length <= 0){ auto xmax = s[_X_].max() * 2.0; auto ymax = s[_Y_].max() * 2.0; unit_length = std::max(xmax, ymax); } auto gmin_size = s.grid().min_size(); for (auto& index : s.order()) { auto x = s.grid().c_(_X_, index); auto y = s.grid().c_(_Y_, index); auto vx = s[_X_](index); auto vy = s[_Y_](index); auto dx = vx / unit_length * gmin_size; auto dy = vy / unit_length * gmin_size; if(color_idx < 0){ colorx = vx; colory = vy; } actor->data().push_back(ToString(x, y, dx, 0.0, colorx, " ")); actor->data().push_back(ToString(x, y, 0.0, dy, colory, " ")); } return actor; } static spActor Arrows( const VC2& s, Vt unit_length = -1.0, int color_idx = -1) { spActor actor = spActor(new Gnuplot_actor()); Vt color = color_idx; actor->command() = "using 1:2:3:4:5 title \"\" "; actor->style() = "with vectors lc variable"; auto ss = SquareSum(s[_X_], s[_Y_]); if (unit_length <= 0) { unit_length = std::sqrt(ss.max()) * 2.0; } auto gmin_size = s.grid().min_size(); for (auto& index : s.order()) { auto x = s.grid().c_(_X_, index); auto y = s.grid().c_(_Y_, index); auto vx = s[_X_](index); auto vy = s[_Y_](index); auto dx = vx / unit_length * gmin_size; auto dy = vy / unit_length * gmin_size; if (color_idx < 0) { color = std::sqrt(ss(index)); } actor->data().push_back(ToString(x, y, dx, dy, color, " ")); } return actor; } static spActor Arrows( const VC3& s, Vt unit_length = -1.0, int color_idx = -1) { spActor actor = spActor(new Gnuplot_actor()); Vt color = color_idx; actor->command() = "using 1:2:3:4:5:6:7 title \"\" "; actor->style() = "with vectors lc variable"; auto ss = SquareSum(s[_X_], s[_Y_], s[_Z_]); if (unit_length <= 0) { unit_length = std::sqrt(ss.max()) * 2.0; } auto gmin_size = s.grid().min_size(); for (auto& index : s.order()) { auto x = s.grid().c_(_X_, index); auto y = s.grid().c_(_Y_, index); auto z = s.grid().c_(_Z_, index); auto vx = s[_X_](index); auto vy = s[_Y_](index); auto vz = s[_Z_](index); auto dx = vx / unit_length * gmin_size; auto dy = vy / unit_length * gmin_size; auto dz = vz / unit_length * gmin_size; if (color_idx < 0) { color = std::sqrt(ss(index)); } actor->data().push_back(ToString(x, y, z, dx, dy, dz, color, " ")); } return actor; } static spActor WireFrame( const Corner2& corner, int color_idx = -1 ){ spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3:4 title \"\" "; actor->style() = "with lines lc variable"; int c = (color_idx == -1) ? 0 : color_idx; for (auto& idx : corner.order()) { short order[] = { 0, 1, 3, 2, 0}; for (short o = 0; o < 5; ++o) { auto p = corner.grid().v(order[o], idx); auto vc = corner(order[o], idx); actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), vc, vc, " ")); // std::cout << ToString(p.value(_X_), // p.value(_Y_), // vc, // vc, // " ") << std::endl; } actor->data().push_back(""); //splot sperated with two lines actor->data().push_back(""); } return actor; } // splot static spActor WireFrame( const Grid3& grid, int color_idx = -1) { spActor actor = spActor(new Gnuplot_actor()); actor->command() = "using 1:2:3:4 title \"\" "; actor->style() = "with lines lc variable"; int c = (color_idx == -1) ? 0 : color_idx; short order1[] = { 0, 1, 3, 2, 0 }; //xm short order2[] = { 4, 5, 7, 6, 4 }; //xp short order3[] = { 0, 4, 5, 1, 0 }; //ym short order4[] = { 2, 3, 7, 6, 2 }; //ym for (St k = 0; k < grid.n(_Z_); k++) { for (St j = 0; j < grid.n(_Y_); j++) { for (St i = 0; i < grid.n(_X_); i++) { typename Grid3::Index index(i, j, k); for (short o = 0; o < 5; ++o) { typename Grid3::Poi p = grid.v(order1[o], index); actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), p.value(_Z_), c, " ")); } actor->data().push_back(""); //splot sperated with two lines actor->data().push_back(""); for (short o = 0; o < 5; ++o) { typename Grid3::Poi p = grid.v(order2[o], index); actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), p.value(_Z_), c, " ")); } actor->data().push_back(""); actor->data().push_back(""); for (short o = 0; o < 5; ++o) { typename Grid3::Poi p = grid.v(order3[o], index); actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), p.value(_Z_), c, " ")); } actor->data().push_back(""); actor->data().push_back(""); for (short o = 0; o < 5; ++o) { typename Grid3::Poi p = grid.v(order4[o], index); actor->data().push_back( ToString(p.value(_X_), p.value(_Y_), p.value(_Z_), c, " ")); } actor->data().push_back(""); actor->data().push_back(""); } } } return actor; } static Gnuplot& OrderLabel(Gnuplot& gnu, const Order& order){ spActor actor = spActor(new Gnuplot_actor()); auto& grid = order.grid(); auto& ghost = order.ghost(); auto fun = [&actor, &grid, &ghost, &gnu, &order](const Index& idx, St tn){ auto cp = grid.c(idx); auto o = order.get_order(idx); std::string text = ToString(tn) + ", " + ToString(o); std::string adds = " center textcolor lt " + ToString(tn + 1); gnu.set_label(o+1, text, cp.x(), cp.y(), adds); }; Loop::ForEachIndex(order, fun); return gnu; } }; } #endif
36.252459
118
0.45591
hyperpower
3b733e6e5f21df17de7c12862ca8ccb3f0e50141
871
cpp
C++
137-SingleNumberII.cpp
frost1990/leetcode_anwsers
ad7f84089b11591fab0f9407bc87b9f3fa8f2cf2
[ "MIT" ]
null
null
null
137-SingleNumberII.cpp
frost1990/leetcode_anwsers
ad7f84089b11591fab0f9407bc87b9f3fa8f2cf2
[ "MIT" ]
null
null
null
137-SingleNumberII.cpp
frost1990/leetcode_anwsers
ad7f84089b11591fab0f9407bc87b9f3fa8f2cf2
[ "MIT" ]
null
null
null
/* Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? */ #include <stdio.h> #include <vector> using namespace std; class Solution { public: int singleNumber(vector<int>& nums) { int ones = 0; int twos = 0; int not_threes = 0; for (size_t i = 0; i < nums.size(); i++) { twos |= ones & nums[i]; ones ^= nums[i]; not_threes = ~(ones & twos); ones &= not_threes; twos &= not_threes; } return ones; } }; int main() { int array[16] = {0, 0, 0, 1, 1, 1, 4, 3, 3, 3, 6, 6, 6, 2, 2, 2}; vector <int> source; for (int i = 0; i < 16; i++) { source.push_back(array[i]); } Solution s; int ret = s.singleNumber(source); printf("Return value is %d\n", ret); return 0; }
20.255814
106
0.617681
frost1990
3b7534d0bdfc267090cf3e38032d7fb0681b645c
1,779
hpp
C++
include/alb-program.hpp
albertonl/alb
8779ed2f047d63eff2bc96b658b2659641364322
[ "MIT" ]
2
2019-06-08T16:47:22.000Z
2019-06-08T16:56:18.000Z
include/alb-program.hpp
albertonl/alb
8779ed2f047d63eff2bc96b658b2659641364322
[ "MIT" ]
2
2019-02-02T21:15:45.000Z
2019-06-10T08:23:09.000Z
include/alb-program.hpp
albertonl/alb
8779ed2f047d63eff2bc96b658b2659641364322
[ "MIT" ]
1
2019-06-08T17:23:55.000Z
2019-06-08T17:23:55.000Z
/* Program class and reserved keywords The ALB Programming Language Alberto Navalon Lillo (C) 2019 This software is distributed under the MIT license Visit https://github.com/albertonl/alb/LICENSE for further details */ #ifndef ALB_PROGRAM_HPP #define ALB_PROGRAM_HPP #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <cstdlib> #include <cstdio> #include <cmath> #include <ctime> #include <string> #include "alb-statement.hpp" // Program class and reserved keywords using namespace alb_statement; namespace alb_program{ // Reserved keywords enum keywords{ GENERAL, BEGIN,END }; // Program class class Program{ private: std::vector<Statement> statements; public: Program() = default; // Void constructor void readSource(const std::string& fileName){ // Read source code into vector ifstream source; // source file std::string holder; // to hold the value of the current token source.open(fileName.c_str(), ios::in); // Open file in read mode // Now, we will read the file until we reach the end while(!source.eof()){ // Complete here } source.close(); } // void readSource() // This function can be executed slowly, specially in large files }; void Program::readSource(const std::string& fileName){ ifstream source; // File source.open(fileName.c_str(), ios::in); // Open file in read mode (allowing input) // Now, we will read the file until it finishes while(!source.eof()){ } source.close(); // Close file } // void Program::readSource() /* TODO: - Complete loop in readSource() so it reads every token and stores it with its corresponding attributes (level, type) in the vector statements */ } // alb_program #endif // ALB_PROGRAM_HPP
23.103896
145
0.704328
albertonl
3b7af5708aadc588cb20cd34edfb9868f866e02f
295
cpp
C++
Uva/uva11401.cpp
Tunghohin/Competitive_coding
879238605d5525cda9fd0cfa1155ba67959179a6
[ "MIT" ]
2
2021-09-06T08:34:00.000Z
2021-11-22T14:52:41.000Z
Uva/uva11401.cpp
Tunghohin/Competitive_coding
879238605d5525cda9fd0cfa1155ba67959179a6
[ "MIT" ]
null
null
null
Uva/uva11401.cpp
Tunghohin/Competitive_coding
879238605d5525cda9fd0cfa1155ba67959179a6
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; unsigned long long f[1000010]; int main() { for (int i = 4; i <= 1000000; i++) { f[i] = f[i - 1] + ((unsigned long long)(i - 1) * (i - 2) / 2 - (i - 1) / 2) / 2; } int n; while (cin >> n) { if (n < 3) return 0; cout << f[n] << '\n'; } }
14.047619
82
0.477966
Tunghohin
3b82c1b77ccb6b643f712a3a8156f8475ca7dbc1
1,128
cpp
C++
BOJ4949_balanced/balanced.cpp
wjoh0315/BOJSolution2
3bf41835d5bc04c92a0104d3651fb009298f08d7
[ "MIT" ]
null
null
null
BOJ4949_balanced/balanced.cpp
wjoh0315/BOJSolution2
3bf41835d5bc04c92a0104d3651fb009298f08d7
[ "MIT" ]
null
null
null
BOJ4949_balanced/balanced.cpp
wjoh0315/BOJSolution2
3bf41835d5bc04c92a0104d3651fb009298f08d7
[ "MIT" ]
null
null
null
//https://www.acmicpc.net/problem/4949 #include <iostream> #include <string> using namespace std; int stack[100]; int top = -1; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); while (true) { top = -1; string in; getline(cin, in, '.'); if (in.length() <= 1) break; for (int i=0; i < in.length(); i++) { if (in[i] == '(') { top++; stack[top] = 0; } else if (in[i] == ')') { if (--top < -1) break; if (stack[++top] != 0) break; top--; } else if (in[i] == '[') { top++; stack[top] = 1; } else if (in[i] == ']') { if (--top < -1) break; if (stack[++top] != 1) break; top--; } } cout << (top == -1 ? "yes" : "no") << '\n'; } }
20.509091
51
0.296099
wjoh0315
3b838143d4abf80840c758eaf84d7a3a74cb9e20
9,735
cc
C++
modules/audio_coding/main/source/acm_celt.cc
SlimXperiments/external_chromium_org_third_party_webrtc
14c8d0b9402c3eaa282f34f7652c08a5b624279e
[ "DOC", "BSD-3-Clause" ]
1
2019-02-22T05:37:43.000Z
2019-02-22T05:37:43.000Z
modules/audio_coding/main/source/acm_celt.cc
SlimXperiments/external_chromium_org_third_party_webrtc
14c8d0b9402c3eaa282f34f7652c08a5b624279e
[ "DOC", "BSD-3-Clause" ]
null
null
null
modules/audio_coding/main/source/acm_celt.cc
SlimXperiments/external_chromium_org_third_party_webrtc
14c8d0b9402c3eaa282f34f7652c08a5b624279e
[ "DOC", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/audio_coding/main/source/acm_celt.h" #include "webrtc/modules/audio_coding/main/acm2/acm_common_defs.h" #include "webrtc/modules/audio_coding/main/source/acm_neteq.h" #include "webrtc/modules/audio_coding/neteq/interface/webrtc_neteq.h" #include "webrtc/modules/audio_coding/neteq/interface/webrtc_neteq_help_macros.h" #include "webrtc/system_wrappers/interface/trace.h" #ifdef WEBRTC_CODEC_CELT // NOTE! Celt is not included in the open-source package. Modify this file or // your codec API to match the function call and name of used Celt API file. #include "celt_interface.h" #endif namespace webrtc { namespace acm1 { #ifndef WEBRTC_CODEC_CELT ACMCELT::ACMCELT(int16_t /* codec_id */) : enc_inst_ptr_(NULL), dec_inst_ptr_(NULL), sampling_freq_(0), bitrate_(0), channels_(1), dec_channels_(1) { return; } ACMCELT::~ACMCELT() { return; } int16_t ACMCELT::InternalEncode(uint8_t* /* bitstream */, int16_t* /* bitstream_len_byte */) { return -1; } int16_t ACMCELT::DecodeSafe(uint8_t* /* bitstream */, int16_t /* bitstream_len_byte */, int16_t* /* audio */, int16_t* /* audio_samples */, int8_t* /* speech_type */) { return -1; } int16_t ACMCELT::InternalInitEncoder(WebRtcACMCodecParams* /* codec_params */) { return -1; } int16_t ACMCELT::InternalInitDecoder(WebRtcACMCodecParams* /* codec_params */) { return -1; } int32_t ACMCELT::CodecDef(WebRtcNetEQ_CodecDef& /* codec_def */, const CodecInst& /* codec_inst */) { return -1; } ACMGenericCodec* ACMCELT::CreateInstance(void) { return NULL; } int16_t ACMCELT::InternalCreateEncoder() { return -1; } void ACMCELT::DestructEncoderSafe() { return; } int16_t ACMCELT::InternalCreateDecoder() { return -1; } void ACMCELT::DestructDecoderSafe() { return; } void ACMCELT::InternalDestructEncoderInst(void* /* ptr_inst */) { return; } bool ACMCELT::IsTrueStereoCodec() { return true; } int16_t ACMCELT::SetBitRateSafe(const int32_t /*rate*/) { return -1; } void ACMCELT::SplitStereoPacket(uint8_t* /*payload*/, int32_t* /*payload_length*/) {} #else //===================== Actual Implementation ======================= ACMCELT::ACMCELT(int16_t codec_id) : enc_inst_ptr_(NULL), dec_inst_ptr_(NULL), sampling_freq_(32000), // Default sampling frequency. bitrate_(64000), // Default rate. channels_(1), // Default send mono. dec_channels_(1) { // Default receive mono. // TODO(tlegrand): remove later when ACMGenericCodec has a new constructor. codec_id_ = codec_id; return; } ACMCELT::~ACMCELT() { if (enc_inst_ptr_ != NULL) { WebRtcCelt_FreeEnc(enc_inst_ptr_); enc_inst_ptr_ = NULL; } if (dec_inst_ptr_ != NULL) { WebRtcCelt_FreeDec(dec_inst_ptr_); dec_inst_ptr_ = NULL; } return; } int16_t ACMCELT::InternalEncode(uint8_t* bitstream, int16_t* bitstream_len_byte) { *bitstream_len_byte = 0; // Call Encoder. *bitstream_len_byte = WebRtcCelt_Encode(enc_inst_ptr_, &in_audio_[in_audio_ix_read_], bitstream); // Increment the read index this tell the caller that how far // we have gone forward in reading the audio buffer. in_audio_ix_read_ += frame_len_smpl_ * channels_; if (*bitstream_len_byte < 0) { // Error reported from the encoder. WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_, "InternalEncode: Encode error for Celt"); *bitstream_len_byte = 0; return -1; } return *bitstream_len_byte; } int16_t ACMCELT::DecodeSafe(uint8_t* /* bitstream */, int16_t /* bitstream_len_byte */, int16_t* /* audio */, int16_t* /* audio_samples */, int8_t* /* speech_type */) { return 0; } int16_t ACMCELT::InternalInitEncoder(WebRtcACMCodecParams* codec_params) { // Set bitrate and check that it is within the valid range. int16_t status = SetBitRateSafe((codec_params->codec_inst).rate); if (status < 0) { return -1; } // If number of channels changed we need to re-create memory. if (codec_params->codec_inst.channels != channels_) { WebRtcCelt_FreeEnc(enc_inst_ptr_); enc_inst_ptr_ = NULL; // Store new number of channels. channels_ = codec_params->codec_inst.channels; if (WebRtcCelt_CreateEnc(&enc_inst_ptr_, channels_) < 0) { return -1; } } // Initiate encoder. if (WebRtcCelt_EncoderInit(enc_inst_ptr_, channels_, bitrate_) >= 0) { return 0; } else { return -1; } } int16_t ACMCELT::InternalInitDecoder(WebRtcACMCodecParams* codec_params) { // If number of channels changed we need to re-create memory. if (codec_params->codec_inst.channels != dec_channels_) { WebRtcCelt_FreeDec(dec_inst_ptr_); dec_inst_ptr_ = NULL; // Store new number of channels. dec_channels_ = codec_params->codec_inst.channels; if (WebRtcCelt_CreateDec(&dec_inst_ptr_, dec_channels_) < 0) { return -1; } } // Initiate decoder, both master and slave parts. if (WebRtcCelt_DecoderInit(dec_inst_ptr_) < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_, "InternalInitDecoder: init decoder failed for Celt."); return -1; } if (WebRtcCelt_DecoderInitSlave(dec_inst_ptr_) < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_, "InternalInitDecoder: init decoder failed for Celt."); return -1; } return 0; } int32_t ACMCELT::CodecDef(WebRtcNetEQ_CodecDef& codec_def, const CodecInst& codec_inst) { if (!decoder_initialized_) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_, "CodecDef: Decoder uninitialized for Celt"); return -1; } // Fill up the structure by calling // "SET_CODEC_PAR" and "SET_CELT_FUNCTIONS" or "SET_CELTSLAVE_FUNCTIONS". // Then call NetEQ to add the codec to it's // database. if (codec_inst.channels == 1) { SET_CODEC_PAR(codec_def, kDecoderCELT_32, codec_inst.pltype, dec_inst_ptr_, 32000); } else { SET_CODEC_PAR(codec_def, kDecoderCELT_32_2ch, codec_inst.pltype, dec_inst_ptr_, 32000); } // If this is the master of NetEQ, regular decoder will be added, otherwise // the slave decoder will be used. if (is_master_) { SET_CELT_FUNCTIONS(codec_def); } else { SET_CELTSLAVE_FUNCTIONS(codec_def); } return 0; } ACMGenericCodec* ACMCELT::CreateInstance(void) { return NULL; } int16_t ACMCELT::InternalCreateEncoder() { if (WebRtcCelt_CreateEnc(&enc_inst_ptr_, num_channels_) < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_, "InternalCreateEncoder: create encoder failed for Celt"); return -1; } channels_ = num_channels_; return 0; } void ACMCELT::DestructEncoderSafe() { encoder_exist_ = false; encoder_initialized_ = false; if (enc_inst_ptr_ != NULL) { WebRtcCelt_FreeEnc(enc_inst_ptr_); enc_inst_ptr_ = NULL; } } int16_t ACMCELT::InternalCreateDecoder() { if (WebRtcCelt_CreateDec(&dec_inst_ptr_, dec_channels_) < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_, "InternalCreateDecoder: create decoder failed for Celt"); return -1; } return 0; } void ACMCELT::DestructDecoderSafe() { decoder_exist_ = false; decoder_initialized_ = false; if (dec_inst_ptr_ != NULL) { WebRtcCelt_FreeDec(dec_inst_ptr_); dec_inst_ptr_ = NULL; } } void ACMCELT::InternalDestructEncoderInst(void* ptr_inst) { if (ptr_inst != NULL) { WebRtcCelt_FreeEnc(static_cast<CELT_encinst_t*>(ptr_inst)); } return; } bool ACMCELT::IsTrueStereoCodec() { return true; } int16_t ACMCELT::SetBitRateSafe(const int32_t rate) { // Check that rate is in the valid range. if ((rate >= 48000) && (rate <= 128000)) { // Store new rate. bitrate_ = rate; // Initiate encoder with new rate. if (WebRtcCelt_EncoderInit(enc_inst_ptr_, channels_, bitrate_) >= 0) { return 0; } else { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_, "SetBitRateSafe: Failed to initiate Celt with rate %d", rate); return -1; } } else { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_, "SetBitRateSafe: Invalid rate Celt, %d", rate); return -1; } } // Copy the stereo packet so that NetEq will insert into both master and slave. void ACMCELT::SplitStereoPacket(uint8_t* payload, int32_t* payload_length) { // Check for valid inputs. assert(payload != NULL); assert(*payload_length > 0); // Duplicate the payload. memcpy(&payload[*payload_length], &payload[0], sizeof(uint8_t) * (*payload_length)); // Double the size of the packet. *payload_length *= 2; } #endif } // namespace acm1 } // namespace webrtc
28.632353
81
0.662763
SlimXperiments
3b8570b57474c122b44a6915d9975d7bfd83e575
4,901
cpp
C++
np2-rwg/lib/utility.cpp
rightson/network-programming
e656ad08db412c6bbc630f9353bcc5ad61de4f73
[ "MIT" ]
null
null
null
np2-rwg/lib/utility.cpp
rightson/network-programming
e656ad08db412c6bbc630f9353bcc5ad61de4f73
[ "MIT" ]
null
null
null
np2-rwg/lib/utility.cpp
rightson/network-programming
e656ad08db412c6bbc630f9353bcc5ad61de4f73
[ "MIT" ]
null
null
null
#include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> // inet_ntoa #include <fcntl.h> // O_WRONLY #include <sys/stat.h> // mkfifo #include <sys/wait.h> // waitpid #include <sstream> #include "utility.hpp" void die(const char *format, ...) { va_list args; va_start(args, format); vprintf(format, args); va_end(args); exit(EXIT_FAILURE); } char *formatToMessage(const char *format, ...) { static char message[MAX_BUFFER_SIZE]; va_list args; va_start(args, format); vsnprintf(message, MAX_BUFFER_SIZE, format, args); va_end(args); message[strlen(message)] = '\0'; return message; } size_t writeFD(int fd, const char *format, ...) { char buffer[MAX_BUFFER_SIZE]; va_list args; va_start(args, format); vsnprintf(buffer, MAX_BUFFER_SIZE, format, args); va_end(args); buffer[strlen(buffer)] = '\0'; return write(fd, buffer, strlen(buffer)); } size_t readFD(int fd, char *message) { int n = read(fd, message, MAX_BUFFER_SIZE); if (n >= 0) { message[n] = '\0'; } return n; } void createFIFO(const char *fifopath) { if (access(fifopath, F_OK) != -1) { printf("[utility] unlink(%s)\n", fifopath); unlink(fifopath); } printf("[utility] mkfifo(%s, 0755)\n", fifopath); if (mkfifo(fifopath, 0755) == -1) { die("Failed to mkfifo at %s\n"); } } size_t readFIFO(const char *fifopath, char *message) { int fifofd = open(fifopath, O_RDONLY); size_t n = readFD(fifofd, message); close(fifofd); return n; } size_t writeFIFO(const char *fifopath, const char *message) { int fifofd = open(fifopath, O_WRONLY); size_t n = writeFD(fifofd, message); close(fifofd); return n; } char *getIpPortBinding(struct sockaddr_in &cliAddr) { const int MAX_IP_ADDR = 30; char ipAddr[MAX_IP_ADDR]; inet_ntop(AF_INET, &cliAddr.sin_addr, ipAddr, sizeof(ipAddr)); int port = ntohs(cliAddr.sin_port); const int MAX_NAME_SIZE = 36; static char buffer[MAX_NAME_SIZE]; // dirty sprintf(buffer, "%s/%d", ipAddr, port); return buffer; } int getListenSocket(const int port, const int listenQ) { int sockfd; struct sockaddr_in servAddr; sockfd = ::socket(PF_INET, SOCK_STREAM, 0); if (sockfd < 0) { die("Error: failed to create socket\n"); } int enable = 1; if (::setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) { die("Error: failed to set socket option to SO_REUSEADDR"); } memset((char *) &servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_port = htons(port); servAddr.sin_addr.s_addr = htonl(INADDR_ANY); if (::bind(sockfd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0) { die("Error: failed to bind socket %d with port %d\n", sockfd, port); } if (::listen(sockfd, listenQ) < 0) { die("Error: failed to listen socket %d with port %d\n", sockfd, port); } return sockfd; } int getAcceptSocket(int listenfd, struct sockaddr_in &cliAddr) { memset((char *) &cliAddr, 0, sizeof(cliAddr)); socklen_t clientLen = sizeof(cliAddr); int sockfd = ::accept(listenfd, (struct sockaddr *)&cliAddr, &clientLen); if (sockfd < 0) { printf("Error: failed to accept socket (connfd = %d)\n", sockfd); } return sockfd; } void explodeString(const std::string &buffer, std::vector<std::string>& tokens) { std::string token; std::istringstream iss(buffer); while (iss >> token) { tokens.push_back(token); } } char** stringVector2CharArray(const std::vector<std::string> &stringVector, std::vector<char*>& argv) { argv.clear(); for (size_t i = 0; i < stringVector.size(); ++i) { argv.push_back((char *)stringVector[i].c_str()); } argv.push_back(NULL); return &argv[0]; } std::string stringVectorToString(std::vector<std::string> &stringVector) { std::ostringstream oss; for (std::size_t j = 0; j < stringVector.size(); ++j) { oss << stringVector[j]; if ((j+1) != stringVector.size()) { oss << " " << std::flush; } } return oss.str(); } bool execProcess(int stdinfd, int stdoutfd, int stderrfd, const std::vector<std::string> &stringVector) { pid_t pid; if ((pid = fork()) == 0) { dup2(stdinfd, STDIN_FILENO); dup2(stdoutfd, STDOUT_FILENO); dup2(stderrfd, STDERR_FILENO); std::vector<char*> argv; char **command = stringVector2CharArray(stringVector, argv); if (execvp(basename(command[0]), (char * const*)command) == -1) { writeFD(stderrfd, "Unknown command: [%s].\n", command[0]); exit(EXIT_FAILURE); } } int status; return (pid == waitpid(pid, &status, 0) && status == 0); }
28.660819
105
0.620894
rightson
3b871bc2b6e5a37375ce8bf437ad16d080f95a1d
1,590
cpp
C++
JSLAMPLUS/jslam/main.cpp
Johk3/JSLAM
19072c2058effef861964849fae3c6e9b4e37aaa
[ "MIT" ]
4
2019-02-21T17:28:02.000Z
2021-01-09T21:29:58.000Z
JSLAMPLUS/jslam/main.cpp
Johk3/JSLAM
19072c2058effef861964849fae3c6e9b4e37aaa
[ "MIT" ]
null
null
null
JSLAMPLUS/jslam/main.cpp
Johk3/JSLAM
19072c2058effef861964849fae3c6e9b4e37aaa
[ "MIT" ]
2
2019-02-21T17:28:01.000Z
2019-02-21T19:50:13.000Z
#include <opencv2/highgui.hpp> #include "opencv2/imgproc.hpp" #include "opencv2/video/background_segm.hpp" #include "opencv2/video/tracking.hpp" #include "opencv2/xfeatures2d.hpp" #include "opencv2/core.hpp" #include "opencv2/features2d.hpp" #include "opencv2/imgcodecs.hpp" #include <iostream> int main( int argc, char** argv ) { // Use these compiler option to run the code // g++ main.cpp -o output `pkg-config --cflags --libs opencv` // This is the section for reading a image // cv::Mat image; // image = cv::imread("frame.png" , CV_LOAD_IMAGE_COLOR); // // if(! image.data ) { // std::cout << "Could not open or find the image" << std::endl ; // return -1; // } // // cv::namedWindow( "Jslam", cv::WINDOW_AUTOSIZE ); // cv::imshow( "Jslam", image ); // // cv::waitKey(0); cv::VideoCapture cap("media/fastcar.mp4"); cv::namedWindow("frame", cv::WINDOW_AUTOSIZE); if(!cap.isOpened()){ std::cout << "Error opening video stream or file" << "\n"; return -1; } while(1){ int W = cap.get(cv::CAP_PROP_FRAME_WIDTH)/2; int H = cap.get(cv::CAP_PROP_FRAME_HEIGHT)/2; cv::Mat frame; cv::Mat outframe; // Capture frame-by-frame cap >> frame; if(frame.empty()) break; cv::resize(frame, outframe, cv::Size(), 0.50, 0.50); cv::imshow("frame", outframe); char c=(char)cv::waitKey(25); if(c==27) break; } // When everything is done, release the video capture cap.release(); //Closes all the frames cv::destroyAllWindows(); return 0; }
26.949153
71
0.613208
Johk3
3b8aa1cfbbb77793737f9aeda63a1e31a88f0a79
1,365
cpp
C++
src/Boundaries.cpp
lzanotto/mo802-spitz
3d3ce9f0fa6d345bd309aea5e2f4f64a8a4f4714
[ "Apache-2.0" ]
175
2015-01-03T21:50:11.000Z
2022-03-07T00:20:08.000Z
src/Boundaries.cpp
KsGin-Fork/RayTracer
4c9f2dd389ace5f7601af367d2aa0e8db70b2b7d
[ "Apache-2.0" ]
4
2016-08-04T10:13:04.000Z
2020-10-26T09:36:35.000Z
src/Boundaries.cpp
KsGin-Fork/RayTracer
4c9f2dd389ace5f7601af367d2aa0e8db70b2b7d
[ "Apache-2.0" ]
49
2015-03-04T16:13:21.000Z
2022-02-23T00:27:13.000Z
#include "Boundaries.h" #include <algorithm> // Returns the center value for the given axis. double Boundaries::splitValue(char axis) { switch(axis) { case 'x': return (min.x + max.x) / 2; case 'y': return (min.y + max.y) / 2; case 'z': return (min.z + max.z) / 2; default: return 0.0f; } } /** * Ray axis aligned bounding box intersection. * Adapted from: http://gamedev.stackexchange.com/a/18459 */ bool Boundaries::intersect(const Ray& ray, double* dist) { // lb is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner // r.org is origin of ray double t1 = (min.x - ray.origin.x) * ray.fracDir.x; double t2 = (max.x - ray.origin.x) * ray.fracDir.x; double t3 = (min.y - ray.origin.y) * ray.fracDir.y; double t4 = (max.y - ray.origin.y) * ray.fracDir.y; double t5 = (min.z - ray.origin.z) * ray.fracDir.z; double t6 = (max.z - ray.origin.z) * ray.fracDir.z; double tmin = std::max(std::max(std::min(t1, t2), std::min(t3, t4)), std::min(t5, t6)); double tmax = std::min(std::min(std::max(t1, t2), std::max(t3, t4)), std::max(t5, t6)); // If tmax < 0, ray is intersecting AABB, but whole AABB is behind us. if (tmax < 0) { return false; } // If tmin > tmax, ray doesn't intersect AABB. if (tmin > tmax) { return false; } return true; }
31.744186
91
0.610256
lzanotto
3b8de2709b87a38719a43e3d0d43c1497f16ed9a
3,370
hpp
C++
simulation/traffic_simulator/include/traffic_simulator/math/hermite_curve.hpp
WJaworskiRobotec/scenario_simulator_v2
c23497ac8716dcefef20d4b5a4ff1185e01f48e6
[ "Apache-2.0" ]
null
null
null
simulation/traffic_simulator/include/traffic_simulator/math/hermite_curve.hpp
WJaworskiRobotec/scenario_simulator_v2
c23497ac8716dcefef20d4b5a4ff1185e01f48e6
[ "Apache-2.0" ]
null
null
null
simulation/traffic_simulator/include/traffic_simulator/math/hermite_curve.hpp
WJaworskiRobotec/scenario_simulator_v2
c23497ac8716dcefef20d4b5a4ff1185e01f48e6
[ "Apache-2.0" ]
null
null
null
// Copyright 2015-2020 Tier IV, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TRAFFIC_SIMULATOR__MATH__HERMITE_CURVE_HPP_ #define TRAFFIC_SIMULATOR__MATH__HERMITE_CURVE_HPP_ #include <gtest/gtest.h> #include <quaternion_operation/quaternion_operation.h> #include <boost/optional.hpp> #include <geometry_msgs/msg/point.hpp> #include <geometry_msgs/msg/pose.hpp> #include <geometry_msgs/msg/vector3.hpp> #include <traffic_simulator/math/polynomial_solver.hpp> #include <vector> namespace traffic_simulator { namespace math { class HermiteCurve { private: friend class HermiteCurveTest; double ax_, bx_, cx_, dx_; double ay_, by_, cy_, dy_; double az_, bz_, cz_, dz_; traffic_simulator::math::PolynomialSolver solver_; public: HermiteCurve( geometry_msgs::msg::Pose start_pose, geometry_msgs::msg::Pose goal_pose, geometry_msgs::msg::Vector3 start_vec, geometry_msgs::msg::Vector3 goal_vec); HermiteCurve( double ax, double bx, double cx, double dx, double ay, double by, double cy, double dy, double az, double bz, double cz, double dz); std::vector<geometry_msgs::msg::Point> getTrajectory(size_t num_points = 30) const; const std::vector<geometry_msgs::msg::Point> getTrajectory( double start_s, double end_s, double resolution, bool autoscale = false) const; const geometry_msgs::msg::Pose getPose(double s, bool autoscale = false) const; const geometry_msgs::msg::Point getPoint(double s, bool autoscale = false) const; const geometry_msgs::msg::Vector3 getTangentVector(double s, bool autoscale = false) const; const geometry_msgs::msg::Vector3 getNormalVector(double s, bool autoscale = false) const; double get2DCurvature(double s, bool autoscale = false) const; double getMaximum2DCurvature() const; double getLength(size_t num_points) const; double getLength() const { return length_; } boost::optional<double> getSValue( const geometry_msgs::msg::Pose & pose, double threshold_distance = 3.0, bool autoscale = false) const; double getSquaredDistanceIn2D( const geometry_msgs::msg::Point & point, double s, bool autoscale = false) const; geometry_msgs::msg::Vector3 getSquaredDistanceVector( const geometry_msgs::msg::Point & point, double s, bool autoscale = false) const; boost::optional<double> getCollisionPointIn2D( const geometry_msgs::msg::Point & point0, const geometry_msgs::msg::Point & point1, bool search_backward = false) const; boost::optional<double> getCollisionPointIn2D( const std::vector<geometry_msgs::msg::Point> & polygon, bool search_backward = false, bool close_start_end = true) const; private: std::pair<double, double> get2DMinMaxCurvatureValue() const; double length_; }; } // namespace math } // namespace traffic_simulator #endif // TRAFFIC_SIMULATOR__MATH__HERMITE_CURVE_HPP_
41.604938
93
0.760831
WJaworskiRobotec
3b8e317d40b0d15d4fdade9d70e5392190717415
767
cc
C++
Regex.cc
Phoenix500526/T-Reg
8f9a79d0e117ec63b2ffc848bdce6a2c440ff5c1
[ "MIT" ]
null
null
null
Regex.cc
Phoenix500526/T-Reg
8f9a79d0e117ec63b2ffc848bdce6a2c440ff5c1
[ "MIT" ]
null
null
null
Regex.cc
Phoenix500526/T-Reg
8f9a79d0e117ec63b2ffc848bdce6a2c440ff5c1
[ "MIT" ]
null
null
null
#include "Regex.h" #include <string.h> #include "ASTBuilder.h" namespace treg { Regex::Regex(const char* regex) { Compile(regex); } Regex::Regex(const std::string& regex) { Compile(regex); } bool Regex::Compile(const char* regex) { return Compile(regex, strlen(regex)); } bool Regex::Compile(const char* regex, std::size_t len) { detail::ASTBuilder astBuilder; if (!astBuilder.Build(regex, len)) return false; return dfa_.Construct(astBuilder.GetASTRoot()); } bool Regex::Compile(const std::string& regex) { return Compile(regex.data(), regex.size()); } bool Regex::Match(const char* pattern) const { return dfa_.Match(pattern); } bool Regex::Match(const std::string& pattern) const { return dfa_.Match(pattern.c_str(), pattern.size()); } } // treg
27.392857
80
0.706649
Phoenix500526
3b8ee442e4fd95d3b24ad998976be842e1638f71
5,010
cpp
C++
sanity/unit/ComputeFunction_unittest.cpp
lambday/tesseract
b38cf14545940f3b227285a19d40907260f057e6
[ "MIT" ]
3
2015-01-09T08:15:28.000Z
2019-05-24T08:34:04.000Z
sanity/unit/ComputeFunction_unittest.cpp
lambday/tesseract
b38cf14545940f3b227285a19d40907260f057e6
[ "MIT" ]
null
null
null
sanity/unit/ComputeFunction_unittest.cpp
lambday/tesseract
b38cf14545940f3b227285a19d40907260f057e6
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2014 Soumyajit De * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <tesseract/computation/ComputeFunction.hpp> #include <tesseract/regularizer/DummyRegularizer.hpp> #include <tesseract/regularizer/SmoothedDifferentialEntropy.hpp> #include <cstdlib> #include <limits> #include <iostream> #include <cmath> using namespace tesseract; using namespace Eigen; void test1() { int dim = 2; int n = 3; MatrixXd m(n, dim + 1); m << 0.68037, 0.59688, -0.32955, -0.21123, 0.82329, 0.53646, 0.56620, -0.60490, -0.44445; ComputeFunction<DummyRegularizer, float64_t> f; float64_t val = f(m.transpose() * m); // compute it another way MatrixXd A = m.block(0, 0, n, dim); VectorXd b = m.col(m.cols()-1); // compute by solving least squares VectorXd beta = (A.transpose() * A).ldlt().solve(A.transpose() * b); float val2 = 1 - pow((b - A*beta).norm(),2); // since we are using dummy regularizer so these two values should be same // in fact is should be 0.936133 (computed using octave) assert(abs(val - val2) < std::numeric_limits<float64_t>::epsilon()); } void test2() { int dim = 2; int n = 3; MatrixXd m(n, dim + 1); m << 0.68037, 0.59688, -0.32955, -0.21123, 0.82329, 0.53646, 0.56620, -0.60490, -0.44445; float64_t eta = ComputeFunction<SmoothedDifferentialEntropy, float64_t>::default_eta; float64_t delta = SmoothedDifferentialEntropyParam<float64_t>::default_delta; typedef SmoothedDifferentialEntropy<float64_t>::param_type reg_param_type; ComputeFunction<SmoothedDifferentialEntropy, float64_t> f; f.set_eta(eta); f.set_reg_params(reg_param_type(delta)); MatrixXd cov = m.transpose() * m; float64_t val = f(cov); // compute it another way MatrixXd A = m.block(0, 0, n, dim); VectorXd b = m.col(m.cols()-1); // compute by solving least squares VectorXd beta = (A.transpose() * A).ldlt().solve(A.transpose() * b); float64_t val2 = 1 - pow((b - A*beta).norm(),2); // compute the regularizer SmoothedDifferentialEntropy<float64_t> r; r.set_params(reg_param_type(delta)); float64_t val3 = r(cov.topLeftCorner(dim, dim)); assert(abs(val - (val2 + eta * val3)) < std::numeric_limits<float64_t>::epsilon()); } void test3() { int dim = 2; int n = 3; MatrixXd m(n, dim + 1); m << 0.68037, 0.59688, -0.32955, -0.21123, 0.82329, 0.53646, 0.56620, -0.60490, -0.44445; float64_t eta = 0.8; float64_t delta = 0.1; typedef SmoothedDifferentialEntropy<float64_t>::param_type reg_param_type; ComputeFunction<SmoothedDifferentialEntropy, float64_t> f; f.set_eta(eta); f.set_reg_params(reg_param_type(delta)); MatrixXd cov = m.transpose() * m; float64_t val = f(cov); // compute it another way MatrixXd A = m.block(0, 0, n, dim); VectorXd b = m.col(m.cols()-1); // compute by solving least squares VectorXd beta = (A.transpose() * A).ldlt().solve(A.transpose() * b); float64_t val2 = 1 - pow((b - A*beta).norm(),2); // compute the regularizer SmoothedDifferentialEntropy<float64_t> r; r.set_params(reg_param_type(delta)); float64_t val3 = r(cov.topLeftCorner(dim, dim)); assert(abs(val - (val2 + eta * val3)) < std::numeric_limits<float64_t>::epsilon()); } void test4() { int dim = 3; int n = 5; MatrixXd m(n, dim + 1); m << -0.620251, 0.043870, 0.126634, 0.883738, -0.649199, -0.156014, 0.025161, -0.116296, -0.179758, -0.387849, 0.067516, 0.270564, 0.256471, -0.463623, -0.604798, -0.161666, -0.309417, 0.779976, 0.782938, 0.325794; ComputeFunction<DummyRegularizer, float64_t> f; float64_t val = f(m.transpose() * m); // octave computed value from the following code /* X = m(:,linspace(1, dim, dim)) y = m(:,[dim + 1]) C = m'*m C_S = C(linspace(1, dim, dim),linspace(1, dim, dim)) b_S = C(linspace(1, dim, dim),[dim + 1]) R_sq = dot(b_S, C_S \ b_S) */ assert(abs(val - 0.46923) < 1E-6); } int main(int argc, char** argv) { test1(); test2(); test3(); test4(); return 0; }
29.298246
86
0.688822
lambday