hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
eb0ceebfc7a0426ad00062d5f076adb2e7972a5f
9,454
cc
C++
src/third_party/mozc/session/ime_switch_util_test.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
src/third_party/mozc/session/ime_switch_util_test.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
null
null
null
src/third_party/mozc/session/ime_switch_util_test.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
3
2018-11-28T14:54:13.000Z
2020-07-02T07:36:07.000Z
// Copyright 2010-2011, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "session/ime_switch_util.h" #include <string> #include "base/util.h" #include "config/config_handler.h" #include "session/key_event_normalizer.h" #include "session/key_parser.h" #include "session/internal/keymap.h" #include "testing/base/public/gunit.h" #include "testing/base/public/googletest.h" namespace mozc { namespace config { class ImeSwitchUtilTest : public testing::Test { protected: virtual void SetUp() { ImeSwitchUtil::Reload(); Util::SetUserProfileDirectory(FLAGS_test_tmpdir); } }; TEST_F(ImeSwitchUtilTest, PresetTest) { Config config; ConfigHandler::GetConfig(&config); config.set_session_keymap(Config::ATOK); ConfigHandler::SetConfig(config); ImeSwitchUtil::Reload(); { commands::KeyEvent key; KeyParser::ParseKey("HENKAN", &key); EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } { commands::KeyEvent key; KeyParser::ParseKey("EISU", &key); EXPECT_FALSE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } { commands::KeyEvent key; KeyParser::ParseKey("ON", &key); EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } { // Reconcersion commands::KeyEvent key; KeyParser::ParseKey("Shift HENKAN", &key); EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } config.set_session_keymap(Config::MSIME); ConfigHandler::SetConfig(config); ImeSwitchUtil::Reload(); { commands::KeyEvent key; KeyParser::ParseKey("HENKAN", &key); EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } { commands::KeyEvent key; KeyParser::ParseKey("EISU", &key); EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } { commands::KeyEvent key; KeyParser::ParseKey("ON", &key); EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } config.set_session_keymap(Config::KOTOERI); ConfigHandler::SetConfig(config); ImeSwitchUtil::Reload(); { commands::KeyEvent key; KeyParser::ParseKey("HENKAN", &key); EXPECT_FALSE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } { commands::KeyEvent key; KeyParser::ParseKey("EISU", &key); EXPECT_FALSE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } { commands::KeyEvent key; KeyParser::ParseKey("ON", &key); EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } { // Reconcersion commands::KeyEvent key; KeyParser::ParseKey("Ctrl Shift r", &key); EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } } TEST_F(ImeSwitchUtilTest, DefaultTest) { Config config; ConfigHandler::GetConfig(&config); config.set_session_keymap(Config::NONE); ConfigHandler::SetConfig(config); ImeSwitchUtil::Reload(); // MSIME for windows, KOTOERI for others { commands::KeyEvent key; KeyParser::ParseKey("HENKAN", &key); // HENKAN key in MSIME is TurnOn key while it's not in KOTOERI. if (keymap::KeyMapManager::GetDefaultKeyMap() == config::Config::MSIME) { EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } else { EXPECT_FALSE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } } { commands::KeyEvent key; KeyParser::ParseKey("EISU", &key); if (keymap::KeyMapManager::GetDefaultKeyMap() == config::Config::MSIME) { EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } else { EXPECT_FALSE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } } { commands::KeyEvent key; KeyParser::ParseKey("ON", &key); key.set_special_key(commands::KeyEvent::ON); EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } } TEST_F(ImeSwitchUtilTest, CustomTest) { Config config; ConfigHandler::GetConfig(&config); const string custom_keymap_table = "status\tkey\tcommand\n" "DirectInput\tCtrl j\tIMEOn\n" "DirectInput\tHenkan\tIMEOn\n" "DirectInput\tCtrl k\tIMEOff\n" "Precomposition\tCtrl l\tIMEOn\n"; config.set_session_keymap(Config::CUSTOM); config.set_custom_keymap_table(custom_keymap_table); ConfigHandler::SetConfig(config); ImeSwitchUtil::Reload(); { commands::KeyEvent key; KeyParser::ParseKey("HENKAN", &key); EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } { commands::KeyEvent key; KeyParser::ParseKey("EISU", &key); EXPECT_FALSE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } { commands::KeyEvent key; KeyParser::ParseKey("ctrl j", &key); EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } { commands::KeyEvent key; KeyParser::ParseKey("ctrl k", &key); EXPECT_FALSE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } { commands::KeyEvent key; KeyParser::ParseKey("ctrl l", &key); EXPECT_FALSE(ImeSwitchUtil::IsTurnOnInDirectMode(key)); } } namespace { bool IsIncludedKeyEvent(const commands::KeyEvent &key_event, const vector<commands::KeyEvent> &key_event_list) { uint64 key; if (!KeyEventNormalizer::ToUint64(key_event, &key)) { return false; } for (size_t i = 0; i < key_event_list.size(); ++i) { uint64 listed_key; if (!KeyEventNormalizer::ToUint64(key_event_list[i], &listed_key)) { return false; } if (key == listed_key) { return true; } } return false; } } TEST_F(ImeSwitchUtilTest, GetKeyEventListTest) { Config config; ConfigHandler::GetConfig(&config); const string custom_keymap_table = "status\tkey\tcommand\n" "DirectInput\tCtrl j\tIMEOn\n" "DirectInput\tHenkan\tIMEOn\n" "DirectInput\tCtrl k\tIMEOff\n" "Precomposition\tCtrl l\tIMEOn\n"; config.set_session_keymap(Config::CUSTOM); config.set_custom_keymap_table(custom_keymap_table); ConfigHandler::SetConfig(config); ImeSwitchUtil::Reload(); vector<commands::KeyEvent> key_event_list; ImeSwitchUtil::GetTurnOnInDirectModeKeyEventList(&key_event_list); EXPECT_EQ(2, key_event_list.size()); { commands::KeyEvent key_event; KeyParser::ParseKey("HENKAN", &key_event); EXPECT_TRUE(IsIncludedKeyEvent(key_event, key_event_list)); } { commands::KeyEvent key_event; KeyParser::ParseKey("EISU", &key_event); EXPECT_FALSE(IsIncludedKeyEvent(key_event, key_event_list)); } { commands::KeyEvent key_event; KeyParser::ParseKey("ctrl j", &key_event); EXPECT_TRUE(IsIncludedKeyEvent(key_event, key_event_list)); } { commands::KeyEvent key_event; KeyParser::ParseKey("ctrl k", &key_event); EXPECT_FALSE(IsIncludedKeyEvent(key_event, key_event_list)); } { commands::KeyEvent key_event; KeyParser::ParseKey("ctrl l", &key_event); EXPECT_FALSE(IsIncludedKeyEvent(key_event, key_event_list)); } } TEST_F(ImeSwitchUtilTest, MigrationTest) { Config config; ConfigHandler::GetConfig(&config); const string custom_keymap_table = "status\tkey\tcommand\n" "DirectInput\tON\tIMEOn\n"; config.set_session_keymap(Config::CUSTOM); config.set_custom_keymap_table(custom_keymap_table); ConfigHandler::SetConfig(config); ImeSwitchUtil::Reload(); vector<commands::KeyEvent> key_event_list; ImeSwitchUtil::GetTurnOnInDirectModeKeyEventList(&key_event_list); EXPECT_EQ(3, key_event_list.size()); { commands::KeyEvent key_event; KeyParser::ParseKey("ON", &key_event); EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key_event)); EXPECT_TRUE(IsIncludedKeyEvent(key_event, key_event_list)); } { commands::KeyEvent key_event; KeyParser::ParseKey("Hankaku/Zenkaku", &key_event); EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key_event)); EXPECT_TRUE(IsIncludedKeyEvent(key_event, key_event_list)); } { commands::KeyEvent key_event; KeyParser::ParseKey("Kanji", &key_event); EXPECT_TRUE(ImeSwitchUtil::IsTurnOnInDirectMode(key_event)); EXPECT_TRUE(IsIncludedKeyEvent(key_event, key_event_list)); } } } // namespace config } // namespace mozc
31.304636
77
0.715676
[ "vector" ]
eb0ef8cfd0e7ec6983c84f67c75a63235a049adf
13,516
hxx
C++
include/pqxx/except.hxx
mpapierski/pqxx
a4916e042b1845ef193bd657733adfd3b5dafaec
[ "BSD-3-Clause" ]
null
null
null
include/pqxx/except.hxx
mpapierski/pqxx
a4916e042b1845ef193bd657733adfd3b5dafaec
[ "BSD-3-Clause" ]
null
null
null
include/pqxx/except.hxx
mpapierski/pqxx
a4916e042b1845ef193bd657733adfd3b5dafaec
[ "BSD-3-Clause" ]
null
null
null
/*------------------------------------------------------------------------- * * FILE * pqxx/except.hxx * * DESCRIPTION * definition of libpqxx exception classes * pqxx::sql_error, pqxx::broken_connection, pqxx::in_doubt_error, ... * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/except instead. * * Copyright (c) 2003-2015, Jeroen T. Vermeulen <jtv@xs4all.nl> * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. * *------------------------------------------------------------------------- */ #ifndef PQXX_H_EXCEPT #define PQXX_H_EXCEPT #include "pqxx/compiler-public.hxx" #include "pqxx/compiler-internal-pre.hxx" #include <stdexcept> #include "pqxx/util" namespace pqxx { /** * @addtogroup exception Exception classes * * These exception classes follow, roughly, the two-level hierarchy defined by * the PostgreSQL error codes (see Appendix A of the PostgreSQL documentation * corresponding to your server version). The hierarchy given here is, as yet, * not a complete mirror of the error codes. There are some other differences * as well, e.g. the error code statement_completion_unknown has a separate * status in libpqxx as in_doubt_error, and too_many_connections is classified * as a broken_connection rather than a subtype of insufficient_resources. * * @see http://www.postgresql.org/docs/9.4/interactive/errcodes-appendix.html * * @{ */ /// Mixin base class to identify libpqxx-specific exception types /** * If you wish to catch all exception types specific to libpqxx for some reason, * catch this type. All of libpqxx's exception classes are derived from it * through multiple-inheritance (they also fit into the standard library's * exception hierarchy in more fitting places). * * This class is not derived from std::exception, since that could easily lead * to exception classes with multiple std::exception base-class objects. As * Bart Samwel points out, "catch" is subject to some nasty fineprint in such * cases. */ class PQXX_LIBEXPORT PQXX_NOVTABLE pqxx_exception { public: /// Support run-time polymorphism, and keep this class abstract virtual ~pqxx_exception() PQXX_NOEXCEPT =0; /// Return std::exception base-class object /** Use this to get at the exception's what() function, or to downcast to a * more specific type using dynamic_cast. * * Casting directly from pqxx_exception to a specific exception type is not * likely to work since pqxx_exception is not (and could not safely be) * derived from std::exception. * * For example, to test dynamically whether an exception is an sql_error: * * @code * try * { * // ... * } * catch (const pqxx::pqxx_exception &e) * { * std::cerr << e.base().what() << std::endl; * const pqxx::sql_error *s=dynamic_cast<const pqxx::sql_error*>(&e.base()); * if (s) std::cerr << "Query was: " << s->query() << std::endl; * } * @endcode */ PQXX_CONST virtual const std::exception &base() //[t0] const PQXX_NOEXCEPT =0; }; /// Run-time failure encountered by libpqxx, similar to std::runtime_error class PQXX_LIBEXPORT failure : public pqxx_exception, public std::runtime_error { virtual const std::exception &base() const PQXX_NOEXCEPT PQXX_OVERRIDE { return *this; } public: explicit failure(const std::string &); }; /// Exception class for lost or failed backend connection. /** * @warning When this happens on Unix-like systems, you may also get a SIGPIPE * signal. That signal aborts the program by default, so if you wish to be able * to continue after a connection breaks, be sure to disarm this signal. * * If you're working on a Unix-like system, see the manual page for * @c signal (2) on how to deal with SIGPIPE. The easiest way to make this * signal harmless is to make your program ignore it: * * @code * #include <signal.h> * * int main() * { * signal(SIGPIPE, SIG_IGN); * // ... * @endcode */ class PQXX_LIBEXPORT broken_connection : public failure { public: broken_connection(); explicit broken_connection(const std::string &); }; /// Exception class for failed queries. /** Carries a copy of the failed query in addition to a regular error message */ class PQXX_LIBEXPORT sql_error : public failure { std::string m_Q; public: sql_error(); explicit sql_error(const std::string &); sql_error(const std::string &, const std::string &Q); virtual ~sql_error() PQXX_NOEXCEPT; /// The query whose execution triggered the exception PQXX_PURE const std::string &query() const PQXX_NOEXCEPT; //[t56] }; // TODO: should this be called statement_completion_unknown!? /// "Help, I don't know whether transaction was committed successfully!" /** Exception that might be thrown in rare cases where the connection to the * database is lost while finishing a database transaction, and there's no way * of telling whether it was actually executed by the backend. In this case * the database is left in an indeterminate (but consistent) state, and only * manual inspection will tell which is the case. */ class PQXX_LIBEXPORT in_doubt_error : public failure { public: explicit in_doubt_error(const std::string &); }; /// Internal error in libpqxx library class PQXX_LIBEXPORT internal_error : public pqxx_exception, public std::logic_error { virtual const std::exception &base() const PQXX_NOEXCEPT PQXX_OVERRIDE { return *this; } public: explicit internal_error(const std::string &); }; /// Error in usage of libpqxx library, similar to std::logic_error class PQXX_LIBEXPORT usage_error : public pqxx_exception, public std::logic_error { virtual const std::exception &base() const PQXX_NOEXCEPT PQXX_OVERRIDE { return *this; } public: explicit usage_error(const std::string &); }; /// Invalid argument passed to libpqxx, similar to std::invalid_argument class PQXX_LIBEXPORT argument_error : public pqxx_exception, public std::invalid_argument { virtual const std::exception &base() const PQXX_NOEXCEPT PQXX_OVERRIDE { return *this; } public: explicit argument_error(const std::string &); }; class PQXX_LIBEXPORT conversion_error : public pqxx_exception, public std::domain_error { virtual const std::exception &base() const PQXX_NOEXCEPT PQXX_OVERRIDE { return *this; } public: explicit conversion_error(const std::string &); }; /// Something is out of range, similar to std::out_of_range class PQXX_LIBEXPORT range_error : public pqxx_exception, public std::out_of_range { virtual const std::exception &base() const PQXX_NOEXCEPT PQXX_OVERRIDE { return *this; } public: explicit range_error(const std::string &); }; /// Database feature not supported in current setup class PQXX_LIBEXPORT feature_not_supported : public sql_error { public: explicit feature_not_supported(const std::string &err) : sql_error(err) {} feature_not_supported(const std::string &err, const std::string &Q) : sql_error(err,Q) {} }; /// Error in data provided to SQL statement class PQXX_LIBEXPORT data_exception : public sql_error { public: explicit data_exception(const std::string &err) : sql_error(err) {} data_exception(const std::string &err, const std::string &Q) : sql_error(err,Q) {} }; class PQXX_LIBEXPORT integrity_constraint_violation : public sql_error { public: explicit integrity_constraint_violation(const std::string &err) : sql_error(err) {} integrity_constraint_violation(const std::string &err, const std::string &Q) : sql_error(err, Q) {} }; class PQXX_LIBEXPORT restrict_violation : public integrity_constraint_violation { public: explicit restrict_violation(const std::string &err) : integrity_constraint_violation(err) {} restrict_violation(const std::string &err, const std::string &Q) : integrity_constraint_violation(err, Q) {} }; class PQXX_LIBEXPORT not_null_violation : public integrity_constraint_violation { public: explicit not_null_violation(const std::string &err) : integrity_constraint_violation(err) {} not_null_violation(const std::string &err, const std::string &Q) : integrity_constraint_violation(err, Q) {} }; class PQXX_LIBEXPORT foreign_key_violation : public integrity_constraint_violation { public: explicit foreign_key_violation(const std::string &err) : integrity_constraint_violation(err) {} foreign_key_violation(const std::string &err, const std::string &Q) : integrity_constraint_violation(err, Q) {} }; class PQXX_LIBEXPORT unique_violation : public integrity_constraint_violation { public: explicit unique_violation(const std::string &err) : integrity_constraint_violation(err) {} unique_violation(const std::string &err, const std::string &Q) : integrity_constraint_violation(err, Q) {} }; class PQXX_LIBEXPORT check_violation : public integrity_constraint_violation { public: explicit check_violation(const std::string &err) : integrity_constraint_violation(err) {} check_violation(const std::string &err, const std::string &Q) : integrity_constraint_violation(err, Q) {} }; class PQXX_LIBEXPORT invalid_cursor_state : public sql_error { public: explicit invalid_cursor_state(const std::string &err) : sql_error(err) {} invalid_cursor_state(const std::string &err, const std::string &Q) : sql_error(err,Q) {} }; class PQXX_LIBEXPORT invalid_sql_statement_name : public sql_error { public: explicit invalid_sql_statement_name(const std::string &err) : sql_error(err) {} invalid_sql_statement_name(const std::string &err, const std::string &Q) : sql_error(err,Q) {} }; class PQXX_LIBEXPORT invalid_cursor_name : public sql_error { public: explicit invalid_cursor_name(const std::string &err) : sql_error(err) {} invalid_cursor_name(const std::string &err, const std::string &Q) : sql_error(err,Q) {} }; class PQXX_LIBEXPORT syntax_error : public sql_error { public: /// Approximate position in string where error occurred, or -1 if unknown. const int error_position; explicit syntax_error(const std::string &err, int pos=-1) : sql_error(err), error_position(pos) {} syntax_error(const std::string &err, const std::string &Q, int pos=-1) : sql_error(err,Q), error_position(pos) {} }; class PQXX_LIBEXPORT undefined_column : public syntax_error { public: explicit undefined_column(const std::string &err) : syntax_error(err) {} undefined_column(const std::string &err, const std::string &Q) : syntax_error(err, Q) {} }; class PQXX_LIBEXPORT undefined_function : public syntax_error { public: explicit undefined_function(const std::string &err) : syntax_error(err) {} undefined_function(const std::string &err, const std::string &Q) : syntax_error(err, Q) {} }; class PQXX_LIBEXPORT undefined_table : public syntax_error { public: explicit undefined_table(const std::string &err) : syntax_error(err) {} undefined_table(const std::string &err, const std::string &Q) : syntax_error(err, Q) {} }; class PQXX_LIBEXPORT insufficient_privilege : public sql_error { public: explicit insufficient_privilege(const std::string &err) : sql_error(err) {} insufficient_privilege(const std::string &err, const std::string &Q) : sql_error(err,Q) {} }; /// Resource shortage on the server class PQXX_LIBEXPORT insufficient_resources : public sql_error { public: explicit insufficient_resources(const std::string &err) : sql_error(err) {} insufficient_resources(const std::string &err, const std::string &Q) : sql_error(err,Q) {} }; class PQXX_LIBEXPORT disk_full : public insufficient_resources { public: explicit disk_full(const std::string &err) : insufficient_resources(err) {} disk_full(const std::string &err, const std::string &Q) : insufficient_resources(err,Q) {} }; class PQXX_LIBEXPORT out_of_memory : public insufficient_resources { public: explicit out_of_memory(const std::string &err) : insufficient_resources(err) {} out_of_memory(const std::string &err, const std::string &Q) : insufficient_resources(err,Q) {} }; class PQXX_LIBEXPORT too_many_connections : public broken_connection { public: explicit too_many_connections(const std::string &err) : broken_connection(err) {} }; /// PL/pgSQL error /** Exceptions derived from this class are errors from PL/pgSQL procedures. */ class PQXX_LIBEXPORT plpgsql_error : public sql_error { public: explicit plpgsql_error(const std::string &err) : sql_error(err) {} plpgsql_error(const std::string &err, const std::string &Q) : sql_error(err, Q) {} }; /// Exception raised in PL/pgSQL procedure class PQXX_LIBEXPORT plpgsql_raise : public plpgsql_error { public: explicit plpgsql_raise(const std::string &err) : plpgsql_error(err) {} plpgsql_raise(const std::string &err, const std::string &Q) : plpgsql_error(err, Q) {} }; class PQXX_LIBEXPORT plpgsql_no_data_found : public plpgsql_error { public: explicit plpgsql_no_data_found(const std::string &err) : plpgsql_error(err) {} plpgsql_no_data_found(const std::string &err, const std::string &Q) : plpgsql_error(err, Q) {} }; class PQXX_LIBEXPORT plpgsql_too_many_rows : public plpgsql_error { public: explicit plpgsql_too_many_rows(const std::string &err) : plpgsql_error(err) {} plpgsql_too_many_rows(const std::string &err, const std::string &Q) : plpgsql_error(err, Q) {} }; /** * @} */ } #include "pqxx/compiler-internal-post.hxx" #endif
29.770925
80
0.727508
[ "object" ]
eb102c1293ac5e3ade56828fce56bc5049b5574e
1,611
cpp
C++
2021-2022/04_tsp_hc_sa_ts/tsp1.cpp
pantadeusz/meh
16d2826330c9bfdb4c7a315f2f69ec33b464541d
[ "MIT" ]
null
null
null
2021-2022/04_tsp_hc_sa_ts/tsp1.cpp
pantadeusz/meh
16d2826330c9bfdb4c7a315f2f69ec33b464541d
[ "MIT" ]
null
null
null
2021-2022/04_tsp_hc_sa_ts/tsp1.cpp
pantadeusz/meh
16d2826330c9bfdb4c7a315f2f69ec33b464541d
[ "MIT" ]
null
null
null
#include <chrono> #include <fstream> #include <functional> #include <iostream> #include <random> #include <sstream> #include <vector> // different methods #include "m_bruteforce.hpp" #include "m_hillclimb.hpp" // problem definition #include "tsp_problem.hpp" using namespace std; ///< bad practice, but useful in examples for MHE // the experiment int main(int argc, char** argv) { vector<pair<double, double>> cities_coordinates; auto problem = generate_random_problem((argc < 2) ? 5 : stoi(argv[1]), [&cities_coordinates](auto coords) { cities_coordinates = coords; }); cout << problem << endl; auto cost_func = cost_function_factory(problem); work_point_t best_solution = brute_force_tsp( cost_func, [&]() { return generate_first_tsp_point(problem); }, get_next_point, [](int c, double dt) { cout << "# count BF: " << c << "; dt: " << dt << endl; }); work_point_t result_hc = hill_climb_rnd( cost_func, [&]() { return generate_random_tsp_point(problem); }, generate_random_tsp_neighbour, 10000, [](int c, double dt) { cout << "# count HC: " << c << "; dt: " << dt << endl; }); // cout << "best cost for: " << make_pair(problem, best_solution) << "is " << cost_func(best_solution) << endl; cout << "best BF:\n" << make_pair(cities_coordinates, best_solution) << " is " << cost_func(best_solution) << endl; cout << "best HC:\n" << make_pair(cities_coordinates, result_hc) << " is " << cost_func(result_hc) << endl; return 0; }
31.588235
144
0.614525
[ "vector" ]
eb1701698aea07b9df4dd53d756babee955952e0
14,950
cpp
C++
src/utils/Utils.cpp
leet-feat/feather
ff6e6adf0c853fcf664bd8f0b2ee94a51550b4f8
[ "BSD-3-Clause" ]
null
null
null
src/utils/Utils.cpp
leet-feat/feather
ff6e6adf0c853fcf664bd8f0b2ee94a51550b4f8
[ "BSD-3-Clause" ]
null
null
null
src/utils/Utils.cpp
leet-feat/feather
ff6e6adf0c853fcf664bd8f0b2ee94a51550b4f8
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2020-2021, The Monero Project. #include <QMessageBox> #include <QtNetwork> #include <QClipboard> #include <QDesktopServices> #include <QPushButton> #include "constants.h" #include "networktype.h" #include "Utils.h" #include "utils/ColorScheme.h" #include "utils/config.h" #include "utils/os/tails.h" #include "utils/os/whonix.h" namespace Utils { bool fileExists(const QString &path) { QFileInfo check_file(path); return check_file.exists() && check_file.isFile(); } QByteArray fileOpen(const QString &path) { QFile file(path); if (!file.open(QFile::ReadOnly | QFile::Text)) { return QByteArray(); } QByteArray data = file.readAll(); file.close(); return data; } QByteArray fileOpenQRC(const QString &path) { QFile file(path); if (!file.open(QIODevice::ReadOnly)) { qDebug() << "error: " << file.errorString(); return QByteArray(); } QByteArray data = file.readAll(); file.close(); return data; } bool fileWrite(const QString &path, const QString &data) { QFile file(path); if (file.open(QIODevice::WriteOnly)) { QTextStream out(&file); out << data << Qt::endl; file.close(); return true; } return false; } bool pixmapWrite(const QString &path, const QPixmap &pixmap) { qDebug() << "Writing xdg icon: " << path; QFile file(path); QFileInfo iconInfo(file); QDir().mkpath(iconInfo.path()); if(file.open(QIODevice::WriteOnly)){ pixmap.save(&file, "PNG"); file.close(); return true; } return false; } QStringList fileFind(const QRegExp &pattern, const QString &baseDir, int level, int depth, const int maxPerDir) { // like `find /foo -name -maxdepth 2 "*.jpg"` QStringList rtn; QDir dir(baseDir); dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoSymLinks | QDir::NoDot | QDir::NoDotDot); int fileCount = 0; for (const auto &fileInfo: dir.entryInfoList({"*"})) { fileCount += 1; if(fileCount > maxPerDir) return rtn; if(!fileInfo.isReadable()) continue; const auto fn = fileInfo.fileName(); const auto path = fileInfo.filePath(); if (fileInfo.isDir()) { if (level + 1 <= depth) rtn << fileFind(pattern, path, level + 1, depth, maxPerDir); } else if (pattern.exactMatch(fn)) rtn << path; } return rtn; } bool dirExists(const QString &path) { QDir pathDir(path); return pathDir.exists(); } QString defaultWalletDir() { QString portablePath = QCoreApplication::applicationDirPath().append("/%1"); if (QFile::exists(portablePath.arg(".portable"))) { return portablePath.arg("feather_data/wallets"); } if (TailsOS::detect()) { QString path = []{ QString appImagePath = qgetenv("APPIMAGE"); if (appImagePath.isEmpty()) { qDebug() << "Not an appimage, using currentPath()"; return QDir::currentPath() + "/.feather/Monero/wallets"; } QFileInfo appImageDir(appImagePath); return appImageDir.absoluteDir().path() + "/.feather/Monero/wallets"; }(); return path; } #if defined(Q_OS_LINUX) or defined(Q_OS_MAC) return QString("%1/Monero/wallets").arg(QDir::homePath()); #elif defined(Q_OS_WIN) return QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/Monero/wallets"; #endif } bool validateJSON(const QByteArray &blob) { QJsonDocument doc = QJsonDocument::fromJson(blob); QString jsonString = doc.toJson(QJsonDocument::Indented); return !jsonString.isEmpty(); } bool readJsonFile(QIODevice &device, QSettings::SettingsMap &map) { QJsonDocument json = QJsonDocument::fromJson(device.readAll()); map = json.object().toVariantMap(); return true; } bool writeJsonFile(QIODevice &device, const QSettings::SettingsMap &map) { device.write(QJsonDocument(QJsonObject::fromVariantMap(map)).toJson(QJsonDocument::Indented)); return true; } void copyToClipboard(const QString &string){ QClipboard * clipboard = QApplication::clipboard(); if (!clipboard) { qWarning() << "Unable to access clipboard"; return; } clipboard->setText(string, QClipboard::Clipboard); if (clipboard->supportsSelection()) clipboard->setText(string, QClipboard::Selection); #if defined(Q_OS_LINUX) QThread::msleep(1); #endif } QString copyFromClipboard() { QClipboard * clipboard = QApplication::clipboard(); if (!clipboard) { qWarning() << "Unable to access clipboard"; return ""; } return clipboard->text(); } QString xdgDesktopEntry(){ return QString( "[Desktop Entry]\n" "Name=Feather\n" "GenericName=Feather\n" "X-GNOME-FullName=Feather\n" "Comment=a free Monero desktop wallet\n" "Keywords=Monero;\n" "Exec=\"%1\" %u\n" "Terminal=false\n" "Type=Application\n" "Icon=monero\n" "Categories=Network;GNOME;Qt;\n" "StartupNotify=true\n" ).arg(QApplication::applicationFilePath()); } bool xdgDesktopEntryWrite(const QString &path){ QString mime = xdgDesktopEntry(); QFileInfo file(path); QDir().mkpath(file.path()); qDebug() << "Writing xdg desktop entry: " << path; return fileWrite(path, mime); } void xdgRefreshApplications(){ QStringList args = {QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation)}; QProcess::startDetached("update-desktop-database", args); } bool xdgDesktopEntryRegister() { #if defined(Q_OS_MACOS) return false; #endif #if defined(Q_OS_WIN) // @TODO: implement return false; #endif QPixmap appIcon(":assets/images/feather.png"); QString pathIcon = QString("%1/.local/share/icons/feather.png").arg(QDir::homePath()); if (!fileExists(pathIcon)) { pixmapWrite(pathIcon, appIcon); } xdgDesktopEntryWrite(QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation)); xdgRefreshApplications(); return true; } bool portOpen(const QString &hostname, quint16 port){ QTcpSocket socket; socket.connectToHost(hostname, port); return socket.waitForConnected(600); } quint16 getDefaultRpcPort(NetworkType::Type type) { switch (type) { case NetworkType::Type::MAINNET: return 18081; case NetworkType::Type::TESTNET: return 28081; case NetworkType::Type::STAGENET: return 38081; } return 18081; } bool isTorsocks() { #if defined(Q_OS_MAC) return qgetenv("DYLD_INSERT_LIBRARIES").indexOf("libtorsocks") >= 0; #elif defined(Q_OS_LINUX) return qgetenv("LD_PRELOAD").indexOf("libtorsocks") >= 0; #else return false; #endif } double roundSignificant(double N, double n) { int h; double b, d, e, i, j, m, f; b = N; for (i = 0; b >= 1; ++i) b = b / 10; d = n - i; b = N; b = b * pow(10, d); e = b + 0.5; if ((float)e == (float)ceil(b)) { f = (ceil(b)); h = f - 2; if (h % 2 != 0) { e = e - 1; } } j = floor(e); m = pow(10, d); j = j / m; return j; } int maxLength(const QVector<QString> &array) { int maxLength = 0; for (const auto &str: array) { auto length = str.length(); if (length > maxLength) { maxLength = length; } } return maxLength; } QString formatBytes(quint64 bytes) { QVector<QString> sizes = { "B", "KB", "MB", "GB", "TB" }; int i; double _data; for (i = 0; i < sizes.count() && bytes >= 10000; i++, bytes /= 1000) _data = bytes / 1000.0; if (_data < 0) _data = 0; // unrealistic if (_data > 10000) _data = 0; return QString("%1 %2").arg(QString::number(_data, 'f', 1), sizes[i]); } QMap<QString, QLocale> localeCache = {}; QLocale getCurrencyLocale(const QString &currencyCode) { QLocale locale; if (localeCache.contains(currencyCode)) { locale = localeCache[currencyCode]; } else { QList<QLocale> allLocales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::AnyCountry); for (const auto& locale_: allLocales) { if (locale_.currencySymbol(QLocale::CurrencyIsoCode) == currencyCode) { locale = locale_; } } localeCache[currencyCode] = locale; } return locale; } QString amountToCurrencyString(double amount, const QString &currencyCode) { QLocale locale = getCurrencyLocale(currencyCode); // \xC2\xA0 = UTF-8 non-breaking space, it looks off. if (currencyCode == "USD") return locale.toCurrencyString(amount, "$").remove("\xC2\xA0"); return locale.toCurrencyString(amount).remove("\xC2\xA0"); } QStandardItem *qStandardItem(const QString& text) { auto font = QApplication::font(); return Utils::qStandardItem(text, font); } QStandardItem *qStandardItem(const QString& text, QFont &font) { // stupid Qt doesnt set font sizes correctly on OSX // @TODO: memleak auto item = new QStandardItem(text); item->setFont(font); return item; } QString blockExplorerLink(const QString &blockExplorer, NetworkType::Type nettype, const QString &txid) { if (blockExplorer == "exploremonero.com") { if (nettype == NetworkType::MAINNET) { return QString("https://exploremonero.com/transaction/%1").arg(txid); } } else if (blockExplorer == "moneroblocks.info") { if (nettype == NetworkType::MAINNET) { return QString("https://moneroblocks.info/tx/%1").arg(txid); } } else if (blockExplorer == "blockchair.com") { if (nettype == NetworkType::MAINNET) { return QString("https://blockchair.com/monero/transaction/%1").arg(txid); } } switch (nettype) { case NetworkType::MAINNET: return QString("https://xmrchain.net/tx/%1").arg(txid); case NetworkType::STAGENET: return QString("https://stagenet.xmrchain.net/tx/%1").arg(txid); case NetworkType::TESTNET: return QString("https://testnet.xmrchain.net/tx/%1").arg(txid); } return QString(""); } void externalLinkWarning(QWidget *parent, const QString &url){ if (!config()->get(Config::warnOnExternalLink).toBool()) { QDesktopServices::openUrl(QUrl(url)); return; } QString body = "You are about to open the following link:\n\n"; body += QString("%1").arg(url); if (!(TailsOS::detect() || WhonixOS::detect())) body += "\n\nYou will NOT be using Tor."; QMessageBox linkWarning(parent); linkWarning.setWindowTitle("External link warning"); linkWarning.setText(body); QPushButton *copy = linkWarning.addButton("Copy link", QMessageBox::HelpRole); linkWarning.addButton(QMessageBox::Cancel); linkWarning.addButton(QMessageBox::Ok); linkWarning.setDefaultButton(QMessageBox::Ok); linkWarning.exec(); if (linkWarning.clickedButton() == copy) { Utils::copyToClipboard(url); } else if (linkWarning.result() == QMessageBox::Ok) { QDesktopServices::openUrl(QUrl(url)); } } void desktopNotify(const QString &title, const QString &message, int duration) { QStringList notify_send = QStringList() << title << message << "-t" << QString::number(duration); QStringList kdialog = QStringList() << title << message; QStringList macos = QStringList() << "-e" << QString(R"(display notification "%1" with title "%2")").arg(message).arg(title); #if defined(Q_OS_LINUX) QProcess process; if (fileExists("/usr/bin/kdialog")) process.start("/usr/bin/kdialog", kdialog); else if (fileExists("/usr/bin/notify-send")) process.start("/usr/bin/notify-send", notify_send); process.waitForFinished(-1); QString stdout = process.readAllStandardOutput(); QString stderr = process.readAllStandardError(); #elif defined(Q_OS_MACOS) QProcess process; // @TODO: need to escape special chars with "\" process.start("osascript", macos); process.waitForFinished(-1); QString stdout = process.readAllStandardOutput(); QString stderr = process.readAllStandardError(); #endif } QTextCharFormat addressTextFormat(const SubaddressIndex &index, quint64 amount) { QTextCharFormat rec; if (index.isPrimary()) { rec.setBackground(QBrush(ColorScheme::YELLOW.asColor(true))); rec.setToolTip("Wallet change/primary address"); } else if (index.isValid()) { rec.setBackground(QBrush(ColorScheme::GREEN.asColor(true))); rec.setToolTip("Wallet receive address"); } else if (amount == 0) { rec.setBackground(QBrush(ColorScheme::GRAY.asColor(true))); rec.setToolTip("Dummy output (Min. 2 outs consensus rule)"); } return rec; } void applicationLogHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { const QString fn = context.function ? QString::fromUtf8(context.function) : ""; const QString date = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"); QString line; switch (type) { case QtDebugMsg: line = QString("[%1 D] %2(:%3) %4\n").arg(date).arg(fn).arg(context.line).arg(msg); fprintf(stderr, "%s", line.toLatin1().data()); break; case QtInfoMsg: line = QString("[%1 I] %2\n").arg(date).arg(msg); fprintf(stdout, "%s", line.toLatin1().data()); break; case QtWarningMsg: line = QString("[%1 W] %2(:%3) %4\n").arg(date).arg(fn).arg(context.line).arg(msg); fprintf(stdout, "%s", line.toLatin1().data()); break; case QtCriticalMsg: line = QString("[%1 C] %2(:%3) %4\n").arg(date).arg(fn).arg(context.line).arg(msg); fprintf(stderr, "%s", line.toLatin1().data()); break; case QtFatalMsg: line = QString("[%1 F] %2(:%3) %4\n").arg(date).arg(fn).arg(context.line).arg(msg); fprintf(stderr, "%s", line.toLatin1().data()); break; } } QString barrayToString(const QByteArray &data) { return QString(QTextCodec::codecForMib(106)->toUnicode(data)); } QString getAccountName() { QString accountName = qgetenv("USER"); // mac/linux if (accountName.isEmpty()) accountName = qgetenv("USERNAME"); // Windows if (accountName.isEmpty()) throw std::runtime_error("Could derive system account name from env vars: USER or USERNAME"); return accountName; } QFont relativeFont(int delta) { auto font = QApplication::font(); font.setPointSize(font.pointSize() + delta); return font; } }
30.510204
129
0.62602
[ "object" ]
a3e2738380dd74ebafe5821d654c3e2c967b567d
7,780
cpp
C++
source/HealthGPS.Tests/Core.UnivariateSummary.Test.cpp
imperialCHEPI/healthgps
58a0f03b61eb5427a5d259abde67ef740a7fda52
[ "BSD-3-Clause" ]
null
null
null
source/HealthGPS.Tests/Core.UnivariateSummary.Test.cpp
imperialCHEPI/healthgps
58a0f03b61eb5427a5d259abde67ef740a7fda52
[ "BSD-3-Clause" ]
14
2021-07-05T14:37:46.000Z
2021-12-08T18:04:27.000Z
source/HealthGPS.Tests/Core.UnivariateSummary.Test.cpp
imperialCHEPI/healthgps
58a0f03b61eb5427a5d259abde67ef740a7fda52
[ "BSD-3-Clause" ]
null
null
null
#include "pch.h" #include <optional> #include "HealthGPS.Core\univariate_summary.h" TEST(TestCore_UnivariateSummary, CreateEmptyWithoutName) { using namespace hgps::core; auto init_empty = UnivariateSummary(); ASSERT_TRUE(init_empty.is_empty()); EXPECT_EQ("Untitled", init_empty.name()); EXPECT_TRUE(std::isnan(init_empty.min())); EXPECT_TRUE(std::isnan(init_empty.max())); EXPECT_EQ(0, init_empty.count_valid()); EXPECT_EQ(0, init_empty.count_null()); EXPECT_EQ(0, init_empty.count_total()); } TEST(TestCore_UnivariateSummary, CreateEmptyWithName) { using namespace hgps::core; auto init_name = UnivariateSummary("Test"); ASSERT_TRUE(init_name.is_empty()); EXPECT_EQ("Test", init_name.name()); EXPECT_TRUE(std::isnan(init_name.min())); EXPECT_TRUE(std::isnan(init_name.max())); EXPECT_EQ(0, init_name.count_valid()); EXPECT_EQ(0, init_name.count_null()); EXPECT_EQ(0, init_name.count_total()); } TEST(TestCore_UnivariateSummary, CreateFullFromVectorWithoutName) { using namespace hgps::core; auto data = std::vector<double>{ 1.0, 2.0, 3.0, 4.0, 5.0 }; auto init_vector = UnivariateSummary(data); ASSERT_FALSE(init_vector.is_empty()); ASSERT_EQ("Untitled", init_vector.name()); ASSERT_EQ(data.size(), init_vector.count_valid()); ASSERT_EQ(0, init_vector.count_null()); ASSERT_EQ(data.size(), init_vector.count_total()); EXPECT_FALSE(std::isnan(init_vector.min())); EXPECT_FALSE(std::isnan(init_vector.max())); } TEST(TestCore_UnivariateSummary, CreateFullFromVectorWithName) { using namespace hgps::core; auto data = std::vector<double>{ 1.0, 2.0, 3.0, 4.0, 5.0 }; auto init_full = UnivariateSummary("Test", data); ASSERT_FALSE(init_full.is_empty()); ASSERT_EQ("Test", init_full.name()); ASSERT_EQ(data.size(), init_full.count_valid()); ASSERT_EQ(0, init_full.count_null()); ASSERT_EQ(data.size(), init_full.count_total()); EXPECT_FALSE(std::isnan(init_full.min())); EXPECT_FALSE(std::isnan(init_full.max())); } TEST(TestCore_UnivariateSummary, CreateFullFromListWithName) { using namespace hgps::core; auto data = std::vector<double>{ 1.0, 2.0, 3.0, 4.0, 5.0 }; auto init_list = UnivariateSummary("Test", { 1.0, 2.0, 3.0, 4.0, 5.0 }); ASSERT_FALSE(init_list.is_empty()); ASSERT_EQ("Test", init_list.name()); ASSERT_EQ(data.size(), init_list.count_valid()); ASSERT_EQ(0, init_list.count_null()); ASSERT_EQ(data.size(), init_list.count_total()); EXPECT_FALSE(std::isnan(init_list.min())); EXPECT_FALSE(std::isnan(init_list.max())); } TEST(TestCore_UnivariateSummary, CreateFullValues) { using namespace hgps::core; auto data = std::vector<double>{ 3.4, 0.5, 2.5, 12.6, 5.7, 8.3, 10.2, 15.8, 7.3, 9.7 }; // min, max, range, sum, average, variance, std_dev, std_error, kurtosis, skewness auto expected = std::vector<double>{ 0.5, 15.8, 15.3, 76.0, 7.6, 22.4066666666667, 4.73356806929685, 1.49688565584238, -0.533980927444051, 0.172868169857032 }; auto tolerance = 1e-10; auto summary = UnivariateSummary("Test", data); ASSERT_EQ("Test", summary.name()); ASSERT_FALSE(summary.is_empty()); ASSERT_EQ(0, summary.count_null()); ASSERT_EQ(data.size(), summary.count_valid()); ASSERT_EQ(data.size(), summary.count_total()); ASSERT_DOUBLE_EQ(expected[0], summary.min()); ASSERT_DOUBLE_EQ(expected[1], summary.max()); ASSERT_DOUBLE_EQ(expected[2], summary.range()); ASSERT_DOUBLE_EQ(expected[3], summary.sum()); ASSERT_DOUBLE_EQ(expected[4], summary.average()); EXPECT_NEAR(expected[5], summary.variance(), tolerance); EXPECT_NEAR(expected[6], summary.std_deviation(), tolerance); EXPECT_NEAR(expected[7], summary.std_error(), tolerance); EXPECT_NEAR(expected[8], summary.kurtosis(), tolerance); EXPECT_NEAR(expected[9], summary.skewness(), tolerance); } TEST(TestCore_UnivariateSummary, AppendOneValues) { using namespace hgps::core; auto data = std::vector<double>{ 3.4, 0.5, 2.5, 12.6, 5.7, 8.3, 10.2, 15.8, 7.3, 9.7 }; // min, max, range, sum, average, variance, std_dev, std_error, kurtosis, skewness auto expected = std::vector<double>{ 0.5, 15.8, 15.3, 76.0, 7.6, 22.4066666666667, 4.73356806929685, 1.49688565584238, -0.533980927444051, 0.172868169857032 }; auto tolerance = 1e-10; auto summary = UnivariateSummary("Test"); for (auto& v : data) { summary.append(v); } ASSERT_EQ("Test", summary.name()); ASSERT_FALSE(summary.is_empty()); ASSERT_EQ(0, summary.count_null()); ASSERT_EQ(data.size(), summary.count_valid()); ASSERT_EQ(data.size(), summary.count_total()); ASSERT_DOUBLE_EQ(expected[0], summary.min()); ASSERT_DOUBLE_EQ(expected[1], summary.max()); ASSERT_DOUBLE_EQ(expected[2], summary.range()); ASSERT_DOUBLE_EQ(expected[3], summary.sum()); ASSERT_DOUBLE_EQ(expected[4], summary.average()); EXPECT_NEAR(expected[5], summary.variance(), tolerance); EXPECT_NEAR(expected[6], summary.std_deviation(), tolerance); EXPECT_NEAR(expected[7], summary.std_error(), tolerance); EXPECT_NEAR(expected[8], summary.kurtosis(), tolerance); EXPECT_NEAR(expected[9], summary.skewness(), tolerance); } TEST(TestCore_UnivariateSummary, AppendRangeValues) { using namespace hgps::core; auto data = std::vector<double>{ 3.4, 0.5, 2.5, 12.6, 5.7, 8.3, 10.2, 15.8, 7.3, 9.7 }; // min, max, range, sum, average, variance, std_dev, std_error, kurtosis, skewness auto expected = std::vector<double>{ 0.5, 15.8, 15.3, 76.0, 7.6, 22.4066666666667, 4.73356806929685, 1.49688565584238, -0.533980927444051, 0.172868169857032 }; auto tolerance = 1e-10; auto summary = UnivariateSummary("Test"); summary.append(data); ASSERT_EQ("Test", summary.name()); ASSERT_FALSE(summary.is_empty()); ASSERT_EQ(0, summary.count_null()); ASSERT_EQ(data.size(), summary.count_valid()); ASSERT_EQ(data.size(), summary.count_total()); ASSERT_DOUBLE_EQ(expected[0], summary.min()); ASSERT_DOUBLE_EQ(expected[1], summary.max()); ASSERT_DOUBLE_EQ(expected[2], summary.range()); ASSERT_DOUBLE_EQ(expected[3], summary.sum()); ASSERT_DOUBLE_EQ(expected[4], summary.average()); EXPECT_NEAR(expected[5], summary.variance(), tolerance); EXPECT_NEAR(expected[6], summary.std_deviation(), tolerance); EXPECT_NEAR(expected[7], summary.std_error(), tolerance); EXPECT_NEAR(expected[8], summary.kurtosis(), tolerance); EXPECT_NEAR(expected[9], summary.skewness(), tolerance); } TEST(TestCore_UnivariateSummary, AppendNullValues) { using namespace hgps::core; auto data = std::vector<double>{ 3.4, 0.5, 2.5, 12.6, 5.7, 8.3, 10.2, 15.8, 7.3, 9.7 }; // min, max, range, sum, average, variance, std_dev, std_error, kurtosis, skewness auto expected = std::vector<double>{ 0.5, 15.8, 15.3, 76.0, 7.6, 22.4066666666667, 4.73356806929685, 1.49688565584238, -0.533980927444051, 0.172868169857032 }; auto tolerance = 1e-10; auto summary = UnivariateSummary("Test", data); auto null_count = 4; auto null_value = std::optional<double>(); summary.append_null(); summary.append_null(2); summary.append(null_value); auto report = summary.to_string(); ASSERT_TRUE(report.size() > 1); ASSERT_EQ("Test", summary.name()); ASSERT_FALSE(summary.is_empty()); ASSERT_EQ(null_count, summary.count_null()); ASSERT_EQ(data.size(), summary.count_valid()); ASSERT_EQ(data.size()+ null_count, summary.count_total()); ASSERT_DOUBLE_EQ(expected[0], summary.min()); ASSERT_DOUBLE_EQ(expected[1], summary.max()); ASSERT_DOUBLE_EQ(expected[2], summary.range()); ASSERT_DOUBLE_EQ(expected[3], summary.sum()); ASSERT_DOUBLE_EQ(expected[4], summary.average()); EXPECT_NEAR(expected[5], summary.variance(), tolerance); EXPECT_NEAR(expected[6], summary.std_deviation(), tolerance); EXPECT_NEAR(expected[7], summary.std_error(), tolerance); EXPECT_NEAR(expected[8], summary.kurtosis(), tolerance); EXPECT_NEAR(expected[9], summary.skewness(), tolerance); }
34.887892
88
0.725707
[ "vector" ]
a3e64f4bcf337bfab0c980a6c6fe545f39a7c8ae
1,907
hpp
C++
source/proxyd/entitymetadata.hpp
mgrech/vitamine
d2fab653a0146b0ad9eb40d62213c968af2a100b
[ "Apache-2.0" ]
null
null
null
source/proxyd/entitymetadata.hpp
mgrech/vitamine
d2fab653a0146b0ad9eb40d62213c968af2a100b
[ "Apache-2.0" ]
null
null
null
source/proxyd/entitymetadata.hpp
mgrech/vitamine
d2fab653a0146b0ad9eb40d62213c968af2a100b
[ "Apache-2.0" ]
null
null
null
#pragma once #include <stdexcept> #include <variant> #include <common/buffer.hpp> #include <common/types.hpp> #include <proxyd/deserialize.hpp> #include <proxyd/serialize.hpp> namespace vitamine::proxyd { enum struct EntityMetadataType : Int32 { BYTE, VARINT, FLOAT, STRING, CHAT, OPT_CHAT, SLOT, BOOL, ROTATION, POSITION, OPT_POSITION, DIRECTION, OPT_UUID, OPT_BLOCK_ID, NBT, PARTICLE, VILLAGER_DATA, OPT_VARINT, POSE, }; enum struct EntityMetadataPose : Int32 { STANDING = 0, FALL_FLYING = 1, SLEEPING = 2, SWIMMING = 3, SPIN_ATTACK = 4, CROUCHING = 5, DYING = 6, }; struct EntityMetadata { UInt8 index; EntityMetadataType type; std::variant<UInt8, Int32, Float32, Span<Char8 const>, bool, EntityMetadataPose> value; }; inline void serializeEntityMetadata(Buffer& buffer, std::vector<EntityMetadata> const& meta) { for(auto& entry : meta) { serializeInt(buffer, entry.index); serializeVarInt(buffer, (Int32)entry.type); switch(entry.type) { case EntityMetadataType::BYTE: serializeInt(buffer, std::get<UInt8>(entry.value)); break; case EntityMetadataType::VARINT: serializeVarInt(buffer, std::get<Int32>(entry.value)); break; case EntityMetadataType::FLOAT: serializeFloat(buffer, std::get<Float32>(entry.value)); break; case EntityMetadataType::BOOL: serializeBool(buffer, std::get<bool>(entry.value)); break; case EntityMetadataType::POSE: serializeVarInt(buffer, (Int32)std::get<EntityMetadataPose>(entry.value)); break; default: // TODO: implement throw std::runtime_error("unimplemented"); } } serializeInt(buffer, (UInt8)0xff); } inline DeserializeStatus deserializeEntityMetadata(UInt8 const** bufpp, UInt* sizep, std::vector<EntityMetadata>* out) { // TODO: implement throw std::runtime_error("unimplemented"); } }
19.07
112
0.694809
[ "vector" ]
a3e739697c0e3bac853b12b2344de0f282ca72d6
63,529
cpp
C++
src/Sequence.cpp
fuchensuq/sneedacity
5740887044a84aa14e902f44c1159885cce71a2b
[ "CC-BY-3.0" ]
986
2021-07-05T22:58:16.000Z
2022-03-31T03:02:03.000Z
src/Sequence.cpp
fuchensuq/sneedacity
5740887044a84aa14e902f44c1159885cce71a2b
[ "CC-BY-3.0" ]
191
2021-07-05T23:02:36.000Z
2022-03-29T20:31:08.000Z
src/Sequence.cpp
fuchensuq/sneedacity
5740887044a84aa14e902f44c1159885cce71a2b
[ "CC-BY-3.0" ]
124
2021-07-05T22:58:01.000Z
2022-03-27T04:50:02.000Z
/********************************************************************** Sneedacity: A Digital Audio Editor Sequence.cpp Dominic Mazzoni *******************************************************************//** \file Sequence.cpp \brief Implements classes Sequence and SeqBlock. *//****************************************************************//** \class Sequence \brief A WaveTrack contains WaveClip(s). A WaveClip contains a Sequence. A Sequence is primarily an interface to an array of SeqBlock instances, corresponding to the audio sample blocks in the database. Contrast with RingBuffer. *//****************************************************************//** \class SeqBlock \brief Data structure containing pointer to a sample block and a start time. Element of a BlockArray. *//*******************************************************************/ #include "Sequence.h" #include <algorithm> #include <float.h> #include <math.h> #include <wx/intl.h> #include <wx/filefn.h> #include <wx/ffile.h> #include <wx/log.h> #include "SampleBlock.h" #include "InconsistencyException.h" #include "widgets/SneedacityMessageBox.h" size_t Sequence::sMaxDiskBlockSize = 1048576; // Sequence methods Sequence::Sequence( const SampleBlockFactoryPtr &pFactory, sampleFormat format) : mpFactory(pFactory), mSampleFormat(format), mMinSamples(sMaxDiskBlockSize / SAMPLE_SIZE(mSampleFormat) / 2), mMaxSamples(mMinSamples * 2) { } // essentially a copy constructor - but you must pass in the // current project, because we might be copying from one // project to another Sequence::Sequence( const Sequence &orig, const SampleBlockFactoryPtr &pFactory) : mpFactory(pFactory), mSampleFormat(orig.mSampleFormat), mMinSamples(orig.mMinSamples), mMaxSamples(orig.mMaxSamples) { Paste(0, &orig); } Sequence::~Sequence() { } size_t Sequence::GetMaxBlockSize() const { return mMaxSamples; } size_t Sequence::GetIdealBlockSize() const { return mMaxSamples; } bool Sequence::CloseLock() { for (unsigned int i = 0; i < mBlock.size(); i++) mBlock[i].sb->CloseLock(); return true; } sampleFormat Sequence::GetSampleFormat() const { return mSampleFormat; } /* bool Sequence::SetSampleFormat(sampleFormat format) { if (mBlock.size() > 0 || mNumSamples > 0) return false; mSampleFormat = format; return true; } */ namespace { void ensureSampleBufferSize(SampleBuffer &buffer, sampleFormat format, size_t &size, size_t required, SampleBuffer *pSecondBuffer = nullptr) { // This should normally do nothing, but it is a defense against corrupt // projects than might have inconsistent block files bigger than the // expected maximum size. if (size < required) { // reallocate buffer.Allocate(required, format); if (pSecondBuffer && pSecondBuffer->ptr()) pSecondBuffer->Allocate(required, format); if (!buffer.ptr() || (pSecondBuffer && !pSecondBuffer->ptr())) { // malloc failed // Perhaps required is a really crazy value, // and perhaps we should throw an SneedacityException, but that is // a second-order concern THROW_INCONSISTENCY_EXCEPTION; } size = required; } } } /*! @excsafety{Strong} */ bool Sequence::ConvertToSampleFormat(sampleFormat format, const std::function<void(size_t)> & progressReport) { if (format == mSampleFormat) // no change return false; if (mBlock.size() == 0) { mSampleFormat = format; return true; } const sampleFormat oldFormat = mSampleFormat; mSampleFormat = format; const auto oldMinSamples = mMinSamples, oldMaxSamples = mMaxSamples; // These are the same calculations as in the constructor. mMinSamples = sMaxDiskBlockSize / SAMPLE_SIZE(mSampleFormat) / 2; mMaxSamples = mMinSamples * 2; bool bSuccess = false; auto cleanup = finally( [&] { if (!bSuccess) { // Conversion failed. Revert these member vars. mSampleFormat = oldFormat; mMaxSamples = oldMaxSamples; mMinSamples = oldMinSamples; } } ); BlockArray newBlockArray; // Use the ratio of old to NEW mMaxSamples to make a reasonable guess // at allocation. newBlockArray.reserve (1 + mBlock.size() * ((float)oldMaxSamples / (float)mMaxSamples)); { size_t oldSize = oldMaxSamples; SampleBuffer bufferOld(oldSize, oldFormat); size_t newSize = oldMaxSamples; SampleBuffer bufferNew(newSize, format); for (size_t i = 0, nn = mBlock.size(); i < nn; i++) { SeqBlock &oldSeqBlock = mBlock[i]; const auto &oldBlockFile = oldSeqBlock.sb; const auto len = oldBlockFile->GetSampleCount(); ensureSampleBufferSize(bufferOld, oldFormat, oldSize, len); Read(bufferOld.ptr(), oldFormat, oldSeqBlock, 0, len, true); ensureSampleBufferSize(bufferNew, format, newSize, len); CopySamples(bufferOld.ptr(), oldFormat, bufferNew.ptr(), format, len); // Note this fix for http://bugzilla.audacityteam.org/show_bug.cgi?id=451, // using Blockify, allows (len < mMinSamples). // This will happen consistently when going from more bytes per sample to fewer... // This will create a block that's smaller than mMinSamples, which // shouldn't be allowed, but we agreed it's okay for now. //vvv ANSWER-ME: Does this cause any bugs, or failures on write, elsewhere? // If so, need to special-case (len < mMinSamples) and start combining data // from the old blocks... Oh no! // Using Blockify will handle the cases where len > the NEW mMaxSamples. Previous code did not. const auto blockstart = oldSeqBlock.start; Blockify(*mpFactory, mMaxSamples, mSampleFormat, newBlockArray, blockstart, bufferNew.ptr(), len); if (progressReport) progressReport(len); } } // Invalidate all the old, non-aliased block files. // Aliased files will be converted at save, per comment above. // Commit the changes to block file array CommitChangesIfConsistent (newBlockArray, mNumSamples, wxT("Sequence::ConvertToSampleFormat()")); // Commit the other changes bSuccess = true; return true; } std::pair<float, float> Sequence::GetMinMax( sampleCount start, sampleCount len, bool mayThrow) const { if (len == 0 || mBlock.size() == 0) { return { 0.f, // FLT_MAX? So it doesn't look like a spurious '0' to a caller? 0.f // -FLT_MAX? So it doesn't look like a spurious '0' to a caller? }; } float min = FLT_MAX; float max = -FLT_MAX; unsigned int block0 = FindBlock(start); unsigned int block1 = FindBlock(start + len - 1); // First calculate the min/max of the blocks in the middle of this region; // this is very fast because we have the min/max of every entire block // already in memory. for (unsigned b = block0 + 1; b < block1; ++b) { auto results = mBlock[b].sb->GetMinMaxRMS(mayThrow); if (results.min < min) min = results.min; if (results.max > max) max = results.max; } // Now we take the first and last blocks into account, noting that the // selection may only partly overlap these blocks. If the overall min/max // of either of these blocks is within min...max, then we can ignore them. // If not, we need read some samples and summaries from disk. { const SeqBlock &theBlock = mBlock[block0]; const auto &theFile = theBlock.sb; auto results = theFile->GetMinMaxRMS(mayThrow); if (results.min < min || results.max > max) { // start lies within theBlock: auto s0 = ( start - theBlock.start ).as_size_t(); const auto maxl0 = ( // start lies within theBlock: theBlock.start + theFile->GetSampleCount() - start ).as_size_t(); wxASSERT(maxl0 <= mMaxSamples); // Vaughan, 2011-10-19 const auto l0 = limitSampleBufferSize ( maxl0, len ); results = theFile->GetMinMaxRMS(s0, l0, mayThrow); if (results.min < min) min = results.min; if (results.max > max) max = results.max; } } if (block1 > block0) { const SeqBlock &theBlock = mBlock[block1]; const auto &theFile = theBlock.sb; auto results = theFile->GetMinMaxRMS(mayThrow); if (results.min < min || results.max > max) { // start + len - 1 lies in theBlock: const auto l0 = ( start + len - theBlock.start ).as_size_t(); wxASSERT(l0 <= mMaxSamples); // Vaughan, 2011-10-19 results = theFile->GetMinMaxRMS(0, l0, mayThrow); if (results.min < min) min = results.min; if (results.max > max) max = results.max; } } return { min, max }; } float Sequence::GetRMS(sampleCount start, sampleCount len, bool mayThrow) const { // len is the number of samples that we want the rms of. // it may be longer than a block, and the code is carefully set up to handle that. if (len == 0 || mBlock.size() == 0) return 0.f; double sumsq = 0.0; sampleCount length = 0; // this is the cumulative length of the bits we have the ms of so far, and should end up == len unsigned int block0 = FindBlock(start); unsigned int block1 = FindBlock(start + len - 1); // First calculate the rms of the blocks in the middle of this region; // this is very fast because we have the rms of every entire block // already in memory. for (unsigned b = block0 + 1; b < block1; b++) { const SeqBlock &theBlock = mBlock[b]; const auto &sb = theBlock.sb; auto results = sb->GetMinMaxRMS(mayThrow); const auto fileLen = sb->GetSampleCount(); const auto blockRMS = results.RMS; sumsq += blockRMS * blockRMS * fileLen; length += fileLen; } // Now we take the first and last blocks into account, noting that the // selection may only partly overlap these blocks. // If not, we need read some samples and summaries from disk. { const SeqBlock &theBlock = mBlock[block0]; const auto &sb = theBlock.sb; // start lies within theBlock auto s0 = ( start - theBlock.start ).as_size_t(); // start lies within theBlock const auto maxl0 = (theBlock.start + sb->GetSampleCount() - start).as_size_t(); wxASSERT(maxl0 <= mMaxSamples); // Vaughan, 2011-10-19 const auto l0 = limitSampleBufferSize( maxl0, len ); auto results = sb->GetMinMaxRMS(s0, l0, mayThrow); const auto partialRMS = results.RMS; sumsq += partialRMS * partialRMS * l0; length += l0; } if (block1 > block0) { const SeqBlock &theBlock = mBlock[block1]; const auto &sb = theBlock.sb; // start + len - 1 lies within theBlock const auto l0 = ( start + len - theBlock.start ).as_size_t(); wxASSERT(l0 <= mMaxSamples); // PRL: I think Vaughan missed this auto results = sb->GetMinMaxRMS(0, l0, mayThrow); const auto partialRMS = results.RMS; sumsq += partialRMS * partialRMS * l0; length += l0; } // PRL: catch bugs like 1320: wxASSERT(length == len); return sqrt(sumsq / length.as_double() ); } // Must pass in the correct factory for the result. If it's not the same // as in this, then block contents must be copied. std::unique_ptr<Sequence> Sequence::Copy( const SampleBlockFactoryPtr &pFactory, sampleCount s0, sampleCount s1) const { // Make a new Sequence object for the specified factory: auto dest = std::make_unique<Sequence>(pFactory, mSampleFormat); if (s0 >= s1 || s0 >= mNumSamples || s1 < 0) { return dest; } // Decide whether to share sample blocks or make new copies, when whole block // contents are used -- must copy if factories are different: auto pUseFactory = (pFactory == mpFactory) ? nullptr : pFactory.get(); int numBlocks = mBlock.size(); int b0 = FindBlock(s0); const int b1 = FindBlock(s1 - 1); wxASSERT(b0 >= 0); wxASSERT(b0 < numBlocks); wxASSERT(b1 < numBlocks); wxUnusedVar(numBlocks); wxASSERT(b0 <= b1); dest->mBlock.reserve(b1 - b0 + 1); auto bufferSize = mMaxSamples; SampleBuffer buffer(bufferSize, mSampleFormat); int blocklen; // Do any initial partial block const SeqBlock &block0 = mBlock[b0]; if (s0 != block0.start) { const auto &sb = block0.sb; // Nonnegative result is length of block0 or less: blocklen = ( std::min(s1, block0.start + sb->GetSampleCount()) - s0 ).as_size_t(); wxASSERT(blocklen <= (int)mMaxSamples); // Vaughan, 2012-02-29 ensureSampleBufferSize(buffer, mSampleFormat, bufferSize, blocklen); Get(b0, buffer.ptr(), mSampleFormat, s0, blocklen, true); dest->Append(buffer.ptr(), mSampleFormat, blocklen); } else --b0; // If there are blocks in the middle, use the blocks whole for (int bb = b0 + 1; bb < b1; ++bb) AppendBlock(pUseFactory, mSampleFormat, dest->mBlock, dest->mNumSamples, mBlock[bb]); // Increase ref count or duplicate file // Do the last block if (b1 > b0) { // Probable case of a partial block const SeqBlock &block = mBlock[b1]; const auto &sb = block.sb; // s1 is within block: blocklen = (s1 - block.start).as_size_t(); wxASSERT(blocklen <= (int)mMaxSamples); // Vaughan, 2012-02-29 if (blocklen < (int)sb->GetSampleCount()) { ensureSampleBufferSize(buffer, mSampleFormat, bufferSize, blocklen); Get(b1, buffer.ptr(), mSampleFormat, block.start, blocklen, true); dest->Append(buffer.ptr(), mSampleFormat, blocklen); } else // Special case of a whole block AppendBlock(pUseFactory, mSampleFormat, dest->mBlock, dest->mNumSamples, block); // Increase ref count or duplicate file } dest->ConsistencyCheck(wxT("Sequence::Copy()")); return dest; } namespace { inline bool Overflows(double numSamples) { return numSamples > wxLL(9223372036854775807); } SampleBlockPtr ShareOrCopySampleBlock( SampleBlockFactory *pFactory, sampleFormat format, SampleBlockPtr sb ) { if ( pFactory ) { // must copy contents to a fresh SampleBlock object in another database auto sampleCount = sb->GetSampleCount(); SampleBuffer buffer{ sampleCount, format }; sb->GetSamples( buffer.ptr(), format, 0, sampleCount ); sb = pFactory->Create( buffer.ptr(), sampleCount, format ); } else // Can just share ; return sb; } } /*! @excsafety{Strong} */ void Sequence::Paste(sampleCount s, const Sequence *src) { if ((s < 0) || (s > mNumSamples)) { wxLogError( wxT("Sequence::Paste: sampleCount s %s is < 0 or > mNumSamples %s)."), // PRL: Why bother with Internat when the above is just wxT? Internat::ToString(s.as_double(), 0), Internat::ToString(mNumSamples.as_double(), 0)); THROW_INCONSISTENCY_EXCEPTION; } // Quick check to make sure that it doesn't overflow if (Overflows((mNumSamples.as_double()) + (src->mNumSamples.as_double()))) { wxLogError( wxT("Sequence::Paste: mNumSamples %s + src->mNumSamples %s would overflow."), // PRL: Why bother with Internat when the above is just wxT? Internat::ToString(mNumSamples.as_double(), 0), Internat::ToString(src->mNumSamples.as_double(), 0)); THROW_INCONSISTENCY_EXCEPTION; } if (src->mSampleFormat != mSampleFormat) { wxLogError( wxT("Sequence::Paste: Sample format to be pasted, %s, does not match destination format, %s."), GetSampleFormatStr(src->mSampleFormat).Debug(), GetSampleFormatStr(mSampleFormat).Debug()); THROW_INCONSISTENCY_EXCEPTION; } const BlockArray &srcBlock = src->mBlock; auto addedLen = src->mNumSamples; const unsigned int srcNumBlocks = srcBlock.size(); auto sampleSize = SAMPLE_SIZE(mSampleFormat); if (addedLen == 0 || srcNumBlocks == 0) return; const size_t numBlocks = mBlock.size(); // Decide whether to share sample blocks or make new copies, when whole block // contents are used -- must copy if factories are different: auto pUseFactory = (src->mpFactory == mpFactory) ? nullptr : mpFactory.get(); if (numBlocks == 0 || (s == mNumSamples && mBlock.back().sb->GetSampleCount() >= mMinSamples)) { // Special case: this track is currently empty, or it's safe to append // onto the end because the current last block is longer than the // minimum size // Build and swap a copy so there is a strong exception safety guarantee BlockArray newBlock{ mBlock }; sampleCount samples = mNumSamples; for (unsigned int i = 0; i < srcNumBlocks; i++) // AppendBlock may throw for limited disk space, if pasting from // one project into another. AppendBlock(pUseFactory, mSampleFormat, newBlock, samples, srcBlock[i]); CommitChangesIfConsistent (newBlock, samples, wxT("Paste branch one")); return; } const int b = (s == mNumSamples) ? mBlock.size() - 1 : FindBlock(s); wxASSERT((b >= 0) && (b < (int)numBlocks)); SeqBlock *const pBlock = &mBlock[b]; const auto length = pBlock->sb->GetSampleCount(); const auto largerBlockLen = addedLen + length; // PRL: when insertion point is the first sample of a block, // and the following test fails, perhaps we could test // whether coalescence with the previous block is possible. if (largerBlockLen <= mMaxSamples) { // Special case: we can fit all of the NEW samples inside of // one block! SeqBlock &block = *pBlock; // largerBlockLen is not more than mMaxSamples... SampleBuffer buffer(largerBlockLen.as_size_t(), mSampleFormat); // ...and addedLen is not more than largerBlockLen auto sAddedLen = addedLen.as_size_t(); // s lies within block: auto splitPoint = ( s - block.start ).as_size_t(); Read(buffer.ptr(), mSampleFormat, block, 0, splitPoint, true); src->Get(0, buffer.ptr() + splitPoint*sampleSize, mSampleFormat, 0, sAddedLen, true); Read(buffer.ptr() + (splitPoint + sAddedLen) * sampleSize, mSampleFormat, block, splitPoint, length - splitPoint, true); // largerBlockLen is not more than mMaxSamples... block.sb = mpFactory->Create( buffer.ptr(), largerBlockLen.as_size_t(), mSampleFormat); // Don't make a duplicate array. We can still give Strong-guarantee // if we modify only one block in place. // use No-fail-guarantee in remaining steps for (unsigned int i = b + 1; i < numBlocks; i++) mBlock[i].start += addedLen; mNumSamples += addedLen; // This consistency check won't throw, it asserts. // Proof that we kept consistency is not hard. ConsistencyCheck(wxT("Paste branch two"), false); return; } // Case three: if we are inserting four or fewer blocks, // it's simplest to just lump all the data together // into one big block along with the split block, // then resplit it all BlockArray newBlock; newBlock.reserve(numBlocks + srcNumBlocks + 2); newBlock.insert(newBlock.end(), mBlock.begin(), mBlock.begin() + b); SeqBlock &splitBlock = mBlock[b]; auto splitLen = splitBlock.sb->GetSampleCount(); // s lies within splitBlock auto splitPoint = ( s - splitBlock.start ).as_size_t(); unsigned int i; if (srcNumBlocks <= 4) { // addedLen is at most four times maximum block size auto sAddedLen = addedLen.as_size_t(); const auto sum = splitLen + sAddedLen; SampleBuffer sumBuffer(sum, mSampleFormat); Read(sumBuffer.ptr(), mSampleFormat, splitBlock, 0, splitPoint, true); src->Get(0, sumBuffer.ptr() + splitPoint * sampleSize, mSampleFormat, 0, sAddedLen, true); Read(sumBuffer.ptr() + (splitPoint + sAddedLen) * sampleSize, mSampleFormat, splitBlock, splitPoint, splitLen - splitPoint, true); Blockify(*mpFactory, mMaxSamples, mSampleFormat, newBlock, splitBlock.start, sumBuffer.ptr(), sum); } else { // The final case is that we're inserting at least five blocks. // We divide these into three groups: the first two get merged // with the first half of the split block, the middle ones get // used whole, and the last two get merged with the last // half of the split block. const auto srcFirstTwoLen = srcBlock[0].sb->GetSampleCount() + srcBlock[1].sb->GetSampleCount(); const auto leftLen = splitPoint + srcFirstTwoLen; const SeqBlock &penultimate = srcBlock[srcNumBlocks - 2]; const auto srcLastTwoLen = penultimate.sb->GetSampleCount() + srcBlock[srcNumBlocks - 1].sb->GetSampleCount(); const auto rightSplit = splitBlock.sb->GetSampleCount() - splitPoint; const auto rightLen = rightSplit + srcLastTwoLen; SampleBuffer sampleBuffer(std::max(leftLen, rightLen), mSampleFormat); Read(sampleBuffer.ptr(), mSampleFormat, splitBlock, 0, splitPoint, true); src->Get(0, sampleBuffer.ptr() + splitPoint*sampleSize, mSampleFormat, 0, srcFirstTwoLen, true); Blockify(*mpFactory, mMaxSamples, mSampleFormat, newBlock, splitBlock.start, sampleBuffer.ptr(), leftLen); for (i = 2; i < srcNumBlocks - 2; i++) { const SeqBlock &block = srcBlock[i]; auto sb = ShareOrCopySampleBlock( pUseFactory, mSampleFormat, block.sb ); newBlock.push_back(SeqBlock(sb, block.start + s)); } auto lastStart = penultimate.start; src->Get(srcNumBlocks - 2, sampleBuffer.ptr(), mSampleFormat, lastStart, srcLastTwoLen, true); Read(sampleBuffer.ptr() + srcLastTwoLen * sampleSize, mSampleFormat, splitBlock, splitPoint, rightSplit, true); Blockify(*mpFactory, mMaxSamples, mSampleFormat, newBlock, s + lastStart, sampleBuffer.ptr(), rightLen); } // Copy remaining blocks to NEW block array and // swap the NEW block array in for the old for (i = b + 1; i < numBlocks; i++) newBlock.push_back(mBlock[i].Plus(addedLen)); CommitChangesIfConsistent (newBlock, mNumSamples + addedLen, wxT("Paste branch three")); } /*! @excsafety{Strong} */ void Sequence::SetSilence(sampleCount s0, sampleCount len) { SetSamples(NULL, mSampleFormat, s0, len); } /*! @excsafety{Strong} */ void Sequence::InsertSilence(sampleCount s0, sampleCount len) { auto &factory = *mpFactory; // Quick check to make sure that it doesn't overflow if (Overflows((mNumSamples.as_double()) + (len.as_double()))) THROW_INCONSISTENCY_EXCEPTION; if (len <= 0) return; // Create a NEW track containing as much silence as we // need to insert, and then call Paste to do the insertion. Sequence sTrack(mpFactory, mSampleFormat); auto idealSamples = GetIdealBlockSize(); sampleCount pos = 0; // Could nBlocks overflow a size_t? Not very likely. You need perhaps // 2 ^ 52 samples which is over 3000 years at 44.1 kHz. auto nBlocks = (len + idealSamples - 1) / idealSamples; sTrack.mBlock.reserve(nBlocks.as_size_t()); if (len >= idealSamples) { auto silentFile = factory.CreateSilent( idealSamples, mSampleFormat); while (len >= idealSamples) { sTrack.mBlock.push_back(SeqBlock(silentFile, pos)); pos += idealSamples; len -= idealSamples; } } if (len != 0) { // len is not more than idealSamples: sTrack.mBlock.push_back(SeqBlock( factory.CreateSilent(len.as_size_t(), mSampleFormat), pos)); pos += len; } sTrack.mNumSamples = pos; // use Strong-guarantee Paste(s0, &sTrack); } void Sequence::AppendBlock( SampleBlockFactory *pFactory, sampleFormat format, BlockArray &mBlock, sampleCount &mNumSamples, const SeqBlock &b) { // Quick check to make sure that it doesn't overflow if (Overflows((mNumSamples.as_double()) + ((double)b.sb->GetSampleCount()))) THROW_INCONSISTENCY_EXCEPTION; auto sb = ShareOrCopySampleBlock( pFactory, format, b.sb ); SeqBlock newBlock(sb, mNumSamples); // We can assume newBlock.sb is not null mBlock.push_back(newBlock); mNumSamples += newBlock.sb->GetSampleCount(); // Don't do a consistency check here because this // function gets called in an inner loop. } sampleCount Sequence::GetBlockStart(sampleCount position) const { int b = FindBlock(position); return mBlock[b].start; } size_t Sequence::GetBestBlockSize(sampleCount start) const { // This method returns a nice number of samples you should try to grab in // one big chunk in order to land on a block boundary, based on the starting // sample. The value returned will always be nonzero and will be no larger // than the value of GetMaxBlockSize() if (start < 0 || start >= mNumSamples) return mMaxSamples; int b = FindBlock(start); int numBlocks = mBlock.size(); const SeqBlock &block = mBlock[b]; // start is in block: auto result = (block.start + block.sb->GetSampleCount() - start).as_size_t(); decltype(result) length; while(result < mMinSamples && b+1<numBlocks && ((length = mBlock[b+1].sb->GetSampleCount()) + result) <= mMaxSamples) { b++; result += length; } wxASSERT(result > 0 && result <= mMaxSamples); return result; } bool Sequence::HandleXMLTag(const wxChar *tag, const wxChar **attrs) { auto &factory = *mpFactory; /* handle waveblock tag and its attributes */ if (!wxStrcmp(tag, wxT("waveblock"))) { SeqBlock wb; // Give SampleBlock a go at the attributes first wb.sb = factory.CreateFromXML(mSampleFormat, attrs); if (wb.sb == nullptr) { mErrorOpening = true; return false; } // loop through attrs, which is a null-terminated list of attribute-value pairs while(*attrs) { const wxChar *attr = *attrs++; const wxChar *value = *attrs++; if (!value) { break; } long long nValue = 0; const wxString strValue = value; // promote string, we need this for all if (wxStrcmp(attr, wxT("start")) == 0) { // This attribute is a sample offset, so can be 64bit if (!XMLValueChecker::IsGoodInt64(strValue) || !strValue.ToLongLong(&nValue) || (nValue < 0)) { mErrorOpening = true; return false; } wb.start = nValue; } } mBlock.push_back(wb); return true; } /* handle sequence tag and its attributes */ if (!wxStrcmp(tag, wxT("sequence"))) { while(*attrs) { const wxChar *attr = *attrs++; const wxChar *value = *attrs++; if (!value) { break; } long long nValue = 0; const wxString strValue = value; // promote string, we need this for all if (!wxStrcmp(attr, wxT("maxsamples"))) { // This attribute is a sample count, so can be 64bit if (!XMLValueChecker::IsGoodInt64(strValue) || !strValue.ToLongLong(&nValue) || (nValue < 0)) { mErrorOpening = true; return false; } // Dominic, 12/10/2006: // Let's check that maxsamples is >= 1024 and <= 64 * 1024 * 1024 // - that's a pretty wide range of reasonable values. if ((nValue < 1024) || (nValue > 64 * 1024 * 1024)) { mErrorOpening = true; return false; } // nValue is now safe for size_t mMaxSamples = nValue; } else if (!wxStrcmp(attr, wxT("sampleformat"))) { // This attribute is a sample format, normal int long fValue; if (!XMLValueChecker::IsGoodInt(strValue) || !strValue.ToLong(&fValue) || (fValue < 0) || !XMLValueChecker::IsValidSampleFormat(fValue)) { mErrorOpening = true; return false; } mSampleFormat = (sampleFormat)fValue; } else if (!wxStrcmp(attr, wxT("numsamples"))) { // This attribute is a sample count, so can be 64bit if (!XMLValueChecker::IsGoodInt64(strValue) || !strValue.ToLongLong(&nValue) || (nValue < 0)) { mErrorOpening = true; return false; } mNumSamples = nValue; } } // while return true; } return false; } void Sequence::HandleXMLEndTag(const wxChar *tag) { if (wxStrcmp(tag, wxT("sequence")) != 0) { return; } // Make sure that the sequence is valid. // Make sure that start times and lengths are consistent sampleCount numSamples = 0; for (unsigned b = 0, nn = mBlock.size(); b < nn; b++) { SeqBlock &block = mBlock[b]; if (block.start != numSamples) { wxLogWarning( wxT("Gap detected in project file.\n") wxT(" Start (%s) for block file %lld is not one sample past end of previous block (%s).\n") wxT(" Moving start so blocks are contiguous."), // PRL: Why bother with Internat when the above is just wxT? Internat::ToString(block.start.as_double(), 0), block.sb->GetBlockID(), Internat::ToString(numSamples.as_double(), 0)); block.start = numSamples; mErrorOpening = true; } numSamples += block.sb->GetSampleCount(); } if (mNumSamples != numSamples) { wxLogWarning( wxT("Gap detected in project file. Correcting sequence sample count from %s to %s."), // PRL: Why bother with Internat when the above is just wxT? Internat::ToString(mNumSamples.as_double(), 0), Internat::ToString(numSamples.as_double(), 0)); mNumSamples = numSamples; mErrorOpening = true; } } XMLTagHandler *Sequence::HandleXMLChild(const wxChar *tag) { if (!wxStrcmp(tag, wxT("waveblock"))) { return this; } return nullptr; } // Throws exceptions rather than reporting errors. void Sequence::WriteXML(XMLWriter &xmlFile) const // may throw { unsigned int b; xmlFile.StartTag(wxT("sequence")); xmlFile.WriteAttr(wxT("maxsamples"), mMaxSamples); xmlFile.WriteAttr(wxT("sampleformat"), (size_t)mSampleFormat); xmlFile.WriteAttr(wxT("numsamples"), mNumSamples.as_long_long() ); for (b = 0; b < mBlock.size(); b++) { const SeqBlock &bb = mBlock[b]; // See http://bugzilla.audacityteam.org/show_bug.cgi?id=451. if (bb.sb->GetSampleCount() > mMaxSamples) { // PRL: Bill observed this error. Not sure how it was caused. // I have added code in ConsistencyCheck that should abort the // editing operation that caused this, not fixing // the problem but moving the point of detection earlier if we // find a reproducible case. auto sMsg = XO("Sequence has block file exceeding maximum %s samples per block.\nTruncating to this maximum length.") .Format( Internat::ToString(((wxLongLong)mMaxSamples).ToDouble(), 0) ); SneedacityMessageBox( sMsg, XO("Warning - Truncating Overlong Block File"), wxICON_EXCLAMATION | wxOK); wxLogWarning(sMsg.Translation()); //Debug? // bb.sb->SetLength(mMaxSamples); } xmlFile.StartTag(wxT("waveblock")); xmlFile.WriteAttr(wxT("start"), bb.start.as_long_long() ); bb.sb->SaveXML(xmlFile); xmlFile.EndTag(wxT("waveblock")); } xmlFile.EndTag(wxT("sequence")); } int Sequence::FindBlock(sampleCount pos) const { wxASSERT(pos >= 0 && pos < mNumSamples); if (pos == 0) return 0; int numBlocks = mBlock.size(); size_t lo = 0, hi = numBlocks, guess; sampleCount loSamples = 0, hiSamples = mNumSamples; while (true) { //this is not a binary search, but a //dictionary search where we guess something smarter than the binary division //of the unsearched area, since samples are usually proportional to block file number. const double frac = (pos - loSamples).as_double() / (hiSamples - loSamples).as_double(); guess = std::min(hi - 1, lo + size_t(frac * (hi - lo))); const SeqBlock &block = mBlock[guess]; wxASSERT(block.sb->GetSampleCount() > 0); wxASSERT(lo <= guess && guess < hi && lo < hi); if (pos < block.start) { wxASSERT(lo != guess); hi = guess; hiSamples = block.start; } else { const sampleCount nextStart = block.start + block.sb->GetSampleCount(); if (pos < nextStart) break; else { wxASSERT(guess < hi - 1); lo = guess + 1; loSamples = nextStart; } } } const int rval = guess; wxASSERT(rval >= 0 && rval < numBlocks && pos >= mBlock[rval].start && pos < mBlock[rval].start + mBlock[rval].sb->GetSampleCount()); return rval; } //static bool Sequence::Read(samplePtr buffer, sampleFormat format, const SeqBlock &b, size_t blockRelativeStart, size_t len, bool mayThrow) { const auto &sb = b.sb; wxASSERT(blockRelativeStart + len <= sb->GetSampleCount()); // Either throws, or of !mayThrow, tells how many were really read auto result = sb->GetSamples(buffer, format, blockRelativeStart, len, mayThrow); if (result != len) { wxLogWarning(wxT("Expected to read %ld samples, got %ld samples."), len, result); return false; } return true; } bool Sequence::Get(samplePtr buffer, sampleFormat format, sampleCount start, size_t len, bool mayThrow) const { if (start == mNumSamples) { return len == 0; } if (start < 0 || start + len > mNumSamples) { if (mayThrow) THROW_INCONSISTENCY_EXCEPTION; ClearSamples( buffer, floatSample, 0, len ); return false; } int b = FindBlock(start); return Get(b, buffer, format, start, len, mayThrow); } bool Sequence::Get(int b, samplePtr buffer, sampleFormat format, sampleCount start, size_t len, bool mayThrow) const { bool result = true; while (len) { const SeqBlock &block = mBlock[b]; // start is in block const auto bstart = (start - block.start).as_size_t(); // bstart is not more than block length const auto blen = std::min(len, block.sb->GetSampleCount() - bstart); if (! Read(buffer, format, block, bstart, blen, mayThrow) ) result = false; len -= blen; buffer += (blen * SAMPLE_SIZE(format)); b++; start += blen; } return result; } // Pass NULL to set silence /*! @excsafety{Strong} */ void Sequence::SetSamples(constSamplePtr buffer, sampleFormat format, sampleCount start, sampleCount len) { auto &factory = *mpFactory; const auto size = mBlock.size(); if (start < 0 || start + len > mNumSamples) THROW_INCONSISTENCY_EXCEPTION; size_t tempSize = mMaxSamples; // to do: allocate this only on demand SampleBuffer scratch(tempSize, mSampleFormat); SampleBuffer temp; if (buffer && format != mSampleFormat) { temp.Allocate(tempSize, mSampleFormat); } int b = FindBlock(start); BlockArray newBlock; std::copy( mBlock.begin(), mBlock.begin() + b, std::back_inserter(newBlock) ); while (len > 0 // Redundant termination condition, // but it guards against infinite loop in case of inconsistencies // (too-small files, not yet seen?) // that cause the loop to make no progress because blen == 0 && b < (int)size ) { newBlock.push_back( mBlock[b] ); SeqBlock &block = newBlock.back(); // start is within block const auto bstart = ( start - block.start ).as_size_t(); const auto fileLength = block.sb->GetSampleCount(); // the std::min is a guard against inconsistent Sequence const auto blen = limitSampleBufferSize( fileLength - std::min( bstart, fileLength ), len ); wxASSERT(blen == 0 || bstart + blen <= fileLength); #if 0 // PRL: This inconsistency (too-big file) has been seen in "the wild" // in 2.2.0. It is the least problematic kind of inconsistency. // We will tolerate it for 2.2.1. // Not known whether it is only in projects saved in earlier versions. // After 2.2.1, we should detect and correct it at file loading time. if (fileLength > mMaxSamples) { THROW_INCONSISTENCY_EXCEPTION; } #endif ensureSampleBufferSize(scratch, mSampleFormat, tempSize, fileLength, &temp); auto useBuffer = buffer; if (buffer && format != mSampleFormat) { // To do: remove the extra movement. // Note: we ensured temp can hold fileLength. blen is not more CopySamples(buffer, format, temp.ptr(), mSampleFormat, blen); useBuffer = temp.ptr(); } // We don't ever write to an existing block; to support Undo, // we copy the old block entirely into memory, dereference it, // make the change, and then write the NEW block to disk. if ( bstart > 0 || blen < fileLength ) { // First or last block is only partially overwritten Read(scratch.ptr(), mSampleFormat, block, 0, fileLength, true); if (useBuffer) { auto sampleSize = SAMPLE_SIZE(mSampleFormat); memcpy(scratch.ptr() + bstart * sampleSize, useBuffer, blen * sampleSize); } else ClearSamples(scratch.ptr(), mSampleFormat, bstart, blen); block.sb = factory.Create( scratch.ptr(), fileLength, mSampleFormat); } else { // Avoid reading the disk when the replacement is total if (useBuffer) block.sb = factory.Create(useBuffer, fileLength, mSampleFormat); else block.sb = factory.CreateSilent(fileLength, mSampleFormat); } // blen might be zero for inconsistent Sequence... if( buffer ) buffer += (blen * SAMPLE_SIZE(format)); len -= blen; start += blen; // ... but this, at least, always guarantees some loop progress: b++; } std::copy( mBlock.begin() + b, mBlock.end(), std::back_inserter(newBlock) ); CommitChangesIfConsistent( newBlock, mNumSamples, wxT("SetSamples") ); } namespace { struct MinMaxSumsq { MinMaxSumsq(const float *pv, int count, int divisor) { min = FLT_MAX, max = -FLT_MAX, sumsq = 0.0f; while (count--) { float v; switch (divisor) { default: case 1: // array holds samples v = *pv++; if (v < min) min = v; if (v > max) max = v; sumsq += v * v; break; case 256: case 65536: // array holds triples of min, max, and rms values v = *pv++; if (v < min) min = v; v = *pv++; if (v > max) max = v; v = *pv++; sumsq += v * v; break; } } } float min; float max; float sumsq; }; } bool Sequence::GetWaveDisplay(float *min, float *max, float *rms, int* bl, size_t len, const sampleCount *where) const { wxASSERT(len > 0); const auto s0 = std::max(sampleCount(0), where[0]); if (s0 >= mNumSamples) // None of the samples asked for are in range. Abandon. return false; // In case where[len - 1] == where[len], raise the limit by one, // so we load at least one pixel for column len - 1 // ... unless the mNumSamples ceiling applies, and then there are other defenses const auto s1 = std::min(mNumSamples, std::max(1 + where[len - 1], where[len])); Floats temp{ mMaxSamples }; decltype(len) pixel = 0; auto srcX = s0; decltype(srcX) nextSrcX = 0; int lastRmsDenom = 0; int lastDivisor = 0; auto whereNow = std::min(s1 - 1, where[0]); decltype(whereNow) whereNext = 0; // Loop over block files, opening and reading and closing each // not more than once unsigned nBlocks = mBlock.size(); const unsigned int block0 = FindBlock(s0); for (unsigned int b = block0; b < nBlocks; ++b) { if (b > block0) srcX = nextSrcX; if (srcX >= s1) break; // Find the range of sample values for this block that // are in the display. const SeqBlock &seqBlock = mBlock[b]; const auto start = seqBlock.start; nextSrcX = std::min(s1, start + seqBlock.sb->GetSampleCount()); // The column for pixel p covers samples from // where[p] up to but excluding where[p + 1]. // Find the range of pixels covered by the current block file // (Their starting samples covered by it, to be exact) decltype(len) nextPixel; if (nextSrcX >= s1) // last pass nextPixel = len; else { nextPixel = pixel; // Taking min with s1 - 1, here and elsewhere, is another defense // to be sure the last pixel column gets at least one sample while (nextPixel < len && (whereNext = std::min(s1 - 1, where[nextPixel])) < nextSrcX) ++nextPixel; } if (nextPixel == pixel) // The entire block's samples fall within one pixel column. // Either it's a rare odd block at the end, or else, // we must be really zoomed out! // Omit the entire block's contents from min/max/rms // calculation, which is not correct, but correctness might not // be worth the compute time if this happens every pixel // column. -- PRL continue; if (nextPixel == len) whereNext = s1; // Decide the summary level const double samplesPerPixel = (whereNext - whereNow).as_double() / (nextPixel - pixel); const int divisor = (samplesPerPixel >= 65536) ? 65536 : (samplesPerPixel >= 256) ? 256 : 1; int blockStatus = b; // How many samples or triples are needed? const size_t startPosition = // srcX and start are in the same block std::max(sampleCount(0), (srcX - start) / divisor).as_size_t(); const size_t inclusiveEndPosition = // nextSrcX - 1 and start are in the same block std::min((sampleCount(mMaxSamples) / divisor) - 1, (nextSrcX - 1 - start) / divisor).as_size_t(); const auto num = 1 + inclusiveEndPosition - startPosition; if (num <= 0) { // What? There was a zero length block file? wxASSERT(false); // Do some defense against this case anyway while (pixel < nextPixel) { min[pixel] = max[pixel] = rms[pixel] = 0; bl[pixel] = blockStatus;//MC ++pixel; } continue; } // Read from the block file or its summary switch (divisor) { default: case 1: // Read samples // no-throw for display operations! Read((samplePtr)temp.get(), floatSample, seqBlock, startPosition, num, false); break; case 256: // Read triples // Ignore the return value. // This function fills with zeroes if read fails seqBlock.sb->GetSummary256(temp.get(), startPosition, num); break; case 65536: // Read triples // Ignore the return value. // This function fills with zeroes if read fails seqBlock.sb->GetSummary64k(temp.get(), startPosition, num); break; } auto filePosition = startPosition; // The previous pixel column might straddle blocks. // If so, impute some of the data to it. if (b > block0 && pixel > 0) { // whereNow and start are in the same block auto midPosition = ((whereNow - start) / divisor).as_size_t(); int diff(midPosition - filePosition); if (diff > 0) { MinMaxSumsq values(temp.get(), diff, divisor); const int lastPixel = pixel - 1; float &lastMin = min[lastPixel]; lastMin = std::min(lastMin, values.min); float &lastMax = max[lastPixel]; lastMax = std::max(lastMax, values.max); float &lastRms = rms[lastPixel]; int lastNumSamples = lastRmsDenom * lastDivisor; lastRms = sqrt( (lastRms * lastRms * lastNumSamples + values.sumsq * divisor) / (lastNumSamples + diff * divisor) ); filePosition = midPosition; } } // Loop over file positions int rmsDenom = 0; for (; filePosition <= inclusiveEndPosition;) { // Find range of pixel columns for this file position // (normally just one, but maybe more when zoomed very close) // and the range of positions for those columns // (normally one or more, for that one column) auto pixelX = pixel + 1; decltype(filePosition) positionX = 0; while (pixelX < nextPixel && filePosition == (positionX = ( // s1 - 1 or where[pixelX] and start are in the same block (std::min(s1 - 1, where[pixelX]) - start) / divisor).as_size_t() ) ) ++pixelX; if (pixelX >= nextPixel) positionX = 1 + inclusiveEndPosition; // Find results to assign rmsDenom = (positionX - filePosition); wxASSERT(rmsDenom > 0); const float *const pv = temp.get() + (filePosition - startPosition) * (divisor == 1 ? 1 : 3); MinMaxSumsq values(pv, std::max(0, rmsDenom), divisor); // Assign results std::fill(&min[pixel], &min[pixelX], values.min); std::fill(&max[pixel], &max[pixelX], values.max); std::fill(&bl[pixel], &bl[pixelX], blockStatus); std::fill(&rms[pixel], &rms[pixelX], (float)sqrt(values.sumsq / rmsDenom)); pixel = pixelX; filePosition = positionX; } wxASSERT(pixel == nextPixel); whereNow = whereNext; pixel = nextPixel; lastDivisor = divisor; lastRmsDenom = rmsDenom; } // for each block file wxASSERT(pixel == len); return true; } size_t Sequence::GetIdealAppendLen() const { int numBlocks = mBlock.size(); const auto max = GetMaxBlockSize(); if (numBlocks == 0) return max; const auto lastBlockLen = mBlock.back().sb->GetSampleCount(); if (lastBlockLen >= max) return max; else return max - lastBlockLen; } /*! @excsafety{Strong} */ SeqBlock::SampleBlockPtr Sequence::AppendNewBlock( constSamplePtr buffer, sampleFormat format, size_t len) { return DoAppend( buffer, format, len, false ); } /*! @excsafety{Strong} */ void Sequence::AppendSharedBlock(const SeqBlock::SampleBlockPtr &pBlock) { auto len = pBlock->GetSampleCount(); // Quick check to make sure that it doesn't overflow if (Overflows(mNumSamples.as_double() + ((double)len))) THROW_INCONSISTENCY_EXCEPTION; BlockArray newBlock; newBlock.emplace_back( pBlock, mNumSamples ); auto newNumSamples = mNumSamples + len; AppendBlocksIfConsistent(newBlock, false, newNumSamples, wxT("Append")); // JKC: During generate we use Append again and again. // If generating a long sequence this test would give O(n^2) // performance - not good! #ifdef VERY_SLOW_CHECKING ConsistencyCheck(wxT("Append")); #endif } /*! @excsafety{Strong} */ void Sequence::Append(constSamplePtr buffer, sampleFormat format, size_t len) { DoAppend(buffer, format, len, true); } /*! @excsafety{Strong} */ SeqBlock::SampleBlockPtr Sequence::DoAppend( constSamplePtr buffer, sampleFormat format, size_t len, bool coalesce) { SeqBlock::SampleBlockPtr result; if (len == 0) return result; auto &factory = *mpFactory; // Quick check to make sure that it doesn't overflow if (Overflows(mNumSamples.as_double() + ((double)len))) THROW_INCONSISTENCY_EXCEPTION; BlockArray newBlock; sampleCount newNumSamples = mNumSamples; // If the last block is not full, we need to add samples to it int numBlocks = mBlock.size(); SeqBlock *pLastBlock; decltype(pLastBlock->sb->GetSampleCount()) length; size_t bufferSize = mMaxSamples; SampleBuffer buffer2(bufferSize, mSampleFormat); bool replaceLast = false; if (coalesce && numBlocks > 0 && (length = (pLastBlock = &mBlock.back())->sb->GetSampleCount()) < mMinSamples) { // Enlarge a sub-minimum block at the end const SeqBlock &lastBlock = *pLastBlock; const auto addLen = std::min(mMaxSamples - length, len); Read(buffer2.ptr(), mSampleFormat, lastBlock, 0, length, true); CopySamples(buffer, format, buffer2.ptr() + length * SAMPLE_SIZE(mSampleFormat), mSampleFormat, addLen); const auto newLastBlockLen = length + addLen; SampleBlockPtr pBlock = factory.Create( buffer2.ptr(), newLastBlockLen, mSampleFormat); SeqBlock newLastBlock(pBlock, lastBlock.start); newBlock.push_back( newLastBlock ); len -= addLen; newNumSamples += addLen; buffer += addLen * SAMPLE_SIZE(format); replaceLast = true; } // Append the rest as NEW blocks while (len) { const auto idealSamples = GetIdealBlockSize(); const auto addedLen = std::min(idealSamples, len); SampleBlockPtr pBlock; if (format == mSampleFormat) { pBlock = factory.Create(buffer, addedLen, mSampleFormat); // It's expected that when not requesting coalescence, the // data should fit in one block wxASSERT( coalesce || !result ); result = pBlock; } else { CopySamples(buffer, format, buffer2.ptr(), mSampleFormat, addedLen); pBlock = factory.Create(buffer2.ptr(), addedLen, mSampleFormat); } newBlock.push_back(SeqBlock(pBlock, newNumSamples)); buffer += addedLen * SAMPLE_SIZE(format); newNumSamples += addedLen; len -= addedLen; } AppendBlocksIfConsistent(newBlock, replaceLast, newNumSamples, wxT("Append")); // JKC: During generate we use Append again and again. // If generating a long sequence this test would give O(n^2) // performance - not good! #ifdef VERY_SLOW_CHECKING ConsistencyCheck(wxT("Append")); #endif return result; } void Sequence::Blockify(SampleBlockFactory &factory, size_t mMaxSamples, sampleFormat mSampleFormat, BlockArray &list, sampleCount start, constSamplePtr buffer, size_t len) { if (len <= 0) return; auto num = (len + (mMaxSamples - 1)) / mMaxSamples; list.reserve(list.size() + num); for (decltype(num) i = 0; i < num; i++) { SeqBlock b; const auto offset = i * len / num; b.start = start + offset; int newLen = ((i + 1) * len / num) - offset; auto bufStart = buffer + (offset * SAMPLE_SIZE(mSampleFormat)); b.sb = factory.Create(bufStart, newLen, mSampleFormat); list.push_back(b); } } /*! @excsafety{Strong} */ void Sequence::Delete(sampleCount start, sampleCount len) { if (len == 0) return; if (len < 0 || start < 0 || start + len > mNumSamples) THROW_INCONSISTENCY_EXCEPTION; auto &factory = *mpFactory; const unsigned int numBlocks = mBlock.size(); const unsigned int b0 = FindBlock(start); unsigned int b1 = FindBlock(start + len - 1); auto sampleSize = SAMPLE_SIZE(mSampleFormat); SeqBlock *pBlock; decltype(pBlock->sb->GetSampleCount()) length; // One buffer for reuse in various branches here SampleBuffer scratch; // The maximum size that should ever be needed auto scratchSize = mMaxSamples + mMinSamples; // Special case: if the samples to DELETE are all within a single // block and the resulting length is not too small, perform the // deletion within this block: if (b0 == b1 && (length = (pBlock = &mBlock[b0])->sb->GetSampleCount()) - len >= mMinSamples) { SeqBlock &b = *pBlock; // start is within block auto pos = ( start - b.start ).as_size_t(); // Guard against failure of this anyway below with limitSampleBufferSize wxASSERT(len < length); // len must be less than length // because start + len - 1 is also in the block... auto newLen = ( length - limitSampleBufferSize( length, len ) ); scratch.Allocate(scratchSize, mSampleFormat); ensureSampleBufferSize(scratch, mSampleFormat, scratchSize, newLen); Read(scratch.ptr(), mSampleFormat, b, 0, pos, true); Read(scratch.ptr() + (pos * sampleSize), mSampleFormat, b, // ... and therefore pos + len // is not more than the length of the block ( pos + len ).as_size_t(), newLen - pos, true); b.sb = factory.Create(scratch.ptr(), newLen, mSampleFormat); // Don't make a duplicate array. We can still give Strong-guarantee // if we modify only one block in place. // use No-fail-guarantee in remaining steps for (unsigned int j = b0 + 1; j < numBlocks; j++) mBlock[j].start -= len; mNumSamples -= len; // This consistency check won't throw, it asserts. // Proof that we kept consistency is not hard. ConsistencyCheck(wxT("Delete - branch one"), false); return; } // Create a NEW array of blocks BlockArray newBlock; newBlock.reserve(numBlocks - (b1 - b0) + 2); // Copy the blocks before the deletion point over to // the NEW array newBlock.insert(newBlock.end(), mBlock.begin(), mBlock.begin() + b0); unsigned int i; // First grab the samples in block b0 before the deletion point // into preBuffer. If this is enough samples for its own block, // or if this would be the first block in the array, write it out. // Otherwise combine it with the previous block (splitting them // 50/50 if necessary). const SeqBlock &preBlock = mBlock[b0]; // start is within preBlock auto preBufferLen = ( start - preBlock.start ).as_size_t(); if (preBufferLen) { if (preBufferLen >= mMinSamples || b0 == 0) { if (!scratch.ptr()) scratch.Allocate(scratchSize, mSampleFormat); ensureSampleBufferSize(scratch, mSampleFormat, scratchSize, preBufferLen); Read(scratch.ptr(), mSampleFormat, preBlock, 0, preBufferLen, true); auto pFile = factory.Create(scratch.ptr(), preBufferLen, mSampleFormat); newBlock.push_back(SeqBlock(pFile, preBlock.start)); } else { const SeqBlock &prepreBlock = mBlock[b0 - 1]; const auto prepreLen = prepreBlock.sb->GetSampleCount(); const auto sum = prepreLen + preBufferLen; if (!scratch.ptr()) scratch.Allocate(scratchSize, mSampleFormat); ensureSampleBufferSize(scratch, mSampleFormat, scratchSize, sum); Read(scratch.ptr(), mSampleFormat, prepreBlock, 0, prepreLen, true); Read(scratch.ptr() + prepreLen*sampleSize, mSampleFormat, preBlock, 0, preBufferLen, true); newBlock.pop_back(); Blockify(*mpFactory, mMaxSamples, mSampleFormat, newBlock, prepreBlock.start, scratch.ptr(), sum); } } else { // The sample where we begin deletion happens to fall // right on the beginning of a block. } // Now, symmetrically, grab the samples in block b1 after the // deletion point into postBuffer. If this is enough samples // for its own block, or if this would be the last block in // the array, write it out. Otherwise combine it with the // subsequent block (splitting them 50/50 if necessary). const SeqBlock &postBlock = mBlock[b1]; // start + len - 1 lies within postBlock const auto postBufferLen = ( (postBlock.start + postBlock.sb->GetSampleCount()) - (start + len) ).as_size_t(); if (postBufferLen) { if (postBufferLen >= mMinSamples || b1 == numBlocks - 1) { if (!scratch.ptr()) // Last use of scratch, can ask for smaller scratch.Allocate(postBufferLen, mSampleFormat); // start + len - 1 lies within postBlock auto pos = (start + len - postBlock.start).as_size_t(); Read(scratch.ptr(), mSampleFormat, postBlock, pos, postBufferLen, true); auto file = factory.Create(scratch.ptr(), postBufferLen, mSampleFormat); newBlock.push_back(SeqBlock(file, start)); } else { SeqBlock &postpostBlock = mBlock[b1 + 1]; const auto postpostLen = postpostBlock.sb->GetSampleCount(); const auto sum = postpostLen + postBufferLen; if (!scratch.ptr()) // Last use of scratch, can ask for smaller scratch.Allocate(sum, mSampleFormat); // start + len - 1 lies within postBlock auto pos = (start + len - postBlock.start).as_size_t(); Read(scratch.ptr(), mSampleFormat, postBlock, pos, postBufferLen, true); Read(scratch.ptr() + (postBufferLen * sampleSize), mSampleFormat, postpostBlock, 0, postpostLen, true); Blockify(*mpFactory, mMaxSamples, mSampleFormat, newBlock, start, scratch.ptr(), sum); b1++; } } else { // The sample where we begin deletion happens to fall // right on the end of a block. } // Copy the remaining blocks over from the old array for (i = b1 + 1; i < numBlocks; i++) newBlock.push_back(mBlock[i].Plus(-len)); CommitChangesIfConsistent (newBlock, mNumSamples - len, wxT("Delete - branch two")); } void Sequence::ConsistencyCheck(const wxChar *whereStr, bool mayThrow) const { ConsistencyCheck(mBlock, mMaxSamples, 0, mNumSamples, whereStr, mayThrow); } void Sequence::ConsistencyCheck (const BlockArray &mBlock, size_t maxSamples, size_t from, sampleCount mNumSamples, const wxChar *whereStr, bool WXUNUSED(mayThrow)) { // Construction of the exception at the appropriate line of the function // gives a little more discrimination Optional<InconsistencyException> ex; unsigned int numBlocks = mBlock.size(); unsigned int i; sampleCount pos = from < numBlocks ? mBlock[from].start : mNumSamples; if ( from == 0 && pos != 0 ) ex.emplace( CONSTRUCT_INCONSISTENCY_EXCEPTION ); for (i = from; !ex && i < numBlocks; i++) { const SeqBlock &seqBlock = mBlock[i]; if (pos != seqBlock.start) ex.emplace( CONSTRUCT_INCONSISTENCY_EXCEPTION ); if ( seqBlock.sb ) { const auto length = seqBlock.sb->GetSampleCount(); if (length > maxSamples) ex.emplace( CONSTRUCT_INCONSISTENCY_EXCEPTION ); pos += length; } else ex.emplace( CONSTRUCT_INCONSISTENCY_EXCEPTION ); } if ( !ex && pos != mNumSamples ) ex.emplace( CONSTRUCT_INCONSISTENCY_EXCEPTION ); if ( ex ) { wxLogError(wxT("*** Consistency check failed at %d after %s. ***"), ex->GetLine(), whereStr); wxString str; DebugPrintf(mBlock, mNumSamples, &str); wxLogError(wxT("%s"), str); wxLogError(wxT("*** Please report this error to https://github.com/Sneeds-Feed-and-Seed/sneedacity/issues. ***\n\n") wxT("Recommended course of action:\n") wxT("Undo the failed operation(s), then export or save your work and quit.")); //if (mayThrow) //throw *ex; //else wxASSERT(false); } } void Sequence::CommitChangesIfConsistent (BlockArray &newBlock, sampleCount numSamples, const wxChar *whereStr) { ConsistencyCheck( newBlock, mMaxSamples, 0, numSamples, whereStr ); // may throw // now commit // use No-fail-guarantee mBlock.swap(newBlock); mNumSamples = numSamples; } void Sequence::AppendBlocksIfConsistent (BlockArray &additionalBlocks, bool replaceLast, sampleCount numSamples, const wxChar *whereStr) { // Any additional blocks are meant to be appended, // replacing the final block if there was one. if (additionalBlocks.empty()) return; bool tmpValid = false; SeqBlock tmp; if ( replaceLast && ! mBlock.empty() ) { tmp = mBlock.back(), tmpValid = true; mBlock.pop_back(); } auto prevSize = mBlock.size(); bool consistent = false; auto cleanup = finally( [&] { if ( !consistent ) { mBlock.resize( prevSize ); if ( tmpValid ) mBlock.push_back( tmp ); } } ); std::copy( additionalBlocks.begin(), additionalBlocks.end(), std::back_inserter( mBlock ) ); // Check consistency only of the blocks that were added, // avoiding quadratic time for repeated checking of repeating appends ConsistencyCheck( mBlock, mMaxSamples, prevSize, numSamples, whereStr ); // may throw // now commit // use No-fail-guarantee mNumSamples = numSamples; consistent = true; } void Sequence::DebugPrintf (const BlockArray &mBlock, sampleCount mNumSamples, wxString *dest) { unsigned int i; decltype(mNumSamples) pos = 0; for (i = 0; i < mBlock.size(); i++) { const SeqBlock &seqBlock = mBlock[i]; *dest += wxString::Format (wxT(" Block %3u: start %8lld, len %8lld, refs %ld, id %lld"), i, seqBlock.start.as_long_long(), seqBlock.sb ? (long long) seqBlock.sb->GetSampleCount() : 0, seqBlock.sb ? seqBlock.sb.use_count() : 0, seqBlock.sb ? (long long) seqBlock.sb->GetBlockID() : 0); if ((pos != seqBlock.start) || !seqBlock.sb) *dest += wxT(" ERROR\n"); else *dest += wxT("\n"); if (seqBlock.sb) pos += seqBlock.sb->GetSampleCount(); } if (pos != mNumSamples) *dest += wxString::Format (wxT("ERROR mNumSamples = %lld\n"), mNumSamples.as_long_long()); } // static void Sequence::SetMaxDiskBlockSize(size_t bytes) { sMaxDiskBlockSize = bytes; } size_t Sequence::GetMaxDiskBlockSize() { return sMaxDiskBlockSize; }
32.462443
148
0.614176
[ "object" ]
a3ebaffcc9a35d6a52bcc3594f42cfc470b8e8e9
9,151
cpp
C++
ivec/UT/ivecUT.cpp
DavidPetr/Internship_Tasks
6c22cf2af667325553df99ebe79c3f5ebd741689
[ "MIT" ]
null
null
null
ivec/UT/ivecUT.cpp
DavidPetr/Internship_Tasks
6c22cf2af667325553df99ebe79c3f5ebd741689
[ "MIT" ]
null
null
null
ivec/UT/ivecUT.cpp
DavidPetr/Internship_Tasks
6c22cf2af667325553df99ebe79c3f5ebd741689
[ "MIT" ]
null
null
null
#include "ivecUT.h" void ivecUT::test_constructor() { { ivec v; if (&v == nullptr) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } void ivecUT::test_constructor_copy() { { ivec v1; ivec v2(v1); if (&v1 == nullptr || &v2 == nullptr) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } { ivec v1(10, 20); ivec v2(v1); if (v1.size() != v2.size()) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } if (v1.capacity() != v2.capacity()) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } for (int i = 0; i < v1.size(); ++i) { if (v1[i] != v2[i]) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } } void ivecUT::test_assigment_operator() { { ivec v1; ivec v2; v2 = v1; v2 = v2; if (&v1 == nullptr || &v2 == nullptr) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } { ivec v1(10, 20); ivec v2; v2 = v1; v2 = v2; if (v1.size() != v2.size()) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } if (v1.capacity() != v2.capacity()) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } for (int i = 0; i < v1.size(); ++i) { if (v1[i] != v2[i]) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } } void ivecUT::test_reserve() { { ivec v; v.reserve(15); if (v.capacity() < 15) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } v.reserve(10); if (v.capacity() < 15) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } v.reserve(15); if (v.capacity() < 15) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } void ivecUT::test_resize() { { ivec v; v.resize(10); if (v.size() < 10) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } v.resize(5); if (v.size() < 5) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } v.resize(0); if (!v.empty()) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } void ivecUT::test_push_back() { { ivec v; v.push_back(10); if (v.size() != 1) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } if (v[0] != 10) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } void ivecUT::test_pop_back() { { ivec v; v.push_back(10); v.pop_back(); if (!v.empty()) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } try { v.pop_back(); } catch (std::out_of_range &e) { std::string s = e.what(); if (s != "Trying to pop from empty object!!!") { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } } void ivecUT::test_index_operator() { { ivec v(10, 4); if (v[0] != 4) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } v.push_back(28); if (v.back() != 28) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } void ivecUT::test_erase() { { ivec v; ivec::iterator it = v.begin(); try { v.erase(it); } catch (std::logic_error& e) { std::string s = e.what(); if (s != "Trying erase null const iterator!!!") { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } v.push_back(1); it = v.begin(); v.erase(it); if (!v.empty()) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } v.push_back(1); v.push_back(2); v.push_back(3); it = v.begin(); ++it; v.erase(it); if (v[1] != 3) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } void ivecUT::test_insert() { { ivec v; ivec::iterator it = v.begin(); try { v.insert(it, 0); } catch (std::logic_error& e) { std::string s = e.what(); if (s != "Trying insert null iterator!!!") { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } { ivec v(2, 3); ivec::iterator it = v.begin(); v.insert(it, 0); if (v[0] != 0) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } it = v.begin(); ++it; v.insert(it, 1); if (v[1] != 1) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } it = v.begin(); it += 2; v.insert(it, 2); if (v[2] != 2) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } it = v.end(); v.insert(it, 6); if (v[5] != 6) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } it = v.end(); --it; v.insert(it, 5); if (v[5] != 5) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } if (v[3] != 3 || v[4] != 3) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } void ivecUT::test_empty() { { ivec v; if (!v.empty()) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } v.push_back(10); if (v.empty()) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } void ivecUT::test_clear() { { ivec v(3, 4); v.clear(); if (!v.empty()) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } ivec v1; v1.clear(); if (!v1.empty()) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } void ivecUT::test_back() { { ivec v; try { v.back(); } catch (std::logic_error& e) { std::string s = e.what(); if (s != "Trying access to empty object!!!") { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } { ivec v; v.push_back(1); if (v.back() != 1) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } void ivecUT::test_front() { { ivec v; try { v.front(); } catch (std::logic_error& e) { std::string s = e.what(); if (s != "Trying access to empty object!!!") { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } { ivec v; v.push_back(1); if (v.front() != 1) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } void ivecUT::test_at() { { ivec v; try { v.at(0); } catch (std::out_of_range& e) { std::string s = e.what(); if (s != "Trying to access via out of range index!!!") { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } { ivec v(3, 2); try { v.at(3); } catch (std::out_of_range& e) { std::string s = e.what(); if (s != "Trying to access via out of range index!!!") { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } v.push_back(10); if (v.at(3) != 10) { std::stringstream sstm; sstm << "Error on line " << __LINE__; throw std::logic_error(sstm.str()); } } } void ivecUT::Test() { bool testOK = true; try { test_constructor(); test_constructor_copy(); test_assigment_operator(); test_reserve(); test_resize(); test_push_back(); test_pop_back(); test_index_operator(); test_erase(); test_insert(); test_empty(); test_clear(); test_back(); test_front(); test_at(); } catch (std::logic_error const& e) { testOK = false; std::cout << "Test failed: " << e.what() << std::endl; } catch (...) { std::cout << "Unexpected Error" << std::endl; } if (testOK) { std::cout << "TestSucceeded!!!" << std::endl; } }
16.399642
57
0.550432
[ "object" ]
a3ef6f52366321cebe22d8d821e880fa391e751b
2,709
hpp
C++
liblava/core/types.hpp
torss/liblava
1e7dc2a9e645107e1fa842182986f6307d79c4b1
[ "MIT" ]
null
null
null
liblava/core/types.hpp
torss/liblava
1e7dc2a9e645107e1fa842182986f6307d79c4b1
[ "MIT" ]
null
null
null
liblava/core/types.hpp
torss/liblava
1e7dc2a9e645107e1fa842182986f6307d79c4b1
[ "MIT" ]
null
null
null
// file : liblava/core/types.hpp // copyright : Copyright (c) 2018-present, Lava Block OÜ // license : MIT; see accompanying LICENSE file #pragma once #include <liblava/def.hpp> #include <cassert> #include <cstdint> #include <string> #include <string_view> #include <vector> #include <map> #include <functional> namespace lava { using int8 = std::int8_t; using i8 = int8; using uint8 = std::uint8_t; using ui8 = uint8; using int16 = std::int16_t; using i16 = int16; using uint16 = std::uint16_t; using ui16 = uint16; using int32 = std::int32_t; using i32 = int32; using uint32 = std::uint32_t; using ui32 = uint32; using int64 = std::int64_t; using i64 = int64; using uint64 = std::uint64_t; using ui64 = uint64; using char8 = std::int_fast8_t; using c8 = char8; using uchar8 = std::uint_fast8_t; using uc8 = uchar8; using char16 = int16; using c16 = char16; using uchar16 = uint16; using uc16 = uchar16; using char32 = int32; using c32 = char32; using uchar32 = uint32; using uc32 = uchar32; using size_t = std::size_t; using uchar = unsigned char; using r32 = float; using r64 = double; using real = r64; using delta = r32; using type = ui32; constexpr type const no_type = 0xffffffff; constexpr type const undef = 0; using index = type; constexpr index const no_index = no_type; using index_list = std::vector<index>; using index_map = std::map<index, index>; using string = std::string; using string_ref = string const&; using string_list = std::vector<string>; using string_view = std::string_view; using name = char const*; using names = std::vector<name>; using names_ref = names const&; constexpr name _lava_ = "lava"; constexpr name _liblava_ = "liblava"; inline name str(string_ref value) { return value.c_str(); } template <typename T> inline r32 to_r32(T value) { return static_cast<r32>(value); } template <typename T> inline r64 to_r64(T value) { return static_cast<r64>(value); } template <typename T> inline i32 to_i32(T value) { return static_cast<i32>(value); } template <typename T> inline i64 to_i64(T value) { return static_cast<i64>(value); } template <typename T> inline ui32 to_ui32(T value) { return static_cast<ui32>(value); } template <typename T> inline ui64 to_ui64(T value) { return static_cast<ui64>(value); } template <typename T> inline size_t to_size_t(T value) { return static_cast<size_t>(value); } template <typename T> inline index to_index(T value) { return static_cast<index>(value); } struct no_copy_no_move { no_copy_no_move() = default; no_copy_no_move(no_copy_no_move const&) = delete; void operator=(no_copy_no_move const&) = delete; }; struct interface { virtual ~interface() = default; }; } // lava
20.838462
71
0.719085
[ "vector" ]
a3fb9d78c7ccb6a8844b196a90fe403f4a437bf0
7,616
cpp
C++
lemon-based-parser/lemon-9-final/AST.cpp
PS-Group/compiler-theory-samples
c916af50eb42020024257ecd17f9be1580db7bf0
[ "MIT" ]
null
null
null
lemon-based-parser/lemon-9-final/AST.cpp
PS-Group/compiler-theory-samples
c916af50eb42020024257ecd17f9be1580db7bf0
[ "MIT" ]
null
null
null
lemon-based-parser/lemon-9-final/AST.cpp
PS-Group/compiler-theory-samples
c916af50eb42020024257ecd17f9be1580db7bf0
[ "MIT" ]
null
null
null
#include "AST.h" #include "VariablesScope.h" #include "InterpreterContext.h" #include <limits> #include <algorithm> #include <iostream> #include <cmath> #include <cassert> namespace { void ExecuteAll(StatementsList const& list, CInterpreterContext & context) { for (auto const& stmt : list) { stmt->Execute(context); } } class CScopedVariableScope { public: CScopedVariableScope(CInterpreterContext &context) : m_context(context) { m_context.PushScope(std::make_unique<CVariablesScope>()); } ~CScopedVariableScope() { m_context.PopScope(); } private: CInterpreterContext &m_context; }; class CVariableScopeCleaner { public: CVariableScopeCleaner(CInterpreterContext &context) : m_context(context) { // Убираем все области видимости, кроме верхней. while (m_context.GetScopesCount() > 1) { m_scopes.emplace_back(m_context.PopScope()); } } ~CVariableScopeCleaner() { for (std::unique_ptr<CVariablesScope> &pScope : m_scopes) { m_context.PushScope(std::unique_ptr<CVariablesScope>(pScope.release())); } } private: CInterpreterContext &m_context; std::vector<std::unique_ptr<CVariablesScope>> m_scopes; }; } CPrintAst::CPrintAst(ExpressionList &&expressions) : m_expressions(std::move(expressions)) { } void CPrintAst::Execute(CInterpreterContext &context)const { std::vector<CValue> values; for (const auto &pExpr : m_expressions) { values.push_back(pExpr->Evaluate(context)); } context.PrintResults(values); } CAssignAst::CAssignAst(unsigned nameId, IExpressionAstUniquePtr &&value) : m_nameId(nameId) , m_value(std::move(value)) { } void CAssignAst::Execute(CInterpreterContext &context)const { const CValue value = m_value->Evaluate(context); context.AssignVariable(m_nameId, value); } CBinaryExpressionAst::CBinaryExpressionAst(IExpressionAstUniquePtr &&left, BinaryOperation op, IExpressionAstUniquePtr &&right) : m_left(std::move(left)) , m_operation(op) , m_right(std::move(right)) { } CValue CBinaryExpressionAst::Evaluate(CInterpreterContext &context) const { const CValue a = m_left->Evaluate(context); const CValue b = m_right->Evaluate(context); switch (m_operation) { case BinaryOperation::Less: return a < b; case BinaryOperation::Equals: return a == b; case BinaryOperation::And: return a && b; case BinaryOperation::Or: return a || b; case BinaryOperation::Add: return a + b; case BinaryOperation::Substract: return a - b; case BinaryOperation::Multiply: return a * b; case BinaryOperation::Divide: return a / b; case BinaryOperation::Modulo: return a % b; } return CValue::FromErrorMessage("binary operation not implemented"); } CUnaryExpressionAst::CUnaryExpressionAst(UnaryOperation op, IExpressionAstUniquePtr &&value) : m_operation(op) , m_expr(std::move(value)) { } CValue CUnaryExpressionAst::Evaluate(CInterpreterContext &context) const { const CValue value = m_expr->Evaluate(context); switch (m_operation) { case UnaryOperation::Plus: return +value; case UnaryOperation::Minus: return -value; case UnaryOperation::Not: return !value; } return CValue::FromErrorMessage("unary operation not implemented"); } CLiteralAst::CLiteralAst(CValue value) : m_value(value) { } CValue CLiteralAst::Evaluate(CInterpreterContext &context) const { (void)context; return m_value; } CVariableRefAst::CVariableRefAst(unsigned nameId) : m_nameId(nameId) { } CValue CVariableRefAst::Evaluate(CInterpreterContext &context) const { return context.GetVariableValue(m_nameId); } CIfAst::CIfAst(IExpressionAstUniquePtr &&condition, StatementsList &&thenBody, StatementsList &&elseBody) : m_condition(std::move(condition)) , m_thenBody(std::move(thenBody)) , m_elseBody(std::move(elseBody)) { } void CIfAst::Execute(CInterpreterContext &context) const { CValue result = m_condition->Evaluate(context); if (bool(result)) { ExecuteAll(m_thenBody, context); } else { ExecuteAll(m_elseBody, context); } } CProgramAst::CProgramAst(CInterpreterContext &context) : m_context(context) { m_context.PushScope(std::make_unique<CVariablesScope>()); } CProgramAst::~CProgramAst() { m_context.PopScope(); } void CProgramAst::AddStatement(IStatementAstUniquePtr &&stmt) { stmt->Execute(m_context); } void CProgramAst::AddFunction(IFunctionAstUniquePtr &&function) { unsigned nameId = function->GetNameId(); m_context.AddFunction(nameId, function.get()); m_functions.emplace_back(std::move(function)); } CWhileAst::CWhileAst(IExpressionAstUniquePtr &&condition, StatementsList &&body) : m_condition(std::move(condition)) , m_body(std::move(body)) { } void CWhileAst::Execute(CInterpreterContext &context) const { while (bool(m_condition->Evaluate(context))) { ExecuteAll(m_body, context); } } CRepeatAst::CRepeatAst(IExpressionAstUniquePtr &&condition, StatementsList &&body) : m_condition(std::move(condition)) , m_body(std::move(body)) { } void CRepeatAst::Execute(CInterpreterContext &context) const { do { ExecuteAll(m_body, context); } while (bool(m_condition->Evaluate(context))); } CCallAst::CCallAst(unsigned nameId, ExpressionList && arguments) : m_nameId(nameId) , m_arguments(std::move(arguments)) { } CValue CCallAst::Evaluate(CInterpreterContext &context) const { if (IFunctionAst *func = context.GetFunction(m_nameId)) { std::vector<CValue> args(m_arguments.size()); std::transform(m_arguments.begin(), m_arguments.end(), args.begin(), [&](IExpressionAstUniquePtr const& ast) { return ast->Evaluate(context); }); return func->Call(context, args); } return CValue::FromErrorMessage("Attempt to call unknown function."); } CFunctionAst::CFunctionAst(unsigned nameId, std::vector<unsigned> argumentNames, StatementsList && body) : m_nameId(nameId) , m_argumentNames(argumentNames) , m_body(std::move(body)) { } unsigned CFunctionAst::GetNameId() const { return m_nameId; } CValue CFunctionAst::Call(CInterpreterContext &context, const std::vector<CValue> &arguments) const { if (arguments.size() != m_argumentNames.size()) { return CValue::FromErrorMessage("arguments and parameters count mismatch"); } CVariableScopeCleaner cleaner(context); CScopedVariableScope scopedScope(context); auto argumentIt = arguments.begin(); for (unsigned nameId : m_argumentNames) { context.DefineVariable(nameId, *argumentIt); ++argumentIt; } boost::optional<CValue> returnedValue; for (IStatementAstUniquePtr const& stmt : m_body) { stmt->Execute(context); returnedValue = context.GetReturnValue(); if (returnedValue) { context.SetReturnValue(boost::none); break; } } if (returnedValue.is_initialized()) { return *returnedValue; } return CValue::FromErrorMessage("Function returned no value"); } CReturnAst::CReturnAst(IExpressionAstUniquePtr &&value) : m_value(std::move(value)) { } void CReturnAst::Execute(CInterpreterContext &context) const { CValue result = m_value->Evaluate(context); context.SetReturnValue(result); }
23.725857
127
0.683036
[ "vector", "transform" ]
a3fbe83d2e431fb8ccc86228ee25d7fdb046c242
6,329
cpp
C++
src/Gui/Widgets/CustomFrames.cpp
heroesiiifan/FreeHeroes
d9b396b527918cdf863fd2310bcf261e213bf553
[ "MIT" ]
17
2020-08-13T03:23:27.000Z
2022-02-04T00:17:53.000Z
src/Gui/Widgets/CustomFrames.cpp
heroesiiifan/FreeHeroes
d9b396b527918cdf863fd2310bcf261e213bf553
[ "MIT" ]
2
2021-09-05T21:00:31.000Z
2021-09-12T07:46:53.000Z
src/Gui/Widgets/CustomFrames.cpp
heroesiiifan/FreeHeroes
d9b396b527918cdf863fd2310bcf261e213bf553
[ "MIT" ]
2
2021-09-08T10:37:34.000Z
2021-09-09T00:35:44.000Z
/* * Copyright (C) 2020 Smirnov Vladimir / mapron1@gmail.com * SPDX-License-Identifier: MIT * See LICENSE file for details. */ #include "CustomFrames.hpp" #include <QStyleOption> #include <QStylePainter> #include <QAbstractItemView> #include <QEvent> #include <QPainter> #include <QTreeView> #include <QHeaderView> namespace FreeHeroes::Gui { FlatButton::FlatButton(QWidget* parent) : QPushButton(parent) { setFlat(true); m_focusActiveColor = QColor("#E8D478"); } void FlatButton::enableHoverTracking(bool state) { m_hoverEnabled = state; } void FlatButton::setFocusActiveColor(QColor color) { m_focusActiveColor = color; update(); } void FlatButton::setBorderWidth(int borderWidth, bool adjustSize) { m_borderWidth = borderWidth; if (adjustSize) { int b = borderWidth - m_borderWidth; this->setFixedSize(this->size().width() + b * 2, this->size().height() + b * 2); } update(); } void FlatButton::setAdditionalCheckedHighlight(bool state) { m_additionalCheckedHighlight = state; } void FlatButton::paintEvent(QPaintEvent*) { QIcon icn = this->icon(); QPixmap pix; // normal, pressed, disabled, hovered. // normal = QIcon::Off + QIcon::Normal // pressed = QIcon::On + QIcon::Normal // disabled = QIcon::Off + QIcon::Disabled // hovered = QIcon::Off + QIcon::Selected QRect boundingRect = this->rect(); QRect pixmapRect = boundingRect.adjusted(m_borderWidth, m_borderWidth, -m_borderWidth, -m_borderWidth); bool isPressed = m_isPressed || (this->isCheckable() && this->isChecked()); if (!this->isEnabled()) { pix = icn.pixmap(pixmapRect.size(), QIcon::Disabled, QIcon::Off); } else if (isPressed) { pix = icn.pixmap(pixmapRect.size(), QIcon::Normal, QIcon::On); } else if (m_isHovered) { //pix = icn.pixmap(iconSize(), QIcon::Selected, QIcon::Off); pix = icn.pixmap(pixmapRect.size(), QIcon::Normal, QIcon::Off); } else { pix = icn.pixmap(pixmapRect.size(), QIcon::Normal, QIcon::Off); } QPainter p(this); p.drawPixmap(pixmapRect.x(), pixmapRect.y(), pix); if (isEnabled() && !isChecked() && m_additionalCheckedHighlight) { p.setPen(Qt::NoPen); p.setBrush(QBrush(QColor(0, 0, 0, 30))); p.drawRect(pixmapRect.adjusted(0, 0, -1, -1)); } if (isEnabled() && ((m_isHovered && !m_isPressed) || (isChecked() && m_additionalCheckedHighlight))) { QRect rDraw = pixmapRect.adjusted(0, 0, -1, -1); const qreal boxWidth = rDraw.width(); const qreal boxHeight = rDraw.height(); qreal thick = 4; QList<QPointF> startPoints{ QPointF{ 0, 0 }, QPointF{ 0, 0 }, QPointF{ boxWidth, boxHeight }, QPointF{ boxWidth, boxHeight } }; QList<QPointF> endPoints{ QPointF{ 0, thick }, QPointF{ thick, 0 }, QPointF{ boxWidth - thick, boxHeight }, QPointF{ boxWidth, boxHeight - thick } }; for (int i = 0; i < 4; i++) { QLinearGradient grad(startPoints[i], endPoints[i]); grad.setColorAt(0, QColor(255, 255, 255, 50)); grad.setColorAt(1, QColor(255, 255, 255, 0)); p.setPen(Qt::NoPen); p.setBrush(QBrush(grad)); p.drawRect(rDraw); } } if (m_borderWidth && this->hasFocus()) { p.setPen(QPen(m_focusActiveColor, m_borderWidth)); p.setBrush(Qt::NoBrush); p.drawRect(boundingRect.adjusted(0, 0, -1, -1)); } } void FlatButton::mousePressEvent(QMouseEvent* ev) { m_isPressed = true; repaint(); QPushButton::mousePressEvent(ev); } void FlatButton::mouseReleaseEvent(QMouseEvent* ev) { QPushButton::mouseReleaseEvent(ev); m_isPressed = false; update(); } void FlatButton::mouseDoubleClickEvent(QMouseEvent* ev) { QPushButton::mouseDoubleClickEvent(ev); emit doubleClicked(); } bool FlatButton::event(QEvent* ev) { auto res = QPushButton::event(ev); if (m_hoverEnabled) { if (ev->type() == QEvent::Enter) m_isHovered = true; else if (ev->type() == QEvent::Leave) m_isHovered = false; else return res; update(); } else { m_isHovered = false; } return res; } ResizeableComboBox::ResizeableComboBox(QWidget* parent) : QComboBox(parent) { this->setMinimumContentsLength(20); this->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon); } void ResizeableComboBox::showPopup() { this->view()->setMinimumWidth(calculateMaxModelWidth() + this->iconSize().width() + 20); QComboBox::showPopup(); } int ResizeableComboBox::calculateMaxModelWidth() const { auto srcModel = this->model(); Q_ASSERT(srcModel); int rc = srcModel->rowCount(); int maxWidth = 0; QFontMetrics fm = this->fontMetrics(); for (int i = 0; i < rc; ++i) { const QString text = srcModel->data(srcModel->index(i, 0)).toString(); maxWidth = std::max(maxWidth, fm.horizontalAdvance(text)); } return maxWidth; } TreeComboBox::TreeComboBox(QWidget* parent) : ResizeableComboBox(parent) { m_view = new QTreeView(parent); m_view->setFrameShape(QFrame::NoFrame); m_view->setEditTriggers(QTreeView::NoEditTriggers); m_view->setAlternatingRowColors(false); m_view->setSelectionBehavior(QTreeView::SelectRows); m_view->setRootIsDecorated(false); m_view->setAllColumnsShowFocus(false); m_view->setItemsExpandable(false); setView(m_view); m_view->header()->setVisible(false); } void TreeComboBox::expandAll() { m_view->expandAll(); } void TreeComboBox::selectIndex(const QModelIndex& index) { setRootModelIndex(index.parent()); setCurrentIndex(index.row()); m_view->setCurrentIndex(index); } void TreeComboBox::showPopup() { setRootModelIndex(QModelIndex()); // @todo: calculateMaxModelWidth not accurate here, it does not walk recursive. this->view()->setMinimumWidth(calculateMaxModelWidth() + this->iconSize().width() * 2 + 50); QComboBox::showPopup(); } void TreeComboBox::hidePopup() { setRootModelIndex(m_view->currentIndex().parent()); setCurrentIndex(m_view->currentIndex().row()); ResizeableComboBox::hidePopup(); } }
29.853774
157
0.644178
[ "model" ]
4305d6bc4af5bf4704c76052f232d7a696fa894c
19,029
hxx
C++
include/opengm/inference/trws/trws_reparametrization.hxx
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
318
2015-01-07T15:22:02.000Z
2022-01-22T10:10:29.000Z
include/opengm/inference/trws/trws_reparametrization.hxx
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
89
2015-03-24T14:33:01.000Z
2020-07-10T13:59:13.000Z
include/opengm/inference/trws/trws_reparametrization.hxx
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
119
2015-01-13T08:35:03.000Z
2022-03-01T01:49:08.000Z
#ifndef REPARAMETRIZATION_HXX #define REPARAMETRIZATION_HXX #include <valarray> #include <iostream> #include <map> #include <opengm/inference/trws/trws_subproblemsolver.hxx> #include <opengm/inference/inference.hxx> #include <opengm/inference/trws/trws_base.hxx> #include <opengm/inference/trws/utilities2.hxx> #include <opengm/inference/auxiliary/lp_reparametrization.hxx> namespace opengm { namespace trws_base{ /* * Trivialization solver computes dual variables, which trivialize the input problem, making local decision globally consistent */ template<class GM,class ACC,class InputIterator> class TrivializationSolver : protected MaxSumSolver<GM,ACC,InputIterator> { public: typedef MaxSumSolver<GM,ACC,InputIterator> parent; typedef typename parent::ValueType ValueType; typedef typename parent::IndexType IndexType; typedef typename parent::LabelType LabelType; typedef typename parent::InputIteratorType InputIteratorType; typedef typename parent::Storage Storage; typedef opengm::LPReparametrisationStorage<GM> DualStorage; typedef typename parent::MoveDirection MoveDirection; typedef typename parent::UnaryFactor UnaryFactor; typedef typename UnaryFactor::const_iterator const_uIterator; typedef typename parent::FactorProperties FactorProperties; typedef typename std::vector<bool> MaskType; typedef typename std::vector<MaskType> ImmovableLabelingType; TrivializationSolver(Storage& primalstorage, DualStorage& dualstorage, const FactorProperties& fp, bool fastComputations=true) :parent(primalstorage,fp,fastComputations), _dualstorage(dualstorage){}; void ForwardMove(MoveDirection direction=Storage::Direct){parent::InitMove(direction); parent::Move();}; void BackwardMove(const MaskType* pmask=0); //void BackwardMove(const ImmovableLabelingType& immovableLabels); ValueType GetObjectiveValue()const{return parent::GetObjectiveValue();} private: void _PushBack(); //void _PushBack(const MaskType& mask); IndexType _distanceFromStart(); void _InitBackwardMoveBuffer(IndexType index); void _setDuals(IndexType index,typename SequenceStorage<GM>::MoveDirection moveDir,const_uIterator it); DualStorage& _dualstorage; MaskType _mask; IndexType _numberOfBoundaryTerms; // computation optimization //std::vector<ValueType> _multipliers; }; //=======================TrivializationSolver implementation =========================================== template<class GM,class ACC,class InputIterator> typename TrivializationSolver<GM,ACC,InputIterator>::IndexType TrivializationSolver<GM,ACC,InputIterator>::_distanceFromStart() { if (parent::_moveDirection==Storage::Direct) return parent::_currentUnaryIndex; else return parent::size()-1-parent::_currentUnaryIndex; } template<class GM,class ACC,class InputIterator> void TrivializationSolver<GM,ACC,InputIterator>::_InitBackwardMoveBuffer(IndexType index) { assert(index < parent::_storage.size()); parent::_currentUnaryIndex=index; parent::_currentUnaryFactor.resize(parent::_storage.unaryFactors(parent::_currentUnaryIndex).size()); std::copy(parent::_marginals[parent::_currentUnaryIndex]. begin(),parent::_marginals[parent::_currentUnaryIndex].end(),parent::_currentUnaryFactor.begin()); _numberOfBoundaryTerms=std::count(_mask.begin(),_mask.end(),true); } template<class GM,class ACC,class InputIterator> void TrivializationSolver<GM,ACC,InputIterator>::_PushBack() { OPENGM_ASSERT(_mask.size()==parent::size()); ValueType multiplier; if (_mask[parent::_currentUnaryIndex]) { multiplier=((ValueType)_numberOfBoundaryTerms-1.0)/_numberOfBoundaryTerms; --_numberOfBoundaryTerms; } else { multiplier=1.0; } transform_inplace(parent::_currentUnaryFactor.begin(), parent::_currentUnaryFactor.end(), std::bind2nd(std::multiplies<ValueType>(),multiplier)); std::transform(parent::_currentUnaryFactor.begin(), parent::_currentUnaryFactor.end(), parent::_marginals[parent::_currentUnaryIndex].begin(), parent::_currentUnaryFactor.begin(), std::minus<ValueType>()); std::transform(parent::_currentUnaryFactor.begin(),parent::_currentUnaryFactor.end(), parent::_storage.unaryFactors(parent::_currentUnaryIndex).begin(), parent::_currentUnaryFactor.begin(),std::plus<ValueType>()); _setDuals(parent::_currentUnaryIndex,parent::_moveDirection,parent::_currentUnaryFactor.begin()); parent::_PushMessagesToFactor(); parent::_currentUnaryIndex=parent::_next(parent::_currentUnaryIndex);//instead of _InitCurrentUnaryBuffer(_next(_currentUnaryIndex)); parent::_currentUnaryFactor.assign(parent::_storage.unaryFactors(parent::_currentUnaryIndex).size(),0.0); parent::_ClearMessages(); transform_inplace(parent::_currentUnaryFactor.begin(), parent::_currentUnaryFactor.end(), std::bind2nd(std::multiplies<ValueType>(),-1.0)); _setDuals(parent::_currentUnaryIndex,Storage::ReverseDirection(parent::_moveDirection), parent::_currentUnaryFactor.begin()); std::transform(parent::_marginals[parent::_currentUnaryIndex].begin(), parent::_marginals[parent::_currentUnaryIndex].end(), parent::_currentUnaryFactor.begin(),parent::_currentUnaryFactor.begin(), std::minus<ValueType>()); } //template<class GM,class ACC,class InputIterator> //void TrivializationSolver<GM,ACC,InputIterator>::_PushBack(const MaskType& mask) //{ // OPENGM_ASSERT(mask.size()==parent::_currentUnaryFactor.size()); // _multipliers.resize(parent::_currentUnaryFactor.size()); // bool decrease=false; // // //std::cout << "_numberOfBoundaryTerms="<<_numberOfBoundaryTerms<<std::endl; // // for (IndexType label=0;label<_multipliers.size();++label) // { // if (mask[label]) _multipliers[label]=1.0; // else // { // _multipliers[label]=((ValueType)_numberOfBoundaryTerms-1.0)/_numberOfBoundaryTerms; // decrease=true; // } // } // // if (decrease) // { // --_numberOfBoundaryTerms; // decrease=false; // } // // //std::cout << "_multipliers:" <<_multipliers<<std::endl; // // transform(parent::_currentUnaryFactor.begin(), // parent::_currentUnaryFactor.end(), // _multipliers.begin(),parent::_currentUnaryFactor.begin(), // std::multiplies<ValueType>()); // // std::transform(parent::_currentUnaryFactor.begin(), // parent::_currentUnaryFactor.end(), // parent::_marginals[parent::_currentUnaryIndex].begin(), // parent::_currentUnaryFactor.begin(), // std::minus<ValueType>()); // std::transform(parent::_currentUnaryFactor.begin(),parent::_currentUnaryFactor.end(), // parent::_storage.unaryFactors(parent::_currentUnaryIndex).begin(), // parent::_currentUnaryFactor.begin(),std::plus<ValueType>()); // // _setDuals(parent::_currentUnaryIndex,parent::_moveDirection,parent::_currentUnaryFactor.begin()); // // parent::_PushMessagesToFactor(); // parent::_currentUnaryIndex=parent::_next(parent::_currentUnaryIndex);//instead of _InitCurrentUnaryBuffer(_next(_currentUnaryIndex)); // parent::_currentUnaryFactor.assign(parent::_storage.unaryFactors(parent::_currentUnaryIndex).size(),0.0); // parent::_ClearMessages(); // // transform_inplace(parent::_currentUnaryFactor.begin(), // parent::_currentUnaryFactor.end(), // std::bind2nd(std::multiplies<ValueType>(),-1.0)); // _setDuals(parent::_currentUnaryIndex,Storage::ReverseDirection(parent::_moveDirection), // parent::_currentUnaryFactor.begin()); // // std::transform(parent::_marginals[parent::_currentUnaryIndex].begin(), // parent::_marginals[parent::_currentUnaryIndex].end(), // parent::_currentUnaryFactor.begin(),parent::_currentUnaryFactor.begin(), // std::minus<ValueType>()); //} template<class GM,class ACC,class InputIterator> void TrivializationSolver<GM,ACC,InputIterator>::BackwardMove(const MaskType* pmask) { if (pmask==0) _mask.assign(parent::size(),true); else _mask=*pmask; parent::_moveDirection=Storage::ReverseDirection(parent::_moveDirection); if (parent::_moveDirection==Storage::Direct) _InitBackwardMoveBuffer(0); else _InitBackwardMoveBuffer(parent::size()-1); for (IndexType i=0;i<parent::size()-1;++i)//!> number of iterations is equal to a number of pairwise factors _PushBack(); //_Push(size()-i) - the current value of i is known, as _currentIndex parent::_bInitializationNeeded=true; } //template<class GM,class ACC,class InputIterator> //void TrivializationSolver<GM,ACC,InputIterator>::BackwardMove(const ImmovableLabelingType& immovableLabels) //{ // _mask.assign(parent::size(),true); // parent::_moveDirection=Storage::ReverseDirection(parent::_moveDirection); // // if (parent::_moveDirection==Storage::Direct) // { // //std::cout << "Direct"<<std::endl; // _InitBackwardMoveBuffer(0); // } // else // { // //std::cout << "Reverse"<<std::endl; // _InitBackwardMoveBuffer(parent::size()-1); // } // // //for (IndexType i=0;i<parent::size()-1;++i)//!> number of iterations is equal to a number of pairwise factors // for (IndexType i=0;i<parent::size()-1;++i)//!> number of iterations is equal to a number of pairwise factors // _PushBack(immovableLabels[parent::_currentUnaryIndex]); //_Push(size()-i) - the current value of i is known, as _currentIndex // // parent::_bInitializationNeeded=true; //} template<class GM,class ACC,class InputIterator> void TrivializationSolver<GM,ACC,InputIterator> ::_setDuals(IndexType index,typename SequenceStorage<GM>::MoveDirection movedir,const_uIterator it) { IndexType pwId, varId; if (movedir==Storage::Direct) { pwId=parent::_storage.pwForwardFactor(index); varId=(parent::_storage.pwDirection(index)==Storage::Direct ? 0 : 1); } else { pwId=parent::_storage.pwForwardFactor(index-1); varId=(parent::_storage.pwDirection(index-1)==Storage::Direct ? 1 : 0); } std::pair<typename DualStorage::uIterator,typename DualStorage::uIterator> dualIt =_dualstorage.getIterators(pwId,varId); std::copy(it,it+(dualIt.second-dualIt.first),dualIt.first); }; }//namespace trws_base template<class ValueType> struct TRWS_Reparametrizer_Parameters { bool fastComputations_; TRWS_Reparametrizer_Parameters(bool fastComputations=true): fastComputations_(fastComputations) {}; }; template<class Storage,class ACC> class TRWS_Reparametrizer : public opengm::LPReparametrizer<typename Storage::GraphicalModelType, ACC> { public: typedef typename opengm::LPReparametrizer<typename Storage::GraphicalModelType, ACC> parent; typedef typename parent::GraphicalModelType GraphicalModelType; typedef typename GraphicalModelType::ValueType ValueType; typedef typename GraphicalModelType::IndexType IndexType; typedef typename GraphicalModelType::LabelType LabelType; typedef typename parent::RepaStorageType RepaStorageType; typedef typename parent::MaskType MaskType; typedef typename parent::ImmovableLabelingType ImmovableLabelingType; typedef typename parent::ReparametrizedGMType ReparametrizedGMType; typedef trws_base::TrivializationSolver<GraphicalModelType,ACC,typename std::vector<typename GraphicalModelType::ValueType>::const_iterator> SubSolverType; typedef TRWS_Reparametrizer_Parameters<ValueType> Parameter; typedef trws_base::FunctionParameters<GraphicalModelType> FunctionParametersType; TRWS_Reparametrizer(Storage& storage,const FunctionParametersType& fparams,const Parameter& params=Parameter()); virtual ~TRWS_Reparametrizer(); void reparametrize(const MaskType* pmask=0); void reparametrize(const ImmovableLabelingType& immovableLabeling); private: Storage& _storage; std::vector<SubSolverType*> _subSolvers; }; template<class Storage,class ACC> TRWS_Reparametrizer<Storage,ACC>::~TRWS_Reparametrizer() { std::for_each(_subSolvers.begin(),_subSolvers.end(),trws_base::DeallocatePointer<SubSolverType>); } template<class Storage,class ACC> TRWS_Reparametrizer<Storage,ACC>::TRWS_Reparametrizer(Storage& storage, const FunctionParametersType& fparams, const Parameter& params): parent(storage.masterModel()), _storage(storage) { _subSolvers.resize(_storage.numberOfModels()); for (size_t modelId=0;modelId<_subSolvers.size();++modelId) { _subSolvers[modelId]= new SubSolverType(_storage.subModel(modelId),parent::Reparametrization(),fparams,params.fastComputations_); } } template<class Storage,class ACC> void TRWS_Reparametrizer<Storage,ACC>::reparametrize(const MaskType* pmask) { MaskType mask(pmask!=0 ? *pmask : MaskType(_storage.masterModel().numberOfVariables(),true)); OPENGM_ASSERT(mask.size()==_storage.masterModel().numberOfVariables()); ValueType bound=0; MaskType sequenceMask; for (size_t i=0;i<_subSolvers.size();++i) { typename Storage::SubModel& model=_storage.subModel(i); sequenceMask.resize(model.size()); for (IndexType localInd=0; localInd<sequenceMask.size();++localInd) { OPENGM_ASSERT(model.varIndex(localInd) < mask.size()); sequenceMask[localInd]=mask[model.varIndex(localInd)]; } _subSolvers[i]->ForwardMove(); _subSolvers[i]->BackwardMove(&sequenceMask); bound+=_subSolvers[i]->GetObjectiveValue(); } } //template<class Storage,class ACC> //void TRWS_Reparametrizer<Storage,ACC>::reparametrize(const ImmovableLabelingType& immovableLabeling) //{ // // //MaskType mask(pmask!=0 ? *pmask : MaskType(_storage.masterModel().numberOfVariables(),true)); // OPENGM_ASSERT(immovableLabeling.size()==_storage.masterModel().numberOfVariables()); // ValueType bound=0; // ImmovableLabelingType sequenceLabeling; // for (size_t i=0;i<_subSolvers.size();++i) // { // typename Storage::SubModel& model=_storage.subModel(i); // sequenceLabeling.resize(model.size()); // for (IndexType localInd=0; localInd<sequenceLabeling.size();++localInd) // { // OPENGM_ASSERT(model.varIndex(localInd) < immovableLabeling.size()); // sequenceLabeling[localInd]=immovableLabeling[model.varIndex(localInd)]; // } // // //std::cout << "ForwardMove: "; // _subSolvers[i]->ForwardMove(); // //std::cout << "BackwardMove: "; // _subSolvers[i]->BackwardMove(sequenceLabeling); // bound+=_subSolvers[i]->GetObjectiveValue(); // } // //} template<class Storage,class ACC> void TRWS_Reparametrizer<Storage,ACC>::reparametrize(const ImmovableLabelingType& immovableLabeling) { OPENGM_ASSERT(immovableLabeling.size()==_storage.masterModel().numberOfVariables()); reparametrize(); typedef typename parent::RepaStorageType::uIterator uIterator; const typename Storage::GraphicalModelType& gm=_storage.masterModel(); for (IndexType factorID=0;factorID < gm.numberOfFactors();++factorID) { if (gm[factorID].numberOfVariables()<2) continue; /* * Make zero potentials for immovable labels */ for (IndexType localVarID=0;localVarID<gm[factorID].numberOfVariables();++localVarID) { std::pair<uIterator,uIterator> it=parent::Reparametrization().getIterators(factorID,localVarID); IndexType globalVarID=gm[factorID].variableIndex(localVarID); typename MaskType::const_iterator labIt=immovableLabeling[globalVarID].begin(); for (;it.first!=it.second;++it.first) if (*labIt++) *it.first=0; } /* * Make reparametrized pairwise factors non-negative */ if (gm[factorID].numberOfVariables()!=2) throw std::runtime_error("TRWS_Reparametrizer<Storage,ACC>::reparametrize(): factors of order higher than 2 are not supported!"); std::vector<IndexType> labeling(2); for (IndexType localVarID=0;localVarID<gm[factorID].numberOfVariables();++localVarID) { std::pair<uIterator,uIterator> it=parent::Reparametrization().getIterators(factorID,localVarID); uIterator it_begin=it.first; IndexType globalVarID=gm[factorID].variableIndex(localVarID); typename MaskType::const_iterator labIt=immovableLabeling[globalVarID].begin(); ValueType res=ACC::template neutral<ValueType>(); for (;it.first!=it.second;++it.first) if (!(*labIt++)) { IndexType otherVarID=(localVarID==0 ? 1 : 0); labeling[localVarID]=it.first-it_begin; for (LabelType label=0;label<gm.numberOfLabels(otherVarID);++label) { labeling[otherVarID]=label; ValueType res1=parent::Reparametrization().getFactorValue(factorID,labeling.begin()); ACC::op(res,res1,res); } *it.first-=res; } } } } //============ LP reparametrization to TRWS reparametrization =========================== template<class GM> void LPtoDecompositionStorage(const LPReparametrisationStorage<GM>& lpRepa, trws_base::DecompositionStorage<GM>* ptrwsRepa) { OPENGM_ASSERT(&lpRepa.graphicalModel() == &ptrwsRepa->masterModel()); typedef typename LPReparametrisationStorage<GM>::uIterator uIterator; typedef typename GM::ValueType ValueType; typedef typename GM::IndexType IndexType; typedef typename GM::LabelType LabelType; typedef typename trws_base::DecompositionStorage<GM> DecompositionStorage; std::vector<ValueType> repaUnary; //for all variables (and related unary factors) for (IndexType varId=0;varId<lpRepa.graphicalModel().numberOfVariables();++varId)// all variables { const typename DecompositionStorage::SubVariableListType& varList=ptrwsRepa->getSubVariableList(varId); if (varList.size()==1) continue; // compute common part - the sum of all potentials repaUnary.resize(lpRepa.graphicalModel().numberOfLabels(varId)); for (LabelType label=0;label<repaUnary.size();++label) { repaUnary[label]=lpRepa.getVariableValue(varId,label); } trws_base::transform_inplace(repaUnary.begin(),repaUnary.end(),std::bind2nd(std::multiplies<ValueType>(),1.0/varList.size()));//!> repaUnary:=repaUnary/numberTrees //for all submodels for(typename DecompositionStorage::SubVariableListType::const_iterator modelIt=varList.begin(); modelIt!=varList.end();++modelIt) //all related models { typename DecompositionStorage::SubModel& subModel=ptrwsRepa->subModel(modelIt->subModelId_); typename DecompositionStorage::SubModel::UnaryFactor::iterator uit_begin=subModel.ufBegin(modelIt->subVariableId_); typename DecompositionStorage::SubModel::UnaryFactor::iterator uit_end =subModel.ufEnd(modelIt->subVariableId_); //unary=repaUnary/numberTrees std::copy(repaUnary.begin(),repaUnary.end(),uit_begin); //add only potentials belonging to the submodel // std::pair<uIterator,uIterator> repaIt; const typename LPReparametrisationStorage<GM>::UnaryFactor* prepaUF; if (modelIt->subVariableId_ < subModel.size()-1) { IndexType pwId=subModel.pwForwardFactor(modelIt->subVariableId_); if (lpRepa.graphicalModel()[pwId].variableIndex(0)==varId) prepaUF=&lpRepa.get(pwId,0); else prepaUF=&lpRepa.get(pwId,1); std::transform(uit_begin,uit_end,prepaUF->begin(),uit_begin,std::plus<ValueType>()); } if (modelIt->subVariableId_ >0) { IndexType pwId=subModel.pwForwardFactor(modelIt->subVariableId_-1); if (lpRepa.graphicalModel()[pwId].variableIndex(0)==varId) prepaUF=&lpRepa.get(pwId,0); else prepaUF=&lpRepa.get(pwId,1); std::transform(uit_begin,uit_end,prepaUF->begin(),uit_begin,std::plus<ValueType>()); } } } } } //namespace opengm #endif
37.458661
172
0.753166
[ "vector", "model", "transform" ]
43088bc65e0f9f8678da06bf5d6cabb103ea4a1d
53,325
cpp
C++
dev/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.cpp
CJoriginal/cjlumberyard
2e3184a7d8e59ba05e5707371b8cb6fe40b0ca60
[ "AML" ]
2
2020-08-20T03:40:24.000Z
2021-02-07T20:31:43.000Z
dev/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.cpp
CJoriginal/cjlumberyard
2e3184a7d8e59ba05e5707371b8cb6fe40b0ca60
[ "AML" ]
null
null
null
dev/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.cpp
CJoriginal/cjlumberyard
2e3184a7d8e59ba05e5707371b8cb6fe40b0ca60
[ "AML" ]
5
2020-08-27T20:44:18.000Z
2021-08-21T22:54:11.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "StdAfx.h" #include <smartptr.h> #include "Util.h" #include "ZipFileFormat.h" #include "zipdirstructures.h" #include "ZipDirTree.h" #include "ZipDirList.h" #include "ZipDirCache.h" #include "ZipDirCacheRW.h" #include "ZipDirCacheFactory.h" #include "ZipDirFindRW.h" #include "ThreadUtils.h" #include <zlib.h> // declaration of Z_OK for ZipRawDecompress #include <AzCore/std/parallel/mutex.h> #include <AzFramework/IO/LocalFileIO.h> using namespace ZipFile; enum PackFileStatus { PACKFILE_COMPRESSED, PACKFILE_ADDED, PACKFILE_UPTODATE, PACKFILE_SKIPPED, PACKFILE_MISSING, PACKFILE_FAILED }; class PackFilePool; struct PackFileBatch { PackFilePool* pool; int zipMaxSize; int sourceMinSize; int sourceMaxSize; int compressionMethod; int compressionLevel; PackFileBatch() : pool(0) , sourceMinSize(0) , sourceMaxSize(0) , zipMaxSize(0) , compressionMethod(0) , compressionLevel(0) { } }; class PackFilePool; struct PackFileJob { int index; int key; PackFileBatch* batch; const char* relativePathSrc; const char* realFilename; unsigned int existingCRC; void* compressedData; unsigned long compressedSize; unsigned long compressedSizePreviously; void* uncompressedData; unsigned long uncompressedSize; unsigned long uncompressedSizePreviously; __int64 modTime; ZipDir::ErrorEnum zdError; PackFileStatus status; PackFileJob() : index(0) , key(0) , batch(0) , realFilename(0) , relativePathSrc(0) , existingCRC(0) , compressedData(0) , compressedSize(0) , compressedSizePreviously(0) , uncompressedData(0) , uncompressedSize(0) , uncompressedSizePreviously(0) , modTime(0) , zdError(ZipDir::ZD_ERROR_NOT_IMPLEMENTED) , status(PACKFILE_FAILED) { } void DetachUncompressedData() { if (uncompressedData && uncompressedData == compressedData) { compressedData = 0; compressedSize = 0; } uncompressedData = 0; uncompressedSize = 0; } ~PackFileJob() { if (compressedData && compressedData != uncompressedData) { free(compressedData); compressedData = 0; } if (uncompressedData) { free(uncompressedData); uncompressedData = 0; } } }; // --------------------------------------------------------------------------- static void PackFileFromDisc(PackFileJob* job); class PackFilePool { public: PackFilePool(int numFiles, size_t memoryLimit) : m_pool(false) , m_skip(false) , m_awaitedFile(0) , m_memoryLimit(memoryLimit) , m_allocatedMemory(0) { m_files.reserve(numFiles); } ~PackFilePool() { } void Submit(int key, const PackFileJob& job) { PackFileJob* newJob = new PackFileJob(job); // index in queue, and custom key for identification newJob->index = int(m_files.size()); newJob->key = key; m_files.push_back(newJob); } PackFileJob* WaitForFile(int index) { while (true) { { AZStd::lock_guard<AZStd::mutex> lock(m_filesLock); m_awaitedFile = index; if (size_t(index) >= m_files.size()) { return 0; } if (m_files[index]) { return m_files[index]; } } Sleep(0); } assert(0); return 0; } void Start(unsigned numExtraThreads) { if (numExtraThreads == 0) { for (PackFileJob* job : m_files) { PackFileFromDisc(job); } } else { for (size_t i = 0; i < m_files.size(); ++i) { PackFileJob* job = m_files[i]; m_files[i] = 0; m_pool.Submit(&ProcessFile, job); } m_pool.Start(numExtraThreads); } } size_t GetJobCount() const { return m_files.size(); } void SkipPendingFiles() { m_skip = true; } void ReleaseFile(int index) { assert(m_files[index] != 0); if (m_files[index]) { if (m_memoryLimit != 0) { AZStd::lock_guard<AZStd::mutex> lock(m_filesLock); m_allocatedMemory -= m_files[index]->uncompressedSize; m_allocatedMemory -= m_files[index]->compressedSize; } delete m_files[index]; m_files[index] = 0; } } private: // called from non-main thread static void ProcessFile(PackFileJob* job) { PackFilePool* self = job->batch->pool; if (!self->m_skip) { if (self->m_memoryLimit != 0) { while (true) { size_t allocatedMemory = 0; int awaitedFile = 0; { AZStd::lock_guard<AZStd::mutex> lock(self->m_filesLock); allocatedMemory = self->m_allocatedMemory; awaitedFile = self->m_awaitedFile; } if (allocatedMemory > self->m_memoryLimit && job->index > awaitedFile + 1) { Sleep(10); // give time to main thread to write data to file } else { break; } } } PackFileFromDisc(job); } self->FileCompleted(job); } // called from non-main thread void FileCompleted(PackFileJob* job) { AZStd::lock_guard<AZStd::mutex> lock(m_filesLock); assert(job); assert(job->index < m_files.size()); assert(m_files[job->index] == 0); m_files[job->index] = job; if (m_memoryLimit != 0) { m_allocatedMemory += job->uncompressedSize; m_allocatedMemory += job->compressedSize; } } size_t m_memoryLimit; AZStd::mutex m_filesLock; std::vector<PackFileJob*> m_files; int m_awaitedFile; size_t m_allocatedMemory; bool m_skip; ThreadUtils::SimpleThreadPool m_pool; }; ////////////////////////////////////////////////////////////////////////// static size_t AlignTo(size_t offset, size_t alignment) { const size_t remainder = offset % alignment; return remainder ? offset + alignment - remainder : offset; } ////////////////////////////////////////////////////////////////////////// // Calculates new offset of the header to make sure that following data are // aligned properly static size_t CalculateAlignedHeaderOffset(const char* fileName, size_t currentOffset, size_t alignment) { // Since file should start from header if (currentOffset == 0) { return 0; } // Local header is followed by filename const size_t totalHeaderSize = sizeof(LocalFileHeader) + strlen(fileName); // Align end of the header const size_t dataOffset = AlignTo(currentOffset + totalHeaderSize, alignment); return dataOffset - totalHeaderSize; } ////////////////////////////////////////////////////////////////////////// ZipDir::CacheRW::CacheRW(bool encryptHeaders, const EncryptionKey& encryptionKey) : m_pFile (NULL) , m_nFlags (0) , m_lCDROffset (0) , m_fileAlignment (1) , m_bEncryptedHeaders(encryptHeaders) , m_bHeadersEncryptedOnClose(encryptHeaders) , m_encryptionKey(encryptionKey) { m_nRefCount = 0; } ////////////////////////////////////////////////////////////////////////// ZipDir::CacheRW::~CacheRW() { Close(); } ////////////////////////////////////////////////////////////////////////// void ZipDir::CacheRW::AddRef() { ++m_nRefCount; } ////////////////////////////////////////////////////////////////////////// void ZipDir::CacheRW::Release() { if (--m_nRefCount <= 0) { delete this; } } void ZipDir::CacheRW::Close() { if (m_pFile) { if (!(m_nFlags & FLAGS_READ_ONLY)) { if ((m_nFlags & FLAGS_UNCOMPACTED) && !(m_nFlags & FLAGS_DONT_COMPACT)) { if (!RelinkZip()) { WriteCDR(); } } else if (m_nFlags & FLAGS_CDR_DIRTY) { WriteCDR(); } } if (m_pFile) // RelinkZip() might have closed the file { fclose (m_pFile); } m_pFile = NULL; } m_treeDir.Clear(); } ////////////////////////////////////////////////////////////////////////// char* ZipDir::CacheRW::UnifyPath(char* const str, const char* pPath) { assert(str); const char* src = pPath; char* trg = str; while (*src) { if (*src != '/') { *trg++ = ::tolower(*src++); } else { *trg++ = '\\'; src++; } } *trg = 0; return str; } ////////////////////////////////////////////////////////////////////////// char* ZipDir::CacheRW::ToUnixPath(char* const str, const char* pPath) { assert(str); const char* src = pPath; char* trg = str; while (*src) { if (*src != '/') { *trg++ = *src++; } else { *trg++ = '\\'; src++; } } *trg = 0; return str; } ////////////////////////////////////////////////////////////////////////// char* ZipDir::CacheRW::AllocPath(const char* pPath) { char str[_MAX_PATH]; char* temp = ToUnixPath(str, pPath); temp = m_tempStringPool.Append(temp, strlen(temp)); return temp; } static void PackFileFromMemory(PackFileJob* job) { if (job->existingCRC != 0) { unsigned int crcCode = (unsigned int)crc32(0, (unsigned char*)job->uncompressedData, job->uncompressedSize); if (crcCode == job->existingCRC) { job->compressedData = 0; job->compressedSize = 0; job->status = PACKFILE_UPTODATE; job->zdError = ZipDir::ZD_ERROR_SUCCESS; // This file with same data already in pak, skip it. return; } } switch (job->batch->compressionMethod) { case METHOD_DEFLATE_AND_ENCRYPT: case METHOD_DEFLATE: { // allocate memory for compression. Min is nSize * 1.001 + 12 if (job->uncompressedSize > 0) { job->compressedSize = job->uncompressedSize + (job->uncompressedSize >> 3) + 32; job->compressedData = malloc(job->compressedSize); int error = ZipDir::ZipRawCompress(job->uncompressedData, &job->compressedSize, job->compressedData, job->uncompressedSize, job->batch->compressionLevel); if (error == Z_OK) { job->status = PACKFILE_COMPRESSED; job->zdError = ZipDir::ZD_ERROR_SUCCESS; } else { job->status = PACKFILE_FAILED; job->zdError = ZipDir::ZD_ERROR_ZLIB_FAILED; } } else { job->status = PACKFILE_COMPRESSED; job->zdError = ZipDir::ZD_ERROR_SUCCESS; job->compressedSize = 0; job->compressedData = 0; } break; } case METHOD_STORE: job->compressedData = job->uncompressedData; job->compressedSize = job->uncompressedSize; job->status = PACKFILE_COMPRESSED; job->zdError = ZipDir::ZD_ERROR_SUCCESS; break; default: job->status = PACKFILE_FAILED; job->zdError = ZipDir::ZD_ERROR_UNSUPPORTED; break; } } bool ZipDir::CacheRW::WriteCompressedData(const char* data, size_t size, bool encrypt, FILE* file) { if (size <= 0) { return true; } std::vector<char> buffer; if (encrypt) { buffer.resize(size); memcpy(&buffer[0], data, size); ZipDir::Encrypt(&buffer[0], size, m_encryptionKey); data = &buffer[0]; } // Danny - writing a single large chunk (more than 6MB?) causes // Windows fwrite to (silently?!) fail. So we're writing data // in small chunks. while (size > 0) { const size_t sizeToWrite = Util::getMin(size, size_t(1024 * 1024)); if (fwrite(data, sizeToWrite, 1, file) != 1) { return false; } data += sizeToWrite; size -= sizeToWrite; } return true; } static bool WriteRandomData(FILE* file, size_t size) { if (size <= 0) { return true; } const size_t bufferSize = Util::getMin(size, size_t(1024 * 1024)); std::vector<char> buffer(bufferSize); while (size > 0) { const size_t sizeToWrite = Util::getMin(size, bufferSize); for (size_t i = 0; i < sizeToWrite; ++i) { buffer[i] = rand() & 0xff; } if (fwrite(&buffer[0], sizeToWrite, 1, file) != 1) { return false; } size -= sizeToWrite; } return true; } bool ZipDir::CacheRW::WriteNullData(size_t size) { if (size <= 0) { return true; } const size_t bufferSize = Util::getMin(size, size_t(1024 * 1024)); std::vector<char> buffer(bufferSize, 0); while (size > 0) { const size_t sizeToWrite = Util::getMin(size, bufferSize); if (fwrite(&buffer[0], sizeToWrite, 1, m_pFile) != 1) { return false; } size -= sizeToWrite; } return true; } void ZipDir::CacheRW::StorePackedFile(PackFileJob* job) { if (job->batch->zipMaxSize > 0 && GetTotalFileSize() > job->batch->zipMaxSize) { job->status = PACKFILE_SKIPPED; job->zdError = ZipDir::ZD_ERROR_SUCCESS; return; } job->status = PACKFILE_FAILED; char str[_MAX_PATH]; char* relativePath = UnifyPath(str, job->relativePathSrc); // create or find the file entry.. this object will rollback (delete the object // if the operation fails) if needed. FileEntryTransactionAdd pFileEntry(this, AllocPath(job->relativePathSrc), AllocPath(relativePath)); if (!pFileEntry) { job->zdError = ZipDir::ZD_ERROR_INVALID_PATH; return; } pFileEntry->OnNewFileData(job->uncompressedData, job->uncompressedSize, job->compressedSize, job->batch->compressionMethod, false); pFileEntry->SetFromFileTimeNTFS(job->modTime); // since we changed the time, we'll have to update CDR m_nFlags |= FLAGS_CDR_DIRTY; // the new CDR position, if the operation completes successfully unsigned lNewCDROffset = m_lCDROffset; if (pFileEntry->IsInitialized()) { // this file entry is already allocated in CDR // check if the new compressed data fits into the old place unsigned nFreeSpace = pFileEntry->nEOFOffset - pFileEntry->nFileHeaderOffset - (unsigned)sizeof(ZipFile::LocalFileHeader) - (unsigned)strlen(relativePath); if (nFreeSpace != job->compressedSize) { m_nFlags |= FLAGS_UNCOMPACTED; } if (nFreeSpace >= job->compressedSize) { // and we can just override the compressed data in the file ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, job->relativePathSrc, m_bEncryptedHeaders); if (e != ZipDir::ZD_ERROR_SUCCESS) { job->zdError = e; return; } } else { // we need to write the file anew - in place of current CDR pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(job->relativePathSrc, m_lCDROffset, m_fileAlignment); ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, job->relativePathSrc, m_bEncryptedHeaders); lNewCDROffset = pFileEntry->nEOFOffset; if (e != ZipDir::ZD_ERROR_SUCCESS) { job->zdError = e; return; } } } else { pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(job->relativePathSrc, m_lCDROffset, m_fileAlignment); ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, job->relativePathSrc, m_bEncryptedHeaders); if (e != ZipDir::ZD_ERROR_SUCCESS) { job->zdError = e; return; } lNewCDROffset = pFileEntry->nFileDataOffset + job->compressedSize; m_nFlags |= FLAGS_CDR_DIRTY; } // now we have the fresh local header and data offset #ifdef WIN32 if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileDataOffset, SEEK_SET) != 0) #else if (fseek (m_pFile, pFileEntry->nFileDataOffset, SEEK_SET) != 0) #endif { job->zdError = ZD_ERROR_IO_FAILED; return; } const bool encrypt = pFileEntry->nMethod == METHOD_DEFLATE_AND_ENCRYPT; if (!WriteCompressedData((char*)job->compressedData, job->compressedSize, encrypt, m_pFile)) { job->zdError = ZD_ERROR_IO_FAILED; return; } // since we wrote the file successfully, update the new CDR position m_lCDROffset = lNewCDROffset; pFileEntry.Commit(); job->status = PACKFILE_ADDED; job->zdError = ZD_ERROR_SUCCESS; } // Adds a new file to the zip or update an existing one // adds a directory (creates several nested directories if needed) ZipDir::ErrorEnum ZipDir::CacheRW::UpdateFile (const char* szRelativePathSrc, void* pUncompressed, unsigned nSize, unsigned nCompressionMethod, int nCompressionLevel, __time64_t modTime) { char str[_MAX_PATH]; char* szRelativePath = UnifyPath(str, szRelativePathSrc); PackFileBatch batch; batch.compressionMethod = nCompressionMethod; batch.compressionLevel = nCompressionLevel; PackFileJob job; job.relativePathSrc = szRelativePathSrc; job.modTime = modTime; job.uncompressedData = pUncompressed; job.uncompressedSize = nSize; job.batch = &batch; // crc will be used to check if this file need to be updated at all ZipDir::FileEntry* entry = FindFile(szRelativePath); if (entry) { job.existingCRC = entry->desc.lCRC32; } PackFileFromMemory(&job); switch (job.status) { case PACKFILE_SKIPPED: case PACKFILE_MISSING: case PACKFILE_FAILED: return ZD_ERROR_IO_FAILED; } StorePackedFile(&job); job.DetachUncompressedData(); return job.zdError; } static FILETIME GetFileWriteTimeAndSize(uint64* fileSize, const char* filename) { // Warning: FindFirstFile on NTFS may report file size that // is not up-to-date with the actual file content. // http://blogs.msdn.com/b/oldnewthing/archive/2011/12/26/10251026.aspx FILETIME fileTime; #if defined(AZ_PLATFORM_WINDOWS) WIN32_FIND_DATAA FindFileData; HANDLE hFind = FindFirstFileA(filename, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { fileTime.dwLowDateTime = 0; fileTime.dwHighDateTime = 0; if (fileSize) { *fileSize = 0; } } else { fileTime.dwLowDateTime = FindFileData.ftLastWriteTime.dwLowDateTime; fileTime.dwHighDateTime = FindFileData.ftLastWriteTime.dwHighDateTime; if (fileSize) { *fileSize = (uint64(FindFileData.nFileSizeHigh) << 32) + FindFileData.nFileSizeLow; } FindClose(hFind); } #elif defined(AZ_PLATFORM_APPLE) || defined(AZ_PLATFORM_LINUX) //We cant use this implmentation for the windows version because ModificationTime //returns the time filename was changed(ChangeTime) not last written into(LastWriteTime). //If LocalFileIO ever adds support for LastWriteTime we can have a common implementation. AZ::IO::LocalFileIO localFileIO; AZ::u64 modTime = 0; modTime = localFileIO.ModificationTime(filename); if(modTime != 0) { fileTime.dwHighDateTime = modTime >> 32; fileTime.dwLowDateTime = modTime & 0xFFFFFFFF; if (fileSize) { localFileIO.Size(filename, *fileSize); } } #else #error Needs implmentation! #endif return fileTime; } static void PackFileFromDisc(PackFileJob* job) { const FILETIME ft = GetFileWriteTimeAndSize(0, job->realFilename); LARGE_INTEGER lt; lt.HighPart = ft.dwHighDateTime; lt.LowPart = ft.dwLowDateTime; job->modTime = lt.QuadPart; FILE* f = nullptr; azfopen(&f, job->realFilename, "rb"); if (!f) { job->status = PACKFILE_FAILED; job->zdError = ZipDir::ZD_ERROR_FILE_NOT_FOUND; return; } fseek(f, 0, SEEK_END); size_t fileSize = (size_t)ftell(f); if (fileSize < job->batch->sourceMinSize || (job->batch->sourceMaxSize > 0 && fileSize > job->batch->sourceMaxSize)) { fclose(f); job->status = PACKFILE_SKIPPED; job->zdError = ZipDir::ZD_ERROR_SUCCESS; return; } job->uncompressedData = malloc(fileSize); fseek(f, 0, SEEK_SET); if (fread(job->uncompressedData, 1, fileSize, f) != fileSize) { free(job->uncompressedData); job->uncompressedData = 0; fclose(f); job->status = PACKFILE_FAILED; job->zdError = ZipDir::ZD_ERROR_IO_FAILED; return; } fclose(f); job->uncompressedSize = fileSize; PackFileFromMemory(job); } bool ZipDir::CacheRW::UpdateMultipleFiles(const char** realFilenames, const char** filenamesInZip, size_t fileCount, int compressionLevel, bool encryptContent, size_t zipMaxSize, int sourceMinSize, int sourceMaxSize, unsigned numExtraThreads, ZipDir::IReporter* reporter, ZipDir::ISplitter* splitter) { int compressionMethod = METHOD_DEFLATE; if (encryptContent) { compressionMethod = METHOD_DEFLATE_AND_ENCRYPT; } else if (compressionLevel == 0) { compressionMethod = METHOD_STORE; } uint64 totalSize = 0; clock_t startTime = clock(); PackFileBatch batch; batch.compressionLevel = compressionLevel; batch.compressionMethod = compressionMethod; batch.sourceMinSize = sourceMinSize; batch.sourceMaxSize = sourceMaxSize; batch.zipMaxSize = zipMaxSize; const size_t memoryLimit = 1024 * 1024 * 1024; // prevents threads from generating more than 1GB of data PackFilePool pool(fileCount, memoryLimit); batch.pool = &pool; for (int i = 0; i < fileCount; ++i) { const char* realFilename = realFilenames[i]; const char* filenameInZip = filenamesInZip[i]; PackFileJob job; job.relativePathSrc = filenameInZip; job.realFilename = realFilename; job.batch = &batch; { // crc will be used to check if this file need to be updated at all ZipDir::FileEntry* entry = FindFile(filenameInZip); if (entry) { uint64 fileSize = 0; const FILETIME ft = GetFileWriteTimeAndSize(&fileSize, realFilename); LARGE_INTEGER lt; lt.HighPart = ft.dwHighDateTime; lt.LowPart = ft.dwLowDateTime; job.modTime = lt.QuadPart; job.existingCRC = entry->desc.lCRC32; job.compressedSizePreviously = entry->desc.lSizeCompressed; job.uncompressedSizePreviously = entry->desc.lSizeUncompressed; // Check if file with the same name, timestamp and size already exists in pak. if (entry->CompareFileTimeNTFS(job.modTime) && fileSize == entry->desc.lSizeUncompressed) { if (reporter) { reporter->ReportUpToDate(filenameInZip); } continue; } } } pool.Submit(i, job); } // Get the number of submitted jobs, which is at most // as large as the largest successfully submitted file-index. // Any number of files can be skipped for submission. const int jobCount = pool.GetJobCount(); if (jobCount == 0) { return true; } pool.Start(numExtraThreads); for (int i = 0; i < jobCount; ++i) { PackFileJob* job = pool.WaitForFile(i); if (!job) { assert(job); continue; } if (job->status == PACKFILE_COMPRESSED) { if (splitter) { size_t dsk = GetTotalFileSizeOnDiskSoFar(); size_t bse = 0; size_t add = 0; size_t sub = 0; bse += sizeof(ZipFile::CDRFileHeader) + strlen(job->relativePathSrc); bse += sizeof(ZipFile::LocalFileHeader) + strlen(job->relativePathSrc); if (job->compressedSize) { add += bse + job->compressedSize; } if (job->compressedSizePreviously) { sub += bse + job->compressedSizePreviously; } if (splitter->CheckWriteLimit(dsk, add, sub)) { splitter->SetLastFile(dsk, add, sub, job->key - 1); // deplete the pool before leaving the loop pool.SkipPendingFiles(); for (; i < jobCount; ++i) { pool.WaitForFile(i); pool.ReleaseFile(i); } break; } } StorePackedFile(job); } switch (job->status) { case PACKFILE_ADDED: if (reporter) { reporter->ReportAdded(job->relativePathSrc); } totalSize += job->uncompressedSize; break; case PACKFILE_MISSING: if (reporter) { reporter->ReportMissing(job->realFilename); } break; case PACKFILE_UPTODATE: if (reporter) { reporter->ReportUpToDate(job->realFilename); } break; case PACKFILE_SKIPPED: if (reporter) { reporter->ReportSkipped(job->realFilename); } break; default: if (reporter) { reporter->ReportFailed(job->realFilename, ""); // TODO reason } break; } pool.ReleaseFile(i); } clock_t endTime = clock(); double timeSeconds = double(endTime - startTime) / CLOCKS_PER_SEC; double speed = (endTime - startTime) == 0 ? 0.0 : double(totalSize) / timeSeconds; if (reporter) { reporter->ReportSpeed(speed); } return true; } // Adds a new file to the zip or update an existing one if it is not compressed - just stored - start a big file ZipDir::ErrorEnum ZipDir::CacheRW::StartContinuousFileUpdate(const char* szRelativePathSrc, unsigned nSize) { char str[_MAX_PATH]; char* szRelativePath = UnifyPath(str, szRelativePathSrc); SmartPtr pBufferDestroyer; // create or find the file entry.. this object will rollback (delete the object // if the operation fails) if needed. FileEntryTransactionAdd pFileEntry(this, AllocPath(szRelativePathSrc), AllocPath(szRelativePath)); if (!pFileEntry) { return ZD_ERROR_INVALID_PATH; } pFileEntry->OnNewFileData (NULL, nSize, nSize, METHOD_STORE, false); // since we changed the time, we'll have to update CDR m_nFlags |= FLAGS_CDR_DIRTY; // the new CDR position, if the operation completes successfully unsigned lNewCDROffset = m_lCDROffset; if (pFileEntry->IsInitialized()) { // check if the new compressed data fits into the old place unsigned nFreeSpace = pFileEntry->nEOFOffset - pFileEntry->nFileHeaderOffset - (unsigned)sizeof(ZipFile::LocalFileHeader) - (unsigned)strlen(szRelativePath); if (nFreeSpace != nSize) { m_nFlags |= FLAGS_UNCOMPACTED; } if (nFreeSpace >= nSize) { // and we can just override the compressed data in the file ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePathSrc, m_bEncryptedHeaders); if (e != ZD_ERROR_SUCCESS) { return e; } } else { // we need to write the file anew - in place of current CDR pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(szRelativePathSrc, m_lCDROffset, m_fileAlignment); ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePathSrc, m_bEncryptedHeaders); lNewCDROffset = pFileEntry->nEOFOffset; if (e != ZD_ERROR_SUCCESS) { return e; } } } else { pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(szRelativePathSrc, m_lCDROffset, m_fileAlignment); ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePathSrc, m_bEncryptedHeaders); if (e != ZD_ERROR_SUCCESS) { return e; } lNewCDROffset = pFileEntry->nFileDataOffset + nSize; m_nFlags |= FLAGS_CDR_DIRTY; } #ifdef WIN32 if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileDataOffset, SEEK_SET) != 0) #else if (fseek (m_pFile, pFileEntry->nFileDataOffset, SEEK_SET) != 0) #endif { return ZD_ERROR_IO_FAILED; } if (!WriteNullData(nSize)) { return ZD_ERROR_IO_FAILED; } pFileEntry->nEOFOffset = pFileEntry->nFileDataOffset; // since we wrote the file successfully, update the new CDR position m_lCDROffset = lNewCDROffset; pFileEntry.Commit(); return ZD_ERROR_SUCCESS; } // Adds a new file to the zip or update an existing's segment if it is not compressed - just stored // adds a directory (creates several nested directories if needed) ZipDir::ErrorEnum ZipDir::CacheRW::UpdateFileContinuousSegment (const char* szRelativePathSrc, unsigned nSize, void* pUncompressed, unsigned nSegmentSize, unsigned nOverwriteSeekPos) { char str[_MAX_PATH]; char* szRelativePath = UnifyPath(str, szRelativePathSrc); SmartPtr pBufferDestroyer; // create or find the file entry.. this object will rollback (delete the object // if the operation fails) if needed. FileEntryTransactionAdd pFileEntry(this, AllocPath(szRelativePathSrc), AllocPath(szRelativePath)); if (!pFileEntry) { return ZD_ERROR_INVALID_PATH; } pFileEntry->OnNewFileData (pUncompressed, nSegmentSize, nSegmentSize, METHOD_STORE, true); // since we changed the time, we'll have to update CDR m_nFlags |= FLAGS_CDR_DIRTY; // this file entry is already allocated in CDR unsigned lSegmentOffset = pFileEntry->nEOFOffset; #ifdef WIN32 if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) #else if (fseek (m_pFile, pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) #endif { return ZD_ERROR_IO_FAILED; } // and we can just override the compressed data in the file ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePath, m_bEncryptedHeaders); if (e != ZD_ERROR_SUCCESS) { return e; } if (nOverwriteSeekPos != 0xffffffff) { lSegmentOffset = pFileEntry->nFileDataOffset + nOverwriteSeekPos; } // now we have the fresh local header and data offset #ifdef WIN32 if (_fseeki64 (m_pFile, (__int64)lSegmentOffset, SEEK_SET) != 0) #else if (fseek (m_pFile, lSegmentOffset, SEEK_SET) != 0) #endif { return ZD_ERROR_IO_FAILED; } const bool encrypt = false; // encryption is not supported for continous updates if (!WriteCompressedData((char*)pUncompressed, nSegmentSize, encrypt, m_pFile)) { return ZD_ERROR_IO_FAILED; } if (nOverwriteSeekPos == 0xffffffff) { pFileEntry->nEOFOffset = lSegmentOffset + nSegmentSize; } // since we wrote the file successfully, update CDR pFileEntry.Commit(); return ZD_ERROR_SUCCESS; } ZipDir::ErrorEnum ZipDir::CacheRW::UpdateFileCRC (const char* szRelativePathSrc, unsigned dwCRC32) { char str[_MAX_PATH]; char* szRelativePath = UnifyPath(str, szRelativePathSrc); SmartPtr pBufferDestroyer; // create or find the file entry.. this object will rollback (delete the object // if the operation fails) if needed. FileEntryTransactionAdd pFileEntry(this, AllocPath(szRelativePathSrc), AllocPath(szRelativePath)); if (!pFileEntry) { return ZD_ERROR_INVALID_PATH; } // since we changed the time, we'll have to update CDR m_nFlags |= FLAGS_CDR_DIRTY; pFileEntry->desc.lCRC32 = dwCRC32; #ifdef WIN32 if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) #else if (fseek (m_pFile, pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) #endif { return ZD_ERROR_IO_FAILED; } // and we can just override the compressed data in the file ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePath, m_bEncryptedHeaders); if (e != ZD_ERROR_SUCCESS) { return e; } // since we wrote the file successfully, update pFileEntry.Commit(); return ZD_ERROR_SUCCESS; } // deletes the file from the archive ZipDir::ErrorEnum ZipDir::CacheRW::RemoveFile (const char* szRelativePathSrc) { char str[_MAX_PATH]; char* szRelativePath = UnifyPath(str, szRelativePathSrc); // find the last slash in the path const char* pSlash = (std::max)(strrchr(szRelativePath, '/'), strrchr(szRelativePath, '\\')); const char* pFileName; // the name of the file to delete FileEntryTree* pDir; // the dir from which the subdir will be deleted if (pSlash) { FindDirRW fd (GetRoot()); // the directory to remove pDir = fd.FindExact(string (szRelativePath, pSlash - szRelativePath).c_str()); if (!pDir) { return ZD_ERROR_DIR_NOT_FOUND;// there is no such directory } pFileName = pSlash + 1; } else { pDir = GetRoot(); pFileName = szRelativePath; } ErrorEnum e = pDir->RemoveFile (pFileName); if (e == ZD_ERROR_SUCCESS) { m_nFlags |= FLAGS_UNCOMPACTED | FLAGS_CDR_DIRTY; } return e; } // deletes the directory, with all its descendants (files and subdirs) ZipDir::ErrorEnum ZipDir::CacheRW::RemoveDir (const char* szRelativePathSrc) { char str[_MAX_PATH]; char* szRelativePath = UnifyPath(str, szRelativePathSrc); // find the last slash in the path const char* pSlash = (std::max)(strrchr(szRelativePath, '/'), strrchr(szRelativePath, '\\')); const char* pDirName; // the name of the dir to delete FileEntryTree* pDir; // the dir from which the subdir will be deleted if (pSlash) { FindDirRW fd (GetRoot()); // the directory to remove pDir = fd.FindExact(string (szRelativePath, pSlash - szRelativePath).c_str()); if (!pDir) { return ZD_ERROR_DIR_NOT_FOUND;// there is no such directory } pDirName = pSlash + 1; } else { pDir = GetRoot(); pDirName = szRelativePath; } ErrorEnum e = pDir->RemoveDir (pDirName); if (e == ZD_ERROR_SUCCESS) { m_nFlags |= FLAGS_UNCOMPACTED | FLAGS_CDR_DIRTY; } return e; } // deletes all files and directories in this archive ZipDir::ErrorEnum ZipDir::CacheRW::RemoveAll() { ErrorEnum e = m_treeDir.RemoveAll(); if (e == ZD_ERROR_SUCCESS) { m_nFlags |= FLAGS_UNCOMPACTED | FLAGS_CDR_DIRTY; } return e; } ZipDir::ErrorEnum ZipDir::CacheRW::ReadFile (FileEntry* pFileEntry, void* pCompressed, void* pUncompressed) { if (!pFileEntry) { return ZD_ERROR_INVALID_CALL; } if (pFileEntry->desc.lSizeUncompressed == 0) { assert (pFileEntry->desc.lSizeCompressed == 0); return ZD_ERROR_SUCCESS; } assert (pFileEntry->desc.lSizeCompressed > 0); ErrorEnum nError = Refresh(pFileEntry); if (nError != ZD_ERROR_SUCCESS) { return nError; } #ifdef WIN32 if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileDataOffset, SEEK_SET)) #else if (fseek (m_pFile, pFileEntry->nFileDataOffset, SEEK_SET)) #endif { return ZD_ERROR_IO_FAILED; } SmartPtr pBufferDestroyer; void* pBuffer = pCompressed; // the buffer where the compressed data will go if (pFileEntry->nMethod == 0 && pUncompressed) { // we can directly read into the uncompress buffer pBuffer = pUncompressed; } if (!pBuffer) { if (!pUncompressed) { // what's the sense of it - no buffers at all? return ZD_ERROR_INVALID_CALL; } pBuffer = malloc(pFileEntry->desc.lSizeCompressed); pBufferDestroyer.Attach(pBuffer); // we want it auto-freed once we return } if (fread((char*)pBuffer, pFileEntry->desc.lSizeCompressed, 1, m_pFile) != 1) { return ZD_ERROR_IO_FAILED; } if (pFileEntry->nMethod == METHOD_DEFLATE_AND_ENCRYPT) { ZipDir::Decrypt((char*)pBuffer, pFileEntry->desc.lSizeCompressed, m_encryptionKey); } // if there's a buffer for uncompressed data, uncompress it to that buffer if (pUncompressed) { if (pFileEntry->nMethod == 0) { assert (pBuffer == pUncompressed); //assert (pFileEntry->nSizeCompressed == pFileEntry->nSizeUncompressed); //memcpy (pUncompressed, pBuffer, pFileEntry->nSizeCompressed); } else { unsigned long nSizeUncompressed = pFileEntry->desc.lSizeUncompressed; if (nSizeUncompressed > 0) { if (Z_OK != ZipRawUncompress(pUncompressed, &nSizeUncompressed, pBuffer, pFileEntry->desc.lSizeCompressed)) { return ZD_ERROR_CORRUPTED_DATA; } } } } return ZD_ERROR_SUCCESS; } ////////////////////////////////////////////////////////////////////////// // finds the file by exact path ZipDir::FileEntry* ZipDir::CacheRW::FindFile (const char* szPathSrc, bool bFullInfo) { char str[_MAX_PATH]; char* szPath = UnifyPath(str, szPathSrc); ZipDir::FindFileRW fd (GetRoot()); if (!fd.FindExact(szPath)) { assert (!fd.GetFileEntry()); return NULL; } assert (fd.GetFileEntry()); return fd.GetFileEntry(); } // returns the size of memory occupied by the instance referred to by this cache size_t ZipDir::CacheRW::GetSize() const { return sizeof(*this) + m_strFilePath.capacity() + m_treeDir.GetSize() - sizeof(m_treeDir); } // returns the compressed size of all the entries size_t ZipDir::CacheRW::GetCompressedSize() const { return m_treeDir.GetCompressedFileSize(); } // returns the total size of memory occupied by the instance of this cache and all the compressed files size_t ZipDir::CacheRW::GetTotalFileSize() const { return GetSize() + GetCompressedSize(); } // returns the total size of space occupied on disk by the instance of this cache and all the compressed files size_t ZipDir::CacheRW::GetTotalFileSizeOnDiskSoFar() { FileRecordList arrFiles(GetRoot()); FileRecordList::ZipStats statFiles = arrFiles.GetStats(); return m_lCDROffset + statFiles.nSizeCDR; } // refreshes information about the given file entry into this file entry ZipDir::ErrorEnum ZipDir::CacheRW::Refresh (FileEntry* pFileEntry) { if (!pFileEntry) { return ZD_ERROR_INVALID_CALL; } if (pFileEntry->nFileDataOffset != pFileEntry->INVALID_DATA_OFFSET) { return ZD_ERROR_SUCCESS; // the data offset has been successfully read.. } return ZipDir::Refresh(m_pFile, pFileEntry, m_bEncryptedHeaders); } // writes the CDR to the disk bool ZipDir::CacheRW::WriteCDR(FILE* fTarget, bool encryptCDR) { if (!fTarget) { return false; } #ifdef WIN32 if (_fseeki64(fTarget, (__int64)m_lCDROffset, SEEK_SET)) #else if (fseek(fTarget, m_lCDROffset, SEEK_SET)) #endif { return false; } FileRecordList arrFiles(GetRoot()); //arrFiles.SortByFileOffset(); size_t nSizeCDR = arrFiles.GetStats().nSizeCDR; void* pCDR = malloc(nSizeCDR); size_t nSizeCDRSerialized = arrFiles.MakeZipCDR(m_lCDROffset, pCDR, encryptCDR); assert (nSizeCDRSerialized == nSizeCDR); if (encryptCDR) { // We do not encrypt CDREnd, so we could find it by signature ZipDir::Encrypt((char*)pCDR, nSizeCDR - sizeof(ZipFile::CDREnd), m_encryptionKey); } size_t nWriteRes = fwrite (pCDR, nSizeCDR, 1, fTarget); free(pCDR); return nWriteRes == 1; } // generates random file name string ZipDir::CacheRW::GetRandomName(int nAttempt) { if (nAttempt) { char szBuf[8]; int i; for (i = 0; i < sizeof(szBuf) - 1; ++i) { int r = rand() % (10 + 'z' - 'a' + 1); szBuf[i] = r > 9 ? (r - 10) + 'a' : '0' + r; } szBuf[i] = '\0'; return szBuf; } else { return string(); } } bool ZipDir::CacheRW::RelinkZip() { AZ::IO::LocalFileIO localFileIO; for (int nAttempt = 0; nAttempt < 32; ++nAttempt) { string strNewFilePath = m_strFilePath + "$" + GetRandomName(nAttempt); FILE* f = nullptr; azfopen(&f, strNewFilePath.c_str(), "wb"); if (f) { bool bOk = RelinkZip(f); fclose (f); // we don't need the temporary file handle anyway if (!bOk) { // we don't need the temporary file localFileIO.Remove(strNewFilePath.c_str()); return false; } // we successfully relinked, now copy the temporary file to the original file fclose (m_pFile); m_pFile = NULL; localFileIO.Remove(m_strFilePath.c_str()); if (localFileIO.Rename(strNewFilePath.c_str(), m_strFilePath.c_str()) == 0) { // successfully renamed - reopen m_pFile = nullptr; azfopen(&m_pFile, m_strFilePath.c_str(), "r+b"); return m_pFile == NULL; } else { // could not rename //m_pFile = fopen (strNewFilePath.c_str(), "r+b"); return false; } } } // couldn't open temp file return false; } bool ZipDir::CacheRW::RelinkZip(FILE* fTmp) { FileRecordList arrFiles(GetRoot()); arrFiles.SortByFileOffset(); FileRecordList::ZipStats Stats = arrFiles.GetStats(); // we back up our file entries, because we'll need to restore them // in case the operation fails std::vector<FileEntry> arrFileEntryBackup; arrFiles.Backup (arrFileEntryBackup); // this is the set of files that are to be written out - compressed data and the file record iterator std::vector<FileDataRecordPtr> queFiles; queFiles.reserve (g_nMaxItemsRelinkBuffer); // the total size of data in the queue unsigned nQueueSize = 0; for (FileRecordList::iterator it = arrFiles.begin(); it != arrFiles.end(); ++it) { FileEntry* entry = it->pFileEntry; // find the file data offset if (ZD_ERROR_SUCCESS != Refresh(entry)) { return false; } // go to the file data #ifdef WIN32 if (_fseeki64 (m_pFile, (__int64)entry->nFileDataOffset, SEEK_SET) != 0) #else if (fseek (m_pFile, entry->nFileDataOffset, SEEK_SET) != 0) #endif { return false; } // allocate memory for the file compressed data FileDataRecordPtr pFile = FileDataRecord::New (*it); if (!pFile) { return false; } // read the compressed data if (entry->desc.lSizeCompressed && fread (pFile->GetData(), entry->desc.lSizeCompressed, 1, m_pFile) != 1) { return false; } if (entry->nMethod == METHOD_DEFLATE_AND_ENCRYPT) { ZipDir::Decrypt((char*)pFile->GetData(), entry->desc.lSizeCompressed, m_encryptionKey); } // put the file into the queue for copying (writing) queFiles.push_back(pFile); nQueueSize += entry->desc.lSizeCompressed; // if the queue is big enough, write it out if (nQueueSize > g_nSizeRelinkBuffer || queFiles.size() >= g_nMaxItemsRelinkBuffer) { nQueueSize = 0; if (!WriteZipFiles(queFiles, fTmp)) { return false; } } } if (!WriteZipFiles(queFiles, fTmp)) { return false; } ZipFile::ulong lOldCDROffset = m_lCDROffset; // the file data has now been written out. Now write the CDR #ifdef WIN32 m_lCDROffset = (ZipFile::ulong)_ftelli64(fTmp); #else m_lCDROffset = ftell(fTmp); #endif if (m_lCDROffset >= 0 && WriteCDR(fTmp, m_bHeadersEncryptedOnClose) && 0 == fflush (fTmp)) { // the new file positions are already there - just discard the backup and return return true; } // recover from backup arrFiles.Restore (arrFileEntryBackup); m_lCDROffset = lOldCDROffset; m_bEncryptedHeaders = m_bHeadersEncryptedOnClose; return false; } // writes out the file data in the queue into the given file. Empties the queue bool ZipDir::CacheRW::WriteZipFiles(std::vector<FileDataRecordPtr>& queFiles, FILE* fTmp) { for (std::vector<FileDataRecordPtr>::iterator it = queFiles.begin(); it != queFiles.end(); ++it) { // set the new header offset to the file entry - we won't need it #ifdef WIN32 const unsigned long currentPos = (unsigned long)_ftelli64 (fTmp); #else const unsigned long currentPos = ftell (fTmp); #endif (*it)->pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset((*it)->strPath.c_str(), currentPos, m_fileAlignment); // while writing the local header, the data offset will also be calculated if (ZD_ERROR_SUCCESS != WriteLocalHeader(fTmp, (*it)->pFileEntry, (*it)->strPath.c_str(), m_bHeadersEncryptedOnClose)) { return false; } ; // write the compressed file data const bool encrypt = (*it)->pFileEntry->nMethod == METHOD_DEFLATE_AND_ENCRYPT; if (!WriteCompressedData((char*)(*it)->GetData(), (*it)->pFileEntry->desc.lSizeCompressed, encrypt, fTmp)) { return false; } #ifdef WIN32 assert ((*it)->pFileEntry->nEOFOffset == (unsigned long)_ftelli64 (fTmp)); #else assert ((*it)->pFileEntry->nEOFOffset == ftell (fTmp)); #endif } queFiles.clear(); queFiles.reserve (g_nMaxItemsRelinkBuffer); return true; } void TruncateFile(FILE* file, size_t newLength) { #if defined(AZ_PLATFORM_WINDOWS) int filedes = _fileno(file); _chsize_s(filedes, newLength); #elif defined(AZ_PLATFORM_APPLE) || defined(AZ_PLATFORM_LINUX) ftruncate(fileno(file), newLength); #else #error Not implemented! #endif } bool ZipDir::CacheRW::EncryptArchive(EncryptionChange change, IEncryptPredicate* encryptContentPredicate, int* numChanged, int* numSkipped) { FileRecordList arrFiles(GetRoot()); arrFiles.SortByFileOffset(); // the total size of data in the queue unsigned nQueueSize = 0; size_t unusedSpace = 0; size_t lastDataEnd = 0; for (FileRecordList::iterator it = arrFiles.begin(); it != arrFiles.end(); ++it) { FileEntry* entry = it->pFileEntry; if (entry->nFileHeaderOffset > lastDataEnd) { fseek(m_pFile, lastDataEnd, SEEK_SET); size_t gapLength = entry->nFileHeaderOffset - lastDataEnd; unusedSpace += gapLength; if (change == ENCRYPT) { if (!WriteRandomData(m_pFile, gapLength)) { return false; } } else { if (!WriteNullData(gapLength)) { return false; } } } lastDataEnd = entry->nEOFOffset; if (numSkipped) { ++(*numSkipped); } // find the file data offset if (ZD_ERROR_SUCCESS != Refresh (entry)) { return false; } bool methodChanged = false; ZipFile::ushort oldMethod = entry->nMethod; ZipFile::ushort newMethod = oldMethod; if (change == ENCRYPT) { if (entry->nMethod == METHOD_DEFLATE) { newMethod = METHOD_DEFLATE_AND_ENCRYPT; } } else { if (entry->nMethod == METHOD_DEFLATE_AND_ENCRYPT) { newMethod = METHOD_DEFLATE; } } // allow encryption only for matching files if (newMethod == METHOD_DEFLATE_AND_ENCRYPT && (!encryptContentPredicate || !encryptContentPredicate->Match(it->strPath.c_str()))) { newMethod = METHOD_DEFLATE; } entry->nMethod = newMethod; const bool encryptHeaders = change == ENCRYPT; // encryption is toggled or compression method changed... if (newMethod != oldMethod || encryptHeaders != m_bEncryptedHeaders) { // ... update header if (ZipDir::WriteLocalHeader(m_pFile, entry, it->strPath.c_str(), encryptHeaders) != ZD_ERROR_SUCCESS) { return false; } } if (newMethod == oldMethod) { // no need to update file content continue; } // go to the file data #ifdef WIN32 if (_fseeki64 (m_pFile, (__int64)entry->nFileDataOffset, SEEK_SET) != 0) #else if (fseek (m_pFile, entry->nFileDataOffset, SEEK_SET) != 0) #endif { return false; } // allocate memory for the file compressed data FileDataRecordPtr pFile = FileDataRecord::New(*it); if (!pFile) { return false; } // read the compressed data if (entry->desc.lSizeCompressed && fread (pFile->GetData(), entry->desc.lSizeCompressed, 1, m_pFile) != 1) { return false; } if (oldMethod == METHOD_DEFLATE_AND_ENCRYPT) { ZipDir::Decrypt((char*)pFile->GetData(), entry->desc.lSizeCompressed, m_encryptionKey); } #ifdef WIN32 if (_fseeki64 (m_pFile, (__int64)entry->nFileDataOffset, SEEK_SET) != 0) #else if (fseek (m_pFile, entry->nFileDataOffset, SEEK_SET) != 0) #endif { return false; } const bool encryptContent = newMethod == METHOD_DEFLATE_AND_ENCRYPT; if (!WriteCompressedData((const char*)pFile->GetData(), entry->desc.lSizeCompressed, encryptContent, m_pFile)) { return false; } if (numSkipped) { --(*numSkipped); } if (numChanged) { ++(*numChanged); } } m_bEncryptedHeaders = change == ENCRYPT; m_bHeadersEncryptedOnClose = m_bEncryptedHeaders; if (!WriteCDR(m_pFile, m_bEncryptedHeaders)) { return false; } if (fflush (m_pFile) != 0) { return false; } size_t endOfCDR = (size_t)ftell(m_pFile); fseek(m_pFile, 0, SEEK_END); size_t fileSize = (size_t)ftell(m_pFile); if (fileSize != endOfCDR) { TruncateFile(m_pFile, endOfCDR); } #if 0 if (unusedSpace > 0) { RCLog("Archive contains %i bytes of uncompacted space.", (int)unusedSpace); } #endif fclose(m_pFile); m_pFile = 0; m_treeDir.Clear(); return true; }
27.889644
182
0.587361
[ "object", "vector" ]
43168f6a9641a60853fd6d63fe8b466384732551
2,635
hpp
C++
src/3rdparty/torrent-rasterbar/include/libtorrent/session_stats.hpp
adem4ik/LIII
6aed4f91641c63b0e3d8d121769b9ecbb832602f
[ "MIT" ]
664
2017-08-14T22:25:24.000Z
2022-03-29T13:54:39.000Z
src/3rdparty/torrent-rasterbar/include/libtorrent/session_stats.hpp
adem4ik/LIII
6aed4f91641c63b0e3d8d121769b9ecbb832602f
[ "MIT" ]
21
2018-11-05T22:03:20.000Z
2022-03-25T15:04:59.000Z
src/3rdparty/torrent-rasterbar/include/libtorrent/session_stats.hpp
adem4ik/LIII
6aed4f91641c63b0e3d8d121769b9ecbb832602f
[ "MIT" ]
65
2019-07-23T11:56:01.000Z
2022-03-16T06:17:37.000Z
/* Copyright (c) 2012-2016, Arvid Norberg 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 author 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. */ #ifndef TORRENT_SESSION_STATS_HPP_INCLUDED #define TORRENT_SESSION_STATS_HPP_INCLUDED #include "libtorrent/config.hpp" #include <vector> namespace libtorrent { // describes one statistics metric from the session. For more information, // see the session-statistics_ section. struct TORRENT_EXPORT stats_metric { char const* name; int value_index; enum metric_type_t { type_counter, type_gauge }; metric_type_t type; }; // This free function returns the list of available metrics exposed by // libtorrent's statistics API. Each metric has a name and a *value index*. // The value index is the index into the array in session_stats_alert where // this metric's value can be found when the session stats is sampled (by // calling post_session_stats()). TORRENT_EXPORT std::vector<stats_metric> session_stats_metrics(); // given a name of a metric, this function returns the counter index of it, // or -1 if it could not be found. The counter index is the index into the // values array returned by session_stats_alert. TORRENT_EXPORT int find_metric_idx(char const* name); } #endif
38.188406
78
0.781784
[ "vector" ]
431adc3b83b7f24ad9198eeeb2d99fcff9d26119
2,623
cpp
C++
src/webots/core/WbWebotsUpdateManager.cpp
junjihashimoto/webots
12eb8c010275f390ae97d91d5c04906ffa00c262
[ "Apache-2.0" ]
null
null
null
src/webots/core/WbWebotsUpdateManager.cpp
junjihashimoto/webots
12eb8c010275f390ae97d91d5c04906ffa00c262
[ "Apache-2.0" ]
null
null
null
src/webots/core/WbWebotsUpdateManager.cpp
junjihashimoto/webots
12eb8c010275f390ae97d91d5c04906ffa00c262
[ "Apache-2.0" ]
null
null
null
// Copyright 1996-2019 Cyberbotics Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "WbWebotsUpdateManager.hpp" #include "WbNetwork.hpp" #include <QtCore/QCoreApplication> #include <QtCore/QJsonDocument> #include <QtCore/QJsonObject> #include <QtNetwork/QNetworkReply> #include <cassert> WbWebotsUpdateManager *WbWebotsUpdateManager::cInstance = NULL; WbWebotsUpdateManager::WbWebotsUpdateManager() : mVersion(), mTargetVersionAvailable(false), mError() { sendRequest(); } WbWebotsUpdateManager::~WbWebotsUpdateManager() { } WbWebotsUpdateManager *WbWebotsUpdateManager::instance() { if (!cInstance) { cInstance = new WbWebotsUpdateManager(); qAddPostRoutine(WbWebotsUpdateManager::cleanup); } return cInstance; } void WbWebotsUpdateManager::cleanup() { if (cInstance) { delete cInstance; cInstance = NULL; } } void WbWebotsUpdateManager::sendRequest() { QNetworkRequest request; request.setUrl(QUrl("https://api.github.com/repos/cyberbotics/webots/releases/latest")); QNetworkReply *reply = WbNetwork::instance()->networkAccessManager()->get(request); connect(reply, &QNetworkReply::finished, this, &WbWebotsUpdateManager::downloadReplyFinished, Qt::UniqueConnection); } void WbWebotsUpdateManager::downloadReplyFinished() { QNetworkReply *reply = dynamic_cast<QNetworkReply *>(sender()); assert(reply); if (!reply) return; if (reply->error()) { mError = tr("Cannot get the Webots current version due to: \"%1\"").arg(reply->errorString()); return; } disconnect(reply, &QNetworkReply::finished, this, &WbWebotsUpdateManager::downloadReplyFinished); bool success = false; QJsonDocument doc = QJsonDocument::fromJson(reply->readAll()); if (!doc.isNull()) { if (doc.isObject()) { QJsonObject obj = doc.object(); if (obj.contains("tag_name")) success = mVersion.fromString(obj.value("tag_name").toString()); } } if (!success) { mError = tr("Invalid answer from the GitHub REST API."); return; } mError = ""; mTargetVersionAvailable = true; emit targetVersionAvailable(); }
29.47191
118
0.726268
[ "object" ]
431bca9076770c1a91fbf301c785485237aa5188
3,163
cc
C++
test/chef_base_test/chef_stuff_op_test.cc
q191201771/libchef
678a5d92611aa15783ac86f6db362884cf211582
[ "MIT" ]
123
2018-12-28T02:18:10.000Z
2022-03-31T12:04:58.000Z
test/chef_base_test/chef_stuff_op_test.cc
q191201771/libchef
678a5d92611aa15783ac86f6db362884cf211582
[ "MIT" ]
null
null
null
test/chef_base_test/chef_stuff_op_test.cc
q191201771/libchef
678a5d92611aa15783ac86f6db362884cf211582
[ "MIT" ]
30
2019-01-02T10:51:40.000Z
2022-03-29T12:04:40.000Z
#include "chef_base/chef_stuff_op.hpp" #include "chef_base/chef_strings_op.hpp" #include "./common/assert_wrapper.hpp" #include "./common/check_log.hpp" #include <vector> static void example() { } void readable_bytes_test() { assert(chef::stuff_op::readable_bytes(768) == "768.0B"); assert(chef::stuff_op::readable_bytes(10000) == "9.8K"); assert(chef::stuff_op::readable_bytes(100001221) == "95.4M"); assert(chef::stuff_op::readable_bytes(1000) == "1000.0B"); assert(chef::stuff_op::readable_bytes(1023) == "1023.0B"); assert(chef::stuff_op::readable_bytes(1024) == "1.0K"); assert(chef::stuff_op::readable_bytes(1025) == "1.0K"); assert(chef::stuff_op::readable_bytes(1000UL * 1000) == "976.6K"); assert(chef::stuff_op::readable_bytes(1024UL * 1024) == "1.0M"); assert(chef::stuff_op::readable_bytes(1000UL * 1000 * 1000) == "953.7M"); assert(chef::stuff_op::readable_bytes(1024UL * 1024 * 1024) == "1.0G"); assert(chef::stuff_op::readable_bytes(1024UL * 1024 * 1024 + 1000UL * 1000 * 1000) == "1.9G"); assert(chef::stuff_op::readable_bytes(1000UL * 1000 * 1000 * 1000) == "931.3G"); assert(chef::stuff_op::readable_bytes(1024UL * 1024 * 1024 * 1024) == "1.0T"); assert(chef::stuff_op::readable_bytes(1024UL * 1024 * 1024 * 1024 * 1024) == "1.0P"); assert(chef::stuff_op::readable_bytes(1024UL * 1024 * 1024 * 1024 * 1024 * 1024) == "1.0E"); assert(chef::stuff_op::readable_bytes(1024UL * 1024 * 1024 * 1024 * 1024 * 1024 * 15) == "15.0E"); assert(chef::stuff_op::readable_bytes(0UL - 1) == "16.0E"); assert(chef::stuff_op::readable_bytes(18446744073709551615UL) == "16.0E"); } void get_host_by_name_test() { std::vector<std::string> domains = { "http://www.baidu.com/test?a=b", "http://www.baidu.com/test", "http://www.baidu.com/", "http://www.baidu.com", "www.baidu.com", "localhost", "not exist", "58.96.168.38" }; for (auto iter : domains) { std::string ip = chef::stuff_op::get_host_by_name(iter.c_str()); (void)ip; printf("%s: %s\n", iter.c_str(), ip.c_str()); } } int main() { ENTER_TEST; example(); std::cout << "unix timestamp msec:" << chef::stuff_op::unix_timestamp_msec() << std::endl; std::cout << "tick msec:" << chef::stuff_op::tick_msec() << std::endl; std::cout << "tid:" << chef::stuff_op::gettid() << std::endl; chef::stuff_op::set_thread_name("yokothd"); readable_bytes_test(); get_host_by_name_test(); std::cout << "tick msec:" << chef::stuff_op::tick_msec() << std::endl; std::cout << "unix timestamp msec:" << chef::stuff_op::unix_timestamp_msec() << std::endl; char *buf; static const char BUF[] = "1234567890abcdefghijklmn"; //buf = BUF; //buf = chef::PRINTABLE.c_str(); uint8_t buf2[256]; for (std::size_t i = 0; i < 255; i++) { buf2[i] = i; } buf = (char *)buf2; std::string hex; for (std::size_t i = 0; i < 2; i++) { //for (std::size_t j = strlen(buf)-1; j < strlen(buf); j++) { for (std::size_t j = 255; j < 256; j++) { std::cout << "-----\n"; hex = chef::stuff_op::bytes_to_hex((const uint8_t *)buf, j+1, 16, i % 2); std::cout << hex; } } return 0; }
35.539326
100
0.627253
[ "vector" ]
4333aa91d2e77229a5927158e9fef0981d1706c5
5,486
cpp
C++
test/check_numerics_test.cpp
syoyo/MIOpen
8784e34e04ca97ca7db6ece102155c1546074bea
[ "MIT" ]
null
null
null
test/check_numerics_test.cpp
syoyo/MIOpen
8784e34e04ca97ca7db6ece102155c1546074bea
[ "MIT" ]
null
null
null
test/check_numerics_test.cpp
syoyo/MIOpen
8784e34e04ca97ca7db6ece102155c1546074bea
[ "MIT" ]
null
null
null
/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * 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 "test.hpp" #include <miopen/handle.hpp> #include <miopen/check_numerics.hpp> #include <miopen/miopen.h> struct check_numerics_base { static const int size = 42; miopen::Handle h{}; miopen::TensorDescriptor desc{miopenFloat, {size}}; miopen::Allocator::ManageDataPtr buffer = nullptr; check_numerics_base(float val = 0.0) { std::vector<float> data(size, val); buffer = h.Write(data); } }; struct check_numeric_normal : check_numerics_base { check_numeric_normal(float val) : check_numerics_base(val) {} void run() { CHECK( !miopen::checkNumericsImpl(h, miopen::CheckNumerics::Throw, desc, buffer.get(), true)); CHECK( !miopen::checkNumericsImpl(h, miopen::CheckNumerics::Throw, desc, buffer.get(), false)); CHECK(!miopen::checkNumericsImpl(h, miopen::CheckNumerics::Throw | miopen::CheckNumerics::ComputeStats, desc, buffer.get(), true)); CHECK(!miopen::checkNumericsImpl(h, miopen::CheckNumerics::Throw | miopen::CheckNumerics::ComputeStats, desc, buffer.get(), false)); } }; struct check_numeric_abnormal : check_numerics_base { check_numeric_abnormal(float val) : check_numerics_base(val) {} void run() { CHECK(miopen::checkNumericsImpl(h, miopen::CheckNumerics::Warn, desc, buffer.get(), true)); CHECK(miopen::checkNumericsImpl(h, miopen::CheckNumerics::Warn, desc, buffer.get(), false)); CHECK(throws([&] { miopen::checkNumericsImpl(h, miopen::CheckNumerics::Throw, desc, buffer.get(), true); })); CHECK(throws([&] { miopen::checkNumericsImpl(h, miopen::CheckNumerics::Throw, desc, buffer.get(), false); })); CHECK(miopen::checkNumericsImpl(h, miopen::CheckNumerics::Warn | miopen::CheckNumerics::ComputeStats, desc, buffer.get(), true)); CHECK(miopen::checkNumericsImpl(h, miopen::CheckNumerics::Warn | miopen::CheckNumerics::ComputeStats, desc, buffer.get(), false)); CHECK(throws([&] { miopen::checkNumericsImpl(h, miopen::CheckNumerics::Throw | miopen::CheckNumerics::ComputeStats, desc, buffer.get(), true); })); CHECK(throws([&] { miopen::checkNumericsImpl(h, miopen::CheckNumerics::Throw | miopen::CheckNumerics::ComputeStats, desc, buffer.get(), false); })); } }; struct numeric_0 : check_numeric_normal { numeric_0() : check_numeric_normal(0.0) {} }; struct numeric_1 : check_numeric_normal { numeric_1() : check_numeric_normal(1.0) {} }; struct numeric_nan : check_numeric_abnormal { numeric_nan() : check_numeric_abnormal(std::numeric_limits<float>::quiet_NaN()) {} }; struct numeric_inf : check_numeric_abnormal { numeric_inf() : check_numeric_abnormal(std::numeric_limits<float>::infinity()) {} }; int main() { run_test<numeric_0>(); run_test<numeric_1>(); run_test<numeric_nan>(); run_test<numeric_inf>(); }
37.319728
100
0.518593
[ "vector" ]
4339335f3c8a3094b0443036ccd65d6412c7c8b6
1,030
cpp
C++
SQLWindows.UserInterface/SQLWindows.UserInterface/MessageBox.cpp
t-mxcom/SQLWindows.UserInterface
4d0aff61056aa5fd1f4fdd189d26dbf37adcc6bc
[ "MIT" ]
null
null
null
SQLWindows.UserInterface/SQLWindows.UserInterface/MessageBox.cpp
t-mxcom/SQLWindows.UserInterface
4d0aff61056aa5fd1f4fdd189d26dbf37adcc6bc
[ "MIT" ]
null
null
null
SQLWindows.UserInterface/SQLWindows.UserInterface/MessageBox.cpp
t-mxcom/SQLWindows.UserInterface
4d0aff61056aa5fd1f4fdd189d26dbf37adcc6bc
[ "MIT" ]
null
null
null
#include "stdafx.h" #define INCLUDE_EXTMSGBOX #include "Prof-UIS.h" extern "C" __declspec(dllexport) int WINAPI UISalMessageBoxEx(HWND parentWindow, LPCWSTR message, LPCWSTR caption, UINT style, UINT helpID, LPCWSTR uniqueID, UINT extendedStyle, UINT timeout, BOOL buttonsDisabledDuringTimeout, HICON icon) { // prepare icon if HICON was passed CExtBitmap* customIcon = NULL; if (icon != NULL) { // create object customIcon = new CExtBitmap(); customIcon->AssignFromHICON(icon, false); } // create message box object CExtMsgBox* messageBox = new CExtMsgBox( parentWindow, message, caption, style, helpID, uniqueID, extendedStyle); // show message box int result = messageBox->DoMsgBox( parentWindow, message, caption, style, helpID, uniqueID, extendedStyle, timeout, buttonsDisabledDuringTimeout, customIcon); delete messageBox; messageBox = NULL; // free icon object if created if (customIcon != NULL) { // free object delete customIcon; } return (DWORD)result; }
20.6
238
0.728155
[ "object" ]
433aa7cc4c189149b1692163e7e142e481556f63
12,454
hpp
C++
ImGuiBuilder/third-party/rapidfuzz/rapidfuzz/details/string_metrics/weighted_levenshtein_impl.hpp
NukeULater/ImGuiBuilder
8a086a1593df6adfabb58276a2f315c93e603033
[ "MIT" ]
null
null
null
ImGuiBuilder/third-party/rapidfuzz/rapidfuzz/details/string_metrics/weighted_levenshtein_impl.hpp
NukeULater/ImGuiBuilder
8a086a1593df6adfabb58276a2f315c93e603033
[ "MIT" ]
null
null
null
ImGuiBuilder/third-party/rapidfuzz/rapidfuzz/details/string_metrics/weighted_levenshtein_impl.hpp
NukeULater/ImGuiBuilder
8a086a1593df6adfabb58276a2f315c93e603033
[ "MIT" ]
null
null
null
/* SPDX-License-Identifier: MIT */ /* Copyright © 2021 Max Bachmann */ #include <rapidfuzz/details/common.hpp> #include <rapidfuzz/details/intrinsics.hpp> #include <algorithm> #include <array> #include <limits> #include <stdexcept> #include <string> namespace rapidfuzz { namespace string_metric { namespace detail { /* * An encoded mbleven model table. * * Each 8-bit integer represents an edit sequence, with using two * bits for a single operation. * * Each Row of 8 integers represent all possible combinations * of edit sequences for a gived maximum edit distance and length * difference between the two strings, that is below the maximum * edit distance * * 0x1 = 01 = DELETE, * 0x2 = 10 = INSERT * * 0x5 -> DEL + DEL * 0x6 -> DEL + INS * 0x9 -> INS + DEL * 0xA -> INS + INS */ static constexpr uint8_t weighted_levenshtein_mbleven2018_matrix[14][7] = { /* max edit distance 1 */ {0}, /* case does not occur */ /* len_diff 0 */ {0x01}, /* len_diff 1 */ /* max edit distance 2 */ {0x09, 0x06}, /* len_diff 0 */ {0x01}, /* len_diff 1 */ {0x05}, /* len_diff 2 */ /* max edit distance 3 */ {0x09, 0x06}, /* len_diff 0 */ {0x25, 0x19, 0x16}, /* len_diff 1 */ {0x05}, /* len_diff 2 */ {0x15}, /* len_diff 3 */ /* max edit distance 4 */ {0x96, 0x66, 0x5A, 0x99, 0x69, 0xA5}, /* len_diff 0 */ {0x25, 0x19, 0x16}, /* len_diff 1 */ {0x65, 0x56, 0x95, 0x59}, /* len_diff 2 */ {0x15}, /* len_diff 3 */ {0x55}, /* len_diff 4 */ }; template <typename CharT1, typename CharT2> std::size_t weighted_levenshtein_mbleven2018(basic_string_view<CharT1> s1, basic_string_view<CharT2> s2, std::size_t max) { if (s1.size() < s2.size()) { return weighted_levenshtein_mbleven2018(s2, s1, max); } std::size_t len_diff = s1.size() - s2.size(); auto possible_ops = weighted_levenshtein_mbleven2018_matrix[(max + max * max) / 2 + len_diff - 1]; std::size_t dist = max + 1; for (int pos = 0; possible_ops[pos] != 0; ++pos) { int ops = possible_ops[pos]; std::size_t s1_pos = 0; std::size_t s2_pos = 0; std::size_t cur_dist = 0; while (s1_pos < s1.size() && s2_pos < s2.size()) { if (common::mixed_sign_unequal(s1[s1_pos], s2[s2_pos])) { cur_dist++; if (!ops) break; if (ops & 1) s1_pos++; else if (ops & 2) s2_pos++; ops >>= 2; } else { s1_pos++; s2_pos++; } } cur_dist += (s1.size() - s1_pos) + (s2.size() - s2_pos); dist = (std::min)(dist, cur_dist); } return (dist > max) ? (std::size_t)-1 : dist; } template <std::size_t N, typename CharT1> static inline std::size_t longest_common_subsequence_unroll(basic_string_view<CharT1> s1, const common::PatternMatchVector* block, std::size_t s2_len) { std::uint64_t S[N]; for (std::size_t i = 0; i < N; ++i) { S[i] = ~0x0ull; } for (const auto& ch1 : s1) { uint64_t carry = 0; std::uint64_t Matches[N]; std::uint64_t u[N]; std::uint64_t x[N]; for (std::size_t i = 0; i < N; ++i) { Matches[i] = block[i].get(ch1); u[i] = S[i] & Matches[i]; x[i] = intrinsics::addc64(S[i], u[i], carry, &carry); S[i] = x[i] | (S[i] - u[i]); } } std::size_t res = 0; for (std::size_t i = 0; i < N; ++i) { res += intrinsics::popcount64(~S[i]); } return s1.size() + s2_len - 2 * res; } template <typename CharT1> static inline std::size_t longest_common_subsequence_blockwise(basic_string_view<CharT1> s1, const common::BlockPatternMatchVector& block, std::size_t s2_len) { std::size_t words = block.m_val.size(); std::vector<std::uint64_t> S(words, ~0x0ull); for (const auto& ch1 : s1) { uint64_t carry = 0; for (std::size_t word = 0; word < words; ++word) { const uint64_t Matches = block.get(word, ch1); uint64_t Stemp = S[word]; uint64_t u = Stemp & Matches; uint64_t x = intrinsics::addc64(Stemp, u, carry, &carry); S[word] = x | (Stemp - u); } } std::size_t res = 0; for (uint64_t Stemp : S) { res += intrinsics::popcount64(~Stemp); } return s1.size() + s2_len - 2 * res; } template <typename CharT1> std::size_t longest_common_subsequence(basic_string_view<CharT1> s1, const common::BlockPatternMatchVector& block, std::size_t s2_len) { switch(block.m_val.size()) { case 1: return longest_common_subsequence_unroll<1>(s1, &block.m_val[0], s2_len); case 2: return longest_common_subsequence_unroll<2>(s1, &block.m_val[0], s2_len); case 3: return longest_common_subsequence_unroll<3>(s1, &block.m_val[0], s2_len); case 4: return longest_common_subsequence_unroll<4>(s1, &block.m_val[0], s2_len); case 5: return longest_common_subsequence_unroll<5>(s1, &block.m_val[0], s2_len); case 6: return longest_common_subsequence_unroll<6>(s1, &block.m_val[0], s2_len); case 7: return longest_common_subsequence_unroll<7>(s1, &block.m_val[0], s2_len); case 8: return longest_common_subsequence_unroll<8>(s1, &block.m_val[0], s2_len); default: return longest_common_subsequence_blockwise(s1, block, s2_len); } } template <typename CharT1, typename CharT2> std::size_t longest_common_subsequence(basic_string_view<CharT1> s1, basic_string_view<CharT2> s2) { std::size_t nr = (s2.size() / 64) + (std::size_t)((s2.size() % 64) > 0); switch(nr) { case 1: { auto block = common::PatternMatchVector(s2); return longest_common_subsequence_unroll<1>(s1, &block, s2.size()); } case 2: { auto block = common::BlockPatternMatchVector(s2); return longest_common_subsequence_unroll<2>(s1, &block.m_val[0], s2.size()); } case 3: { auto block = common::BlockPatternMatchVector(s2); return longest_common_subsequence_unroll<3>(s1, &block.m_val[0], s2.size()); } case 4: { auto block = common::BlockPatternMatchVector(s2); return longest_common_subsequence_unroll<4>(s1, &block.m_val[0], s2.size()); } case 5: { auto block = common::BlockPatternMatchVector(s2); return longest_common_subsequence_unroll<5>(s1, &block.m_val[0], s2.size()); } case 6: { auto block = common::BlockPatternMatchVector(s2); return longest_common_subsequence_unroll<6>(s1, &block.m_val[0], s2.size()); } case 7: { auto block = common::BlockPatternMatchVector(s2); return longest_common_subsequence_unroll<7>(s1, &block.m_val[0], s2.size()); } case 8: { auto block = common::BlockPatternMatchVector(s2); return longest_common_subsequence_unroll<8>(s1, &block.m_val[0], s2.size()); } default: { auto block = common::BlockPatternMatchVector(s2); return longest_common_subsequence_blockwise(s1, block, s2.size()); } } } // TODO this implementation needs some cleanup template <typename CharT1, typename CharT2> std::size_t weighted_levenshtein(basic_string_view<CharT1> s1, const common::BlockPatternMatchVector& block, basic_string_view<CharT2> s2, std::size_t max) { // when no differences are allowed a direct comparision is sufficient if (max == 0) { if (s1.size() != s2.size()) { return (std::size_t)-1; } return std::equal(s1.begin(), s1.end(), s2.begin()) ? 0 : (std::size_t)-1; } // when the strings have a similar length each difference causes // at least a edit distance of 2, so a direct comparision is sufficient if (max == 1) { if (s1.size() == s2.size()) { return std::equal(s1.begin(), s1.end(), s2.begin()) ? 0 : (std::size_t)-1; } } // at least length difference insertions/deletions required std::size_t len_diff = (s1.size() < s2.size()) ? s2.size() - s1.size() : s1.size() - s2.size(); if (len_diff > max) { return (std::size_t)-1; } // important to catch, since this causes block.m_val to be empty -> raises exception on access if (s2.empty()) { return s1.size(); } // do this first, since we can not remove any affix in encoded form if (max >= 5) { std::size_t dist = longest_common_subsequence(s1, block, s2.size()); return (dist > max) ? (std::size_t)-1 : dist; } // The Levenshtein distance between <prefix><string1><suffix> and <prefix><string2><suffix> // is similar to the distance between <string1> and <string2>, so they can be removed in linear // time common::remove_common_affix(s1, s2); if (s2.empty()) { return s1.size(); } if (s1.empty()) { return s2.size(); } return weighted_levenshtein_mbleven2018(s1, s2, max); } template <typename CharT1, typename CharT2> std::size_t weighted_levenshtein(basic_string_view<CharT1> s1, basic_string_view<CharT2> s2, std::size_t max) { // Swapping the strings so the second string is shorter if (s1.size() < s2.size()) { return weighted_levenshtein(s2, s1, max); } // when no differences are allowed a direct comparision is sufficient if (max == 0) { if (s1.size() != s2.size()) { return (std::size_t)-1; } return std::equal(s1.begin(), s1.end(), s2.begin()) ? 0 : (std::size_t)-1; } // when the strings have a similar length each difference causes // at least a edit distance of 2, so a direct comparision is sufficient if (max == 1) { if (s1.size() == s2.size()) { return std::equal(s1.begin(), s1.end(), s2.begin()) ? 0 : (std::size_t)-1; } } // at least length difference insertions/deletions required if (s1.size() - s2.size() > max) { return (std::size_t)-1; } // The Levenshtein distance between <prefix><string1><suffix> and <prefix><string2><suffix> // is similar to the distance between <string1> and <string2>, so they can be removed in linear // time common::remove_common_affix(s1, s2); if (s2.empty()) { return s1.size(); } if (max < 5) { return weighted_levenshtein_mbleven2018(s1, s2, max); } std::size_t dist = longest_common_subsequence(s1, s2); return (dist > max) ? (std::size_t)-1 : dist; } template <typename CharT1, typename CharT2> double normalized_weighted_levenshtein(basic_string_view<CharT1> s1, const common::BlockPatternMatchVector& block, basic_string_view<CharT2> s2, const double score_cutoff) { if (s1.empty() || s2.empty()) { return static_cast<double>(s1.empty() && s2.empty()); } std::size_t lensum = s1.size() + s2.size(); auto cutoff_distance = common::score_cutoff_to_distance(score_cutoff, lensum); std::size_t dist = weighted_levenshtein(s1, block, s2, cutoff_distance); return (dist <= cutoff_distance) ? common::norm_distance(dist, lensum, score_cutoff) : 0.0; } template <typename CharT1, typename CharT2> double normalized_weighted_levenshtein(basic_string_view<CharT1> s1, basic_string_view<CharT2> s2, const double score_cutoff) { if (s1.empty() || s2.empty()) { return static_cast<double>(s1.empty() && s2.empty()); } std::size_t lensum = s1.size() + s2.size(); auto cutoff_distance = common::score_cutoff_to_distance(score_cutoff, lensum); std::size_t dist = weighted_levenshtein(s1, s2, cutoff_distance); return (dist <= cutoff_distance) ? common::norm_distance(dist, lensum, score_cutoff) : 0.0; } } // namespace detail } // namespace string_metric } // namespace rapidfuzz
32.94709
99
0.58704
[ "vector", "model" ]
433d170ad36478f737cfb69fe36398eb6fe662e5
20,285
hh
C++
include/webster.hh
brunexgeek/webster
51592927272355ddf59be2c1c4b604bd70814d7d
[ "Apache-2.0" ]
3
2018-10-30T05:46:40.000Z
2020-06-27T13:27:22.000Z
source/webster.hh
brunexgeek/dns-blocker
d4a94489e6eb18c9abd97b5fc424b5d7441b26b6
[ "Apache-2.0" ]
1
2020-12-22T14:04:16.000Z
2020-12-22T14:04:16.000Z
source/webster.hh
brunexgeek/dns-blocker
d4a94489e6eb18c9abd97b5fc424b5d7441b26b6
[ "Apache-2.0" ]
2
2018-10-30T05:46:42.000Z
2021-06-14T02:43:20.000Z
/* * Copyright 2020 Bruno Ribeiro * <https://github.com/brunexgeek/webster> * * 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 WEBSTER_API_HH #define WEBSTER_API_HH #if defined(_MSC_VER) || defined(WIN32) || defined(_WIN32) #define WEBSTER_PRIVATE #define WB_WINDOWS 1 #else #define WEBSTER_PRIVATE __attribute__((__visibility__("hidden"))) #endif #include <stdint.h> #include <stddef.h> #include <functional> #include <string> #include <type_traits> /// Operation completed with success. const int WBERR_OK = 0; const int WBERR_INVALID_ARGUMENT = -1; const int WBERR_MEMORY_EXHAUSTED = -2; const int WBERR_INVALID_ADDRESS = -3; const int WBERR_SOCKET = -4; /// The communication was completed with success and the connection will be closed. const int WBERR_COMPLETE = -6; const int WBERR_TOO_LONG = -7; const int WBERR_TIMEOUT = -11; const int WBERR_INVALID_STATE = -12; const int WBERR_INVALID_HTTP_METHOD = -14; const int WBERR_INVALID_HTTP_VERSION = -16; const int WBERR_INVALID_HTTP_MESSAGE = -17; const int WBERR_INVALID_TARGET = -18; const int WBERR_INVALID_SCHEME = -19; const int WBERR_INVALID_HOST = -20; const int WBERR_INVALID_PORT = -21; const int WBERR_INVALID_CHANNEL = -22; const int WBERR_REFUSED = -23; const int WBERR_UNREACHABLE = -24; const int WBERR_IN_PROGRESS = -25; const int WBERR_ADDRESS_IN_USE = -27; const int WBERR_INVALID_CHUNK = -28; const int WBERR_NOT_CONNECTED = -29; const int WBERR_SIGNAL = -30; const int WBERR_INVALID_HTTP_FIELD = -32; const int WBERR_PERMISSION = -31; const int WBERR_INVALID_HANDLER = -33; const int WBERR_NOT_IMPLEMENTED = -34; const int WBERR_NO_RESOURCES = -35; const int WBERR_ALREADY_CONNECTED = -36; const int WBERR_INVALID_PROTOCOL = -37; const int WBERR_UPGRADED = -38; const int WBERR_READ_ONLY = -39; const int WBERR_WRITE_ONLY = -40; /** * HTTP header field identifier. */ enum FieldID { WBFI_NON_STANDARD = 0, WBFI_ACCEPT, WBFI_ACCEPT_CHARSET, WBFI_ACCEPT_ENCODING, WBFI_ACCEPT_LANGUAGE, WBFI_ACCEPT_PATCH, WBFI_ACCEPT_RANGES, WBFI_ACCESS_CONTROL_ALLOW_CREDENTIALS, WBFI_ACCESS_CONTROL_ALLOW_HEADERS, WBFI_ACCESS_CONTROL_ALLOW_METHODS, WBFI_ACCESS_CONTROL_ALLOW_ORIGIN, WBFI_ACCESS_CONTROL_EXPOSE_HEADERS, WBFI_ACCESS_CONTROL_MAX_AGE, WBFI_ACCESS_CONTROL_REQUEST_HEADERS, WBFI_ACCESS_CONTROL_REQUEST_METHOD, WBFI_AGE, // RFC-7234 WBFI_ALLOW, WBFI_ALT_SVC, WBFI_AUTHORIZATION, WBFI_CACHE_CONTROL, WBFI_CONNECTION, WBFI_CONTENT_DISPOSITION, WBFI_CONTENT_ENCODING, WBFI_CONTENT_LANGUAGE, WBFI_CONTENT_LENGTH, WBFI_CONTENT_LOCATION, WBFI_CONTENT_RANGE, WBFI_CONTENT_TYPE, WBFI_COOKIE, WBFI_DATE, WBFI_DNT, WBFI_ETAG, WBFI_EXPECT, WBFI_EXPIRES, WBFI_FORWARDED, WBFI_FROM, WBFI_HOST, WBFI_IF_MATCH, WBFI_IF_MODIFIED_SINCE, WBFI_IF_NONE_MATCH, WBFI_IF_RANGE, WBFI_IF_UNMODIFIED_SINCE, WBFI_LAST_MODIFIED, WBFI_LINK, WBFI_LOCATION, WBFI_MAX_FORWARDS, WBFI_ORIGIN, WBFI_PRAGMA, WBFI_PROXY_AUTHENTICATE, WBFI_PROXY_AUTHORIZATION, WBFI_PUBLIC_KEY_PINS, WBFI_RANGE, WBFI_REFERER, WBFI_RETRY_AFTER, WBFI_SERVER, WBFI_SET_COOKIE, WBFI_STRICT_TRANSPORT_SECURITY, WBFI_TE, WBFI_TK, WBFI_TRAILER, WBFI_TRANSFER_ENCODING, WBFI_UPGRADE, WBFI_UPGRADE_INSECURE_REQUESTS, WBFI_USER_AGENT, WBFI_VARY, WBFI_VIA, WBFI_WARNING, WBFI_WWW_AUTHENTICATE, }; // Request target types const int WBRT_ORIGIN = 0x01; const int WBRT_AUTHORITY = 0x02; const int WBRT_ABSOLUTE = (WBRT_ORIGIN + 0x04 + WBRT_AUTHORITY); const int WBRT_ASTERISK = 0x08; // Schemas const int WBS_AUTO = 0; const int WBS_HTTP = 1; const int WBS_HTTPS = 2; // Limits const int WBL_MIN_BUFFER_SIZE = 64; const int WBL_MAX_BUFFER_SIZE = 10485760; // 10 MB const int WBL_DEF_BUFFER_SIZE = 4096; // 4KB const int WBL_MAX_CONNECTIONS = 10000; const int WBL_DEF_CONNECTIONS = 200; const int WBL_DEF_TIMEOUT = 10000; // 10 sec const int WBL_MAX_TIMEOUT = 620000; // 10 minutes #include <memory> #include <map> #include <string> #include <vector> #include <stdint.h> namespace webster { WEBSTER_PRIVATE uint64_t tick(); WEBSTER_PRIVATE int strcmpi(const char *s1, const char *s2); struct Target { int type; int scheme; std::string user; std::string host; int port; std::string path; std::string query; Target(); Target( const Target & ) = default; Target( Target && ) = default; Target &operator=( const Target & ) = default; static int parse( const char *url, Target &target ); // TODO: make this dynamic static int parse( const std::string &url, Target &target ); // TODO: make this dynamic static std::string encode( const std::string & value ); static std::string decode( const std::string & value ); void swap( Target &that ); void clear(); }; class Channel {}; /** * Abstraction for network adapters. */ class Network { public: enum Type { CLIENT, SERVER }; /** * Create a channel. * * @returns WBERR_OK on success; error code otherwise. */ virtual int open( Channel **channel, Type type ) = 0; /** * Close and destroy a channel. * * @returns WBERR_OK on success; error code otherwise. */ virtual int close( Channel *channel ) = 0; /** * Connect to a HTTP server. * * @returns WBERR_OK on success; error code otherwise. */ virtual int connect( Channel *channel, int scheme, const char *host, int port, int timeout ) = 0; /** * Receive data. * * @param channel Pointer to the channel. * @param buffer Pointer to the destination buffer. * @param size Buffer size. * @param received Pointer to store the amount of data retrieved. * @param timeout Aproximated number of milliseconds the function will block * waiting for data. * @returns WBERR_OK on success; error code otherwise. */ virtual int receive( Channel *channel, uint8_t *buffer, int size, int *received, int timeout ) = 0; /** * Write data. * * This function will succeed only if all data is written. * * @param channel Pointer to the channel. * @param buffer Pointer to the destination buffer. * @param size Buffer size. * @param timeout Aproximated number of milliseconds the function will block * writing data. * @returns WBERR_OK on success; error code otherwise. */ virtual int send( Channel *channel, const uint8_t *buffer, int size, int timeout ) = 0; /** * Accept client connections. * * This function will return if interrupted by signals. * * @param channel Pointer to the channel. * @param channel Pointer to the new channel. * @param timeout Aproximated number of milliseconds the function will block * waiting for connections. */ virtual int accept( Channel *channel, Channel **client, int timeout ) = 0; virtual int listen( Channel *channel, const char *host, int port, int maxClients ) = 0; }; struct Parameters { /** * Pointer to custom network implementation. * * Set to 'nullptr' to use the default implementation. Note that the default * implementation is not available if 'WEBSTER_NO_DEFAULT_NETWORK' is set. */ std::shared_ptr<Network> network; /** * Maximum number of remote clients in the server queue. The default value is * WBL_DEF_CONNECTIONS. */ int max_clients; /** * Size (in bytes) of the message internal output buffer. The default value * is WBL_DEF_BUFFER_SIZE. */ int buffer_size; /** * Read timeout in milliseconds (between 1 and ``WBL_MAX_TIMEOUT``). */ int read_timeout; /** * Write timeout in milliseconds (between 1 and ``WBL_MAX_TIMEOUT``). */ int write_timeout; /** * Connection timeout in milliseconds (between 1 and ``WBL_MAX_TIMEOUT``). */ int connect_timeout; Parameters(); Parameters( const Parameters &that ); Parameters &operator=( const Parameters &that ); }; enum Protocol { WBCP_NONE, // No protocol WBCP_HTTP_1 // HTTP 1.1 }; enum ClientType { /// Client used to connect to a remote host. WBCT_LOCAL, /// Client trying to connect the server. WBCT_REMOTE, }; class Client; class Server; enum Method { WBM_NONE = 0, WBM_GET = 1, WBM_HEAD = 2, WBM_POST = 3, WBM_PUT = 4, WBM_DELETE = 5, WBM_CONNECT = 6, WBM_OPTIONS = 7, WBM_TRACE = 8, WBM_PATCH = 9, }; struct less { typedef std::string first_argument_type; typedef std::string second_argument_type; typedef bool result_type; bool operator() (const std::string& x, const std::string& y) const { return strcmpi(x.c_str(), y.c_str()) < 0; } }; class HeaderFields : public std::map<std::string, std::string, webster::less> { public: using std::map<std::string, std::string, webster::less>::count; std::string get( const std::string &name ) const; std::string get( FieldID id ) const; std::string get( const std::string &name, const std::string &value ) const; std::string get( FieldID id, const std::string &value ) const; template<typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0> T get( const std::string &name, T value ) const { auto it = find(name); if (it == end()) return value; return (T) strtol(it->second.c_str(), nullptr, 10); } template<typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0> T get( FieldID id, T value ) const { return get(get_name(id), value); } void set( const std::string &name, const std::string &value ); void set( FieldID id, const std::string &value ); template<typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0> void set( const std::string &name, T value ) { set(name, std::to_string(value)); } template<typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0> void set( FieldID id, T value ) { set(get_name(id), std::to_string(value)); } size_t count( FieldID id ) const; static const char *get_name( FieldID id ); }; struct Header { Target target; int status; HeaderFields fields; Method method; Header(); Header( const Header & ) = default; Header( Header && ) = default; Header &operator=( const Header & ) = default; void swap( Header &that ); void clear(); }; class Message { public: Header header; virtual ~Message() = default; /** * Try to read bytes from the message. * * @param buffer Pointer to destination buffer . * @param size Buffer size. * @returns Positive number of bytes read or a negative error code. */ virtual int read( uint8_t *buffer, int size ) = 0; /** * Try to read bytes from the message. * * This function may read less bytes than requested. * * Although the buffer is a 'char' array, this function reads data * as binary. Thus, the output buffer may contain null characters. * * The output buffer is guaranteed to have a null terminator after * a successfully call. * * @param buffer Pointer to destination buffer . * @param size Buffer size. * @returns Positive number of bytes read or a negative error code. */ virtual int read( char *buffer, int size ) = 0; /** * Read the remaining data to a 'std::vector<uint8>' object. * * @param buffer Vector object to store the data. * @returns WBERR_OK if succeed or a negative error code. */ virtual int read_all( std::vector<uint8_t> &buffer ) = 0; /** * Read the remaining data to a 'std::string' object. * * Although the buffer is a string object, this function reads data * as binary. Thus, the output buffer may contain null characters. * * @param buffer String object to store the data. * @returns WBERR_OK if succeed or a negative error code. */ virtual int read_all( std::string &buffer ) = 0; virtual int write( const uint8_t *buffer, int size ) = 0; virtual int write( const char *buffer ) = 0; virtual int write( const std::string &buffer ) = 0; virtual int write( const std::vector<uint8_t> &buffer ) = 0; template<typename T, typename std::enable_if<std::is_integral<T>::value, bool>::type = true> int write( const T &value ) { return write(std::to_string(value)); } /** * Wait until the message body is ready to be read or written. * * This function will block the execution until the message body is ready. * The amount of time the function waits is the read or write timeout, * depending on the message type (incomming or outgoing). * * For incomming messages, the HTTP header will be completely received. * For outgoing messages, this function will force the HTTP header to be sent. */ virtual int ready() = 0; /** * Send all buffered data of the outgoing message. * * By default, every write call is buffered and no data is sent until * the buffer is full. This function force the current buffer content * be sent. * * This function will force the HTTP header to be sent. */ virtual int flush() = 0; /** * Finish the message by discarding or writing necessary data. * * For incomming messages, this function discard all incomming body data * until the end of the message. * * For outgoing messages, this function write any necessary data and * complete the message. No more data can be written after this call. */ virtual int finish() = 0; Message &operator<<( const std::string &value ) { write(value); return *this; } Message &operator<<( const char &value ) { write(value); return *this; } template<typename T, typename std::enable_if<std::is_integral<T>::value, bool>::type = true> Message &operator<<( const T &value ) { write(value); return *this; } }; class HttpListener { public: HttpListener() = default; HttpListener( const HttpListener & ) = default; HttpListener( HttpListener && ) = default; HttpListener( std::function<int(Message&,Message&)> ); HttpListener( int (&func)(Message&,Message&) ); /** * Perform an HTTP comunication between client and server. * * For local clients, the listener must generate a request and process the response. * For remote clients, the listener must process the request and generate a response. * * @param request Request messages. * @param response Response messages. * @return WBERR_OK or WBERR_COMPLETE in case of success. An error code otherwhise. */ virtual int operator()(Message &request, Message &response); protected: std::function<int(Message&,Message&)> func_; }; class HttpServer; class HttpClient { public: HttpClient( ClientType type = WBCT_LOCAL, Client *client = nullptr ); ~HttpClient(); /** * Connect to a remote host. * * @param url URL to the remote host. * @param params Network parameters. * @return WBERR_OK in case of success. An error code otherwhise. */ int open( const char *url, const Parameters &params = Parameters() ); /** * Connect to a remote host. * * @param url URL to the remote host. * @param params Network parameters. * @return WBERR_OK in case of success. An error code otherwhise. */ int open( const Target &url, const Parameters &params = Parameters() ); /** * Close the connection with the HTTP server. * * @return WBERR_OK in case of success. An error code otherwhise. */ int close(); /** * Perform an HTTP comunication between client and server. * * If this is a local client, the listener must generate a request and process the response. * If this is a remote client, the listener must process the request and generate a response. * * The path to the resource is obtained from the connection URL. * * @param listener Listener to process the messages. * @return WBERR_OK or WBERR_COMPLETE in case of success. An error code otherwhise. */ int communicate( HttpListener &listener ); /** * Perform an HTTP comunication between client and server. * * If this is a local client, the listener must generate a request and process the response. * If this is a remote client, the listener must process the request and generate a response. * * @param path Path to the resource. * @param listener Listener to process the messages. * @return WBERR_OK or WBERR_COMPLETE in case of success. An error code otherwhise. */ int communicate( const std::string &path, HttpListener &listener ); /** * Returns the protocol implemented by the client. * * @return Protocol code. */ Protocol get_protocol() const; /** * Returns the pointer to the internal client object. * * @return Pointer to client object. If the client is not connected, returns nullptr. */ Client *get_client(); /** * Returns the client type; * * @returns WBCT_LOCAL for local client or WBCT_REMOTE for remote client. */ ClientType get_type() const; protected: Client *client_; Protocol proto_; ClientType type_; int communicate_local( const std::string &path, HttpListener &listener ); int communicate_remote( HttpListener &listener ); }; class HttpServer { public: HttpServer(); HttpServer( Parameters params ); ~HttpServer(); int start( const Target &target ); int start( const std::string &target ); int stop(); int accept( HttpClient **remote ); const Parameters &get_parameters() const; const Target &get_target() const; protected: Server *server_; }; } // namespace webster #endif // WEBSTER_API_HH
32.147385
107
0.61824
[ "object", "vector" ]
4341262323a14fe31deb081a5236dc0cca7915d0
2,009
cpp
C++
String Search Comparison/strings/utils.cpp
Paddylonglegs/CMP202-Threaded-Boyer-Moore-Horspool-Algorithm
cb3ce6fe0d4e0537b67162e354001265f1075edf
[ "MIT" ]
null
null
null
String Search Comparison/strings/utils.cpp
Paddylonglegs/CMP202-Threaded-Boyer-Moore-Horspool-Algorithm
cb3ce6fe0d4e0537b67162e354001265f1075edf
[ "MIT" ]
null
null
null
String Search Comparison/strings/utils.cpp
Paddylonglegs/CMP202-Threaded-Boyer-Moore-Horspool-Algorithm
cb3ce6fe0d4e0537b67162e354001265f1075edf
[ "MIT" ]
null
null
null
/* ©️license MIT https://github.com/Paddylonglegs/ */ #include <cstdlib> #include <fstream> #include <iostream> #include <string> #include <vector> #include "utils.h" using std::cerr; using std::cout; using std::ifstream; using std::string; using std::vector; void die(const string& msg) { cerr << "Error: " << msg << "\n"; #ifdef _DEBUG abort(); #else exit(1); #endif } void load_file(const string& filename, string& str) { // To make this program less fussy about where exactly it's run // from relative to the file, try looking in parent directories too. std::string directory = ""; for (int i = 0; i < 6; i++) { ifstream f(directory + filename, std::ios_base::binary); if (!f.good()) { directory = "../" + directory; continue; } // Seek to the end of the file to find its length. f.seekg(0, std::ios_base::end); const size_t length = f.tellg(); // Seek back to the start of the file and read the data. vector<char> buf(length); f.seekg(0); f.read(buf.data(), length); str.assign(buf.begin(), buf.end()); return; } die("Unable to find " + filename); } void load_jute_book(string& str) { // Read the whole file into str. load_file("jute-book.txt", str); // Extract only the main text of the book, removing the Project Gutenberg // header/footer and indices. str = str.substr(0x4d7); } void show_context(const string& str, Position pos) { const int width = 76; Position left = pos - (width / 2); Position right = pos + (width / 2); Position len = str.size(); for (Position i = left; i < right; ++i) { if (i < 0 || i >= len) { cout << ' '; continue; } char c = str[i]; if (c >= 32 && c < 128) { cout << c; } else { // Show control characters as @s. cout << '@'; } } cout << '\n'; for (Position i = left; i < right; ++i) { if (i < pos) { cout << ' '; } else if (i == pos) { cout << "^ " << pos; } } cout << '\n'; }
21.836957
75
0.577899
[ "vector" ]
4344afb4ab925a60be43a668e926f7b67809c7bb
31,717
cpp
C++
Windows/Eudora71/Eudora/QCMailboxTreeCtrl.cpp
officialrafsan/EUDORA
bf43221f5663ec2338aaf90710a89d1490b92ed2
[ "MIT" ]
1
2022-01-18T08:16:18.000Z
2022-01-18T08:16:18.000Z
Windows/Eudora71/Eudora/QCMailboxTreeCtrl.cpp
officialrafsan/EUDORA
bf43221f5663ec2338aaf90710a89d1490b92ed2
[ "MIT" ]
null
null
null
Windows/Eudora71/Eudora/QCMailboxTreeCtrl.cpp
officialrafsan/EUDORA
bf43221f5663ec2338aaf90710a89d1490b92ed2
[ "MIT" ]
null
null
null
// QCMailboxTreeCtrl.cpp // // Smart mailbox-specific tree control that is meant to be embedded // in a parent "dialog" class. // // Copyright (c) 1997-2000 by QUALCOMM, Incorporated /* Copyright (c) 2016, Computer History Museum All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) 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 Computer History Museum nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. 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 "stdafx.h" #include "resource.h" #include "QCMailboxTreeCtrl.h" #include "QCMailboxCommand.h" #include "QCMailboxDirector.h" #include "mboxtree.h" #include "DynamicMailboxMenu.h" #include "fileutil.h" #ifdef IMAP4 #include "QCImapMailboxCommand.h" #include "ImapMailbox.h" #endif // IMAP4 #include "DebugNewHelpers.h" extern CString EudoraDirNoBackslash; // avoids inclusion of fileutil.h extern QCMailboxDirector g_theMailboxDirector; IMPLEMENT_DYNAMIC( QCMailboxTreeCtrl, QCTreeCtrl ) BEGIN_MESSAGE_MAP(QCMailboxTreeCtrl, QCTreeCtrl) //{{AFX_MSG_MAP(QCMailboxTreeCtrl) ON_NOTIFY_REFLECT(TVN_ITEMEXPANDED, OnItemExpanded) ON_WM_DESTROY() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // QCMailboxTreeCtrl QCMailboxTreeCtrl::QCMailboxTreeCtrl() { m_hRecentFolderItem = NULL; } QCMailboxTreeCtrl::~QCMailboxTreeCtrl() { } //////////////////////////////////////////////////////////////////////// // Init [public, virtual] // //////////////////////////////////////////////////////////////////////// BOOL QCMailboxTreeCtrl::Init() { if (! QCTreeCtrl::Init()) return FALSE; // // Add the bitmap images for tree control. // if (! m_ImageList.Load()) { return FALSE; // mangled resources? } SetImageList( &m_ImageList, TVSIL_NORMAL); return TRUE; } //////////////////////////////////////////////////////////////////////// // Reset [public] // // Delete all tree items and their lParam-based storage from this // tree control. Clients should not call the DeleteItem() or // DeleteAllItems() methods directly. // //////////////////////////////////////////////////////////////////////// BOOL QCMailboxTreeCtrl::Reset(void) { // // First, loop through all items and delete the lParam-based storage. // HTREEITEM h_item = GetRootItem(); if (h_item != NULL) { // // Recursively process the entire tree. // DeleteItemData(h_item); #ifdef IMAP4 // Prevent undesirable "OnEndLabelEdit()" // SendMessage(TVM_ENDEDITLABELNOW, TRUE, 0); // May have siblings at level 0 - delete them too. HTREEITEM h_sibling = GetNextSiblingItem(h_item); while (h_sibling) { DeleteItemData(h_sibling); h_sibling = GetNextSiblingItem(h_sibling); } #endif // IMAP4 } DeleteAllItems(); return TRUE; } //////////////////////////////////////////////////////////////////////// // DeleteItemData [private] // // Recursively delete all lParam-based storage from this tree item // and all of its children. Does not delete the items themselves. // //////////////////////////////////////////////////////////////////////// void QCMailboxTreeCtrl::DeleteItemData(HTREEITEM hItem) { // // First, process this item (the "root"). // ASSERT(hItem != NULL); CMboxTreeItemData* p_itemdata = (CMboxTreeItemData *) GetItemData(hItem); ASSERT(p_itemdata != NULL); delete p_itemdata; p_itemdata = NULL; // good hygiene HTREEITEM h_child = GetChildItem(hItem); while (h_child != NULL) { // cleanup subtrees recursively! DeleteItemData(h_child); h_child = GetNextSiblingItem(h_child); } } // virtual BOOL QCMailboxTreeCtrl::GetItemStruct(TV_INSERTSTRUCT &tvstruct, ItemType itemType, const char* itemName, QCMailboxCommand* pCommand, BOOL isChecked) { HTREEITEM hItem; CString szSibling; // // Initialize record. // tvstruct.hParent = NULL; // normally overwritten later tvstruct.hInsertAfter = TVI_LAST; tvstruct.item.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM | TVIF_STATE; tvstruct.item.hItem = 0; tvstruct.item.state = 0; // may be overwritten later tvstruct.item.stateMask = TVIS_BOLD; tvstruct.item.pszText = (char*)itemName; tvstruct.item.cchTextMax = -1; // unused tvstruct.item.iImage = -1; // normally overwritten later tvstruct.item.iSelectedImage = -1; // normally overwritten later tvstruct.item.lParam = NULL; // normally overwritten later // // Create an item data object and attach it to the item. // CMboxTreeItemData* p_itemdata = DEBUG_NEW_NOTHROW CMboxTreeItemData(itemType, pCommand); if (p_itemdata != NULL) tvstruct.item.lParam = long(p_itemdata); // cast to long else return FALSE; // out of memory // // Then, handle item-specific stuff. // if (isChecked) tvstruct.item.state = TVIS_BOLD; switch (itemType) { case ITEM_ROOT: tvstruct.hParent = TVI_ROOT; tvstruct.item.iImage = QCMailboxImageList::IMAGE_EUDORA; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_EUDORA; break; case ITEM_IN_MBOX: tvstruct.hParent = GetRootItem(); tvstruct.item.iImage = QCMailboxImageList::IMAGE_IN_MBOX; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_IN_MBOX; break; case ITEM_OUT_MBOX: tvstruct.hParent = GetRootItem(); tvstruct.item.iImage = QCMailboxImageList::IMAGE_OUT_MBOX; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_OUT_MBOX; break; case ITEM_TRASH_MBOX: tvstruct.hParent = GetRootItem(); tvstruct.item.iImage = QCMailboxImageList::IMAGE_TRASH_MBOX; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_TRASH_MBOX; break; case ITEM_JUNK_MBOX: tvstruct.hParent = GetRootItem(); tvstruct.item.iImage = QCMailboxImageList::IMAGE_JUNK_MBOX; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_JUNK_MBOX; break; case ITEM_FOLDER: // // We have to figure out where to place this in the hierarchy. // tvstruct.hParent = pCommand? GetParentFromPathname(pCommand->GetPathname()) : GetRootItem(); tvstruct.item.iImage = QCMailboxImageList::IMAGE_CLOSED_FOLDER; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_CLOSED_FOLDER; break; case ITEM_USER_MBOX: // // We have to figure out where to place this in the hierarchy. // tvstruct.hParent = GetParentFromPathname( pCommand->GetPathname() ); tvstruct.item.iImage = QCMailboxImageList::IMAGE_NORMAL_MBOX; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_NORMAL_MBOX; break; default: ASSERT(0); break; } // // find the right place to insert // if( tvstruct.hParent && ( itemType == ITEM_FOLDER || itemType == ITEM_USER_MBOX ) ) { if( ItemHasChildren( tvstruct.hParent ) ) { hItem = GetChildItem( tvstruct.hParent ); while( hItem ) { p_itemdata = ( CMboxTreeItemData* ) GetItemData( hItem ); if( itemType == ITEM_FOLDER ) { if( p_itemdata->m_itemType != ITEM_FOLDER || !p_itemdata->m_pCommand ) { hItem = GetNextSiblingItem( hItem ); continue; } } else { if( p_itemdata->m_itemType == ITEM_FOLDER && p_itemdata->m_pCommand ) { hItem = GetPrevSiblingItem( hItem ); if( hItem == NULL ) { hItem = TVI_FIRST; } break; } else if( p_itemdata->m_itemType != ITEM_USER_MBOX ) { hItem = GetNextSiblingItem( hItem ); continue; } } szSibling = GetItemText( hItem ); if( szSibling.CompareNoCase( itemName ) < 0 ) { hItem = GetNextSiblingItem( hItem ); } else { hItem = GetPrevSiblingItem( hItem ); if( hItem == NULL ) { hItem = TVI_FIRST; } break; } } if( hItem ) { tvstruct.hInsertAfter = hItem; } } } return (TRUE); } //////////////////////////////////////////////////////////////////////// // AddItem [public] // // The 'itemType' and 'itemDepth' parameters determines the level of // the tree where the new item gets added. The root item is defined // to be at level 0, the top-level mailboxes/folders at are level 1, // and so on. //////////////////////////////////////////////////////////////////////// HTREEITEM QCMailboxTreeCtrl::AddItem( ItemType itemType, const char* itemName, QCMailboxCommand* pCommand, BOOL isChecked) { TV_INSERTSTRUCT tvstruct; if (GetItemStruct(tvstruct, itemType, itemName, pCommand, isChecked)) { // Do the insert... HTREEITEM hItem = InsertItem(&tvstruct); if (hItem != NULL) { if( itemType == ITEM_ROOT ) { PostMessage( TVM_EXPAND, WPARAM( TVE_EXPAND ), LPARAM( hItem ) ); } else if (itemType == ITEM_TRASH_MBOX) UpdateRecentFolder(); return hItem; } } ASSERT(0); return NULL; } ///////////////////////////////////////////////////////////////////////////// // QCMailboxTreeCtrl message handlers //////////////////////////////////////////////////////////////////////// // OnDestroy [protected] // // Handles QCTreeCtrl HWND destruction by calling the Reset() method // to cleanup all the heap-allocated memory. // //////////////////////////////////////////////////////////////////////// void QCMailboxTreeCtrl::OnDestroy() { Reset(); // make sure heap allocations are cleared up QCTreeCtrl::OnDestroy(); } //////////////////////////////////////////////////////////////////////// // AutoCloseOpenedFolders [public] // // Process the list of auto-opened folders by closing them in reverse // order. // //////////////////////////////////////////////////////////////////////// BOOL QCMailboxTreeCtrl::AutoCloseOpenedFolders() { TRACE0("QCMailboxTreeCtrl::AutoCloseOpenedFolders()\n"); while (! m_autoOpenFolderList.IsEmpty()) { HTREEITEM h_item = HTREEITEM(m_autoOpenFolderList.RemoveTail()); Expand(h_item, TVE_COLLAPSE); // // Okay, the TVM_EXPAND message does not send the corresponding // TVN_ITEMEXPANDED notification message like you might // expect, so we have to do it ourselves. Whatta pain. // NM_TREEVIEW nmtv; nmtv.action = TVE_COLLAPSE; nmtv.itemNew.mask = TVIF_HANDLE | TVIF_PARAM; nmtv.itemNew.hItem = h_item; nmtv.itemNew.lParam = GetItemData(h_item); LRESULT unused; OnItemExpanded((NMHDR* ) &nmtv, &unused); } return TRUE; } //////////////////////////////////////////////////////////////////////// // UpdateRecentFolder [public] // // Update the list of recent mailboxes // //////////////////////////////////////////////////////////////////////// void QCMailboxTreeCtrl::UpdateRecentFolder() { const int MaxRecent = GetIniShort(IDS_INI_MAX_RECENT_MAILBOX); if (!MaxRecent) { if (m_hRecentFolderItem) { DeleteItemData(m_hRecentFolderItem); DeleteItem(m_hRecentFolderItem); m_hRecentFolderItem = NULL; } } else { if (!m_hRecentFolderItem) { QCMailboxDirector::BuildRecentMailboxesList(); CRString RecentName(IDS_RECENT_MBOX_MENU); RecentName.Remove('&'); TV_INSERTSTRUCT tvstruct; if (GetItemStruct(tvstruct, QCMailboxTreeCtrl::ITEM_FOLDER, RecentName, NULL, FALSE)) { HTREEITEM hItem = GetChildItem(GetRootItem()); // Insert after Trash mailbox while (hItem) { CMboxTreeItemData* p_itemdata = (CMboxTreeItemData *) GetItemData(hItem); if (p_itemdata->m_itemType == ITEM_TRASH_MBOX) break; hItem = GetNextSiblingItem(hItem); } tvstruct.hParent = GetRootItem(); tvstruct.hInsertAfter = hItem; VERIFY(m_hRecentFolderItem = InsertItem(&tvstruct)); } } HTREEITEM hItem = GetChildItem(m_hRecentFolderItem); HTREEITEM hPrevItem = NULL; for (std::list<LPCTSTR>::iterator it = QCMailboxDirector::s_RecentMailboxList.begin(); it != QCMailboxDirector::s_RecentMailboxList.end(); ++it) { QCMailboxCommand* pCommand = g_theMailboxDirector.FindByPathname(EudoraDir + *it); if (pCommand) { // Get rid of items in the tree that don't match this one, but not if we're at the // first item in the recent list as that may have just been added to the front CMboxTreeItemData* p_itemdata = hItem? (CMboxTreeItemData *) GetItemData(hItem) : NULL; if (it != QCMailboxDirector::s_RecentMailboxList.begin()) { while (hItem) { if (p_itemdata->m_pCommand == pCommand) break; HTREEITEM hNextItem = GetNextSiblingItem(hItem); DeleteItemData(hItem); DeleteItem(hItem); hItem = hNextItem; p_itemdata = hItem? (CMboxTreeItemData *) GetItemData(hItem) : NULL; } } // If the mailbox on the recent list is already at the right spot in the tree, // then don't add anything, just go to the next tree item if (!p_itemdata || p_itemdata->m_pCommand != pCommand) { // Insert the first item from the recent list if it's not already there at the front TV_INSERTSTRUCT tvstruct; ItemType itemType = ITEM_USER_MBOX; switch (pCommand->GetType()) { case MBT_IN: itemType = ITEM_IN_MBOX; break; case MBT_OUT: itemType = ITEM_OUT_MBOX; break; case MBT_JUNK: itemType = ITEM_JUNK_MBOX; break; case MBT_TRASH: itemType = ITEM_TRASH_MBOX; break; case MBT_REGULAR: itemType = ITEM_USER_MBOX; break; case MBT_IMAP_MAILBOX: itemType = ITEM_IMAP_MAILBOX; break; default: // Shouldn't get here ASSERT(0); break; } BOOL bStatus = FALSE; if (pCommand->IsImapType()) bStatus = GetImapItemStruct(tvstruct, itemType, pCommand->GetName(), pCommand, pCommand->GetStatus() == US_YES); else bStatus = GetItemStruct(tvstruct, itemType, pCommand->GetName(), pCommand, pCommand->GetStatus() == US_YES); if (bStatus) { tvstruct.hParent = m_hRecentFolderItem; tvstruct.hInsertAfter = hPrevItem? hPrevItem : TVI_FIRST; VERIFY(hItem = InsertItem(&tvstruct)); } } } hPrevItem = hItem; if (hItem) hItem = GetNextSiblingItem(hItem); } // Remove existing items at the end of the tree control that // are no longer on the recent mailbox list while (hItem) { HTREEITEM hNextItem = GetNextSiblingItem(hItem); DeleteItemData(hItem); DeleteItem(hItem); hItem = hNextItem; } } } //////////////////////////////////////////////////////////////////////// // OnItemExpanded [protected] // // Handles QCTreeCtrl expanded/collapsed notification message by updating // the graphic associated with the changed tree item. // //////////////////////////////////////////////////////////////////////// void QCMailboxTreeCtrl::OnItemExpanded(NMHDR* pNMHDR, LRESULT* pResult) { NM_TREEVIEW* p_treeview = (NM_TREEVIEW * )pNMHDR; // type cast ASSERT(p_treeview); CMboxTreeItemData* p_dataitem = (CMboxTreeItemData *) (p_treeview->itemNew.lParam); ASSERT(p_dataitem != NULL); switch (p_treeview->action) { case TVE_COLLAPSE: if (ITEM_ROOT == p_dataitem->m_itemType) SetItemImage(p_treeview->itemNew.hItem, QCMailboxImageList::IMAGE_EUDORA, QCMailboxImageList::IMAGE_EUDORA); else if (ITEM_FOLDER == p_dataitem->m_itemType) SetItemImage(p_treeview->itemNew.hItem, QCMailboxImageList::IMAGE_CLOSED_FOLDER, QCMailboxImageList::IMAGE_CLOSED_FOLDER); #ifdef IMAP4 else if ( (ITEM_IMAP_ACCOUNT == p_dataitem->m_itemType) || (ITEM_IMAP_NAMESPACE == p_dataitem->m_itemType) || (ITEM_IMAP_MAILBOX == p_dataitem->m_itemType) ) { UpdateImapItemImage (p_treeview->itemNew.hItem, p_treeview->action); } #endif // IMAP4 else SetItemImage(p_treeview->itemNew.hItem, QCMailboxImageList::IMAGE_NORMAL_MBOX, QCMailboxImageList::IMAGE_NORMAL_MBOX); break; case TVE_EXPAND: if (ITEM_ROOT == p_dataitem->m_itemType) SetItemImage(p_treeview->itemNew.hItem, QCMailboxImageList::IMAGE_EUDORA, QCMailboxImageList::IMAGE_EUDORA); else if (ITEM_FOLDER == p_dataitem->m_itemType) SetItemImage(p_treeview->itemNew.hItem, QCMailboxImageList::IMAGE_OPEN_FOLDER, QCMailboxImageList::IMAGE_OPEN_FOLDER); #ifdef IMAP4 else if ( (ITEM_IMAP_ACCOUNT == p_dataitem->m_itemType) || (ITEM_IMAP_NAMESPACE == p_dataitem->m_itemType) || (ITEM_IMAP_MAILBOX == p_dataitem->m_itemType) ) { UpdateImapItemImage (p_treeview->itemNew.hItem, p_treeview->action); } #endif // IMAP4 else SetItemImage(p_treeview->itemNew.hItem, QCMailboxImageList::IMAGE_NORMAL_MBOX, QCMailboxImageList::IMAGE_NORMAL_MBOX); break; default: ASSERT(0); break; } *pResult = 0; } //////////////////////////////////////////////////////////////////////// // DoSomethingWhileUserPausedMouseAtPoint [protected, virtual] // //////////////////////////////////////////////////////////////////////// void QCMailboxTreeCtrl::DoSomethingWhileUserPausedMouseAtPoint(CPoint pt) { // // Check to see if we hit a folder item. If so, then handle // the auto-open behavior here. // UINT flags = TVHT_ONITEM; HTREEITEM h_target = HitTest(pt, &flags); if (h_target != NULL) { CMboxTreeItemData* p_itemdata = (CMboxTreeItemData *) GetItemData(h_target); ASSERT(p_itemdata != NULL); switch (p_itemdata->m_itemType) { case ITEM_ROOT: case ITEM_FOLDER: { // // If we're doing a mailbox move operation via // an internal drag and drop, then don't execute // the auto-open action. The problem seems to be // that the auto-close will crash due to stale // HTREEITEM handles! // UINT state = GetItemState(h_target, TVIS_EXPANDED | TVIS_DROPHILITED); if (state & TVIS_DROPHILITED) { if (0 == (state & TVIS_EXPANDED)) { // // User has paused over a closed folder, so let's // auto-open it for them. // CImageList::DragShowNolock(FALSE); // allow window updates Expand(h_target, TVE_EXPAND); // // Okay, the TVM_EXPAND message does not send the corresponding // TVN_ITEMEXPANDED notification message like you might // expect, so we have to do it ourselves. Whatta pain. // NM_TREEVIEW nmtv; nmtv.action = TVE_EXPAND; nmtv.itemNew.mask = TVIF_HANDLE | TVIF_PARAM; nmtv.itemNew.hItem = h_target; nmtv.itemNew.lParam = GetItemData(h_target); LRESULT unused; OnItemExpanded((NMHDR* ) &nmtv, &unused); CImageList::DragShowNolock(TRUE); // lock window updates // // Keep track of which folders we've auto-opened // so that we can auto-close them when we're done. // m_autoOpenFolderList.AddTail((void *) h_target); } } } break; case ITEM_IN_MBOX: case ITEM_OUT_MBOX: case ITEM_TRASH_MBOX: case ITEM_JUNK_MBOX: case ITEM_USER_MBOX: break; default: ASSERT(0); break; } } } HTREEITEM QCMailboxTreeCtrl::GetParentFromPathname(LPCSTR szPathname) { char szChildPath[_MAX_PATH + 1]; strcpy(szChildPath, szPathname); char* LastBS = strrchr(szChildPath, '\\'); if (LastBS) *LastBS = 0; else ASSERT(0); return GetParentFromPathname( GetRootItem(), EudoraDirNoBackslash, szChildPath ); } HTREEITEM QCMailboxTreeCtrl::GetParentFromPathname(HTREEITEM hParent, LPCSTR szParentPath, LPCSTR szChildPath) { const int ChildPathLen = strlen(szChildPath); CString Dir; while (1) { if ( stricmp(szChildPath, szParentPath ) == 0 ) return hParent; // This fixes a bug that arises if we have mailbox names like mbox and mbox0! const int ParentPathLen = strlen(szParentPath); if (ChildPathLen > ParentPathLen && szChildPath[ParentPathLen] == '\\' && strnicmp(szParentPath, szChildPath, ParentPathLen) == 0) { // its in this sub tree hParent = GetChildItem( hParent ); } else { // check the next sibling hParent = GetNextSiblingItem( hParent ); } if (!hParent) break; CMboxTreeItemData* pItemData = (CMboxTreeItemData *) GetItemData( hParent ); if (pItemData != NULL && pItemData->m_pCommand) { if ( (pItemData->m_itemType == ITEM_IMAP_ACCOUNT) || (pItemData->m_itemType == ITEM_IMAP_MAILBOX) || (pItemData->m_itemType == ITEM_IMAP_NAMESPACE) ) { ((QCImapMailboxCommand *) pItemData->m_pCommand)->GetObjectDirectory (Dir); szParentPath = Dir; } else { szParentPath = pItemData->m_pCommand->GetPathname(); } } } return NULL; } void QCMailboxTreeCtrl::CheckItemByMenuId(const char* itemFilename, BOOL isChecked) { } void QCMailboxTreeCtrl::RenameItemByMenuId(const char* oldItemFilename, const char* newItemFilename) { } void QCMailboxTreeCtrl::RetypeItemByMenuId(const char* itemFilename, ItemType newType) { } #ifdef IMAP4 //=========================================================// // virtual BOOL QCMailboxTreeCtrl::GetImapItemStruct(TV_INSERTSTRUCT &tvstruct, ItemType itemType, const char* itemName, QCMailboxCommand* pCommand, BOOL isChecked) { CString szObjectDir; // Must have a valid command object. if (!pCommand) return FALSE; // // Initialize record. // tvstruct.hParent = NULL; // normally overwritten later tvstruct.hInsertAfter = TVI_LAST; tvstruct.item.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM | TVIF_STATE; tvstruct.item.hItem = 0; tvstruct.item.state = 0; // may be overwritten later tvstruct.item.stateMask = TVIS_BOLD; tvstruct.item.pszText = (char *) ((const char *) itemName); tvstruct.item.cchTextMax = -1; // unused tvstruct.item.iImage = -1; // normally overwritten later tvstruct.item.iSelectedImage = -1; // normally overwritten later tvstruct.item.lParam = NULL; // normally overwritten later // // Create an item data object and attach it to the item. // CMboxTreeItemData* p_itemdata = DEBUG_NEW_NOTHROW CMboxTreeItemData(itemType, pCommand); if (p_itemdata != NULL) tvstruct.item.lParam = long(p_itemdata); // cast to long else return FALSE; // out of memory // Cast this now. QCImapMailboxCommand *pImapCommand = (QCImapMailboxCommand *)pCommand; if (!pImapCommand) { return FALSE; } // // Then, handle item-specific stuff. // // Bold the entry only if it has unread mail and it isn't the Junk mailbox or the user doesn't // want the Junk mailbox to be marked unread. if (isChecked && (!IsJunk(pImapCommand->GetName()) || (GetIniShort(IDS_INI_JUNK_NEVER_UNREAD) == 0))) tvstruct.item.state = TVIS_BOLD; switch (itemType) { case ITEM_IMAP_ACCOUNT: // Can now be at any depth. tvstruct.hParent = TVI_ROOT; tvstruct.item.iImage = QCMailboxImageList::IMAGE_EUDORA; // JOK - change to image of a server. tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_EUDORA; break; case ITEM_IMAP_NAMESPACE: pImapCommand->GetObjectDirectory(szObjectDir); tvstruct.hParent = ImapGetParentFromPathname( szObjectDir ); tvstruct.item.iImage = QCMailboxImageList::IMAGE_CLOSED_FOLDER; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_CLOSED_FOLDER; break; case ITEM_IMAP_MAILBOX: pImapCommand->GetObjectDirectory(szObjectDir); tvstruct.hParent = ImapGetParentFromPathname( szObjectDir ); if (pImapCommand->CanHaveChildren()) { if ( pImapCommand->IsReadOnly() ) { if (pImapCommand->IsAutoSync()) { tvstruct.item.iImage = QCMailboxImageList::IMAGE_IMAP_FOLDER_READ_AUTOSYNC; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_IMAP_FOLDER_READ_AUTOSYNC; } else { tvstruct.item.iImage = QCMailboxImageList::IMAGE_IMAP_FOLDER_READ; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_IMAP_FOLDER_READ; } } else { if (pImapCommand->IsAutoSync()) { tvstruct.item.iImage = QCMailboxImageList::IMAGE_IMAP_FOLDER_AUTOSYNC; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_IMAP_FOLDER_AUTOSYNC; } else { tvstruct.item.iImage = QCMailboxImageList::IMAGE_IMAP_FOLDER; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_IMAP_FOLDER; } } } else { if ( pImapCommand->IsReadOnly() ) { if (pImapCommand->IsAutoSync()) { tvstruct.item.iImage = QCMailboxImageList::IMAGE_IMAP_MBOX_READ_AUTOSYNC; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_IMAP_MBOX_READ_AUTOSYNC; } else { tvstruct.item.iImage = QCMailboxImageList::IMAGE_IMAP_MBOX_READ; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_IMAP_MBOX_READ; } } else { if (pImapCommand->IsAutoSync()) { tvstruct.item.iImage = QCMailboxImageList::IMAGE_IMAP_MBOX_AUTOSYNC; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_IMAP_MBOX_AUTOSYNC; } else { tvstruct.item.iImage = QCMailboxImageList::IMAGE_IMAP_MBOX; tvstruct.item.iSelectedImage = QCMailboxImageList::IMAGE_IMAP_MBOX; } } } break; default: ASSERT(0); break; } return (TRUE); } //////////////////////////////////////////////////////////////////////// // AddImapItem [public] // // As AddItem, except that now we may pass the parent tree item //////////////////////////////////////////////////////////////////////// BOOL QCMailboxTreeCtrl::AddImapItem( ItemType itemType, const char* itemName, QCMailboxCommand* pCommand, BOOL isChecked) { TV_INSERTSTRUCT tvstruct; if (GetImapItemStruct(tvstruct, itemType, itemName, pCommand, isChecked)) { // Do the insert... HTREEITEM newItem = InsertItem(&tvstruct); // Expand accounts. if( newItem != NULL) { if( itemType == ITEM_IMAP_ACCOUNT ) { PostMessage( TVM_EXPAND, WPARAM( TVE_EXPAND ), LPARAM( newItem ) ); } } else ASSERT(0); } return TRUE; } // ImapGetParentFromPathname // NOTES // This is different from GetParentFromPathname() in that it searches IMAP trees only. // END NOTES HTREEITEM QCMailboxTreeCtrl::ImapGetParentFromPathname(LPCSTR szPathname) { char szChildPath[_MAX_PATH + 1]; strcpy(szChildPath, szPathname); char* LastBS = strrchr(szChildPath, '\\'); if (LastBS) *LastBS = 0; else ASSERT(0); // Start at the root. HTREEITEM hParent = GetRootItem(); HTREEITEM hItem = NULL; CString szParentPath; // Loop through top level nodes. while (hParent) { CMboxTreeItemData* p_itemdata = (CMboxTreeItemData *) GetItemData(hParent); if (p_itemdata && p_itemdata->m_pCommand) { if ( (p_itemdata->m_itemType == ITEM_IMAP_ACCOUNT) ) { ((QCImapMailboxCommand *) p_itemdata->m_pCommand)->GetObjectDirectory( szParentPath ); hItem = GetParentFromPathname(hParent, szParentPath, szChildPath); if (hItem) break; } } hParent = GetNextSiblingItem ( hParent ); } return hItem; } //////////////////////////////////////////////////////////////////////// // OnItemExpanded [protected] // // Handles QCTreeCtrl expanded/collapsed notification message by updating // the graphic associated with the changed tree item. // //////////////////////////////////////////////////////////////////////// void QCMailboxTreeCtrl::UpdateImapItemImage (HTREEITEM hItem, UINT action) { // Must have a non-zero item if (!hItem) { ASSERT (0); return; } // // Get the item's data. // CMboxTreeItemData* p_itemdata = (CMboxTreeItemData *) GetItemData(hItem); if (!p_itemdata) { ASSERT (0); return; } // // Must have a command object. // QCImapMailboxCommand *pImapCommand = (QCImapMailboxCommand *)p_itemdata->m_pCommand; if (! ( pImapCommand && hItem) ) { ASSERT (0); return; } // // Verify that it's of the right class type. // if( ! ( pImapCommand->IsKindOf( RUNTIME_CLASS ( QCImapMailboxCommand ) ) ) ) { ASSERT (0); return; } // // Type of IMAP mailbox/object // switch (p_itemdata->m_itemType) { // ACCOUNTS are easy. case ITEM_IMAP_ACCOUNT: SetItemImage(hItem, QCMailboxImageList::IMAGE_IMAP_ACCOUNT, QCMailboxImageList::IMAGE_IMAP_ACCOUNT); break; // Name spaces not yet handled. case ITEM_IMAP_NAMESPACE: SetItemImage(hItem, QCMailboxImageList::IMAGE_IMAP_FOLDER, QCMailboxImageList::IMAGE_IMAP_FOLDER); break; case ITEM_IMAP_MAILBOX: // // expandable mailbox? // if ( pImapCommand->CanHaveChildren () ) { // Is it expanded?? BOOL bIsExpanded = GetItemState( hItem, TVIS_EXPANDED ) & TVIS_EXPANDED; if ( (action == TVE_EXPAND) || ( (action == 0) && bIsExpanded) ) { // Is it read-only??: if (pImapCommand->IsAutoSync()) { if ( pImapCommand->IsReadOnly() ) SetItemImage(hItem, QCMailboxImageList::IMAGE_IMAP_FOLDER_OPEN_READ_AUTOSYNC, QCMailboxImageList::IMAGE_IMAP_FOLDER_OPEN_READ_AUTOSYNC); else SetItemImage(hItem, QCMailboxImageList::IMAGE_IMAP_FOLDER_OPEN_AUTOSYNC, QCMailboxImageList::IMAGE_IMAP_FOLDER_OPEN_AUTOSYNC); } else { if ( pImapCommand->IsReadOnly() ) SetItemImage(hItem, QCMailboxImageList::IMAGE_IMAP_FOLDER_OPEN_READ, QCMailboxImageList::IMAGE_IMAP_FOLDER_OPEN_READ); else SetItemImage(hItem, QCMailboxImageList::IMAGE_IMAP_FOLDER_OPEN, QCMailboxImageList::IMAGE_IMAP_FOLDER_OPEN); } } else { // Is it read-only? if (pImapCommand->IsAutoSync()) { if ( pImapCommand->IsReadOnly() ) SetItemImage(hItem, QCMailboxImageList::IMAGE_IMAP_FOLDER_READ_AUTOSYNC, QCMailboxImageList::IMAGE_IMAP_FOLDER_READ_AUTOSYNC); else SetItemImage(hItem, QCMailboxImageList::IMAGE_IMAP_FOLDER_AUTOSYNC, QCMailboxImageList::IMAGE_IMAP_FOLDER_AUTOSYNC); } else { if ( pImapCommand->IsReadOnly() ) SetItemImage(hItem, QCMailboxImageList::IMAGE_IMAP_FOLDER_READ, QCMailboxImageList::IMAGE_IMAP_FOLDER_READ); else SetItemImage(hItem, QCMailboxImageList::IMAGE_IMAP_FOLDER, QCMailboxImageList::IMAGE_IMAP_FOLDER); } } } // no-inferiors mailbox. else { if (pImapCommand->IsAutoSync()) { if ( pImapCommand->IsReadOnly() ) SetItemImage(hItem, QCMailboxImageList::IMAGE_IMAP_MBOX_READ_AUTOSYNC, QCMailboxImageList::IMAGE_IMAP_MBOX_READ_AUTOSYNC); else SetItemImage(hItem, QCMailboxImageList::IMAGE_IMAP_MBOX_AUTOSYNC, QCMailboxImageList::IMAGE_IMAP_MBOX_AUTOSYNC); } else { if ( pImapCommand->IsReadOnly() ) SetItemImage(hItem, QCMailboxImageList::IMAGE_IMAP_MBOX_READ, QCMailboxImageList::IMAGE_IMAP_MBOX_READ); else SetItemImage(hItem, QCMailboxImageList::IMAGE_IMAP_MBOX, QCMailboxImageList::IMAGE_IMAP_MBOX); } } break; default: ASSERT(0); break; } } #endif // IMAP4
28.192889
146
0.66756
[ "object" ]
43486b5f505a1f2133cdfe3914782a1d7027928d
8,573
hpp
C++
Vitis-AI-Library/libsrc/libdpsegmentation/include/xilinx/ai/segmentation.hpp
Trabing/Vitis-AI
936881527ed9a4dcd4956b1269ab157c888f4be6
[ "Apache-2.0" ]
2
2021-03-18T17:00:07.000Z
2022-03-18T18:28:23.000Z
Vitis-AI-Library/libsrc/libdpsegmentation/include/xilinx/ai/segmentation.hpp
Trabing/Vitis-AI
936881527ed9a4dcd4956b1269ab157c888f4be6
[ "Apache-2.0" ]
null
null
null
Vitis-AI-Library/libsrc/libdpsegmentation/include/xilinx/ai/segmentation.hpp
Trabing/Vitis-AI
936881527ed9a4dcd4956b1269ab157c888f4be6
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Xilinx Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Filename:segmentation.hpp * * Description: * Segmentation for ADAS * * Please refer to document "Xilinx_AI_SDK_User_Guide.pdf" for more *details of these APIs. */ #pragma once #include <memory> #include <opencv2/core.hpp> #include <xilinx/ai/nnpp/segmentation.hpp> namespace xilinx { namespace ai { /// Declaration Segmentation Network /// num of segmentation classes /// label 0 name: "unlabeled" /// label 1 name: "ego vehicle" /// label 2 name: "rectification border" /// label 3 name: "out of roi" /// label 4 name: "static" /// label 5 name: "dynamic" /// label 6 name: "ground" /// label 7 name: "road" /// label 8 name: "sidewalk" /// label 9 name: "parking" /// label 10 name: "rail track" /// label 11 name: "building" /// label 12 name: "wall" /// label 13 name: "fence" /// label 14 name: "guard rail" /// label 15 name: "bridge" /// label 16 name: "tunnel" /// label 17 name: "pole" /// label 18 name: "polegroup" /** * @brief Base class for Segmentation. * * Input is an image (cv:Mat). * * Output is result of running the Segmentation network. * * Sample code : @code auto det =xilinx::ai::Segmentation::create("fpn", true); auto img= cv::imread("sample_segmentation.jpg"); int width = det->getInputWidth(); int height = det->getInputHeight(); cv::Mat image; cv::resize(img, image, cv::Size(width, height), 0, 0, cv::INTER_LINEAR); auto result = det->run_8UC1(image); for (auto y = 0; y < result.segmentation.rows; y++) { for (auto x = 0; x < result.segmentation.cols; x++) { result.segmentation.at<uchar>(y,x) *= 10; } } cv::imwrite("segres.jpg",result.segmentation); auto resultshow = det->run_8UC3(image); resize(resultshow.segmentation, resultshow.segmentation, cv::Size(resultshow.cols * 2, resultshow.rows * 2)); cv::imwrite("sample_segmentation_result.jpg",resultshow.segmentation); @endcode * * @image latex images/sample_segmentation_result.jpg "segmentation visulization result image" width=\textwidth * */ class Segmentation { public: /** * @brief Factory function to get an instance of derived classes of class * Segmentation. * * @param model_name Model name * @param need_preprocess Normalize with mean/scale or not, default value is * true. * @return An instance of Segmentation class. * */ static std::unique_ptr<Segmentation> create(const std::string &model_name, bool need_preprocess = true); protected: explicit Segmentation(); Segmentation(const Segmentation &) = delete; public: virtual ~Segmentation(); public: /** * @brief Function to get InputWidth of the segmentation network (input image * cols). * * @return InputWidth of the segmentation network. */ virtual int getInputWidth() const = 0; /** * @brief Function to get InputHight of the segmentation network (input image * rows). * * @return InputHeight of the segmentation network. */ virtual int getInputHeight() const = 0; /** * @brief Function of get running result of the segmentation network. * * @note The type of CV_8UC1 of the Reuslt's segmentation. * * @param image Input data of input image (cv::Mat). * * @return a result include segmentation output data. * */ virtual SegmentationResult run_8UC1(const cv::Mat &image) = 0; /** * @brief Function of get running result of the segmentation network. * * @note The type of CV_8UC3 of the Reuslt's segmentation. * @param image Input data of input image (cv::Mat). * * @return a result include segmentation image and shape;. * */ virtual SegmentationResult run_8UC3(const cv::Mat &image) = 0; }; /** * @brief The Class of Segmentation8UC1, this class run function return a cv::Mat with the type is cv_8UC1 *Sample code : @code auto det = xilinx::ai::Segmentation8UC1::create(xilinx::ai::SEGMENTATION_FPN); auto img = cv::imread("sample_segmentation.jpg"); int width = det->getInputWidth(); int height = det->getInputHeight(); cv::Mat image; cv::resize(img, image, cv::Size(width, height), 0, 0, cv::INTER_LINEAR); auto result = det->run(image); for (auto y = 0; y < result.segmentation.rows; y++) { for (auto x = 0; x < result.segmentation.cols; x++) { result.segmentation.at<uchar>(y,x) *= 10; } } cv::imwrite("segres.jpg",result.segmentation); @endcode * */ class Segmentation8UC1 { public: /** * @brief Factory function to get an instance of derived classes of class * Segmentation8UC1. * * @param model_name Model name * @param need_preprocess Normalize with mean/scale or not, default value is * true. * @return An instance of Segmentation8UC1 class. * */ static std::unique_ptr<Segmentation8UC1> create(const std::string &model_name, bool need_preprocess = true); protected: explicit Segmentation8UC1(std::unique_ptr<Segmentation> segmentation); Segmentation8UC1(const Segmentation8UC1 &) = delete; public: ~Segmentation8UC1(); public: /** * @brief Function to get InputWidth of the segmentation network (input image *cols). * * @return InputWidth of the segmentation network. */ int getInputWidth() const; /** * @brief Function to get InputHight of the segmentation network (input image *cols). * * @return InputHeight of the segmentation network. */ int getInputHeight() const; /** *@brief Function of get running result of the segmentation network. *@note The result cv::Mat of the type is CV_8UC1. *@param image Input data of the image (cv::Mat) *@return A Struct of SegmentationResult ,the result of segmentation network. */ SegmentationResult run(const cv::Mat &image); private: std::unique_ptr<Segmentation> segmentation_; }; /** * @brief The Class of Segmentation8UC3, this class run function return a cv::Mat with the type is cv_8UC3 * Sample code : @code auto det = xilinx::ai::Segmentation8UC3::create(xilinx::ai::SEGMENTATION_FPN); auto img = cv::imread("sample_segmentation.jpg"); int width = det->getInputWidth(); int height = det->getInputHeight(); cv::Mat image; cv::resize(img, image, cv::Size(width, height), 0, 0, cv::INTER_LINEAR); auto result = det->run(image); cv::imwrite("segres.jpg",result.segmentation); @endcode * */ class Segmentation8UC3 { public: /** * @brief Factory function to get an instance of derived classes of class * Segmentation8UC3. * * @param model_name Model name * @param need_preprocess Normalize with mean/scale or not, default value is * true. * @return An instance of Segmentation8UC3 class. * */ static std::unique_ptr<Segmentation8UC3> create(const std::string &model_name, bool need_preprocess = true); protected: explicit Segmentation8UC3(std::unique_ptr<Segmentation> segmentation); Segmentation8UC3(const Segmentation8UC3 &) = delete; public: ~Segmentation8UC3(); public: /** * @brief Function to get InputWidth of the segmentation network (input image *cols). * * @return InputWidth of the segmentation network. */ int getInputWidth() const; /** * @brief Function to get InputWidth of the segmentation network (input *image *cols). * * @return InputWidth of the segmentation network. */ int getInputHeight() const; /** *@brief Function of get running result of the segmentation network. *@note The result cv::Mat of the type is CV_8UC1. *@param image Input data of the image (cv::Mat) *@return SegmentationResult The result of segmentation network. */ SegmentationResult run(const cv::Mat &image); private: std::unique_ptr<Segmentation> segmentation_; }; } // namespace ai } // namespace xilinx
29.061017
111
0.668144
[ "shape", "model" ]
434be7cc8671a522a39b254b67f4f485a0950a7f
8,865
cc
C++
p2p/server/service_publisher.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
p2p/server/service_publisher.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
p2p/server/service_publisher.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "p2p/server/service_publisher.h" #include <avahi-client/client.h> #include <avahi-client/publish.h> #include <avahi-common/error.h> #include <avahi-glib/glib-watch.h> #include <glib.h> #include <map> #include <base/logging.h> #include <base/strings/stringprintf.h> #include "p2p/common/util.h" using std::map; using std::string; namespace p2p { namespace server { // File sizes can change very quickly and very often so rate-limit // these kind of changes to once every ten seconds. Otherwise we // may end up generate a lot of unnecessary traffic. const int kFileChangedDelayMSec = 10000; class ServicePublisherAvahi : public ServicePublisher { public: explicit ServicePublisherAvahi(uint16_t http_port); ServicePublisherAvahi(const ServicePublisherAvahi&) = delete; ServicePublisherAvahi& operator=(const ServicePublisherAvahi&) = delete; ~ServicePublisherAvahi() override; void AddFile(const string& file, size_t file_size) override; void RemoveFile(const string& file) override; void UpdateFileSize(const string& file, size_t file_size) override; void SetNumConnections(int num_connections) override; map<string, size_t> files() override; bool Init(); private: // Callback used for timeout management - see kFileChangedDelayMSec. static gboolean OnDelayTimeoutExpired(gpointer user_data); // Callback used for when Avahi changes state. static void OnAvahiChanged(AvahiClient* client, AvahiClientState state, void* user_data); // Helper for calculating the TXT records to publish. AvahiStringList* CalculateTXTRecords(); // Method used to publish the information in files_ to Avahi. void Publish(bool may_delay); // The TCP port of the HTTP server. uint16_t http_port_; // The LAN name currently used by Avahi. This is used as the // identifier of the DNS-SD service being exported via mDNS. string lan_name_; // Object used for integrating Avahi with the GLib mainloop. AvahiGLibPoll* poll_; // The Avahi object. AvahiClient* client_; // Object used to publish DNS-SD records. AvahiEntryGroup* group_; // The files (and their sizes) to export. These are exported in TXT // records of the DNS-SD service (prefixed with id_). map<string, size_t> files_; // The current number of HTTP connections. This is exported as a // decimal number in the "num-connections" TXT record. int num_connections_; // GLib source id used for timeout management - see kFileChangedDelayMSec. guint delay_timeout_id_; }; ServicePublisherAvahi::ServicePublisherAvahi(uint16_t http_port) : http_port_(http_port), poll_(NULL), client_(NULL), group_(NULL), num_connections_(0), delay_timeout_id_(0) {} ServicePublisherAvahi::~ServicePublisherAvahi() { if (delay_timeout_id_ != 0) g_source_remove(delay_timeout_id_); if (group_ != NULL) avahi_entry_group_free(group_); if (client_ != NULL) avahi_client_free(client_); if (poll_ != NULL) avahi_glib_poll_free(poll_); } AvahiStringList* ServicePublisherAvahi::CalculateTXTRecords() { AvahiStringList* list; string str = base::StringPrintf("num_connections=%d", num_connections_); list = avahi_string_list_new(str.c_str(), NULL); for (auto& item : files_) { string key = string("id_") + item.first; string value = std::to_string(item.second); // TODO(zeuthen): ensure that len(key+"="+value) <= 255 list = avahi_string_list_add_pair(list, key.c_str(), value.c_str()); } return list; } gboolean ServicePublisherAvahi::OnDelayTimeoutExpired(gpointer user_data) { ServicePublisherAvahi* publisher = reinterpret_cast<ServicePublisherAvahi*>(user_data); VLOG(1) << "Publishing timeout expired"; publisher->delay_timeout_id_ = 0; publisher->Publish(false); return FALSE; // Remove timeout source } void ServicePublisherAvahi::Publish(bool may_delay) { int rc; AvahiStringList* txt; if (may_delay) { if (delay_timeout_id_ != 0) { // Already have a timeout, no need to schedule a new one return; } delay_timeout_id_ = g_timeout_add(kFileChangedDelayMSec, static_cast<GSourceFunc>(OnDelayTimeoutExpired), this); VLOG(1) << "Scheduling publishing to happen in " << kFileChangedDelayMSec << " msec"; return; } else { // Not allowed to delay, have to publish immediately .. so if we have // a timeout cancel it if (delay_timeout_id_ != 0) { g_source_remove(delay_timeout_id_); delay_timeout_id_ = 0; VLOG(1) << "Cancelling already scheduled publishing event"; } } VLOG(1) << "Publishing records"; txt = CalculateTXTRecords(); if (group_ == NULL) { group_ = avahi_entry_group_new(client_, NULL, NULL); /* user_data */ if (group_ == NULL) { LOG(ERROR) << "Error creating AvahiEntryGroup: " << avahi_strerror(avahi_client_errno(client_)); avahi_string_list_free(txt); return; } rc = avahi_entry_group_add_service_strlst( group_, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, (AvahiPublishFlags)0, lan_name_.c_str(), "_cros_p2p._tcp", /* service type */ NULL, /* domain */ NULL, /* host */ http_port_, /* IP port */ txt); if (rc != AVAHI_OK) { LOG(ERROR) << "Error adding service to AvahiEntryGroup: " << avahi_strerror(avahi_client_errno(client_)); avahi_string_list_free(txt); return; } rc = avahi_entry_group_commit(group_); if (rc != AVAHI_OK) { LOG(ERROR) << "Error committing AvahiEntryGroup: " << avahi_strerror(avahi_client_errno(client_)); } } else { avahi_entry_group_update_service_txt_strlst( group_, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, (AvahiPublishFlags)0, lan_name_.c_str(), "_cros_p2p._tcp", /* service type */ NULL, /* domain */ txt); } avahi_string_list_free(txt); } void ServicePublisherAvahi::OnAvahiChanged(AvahiClient* client, AvahiClientState state, void* user_data) { ServicePublisherAvahi* publisher = reinterpret_cast<ServicePublisherAvahi*>(user_data); // So, we're called directly by avahi_client_new() - meaning // client_ member isn't set yet - thanks :-/ if (publisher->client_ == NULL) publisher->client_ = client; VLOG(1) << "OnAvahiChanged, state=" << state; if (state == AVAHI_CLIENT_S_RUNNING) { // Free the existing group, if there is one. This can happen if // e.g. the LAN name used by Avahi changes. if (publisher->group_ != NULL) { avahi_entry_group_free(publisher->group_); publisher->group_ = NULL; } publisher->lan_name_ = string(avahi_client_get_host_name(client)); VLOG(1) << "Server running, publishing services using LAN name '" << publisher->lan_name_ << "'"; publisher->Publish(false); } } bool ServicePublisherAvahi::Init() { int error; poll_ = avahi_glib_poll_new(NULL, G_PRIORITY_DEFAULT); client_ = avahi_client_new(avahi_glib_poll_get(poll_), (AvahiClientFlags)0, OnAvahiChanged, this, &error); if (client_ == NULL) { LOG(ERROR) << "Error constructing AvahiClient: " << error; return false; } return true; } void ServicePublisherAvahi::AddFile(const string& file, size_t file_size) { files_[file] = file_size; Publish(false); } void ServicePublisherAvahi::RemoveFile(const string& file) { if (files_.erase(file) != 1) { LOG(WARNING) << "Removing file " << file << " not in map"; } Publish(false); } void ServicePublisherAvahi::UpdateFileSize(const string& file, size_t file_size) { auto it = files_.find(file); if (it == files_.end()) { LOG(WARNING) << "Trying to set size for file " << file << " not in map"; return; } it->second = file_size; Publish(true); } void ServicePublisherAvahi::SetNumConnections(int num_connections) { if (num_connections_ == num_connections) return; num_connections_ = num_connections; Publish(false); } map<string, size_t> ServicePublisherAvahi::files() { return files_; } // ----------------------------------------------------------------------------- ServicePublisher* ServicePublisher::Construct(uint16_t http_port) { ServicePublisherAvahi* instance = new ServicePublisherAvahi(http_port); if (!instance->Init()) { delete instance; return NULL; } else { return instance; } } } // namespace server } // namespace p2p
30.359589
80
0.672081
[ "object" ]
434f0ac49106c6d329443c622c1485d88ebcde49
3,509
hpp
C++
include/SFGUI/ListBox.hpp
pL0ck/SFGUI
a4115c25f4c92a0ef121896baea6aab4a51e3b3d
[ "Zlib" ]
null
null
null
include/SFGUI/ListBox.hpp
pL0ck/SFGUI
a4115c25f4c92a0ef121896baea6aab4a51e3b3d
[ "Zlib" ]
null
null
null
include/SFGUI/ListBox.hpp
pL0ck/SFGUI
a4115c25f4c92a0ef121896baea6aab4a51e3b3d
[ "Zlib" ]
null
null
null
#pragma once #include <SFGUI/Container.hpp> #include <SFGUI/Scrollbar.hpp> #include <SFML/System/String.hpp> #include <initializer_list> #include <memory> #include <set> #include <vector> namespace sfg { class SFGUI_API ListBox : public Container { public: typedef std::shared_ptr<ListBox> Ptr; //!< Shared pointer. typedef std::shared_ptr<const ListBox> PtrConst; //!< Shared pointer. typedef int IndexType; static const IndexType NONE; enum class SelectionMode : char { NO_SELECTION, SINGLE_SELECTION, MULTI_SELECTION, DEFAULT = SINGLE_SELECTION }; enum class ScrollbarPolicy : char { VERTICAL_ALWAYS, VERTICAL_AUTOMATIC, VERTICAL_NEVER, DEFAULT = VERTICAL_AUTOMATIC }; enum class ItemTextPolicy : char { RESIZE_LISTBOX, SHRINK, DEFAULT = RESIZE_LISTBOX }; /** Create listbox. * @return ListBox. */ static Ptr Create(); const std::string& GetName() const override; void AppendItem(const sf::String& str); void InsertItem(IndexType index, const sf::String& str); void PrependItem(const sf::String& str); void ChangeItem(IndexType index, const sf::String& str); void RemoveItem(IndexType index); void Clear(); IndexType GetItemsCount() const; const sf::String& GetItemText(IndexType index) const; const sf::String& GetDisplayedItemText(IndexType index) const; IndexType GetHighlightedItem() const; void SetSelection(IndexType index); void SetSelection(std::initializer_list<IndexType> indices); void AppendToSelection(IndexType index); void RemoveFromSelection(IndexType index); void ClearSelection(); bool IsItemSelected(IndexType index) const; IndexType GetSelectedItemsCount() const; IndexType GetSelectedItemIndex(IndexType index = 0) const; const sf::String& GetSelectedItemText(IndexType index = 0) const; IndexType GetFirstDisplayedItemIndex() const; IndexType GetDisplayedItemsCount() const; IndexType GetMaxDisplayedItemsCount() const; SelectionMode GetSelectionMode() const; void SetSelectionMode(SelectionMode mode); ScrollbarPolicy GetScrollbarPolicy() const; void SetScrollbarPolicy(ScrollbarPolicy policy); ItemTextPolicy GetItemTextPolicy() const; void SetItemTextPolicy(ItemTextPolicy policy); // Signals. static Signal::SignalID OnSelect; //!< Fired when an entry is selected. protected: /** Ctor. */ ListBox(); std::unique_ptr<RenderQueue> InvalidateImpl() const override; sf::Vector2f CalculateRequisition() override; private: void HandleMouseEnter(int x, int y) override; void HandleMouseLeave(int x, int y) override; void HandleMouseMoveEvent(int x, int y) override; void HandleMouseButtonEvent(sf::Mouse::Button button, bool press, int x, int y) override; void HandleSizeChange() override; bool HandleAdd(Widget::Ptr) override; void HandleRemove(Widget::Ptr) override; IndexType GetItemAt(float y) const; bool IsScrollbarVisible() const; void UpdateDisplayedItems(); void UpdateScrollbarAdjustment(); void UpdateScrollbarAllocation(); void UpdateDisplayedItemsText(); void OnScrollbarChanged(); std::vector<sf::String> m_items; SelectionMode m_selection_mode; std::set<IndexType> m_selected_items; IndexType m_highlighted_item; IndexType m_first_displayed_item; IndexType m_max_displayed_items_count; Scrollbar::Ptr m_vertical_scrollbar; ScrollbarPolicy m_scrollbar_policy; ItemTextPolicy m_item_text_policy; std::vector<sf::String> m_displayed_items_texts; }; }
25.801471
91
0.755771
[ "vector" ]
434f739785827a33242d7b2d79ccbfd146c5741e
46,801
cpp
C++
docker/build/face_detection/face_detector/3rdparty/ncnn/tools/caffe/caffe2ncnn-mtcnn.cpp
mykiscool/DeepCamera
e77cdbf45ab09895f315aa299bd6ac87b3bb6d66
[ "MIT" ]
914
2019-03-07T14:57:45.000Z
2022-03-31T14:54:15.000Z
docker/build/face_detection/face_detector/3rdparty/ncnn/tools/caffe/caffe2ncnn-mtcnn.cpp
mykiscool/DeepCamera
e77cdbf45ab09895f315aa299bd6ac87b3bb6d66
[ "MIT" ]
45
2019-03-11T09:53:37.000Z
2022-03-30T21:59:37.000Z
docker/build/face_detection/face_detector/3rdparty/ncnn/tools/caffe/caffe2ncnn-mtcnn.cpp
mykiscool/DeepCamera
e77cdbf45ab09895f315aa299bd6ac87b3bb6d66
[ "MIT" ]
148
2019-03-08T00:40:28.000Z
2022-03-30T09:22:18.000Z
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #include <stdio.h> #include <limits.h> #include <math.h> #include <fstream> #include <set> #include <limits> #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/text_format.h> #include <google/protobuf/message.h> #include "caffe.pb.h" #include <iostream> static inline size_t alignSize(size_t sz, int n) { return (sz + n-1) & -n; } // convert float to half precision floating point static unsigned short float2half(float value) { // 1 : 8 : 23 union { unsigned int u; float f; } tmp; tmp.f = value; // 1 : 8 : 23 unsigned short sign = (tmp.u & 0x80000000) >> 31; unsigned short exponent = (tmp.u & 0x7F800000) >> 23; unsigned int significand = tmp.u & 0x7FFFFF; // fprintf(stderr, "%d %d %d\n", sign, exponent, significand); // 1 : 5 : 10 unsigned short fp16; if (exponent == 0) { // zero or denormal, always underflow fp16 = (sign << 15) | (0x00 << 10) | 0x00; } else if (exponent == 0xFF) { // infinity or NaN fp16 = (sign << 15) | (0x1F << 10) | (significand ? 0x200 : 0x00); } else { // normalized short newexp = exponent + (- 127 + 15); if (newexp >= 31) { // overflow, return infinity fp16 = (sign << 15) | (0x1F << 10) | 0x00; } else if (newexp <= 0) { // underflow if (newexp >= -10) { // denormal half-precision unsigned short sig = (significand | 0x800000) >> (14 - newexp); fp16 = (sign << 15) | (0x00 << 10) | sig; } else { // underflow fp16 = (sign << 15) | (0x00 << 10) | 0x00; } } else { fp16 = (sign << 15) | (newexp << 10) | (significand >> 13); } } return fp16; } static int quantize_weight(float *data, size_t data_length, std::vector<unsigned short>& float16_weights) { float16_weights.resize(data_length); for (size_t i = 0; i < data_length; i++) { float f = data[i]; unsigned short fp16 = float2half(f); float16_weights[i] = fp16; } // magic tag for half-precision floating point return 0x01306B47; } static bool quantize_weight(float *data, size_t data_length, int quantize_level, std::vector<float> &quantize_table, std::vector<unsigned char> &quantize_index) { assert(quantize_level != 0); assert(data != NULL); assert(data_length > 0); if (data_length < static_cast<size_t>(quantize_level)) { fprintf(stderr, "No need quantize,because: data_length < quantize_level"); return false; } quantize_table.reserve(quantize_level); quantize_index.reserve(data_length); // 1. Find min and max value float max_value = std::numeric_limits<float>::min(); float min_value = std::numeric_limits<float>::max(); for (size_t i = 0; i < data_length; ++i) { if (max_value < data[i]) max_value = data[i]; if (min_value > data[i]) min_value = data[i]; } float strides = (max_value - min_value) / quantize_level; // 2. Generate quantize table for (int i = 0; i < quantize_level; ++i) { quantize_table.push_back(min_value + i * strides); } // 3. Align data to the quantized value for (size_t i = 0; i < data_length; ++i) { size_t table_index = int((data[i] - min_value) / strides); table_index = std::min<float>(table_index, quantize_level - 1); float low_value = quantize_table[table_index]; float high_value = low_value + strides; // find a nearest value between low and high value. float targetValue = data[i] - low_value < high_value - data[i] ? low_value : high_value; table_index = int((targetValue - min_value) / strides); table_index = std::min<float>(table_index, quantize_level - 1); quantize_index.push_back(table_index); } return true; } static bool read_proto_from_text(const char* filepath, google::protobuf::Message* message) { std::ifstream fs(filepath, std::ifstream::in); if (!fs.is_open()) { fprintf(stderr, "open failed %s\n", filepath); return false; } google::protobuf::io::IstreamInputStream input(&fs); bool success = google::protobuf::TextFormat::Parse(&input, message); fs.close(); return success; } static bool read_proto_from_binary(const char* filepath, google::protobuf::Message* message) { std::ifstream fs(filepath, std::ifstream::in | std::ifstream::binary); if (!fs.is_open()) { fprintf(stderr, "open failed %s\n", filepath); return false; } google::protobuf::io::IstreamInputStream input(&fs); google::protobuf::io::CodedInputStream codedstr(&input); codedstr.SetTotalBytesLimit(INT_MAX, INT_MAX / 2); bool success = message->ParseFromCodedStream(&codedstr); fs.close(); return success; } int main(int argc, char** argv) { if (!(argc == 3 || argc == 5 || argc == 6)) { fprintf(stderr, "Usage: %s [caffeproto] [caffemodel] [ncnnproto] [ncnnbin] [quantizelevel]\n", argv[0]); return -1; } const char* caffeproto = argv[1]; const char* caffemodel = argv[2]; const char* ncnn_prototxt = argc >= 5 ? argv[3] : "ncnn.proto"; const char* ncnn_modelbin = argc >= 5 ? argv[4] : "ncnn.bin"; const char* quantize_param = argc == 6 ? argv[5] : "0"; int quantize_level = atoi(quantize_param); if (quantize_level != 0 && quantize_level != 256 && quantize_level != 65536) { fprintf(stderr, "%s: only support quantize level = 0, 256, or 65536", argv[0]); return -1; } caffe::NetParameter proto; caffe::NetParameter net; // load bool s0 = read_proto_from_text(caffeproto, &proto); if (!s0) { fprintf(stderr, "read_proto_from_text failed\n"); return -1; } bool s1 = read_proto_from_binary(caffemodel, &net); if (!s1) { fprintf(stderr, "read_proto_from_binary failed\n"); return -1; } FILE* pp = fopen(ncnn_prototxt, "wb"); FILE* bp = fopen(ncnn_modelbin, "wb"); // magic fprintf(pp, "7767517\n"); // rename mapping for identical bottom top style std::map<std::string, std::string> blob_name_decorated; // bottom blob reference std::map<std::string, int> bottom_reference; // global definition line // [layer count] [blob count] int layer_count = proto.layer_size(); std::set<std::string> blob_names; for (int i=0; i<layer_count; i++) { const caffe::LayerParameter& layer = proto.layer(i); for (int j=0; j<layer.bottom_size(); j++) { std::string blob_name = layer.bottom(j); if (blob_name_decorated.find(blob_name) != blob_name_decorated.end()) { blob_name = blob_name_decorated[blob_name]; } blob_names.insert(blob_name); if (bottom_reference.find(blob_name) == bottom_reference.end()) { bottom_reference[blob_name] = 1; } else { bottom_reference[blob_name] = bottom_reference[blob_name] + 1; } } if (layer.bottom_size() == 1 && layer.top_size() == 1 && layer.bottom(0) == layer.top(0)) { std::string blob_name = layer.top(0) + "_" + layer.name(); blob_name_decorated[layer.top(0)] = blob_name; blob_names.insert(blob_name); } else { for (int j=0; j<layer.top_size(); j++) { std::string blob_name = layer.top(j); blob_names.insert(blob_name); } } } // remove bottom_reference entry with reference equals to one int splitncnn_blob_count = 0; std::map<std::string, int>::iterator it = bottom_reference.begin(); while (it != bottom_reference.end()) { if (it->second == 1) { bottom_reference.erase(it++); } else { splitncnn_blob_count += it->second; // fprintf(stderr, "%s %d\n", it->first.c_str(), it->second); ++it; } } fprintf(pp, "%lu %lu\n", layer_count + bottom_reference.size(), blob_names.size() + splitncnn_blob_count); // populate blob_name_decorated.clear(); int internal_split = 0; for (int i=0; i<layer_count; i++) { const caffe::LayerParameter& layer = proto.layer(i); // layer definition line, repeated // [type] [name] [bottom blob count] [top blob count] [bottom blobs] [top blobs] [layer specific params] if (layer.type() == "Convolution") { const caffe::ConvolutionParameter& convolution_param = layer.convolution_param(); if (convolution_param.group() != 1) fprintf(pp, "%-16s", "ConvolutionDepthWise"); else fprintf(pp, "%-16s", "Convolution"); } else if (layer.type() == "ConvolutionDepthwise") { fprintf(pp, "%-16s", "ConvolutionDepthWise"); } else if (layer.type() == "Deconvolution") { const caffe::ConvolutionParameter& convolution_param = layer.convolution_param(); if (convolution_param.group() != 1) fprintf(pp, "%-16s", "DeconvolutionDepthWise"); else fprintf(pp, "%-16s", "Deconvolution"); } else if (layer.type() == "MemoryData") { fprintf(pp, "%-16s", "Input"); } else if (layer.type() == "Python") { const caffe::PythonParameter& python_param = layer.python_param(); std::string python_layer_name = python_param.layer(); if (python_layer_name == "ProposalLayer") fprintf(pp, "%-16s", "Proposal"); else fprintf(pp, "%-16s", python_layer_name.c_str()); } else { fprintf(pp, "%-16s", layer.type().c_str()); } fprintf(pp, " %-16s %d %d", layer.name().c_str(), layer.bottom_size(), layer.top_size()); for (int j=0; j<layer.bottom_size(); j++) { std::string blob_name = layer.bottom(j); if (blob_name_decorated.find(layer.bottom(j)) != blob_name_decorated.end()) { blob_name = blob_name_decorated[layer.bottom(j)]; } if (bottom_reference.find(blob_name) != bottom_reference.end()) { int refidx = bottom_reference[blob_name] - 1; bottom_reference[blob_name] = refidx; char splitsuffix[256]; sprintf(splitsuffix, "_splitncnn_%d", refidx); blob_name = blob_name + splitsuffix; } fprintf(pp, " %s", blob_name.c_str()); } // decorated if (layer.bottom_size() == 1 && layer.top_size() == 1 && layer.bottom(0) == layer.top(0)) { std::string blob_name = layer.top(0) + "_" + layer.name(); blob_name_decorated[layer.top(0)] = blob_name; fprintf(pp, " %s", blob_name.c_str()); } else { for (int j=0; j<layer.top_size(); j++) { std::string blob_name = layer.top(j); fprintf(pp, " %s", blob_name.c_str()); } } // find blob binary by layer name int netidx; for (netidx=0; netidx<net.layer_size(); netidx++) { if (net.layer(netidx).name() == layer.name()) { break; } } // layer specific params if (layer.type() == "BatchNorm") { const caffe::LayerParameter& binlayer = net.layer(netidx); const caffe::BlobProto& mean_blob = binlayer.blobs(0); const caffe::BlobProto& var_blob = binlayer.blobs(1); fprintf(pp, " 0=%d", (int)mean_blob.data_size()); const caffe::BatchNormParameter& batch_norm_param = layer.batch_norm_param(); float eps = batch_norm_param.eps(); std::vector<float> ones(mean_blob.data_size(), 1.f); fwrite(ones.data(), sizeof(float), ones.size(), bp);// slope if (binlayer.blobs_size() < 3) { fwrite(mean_blob.data().data(), sizeof(float), mean_blob.data_size(), bp); float tmp; for (int j=0; j<var_blob.data_size(); j++) { tmp = var_blob.data().data()[j] + eps; fwrite(&tmp, sizeof(float), 1, bp); } } else { float scale_factor = 1 / binlayer.blobs(2).data().data()[0]; // premultiply scale_factor to mean and variance float tmp; for (int j=0; j<mean_blob.data_size(); j++) { tmp = mean_blob.data().data()[j] * scale_factor; fwrite(&tmp, sizeof(float), 1, bp); } for (int j=0; j<var_blob.data_size(); j++) { tmp = var_blob.data().data()[j] * scale_factor + eps; fwrite(&tmp, sizeof(float), 1, bp); } } std::vector<float> zeros(mean_blob.data_size(), 0.f); fwrite(zeros.data(), sizeof(float), zeros.size(), bp);// bias } else if (layer.type() == "Concat") { const caffe::ConcatParameter& concat_param = layer.concat_param(); int dim = concat_param.axis() - 1; fprintf(pp, " 0=%d", dim); } else if (layer.type() == "Convolution" || layer.type() == "ConvolutionDepthwise") { std::cout << "layer type: " << layer.type() << std::endl; const caffe::LayerParameter& binlayer = net.layer(netidx); const caffe::BlobProto& weight_blob = binlayer.blobs(0); const caffe::ConvolutionParameter& convolution_param = layer.convolution_param(); fprintf(pp, " 0=%d", convolution_param.num_output()); if (convolution_param.has_kernel_w() && convolution_param.has_kernel_h()) { fprintf(pp, " 1=%d", convolution_param.kernel_w()); fprintf(pp, " 11=%d", convolution_param.kernel_h()); } else { fprintf(pp, " 1=%d", convolution_param.kernel_size(0)); } fprintf(pp, " 2=%d", convolution_param.dilation_size() != 0 ? convolution_param.dilation(0) : 1); if (convolution_param.has_stride_w() && convolution_param.has_stride_h()) { fprintf(pp, " 3=%d", convolution_param.stride_w()); fprintf(pp, " 13=%d", convolution_param.stride_h()); } else { fprintf(pp, " 3=%d", convolution_param.stride_size() != 0 ? convolution_param.stride(0) : 1); } if (convolution_param.has_pad_w() && convolution_param.has_pad_h()) { fprintf(pp, " 4=%d", convolution_param.pad_w()); fprintf(pp, " 14=%d", convolution_param.pad_h()); } else { fprintf(pp, " 4=%d", convolution_param.pad_size() != 0 ? convolution_param.pad(0) : 0); } fprintf(pp, " 5=%d", convolution_param.bias_term()); fprintf(pp, " 6=%d", weight_blob.data_size()); if (layer.type() == "ConvolutionDepthwise") { fprintf(pp, " 7=%d", convolution_param.num_output()); } else if (convolution_param.group() != 1) { fprintf(pp, " 7=%d", convolution_param.group()); } std::cout << "binlayer blob size: " << binlayer.blobs_size() << std::endl; for (int j = 0; j < binlayer.blobs_size(); j++) { int quantize_tag = 0; const caffe::BlobProto& blob = binlayer.blobs(j); std::vector<float> quantize_table; std::vector<unsigned char> quantize_index; std::vector<unsigned short> float16_weights; // we will not quantize the bias values if (j == 0 && quantize_level != 0) { if (quantize_level == 256) { quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), quantize_level, quantize_table, quantize_index); } else if (quantize_level == 65536) { quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), float16_weights); } } // write quantize tag first if (j == 0) fwrite(&quantize_tag, sizeof(int), 1, bp); if (quantize_tag) { int p0 = ftell(bp); if (quantize_level == 256) { // write quantize table and index fwrite(quantize_table.data(), sizeof(float), quantize_table.size(), bp); fwrite(quantize_index.data(), sizeof(unsigned char), quantize_index.size(), bp); } else if (quantize_level == 65536) { fwrite(float16_weights.data(), sizeof(unsigned short), float16_weights.size(), bp); } // padding to 32bit align int nwrite = ftell(bp) - p0; int nalign = alignSize(nwrite, 4); unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00}; fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp); } else { printf("write original data, blob.data_size()=%d\n", blob.data_size()); #if 1 int tempSize = blob.data_size(); if((tempSize==270)||(tempSize==1440)||(tempSize==4608)||(tempSize==756)||(tempSize==12096)||(tempSize==864)||(tempSize==18432)||(tempSize==36864)) { for(int i = 0; i<blob.data_size()/9; i++) { for(int j =0; j<3; j++) { fwrite(blob.data().data()+9*i+j+0, sizeof(float), 1, bp); fwrite(blob.data().data()+9*i+j+3, sizeof(float), 1, bp); fwrite(blob.data().data()+9*i+j+6, sizeof(float), 1, bp); } } } else if((tempSize==12288)||(tempSize==32768)) { for(int i = 0; i<blob.data_size()/4; i++) { for(int j =0; j<2; j++) { fwrite(blob.data().data()+4*i+j+0, sizeof(float), 1, bp); fwrite(blob.data().data()+4*i+j+2, sizeof(float), 1, bp); } } } else { // write original data fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp); } #endif // write original data //fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp); } } } else if (layer.type() == "Crop") { const caffe::CropParameter& crop_param = layer.crop_param(); int num_offset = crop_param.offset_size(); int woffset = (num_offset == 2) ? crop_param.offset(0) : 0; int hoffset = (num_offset == 2) ? crop_param.offset(1) : 0; fprintf(pp, " 0=%d", woffset); fprintf(pp, " 1=%d", hoffset); } else if (layer.type() == "Deconvolution") { const caffe::LayerParameter& binlayer = net.layer(netidx); const caffe::BlobProto& weight_blob = binlayer.blobs(0); const caffe::ConvolutionParameter& convolution_param = layer.convolution_param(); fprintf(pp, " 0=%d", convolution_param.num_output()); if (convolution_param.has_kernel_w() && convolution_param.has_kernel_h()) { fprintf(pp, " 1=%d", convolution_param.kernel_w()); fprintf(pp, " 11=%d", convolution_param.kernel_h()); } else { fprintf(pp, " 1=%d", convolution_param.kernel_size(0)); } fprintf(pp, " 2=%d", convolution_param.dilation_size() != 0 ? convolution_param.dilation(0) : 1); if (convolution_param.has_stride_w() && convolution_param.has_stride_h()) { fprintf(pp, " 3=%d", convolution_param.stride_w()); fprintf(pp, " 13=%d", convolution_param.stride_h()); } else { fprintf(pp, " 3=%d", convolution_param.stride_size() != 0 ? convolution_param.stride(0) : 1); } if (convolution_param.has_pad_w() && convolution_param.has_pad_h()) { fprintf(pp, " 4=%d", convolution_param.pad_w()); fprintf(pp, " 14=%d", convolution_param.pad_h()); } else { fprintf(pp, " 4=%d", convolution_param.pad_size() != 0 ? convolution_param.pad(0) : 0); } fprintf(pp, " 5=%d", convolution_param.bias_term()); fprintf(pp, " 6=%d", weight_blob.data_size()); int group = convolution_param.group(); if (group != 1) { fprintf(pp, " 7=%d", group); } int quantized_weight = 0; fwrite(&quantized_weight, sizeof(int), 1, bp); for (int g=0; g<group; g++) { // reorder weight from inch-outch to outch-inch int ksize = convolution_param.kernel_size(0); int num_output = convolution_param.num_output() / group; int num_input = weight_blob.data_size() / (ksize * ksize) / num_output / group; const float* weight_data_ptr = weight_blob.data().data() + g * (ksize * ksize) * num_output * num_input; for (int k=0; k<num_output; k++) { for (int j=0; j<num_input; j++) { fwrite(weight_data_ptr + (j*num_output + k) * ksize * ksize, sizeof(float), ksize * ksize, bp); } } } for (int j=1; j<binlayer.blobs_size(); j++) { const caffe::BlobProto& blob = binlayer.blobs(j); fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp); } } else if (layer.type() == "DetectionOutput") { const caffe::DetectionOutputParameter& detection_output_param = layer.detection_output_param(); const caffe::NonMaximumSuppressionParameter& nms_param = detection_output_param.nms_param(); fprintf(pp, " 0=%d", detection_output_param.num_classes()); fprintf(pp, " 1=%f", nms_param.nms_threshold()); fprintf(pp, " 2=%d", nms_param.top_k()); fprintf(pp, " 3=%d", detection_output_param.keep_top_k()); fprintf(pp, " 4=%f", detection_output_param.confidence_threshold()); } else if (layer.type() == "Dropout") { const caffe::DropoutParameter& dropout_param = layer.dropout_param(); if (dropout_param.has_scale_train() && !dropout_param.scale_train()) { float scale = 1.f - dropout_param.dropout_ratio(); fprintf(pp, " 0=%f", scale); } } else if (layer.type() == "Eltwise") { const caffe::EltwiseParameter& eltwise_param = layer.eltwise_param(); int coeff_size = eltwise_param.coeff_size(); fprintf(pp, " 0=%d", (int)eltwise_param.operation()); fprintf(pp, " -23301=%d", coeff_size); for (int j=0; j<coeff_size; j++) { fprintf(pp, ",%f", eltwise_param.coeff(j)); } } else if (layer.type() == "ELU") { const caffe::ELUParameter& elu_param = layer.elu_param(); fprintf(pp, " 0=%f", elu_param.alpha()); } else if (layer.type() == "InnerProduct") { std::cout << "===layer type inner product====" << std::endl; const caffe::LayerParameter& binlayer = net.layer(netidx); const caffe::BlobProto& weight_blob = binlayer.blobs(0); const caffe::InnerProductParameter& inner_product_param = layer.inner_product_param(); fprintf(pp, " 0=%d", inner_product_param.num_output()); fprintf(pp, " 1=%d", inner_product_param.bias_term()); fprintf(pp, " 2=%d", weight_blob.data_size()); std::cout << "bin Layer blobs_size: " << binlayer.blobs_size()<< std::endl; for (int j=0; j<binlayer.blobs_size(); j++) { int quantize_tag = 0; const caffe::BlobProto& blob = binlayer.blobs(j); std::vector<float> quantize_table; std::vector<unsigned char> quantize_index; std::vector<unsigned short> float16_weights; // we will not quantize the bias values if (j == 0 && quantize_level != 0) { if (quantize_level == 256) { quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), quantize_level, quantize_table, quantize_index); } else if (quantize_level == 65536) { quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), float16_weights); } } // write quantize tag first if (j == 0) fwrite(&quantize_tag, sizeof(int), 1, bp); if (quantize_tag) { int p0 = ftell(bp); if (quantize_level == 256) { // write quantize table and index fwrite(quantize_table.data(), sizeof(float), quantize_table.size(), bp); fwrite(quantize_index.data(), sizeof(unsigned char), quantize_index.size(), bp); } else if (quantize_level == 65536) { fwrite(float16_weights.data(), sizeof(unsigned short), float16_weights.size(), bp); } // padding to 32bit align int nwrite = ftell(bp) - p0; int nalign = alignSize(nwrite, 4); unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00}; fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp); } else { // write original data printf("InnerProduct blob.data_size() = %d\n", blob.data_size()); int tempSize = blob.data_size(); if((tempSize==73728)||(tempSize==294912)) { for(int i = 0; i<tempSize/9; i++) { for(int j =0; j<3; j++) { fwrite(blob.data().data()+9*i+j+0, sizeof(float), 1, bp); fwrite(blob.data().data()+9*i+j+3, sizeof(float), 1, bp); fwrite(blob.data().data()+9*i+j+6, sizeof(float), 1, bp); } } } else { fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp); } } } } else if (layer.type() == "Input") { const caffe::InputParameter& input_param = layer.input_param(); const caffe::BlobShape& bs = input_param.shape(0); if (bs.dim_size() == 4) { fprintf(pp, " 0=%ld", bs.dim(3)); fprintf(pp, " 1=%ld", bs.dim(2)); fprintf(pp, " 2=%ld", bs.dim(1)); } else if (bs.dim_size() == 3) { fprintf(pp, " 0=%ld", bs.dim(2)); fprintf(pp, " 1=%ld", bs.dim(1)); fprintf(pp, " 2=-233"); } else if (bs.dim_size() == 2) { fprintf(pp, " 0=%ld", bs.dim(1)); fprintf(pp, " 1=-233"); fprintf(pp, " 2=-233"); } } else if (layer.type() == "Interp") { const caffe::InterpParameter& interp_param = layer.interp_param(); fprintf(pp, " 0=%d", 2); fprintf(pp, " 1=%f", (float)interp_param.zoom_factor()); fprintf(pp, " 2=%f", (float)interp_param.zoom_factor()); fprintf(pp, " 3=%d", interp_param.height()); fprintf(pp, " 4=%d", interp_param.width()); } else if (layer.type() == "LRN") { const caffe::LRNParameter& lrn_param = layer.lrn_param(); fprintf(pp, " 0=%d", lrn_param.norm_region()); fprintf(pp, " 1=%d", lrn_param.local_size()); fprintf(pp, " 2=%f", lrn_param.alpha()); fprintf(pp, " 3=%f", lrn_param.beta()); } else if (layer.type() == "MemoryData") { const caffe::MemoryDataParameter& memory_data_param = layer.memory_data_param(); fprintf(pp, " 0=%d", memory_data_param.width()); fprintf(pp, " 1=%d", memory_data_param.height()); fprintf(pp, " 2=%d", memory_data_param.channels()); } else if (layer.type() == "MVN") { const caffe::MVNParameter& mvn_param = layer.mvn_param(); fprintf(pp, " 0=%d", mvn_param.normalize_variance()); fprintf(pp, " 1=%d", mvn_param.across_channels()); fprintf(pp, " 2=%f", mvn_param.eps()); } else if (layer.type() == "Normalize") { const caffe::LayerParameter& binlayer = net.layer(netidx); const caffe::BlobProto& scale_blob = binlayer.blobs(0); const caffe::NormalizeParameter& norm_param = layer.norm_param(); fprintf(pp, " 0=%d", norm_param.across_spatial()); fprintf(pp, " 1=%d", norm_param.channel_shared()); fprintf(pp, " 2=%f", norm_param.eps()); fprintf(pp, " 3=%d", scale_blob.data_size()); fwrite(scale_blob.data().data(), sizeof(float), scale_blob.data_size(), bp); } else if (layer.type() == "Permute") { const caffe::PermuteParameter& permute_param = layer.permute_param(); int order_size = permute_param.order_size(); int order_type = 0; if (order_size == 0) order_type = 0; if (order_size == 1) { int order0 = permute_param.order(0); if (order0 == 0) order_type = 0; // permute with N not supported } if (order_size == 2) { int order0 = permute_param.order(0); int order1 = permute_param.order(1); if (order0 == 0) { if (order1 == 1) // 0 1 2 3 order_type = 0; else if (order1 == 2) // 0 2 1 3 order_type = 2; else if (order1 == 3) // 0 3 1 2 order_type = 4; } // permute with N not supported } if (order_size == 3 || order_size == 4) { int order0 = permute_param.order(0); int order1 = permute_param.order(1); int order2 = permute_param.order(2); if (order0 == 0) { if (order1 == 1) { if (order2 == 2) // 0 1 2 3 order_type = 0; if (order2 == 3) // 0 1 3 2 order_type = 1; } else if (order1 == 2) { if (order2 == 1) // 0 2 1 3 order_type = 2; if (order2 == 3) // 0 2 3 1 order_type = 3; } else if (order1 == 3) { if (order2 == 1) // 0 3 1 2 order_type = 4; if (order2 == 2) // 0 3 2 1 order_type = 5; } } // permute with N not supported } fprintf(pp, " 0=%d", order_type); } else if (layer.type() == "Pooling") { const caffe::PoolingParameter& pooling_param = layer.pooling_param(); fprintf(pp, " 0=%d", pooling_param.pool()); if (pooling_param.has_kernel_w() && pooling_param.has_kernel_h()) { fprintf(pp, " 1=%d", pooling_param.kernel_w()); fprintf(pp, " 11=%d", pooling_param.kernel_h()); } else { fprintf(pp, " 1=%d", pooling_param.kernel_size()); } if (pooling_param.has_stride_w() && pooling_param.has_stride_h()) { fprintf(pp, " 2=%d", pooling_param.stride_w()); fprintf(pp, " 12=%d", pooling_param.stride_h()); } else { fprintf(pp, " 2=%d", pooling_param.stride()); } if (pooling_param.has_pad_w() && pooling_param.has_pad_h()) { fprintf(pp, " 3=%d", pooling_param.pad_w()); fprintf(pp, " 13=%d", pooling_param.pad_h()); } else { fprintf(pp, " 3=%d", pooling_param.pad()); } fprintf(pp, " 4=%d", pooling_param.has_global_pooling() ? pooling_param.global_pooling() : 0); } else if (layer.type() == "Power") { const caffe::PowerParameter& power_param = layer.power_param(); fprintf(pp, " 0=%f", power_param.power()); fprintf(pp, " 1=%f", power_param.scale()); fprintf(pp, " 2=%f", power_param.shift()); } else if (layer.type() == "PReLU") { const caffe::LayerParameter& binlayer = net.layer(netidx); const caffe::BlobProto& slope_blob = binlayer.blobs(0); fprintf(pp, " 0=%d", slope_blob.data_size()); fwrite(slope_blob.data().data(), sizeof(float), slope_blob.data_size(), bp); } else if (layer.type() == "PriorBox") { const caffe::PriorBoxParameter& prior_box_param = layer.prior_box_param(); int num_aspect_ratio = prior_box_param.aspect_ratio_size(); for (int j=0; j<prior_box_param.aspect_ratio_size(); j++) { float ar = prior_box_param.aspect_ratio(j); if (fabs(ar - 1.) < 1e-6) { num_aspect_ratio--; } } float variances[4] = {0.1f, 0.1f, 0.1f, 0.1f}; if (prior_box_param.variance_size() == 4) { variances[0] = prior_box_param.variance(0); variances[1] = prior_box_param.variance(1); variances[2] = prior_box_param.variance(2); variances[3] = prior_box_param.variance(3); } else if (prior_box_param.variance_size() == 1) { variances[0] = prior_box_param.variance(0); variances[1] = prior_box_param.variance(0); variances[2] = prior_box_param.variance(0); variances[3] = prior_box_param.variance(0); } int flip = prior_box_param.has_flip() ? prior_box_param.flip() : 1; int clip = prior_box_param.has_clip() ? prior_box_param.clip() : 0; int image_width = -233; int image_height = -233; if (prior_box_param.has_img_size()) { image_width = prior_box_param.img_size(); image_height = prior_box_param.img_size(); } else if (prior_box_param.has_img_w() && prior_box_param.has_img_h()) { image_width = prior_box_param.img_w(); image_height = prior_box_param.img_h(); } float step_width = -233; float step_height = -233; if (prior_box_param.has_step()) { step_width = prior_box_param.step(); step_height = prior_box_param.step(); } else if (prior_box_param.has_step_w() && prior_box_param.has_step_h()) { step_width = prior_box_param.step_w(); step_height = prior_box_param.step_h(); } fprintf(pp, " -23300=%d", prior_box_param.min_size_size()); for (int j=0; j<prior_box_param.min_size_size(); j++) { fprintf(pp, ",%f", prior_box_param.min_size(j)); } fprintf(pp, " -23301=%d", prior_box_param.max_size_size()); for (int j=0; j<prior_box_param.max_size_size(); j++) { fprintf(pp, ",%f", prior_box_param.max_size(j)); } fprintf(pp, " -23302=%d", num_aspect_ratio); for (int j=0; j<prior_box_param.aspect_ratio_size(); j++) { float ar = prior_box_param.aspect_ratio(j); if (fabs(ar - 1.) < 1e-6) { continue; } fprintf(pp, ",%f", ar); } fprintf(pp, " 3=%f", variances[0]); fprintf(pp, " 4=%f", variances[1]); fprintf(pp, " 5=%f", variances[2]); fprintf(pp, " 6=%f", variances[3]); fprintf(pp, " 7=%d", flip); fprintf(pp, " 8=%d", clip); fprintf(pp, " 9=%d", image_width); fprintf(pp, " 10=%d", image_height); fprintf(pp, " 11=%f", step_width); fprintf(pp, " 12=%f", step_height); fprintf(pp, " 13=%f", prior_box_param.offset()); } else if (layer.type() == "Python") { const caffe::PythonParameter& python_param = layer.python_param(); std::string python_layer_name = python_param.layer(); if (python_layer_name == "ProposalLayer") { int feat_stride = 16; sscanf(python_param.param_str().c_str(), "'feat_stride': %d", &feat_stride); int base_size = 16; // float ratio; // float scale; int pre_nms_topN = 6000; int after_nms_topN = 300; float nms_thresh = 0.7; int min_size = 16; fprintf(pp, " 0=%d", feat_stride); fprintf(pp, " 1=%d", base_size); fprintf(pp, " 2=%d", pre_nms_topN); fprintf(pp, " 3=%d", after_nms_topN); fprintf(pp, " 4=%f", nms_thresh); fprintf(pp, " 5=%d", min_size); } } else if (layer.type() == "ReLU") { const caffe::ReLUParameter& relu_param = layer.relu_param(); if (relu_param.has_negative_slope()) { fprintf(pp, " 0=%f", relu_param.negative_slope()); } } else if (layer.type() == "Reshape") { const caffe::ReshapeParameter& reshape_param = layer.reshape_param(); const caffe::BlobShape& bs = reshape_param.shape(); if (bs.dim_size() == 1) { fprintf(pp, " 0=%ld 1=-233 2=-233", bs.dim(0)); } else if (bs.dim_size() == 2) { fprintf(pp, " 0=%ld 1=%ld 2=-233", bs.dim(1), bs.dim(0)); } else if (bs.dim_size() == 3) { fprintf(pp, " 0=%ld 1=%ld 2=%ld", bs.dim(2), bs.dim(1), bs.dim(0)); } else // bs.dim_size() == 4 { fprintf(pp, " 0=%ld 1=%ld 2=%ld", bs.dim(3), bs.dim(2), bs.dim(1)); } fprintf(pp, " 3=0");// permute } else if (layer.type() == "ROIPooling") { const caffe::ROIPoolingParameter& roi_pooling_param = layer.roi_pooling_param(); fprintf(pp, " 0=%d", roi_pooling_param.pooled_w()); fprintf(pp, " 1=%d", roi_pooling_param.pooled_h()); fprintf(pp, " 2=%f", roi_pooling_param.spatial_scale()); } else if (layer.type() == "Scale") { const caffe::LayerParameter& binlayer = net.layer(netidx); const caffe::ScaleParameter& scale_param = layer.scale_param(); bool scale_weight = scale_param.bias_term() ? (binlayer.blobs_size() == 2) : (binlayer.blobs_size() == 1); if (scale_weight) { const caffe::BlobProto& weight_blob = binlayer.blobs(0); fprintf(pp, " 0=%d", (int)weight_blob.data_size()); } else { fprintf(pp, " 0=-233"); } fprintf(pp, " 1=%d", scale_param.bias_term()); for (int j=0; j<binlayer.blobs_size(); j++) { const caffe::BlobProto& blob = binlayer.blobs(j); fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp); } } else if (layer.type() == "ShuffleChannel") { const caffe::ShuffleChannelParameter& shuffle_channel_param = layer.shuffle_channel_param(); fprintf(pp, " 0=%d", shuffle_channel_param.group()); } else if (layer.type() == "Slice") { const caffe::SliceParameter& slice_param = layer.slice_param(); if (slice_param.slice_point_size() == 0) { int num_slice = layer.top_size(); fprintf(pp, " -23300=%d", num_slice); for (int j=0; j<num_slice; j++) { fprintf(pp, ",-233"); } } else { int num_slice = slice_param.slice_point_size() + 1; fprintf(pp, " -23300=%d", num_slice); int prev_offset = 0; for (int j=0; j<slice_param.slice_point_size(); j++) { int offset = slice_param.slice_point(j); fprintf(pp, ",%d", offset - prev_offset); prev_offset = offset; } fprintf(pp, ",-233"); } int dim = slice_param.axis() - 1; fprintf(pp, " 1=%d", dim); } else if (layer.type() == "Softmax") { const caffe::SoftmaxParameter& softmax_param = layer.softmax_param(); int dim = softmax_param.axis() - 1; fprintf(pp, " 0=%d", dim); } else if (layer.type() == "Threshold") { const caffe::ThresholdParameter& threshold_param = layer.threshold_param(); fprintf(pp, " 0=%f", threshold_param.threshold()); } fprintf(pp, "\n"); // add split layer if top reference larger than one if (layer.bottom_size() == 1 && layer.top_size() == 1 && layer.bottom(0) == layer.top(0)) { std::string blob_name = blob_name_decorated[layer.top(0)]; if (bottom_reference.find(blob_name) != bottom_reference.end()) { int refcount = bottom_reference[blob_name]; if (refcount > 1) { char splitname[256]; sprintf(splitname, "splitncnn_%d", internal_split); fprintf(pp, "%-16s %-16s %d %d", "Split", splitname, 1, refcount); fprintf(pp, " %s", blob_name.c_str()); for (int j=0; j<refcount; j++) { fprintf(pp, " %s_splitncnn_%d", blob_name.c_str(), j); } fprintf(pp, "\n"); internal_split++; } } } else { for (int j=0; j<layer.top_size(); j++) { std::string blob_name = layer.top(j); if (bottom_reference.find(blob_name) != bottom_reference.end()) { int refcount = bottom_reference[blob_name]; if (refcount > 1) { char splitname[256]; sprintf(splitname, "splitncnn_%d", internal_split); fprintf(pp, "%-16s %-16s %d %d", "Split", splitname, 1, refcount); fprintf(pp, " %s", blob_name.c_str()); for (int j=0; j<refcount; j++) { fprintf(pp, " %s_splitncnn_%d", blob_name.c_str(), j); } fprintf(pp, "\n"); internal_split++; } } } } } fclose(pp); fclose(bp); return 0; }
37.530874
162
0.495395
[ "shape", "vector" ]
43550d21b504b5eb90dce3c30b9b468ca8658797
1,480
cpp
C++
KJSC2020/Octave-Tunes/setter.cpp
KJSCE-Codecell/Contests
c47732ed413587c98061d14e103da9cee425d809
[ "MIT" ]
2
2018-09-09T07:40:23.000Z
2018-09-13T15:35:19.000Z
KJSC2020/Octave-Tunes/setter.cpp
KJSCE-Codecell/Contests
c47732ed413587c98061d14e103da9cee425d809
[ "MIT" ]
null
null
null
KJSC2020/Octave-Tunes/setter.cpp
KJSCE-Codecell/Contests
c47732ed413587c98061d14e103da9cee425d809
[ "MIT" ]
1
2018-09-09T08:38:16.000Z
2018-09-09T08:38:16.000Z
#include <bits/stdc++.h> using namespace std; typedef vector<int> vi; typedef vector<long long> vl; typedef pair<int, int> pii; #define endl "\n" #define debug(val) printf("check%d\n", val) #define all(v) v.begin(), v.end() #define pb push_back #define mp make_pair #define FF first #define SS second #define ll long long #define ull unsigned long long #define FOR(i, j, k, in) for (int i = j; i < k; i += in) #define forr(k) for (int i = 0; i < k; i += 1) #define For(j, k) for (int i = j; i < k; i += 1) #define MOD 1000000007 #define clr(val) memset(val, 0, sizeof(val)) #define what_is(x) cerr << #x << " is " << x << endl; #define OJ \ freopen("input6.txt", "r", stdin); \ freopen("output6.txt", "w", stdout); #define FIO \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); int main() { FIO; ll t; cin >> t; while (t--) { ll n, temp; ll min = 1000000000; cin >> n; ll count = 0; map<int, ll> m; for (ll i = 0; i < n; i++) { cin >> temp; m[temp]++; } for (auto &k : m) { count++; if (k.second < min) { min = k.second; } } if (count < 8) { cout << 0 << endl; } else cout << min << endl; } return 0; }
22.424242
56
0.460135
[ "vector" ]
435a812d6e693bd391367393b8d34d90bb9f33c9
365
cpp
C++
Algorithms/1800.Maximum_Ascending_Subarray_Sum.cpp
metehkaya/LeetCode
52f4a1497758c6f996d515ced151e8783ae4d4d2
[ "MIT" ]
2
2020-07-20T06:40:22.000Z
2021-11-20T01:23:26.000Z
Problems/LeetCode/Problems/1800.Maximum_Ascending_Subarray_Sum.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
Problems/LeetCode/Problems/1800.Maximum_Ascending_Subarray_Sum.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
class Solution { public: int maxAscendingSum(vector<int>& ar) { int ans = 0; int n = ar.size(); for( int i = 0 , j = 0 ; i < n ; i = j+1 ) { j = i; int sum = ar[i]; while(j+1 < n && ar[j] < ar[j+1]) sum += ar[++j]; ans = max(ans,sum); } return ans; } };
24.333333
52
0.364384
[ "vector" ]
435f04e7f3617be99f825ae1dea81372e4c015b0
5,823
cpp
C++
src/camera/camera_pinhole.cpp
infobeisel/lightmetrica-v3
833d74e5ed8a470c33aca100c9494be11ecbf1be
[ "MIT" ]
null
null
null
src/camera/camera_pinhole.cpp
infobeisel/lightmetrica-v3
833d74e5ed8a470c33aca100c9494be11ecbf1be
[ "MIT" ]
null
null
null
src/camera/camera_pinhole.cpp
infobeisel/lightmetrica-v3
833d74e5ed8a470c33aca100c9494be11ecbf1be
[ "MIT" ]
1
2021-05-19T14:44:01.000Z
2021-05-19T14:44:01.000Z
/* Lightmetrica - Copyright (c) 2019 Hisanari Otsu Distributed under MIT license. See LICENSE file for details. */ #include <pch.h> #include <lm/core.h> #include <lm/camera.h> #include <lm/film.h> LM_NAMESPACE_BEGIN(LM_NAMESPACE) /* \rst .. function:: camera::pinhole Pinhole camera. :param str film: Underlying film specified by asset name or locator. :param vec3 position: Camera position. :param vec3 center: Look-at position. :param vec3 up: Up vector. :param float vfov: Vertical field of view. This component implements pinhole camera where all the incoming lights pass through an small aperture and projected onto a film in the opposite side of the aperture. Unlike real pinhole camera, the apearture is modeled as a point, and the film can be placed in front of the pinhole. The configuration of the pinhole camera is described by a 3-tuple by ``position``, ``center``, and ``up`` vector. ``position`` represents a position of the pinhole, ``center`` for look-at position. This means the camera faces toward the direction to ``center`` from ``position``. ``up`` describes the upward direction of the camera. Field of view (FoV) describe the extent of the viewing angle of the camera. In this implementation, the configuration is given by ``vfov`` parameter. Note that we adopted vertical FoV. Be careful if you want to convert from other tools that might adopt horizontal FoV. \endrst */ class Camera_Pinhole final : public Camera { private: Vec3 position_; // Camera position Vec3 center_; // Lookat position Vec3 up_; // Up vector Vec3 u_, v_, w_; // Basis for camera coordinates Float vfov_; // Vertical field of view Float tf_; // Half of the screen height at 1 unit forward from the position public: LM_SERIALIZE_IMPL(ar) { ar(position_, center_, up_, u_, v_, w_, vfov_, tf_); } public: virtual Json underlying_value(const std::string&) const override { return { {"eye", position_}, {"center", center_}, {"up", up_}, {"vfov", vfov_} }; } virtual void construct(const Json& prop) override { const auto it = prop.find("matrix"); if (it != prop.end()) { Mat4 viewM = *it; position_ = Vec3(viewM[3]); const auto viewM3 = Mat3(viewM); u_ = -viewM3[0]; v_ = viewM3[1]; w_ = -viewM3[2]; } else { position_ = json::value<Vec3>(prop, "position"); // Camera position center_ = json::value<Vec3>(prop, "center"); // Look-at position up_ = json::value<Vec3>(prop, "up"); // Up vector w_ = glm::normalize(position_ - center_); // Compute basis u_ = glm::normalize(glm::cross(up_, w_)); v_ = cross(w_, u_); } vfov_ = json::value<Float>(prop, "vfov"); // Vertical FoV tf_ = tan(vfov_ * Pi / 180_f * .5_f); // Precompute half of screen height } virtual bool is_specular(const PointGeometry&) const override { return false; } virtual Ray primary_ray(Vec2 rp, Float aspect_ratio) const override { rp = 2_f*rp-1_f; const auto d = glm::normalize(Vec3(aspect_ratio*tf_*rp.x, tf_*rp.y, -1_f)); return { position_, u_*d.x+v_*d.y+w_*d.z }; } virtual std::optional<Vec2> raster_position(Vec3 wo, Float aspect_ratio) const override { // Convert to camera space const auto to_eye = glm::transpose(Mat3(u_, v_, w_)); const auto wo_eye = to_eye * wo; if (wo_eye.z >= 0) { // wo is directed to the opposition direction return {}; } // Calculate raster position const auto rp = Vec2( -wo_eye.x/wo_eye.z/tf_/aspect_ratio, -wo_eye.y/wo_eye.z/tf_)*.5_f + .5_f; if (rp.x < 0_f || rp.x > 1_f || rp.y < 0_f || rp.y > 1_f) { // wo is not in the view frustum return {}; } return rp; } virtual std::optional<CameraRaySample> sample_primary_ray(Rng& rng, Vec4 window, Float aspect_ratio) const override { const auto [x, y, w, h] = window.data.data; return CameraRaySample{ PointGeometry::make_degenerated(position_), primary_ray({x+w*rng.u(), y+h*rng.u()}, aspect_ratio).d, Vec3(1_f) }; } virtual Float pdf(Vec3 wo, Float aspect_ratio) const override { // Given directions is not samplable if raster position is not in [0,1]^2 if (!raster_position(wo, aspect_ratio)) { return 0_f; } return J(wo, aspect_ratio); } virtual Vec3 eval(Vec3 wo, Float aspect_ratio) const override { if (!raster_position(wo, aspect_ratio)) { return Vec3(0_f); } return Vec3(J(wo, aspect_ratio)); } virtual Mat4 view_matrix() const override { return glm::lookAt(position_, position_ - w_, up_); } virtual Mat4 projection_matrix(Float aspect_ratio) const override { return glm::perspective(glm::radians(vfov_), aspect_ratio, 0.01_f, 10000_f); } private: // Compute Jacobian // TODO. Add derivation in documentataion Float J(Vec3 wo, Float aspect_ratio) const { const auto V = glm::transpose(Mat3(u_, v_, w_)); const auto wo_eye = V * wo; const Float cos_theta = -wo_eye.z; const Float inv_cos_theta = 1_f / cos_theta; const Float A = tf_ * tf_ * aspect_ratio * 4_f; return inv_cos_theta * inv_cos_theta * inv_cos_theta / A; } }; LM_COMP_REG_IMPL(Camera_Pinhole, "camera::pinhole"); LM_NAMESPACE_END(LM_NAMESPACE)
34.455621
121
0.607762
[ "vector" ]
cb1efd95751ad79ca07e9567ca49170f7c42f03f
14,138
cpp
C++
src/SymtabBuilder.cpp
gian21391/synthlib2parser
5c0d385c87c579178adb118aadb4acbd2af60e02
[ "BSD-3-Clause" ]
null
null
null
src/SymtabBuilder.cpp
gian21391/synthlib2parser
5c0d385c87c579178adb118aadb4acbd2af60e02
[ "BSD-3-Clause" ]
null
null
null
src/SymtabBuilder.cpp
gian21391/synthlib2parser
5c0d385c87c579178adb118aadb4acbd2af60e02
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2013, Abhishek Udupa, Mukund Raghothaman, The University of Pennsylvania All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of 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 <LogicSymbols.hpp> #include <SymtabBuilder.hpp> namespace SynthLib2Parser { SymtabBuilder::SymtabBuilder(SymbolTable* TheSymbolTable) : ASTVisitorBase("SymtabBuilder"), TheSymbolTable(TheSymbolTable) { // Nothing here } SymtabBuilder::~SymtabBuilder() { // Nothing here } void SymtabBuilder::VisitProgram(const Program* Prog) { // Delegate to base class ASTVisitorBase::VisitProgram(Prog); } void SymtabBuilder::VisitFunDefCmd(const FunDefCmd* Cmd) { // previsit. Push a new scope onto the symbol table TheSymbolTable->Push(); // Check that the formals are okay. // And bind them in the new scope // also gather the argument sorts for later use vector<const SortExpr*> ArgSorts; for(auto const& ASPair : Cmd->GetArgs()) { ASPair->Accept(this); TheSymbolTable->BindFormal(ASPair->GetName(), static_cast<const SortExpr*>(ASPair->GetSort()->Clone())); ArgSorts.push_back(ASPair->GetSort()); } // Check that the type of the term is the same as the one declared // Push the builder through the term to ensure that let-bound terms are // appropriately bound Cmd->GetTerm()->Accept(this); auto TermSort = Cmd->GetTerm()->GetTermSort(TheSymbolTable); auto ExpTermSort = Cmd->GetSort(); if(!TheSymbolTable->ResolveSort(TermSort)->Equals(*(TheSymbolTable->ResolveSort(ExpTermSort)))) { throw SynthLib2ParserException((string)"Definition of function symbol \"" + Cmd->GetFunName() + "\" does not match expected sort\n" + Cmd->GetLocation().ToString()); } Cmd->SetScope(TheSymbolTable->Pop()); // Finally, we check that a function of the same name // is not already defined if (TheSymbolTable->LookupFun(Cmd->GetFunName(), ArgSorts) != NULL) { throw SynthLib2ParserException((string)"Function with name \"" + Cmd->GetFunName() + "\" has already been defined/declared.\n" + Cmd->GetLocation().ToString()); } // All seems good. // Bind the def TheSymbolTable->BindUserFun(static_cast<FunDefCmd*>(Cmd->Clone())); } void SymtabBuilder::VisitFunDeclCmd(const FunDeclCmd* Cmd) { // Recurse to make sure all sorts are well formed ASTVisitorBase::VisitFunDeclCmd(Cmd); // Ensure that no other function symbol exists if (TheSymbolTable->LookupFun(Cmd->GetFunName(), Cmd->GetArgSorts()) != NULL) { throw SynthLib2ParserException((string)"Function with name \"" + Cmd->GetFunName() + "\" has already been defined/declared.\n" + Cmd->GetLocation().ToString()); } // Bind this func decl TheSymbolTable->BindUninterpFun(Cmd->GetFunName(), CloneVector(Cmd->GetArgSorts()), static_cast<const SortExpr*>(Cmd->GetSort())); } void SymtabBuilder::VisitSynthFunCmd(const SynthFunCmd* Cmd) { // Push a new scope TheSymbolTable->Push(); ASTVisitorBase::VisitSynthFunCmd(Cmd); // All is good Cmd->SetScope(TheSymbolTable->Pop()); // Gather the arg sorts auto const& Args = Cmd->GetArgs(); const u32 NumArgs = Args.size(); vector<const SortExpr*> ArgSorts(NumArgs); for(u32 i = 0; i < NumArgs; ++i) { ArgSorts[i] = Args[i]->GetSort(); } // Check that no function exists of the same name if (TheSymbolTable->LookupFun(Cmd->GetFunName(), ArgSorts) != NULL) { throw SynthLib2ParserException((string)"Function with name \"" + Cmd->GetFunName() + "\" has already been defined/declared.\n" + Cmd->GetLocation().ToString()); } // Bind TheSymbolTable->BindSynthFun(Cmd->GetFunName(), CloneVector(ArgSorts), static_cast<SortExpr*>(Cmd->GetSort()->Clone())); } void SymtabBuilder::VisitSortDefCmd(const SortDefCmd* Cmd) { ASTVisitorBase::VisitSortDefCmd(Cmd); // Check for redeclaration vector<const SortExpr*> ArgSortDummy; if (TheSymbolTable->LookupSort(Cmd->GetName()) != NULL || TheSymbolTable->LookupVariable(Cmd->GetName()) != NULL || TheSymbolTable->LookupFun(Cmd->GetName(), ArgSortDummy) != NULL) { throw SynthLib2ParserException((string)"Identifier \"" + Cmd->GetName() + "\" has " + "already been declared/defined as a sort/variable/constant.\n" + Cmd->GetLocation().ToString()); } // Bind TheSymbolTable->BindSort(Cmd->GetName(), static_cast<SortExpr*>(Cmd->GetSortExpr()->Clone())); } void SymtabBuilder::VisitSetOptsCmd(const SetOptsCmd* Cmd) { ASTVisitorBase::VisitSetOptsCmd(Cmd); } void SymtabBuilder::VisitVarDeclCmd(const VarDeclCmd* Cmd) { // Ensure that the sort is okay ASTVisitorBase::VisitVarDeclCmd(Cmd); // Check for redeclarations vector<const SortExpr*> ArgSortDummy; if (TheSymbolTable->LookupSort(Cmd->GetName()) != NULL || TheSymbolTable->LookupVariable(Cmd->GetName()) != NULL || TheSymbolTable->LookupFun(Cmd->GetName(), ArgSortDummy) != NULL) { throw SynthLib2ParserException((string)"Identifier \"" + Cmd->GetName() + "\" has " + "already been declared/defined as a sort/variable/constant.\n" + Cmd->GetLocation().ToString()); } // Bind TheSymbolTable->BindVariable(Cmd->GetName(), static_cast<SortExpr*>(Cmd->GetSort()->Clone())); } void SymtabBuilder::VisitConstraintCmd(const ConstraintCmd* Cmd) { // Check that the type of the term is okay auto Sort = Cmd->GetTerm()->GetTermSort(TheSymbolTable); if (TheSymbolTable->ResolveSort(Sort)->GetKind() != SORTKIND_BOOL) { throw SynthLib2ParserException((string)"Constraint terms must be boolean typed.\n" + Cmd->GetLocation().ToString()); } // Do nothing otherwise return; } void SymtabBuilder::VisitSetLogicCmd(const SetLogicCmd* Cmd) { ASTVisitorBase::VisitSetLogicCmd(Cmd); } void SymtabBuilder::VisitCheckSynthCmd(const CheckSynthCmd* Cmd) { ASTVisitorBase::VisitCheckSynthCmd(Cmd); } void SymtabBuilder::VisitArgSortPair(const ArgSortPair* ASPair) { // Just check that the sort is well formed ASTVisitorBase::VisitArgSortPair(ASPair); } void SymtabBuilder::VisitIntSortExpr(const IntSortExpr* Sort) { ASTVisitorBase::VisitIntSortExpr(Sort); } void SymtabBuilder::VisitBVSortExpr(const BVSortExpr* Sort) { ASTVisitorBase::VisitBVSortExpr(Sort); LogicSymbolLoader::RegisterSort(TheSymbolTable, Sort); } void SymtabBuilder::VisitNamedSortExpr(const NamedSortExpr* Sort) { // Check that the named sort actually resolves to something auto STE = TheSymbolTable->LookupSort(Sort->GetName()); if(STE == NULL || STE->GetKind() != STENTRY_SORT) { throw SynthLib2ParserException((string)"Sort name \"" + Sort->GetName() + "\" could not " + "be resolved to anything meaningful.\n" + Sort->GetLocation().ToString()); } auto SortE = STE->GetSort(); if (TheSymbolTable->ResolveSort(SortE) == NULL) { throw SynthLib2ParserException((string)"Sort name \"" + Sort->GetName() + "\" could not " + "be resolved to anything meaningful.\n" + Sort->GetLocation().ToString()); } // Do nothing otherwise return; } void SymtabBuilder::VisitArraySortExpr(const ArraySortExpr* Sort) { ASTVisitorBase::VisitArraySortExpr(Sort); LogicSymbolLoader::RegisterSort(TheSymbolTable, Sort); } void SymtabBuilder::VisitRealSortExpr(const RealSortExpr* Sort) { ASTVisitorBase::VisitRealSortExpr(Sort); } void SymtabBuilder::VisitFunSortExpr(const FunSortExpr* Sort) { ASTVisitorBase::VisitFunSortExpr(Sort); } void SymtabBuilder::VisitBoolSortExpr(const BoolSortExpr* Sort) { ASTVisitorBase::VisitBoolSortExpr(Sort); } void SymtabBuilder::VisitEnumSortExpr(const EnumSortExpr* Sort) { ASTVisitorBase::VisitEnumSortExpr(Sort); LogicSymbolLoader::RegisterSort(TheSymbolTable, Sort); } void SymtabBuilder::VisitLetBindingTerm(const LetBindingTerm* Binding) { // Check the sorts ASTVisitorBase::VisitLetBindingTerm(Binding); // Check that the sort of the term is what is expected auto TermSort = Binding->GetBoundToTerm()->GetTermSort(TheSymbolTable); auto ExpectedSort = Binding->GetVarSort(); if (!TheSymbolTable->ResolveSort(TermSort)->Equals(*(TheSymbolTable->ResolveSort(ExpectedSort)))) { throw SynthLib2ParserException((string)"Let bound term \"" + Binding->GetVarName() + "\" does not match the expected sort.\n" + Binding->GetLocation().ToString()); } // let bound terms can shadow anything TheSymbolTable->BindLetVariable(Binding->GetVarName(), static_cast<Term*>(Binding->GetBoundToTerm()->Clone())); return; } void SymtabBuilder::VisitFunTerm(const FunTerm* TheTerm) { ASTVisitorBase::VisitFunTerm(TheTerm); } void SymtabBuilder::VisitLiteralTerm(const LiteralTerm* TheTerm) { ASTVisitorBase::VisitLiteralTerm(TheTerm); } void SymtabBuilder::VisitSymbolTerm(const SymbolTerm* TheTerm) { ASTVisitorBase::VisitSymbolTerm(TheTerm); } void SymtabBuilder::VisitLetTerm(const LetTerm* TheTerm) { // Push a new scope TheSymbolTable->Push(); // Visit the bindings to ensure that everything is in order // This process also creates the bindings in the current scope ASTVisitorBase::VisitLetTerm(TheTerm); // Push the scope to the let term TheTerm->SetScope(TheSymbolTable->Pop()); return; } void SymtabBuilder::VisitLetBindingGTerm(const LetBindingGTerm* Binding) { // We don't handle this here. // except for checking the sort exprs ASTVisitorBase::VisitLetBindingGTerm(Binding); } void SymtabBuilder::VisitFunGTerm(const FunGTerm* TheTerm) { ASTVisitorBase::VisitFunGTerm(TheTerm); } void SymtabBuilder::VisitLiteralGTerm(const LiteralGTerm* TheTerm) { ASTVisitorBase::VisitLiteralGTerm(TheTerm); } void SymtabBuilder::VisitSymbolGTerm(const SymbolGTerm* TheTerm) { ASTVisitorBase::VisitSymbolGTerm(TheTerm); } void SymtabBuilder::VisitLetGTerm(const LetGTerm* TheTerm) { ASTVisitorBase::VisitLetGTerm(TheTerm); } void SymtabBuilder::VisitConstantGTerm(const ConstantGTerm* TheTerm) { ASTVisitorBase::VisitConstantGTerm(TheTerm); } void SymtabBuilder::VisitVariableGTerm(const VariableGTerm* TheTerm) { ASTVisitorBase::VisitVariableGTerm(TheTerm); } void SymtabBuilder::VisitNTDef(const NTDef* Def) { ASTVisitorBase::VisitNTDef(Def); } void SymtabBuilder::VisitLiteral(const Literal* TheLiteral) { ASTVisitorBase::VisitLiteral(TheLiteral); } void SymtabBuilder::Do(const Program* Prog, SymbolTable* TheSymbolTable) { SymtabBuilder Builder(TheSymbolTable); Prog->Accept(&Builder); } } /* end namespace */
37.107612
107
0.615363
[ "vector" ]
cb20881c1c5f784c44d40ecf1a384600e9580eb5
7,956
cc
C++
src/relay/op/nn/upsampling.cc
jiangzoi/incubator-tvm
144c6f45f7217b9df2f5605e06f0903e470ac11c
[ "Apache-2.0" ]
9
2019-12-17T08:03:54.000Z
2022-01-19T02:34:23.000Z
src/relay/op/nn/upsampling.cc
jiangzoi/incubator-tvm
144c6f45f7217b9df2f5605e06f0903e470ac11c
[ "Apache-2.0" ]
2
2020-06-18T21:15:42.000Z
2020-06-24T17:38:37.000Z
src/relay/op/nn/upsampling.cc
jiangzoi/incubator-tvm
144c6f45f7217b9df2f5605e06f0903e470ac11c
[ "Apache-2.0" ]
3
2020-10-04T20:30:18.000Z
2022-01-24T18:03:52.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file upsampling.cc * \brief upsampling operator */ #include <tvm/relay/attrs/nn.h> #include <tvm/relay/op.h> #include <tvm/relay/op_attr_types.h> #include <tvm/tir/data_layout.h> #include <vector> #include "../op_common.h" namespace tvm { namespace relay { TVM_REGISTER_NODE_TYPE(UpSamplingAttrs); TVM_REGISTER_NODE_TYPE(UpSampling3DAttrs); template <typename T> Array<Array<Layout> > UpsamplingInferCorrectLayout(const Attrs& attrs, const Array<Layout>& new_in_layouts, const Array<Layout>& old_in_layouts, const Array<tvm::relay::Type>& old_in_types) { // NOTE: Discard "const" qualifier here. T* params = const_cast<T*>(attrs.as<T>()); if (new_in_layouts.defined()) { CHECK_EQ(new_in_layouts.size(), 1); Layout raw_layout(params->layout); Layout input = new_in_layouts[0]; if (input.IndexOf(LayoutAxis::Get('W')) == raw_layout.IndexOf(LayoutAxis::Get('W')) && input.IndexOf(LayoutAxis::Get('H')) == raw_layout.IndexOf(LayoutAxis::Get('H')) && !input.Contains(LayoutAxis::Get('w')) && !input.Contains(LayoutAxis::Get('h')) && (input.IndexOf(LayoutAxis::Get('D')) == -1 || (input.IndexOf(LayoutAxis::Get('D')) == raw_layout.IndexOf(LayoutAxis::Get('D')) && !input.Contains(LayoutAxis::Get('d'))))) { params->layout = input.name(); // modify self to follow the input layout } } Layout inferred_layout(params->layout); return Array<Array<Layout> >{{inferred_layout}, {inferred_layout}}; } bool UpSamplingRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { CHECK_EQ(types.size(), 2); const auto* data = types[0].as<TensorTypeNode>(); if (data == nullptr) return false; static const Layout kNCHW("NCHW"); const UpSamplingAttrs* param = attrs.as<UpSamplingAttrs>(); CHECK(param != nullptr); const Layout in_layout(param->layout); auto layout_converter = tir::BijectiveLayout(in_layout, kNCHW); CHECK(layout_converter.defined()) << "UpSampling only support input layouts that are convertible from NCHW." << " But got " << in_layout; auto oshape = layout_converter.ForwardShape(data->shape); oshape.Set(2, tir::Cast(oshape[2].dtype(), tvm::round(oshape[2] * param->scale_h))); oshape.Set(3, tir::Cast(oshape[3].dtype(), tvm::round(oshape[3] * param->scale_w))); // assign output type reporter->Assign(types[1], TensorType(layout_converter.BackwardShape(oshape), data->dtype)); return true; } // Positional relay function to create upsampling operator // used by frontend FFI. Expr MakeUpSampling(Expr data, double scale_h, double scale_w, String layout, String method, bool align_corners) { auto attrs = make_object<UpSamplingAttrs>(); attrs->layout = std::move(layout); attrs->method = std::move(method); attrs->scale_h = scale_h; attrs->scale_w = scale_w; attrs->align_corners = align_corners; static const Op& op = Op::Get("nn.upsampling"); return Call(op, {data}, Attrs(attrs), {}); } TVM_REGISTER_GLOBAL("relay.op.nn._make.upsampling").set_body_typed(MakeUpSampling); RELAY_REGISTER_OP("nn.upsampling") .describe( R"code(Perform upsampling on input array with nearest neighbour or bilinear interpolation. - **data**: data is 4D array of shape (batch_size, channels, in_height, in_width) for NCHW (batch_size, in_height, in_width, channels) for NHWC - **out**: Output is 4D array of shape for layout NCHW (batch_size, channels, in_height*scale, in_width*scale) for layout NHWC (batch_size, in_height*scale, in_width*scale, channels) )code" TVM_ADD_FILELINE) .set_attrs_type<UpSamplingAttrs>() .set_num_inputs(1) .add_argument("data", "Tensor", "The input tensor.") .set_support_level(2) .add_type_rel("UpSampling", UpSamplingRel) .set_attr<FInferCorrectLayout>("FInferCorrectLayout", UpsamplingInferCorrectLayout<UpSamplingAttrs>) .set_attr<TOpPattern>("TOpPattern", kInjective); // UpSampling3D bool UpSampling3DRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { CHECK_EQ(types.size(), 2); const auto* data = types[0].as<TensorTypeNode>(); if (data == nullptr) return false; static const Layout kNCDHW("NCDHW"); const UpSampling3DAttrs* param = attrs.as<UpSampling3DAttrs>(); CHECK(param != nullptr); const Layout in_layout(param->layout); auto layout_converter = tir::BijectiveLayout(in_layout, kNCDHW); CHECK(layout_converter.defined()) << "UpSampling3D only support input layouts that are convertible from NCDHW." << " But got " << in_layout; auto oshape = layout_converter.ForwardShape(data->shape); oshape.Set(2, tir::Cast(oshape[2].dtype(), tvm::round(oshape[2] * param->scale_d))); oshape.Set(3, tir::Cast(oshape[3].dtype(), tvm::round(oshape[3] * param->scale_h))); oshape.Set(4, tir::Cast(oshape[4].dtype(), tvm::round(oshape[4] * param->scale_w))); // assign output type reporter->Assign(types[1], TensorType(layout_converter.BackwardShape(oshape), data->dtype)); return true; } // Positional relay function to create upsampling3d operator // used by frontend FFI. Expr MakeUpSampling3D(Expr data, double scale_d, double scale_h, double scale_w, String layout, String method, String coordinate_transformation_mode) { auto attrs = make_object<UpSampling3DAttrs>(); attrs->layout = std::move(layout); attrs->method = std::move(method); attrs->scale_d = scale_d; attrs->scale_h = scale_h; attrs->scale_w = scale_w; attrs->coordinate_transformation_mode = coordinate_transformation_mode; static const Op& op = Op::Get("nn.upsampling3d"); return Call(op, {data}, Attrs(attrs), {}); } TVM_REGISTER_GLOBAL("relay.op.nn._make.upsampling3d").set_body_typed(MakeUpSampling3D); RELAY_REGISTER_OP("nn.upsampling3d") .describe(R"code(Perform upsampling on input array with nearest neighbour or bilinear interpolation. - **data**: data is 5D array of shape (batch_size, channels, in_depth, in_height, in_width) for NCDHW (batch_size, in_depth, in_height, in_width, channels) for NDHWC - **out**: Output is 5D array of shape for layout NCDHW (batch_size, channels, in_depth*scale, in_height*scale, in_width*scale) for layout NDHWC (batch_size, in_depth*scale, in_height*scale, in_width*scale, channels) )code" TVM_ADD_FILELINE) .set_attrs_type<UpSampling3DAttrs>() .set_num_inputs(1) .add_argument("data", "Tensor", "The input tensor.") .set_support_level(2) .add_type_rel("UpSampling3D", UpSampling3DRel) .set_attr<FInferCorrectLayout>("FInferCorrectLayout", UpsamplingInferCorrectLayout<UpSampling3DAttrs>) .set_attr<TOpPattern>("TOpPattern", kInjective); } // namespace relay } // namespace tvm
38.809756
98
0.684515
[ "shape", "vector" ]
cb21ebc790c860aeb14d5ac4ee33324b56e082f2
6,573
cpp
C++
vm/builtin/variable_scope.cpp
sshao/rubinius
368df60245471f45f1294b0cd18f769377437246
[ "BSD-3-Clause" ]
null
null
null
vm/builtin/variable_scope.cpp
sshao/rubinius
368df60245471f45f1294b0cd18f769377437246
[ "BSD-3-Clause" ]
null
null
null
vm/builtin/variable_scope.cpp
sshao/rubinius
368df60245471f45f1294b0cd18f769377437246
[ "BSD-3-Clause" ]
null
null
null
#include "builtin/class.hpp" #include "builtin/exception.hpp" #include "builtin/fiber.hpp" #include "builtin/object.hpp" #include "builtin/system.hpp" #include "builtin/tuple.hpp" #include "builtin/variable_scope.hpp" #include "call_frame.hpp" #include "fiber_data.hpp" #include "gc/gc.hpp" #include "object_memory.hpp" #include "ontology.hpp" namespace rubinius { void VariableScope::init(STATE) { GO(variable_scope).set(ontology::new_class(state, "VariableScope", G(object), G(rubinius))); G(variable_scope)->set_object_type(state, VariableScopeType); } void VariableScope::bootstrap_methods(STATE) { GCTokenImpl gct; System::attach_primitive(state, gct, G(variable_scope), false, state->symbol("method_visibility"), state->symbol("variable_scope_method_visibility")); } VariableScope* VariableScope::of_sender(STATE, CallFrame* call_frame) { CallFrame* dest = call_frame->previous; // Skip any frames for native methods while(dest->native_method_p()) { dest = dest->previous; } return dest->promote_scope(state); } VariableScope* VariableScope::current(STATE, CallFrame* call_frame) { if(call_frame->native_method_p()) return nil<VariableScope>(); return call_frame->promote_scope(state); } VariableScope* VariableScope::synthesize(STATE, CompiledCode* method, Module* module, Object* parent, Object* self, Object* block, Tuple* locals) { VariableScope* scope = state->new_object<VariableScope>(G(variable_scope)); scope->block(state, block); scope->module(state, module); scope->method(state, method); if(VariableScope* vs = try_as<VariableScope>(parent)) { scope->parent(state, vs); } else { scope->parent(state, nil<VariableScope>()); } scope->heap_locals(state, locals); scope->last_match(state, cNil); scope->self(state, self); scope->number_of_locals_ = locals->num_fields(); scope->isolated_ = 1; scope->locals_ = 0; scope->flags_ = 0; scope->lock_.init(); return scope; } Tuple* VariableScope::locals(STATE) { Tuple* tup = Tuple::create_dirty(state, number_of_locals_); for(int i = 0; i < number_of_locals_; i++) { tup->put(state, i, get_local(state, i)); } return tup; } Object* VariableScope::set_local_prim(STATE, Fixnum* number, Object* object) { int num = number->to_int(); if(num < 0) { Exception::argument_error(state, "negative local index"); } else if(num >= number_of_locals_) { Exception::argument_error(state, "index larger than number of locals"); } set_local(state, num, object); return cNil; } // bootstrap method, replaced with an attr_accessor in kernel. Object* VariableScope::method_visibility(STATE) { return cNil; } Object* VariableScope::locked(STATE) { return RBOOL(locked_p()); } Object* VariableScope::set_locked(STATE) { flags_ |= CallFrame::cScopeLocked; VariableScope* parent = parent_; while(parent && !parent->nil_p()) { parent->set_locked(state); parent = parent->parent(); } return cNil; } void VariableScope::set_local_internal(STATE, int pos, Object* val) { if(isolated_) { heap_locals_->put(state, pos, val); } else { set_local(pos, val); } } void VariableScope::set_local(STATE, int pos, Object* val) { if(unlikely(locked_p())) { utilities::thread::SpinLock::LockGuard guard(lock_); set_local_internal(state, pos, val); } else { set_local_internal(state, pos, val); } } void VariableScope::set_local(int pos, Object* val) { Object** ary = locals_; if(Fiber* fib = try_as<Fiber>(fiber_)) { FiberData* data = fib->data(); if(data) { AddressDisplacement dis(data->data_offset(), data->data_lower_bound(), data->data_upper_bound()); ary = dis.displace(ary); } } ary[pos] = val; } Object* VariableScope::get_local_internal(STATE, int pos) { if(isolated_) { return heap_locals_->at(pos); } else { return get_local(pos); } } Object* VariableScope::get_local(STATE, int pos) { if(unlikely(locked_p())) { utilities::thread::SpinLock::LockGuard guard(lock_); return get_local_internal(state, pos); } else { return get_local_internal(state, pos); } } Object* VariableScope::get_local(int pos) { Object** ary = locals_; if(Fiber* fib = try_as<Fiber>(fiber_)) { FiberData* data = fib->data(); if(data) { AddressDisplacement dis(data->data_offset(), data->data_lower_bound(), data->data_upper_bound()); ary = dis.displace(ary); } } return ary[pos]; } Object* VariableScope::top_level_visibility(STATE) { return RBOOL(top_level_visibility_p()); } Object* VariableScope::script(STATE) { return RBOOL(script_p()); } void VariableScope::flush_to_heap_internal(STATE) { if(isolated_) return; Tuple* new_locals = Tuple::create_dirty(state, number_of_locals_); for(int i = 0; i < number_of_locals_; i++) { new_locals->put(state, i, locals_[i]); } heap_locals(state, new_locals); isolated_ = 1; } void VariableScope::flush_to_heap(STATE) { if(unlikely(locked_p())) { utilities::thread::SpinLock::LockGuard guard(lock_); flush_to_heap_internal(state); flags_ &= ~CallFrame::cScopeLocked; } else { flush_to_heap_internal(state); } } void VariableScope::Info::mark(Object* obj, ObjectMark& mark) { auto_mark(obj, mark); VariableScope* vs = as<VariableScope>(obj); if(!vs->isolated()) { Object** ary = vs->locals_; if(Fiber* fib = try_as<Fiber>(vs->fiber())) { FiberData* data = fib->data(); if(data) { AddressDisplacement dis(data->data_offset(), data->data_lower_bound(), data->data_upper_bound()); ary = dis.displace(ary); } } size_t locals = vs->number_of_locals(); for(size_t i = 0; i < locals; i++) { if(Object* tmp = mark.call(ary[i])) { ary[i] = tmp; } } } } }
27.970213
80
0.603986
[ "object" ]
cb2320e79d73965ca1ec8dd1d321883498777298
4,347
cpp
C++
openstudiocore/src/model/test/CmpntCostAdjustments_GTest.cpp
OpenStudioThailand/OpenStudio
4e2173955e687ef1b934904acc10939ac0bed52f
[ "MIT" ]
1
2017-10-13T09:23:04.000Z
2017-10-13T09:23:04.000Z
openstudiocore/src/model/test/CmpntCostAdjustments_GTest.cpp
OpenStudioThailand/OpenStudio
4e2173955e687ef1b934904acc10939ac0bed52f
[ "MIT" ]
null
null
null
openstudiocore/src/model/test/CmpntCostAdjustments_GTest.cpp
OpenStudioThailand/OpenStudio
4e2173955e687ef1b934904acc10939ac0bed52f
[ "MIT" ]
1
2022-03-20T13:19:42.000Z
2022-03-20T13:19:42.000Z
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2017, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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, THE UNITED STATES GOVERNMENT, OR ANY 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 <gtest/gtest.h> /* #include "ModelFixture.hpp" #include "../Model.hpp" #include "../../energyplus/ReverseTranslator.hpp" #include "../CmpntCostAdjustments.hpp" #include "../../utilities/sql/SqlFile.hpp" #include "../../utilities/data/TimeSeries.hpp" #include <utilities/idd/OS_ComponentCost_Adjustments_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> #include "../../utilities/idf/Workspace.hpp" #include "../../utilities/core/Optional.hpp" #include <boost/algorithm/string/case_conv.hpp> using namespace zero::model; using namespace zero; void checkObject(ComponentCostAdjustments object){ // object will have a total and costperarea OptionalDouble CostEstTotal = object.getCostEstTotalBldg(); ASSERT_TRUE(*CostEstTotal); ASSERT_NE(0, *CostEstTotal)<< " - total is zero, it should not be"; OptionalDouble iCostPer = object.getCostPerBldgAreaBldg(); ASSERT_TRUE(*iCostPer); EXPECT_NE(0, *iCostPer)<< " - costperarea is zero. total could be zero and it should not be - or some other problem"; } TEST_F(ModelFixture, ComponentCostAdj) { zero::path idfPath = resourcesPath() / toPath("energyplus/Daylighting_School/in.idf"); IdfFile idfFile(idfPath); Workspace workspace(idfFile); energyplus::ReverseTranslator reverseTranslator(workspace); OptionalModel optModel = reverseTranslator.convert(); ASSERT_TRUE(optModel) << "OptModel not reverse translated"; Model model = optModel.get(); zero::path sqlPath = resourcesPath() / toPath("energyplus/Daylighting_School/eplusout.sql"); SqlFile sqlFile(sqlPath); ASSERT_TRUE(sqlFile.connectionOpen()) << "sqlFile connection not opened :("; model.setSqlFile(sqlFile); // EXPECT_EQ(static_cast<size_t>(10), ComponentCostAdjustments::getComponentCostAdjustments_All().size()) << "size of ComponentCostAdjustments vector is !=10"; //<<ComponentCostAdjustments::getComponentCostAdjustments_All(model).size(); //not sure I need foreach. I think it only does this once. // for (const ComponentCostAdjustments& adjItem : ComponentCostAdjustments::getComponentCostAdjustments_All()){ // checkObject(adjItem); // } } */
49.965517
237
0.722107
[ "object", "vector", "model" ]
cb24e5ef5a05df19b919d7cf7cc9a28d31521f8e
4,831
cc
C++
components/service/ucloud/imm/src/model/IndexImageRequest.cc
wanguojian/AliOS-Things
47fce29d4dd39d124f0bfead27998ad7beea8441
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
components/service/ucloud/imm/src/model/IndexImageRequest.cc
wanguojian/AliOS-Things
47fce29d4dd39d124f0bfead27998ad7beea8441
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
components/service/ucloud/imm/src/model/IndexImageRequest.cc
wanguojian/AliOS-Things
47fce29d4dd39d124f0bfead27998ad7beea8441
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/imm/model/IndexImageRequest.h> using AlibabaCloud::Imm::Model::IndexImageRequest; IndexImageRequest::IndexImageRequest() : RpcServiceRequest("imm", "2017-09-06", "IndexImage") { setMethod(HttpRequest::Method::Post); } IndexImageRequest::~IndexImageRequest() {} std::string IndexImageRequest::getProject()const { return project_; } void IndexImageRequest::setProject(const std::string& project) { project_ = project; setParameter("Project", project); } std::string IndexImageRequest::getExternalId()const { return externalId_; } void IndexImageRequest::setExternalId(const std::string& externalId) { externalId_ = externalId; setParameter("ExternalId", externalId); } std::string IndexImageRequest::getAccessKeyId()const { return accessKeyId_; } void IndexImageRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); } std::string IndexImageRequest::getNotifyEndpoint()const { return notifyEndpoint_; } void IndexImageRequest::setNotifyEndpoint(const std::string& notifyEndpoint) { notifyEndpoint_ = notifyEndpoint; setParameter("NotifyEndpoint", notifyEndpoint); } std::string IndexImageRequest::getSourceType()const { return sourceType_; } void IndexImageRequest::setSourceType(const std::string& sourceType) { sourceType_ = sourceType; setParameter("SourceType", sourceType); } std::string IndexImageRequest::getRealUid()const { return realUid_; } void IndexImageRequest::setRealUid(const std::string& realUid) { realUid_ = realUid; setParameter("RealUid", realUid); } std::string IndexImageRequest::getNotifyTopicName()const { return notifyTopicName_; } void IndexImageRequest::setNotifyTopicName(const std::string& notifyTopicName) { notifyTopicName_ = notifyTopicName; setParameter("NotifyTopicName", notifyTopicName); } std::string IndexImageRequest::getRemarksB()const { return remarksB_; } void IndexImageRequest::setRemarksB(const std::string& remarksB) { remarksB_ = remarksB; setParameter("RemarksB", remarksB); } std::string IndexImageRequest::getRemarksA()const { return remarksA_; } void IndexImageRequest::setRemarksA(const std::string& remarksA) { remarksA_ = remarksA; setParameter("RemarksA", remarksA); } std::string IndexImageRequest::getImageUri()const { return imageUri_; } void IndexImageRequest::setImageUri(const std::string& imageUri) { imageUri_ = imageUri; setParameter("ImageUri", imageUri); } std::string IndexImageRequest::getRemarksArrayA()const { return remarksArrayA_; } void IndexImageRequest::setRemarksArrayA(const std::string& remarksArrayA) { remarksArrayA_ = remarksArrayA; setParameter("RemarksArrayA", remarksArrayA); } std::string IndexImageRequest::getRemarksArrayB()const { return remarksArrayB_; } void IndexImageRequest::setRemarksArrayB(const std::string& remarksArrayB) { remarksArrayB_ = remarksArrayB; setParameter("RemarksArrayB", remarksArrayB); } std::string IndexImageRequest::getSourceUri()const { return sourceUri_; } void IndexImageRequest::setSourceUri(const std::string& sourceUri) { sourceUri_ = sourceUri; setParameter("SourceUri", sourceUri); } std::string IndexImageRequest::getSourcePosition()const { return sourcePosition_; } void IndexImageRequest::setSourcePosition(const std::string& sourcePosition) { sourcePosition_ = sourcePosition; setParameter("SourcePosition", sourcePosition); } std::string IndexImageRequest::getRemarksD()const { return remarksD_; } void IndexImageRequest::setRemarksD(const std::string& remarksD) { remarksD_ = remarksD; setParameter("RemarksD", remarksD); } std::string IndexImageRequest::getRemarksC()const { return remarksC_; } void IndexImageRequest::setRemarksC(const std::string& remarksC) { remarksC_ = remarksC; setParameter("RemarksC", remarksC); } std::string IndexImageRequest::getSetId()const { return setId_; } void IndexImageRequest::setSetId(const std::string& setId) { setId_ = setId; setParameter("SetId", setId); }
22.262673
79
0.743738
[ "model" ]
cb2516f2ebad9f7702659985f68a4b695c48c55b
3,281
hpp
C++
include/utils/ScopeUtils.hpp
cgyurgyik/tnt
8ea24c1a9d2863b8b91775e5aba370584896fd9c
[ "MIT" ]
null
null
null
include/utils/ScopeUtils.hpp
cgyurgyik/tnt
8ea24c1a9d2863b8b91775e5aba370584896fd9c
[ "MIT" ]
null
null
null
include/utils/ScopeUtils.hpp
cgyurgyik/tnt
8ea24c1a9d2863b8b91775e5aba370584896fd9c
[ "MIT" ]
null
null
null
#ifndef TNT_SCOPE_UTILS_HPP #define TNT_SCOPE_UTILS_HPP #include <exception> namespace tnt { // call the destructor of the object when it goes out of scope. // template <typename Constructor, typename Destructor> // class scope_guard // { // public: // template <typename... Args> // scope_guard(Args &&...args):data{} {} // ~scope_guard() // { // data->~T(); // } // scope_guard(scope_guard const &guard) : data{guard.data} {} // scope_guard(scope_guard &&guard) : data{std::move(guard.data)} {} // scope_guard &operator=(scope_guard const &) = delete; // private: // T *data; // }; /// @brief Execute function only if no exception is thrown in the scope. /// @tparam F The type of the function to be wrapped by scope_success. template <typename F> class scope_success { public: /// @brief Create a new scope_success. /// @param f_ The function to be wrapped by the scope_success. ///@note f_() might throw, as it can be caught normally. explicit scope_success(const F &f_) : f{f_} {} scope_success(const scope_success &) = delete; scope_success &operator=(const scope_success &) = delete; /// @brief Destroy the scope_success. ~scope_success() noexcept(noexcept(f())) { if (uncaught_exception_count == std::uncaught_exceptions()) f(); } private: F f; int uncaught_exception_count = std::uncaught_exceptions(); }; /// @brief Execute function only if any exception is thrown in the scope. /// @tparam F The type of the function to be wrapped by scope_fail. template <typename F> class scope_fail { public: /// @brief Create a new scope_fail. /// @param f_ The function to be wrapped by the scope_fail. /// @note f_() should not throw, else @c std::terminate is called. explicit scope_fail(const F &f_) : f{f_} {} scope_fail(const scope_fail &) = delete; scope_fail &operator=(const scope_fail &) = delete; /// @brief Destroy the scope_fail. ~scope_fail() { if (uncaught_exception_count != std::uncaught_exceptions()) f(); } private: F f; int uncaught_exception_count = std::uncaught_exceptions(); }; /// @brief execute function when goes out of scope. /// @tparam Function The type of the function to be wrapped by finally. template <typename Function> class finally final { public: /// @brief Create a finally instance that wraps f_. /// @param f_ The function to be called by finally. explicit finally(Function &&f_) : f{std::move(f_)} {} finally(const finally &) = delete; finally(finally &&) = delete; finally &operator=(const finally &) = delete; finally &operator=(finally &&) = delete; /// @brief Destroy the finally instance. ~finally() noexcept(noexcept(f())) { f(); } private: Function f; }; namespace detail { template <typename T> concept callable = std::is_function_v<T>; } /// @brief Run a function when exiting the current scope. /// @param f A callable object. auto on_exit(detail::callable auto &&f) { return finally<std::decay_t<decltype(f)>>{std::forward<decltype(f)>(f)}; } } // namespace tnt #endif //! TNT_SCOPE_UTILS_HPP
28.042735
76
0.643097
[ "object" ]
cb2c3180f6ebeae79807555396e4eb12ee0bac29
9,911
cc
C++
chrome/browser/safe_browsing/malware_details.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-02-20T14:25:04.000Z
2019-12-13T13:58:28.000Z
chrome/browser/safe_browsing/malware_details.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
chrome/browser/safe_browsing/malware_details.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-08-09T09:03:23.000Z
2020-05-26T09:14:49.000Z
// Copyright (c) 2011 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. // // Implementation of the MalwareDetails class. #include "chrome/browser/safe_browsing/malware_details.h" #include "base/callback.h" #include "base/lazy_instance.h" #include "chrome/browser/net/chrome_url_request_context.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/safe_browsing/malware_details_cache.h" #include "chrome/browser/safe_browsing/report.pb.h" #include "chrome/browser/safe_browsing/safe_browsing_service.h" #include "chrome/common/safe_browsing/safebrowsing_messages.h" #include "content/browser/browser_thread.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/navigation_entry.h" #include "content/browser/tab_contents/tab_contents.h" #include "net/base/io_buffer.h" #include "net/disk_cache/disk_cache.h" #include "net/url_request/url_request_context_getter.h" using safe_browsing::ClientMalwareReportRequest; // Keep in sync with KMaxNodes in renderer/safe_browsing/malware_dom_details static const uint32 kMaxDomNodes = 500; // static MalwareDetailsFactory* MalwareDetails::factory_ = NULL; // The default MalwareDetailsFactory. Global, made a singleton so we // don't leak it. class MalwareDetailsFactoryImpl : public MalwareDetailsFactory { public: MalwareDetails* CreateMalwareDetails( SafeBrowsingService* sb_service, TabContents* tab_contents, const SafeBrowsingService::UnsafeResource& unsafe_resource) { return new MalwareDetails(sb_service, tab_contents, unsafe_resource); } private: friend struct base::DefaultLazyInstanceTraits< MalwareDetailsFactoryImpl>; MalwareDetailsFactoryImpl() { } DISALLOW_COPY_AND_ASSIGN(MalwareDetailsFactoryImpl); }; static base::LazyInstance<MalwareDetailsFactoryImpl> g_malware_details_factory_impl(base::LINKER_INITIALIZED); // Create a MalwareDetails for the given tab. /* static */ MalwareDetails* MalwareDetails::NewMalwareDetails( SafeBrowsingService* sb_service, TabContents* tab_contents, const SafeBrowsingService::UnsafeResource& resource) { // Set up the factory if this has not been done already (tests do that // before this method is called). if (!factory_) factory_ = g_malware_details_factory_impl.Pointer(); return factory_->CreateMalwareDetails(sb_service, tab_contents, resource); } // Create a MalwareDetails for the given tab. Runs in the UI thread. MalwareDetails::MalwareDetails( SafeBrowsingService* sb_service, TabContents* tab_contents, const SafeBrowsingService::UnsafeResource& resource) : TabContentsObserver(tab_contents), request_context_getter_(tab_contents->profile()->GetRequestContext()), sb_service_(sb_service), resource_(resource), cache_collector_(new MalwareDetailsCacheCollector) { StartCollection(); } MalwareDetails::~MalwareDetails() { } bool MalwareDetails::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(MalwareDetails, message) IPC_MESSAGE_HANDLER(SafeBrowsingHostMsg_MalwareDOMDetails, OnReceivedMalwareDOMDetails) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } bool MalwareDetails::IsPublicUrl(const GURL& url) const { return url.SchemeIs("http"); // TODO(panayiotis): also skip internal urls. } // Looks for a Resource for the given url in resources_. If found, it // updates |resource|. Otherwise, it creates a new message, adds it to // resources_ and updates |resource| to point to it. ClientMalwareReportRequest::Resource* MalwareDetails::FindOrCreateResource( const GURL& url) { safe_browsing::ResourceMap::iterator it = resources_.find(url.spec()); if (it != resources_.end()) { return it->second.get(); } // Create the resource for |url|. int id = resources_.size(); linked_ptr<ClientMalwareReportRequest::Resource> new_resource( new ClientMalwareReportRequest::Resource()); new_resource->set_url(url.spec()); new_resource->set_id(id); resources_[url.spec()] = new_resource; return new_resource.get(); } void MalwareDetails::AddUrl(const GURL& url, const GURL& parent, const std::string& tagname, const std::vector<GURL>* children) { if (!IsPublicUrl(url)) return; // Find (or create) the resource for the url. ClientMalwareReportRequest::Resource* url_resource = FindOrCreateResource(url); if (!tagname.empty()) { url_resource->set_tag_name(tagname); } if (!parent.is_empty() && IsPublicUrl(parent)) { // Add the resource for the parent. ClientMalwareReportRequest::Resource* parent_resource = FindOrCreateResource(parent); // Update the parent-child relation url_resource->set_parent_id(parent_resource->id()); } if (children) { for (std::vector<GURL>::const_iterator it = children->begin(); it != children->end(); it++) { ClientMalwareReportRequest::Resource* child_resource = FindOrCreateResource(*it); url_resource->add_child_ids(child_resource->id()); } } } void MalwareDetails::StartCollection() { DVLOG(1) << "Starting to compute malware details."; report_.reset(new ClientMalwareReportRequest()); if (IsPublicUrl(resource_.url)) { report_->set_malware_url(resource_.url.spec()); } GURL page_url = tab_contents()->GetURL(); if (IsPublicUrl(page_url)) { report_->set_page_url(page_url.spec()); } GURL referrer_url; NavigationEntry* nav_entry = tab_contents()->controller().GetActiveEntry(); if (nav_entry) { referrer_url = nav_entry->referrer(); if (IsPublicUrl(referrer_url)) { report_->set_referrer_url(referrer_url.spec()); } } // Add the nodes, starting from the page url. AddUrl(page_url, GURL(), "", NULL); // Add the resource_url and its original url, if non-empty and different. if (!resource_.original_url.is_empty() && resource_.url != resource_.original_url) { // Add original_url, as the parent of resource_url. AddUrl(resource_.original_url, GURL(), "", NULL); AddUrl(resource_.url, resource_.original_url, "", NULL); } else { AddUrl(resource_.url, GURL(), "", NULL); } // Add the redirect urls, if non-empty. The redirect urls do not include the // original url, but include the unsafe url which is the last one of the // redirect urls chain GURL parent_url; // Set the original url as the parent of the first redirect url if it's not // empty. if (!resource_.original_url.is_empty()) { parent_url = resource_.original_url; } // Set the previous redirect url as the parent of the next one for (unsigned int i = 0; i < resource_.redirect_urls.size(); ++i) { AddUrl(resource_.redirect_urls[i], parent_url, "", NULL); parent_url = resource_.redirect_urls[i]; } // Add the referrer url. if (nav_entry && !referrer_url.is_empty()) { AddUrl(referrer_url, GURL(), "", NULL); } // Get URLs of frames, scripts etc from the DOM. // OnReceivedMalwareDOMDetails will be called when the renderer replies. tab_contents()->render_view_host()->GetMalwareDOMDetails(); } // When the renderer is done, this is called. void MalwareDetails::OnReceivedMalwareDOMDetails( const std::vector<SafeBrowsingHostMsg_MalwareDOMDetails_Node>& params) { // Schedule this in IO thread, so it doesn't conflict with future users // of our data structures (eg GetSerializedReport). BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod( this, &MalwareDetails::AddDOMDetails, params)); } void MalwareDetails::AddDOMDetails( const std::vector<SafeBrowsingHostMsg_MalwareDOMDetails_Node>& params) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DVLOG(1) << "Nodes from the DOM: " << params.size(); // If we have already started collecting data from the HTTP cache, don't // modify our state. if (cache_collector_->HasStarted()) return; // Add the urls from the DOM to |resources_|. The renderer could be // sending bogus messages, so limit the number of nodes we accept. for (uint32 i = 0; i < params.size() && i < kMaxDomNodes; ++i) { SafeBrowsingHostMsg_MalwareDOMDetails_Node node = params[i]; DVLOG(1) << node.url << ", " << node.tag_name << ", " << node.parent; AddUrl(node.url, node.parent, node.tag_name, &(node.children)); } } // Called from the SB Service on the IO thread, after the user has // closed the tab, or clicked proceed or goback. Since the user needs // to take an action, we expect this to be called after // OnReceivedMalwareDOMDetails in most cases. If not, we don't include // the DOM data in our report. void MalwareDetails::FinishCollection() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); cache_collector_->StartCacheCollection( request_context_getter_, &resources_, &cache_result_, NewRunnableMethod(this, &MalwareDetails::OnCacheCollectionReady)); } void MalwareDetails::OnCacheCollectionReady() { DVLOG(1) << "OnCacheCollectionReady."; // Add all the urls in our |resources_| maps to the |report_| protocol buffer. for (safe_browsing::ResourceMap::const_iterator it = resources_.begin(); it != resources_.end(); it++) { ClientMalwareReportRequest::Resource* pb_resource = report_->add_resources(); pb_resource->CopyFrom(*(it->second)); } report_->set_complete(cache_result_); // Send the report, using the SafeBrowsingService. std::string serialized; if (!report_->SerializeToString(&serialized)) { DLOG(ERROR) << "Unable to serialize the malware report."; return; } sb_service_->SendSerializedMalwareDetails(serialized); }
35.90942
80
0.724952
[ "vector" ]
cb2de1df031438229ef3cafaf459a8be570ee922
5,592
cpp
C++
Examples/DebugRendering/DebugRenderingExample.cpp
jcfr/iMSTK
1602383c32eb116916fa5ca7a19e6c60a540922c
[ "Apache-2.0" ]
15
2021-09-20T17:33:52.000Z
2022-02-12T09:49:57.000Z
Examples/DebugRendering/DebugRenderingExample.cpp
jcfr/iMSTK
1602383c32eb116916fa5ca7a19e6c60a540922c
[ "Apache-2.0" ]
null
null
null
Examples/DebugRendering/DebugRenderingExample.cpp
jcfr/iMSTK
1602383c32eb116916fa5ca7a19e6c60a540922c
[ "Apache-2.0" ]
3
2021-10-06T19:55:41.000Z
2022-02-17T21:59:16.000Z
/*========================================================================= Library: iMSTK Copyright (c) Kitware, Inc. & Center for Modeling, Simulation, & Imaging in Medicine, Rensselaer Polytechnic Institute. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #include "imstkCamera.h" #include "imstkDebugGeometryObject.h" #include "imstkDirectionalLight.h" #include "imstkKeyboardSceneControl.h" #include "imstkLogger.h" #include "imstkMouseSceneControl.h" #include "imstkNew.h" #include "imstkScene.h" #include "imstkSceneManager.h" #include "imstkSimulationManager.h" #include "imstkVTKTextStatusManager.h" #include "imstkVTKViewer.h" using namespace imstk; static Vec3d getRandomPositions(const double radius) { return radius * Vec3d( 2.0 * static_cast<double>(rand()) / static_cast<double>(RAND_MAX) - 1.0, 2.0 * static_cast<double>(rand()) / static_cast<double>(RAND_MAX) - 1.0, 2.0 * static_cast<double>(rand()) / static_cast<double>(RAND_MAX) - 1.0); } static Color getRandomColor() { return Color( static_cast<double>(rand()) / static_cast<double>(RAND_MAX), static_cast<double>(rand()) / static_cast<double>(RAND_MAX), static_cast<double>(rand()) / static_cast<double>(RAND_MAX), 1.0); } /// /// \brief This example demonstrates debug rendering in iMSTK /// int main() { // Setup logger (write to file and stdout) Logger::startLogger(); // Create a scene imstkNew<Scene> scene("Debug rendering example"); scene->getConfig()->debugCamBoundingBox = false; scene->getCamera("debug")->setPosition(0.0, 0.0, 50.0); // Setup a viewer to render in its own thread imstkNew<VTKViewer> viewer; viewer->setActiveScene(scene); viewer->setWindowTitle("Debug Rendering"); viewer->setSize(1920, 1080); // Seed with system time srand(time(NULL)); auto statusManager = viewer->getTextStatusManager(); statusManager->setStatusFontSize(VTKTextStatusManager::StatusType::Custom, 30); statusManager->setStatusFontColor(VTKTextStatusManager::StatusType::Custom, Color::Orange); imstkNew<DebugGeometryObject> debugGeometryObj; scene->addSceneObject(debugGeometryObj); int mode = 0; // 0: add point, 1: add line, 2: add triangle int count = 0; // The number of times cycling between modes auto updateFunc = [&](Event*) { if (count > 100) { count = 0; debugGeometryObj->clear(); } if (mode % 3 == 0) { debugGeometryObj->addPoint( getRandomPositions(15.0), getRandomColor()); } else if (mode % 3 == 1) { Vec3d p = getRandomPositions(50.0); Vec3d shift = getRandomPositions(1.0); debugGeometryObj->addLine(p + shift, -p + shift, getRandomColor()); } else { Vec3d shift = getRandomPositions(10.0); debugGeometryObj->addTriangle( getRandomPositions(5.0) + shift, getRandomPositions(5.0) + shift, getRandomPositions(5.0) + shift, getRandomColor()); mode = -1; count++; } mode++; statusManager->setCustomStatus("Primitives: " + std::to_string(debugGeometryObj->getNumPoints()) + " (points) | " + std::to_string(debugGeometryObj->getNumLines()) + " (lines) | " + std::to_string(debugGeometryObj->getNumTriangles()) + " (triangles)" ); }; // Set Camera configuration scene->getActiveCamera()->setPosition(Vec3d(0.0, 0.0, 50.0)); // Light imstkNew<DirectionalLight> light1; light1->setFocalPoint(Vec3d(-1.0, -1.0, -1.0)); light1->setIntensity(1.0); scene->addLight("light1", light1); // Run the simulation { // Setup a scene manager to advance the scene in its own thread imstkNew<SceneManager> sceneManager; sceneManager->setActiveScene(scene); connect<Event>(sceneManager, &SceneManager::postUpdate, updateFunc); imstkNew<SimulationManager> driver; driver->addModule(viewer); driver->addModule(sceneManager); driver->setDesiredDt(0.1); // Add mouse and keyboard controls to the viewer { imstkNew<MouseSceneControl> mouseControl(viewer->getMouseDevice()); mouseControl->setSceneManager(sceneManager); viewer->addControl(mouseControl); imstkNew<KeyboardSceneControl> keyControl(viewer->getKeyboardDevice()); keyControl->setSceneManager(sceneManager); keyControl->setModuleDriver(driver); viewer->addControl(keyControl); } driver->start(); } return 0; }
33.088757
95
0.601574
[ "render" ]
cb31b44b7ddfb8aafef71b4889320746ee50f977
121,565
cpp
C++
ecl/hql/hqlattr.cpp
timothyklemm/HPCC-Platform
1ea50797eb59cc192cbf3c76ad70140c34ab3612
[ "Apache-2.0" ]
null
null
null
ecl/hql/hqlattr.cpp
timothyklemm/HPCC-Platform
1ea50797eb59cc192cbf3c76ad70140c34ab3612
[ "Apache-2.0" ]
null
null
null
ecl/hql/hqlattr.cpp
timothyklemm/HPCC-Platform
1ea50797eb59cc192cbf3c76ad70140c34ab3612
[ "Apache-2.0" ]
null
null
null
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ############################################################################## */ #include "jmisc.hpp" #include "jfile.hpp" #include "jiter.ipp" #include "jexcept.hpp" #include "jmutex.hpp" #include "jsort.hpp" #include "jutil.hpp" #include "hql.hpp" #include "hqlexpr.ipp" #include "hqlgram.hpp" #include "hqlfold.hpp" #include "hqlthql.hpp" #include "hqlpmap.hpp" #include <math.h> #include "hqlerrors.hpp" #include "hqlerror.hpp" #include "hqlplugins.hpp" #include "hqltrans.ipp" #include "hqlutil.hpp" #include "eclrtl.hpp" #include "hqlattr.hpp" #include "hqlmeta.hpp" static SpinLock * propertyLock; MODULE_INIT(INIT_PRIORITY_HQLINTERNAL) { propertyLock = new SpinLock; return true; } MODULE_EXIT() { delete propertyLock; } // This file should contain most of the derived property calculation for nodes in the expression tree, // Other candidates are // checkConstant, getChilddatasetType(), getNumChildTables // queryHasRows, definesColumnList(), queryTransformIndex // initFlagsBefore(), updatFlagsAfter() // getCachedEclCRC(), cacheTablesUsed(), isIndependentOfScope() // logic inside createDataset //Originally the idea was to have a class instance for each kind of opcode, and to call opcode[op]->evalautePropXXXXXX(this); //to evaluate the property. However because there are so many opcodes I'm not convinced this is the best way. //Better may be to model it more on the way queryRecordCount() is implemented. //This switch statement provides an entry of each opcode grouped according to its function. //within each group try and maintain alphabetical ordering unsigned getOperatorMetaFlags(node_operator op) { switch (op) { case no_none: case no_nobody: //Records/types case no_field: case no_record: case no_type: case no_ifblock: case no_enum: case no_selfref: case no_typedef: //Simple arithmetic expressions with no children: case no_constant: case no_variable: case no_quoted: // codegen only case no_getresult: case no_matched: case no_matchtext: case no_matchlength: case no_matchposition: case no_failcode: case no_failmessage: case no_id2blob: case no_blob2id: case no_clustersize: case no_loopcounter: case no_callback: case no_assertwild: case no_eventname: case no_eventextra: case no_debug_option_value: //Arithmetic operators case no_mul: case no_div: case no_modulus: case no_negate: case no_add: case no_sub: case no_exp: case no_power: case no_round: case no_roundup: case no_ln: case no_log10: case no_sin: case no_cos: case no_tan: case no_asin: case no_acos: case no_atan: case no_atan2: case no_sinh: case no_cosh: case no_tanh: case no_sqrt: case no_truncate: case no_cast: case no_implicitcast: case no_abs: case no_charlen: case no_sizeof: case no_offsetof: case no_nameof: case no_band: case no_bor: case no_bxor: case no_bnot: case no_order: //?? also a comparison case no_rank: case no_ranked: case no_hash: case no_typetransfer: case no_lshift: case no_rshift: case no_crc: case no_random: case no_counter: case no_address: case no_hash32: case no_hash64: case no_wuid: case no_countdict: case no_existslist: case no_countlist: case no_maxlist: case no_minlist: case no_sumlist: case no_unicodeorder: case no_assertkeyed: case no_hashmd5: case no_pure: case no_sequence: case no_getenv: //Selection operators - could be arithmetic, string, dataset etc. case no_map: case no_if: case no_choose: case no_which: case no_rejected: case no_mapto: case no_case: //String operators: case no_concat: case no_substring: case no_asstring: case no_intformat: case no_realformat: case no_trim: case no_fromunicode: case no_tounicode: case no_keyunicode: case no_rowdiff: case no_xmltext: case no_xmlunicode: case no_xmldecode: case no_xmlencode: case no_matchunicode: case no_matchutf8: case no_regex_find: case no_regex_findset: case no_regex_replace: case no_toxml: case no_tojson: //Boolean operators: case no_eq: case no_ne: case no_lt: case no_le: case no_gt: case no_ge: case no_not: case no_notnot: case no_and: case no_or: case no_xor: case no_notin: case no_in: case no_notbetween: case no_between: case no_is_valid: case no_indict: //Lists/Sets etc. case no_list: case no_all: case no_addsets: case no_createset: case no_rowset: case no_rowsetindex: case no_rowsetrange: case no_sortlist: case no_recordlist: case no_datasetlist: case no_transformlist: //Aggregate operators case no_count: case no_exists: case no_existsdict: case no_max: case no_min: case no_sum: case no_ave: case no_variance: case no_covariance: case no_correlation: case no_countgroup: case no_existsgroup: case no_maxgroup: case no_mingroup: case no_sumgroup: case no_avegroup: case no_vargroup: case no_covargroup: case no_corrgroup: case no_within: case no_notwithin: case no_countcompare: //Selectors case no_left: case no_right: case no_self: case no_activetable: case no_activerow: case no_top: //Transforms case no_transform: case no_assign: case no_assignall: case no_newtransform: //Rows case no_selectmap: case no_selectnth: case no_matchrow: case no_matchattr: // and scalar case no_projectrow: case no_createrow: case no_newrow: case no_temprow: //Dictionaries case no_createdictionary: //Datasets [see also selection operators] case no_rollup: case no_iterate: case no_hqlproject: case no_group: case no_cogroup: case no_cosort: case no_index: case no_table: case no_keyindex: case no_temptable: case no_usertable: case no_choosen: case no_filter: case no_fetch: case no_join: case no_sort: case no_subsort: case no_sorted: case no_dedup: case no_enth: case no_sample: case no_selectfields: case no_addfiles: case no_distribute: case no_normalize: case no_distributed: case no_preservemeta: case no_unordered: case no_grouped: case no_denormalize: case no_newusertable: case no_newaggregate: case no_aggregate: case no_choosesets: case no_workunit_dataset: case no_split: case no_spill: case no_readspill: case no_writespill: case no_commonspill: case no_parse: case no_newparse: case no_throughaggregate: case no_compound_diskread: case no_compound_disknormalize: case no_compound_diskaggregate: case no_compound_diskcount: case no_compound_diskgroupaggregate: case no_compound_indexread: case no_compound_indexnormalize: case no_compound_indexaggregate: case no_compound_indexcount: case no_compound_indexgroupaggregate: case no_compound_childread: case no_compound_childnormalize: case no_compound_childaggregate: case no_compound_childcount: case no_compound_childgroupaggregate: case no_compound_inline: case no_getgraphresult: case no_compound_fetch: case no_topn: case no_newxmlparse: case no_httpcall: case no_soapcall: case no_soapcall_ds: case no_newsoapcall: case no_newsoapcall_ds: case no_quantile: case no_nonempty: case no_filtergroup: case no_limit: case no_catchds: case no_loop: case no_forcenolocal: case no_allnodes: case no_selfjoin: case no_process: case no_thisnode: case no_getgraphloopresult: case no_graphloop: case no_assertstepped: case no_assertsorted: case no_assertgrouped: case no_assertdistributed: case no_mergejoin: case no_nwayjoin: case no_nwaymerge: case no_stepped: case no_datasetfromrow: case no_datasetfromdictionary: case no_assert_ds: case no_combine: case no_rollupgroup: case no_regroup: case no_combinegroup: case no_inlinetable: case no_denormalizegroup: case no_xmlproject: case no_spillgraphresult: case no_rows: case no_keyedlimit: case no_compound_selectnew: case no_getgraphloopresultset: case no_preload: case no_merge: case no_keyeddistribute: case no_newkeyindex: case no_anon: case no_pseudods: case no_deserialize: case no_serialize: case no_forcegraph: case no_related: case no_executewhen: case no_callsideeffect: case no_fromxml: case no_fromjson: case no_xmlparse: case no_normalizegroup: case no_owned_ds: case no_dataset_alias: case no_chooseds: //Multiple different kinds of values case no_select: case no_indirect: case no_selectindirect: case no_null: case no_globalscope: case no_nothor: case no_embedbody: case no_alias_scope: case no_evalonce: case no_forcelocal: case no_cluster: //Parser only - not in normalized expression trees case no_evaluate: case no_macro: case no_transformebcdic: case no_transformascii: case no_metaactivity: case no_loadxml: case no_fieldmap: case no_template_context: case no_processing: case no_merge_pending: case no_merge_nomatch: case no_namedactual: case no_assertconstant: case no_assertconcrete: case no_delayedscope: //Code generator only - only created once code is being generated. case no_postinc: case no_postdec: case no_preinc: case no_predec: case no_pselect: case no_deref: case no_ordered: case no_decimalstack: case no_translated: case no_filepos: case no_file_logicalname: case no_reference: case no_assign_addfiles: case no_nullptr: case no_childquery: //Workflow case no_stored: case no_failure: case no_success: case no_recovery: case no_wait: case no_event: case no_persist: case no_critical: case no_when: case no_setconditioncode: case no_priority: case no_colon: case no_setworkflow_cond: case no_global: case no_workflow: case no_workflow_action: case no_checkpoint: case no_define: case no_independent: case no_catch: case no_once: //Patterns case no_pat_select: case no_pat_const: case no_pat_pattern: case no_pat_follow: case no_pat_first: case no_pat_last: case no_pat_repeat: case no_pat_instance: case no_pat_anychar: case no_pat_token: case no_pat_imptoken: case no_pat_set: case no_pat_checkin: case no_pat_x_before_y: case no_pat_x_after_y: case no_pat_index: case no_pat_beginpattern: case no_pat_endpattern: case no_pat_checklength: case no_pat_featureparam: case no_pat_featureactual: case no_pat_featuredef: case no_pat_validate: case no_pat_use: case no_featuretype: case no_pat_guard: case no_penalty: case no_pat_case: case no_pat_nocase: case no_pat_before_y: case no_pat_after_y: case no_pat_production: case no_pat_or: //Pseudo-Attributes case no_csv: case no_sql: case no_thor: case no_flat: case no_pipe: case no_joined: case no_any: case no_xml: case no_json: case no_distributer: case no_keyed: case no_sortpartition: //Multiple types case no_outofline: case no_create_initializer: //Actions case no_buildindex: case no_output: case no_apply: case no_fail: case no_distribution: case no_ensureresult: case no_setresult: case no_sequential: case no_parallel: case no_actionlist: case no_orderedactionlist: case no_soapaction_ds: case no_newsoapaction_ds: case no_keydiff: case no_keypatch: case no_returnresult: case no_outputscalar: case no_evaluate_stmt: case no_return_stmt: case no_setgraphloopresult: case no_skip: case no_assert: case no_notify: case no_setgraphresult: case no_extractresult: case no_unused81: case no_definesideeffect: // Scopes etc. case no_scope: case no_forwardscope: case no_remotescope: case no_privatescope: case no_virtualscope: case no_concretescope: case no_mergedscope: //Used for representing functional attributes case no_service: case no_external: case no_funcdef: case no_externalcall: case no_libraryselect: case no_bound_func: case no_purevirtual: case no_internalselect: case no_delayedselect: case no_unboundselect: case no_libraryscope: case no_libraryscopeinstance: case no_libraryinput: case no_call: case no_attrname: // Other case no_comma: case no_uncommoned_comma: case no_compound: case no_param: case no_setmeta: case no_omitted: case no_range: case no_rangeto: case no_rangefrom: case no_rangecommon: case no_nofold: case no_nohoist: case no_nocombine: case no_section: case no_sectioninput: case no_alias: case no_unknown: // used for callbacks case no_attr: case no_attr_link: case no_attr_expr: case no_cachealias: case no_subgraph: case no_rowvalue: case no_loopbody: case no_complex: case no_likely: case no_unlikely: //Not implemented anywhere: case no_impure: // not really used case no_dependenton: case no_alias_project: case no_nolink: case no_joincount: case no_guard: case no_hint: case no_cloned: case no_childdataset: case no_envsymbol: case no_bound_type: case no_mix: case no_persist_check: case no_dataset_from_transform: case no_id: case no_unused6: case no_unused13: case no_unused14: case no_unused15: case no_unused32: case no_unused33: case no_unused34: case no_unused35: case no_unused36: case no_unused37: case no_unused38: case no_unused40: case no_unused41: case no_unused42: case no_unused43: case no_unused44: case no_unused45: case no_unused46: case no_unused47: case no_unused48: case no_unused49: case no_unused50: case no_unused52: case no_unused80: case no_unused102: case no_is_null: case no_position: case no_current_time: case no_current_date: case no_current_timestamp: case no_update: //The following never get created IHqlExpressions, they are used as constants in the PARSE internal structures. case no_pat_compound: case no_pat_begintoken: case no_pat_endtoken: case no_pat_begincheck: case no_pat_endcheckin: case no_pat_endchecklength: case no_pat_beginseparator: case no_pat_endseparator: case no_pat_separator: case no_pat_beginvalidate: case no_pat_endvalidate: case no_pat_dfa: case no_pat_singlechar: case no_pat_beginrecursive: case no_pat_endrecursive: case no_pat_utf8single: case no_pat_utf8lead: case no_pat_utf8follow: case no_eclcrc: return 0; case no_isomitted: return 0; default: DBGLOG("**** Missing meta flags for operator %d ***", (int)op); return 0; } } //--------------------------------------------------------------------------------- inline unsigned truncMaxlength(unsigned __int64 value) { return (value > MAX_MAXLENGTH) ? MAX_MAXLENGTH : (unsigned)value; } static unsigned getMaxSize(ITypeInfo * type, IHqlExpression * maxLength, IHqlExpression * maxSize, IHqlExpression * maxCount) { unsigned size = type->getSize(); if (size != UNKNOWN_LENGTH) return size; if (!maxLength) maxLength = queryAttributeChild(type, maxLengthAtom, 0); if (!maxSize) maxSize = queryAttributeChild(type, maxSizeAtom, 0); if (!maxCount) maxCount = queryAttributeChild(type, maxCountAtom, 0); if (maxSize) return (unsigned)getIntValue(maxSize, 0); if (maxLength) { unsigned __int64 len = (unsigned)getIntValue(maxLength, 0); switch (type->getTypeCode()) { case type_string: case type_data: return truncMaxlength(sizeof(size32_t) + len); case type_unicode: return truncMaxlength(sizeof(size32_t) + len*sizeof(UChar)); case type_qstring: return truncMaxlength(sizeof(size32_t) + rtlQStrSize((unsigned)len)); case type_varstring: return truncMaxlength(len + 1); case type_varunicode: return truncMaxlength((len + 1) * sizeof(UChar)); case type_utf8: return truncMaxlength(sizeof(size32_t) + (len * 4)); case type_set: return truncMaxlength(len); } } if (maxCount) { unsigned __int64 count = getIntValue(maxCount, 0); switch (type->getTypeCode()) { case type_set: { ITypeInfo * childType = type->queryChildType(); if (!childType) break; unsigned elemSize = getMaxSize(childType, NULL, NULL, NULL); if (elemSize != UNKNOWN_LENGTH) return truncMaxlength(sizeof(bool) + sizeof(size32_t) + count * elemSize); break; } } } return UNKNOWN_LENGTH; } static unsigned getMaxSize(IHqlExpression * field) { switch (field->getOperator()) { case no_select: return getMaxSize(field->queryChild(1)); case no_indirect: return getMaxSize(field->queryChild(0)); } ITypeInfo * type = field->queryType(); IHqlExpression * maxLength = queryAttributeChild(field, maxLengthAtom, 0); IHqlExpression * maxSize = queryAttributeChild(field, maxSizeAtom, 0); IHqlExpression * maxCount = queryAttributeChild(field, maxCountAtom, 0); unsigned max = getMaxSize(type, maxLength, maxSize, maxCount); if (max != UNKNOWN_LENGTH) return max; ITypeInfo * indirect = queryModifier(type, typemod_indirect); if (indirect) { IHqlExpression * original = static_cast<IHqlExpression *>(indirect->queryModifierExtra()); return getMaxSize(original); } return max; } //Some arbitrary guess at the size of a variable length string field. static double twoThirds = 2.0/3.0; static unsigned guessSize(unsigned minLen, unsigned maxLen) { if (maxLen == UNKNOWN_LENGTH) maxLen = 4096; if (maxLen < minLen) return minLen; double value = pow((double)(maxLen-minLen), twoThirds); return truncMaxlength(minLen + (unsigned __int64)ceil(value)); } static IHqlExpression * querySerializedForm(IHqlExpression * expr, IAtom * variation) { if (expr) { ExprPropKind kind; if (variation == diskAtom) kind = EPdiskserializedForm; else if (variation == internalAtom) kind = EPinternalserializedForm; else throwUnexpected(); IHqlExpression * attr = expr->queryProperty(kind); if (attr) return attr; } return expr; } static HqlTransformerInfo serializedRecordCreatorInfo("SerializedRecordCreator"); class SerializedRecordCreator : public QuickHqlTransformer { public: SerializedRecordCreator(IAtom * _variety) : QuickHqlTransformer(serializedRecordCreatorInfo, NULL), variety(_variety) {} virtual IHqlExpression * createTransformedBody(IHqlExpression * expr) { switch (expr->getOperator()) { case no_field: { //Remove the default value before transforming to avoid waste when processing before the expression tree is normalized if (queryRealChild(expr, 0)) { HqlExprArray children; unwindChildren(children, expr, 1); OwnedHqlExpr plain = expr->clone(children); return transform(plain); } if (expr->hasAttribute(_linkCounted_Atom)) { OwnedHqlExpr transformed = QuickHqlTransformer::createTransformedBody(expr); return removeAttribute(transformed, _linkCounted_Atom); } break; } } return QuickHqlTransformer::createTransformedBody(expr); } virtual ITypeInfo * transformType(ITypeInfo * type) { Owned<ITypeInfo> transformed = QuickHqlTransformer::transformType(type); return getSerializedForm(transformed, variety); } protected: IAtom * variety; }; static IHqlExpression * evaluateSerializedRecord(IHqlExpression * expr, IAtom * variation) { SerializedRecordCreator transformer(variation); return transformer.transform(expr); } //--------------------------------------------------------------------------------- class CHqlExprMeta { public: static inline void addProperty(IHqlExpression * expr, ExprPropKind kind, IInterface * value) { CHqlExpression * cexpr = static_cast<CHqlExpression *>(expr); cexpr->addProperty(kind, value); } static inline IInterface * queryExistingProperty(IHqlExpression * expr, ExprPropKind kind) { CHqlExpression * cexpr = static_cast<CHqlExpression *>(expr); return cexpr->queryExistingProperty(kind); } } meta; //-- Attribute: serialized form ------------------------------------------------------------------------------- static IHqlExpression * evaluatePropSerializedForm(IHqlExpression * expr, ExprPropKind kind, IAtom * variation) { if (expr->getOperator() == no_record || expr->getOperator() == no_field) { OwnedHqlExpr serialized = evaluateSerializedRecord(expr, variation); if (serialized != expr) { //Tag serialized form so don't re-evaluated meta.addProperty(serialized, kind, serialized); } meta.addProperty(expr, kind, serialized); return serialized; } return NULL; } //-- Attribute: size ------------------------------------------------------------------------------- //no_field static IHqlExpression * evaluateFieldAttrSize(IHqlExpression * expr) { ITypeInfo * type = expr->queryType(); unsigned minSize = UNKNOWN_LENGTH; unsigned maxSize = 0; unsigned thisSize = type->getSize(); OwnedHqlExpr thisMaxSizeExpr; if (expr->hasAttribute(_isBlobInIndex_Atom)) { thisSize = sizeof(unsigned __int64); } else { switch (type->getTypeCode()) { case type_bitfield: { thisSize = type->queryChildType()->getSize(); break; } case type_record: case type_row: { if (hasReferenceModifier(type)) thisSize = sizeof(void *); else { IHqlExpression * ret = expr->queryRecord()->queryProperty(EPsize); meta.addProperty(expr, EPsize, ret); return ret; } break; } case type_dictionary: case type_groupedtable: case type_table: { if (expr->hasAttribute(_linkCounted_Atom)) { thisSize = sizeof(size32_t) + sizeof(byte * *); break; } IHqlExpression * count = NULL; IHqlExpression * size = NULL; IHqlExpression * maxLength = NULL; IHqlExpression * maxCount = NULL; ForEachChild(i, expr) { IHqlExpression * attr = expr->queryChild(i); if (attr->isAttribute()) { IAtom * name = attr->queryName(); if (name == countAtom) count = attr->queryChild(0); else if (name == sizeofAtom) size = attr->queryChild(0); else if (name == maxLengthAtom) maxLength = attr->queryChild(0); else if (name == maxSizeAtom) maxLength = attr->queryChild(0); else if (name == maxCountAtom) maxCount = attr->queryChild(0); else if ((name == choosenAtom) && attr->queryChild(0)->queryValue()) maxCount = attr->queryChild(0); } } IHqlExpression * record = expr->queryRecord(); IHqlExpression * childRecordSizeExpr = record->queryProperty(EPsize); unsigned childExpectedSize = (unsigned)getIntValue(childRecordSizeExpr->queryChild(0)); unsigned childMinimumSize = (unsigned)getIntValue(childRecordSizeExpr->queryChild(1)); IHqlExpression * childMaximumSizeExpr = childRecordSizeExpr->queryChild(2); unsigned childMaximumSize = (unsigned)getIntValue(childMaximumSizeExpr, UNKNOWN_LENGTH); ITypeInfo * sizetType = childMaximumSizeExpr->queryType(); if (count || size) { minSize = 0; if (size && size->queryValue()) thisSize = (unsigned)getIntValue(size); else if (count && count->queryValue()) { unsigned __int64 num = (unsigned)getIntValue(count); thisSize = truncMaxlength(num * childExpectedSize); minSize = truncMaxlength(num * childMinimumSize); if (childMaximumSize != UNKNOWN_LENGTH) maxSize = truncMaxlength(num * childMaximumSize); else thisMaxSizeExpr.setown(createValue(no_mul, LINK(sizetType), ensureExprType(count, sizetType), LINK(childMaximumSizeExpr))); } else { thisSize = UNKNOWN_LENGTH; if (maxLength) maxSize = (unsigned)getIntValue(maxLength); else if (maxCount) { if (childMaximumSize != UNKNOWN_LENGTH) maxSize = truncMaxlength((unsigned __int64)getIntValue(maxCount) * childMaximumSize); else thisMaxSizeExpr.setown(createValue(no_mul, LINK(sizetType), ensureExprType(maxCount, sizetType), LINK(childMaximumSizeExpr))); } else maxSize = UNKNOWN_LENGTH; } } else { minSize = sizeof(size32_t); if (maxLength) maxSize = (unsigned)getIntValue(maxLength); else if (maxCount) { if (childMaximumSize != UNKNOWN_LENGTH) maxSize = truncMaxlength(sizeof(size32_t) + (unsigned __int64)getIntValue(maxCount) * childMaximumSize); else thisMaxSizeExpr.setown(createValue(no_add, LINK(sizetType), getSizetConstant(sizeof(size32_t)), createValue(no_mul, LINK(sizetType), ensureExprType(maxCount, sizetType), LINK(childMaximumSizeExpr)))); } else maxSize = UNKNOWN_LENGTH; } break; } case type_string: case type_data: case type_unicode: case type_qstring: case type_utf8: if (thisSize == UNKNOWN_LENGTH) { minSize = sizeof(size32_t); maxSize = getMaxSize(expr); } break; case type_varstring: if (thisSize == UNKNOWN_LENGTH) { minSize = 1; maxSize = getMaxSize(expr); } break; case type_varunicode: if (thisSize == UNKNOWN_LENGTH) { minSize = sizeof(UChar); maxSize = getMaxSize(expr); } break; case type_set: if (thisSize == UNKNOWN_LENGTH) { minSize = sizeof(size32_t)+sizeof(bool); maxSize = getMaxSize(expr); } break; case type_alien: { IHqlAlienTypeInfo * alien = queryAlienType(type); thisSize = alien->getPhysicalTypeSize(); if (thisSize == UNKNOWN_LENGTH) { IHqlExpression * lengthAttr = queryUncastExpr(alien->queryLengthFunction()); if (lengthAttr->isConstant() && !lengthAttr->isFunction()) { OwnedHqlExpr folded = foldHqlExpression(lengthAttr); if (folded->queryValue()) thisSize = (unsigned)getIntValue(folded); } } if (thisSize == UNKNOWN_LENGTH) { minSize = 0; IHqlExpression * maxSizeExpr = expr->queryAttribute(maxSizeAtom); if (!maxSizeExpr) maxSizeExpr = expr->queryAttribute(maxLengthAtom); if (maxSizeExpr) maxSize = (unsigned)getIntValue(maxSizeExpr->queryChild(0)); else maxSize = alien->getMaxSize(); } break; } case type_packedint: minSize = 1; maxSize = (type->queryPromotedType()->getSize()+1); thisSize = (maxSize > 2) ? 2 : 1; break; case type_any: minSize = 1; maxSize = getMaxSize(expr); break; default: assertex(thisSize != UNKNOWN_LENGTH); break; } } if (thisMaxSizeExpr) maxSize = UNKNOWN_LENGTH; if (thisSize == UNKNOWN_LENGTH) thisSize = guessSize(minSize, maxSize); else { if (minSize == UNKNOWN_LENGTH) minSize = thisSize; if (maxSize == 0) maxSize = thisSize; } if ((thisSize == minSize) && (minSize == maxSize)) { OwnedHqlExpr attr = getFixedSizeAttr(thisSize); meta.addProperty(expr, EPsize, attr); return attr; } if (!thisMaxSizeExpr) thisMaxSizeExpr.setown((maxSize == UNKNOWN_LENGTH) ? createAttribute(unknownSizeFieldAtom) : getSizetConstant(maxSize)); OwnedHqlExpr attr = createExprAttribute(_propSize_Atom, getSizetConstant(thisSize), getSizetConstant(minSize), thisMaxSizeExpr.getClear()); meta.addProperty(expr, EPsize, attr); return attr; } //no_ifblock static IHqlExpression * evaluateIfBlockAttrSize(IHqlExpression * expr) { IHqlExpression * size = expr->queryChild(1)->queryProperty(EPsize); unsigned averageSize = (unsigned)getIntValue(size->queryChild(0), 0)/2; OwnedHqlExpr attr = createExprAttribute(_propSize_Atom, getSizetConstant(averageSize), getSizetConstant(0), LINK(size->queryChild(2))); meta.addProperty(expr, EPsize, attr); return attr; } //no_record static IHqlExpression * evaluateRecordAttrSize(IHqlExpression * expr) { unsigned __int64 expectedSize = 0; unsigned __int64 minimumSize = 0; unsigned __int64 maximumSize = 0; OwnedHqlExpr maximumSizeExpr; OwnedHqlExpr derivedSizeExpr; bool hasUnknownMaxSizeField = false; BitfieldPacker packer; ForEachChild(i, expr) { IHqlExpression * cur = expr->queryChild(i); ITypeInfo * type = cur->queryType(); if (type && type->getTypeCode() == type_bitfield) { unsigned thisBitOffset, thisBits; if (!packer.checkSpaceAvailable(thisBitOffset, thisBits, type)) { size32_t thisSize = type->queryChildType()->getSize(); expectedSize += thisSize; minimumSize += thisSize; maximumSize += thisSize; } } else { packer.reset(); IHqlExpression * size = cur->queryProperty(EPsize); if (size) { expectedSize += (size32_t)getIntValue(size->queryChild(0)); minimumSize += (size32_t)getIntValue(size->queryChild(1)); IHqlExpression * maxExpr = size->queryChild(2); if (maxExpr->queryValue()) maximumSize += (size32_t)getIntValue(maxExpr); else if (maxExpr->isAttribute()) { assertex(maxExpr->queryName() == unknownSizeFieldAtom); hasUnknownMaxSizeField = true; } else extendAdd(maximumSizeExpr, maxExpr); } } } if ((minimumSize != maximumSize) || maximumSizeExpr || hasUnknownMaxSizeField) { IHqlExpression * maxLength = queryAttributeChild(expr, maxLengthAtom, 0); if (maxLength) { if (!hasUnknownMaxSizeField) { if (maximumSize || !maximumSizeExpr) { OwnedHqlExpr maxExpr = getSizetConstant(truncMaxlength(maximumSize)); extendAdd(maximumSizeExpr, maxExpr); } derivedSizeExpr.set(maximumSizeExpr); } maximumSize = (unsigned)getIntValue(maxLength, UNKNOWN_LENGTH); maximumSizeExpr.clear(); if (derivedSizeExpr) { //If not a constant then it is derived from the default maxlength, so the explicit maxlength is better //otherwise use the minimum value if (derivedSizeExpr->queryValue()) { unsigned maxDerived = (unsigned)getIntValue(derivedSizeExpr); if (maximumSize > maxDerived) maximumSize = maxDerived; } } } else if (hasUnknownMaxSizeField) { OwnedHqlExpr maxExpr = getSizetConstant(truncMaxlength(maximumSize)); extendAdd(maximumSizeExpr, maxExpr); maximumSize = 0; //?create an expression to represent // if (totalSize * 2 > defaultMaxRecordSize, totalSize + defaultMaxRecordSize / 2, defaultMaxRecordSize); IHqlExpression * defaultMaxLength = queryDefaultMaxRecordLengthExpr(); OwnedHqlExpr minmax = LINK(maximumSizeExpr); OwnedHqlExpr minMaxTimes2 = createValue(no_mul, defaultMaxLength->getType(), LINK(minmax), getSizetConstant(2)); OwnedHqlExpr cond = createBoolExpr(no_gt, LINK(minMaxTimes2), LINK(defaultMaxLength)); OwnedHqlExpr trueExpr = createValue(no_add, defaultMaxLength->getType(), LINK(minmax), createValue(no_div, defaultMaxLength->getType(), LINK(defaultMaxLength), getSizetConstant(2))); maximumSizeExpr.setown(createValue(no_if, defaultMaxLength->getType(), LINK(cond), LINK(trueExpr), LINK(defaultMaxLength))); } } if ((maximumSize == 0) && expr->hasAttribute(_nonEmpty_Atom)) { expectedSize = 1; minimumSize = 1; maximumSize = 1; } if (maximumSize || !maximumSizeExpr) { OwnedHqlExpr maxExpr = getSizetConstant(truncMaxlength(maximumSize)); extendAdd(maximumSizeExpr, maxExpr); } HqlExprArray args; args.append(*getSizetConstant(truncMaxlength(expectedSize))); args.append(*getSizetConstant(truncMaxlength(minimumSize))); args.append(*LINK(maximumSizeExpr)); if (derivedSizeExpr) args.append(*LINK(derivedSizeExpr)); OwnedHqlExpr sizeAttr = createExprAttribute(_propSize_Atom, args); meta.addProperty(expr, EPsize, sizeAttr); return sizeAttr; } static IHqlExpression * evalautePropSize(IHqlExpression * expr) { switch (expr->getOperator()) { case no_field: return evaluateFieldAttrSize(expr); case no_ifblock: return evaluateIfBlockAttrSize(expr); case no_record: return evaluateRecordAttrSize(expr); case no_transform: case no_newtransform: { //MORE: This could calculate a better estimate for the size of the record by taking into account any constant values or datasets that are assigned. IHqlExpression * record = expr->queryRecord(); IHqlExpression * recordSize = record->queryProperty(EPsize); meta.addProperty(expr, EPsize, recordSize); return recordSize; } } IHqlExpression * record = expr->queryRecord(); if (record) return record->queryProperty(EPsize); return NULL; } IHqlExpression * getSerializedForm(IHqlExpression * expr, IAtom * variation) { return LINK(querySerializedForm(expr, variation)); } ITypeInfo * getSerializedForm(ITypeInfo * type, IAtom * variation) { if (!type) return NULL; switch (type->getTypeCode()) { case type_record: { IHqlExpression * record = queryRecord(queryUnqualifiedType(type)); IHqlExpression * serializedRecord = querySerializedForm(record, variation); if (record == serializedRecord) return LINK(type); return cloneModifiers(type, serializedRecord->queryType()); } case type_row: case type_transform: case type_table: case type_groupedtable: { //MORE: If (variant == internalAtom) consider using a format that prefixes the dataset with a count instead of a size OwnedITypeInfo noOutOfLineType = removeModifier(type, typemod_outofline); OwnedITypeInfo noLinkCountType = removeAttribute(noOutOfLineType, _linkCounted_Atom); ITypeInfo * childType = noLinkCountType->queryChildType(); OwnedITypeInfo newChild = getSerializedForm(childType, variation); return replaceChildType(noLinkCountType, newChild); } case type_dictionary: { OwnedITypeInfo noOutOfLineType = removeModifier(type, typemod_outofline); OwnedITypeInfo noLinkCountType = removeAttribute(noOutOfLineType, _linkCounted_Atom); ITypeInfo * childType = noLinkCountType->queryChildType(); OwnedITypeInfo newChild = getSerializedForm(childType, variation); if (variation == internalAtom) return replaceChildType(noLinkCountType, newChild); OwnedITypeInfo datasetType = makeTableType(LINK(newChild)); return cloneModifiers(noLinkCountType, datasetType); } } return LINK(type); } //-- Attribute: unadorned form (no annotations) ------------------------------------------------------------------------------- //Use a transformer to implement the mapping - since it contains the logic for processing types etc, but use the attributes as an extra cache. class HqlCachedPropertyTransformer : public QuickHqlTransformer { public: HqlCachedPropertyTransformer(HqlTransformerInfo & _transformInfo, ExprPropKind _propKind); virtual IHqlExpression * transform(IHqlExpression * expr); protected: ExprPropKind propKind; }; HqlCachedPropertyTransformer::HqlCachedPropertyTransformer(HqlTransformerInfo & _transformInfo, ExprPropKind _propKind) : QuickHqlTransformer(_transformInfo, NULL), propKind(_propKind) { } IHqlExpression * HqlCachedPropertyTransformer::transform(IHqlExpression * expr) { if (expr != expr->queryBody()) return QuickHqlTransformer::transform(expr); IInterface * match = meta.queryExistingProperty(expr, propKind); if (match) return static_cast<IHqlExpression *>(LINK(match)); OwnedHqlExpr transformed = QuickHqlTransformer::transform(expr); if (transformed != expr) { //Very unusual - e.g., no_delayedselect IHqlExpression * body = transformed->queryBody(); if (transformed != body) transformed.set(body); //Tag serialized form so don't re-evaluate meta.addProperty(transformed, propKind, transformed); } meta.addProperty(expr, propKind, transformed); return transformed.getClear(); } class HqlUnadornedNormalizer : public HqlCachedPropertyTransformer { public: HqlUnadornedNormalizer(); virtual IHqlExpression * createTransformed(IHqlExpression * expr); virtual ITypeInfo * transformType(ITypeInfo * type); }; static HqlTransformerInfo hqlUnadornedInfo("HqlUnadornedNormalizer"); HqlUnadornedNormalizer::HqlUnadornedNormalizer() : HqlCachedPropertyTransformer(hqlUnadornedInfo, EPunadorned) { } ITypeInfo * HqlUnadornedNormalizer::transformType(ITypeInfo * type) { return HqlCachedPropertyTransformer::transformType(queryUnqualifiedType(type)); } IHqlExpression * HqlUnadornedNormalizer::createTransformed(IHqlExpression * expr) { IHqlExpression * body = expr->queryBody(false); if (expr != body) return transform(body); node_operator op = expr->getOperator(); switch (op) { case no_field: { //Remove the default values... HqlExprArray children; bool same = true; ForEachChild(idx, expr) { IHqlExpression * cur = expr->queryChild(idx); if (cur->isAttribute()) { IHqlExpression * mapped = transform(cur); children.append(*mapped); if (mapped != cur) same = false; } else same = false; } ITypeInfo * type = expr->queryType(); OwnedITypeInfo newType = transformType(type); IIdAtom * id = expr->queryId(); //Fields names compare case-insignificantly therefore the field name is converted to lower case so that //equivalent fields are mapped to the same normalized expression. IIdAtom * newid = createIdAtom(str(lower(id))); if ((type != newType) || (id != newid)) return createField(newid, newType.getClear(), children); if (same) return LINK(expr); return expr->clone(children); } case no_param: { ITypeInfo * type = expr->queryType(); OwnedITypeInfo newType = transformType(type); HqlExprArray children; transformChildren(expr, children); // could just unwind return createParameter(expr->queryId(), UnadornedParameterIndex, newType.getClear(), children); } } return HqlCachedPropertyTransformer::createTransformed(expr); } static IHqlExpression * evalautePropUnadorned(IHqlExpression * expr) { HqlUnadornedNormalizer normalizer; //NB: Also has the side-effect of adding any missing attributes OwnedHqlExpr dummy = normalizer.transform(expr); return static_cast<IHqlExpression *>(meta.queryExistingProperty(expr, EPunadorned)); } //--------------------------------------------------------------------------------- static unsigned queryFieldAlignment(ITypeInfo * type) { unsigned size = type->getSize(); type_t tc = type->getTypeCode(); switch (tc) { case type_int: case type_swapint: switch (size) { case 2: case 4: case 8: return size; } return 1; case type_boolean: case type_real: return size; case type_string: case type_varstring: case type_data: if (hasLinkCountedModifier(type)) return sizeof(void *); return 1; case type_char: case type_decimal: case type_packedint: case type_set: // would be nicer if properly aligned. Even nicer if the (isall,size) were separate case type_utf8: case type_qstring: case type_any: return 1; case type_bitfield: case type_array: case type_enumerated: return queryFieldAlignment(type->queryChildType()); case type_pointer: return sizeof(void *); case type_table: case type_row: case type_groupedtable: if (hasLinkCountedModifier(type)) return sizeof(void *); return 1; case type_alien: return queryFieldAlignment(type->queryChildType()); case type_unicode: case type_varunicode: return sizeof(UChar); default: throwUnexpectedType(type); } } static unsigned queryFieldAlignment(IHqlExpression * field) { return queryFieldAlignment(field->queryType()); } class FieldAlignCompare : public ICompare { public: FieldAlignCompare(const HqlExprCopyArray & _original) : original(_original) {} virtual int docompare(const void * inleft, const void * inright) const { IInterface * pleft = (IInterface *)(inleft); IInterface * pright = (IInterface *)(inright); IHqlExpression * left = static_cast<IHqlExpression *>(pleft); IHqlExpression * right = static_cast<IHqlExpression *>(pright); IHqlExpression * leftSizeAttr = left->queryProperty(EPsize); IHqlExpression * rightSizeAttr = right->queryProperty(EPsize); bool leftIsFixedSize = leftSizeAttr->queryChild(1) == leftSizeAttr->queryChild(2); bool rightIsFixedSize = rightSizeAttr->queryChild(1) == rightSizeAttr->queryChild(2); if (leftIsFixedSize && rightIsFixedSize) { bool leftIsBitfield = (left->queryType()->getTypeCode() == type_bitfield); bool rightIsBitfield = (right->queryType()->getTypeCode() == type_bitfield); if (!leftIsBitfield && !rightIsBitfield) { //First choose the largest alignment first unsigned leftAlign = queryFieldAlignment(left); unsigned rightAlign = queryFieldAlignment(right); if (leftAlign != rightAlign) return (int)(rightAlign - leftAlign); #if 0 //Then choose smallest item next - so access is more compact unsigned leftSize = getIntValue(leftSizeAttr->queryChild(0)); unsigned rightSize = getIntValue(rightSizeAttr->queryChild(0)); if (leftSize != rightSize) return (int)(leftSize - rightSize); #endif //fall through to default } else if (!leftIsBitfield) return -1; else if (!rightIsBitfield) return +1; else { //Two bitfields - need better handling } } else if (leftIsFixedSize) return -1; else if (rightIsFixedSize) return +1; else { //both variable size } //default processing currently by name - may change to use original order return original.find(*left) - original.find(*right); // return stricmp(left->queryName()->str(), right->queryName()->str()); } protected: const HqlExprCopyArray & original; } ; static bool optimizeFieldOrder(HqlExprArray & out, const HqlExprCopyArray & in) { HqlExprCopyArray sorted; appendArray(sorted, in); FieldAlignCompare compare(in); qsortvec((void * *)sorted.getArray(), sorted.ordinality(), compare); ForEachItemIn(i, sorted) out.append(OLINK(sorted.item(i))); return true; } static IHqlExpression * evalautePropAligned(IHqlExpression * expr) { bool same = true; HqlExprArray result; HqlExprCopyArray reorder; assertex(expr->getOperator() == no_record); ForEachChild(i, expr) { IHqlExpression * cur = expr->queryChild(i); switch (cur->getOperator()) { case no_field: reorder.append(*cur); break; case no_ifblock: case no_record: default: if (optimizeFieldOrder(result, reorder)) same = false; result.append(*LINK(cur)); reorder.kill(); break; } } if (optimizeFieldOrder(result, reorder)) same = false; OwnedHqlExpr newRecord = same ? LINK(expr) : expr->clone(result); if (expr == newRecord) { meta.addProperty(expr, EPaligned, queryAlignedAttr()); return queryAlignedAttr(); } meta.addProperty(newRecord, EPaligned, queryAlignedAttr()); OwnedHqlExpr alignAttr = createExprAttribute(_propAligned_Atom, newRecord.getClear()); meta.addProperty(expr, EPaligned, alignAttr); return alignAttr; } //--------------------------------------------------------------------------------- MODULE_INIT(INIT_PRIORITY_HQLMETA) { for (node_operator op = (node_operator)(no_none+1); op < no_last_op; op = (node_operator)(op+1)) getOperatorMetaFlags(op); return true; } MODULE_EXIT() { } //--------------------------------------------------------------------------------- // Functions that provide simple information about an operator, that don't require tree traversal. bool isLocalActivity(IHqlExpression * expr) { switch (expr->getOperator()) { case no_distribute: case no_keyeddistribute: case no_if: case no_chooseds: return false; case no_forcelocal: case no_combinegroup: case no_regroup: return true; //local makes no sense for the following case no_throughaggregate: case no_filter: case no_related: return false; case no_group: case no_grouped: case no_dedup: case no_cogroup: case no_cosort: case no_sort: case no_subsort: case no_sorted: case no_topn: case no_iterate: case no_rollup: case no_newaggregate: case no_merge: case no_choosen: case no_choosesets: case no_enth: case no_sample: case no_buildindex: case no_limit: case no_catchds: case no_newkeyindex: case no_table: case no_process: case no_assertsorted: case no_assertgrouped: case no_nonempty: case no_loop: case no_graphloop: case no_aggregate: case no_combine: case no_denormalize: case no_denormalizegroup: case no_join: case no_mergejoin: //??? case no_nwayjoin: case no_nwaymerge: case no_selfjoin: case no_joincount: assertex(localChangesActivity(expr)); return expr->hasAttribute(localAtom); case no_newusertable: if (isAggregateDataset(expr)) return expr->hasAttribute(localAtom); return false; case no_hqlproject: // count project may result in distributed output, but not be local(!) if (expr->hasAttribute(_countProject_Atom)) return expr->hasAttribute(localAtom); return false; case no_compound: return isLocalActivity(expr->queryChild(1)); case no_compound_diskread: case no_compound_disknormalize: case no_compound_diskaggregate: case no_compound_diskcount: case no_compound_diskgroupaggregate: case no_compound_indexread: case no_compound_indexnormalize: case no_compound_indexaggregate: case no_compound_indexcount: case no_compound_indexgroupaggregate: { if (expr->hasAttribute(localAtom)) return true; IHqlExpression * root = queryRoot(expr); while (root->getOperator() == no_select) { bool isNew; IHqlExpression * ds = querySelectorDataset(root, isNew); if (!isNew) break; root = queryRoot(ds); } return isLocalActivity(root); } case no_compound_childread: case no_compound_childnormalize: case no_compound_childaggregate: case no_compound_childcount: case no_compound_childgroupaggregate: case no_compound_selectnew: case no_compound_inline: return true; case no_dataset_from_transform: return expr->hasAttribute(localAtom); default: { assertex(!localChangesActivity(expr)); return false; } } } bool isGroupedAggregateActivity(IHqlExpression * expr, IHqlExpression * grouping) { if (grouping && !grouping->isAttribute()) return expr->hasAttribute(groupedAtom); return isGrouped(expr->queryChild(0)); } bool isGroupedActivity(IHqlExpression * expr) { switch (expr->getOperator()) { case no_group: case no_enth: case no_distribute: case no_fetch: case no_keyeddistribute: case no_merge: case no_graphloop: return false; case no_denormalize: case no_denormalizegroup: case no_regroup: case no_addfiles: case no_join: case no_mergejoin: case no_nwayjoin: case no_nwaymerge: case no_selfjoin: case no_combine: case no_combinegroup: case no_if: case no_chooseds: case no_case: case no_map: case no_loop: case no_choosen: case no_process: case no_nonempty: case no_related: case no_pipe: return isGrouped(expr->queryType()); case no_selectfields: case no_usertable: return isGroupedAggregateActivity(expr, expr->queryChild(2)); case no_aggregate: case no_newaggregate: case no_newusertable: return isGroupedAggregateActivity(expr, expr->queryChild(3)); case no_null: case no_anon: case no_pseudods: case no_fail: case no_skip: case no_all: case no_workunit_dataset: case no_getgraphresult: case no_getgraphloopresult: case no_getresult: case no_rows: case no_internalselect: case no_delayedselect: case no_unboundselect: case no_libraryselect: case no_purevirtual: case no_libraryinput: //All the source activities return isGrouped(expr->queryType()); case no_compound: return isGroupedActivity(expr->queryChild(1)); case no_output: return expr->hasAttribute(groupedAtom) && isGroupedActivity(expr->queryChild(0)); default: if (getNumChildTables(expr) == 1) return isGrouped(expr->queryChild(0)); return false; } } bool localChangesActivityData(IHqlExpression * expr) { switch (expr->getOperator()) { case no_compound_diskread: case no_compound_disknormalize: case no_compound_diskaggregate: case no_compound_diskcount: case no_compound_diskgroupaggregate: case no_compound_indexread: case no_compound_indexnormalize: case no_compound_indexaggregate: case no_compound_indexcount: case no_compound_indexgroupaggregate: case no_newkeyindex: case no_table: return true; case no_denormalize: case no_denormalizegroup: case no_join: case no_joincount: return isKeyedJoin(expr); // keyed join, local means only look at the local key part. //case no_fetch:////???? } return false; } bool localChangesActivityAction(IHqlExpression * expr) { switch (expr->getOperator()) { case no_dedup: case no_group: case no_grouped: case no_cogroup: case no_cosort: case no_sort: case no_subsort: case no_sorted: case no_topn: case no_iterate: case no_rollup: case no_newaggregate: case no_aggregate: case no_merge: case no_choosen: case no_choosesets: case no_enth: case no_sample: case no_buildindex: case no_limit: case no_catchds: case no_compound_diskaggregate: case no_compound_diskgroupaggregate: case no_compound_indexaggregate: case no_compound_indexgroupaggregate: case no_process: case no_assertsorted: case no_assertgrouped: case no_nonempty: case no_loop: case no_graphloop: case no_combine: case no_dataset_from_transform: return true; case no_hqlproject: return expr->hasAttribute(_countProject_Atom); case no_newusertable: return isAggregateDataset(expr); case no_denormalize: case no_denormalizegroup: case no_join: case no_mergejoin: //??? case no_nwayjoin: case no_nwaymerge: case no_selfjoin: case no_joincount: return !isKeyedJoin(expr); // Keyed joins always } return false; } bool localChangesActivity(IHqlExpression * expr) { return localChangesActivityData(expr) || localChangesActivityAction(expr); } unsigned isStreamingActivity(IHqlExpression * expr) { switch (expr->getOperator()) { case no_sort: case no_topn: if (isGrouped(expr)) return 0; return 1; case no_join: case no_denormalize: if (isKeyedJoin(expr)) return 0; if (expr->hasAttribute(lookupAtom)) return 2; return 3; // ok if lhs/rhs are sorted... case no_selfjoin: return 1; // ok if sorted. case no_dedup: if (isGrouped(expr)) return 0; if (expr->hasAttribute(hashAtom) || expr->hasAttribute(allAtom)) return false; break; case no_addfiles: //if ordered and same item is read by lhs and rhs // ordered addfiles? break; case no_libraryselect: //???? return 1; case no_spillgraphresult: case no_setgraphresult: case no_setgraphloopresult: break; //except for default loop output because likely to be read by a child as a whole } return 0; } // More complex derived information which requires tree traversal. bool isInlineTrivialDataset(IHqlExpression * expr) { loop { switch (expr->getOperator()) { case no_selectnth: switch (expr->queryChild(1)->getOperator()) { case no_constant: case no_counter: break; default: return false; } expr = expr->queryChild(0); break; case no_workunit_dataset: case no_getresult: return !expr->hasAttribute(wuidAtom); case no_null: return true; case no_getgraphresult: return !expr->hasAttribute(_distributed_Atom); default: return false; } } } bool isTrivialDataset(IHqlExpression * expr) { loop { if (isInlineTrivialDataset(expr)) return true; switch (expr->getOperator()) { case no_translated: case no_null: case no_temprow: case no_projectrow: case no_left: case no_right: case no_id2blob: case no_activerow: case no_typetransfer: case no_rows: case no_skip: case no_matchattr: case no_matchrow: case no_libraryinput: case no_workunit_dataset: case no_activetable: case no_top: return true; case no_select: if (!isNewSelector(expr)) return false; if (expr->isDataset()) return true; expr = expr->queryChild(0); break; case no_selectnth: case no_alias: case no_sorted: case no_distributed: case no_grouped: case no_preservemeta: case no_dataset_alias: case no_filter: case no_unordered: expr = expr->queryChild(0); break; case no_inlinetable: return isConstantDataset(expr); default: return false; } } } static unsigned estimateRowSize(IHqlExpression * record) { IHqlExpression * size = record->queryProperty(EPsize); if (!size || !size->queryChild(2)->queryValue()) return UNKNOWN_LENGTH; return (unsigned)getIntValue(size->queryChild(0)); } bool reducesRowSize(IHqlExpression * expr) { //More: This should be improved...., but slightly tricky without doing lots more processing. IHqlExpression * transform = queryNewColumnProvider(expr); IHqlExpression * prevRecord = expr->queryChild(0)->queryRecord(); unsigned newRowSize = estimateRowSize(transform->queryRecord()); unsigned prevRowSize = estimateRowSize(prevRecord); if ((newRowSize != UNKNOWN_LENGTH) && (prevRowSize != UNKNOWN_LENGTH)) return newRowSize < prevRowSize; IHqlExpression * record = expr->queryRecord(); if (getFlatFieldCount(record) < getFlatFieldCount(prevRecord)) return true; return false; } bool increasesRowSize(IHqlExpression * expr) { IHqlExpression * transform = queryNewColumnProvider(expr); IHqlExpression * prevRecord = expr->queryChild(0)->queryRecord(); unsigned newRowSize = estimateRowSize(transform); unsigned prevRowSize = estimateRowSize(prevRecord); if ((newRowSize != UNKNOWN_LENGTH) && (prevRowSize != UNKNOWN_LENGTH)) return newRowSize > prevRowSize; IHqlExpression * record = expr->queryRecord(); if (getFlatFieldCount(record) > getFlatFieldCount(prevRecord)) return true; return false; } bool isLimitedDataset(IHqlExpression * expr, bool onFailOnly) { loop { if (expr->hasAttribute(limitAtom)) return true; switch (expr->getOperator()) { case no_choosen: case no_limit: if (!onFailOnly || expr->hasAttribute(onFailAtom)) return true; break; case no_keyedlimit: if (onFailOnly && expr->hasAttribute(onFailAtom)) return true; break; case no_table: case no_newkeyindex: return false; default: if (getNumChildTables(expr) != 1) return false; break; } expr = expr->queryChild(0); } } bool containsAnyActions(IHqlExpression * expr) { switch (expr->getOperator()) { case no_comma: case no_compound: case no_actionlist: case no_orderedactionlist: { ForEachChild(i, expr) { if (containsAnyActions(expr->queryChild(i))) return true; } return false; } case no_setmeta: return false; default: return true; } } //-- Attribute: record count ------------------------------------------------------------------------------- unsigned getCardinality(IHqlExpression * expr) { loop { switch (expr->getOperator()) { case no_select: expr = expr->queryChild(1); break; case no_constant: return 1; case no_field: { IHqlExpression * cardinality = queryAttributeChild(expr, cardinalityAtom, 0); if (cardinality) return (unsigned)getIntValue(cardinality); } //fall through: default: return expr->queryType()->getCardinality(); } } } bool isSmallGrouping(IHqlExpression * sortlist) { unsigned __int64 totalCardinality = 1; unsigned max = sortlist->numChildren(); for (unsigned idx = 0; idx < max; idx++) { IHqlExpression * cur = sortlist->queryChild(idx); unsigned cardinality = getCardinality(cur); if (!cardinality) return false; totalCardinality *= cardinality; //don't use hash aggregation if larger than 100,000 potential elements if (totalCardinality >= 100000) return false; } return true; } //An estimate of the order of magnitude of the number of rows in a dataset. See function below for artificial thresholds. const static unsigned __int64 RCtinyLimit = 10; const static unsigned __int64 RCgroupLimit = 1000; const static unsigned __int64 RCfewLimit = 100000; const static unsigned __int64 RCmemoryLimit = 50000000; const static unsigned __int64 RCclusterSizeEstimate = 5000; enum RowCountMagnitude { RCMnone, // 0 RCMtiny, // < 10 RCMgroup, // < 1000 RCMfew, // < 100,000 RCMmemory, // < memory RCMdisk, // who knows? RCMunknown }; const char * const magnitudeText[] = { "empty", "tiny", "group", "few", "memory", "disk", "unknown" }; inline RowCountMagnitude getRowCountMagnitude(__int64 num) { if (num == 0) return RCMnone; if (num <= RCtinyLimit) return RCMtiny; if (num <= RCgroupLimit) return RCMgroup; if (num <= RCfewLimit) return RCMfew; if (num <= RCmemoryLimit) return RCMmemory; return RCMdisk; } static IHqlExpression * makeConstant(__int64 value) { if ((value >= 0) && (size32_t)value == value) return getSizetConstant((size32_t)value); return createConstant(value); } struct HqlRowCountInfo { public: HqlRowCountInfo() { setUnknown(RCMnone); } void applyChoosen(IHqlExpression * limitExpr, __int64 limit, bool isLocal, bool isGrouped); void combineAlternatives(const HqlRowCountInfo & other); void combineBoth(const HqlRowCountInfo & other); bool extractHint(IHqlExpression * hint); void limitMin(__int64 value); void setEstimate(__int64 n); void scaleFixed(__int64 scale); void scaleRange(__int64 scale); void setMin(__int64 n) { min.setown(makeConstant(n)); } void setMin(IHqlExpression * value) { min.set(value); } void setN(__int64 n); void setN(IHqlExpression * value); void setRange(__int64 low, __int64 high); void setUnknown(RowCountMagnitude _magnitude); void setMaxMagnitude(RowCountMagnitude _magnitude) { if (magnitude > _magnitude) magnitude = _magnitude; } IHqlExpression * createRecordCountAttr() { return createExprAttribute(_propRecordCount_Atom, makeConstant(magnitude), LINK(min), LINK(max));// , LINK(estimate)); } void extract(IHqlExpression * attr) { assertex(attr->queryName() == _propRecordCount_Atom); magnitude = (RowCountMagnitude)getIntValue(attr->queryChild(0)); min.set(attr->queryChild(1)); max.set(attr->queryChild(2)); //estimate.set(attr->queryChild(3)); } inline void setSingleRow() { setN(1); } void getText(StringBuffer & text) const; __int64 getMin() const { return getIntValue(min); } inline bool isSingleRow() const { return matchesConstantValue(min, 1) && matchesConstantValue(max, 1); } inline bool alwaysHasRow() const { return !matchesConstantValue(min, 0); } public: OwnedHqlExpr min; // Absolute minimum - can't be fewer records OwnedHqlExpr max; // Absolute maximum - can't be more records RowCountMagnitude magnitude; // Expected magnitude. Normally matches max, but may occasionally diverge,. //It might be possible to calculate an estimate of the number of rows, but I'm not sure if it //is possible to make it significantly more useful than the magnitude. // OwnedHqlExpr estimate; }; void HqlRowCountInfo::applyChoosen(IHqlExpression * limitExpr, __int64 limit, bool isLocal, bool isGrouped) { if (getMin() > limit) { if (limitExpr->isConstant() && (limit >= 0)) min.set(limitExpr); else min.setown(makeConstant(0)); } if (!isGrouped && (limit != 0)) { __int64 maxLimit = isLocal ? RCclusterSizeEstimate*limit : limit; if (getIntValue(max, maxLimit+1) > maxLimit) { if (isLocal) max.setown(makeConstant(maxLimit)); else max.set(limitExpr); } RowCountMagnitude newMagnitude = getRowCountMagnitude(maxLimit); if (magnitude > newMagnitude) magnitude = newMagnitude; } } void HqlRowCountInfo::combineAlternatives(const HqlRowCountInfo & other) { if (other.getMin() < getMin()) min.set(other.min); IValue * maxValue = max->queryValue(); if (maxValue) { IValue * otherMaxValue = other.max->queryValue(); if (!otherMaxValue || (otherMaxValue->getIntValue() > maxValue->getIntValue())) max.set(other.max); } if (magnitude < other.magnitude) magnitude = other.magnitude; } void HqlRowCountInfo::combineBoth(const HqlRowCountInfo & other) { min.setown(makeConstant(getMin()+other.getMin())); IValue * maxValue = max->queryValue(); IValue * otherMaxValue = other.max->queryValue(); if (!otherMaxValue) max.set(other.max); else if (maxValue) { __int64 newMax = maxValue->getIntValue()+otherMaxValue->getIntValue(); max.setown(makeConstant(newMax)); } //Appending shouldn't change to a larger magnitude. if (magnitude < other.magnitude) magnitude = other.magnitude; } bool HqlRowCountInfo::extractHint(IHqlExpression * hint) { IHqlExpression * arg = hint->queryChild(0); if (!arg) return false; switch (arg->getOperator()) { case no_constant: setN(arg); return true; case no_rangeto: setRange(0, getIntValue(arg->queryChild(0))); return true; case no_range: setRange(getIntValue(arg->queryChild(0)), getIntValue(arg->queryChild(1))); return true; case no_attr: { IAtom * name = arg->queryName(); RowCountMagnitude magnitude = RCMnone; if (name == tinyAtom) magnitude = RCMtiny; else if (name == groupAtom) magnitude = RCMgroup; else if (name == fewAtom) magnitude = RCMfew; else if (name == memoryAtom) magnitude = RCMmemory; if (magnitude != RCMnone) { setUnknown(magnitude); return true; } break; } } return false; } void HqlRowCountInfo::getText(StringBuffer & text) const { min->queryValue()->generateECL(text); if (getMin() != getIntValue(max, -1)) { text.append(".."); if (max->queryValue()) max->queryValue()->generateECL(text); else text.append("?"); text.append("[").append(magnitudeText[magnitude]).append("]"); } } void HqlRowCountInfo::limitMin(__int64 value) { if (getMin() > value) min.setown(makeConstant(value)); } void HqlRowCountInfo::scaleFixed(__int64 scale) { __int64 minValue = getMin(); __int64 maxValue = getIntValue(max, 0); if (maxValue) { setRange(minValue * scale, maxValue * scale); // MORE: Worry about 64bit overflow } else { setUnknown(RCMdisk); setMin(minValue * scale); } } void HqlRowCountInfo::scaleRange(__int64 scale) { scaleFixed(scale); min.setown(makeConstant(0)); } void HqlRowCountInfo::setEstimate(__int64 n) { magnitude = getRowCountMagnitude(n); } void HqlRowCountInfo::setN(__int64 n) { setMin(n); max.set(min); magnitude = getRowCountMagnitude(n); } void HqlRowCountInfo::setN(IHqlExpression * value) { min.set(value); max.set(min); magnitude = getRowCountMagnitude(getIntValue(value)); } void HqlRowCountInfo::setRange(__int64 low, __int64 high) { min.setown(makeConstant(low)); max.setown(makeConstant(high)); magnitude = getRowCountMagnitude(high); } void HqlRowCountInfo::setUnknown(RowCountMagnitude _magnitude) { min.setown(getSizetConstant(0)); max.setown(getUnknownAttribute()); magnitude = _magnitude; } //MORE: This information should be cached in an attribute, once it is working, and used in more than one place. void retrieveRowInformation(HqlRowCountInfo & info, IHqlExpression * expr) { IHqlExpression * attr = expr->queryProperty(EPrecordCount); info.extract(attr); } static void calcIntersectingRowInformation(HqlRowCountInfo & info, IHqlExpression * expr, unsigned firstDs) { retrieveRowInformation(info, expr->queryChild(firstDs)); ForEachChildFrom(i, expr, firstDs+1) { IHqlExpression * cur = expr->queryChild(i); if (!cur->isAttribute()) { HqlRowCountInfo nextInfo; retrieveRowInformation(nextInfo, cur); info.combineBoth(nextInfo); } } } //MORE: This would benefit from knowing if the target is hthor/roxie (or a thoir child query) so it could tell if local means //anything. The best solution is to annotate the graph with _global_ for thor, or _single_ for the others. One day.... IHqlExpression * calcRowInformation(IHqlExpression * expr) { HqlRowCountInfo info; IHqlExpression * hint = queryHint(expr, outputAtom); if (hint && info.extractHint(hint)) return info.createRecordCountAttr(); IHqlExpression * ds = expr->queryChild(0); node_operator op = expr->getOperator(); switch (op) { case no_nothor: case no_thor: case no_compound_diskread: case no_compound_disknormalize: case no_compound_diskaggregate: case no_compound_diskcount: case no_compound_diskgroupaggregate: case no_compound_indexread: case no_compound_indexnormalize: case no_compound_indexaggregate: case no_compound_indexcount: case no_compound_indexgroupaggregate: case no_compound_childread: case no_compound_childnormalize: case no_compound_childaggregate: case no_compound_childcount: case no_compound_childgroupaggregate: case no_compound_inline: case no_compound_selectnew: case no_compound_fetch: case no_alias: case no_forcelocal: case no_distribute: case no_distributed: case no_preservemeta: case no_keyeddistribute: case no_sorted: case no_stepped: case no_assertsorted: case no_assertgrouped: case no_assertdistributed: case no_sort: case no_subsort: case no_nohoist: case no_section: case no_sectioninput: case no_assert_ds: case no_readspill: case no_writespill: case no_commonspill: case no_forcegraph: case no_split: case no_spill: case no_spillgraphresult: case no_outofline: case no_globalscope: case no_throughaggregate: case no_alias_scope: case no_thisnode: case no_preload: case no_combine: case no_catchds: case no_metaactivity: case no_cosort: case no_serialize: case no_deserialize: case no_executewhen: case no_owned_ds: case no_dataset_alias: case no_nocombine: case no_unordered: { return getRecordCountInfo(ds); } case no_allnodes: { retrieveRowInformation(info, ds); info.scaleRange(RCclusterSizeEstimate); break; } case no_limit: case no_keyedlimit: { retrieveRowInformation(info, ds); IHqlExpression * limitExpr = expr->queryChild(1); __int64 limit = getIntValue(limitExpr, 0); info.applyChoosen(limitExpr, limit, isLocalActivity(expr), isGrouped(expr)); break; } case no_hqlproject: case no_iterate: { retrieveRowInformation(info, ds); if (transformContainsSkip(expr->queryChild(1))) info.limitMin(0); break; } case no_fetch: { retrieveRowInformation(info, expr->queryChild(1)); if (transformContainsSkip(expr->queryChild(3))) info.limitMin(0); break; } case no_dedup: { retrieveRowInformation(info, ds); //Only affect minimum => Grouped, local and non grouped may all reduce to 1 info.limitMin(1); break; } case no_rollup: case no_rollupgroup: { //rollup on a single row is a single row, rollup on non single may or may not be. retrieveRowInformation(info, ds); if (transformContainsSkip(queryNewColumnProvider(expr))) info.limitMin(0); else info.limitMin(1); break; } case no_aggregate: case no_newaggregate: case no_newusertable: case no_selectfields: case no_usertable: { retrieveRowInformation(info, ds); if (isAggregateDataset(expr)) { IHqlExpression * grouping = queryDatasetGroupBy(expr); if (!grouping) grouping = queryGrouping(ds); if (grouping) { //Either aggregate grouped dataset, or grouping supplied. Similar semantics. //minimum is 1 unless inputs has minimum of 0 info.limitMin(1); if (expr->hasAttribute(fewAtom)) info.setMaxMagnitude(RCMfew); else if (isSmallGrouping(grouping)) info.setMaxMagnitude(RCMfew); } else if (isLocalActivity(expr)) { info.setRange(1, RCclusterSizeEstimate); // local,ungrouped -> one per node } else info.setSingleRow(); } else { if (transformContainsSkip(queryNewColumnProvider(expr))) info.limitMin(0); } break; // maybe a project of an aggregate } case no_selectnth: case no_datasetfromrow: case no_activerow: { info.setSingleRow(); break; } case no_rows: { info.setUnknown(RCMgroup); break; } case no_rowsetindex: case no_rowsetrange: { info.setUnknown(RCMmemory); break; } case no_workunit_dataset: case no_getgraphresult: case no_getgraphloopresult: case no_getresult: { IHqlExpression * attr = expr->queryAttribute(_propRecordCount_Atom); if (attr) return LINK(attr); if (expr->isDatarow() || expr->hasAttribute(rowAtom)) { info.setSingleRow(); } else { if (expr->hasAttribute(_distributed_Atom)) info.setUnknown(RCMdisk); else info.setUnknown(RCMfew); } break; } case no_table: case no_keyindex: case no_newkeyindex: { IHqlExpression * attr = expr->queryAttribute(_propRecordCount_Atom); if (attr) return LINK(attr); if (expr->isDatarow() || expr->hasAttribute(rowAtom)) { info.setSingleRow(); } else { info.setUnknown(RCMdisk); //Allow an annotation on a dataset to specify exact and ranges of counts. IHqlExpression * count = queryAttributeChild(expr, countAtom, 0); IHqlExpression * maxCount = queryAttributeChild(expr, maxCountAtom, 0); IHqlExpression * aveCount = queryAttributeChild(expr, aveAtom, 0); if (count) info.setN(count); else if (maxCount) info.setRange(0, getIntValue(maxCount)); else if (aveCount) info.setEstimate(getIntValue(aveCount)); } break; } case no_filter: case no_filtergroup: case no_sample: { retrieveRowInformation(info, ds); info.limitMin(0); //More sample could potentially reduce the magnitude break; } case no_temptable: { IHqlExpression * values = expr->queryChild(0); if (values->getOperator() == no_recordlist) info.setN(values->numChildren()); else info.setUnknown(RCMfew); break; } case no_inlinetable: { IHqlExpression * transforms = expr->queryChild(0); unsigned maxValue = transforms->numChildren(); unsigned minValue = 0; for (unsigned i=0; i < maxValue; i++) { if (!containsSkip(transforms->queryChild(i))) minValue++; } info.setRange(minValue, maxValue); break; } case no_dataset_from_transform: { // only if the count is a constant value IHqlExpression * count = expr->queryChild(0); IValue * value = count->queryValue(); if (value) { IHqlExpression * transform = expr->queryChild(1); __int64 maxCount = value->getIntValue(); if (containsSkip(transform)) { if (expr->hasAttribute(localAtom)) info.setUnknown(RCMunknown); else info.setRange(0, maxCount); } else { if (expr->hasAttribute(localAtom)) { info.setUnknown(RCMdisk); info.setMin(count); } else info.setN(count); } } else info.setUnknown(RCMdisk); // leave it be, if it's a constant expression or a variable break; } case no_null: info.setN(expr->isDatarow() ? 1 : 0); break; case no_fail: info.setN(I64C(0)); break; case no_if: { retrieveRowInformation(info, expr->queryChild(1)); IHqlExpression * rhs = expr->queryChild(2); if (rhs) { HqlRowCountInfo rhsInfo; retrieveRowInformation(rhsInfo, rhs); info.combineAlternatives(rhsInfo); } else { info.min.setown(getSizetConstant(0)); } break; } case no_nonempty: { retrieveRowInformation(info, ds); //Go through the children so we get a sensible value for the magnitude unsigned max = expr->numChildren(); for (unsigned i=1; i< max; i++) { if (!isZero(info.min)) break; IHqlExpression * cur = expr->queryChild(i); if (!cur->isAttribute()) { HqlRowCountInfo nextInfo; retrieveRowInformation(nextInfo, cur); info.min.set(nextInfo.min); info.combineAlternatives(nextInfo); } } break; } case no_chooseds: case no_regroup: case no_combinegroup: case no_addfiles: case no_merge: { unsigned firstDataset = getFirstActivityArgument(expr); calcIntersectingRowInformation(info, expr, firstDataset); break; } case no_choosen: { retrieveRowInformation(info, ds); IHqlExpression * limitExpr = expr->queryChild(1); __int64 choosenLimit = getIntValue(limitExpr, 0); if (choosenLimit == CHOOSEN_ALL_LIMIT) info.limitMin(0); // play safe - could be clever if second value is constant, and min/max known. else info.applyChoosen(limitExpr, choosenLimit, isLocalActivity(expr), isGrouped(expr)); } break; case no_quantile: { __int64 parts = getIntValue(expr->queryChild(1), 0); if ((parts > 0) && !isGrouped(expr) && !isLocalActivity(expr)) { if (expr->hasAttribute(firstAtom)) parts++; if (expr->hasAttribute(lastAtom)) parts++; IHqlExpression * transform = queryNewColumnProvider(expr); if (transformContainsSkip(transform) || expr->hasAttribute(dedupAtom)) info.setRange(0,parts-1); else info.setN(parts-1); } else info.setUnknown(RCMfew); } break; case no_topn: { retrieveRowInformation(info, ds); IHqlExpression * limitExpr = expr->queryChild(2); __int64 choosenLimit = getIntValue(limitExpr, 0); info.applyChoosen(limitExpr, choosenLimit, isLocalActivity(expr), isGrouped(expr)); } break; case no_select: { bool isNew; IHqlExpression * realDs = querySelectorDataset(expr, isNew); if (isNew) retrieveRowInformation(info, realDs); else info.setSingleRow(); if (!expr->isDatarow()) { IHqlExpression * field = expr->queryChild(1); __int64 count = getIntValue(queryAttributeChild(field, countAtom, 0), 0); __int64 maxcount = getIntValue(queryAttributeChild(field, maxCountAtom, 0), 0); if (count) info.scaleFixed(count); else if (maxcount) info.scaleRange(maxcount); else if (info.isSingleRow()) info.setUnknown(RCMfew); else info.setUnknown(RCMdisk); } break; } case no_normalize: { retrieveRowInformation(info, ds); IValue * numRows = expr->queryChild(1)->queryValue(); if (numRows) { __int64 scale = numRows->getIntValue(); if (containsSkip(expr->queryChild(2))) info.scaleRange(scale); else info.scaleFixed(scale); } else info.setUnknown(RCMdisk); break; } case no_group: case no_grouped: //MORE: Not completely sure how we should handle groups. return getRecordCountInfo(ds); case no_join: case no_selfjoin: { __uint64 maxMatchesPerLeftRow = (__uint64)-1; if (expr->hasAttribute(leftonlyAtom)) maxMatchesPerLeftRow = 1; else if (isLeftJoin(expr) || isInnerJoin(expr)) { //MORE: Could process other small scalings e.g., < 10 from keep/atmost attributes IHqlExpression * keep = queryAttributeChild(expr, keepAtom, 0); if (matchesConstantValue(keep, 1)) maxMatchesPerLeftRow = 1; IHqlExpression * atmost = queryAttributeChild(expr, atmostAtom, 0); if (matchesConstantValue(atmost, 1)) maxMatchesPerLeftRow = 1; } if (maxMatchesPerLeftRow == 1) { retrieveRowInformation(info, ds); if (!expr->hasAttribute(leftouterAtom) || containsSkip(expr->queryChild(3))) info.limitMin(0); } else info.setUnknown(RCMdisk); break; } case no_denormalize: case no_denormalizegroup: { retrieveRowInformation(info, ds); if (containsSkip(expr->queryChild(3))) info.limitMin(0); break; } case no_mergejoin: case no_nwayjoin: case no_nwaymerge: info.setUnknown(RCMdisk); break; case no_loop: case no_graphloop: case no_libraryselect: case no_libraryinput: case no_param: case no_anon: case no_nofold: // assume nothing - to stop subsequent optimizations case no_delayedselect: case no_unboundselect: case no_internalselect: info.setUnknown(RCMdisk); break; case no_parse: case no_newparse: case no_xmlparse: case no_newxmlparse: case no_soapcall: case no_soapcall_ds: case no_newsoapcall: case no_newsoapcall_ds: case no_httpcall: case no_process: case no_pipe: case no_translated: case no_datasetfromdictionary: //MORE could improve each of these info.setUnknown(RCMdisk); break; case no_map: case no_case: { if (expr->isDatarow()) { info.setSingleRow(); break; } //This is primarily implemented so the annotations in the graph look correct unsigned start = (op == no_case) ? 1 : 0; IHqlExpression * dft = NULL; ForEachChildFrom(i1, expr, start) { IHqlExpression * cur = expr->queryChild(i1); if (cur->getOperator() != no_mapto) { if (!cur->isAttribute()) dft = cur; break; } } if (dft) retrieveRowInformation(info, dft); else info.setN(I64C(0)); ForEachChildFrom(i2, expr, start) { IHqlExpression * cur = expr->queryChild(i2); if (cur->getOperator() == no_mapto) { HqlRowCountInfo rhsInfo; retrieveRowInformation(rhsInfo, cur->queryChild(1)); info.combineAlternatives(rhsInfo); } } break; } case no_id2blob: case no_xmlproject: case no_call: case no_externalcall: case no_embedbody: info.setUnknown(RCMfew); break; case no_colon: { IHqlExpression * workflow = expr->queryChild(1); //For either of if (queryOperatorInList(no_stored, workflow) || queryOperatorInList(no_recovery, workflow)) { info.setUnknown(RCMdisk); break; } //MORE: Could restrict based on few flags return getRecordCountInfo(ds); } case no_choosesets: case no_enth: //MORE: Could sum the numbers to return return getRecordCountInfo(ds); case no_compound: return getRecordCountInfo(expr->queryChild(1)); default: if (expr->isDataset()) UNIMPLEMENTED_XY("Record count calculation for operator", getOpString(op)); if (expr->isDatarow()) info.setSingleRow(); else info.setUnknown(RCMdisk); //Assume the worse case... break; } return info.createRecordCountAttr(); } static IHqlExpression * evalautePropRecordCount(IHqlExpression * expr) { OwnedHqlExpr info = calcRowInformation(expr); meta.addProperty(expr, EPrecordCount, info); return info; } void getRecordCountText(StringBuffer & result, IHqlExpression * expr) { HqlRowCountInfo info; retrieveRowInformation(info, expr); info.getText(result); } //--------------------------------------------------------------------------------- bool hasFewRows(IHqlExpression * expr) { HqlRowCountInfo info; retrieveRowInformation(info, expr); return (info.magnitude <= RCMfew); } bool spillToWorkunitNotFile(IHqlExpression * expr, ClusterType platform) { if (platform == RoxieCluster) return true; if (isThorCluster(platform)) { //In thor, all rows will get sent to master and written to dali, and then read back on slave 0 //not likely to be more efficient unless only a single row - although the generated code accessing //from a child query is better return hasNoMoreRowsThan(expr, 1); } return hasFewRows(expr); } bool hasSingleRow(IHqlExpression * expr) { HqlRowCountInfo info; retrieveRowInformation(info, expr); return info.isSingleRow(); } bool hasNoMoreRowsThan(IHqlExpression * expr, __int64 limit) { HqlRowCountInfo info; retrieveRowInformation(info, expr); return getIntValue(info.max, limit+1) <= limit; } IHqlExpression * queryFixedRowCount(IHqlExpression * expr) { HqlRowCountInfo info; retrieveRowInformation(info, expr); if (info.min == info.max) return LINK(info.min); return NULL; } // Functions for testing whether // Functions for accessing attributes from types etc. IHqlExpression * queryAttribute(ITypeInfo * type, IAtom * search) { loop { typemod_t curModifier = type->queryModifier(); switch (curModifier) { case typemod_none: return NULL; case typemod_attr: { IHqlExpression * prop = static_cast<IHqlExpression *>(type->queryModifierExtra()); if (prop->queryName() == search) return prop; break; } case typemod_original: { IHqlExpression * original = static_cast<IHqlExpression *>(type->queryModifierExtra()); IHqlExpression * match = original->queryAttribute(search); if (match) return match; break; } } type = type->queryTypeBase(); } } IHqlExpression * queryAttributeChild(ITypeInfo * type, IAtom * search, unsigned idx) { IHqlExpression * match = queryAttribute(type, search); if (match) return match->queryChild(idx); return NULL; } // Functions for extracting and preserving attribute information on types and fields. void cloneFieldModifier(Shared<ITypeInfo> & type, ITypeInfo * donorType, IAtom * attr) { IHqlExpression * match = queryAttribute(donorType, attr); if (!match) return; IHqlExpression * existing = queryAttribute(type, attr); if (match == existing) return; type.setown(makeAttributeModifier(type.getClear(), LINK(match))); } ITypeInfo * cloneEssentialFieldModifiers(ITypeInfo * donor, ITypeInfo * rawtype) { Linked<ITypeInfo> type = rawtype; cloneFieldModifier(type, donor, maxLengthAtom); cloneFieldModifier(type, donor, maxSizeAtom); cloneFieldModifier(type, donor, maxCountAtom); return type.getClear(); } ITypeInfo * removeAttribute(ITypeInfo * t, IAtom * search) { typemod_t curModifier = t->queryModifier(); if (curModifier == typemod_none) return LINK(t); ITypeInfo * base = t->queryTypeBase(); if (curModifier == typemod_attr) { IHqlExpression * attr = (IHqlExpression *)t->queryModifierExtra(); if (attr->queryName() == search) return LINK(base); } OwnedITypeInfo newBase = removeAttribute(base, search); if (newBase == base) return LINK(t); return makeModifier(newBase.getClear(), curModifier, LINK(t->queryModifierExtra())); } bool isUninheritedFieldAttribute(IHqlExpression * expr) { if (expr->isAttribute()) { IAtom * name = expr->queryName(); //MORE: Attributes of datasets need a different representation - should probably be include in the type somehow... if ((name == virtualAtom) || (name == countAtom)) return true; } return false; } bool hasUninheritedAttribute(IHqlExpression * field) { ForEachChild(i, field) if (isUninheritedFieldAttribute(field->queryChild(i))) return true; return false; } IHqlExpression * extractFieldAttrs(IHqlExpression * field) { IHqlExpression * attrs = NULL; ForEachChild(idx, field) { IHqlExpression * child = field->queryChild(idx); if (child->isAttribute()) { //MORE: Attributes of datasets need a different representation - should probably be include in the type somehow... if (!isUninheritedFieldAttribute(child)) { // which others should we ignore? attrs = createComma(attrs, LINK(child)); } } } return attrs; } IHqlExpression * extractAttrsFromExpr(IHqlExpression * value) { if (!value) return NULL; if (value->getOperator() == no_select) value = value->queryChild(1); if (value->getOperator() == no_field) return extractFieldAttrs(value); return NULL; } // Type processing ITypeInfo * getPromotedECLType(ITypeInfo * lType, ITypeInfo * rType) { return ::getPromotedType(lType, rType); } ITypeInfo * getPromotedECLCompareType(ITypeInfo * lType, ITypeInfo * rType) { return ::getPromotedCompareType(lType, rType); } unsigned getMaxRecordSize(IHqlExpression * record, unsigned defaultMaxRecordSize, bool & hasKnownSize, bool & usedDefault) { IHqlExpression * size = record->queryProperty(EPsize); IHqlExpression * minSizeExpr = size->queryChild(1); IHqlExpression * maxSizeExpr = size->queryChild(2); unsigned maxSize = (unsigned)getIntValue(maxSizeExpr, UNKNOWN_LENGTH); hasKnownSize = (minSizeExpr == maxSizeExpr); if (maxSize == UNKNOWN_LENGTH) { OwnedHqlExpr defaultExpr = getSizetConstant(defaultMaxRecordSize); OwnedHqlExpr value = replaceExpression(maxSizeExpr, queryDefaultMaxRecordLengthExpr(), defaultExpr); OwnedHqlExpr folded = foldHqlExpression(value); assertex(folded); maxSize = (unsigned)getIntValue(folded); unsigned minSize = (unsigned)getIntValue(minSizeExpr); if (maxSize < minSize) maxSize = minSize; usedDefault = true; } else usedDefault = false; return maxSize; } size32_t getExpectedRecordSize(IHqlExpression * record) { IHqlExpression * size = record->queryProperty(EPsize); return size ? (size32_t)getIntValue(size->queryChild(0)) : 0; } size32_t getMinRecordSize(IHqlExpression * record) { IHqlExpression * size = record->queryProperty(EPsize); return size ? (size32_t)getIntValue(size->queryChild(1)) : 0; } unsigned getMaxRecordSize(IHqlExpression * record, unsigned defaultMaxRecordSize) { bool isKnownSize, usedDefault; return getMaxRecordSize(record, defaultMaxRecordSize, isKnownSize, usedDefault); } bool maxRecordSizeUsesDefault(IHqlExpression * record) { IHqlExpression * maxSize = record->queryProperty(EPsize)->queryChild(2); return (maxSize->queryValue() == NULL); } bool isVariableSizeRecord(IHqlExpression * record) { IHqlExpression * sizeAttr = record->queryProperty(EPsize); return sizeAttr->queryChild(1) != sizeAttr->queryChild(2); } bool maxRecordSizeIsAmbiguous(IHqlExpression * record, size32_t & specifiedSize, size32_t & derivedSize) { IHqlExpression * sizeAttr = record->queryProperty(EPsize); IHqlExpression * derivedSizeExpr = sizeAttr->queryChild(3); if (!derivedSizeExpr || !derivedSizeExpr->isConstant()) return false; OwnedHqlExpr foldedDerivedSize = foldHqlExpression(derivedSizeExpr); if (!foldedDerivedSize->queryValue()) return false; IHqlExpression * maxLength = sizeAttr->queryChild(2); OwnedHqlExpr foldedMaxLength = foldHqlExpression(maxLength); if (!foldedMaxLength->queryValue()) return false; specifiedSize = (size32_t)foldedMaxLength->queryValue()->getIntValue(); derivedSize = (size32_t) foldedDerivedSize->queryValue()->getIntValue(); return derivedSize != specifiedSize; } bool maxRecordSizeCanBeDerived(IHqlExpression * record) { if (!isVariableSizeRecord(record)) return true; if (record->hasAttribute(maxLengthAtom)) { IHqlExpression * sizeAttr = record->queryProperty(EPsize); IHqlExpression * derivedSizeExpr = sizeAttr->queryChild(3); return (derivedSizeExpr != NULL); } return !maxRecordSizeUsesDefault(record); } //--------------------------------------------------------------------------------- bool recordRequiresSerialization(IHqlExpression * expr, IAtom * serializeForm) { if (!expr) return false; if (querySerializedForm(expr, serializeForm) != expr) return true; return false; } bool recordRequiresDestructor(IHqlExpression * expr) { if (!expr) return false; IHqlExpression * body = expr->queryBody(); //true if the internal serialized form is different if (querySerializedForm(body, internalAtom) != body) return true; return false; } bool recordRequiresLinkCount(IHqlExpression * expr) { //MORE: This should strictly speaking check if any of the child fields are link counted. //This function is a sufficient proxy at the moment return recordRequiresDestructor(expr); } bool recordSerializationDiffers(IHqlExpression * expr, IAtom * serializeForm1, IAtom * serializeForm2) { return querySerializedForm(expr, serializeForm1) != querySerializedForm(expr, serializeForm2); } extern HQL_API bool typeRequiresDeserialization(ITypeInfo * type, IAtom * serializeForm) { Owned<ITypeInfo> serializedType = getSerializedForm(type, serializeForm); if (queryUnqualifiedType(serializedType) == queryUnqualifiedType(type)) return false; type_t stc = serializedType->getTypeCode(); if (stc != type->getTypeCode()) return true; if (stc == type_table) { if (recordTypesMatch(serializedType, type)) return false; return true; } return true; } //--------------------------------------------------------------------------------- IHqlExpression * queryRecordCountInfo(IHqlExpression * expr) { return expr->queryProperty(EPrecordCount); } IHqlExpression * getRecordCountInfo(IHqlExpression * expr) { return LINK(expr->queryProperty(EPrecordCount)); } IHqlExpression * queryExpectedRecordCount(IHqlExpression * expr) { IHqlExpression * attr = expr->queryProperty(EPrecordCount); return attr ? attr->queryChild(0) : NULL; } IHqlExpression * getPackedRecord(IHqlExpression * expr) { IHqlExpression * attr = expr->queryProperty(EPaligned); IHqlExpression * packed = attr->queryChild(0); if (!packed) packed = expr; return LINK(packed); } /* * This function can be called while parsing (or later) to find a "normalized" version of a record or a field. * It ignores default values for fields, and removes named symbols/ other location specific information - so * that identical records defined in macros etc. are treated as identical. */ IHqlExpression * getUnadornedRecordOrField(IHqlExpression * expr) { if (!expr) return NULL; IHqlExpression * attr = expr->queryProperty(EPunadorned); return LINK(attr); } //--------------------------------------------------------------------------------- inline bool isAlwaysLocationIndependent(IHqlExpression * expr) { switch (expr->getOperator()) { case no_constant: case no_param: case no_quoted: case no_variable: return true; case no_attr: return (expr->numChildren() == 0); } return false; } class HqlLocationIndependentNormalizer : public QuickHqlTransformer { public: HqlLocationIndependentNormalizer(); virtual IHqlExpression * createTransformed(IHqlExpression * expr); virtual ITypeInfo * transformType(ITypeInfo * type); protected: IHqlExpression * doCreateTransformed(IHqlExpression * expr); }; static HqlTransformerInfo hqlLocationIndependentInfo("HqlLocationIndependentNormalizer"); HqlLocationIndependentNormalizer::HqlLocationIndependentNormalizer() : QuickHqlTransformer(hqlLocationIndependentInfo, NULL) { } ITypeInfo * HqlLocationIndependentNormalizer::transformType(ITypeInfo * type) { switch (type->queryModifier()) { case typemod_original: return transformType(type->queryTypeBase()); case typemod_none: return QuickHqlTransformer::transformType(type); case typemod_indirect: { IHqlExpression * original = static_cast<IHqlExpression *>(type->queryModifierExtra()); OwnedHqlExpr transformed = transform(original); return makeModifier(transformed->getType(), typemod_indirect, LINK(transformed)); } default: { ITypeInfo * typeBase = type->queryTypeBase(); Owned<ITypeInfo> newType = transformType(typeBase); if (typeBase == newType) return LINK(type); return cloneModifier(type, newType); } } } IHqlExpression * HqlLocationIndependentNormalizer::doCreateTransformed(IHqlExpression * expr) { node_operator op = expr->getOperator(); switch (op) { case no_attr: { //Original attributes cause chaos => remove all children from attributes if (expr->numChildren() != 0) { IAtom * name = expr->queryName(); if ((name != _countProject_Atom) && (name != _metadata_Atom)) return createAttribute(expr->queryName()); } return LINK(expr); } case no_field: { //Remove the default values from fields since they just confuse. HqlExprArray children; bool same = true; ForEachChild(idx, expr) { IHqlExpression * cur = expr->queryChild(idx); if (cur->isAttribute()) { IHqlExpression * mapped = transform(cur); children.append(*mapped); if (mapped != cur) same = false; } else same = false; } ITypeInfo * type = expr->queryType(); OwnedITypeInfo newType = transformType(type); if (type != newType) return createField(expr->queryId(), newType.getClear(), children); if (same) return LINK(expr); return expr->clone(children); } } return QuickHqlTransformer::createTransformed(expr); } IHqlExpression * HqlLocationIndependentNormalizer::createTransformed(IHqlExpression * expr) { //Remove all annotations. It is vaguely possible there are some annotations we would want to retain, but I don't know of any IHqlExpression * body = expr->queryBody(false); if (expr != body) return transform(body); if (isAlwaysLocationIndependent(expr)) return LINK(expr); IInterface * match = meta.queryExistingProperty(expr, EPlocationIndependent); if (match) return static_cast<IHqlExpression *>(LINK(match)); OwnedHqlExpr transformed = doCreateTransformed(expr); meta.addProperty(expr, EPlocationIndependent, transformed); return transformed.getClear(); } IHqlExpression * evalautePropLocationIndependent(IHqlExpression * expr) { if (isAlwaysLocationIndependent(expr)) return expr->queryBody(); //Because the transformers contain all the logic for how scopes etc. are transformed it is much better to //use a transformer which caches the result in the expression tree instead of trying to replicate //all the rules in some member functions. HqlLocationIndependentNormalizer normalizer; OwnedHqlExpr transformed = normalizer.transform(expr); return transformed; // NB: no getClear(). Because it is cached it is guaranteed to exist even when this link is released. } IHqlExpression * queryLocationIndependent(IHqlExpression * expr) { IHqlExpression * match = expr->queryProperty(EPlocationIndependent); if (match) return match; return expr; } static void cloneAttributeAsModifier(Owned<ITypeInfo> & type, IHqlExpression * donor, IAtom * attr) { if (queryAttribute(type, attr)) return; IHqlExpression * match = donor->queryAttribute(attr); if (!match) return; type.setown(makeAttributeModifier(type.getClear(), LINK(match))); } ITypeInfo * preserveTypeQualifiers(ITypeInfo * ownedType, IHqlExpression * donor) { //The following would be a good idea, but it won't work until we introduce a recordof() operator //and use that whenever queryRecord() is currenly called (see bug46863) // type = makeModifier(type, typemod_indirect, LINK(arg)); //Instead, just clone the attributes we need IHqlExpression * field = queryFieldFromExpr(donor); switch (field->getOperator()) { case no_field: // case no_record: break; default: return ownedType; } OwnedITypeInfo type = ownedType; cloneAttributeAsModifier(type, field, maxLengthAtom); cloneAttributeAsModifier(type, field, maxSizeAtom); cloneAttributeAsModifier(type, field, maxCountAtom); return type.getClear(); } static bool cloneModifierAsAttribute(HqlExprArray & args, ITypeInfo * donor, IAtom * attr) { IHqlExpression * match = queryAttribute(donor, attr); if (!match) return true; if (queryAttribute(attr, args)) return true; args.append(*LINK(match)); return false; } bool preserveTypeQualifiers(HqlExprArray & args, ITypeInfo * donor) { bool same = true; same = cloneModifierAsAttribute(args, donor, maxLengthAtom) && same; same = cloneModifierAsAttribute(args, donor, maxSizeAtom) && same; same = cloneModifierAsAttribute(args, donor, maxCountAtom) && same; return same; } IHqlExpression * preserveTypeQualifiers(IHqlExpression * ownedField, ITypeInfo * donor) { OwnedHqlExpr field = ownedField; HqlExprArray args; unwindChildren(args, field); if (preserveTypeQualifiers(args, donor)) return field.getClear(); return field->clone(args); } bool isLinkedRowset(ITypeInfo * t) { switch (t->getTypeCode()) { case type_table: case type_groupedtable: case type_dictionary: return hasLinkCountedModifier(t); } return false; } bool isArrayRowset(ITypeInfo * t) { switch (t->getTypeCode()) { case type_table: case type_groupedtable: case type_array: case type_dictionary: { if (hasStreamedModifier(t)) return false; if (hasLinkCountedModifier(t)) assertex(hasLinkCountedModifier(t->queryChildType())); if (hasOutOfLineModifier(t) || hasLinkCountedModifier(t)) return true; ITypeInfo * rowType = t->queryChildType(); if (hasOutOfLineModifier(rowType) || hasLinkCountedModifier(rowType)) throwUnexpected(); return false; } case type_row: throwUnexpected(); } return false; } bool hasLinkedRow(ITypeInfo * t) { switch (t->getTypeCode()) { case type_table: case type_groupedtable: case type_dictionary: return hasLinkedRow(t->queryChildType()); case type_row: return hasLinkCountedModifier(t); } return false; } ITypeInfo * setLinkCountedAttr(ITypeInfo * _type, bool setValue) { Linked<ITypeInfo> type = _type; switch (type->getTypeCode()) { case type_table: case type_groupedtable: case type_dictionary: { ITypeInfo * rowType = type->queryChildType(); Owned<ITypeInfo> newRowType = setLinkCountedAttr(rowType, setValue); if (rowType != newRowType) type.setown(replaceChildType(type, newRowType)); break; } case type_row: break; default: return type.getClear(); } if (hasLinkCountedModifier(type)) { if (setValue) return LINK(type); return removeAttribute(type, _linkCounted_Atom); } else { if (setValue) return makeAttributeModifier(LINK(type), getLinkCountedAttr()); return LINK(type); } } ITypeInfo * setStreamedAttr(ITypeInfo * _type, bool setValue) { Linked<ITypeInfo> type = _type; switch (type->getTypeCode()) { case type_groupedtable: { ITypeInfo * dsType = type->queryChildType(); Owned<ITypeInfo> newDsType = setStreamedAttr(dsType, setValue); if (dsType != newDsType) type.setown(replaceChildType(type, newDsType)); break; } case type_table: break; default: return type.getClear(); } if (hasStreamedModifier(type)) { if (setValue) return LINK(type); return removeAttribute(type, streamedAtom); } else { if (setValue) return makeAttributeModifier(LINK(type), getStreamedAttr()); return LINK(type); } } //--------------------------------------------------------------------------------- inline IHqlExpression * queryLikelihoodExpr(IHqlExpression * expr) { return expr->queryProperty(EPlikelihood); } IHqlExpression * evaluateLikelihood(IHqlExpression * expr) { LinkedHqlExpr likelihoodExpr; switch(expr->getOperator()) { case no_likely: if (expr->numChildren() > 1) likelihoodExpr.set(expr->queryChild(1)); else likelihoodExpr.set(queryConstantLikelihoodLikely()); break; case no_unlikely: likelihoodExpr.set(queryConstantLikelihoodUnlikely()); break; case no_alias: case no_nofold: likelihoodExpr.set(queryLikelihoodExpr(expr->queryChild(0))); break; case no_constant: if (expr->queryValue()->getBoolValue()) likelihoodExpr.set(queryConstantLikelihoodTrue()); else likelihoodExpr.set(queryConstantLikelihoodFalse()); break; case no_and: { double p1 = queryLikelihood(expr->queryChild(0)); if (isKnownLikelihood(p1)) { double p2 = queryLikelihood(expr->queryChild(1)); if (isKnownLikelihood(p2)) { likelihoodExpr.set(createConstant(createRealValue(p1*p2,8))); break; } } likelihoodExpr.set(queryConstantLikelihoodUnknown()); break; } case no_or: { double p1 = queryLikelihood(expr->queryChild(0)); if (isKnownLikelihood(p1)) { double p2 = queryLikelihood(expr->queryChild(1)); if (isKnownLikelihood(p2)) { likelihoodExpr.set(createConstant(createRealValue(p1+p2-p1*p2,8))); break; } } likelihoodExpr.set(queryConstantLikelihoodUnknown()); break; } case no_not: { double p1 = queryLikelihood(expr->queryChild(0)); if (isKnownLikelihood(p1)) { likelihoodExpr.set(createConstant(createRealValue(1.0-p1,8))); break; } likelihoodExpr.set(queryConstantLikelihoodUnknown()); break; } default: likelihoodExpr.set(queryConstantLikelihoodUnknown()); break; } meta.addProperty(expr, EPlikelihood, likelihoodExpr); return likelihoodExpr; } double queryLikelihood(IHqlExpression * expr) { IHqlExpression * likelihoodExpr = expr->queryProperty(EPlikelihood); return likelihoodExpr->queryValue()->getRealValue(); } double queryActivityLikelihood(IHqlExpression * expr) { assertex(expr->getOperator() == no_filter); double filterLikelihood = 1.0; ForEachChildFrom(idx, expr, 1) { IHqlExpression *child = expr->queryChild(idx); if (child->isAttribute()) continue; double likelihood = queryLikelihood(child); if (isKnownLikelihood(likelihood)) // Combine the likelihood of the 2 filter conditions // N.B. this only works if the filter probability are independent filterLikelihood *= likelihood; else { // One of the filter probability is unknown, so the overall probability is unknown setUnknownLikelihood(filterLikelihood); break; } } return filterLikelihood; } //--------------------------------------------------------------------------------------------------------------------- IInterface * CHqlRealExpression::queryExistingProperty(ExprPropKind propKind) const { //If this was used significantly in a multi threaded environment then reduce the work in the spinblock SpinBlock block(*propertyLock); CHqlDynamicProperty * cur = attributes; while (cur) { if (cur->kind == propKind) { IInterface * value = cur->value; if (value) return value; return static_cast<IHqlExpression *>(const_cast<CHqlRealExpression *>(this)); } cur = cur->next; } return NULL; } void CHqlRealExpression::addProperty(ExprPropKind kind, IInterface * value) { if (value == static_cast<IHqlExpression *>(this)) value = NULL; CHqlDynamicProperty * attr = new CHqlDynamicProperty(kind, value); SpinBlock block(*propertyLock); //theoretically we should test if the attribute has already been added by another thread, but in practice there is no //problem if the attribute is present twice. attr->next = attributes; attributes = attr; } //A specialised version of addProperty/queryExistingProperty. Uses sizeof(void*) all the time instead //of 3*sizeof(void *)+heap overhead when used. //Possibly saves a bit of time, but more useful as a proof of concept in case it was useful elsewhere.. void CHqlDataset::addProperty(ExprPropKind kind, IInterface * value) { if (kind == EPmeta) { SpinBlock block(*propertyLock); //ensure once meta is set it is never modified if (!metaProperty) metaProperty.set(value); } else CHqlRealExpression::addProperty(kind, value); } IInterface * CHqlDataset::queryExistingProperty(ExprPropKind kind) const { if (kind == EPmeta) { SpinBlock block(*propertyLock); return metaProperty; } return CHqlRealExpression::queryExistingProperty(kind); } //--------------------------------------------------------------------------------------------------------------------- IHqlExpression * CHqlRealExpression::queryProperty(ExprPropKind kind) { IInterface * match = queryExistingProperty(kind); if (match) return static_cast<IHqlExpression *>(match); switch (kind) { case EPrecordCount: return evalautePropRecordCount(this); case EPdiskserializedForm: return evaluatePropSerializedForm(this, kind, diskAtom); case EPinternalserializedForm: return evaluatePropSerializedForm(this, kind, internalAtom); case EPsize: return evalautePropSize(this); case EPaligned: return evalautePropAligned(this); case EPunadorned: return evalautePropUnadorned(this); case EPlocationIndependent: return evalautePropLocationIndependent(this); case EPlikelihood: return evaluateLikelihood(this); } return NULL; } CHqlMetaProperty * queryMetaProperty(IHqlExpression * expr) { IHqlExpression * body = expr->queryBody(); IInterface * match = CHqlExprMeta::queryExistingProperty(body, EPmeta); if (match) return static_cast<CHqlMetaProperty *>(match); CHqlMetaProperty * simple = querySimpleDatasetMeta(body); if (simple) { CHqlExprMeta::addProperty(body, EPmeta, simple); return simple; } Owned<CHqlMetaProperty> info = new CHqlMetaProperty; calculateDatasetMeta(info->meta, body); CHqlExprMeta::addProperty(body, EPmeta, info); return info; }
30.135102
194
0.610645
[ "model", "transform" ]
cb325e2b275328bb3c4c2f0eb0330a9c72e25dd8
6,875
cpp
C++
DevTools/HackStudio/Debugger.cpp
magicmarvman/serenity
f8489b4a697f441cbf53e5ac7d29e0716f238174
[ "BSD-2-Clause" ]
2
2020-05-31T16:21:19.000Z
2021-06-09T23:40:52.000Z
DevTools/HackStudio/Debugger.cpp
magicmarvman/serenity
f8489b4a697f441cbf53e5ac7d29e0716f238174
[ "BSD-2-Clause" ]
1
2020-10-04T22:05:02.000Z
2020-10-04T22:05:02.000Z
DevTools/HackStudio/Debugger.cpp
magicmarvman/serenity
f8489b4a697f441cbf53e5ac7d29e0716f238174
[ "BSD-2-Clause" ]
1
2021-06-25T06:30:52.000Z
2021-06-25T06:30:52.000Z
/* * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 "Debugger.h" static Debugger* s_the; Debugger& Debugger::the() { ASSERT(s_the); return *s_the; } void Debugger::initialize( Function<HasControlPassedToUser(const PtraceRegisters&)> on_stop_callback, Function<void()> on_continue_callback, Function<void()> on_exit_callback) { s_the = new Debugger(move(on_stop_callback), move(on_continue_callback), move(on_exit_callback)); } bool Debugger::is_initialized() { return s_the; } Debugger::Debugger( Function<HasControlPassedToUser(const PtraceRegisters&)> on_stop_callback, Function<void()> on_continue_callback, Function<void()> on_exit_callback) : m_on_stopped_callback(move(on_stop_callback)) , m_on_continue_callback(move(on_continue_callback)) , m_on_exit_callback(move(on_exit_callback)) { pthread_mutex_init(&m_continue_mutex, nullptr); pthread_cond_init(&m_continue_cond, nullptr); } void Debugger::on_breakpoint_change(const String& file, size_t line, BreakpointChange change_type) { auto position = create_source_position(file, line); if (change_type == BreakpointChange::Added) { Debugger::the().m_breakpoints.append(position); } else { Debugger::the().m_breakpoints.remove_all_matching([&](DebugInfo::SourcePosition val) { return val == position; }); } auto session = Debugger::the().session(); if (!session) return; auto address = session->debug_info().get_instruction_from_source(position.file_path, position.line_number); if (!address.has_value()) return; if (change_type == BreakpointChange::Added) { bool success = session->insert_breakpoint(reinterpret_cast<void*>(address.value())); ASSERT(success); } else { bool success = session->remove_breakpoint(reinterpret_cast<void*>(address.value())); ASSERT(success); } } DebugInfo::SourcePosition Debugger::create_source_position(const String& file, size_t line) { return { String::format("./%s", file.characters()), line + 1 }; } int Debugger::start_static() { Debugger::the().start(); return 0; } void Debugger::start() { m_debug_session = DebugSession::exec_and_attach(m_executable_path); ASSERT(!!m_debug_session); for (const auto& breakpoint : m_breakpoints) { dbg() << "insertig breakpoint at: " << breakpoint.file_path << ":" << breakpoint.line_number; auto address = m_debug_session->debug_info().get_instruction_from_source(breakpoint.file_path, breakpoint.line_number); if (address.has_value()) { bool success = m_debug_session->insert_breakpoint(reinterpret_cast<void*>(address.value())); ASSERT(success); } else { dbg() << "couldn't insert breakpoint"; } } debugger_loop(); } int Debugger::debugger_loop() { bool in_single_step_mode = false; Vector<void*> temporary_breakpoints; m_debug_session->run([&](DebugSession::DebugBreakReason reason, Optional<PtraceRegisters> optional_regs) { if (reason == DebugSession::DebugBreakReason::Exited) { dbg() << "Program exited"; m_on_exit_callback(); return DebugSession::DebugDecision::Detach; } ASSERT(optional_regs.has_value()); const PtraceRegisters& regs = optional_regs.value(); if (in_single_step_mode) { for (auto address : temporary_breakpoints) { m_debug_session->remove_breakpoint(address); } temporary_breakpoints.clear(); in_single_step_mode = false; } auto control_passed_to_user = m_on_stopped_callback(regs); if (control_passed_to_user == HasControlPassedToUser::Yes) { pthread_mutex_lock(&m_continue_mutex); pthread_cond_wait(&m_continue_cond, &m_continue_mutex); pthread_mutex_unlock(&m_continue_mutex); m_on_continue_callback(); } else { m_continue_type = ContinueType::Continue; } if (m_continue_type == ContinueType::Continue) { return DebugSession::DebugDecision::Continue; } if (m_continue_type == ContinueType::SourceSingleStep) { // A possible method for source level single stepping is to single step // in assembly level, until the current instruction's source position has changed. // However, since we do not currently generate debug symbols for library code, // we may have to single-step over lots of library code instructions until we get back to our code, // which is very slow. // So the current method is to insert a temporary breakpoint at every known statement in our source code, // continue execution, and remove the temporary breakpoints once we hit the first breakpoint. m_debug_session->debug_info().for_each_source_position([&](DebugInfo::SourcePosition position) { auto address = (void*)position.address_of_first_statement; if ((u32)address != regs.eip && !m_debug_session->breakpoint_exists(address)) { m_debug_session->insert_breakpoint(address); temporary_breakpoints.append(address); } }); in_single_step_mode = true; return DebugSession::DebugDecision::Continue; } ASSERT_NOT_REACHED(); }); m_debug_session.clear(); return 0; }
38.194444
127
0.685527
[ "vector" ]
cb379a24cc0ff8df37332b6972a17553d6f25d1e
11,423
cpp
C++
native/cocos/renderer/pipeline/deferred/PostProcessStage.cpp
SteveLau-GameDeveloper/engine
159e5acd0f5115a878d59ed59f924ce7627a5466
[ "Apache-2.0", "MIT" ]
null
null
null
native/cocos/renderer/pipeline/deferred/PostProcessStage.cpp
SteveLau-GameDeveloper/engine
159e5acd0f5115a878d59ed59f924ce7627a5466
[ "Apache-2.0", "MIT" ]
null
null
null
native/cocos/renderer/pipeline/deferred/PostProcessStage.cpp
SteveLau-GameDeveloper/engine
159e5acd0f5115a878d59ed59f924ce7627a5466
[ "Apache-2.0", "MIT" ]
null
null
null
/**************************************************************************** Copyright (c) 2020-2021 Huawei Technologies Co., Ltd. http://www.cocos.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated engine source code (the "Software"), a limited, worldwide, royalty-free, non-assignable, revocable and non-exclusive license to use Cocos Creator solely to develop games on your target platforms. You shall not use Cocos Creator software for developing other software or tools that's used for developing games. You are not granted to publish, distribute, sublicense, and/or sell copies of Cocos Creator. The software or tools in this License Agreement are licensed, not sold. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. 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 "PostProcessStage.h" #include "frame-graph/DevicePass.h" #include "frame-graph/PassNodeBuilder.h" #include "frame-graph/Resource.h" #include "gfx-base/GFXDevice.h" #include "pipeline/Define.h" #include "pipeline/UIPhase.h" #include "pipeline/helper/Utils.h" #include "profiler/Profiler.h" #include "renderer/pipeline/GlobalDescriptorSetManager.h" #include "renderer/pipeline/PipelineStateManager.h" #include "renderer/pipeline/PipelineUBO.h" #include "renderer/pipeline/RenderPipeline.h" #include "renderer/pipeline/RenderQueue.h" #include "renderer/pipeline/UIPhase.h" #include "renderer/pipeline/deferred/DeferredPipelineSceneData.h" #include "scene/Camera.h" #include "scene/Pass.h" #include "scene/RenderWindow.h" #include "scene/SubModel.h" namespace cc { namespace pipeline { namespace { const ccstd::string STAGE_NAME = "PostProcessStage"; } RenderStageInfo PostProcessStage::initInfo = { STAGE_NAME, static_cast<uint>(DeferredStagePriority::POSTPROCESS), 0, {{true, RenderQueueSortMode::BACK_TO_FRONT, {"default"}}}, }; const RenderStageInfo &PostProcessStage::getInitializeInfo() { return PostProcessStage::initInfo; } PostProcessStage::PostProcessStage() { _uiPhase = CC_NEW(UIPhase); } bool PostProcessStage::initialize(const RenderStageInfo &info) { RenderStage::initialize(info); _renderQueueDescriptors = info.renderQueues; return true; } void PostProcessStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { RenderStage::activate(pipeline, flow); _uiPhase->activate(pipeline); _phaseID = getPhaseID("default"); for (const auto &descriptor : _renderQueueDescriptors) { uint phase = 0; for (const auto &stage : descriptor.stages) { phase |= getPhaseID(stage); } std::function<int(const RenderPass &, const RenderPass &)> sortFunc = opaqueCompareFn; switch (descriptor.sortMode) { case RenderQueueSortMode::BACK_TO_FRONT: sortFunc = transparentCompareFn; break; case RenderQueueSortMode::FRONT_TO_BACK: sortFunc = opaqueCompareFn; default: break; } RenderQueueCreateInfo info = {descriptor.isTransparent, phase, sortFunc}; _renderQueues.emplace_back(CC_NEW(RenderQueue(_pipeline, std::move(info)))); } } void PostProcessStage::destroy() { CC_SAFE_DELETE(_uiPhase); } void PostProcessStage::render(scene::Camera *camera) { CC_PROFILE(PostProcessStageRender); static framegraph::StringHandle fgStrHandlePostProcessOutTexture = framegraph::FrameGraph::stringToHandle("postProcessOutputTexture"); struct RenderData { framegraph::TextureHandle outColorTex; // read from lighting output framegraph::TextureHandle backBuffer; // write to back buffer framegraph::TextureHandle depth; }; if (hasFlag(static_cast<gfx::ClearFlags>(camera->getClearFlag()), gfx::ClearFlagBit::COLOR)) { _clearColors[0].x = camera->getClearColor().x; _clearColors[0].y = camera->getClearColor().y; _clearColors[0].z = camera->getClearColor().z; } _clearColors[0].w = camera->getClearColor().w; _renderArea = RenderPipeline::getRenderArea(camera); _inputAssembler = _pipeline->getIAByRenderArea(_renderArea); auto *pipeline = _pipeline; float shadingScale{_pipeline->getPipelineSceneData()->getShadingScale()}; auto postSetup = [&](framegraph::PassNodeBuilder &builder, RenderData &data) { if (pipeline->isBloomEnabled()) { data.outColorTex = framegraph::TextureHandle(builder.readFromBlackboard(RenderPipeline::fgStrHandleBloomOutTexture)); } else { data.outColorTex = framegraph::TextureHandle(builder.readFromBlackboard(RenderPipeline::fgStrHandleOutColorTexture)); } if (!data.outColorTex.isValid()) { framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = gfx::Format::RGBA16F; colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; colorTexInfo.width = static_cast<uint>(static_cast<float>(pipeline->getWidth()) * shadingScale); colorTexInfo.height = static_cast<uint>(static_cast<float>(pipeline->getHeight()) * shadingScale); data.outColorTex = builder.create(RenderPipeline::fgStrHandleOutColorTexture, colorTexInfo); } data.outColorTex = builder.read(data.outColorTex); builder.writeToBlackboard(RenderPipeline::fgStrHandleOutColorTexture, data.outColorTex); framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; colorAttachmentInfo.clearColor = _clearColors[0]; colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; auto clearFlags = static_cast<gfx::ClearFlagBit>(camera->getClearFlag()); if (!hasFlag(clearFlags, gfx::ClearFlagBit::COLOR)) { if (hasFlag(clearFlags, static_cast<gfx::ClearFlagBit>(skyboxFlag))) { colorAttachmentInfo.loadOp = gfx::LoadOp::DISCARD; } else { colorAttachmentInfo.loadOp = gfx::LoadOp::LOAD; } } colorAttachmentInfo.beginAccesses = colorAttachmentInfo.endAccesses = camera->getWindow()->getSwapchain() ? gfx::AccessFlagBit::COLOR_ATTACHMENT_WRITE : gfx::AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE; gfx::TextureInfo textureInfo = { gfx::TextureType::TEX2D, gfx::TextureUsageBit::COLOR_ATTACHMENT, gfx::Format::RGBA8, static_cast<uint>(static_cast<float>(camera->getWindow()->getWidth()) * shadingScale), static_cast<uint>(static_cast<float>(camera->getWindow()->getHeight()) * shadingScale), }; if (shadingScale != 1.F) { textureInfo.usage |= gfx::TextureUsageBit::TRANSFER_SRC; } data.backBuffer = builder.create(fgStrHandlePostProcessOutTexture, textureInfo); data.backBuffer = builder.write(data.backBuffer, colorAttachmentInfo); builder.writeToBlackboard(fgStrHandlePostProcessOutTexture, data.backBuffer); // depth framegraph::RenderTargetAttachment::Descriptor depthAttachmentInfo; depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; depthAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; depthAttachmentInfo.beginAccesses = depthAttachmentInfo.endAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE; data.depth = framegraph::TextureHandle(builder.readFromBlackboard(RenderPipeline::fgStrHandleOutDepthTexture)); if (!data.depth.isValid()) { gfx::TextureInfo depthTexInfo{ gfx::TextureType::TEX2D, gfx::TextureUsageBit::DEPTH_STENCIL_ATTACHMENT, gfx::Format::DEPTH_STENCIL, static_cast<uint>(static_cast<float>(pipeline->getWidth()) * shadingScale), static_cast<uint>(static_cast<float>(pipeline->getHeight()) * shadingScale), }; data.depth = builder.create(RenderPipeline::fgStrHandleOutDepthTexture, depthTexInfo); } data.depth = builder.write(data.depth, depthAttachmentInfo); builder.writeToBlackboard(RenderPipeline::fgStrHandleOutDepthTexture, data.depth); builder.setViewport(pipeline->getViewport(camera), pipeline->getScissor(camera)); }; auto postExec = [this, camera](RenderData const &data, const framegraph::DevicePassResourceTable &table) { auto * pipeline = _pipeline; gfx::RenderPass *renderPass = table.getRenderPass(); auto * cmdBuff = pipeline->getCommandBuffers()[0]; const ccstd::array<uint, 1> globalOffsets = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; cmdBuff->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), utils::toUint(globalOffsets.size()), globalOffsets.data()); if (!pipeline->getPipelineSceneData()->getRenderObjects().empty()) { // post process auto *const sceneData = static_cast<DeferredPipelineSceneData *>(pipeline->getPipelineSceneData()); scene::Pass *pv = sceneData->getPostPass(); gfx::Shader *sd = sceneData->getPostPassShader(); float shadingScale{sceneData->getShadingScale()}; // get pso and draw quad gfx::PipelineState * pso = PipelineStateManager::getOrCreatePipelineState(pv, sd, _inputAssembler, renderPass); pipeline::GlobalDSManager *globalDS = pipeline->getGlobalDSManager(); gfx::Sampler * sampler = shadingScale < 1.F ? globalDS->getPointSampler() : globalDS->getLinearSampler(); pv->getDescriptorSet()->bindTexture(0, table.getRead(data.outColorTex)); pv->getDescriptorSet()->bindSampler(0, sampler); pv->getDescriptorSet()->update(); cmdBuff->bindPipelineState(pso); cmdBuff->bindDescriptorSet(materialSet, pv->getDescriptorSet()); cmdBuff->bindInputAssembler(_inputAssembler); cmdBuff->draw(_inputAssembler); } _uiPhase->render(camera, renderPass); renderProfiler(renderPass, cmdBuff, pipeline->getProfiler(), camera); renderDebugRenderer(renderPass, cmdBuff, pipeline->getPipelineSceneData(), camera); }; // add pass pipeline->getFrameGraph().addPass<RenderData>(static_cast<uint>(CommonInsertPoint::DIP_POSTPROCESS), RenderPipeline::fgStrHandlePostprocessPass, postSetup, postExec); pipeline->getFrameGraph().presentFromBlackboard(fgStrHandlePostProcessOutTexture, camera->getWindow()->getFramebuffer()->getColorTextures()[0], shadingScale == 1.F); } } // namespace pipeline } // namespace cc
47.595833
170
0.686335
[ "render" ]
cb3b080a8cb6659f523912fd75fd27bf03df9f09
67,596
cpp
C++
core/TestcaseRunner/TestExecutorGDB.cpp
joyride9999/fluffi
028f16ee23d0232a9f53ca70aece116526655ea9
[ "MIT" ]
null
null
null
core/TestcaseRunner/TestExecutorGDB.cpp
joyride9999/fluffi
028f16ee23d0232a9f53ca70aece116526655ea9
[ "MIT" ]
null
null
null
core/TestcaseRunner/TestExecutorGDB.cpp
joyride9999/fluffi
028f16ee23d0232a9f53ca70aece116526655ea9
[ "MIT" ]
null
null
null
/* Copyright 2017-2019 Siemens AG 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. Author(s): Thomas Riedmaier, Abian Blome, Roman Bendt */ #include "stdafx.h" #include "TestExecutorGDB.h" #include "FluffiTestcaseID.h" #include "DebugExecutionOutput.h" #include "Util.h" #include "SharedMemIPC.h" #include "GarbageCollectorWorker.h" #include "GDBBreakpoint.h" TestExecutorGDB::TestExecutorGDB(const std::string targetCMDline, int hangTimeoutMS, const std::set<Module> modulesToCover, const std::string testcaseDir, ExternalProcess::CHILD_OUTPUT_TYPE child_output_mode, GarbageCollectorWorker* garbageCollectorWorker, const std::string feederCmdline, const std::string starterCmdline, int initializationTimeoutMS, int forceRestartAfterXTCs, std::set<FluffiBasicBlock> blocksToCover, uint32_t bpInstr, int bpInstrBytes) : FluffiTestExecutor(targetCMDline, hangTimeoutMS, modulesToCover, testcaseDir, child_output_mode, "", garbageCollectorWorker), //As we rely on starters, the Environment of the target process cannot be influenced here m_feederCmdline(feederCmdline), m_starterCmdline(starterCmdline), m_initializationTimeoutMS(initializationTimeoutMS), m_forceRestartAfterXTCs(forceRestartAfterXTCs), m_executionsSinceLastRestart(0), m_sharedMemIPC_toFeeder(nullptr), m_feederProcess(std::make_shared<ExternalProcess>("", ExternalProcess::CHILD_OUTPUT_TYPE::SUPPRESS)), m_gDBThreadCommunication{ std::make_shared<GDBThreadCommunication>() }, m_blocksToCover(blocksToCover), m_target_and_feeder_okay(false), m_bpInstr(bpInstr), m_bpInstrBytes(bpInstrBytes), #if defined(_WIN32) || defined(_WIN64) m_SharedMemIPCInterruptEvent(NULL) #else m_SharedMemIPCInterruptFD{ -1, -1 } #endif { #if defined(_WIN32) || defined(_WIN64) LOG(DEBUG) << "Setting the SharedMemIPCInterruptEvent to stop the current execution"; m_SharedMemIPCInterruptEvent = CreateEvent(NULL, false, false, NULL); if (m_SharedMemIPCInterruptEvent == NULL) { LOG(ERROR) << "failed to create the SharedMemIPCInterruptEvent"; } #else LOG(DEBUG) << "Creating the SharedMemIPCInterruptFD to stop the current execution"; if (pipe(m_SharedMemIPCInterruptFD) == -1) { LOG(ERROR) << "failed to create the SharedMemIPCInterruptFD"; } #endif } TestExecutorGDB::~TestExecutorGDB() { m_gDBThreadCommunication->set_gdbThreadShouldTerminate(); //Stop the gdb debugging thread #if defined(_WIN32) || defined(_WIN64) if (m_sharedMemIPC_toFeeder != nullptr) { delete m_sharedMemIPC_toFeeder; m_sharedMemIPC_toFeeder = nullptr; } if (m_SharedMemIPCInterruptEvent != NULL) { CloseHandle(m_SharedMemIPCInterruptEvent); m_SharedMemIPCInterruptEvent = NULL; } #else if (m_sharedMemIPC_toFeeder != nullptr) { delete m_sharedMemIPC_toFeeder; m_sharedMemIPC_toFeeder = nullptr; } //Try closing the interrupt pipe close(m_SharedMemIPCInterruptFD[0]); m_SharedMemIPCInterruptFD[0] = -1; close(m_SharedMemIPCInterruptFD[1]); m_SharedMemIPCInterruptFD[1] = -1; #endif waitForDebuggerToTerminate(); // Avoid ugly memleaks } std::shared_ptr<DebugExecutionOutput> TestExecutorGDB::execute(const FluffiTestcaseID testcaseId, bool forceFullCoverage) { LOG(DEBUG) << "Executing: " << testcaseId; if (m_forceRestartAfterXTCs > 0 && m_executionsSinceLastRestart++ > m_forceRestartAfterXTCs) { LOG(INFO) << "Forcing a restart of the target as we reached the defined maximum of TCs without restart"; m_target_and_feeder_okay = false; } bool firstRun = false; if (!m_target_and_feeder_okay) { m_target_and_feeder_okay = attemptStartTargetAndFeeder(); if (!m_target_and_feeder_okay) { //Either target or feeder could not be started! std::shared_ptr<DebugExecutionOutput> exResult = std::make_shared<DebugExecutionOutput>(); exResult->m_hasFullCoverage = false; exResult->m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; exResult->m_terminationDescription = "Either target or feeder could not be started!"; return exResult; } firstRun = true; } std::shared_ptr<DebugExecutionOutput> exOutput_FROM_FEEDER = std::make_shared<DebugExecutionOutput>(); exOutput_FROM_FEEDER->m_hasFullCoverage = forceFullCoverage | firstRun; m_target_and_feeder_okay = runSingleTestcase(testcaseId, exOutput_FROM_FEEDER, exOutput_FROM_FEEDER->m_hasFullCoverage ? CoverageMode::FULL : CoverageMode::PARTIAL); //m_target_and_feeder_okay will be set to false always but on clean exit. This will lead to a restart of fuzzer and target on next testcase by attemptStartTargetAndFeeder switch (m_gDBThreadCommunication->m_exOutput.m_terminationType) { case DebugExecutionOutput::CLEAN: //Check if the target still runs. Clean may mean "Target still running - no problem so far" and "Target terminated without an Exception" if (m_gDBThreadCommunication->get_exitStatus() == -1) { //Case "Target still running - no problem so far" (exit status was not yet set to a meaningfull value) switch (exOutput_FROM_FEEDER->m_terminationType) { case DebugExecutionOutput::CLEAN: LOG(DEBUG) << "Testcase execution successfull! Reporting coverage..."; return exOutput_FROM_FEEDER; case DebugExecutionOutput::TIMEOUT: LOG(DEBUG) << "Testcase execution yielded a timeout"; m_target_and_feeder_okay = false; return exOutput_FROM_FEEDER; case DebugExecutionOutput::EXCEPTION_OTHER: LOG(DEBUG) << "Feeder claims that the target encountered an exception."; m_target_and_feeder_okay = false; return exOutput_FROM_FEEDER; case DebugExecutionOutput::EXCEPTION_ACCESSVIOLATION: case DebugExecutionOutput::ERR: default: LOG(WARNING) << "Testcase execution yielded an internal error (1): " << exOutput_FROM_FEEDER->m_terminationDescription; m_target_and_feeder_okay = false; return exOutput_FROM_FEEDER; } LOG(ERROR) << "The testcase exectution did not trigger a case in the switch statement (1)"; google::protobuf::ShutdownProtobufLibrary(); _exit(EXIT_FAILURE); //make compiler happy; } //Case "Target terminated without an Exception" - treat this like an Exception /* fall through */ case DebugExecutionOutput::EXCEPTION_OTHER: case DebugExecutionOutput::EXCEPTION_ACCESSVIOLATION: LOG(DEBUG) << "Testcase execution yielded an exception - or the target terminated \"cleanly\" by itself. Let's try to reproduce this without breakpoints."; { //Do a second run without setting breakpoints DebugExecutionOutput::PROCESS_TERMINATION_TYPE originalCrashType = m_gDBThreadCommunication->m_exOutput.m_terminationType; m_target_and_feeder_okay = attemptStartTargetAndFeeder(); if (!m_target_and_feeder_okay) { //Either target or feeder could not be started! std::shared_ptr<DebugExecutionOutput> exResult = std::make_shared<DebugExecutionOutput>(); exResult->m_hasFullCoverage = false; exResult->m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; exResult->m_terminationDescription = "Either target or feeder coould not be started to reproduce the exception!"; return exResult; } std::shared_ptr<DebugExecutionOutput> second_exOutput_FROM_FEEDER = std::make_shared<DebugExecutionOutput>(); second_exOutput_FROM_FEEDER->m_hasFullCoverage = false; runSingleTestcase(testcaseId, second_exOutput_FROM_FEEDER, CoverageMode::NONE); //If the feeder timed out - i.e. there was no response from target - it crashed and we need to wait for the debugger thread if (second_exOutput_FROM_FEEDER->m_terminationType != DebugExecutionOutput::CLEAN) { waitForDebuggerToTerminate(); } //Check if the target still runs. Clean may mean "Target still running - no problem so far" and "Target terminated without an Exception" if (m_gDBThreadCommunication->m_exOutput.m_terminationType == DebugExecutionOutput::CLEAN && m_gDBThreadCommunication->get_exitStatus() != -1) { //Case "Target terminated without an Exception" std::shared_ptr<DebugExecutionOutput> exResult = std::make_shared<DebugExecutionOutput>(); exResult->m_terminationType = originalCrashType; exResult->m_terminationDescription = "The request reproducibly causes the target to terminate!"; exResult->m_firstCrash = "TARGET_TERMINATED"; exResult->m_lastCrash = "TARGET_TERMINATED"; m_target_and_feeder_okay = false; //force reinitialization (dyn rio needs to be reactivated) return exResult; } if (m_gDBThreadCommunication->m_exOutput.m_terminationType == DebugExecutionOutput::CLEAN || m_gDBThreadCommunication->m_exOutput.m_terminationType == DebugExecutionOutput::TIMEOUT || m_gDBThreadCommunication->m_exOutput.m_terminationType == DebugExecutionOutput::ERR) { std::shared_ptr<DebugExecutionOutput> exResult = std::make_shared<DebugExecutionOutput>(); exResult->m_hasFullCoverage = false; exResult->m_terminationType = originalCrashType; exResult->m_terminationDescription = "The found exception could not be reproduced!"; exResult->m_firstCrash = "NOT_REPRODUCIBLE"; exResult->m_lastCrash = "NOT_REPRODUCIBLE"; m_target_and_feeder_okay = false; //force reinitialization return exResult; } } m_target_and_feeder_okay = false; //force reinitialization return std::make_shared<DebugExecutionOutput>(m_gDBThreadCommunication->m_exOutput); case DebugExecutionOutput::ERR: case DebugExecutionOutput::TIMEOUT: default: LOG(WARNING) << "Testcase execution yielded an internal error (2): " << m_gDBThreadCommunication->m_exOutput.m_terminationDescription; m_target_and_feeder_okay = false; return std::make_shared<DebugExecutionOutput>(m_gDBThreadCommunication->m_exOutput); } LOG(ERROR) << "The testcase exectution did not trigger a case in the switch statement (2)"; google::protobuf::ShutdownProtobufLibrary(); _exit(EXIT_FAILURE); //make compiler happy; } bool TestExecutorGDB::isSetupFunctionable() { //1)Check if targetCMDline is a functional GDB { std::chrono::time_point<std::chrono::steady_clock> routineEntryTimeStamp = std::chrono::steady_clock::now(); std::chrono::time_point<std::chrono::steady_clock> latestRoutineExitTimeStamp = routineEntryTimeStamp + std::chrono::milliseconds(500); ExternalProcess ep(m_targetCMDline + " --version", ExternalProcess::CHILD_OUTPUT_TYPE::SPECIAL); bool success = ep.initProcess(); if (!success) { LOG(ERROR) << "targetCMDline " << m_targetCMDline << "could not be initialized"; return false; } std::istream* is = ep.getStdOutIstream(); success = ep.run(); if (!success) { LOG(ERROR) << "targetCMDline " << m_targetCMDline << "could not be run"; return false; } char identifier[8]; identifier[7] = 0; std::streamsize charsRead = 0; while (charsRead < 7 && std::chrono::steady_clock::now() < latestRoutineExitTimeStamp) { std::streamsize charsToRead = 7 - charsRead; if (is->peek() != EOF) { charsRead += is->readsome(&identifier[charsRead], charsToRead); } } if (charsRead < 7 || std::string(identifier) != "GNU gdb") { LOG(ERROR) << "targetCMDline seems not to point to a valid GDB"; return false; } } //2) check if the feeder executable file exists { #if defined(_WIN32) || defined(_WIN64) std::wstring wfeedercmdline = std::wstring(m_feederCmdline.begin(), m_feederCmdline.end()); int numOfBlocks; LPWSTR* szArglist = CommandLineToArgvW(wfeedercmdline.c_str(), &numOfBlocks); //for some reasons this does not exist for Ascii :( if (NULL == szArglist || numOfBlocks < 1) { LOG(ERROR) << "feeder command line invalid"; return false; } if (!std::experimental::filesystem::exists(szArglist[0])) { LocalFree(szArglist); LOG(ERROR) << "feeder executable file does not exist"; return false; } LocalFree(szArglist); #else std::string tmp = m_feederCmdline; std::replace(tmp.begin(), tmp.end(), '<', '_'); // replace all '<' to '_' (handle <RANDOM_SHAREDMEM> et al) std::replace(tmp.begin(), tmp.end(), '>', '_'); // replace all '>' to '_' (handle <RANDOM_SHAREDMEM> et al) char** argv = ExternalProcess::split_commandline(tmp); if (argv == NULL || argv[0] == NULL) { LOG(ERROR) << "Splitting feeder command line \"" << tmp << "\" failed."; if (argv != NULL) { free(argv); } return false; } bool setupFunctionable = std::experimental::filesystem::exists(argv[0]); //free argv int i = 0; while (argv[i] != NULL) { free(argv[i]); i++; } free(argv); if (!setupFunctionable) { LOG(WARNING) << "feeder executable not found"; return false; } #endif } //3) check if the starter executable file exists #if defined(_WIN32) || defined(_WIN64) std::wstring wstartercmdline = std::wstring(m_starterCmdline.begin(), m_starterCmdline.end()); int numOfBlocks; LPWSTR* szArglist = CommandLineToArgvW(wstartercmdline.c_str(), &numOfBlocks); //for some reasons this does not exist for Ascii :( if (NULL == szArglist || numOfBlocks < 1) { LOG(ERROR) << "starter command line invalid"; return false; } if (!std::experimental::filesystem::exists(szArglist[0])) { LocalFree(szArglist); LOG(ERROR) << "starter executable file does not exist"; return false; } LocalFree(szArglist); #else std::string tmp = m_starterCmdline; std::replace(tmp.begin(), tmp.end(), '<', '_'); // replace all '<' to '_' (handle <RANDOM_SHAREDMEM> et al) std::replace(tmp.begin(), tmp.end(), '>', '_'); // replace all '>' to '_' (handle <RANDOM_SHAREDMEM> et al) char** argv = ExternalProcess::split_commandline(tmp); if (argv == NULL || argv[0] == NULL) { LOG(ERROR) << "Splitting starter command line \"" << tmp << "\" failed."; if (argv != NULL) { free(argv); } return false; } bool setupFunctionable = std::experimental::filesystem::exists(argv[0]); //free argv int i = 0; while (argv[i] != NULL) { free(argv[i]); i++; } free(argv); if (!setupFunctionable) { LOG(WARNING) << "starter executable not found"; return false; } #endif //4) check if the testcase directory exists if (!std::experimental::filesystem::exists(m_testcaseDir)) { LOG(ERROR) << "testcase directory does not exist"; return false; } //5) check if we have at least one block to cover if (m_blocksToCover.size() == 0) { LOG(ERROR) << "There are no blocks to cover!"; return false; } //6) check if we have a moduleid for all blocks to cover have for (const FluffiBasicBlock& fluffiBasicBlockit : m_blocksToCover) { bool isThereAModule = false; for (const Module& modIt : m_modulesToCover) { if (fluffiBasicBlockit.m_moduleID == modIt.m_moduleid) { isThereAModule = true; break; } } if (!isThereAModule) { LOG(ERROR) << "There are blocks we should cover for which we do not have a module!"; return false; } } //7) check if m_bpInstr and m_bpInstrBytes are set and valid switch (m_bpInstrBytes) { case 1: if (m_bpInstr > 255) { LOG(ERROR) << "m_bpInstr cannot be represented in 1 byte, as it is " << m_bpInstr; return false; } break; case 2: if (m_bpInstr > 65535) { LOG(ERROR) << "m_bpInstr cannot be represented in 2 bytes, as it is " << m_bpInstr; return false; } break; case 4: //Currently, m_bpInstr is an uint32, which can always be represented as 4 bytes break; default: LOG(ERROR) << "bpInstrBytes must be 1,2, or 4"; return false; } return true; } bool TestExecutorGDB::waitUntilTargetIsBeingDebugged(std::shared_ptr<GDBThreadCommunication> gDBThreadCommunication, int timeoutMS) { std::chrono::time_point<std::chrono::steady_clock> routineEntryTimeStamp = std::chrono::steady_clock::now(); std::chrono::time_point<std::chrono::steady_clock> latestRoutineExitTimeStamp = routineEntryTimeStamp + std::chrono::milliseconds(timeoutMS); gDBThreadCommunication->waitForDebuggingReadyTimeout(latestRoutineExitTimeStamp - std::chrono::steady_clock::now()); return gDBThreadCommunication->get_debuggingReady(); } bool TestExecutorGDB::waitUntilCoverageState(std::shared_ptr<GDBThreadCommunication> gDBThreadCommunication, GDBThreadCommunication::COVERAGE_STATE desiredState, int timeoutMS) { std::chrono::time_point<std::chrono::steady_clock> routineEntryTimeStamp = std::chrono::steady_clock::now(); std::chrono::time_point<std::chrono::steady_clock> latestRoutineExitTimeStamp = routineEntryTimeStamp + std::chrono::milliseconds(timeoutMS); while (!gDBThreadCommunication->get_gdbThreadShouldTerminate() && gDBThreadCommunication->get_coverageState() != desiredState && std::chrono::steady_clock::now() < latestRoutineExitTimeStamp) { gDBThreadCommunication->waitForTerminateMessageOrCovStateChangeTimeout(latestRoutineExitTimeStamp - std::chrono::steady_clock::now(), &desiredState, 1); } return gDBThreadCommunication->get_coverageState() == desiredState; } bool TestExecutorGDB::attemptStartTargetAndFeeder() { std::chrono::time_point<std::chrono::steady_clock> routineEntryTimeStamp = std::chrono::steady_clock::now(); std::chrono::time_point<std::chrono::steady_clock> latestRoutineExitTimeStamp = routineEntryTimeStamp + std::chrono::milliseconds(m_initializationTimeoutMS); LOG(DEBUG) << "Attempting to start target and feeder"; /*Design decission: Target is ALWAYS started before feeder. - feeder can be told the target's PID - from a feeder's perspective the target always looks like an already running server (no matter what it actually is) */ m_executionsSinceLastRestart = 0; //Target part ------------------------------------------------- m_gDBThreadCommunication->set_gdbThreadShouldTerminate(); //Stop the gdb debugging thread //Start the target by starting the starter (starter is a class member, so the destructor is called when a new starter is created or on class destruct) std::string gdbInitFile = m_testcaseDir + Util::pathSeperator + "GDBInit_" + Util::newGUID(); std::shared_ptr<ExternalProcess> starterProcess = std::make_shared<ExternalProcess>(m_starterCmdline + " \"" + gdbInitFile + "\"", m_child_output_mode); #if defined(_WIN32) || defined(_WIN64) starterProcess->setAllowBreakAway(); //children of the starter process should run outside of the starter job. #else //No need to set allow break away as on Linux we trace only the direct child anyway. It is free to create new processes as it likes #endif if (starterProcess->initProcess()) { if (!starterProcess->runAndWaitForCompletion(static_cast<unsigned long>(std::chrono::duration_cast<std::chrono::milliseconds>(latestRoutineExitTimeStamp - std::chrono::steady_clock::now()).count()))) { LOG(ERROR) << "The starter process was not able to start the target in time"; m_garbageCollectorWorker->markFileForDelete(gdbInitFile); return false; } } else { LOG(ERROR) << "Could not initialize starter process"; m_garbageCollectorWorker->markFileForDelete(gdbInitFile); return false; } m_gDBThreadCommunication = std::make_shared<GDBThreadCommunication>(); #if defined(_WIN32) || defined(_WIN64) std::thread debuggerThread(&TestExecutorGDB::debuggerThreadMain, m_targetCMDline, m_gDBThreadCommunication, m_child_output_mode, gdbInitFile, m_SharedMemIPCInterruptEvent, m_modulesToCover, m_blocksToCover, m_bpInstr, m_bpInstrBytes); #else std::thread debuggerThread(&TestExecutorGDB::debuggerThreadMain, m_targetCMDline, m_gDBThreadCommunication, m_child_output_mode, gdbInitFile, m_SharedMemIPCInterruptFD[1], m_modulesToCover, m_blocksToCover, m_bpInstr, m_bpInstrBytes); #endif debuggerThread.detach(); //we do not want to join this. It will terminate as we set m_gDBThreadCommunication->m_gdbThreadShouldTerminate to true LOG(DEBUG) << "started debugger thread"; //We need to wait for the target's initialization ("ready to debug"). if (!waitUntilTargetIsBeingDebugged(m_gDBThreadCommunication, static_cast<int>(std::chrono::duration_cast<std::chrono::milliseconds>(latestRoutineExitTimeStamp - std::chrono::steady_clock::now()).count()))) { LOG(ERROR) << "Failed to wait for the target's/debugger's initialization."; m_garbageCollectorWorker->markFileForDelete(gdbInitFile); return false; } //Initialization is done - we don't need this any longer m_garbageCollectorWorker->markFileForDelete(gdbInitFile); //End of Target part ------------------------------------------------- //Feeder part ------------------------------------------------- #if defined(_WIN32) || defined(_WIN64) std::string feederSharedMemName = "FLUFFI_SharedMem_" + Util::newGUID(); #else std::string feederSharedMemName = "/FLUFFI_SharedMem_" + Util::newGUID(); #endif if (m_sharedMemIPC_toFeeder != nullptr) { delete m_sharedMemIPC_toFeeder; m_sharedMemIPC_toFeeder = nullptr; } m_sharedMemIPC_toFeeder = new SharedMemIPC(feederSharedMemName.c_str()); if (!m_sharedMemIPC_toFeeder->initializeAsServer()) { LOG(ERROR) << "Could not create the shared memory ipc connection to talk to the feeder "; return false; } m_feederProcess = std::make_shared<ExternalProcess>(m_feederCmdline + " " + feederSharedMemName, m_child_output_mode); if (!initializeFeeder(m_feederProcess, m_sharedMemIPC_toFeeder, m_gDBThreadCommunication->m_exOutput.m_PID, static_cast<int>(std::chrono::duration_cast<std::chrono::milliseconds>(latestRoutineExitTimeStamp - std::chrono::steady_clock::now()).count()))) { LOG(ERROR) << "Could not initialize the feeder "; return false; } #if defined(_WIN32) || defined(_WIN64) if (0 == ResetEvent(m_SharedMemIPCInterruptEvent)) { LOG(ERROR) << "Could not reset the m_SharedMemIPCInterruptEvent!"; return false; } else { LOG(DEBUG) << "The SharedMemIPCInterruptEvent was resetted"; } #else //clear the interrupt pipe int nbytes = 0; ioctl(m_SharedMemIPCInterruptFD[0], FIONREAD, &nbytes); if (nbytes > 0) { char* buff = new char[nbytes]; ssize_t bytesRead = read(m_SharedMemIPCInterruptFD[0], buff, nbytes); delete[] buff; if (bytesRead == nbytes) { LOG(DEBUG) << "The m_SharedMemIPCInterruptFD was resetted"; } else { LOG(ERROR) << "Could not reset the m_SharedMemIPCInterruptFD!"; return false; } } else { LOG(DEBUG) << "The m_SharedMemIPCInterruptFD was not resetted as it was not set"; } #endif //End of Feeder part ------------------------------------------------- return true; } #if defined(_WIN32) || defined(_WIN64) void TestExecutorGDB::debuggerThreadMain(const std::string targetCMDline, std::shared_ptr<GDBThreadCommunication> gDBThreadCommunication, ExternalProcess::CHILD_OUTPUT_TYPE child_output_mode, const std::string gdbInitFile, HANDLE sharedMemIPCInterruptEvent, const std::set<Module> modulesToCover, const std::set<FluffiBasicBlock> blocksToCover, uint32_t bpInstr, int bpInstrBytes) { #else void TestExecutorGDB::debuggerThreadMain(const std::string targetCMDline, std::shared_ptr<GDBThreadCommunication> gDBThreadCommunication, ExternalProcess::CHILD_OUTPUT_TYPE child_output_mode, const std::string gdbInitFile, int sharedMemIPCInterruptWriteFD, const std::set<Module> modulesToCover, const std::set<FluffiBasicBlock> blocksToCover, unsigned int bpInstr, int bpInstrBytes) { #endif gDBThreadCommunication->m_exOutput.m_debuggerThreadDone = false; gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "The target did not run!"; //Start gdb ExternalProcess gdbProc = ExternalProcess(targetCMDline, ExternalProcess::CHILD_OUTPUT_TYPE::SPECIAL); bool success = gdbProc.initProcess(); if (!success) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "debuggerThreadMain: Calling \"initProcess\" on the GDB process failed!"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; gDBThreadCommunication->set_gdbThreadShouldTerminate(); gDBThreadCommunication->m_exOutput.m_debuggerThreadDone = true; return; } gDBThreadCommunication->m_ostreamToGdb = gdbProc.getStdInOstream(); HANDLETYPE inputHandleFromGdb = gdbProc.getStdOutHandle(); #if defined(_WIN32) || defined(_WIN64) #else gDBThreadCommunication->m_gdbPid = gdbProc.getProcessID(); #endif success = gdbProc.run(); if (!success) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "debuggerThreadMain: Calling \"run\" on the GDB process failed!"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; gDBThreadCommunication->set_gdbThreadShouldTerminate(); gDBThreadCommunication->m_exOutput.m_debuggerThreadDone = true; return; } //Init gdb std::ifstream initCommandFile(gdbInitFile, std::ifstream::in); if (!initCommandFile.is_open()) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "debuggerThreadMain: Could not open the gdbInitFile!"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; gDBThreadCommunication->set_gdbThreadShouldTerminate(); gDBThreadCommunication->m_exOutput.m_debuggerThreadDone = true; return; } *gDBThreadCommunication->m_ostreamToGdb << initCommandFile.rdbuf(); //*gDBThreadCommunication->m_ostreamToGdb << "set stop-on-solib-events 1" << std::endl; //stop on module load *gDBThreadCommunication->m_ostreamToGdb << "set new-console on" << std::endl; //do not print the debugees output in our console gDBThreadCommunication->m_ostreamToGdb->flush(); initCommandFile.close(); //Init gdbLinereader std::thread gdbLinereaderThread(&TestExecutorGDB::gdbLinereaderThread, gDBThreadCommunication, inputHandleFromGdb, child_output_mode); gdbLinereaderThread.detach(); //we do not want to join this. It will terminate as soon as gDBThreadCommunication->m_gdbThreadShouldTerminate is set to true //Remove the gdb headers from the gdbOutputQueue by sending a dummy command (when it's response arrives, we now we are done) //As there might be leftover commands we might need to clean that first std::string resp; bool noProblem = false; while (true) { noProblem = sendCommandToGDBAndWaitForResponse("set", &resp, gDBThreadCommunication); if (noProblem) { break; } else if (resp == "LEFTOVER") { while (gDBThreadCommunication->get_gdbOutputQueue_size() > 0) { gDBThreadCommunication->gdbOutputQueue_pop_front(); } continue; } break; } if (!noProblem) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "debuggerThreadMain: clearing the gdb output queue failed"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; gDBThreadCommunication->set_gdbThreadShouldTerminate(); gDBThreadCommunication->m_exOutput.m_debuggerThreadDone = true; return; } gdbDebug(gDBThreadCommunication, modulesToCover, blocksToCover, bpInstr, bpInstrBytes); if (gDBThreadCommunication->m_exOutput.m_terminationType == DebugExecutionOutput::PROCESS_TERMINATION_TYPE::EXCEPTION_ACCESSVIOLATION || gDBThreadCommunication->m_exOutput.m_terminationType == DebugExecutionOutput::PROCESS_TERMINATION_TYPE::EXCEPTION_OTHER) { //In case an exception occured, set sharedMemIPCInterruptEvent / write to the sharedMemIPCInterruptWriteFD, so the shared mem communication does not need to wait for an timeout but terminates early #if defined(_WIN32) || defined(_WIN64) if (0 == SetEvent(sharedMemIPCInterruptEvent)) { LOG(ERROR) << "Failed setting the sharedMemIPCInterruptEvent"; } #else char buf[] = "X"; ssize_t charsWritten = write(sharedMemIPCInterruptWriteFD, buf, 1); if (charsWritten != 1) { LOG(ERROR) << "Failed setting the sharedMemIPCInterruptWriteFD"; } #endif } gDBThreadCommunication->set_gdbThreadShouldTerminate(); gDBThreadCommunication->m_exOutput.m_debuggerThreadDone = true; return; } bool TestExecutorGDB::sendCommandToGDBAndWaitForResponse(const std::string command, std::string* response, std::shared_ptr<GDBThreadCommunication> gDBThreadCommunication, bool sendCtrlZ) { //LOG(DEBUG) << "sendCommandToGDBAndWaitForResponse:\"" << command << "\""; if (command == "") { //Nothing to do return true; } if (gDBThreadCommunication->get_gdbOutputQueue_size() != 0) { //There is something left over from the last call. This is most likely a bug! *response = "LEFTOVER"; return false; } if (sendCtrlZ) { #if defined(_WIN32) || defined(_WIN64) // Disable Ctrl-C handling for our program if (SetConsoleCtrlHandler(NULL, true) == 0) { *response = "ERROR"; return false; } //Send Ctrl-C to all programs in our Console if (GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0) == 0) { SetConsoleCtrlHandler(NULL, false); *response = "ERROR"; return false; } #else kill(gDBThreadCommunication->m_gdbPid, SIGINT); #endif } for (size_t i = 0; i < command.length(); i += 1000) { //Handle gdbThreadShouldTerminate if (gDBThreadCommunication->get_gdbThreadShouldTerminate()) { #if defined(_WIN32) || defined(_WIN64) if (sendCtrlZ) { //Re-enable Ctrl-C handling or any subsequently started //programs will inherit the disabled state. SetConsoleCtrlHandler(NULL, false); } #endif *response = "INTERRUPTED"; return false; } *gDBThreadCommunication->m_ostreamToGdb << command.substr(i, 1000); gDBThreadCommunication->m_ostreamToGdb->flush(); } *gDBThreadCommunication->m_ostreamToGdb << std::endl << "fluffi" << std::endl; std::stringstream responseSS; bool firstLine = true; while (true) { gDBThreadCommunication->waitForTerminateMessageOrCovStateChange(nullptr, 0); //Handle gdbThreadShouldTerminate if (gDBThreadCommunication->get_gdbThreadShouldTerminate()) { #if defined(_WIN32) || defined(_WIN64) if (sendCtrlZ) { //Re-enable Ctrl-C handling or any subsequently started //programs will inherit the disabled state. SetConsoleCtrlHandler(NULL, false); } #endif *response = "INTERRUPTED"; return false; } //Handle gdbOutputQueue while (gDBThreadCommunication->get_gdbOutputQueue_size() > 0) { std::string line = gDBThreadCommunication->gdbOutputQueue_pop_front(); if (line.find("Undefined command") != std::string::npos) { #if defined(_WIN32) || defined(_WIN64) if (sendCtrlZ) { //Re-enable Ctrl-C handling or any subsequently started //programs will inherit the disabled state. SetConsoleCtrlHandler(NULL, false); } #endif *response = responseSS.str(); return true; } else { if (firstLine) { firstLine = false; } else { responseSS << "\n"; } responseSS << line; } } } } std::string TestExecutorGDB::getCrashRVA(std::vector<tModuleAddressesAndSizes>& baseAddressesAndSizes, uint64_t signalAddress) { for (tModuleAddressesAndSizes& baseAddressesAndSizesit : baseAddressesAndSizes) { if (std::get<1>(baseAddressesAndSizesit) < signalAddress &&std::get<1>(baseAddressesAndSizesit) + std::get<2>(baseAddressesAndSizesit) > signalAddress) { std::stringstream oss; oss << std::get<0>(baseAddressesAndSizesit) << "+0x" << std::hex << std::setw(8) << std::setfill('0') << signalAddress - std::get<1>(baseAddressesAndSizesit); return oss.str(); } } std::stringstream oss; oss << "unknown+0x" << std::hex << std::setw(8) << std::setfill('0') << signalAddress; return oss.str(); } bool TestExecutorGDB::handleSignal(std::shared_ptr<GDBThreadCommunication> gDBThreadCommunication, std::string signalmessage, std::map<uint64_t, GDBBreakpoint>* allBreakpoints, std::set<FluffiBasicBlock>* blocksCoveredSinceLastReset, int bpInstrBytes) { std::string signalName; std::string::size_type pos = signalmessage.find(','); if (pos != std::string::npos) { signalName = signalmessage.substr(24, pos - 24); } else { signalName = signalmessage.substr(24, 9); } std::string addressLine; bool gotAddressLine = false; while (!gotAddressLine) { if (gDBThreadCommunication->get_gdbOutputQueue_size() == 0) { //Try to wait for the message that contains the current ip gDBThreadCommunication->waitForTerminateMessageOrCovStateChange(nullptr, 0); if (gDBThreadCommunication->get_gdbOutputQueue_size() == 0) { //waiting failed: we should terminate return false; } } //read a line from the gdb input addressLine = gDBThreadCommunication->gdbOutputQueue_pop_front(); //Is it the address line? if (addressLine.substr(0, 2) == "0x") { gotAddressLine = true; } else if (addressLine.find("Switching to Thread") != std::string::npos) { //These are well known and can be ignored } else { LOG(DEBUG) << "handleSignal: Unexpected message from gdb:" << addressLine; } } uint64_t signalAddress; try { signalAddress = std::stoll(addressLine.c_str(), 0, 0x10); if (signalAddress == 0) { LOG(WARNING) << "handleSignal could not parse line " << addressLine << " as address"; } } catch (...) { LOG(ERROR) << "handleSignal could not parse line " << addressLine << " as address: std::stoi/stoll failed"; google::protobuf::ShutdownProtobufLibrary(); _exit(EXIT_FAILURE); //make compiler happy } if (signalName.substr(0, 7) == "SIGTRAP") { //possibly a breakpoint - see if we can handle it bool breakPointKnown = (allBreakpoints->count(signalAddress) > 0); bool breakPointKnownOffByOne = (allBreakpoints->count(signalAddress - 1) > 0); if (breakPointKnown || breakPointKnownOffByOne) { //Yep, this is one of our breakpoints GDBBreakpoint gdbb = allBreakpoints->at(signalAddress - (breakPointKnown ? 0 : 1)); blocksCoveredSinceLastReset->insert(gdbb.m_fbb); //Mark the breakpoint as disabled allBreakpoints->at(signalAddress - (breakPointKnown ? 0 : 1)).m_isEnabled = false; //Remove the breakpoint switch (bpInstrBytes) { case 1: *gDBThreadCommunication->m_ostreamToGdb << "set {unsigned char}0x" << std::hex << gdbb.m_absoluteAdress << " = 0x" << std::hex << gdbb.m_originalBytes << std::endl; break; case 2: *gDBThreadCommunication->m_ostreamToGdb << "set {unsigned short}0x" << std::hex << gdbb.m_absoluteAdress << " = 0x" << std::hex << gdbb.m_originalBytes << std::endl; break; case 4: *gDBThreadCommunication->m_ostreamToGdb << "set {unsigned int}0x" << std::hex << gdbb.m_absoluteAdress << " = 0x" << std::hex << gdbb.m_originalBytes << std::endl; break; default: LOG(ERROR) << "Reached a code path in generateEnableAllCommand, that should be unreachable"; google::protobuf::ShutdownProtobufLibrary(); _exit(EXIT_FAILURE); //make compiler happy } //Jump to the recently written byte (equivaltent to decrementing the instruction pointer and continuing - but that would be architecture dependant) *gDBThreadCommunication->m_ostreamToGdb << "j *0x" << std::hex << gdbb.m_absoluteAdress << std::endl; return true; } } std::vector<tModuleAddressesAndSizes> baseAddressesAndSizes; std::string infoFilesResp; if (!sendCommandToGDBAndWaitForResponse("info files", &infoFilesResp, gDBThreadCommunication)) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "handleSignal: \"info files\" failed"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } if (!getBaseAddressesAndSizes(baseAddressesAndSizes, infoFilesResp)) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "handleSignal: \"getBaseAddressesAndSizes\" failed"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } std::string crashRVA = getCrashRVA(baseAddressesAndSizes, signalAddress); if (gDBThreadCommunication->m_exOutput.m_firstCrash == "") { //first crash gDBThreadCommunication->m_exOutput.m_firstCrash = crashRVA; gDBThreadCommunication->m_exOutput.m_lastCrash = crashRVA; //Try to continue the signal *gDBThreadCommunication->m_ostreamToGdb << "c" << std::endl; } else { if (gDBThreadCommunication->m_exOutput.m_lastCrash == crashRVA) { //Apparently, the program failed to handle the last signal if (signalName.substr(0, 7) == "SIGSEGV") { gDBThreadCommunication->m_exOutput.m_terminationDescription = "Detected an EXCEPTION_ACCESS_VIOLATION"; gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::EXCEPTION_ACCESSVIOLATION; } else { gDBThreadCommunication->m_exOutput.m_terminationDescription = "Detected an Unhandled signal: " + signalName; gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::EXCEPTION_OTHER; } gDBThreadCommunication->set_gdbThreadShouldTerminate(); } else { //Apparently, the program managed to handle the last signal gDBThreadCommunication->m_exOutput.m_lastCrash = crashRVA; //Try to continue the signal *gDBThreadCommunication->m_ostreamToGdb << "c" << std::endl; } } return true; } bool TestExecutorGDB::consumeGDBOutputQueue(std::shared_ptr<GDBThreadCommunication> gDBThreadCommunication, std::set<FluffiBasicBlock>* blocksCoveredSinceLastReset, std::map<uint64_t, GDBBreakpoint>* allBreakpoints, int bpInstrBytes) { while (gDBThreadCommunication->get_gdbOutputQueue_size() > 0) { std::string line = gDBThreadCommunication->gdbOutputQueue_pop_front(); if (line.find_first_not_of(" \t\f\v\n\r", 0) != std::string::npos) { if (line.substr(0, 23) == "Program received signal") { if (!handleSignal(gDBThreadCommunication, line, allBreakpoints, blocksCoveredSinceLastReset, bpInstrBytes)) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "consumeGDBOutputQueue: Failed to handle a signal"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } } else if (line.find("exited with code") != std::string::npos || line.substr(0, 24) == "Program exited normally.") { size_t exitCodePos = line.find("exited with code"); int exitCode = 0; if (exitCodePos != std::string::npos) { try { exitCode = std::stoi(line.c_str() + exitCodePos + 17, 0, 0x10); } catch (...) { exitCode = 0; LOG(WARNING) << "consumeGDBOutputQueue: std::stoi on process exit code failed"; } } gDBThreadCommunication->set_exitStatus(exitCode); //If no exception was observed: Set exit type to normal if (gDBThreadCommunication->m_exOutput.m_terminationType == DebugExecutionOutput::PROCESS_TERMINATION_TYPE::CLEAN) { gDBThreadCommunication->m_exOutput.m_terminationDescription = "Process terminated normally: " + std::to_string(exitCode); } return false; } else if (line.substr(0, 10) == "Continuing" || line.find("New Thread") != std::string::npos || line.find("Switching to Thread") != std::string::npos) { //These are well known and can be ignored } else { LOG(DEBUG) << "Unexpected message from gdb:" << line; } } } return true; } std::string TestExecutorGDB::generateEnableAllCommand(std::map<uint64_t, GDBBreakpoint>& allBreakpoints, uint32_t bpInstr, int bpInstrBytes) { std::stringstream oss; typedef std::pair<const uint64_t, GDBBreakpoint> breakpointPair; for (breakpointPair& it : allBreakpoints) { if (!it.second.m_isEnabled) { //It will be enabled now it.second.m_isEnabled = true; switch (bpInstrBytes) { case 1: oss << "set {unsigned char}0x" << std::hex << it.second.m_absoluteAdress << " = 0x" << std::hex << bpInstr << std::endl; break; case 2: oss << "set {unsigned short}0x" << std::hex << it.second.m_absoluteAdress << " = 0x" << std::hex << bpInstr << std::endl; break; case 4: oss << "set {unsigned int}0x" << std::hex << it.second.m_absoluteAdress << " = 0x" << std::hex << bpInstr << std::endl; break; default: LOG(ERROR) << "Reached a code path in generateEnableAllCommand, that should be unreachable"; google::protobuf::ShutdownProtobufLibrary(); _exit(EXIT_FAILURE); //make compiler happy } } } return oss.str(); } void TestExecutorGDB::gdbDebug(std::shared_ptr<GDBThreadCommunication> gDBThreadCommunication, const std::set<Module> modulesToCover, const std::set<FluffiBasicBlock> blocksToCover, uint32_t bpInstr, int bpInstrBytes) { std::map<uint64_t, GDBBreakpoint> allBreakpoints; if (!gdbPrepareForDebug(gDBThreadCommunication, modulesToCover, blocksToCover, &allBreakpoints, bpInstrBytes)) { return; } *gDBThreadCommunication->m_ostreamToGdb << "c" << std::endl; gDBThreadCommunication->set_debuggingReady(); //So far there is no exception gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::CLEAN; gDBThreadCommunication->m_exOutput.m_terminationDescription = "The target executed without any exception"; std::set<FluffiBasicBlock> blocksCoveredSinceLastReset; GDBThreadCommunication::COVERAGE_STATE statesToWaitFor[] = { GDBThreadCommunication::COVERAGE_STATE::SHOULD_DUMP, GDBThreadCommunication::COVERAGE_STATE::SHOULD_RESET_HARD, GDBThreadCommunication::COVERAGE_STATE::SHOULD_RESET_SOFT }; while (true) { gDBThreadCommunication->waitForTerminateMessageOrCovStateChange(statesToWaitFor, 2); //Handle gdbThreadShouldTerminate if (gDBThreadCommunication->get_gdbThreadShouldTerminate()) { return; } //Handle gdbOutputQueue if (!consumeGDBOutputQueue(gDBThreadCommunication, &blocksCoveredSinceLastReset, &allBreakpoints, bpInstrBytes)) { return; } //Handle coverageState GDBThreadCommunication::COVERAGE_STATE cstate = gDBThreadCommunication->get_coverageState(); switch (cstate) { case GDBThreadCommunication::COVERAGE_STATE::SHOULD_RESET_HARD: //Reset coverage to NULL and enable all breakpoints { //As there might be leftover commands we might need to clean that first std::string resp; bool noProblem = false; while (true) { noProblem = sendCommandToGDBAndWaitForResponse(generateEnableAllCommand(allBreakpoints, bpInstr, bpInstrBytes), &resp, gDBThreadCommunication, true); if (noProblem) { break; } else if (resp == "LEFTOVER") { //Handle gdbOutputQueue if (!consumeGDBOutputQueue(gDBThreadCommunication, &blocksCoveredSinceLastReset, &allBreakpoints, bpInstrBytes)) { return; } continue; } break; } if (!noProblem) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "gdbDebug: Failed enabling all breakpoints"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return; } blocksCoveredSinceLastReset.clear(); *gDBThreadCommunication->m_ostreamToGdb << "c" << std::endl; gDBThreadCommunication->set_coverageState(GDBThreadCommunication::COVERAGE_STATE::RESETTED); break; } case GDBThreadCommunication::COVERAGE_STATE::SHOULD_RESET_SOFT://Reset coverage to NULL { blocksCoveredSinceLastReset.clear(); gDBThreadCommunication->set_coverageState(GDBThreadCommunication::COVERAGE_STATE::RESETTED); break; } case GDBThreadCommunication::COVERAGE_STATE::SHOULD_DUMP: { if (gDBThreadCommunication->m_exOutput.getCoveredBasicBlocks().size() > 0) { LOG(WARNING) << "gDBThreadCommunication->m_exOutput.getCoveredBasicBlocks was not empty. This should not happen!"; DebugExecutionOutput t = DebugExecutionOutput{}; gDBThreadCommunication->m_exOutput.swapBlockVectorWith(t); } for (const FluffiBasicBlock& blockIt : blocksCoveredSinceLastReset) { gDBThreadCommunication->m_exOutput.addCoveredBasicBlock(blockIt); } gDBThreadCommunication->set_coverageState(GDBThreadCommunication::COVERAGE_STATE::DUMPED); break; } default: break; } } } bool TestExecutorGDB::gdbPrepareForDebug(std::shared_ptr<GDBThreadCommunication> gDBThreadCommunication, const std::set<Module> modulesToCover, const std::set<FluffiBasicBlock> blocksToCover, std::map<uint64_t, GDBBreakpoint>* allBreakpoints, int bpInstrBytes) { if (gDBThreadCommunication->get_gdbOutputQueue_size() != 0) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "GDB initialization failed: we got a message when we did not expect it:" + gDBThreadCommunication->gdbOutputQueue_pop_front(); LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } std::string resp; //Check, if the gdb is waiting for us (we attached) bool noProblem = sendCommandToGDBAndWaitForResponse("i r", &resp, gDBThreadCommunication); if (!noProblem) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "gdbPrepareForDebug: first \"i r\" failed"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } if (resp.find("no registers now") != std::string::npos) { //If the GDB did not wait for us, try to start the target noProblem = sendCommandToGDBAndWaitForResponse("br *0x0", &resp, gDBThreadCommunication); if (!noProblem) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "gdbPrepareForDebug: \"br *0x0\" failed"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } int numOfDummyBreakpoint; try { numOfDummyBreakpoint = std::stoi(resp.c_str() + 11); } catch (...) { LOG(ERROR) << "std::stoi failed"; google::protobuf::ShutdownProtobufLibrary(); _exit(EXIT_FAILURE); //make compiler happy } //Program will load but complain that it cannot set fake breakpont at 0 - we got a breakpoint at system entry noProblem = sendCommandToGDBAndWaitForResponse("run", &resp, gDBThreadCommunication); if (!noProblem) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "gdbPrepareForDebug: \"run\" failed"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } noProblem = sendCommandToGDBAndWaitForResponse("d br " + std::to_string(numOfDummyBreakpoint), &resp, gDBThreadCommunication); if (!noProblem) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "gdbPrepareForDebug: deleting 0 breakpoint failed"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } //check if we the program is now loaded noProblem = sendCommandToGDBAndWaitForResponse("i r", &resp, gDBThreadCommunication); if (!noProblem) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "gdbPrepareForDebug: second \"i r\" failed"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } } if (resp.find("rax") == std::string::npos && resp.find("eax") == std::string::npos && resp.find("r0") == std::string::npos) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "gdbPrepareForDebug: The gdb command \"i r\" does not print registers "; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } //get a list of all loaded files and their addresses std::map<int, uint64_t> baseMap; std::string infoFilesResp; if (!sendCommandToGDBAndWaitForResponse("info files", &infoFilesResp, gDBThreadCommunication)) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "gdbPrepareForDebug: \"info files\" failed"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } if (!getBaseAddressesForModules(&baseMap, modulesToCover, infoFilesResp)) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "gdbPrepareForDebug: getBaseAddressesForModules failed "; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } if (baseMap.size() != modulesToCover.size()) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "gdbPrepareForDebug: It was not possible to determine the addresses of all breakpoints to set (Dynamic module loading is currently not supported)"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } //Get the target's PID (if possible) noProblem = sendCommandToGDBAndWaitForResponse("info inferior", &resp, gDBThreadCommunication); if (!noProblem) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "gdbPrepareForDebug: \"info inferior\" failed"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } else { size_t isPos = resp.find("process"); if (isPos != std::string::npos) { try { gDBThreadCommunication->m_exOutput.m_PID = std::stoi(resp.c_str() + isPos + 7); } catch (...) { LOG(ERROR) << "std::stoi failed"; google::protobuf::ShutdownProtobufLibrary(); _exit(EXIT_FAILURE); //make compiler happy } } } //Fill the allBreakpoints map: 1 - Generate the statement to get all "real" bytes where we will set the breakpoints std::stringstream breakpointsToSetSS; bool isFirstBreak = true; for (const FluffiBasicBlock& basicBlockIt : blocksToCover) { if (isFirstBreak) { isFirstBreak = false; } else { breakpointsToSetSS << std::endl; } switch (bpInstrBytes) { case 1: breakpointsToSetSS << "x/1xb 0x" << std::hex << basicBlockIt.m_rva + baseMap[basicBlockIt.m_moduleID]; break; case 2: breakpointsToSetSS << "x/1xh 0x" << std::hex << basicBlockIt.m_rva + baseMap[basicBlockIt.m_moduleID]; break; case 4: breakpointsToSetSS << "x/1xw 0x" << std::hex << basicBlockIt.m_rva + baseMap[basicBlockIt.m_moduleID]; break; default: LOG(ERROR) << "Reached a code path in gdbPrepareForDebug, that should be unreachable"; google::protobuf::ShutdownProtobufLibrary(); _exit(EXIT_FAILURE); //make compiler happy } } noProblem = sendCommandToGDBAndWaitForResponse(breakpointsToSetSS.str(), &resp, gDBThreadCommunication); if (!noProblem) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "gdbPrepareForDebug: getting all real breakpoint bytes failed"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } //Fill the allBreakpoints map: 2 - Store which "breakpoint_bytes" are at which address, and belongs to which Fluffi basic block allBreakpoints->clear(); std::vector<std::string> lines = Util::splitString(resp, "\n"); std::set<FluffiBasicBlock>::iterator fbbIt = blocksToCover.begin(); for (std::string& linesIt : lines) { try { uint64_t absAddress = (*fbbIt).m_rva + baseMap[(*fbbIt).m_moduleID]; if (std::stoull(linesIt.c_str(), 0, 16) == absAddress && linesIt.find_first_of(":") != std::string::npos) { allBreakpoints->insert(std::pair<uint64_t, GDBBreakpoint>(absAddress, GDBBreakpoint(absAddress, static_cast<unsigned int>(std::stoul(linesIt.c_str() + linesIt.find_first_of(":") + 1, 0, 16)), *fbbIt))); if (fbbIt == blocksToCover.end()) { break; } else { ++fbbIt; } } else { LOG(DEBUG) << "Read line \"" << linesIt << "\" when parsing the getting-all-real-breakpoint-bytes output."; continue; } } catch (...) { LOG(ERROR) << "std::stoi/stoll failed"; google::protobuf::ShutdownProtobufLibrary(); _exit(EXIT_FAILURE); //make compiler happy } } if (allBreakpoints->size() != blocksToCover.size()) { gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "gdbPrepareForDebug: Failed getting all real breakpoint bytes - at least one could not be read"; LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return false; } return true; } bool TestExecutorGDB::getBaseAddressesForModules(std::map<int, uint64_t>* modmap, const std::set<Module> modulesToCover, std::string parseInfoOutput) { //Check for the NULL module for (std::set<Module>::iterator it = modulesToCover.begin(); it != modulesToCover.end(); ++it) { if ((*it).m_modulename == "" || (*it).m_modulename == "NULL" || (*it).m_modulename == "0") { modmap->insert(std::pair<int, uint64_t>((*it).m_moduleid, 0)); } } std::vector<tModuleInformation> loadedFiles; if (!parseInfoFiles(loadedFiles, parseInfoOutput)) { return false; } for (std::vector<tModuleInformation>::iterator loadedFilesIT = loadedFiles.begin(); loadedFilesIT != loadedFiles.end(); ++loadedFilesIT) { //Check, if this is something, we are interested in for (std::set<Module>::iterator mod2CoverIT = modulesToCover.begin(); mod2CoverIT != modulesToCover.end(); ++mod2CoverIT) { if ((*mod2CoverIT).m_modulename == std::get<2>((*loadedFilesIT)) + "/" + std::get<3>((*loadedFilesIT)) && ((*mod2CoverIT).m_modulepath == "*" || (*mod2CoverIT).m_modulepath == std::get<4>((*loadedFilesIT)))) { modmap->insert(std::pair<int, uint64_t>((*mod2CoverIT).m_moduleid, std::get<0>((*loadedFilesIT)))); } } } return true; } bool TestExecutorGDB::getBaseAddressesAndSizes(std::vector<tModuleAddressesAndSizes>& outBaseAddressesAndSizes, std::string parseInfoOutput) { // start, end, name, segmentname, path std::vector<tModuleInformation> loadedFiles; if (!parseInfoFiles(loadedFiles, parseInfoOutput)) { return false; } using std::get; for (tModuleInformation& loadedFilesIT : loadedFiles) { outBaseAddressesAndSizes.push_back( std::make_tuple( get<2>(loadedFilesIT) + "/" + get<3>(loadedFilesIT), get<0>(loadedFilesIT), get<1>(loadedFilesIT) - get<0>(loadedFilesIT) ) ); } return true; } bool TestExecutorGDB::parseInfoFiles(std::vector<tModuleInformation>& loadedFiles, std::string infoFilesResp) { std::vector<std::string> lines = Util::splitString(infoFilesResp, "\n"); bool reachedMainPart = false; std::string procName = ""; std::string procPath = ""; for (std::string& lineIt : lines) { //Skip all lines until the list of files if (!reachedMainPart) { if (lineIt.substr(0, 5) == "Local") { reachedMainPart = true; } continue; } //Is this the line that contains the file name? If yes: extract main module name and path if (lineIt.find("file type") != std::string::npos) { size_t start = lineIt.find_first_of(0x60, 0); size_t end = lineIt.find_first_of(0x27, 0); if (start != std::string::npos && end != std::string::npos) { std::string mainPathAndName = lineIt.substr(start + 1, end - start - 1); std::tuple<std::string, std::string> directoryAndFilename = Util::splitPathIntoDirectoryAndFileName(mainPathAndName); procName = std::get<1>(directoryAndFilename); procPath = std::get<0>(directoryAndFilename); } continue; } //Parse each line size_t actualLineStart = lineIt.find_first_not_of(" \t\f\v\n\r", 0); size_t actualLineEnd = lineIt.find_last_not_of(" \t\f\v\n\r", lineIt.length()); if (actualLineStart == std::string::npos || actualLineEnd == std::string::npos) { continue; } std::string trimmedLine = lineIt.substr(actualLineStart, actualLineEnd - actualLineStart + 1); size_t isPos = trimmedLine.find("is "); if (isPos != std::string::npos) { std::string afterIs = trimmedLine.substr(isPos + 3); size_t firstSpaceAfterIs = afterIs.find_first_of(' ', 0); if (firstSpaceAfterIs == std::string::npos) { firstSpaceAfterIs = afterIs.length(); } std::string currentSegmentName = afterIs.substr(0, firstSpaceAfterIs); std::string currentName = ""; std::string currentPath = ""; size_t inPos = afterIs.find("in "); if (inPos != std::string::npos) { std::string afterIn = afterIs.substr(inPos + 3); std::tuple<std::string, std::string> currentDirectoryAndFilename = Util::splitPathIntoDirectoryAndFileName(afterIn); currentName = std::get<1>(currentDirectoryAndFilename); currentPath = std::get<0>(currentDirectoryAndFilename); } else { currentName = procName; currentPath = procPath; } uint64_t currentStartAddress, currentEndAddress; try { currentStartAddress = std::stoll(trimmedLine, NULL, 16); currentEndAddress = std::stoll(trimmedLine.substr(trimmedLine.find("-") + 1), NULL, 16); } catch (...) { LOG(ERROR) << "std::stoi/stoll failed"; google::protobuf::ShutdownProtobufLibrary(); _exit(EXIT_FAILURE); //make compiler happy } loadedFiles.push_back(std::make_tuple(currentStartAddress, currentEndAddress, currentName, currentSegmentName, currentPath)); } } return true; } void TestExecutorGDB::gdbLinereaderThread(std::shared_ptr<GDBThreadCommunication> gDBThreadCommunication, HANDLETYPE inputHandleFromGdb, ExternalProcess::CHILD_OUTPUT_TYPE child_output_mode) { std::vector<char> charsReadButNotReturned; #if defined(_WIN32) || defined(_WIN64) DWORD totalBytesAvail = 0; DWORD bytesRead = 0; while (!gDBThreadCommunication->get_gdbThreadShouldTerminate() && 0 != PeekNamedPipe(inputHandleFromGdb, NULL, NULL, NULL, &totalBytesAvail, NULL)) { if (totalBytesAvail == 0) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); continue; } char* buff = new char[totalBytesAvail]; ReadFile(inputHandleFromGdb, buff, totalBytesAvail, &bytesRead, NULL); if (totalBytesAvail != bytesRead) { #else int nbytes = 0; while (!gDBThreadCommunication->get_gdbThreadShouldTerminate() && 0 != ioctl(inputHandleFromGdb, FIONREAD, &nbytes)) { char* buff = new char[nbytes]; ssize_t bytesRead = read(inputHandleFromGdb, buff, nbytes); if (bytesRead != nbytes) { #endif gDBThreadCommunication->m_exOutput.m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; gDBThreadCommunication->m_exOutput.m_terminationDescription = "gdbLinereaderThread: Failed reading from gdb output pipe"; gDBThreadCommunication->set_gdbThreadShouldTerminate(); LOG(ERROR) << gDBThreadCommunication->m_exOutput.m_terminationDescription; return; } charsReadButNotReturned.insert(charsReadButNotReturned.end(), buff, buff + bytesRead); delete[] buff; while (true) { auto newlinePos = std::find(charsReadButNotReturned.begin(), charsReadButNotReturned.end(), '\n'); if (newlinePos != charsReadButNotReturned.end()) { /* charsReadButNotReturned contains newline */ std::string line(charsReadButNotReturned.begin(), newlinePos); charsReadButNotReturned.erase(charsReadButNotReturned.begin(), newlinePos + 1); //delete the "(gdb) ". It seems to stem from a different stream and is more confusing than helping while (true) { std::string::size_type gdbPos = line.find("(gdb) "); if (gdbPos == std::string::npos) { break; } line.erase(gdbPos, 6); } if (child_output_mode == ExternalProcess::CHILD_OUTPUT_TYPE::OUTPUT) { //Simulate external program's "white" output printf("%s\n", line.c_str()); } gDBThreadCommunication->gdbOutputQueue_push_back(line); } else { /* charsReadButNotReturned DOES NOT contain newline */ break; } } } LOG(DEBUG) << "gdbLinereaderThread terminating"; gDBThreadCommunication->set_gdbThreadShouldTerminate(); return; } bool TestExecutorGDB::runSingleTestcase(const FluffiTestcaseID testcaseId, std::shared_ptr<DebugExecutionOutput> exResult, CoverageMode covMode) { std::chrono::time_point<std::chrono::steady_clock> routineEntryTimeStamp = std::chrono::steady_clock::now(); std::chrono::time_point<std::chrono::steady_clock> latestRoutineExitTimeStamp = routineEntryTimeStamp + std::chrono::milliseconds(m_hangTimeoutMS); LOG(DEBUG) << "runSingleTestcase:" << testcaseId << " in covMode " << ((covMode == CoverageMode::FULL) ? "FULL" : ((covMode == CoverageMode::NONE) ? "NONE" : "PARTIAL")); if (covMode != CoverageMode::NONE) { //reset coverage m_gDBThreadCommunication->set_coverageState((covMode == CoverageMode::FULL) ? GDBThreadCommunication::COVERAGE_STATE::SHOULD_RESET_HARD : GDBThreadCommunication::COVERAGE_STATE::SHOULD_RESET_SOFT); if (!TestExecutorGDB::waitUntilCoverageState(m_gDBThreadCommunication, GDBThreadCommunication::COVERAGE_STATE::RESETTED, static_cast<int>(std::chrono::duration_cast<std::chrono::milliseconds>(latestRoutineExitTimeStamp - std::chrono::steady_clock::now()).count()))) { exResult->m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; exResult->m_terminationDescription = "Problem while resetting the coverage (a timeout occured): Increase hangTimeout!"; return false; } LOG(DEBUG) << "The coverage state RESETTED was reached"; } //send "go" to feeder std::string testcaseFile = Util::generateTestcasePathAndFilename(testcaseId, m_testcaseDir); SharedMemMessage fuzzFilenameMsg{ SHARED_MEM_MESSAGE_FUZZ_FILENAME, testcaseFile.c_str(),static_cast<int>(testcaseFile.length()) }; if (!m_sharedMemIPC_toFeeder->sendMessageToClient(&fuzzFilenameMsg)) { exResult->m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; exResult->m_terminationDescription = "Problem while sending a fuzzing filename to the feeder!"; return false; } //wait for "done" from feeder SharedMemMessage responseFromFeeder; #if defined(_WIN32) || defined(_WIN64) m_sharedMemIPC_toFeeder->waitForNewMessageToServer(&responseFromFeeder, static_cast<DWORD>(std::chrono::duration_cast<std::chrono::milliseconds>(latestRoutineExitTimeStamp - std::chrono::steady_clock::now()).count()), m_SharedMemIPCInterruptEvent); #else m_sharedMemIPC_toFeeder->waitForNewMessageToServer(&responseFromFeeder, static_cast<unsigned long>(std::chrono::duration_cast<std::chrono::milliseconds>(latestRoutineExitTimeStamp - std::chrono::steady_clock::now()).count()), m_SharedMemIPCInterruptFD[0]); #endif if (responseFromFeeder.getMessageType() == SHARED_MEM_MESSAGE_FUZZ_DONE) { //feeder successfully forwarded the test case to the target, which responed in time } else if (responseFromFeeder.getMessageType() == SHARED_MEM_MESSAGE_WAIT_INTERRUPTED) { exResult->m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; exResult->m_terminationDescription = "Communication with feeder was interrupted!"; LOG(DEBUG) << exResult->m_terminationDescription; return false; } else if (responseFromFeeder.getMessageType() == SHARED_MEM_MESSAGE_TRANSMISSION_TIMEOUT) { exResult->m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::TIMEOUT; exResult->m_terminationDescription = "Communication with feeder timed out!"; return false; } else if (responseFromFeeder.getMessageType() == SHARED_MEM_MESSAGE_TARGET_CRASHED) { exResult->m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::EXCEPTION_OTHER; exResult->m_terminationDescription = "Feeder claims that target crashed!"; exResult->m_firstCrash = "FEEDER CLAIMS CRASH"; exResult->m_lastCrash = exResult->m_firstCrash; return true; } else { exResult->m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; exResult->m_terminationDescription = "Feeder returned a not expected message. We received a message of type " + std::to_string(responseFromFeeder.getMessageType()); return false; } if (covMode != CoverageMode::NONE) { //get coverage m_gDBThreadCommunication->set_coverageState(GDBThreadCommunication::COVERAGE_STATE::SHOULD_DUMP); if (!TestExecutorGDB::waitUntilCoverageState(m_gDBThreadCommunication, GDBThreadCommunication::COVERAGE_STATE::DUMPED, static_cast<int>(std::chrono::duration_cast<std::chrono::milliseconds>(latestRoutineExitTimeStamp - std::chrono::steady_clock::now()).count()))) { exResult->m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::ERR; exResult->m_terminationDescription = "Problem while dumping the coverage!"; return false; } LOG(DEBUG) << "The coverage state DUMPED was reached"; //Move coverage to m_gDBThreadCommunication execution result (for compatibility of the execution function with dynrio multi runner - allows better code reusability) m_gDBThreadCommunication->m_exOutput.swapBlockVectorWith(*exResult); } exResult->m_terminationType = DebugExecutionOutput::PROCESS_TERMINATION_TYPE::CLEAN; exResult->m_terminationDescription = "Fuzzcase executed normally!"; return true; } void TestExecutorGDB::waitForDebuggerToTerminate() { std::chrono::time_point<std::chrono::steady_clock> routineEntryTimeStamp = std::chrono::steady_clock::now(); std::chrono::time_point<std::chrono::steady_clock> timestampToKillTheTarget = routineEntryTimeStamp + std::chrono::milliseconds(m_hangTimeoutMS); bool targetKilled = false; LOG(DEBUG) << "Waiting for the debugger thread to terminate."; while (!m_gDBThreadCommunication->m_exOutput.m_debuggerThreadDone) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); if (!targetKilled && std::chrono::steady_clock::now() > timestampToKillTheTarget) { LOG(DEBUG) << "Waiting sucks - killing the target."; m_gDBThreadCommunication->set_gdbThreadShouldTerminate(); //In case the crash is not reproducible, terminate gdb to avoid race conditions. This should also kill the target. targetKilled = true; } } }
43.442159
460
0.749793
[ "vector" ]
cb42f0807f7af121269badce30593018cc50ee12
33,377
cpp
C++
Get Hooked/Motor2D/j1Scene.cpp
Scotland-Fury/Hook_Platformer
d2ea3259d464ff19e2eab395b100561aa8042802
[ "MIT" ]
1
2020-12-03T21:39:26.000Z
2020-12-03T21:39:26.000Z
Get Hooked/Motor2D/j1Scene.cpp
ch0m5/Get_Hooked
d2ea3259d464ff19e2eab395b100561aa8042802
[ "MIT" ]
1
2018-10-11T07:57:57.000Z
2018-10-11T07:57:57.000Z
Get Hooked/Motor2D/j1Scene.cpp
ch0m5/Get_Hooked
d2ea3259d464ff19e2eab395b100561aa8042802
[ "MIT" ]
null
null
null
#include "Brofiler/Brofiler.h" #include "p2Defs.h" #include "p2Log.h" #include "j1App.h" #include "j1Input.h" #include "j1Textures.h" #include "j1Audio.h" #include "j1Render.h" #include "j1Window.h" #include "j1Map.h" #include "j1FadeScene.h" #include "j1Scene.h" #include "j1Collision.h" #include "j1Timer.h" #include "j1EntityManager.h" #include "Player.h" #include "Enemy.h" #include "Item.h" #include "j1Fonts.h" #include "j1UserInterface.h" #include "Image.h" #include "Text.h" #include "Button.h" #include "ActionBox.h" //Button actions //CHANGE/FIX: Locate somewhere else, having this laying around is quite dirty, but putting them in a header creates wierd problems (Difficulty level: Rick didn't find the issue, and neither did I). void StartGame() { App->fade->FadeToBlack(App->fade->GetDelay(), fade_type::START_GAME); } void GoToSettings() { App->fade->FadeToBlack(App->fade->GetDelay(), fade_type::SETTINGS); } void GoToMenu() { App->win->scale = App->win->origScale; App->fade->FadeToBlack(App->fade->GetDelay(), fade_type::MAIN_MENU); } void GoToCredits() { App->fade->FadeToBlack(App->fade->GetDelay(), fade_type::CREDITS); } void CloseGame() { App->mustShutDown = true; } void SaveGame() { if (App->scene->loadButton != nullptr) { App->scene->loadButton->Enable(); } App->SaveGame(); } void LoadGame() { if (App->fade->GetStep() == fade_step::NONE) App->fade->FadeToBlack(App->fade->GetDelay(), fade_type::LOAD_GAME); } void SwitchValue(bool* value) //IMPROVE: This should be the function that a CheckBox calls with it's own saved value as the parameter { *value = !*value; } void OpenSettings() { App->scene->gamePaused = true; if (App->scene->settingsWindow != nullptr) App->scene->settingsWindow->Activate(); } void CloseSettings() { App->scene->gamePaused = false; if (App->scene->settingsWindow != nullptr) App->scene->settingsWindow->Deactivate(); } void OpenWebpage() { ShellExecuteA(NULL, "open", "https://ch0m5.github.io/Get_Hooked/", NULL , NULL , SW_SHOWNORMAL); } // ------------------------------------------------------------------------------ //Constructor j1Scene::j1Scene() : j1Module() { name.create("scene"); loading = true; button = new SDL_Rect[4]; //CHANGE/FIX: Could be improved, probably with a list of structs that have an id. checkButton = new SDL_Rect[3]; exit = new SDL_Rect[4]; shutDown = new SDL_Rect[4]; settings = new SDL_Rect[4]; back = new SDL_Rect[4]; webpage = new SDL_Rect[4]; } // Destructor j1Scene::~j1Scene() { RELEASE_ARRAY(button); RELEASE_ARRAY(checkButton); RELEASE_ARRAY(exit); RELEASE_ARRAY(shutDown); RELEASE_ARRAY(settings); RELEASE_ARRAY(back); RELEASE_ARRAY(webpage); } // Called before render is available bool j1Scene::Awake(pugi::xml_node& config) { LOG("Loading Scene"); bool ret = true; cameraSpeed.x = config.child("cameraSpeed").attribute("x").as_float(); cameraSpeed.y = config.child("cameraSpeed").attribute("y").as_float(); debugMode = config.child("debugMode").attribute("value").as_bool(); scene = (scene_type)config.child("scene").attribute("start").as_int(); pugi::xml_node item; for (item = config.child("maps").first_child(); item != NULL; item = item.next_sibling()) { maps.add(item.attribute("file").as_string()); } menuBackgroundTex.create(config.child("ui").child("menuBackground").child_value()); //CHANGE/FIX: Improvised, not well done //UI Data Awake item = config.child("ui").child("panel"); panel = { item.attribute("x").as_int(), item.attribute("y").as_int(), item.attribute("w").as_int(), item.attribute("h").as_int() }; item = config.child("ui").child("window"); window = { item.attribute("x").as_int(), item.attribute("y").as_int(), item.attribute("w").as_int(), item.attribute("h").as_int() }; RegisterButtonData(config.child("ui").child("button"), button); item = config.child("ui").child("checkButton"); checkButton[0] = { item.attribute("x1").as_int(), item.attribute("y1").as_int(), item.attribute("w1").as_int(), item.attribute("h1").as_int() }; checkButton[1] = { item.attribute("x2").as_int(), item.attribute("y2").as_int(), item.attribute("w2").as_int(), item.attribute("h2").as_int() }; checkButton[2] = { item.attribute("x3").as_int(), item.attribute("y3").as_int(), item.attribute("w3").as_int(), item.attribute("h3").as_int() }; RegisterButtonData(config.child("ui").child("exit"), exit); RegisterButtonData(config.child("ui").child("shutDown"), shutDown); RegisterButtonData(config.child("ui").child("settings"), settings); RegisterButtonData(config.child("ui").child("back"), back); RegisterButtonData(config.child("ui").child("webpage"), webpage); item = config.child("ui").child("healthBar"); healthBar = { item.attribute("x").as_int(), item.attribute("y").as_int(), item.attribute("w").as_int(), item.attribute("h").as_int() }; item = config.child("ui").child("healthChunck"); healthChunck = { item.attribute("x").as_int(), item.attribute("y").as_int(), item.attribute("w").as_int(), item.attribute("h").as_int() }; item = config.child("ui").child("sliderBar"); sliderBar = { item.attribute("x").as_int(), item.attribute("y").as_int(), item.attribute("w").as_int(), item.attribute("h").as_int() }; item = config.child("ui").child("sliderGrab"); sliderGrab = { item.attribute("x").as_int(), item.attribute("y").as_int(), item.attribute("w").as_int(), item.attribute("h").as_int() }; return ret; } void j1Scene::RegisterButtonData(pugi::xml_node& node, SDL_Rect* button) { button[0] = { node.attribute("x1").as_int(), node.attribute("y1").as_int(), node.attribute("w1").as_int(), node.attribute("h1").as_int() }; button[1] = { node.attribute("x2").as_int(), node.attribute("y2").as_int(), node.attribute("w2").as_int(), node.attribute("h2").as_int() }; button[2] = { node.attribute("x3").as_int(), node.attribute("y3").as_int(), node.attribute("w3").as_int(), node.attribute("h3").as_int() }; button[3] = { node.attribute("x4").as_int(), node.attribute("y4").as_int(), node.attribute("w4").as_int(), node.attribute("h4").as_int() }; } // Called before the first frame bool j1Scene::Start() { bool ret = true; pugi::xml_document doc; App->LoadConfig(doc); pugi::xml_node config = doc.child("config"); UIElement* parent; _TTF_Font* gameText = App->font->textFont; //IMPROVE: All the stuff "skipped" by cases, could be cleaner overall pugi::xml_document saveDoc; pugi::xml_parse_result result = saveDoc.load_file("save_game.xml"); switch (scene) { //CHANGE/FIX: All of these should be functions case scene_type::MAIN_MENU: //CHANGE/FIX: Lots of magic numbers and hardcoding, but making it based on the screen size gives a lot of problems (TYPE/int) // iPoint screenCenter = { App->win->GetWindowSize().w / (2 * App->win->GetScale()), App->win->GetWindowSize().h / (2 * App->win->GetScale()) }; App->entityManager->player->active = false; backgroundTexPtr = App->tex->Load(menuBackgroundTex.GetString()); App->ui->CreateImage({ 1024 / 4, 768 / 4 }, { 0, 0, 0, 0 }, backgroundTexPtr, false); App->ui->CreateText({ 1024 / 4, 100 }, "Get Hooked", DEFAULT_COLOR, App->font->titleFont, false); parent = App->ui->CreateActionBox(&StartGame, { 1024 / 4, 180 }, button, NULL, false); App->ui->CreateText(DEFAULT_POINT, "Start", DEFAULT_COLOR, gameText, false, parent); parent = App->ui->CreateActionBox(&LoadGame, { 1024 / 4, 225 }, button, NULL, false); App->ui->CreateText(DEFAULT_POINT, "Continue", DEFAULT_COLOR, gameText, false, parent); loadButton = (ActionBox<void>*)parent; parent = App->ui->CreateActionBox(&GoToSettings, { 1024 / 4, 270 }, button, NULL, false); App->ui->CreateText(DEFAULT_POINT, "Settings", DEFAULT_COLOR, gameText, false, parent); parent = App->ui->CreateActionBox(&GoToCredits, { 1024 / 4, 315 }, button, NULL, false); App->ui->CreateText(DEFAULT_POINT, "Credits", DEFAULT_COLOR, gameText, false, parent); App->ui->CreateActionBox(&CloseGame, { 20, 20 }, shutDown, NULL, false); App->ui->CreateActionBox(&OpenWebpage, { 55, 20 }, webpage, NULL, false); if (result == NULL) { loadButton->Disable(); } App->audio->PlayMusic(App->audio->musicMainMenu.GetString()); break; case scene_type::SETTINGS: App->entityManager->player->active = false; backgroundTexPtr = App->tex->Load(menuBackgroundTex.GetString()); App->ui->CreateImage({ 1024 / 4, 768 / 4 }, { 0, 0, 0, 0 }, backgroundTexPtr, false); parent = App->ui->CreateImage({ 1024 / 4, 200 }, window, NULL, false); App->ui->CreateActionBox(&GoToMenu, { 353, 59 }, back, NULL, false, parent); App->ui->CreateText({ 1024 / 4, 58 }, "Settings", DEFAULT_COLOR, gameText, false, parent); App->ui->CreateActionBox(&CloseGame, { 20, 20 }, shutDown, NULL, false); CreateVolumeSliders(); //App->ui->CreateImage({ 1024 / 4, 300 }, panel, NULL, false); break; case scene_type::CREDITS: App->entityManager->player->active = false; backgroundTexPtr = App->tex->Load(menuBackgroundTex.GetString()); App->ui->CreateImage({ 1024 / 4, 768 / 4 }, { 0, 0, 0, 0 }, backgroundTexPtr, false); parent = App->ui->CreateImage({ 1024 / 4, 200 }, window, NULL, false); App->ui->CreateText({ 1024 / 4, 58 }, "Credits", DEFAULT_COLOR, gameText, false, parent); //CHANGE/FIX: Implement line jumping, this is bad SetupCredits(parent); App->ui->CreateActionBox(&GoToMenu, { 353, 59 }, back, NULL, false, parent); App->ui->CreateActionBox(&CloseGame, { 20, 20 }, shutDown, NULL, false); break; case scene_type::LEVEL_1: App->map->Load(maps.At(0)->data.GetString()); playerStart = { 608, 250 }; //start = App->map->data.checkpoints.start->data; //CHANGE/FIX: Get points close to the ground playerFinish = { 500, 500 }; //finish = App->map->data.checkpoints.end->data; SetupLevel(result, config); App->audio->PlayMusic(App->audio->musicMap1.GetString()); break; case scene_type::LEVEL_2: App->map->Load(maps.At(1)->data.GetString()); playerStart = { 720, -400 }; //start = App->map->data.checkpoints.start->data; playerFinish = { 500, 500 }; //finish = App->map->data.checkpoints.end->data; SetupLevel(result, config); App->audio->PlayMusic(App->audio->musicMap2.GetString()); break; /*case scene_type::LEVEL_3: App->map->Load(mapList.At(2)->data.name.GetString()); break; case scene_type::LEVEL_4: break; case scene_type::LEVEL_5: break;*/ default: ret = false; } App->audio->SetMusicVolume(); return ret; } void j1Scene::SetupCredits(UIElement* window) //CHANGE/FIX: Would be a lot better to have a block of text that cuts on set edges { App->ui->CreateText({ 1024 / 4, 88 }, "MIT License", DEFAULT_COLOR, NULL, false); App->ui->CreateText({ 1024 / 4, 100 }, "Copyright (c) 2018 ch0m5", DEFAULT_COLOR, NULL, false); //App->ui->CreateText({ 1024 / 4, 112 }, "nothing", DEFAULT_COLOR, NULL, false, window); App->ui->CreateText({ 1024 / 4, 124 }, "The software is provided <as is>,", DEFAULT_COLOR, NULL, false); App->ui->CreateText({ 1024 / 4, 136 }, "without warranty of any kind,", DEFAULT_COLOR, NULL, false); App->ui->CreateText({ 1024 / 4, 148 }, "express or implied, including", DEFAULT_COLOR, NULL, false); App->ui->CreateText({ 1024 / 4, 160 }, "but not limited to the warranties", DEFAULT_COLOR, NULL, false); App->ui->CreateText({ 1024 / 4, 172 }, "of merchantability, fitness for a", DEFAULT_COLOR, NULL, false); App->ui->CreateText({ 1024 / 4, 184 }, "particular purpose and", DEFAULT_COLOR, NULL, false); App->ui->CreateText({ 1024 / 4, 196 }, "noninfringement in no event shall", DEFAULT_COLOR, NULL, false); App->ui->CreateText({ 1024 / 4, 208 }, "the authors or copyright holders be", DEFAULT_COLOR, NULL, false); App->ui->CreateText({ 1024 / 4, 220 }, "liable for any claim, damages or", DEFAULT_COLOR, NULL, false); App->ui->CreateText({ 1024 / 4, 232 }, "other liability, whether in an action", DEFAULT_COLOR, NULL, false); App->ui->CreateText({ 1024 / 4, 244 }, "of contract, tort ot otherwise,", DEFAULT_COLOR, NULL, false); App->ui->CreateText({ 1024 / 4, 256 }, "arising from, out of or in connection", DEFAULT_COLOR, NULL, false); App->ui->CreateText({ 1024 / 4, 268 }, "with the software or the use or", DEFAULT_COLOR, NULL, false); App->ui->CreateText({ 1024 / 4, 280 }, "other dealings in the software.", DEFAULT_COLOR, NULL, false); //App->ui->CreateText({ 1024 / 4, 292 }, "nothing", DEFAULT_COLOR, NULL, false, window); App->ui->CreateText({ 1024 / 4, 306 }, "Made by:", DEFAULT_COLOR, NULL, false); App->ui->CreateText({ 1024 / 4, 318 }, "Carles Homs Puchal", DEFAULT_COLOR, NULL, false); /* App->ui->CreateText({ 1024 / 4, 292 }, "software.", DEFAULT_COLOR, NULL, false, window); App->ui->CreateText({ 1024 / 4, 304 }, "an action of contract, tort or otherwise, arising from,", DEFAULT_COLOR, NULL, false, window); App->ui->CreateText({ 1024 / 4, 316 }, "out of or in connection with the software or the use or", DEFAULT_COLOR, NULL, false, window); App->ui->CreateText({ 1024 / 4, 316 }, "other dealings in the software.", DEFAULT_COLOR, NULL, false, window);*/ } void j1Scene::CreateVolumeSliders() { _TTF_Font* gameText = App->font->textFont; UIElement* parent; Image* barPtr; Image* grabPtr; parent = App->ui->CreateImage({ 1024 / 4, 100 }, panel, NULL, false); App->ui->CreateText(DEFAULT_POINT, "Master Volume", DEFAULT_COLOR, gameText, false, parent); parent = App->ui->CreateImage({ 1024 / 4, 135 }, sliderBar, NULL, false); masterSlider = App->ui->CreateImage({ 1024 / 4, 135 }, sliderGrab, NULL, true); barPtr = (Image*)parent; grabPtr = (Image*)masterSlider; grabPtr->SetSlider(barPtr->GetPosition().x, barPtr->GetPosition().x + barPtr->GetSize().x, App->audio->GetMasterVolume()); parent = App->ui->CreateImage({ 1024 / 4, 170 }, panel, NULL, false); App->ui->CreateText(DEFAULT_POINT, "Music Volume", DEFAULT_COLOR, gameText, false, parent); parent = App->ui->CreateImage({ 1024 / 4, 205 }, sliderBar, NULL, false); musicSlider = App->ui->CreateImage({ 1024 / 4, 205 }, sliderGrab, NULL, true); barPtr = (Image*)parent; grabPtr = (Image*)musicSlider; grabPtr->SetSlider(barPtr->GetPosition().x, barPtr->GetPosition().x + barPtr->GetSize().x, App->audio->GetMusicVolume()); parent = App->ui->CreateImage({ 1024 / 4, 240 }, panel, NULL, false); App->ui->CreateText(DEFAULT_POINT, "SFX Volume", DEFAULT_COLOR, gameText, false, parent); parent = App->ui->CreateImage({ 1024 / 4, 275 }, sliderBar, NULL, false); sfxSlider = App->ui->CreateImage({ 1024 / 4, 275 }, sliderGrab, NULL, true); barPtr = (Image*)parent; grabPtr = (Image*)sfxSlider; grabPtr->SetSlider(barPtr->GetPosition().x, barPtr->GetPosition().x + barPtr->GetSize().x, App->audio->GetSfxVolume()); } void j1Scene::SetupLevel(pugi::xml_parse_result& result, pugi::xml_node& config) { UIElement* parent; _TTF_Font* gameText = App->font->textFont; std::string str; p2SString p2Str; App->entityManager->player->SetSpawn(playerStart); App->entityManager->player->active = true; SpawnEntities(scene, config); App->ui->CreateImage({ 390, 35 }, healthBar, NULL, false); App->ui->CreateActionBox(&OpenSettings, { 20, 20 }, settings, NULL, false); str = std::to_string(App->entityManager->player->GetScore()); p2Str.create(" %s", str.c_str()); //CHANGE/FIX: I should add some "reference point" that depends on parent, adding spaces is dirty parent = App->ui->CreateImage({ 150, 25 }, panel, NULL, false); App->ui->CreateText(DEFAULT_POINT, "Score ", DEFAULT_COLOR, gameText, false, parent); score = App->ui->CreateText(DEFAULT_POINT, p2Str.GetString(), DEFAULT_COLOR, gameText, false, parent); str = std::to_string(App->entityManager->player->GetRetry()); p2Str.create(" %s", str.c_str()); parent = App->ui->CreateImage({ 150, 60 }, panel, NULL, false); App->ui->CreateText(DEFAULT_POINT, "Lifes x ", DEFAULT_COLOR, gameText, false, parent); retry = App->ui->CreateText(DEFAULT_POINT, p2Str.GetString(), DEFAULT_COLOR, gameText, false, parent); parent = App->ui->CreateImage({ 150, 95 }, panel, NULL, false); timerText = App->ui->CreateText(DEFAULT_POINT, "0", DEFAULT_COLOR, gameText, false, parent); settingsWindow = App->ui->CreateImage({ 1024 / 4, 200 }, window, NULL, false); App->ui->CreateText({ 1024 / 4, 58 }, "Settings", DEFAULT_COLOR, gameText, false, settingsWindow); App->ui->CreateActionBox(&GoToMenu, { 153, 59 }, back, NULL, false, settingsWindow); App->ui->CreateActionBox(&CloseSettings, { 353, 59 }, exit, NULL, false, settingsWindow); App->ui->CreateActionBox(&SaveGame, { 1024 / 4, 100 }, button, NULL, false, settingsWindow); App->ui->CreateText({ 1024 / 4, 100 }, "Save", DEFAULT_COLOR, gameText, false, settingsWindow); loadButton = (ActionBox<void>*)App->ui->CreateActionBox(&LoadGame, { 1024 / 4, 140 }, button, NULL, false, settingsWindow); App->ui->CreateText({ 1024 / 4, 140 }, "Load", DEFAULT_COLOR, gameText, false, settingsWindow); //Volume widgets Image* barPtr; Image* grabPtr; parent = App->ui->CreateImage({ 1024 / 4, 180 }, panel, NULL, false, settingsWindow); App->ui->CreateText({ 1024 / 4, 180 }, "Master Volume", DEFAULT_COLOR, gameText, false, settingsWindow); parent = App->ui->CreateImage({ 1024 / 4, 205 }, sliderBar, NULL, false, settingsWindow); masterSlider = App->ui->CreateImage({ 1024 / 4, 205 }, sliderGrab, NULL, true, settingsWindow); barPtr = (Image*)parent; grabPtr = (Image*)masterSlider; grabPtr->SetSlider(barPtr->GetPosition().x, barPtr->GetPosition().x + barPtr->GetSize().x, App->audio->GetMasterVolume()); parent = App->ui->CreateImage({ 1024 / 4, 235 }, panel, NULL, false, settingsWindow); App->ui->CreateText({ 1024 / 4, 235 }, "Music Volume", DEFAULT_COLOR, gameText, false, settingsWindow); parent = App->ui->CreateImage({ 1024 / 4, 255 }, sliderBar, NULL, false, settingsWindow); musicSlider = App->ui->CreateImage({ 1024 / 4, 255 }, sliderGrab, NULL, true, settingsWindow); barPtr = (Image*)parent; grabPtr = (Image*)musicSlider; grabPtr->SetSlider(barPtr->GetPosition().x, barPtr->GetPosition().x + barPtr->GetSize().x, App->audio->GetMusicVolume()); parent = App->ui->CreateImage({ 1024 / 4, 285 }, panel, NULL, false, settingsWindow); App->ui->CreateText({ 1024 / 4, 285 }, "SFX Volume", DEFAULT_COLOR, gameText, false, settingsWindow); parent = App->ui->CreateImage({ 1024 / 4, 305 }, sliderBar, NULL, false, settingsWindow); sfxSlider = App->ui->CreateImage({ 1024 / 4, 305 }, sliderGrab, NULL, true, settingsWindow); barPtr = (Image*)parent; grabPtr = (Image*)sfxSlider; grabPtr->SetSlider(barPtr->GetPosition().x, barPtr->GetPosition().x + barPtr->GetSize().x, App->audio->GetSfxVolume()); if (result == NULL) { loadButton->Disable(); } settingsWindow->Deactivate(); levelTimer.Start(); } void j1Scene::HealthToUI(int life) { int i = 0; if (i < life) { //CHANGE/FIX: A loop iteration is obvious, yet "ilegal int to const TYPE" won't let me, debug and fix health[0] = (App->ui->CreateImage({ 340, 35 }, healthChunck, NULL, false)); i++; } if (i < life) { health[1] = (App->ui->CreateImage({ 390, 35 }, healthChunck, NULL, false)); i++; } if (i < life) { health[2] = (App->ui->CreateImage({ 440, 35 }, healthChunck, NULL, false)); i++; } playerLife = i; } void j1Scene::HurtUI() { App->ui->DestroyElement(health[playerLife - 1]); //CHANGE/FIX: Really wierd implementation, but a list created problems health[playerLife - 1] = nullptr; playerLife--; }; // Called each loop iteration bool j1Scene::PreUpdate() //IMPROVE: Full debug input here? { BROFILER_CATEGORY("Module Scene PreUpdate", Profiler::Color::DarkOrange); if (App->fade->GetStep() == fade_step::NONE) { if (debugMode == true) { DebugInput(); // Check debug input } if (App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN && scene > scene_type::CREDITS) { if (settingsWindow->active == false) { App->scene->gamePaused = true; App->scene->settingsWindow->Activate(); } else { App->scene->gamePaused = false; App->scene->settingsWindow->Deactivate(); } } if (scene > scene_type::CREDITS || scene == scene_type::SETTINGS) { Image* sliderImg; if (masterSlider != nullptr) { sliderImg = (Image*)masterSlider; sliderImg->SliderToValue(); sliderImg->LimitSlide(); } if (musicSlider != nullptr) { sliderImg = (Image*)musicSlider; sliderImg->SliderToValue(); sliderImg->LimitSlide(); } if (sfxSlider != nullptr) { sliderImg = (Image*)sfxSlider; sliderImg->SliderToValue(); sliderImg->LimitSlide(); } } } if (scene > scene_type::CREDITS) { std::string str; p2SString p2Str; str = std::to_string((int)levelTimer.ReadSec()); p2Str.create("%s", str.c_str()); if (timerText != nullptr) { Text* timerPtr = (Text*)timerText; timerPtr->ChangeContent(p2Str.GetString()); } } return true; } // Called each frame (logic) bool j1Scene::UpdateTick(float dt) { BROFILER_CATEGORY("Module Scene UpdateTick", Profiler::Color::OrangeRed); AudioInput(); if (debugMode == true && scene > scene_type::CREDITS) { CameraInput(dt); } return true; } // Called each loop iteration (graphic) bool j1Scene::Update() { BROFILER_CATEGORY("Module Scene Update", Profiler::Color::Orange); if (App->entityManager->player != nullptr && App->entityManager->player->CameraFree() == false) { LimitCameraPos(App->entityManager->player->GetPosition()); // Limit camera position } // All blitting in order App->map->Draw(); App->entityManager->Draw(); App->collision->Draw(); App->ui->Draw(); return true; } // Called each loop iteration bool j1Scene::PostUpdate() { BROFILER_CATEGORY("Module Scene PostUpdate", Profiler::Color::DarkOrange); bool ret = true; // @Carles if (App->fade->GetStep() == fade_step::FULLY_FADED) { // When game is fully faded, start game load and disable all entities for the next frame, then enable them. App->entityManager->active = false; // This prevents the entities to use the massive dt value of the after-load frame on their calculations. App->ui->active = false; switch (App->fade->GetType()) { //CHANGE/FIX: This should be a function case fade_type::MAIN_MENU: if (backgroundTexPtr != nullptr) { App->tex->UnLoad(backgroundTexPtr); backgroundTexPtr = nullptr; } App->ui->CleanUp(); ChangeScene(scene_type::MAIN_MENU); break; case fade_type::SETTINGS: if (backgroundTexPtr != nullptr) { App->tex->UnLoad(backgroundTexPtr); backgroundTexPtr = nullptr; } App->ui->CleanUp(); ChangeScene(scene_type::SETTINGS); break; case fade_type::CREDITS: if (backgroundTexPtr != nullptr) { App->tex->UnLoad(backgroundTexPtr); backgroundTexPtr = nullptr; } App->ui->CleanUp(); ChangeScene(scene_type::CREDITS); break; case fade_type::START_GAME: if (backgroundTexPtr != nullptr) { App->tex->UnLoad(backgroundTexPtr); backgroundTexPtr = nullptr; } if (firstStart) { App->entityManager->player->retryLeft = 2; firstStart = false; } else { //App->entityManager->player->ResetRetry(); App->entityManager->player->EraseScore(); } App->ui->CleanUp(); ChangeScene(scene_type::LEVEL_1); break; case fade_type::LOAD_GAME: if (backgroundTexPtr != nullptr) { App->tex->UnLoad(backgroundTexPtr); backgroundTexPtr = nullptr; } App->ui->CleanUp(); App->LoadGame(); break; case fade_type::NEXT_LEVEL: NextLevel(); break; case fade_type::RESTART_LEVEL: App->entityManager->player->ResetScore(); RestartLevel(); break; case fade_type::RESTART_GAME: App->entityManager->player->ResetRetry(); App->entityManager->player->EraseScore(); ChangeScene(scene_type::LEVEL_1); break; case fade_type::LEVEL_1: scene = scene_type::LEVEL_1; CleanUp(); App->entityManager->player->CleanUp(); App->entityManager->CleanEntities(); Start(); App->entityManager->player->LoadStart(); break; case fade_type::LEVEL_2: scene = scene_type::LEVEL_2; CleanUp(); App->entityManager->player->CleanUp(); App->entityManager->CleanEntities(); Start(); App->entityManager->player->LoadStart(); break; default: break; } loading = true; } else if (loading) { App->entityManager->active = true; loading = false; } else if (App->fade->GetStep() == fade_step::UNFADING && App->fade->GetType() == fade_type::LOAD_GAME) { //CHANGE/FIX: God knows why a wall collision resets the player Y pos. but this workaround fixes it for now. App->fade->ResetType(); App->LoadGame(); } if (App->ui->active == false && App->fade->GetStep() == fade_step::NONE) { //CHANGE/FIX: Avoids bugs, but could be improved App->fade->ResetType(); App->ui->active = true; } return ret; } // Called before quitting bool j1Scene::CleanUp() //IMPROVE: When changing scene a lot of new memory is allocated. Memory leaks? { LOG("Freeing scene"); App->map->CleanUp(); App->collision->CleanUp(); health[0] = health[1] = health[2] = nullptr; if (settingsWindow != nullptr) { App->ui->DestroyElement(settingsWindow); settingsWindow = nullptr; } /*if (score != nullptr) { App->ui->DestroyElement(score); score = nullptr; }*/ timerText = nullptr; score = nullptr; retry = nullptr; loadButton = nullptr; masterSlider = nullptr; musicSlider = nullptr; sfxSlider = nullptr; return true; } // Save and Load bool j1Scene::Load(pugi::xml_node& config) { bool ret = true; scene_type current = scene; pugi::xml_node tmpNode; scene = (scene_type)config.child("scene").attribute("current").as_int(); if (saveFix == false) { CleanUp(); App->entityManager->player->CleanUp(); App->entityManager->CleanEntities(); Start(); App->entityManager->player->LoadStart(); saveFix = true; } else { saveFix = false; } return ret; } bool j1Scene::Save(pugi::xml_node& config) const { bool ret = true; pugi::xml_node tmpNode; tmpNode = config.append_child("scene"); tmpNode.append_attribute("current") = (int)scene; return ret; } void j1Scene::DebugInput() { if (scene > scene_type::CREDITS) { if (App->fade->GetStep() == fade_step::NONE) { if (App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN) { App->fade->FadeToBlack(App->fade->GetDelay(), fade_type::RESTART_GAME); } if (App->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN) { App->fade->FadeToBlack(App->fade->GetDelay(), fade_type::RESTART_LEVEL); } if (App->input->GetKey(SDL_SCANCODE_F3) == KEY_DOWN) { App->fade->FadeToBlack(App->fade->GetDelay(), fade_type::NEXT_LEVEL); } if (App->input->GetKey(SDL_SCANCODE_P) == KEY_DOWN) { gamePaused = !gamePaused; } } if (App->input->GetKey(SDL_SCANCODE_F5) == KEY_DOWN && App->entityManager->player->IsDead() == false) { // Save game if (loadButton != nullptr) { loadButton->Enable(); } App->SaveGame(); } if (App->input->GetKey(SDL_SCANCODE_F6) == KEY_DOWN && App->entityManager->player->IsDead() == false) { // Load game if (App->fade->GetStep() == fade_step::NONE) App->fade->FadeToBlack(App->fade->GetDelay(), fade_type::LOAD_GAME); } if (App->input->GetKey(SDL_SCANCODE_F8) == KEY_DOWN && App->ui->mustDebugDraw == false) { // UI logic drawing App->ui->mustDebugDraw = true; } else if (App->input->GetKey(SDL_SCANCODE_F8) == KEY_DOWN && App->ui->mustDebugDraw == true) { App->ui->mustDebugDraw = false; } if (App->input->GetKey(SDL_SCANCODE_F9) == KEY_DOWN && App->collision->mustDebugDraw == false) { // Logic drawing App->collision->mustDebugDraw = true; } else if (App->input->GetKey(SDL_SCANCODE_F9) == KEY_DOWN && App->collision->mustDebugDraw == true) { App->collision->mustDebugDraw = false; } // Change scale if (App->input->GetKey(SDL_SCANCODE_1) == KEY_DOWN) { App->win->scale = 1; } if (App->input->GetKey(SDL_SCANCODE_2) == KEY_DOWN) { App->win->scale = 2; } if (App->input->GetKey(SDL_SCANCODE_3) == KEY_DOWN) { App->win->scale = 3; } if (App->input->GetKey(SDL_SCANCODE_4) == KEY_DOWN) { App->win->scale = 4; } if (App->input->GetKey(SDL_SCANCODE_5) == KEY_DOWN) { App->win->scale = 5; } } else { if (App->input->GetKey(SDL_SCANCODE_F8) == KEY_DOWN && App->ui->mustDebugDraw == false) { // UI logic drawing App->ui->mustDebugDraw = true; } else if (App->input->GetKey(SDL_SCANCODE_F8) == KEY_DOWN && App->ui->mustDebugDraw == true) { App->ui->mustDebugDraw = false; } } } void j1Scene::CameraInput(float dt) // @Carles { if (App->input->GetKey(SDL_SCANCODE_LSHIFT) == KEY_IDLE) { if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT) App->render->camera.y += (int)ceil(cameraSpeed.y * dt); if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT) App->render->camera.y -= (int)ceil(cameraSpeed.y * dt); if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT) App->render->camera.x += (int)ceil(cameraSpeed.x * dt); if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT) App->render->camera.x -= (int)ceil(cameraSpeed.x * dt); } } void j1Scene::AudioInput() // @Carles { if (App->input->GetKey(SDL_SCANCODE_LSHIFT) == KEY_REPEAT) { if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT && App->audio->masterVolume < 100) App->audio->masterVolume++; if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT && App->audio->masterVolume > 0) App->audio->masterVolume--; if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT && App->audio->musicVolume > 0) App->audio->musicVolume--; if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT && App->audio->musicVolume < 100) App->audio->musicVolume++; App->audio->SetMusicVolume(); App->audio->SetSfxVolume(); } } void j1Scene::NextLevel() { scene = (scene_type)((int)scene + 1); if (scene == scene_type::MAX_SCENES) { //Restart Game App->entityManager->player->ResetRetry(); App->entityManager->player->EraseScore(); ChangeScene(scene_type::MAIN_MENU); } else { ChangeScene(scene); } } void j1Scene::RestartLevel() //IMPROVE: Only reload entities, not the full map { CleanUp(); App->entityManager->player->CleanUp(); App->entityManager->CleanEntities(); Start(); App->entityManager->player->LifeToStart(); //CHANGE/FIX: A little bit buggy currently, let's just reset the HP to max for now (also it makes the game easier, which is appreciated) App->entityManager->player->Start(); //OLD /*App->entityManager->player->DeadReset(); App->entityManager->RestartEnemies(); App->entityManager->player->CleanUp(); App->entityManager->player->LifeToStart(); App->entityManager->player->Start();*/ } void j1Scene::ChangeScene(scene_type scene) { this->scene = scene; CleanUp(); App->entityManager->player->CleanUp(); App->entityManager->CleanEntities(); Start(); App->entityManager->player->LifeToMax(); App->entityManager->player->Start(); } SDL_Rect j1Scene::LimitCameraPos(fPoint playerPos) { if (App->render->camera.x < (int)-(playerPos.x * App->win->GetScale() - 350)/* && mapRightLimit is not crossed*/) { //left // Improve: Map limits & eliminate magic numbers App->render->camera.x = (int)-(playerPos.x * App->win->GetScale() - 350); } else if (App->render->camera.x > (int)-(playerPos.x * App->win->GetScale() - 500)/* && mapLeftLimit is not crossed*/) { //right App->render->camera.x = (int)-(playerPos.x * App->win->GetScale() - 500); } if (App->render->camera.y < (int)-(playerPos.y * App->win->GetScale() - 300)/* && mapRightLimit is not crossed*/) { //left App->render->camera.y = (int)-(playerPos.y * App->win->GetScale() - 300); } else if (App->render->camera.y > (int)-(playerPos.y * App->win->GetScale() - 400)/* && mapLeftLimit is not crossed*/) { //right App->render->camera.y = (int)-(playerPos.y * App->win->GetScale() - 400); } return App->render->camera; } bool j1Scene::SpawnEntities(scene_type level, pugi::xml_node& config) { bool ret = true; pugi::xml_node spawns = config.child("scene").child("maps"); pugi::xml_node entities = config.child("entityManager").child("entities"); switch (level) { case scene_type::LEVEL_1: spawns = spawns.child("level_1").child("spawns"); break; case scene_type::LEVEL_2: spawns = spawns.child("level_2").child("spawns"); break; default: return false; } SpawnLevelEntities(entities, spawns); return ret; } bool j1Scene::SpawnLevelEntities(pugi::xml_node& entitiesNode, pugi::xml_node& spawns) { bool ret = true; pugi::xml_node lastChild; Enemy* enemyPtr; lastChild = spawns.child("enemiesEnd"); for (pugi::xml_node spawnPoints = spawns.first_child(); spawnPoints != lastChild; spawnPoints = spawnPoints.next_sibling()) { enemyPtr = (Enemy*)App->entityManager->CreateEntity((entity_type)spawnPoints.attribute("type").as_int(), entitiesNode); enemyPtr->Spawn(spawnPoints.attribute("xSpawn").as_int(), spawnPoints.attribute("ySpawn").as_int()); } Item* itemPtr; lastChild = spawns.child("itemsEnd"); for (pugi::xml_node spawnPoints = spawns.child("enemiesEnd").next_sibling(); spawnPoints != lastChild; spawnPoints = spawnPoints.next_sibling()) { itemPtr = (Item*)App->entityManager->CreateEntity((entity_type)spawnPoints.attribute("type").as_int(), entitiesNode); itemPtr->Spawn(spawnPoints.attribute("xSpawn").as_int(), spawnPoints.attribute("ySpawn").as_int()); itemPtr->UpdateHitbox(); } return ret; }
35.432059
214
0.676873
[ "render" ]
cb4498a564612ebc9b2bee7d160c62e13525e75b
48,139
cpp
C++
Source/OpenMotion/Private/FabrikChain.cpp
SaxonRah/OpenMotion
55e57a9a58c81e7ee08099985e529344a6a7d72e
[ "MIT" ]
13
2020-04-13T16:45:45.000Z
2022-02-04T07:36:09.000Z
Source/OpenMotion/Private/FabrikChain.cpp
SaxonRah/OpenMotion
55e57a9a58c81e7ee08099985e529344a6a7d72e
[ "MIT" ]
null
null
null
Source/OpenMotion/Private/FabrikChain.cpp
SaxonRah/OpenMotion
55e57a9a58c81e7ee08099985e529344a6a7d72e
[ "MIT" ]
3
2021-02-22T01:42:20.000Z
2021-07-19T13:32:05.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "FabrikChain.h" #include "FabrikBone.h" #include "FabrikJoint.h" #include "EJointType.h" #include "FabrikUtil.h" #include "FabrikMat3f.h" #include "FabrikStructure.h" #include "OpenMotion.h" UFabrikChain::UFabrikChain(const FObjectInitializer& ObjectInitializer) { SolveDistanceThreshold = 0.1f; MaxIterationAttempts = 20; MinIterationChange = 0.01f; ChainLength = 0; NumBones = 0; FixedBaseLocation = FVector::ZeroVector; FixedBaseMode = true; BaseboneConstraintType = EBoneConstraintType::BCT_None; BaseboneConstraintUV = FVector::ZeroVector; BaseboneRelativeConstraintUV = FVector::ZeroVector; BaseboneRelativeReferenceConstraintUV = FVector::ZeroVector; LastTargetLocation = CreateMaxVector(); ConstraintLineWidth = 2.0f; LastBaseLocation = CreateMaxVector(); CurrentSolveDistance = FloatMax(); ConnectedChainNumber = -1; ConnectedBoneNumber = -1; EmbeddedTarget = FVector::ZeroVector; UseEmbeddedTarget = false; } FVector UFabrikChain::GetBaseLocation() { return Chain[0]->StartLocation; } void UFabrikChain::Init(UFabrikChain* InSource) { // Force copy by value Chain = InSource->CloneIkChain(); FixedBaseLocation = InSource->GetBaseLocation(); LastTargetLocation = InSource->LastTargetLocation; LastBaseLocation = InSource->LastBaseLocation; EmbeddedTarget = InSource->EmbeddedTarget; // Copy the basebone constraint UV if there is one to copy if (InSource->BaseboneConstraintType != EBoneConstraintType::BCT_None) { BaseboneConstraintUV = InSource->BaseboneConstraintUV; BaseboneRelativeConstraintUV = InSource->BaseboneRelativeConstraintUV; } // Native copy by value for primitive members ChainLength = InSource->ChainLength; NumBones = InSource->NumBones; CurrentSolveDistance = InSource->CurrentSolveDistance; ConnectedChainNumber = InSource->ConnectedChainNumber; ConnectedBoneNumber = InSource->ConnectedBoneNumber; BaseboneConstraintType = InSource->BaseboneConstraintType; Name = InSource->Name; ConstraintLineWidth = InSource->ConstraintLineWidth; UseEmbeddedTarget = InSource->UseEmbeddedTarget; } UFabrikChain* UFabrikChain::Init(FName InName) { Name = InName; return this; } void UFabrikChain::AddBone(UFabrikBone* InBone) { // Add the new bone to the end of the ArrayList of bones Chain.Add(InBone); // If this is the basebone... if (NumBones == 0) { // ...then keep a copy of the fixed start location... FixedBaseLocation = InBone->StartLocation; // ...and set the basebone constraint UV to be around the initial bone direction BaseboneConstraintUV = InBone->GetDirectionUV(); } // Increment the number of bones in the chain and update the chain length ++NumBones; UpdateChainLength(); } void UFabrikChain::AddConsecutiveBone(FVector InDirectionUV, float InLength, FColor InColour) { // Validate the direction unit vector - throws an IllegalArgumentException if it has a magnitude of zero UFabrikUtil::ValidateDirectionUV(InDirectionUV); // Validate the length of the bone - throws an IllegalArgumentException if it is not a positive value UFabrikUtil::ValidateLength(InLength); // If we have at least one bone already in the chain... if (NumBones > 0) { // Get the end location of the last bone, which will be used as the start location of the new bone FVector PrevBoneEnd = Chain[NumBones - 1]->EndLocation;// getEndLocation(); // Add a bone to the end of this IK chain // Note: We use a normalised version of the bone direction UFabrikBone* NewBone = NewObject<UFabrikBone>(); FVector DirN = InDirectionUV; DirN.Normalize(); NewBone->Init(PrevBoneEnd, DirN, InLength, InColour); AddBone(NewBone);// new FabrikBone3D(prevBoneEnd, directionUV.normalised(), length, colour)) } else // Attempting to add a relative bone when there is no basebone for it to be relative to? { UE_LOG(OpenMotionLog, Fatal, TEXT("You cannot add the basebone as a consecutive bone as it does not provide a start location. Use the addBone() method instead.")); //throw new RuntimeException("You cannot add the basebone as a consecutive bone as it does not provide a start location. Use the addBone() method instead."); } } void UFabrikChain::AddConsecutiveBone(FVector InDirectionUV, float InLength) { AddConsecutiveBone(InDirectionUV, InLength, FColor()); } void UFabrikChain::AddConsecutiveFreelyRotatingHingedBone(FVector InDirectionUV, float InLength, EJointType InJointType, FVector InHingeRotationAxis) { // Because we aren't constraining this bone to a reference axis within the hinge rotation axis we don't care about the hinge constraint // reference axis (7th param) so we'll just generate an axis perpendicular to the hinge rotation axis and use that. FVector Perp = UFabrikUtil::VectorGenPerpendicularVectorQuick(InHingeRotationAxis); AddConsecutiveHingedBoneC(InDirectionUV, InLength, InJointType, InHingeRotationAxis, 180.0f, 180.0f, Perp, FColor()); } void UFabrikChain::AddConsecutiveFreelyRotatingHingedBoneC(FVector InDirectionUV, float InLength, EJointType InJointType, FVector InHingeRotationAxis, FColor InColour) { // Because we aren't constraining this bone to a reference axis within the hinge rotation axis we don't care about the hinge constraint // reference axis (7th param) so we'll just generate an axis perpendicular to the hinge rotation axis and use that. FVector Perp = UFabrikUtil::VectorGenPerpendicularVectorQuick(InHingeRotationAxis); AddConsecutiveHingedBoneC(InDirectionUV, InLength, InJointType, InHingeRotationAxis, 180.0f, 180.0f, Perp, InColour); } void UFabrikChain::AddConsecutiveHingedBoneC(FVector InDirectionUV, float InLength, EJointType InJointType, FVector InHingeRotationAxis, float InClockwiseDegs, float InAnticlockwiseDegs, FVector InHingeReferenceAxis, FColor InColour) { // Validate the direction and rotation axis unit vectors, and the length of the bone. UFabrikUtil::ValidateDirectionUV(InDirectionUV); UFabrikUtil::ValidateDirectionUV(InHingeRotationAxis); UFabrikUtil::ValidateLength(InLength); // Cannot add a consectuive bone of any kind if the there is no basebone if (NumBones == 0) { UE_LOG(OpenMotionLog, Fatal, TEXT("You must add a basebone before adding a consectutive bone.")); } // Normalise the direction and hinge rotation axis InDirectionUV.Normalize(); InHingeRotationAxis.Normalize(); // Get the end location of the last bone, which will be used as the start location of the new bone FVector PrevBoneEnd = Chain[NumBones - 1]->EndLocation; // Create a bone and set the draw colour... UFabrikBone* Bone = NewObject<UFabrikBone>(); //new FabrikBone3D(prevBoneEnd, directionUV, length); Bone->Init(PrevBoneEnd, InDirectionUV, InLength); Bone->Color = InColour; // ...then create and set up a joint which we'll apply to that bone. UFabrikJoint* Joint = NewObject<UFabrikJoint>(); switch (InJointType) { case EJointType::JT_GlobalHinge :// GLOBAL_HINGE: Joint->SetAsGlobalHinge(InHingeRotationAxis, InClockwiseDegs, InAnticlockwiseDegs, InHingeReferenceAxis); break; case EJointType::JT_LocalHinge: // LOCAL_HINGE: Joint->SetAsLocalHinge(InHingeRotationAxis, InClockwiseDegs, InAnticlockwiseDegs, InHingeReferenceAxis); break; default: UE_LOG(OpenMotionLog, Fatal, TEXT("Hinge joint types may be only JointType.GLOBAL_HINGE or JointType.LOCAL_HINGE.")); } // Set the joint we just set up on the the new bone we just created Bone->Joint = Joint; // etJoint(joint); // Finally, add the bone to this chain AddBone(Bone); } void UFabrikChain::AddConsecutiveHingedBone(FVector InDirectionUV, float InLength, EJointType InJointType, FVector InHingeRotationAxis, float InClockwiseDegs, float InAnticlockwiseDegs, FVector InHingeConstraintReferenceAxis) { AddConsecutiveHingedBoneC(InDirectionUV, InLength, InJointType, InHingeRotationAxis, InClockwiseDegs, InAnticlockwiseDegs, InHingeConstraintReferenceAxis, FColor()); } void UFabrikChain::AddConsecutiveRotorConstrainedBoneC(FVector InBoneDirectionUV, float InBoneLength, float InConstraintAngleDegs, FColor InColor) { // Validate the bone direction and length and that we have a basebone UFabrikUtil::ValidateDirectionUV(InBoneDirectionUV); UFabrikUtil::ValidateLength(InBoneLength); if (NumBones == 0) { UE_LOG(OpenMotionLog, Fatal, TEXT("Add a basebone before attempting to add consectuive bones.")); //throw new RuntimeException("Add a basebone before attempting to add consectuive bones."); } // Create the bone starting at the end of the previous bone, set its direction, constraint angle and colour // then add it to the chain. Note: The default joint type of a new FabrikBone3D is JointType.BALL. InBoneDirectionUV.Normalize(); UFabrikBone* Bone = NewObject<UFabrikBone>();// new FabrikBone3D(mChain.get(mNumBones - 1).getEndLocation(), InBoneDirectionUV, InBoneLength, InColor); Bone->Init(Chain[NumBones - 1]->EndLocation, InBoneDirectionUV, InBoneLength, InColor); //## setBallJointConstraintDegs => mRotorConstraintDegs Bone->Joint->RotorConstraintDegs = InConstraintAngleDegs; AddBone(Bone); } void UFabrikChain::AddConsecutiveRotorConstrainedBone(FVector InBoneDirectionUV, float InBoneLength, float InConstraintAngleDegs) { AddConsecutiveRotorConstrainedBoneC(InBoneDirectionUV, InBoneLength, InConstraintAngleDegs, FColor()); } UFabrikBone* UFabrikChain::GetBone(int InBoneNumber) { return Chain[InBoneNumber]; } FVector UFabrikChain::GetEffectorLocation() { return Chain[NumBones - 1]->EndLocation; } float UFabrikChain::GetLiveChainLength() { float length = 0.0f; for (int loop = 0; loop < NumBones; ++loop) { length += Chain[loop]->LiveLength(); } return length; } void UFabrikChain::RemoveBone(int InBoneNumber) { // If the bone number is a bone which exists... if (InBoneNumber < NumBones) { // ...then remove the bone, decrease the bone count and update the chain length. Chain.RemoveAt(InBoneNumber); --NumBones; UpdateChainLength(); } else { UE_LOG(OpenMotionLog, Fatal, TEXT("Bone TODO does not exist to be removed from the chain. Bones are zero indexed.")); //throw new IllegalArgumentException("Bone " + boneNumber + " does not exist to be removed from the chain. Bones are zero indexed."); } } void UFabrikChain::SetRotorBaseboneConstraint(EBoneConstraintType InRotorType, FVector InConstraintAxis, float InAngleDegs) { // Sanity checking if (NumBones == 0) { UE_LOG(OpenMotionLog, Fatal, TEXT("Chain must contain a basebone before we can specify the basebone constraint type.")); // //throw new RuntimeException("Chain must contain a basebone before we can specify the basebone constraint type."); } if (!(InConstraintAxis.Size() > 0.0f)) { UE_LOG(OpenMotionLog, Fatal, TEXT("Constraint axis cannot be zero.")); // //throw new IllegalArgumentException("Constraint axis cannot be zero."); } if (InAngleDegs < 0.0f) { InAngleDegs = 0.0f; } if (InAngleDegs > 180.0f) { InAngleDegs = 180.0f; } if (!(InRotorType == EBoneConstraintType::BCT_GlobalRotor || InRotorType == EBoneConstraintType::BCT_LocalRotor)) { UE_LOG(OpenMotionLog, Fatal, TEXT("The only valid rotor types for this method are GLOBAL_ROTOR and LOCAL_ROTOR.")); // //throw new IllegalArgumentException("The only valid rotor types for this method are GLOBAL_ROTOR and LOCAL_ROTOR."); } // Set the constraint type, axis and angle BaseboneConstraintType = InRotorType; InConstraintAxis.Normalize(); BaseboneConstraintUV = InConstraintAxis;// .normalised(); BaseboneRelativeConstraintUV = BaseboneConstraintUV; // .set(mBaseboneConstraintUV); GetBone(0)->Joint->SetAsBallJoint(InAngleDegs); } void UFabrikChain::SetHingeBaseboneConstraint(EBoneConstraintType InHingeType, FVector InHingeRotationAxis, float InCwConstraintDegs, float InAcwConstraintDegs, FVector InHingeReferenceAxis) { // Sanity checking if (NumBones == 0) { UE_LOG(OpenMotionLog, Fatal, TEXT("Chain must contain a basebone before we can specify the basebone constraint type.")); // throw new RuntimeException("Chain must contain a basebone before we can specify the basebone constraint type."); } if (!(InHingeRotationAxis.Size() > 0.0f)) { UE_LOG(OpenMotionLog, Fatal, TEXT("Hinge rotation axis cannot be zero.")); // throw new IllegalArgumentException("Hinge rotation axis cannot be zero."); } if (!(InHingeReferenceAxis.Size() > 0.0f)) { UE_LOG(OpenMotionLog, Fatal, TEXT("Hinge reference axis cannot be zero.")); //throw new IllegalArgumentException("Hinge reference axis cannot be zero."); } if (!(UFabrikUtil::VectorPerpendicular(InHingeRotationAxis, InHingeReferenceAxis))) // Vec3f.perpendicular(hingeRotationAxis, hingeReferenceAxis))) { UE_LOG(OpenMotionLog, Fatal, TEXT("The hinge reference axis must be in the plane of the hinge rotation axis, that is, they must be perpendicular.")); //throw new IllegalArgumentException("The hinge reference axis must be in the plane of the hinge rotation axis, that is, they must be perpendicular."); } if (!(InHingeType == EBoneConstraintType::BCT_GlobalHinge || InHingeType == EBoneConstraintType::BCT_LocalHinge)) { UE_LOG(OpenMotionLog, Fatal, TEXT("The only valid hinge types for this method are GLOBAL_HINGE and LOCAL_HINGE.")); //throw new IllegalArgumentException("The only valid hinge types for this method are GLOBAL_HINGE and LOCAL_HINGE."); } // Set the constraint type, axis and angle BaseboneConstraintType = InHingeType; BaseboneConstraintUV = InHingeRotationAxis; //.set(hingeRotationAxis.normalised()); BaseboneConstraintUV.Normalize(); UFabrikJoint* Hinge = NewObject<UFabrikJoint>();// new FabrikJoint3D(); if (InHingeType == EBoneConstraintType::BCT_GlobalHinge) // .GLOBAL_HINGE) { Hinge->SetHinge(EJointType::JT_GlobalHinge, InHingeRotationAxis, InCwConstraintDegs, InAcwConstraintDegs, InHingeReferenceAxis); } else { Hinge->SetHinge(EJointType::JT_LocalHinge, InHingeRotationAxis, InCwConstraintDegs, InAcwConstraintDegs, InHingeReferenceAxis); } GetBone(0)->Joint = Hinge;// .setJoint(hinge); } void UFabrikChain::SetFreelyRotatingGlobalHingedBasebone(FVector InHingeRotationAxis) { SetHingeBaseboneConstraint(EBoneConstraintType::BCT_GlobalHinge, InHingeRotationAxis, 180.0f, 180.0f, UFabrikUtil::VectorGenPerpendicularVectorQuick(InHingeRotationAxis)); } void UFabrikChain::SetFreelyRotatingLocalHingedBasebone(FVector InHingeRotationAxis) { SetHingeBaseboneConstraint(EBoneConstraintType::BCT_LocalHinge, InHingeRotationAxis, 180.0f, 180.0f, UFabrikUtil::VectorGenPerpendicularVectorQuick(InHingeRotationAxis)); } void UFabrikChain::SetLocalHingedBasebone(FVector InHingeRotationAxis, float InCwDegs, float InAcwDegs, FVector InHingeReferenceAxis) { SetHingeBaseboneConstraint(EBoneConstraintType::BCT_LocalHinge, InHingeRotationAxis, InCwDegs, InAcwDegs, InHingeReferenceAxis); } void UFabrikChain::SetGlobalHingedBasebone(FVector InHingeRotationAxis, float InCwDegs, float InAcwDegs, FVector InHingeReferenceAxis) { SetHingeBaseboneConstraint(EBoneConstraintType::BCT_GlobalHinge, InHingeRotationAxis, InCwDegs, InAcwDegs, InHingeReferenceAxis); } /** void UFabrikChain::SetBaseboneConstraintUV(FVector InConstraintUV) { if (BaseboneConstraintType == EBoneConstraintType::BCT_None) { UE_LOG(OpenMotionLog, Fatal, TEXT("Specify the basebone constraint type with setBaseboneConstraintTypeCannot specify a basebone constraint when the current constraint type is BaseboneConstraint.NONE.")); //throw new IllegalArgumentException("Specify the basebone constraint type with setBaseboneConstraintTypeCannot specify a basebone constraint when the current constraint type is BaseboneConstraint.NONE."); } // Validate the constraint direction unit vector UFabrikUtil::ValidateDirectionUV(InConstraintUV); // All good? Then normalise the constraint direction and set it InConstraintUV.Normalize(); BaseboneConstraintUV = InConstraintUV; }*/ void UFabrikChain::SetColour(FColor InColour) { for (int Loop = 0; Loop < NumBones; ++Loop) { GetBone(Loop)->Color = InColour; } } float UFabrikChain::SolveForEmbeddedTarget() { if (UseEmbeddedTarget) { return SolveForTarget(EmbeddedTarget); } else { UE_LOG(OpenMotionLog, Fatal, TEXT("This chain does not have embedded targets enabled - enable with setEmbeddedTargetMode(true).")); //throw new RuntimeException("This chain does not have embedded targets enabled - enable with setEmbeddedTargetMode(true)."); return 0; } } /** public float solveForTarget(float targetX, float targetY, float targetZ) { return solveForTarget(new Vec3f(targetX, targetY, targetZ)); }*/ float UFabrikChain::SolveForTarget(FVector InNewTarget) { // If we have both the same target and base location as the last run then do not solve if (UFabrikUtil::VectorApproximatelyEquals(LastTargetLocation, InNewTarget, 0.001f) && // LastTargetLocation.approximatelyEquals(newTarget, 0.001f) && UFabrikUtil::VectorApproximatelyEquals(LastBaseLocation, GetBaseLocation(), 0.001f)) //LastBaseLocation.approximatelyEquals(getBaseLocation(), 0.001f)) { return CurrentSolveDistance; } /*** * NOTE: We must allow the best solution of THIS run to be used for a new target or base location - we cannot * just use the last solution (even if it's better) - because that solution was for a different target / base * location combination and NOT for the current setup. */ // Declare a list of bones to use to store our best solution TArray<UFabrikBone*> BestSolution;// = new ArrayList<FabrikBone3D>(); // We start with a best solve distance that can be easily beaten float BestSolveDistance = FloatMax();// Float.MAX_VALUE; // We'll also keep track of the solve distance from the last pass float LastPassSolveDistance = FloatMax();// Float.MAX_VALUE; // Allow up to our iteration limit attempts at solving the chain float SolveDistance; for (int Loop = 0; Loop < MaxIterationAttempts; ++Loop) { // Solve the chain for this target SolveDistance = SolveIK(InNewTarget); // Did we solve it for distance? If so, update our best distance and best solution, and also // update our last pass solve distance. Note: We will ALWAYS beat our last solve distance on the first run. if (SolveDistance < BestSolveDistance) { BestSolveDistance = SolveDistance; BestSolution = this->CloneIkChain(); // If we are happy that this solution meets our distance requirements then we can exit the loop now if (SolveDistance < SolveDistanceThreshold) { break; } } else // Did not solve to our satisfaction? Okay... { // Did we grind to a halt? If so break out of loop to set the best distance and solution that we have if (FMath::Abs(SolveDistance - LastPassSolveDistance) < MinIterationChange) { //System.out.println("Ground to halt on iteration: " + loop); break; } } // Update the last pass solve distance LastPassSolveDistance = SolveDistance; } // End of loop // Update our solve distance and chain configuration to the best solution found CurrentSolveDistance = BestSolveDistance; Chain = BestSolution; // Update our base and target locations LastBaseLocation = GetBaseLocation(); // .set(getBaseLocation()); LastTargetLocation = InNewTarget; // .set(newTarget); return CurrentSolveDistance; } float UFabrikChain::SolveIK(FVector InTarget) { // Sanity check that there are bones in the chain if (NumBones == 0) { UE_LOG(OpenMotionLog, Fatal, TEXT("It makes no sense to solve an IK chain with zero bones.")); } // ---------- Forward pass from end effector to base ----------- // Loop over all bones in the chain, from the end effector (numBones-1) back to the basebone (0) for (int Loop = NumBones - 1; Loop >= 0; --Loop) { // Get the length of the bone we're working on UFabrikBone* ThisBone = Chain[Loop];// Get(loop); float ThisBoneLength = ThisBone->Length;// (); UFabrikJoint* ThisBoneJoint = ThisBone->Joint;// .getJoint(); EJointType ThisBoneJointType = ThisBone->Joint->JointType;//.getJointType(); // If we are NOT working on the end effector bone if (Loop != NumBones - 1) { // Get the outer-to-inner unit vector of the bone further out FVector OuterBoneOuterToInnerUV = Chain[Loop + 1]->GetDirectionUV();//.getDirectionUV().negated(); OuterBoneOuterToInnerUV = UFabrikUtil::VectorNegated(OuterBoneOuterToInnerUV);// OuterBoneOuterToInnerUV.negated(); // Get the outer-to-inner unit vector of this bone FVector ThisBoneOuterToInnerUV = ThisBone->GetDirectionUV();// .getDirectionUV().negated(); ThisBoneOuterToInnerUV = UFabrikUtil::VectorNegated(ThisBoneOuterToInnerUV); // Get the joint type for this bone and handle constraints on thisBoneInnerToOuterUV if (ThisBoneJointType == EJointType::JT_Ball) { // Constrain to relative angle between this bone and the outer bone if required float AngleBetweenDegs = UFabrikUtil::GetAngleBetweenDegs(OuterBoneOuterToInnerUV, ThisBoneOuterToInnerUV); //Vec3f.getAngleBetweenDegs(OuterBoneOuterToInnerUV, ThisBoneOuterToInnerUV); // getBallJointConstraintDegs => mRotorConstraintDegs float ConstraintAngleDegs = ThisBoneJoint->RotorConstraintDegs;//.getBallJointConstraintDegs(); if (AngleBetweenDegs > ConstraintAngleDegs) { ThisBoneOuterToInnerUV = UFabrikUtil::GetAngleLimitedUnitVectorDegs(ThisBoneOuterToInnerUV, OuterBoneOuterToInnerUV, ConstraintAngleDegs); //Vec3f.getAngleLimitedUnitVectorDegs(ThisBoneOuterToInnerUV, OuterBoneOuterToInnerUV, ConstraintAngleDegs); } } else if (ThisBoneJointType == EJointType::JT_GlobalHinge) { // Project this bone outer-to-inner direction onto the hinge rotation axis // Note: The returned vector is normalised. // getHingeRotationAxis => mRotationAxisUV ThisBoneOuterToInnerUV = UFabrikUtil::ProjectOntoPlane(ThisBoneOuterToInnerUV, ThisBoneJoint->RotationAxisUV); // ThisBoneOuterToInnerUV.projectOntoPlane(ThisBoneJoint.getHingeRotationAxis()); // NOTE: Constraining about the hinge reference axis on this forward pass leads to poor solutions... so we won't. } else if (ThisBoneJointType == EJointType::JT_LocalHinge) { // Not a basebone? Then construct a rotation matrix based on the previous bones inner-to-to-inner direction... UFabrikMat3f* M; // UFabrikMat3f::CreateRotationMatrix(FVector InReferenceDirection) Mat3f M; FVector RelativeHingeRotationAxis; if (Loop > 0) { M = UFabrikMat3f::CreateRotationMatrix(Chain[Loop - 1]->GetDirectionUV());// Mat3f.createRotationMatrix(Chain[Loop - 1]->GetDirectionUV()); // getHingeRotationAxis => RelativeHingeRotationAxis = M->Times(ThisBoneJoint->RotationAxisUV);// .normalise(); // M.times(ThisBoneJoint->getHingeRotationAxis()).normalise(); RelativeHingeRotationAxis.Normalize(); } else // ...basebone? Need to construct matrix from the relative constraint UV. { RelativeHingeRotationAxis = BaseboneRelativeConstraintUV; } // ...and transform the hinge rotation axis into the previous bones frame of reference. //Vec3f // Project this bone's outer-to-inner direction onto the plane described by the relative hinge rotation axis // Note: The returned vector is normalised. ThisBoneOuterToInnerUV = UFabrikUtil::ProjectOntoPlane(ThisBoneOuterToInnerUV, RelativeHingeRotationAxis);// ThisBoneOuterToInnerUV.projectOntoPlane(RelativeHingeRotationAxis); // NOTE: Constraining about the hinge reference axis on this forward pass leads to poor solutions... so we won't. } // At this stage we have a outer-to-inner unit vector for this bone which is within our constraints, // so we can set the new inner joint location to be the end joint location of this bone plus the // outer-to-inner direction unit vector multiplied by the length of the bone. FVector NewStartLocation = ThisBone->EndLocation + (ThisBoneOuterToInnerUV * ThisBoneLength);// ().plus(thisBoneOuterToInnerUV.times(thisBoneLength)); // Set the new start joint location for this bone ThisBone->StartLocation = NewStartLocation;// setStartLocation(newStartLocation); // If we are not working on the basebone, then we also set the end joint location of // the previous bone in the chain (i.e. the bone closer to the base) to be the new // start joint location of this bone. if (Loop > 0) { Chain[Loop - 1]->EndLocation = NewStartLocation; // .setEndLocation(newStartLocation); } } else // If we ARE working on the end effector bone... { // Snap the end effector's end location to the target ThisBone->EndLocation = InTarget;//.setEndLocation(target); // Get the UV between the target / end-location (which are now the same) and the start location of this bone FVector ThisBoneOuterToInnerUV = ThisBone->GetDirectionUV();// .getDirectionUV().negated(); ThisBoneOuterToInnerUV = UFabrikUtil::VectorNegated(ThisBoneOuterToInnerUV); // If the end effector is global hinged then we have to snap to it, then keep that // resulting outer-to-inner UV in the plane of the hinge rotation axis switch (ThisBoneJointType) { case EJointType::JT_Ball: // BALL: // Ball joints do not get constrained on this forward pass break; case EJointType::JT_GlobalHinge: // GLOBAL_HINGE: // Global hinges get constrained to the hinge rotation axis, but not the reference axis within the hinge plane // getHingeRotationAxis => mRotationAxisUV ThisBoneOuterToInnerUV = UFabrikUtil::ProjectOntoPlane(ThisBoneOuterToInnerUV, ThisBoneJoint->RotationAxisUV);// ThisBoneOuterToInnerUV.projectOntoPlane(ThisBoneJoint.getHingeRotationAxis()); break; case EJointType::JT_LocalHinge: // LOCAL_HINGE: // Local hinges get constrained to the hinge rotation axis, but not the reference axis within the hinge plane // Construct a rotation matrix based on the previous bones inner-to-to-inner direction... // Mat3f m = Mat3f.createRotationMatrix(Chain[Loop - 1]->GetDirectionUV()); UFabrikMat3f* M = UFabrikMat3f::CreateRotationMatrix(Chain[Loop - 1]->GetDirectionUV()); // ...and transform the hinge rotation axis into the previous bones frame of reference. // getHingeRotationAxis => mRotationAxisUV FVector RelativeHingeRotationAxis = M->Times(ThisBoneJoint->RotationAxisUV);// .normalise(); // m.times(ThisBoneJoint.getHingeRotationAxis()).normalise(); RelativeHingeRotationAxis.Normalize(); // Project this bone's outer-to-inner direction onto the plane described by the relative hinge rotation axis // Note: The returned vector is normalised. ThisBoneOuterToInnerUV = UFabrikUtil::ProjectOntoPlane(ThisBoneOuterToInnerUV, RelativeHingeRotationAxis);// ThisBoneOuterToInnerUV.projectOntoPlane(RelativeHingeRotationAxis); break; } // Calculate the new start joint location as the end joint location plus the outer-to-inner direction UV // multiplied by the length of the bone. FVector NewStartLocation = InTarget + (ThisBoneOuterToInnerUV * ThisBoneLength); // .plus(thisBoneOuterToInnerUV.times(thisBoneLength)); // Set the new start joint location for this bone to be new start location... ThisBone->StartLocation = NewStartLocation;//.setStartLocation(newStartLocation); // ...and set the end joint location of the bone further in to also be at the new start location (if there IS a bone // further in - this may be a single bone chain) if (Loop > 0) { Chain[Loop - 1]->EndLocation = NewStartLocation; } } } // End of forward pass // ---------- Backward pass from base to end effector ----------- for (int Loop = 0; Loop < NumBones; ++Loop) { UFabrikBone* ThisBone = Chain[Loop]; float ThisBoneLength = ThisBone->Length; // Size();// length(); // If we are not working on the basebone if (Loop != 0) { // Get the inner-to-outer direction of this bone as well as the previous bone to use as a baseline FVector ThisBoneInnerToOuterUV = ThisBone->GetDirectionUV(); FVector PrevBoneInnerToOuterUV = Chain[Loop - 1]->GetDirectionUV(); // Dealing with a ball joint? UFabrikJoint* ThisBoneJoint = ThisBone->Joint; EJointType JointType = ThisBone->Joint->JointType; if (JointType == EJointType::JT_Ball) { float AngleBetweenDegs = UFabrikUtil::GetAngleBetweenDegs(PrevBoneInnerToOuterUV, ThisBoneInnerToOuterUV); // Vec3f.getAngleBetweenDegs(prevBoneInnerToOuterUV, thisBoneInnerToOuterUV); // getBallJointConstraintDegs => mRotorConstraintDegs float ConstraintAngleDegs = ThisBoneJoint->RotorConstraintDegs; // Keep this bone direction constrained within the rotor about the previous bone direction if (AngleBetweenDegs > ConstraintAngleDegs) { ThisBoneInnerToOuterUV = UFabrikUtil::GetAngleLimitedUnitVectorDegs(ThisBoneInnerToOuterUV, PrevBoneInnerToOuterUV, ConstraintAngleDegs);//Vec3f.getAngleLimitedUnitVectorDegs(thisBoneInnerToOuterUV, prevBoneInnerToOuterUV, constraintAngleDegs); } } else if (JointType == EJointType::JT_GlobalHinge) { // Get the hinge rotation axis and project our inner-to-outer UV onto it // getHingeRotationAxis => mRotationAxisUV FVector HingeRotationAxis = ThisBoneJoint->RotationAxisUV;// .getHingeRotationAxis(); ThisBoneInnerToOuterUV = UFabrikUtil::ProjectOntoPlane(ThisBoneInnerToOuterUV, HingeRotationAxis); // ThisBoneInnerToOuterUV.projectOntoPlane(HingeRotationAxis); // If there are joint constraints, then we must honour them... float CwConstraintDegs = -ThisBoneJoint->HingeClockwiseConstraintDegs;//.getHingeClockwiseConstraintDegs(); float AcwConstraintDegs = ThisBoneJoint->HingeAnticlockwiseConstraintDegs;// getHingeAnticlockwiseConstraintDegs(); if (!(UFabrikUtil::ApproximatelyEquals(CwConstraintDegs, -UFabrikJoint::MAX_CONSTRAINT_ANGLE_DEGS, 0.001f)) && !(UFabrikUtil::ApproximatelyEquals(AcwConstraintDegs, UFabrikJoint::MAX_CONSTRAINT_ANGLE_DEGS, 0.001f))) { // getHingeReferenceAxis => mReferenceAxisUV FVector HingeReferenceAxis = ThisBoneJoint->ReferenceAxisUV;// .getHingeReferenceAxis(); // Get the signed angle (about the hinge rotation axis) between the hinge reference axis and the hinge-rotation aligned bone UV // Note: ACW rotation is positive, CW rotation is negative. float SignedAngleDegs = UFabrikUtil::GetSignedAngleBetweenDegs(HingeReferenceAxis, ThisBoneInnerToOuterUV, HingeRotationAxis); // Vec3f.getSignedAngleBetweenDegs(HingeReferenceAxis, ThisBoneInnerToOuterUV, HingeRotationAxis); // Make our bone inner-to-outer UV the hinge reference axis rotated by its maximum clockwise or anticlockwise rotation as required if (SignedAngleDegs > AcwConstraintDegs) { ThisBoneInnerToOuterUV = UFabrikUtil::RotateAboutAxisDegs(HingeReferenceAxis, AcwConstraintDegs, HingeRotationAxis);// Vec3f.rotateAboutAxisDegs(HingeReferenceAxis, AcwConstraintDegs, HingeRotationAxis).normalised(); ThisBoneInnerToOuterUV.Normalize(); } else if (SignedAngleDegs < CwConstraintDegs) { ThisBoneInnerToOuterUV = UFabrikUtil::RotateAboutAxisDegs(HingeReferenceAxis, CwConstraintDegs, HingeRotationAxis); // Vec3f.rotateAboutAxisDegs(HingeReferenceAxis, CwConstraintDegs, HingeRotationAxis).normalised(); ThisBoneInnerToOuterUV.Normalize(); } } } else if (JointType == EJointType::JT_LocalHinge) { // Transform the hinge rotation axis to be relative to the previous bone in the chain // getHingeRotationAxis => mRotationAxisUV FVector HingeRotationAxis = ThisBoneJoint->RotationAxisUV;// .getHingeRotationAxis(); // Construct a rotation matrix based on the previous bone's direction //Mat3f m = Mat3f.createRotationMatrix(PrevBoneInnerToOuterUV); UFabrikMat3f* M = UFabrikMat3f::CreateRotationMatrix(PrevBoneInnerToOuterUV); // Transform the hinge rotation axis into the previous bone's frame of reference FVector RelativeHingeRotationAxis = M->Times(HingeRotationAxis);// .normalise(); RelativeHingeRotationAxis.Normalize(); // Project this bone direction onto the plane described by the hinge rotation axis // Note: The returned vector is normalised. ThisBoneInnerToOuterUV = UFabrikUtil::ProjectOntoPlane(ThisBoneInnerToOuterUV, RelativeHingeRotationAxis);// ThisBoneInnerToOuterUV.projectOntoPlane(RelativeHingeRotationAxis); // Constrain rotation about reference axis if required float CwConstraintDegs = -ThisBoneJoint->HingeClockwiseConstraintDegs;//.getHingeClockwiseConstraintDegs(); float AcwConstraintDegs = ThisBoneJoint->HingeAnticlockwiseConstraintDegs; // .getHingeAnticlockwiseConstraintDegs(); if (!(UFabrikUtil::ApproximatelyEquals(CwConstraintDegs, -UFabrikJoint::MAX_CONSTRAINT_ANGLE_DEGS, 0.001f)) && !(UFabrikUtil::ApproximatelyEquals(AcwConstraintDegs, UFabrikJoint::MAX_CONSTRAINT_ANGLE_DEGS, 0.001f))) { // Calc. the reference axis in local space //Vec3f relativeHingeReferenceAxis = mBaseboneRelativeReferenceConstraintUV;//m.times( thisBoneJoint.getHingeReferenceAxis() ).normalise(); // getHingeReferenceAxis => mReferenceAxisUV FVector RelativeHingeReferenceAxis = M->Times(ThisBoneJoint->ReferenceAxisUV);// .normalise(); RelativeHingeReferenceAxis.Normalize(); // Get the signed angle (about the hinge rotation axis) between the hinge reference axis and the hinge-rotation aligned bone UV // Note: ACW rotation is positive, CW rotation is negative. float SignedAngleDegs = UFabrikUtil::GetSignedAngleBetweenDegs(RelativeHingeReferenceAxis, ThisBoneInnerToOuterUV, RelativeHingeRotationAxis); // Vec3f.getSignedAngleBetweenDegs(RelativeHingeReferenceAxis, ThisBoneInnerToOuterUV, RelativeHingeRotationAxis); // Make our bone inner-to-outer UV the hinge reference axis rotated by its maximum clockwise or anticlockwise rotation as required if (SignedAngleDegs > AcwConstraintDegs) { FVector RelativeHingeRotationAxisN = RelativeHingeRotationAxis; ThisBoneInnerToOuterUV = UFabrikUtil::RotateAboutAxisDegs(RelativeHingeReferenceAxis, AcwConstraintDegs, RelativeHingeRotationAxis); // Vec3f.rotateAboutAxisDegs(RelativeHingeReferenceAxis, AcwConstraintDegs, RelativeHingeRotationAxis);// .normalise(); ThisBoneInnerToOuterUV.Normalize(); } else if (SignedAngleDegs < CwConstraintDegs) { ThisBoneInnerToOuterUV = UFabrikUtil::RotateAboutAxisDegs(RelativeHingeReferenceAxis, CwConstraintDegs, RelativeHingeRotationAxis); // Vec3f.rotateAboutAxisDegs(RelativeHingeReferenceAxis, CwConstraintDegs, RelativeHingeRotationAxis);// .normalise(); ThisBoneInnerToOuterUV.Normalize(); } } } // End of local hinge section // At this stage we have a outer-to-inner unit vector for this bone which is within our constraints, // so we can set the new inner joint location to be the end joint location of this bone plus the // outer-to-inner direction unit vector multiplied by the length of the bone. FVector NewEndLocation = ThisBone->StartLocation + (ThisBoneInnerToOuterUV * ThisBoneLength); // ().plus(thisBoneInnerToOuterUV.times(thisBoneLength)); // Set the new start joint location for this bone ThisBone->EndLocation = NewEndLocation; // If we are not working on the end effector bone, then we set the start joint location of the next bone in // the chain (i.e. the bone closer to the target) to be the new end joint location of this bone. if (Loop < NumBones - 1) { Chain[Loop + 1]->StartLocation = NewEndLocation; // setStartLocation(newEndLocation); } } else // If we ARE working on the basebone... { // If the base location is fixed then snap the start location of the basebone back to the fixed base... if (FixedBaseMode) { ThisBone->StartLocation = FixedBaseLocation; } else // ...otherwise project it backwards from the end to the start by its length. { ThisBone->StartLocation = ThisBone->EndLocation - (ThisBone->GetDirectionUV() * ThisBoneLength); //;;.minus(thisBone.getDirectionUV().times(thisBoneLength))); } // If the basebone is unconstrained then process it as usual... if (BaseboneConstraintType == EBoneConstraintType::BCT_None) { // Set the new end location of this bone, and if there are more bones, // then set the start location of the next bone to be the end location of this bone FVector NewEndLocation = ThisBone->StartLocation + (ThisBone->GetDirectionUV() * ThisBoneLength);// .getStartLocation().plus(thisBone.getDirectionUV().times(thisBoneLength)); ThisBone->EndLocation = NewEndLocation; if (NumBones > 1) { Chain[1]->StartLocation = NewEndLocation; } } else // ...otherwise we must constrain it to the basebone constraint unit vector { if (BaseboneConstraintType == EBoneConstraintType::BCT_GlobalRotor) { // Get the inner-to-outer direction of this bone FVector ThisBoneInnerToOuterUV = ThisBone->GetDirectionUV(); float AngleBetweenDegs = UFabrikUtil::GetAngleBetweenDegs(BaseboneConstraintUV, ThisBoneInnerToOuterUV);;// Vec3f.getAngleBetweenDegs(BaseboneConstraintUV, ThisBoneInnerToOuterUV); // getBallJointConstraintDegs => mRotorConstraintDegs float ConstraintAngleDegs = ThisBone->Joint->RotorConstraintDegs;// .getBallJointConstraintDegs(); if (AngleBetweenDegs > ConstraintAngleDegs) { ThisBoneInnerToOuterUV = UFabrikUtil::GetAngleLimitedUnitVectorDegs(ThisBoneInnerToOuterUV, BaseboneConstraintUV, ConstraintAngleDegs);//Vec3f.getAngleLimitedUnitVectorDegs(ThisBoneInnerToOuterUV, BaseboneConstraintUV, ConstraintAngleDegs); } FVector NewEndLocation = ThisBone->StartLocation + (ThisBoneInnerToOuterUV * ThisBoneLength); // .plus(thisBoneInnerToOuterUV.times(thisBoneLength)); ThisBone->EndLocation = NewEndLocation; // Also, set the start location of the next bone to be the end location of this bone if (NumBones > 1) { Chain[1]->StartLocation = NewEndLocation; } } else if (BaseboneConstraintType == EBoneConstraintType::BCT_LocalRotor) { // Note: The mBaseboneRelativeConstraintUV is updated in the FabrikStructure3D.solveForTarget() // method BEFORE this FabrikChain3D.solveForTarget() method is called. We no knowledge of the // direction of the bone we're connected to in another chain and so cannot calculate this // relative basebone constraint direction on our own, but the FabrikStructure3D does it for // us so we are now free to use it here. // Get the inner-to-outer direction of this bone FVector ThisBoneInnerToOuterUV = ThisBone->GetDirectionUV(); // Constrain about the relative basebone constraint unit vector as neccessary float AngleBetweenDegs = UFabrikUtil::GetAngleBetweenDegs(BaseboneRelativeConstraintUV, ThisBoneInnerToOuterUV);// Vec3f.getAngleBetweenDegs(BaseboneRelativeConstraintUV, ThisBoneInnerToOuterUV); // getBallJointConstraintDegs => mRotorConstraintDegs float ConstraintAngleDegs = ThisBone->Joint->RotorConstraintDegs;// getBallJointConstraintDegs(); if (AngleBetweenDegs > ConstraintAngleDegs) { ThisBoneInnerToOuterUV = UFabrikUtil::GetAngleLimitedUnitVectorDegs(ThisBoneInnerToOuterUV, BaseboneRelativeConstraintUV, ConstraintAngleDegs);// Vec3f.getAngleLimitedUnitVectorDegs(ThisBoneInnerToOuterUV, BaseboneRelativeConstraintUV, ConstraintAngleDegs); } // Set the end location FVector NewEndLocation = ThisBone->StartLocation + (ThisBoneInnerToOuterUV * ThisBoneLength); // .plus(thisBoneInnerToOuterUV.times(thisBoneLength)); ThisBone->EndLocation = NewEndLocation; // Also, set the start location of the next bone to be the end location of this bone if (NumBones > 1) { Chain[1]->StartLocation = NewEndLocation; } } else if (BaseboneConstraintType == EBoneConstraintType::BCT_GlobalHinge) { UFabrikJoint* ThisJoint = ThisBone->Joint; // getHingeRotationAxis => mRotationAxisUV FVector HingeRotationAxis = ThisJoint->RotationAxisUV;// getHingeRotationAxis(); float CwConstraintDegs = -ThisJoint->HingeClockwiseConstraintDegs;// GetHingeClockwiseConstraintDegs(); // Clockwise rotation is negative! float AcwConstraintDegs = ThisJoint->HingeAnticlockwiseConstraintDegs;// GetHingeAnticlockwiseConstraintDegs(); // Get the inner-to-outer direction of this bone and project it onto the global hinge rotation axis FVector ThisBoneInnerToOuterUV = UFabrikUtil::ProjectOntoPlane(ThisBone->GetDirectionUV(), HingeRotationAxis);// ThisBone->GetDirectionUV().projectOntoPlane(HingeRotationAxis); // If we have a global hinge which is not freely rotating then we must constrain about the reference axis if (!(UFabrikUtil::ApproximatelyEquals(CwConstraintDegs, UFabrikJoint::MAX_CONSTRAINT_ANGLE_DEGS, 0.01f) && UFabrikUtil::ApproximatelyEquals(AcwConstraintDegs, UFabrikJoint::MAX_CONSTRAINT_ANGLE_DEGS, 0.01f))) { // Grab the hinge reference axis and calculate the current signed angle between it and our bone direction (about the hinge // rotation axis). Note: ACW rotation is positive, CW rotation is negative. // getHingeReferenceAxis => mReferenceAxisUV FVector HingeReferenceAxis = ThisJoint->ReferenceAxisUV;// .getHingeReferenceAxis(); float SignedAngleDegs = UFabrikUtil::GetSignedAngleBetweenDegs(HingeReferenceAxis, ThisBoneInnerToOuterUV, HingeRotationAxis); // Vec3f.getSignedAngleBetweenDegs(HingeReferenceAxis, ThisBoneInnerToOuterUV, HingeRotationAxis); // Constrain as necessary if (SignedAngleDegs > AcwConstraintDegs) { ThisBoneInnerToOuterUV = UFabrikUtil::RotateAboutAxisDegs(HingeReferenceAxis, AcwConstraintDegs, HingeRotationAxis);// Vec3f.rotateAboutAxisDegs(HingeReferenceAxis, AcwConstraintDegs, HingeRotationAxis);// .normalise(); ThisBoneInnerToOuterUV.Normalize(); } else if (SignedAngleDegs < CwConstraintDegs) { ThisBoneInnerToOuterUV = UFabrikUtil::RotateAboutAxisDegs(HingeReferenceAxis, CwConstraintDegs, HingeRotationAxis); // Vec3f.rotateAboutAxisDegs(HingeReferenceAxis, CwConstraintDegs, HingeRotationAxis);// .normalise(); ThisBoneInnerToOuterUV.Normalize(); } } // Calc and set the end location of this bone FVector NewEndLocation = ThisBone->StartLocation + (ThisBoneInnerToOuterUV * ThisBoneLength); // .plus(thisBoneInnerToOuterUV.times(thisBoneLength)); ThisBone->EndLocation = NewEndLocation; // Also, set the start location of the next bone to be the end location of this bone if (NumBones > 1) { Chain[1]->StartLocation = NewEndLocation; } } else if (BaseboneConstraintType == EBoneConstraintType::BCT_LocalHinge) { UFabrikJoint* ThisJoint = ThisBone->Joint; FVector HingeRotationAxis = BaseboneRelativeConstraintUV; // Basebone relative constraint is our hinge rotation axis! float CwConstraintDegs = -ThisJoint->HingeClockwiseConstraintDegs; // Clockwise rotation is negative! float AcwConstraintDegs = ThisJoint->HingeAnticlockwiseConstraintDegs; // Get the inner-to-outer direction of this bone and project it onto the global hinge rotation axis FVector ThisBoneInnerToOuterUV = UFabrikUtil::ProjectOntoPlane(ThisBone->GetDirectionUV(), HingeRotationAxis);// ThisBone->GetDirectionUV().projectOntoPlane(HingeRotationAxis); //If we have a local hinge which is not freely rotating then we must constrain about the reference axis if (!(UFabrikUtil::ApproximatelyEquals(CwConstraintDegs, UFabrikJoint::MAX_CONSTRAINT_ANGLE_DEGS, 0.01f) && UFabrikUtil::ApproximatelyEquals(AcwConstraintDegs, UFabrikJoint::MAX_CONSTRAINT_ANGLE_DEGS, 0.01f))) { // Grab the hinge reference axis and calculate the current signed angle between it and our bone direction (about the hinge // rotation axis). Note: ACW rotation is positive, CW rotation is negative. FVector HingeReferenceAxis = BaseboneRelativeReferenceConstraintUV; //thisJoint.getHingeReferenceAxis(); float SignedAngleDegs = UFabrikUtil::GetSignedAngleBetweenDegs(HingeReferenceAxis, ThisBoneInnerToOuterUV, HingeRotationAxis);// Vec3f.getSignedAngleBetweenDegs(HingeReferenceAxis, ThisBoneInnerToOuterUV, HingeRotationAxis); // Constrain as necessary if (SignedAngleDegs > AcwConstraintDegs) { ThisBoneInnerToOuterUV = UFabrikUtil::RotateAboutAxisDegs(HingeReferenceAxis, AcwConstraintDegs, HingeRotationAxis); // Vec3f.rotateAboutAxisDegs(HingeReferenceAxis, AcwConstraintDegs, HingeRotationAxis).normalise(); ThisBoneInnerToOuterUV.Normalize(); } else if (SignedAngleDegs < CwConstraintDegs) { ThisBoneInnerToOuterUV = UFabrikUtil::RotateAboutAxisDegs(HingeReferenceAxis, CwConstraintDegs, HingeRotationAxis); // Vec3f.rotateAboutAxisDegs(HingeReferenceAxis, CwConstraintDegs, HingeRotationAxis).normalise(); ThisBoneInnerToOuterUV.Normalize(); } } // Calc and set the end location of this bone FVector NewEndLocation = ThisBone->StartLocation + (ThisBoneInnerToOuterUV * ThisBoneLength); // .plus(thisBoneInnerToOuterUV.times(thisBoneLength)); ThisBone->EndLocation = NewEndLocation; // Also, set the start location of the next bone to be the end location of this bone if (NumBones > 1) { Chain[1]->StartLocation = NewEndLocation; } } } // End of basebone constraint handling section } // End of basebone handling section } // End of backward-pass loop over all bones // Update our last target location LastTargetLocation = InTarget; // DEBUG - check the live chain length and the originally calculated chain length are the same /* if (Math.abs( this.getLiveChainLength() - mChainLength) > 0.01f) { System.out.println("Chain length off by > 0.01f"); } */ // Finally, calculate and return the distance between the current effector location and the target. return FVector::Dist(Chain[NumBones - 1]->EndLocation, InTarget); } void UFabrikChain::UpdateChainLength() { // We start adding up the length of the bones from an initial length of zero ChainLength = 0.0f; // Loop over all the bones in the chain, adding the length of each bone to the mChainLength property for (int Loop = 0; Loop < NumBones; ++Loop) { ChainLength += Chain[Loop]->Length; } } TArray<UFabrikBone*> UFabrikChain::CloneIkChain() { // How many bones are in this chain? int NumBonesTmp = Chain.Num(); // Create a new Vector of FabrikBone3D objects of that size TArray<UFabrikBone*> ClonedChain;// = new ArrayList<FabrikBone3D>(numBones); // For each bone in the chain being cloned... for (int Loop = 0; Loop < NumBonesTmp; ++Loop) { // Use the copy constructor to create a new FabrikBone3D with the values set from the source FabrikBone3D. // and add it to the cloned chain. UFabrikBone* Clone = NewObject<UFabrikBone>(); Clone->Init(Chain[Loop]); ClonedChain.Add(Clone);// new FabrikBone3D(mChain.get(loop))); } return ClonedChain; } void UFabrikChain::ConnectToStructure(UFabrikStructure* InStructure, int InChainNumber, int InBoneNumber) { // Sanity check chain exists int NumChains = InStructure->NumChains; if (InChainNumber > NumChains) { UE_LOG(OpenMotionLog, Fatal, TEXT("Structure does not contain a chain TODO - it has TODO chains."));// throw new IllegalArgumentException("Structure does not contain a chain " + chainNumber + " - it has " + numChains + " chains."); } // Sanity check bone exists int NumBonesL = InStructure->Chains[InChainNumber]->NumBones; if (InBoneNumber > NumBonesL) { UE_LOG(OpenMotionLog, Fatal, TEXT("Chain does not contain a bone TODO - it has TODO bones.")); //throw new IllegalArgumentException("Chain does not contain a bone " + boneNumber + " - it has " + numBones + " bones."); } // All good? Set the connection details ConnectedChainNumber = InChainNumber; ConnectedBoneNumber = InBoneNumber; }
47.287819
303
0.762189
[ "vector", "transform" ]
cb462a21dff851de54b8e6ebb3d5af18a1259a71
7,412
hpp
C++
include/lbann/layers/math/binary.hpp
oyamay/lbann
57116ecc030c0d17bc941f81131c1a335bc2c4ad
[ "Apache-2.0" ]
null
null
null
include/lbann/layers/math/binary.hpp
oyamay/lbann
57116ecc030c0d17bc941f81131c1a335bc2c4ad
[ "Apache-2.0" ]
null
null
null
include/lbann/layers/math/binary.hpp
oyamay/lbann
57116ecc030c0d17bc941f81131c1a335bc2c4ad
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <lbann-dev@llnl.gov> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); 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 LBANN_LAYERS_MATH_BINARY_HPP_INCLUDED #define LBANN_LAYERS_MATH_BINARY_HPP_INCLUDED #include "lbann/layers/data_type_layer.hpp" namespace lbann { #define LBANN_DECLARE_ENTRYWISE_BINARY_LAYER(LAYER_NAME, LAYER_STRING) \ template <typename TensorDataType, data_layout Layout, El::Device Device> \ class LAYER_NAME : public data_type_layer<TensorDataType> { \ public: \ LAYER_NAME(lbann_comm *comm) : data_type_layer<TensorDataType>(comm) { \ this->m_expected_num_parent_layers = 2; \ } \ LAYER_NAME* copy() const override { \ return new LAYER_NAME<TensorDataType,Layout,Device>(*this); \ } \ std::string get_type() const override { return LAYER_STRING; } \ data_layout get_data_layout() const override { return Layout; } \ El::Device get_device_allocation() const override { return Device; } \ protected: \ void setup_dims(DataReaderMetaData& dr_metadata) override { \ data_type_layer<TensorDataType>::setup_dims(dr_metadata); \ this->set_output_dims(this->get_input_dims()); \ /* Check that input dimensions match */ \ if (this->get_input_dims(0) != this->get_input_dims(1)) { \ const auto& parents = this->get_parent_layers(); \ std::stringstream err; \ err << this->get_type() << " layer \"" << this->get_name() << "\" " \ << "has input tensors with different dimensions ("; \ for (int i = 0; i < this->get_num_parents(); ++i) { \ const auto& dims = this->get_input_dims(i); \ err << (i > 0 ? ", " : "") \ << "layer \"" << parents[i]->get_name() << "\" outputs "; \ for (size_t j = 0; j < dims.size(); ++j) { \ err << (j > 0 ? " x " : "") << dims[j]; \ } \ } \ err << ")"; \ LBANN_ERROR(err.str()); \ } \ } \ void fp_compute() override; \ void bp_compute() override; \ } // Convenience macros for ETI decls for binary layers #ifndef LBANN_BINARY_LAYER_INSTANTIATE #define BINARY_ETI_DECL_MACRO_DEV(LAYER_NAME, T, DEVICE) \ extern template class LAYER_NAME<T, data_layout::DATA_PARALLEL, DEVICE>; \ extern template class LAYER_NAME<T, data_layout::MODEL_PARALLEL, DEVICE> #else #define BINARY_ETI_DECL_MACRO_DEV(...) #endif // LBANN_BINARY_LAYER_INSTANTIATE // Instnatiate both data and model parallel layers #define BINARY_ETI_INST_MACRO_DEV_DT(LAYER_NAME, T, DEVICE) \ template class LAYER_NAME<T, data_layout::DATA_PARALLEL, DEVICE>; \ template class LAYER_NAME<T, data_layout::MODEL_PARALLEL, DEVICE> // Instantiate a DEVICE for each allowed tensor data type #define BINARY_ETI_INST_MACRO_DEV(LAYER_NAME, DEVICE) \ BINARY_ETI_INST_MACRO_DEV_DT(LAYER_NAME, float, DEVICE); \ BINARY_ETI_INST_MACRO_DEV_DT(LAYER_NAME, double, DEVICE) #ifdef LBANN_HAS_GPU #define BINARY_ETI_DECL_MACRO(LAYER_NAME, T) \ BINARY_ETI_DECL_MACRO_DEV(LAYER_NAME, T, El::Device::CPU); \ BINARY_ETI_DECL_MACRO_DEV(LAYER_NAME, T, El::Device::GPU) #else #define BINARY_ETI_DECL_MACRO(LAYER_NAME, T) \ BINARY_ETI_DECL_MACRO_DEV(LAYER_NAME, T, El::Device::CPU) #endif // LBANN_HAS_GPU // Convenience macro to define an entry-wise binary layer class #define DEFINE_ENTRYWISE_BINARY_LAYER(layer_name, layer_string) \ LBANN_DECLARE_ENTRYWISE_BINARY_LAYER(layer_name, layer_string); \ BINARY_ETI_DECL_MACRO(layer_name, float); \ BINARY_ETI_DECL_MACRO(layer_name, double) // Arithmetic operations DEFINE_ENTRYWISE_BINARY_LAYER(add_layer, "add"); DEFINE_ENTRYWISE_BINARY_LAYER(subtract_layer, "subtract"); DEFINE_ENTRYWISE_BINARY_LAYER(multiply_layer, "multiply"); DEFINE_ENTRYWISE_BINARY_LAYER(divide_layer, "divide"); DEFINE_ENTRYWISE_BINARY_LAYER(mod_layer, "modulo"); DEFINE_ENTRYWISE_BINARY_LAYER(pow_layer, "power"); DEFINE_ENTRYWISE_BINARY_LAYER(safe_divide_layer, "safe divide"); DEFINE_ENTRYWISE_BINARY_LAYER(squared_difference_layer, "squared difference"); // Comparison operations DEFINE_ENTRYWISE_BINARY_LAYER(max_layer, "maximum"); DEFINE_ENTRYWISE_BINARY_LAYER(min_layer, "minimum"); DEFINE_ENTRYWISE_BINARY_LAYER(equal_layer, "equal"); DEFINE_ENTRYWISE_BINARY_LAYER(not_equal_layer, "not equal"); DEFINE_ENTRYWISE_BINARY_LAYER(less_layer, "less than"); DEFINE_ENTRYWISE_BINARY_LAYER(less_equal_layer, "less than or equal"); DEFINE_ENTRYWISE_BINARY_LAYER(greater_layer, "greater than"); DEFINE_ENTRYWISE_BINARY_LAYER(greater_equal_layer, "greater than or equal"); // Logical operations DEFINE_ENTRYWISE_BINARY_LAYER(logical_and_layer, "logical and"); DEFINE_ENTRYWISE_BINARY_LAYER(logical_or_layer, "logical or"); DEFINE_ENTRYWISE_BINARY_LAYER(logical_xor_layer, "logical xor"); } // namespace lbann #undef DEFINE_ENTRYWISE_BINARY_LAYER #undef BINARY_ETI_DECL_MACRO #undef BINARY_ETI_DECL_MACRO_DEV #endif // LBANN_LAYERS_MATH_BINARY_HPP_INCLUDED
52.942857
108
0.582569
[ "model" ]
cb47b07d318bd8db587152520dceefe9c59d262f
83,843
hh
C++
src/Field/FieldListInline.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/Field/FieldListInline.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
17
2020-01-05T08:41:46.000Z
2020-09-18T00:08:32.000Z
src/Field/FieldListInline.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
// Includes. #include "Geometry/MathTraits.hh" #include "NodeIterators.hh" #include "NodeList/FluidNodeList.hh" #include "NodeList/NodeListRegistrar.hh" #include "Neighbor/Neighbor.hh" #include "Field/Field.hh" #include "Kernel/TableKernel.hh" #include "Utilities/allReduce.hh" #ifdef USE_MPI #include <mpi.h> #include "Utilities/DataTypeTraits.hh" #include "Utilities/packElement.hh" #include "Distributed/Communicator.hh" #endif #include <algorithm> #include <limits.h> #include <float.h> namespace Spheral { //------------------------------------------------------------------------------ // Empty constructor. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType>::FieldList(): FieldListBase<Dimension>(), mFieldPtrs(0), mFieldBasePtrs(0), mFieldCache(0), mStorageType(FieldStorageType::ReferenceFields), mNodeListPtrs(0), mNodeListIndexMap(), reductionType(ThreadReduction::SUM), threadMasterPtr(NULL) { } //------------------------------------------------------------------------------ // Construct an empty Field List, with an explict storage type. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType>::FieldList(FieldStorageType aStorageType): FieldListBase<Dimension>(), mFieldPtrs(0), mFieldBasePtrs(0), mFieldCache(0), mStorageType(aStorageType), mNodeListPtrs(0), mNodeListIndexMap(), reductionType(ThreadReduction::SUM), threadMasterPtr(NULL) { } //------------------------------------------------------------------------------ // Copy constructor. // Note that the copy constructor copies the data by reference by default. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType>:: FieldList(const FieldList<Dimension, DataType>& rhs): FieldListBase<Dimension>(rhs), mFieldPtrs(rhs.mFieldPtrs), mFieldBasePtrs(rhs.mFieldBasePtrs), mFieldCache(), mStorageType(rhs.storageType()), mNodeListPtrs(rhs.mNodeListPtrs), mNodeListIndexMap(rhs.mNodeListIndexMap), reductionType(rhs.reductionType), threadMasterPtr(rhs.threadMasterPtr) { // If we're maintaining Fields by copy, then copy the Field cache. #pragma omp critical (FieldList_copy) { if (storageType() == FieldStorageType::CopyFields) { CHECK(mFieldCache.size() == 0); for (typename FieldCacheType::const_iterator itr = rhs.mFieldCache.begin(); itr != rhs.mFieldCache.end(); ++itr) { auto newField = std::make_shared<Field<Dimension, DataType>>(**itr); mFieldCache.push_back(newField); } CHECK(this->size() == mFieldCache.size()); auto fieldPtrItr = this->begin(); auto fieldBasePtrItr = this->begin_base(); auto fieldCacheItr = mFieldCache.begin(); for(; fieldPtrItr != this->end(); ++fieldPtrItr, ++fieldBasePtrItr, ++fieldCacheItr) { CHECK(fieldCacheItr != mFieldCache.end()); (*fieldPtrItr) = fieldCacheItr->get(); (*fieldBasePtrItr) = fieldCacheItr->get(); } CHECK(fieldPtrItr == this->end() && fieldBasePtrItr == this->end_base() && fieldCacheItr == mFieldCache.end()); } NodeListRegistrar<Dimension>::sortInNodeListOrder(mFieldPtrs.begin(), mFieldPtrs.end()); mFieldBasePtrs.clear(); mNodeListPtrs.clear(); for (auto fptr: mFieldPtrs) { mFieldBasePtrs.push_back(fptr); mNodeListPtrs.push_back(const_cast<NodeList<Dimension>*>(fptr->nodeListPtr())); } } // OMP critical // // Register this FieldList with each Field we point to. // for (iterator fieldPtrItr = begin(); fieldPtrItr != end(); ++fieldPtrItr) // registerWithField(**fieldPtrItr); } //------------------------------------------------------------------------------ // Destructor. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType>::~FieldList() { // // Unregister this FieldList from each Field we point to. // if (storageType() == FieldStorageType::ReferenceFields) { // for (iterator fieldPtrItr = begin(); fieldPtrItr != end(); ++fieldPtrItr) // unregisterFromField(**fieldPtrItr); // } } //------------------------------------------------------------------------------ // Assignment with another FieldList. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType>& FieldList<Dimension, DataType>:: operator=(const FieldList<Dimension, DataType>& rhs) { #pragma omp critical (FieldList_assign) { if (this != &rhs) { mStorageType = rhs.storageType(); mNodeListPtrs = rhs.mNodeListPtrs; mFieldCache = FieldCacheType(); mNodeListIndexMap = rhs.mNodeListIndexMap; mFieldPtrs = std::vector<ElementType>(); mFieldBasePtrs = std::vector<BaseElementType>(); mFieldPtrs.reserve(rhs.size()); mFieldBasePtrs.reserve(rhs.size()); reductionType = rhs.reductionType; threadMasterPtr = rhs.threadMasterPtr; // // Unregister from our current set of Fields. // for (iterator fieldPtrItr = begin(); fieldPtrItr != end(); ++fieldPtrItr) // unregisterFromField(**fieldPtrItr); switch(storageType()) { case FieldStorageType::ReferenceFields: for (auto fieldPtrItr = rhs.begin(); fieldPtrItr != rhs.end(); ++fieldPtrItr) { mFieldPtrs.push_back(*fieldPtrItr); mFieldBasePtrs.push_back(*fieldPtrItr); } break; case FieldStorageType::CopyFields: for (auto itr = rhs.mFieldCache.begin(); itr != rhs.mFieldCache.end(); ++itr) { auto newField = std::make_shared<Field<Dimension, DataType>>(**itr); mFieldCache.push_back(newField); mFieldPtrs.push_back(newField.get()); } NodeListRegistrar<Dimension>::sortInNodeListOrder(mFieldPtrs.begin(), mFieldPtrs.end()); for (auto fptr: mFieldPtrs) mFieldBasePtrs.push_back(fptr); CHECK(this->size() == mFieldCache.size()); CHECK(mFieldBasePtrs.size() == mFieldCache.size()); break; } // // Register this FieldList with each Field we point to. // for (iterator fieldPtrItr = begin(); fieldPtrItr != end(); ++fieldPtrItr) // registerWithField(**fieldPtrItr); } } // OMP critical ENSURE(this->size() == rhs.size()); return *this; } //------------------------------------------------------------------------------ // Assignment with a constant. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType>& FieldList<Dimension, DataType>:: operator=(const DataType& rhs) { for (auto fieldPtrItr = begin(); fieldPtrItr < end(); ++fieldPtrItr) { (*fieldPtrItr)->operator=(rhs); } return *this; } //------------------------------------------------------------------------------ // Return the storage type. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldStorageType FieldList<Dimension, DataType>::storageType() const { return mStorageType; } //------------------------------------------------------------------------------ // Force the FieldList to store the fields it points to. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>::copyFields() { if (storageType() != FieldStorageType::CopyFields) { mStorageType = FieldStorageType::CopyFields; // // Unregister this FieldList from each Field we currently point to. // for (iterator fieldPtrItr = begin(); fieldPtrItr != end(); ++fieldPtrItr) // unregisterFromField(**fieldPtrItr); // Store local copies of the fields we're pointing at. mFieldCache = FieldCacheType(); auto itr = begin(); auto baseItr = begin_base(); for (; itr != end(); ++itr, ++baseItr) { auto newField = std::make_shared<Field<Dimension, DataType>>(**itr); mFieldCache.push_back(newField); *itr = mFieldCache.back().get(); *baseItr = mFieldCache.back().get(); } // Make sure the FieldPtrs are in the correct order. NodeListRegistrar<Dimension>::sortInNodeListOrder(mFieldPtrs.begin(), mFieldPtrs.end()); mFieldBasePtrs.clear(); mNodeListPtrs.clear(); for (auto fptr: mFieldPtrs) { mFieldBasePtrs.push_back(fptr); mNodeListPtrs.push_back(const_cast<NodeList<Dimension>*>(fptr->nodeListPtr())); } // for (int i = 0; i < this->size(); ++i) { // mFieldCache.push_back(*((*this)[i])); // (*this)[i] = &(mFieldCache.back()); // } } } //------------------------------------------------------------------------------ // Make this FieldList store copies of Fields from another. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>::copyFields(const FieldList<Dimension, DataType>& fieldList) { mFieldPtrs.clear(); mFieldBasePtrs.clear(); mFieldCache.clear(); mStorageType = FieldStorageType::CopyFields; mNodeListPtrs = fieldList.mNodeListPtrs; mNodeListIndexMap = fieldList.mNodeListIndexMap; reductionType = fieldList.reductionType; threadMasterPtr = fieldList.threadMasterPtr; // Store new copies of the Fields from the other FieldList for (const auto& fieldPtr: fieldList.mFieldPtrs) { auto newFieldPtr = std::make_shared<Field<Dimension, DataType>>(*fieldPtr); mFieldCache.push_back(newFieldPtr); mFieldPtrs.push_back(newFieldPtr.get()); mFieldBasePtrs.push_back(newFieldPtr.get()); } } //------------------------------------------------------------------------------ // Test if a given field is part of this field list. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool FieldList<Dimension, DataType>:: haveField(const Field<Dimension, DataType>& field) const { auto fieldListItr = std::find(this->begin(), this->end(), &field); return fieldListItr != this->end(); } //------------------------------------------------------------------------------ // Test if there is a Field associated with the given NodeList. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool FieldList<Dimension, DataType>:: haveNodeList(const NodeList<Dimension>& nodeList) const { return mNodeListIndexMap.find(&nodeList) != mNodeListIndexMap.end(); } //------------------------------------------------------------------------------ // Set the fields of this field list equal to those of another. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>:: assignFields(const FieldList<Dimension, DataType>& fieldList) { #pragma omp critical (FieldList_assignFields) { auto otherFieldListItr = fieldList.begin(); for (auto fieldListItr = this->begin(); fieldListItr < this->end(); ++fieldListItr, ++otherFieldListItr) { CHECK(otherFieldListItr < fieldList.end()); CHECK((*fieldListItr)->nodeListPtr() == (*otherFieldListItr)->nodeListPtr()); **fieldListItr = **otherFieldListItr; } } // OMP critical } //------------------------------------------------------------------------------ // Make this FieldList reference the fields of another. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>:: referenceFields(const FieldList<Dimension, DataType>& fieldList) { mFieldPtrs = fieldList.mFieldPtrs; mFieldBasePtrs = fieldList.mFieldBasePtrs; mFieldCache.clear(); mStorageType = FieldStorageType::ReferenceFields; mNodeListPtrs = fieldList.mNodeListPtrs; mNodeListIndexMap = fieldList.mNodeListIndexMap; } //------------------------------------------------------------------------------ // Append the given field to the FieldList. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>::appendField(const Field<Dimension, DataType>& field) { if (haveField(field)) { std::cerr << "FieldList::appendField Warning: attempt to append field " << &field << " to FieldList " << this << " which already has it." << std::endl; return; } // Determine the order this Field should be in. const NodeListRegistrar<Dimension>& nlr = NodeListRegistrar<Dimension>::instance(); auto orderItr = nlr.findInsertionPoint(&field, begin(), end()); const auto delta = std::distance(begin(), orderItr); // Insert the field. switch(storageType()) { case FieldStorageType::ReferenceFields: mFieldPtrs.insert(orderItr, const_cast<Field<Dimension, DataType>*>(&field)); mFieldBasePtrs.insert(mFieldBasePtrs.begin() + delta, const_cast<FieldBase<Dimension>*>(dynamic_cast<const FieldBase<Dimension>*>(&field))); break; case FieldStorageType::CopyFields: auto newField = std::make_shared<Field<Dimension, DataType>>(field); mFieldCache.push_back(newField); mFieldPtrs.insert(orderItr, newField.get()); mFieldBasePtrs.insert(mFieldBasePtrs.begin() + delta, newField.get()); } // registerWithField(*mFieldPtrs.back()); // We also update the set of NodeListPtrs in proper order. NodeListRegistrar<Dimension>::sortInNodeListOrder(mFieldPtrs.begin(), mFieldPtrs.end()); mFieldBasePtrs.clear(); mNodeListPtrs.clear(); for (auto fptr: mFieldPtrs) { mFieldBasePtrs.push_back(fptr); mNodeListPtrs.push_back(const_cast<NodeList<Dimension>*>(fptr->nodeListPtr())); } CHECK(mNodeListIndexMap.find(field.nodeListPtr()) == mNodeListIndexMap.end()); buildNodeListIndexMap(); // Post-conditions. BEGIN_CONTRACT_SCOPE ENSURE(mFieldPtrs[mNodeListIndexMap[field.nodeListPtr()]] == *(fieldForNodeList(*field.nodeListPtr()))); ENSURE(this->size() == mNodeListPtrs.size()); END_CONTRACT_SCOPE } //------------------------------------------------------------------------------ // Delete the given field from the FieldList. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>::deleteField(const Field<Dimension, DataType>& field) { if (!haveField(field)) { std::cerr << "FieldList::deleteField Warning: attempt to delete field " << &field << " from FieldList " << this << " which does not recognize it." << std::endl; return; } const auto fieldPtrItr = std::find(this->begin(), this->end(), &field); CHECK(fieldPtrItr != this->end()); const size_t delta = std::distance(this->begin(), fieldPtrItr); auto fieldItr = mFieldCache.begin(); switch(storageType()) { case FieldStorageType::CopyFields: while (fieldItr != mFieldCache.end() && fieldItr->get() != &field) { ++fieldItr; } CHECK(fieldItr != mFieldCache.end()); mFieldCache.erase(fieldItr); [[fallthrough]]; case FieldStorageType::ReferenceFields: mFieldPtrs.erase(fieldPtrItr); mFieldBasePtrs.erase(mFieldBasePtrs.begin() + delta); break; } // Remove the NodeList pointer. auto nodeListItr = std::find(mNodeListPtrs.begin(), mNodeListPtrs.end(), field.nodeListPtr()); CHECK(nodeListItr != mNodeListPtrs.end()); mNodeListPtrs.erase(nodeListItr); buildNodeListIndexMap(); } //------------------------------------------------------------------------------ // Construct a new field and add it to the FieldList. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>:: appendNewField(const typename Field<Dimension, DataType>::FieldName name, const NodeList<Dimension>& nodeList, const DataType value) { VERIFY(mStorageType == FieldStorageType::CopyFields); // Create the field in our cache. mFieldCache.push_back(std::make_shared<Field<Dimension, DataType>>(name, nodeList, value)); Field<Dimension, DataType>* fieldPtr = mFieldCache.back().get(); mFieldPtrs.push_back(fieldPtr); NodeListRegistrar<Dimension>::sortInNodeListOrder(mFieldPtrs.begin(), mFieldPtrs.end()); mFieldBasePtrs.clear(); mNodeListPtrs.clear(); for (auto fptr: mFieldPtrs) { mFieldBasePtrs.push_back(fptr); mNodeListPtrs.push_back(const_cast<NodeList<Dimension>*>(fptr->nodeListPtr())); } // // Determine the order this Field should be in. // const NodeListRegistrar<Dimension>& nlr = NodeListRegistrar<Dimension>::instance(); // auto orderItr = nlr.findInsertionPoint(fieldPtr, // begin(), // end()); // const int delta = std::distance(begin(), orderItr); // // Insert the field. // mFieldPtrs.insert(orderItr, fieldPtr); // mFieldBasePtrs.insert(mFieldBasePtrs.begin() + delta, fieldPtr); // // We also update the set of NodeListPtrs in proper order. // mNodeListPtrs.insert(mNodeListPtrs.begin() + delta, const_cast<NodeList<Dimension>*>(&nodeList)); CHECK(mNodeListIndexMap.find(fieldPtr->nodeListPtr()) == mNodeListIndexMap.end()); buildNodeListIndexMap(); // Post-conditions. BEGIN_CONTRACT_SCOPE ENSURE(mFieldPtrs[mNodeListIndexMap[fieldPtr->nodeListPtr()]] == *(fieldForNodeList(*(fieldPtr->nodeListPtr())))); ENSURE(this->size() == mNodeListPtrs.size()); ENSURE(mFieldBasePtrs.size() == mFieldPtrs.size()); END_CONTRACT_SCOPE } //------------------------------------------------------------------------------ // Standard iterators. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename FieldList<Dimension, DataType>::iterator FieldList<Dimension, DataType>:: begin() { return mFieldPtrs.begin(); } template<typename Dimension, typename DataType> inline typename FieldList<Dimension, DataType>::iterator FieldList<Dimension, DataType>:: end() { return mFieldPtrs.end(); } template<typename Dimension, typename DataType> inline typename FieldList<Dimension, DataType>::reverse_iterator FieldList<Dimension, DataType>:: rbegin() { return mFieldPtrs.rbegin(); } template<typename Dimension, typename DataType> inline typename FieldList<Dimension, DataType>::reverse_iterator FieldList<Dimension, DataType>:: rend() { return mFieldPtrs.rend(); } template<typename Dimension, typename DataType> inline typename FieldList<Dimension, DataType>::const_iterator FieldList<Dimension, DataType>:: begin() const { return mFieldPtrs.begin(); } template<typename Dimension, typename DataType> inline typename FieldList<Dimension, DataType>::const_iterator FieldList<Dimension, DataType>:: end() const { return mFieldPtrs.end(); } template<typename Dimension, typename DataType> inline typename FieldList<Dimension, DataType>::const_reverse_iterator FieldList<Dimension, DataType>:: rbegin() const { return mFieldPtrs.rbegin(); } template<typename Dimension, typename DataType> inline typename FieldList<Dimension, DataType>::const_reverse_iterator FieldList<Dimension, DataType>:: rend() const { return mFieldPtrs.rend(); } //------------------------------------------------------------------------------ // Standard iterators for FieldListBase. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename FieldListBase<Dimension>::iterator FieldList<Dimension, DataType>:: begin_base() { return mFieldBasePtrs.begin(); } template<typename Dimension, typename DataType> inline typename FieldListBase<Dimension>::iterator FieldList<Dimension, DataType>:: end_base() { return mFieldBasePtrs.end(); } template<typename Dimension, typename DataType> inline typename FieldListBase<Dimension>::reverse_iterator FieldList<Dimension, DataType>:: rbegin_base() { return mFieldBasePtrs.rbegin(); } template<typename Dimension, typename DataType> inline typename FieldListBase<Dimension>::reverse_iterator FieldList<Dimension, DataType>:: rend_base() { return mFieldBasePtrs.rend(); } template<typename Dimension, typename DataType> inline typename FieldListBase<Dimension>::const_iterator FieldList<Dimension, DataType>:: begin_base() const { return mFieldBasePtrs.begin(); } template<typename Dimension, typename DataType> inline typename FieldListBase<Dimension>::const_iterator FieldList<Dimension, DataType>:: end_base() const { return mFieldBasePtrs.end(); } template<typename Dimension, typename DataType> inline typename FieldListBase<Dimension>::const_reverse_iterator FieldList<Dimension, DataType>:: rbegin_base() const { return mFieldBasePtrs.rbegin(); } template<typename Dimension, typename DataType> inline typename FieldListBase<Dimension>::const_reverse_iterator FieldList<Dimension, DataType>:: rend_base() const { return mFieldBasePtrs.rend(); } //------------------------------------------------------------------------------ // Index operator. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename FieldList<Dimension, DataType>::ElementType FieldList<Dimension, DataType>:: operator[](const unsigned int index) const { REQUIRE2(index < mFieldPtrs.size(), "FieldList index ERROR: out of bounds " << index << " !< " << mFieldPtrs.size()); return mFieldPtrs[index]; } template<typename Dimension, typename DataType> inline typename FieldList<Dimension, DataType>::ElementType FieldList<Dimension, DataType>:: operator[](const unsigned int index) { REQUIRE2(index < mFieldPtrs.size(), "FieldList index ERROR: out of bounds " << index << " !< " << mFieldPtrs.size()); return mFieldPtrs[index]; } //------------------------------------------------------------------------------ // at version, for consistency with the STL. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename FieldList<Dimension, DataType>::ElementType FieldList<Dimension, DataType>:: at(const unsigned int index) const { return (*this)[index]; } template<typename Dimension, typename DataType> inline typename FieldList<Dimension, DataType>::ElementType FieldList<Dimension, DataType>:: at(const unsigned int index) { return (*this)[index]; } //------------------------------------------------------------------------------ // Return an iterator pointing to the Field member associated with the given // NodeList. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline typename FieldList<Dimension, DataType>::iterator FieldList<Dimension, DataType>:: fieldForNodeList(const NodeList<Dimension>& nodeList) { if (haveNodeList(nodeList)) { return begin() + mNodeListIndexMap.find(&nodeList)->second; } else { return end(); } } template<typename Dimension, typename DataType> inline typename FieldList<Dimension, DataType>::const_iterator FieldList<Dimension, DataType>:: fieldForNodeList(const NodeList<Dimension>& nodeList) const { if (haveNodeList(nodeList)) { return begin() + mNodeListIndexMap.find(&nodeList)->second; } else { return end(); } } //------------------------------------------------------------------------------ // Element access by NodeIteratorBase. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline DataType& FieldList<Dimension, DataType>:: operator()(const NodeIteratorBase<Dimension>& itr) { return this->operator()(itr.fieldID(), itr.nodeID()); } template<typename Dimension, typename DataType> inline const DataType& FieldList<Dimension, DataType>:: operator()(const NodeIteratorBase<Dimension>& itr) const { return this->operator()(itr.fieldID(), itr.nodeID()); } //------------------------------------------------------------------------------ // Provide a more primitive access to Field elements, based on the index of the Field // and the node index within that field. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline DataType& FieldList<Dimension, DataType>:: operator()(const unsigned int fieldIndex, const unsigned int nodeIndex) { REQUIRE2(fieldIndex < mFieldPtrs.size(), "FieldList index ERROR: out of bounds " << fieldIndex << " !< " << mFieldPtrs.size()); REQUIRE2(nodeIndex < mFieldPtrs[fieldIndex]->size(), "FieldList node index ERROR: out of bounds " << nodeIndex << " !< " << mFieldPtrs[fieldIndex]->size()); return mFieldPtrs[fieldIndex]->operator()(nodeIndex); } template<typename Dimension, typename DataType> inline const DataType& FieldList<Dimension, DataType>:: operator()(const unsigned int fieldIndex, const unsigned int nodeIndex) const { REQUIRE2(fieldIndex < mFieldPtrs.size(), "FieldList index ERROR: out of bounds " << fieldIndex << " !< " << mFieldPtrs.size()); REQUIRE2(nodeIndex < mFieldPtrs[fieldIndex]->size(), "FieldList node index ERROR: out of bounds " << nodeIndex << " !< " << mFieldPtrs[fieldIndex]->size()); return mFieldPtrs[fieldIndex]->operator()(nodeIndex); } //------------------------------------------------------------------------------ // Return the interpolated value of the FieldList for the given position. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline DataType FieldList<Dimension, DataType>:: operator()(const typename Dimension::Vector& position, const TableKernel<Dimension>& W) const { DataType result(0.0); // Set the neighbor information for all NodeLists. std::vector<std::vector<int>> masterLists, coarseNeighbors, refineNeighbors; setMasterNodeLists(position, masterLists, coarseNeighbors); setRefineNodeLists(position, coarseNeighbors, refineNeighbors); // Loop over the neighbors. for (auto neighborItr = refineNodeBegin(refineNeighbors); neighborItr < refineNodeEnd(); ++neighborItr) { // Ignore any ghost nodes. if (neighborItr.internalNode()) { // This is horrible, but I need the node weights to do this job. This routine // needs to be rewritten! const Scalar& wj = (neighborItr.fluidNodeListPtr()->weight())(neighborItr); // Add this nodes contribution. const Vector rij = position - neighborItr.fluidNodeListPtr()->positions()(neighborItr); const SymTensor& Hj = neighborItr.fluidNodeListPtr()->Hfield()(neighborItr); double Wj = W(Hj*rij, Hj); result += (*this)(neighborItr)*wj*Wj; } } #ifdef USE_MPI // In parallel, we need to sum up the result across all processors. { int procID, numProcs; MPI_Comm_rank(Communicator::communicator(), &procID); MPI_Comm_size(Communicator::communicator(), &numProcs); VERIFY(DataTypeTraits<DataType>::fixedSize()); const size_t sizeOfElement = DataTypeTraits<DataType>::numElements()*sizeof(typename DataTypeTraits<DataType>::ElementType); std::vector<char> sendBuffer; std::vector<char> recvBuffer(sizeOfElement); packElement(result, sendBuffer); CHECK(sendBuffer.size() == sizeOfElement); for (int sendProc = 0; sendProc != numProcs; ++sendProc) { recvBuffer = sendBuffer; MPI_Bcast(&(*recvBuffer.begin()), sizeOfElement, MPI_CHAR, sendProc, Communicator::communicator()); if (procID != sendProc) { DataType otherValue; auto itr = recvBuffer.begin(); unpackElement(otherValue, itr, recvBuffer.end()); CHECK(itr == recvBuffer.end()); result += otherValue; } } } #endif return result; } //------------------------------------------------------------------------------ // Node ID iterators for all node IDs. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline AllNodeIterator<Dimension> FieldList<Dimension, DataType>::nodeBegin() const { typename std::vector<NodeList<Dimension>*>::const_iterator nodeListItr = mNodeListPtrs.begin(); while (nodeListItr < mNodeListPtrs.end() && (*nodeListItr)->numNodes() == 0) { ++nodeListItr; } return AllNodeIterator<Dimension>(nodeListItr, mNodeListPtrs.begin(), mNodeListPtrs.end()); } template<typename Dimension, typename DataType> inline AllNodeIterator<Dimension> FieldList<Dimension, DataType>::nodeEnd() const { return AllNodeIterator<Dimension>(mNodeListPtrs.end(), mNodeListPtrs.begin(), mNodeListPtrs.end()); } //------------------------------------------------------------------------------ // Node ID iterators for internal nodes. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline InternalNodeIterator<Dimension> FieldList<Dimension, DataType>::internalNodeBegin() const { typename std::vector<NodeList<Dimension>*>::const_iterator nodeListItr = mNodeListPtrs.begin(); while (nodeListItr < mNodeListPtrs.end() && (*nodeListItr)->numInternalNodes() == 0) { ++nodeListItr; } return InternalNodeIterator<Dimension>(nodeListItr, mNodeListPtrs.begin(), mNodeListPtrs.end()); } template<typename Dimension, typename DataType> inline InternalNodeIterator<Dimension> FieldList<Dimension, DataType>::internalNodeEnd() const { return InternalNodeIterator<Dimension>(mNodeListPtrs.end(), mNodeListPtrs.begin(), mNodeListPtrs.end()); } //------------------------------------------------------------------------------ // Node ID iterators for ghost nodes. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline GhostNodeIterator<Dimension> FieldList<Dimension, DataType>::ghostNodeBegin() const { auto nodeListItr = mNodeListPtrs.begin(); while (nodeListItr < mNodeListPtrs.end() && (*nodeListItr)->numGhostNodes() == 0) { ++nodeListItr; } if (nodeListItr < mNodeListPtrs.end()) { CHECK((*nodeListItr)->firstGhostNode() < (*nodeListItr)->numNodes()); return GhostNodeIterator<Dimension>(nodeListItr, mNodeListPtrs.begin(), mNodeListPtrs.end(), (*nodeListItr)->firstGhostNode()); } else { return ghostNodeEnd(); } } template<typename Dimension, typename DataType> inline GhostNodeIterator<Dimension> FieldList<Dimension, DataType>::ghostNodeEnd() const { return GhostNodeIterator<Dimension>(mNodeListPtrs.end(), mNodeListPtrs.begin(), mNodeListPtrs.end()); } //------------------------------------------------------------------------------ // Node ID iterators for master neighbor nodes. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline MasterNodeIterator<Dimension> FieldList<Dimension, DataType>::masterNodeBegin(const std::vector<std::vector<int>>& masterLists) const { auto nodeListItr = mNodeListPtrs.begin(); unsigned iNodeList = 0; while (nodeListItr < mNodeListPtrs.end() && masterLists[iNodeList].empty()) { ++nodeListItr; ++iNodeList; } if (nodeListItr < mNodeListPtrs.end()) { return MasterNodeIterator<Dimension>(nodeListItr, mNodeListPtrs.begin(), mNodeListPtrs.end(), masterLists[iNodeList].begin(), masterLists); } else { return this->masterNodeEnd(); } } template<typename Dimension, typename DataType> inline MasterNodeIterator<Dimension> FieldList<Dimension, DataType>::masterNodeEnd() const { return MasterNodeIterator<Dimension>(mNodeListPtrs.end(), mNodeListPtrs.begin(), mNodeListPtrs.end(), std::vector<std::vector<int>>()); } //------------------------------------------------------------------------------ // Node ID iterators for coarse neighbor nodes. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline CoarseNodeIterator<Dimension> FieldList<Dimension, DataType>::coarseNodeBegin(const std::vector<std::vector<int>>& coarseNeighbors) const { auto nodeListItr = mNodeListPtrs.begin(); unsigned iNodeList = 0; while (nodeListItr < mNodeListPtrs.end() && coarseNeighbors[iNodeList].empty()) { ++nodeListItr; ++iNodeList; } if (nodeListItr < mNodeListPtrs.end()) { return CoarseNodeIterator<Dimension>(nodeListItr, mNodeListPtrs.begin(), mNodeListPtrs.end(), coarseNeighbors[iNodeList].begin(), coarseNeighbors); } else { return this->coarseNodeEnd(); } } template<typename Dimension, typename DataType> inline CoarseNodeIterator<Dimension> FieldList<Dimension, DataType>::coarseNodeEnd() const { return CoarseNodeIterator<Dimension>(mNodeListPtrs.end(), mNodeListPtrs.begin(), mNodeListPtrs.end(), std::vector<std::vector<int>>()); } //------------------------------------------------------------------------------ // Node ID iterators for refine neighbor nodes. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline RefineNodeIterator<Dimension> FieldList<Dimension, DataType>::refineNodeBegin(const std::vector<std::vector<int>>& refineNeighbors) const { auto nodeListItr = mNodeListPtrs.begin(); unsigned iNodeList = 0; while (nodeListItr < mNodeListPtrs.end() && refineNeighbors[iNodeList].empty()) { ++nodeListItr; ++iNodeList; } if (nodeListItr < mNodeListPtrs.end()) { return RefineNodeIterator<Dimension>(nodeListItr, mNodeListPtrs.begin(), mNodeListPtrs.end(), refineNeighbors[iNodeList].begin(), refineNeighbors); } else { return this->refineNodeEnd(); } } template<typename Dimension, typename DataType> inline RefineNodeIterator<Dimension> FieldList<Dimension, DataType>::refineNodeEnd() const { return RefineNodeIterator<Dimension>(mNodeListPtrs.end(), mNodeListPtrs.begin(), mNodeListPtrs.end(), std::vector<std::vector<int>>()); } //------------------------------------------------------------------------------ // Set the master node lists of all the NodeLists. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>:: setMasterNodeLists(const typename Dimension::Vector& r, const typename Dimension::SymTensor& H, std::vector<std::vector<int>>& masterLists, std::vector<std::vector<int>>& coarseNeighbors) const { auto etaMax = 0.0; for (auto nodeListItr = mNodeListPtrs.begin(); nodeListItr != mNodeListPtrs.end(); ++nodeListItr) etaMax = std::max(etaMax, (**nodeListItr).neighbor().kernelExtent()); Neighbor<Dimension>::setMasterNeighborGroup(r, H, mNodeListPtrs.begin(), mNodeListPtrs.end(), etaMax, masterLists, coarseNeighbors); } template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>:: setMasterNodeLists(const typename Dimension::Vector& r, std::vector<std::vector<int>>& masterLists, std::vector<std::vector<int>>& coarseNeighbors) const { this->setMasterNodeLists(r, 1e-30*SymTensor::one, masterLists, coarseNeighbors); } //------------------------------------------------------------------------------ // Set the refine node lists of all the NodeLists. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>:: setRefineNodeLists(const typename Dimension::Vector& r, const typename Dimension::SymTensor& H, const std::vector<std::vector<int>>& coarseNeighbors, std::vector<std::vector<int>>& refineNeighbors) const { const auto numNodeLists = mNodeListPtrs.size(); REQUIRE(coarseNeighbors.size() == numNodeLists); refineNeighbors = std::vector<std::vector<int>>(numNodeLists); auto iNodeList = 0; for (auto nodeListItr = mNodeListPtrs.begin(); nodeListItr < mNodeListPtrs.end(); ++nodeListItr, ++iNodeList) { (*nodeListItr)->neighbor().setRefineNeighborList(r, H, coarseNeighbors[iNodeList], refineNeighbors[iNodeList]); } } template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>:: setRefineNodeLists(const typename Dimension::Vector& r, const std::vector<std::vector<int>>& coarseNeighbors, std::vector<std::vector<int>>& refineNeighbors) const { this->setRefineNodeLists(r, 1e-30*SymTensor::one, coarseNeighbors, refineNeighbors); } //------------------------------------------------------------------------------ // Zero out the FieldList. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>::Zero() { for (auto fieldItr = begin(); fieldItr < end(); ++fieldItr) { (*fieldItr)->Zero(); } } //------------------------------------------------------------------------------ // Apply a minimum data value. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>::applyMin(const DataType& dataMin) { for (auto fieldItr = begin(); fieldItr < end(); ++fieldItr) { (*fieldItr)->applyMin(dataMin); } } //------------------------------------------------------------------------------ // Apply a maximum data value. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>::applyMax(const DataType& dataMax) { for (auto fieldItr = begin(); fieldItr < end(); ++fieldItr) { (*fieldItr)->applyMax(dataMax); } } //------------------------------------------------------------------------------ // Apply a (double) minimum data value. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>::applyScalarMin(const double dataMin) { for (auto fieldItr = begin(); fieldItr < end(); ++fieldItr) { (*fieldItr)->applyScalarMin(dataMin); } } //------------------------------------------------------------------------------ // Apply a (double) maximum data value. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>::applyScalarMax(const double dataMax) { for (auto fieldItr = begin(); fieldItr < end(); ++fieldItr) { (*fieldItr)->applyScalarMax(dataMax); } } //------------------------------------------------------------------------------ // Add two FieldLists. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType> FieldList<Dimension, DataType>::operator+(const FieldList<Dimension, DataType>& rhs) const { // Pre-conditions. BEGIN_CONTRACT_SCOPE REQUIRE(numFields() == rhs.numFields()); for (int i = 0; i != (int)numFields(); ++i) REQUIRE(mFieldPtrs[i]->nodeListPtr() == rhs[i]->nodeListPtr()); END_CONTRACT_SCOPE FieldList<Dimension, DataType> result(*this); result.copyFields(); result += rhs; return result; } //------------------------------------------------------------------------------ // Subtract a FieldList from another. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType> FieldList<Dimension, DataType>::operator-(const FieldList<Dimension, DataType>& rhs) const { // Pre-conditions. BEGIN_CONTRACT_SCOPE REQUIRE(numFields() == rhs.numFields()); for (int i = 0; i != (int)numFields(); ++i) REQUIRE(mFieldPtrs[i]->nodeListPtr() == rhs[i]->nodeListPtr()); END_CONTRACT_SCOPE FieldList<Dimension, DataType> result(*this); result.copyFields(); result -= rhs; return result; } //------------------------------------------------------------------------------ // Add two FieldLists in place. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType>& FieldList<Dimension, DataType>::operator+=(const FieldList<Dimension, DataType>& rhs) { // Pre-conditions. BEGIN_CONTRACT_SCOPE REQUIRE(numFields() == rhs.numFields()); for (auto i = 0u; i != numFields(); ++i) REQUIRE(mFieldPtrs[i]->nodeListPtr() == rhs[i]->nodeListPtr()); END_CONTRACT_SCOPE for (auto i = 0u; i < numFields(); ++i) { CHECK2((*this)[i]->nodeListPtr() == rhs[i]->nodeListPtr(), (*this)[i]->nodeListPtr()->name() << " != " << rhs[i]->nodeListPtr()->name()); *((*this)[i]) += *(rhs[i]); } return *this; } //------------------------------------------------------------------------------ // Subtract a FieldList from another in place. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType>& FieldList<Dimension, DataType>::operator-=(const FieldList<Dimension, DataType>& rhs) { // Pre-conditions. BEGIN_CONTRACT_SCOPE REQUIRE(numFields() == rhs.numFields()); for (int i = 0; i != (int)numFields(); ++i) REQUIRE(mFieldPtrs[i]->nodeListPtr() == rhs[i]->nodeListPtr()); END_CONTRACT_SCOPE for (auto i = 0u; i < numFields(); ++i) { CHECK2((*this)[i]->nodeListPtr() == rhs[i]->nodeListPtr(), (*this)[i]->nodeListPtr()->name() << " != " << rhs[i]->nodeListPtr()->name()); *((*this)[i]) -= *(rhs[i]); } return *this; } //------------------------------------------------------------------------------ // Add a single value to a FieldList. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType> FieldList<Dimension, DataType>::operator+(const DataType& rhs) const { FieldList<Dimension, DataType> result(*this); result.copyFields(); result += rhs; return result; } //------------------------------------------------------------------------------ // Subtract a single value from a Field. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType> FieldList<Dimension, DataType>::operator-(const DataType& rhs) const { FieldList<Dimension, DataType> result(*this); result.copyFields(); result -= rhs; return result; } //------------------------------------------------------------------------------ // Add a single value to the Field in place. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType>& FieldList<Dimension, DataType>::operator+=(const DataType& rhs) { for (auto i = 0u; i < numFields(); ++i) { *((*this)[i]) += rhs; } return *this; } //------------------------------------------------------------------------------ // Subtract a single value from the FieldList in place. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType>& FieldList<Dimension, DataType>::operator-=(const DataType& rhs) { for (auto i = 0u; i < numFields(); ++i) { *((*this)[i]) -= rhs; } return *this; } //------------------------------------------------------------------------------ // Multiply this FieldList by a Scalar FieldList in place. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType>& FieldList<Dimension, DataType>:: operator*=(const FieldList<Dimension, typename Dimension::Scalar>& rhs) { REQUIRE(this->numFields() == rhs.numFields()); for (auto i = 0u; i < numFields(); ++i) { CHECK2((*this)[i]->nodeListPtr() == rhs[i]->nodeListPtr(), (*this)[i]->nodeListPtr()->name() << " != " << rhs[i]->nodeListPtr()->name()); *((*this)[i]) *= *(rhs[i]); } return *this; } //------------------------------------------------------------------------------ // Multiply this FieldList by a Scalar in place. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType>& FieldList<Dimension, DataType>::operator*=(const Scalar& rhs) { for (auto i = 0u; i < numFields(); ++i) { *((*this)[i]) *= rhs; } return *this; } //------------------------------------------------------------------------------ // Divide this FieldList by a Scalar FieldList. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType> FieldList<Dimension, DataType>:: operator/(const FieldList<Dimension, typename Dimension::Scalar>& rhs) const { REQUIRE(this->numFields() == rhs.numFields()); FieldList<Dimension, DataType> result(*this); result.copyFields(); result /= rhs; return result; } //------------------------------------------------------------------------------ // Divide this FieldList by a Scalar value. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType> FieldList<Dimension, DataType>::operator/(const Scalar& rhs) const { REQUIRE(rhs != 0.0); FieldList<Dimension, DataType> result(*this); result.copyFields(); result /= rhs; return result; } //------------------------------------------------------------------------------ // Divide this FieldList by a Scalar FieldList in place. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType>& FieldList<Dimension, DataType>:: operator/=(const FieldList<Dimension, typename Dimension::Scalar>& rhs) { REQUIRE(this->numFields() == rhs.numFields()); for (auto i = 0u; i < numFields(); ++i) { CHECK2((*this)[i]->nodeListPtr() == rhs[i]->nodeListPtr(), (*this)[i]->nodeListPtr()->name() << " != " << rhs[i]->nodeListPtr()->name()); *((*this)[i]) /= *(rhs[i]); } return *this; } //------------------------------------------------------------------------------ // Divide this FieldList by a Scalar in place. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType>& FieldList<Dimension, DataType>::operator/=(const typename Dimension::Scalar& rhs) { REQUIRE(rhs != 0.0); for (auto i = 0u; i < numFields(); ++i) { *((*this)[i]) /= rhs; } return *this; } //------------------------------------------------------------------------------ // Sum the field elements. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline DataType FieldList<Dimension, DataType>:: sumElements() const { return allReduce(this->localSumElements(), MPI_SUM, Communicator::communicator()); } //------------------------------------------------------------------------------ // Find the minimum. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline DataType FieldList<Dimension, DataType>:: min() const { return allReduce(this->localMin(), MPI_MIN, Communicator::communicator()); } //------------------------------------------------------------------------------ // Find the maximum. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline DataType FieldList<Dimension, DataType>:: max() const { return allReduce(this->localMax(), MPI_MAX, Communicator::communicator()); } //------------------------------------------------------------------------------ // Sum the field elements. // LOCAL to processor! //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline DataType FieldList<Dimension, DataType>:: localSumElements() const { auto result = DataTypeTraits<DataType>::zero(); for (auto itr = begin(); itr < end(); ++itr) result += (*itr)->localSumElements(); return result; } //------------------------------------------------------------------------------ // Find the minimum. // LOCAL to processor! //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline DataType FieldList<Dimension, DataType>:: localMin() const { auto result = std::numeric_limits<DataType>::max(); for (auto itr = begin(); itr != end(); ++itr) result = std::min(result, (*itr)->localMin()); return result; } //------------------------------------------------------------------------------ // Find the maximum. // LOCAL to processor! //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline DataType FieldList<Dimension, DataType>:: localMax() const { auto result = -std::numeric_limits<DataType>::max() < std::numeric_limits<DataType>::min() ? -std::numeric_limits<DataType>::max() : std::numeric_limits<DataType>::min(); for (auto itr = begin(); itr < end(); ++itr) result = std::max(result, (*itr)->localMax()); return result; } //------------------------------------------------------------------------------ // operator== //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool FieldList<Dimension, DataType>:: operator==(const FieldList<Dimension, DataType>& rhs) const { // Pre-conditions. BEGIN_CONTRACT_SCOPE REQUIRE(numFields() == rhs.numFields()); for (int i = 0; i != (int)numFields(); ++i) REQUIRE(mFieldPtrs[i]->nodeListPtr() == rhs[i]->nodeListPtr()); END_CONTRACT_SCOPE bool result = true; int i = 0; while (result && i != (int)numFields()) { result = result && (*(mFieldPtrs[i]) == *(rhs[i])); ++i; } return result; } //------------------------------------------------------------------------------ // operator!= //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool FieldList<Dimension, DataType>:: operator!=(const FieldList<Dimension, DataType>& rhs) const { return !(operator==(rhs)); } //------------------------------------------------------------------------------ // operator> //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool FieldList<Dimension, DataType>:: operator>(const FieldList<Dimension, DataType>& rhs) const { // Pre-conditions. BEGIN_CONTRACT_SCOPE REQUIRE(numFields() == rhs.numFields()); for (int i = 0; i != numFields(); ++i) REQUIRE(mFieldPtrs[i]->nodeListPtr() == rhs[i]->nodeListPtr()); END_CONTRACT_SCOPE bool result = true; int i = 0; while (result && i != numFields()) { result = result && (*(mFieldPtrs[i]) > *(rhs[i])); ++i; } return result; } //------------------------------------------------------------------------------ // operator< //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool FieldList<Dimension, DataType>:: operator<(const FieldList<Dimension, DataType>& rhs) const { // Pre-conditions. BEGIN_CONTRACT_SCOPE REQUIRE(numFields() == rhs.numFields()); for (int i = 0; i != numFields(); ++i) REQUIRE(mFieldPtrs[i]->nodeListPtr() == rhs[i]->nodeListPtr()); END_CONTRACT_SCOPE bool result = true; int i = 0; while (result && i != numFields()) { result = result && (*(mFieldPtrs[i]) < *(rhs[i])); ++i; } return result; } //------------------------------------------------------------------------------ // operator>= //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool FieldList<Dimension, DataType>:: operator>=(const FieldList<Dimension, DataType>& rhs) const { return operator>(rhs) || operator==(rhs); } //------------------------------------------------------------------------------ // operator<= //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool FieldList<Dimension, DataType>:: operator<=(const FieldList<Dimension, DataType>& rhs) const { return operator<(rhs) || operator==(rhs); } //------------------------------------------------------------------------------ // operator== //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool FieldList<Dimension, DataType>:: operator==(const DataType& rhs) const { bool result = true; int i = 0; while (result && i != (int)numFields()) { result = result && (*(mFieldPtrs[i]) == rhs); ++i; } return result; } //------------------------------------------------------------------------------ // operator!= //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool FieldList<Dimension, DataType>:: operator!=(const DataType& rhs) const { return !(operator==(rhs)); } //------------------------------------------------------------------------------ // operator> //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool FieldList<Dimension, DataType>:: operator>(const DataType& rhs) const { bool result = true; int i = 0; while (result && i != (int)numFields()) { result = result && (*(mFieldPtrs[i]) > rhs); ++i; } return result; } //------------------------------------------------------------------------------ // operator< //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool FieldList<Dimension, DataType>:: operator<(const DataType& rhs) const { bool result = true; int i = 0; while (result && i != (int)numFields()) { result = result && (*(mFieldPtrs[i]) < rhs); ++i; } return result; } //------------------------------------------------------------------------------ // operator>= //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool FieldList<Dimension, DataType>:: operator>=(const DataType& rhs) const { return operator>(rhs) || operator==(rhs); } //------------------------------------------------------------------------------ // operator<= //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline bool FieldList<Dimension, DataType>:: operator<=(const DataType& rhs) const { return operator<(rhs) || operator==(rhs); } //------------------------------------------------------------------------------ // Return the number of Fields stored in this Field List. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline unsigned FieldList<Dimension, DataType>::numFields() const { return mFieldPtrs.size(); } template<typename Dimension, typename DataType> inline unsigned FieldList<Dimension, DataType>::size() const { return numFields(); } template<typename Dimension, typename DataType> inline unsigned FieldList<Dimension, DataType>::numNodes() const { unsigned numberOfNodes = 0; for (auto iter = begin(); iter != end(); ++iter) { numberOfNodes += (*iter)->nodeList().numNodes(); } return numberOfNodes; } template<typename Dimension, typename DataType> inline unsigned FieldList<Dimension, DataType>::numInternalNodes() const { unsigned numberOfNodes = 0; for (auto iter = begin(); iter != end(); ++iter) { numberOfNodes += (*iter)->nodeList().numInternalNodes(); } return numberOfNodes; } template<typename Dimension, typename DataType> inline unsigned FieldList<Dimension, DataType>::numGhostNodes() const { unsigned numberOfNodes = 0; for (auto iter = begin(); iter != end(); ++iter) { numberOfNodes += (*iter)->nodeList().numGhostNodes(); } return numberOfNodes; } //------------------------------------------------------------------------------ // Return the set of NodeList pointers. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline const std::vector<NodeList<Dimension>*>& FieldList<Dimension, DataType>:: nodeListPtrs() const { return mNodeListPtrs; } //------------------------------------------------------------------------------ // All internal values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline std::vector<DataType> FieldList<Dimension, DataType>:: internalValues() const { const size_t ntot = this->numInternalNodes(); std::vector<DataType> result(ntot); size_t offset = 0; for (auto itr = this->begin(); itr != this->end(); ++itr) { const auto n = (*itr)->numInternalElements(); std::copy((*itr)->begin(), (*itr)->begin() + n, result.begin() + offset); offset += n; } CHECK(offset == ntot); return result; } //------------------------------------------------------------------------------ // All ghost values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline std::vector<DataType> FieldList<Dimension, DataType>:: ghostValues() const { const size_t ntot = this->numGhostNodes(); std::vector<DataType> result(ntot); size_t offset = 0; for (auto itr = this->begin(); itr != this->end(); ++itr) { const auto n = (*itr)->numGhostElements(); std::copy((*itr)->begin(), (*itr)->begin() + n, result.begin() + offset); offset += n; } CHECK(offset == ntot); return result; } //------------------------------------------------------------------------------ // All values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline std::vector<DataType> FieldList<Dimension, DataType>:: allValues() const { const size_t ntot = this->numNodes(); std::vector<DataType> result(ntot); size_t offset = 0; for (auto itr = this->begin(); itr != this->end(); ++itr) { const auto n = (*itr)->numElements(); std::copy((*itr)->begin(), (*itr)->begin() + n, result.begin() + offset); offset += n; } CHECK(offset == ntot); return result; } //------------------------------------------------------------------------------ // Internal method to build the NodeListIndexMap from scratch. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>:: buildNodeListIndexMap() { mNodeListIndexMap = HashMapType(); int i = 0; for (auto itr = begin(); itr != end(); ++itr, ++i) mNodeListIndexMap[(*itr)->nodeListPtr()] = i; ENSURE(mNodeListIndexMap.size() == numFields()); } //------------------------------------------------------------------------------ // Make a thread local copy of the FieldList -- assumes we're already in a // threaded region. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType> FieldList<Dimension, DataType>:: threadCopy(const ThreadReduction reductionType, const bool copy) { FieldList<Dimension, DataType> result; #pragma omp critical (FieldList_threadCopy) { if (omp_get_num_threads() == 1) { // In serial we can skip all the work copying result.referenceFields(*this); } else if (copy or reductionType == ThreadReduction::MIN or reductionType == ThreadReduction::MAX) { // For min/max operations, we need to copy the original data result.copyFields(*this); } else { // Otherwise make standalone Fields of zeros result = FieldList<Dimension, DataType>(FieldStorageType::CopyFields); for (auto fitr = this->begin(); fitr < this->end(); ++fitr) result.appendNewField((*fitr)->name(), (*fitr)->nodeList(), DataTypeTraits<DataType>::zero()); } result.reductionType = reductionType; result.threadMasterPtr = this; } return result; } template<typename Dimension, typename DataType> inline FieldList<Dimension, DataType> FieldList<Dimension, DataType>:: threadCopy(typename SpheralThreads<Dimension>::FieldListStack& stack, const ThreadReduction reductionType, const bool copy) { FieldList<Dimension, DataType> result = this->threadCopy(reductionType, copy); stack.push_back(&result); return result; } //------------------------------------------------------------------------------ // Reduce the values in the FieldList with the passed thread-local values. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType> inline void FieldList<Dimension, DataType>:: threadReduce() const { REQUIRE(threadMasterPtr != NULL); REQUIRE(threadMasterPtr->size() == this->size()); if (omp_get_num_threads() > 1) { const auto numNL = this->size(); for (auto k = 0u; k < numNL; ++k) { const auto n = mFieldPtrs[k]->numInternalElements(); for (auto i = 0u; i < n; ++i) { switch (reductionType) { case ThreadReduction::SUM: (*threadMasterPtr)(k,i) += (*this)(k,i); break; case ThreadReduction::MIN: (*threadMasterPtr)(k,i) = std::min((*threadMasterPtr)(k,i), (*this)(k,i)); break; case ThreadReduction::MAX: (*threadMasterPtr)(k,i) = std::max((*threadMasterPtr)(k,i), (*this)(k,i)); break; } } } } } //****************************** Global Functions ****************************** //------------------------------------------------------------------------------ // Multiply a FieldList by another FieldList. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType, typename OtherDataType> inline FieldList<Dimension, typename CombineTypes<DataType, OtherDataType>::ProductType> operator*(const FieldList<Dimension, DataType>& lhs, const FieldList<Dimension, OtherDataType>& rhs) { REQUIRE(lhs.numFields() == rhs.numFields()); FieldList<Dimension, typename CombineTypes<DataType, OtherDataType>::ProductType> result; result.copyFields(); for (auto i = 0u; i < lhs.numFields(); ++i) { CHECK2(lhs[i]->nodeListPtr() == rhs[i]->nodeListPtr(), lhs[i]->nodeListPtr()->name() << " != " << rhs[i]->nodeListPtr()->name()); result.appendField((*(lhs[i])) * (*(rhs[i]))); } return result; } //------------------------------------------------------------------------------ // Multiply a FieldList by a single value. //------------------------------------------------------------------------------ template<typename Dimension, typename DataType, typename OtherDataType> inline FieldList<Dimension, typename CombineTypes<DataType, OtherDataType>::ProductType> operator*(const FieldList<Dimension, DataType>& lhs, const OtherDataType& rhs) { FieldList<Dimension, typename CombineTypes<DataType, OtherDataType>::ProductType> result; result.copyFields(); for (int i = 0; i < lhs.numFields(); ++i) { result.appendField((*(lhs[i])) * rhs); } return result; } template<typename Dimension, typename DataType, typename OtherDataType> inline FieldList<Dimension, typename CombineTypes<DataType, OtherDataType>::ProductType> operator*(const DataType& lhs, const FieldList<Dimension, OtherDataType>& rhs) { FieldList<Dimension, typename CombineTypes<DataType, OtherDataType>::ProductType> result; result.copyFields(); for (auto i = 0u; i < rhs.numFields(); ++i) { result.appendField(lhs * (*(rhs[i]))); } return result; } // //------------------------------------------------------------------------------ // // Absolute value. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // abs(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(abs(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Inverse cosine. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // acos(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(acos(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Inverse sine. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // asin(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(asin(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Inverse tangent. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // atan(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(atan(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Inverse tangent2. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // atan2(const FieldList<Dimension, typename Dimension::Scalar>& fieldList1, // const FieldList<Dimension, typename Dimension::Scalar>& fieldList2) { // REQUIRE(fieldList1.numFields() == fieldList2.numFields()); // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList1.numFields(); ++i) { // result.appendField(atan2(*(fieldList1[i]), *(fieldList2[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Ceiling. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // ceil(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(ceil(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Cosine. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // cos(FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(cos(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Hyperbolic cosine. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // cosh(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(cosh(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Exponential. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // exp(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(exp(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Absolute value. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // fabs(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(fabs(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Floor. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // floor(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(floor(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Natural logarithm. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // log(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(log(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Log base 10. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // log10(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(log10(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // powN. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // pow2(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(pow2(*(fieldList[i]))); // } // return result; // } // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // pow3(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(pow3(*(fieldList[i]))); // } // return result; // } // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // pow4(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(pow4(*(fieldList[i]))); // } // return result; // } // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // pow5(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(pow5(*(fieldList[i]))); // } // return result; // } // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // pow6(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(pow6(*(fieldList[i]))); // } // return result; // } // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // pow7(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(pow7(*(fieldList[i]))); // } // return result; // } // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // pow8(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(pow8(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Sine. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // sin(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(sin(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Hyperbolic sine. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // sinh(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(sinh(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Square. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // sqr(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(sqr(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Square root. // //------------------------------------------------------------------------------ // template<typename Dimension> // inline // FieldList<Dimension, typename Dimension::Scalar> // sqrt(const FieldList<Dimension, typename Dimension::Scalar>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(sqrt(*(fieldList[i]))); // } // return result; // } // //------------------------------------------------------------------------------ // // Minimum. // //------------------------------------------------------------------------------ // template<typename Dimension, typename DataType> // inline // FieldList<Dimension, DataType> // min(const FieldList<Dimension, DataType>& fieldList1, // const FieldList<Dimension, DataType>& fieldList2) { // REQUIRE(fieldList1.numFields() == fieldList2.numFields()); // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList1.numFields(); ++i) { // result.appendField(min(*(fieldList1[i]), *(fieldList2[i]))); // } // return result; // } // template<typename Dimension, typename DataType> // inline // FieldList<Dimension, DataType> // min(const DataType& value, // const FieldList<Dimension, DataType>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(min(value, *(fieldList[i]))); // } // return result; // } // template<typename Dimension, typename DataType> // inline // FieldList<Dimension, DataType> // min(const FieldList<Dimension, DataType>& fieldList, // const DataType& value) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(min(*(fieldList[i]), value)); // } // return result; // } // //------------------------------------------------------------------------------ // // Maximum. // //------------------------------------------------------------------------------ // template<typename Dimension, typename DataType> // inline // FieldList<Dimension, DataType> // max(const FieldList<Dimension, DataType>& fieldList1, // const FieldList<Dimension, DataType>& fieldList2) { // REQUIRE(fieldList1.numFields() == fieldList2.numFields()); // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList1.numFields(); ++i) { // result.appendField(max(*(fieldList1[i]), *(fieldList2[i]))); // } // return result; // } // template<typename Dimension, typename DataType> // inline // FieldList<Dimension, DataType> // max(const DataType& value, // const FieldList<Dimension, DataType>& fieldList) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(max(value, *(fieldList[i]))); // } // return result; // } // template<typename Dimension, typename DataType> // inline // FieldList<Dimension, DataType> // max(const FieldList<Dimension, DataType>& fieldList, // const DataType& value) { // FieldList<Dimension, typename Dimension::Scalar> result; // result.copyFields(); // for (int i = 0; i < fieldList.numFields(); ++i) { // result.appendField(max(*(fieldList[i]), value)); // } // return result; // } }
36.154808
172
0.547189
[ "geometry", "vector" ]
cb5752994c794902f61b4b408ca04b78409430df
23,725
cpp
C++
SRC/element/UWelements/SSPquad.cpp
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
8
2019-03-05T16:25:10.000Z
2020-04-17T14:12:03.000Z
SRC/element/UWelements/SSPquad.cpp
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
null
null
null
SRC/element/UWelements/SSPquad.cpp
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
3
2019-09-21T03:11:11.000Z
2020-01-19T07:29:37.000Z
/* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** Frank McKenna (fmckenna@ce.berkeley.edu) ** ** Gregory L. Fenves (fenves@ce.berkeley.edu) ** ** Filip C. Filippou (filippou@ce.berkeley.edu) ** ** ** ** ****************************************************************** */ // Created: Chris McGann, UW, 04.2011 // // Description: This file contains the implementation of the SSPquad class // // Reference: McGann, C.R., Arduino, P., and Mackenzie-Helnwein, P. (2012) "Stabilized single-point // 4-node quadrilateral element for dynamic analysis of fluid saturated porous media." // Acta Geotechnica, 7(4):297-311 #include "SSPquad.h" #include <elementAPI.h> #include <Information.h> #include <ElementResponse.h> #include <ElementalLoad.h> #include <ID.h> #include <Domain.h> #include <Node.h> #include <Channel.h> #include <Message.h> #include <FEM_ObjectBroker.h> #include <Renderer.h> #include <G3Globals.h> #include <ErrorHandler.h> #include <NDMaterial.h> #include <Parameter.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #define OPS_Export static int num_SSPquad = 0; OPS_Export void * OPS_SSPquad(void) { if (num_SSPquad == 0) { num_SSPquad++; opserr << "SSPquad element - Written: C.McGann, P.Arduino, P.Mackenzie-Helnwein, U.Washington\n"; } // Pointer to an element that will be returned Element *theElement = 0; int numRemainingInputArgs = OPS_GetNumRemainingInputArgs(); if (numRemainingInputArgs < 8) { opserr << "Invalid #args, want: element SSPquad eleTag? iNode? jNode? kNode? lNode? matTag? type? thickness? <b1? b2?>?\n"; return 0; } int iData[6]; const char *theType; double dData[3] = { 1.0,0.0,0.0 }; int numData = 6; if (OPS_GetIntInput(&numData, iData) != 0) { opserr << "WARNING invalid integer data: element SSPquad " << iData[0] << endln; return 0; } theType = OPS_GetString(); numData = 1; if (OPS_GetDoubleInput(&numData, dData) != 0) { opserr << "WARNING invalid thickness data: element SSPquad " << iData[0] << endln; return 0; } int matID = iData[5]; NDMaterial *theMaterial = OPS_getNDMaterial(matID); if (theMaterial == 0) { opserr << "WARNING element SSPquad " << iData[0] << endln; opserr << " Material: " << matID << "not found\n"; return 0; } if (numRemainingInputArgs == 10) { numData = 2; if (OPS_GetDoubleInput(&numData, &dData[1]) != 0) { opserr << "WARNING invalid optional data: element SSPquad " << iData[0] << endln; return 0; } } // parsing was successful, allocate the element theElement = new SSPquad(iData[0], iData[1], iData[2], iData[3], iData[4], *theMaterial, theType, dData[0], dData[1], dData[2]); if (theElement == 0) { opserr << "WARNING could not create element of type SSPquad\n"; return 0; } return theElement; } // full constructor SSPquad::SSPquad(int tag, int Nd1, int Nd2, int Nd3, int Nd4, NDMaterial &theMat, const char *type, double thick, double b1, double b2) :Element(tag,ELE_TAG_SSPquad), theMaterial(0), mExternalNodes(SSPQ_NUM_NODE), mTangentStiffness(SSPQ_NUM_DOF,SSPQ_NUM_DOF), mInternalForces(SSPQ_NUM_DOF), Q(SSPQ_NUM_DOF), mMass(SSPQ_NUM_DOF,SSPQ_NUM_DOF), mNodeCrd(2,4), Mmem(3,SSPQ_NUM_DOF), Kstab(SSPQ_NUM_DOF,SSPQ_NUM_DOF), mThickness(thick), applyLoad(0) { mExternalNodes(0) = Nd1; mExternalNodes(1) = Nd2; mExternalNodes(2) = Nd3; mExternalNodes(3) = Nd4; mThickness = thick; b[0] = b1; b[1] = b2; appliedB[0] = 0.0; appliedB[1] = 0.0; // get copy of the material object NDMaterial *theMatCopy = theMat.getCopy(type); if (theMatCopy != 0) { theMaterial = (NDMaterial *)theMatCopy; } else { opserr << "SSPquad::SSPquad - failed to get copy of material model\n";; } // check material if (theMaterial == 0) { opserr << "SSPquad::SSPquad - failed to allocate material model pointer\n"; exit(-1); } // check the type if (strcmp(type,"PlaneStrain") != 0 && strcmp(type,"PlaneStress") != 0) { opserr << "SSPquad::SSPquad - improper material type: " << type << "for SSPquad\n"; exit(-1); } } // null constructor SSPquad::SSPquad() :Element(0,ELE_TAG_SSPquad), theMaterial(0), mExternalNodes(SSPQ_NUM_NODE), mTangentStiffness(SSPQ_NUM_DOF,SSPQ_NUM_DOF), mInternalForces(SSPQ_NUM_DOF), Q(SSPQ_NUM_DOF), mMass(SSPQ_NUM_DOF,SSPQ_NUM_DOF), mNodeCrd(2,4), Mmem(3,SSPQ_NUM_DOF), Kstab(SSPQ_NUM_DOF,SSPQ_NUM_DOF), mThickness(0), applyLoad(0) { } // destructor SSPquad::~SSPquad() { if (theMaterial != 0) { delete theMaterial; } } int SSPquad::getNumExternalNodes(void) const { return SSPQ_NUM_NODE; } const ID & SSPquad::getExternalNodes(void) { return mExternalNodes; } Node ** SSPquad::getNodePtrs(void) { return theNodes; } int SSPquad::getNumDOF(void) { return SSPQ_NUM_DOF; } void SSPquad::setDomain(Domain *theDomain) { theNodes[0] = theDomain->getNode(mExternalNodes(0)); theNodes[1] = theDomain->getNode(mExternalNodes(1)); theNodes[2] = theDomain->getNode(mExternalNodes(2)); theNodes[3] = theDomain->getNode(mExternalNodes(3)); for (int i = 0; i < 4; i++) { if (theNodes[i] == 0) { return; // don't go any further - otherwise segmentation fault } } // initialize coordinate vectors const Vector &mIcrd_1 = theNodes[0]->getCrds(); const Vector &mIcrd_2 = theNodes[1]->getCrds(); const Vector &mIcrd_3 = theNodes[2]->getCrds(); const Vector &mIcrd_4 = theNodes[3]->getCrds(); // coordinate matrix mNodeCrd(0,0) = mIcrd_1(0); mNodeCrd(1,0) = mIcrd_1(1); mNodeCrd(0,1) = mIcrd_2(0); mNodeCrd(1,1) = mIcrd_2(1); mNodeCrd(0,2) = mIcrd_3(0); mNodeCrd(1,2) = mIcrd_3(1); mNodeCrd(0,3) = mIcrd_4(0); mNodeCrd(1,3) = mIcrd_4(1); // establish jacobian terms J0 = ((mNodeCrd(0,1)-mNodeCrd(0,3))*(mNodeCrd(1,2)-mNodeCrd(1,0))+(mNodeCrd(0,2)-mNodeCrd(0,0))*(mNodeCrd(1,3)-mNodeCrd(1,1)))/8; J1 = ((mNodeCrd(0,1)-mNodeCrd(0,0))*(mNodeCrd(1,2)-mNodeCrd(1,3))+(mNodeCrd(0,2)-mNodeCrd(0,3))*(mNodeCrd(1,0)-mNodeCrd(1,1)))/24; J2 = ((mNodeCrd(0,0)-mNodeCrd(0,3))*(mNodeCrd(1,2)-mNodeCrd(1,1))+(mNodeCrd(0,2)-mNodeCrd(0,1))*(mNodeCrd(1,3)-mNodeCrd(1,0)))/24; // establish stabilization terms (based on initial material tangent, only need to compute once) GetStab(); // call the base-class method this->DomainComponent::setDomain(theDomain); } int SSPquad::commitState(void) { int retVal = 0; // call element commitState to do any base class stuff if ((retVal = this->Element::commitState()) != 0) { opserr << "SSPquad::commitState() - failed in base class\n"; } retVal = theMaterial->commitState(); return retVal; } int SSPquad::revertToLastCommit(void) { return theMaterial->revertToLastCommit(); } int SSPquad::revertToStart(void) { return theMaterial->revertToStart(); } int SSPquad::update(void) // this function updates variables for an incremental step n to n+1 { // get trial displacement const Vector &mDisp_1 = theNodes[0]->getTrialDisp(); const Vector &mDisp_2 = theNodes[1]->getTrialDisp(); const Vector &mDisp_3 = theNodes[2]->getTrialDisp(); const Vector &mDisp_4 = theNodes[3]->getTrialDisp(); // assemble displacement vector Vector u(8); u(0) = mDisp_1(0); u(1) = mDisp_1(1); u(2) = mDisp_2(0); u(3) = mDisp_2(1); u(4) = mDisp_3(0); u(5) = mDisp_3(1); u(6) = mDisp_4(0); u(7) = mDisp_4(1); Vector strain(3); strain = Mmem*u; theMaterial->setTrialStrain(strain); return 0; } const Matrix & SSPquad::getTangentStiff(void) // this function computes the tangent stiffness matrix for the element { // get material tangent const Matrix &Cmat = theMaterial->getTangent(); // full element stiffness matrix mTangentStiffness = Kstab; mTangentStiffness.addMatrixTripleProduct(1.0, Mmem, Cmat, 4.0*J0*mThickness); return mTangentStiffness; } const Matrix & SSPquad::getInitialStiff(void) // this function computes the initial tangent stiffness matrix for the element { return getTangentStiff(); } const Matrix & SSPquad::getMass(void) { mMass.Zero(); // get mass density from the material double density = theMaterial->getRho(); // return zero matrix if density is zero if (density == 0.0) { return mMass; } // local coordinates of nodes double xi[4]; double eta[4]; xi[0] = -1.0; xi[1] = 1.0; xi[2] = 1.0; xi[3] = -1.0; eta[0] = -1.0; eta[1] = -1.0; eta[2] = 1.0; eta[3] = 1.0; double massTerm; for (int i = 0; i < 4; i++) { massTerm = density*mThickness*(J0 + J1*xi[i] + J2*eta[i]); mMass(2*i,2*i) += massTerm; mMass(2*i+1,2*i+1) += massTerm; } return mMass; } void SSPquad::zeroLoad(void) { applyLoad = 0; appliedB[0] = 0.0; appliedB[1] = 0.0; Q.Zero(); return; } int SSPquad::addLoad(ElementalLoad *theLoad, double loadFactor) { // body forces can be applied in a load pattern int type; const Vector &data = theLoad->getData(type, loadFactor); if (type == LOAD_TAG_SelfWeight) { applyLoad = 1; appliedB[0] += loadFactor*data(0)*b[0]; appliedB[1] += loadFactor*data(1)*b[1]; return 0; } else { opserr << "SSPquad::addLoad - load type unknown for ele with tag: " << this->getTag() << endln; return -1; } return -1; } int SSPquad::addInertiaLoadToUnbalance(const Vector &accel) { // get mass density from the material double density = theMaterial->getRho(); // do nothing if density is zero if (density == 0.0) { return 0; } // Get R * accel from the nodes const Vector &Raccel1 = theNodes[0]->getRV(accel); const Vector &Raccel2 = theNodes[1]->getRV(accel); const Vector &Raccel3 = theNodes[2]->getRV(accel); const Vector &Raccel4 = theNodes[3]->getRV(accel); if (2 != Raccel1.Size() || 2 != Raccel2.Size() || 2 != Raccel3.Size() || 2 != Raccel4.Size()) { opserr << "FourNodeQuad::addInertiaLoadToUnbalance matrix and vector sizes are incompatible\n"; return -1; } static double ra[8]; ra[0] = Raccel1(0); ra[1] = Raccel1(1); ra[2] = Raccel2(0); ra[3] = Raccel2(1); ra[4] = Raccel3(0); ra[5] = Raccel3(1); ra[6] = Raccel4(0); ra[7] = Raccel4(1); // compute mass matrix this->getMass(); for (int i = 0; i < 8; i++) { Q(i) += -mMass(i,i)*ra[i]; } return 0; } const Vector & SSPquad::getResistingForce(void) // this function computes the resisting force vector for the element { // get stress from the material Vector mStress = theMaterial->getStress(); // get trial displacement const Vector &mDisp_1 = theNodes[0]->getTrialDisp(); const Vector &mDisp_2 = theNodes[1]->getTrialDisp(); const Vector &mDisp_3 = theNodes[2]->getTrialDisp(); const Vector &mDisp_4 = theNodes[3]->getTrialDisp(); Vector d(8); d(0) = mDisp_1(0); d(1) = mDisp_1(1); d(2) = mDisp_2(0); d(3) = mDisp_2(1); d(4) = mDisp_3(0); d(5) = mDisp_3(1); d(6) = mDisp_4(0); d(7) = mDisp_4(1); // add stabilization force to internal force vector mInternalForces = Kstab*d; // add internal force from the stress -> fint = Kstab*d + 4*t*Jo*Mmem'*stress mInternalForces.addMatrixTransposeVector(1.0, Mmem, mStress, 4.0*mThickness*J0); // subtract body forces from internal force vector double xi[4]; double eta[4]; xi[0] = -1.0; xi[1] = 1.0; xi[2] = 1.0; xi[3] = -1.0; eta[0] = -1.0; eta[1] = -1.0; eta[2] = 1.0; eta[3] = 1.0; if (applyLoad == 0) { for (int i = 0; i < 4; i++) { mInternalForces(2*i) -= b[0]*mThickness*(J0 + J1*xi[i] + J2*eta[i]); mInternalForces(2*i+1) -= b[1]*mThickness*(J0 + J1*xi[i] + J2*eta[i]); } } else { for (int i = 0; i < 4; i++) { mInternalForces(2*i) -= appliedB[0]*mThickness*(J0 + J1*xi[i] + J2*eta[i]); mInternalForces(2*i+1) -= appliedB[1]*mThickness*(J0 + J1*xi[i] + J2*eta[i]); } } // inertial unbalance load mInternalForces.addVector(1.0, Q, -1.0); return mInternalForces; } const Vector & SSPquad::getResistingForceIncInertia() { // get mass density from the material double density = theMaterial->getRho(); // if density is zero only add damping terms if (density == 0.0) { this->getResistingForce(); // add the damping forces if rayleigh damping if (betaK != 0.0 || betaK0 != 0.0 || betaKc != 0.0) { mInternalForces += this->getRayleighDampingForces(); } return mInternalForces; } const Vector &accel1 = theNodes[0]->getTrialAccel(); const Vector &accel2 = theNodes[1]->getTrialAccel(); const Vector &accel3 = theNodes[2]->getTrialAccel(); const Vector &accel4 = theNodes[3]->getTrialAccel(); static double a[8]; a[0] = accel1(0); a[1] = accel1(1); a[2] = accel2(0); a[3] = accel2(1); a[4] = accel3(0); a[5] = accel3(1); a[6] = accel4(0); a[7] = accel4(1); // compute current resisting force this->getResistingForce(); // compute mass matrix this->getMass(); for (int i = 0; i < 8; i++) { mInternalForces(i) += mMass(i,i)*a[i]; } // add the damping forces if rayleigh damping if (alphaM != 0 || betaK != 0.0 || betaK0 != 0.0 || betaKc != 0.0) { mInternalForces += this->getRayleighDampingForces(); } return mInternalForces; } int SSPquad::sendSelf(int commitTag, Channel &theChannel) { int res = 0; // note: we don't check for dataTag == 0 for Element // objects as that is taken care of in a commit by the Domain // object - don't want to have to do the check if sending data int dataTag = this->getDbTag(); // SSPquad packs its data into a Vector and sends this to theChannel // along with its dbTag and the commitTag passed in the arguments static Vector data(10); data(0) = this->getTag(); data(1) = mThickness; data(2) = b[0]; data(3) = b[1]; data(4) = theMaterial->getClassTag(); data(6) = alphaM; data(7) = betaK; data(8) = betaK0; data(9) = betaKc; // Now quad sends the ids of its materials int matDbTag = theMaterial->getDbTag(); // NOTE: we do have to ensure that the material has a database // tag if we are sending to a database channel. if (matDbTag == 0) { matDbTag = theChannel.getDbTag(); if (matDbTag != 0) theMaterial->setDbTag(matDbTag); } data(5) = matDbTag; res += theChannel.sendVector(dataTag, commitTag, data); if (res < 0) { opserr << "WARNING SSPquad::sendSelf() - " << this->getTag() << " failed to send Vector\n"; return res; } // SSPquad then sends the tags of its four nodes res += theChannel.sendID(dataTag, commitTag, mExternalNodes); if (res < 0) { opserr << "WARNING SSPquad::sendSelf() - " << this->getTag() << " failed to send ID\n"; return res; } // finally, SSPquad asks its material object to send itself res = theMaterial->sendSelf(commitTag, theChannel); if (res < 0) { opserr << "WARNING SSPquad::sendSelf() - " << this->getTag() << " failed to send its Material\n"; return -3; } return 0; } int SSPquad::recvSelf(int commitTag, Channel &theChannel, FEM_ObjectBroker &theBroker) { int res = 0; int dataTag = this->getDbTag(); // SSPquad creates a Vector, receives the Vector and then sets the // internal data with the data in the Vector static Vector data(10); res += theChannel.recvVector(dataTag, commitTag, data); if (res < 0) { opserr << "WARNING SSPquad::recvSelf() - failed to receive Vector\n"; return res; } this->setTag((int)data(0)); mThickness = data(1); b[0] = data(2); b[1] = data(3); // SSPquad now receives the tags of its four external nodes res += theChannel.recvID(dataTag, commitTag, mExternalNodes); if (res < 0) { opserr << "WARNING SSPquad::recvSelf() - " << this->getTag() << " failed to receive ID\n"; return res; } // finally, SSPquad creates a material object of the correct type, sets its // database tag, and asks this new object to receive itself int matClass = (int)data(4); int matDb = (int)data(5); alphaM = data(6); betaK = data(7); betaK0 = data(8); betaKc = data(9); // check if material object exists and that it is the right type if ((theMaterial == 0) || (theMaterial->getClassTag() != matClass)) { // if old one, delete it if (theMaterial != 0) delete theMaterial; // create new material object NDMaterial *theMatCopy = theBroker.getNewNDMaterial(matClass); theMaterial = (NDMaterial *)theMatCopy; if (theMaterial == 0) { opserr << "WARNING SSPquad::recvSelf() - " << this->getTag() << " failed to get a blank Material of type " << matClass << endln; return -3; } } // NOTE: we set the dbTag before we receive the material theMaterial->setDbTag(matDb); res = theMaterial->recvSelf(commitTag, theChannel, theBroker); if (res < 0) { opserr << "WARNING SSPquad::recvSelf() - " << this->getTag() << " failed to receive its Material\n"; return -3; } return 0; } int SSPquad::displaySelf(Renderer &theViewer, int displayMode, float fact, const char **modes, int numMode) { // get the end point display coords static Vector v1(3); static Vector v2(3); static Vector v3(3); static Vector v4(3); theNodes[0]->getDisplayCrds(v1, fact, displayMode); theNodes[1]->getDisplayCrds(v2, fact, displayMode); theNodes[2]->getDisplayCrds(v3, fact, displayMode); theNodes[3]->getDisplayCrds(v4, fact, displayMode); // place values in coords matrix static Matrix coords(4, 3); for (int i = 0; i < 3; i++) { coords(0, i) = v1(i); coords(1, i) = v2(i); coords(2, i) = v3(i); coords(3, i) = v4(i); } // fill RGB vector static Vector values(4); for (int i = 0; i < 4; i++) values(i) = 1.0; // draw the polygon return theViewer.drawPolygon(coords, values, this->getTag()); } void SSPquad::Print(OPS_Stream &s, int flag) { if (flag == OPS_PRINT_CURRENTSTATE) { opserr << "SSPquad, element id: " << this->getTag() << endln; opserr << " Connected external nodes: "; for (int i = 0; i < SSPQ_NUM_NODE; i++) { opserr << mExternalNodes(i) << " "; } } if (flag == OPS_PRINT_PRINTMODEL_JSON) { s << "\t\t\t{"; s << "\"name\": " << this->getTag() << ", "; s << "\"type\": \"SSPquad\", "; s << "\"nodes\": [" << mExternalNodes(0) << ", "; s << mExternalNodes(1) << ", "; s << mExternalNodes(2) << ", "; s << mExternalNodes(3) << "], "; s << "\"thickness\": " << mThickness << ", "; s << "\"bodyForces\": [" << b[0] << ", " << b[1] << "], "; s << "\"material\": \"" << theMaterial->getTag() << "\"}"; } } Response* SSPquad::setResponse(const char **argv, int argc, OPS_Stream &eleInfo) { // no special recorders for this element, call the method in the material class return theMaterial->setResponse(argv, argc, eleInfo); } int SSPquad::getResponse(int responseID, Information &eleInfo) { // no special recorders for this element, call the method in the material class return theMaterial->getResponse(responseID, eleInfo); } int SSPquad::setParameter(const char **argv, int argc, Parameter &param) { if (argc < 1) { return -1; } int res = -1; // no element parameters, call setParameter in the material int matRes = res; matRes = theMaterial->setParameter(argv, argc, param); if (matRes != -1) { res = matRes; } return res; } int SSPquad::updateParameter(int parameterID, Information &info) { int res = -1; int matRes = res; if (parameterID == res) { return -1; } else { matRes = theMaterial->updateParameter(parameterID, info); if (matRes != -1) { res = matRes; } return res; } } Matrix SSPquad::DyadicProd(Vector v1, Vector v2) // computes dyadic product for two vectors (2x1) { Matrix result(2,2); result.Zero(); for (int i = 0; i < v1.Size(); i++) { for (int j = 0; j < v2.Size(); j++) result(i,j) = v1(i) * v2(j); } return result; } void SSPquad::GetStab(void) // this function computes the stabilization stiffness matrix for the element { Vector g1(SSPQ_NUM_DIM); Vector g2(SSPQ_NUM_DIM); Matrix I(SSPQ_NUM_DIM,SSPQ_NUM_DIM); Matrix FCF(SSPQ_NUM_DIM,SSPQ_NUM_DIM); Matrix Jmat(SSPQ_NUM_DIM,SSPQ_NUM_DIM); Matrix Jinv(SSPQ_NUM_DIM,SSPQ_NUM_DIM); Matrix dNloc(SSPQ_NUM_NODE,SSPQ_NUM_DIM); Matrix dN(SSPQ_NUM_NODE,SSPQ_NUM_DIM); Matrix Mben(2,SSPQ_NUM_DOF); double Hss; double Hst; double Htt; // shape function derivatives (local crd) at center dNloc(0,0) = -0.25; dNloc(1,0) = 0.25; dNloc(2,0) = 0.25; dNloc(3,0) = -0.25; dNloc(0,1) = -0.25; dNloc(1,1) = -0.25; dNloc(2,1) = 0.25; dNloc(3,1) = 0.25; // jacobian matrix Jmat = mNodeCrd*dNloc; // inverse of the jacobian matrix Jmat.Invert(Jinv); // shape function derivatives (global crd) dN = dNloc*Jinv; // define hourglass stabilization vector gamma = 0.25*(h - (h^x)*bx - (h^y)*by); double hx = mNodeCrd(0,0) - mNodeCrd(0,1) + mNodeCrd(0,2) - mNodeCrd(0,3); double hy = mNodeCrd(1,0) - mNodeCrd(1,1) + mNodeCrd(1,2) - mNodeCrd(1,3); double gamma[4]; gamma[0] = 0.25*( 1.0 - hx*dN(0,0) - hy*dN(0,1)); gamma[1] = 0.25*(-1.0 - hx*dN(1,0) - hy*dN(1,1)); gamma[2] = 0.25*( 1.0 - hx*dN(2,0) - hy*dN(2,1)); gamma[3] = 0.25*(-1.0 - hx*dN(3,0) - hy*dN(3,1)); // define mapping matrices Mmem.Zero(); Mben.Zero(); for (int i = 0; i < 4; i++) { Mmem(0,2*i) = dN(i,0); Mmem(1,2*i+1) = dN(i,1); Mmem(2,2*i) = dN(i,1); Mmem(2,2*i+1) = dN(i,0); Mben(0,2*i) = gamma[i]; Mben(1,2*i+1) = gamma[i]; } // base vectors g1(0) = Jmat(0,0); g1(1) = Jmat(1,0); g2(0) = Jmat(0,1); g2(1) = Jmat(1,1); // normalize base vectors g1.Normalize(); g2.Normalize(); // compute second moment of area tensor double fourThree = 4.0/3.0; I = fourThree*mThickness*J0*(DyadicProd(g1,g1) + DyadicProd(g2,g2)); // stabilization terms Hss = (I(0,0)*Jinv(1,0)*Jinv(1,0) + I(0,1)*Jinv(0,0)*Jinv(1,0) + I(1,1)*Jinv(0,0)*Jinv(0,0))*0.25; Htt = (I(0,0)*Jinv(1,1)*Jinv(1,1) + I(0,1)*Jinv(0,1)*Jinv(1,1) + I(1,1)*Jinv(0,1)*Jinv(0,1))*0.25; Hst = (I(0,0)*Jinv(1,1)*Jinv(1,0) + I(0,1)*(Jinv(1,0)*Jinv(0,1) + Jinv(1,1)*Jinv(0,0)) + I(1,1)*Jinv(0,1)*Jinv(0,0))*0.25; // get material tangent const Matrix &CmatI = theMaterial->getInitialTangent(); // compute stabilization matrix FCF(0,0) = (CmatI(0,0) - (CmatI(0,1) + CmatI(1,0)) + CmatI(1,1))*Hss; FCF(0,1) = (CmatI(0,1) - (CmatI(0,0) + CmatI(1,1)) + CmatI(1,0))*Hst; FCF(1,0) = (CmatI(1,0) - (CmatI(0,0) + CmatI(1,1)) + CmatI(0,1))*Hst; FCF(1,1) = (CmatI(1,1) - (CmatI(0,1) + CmatI(1,0)) + CmatI(0,0))*Htt; // compute stiffness matrix for stabilization terms Kstab.Zero(); Kstab.addMatrixTripleProduct(1.0, Mben, FCF, 1.0); return; }
27.02164
131
0.618462
[ "object", "shape", "vector", "model" ]
cb58d576f679cd7544ffd9138813e0d91659a500
709
cpp
C++
Codeforces/1234B1 - Social Network (easy version).cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/1234B1 - Social Network (easy version).cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/1234B1 - Social Network (easy version).cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using ll = long long; using namespace std; unordered_map<int, bool> marks; int main() { ios::sync_with_stdio(false); int n, k; cin >> n >> k; vector<int> arr(n); for (int i = 0; i < n; ++i) cin >> arr[i]; deque<int> q; for (int i = 0; i < n; ++i) { if ( marks[arr[i]] == 1 ) continue; if ( q.size() < k ) { q.push_front(arr[i]); marks[arr[i]] = 1; } else { marks[q.back()] = 0; q.pop_back(); q.push_front(arr[i]); marks[arr[i]] = 1; } } cout << q.size() << endl ; for (auto el: q) cout << el << ' '; cout << endl; return 0; }
20.257143
46
0.437236
[ "vector" ]
cb5c4d4e94ec17e15438584189d0f103379f2d81
10,333
cpp
C++
src/tests/functional/inference_engine/transformations/dimension_tracking.cpp
pfinashx/openvino
1d417e888b508415510fb0a92e4a9264cf8bdef7
[ "Apache-2.0" ]
1
2022-02-26T17:33:44.000Z
2022-02-26T17:33:44.000Z
src/tests/functional/inference_engine/transformations/dimension_tracking.cpp
pfinashx/openvino
1d417e888b508415510fb0a92e4a9264cf8bdef7
[ "Apache-2.0" ]
17
2021-11-25T10:22:17.000Z
2022-03-28T13:19:31.000Z
src/tests/functional/inference_engine/transformations/dimension_tracking.cpp
pfinashx/openvino
1d417e888b508415510fb0a92e4a9264cf8bdef7
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include <string> #include <memory> #include <queue> #include <ngraph/function.hpp> #include <openvino/opsets/opset1.hpp> #include <transformations/init_node_info.hpp> #include <transformations/utils/utils.hpp> #include <ngraph/pass/manager.hpp> #include <dimension_tracker.hpp> #include <transformations/common_optimizations/dimension_tracking.hpp> #include <transformations/common_optimizations/divide_fusion.hpp> #include "common_test_utils/ngraph_test_utils.hpp" using namespace testing; TEST(TransformationTests, AutoBatch_LabelPropagation_Transpose) { auto batch = ov::Dimension(5); ov::DimensionTracker::set_label(batch, 7); auto p_shape = ov::PartialShape{batch, 4, 6, 8}; auto arg = std::make_shared<ov::opset1::Parameter>(ov::element::f32, p_shape); auto input_order = ov::opset1::Constant::create(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{2, 1, 0, 3}); auto r = std::make_shared<ov::opset1::Transpose>(arg, input_order); EXPECT_EQ(r->get_output_element_type(0), ov::element::f32); EXPECT_EQ(r->get_output_partial_shape(0), ov::PartialShape({6, 4, batch, 8})); EXPECT_EQ(ov::DimensionTracker::get_label(r->get_output_partial_shape(0)[2]), 7); } TEST(TransformationTests, AutoBatch_LabelPropagation_Convolution) { auto batch = ov::Dimension(5); ov::DimensionTracker::set_label(batch, 7); auto p_shape = ov::PartialShape{batch, 4, 6, 8}; auto arg = std::make_shared<ov::opset1::Parameter>(ov::element::f32, p_shape); const auto& filters = std::make_shared<ov::opset1::Constant>(ov::element::f32, ov::Shape{1, 4, 3, 3}); const auto& conv = std::make_shared<ov::opset1::Convolution>( arg, filters, ov::Strides{1, 1}, ov::CoordinateDiff{0, 0}, ov::CoordinateDiff{0, 0}, ov::Strides{1, 1}); EXPECT_EQ(conv->get_output_element_type(0), ov::element::f32); EXPECT_EQ(conv->get_output_partial_shape(0), ov::PartialShape({batch, 1, 4, 6})); EXPECT_EQ(ov::DimensionTracker::get_label(conv->get_output_partial_shape(0)[0]), 7); } TEST(TransformationTests, AutoBatch_FindBatch_Transpose_and_Convolution) { const auto& data = std::make_shared<ov::opset1::Parameter>(ov::element::f32, ov::Shape{4, 1, 10, 10}); const auto& order = std::make_shared<ov::opset1::Constant>(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{1, 0, 2, 3}); const auto& transpose = std::make_shared<ov::opset1::Transpose>(data, order); const auto& filters = std::make_shared<ov::opset1::Constant>(ov::element::f32, ov::Shape{1, 4, 3, 3}); const auto& conv = std::make_shared<ov::opset1::Convolution>( transpose, filters, ov::Strides{1, 1}, ov::CoordinateDiff{0, 0}, ov::CoordinateDiff{0, 0}, ov::Strides{1, 1}); const auto& f = std::make_shared<ov::Model>(ov::NodeVector{conv}, ov::ParameterVector{data}); ov::pass::Manager m; m.register_pass<ngraph::pass::InitNodeInfo>(); m.register_pass<ov::pass::FindBatch>(); m.run_passes(f); ASSERT_NO_THROW(check_rt_info(f)); const auto& shape = data->get_partial_shape(); ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[0])) << shape; ASSERT_TRUE(ov::DimensionTracker::get_label(shape[1])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[2])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[3])) << shape; } TEST(TransformationTests, AutoBatch_FindBatch_SingleMultiply) { const auto& data = std::make_shared<ov::opset1::Parameter>(ov::element::f32, ov::Shape{1, 4, 10, 10}); const auto& constant = std::make_shared<ov::opset1::Constant>(ov::element::f32, ov::Shape{1, 4, 1, 1}); const auto& mul = std::make_shared<ov::opset1::Multiply>(data, constant); const auto& f = std::make_shared<ov::Model>(ov::NodeVector{mul}, ov::ParameterVector{data}); ov::pass::Manager m; m.register_pass<ngraph::pass::InitNodeInfo>(); m.register_pass<ov::pass::FindBatch>(); m.run_passes(f); ASSERT_NO_THROW(check_rt_info(f)); const auto& shape = data->get_partial_shape(); ASSERT_TRUE(ov::DimensionTracker::get_label(shape[0])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[1])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[2])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[3])) << shape; } TEST(TransformationTests, AutoBatch_FindBatch_Two_Outputs) { const auto& data = std::make_shared<ov::opset1::Parameter>(ov::element::f32, ov::Shape{1, 1, 10, 10}); const auto& order = std::make_shared<ov::opset1::Constant>(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{1, 0, 2, 3}); const auto& transpose = std::make_shared<ov::opset1::Transpose>(data, order); const auto& filters = std::make_shared<ov::opset1::Constant>(ov::element::f32, ov::Shape{1, 1, 3, 3}); const auto& conv = std::make_shared<ov::opset1::Convolution>( data, filters, ov::Strides{1, 1}, ov::CoordinateDiff{0, 0}, ov::CoordinateDiff{0, 0}, ov::Strides{1, 1}); const auto& f = std::make_shared<ov::Model>(ov::NodeVector{conv, transpose}, ov::ParameterVector{data}); ov::pass::Manager m; m.register_pass<ngraph::pass::InitNodeInfo>(); m.register_pass<ov::pass::FindBatch>(); m.run_passes(f); ASSERT_NO_THROW(check_rt_info(f)); const auto& shape = data->get_partial_shape(); ASSERT_TRUE(ov::DimensionTracker::get_label(shape[0])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[1])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[2])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[3])) << shape; } TEST(TransformationTests, AutoBatch_FindBatch_TwoOutputsReversed) { const auto& data = std::make_shared<ov::opset1::Parameter>(ov::element::f32, ov::Shape{1, 1, 10, 10}); const auto& filters = std::make_shared<ov::opset1::Constant>(ov::element::f32, ov::Shape{1, 1, 3, 3}); const auto& conv = std::make_shared<ov::opset1::Convolution>( data, filters, ov::Strides{1, 1}, ov::CoordinateDiff{0, 0}, ov::CoordinateDiff{0, 0}, ov::Strides{1, 1}); const auto& order = std::make_shared<ov::opset1::Constant>(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{1, 0, 2, 3}); const auto& transpose = std::make_shared<ov::opset1::Transpose>(data, order); const auto& f = std::make_shared<ov::Model>(ov::NodeVector{transpose, conv}, ov::ParameterVector{data}); ov::pass::Manager m; m.register_pass<ngraph::pass::InitNodeInfo>(); m.register_pass<ov::pass::FindBatch>(); m.run_passes(f); ASSERT_NO_THROW(check_rt_info(f)); const auto& shape = data->get_partial_shape(); ASSERT_TRUE(ov::DimensionTracker::get_label(shape[0])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[1])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[2])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[3])) << shape; } TEST(TransformationTests, AutoBatch_FindBatch_IndependentBranchesConcated) { const auto& data = std::make_shared<ov::opset1::Parameter>(ov::element::f32, ov::Shape{1, 4, 10, 10}); const auto& constant_0 = std::make_shared<ov::opset1::Constant>(ov::element::f32, ov::Shape{1, 1, 1, 1}); const auto& mul_0 = std::make_shared<ov::opset1::Multiply>(data, constant_0); const auto& constant_1 = std::make_shared<ov::opset1::Constant>(ov::element::f32, ov::Shape{1, 1, 1, 1}); const auto& mul_1 = std::make_shared<ov::opset1::Multiply>(data, constant_1); const auto& filters = std::make_shared<ov::opset1::Constant>(ov::element::f32, ov::Shape{1, 4, 1, 1}); const auto& conv = std::make_shared<ov::opset1::Convolution>( mul_0, filters, ov::Strides{1, 1}, ov::CoordinateDiff{0, 0}, ov::CoordinateDiff{0, 0}, ov::Strides{1, 1}); const auto& concat = std::make_shared<ov::opset1::Concat>(ov::NodeVector{conv, mul_1}, 1); const auto& f = std::make_shared<ov::Model>(ov::NodeVector{concat}, ov::ParameterVector{data}); ov::pass::Manager m; m.register_pass<ngraph::pass::InitNodeInfo>(); m.register_pass<ov::pass::FindBatch>(); m.run_passes(f); ASSERT_NO_THROW(check_rt_info(f)); const auto& shape = data->get_partial_shape(); ASSERT_TRUE(ov::DimensionTracker::get_label(shape[0])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[1])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[2])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[3])) << shape; } TEST(TransformationTests, AutoBatch_FindBatch_TwoConvNetwork) { const auto& data = std::make_shared<ov::opset1::Parameter>(ov::element::f32, ov::Shape{1, 4, 10, 10}); const auto& filters = std::make_shared<ov::opset1::Constant>(ov::element::f32, ov::Shape{1, 4, 3, 3}); const auto& conv_0 = std::make_shared<ov::opset1::Convolution>( data, filters, ov::Strides{1, 1}, ov::CoordinateDiff{0, 0}, ov::CoordinateDiff{0, 0}, ov::Strides{1, 1}); const auto& conv_1 = std::make_shared<ov::opset1::Convolution>( data, filters, ov::Strides{1, 1}, ov::CoordinateDiff{0, 0}, ov::CoordinateDiff{0, 0}, ov::Strides{1, 1}); const auto& f = std::make_shared<ov::Model>(ov::NodeVector{conv_0, conv_1}, ov::ParameterVector{data}); ov::pass::Manager m; m.register_pass<ngraph::pass::InitNodeInfo>(); m.register_pass<ov::pass::FindBatch>(); m.run_passes(f); ASSERT_NO_THROW(check_rt_info(f)); const auto& shape = data->get_partial_shape(); ASSERT_TRUE(ov::DimensionTracker::get_label(shape[0])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[1])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[2])) << shape; ASSERT_TRUE(!ov::DimensionTracker::get_label(shape[3])) << shape; } TEST(partial_shape, cout_with_label) { ov::Dimension a = 5; ov::DimensionTracker::set_label(a, 100500); ov::PartialShape shape{1, 2, 3, a}; std::stringstream stream; stream << shape; ASSERT_EQ(stream.str(), "{1,2,3,l<100500>5}"); } TEST(partial_shape, cout_without_label) { ov::Dimension a = 5; ov::PartialShape shape{1, 2, 3, a}; std::stringstream stream; stream << shape; ASSERT_EQ(stream.str(), "{1,2,3,5}"); }
46.545045
129
0.684603
[ "shape", "vector", "model" ]
cb5ece01c20126def21af203f1c34c927bedee8f
7,055
cpp
C++
Autoware/src/autoware/common/op_planner/src/opendrive/geometry/CenterLine.cpp
sethut1224/Autoware-CARLA
d51b35cc408cf00d663e1a9b2ba590f89be42fa1
[ "Apache-2.0" ]
1
2021-12-25T15:50:31.000Z
2021-12-25T15:50:31.000Z
Autoware/src/autoware/common/op_planner/src/opendrive/geometry/CenterLine.cpp
sethut1224/Autoware-CARLA
d51b35cc408cf00d663e1a9b2ba590f89be42fa1
[ "Apache-2.0" ]
null
null
null
Autoware/src/autoware/common/op_planner/src/opendrive/geometry/CenterLine.cpp
sethut1224/Autoware-CARLA
d51b35cc408cf00d663e1a9b2ba590f89be42fa1
[ "Apache-2.0" ]
null
null
null
/* * ----------------- BEGIN LICENSE BLOCK --------------------------------- * * Copyright (C) 2019 Intel Corporation * * SPDX-License-Identifier: MIT * * ----------------- END LICENSE BLOCK ----------------------------------- */ #include "op_planner/opendrive/geometry/CenterLine.hpp" #include <boost/array.hpp> #include <boost/math/tools/rational.hpp> #include <cmath> #include <iostream> namespace opendrive { namespace geometry { geometry::DirectedPoint CenterLine::eval(double s, bool applyLateralOffset) const { if (s < 0.) { // as the curve is only defined betwen the range [0 , length], we return the line evaluated at s = 0 return eval(0.); } for (auto it = geometry.rbegin(); it != geometry.rend(); it++) { if (s >= (*it)->GetStartOffset()) { auto directedPoint = (*it)->PosFromDist(s - (*it)->GetStartOffset()); // This is parametrized as the landmarks positions do not take into account the lateral offset if (applyLateralOffset) { directedPoint.ApplyLateralOffset(calculateOffset(s)); } return directedPoint; } } auto &lastGeometry = geometry.back(); return lastGeometry->PosFromDist(s - lastGeometry->GetStartOffset()); } std::vector<double> CenterLine::samplingPoints() const { std::vector<double> points; points.push_back(length); double const maxError = 1e-2; // max curve sampling error expected for (auto it = geometry.rbegin(); it != geometry.rend(); it++) { if ((*it)->GetType() == ::opendrive::GeometryType::LINE) { // only start and end point } else if ((*it)->GetType() == ::opendrive::GeometryType::ARC) { auto arc = static_cast<::opendrive::geometry::GeometryArc *>((*it).get()); double theta = fabs(arc->GetCurvature()) * (*it)->GetLength(); if (theta < 1e-2) { points.insert(points.begin(), (*it)->GetStartOffset() + 0.5 * (*it)->GetLength()); } else { double c = fabs(arc->GetCurvature()); double dsmax = 2.0 / c * acos(1.0 - c * maxError); int segments = static_cast<int>((*it)->GetLength() / dsmax); for (auto k = segments - 1; k > 0; --k) { double r = static_cast<double>(k) / static_cast<double>(segments); points.insert(points.begin(), (*it)->GetStartOffset() + r * (*it)->GetLength()); } } } else if ((*it)->GetType() == ::opendrive::GeometryType::POLY3) { int segments = 10; for (auto k = segments - 1; k > 0; --k) { double r = static_cast<double>(k) / static_cast<double>(segments); points.insert(points.begin(), (*it)->GetStartOffset() + r * (*it)->GetLength()); } } else if ((*it)->GetType() == ::opendrive::GeometryType::PARAMPOLY3) { int segments = 10; for (auto k = segments - 1; k > 0; --k) { double r = static_cast<double>(k) / static_cast<double>(segments); points.insert(points.begin(), (*it)->GetStartOffset() + r * (*it)->GetLength()); } } else { // nothing to do } points.insert(points.begin(), (*it)->GetStartOffset()); } return points; } double CenterLine::calculateOffset(double s) const { if (s < 0.) { return calculateOffset(0.); } for (auto it = offsetVector.rbegin(); it != offsetVector.rend(); it++) { if (s >= it->s) { auto poly = boost::array<double, 4>{{it->a, it->b, it->c, it->d}}; return boost::math::tools::evaluate_polynomial(poly, s - it->s); } } return 0.0; } bool generateCenterLine(RoadInformation &roadInfo, CenterLine &centerLine) { bool ok = true; centerLine.geometry.clear(); centerLine.length = roadInfo.attributes.length; centerLine.offsetVector = roadInfo.lanes.lane_offset; // Add geometry information for (auto &geometry_attribute : roadInfo.geometry_attributes) { Point start(geometry_attribute->start_position_x, geometry_attribute->start_position_y); try { switch (geometry_attribute->type) { case ::opendrive::GeometryType::ARC: { auto arc = static_cast<GeometryAttributesArc *>(geometry_attribute.get()); centerLine.geometry.emplace_back(std::make_unique<geometry::GeometryArc>( arc->start_position, arc->length, arc->heading, start, arc->curvature)); break; } case ::opendrive::GeometryType::LINE: { auto line = static_cast<GeometryAttributesLine *>(geometry_attribute.get()); centerLine.geometry.emplace_back( std::make_unique<geometry::GeometryLine>(line->start_position, line->length, line->heading, start)); break; } break; case ::opendrive::GeometryType::SPIRAL: { // currently not yet supported std::cerr << "generateCenterLine() spirals are currently not supported yet\n"; ok = false; break; } break; case ::opendrive::GeometryType::POLY3: { auto poly3 = static_cast<GeometryAttributesPoly3 *>(geometry_attribute.get()); centerLine.geometry.emplace_back(std::make_unique<geometry::GeometryPoly3>( poly3->start_position, poly3->length, poly3->heading, start, poly3->a, poly3->b, poly3->c, poly3->d)); break; } break; case ::opendrive::GeometryType::PARAMPOLY3: { auto paramPoly3 = static_cast<GeometryAttributesParamPoly3 *>(geometry_attribute.get()); centerLine.geometry.emplace_back(std::make_unique<geometry::GeometryParamPoly3>(paramPoly3->start_position, paramPoly3->length, paramPoly3->heading, start, paramPoly3->aU, paramPoly3->bU, paramPoly3->cU, paramPoly3->dU, paramPoly3->aV, paramPoly3->bV, paramPoly3->cV, paramPoly3->dV)); break; } break; default: break; } } catch (...) { std::cerr << "generateCenterLine() Invalid geometry definition\n"; ok = false; } } return ok; } } }
33.436019
117
0.513536
[ "geometry", "vector" ]
cb623de025da455b20fe7f1897e4d844eb3fe81d
12,515
cc
C++
elec/Interpolation.cc
paulkefer/cardioid
59c07b714d8b066b4f84eb50487c36f6eadf634c
[ "MIT-0", "MIT" ]
33
2018-12-12T20:05:06.000Z
2021-09-26T13:30:16.000Z
elec/Interpolation.cc
paulkefer/cardioid
59c07b714d8b066b4f84eb50487c36f6eadf634c
[ "MIT-0", "MIT" ]
5
2019-04-25T11:34:43.000Z
2021-11-14T04:35:37.000Z
elec/Interpolation.cc
paulkefer/cardioid
59c07b714d8b066b4f84eb50487c36f6eadf634c
[ "MIT-0", "MIT" ]
15
2018-12-21T22:44:59.000Z
2021-08-29T10:30:25.000Z
#include "Interpolation.hh" #include "svd.h" #include <set> #include <cmath> #include <cassert> #include <iostream> using namespace std; #ifdef HAVE_LAPACK extern "C" { int dgels_ ( char *trans , int *m , int *n , int *nrhs , double *a , int *lda , double *b , int *ldb , double *work , int *lwork , int *info ); } #endif static vector<double> hornFromCheby(const vector<double>& chebyCoeff, const double lb, const double ub) { int inSize = chebyCoeff.size(); /* * zCoeff = zCoeffFromCheby * chebyCoeff * * zCoeffFromCheby = [ * 1 0 -1 0 1 ... * 0 1 0 -3 0 ... * 0 0 2 0 -8 ... * 0 0 0 4 0 ... * 0 0 0 0 8 ... * . . . . . */ vector<double> zCoeffFromCheby(inSize*inSize, 0); zCoeffFromCheby[0 + 0*inSize] = 1; if (1 < inSize) { zCoeffFromCheby[1 + 1*inSize] = 1; } for (int kk=2; kk<inSize; kk++) { for (int ll=0; ll<inSize; ll++) { double leadingTerm = 0; if (ll>0) { leadingTerm = 2*zCoeffFromCheby[ll-1 + (kk-1)*inSize]; } zCoeffFromCheby[ll + kk*inSize] = leadingTerm - zCoeffFromCheby[ll + (kk-2)*inSize]; } } vector<double> zCoeff(inSize); for (int ii=0; ii<inSize; ii++) { zCoeff[ii] = 0; for (int jj=0; jj<inSize; jj++) { zCoeff[ii] += zCoeffFromCheby[ii + jj*inSize]*chebyCoeff[jj]; } } /* * x=lb -> z=-1 * x=ub -> z= 1 * z = M*x + B * M = 2/(ub-lb) * B = -(ub+lb)/(ub-lb) * * z^2 = (M*x + B)*(M*x + B) = M^2*x^2 + 2*M*B*x + B^2 * z^(i+1) = M*x*(z^i) + B*(z^i) * * xCoeff = xFromZ * zCoeff * * xFromZ = [ * 1 B B*B B*B*B ... * 0 M 2*M*B 3*M*B*B ... * 0 0 M*M 3*M*M*B ... * 0 0 0 M*M*M ... * . . . . */ double MM=2/(ub-lb); double BB=-(ub+lb)/(ub-lb); vector<double> xCoeffFromZ(inSize*inSize, 0); xCoeffFromZ[0 + 0*inSize] = 1; for (int kk=1; kk<inSize; kk++) { for (int ll=0; ll<inSize; ll++) { double leadingTerm=0; if (ll>0) { leadingTerm = MM*xCoeffFromZ[ll-1 + (kk-1)*inSize]; } xCoeffFromZ[ll + kk*inSize] = leadingTerm + BB*xCoeffFromZ[ll + (kk-1)*inSize]; } } vector<double> xCoeff(inSize); for (int ii=0; ii<inSize; ii++) { xCoeff[ii] = 0; for (int jj=0; jj<inSize; jj++) { xCoeff[ii] += xCoeffFromZ[ii + jj*inSize]*zCoeff[jj]; } } return xCoeff; } double Interpolation::create(const vector<double>& inputs, const vector<double>& outputs, const double tolerance, const double rangeWindow) { double lb = inputs[0]; double ub = inputs[inputs.size()-1]; int inSize = inputs.size(); vector<double> chebyPoly(MAX_TERM_COUNT*inSize); for (int ii=0; ii<inSize; ii++) { chebyPoly[ii + 0*inSize] = 1; chebyPoly[ii + 1*inSize] = (inputs[ii] - (ub+lb)/2) * 2/(ub-lb); //convert to z in [-1,1] } for (int jj=2; jj<MAX_TERM_COUNT; jj++) { for (int ii=0; ii<inSize; ii++) { chebyPoly[ii + jj*inSize] = 2*chebyPoly[ii + 1*inSize]*chebyPoly[ii + (jj-1)*inSize] - chebyPoly[ii + (jj-2)*inSize] ; } } /* Fill up a vector of the dynamic range for the function. * * I'd like the tolerance to be a measure of the relative error. * To compute relative error, I need to have a measure of how "big" * the function is. * * Using relative error for each output point individually doesn't * work well, because some function evaluations might be zero or * near zero, which would lead to ridiculously stringent error * requirements. * * Using |max-min| for the function doesn't work for things like * exponential functions, where the extrema of the range are * completely ridiculous, leading to 100% loss of accuracy for the * majority of the range. * * Instead, I'm going to use a moving window, where I compute the * max-min for some subset of the range. This solves the near zero * issue, but also allows for dynamic relative error fits for * different parts of the function. * */ vector<double> range(inSize); if (0) { //range is the output for every point. for (int ii=0; ii<inSize; ii++) { range[ii] = fabs(outputs[ii]); } } else if (0) { //range is set within the whole domain double funcMax = -1e30; double funcMin = 1e30; for (int ii=0; ii<inSize; ii++) { funcMax = max(funcMax,outputs[ii]); funcMin = min(funcMin,outputs[ii]); } //handle trivial case, where function is a constant if (funcMax <= funcMin) { numNumer_ = 1; numDenom_ = 1; coeff_.resize(1); coeff_[0] = funcMax; return 0; } for (int ii=0; ii<inSize; ii++) { range[ii] = funcMax-funcMin; } } else { int filterSize = inSize*rangeWindow; //make sure filterSize is odd if (!(filterSize % 2)) { filterSize++; } if (filterSize > inSize) { filterSize = inSize; if (!(filterSize % 2)) { filterSize--; } } assert(filterSize <= inSize); assert(filterSize >= 2); multiset<double> window; for (int ii=0; ii<filterSize; ii++) { window.insert(outputs[ii]); } for (int ii=0; ii<inSize; ii++) { if (filterSize/2+1 <= ii && ii <= inSize-filterSize/2-1) { window.erase(window.find(outputs[ii-filterSize/2-1])); window.insert(outputs[ii+filterSize/2]); } range[ii] = *(window.rbegin())-*(window.begin()); } } //check to make sure the range is reasonable. double rangeMax = -1e30; for (int ii=0; ii<inSize; ii++) { rangeMax = max(rangeMax,range[ii]); } double absMinRange = rangeMax*1e-7; for (int ii=0; ii<inSize; ii++) { range[ii] = max(absMinRange, range[ii]); } int totalMaxTerm = 2*MAX_TERM_COUNT; double bestError = 1e30; vector<double> bestCoeffs(totalMaxTerm); int bestNumer=-1; int bestDenom=-1; int cost = 2; while (bestError >= tolerance and cost <= 2*MAX_TERM_COUNT) { for (int denomTermCount=1; denomTermCount<cost; denomTermCount++) { //find the number of the numerators and denominators we're fitting here int numerTermCount = cost - denomTermCount; if (denomTermCount == 1) { //no division needed for a unitary numerator numerTermCount = cost; } if (numerTermCount > MAX_TERM_COUNT) { continue; } if (denomTermCount > MAX_TERM_COUNT) { continue; } int coeffCount = numerTermCount + denomTermCount - 1; //find the coefficient matrices vector<double> bbb = outputs; vector<double> currentCoeffs(coeffCount); #ifdef HAVE_LAPACK { vector<double> AAA(coeffCount*inSize); for (int nn=0; nn<numerTermCount; nn++) { for (int ii=0; ii<inSize; ii++) { AAA[ii + nn*inSize] = chebyPoly[ii + nn*inSize]; } } for (int dd=1; dd<denomTermCount; dd++) { for (int ii=0; ii<inSize; ii++) { AAA[ii + (numerTermCount+dd-1)*inSize] = -outputs[ii]*chebyPoly[ii + dd*inSize]; } } int info = -1; char trans = 'N'; int lwork = -1; int one=1; double optimalWork; dgels_(&trans, &inSize, &coeffCount, &one, &AAA[0], &inSize, &bbb[0], &inSize, &optimalWork, &lwork, &info); assert(info == 0); info = -1; lwork = optimalWork; vector<double> work(lwork); dgels_(&trans, &inSize, &coeffCount, &one, &AAA[0], &inSize, &bbb[0], &inSize, &work[0], &lwork, &info); assert(info == 0); for (int cc=0; cc<coeffCount; cc++) currentCoeffs[cc] = bbb[cc]; } #else assert(0 && "Disabling Jim's svd computation for now."); { vector<double> Abuffer(coeffCount*inSize); vector<double*> AAA(inSize); for (int ii=0; ii<inSize; ii++) { AAA[ii] = &Abuffer[ii*coeffCount]; } for (int nn=0; nn<numerTermCount; nn++) { for (int ii=0; ii<inSize; ii++) { AAA[ii][nn] = chebyPoly[ii + nn*inSize]; } } for (int dd=1; dd<denomTermCount; dd++) { for (int ii=0; ii<inSize; ii++) { AAA[ii][numerTermCount+dd-1] = -outputs[ii]*chebyPoly[ii + dd*inSize]; } } svdLinearLeastSquares(inSize, coeffCount, &AAA[0], &bbb[0], &currentCoeffs[0]); } #endif //compute the approximate vector<double> approximate(inSize); for (int ii=0; ii<inSize; ii++) { approximate[ii] = 0; for (int nn=0; nn<numerTermCount; nn++) { approximate[ii] += chebyPoly[ii + nn*inSize]*currentCoeffs[nn]; } double denom=1; for (int dd=1; dd<denomTermCount; dd++) { denom += chebyPoly[ii + dd*inSize]*currentCoeffs[numerTermCount+dd-1]; } approximate[ii] /= denom; } //compute the error double currentError=0; if (0) { //maximum error for (int ii=0; ii<inSize; ii++) { currentError = max(currentError, fabs(outputs[ii]-approximate[ii])/range[ii]); } } else { /* l2 error, assuming uniform step * * Here, assume we're always integrating from 0-1 so the * domain doesn't throw things off. This means that if * the domain of integration changes, we don't want to * have to change our tolerance. * * l2 = sqrt(int((output-approx)^2,lb,ub) / (ub-lb)) * * int(((output-approx)^2,lb,ub)) = * sum(for i=1:n,(output_i-approx_i)^2 * (lb-ub)/n) * * therefore * * l2 = sqrt( * sum(for i=1:n,(output_i-approx_i)^2) / n * ) */ for (int ii=0; ii<inSize; ii++) { double diff = outputs[ii]-approximate[ii]; currentError += (diff/range[ii])*(diff/range[ii]); } currentError = sqrt(currentError/inSize); } //if this is the best answer we've found, save it. if (currentError < bestError) { bestNumer = numerTermCount; bestDenom = denomTermCount; bestCoeffs = currentCoeffs; bestError = currentError; } } cost++; } numNumer_ = bestNumer; numDenom_ = bestDenom; //convert chebychev coeff to horn coeff for better evaluation vector<double> chebyNumerCoeffs(numNumer_); vector<double> chebyDenomCoeffs(numDenom_); for (int nn=0; nn<numNumer_; nn++) { chebyNumerCoeffs[nn] = bestCoeffs[nn]; } chebyDenomCoeffs[0] = 1; for (int dd=1; dd<numDenom_; dd++) { chebyDenomCoeffs[dd] = bestCoeffs[numNumer_+dd-1]; } vector<double> hornNumer(hornFromCheby(chebyNumerCoeffs, lb, ub)); vector<double> hornDenom(hornFromCheby(chebyDenomCoeffs, lb, ub)); //save the final coefficients to be used with eval //remember to renormalize so that the denominator constant is always 1 coeff_.resize(numNumer_+numDenom_-1); for (int nn=0; nn<numNumer_; nn++) { coeff_[nn] = hornNumer[nn]/hornDenom[0]; } for (int dd=1; dd<numDenom_; dd++) { coeff_[numNumer_ + dd-1] = hornDenom[dd]/hornDenom[0]; } return bestError; }
29.447059
146
0.509788
[ "vector" ]
cb66dafc29ada5036c36ebfe55398eaaa418d737
3,804
cpp
C++
kdmapper/utils.cpp
zwd1208/kdmapper
c3b404298bf90b8fb2e74c2be783569dd0eaa06e
[ "MIT" ]
456
2021-02-05T06:05:14.000Z
2022-03-30T03:00:39.000Z
kdmapper/utils.cpp
ry0kvn/kdmapper
c3b404298bf90b8fb2e74c2be783569dd0eaa06e
[ "MIT" ]
54
2021-02-04T15:58:10.000Z
2022-03-31T18:53:34.000Z
kdmapper/utils.cpp
ry0kvn/kdmapper
c3b404298bf90b8fb2e74c2be783569dd0eaa06e
[ "MIT" ]
177
2021-02-07T21:33:13.000Z
2022-03-31T19:49:17.000Z
#include "utils.hpp" std::wstring utils::GetFullTempPath() { wchar_t temp_directory[MAX_PATH + 1] = { 0 }; const uint32_t get_temp_path_ret = GetTempPathW(sizeof(temp_directory) / 2, temp_directory); if (!get_temp_path_ret || get_temp_path_ret > MAX_PATH + 1) { Log(L"[-] Failed to get temp path" << std::endl); return L""; } if (temp_directory[wcslen(temp_directory) - 1] == L'\\') temp_directory[wcslen(temp_directory) - 1] = 0x0; return std::wstring(temp_directory); } bool utils::ReadFileToMemory(const std::wstring& file_path, std::vector<uint8_t>* out_buffer) { std::ifstream file_ifstream(file_path, std::ios::binary); if (!file_ifstream) return false; out_buffer->assign((std::istreambuf_iterator<char>(file_ifstream)), std::istreambuf_iterator<char>()); file_ifstream.close(); return true; } bool utils::CreateFileFromMemory(const std::wstring& desired_file_path, const char* address, size_t size) { std::ofstream file_ofstream(desired_file_path.c_str(), std::ios_base::out | std::ios_base::binary); if (!file_ofstream.write(address, size)) { file_ofstream.close(); return false; } file_ofstream.close(); return true; } uint64_t utils::GetKernelModuleAddress(const std::string& module_name) { void* buffer = nullptr; DWORD buffer_size = 0; NTSTATUS status = NtQuerySystemInformation(static_cast<SYSTEM_INFORMATION_CLASS>(nt::SystemModuleInformation), buffer, buffer_size, &buffer_size); while (status == nt::STATUS_INFO_LENGTH_MISMATCH) { if (buffer != nullptr) VirtualFree(buffer, 0, MEM_RELEASE); buffer = VirtualAlloc(nullptr, buffer_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); status = NtQuerySystemInformation(static_cast<SYSTEM_INFORMATION_CLASS>(nt::SystemModuleInformation), buffer, buffer_size, &buffer_size); } if (!NT_SUCCESS(status)) { if (buffer != nullptr) VirtualFree(buffer, 0, MEM_RELEASE); return 0; } const auto modules = static_cast<nt::PRTL_PROCESS_MODULES>(buffer); if (!modules) return 0; for (auto i = 0u; i < modules->NumberOfModules; ++i) { const std::string current_module_name = std::string(reinterpret_cast<char*>(modules->Modules[i].FullPathName) + modules->Modules[i].OffsetToFileName); if (!_stricmp(current_module_name.c_str(), module_name.c_str())) { const uint64_t result = reinterpret_cast<uint64_t>(modules->Modules[i].ImageBase); VirtualFree(buffer, 0, MEM_RELEASE); return result; } } VirtualFree(buffer, 0, MEM_RELEASE); return 0; } BOOLEAN utils::bDataCompare(const BYTE* pData, const BYTE* bMask, const char* szMask) { for (; *szMask; ++szMask, ++pData, ++bMask) if (*szMask == 'x' && *pData != *bMask) return 0; return (*szMask) == 0; } uintptr_t utils::FindPattern(uintptr_t dwAddress, uintptr_t dwLen, BYTE* bMask, char* szMask) { size_t max_len = dwLen - strlen(szMask); for (uintptr_t i = 0; i < max_len; i++) if (bDataCompare((BYTE*)(dwAddress + i), bMask, szMask)) return (uintptr_t)(dwAddress + i); return 0; } PVOID utils::FindSection(char* sectionName, uintptr_t modulePtr, PULONG size) { size_t namelength = strlen(sectionName); PIMAGE_NT_HEADERS headers = (PIMAGE_NT_HEADERS)(modulePtr + ((PIMAGE_DOS_HEADER)modulePtr)->e_lfanew); PIMAGE_SECTION_HEADER sections = IMAGE_FIRST_SECTION(headers); for (DWORD i = 0; i < headers->FileHeader.NumberOfSections; ++i) { PIMAGE_SECTION_HEADER section = &sections[i]; if (memcmp(section->Name, sectionName, namelength) == 0 && namelength == strlen((char*)section->Name)) { if (!section->VirtualAddress) { return 0; } if (size) { *size = section->Misc.VirtualSize; } return (PVOID)(modulePtr + section->VirtualAddress); } } return 0; }
33.663717
153
0.699264
[ "vector" ]
cb6d5d1024a0729db521c154023edf4f3f99d936
52,558
cpp
C++
3rdparty/UND/src/undname.cpp
vn-os/Vutils
e8c4cbc9ff5eebc6f3cc0114f5239f23ee696ad9
[ "MIT" ]
15
2018-05-17T12:15:45.000Z
2022-03-18T03:22:42.000Z
3rdparty/UND/src/undname.cpp
vn-os/Vutils
e8c4cbc9ff5eebc6f3cc0114f5239f23ee696ad9
[ "MIT" ]
null
null
null
3rdparty/UND/src/undname.cpp
vn-os/Vutils
e8c4cbc9ff5eebc6f3cc0114f5239f23ee696ad9
[ "MIT" ]
14
2018-05-17T12:58:32.000Z
2022-03-18T03:22:46.000Z
/* * Demangle VC++ symbols into C function prototypes * * Copyright 2000 Jon Griffiths * 2004 Eric Pouech * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <ctype.h> #pragma warning(push) #pragma warning(disable : 4267 4018 4244 4996) typedef char CHAR; typedef int BOOL; #define TRUE (1) #define FALSE (0) typedef void* (*malloc_func_t)(size_t); typedef void (*free_func_t)(void*); /* TODO: * - document a bit (grammar + functions) * - back-port this new code into tools/winedump/msmangle.c */ #define UNDNAME_COMPLETE (0x0000) #define UNDNAME_NO_LEADING_UNDERSCORES (0x0001) /* Don't show __ in calling convention */ #define UNDNAME_NO_MS_KEYWORDS (0x0002) /* Don't show calling convention at all */ #define UNDNAME_NO_FUNCTION_RETURNS (0x0004) /* Don't show function/method return value */ #define UNDNAME_NO_ALLOCATION_MODEL (0x0008) #define UNDNAME_NO_ALLOCATION_LANGUAGE (0x0010) #define UNDNAME_NO_MS_THISTYPE (0x0020) #define UNDNAME_NO_CV_THISTYPE (0x0040) #define UNDNAME_NO_THISTYPE (0x0060) #define UNDNAME_NO_ACCESS_SPECIFIERS (0x0080) /* Don't show access specifier (public/protected/private) */ #define UNDNAME_NO_THROW_SIGNATURES (0x0100) #define UNDNAME_NO_MEMBER_TYPE (0x0200) /* Don't show static/virtual specifier */ #define UNDNAME_NO_RETURN_UDT_MODEL (0x0400) #define UNDNAME_32_BIT_DECODE (0x0800) #define UNDNAME_NAME_ONLY (0x1000) /* Only report the variable/method name */ #define UNDNAME_NO_ARGUMENTS (0x2000) /* Don't show method arguments */ #define UNDNAME_NO_SPECIAL_SYMS (0x4000) #define UNDNAME_NO_COMPLEX_TYPE (0x8000) /* How data types modifiers are stored: * M (in the following definitions) is defined for * 'A', 'B', 'C' and 'D' as follows * {<A>}: "" * {<B>}: "const " * {<C>}: "volatile " * {<D>}: "const volatile " * * in arguments: * P<M>x {<M>}x* * Q<M>x {<M>}x* const * A<M>x {<M>}x& * in data fields: * same as for arguments and also the following * ?<M>x {<M>}x * */ struct array { unsigned start; /* first valid reference in array */ unsigned num; /* total number of used elts */ unsigned max; unsigned alloc; char** elts; }; /* Structure holding a parsed symbol */ struct parsed_symbol { unsigned flags; /* the UNDNAME_ flags used for demangling */ malloc_func_t mem_alloc_ptr; /* internal allocator */ free_func_t mem_free_ptr; /* internal deallocator */ const char* current; /* pointer in input (mangled) string */ char* result; /* demangled string */ struct array names; /* array of names for back reference */ struct array stack; /* stack of parsed strings */ void* alloc_list; /* linked list of allocated blocks */ unsigned avail_in_first; /* number of available bytes in head block */ }; /* Type for parsing mangled types */ struct datatype_t { const char* left; const char* right; }; static BOOL symbol_demangle(struct parsed_symbol* sym); /****************************************************************** * und_alloc * * Internal allocator. Uses a simple linked list of large blocks * where we use a poor-man allocator. It's fast, and since all * allocation is pool, memory management is easy (esp. freeing). */ static char* und_alloc(struct parsed_symbol* sym, unsigned int len) { void* ptr; #define BLOCK_SIZE 1024 #define AVAIL_SIZE (1024 - sizeof(void*)) if (len > AVAIL_SIZE) { /* allocate a specific block */ ptr = sym->mem_alloc_ptr(sizeof(void*) + len); if (!ptr) return NULL; *(void**)ptr = sym->alloc_list; sym->alloc_list = ptr; sym->avail_in_first = 0; ptr = (char*)sym->alloc_list + sizeof(void*); } else { if (len > sym->avail_in_first) { /* add a new block */ ptr = sym->mem_alloc_ptr(BLOCK_SIZE); if (!ptr) return NULL; *(void**)ptr = sym->alloc_list; sym->alloc_list = ptr; sym->avail_in_first = AVAIL_SIZE; } /* grab memory from head block */ ptr = (char*)sym->alloc_list + BLOCK_SIZE - sym->avail_in_first; sym->avail_in_first -= len; } return static_cast<char*>(ptr); #undef BLOCK_SIZE #undef AVAIL_SIZE } /****************************************************************** * und_free * Frees all the blocks in the list of large blocks allocated by * und_alloc. */ static void und_free_all(struct parsed_symbol* sym) { void* next; while (sym->alloc_list) { next = *(void**)sym->alloc_list; if(sym->mem_free_ptr) sym->mem_free_ptr(sym->alloc_list); sym->alloc_list = next; } sym->avail_in_first = 0; } /****************************************************************** * str_array_init * Initialises an array of strings */ static void str_array_init(struct array* a) { a->start = a->num = a->max = a->alloc = 0; a->elts = NULL; } /****************************************************************** * str_array_push * Adding a new string to an array */ static BOOL str_array_push(struct parsed_symbol* sym, const char* ptr, int len, struct array* a) { char** _new; assert(ptr); assert(a); if (!a->alloc) { _new = (char**)und_alloc(sym, (a->alloc = 32) * sizeof(a->elts[0])); if (!_new) return FALSE; a->elts = _new; } else if (a->max >= a->alloc) { _new = (char**)und_alloc(sym, (a->alloc * 2) * sizeof(a->elts[0])); if (!_new) return FALSE; memcpy(_new, a->elts, a->alloc * sizeof(a->elts[0])); a->alloc *= 2; a->elts = _new; } if (len == -1) len = strlen(ptr); a->elts[a->num] = und_alloc(sym, len + 1); assert(a->elts[a->num]); memcpy(a->elts[a->num], ptr, len); a->elts[a->num][len] = '\0'; if (++a->num >= a->max) a->max = a->num; { int i; char c; for (i = a->max - 1; i >= 0; i--) { c = '>'; if (i < a->start) c = '-'; else if (i >= a->num) c = '}'; //TRACE("%p\t%d%c %s\n", a, i, c, a->elts[i]); // Silence unused var warning when TRACE is commented out (void)c; } } return TRUE; } /****************************************************************** * str_array_get_ref * Extracts a reference from an existing array (doing proper type * checking) */ static char* str_array_get_ref(struct array* cref, unsigned idx) { if (!cref) return NULL; if (cref->start + idx >= cref->max) { // WARN("Out of bounds: %p %d + %d >= %d\n", // cref, cref->start, idx, cref->max); return NULL; } // TRACE("Returning %p[%d] => %s\n", // cref, idx, cref->elts[cref->start + idx]); return cref->elts[cref->start + idx]; } /****************************************************************** * str_printf * Helper for printf type of command (only %s and %c are implemented) * while dynamically allocating the buffer */ static char* str_printf(struct parsed_symbol* sym, const char* format, ...) { va_list args; unsigned int len = 1, i, sz; char* tmp; char* p; char* t; va_start(args, format); for (i = 0; format[i]; i++) { if (format[i] == '%') { switch (format[++i]) { case 's': t = va_arg(args, char *); if (t) len += strlen(t); break; case 'c': (void)va_arg(args, int); len++; break; default: i--; /* fall through */ case '%': len++; break; } } else len++; } va_end(args); if (!(tmp = und_alloc(sym, len))) return NULL; va_start(args, format); for (p = tmp, i = 0; format[i]; i++) { if (format[i] == '%') { switch (format[++i]) { case 's': t = va_arg(args, char*); if (t) { sz = strlen(t); memcpy(p, t, sz); p += sz; } break; case 'c': *p++ = (char)va_arg(args, int); break; default: i--; /* fall through */ case '%': *p++ = '%'; break; } } else *p++ = format[i]; } va_end(args); *p = '\0'; return tmp; } /* forward declaration */ static BOOL demangle_datatype(struct parsed_symbol* sym, struct datatype_t* ct, struct array* pmt, BOOL in_args); static const char* get_number(struct parsed_symbol* sym) { char* ptr; BOOL sgn = FALSE; if (*sym->current == '?') { sgn = TRUE; sym->current++; } if (*sym->current >= '0' && *sym->current <= '8') { ptr = und_alloc(sym, 3); if (sgn) ptr[0] = '-'; ptr[sgn ? 1 : 0] = *sym->current + 1; ptr[sgn ? 2 : 1] = '\0'; sym->current++; } else if (*sym->current == '9') { ptr = und_alloc(sym, 4); if (sgn) ptr[0] = '-'; ptr[sgn ? 1 : 0] = '1'; ptr[sgn ? 2 : 1] = '0'; ptr[sgn ? 3 : 2] = '\0'; sym->current++; } else if (*sym->current >= 'A' && *sym->current <= 'P') { unsigned int ret = 0; while (*sym->current >= 'A' && *sym->current <= 'P') { ret *= 16; ret += *sym->current++ - 'A'; } if (*sym->current != '@') return NULL; ptr = und_alloc(sym, 17); sprintf(ptr, "%s%u", sgn ? "-" : "", ret); sym->current++; } else return NULL; return ptr; } /****************************************************************** * get_args * Parses a list of function/method arguments, creates a string corresponding * to the arguments' list. */ static char* get_args(struct parsed_symbol* sym, struct array* pmt_ref, BOOL z_term, char open_char, char close_char) { struct datatype_t ct; struct array arg_collect; char* args_str = NULL; char* last; unsigned int i; str_array_init(&arg_collect); /* Now come the function arguments */ while (*sym->current) { /* Decode each data type and append it to the argument list */ if (*sym->current == '@') { sym->current++; break; } if (!demangle_datatype(sym, &ct, pmt_ref, TRUE)) return NULL; /* 'void' terminates an argument list in a function */ if (z_term && !strcmp(ct.left, "void")) break; if (!str_array_push(sym, str_printf(sym, "%s%s", ct.left, ct.right), -1, &arg_collect)) return NULL; if (!strcmp(ct.left, "...")) break; } /* Functions are always terminated by 'Z'. If we made it this far and * don't find it, we have incorrectly identified a data type. */ if (z_term && *sym->current++ != 'Z') return NULL; if (arg_collect.num == 0 || (arg_collect.num == 1 && !strcmp(arg_collect.elts[0], "void"))) return str_printf(sym, "%cvoid%c", open_char, close_char); for (i = 1; i < arg_collect.num; i++) { args_str = str_printf(sym, "%s,%s", args_str, arg_collect.elts[i]); } last = args_str ? args_str : arg_collect.elts[0]; if (close_char == '>' && last[strlen(last) - 1] == '>') args_str = str_printf(sym, "%c%s%s %c", open_char, arg_collect.elts[0], args_str, close_char); else args_str = str_printf(sym, "%c%s%s%c", open_char, arg_collect.elts[0], args_str, close_char); return args_str; } /****************************************************************** * get_modifier * Parses the type modifier. Always returns static strings. */ static BOOL get_modifier(struct parsed_symbol *sym, const char **ret, const char **ptr_modif) { *ptr_modif = NULL; if (*sym->current == 'E') { *ptr_modif = "__ptr64"; sym->current++; } switch (*sym->current++) { case 'A': *ret = NULL; break; case 'B': *ret = "const"; break; case 'C': *ret = "volatile"; break; case 'D': *ret = "const volatile"; break; default: return FALSE; } return TRUE; } static BOOL get_modified_type(struct datatype_t *ct, struct parsed_symbol* sym, struct array *pmt_ref, char modif, BOOL in_args) { const char* modifier; const char* str_modif; const char *ptr_modif = ""; if (*sym->current == 'E') { ptr_modif = " __ptr64"; sym->current++; } switch (modif) { case 'A': str_modif = str_printf(sym, " &%s", ptr_modif); break; case 'B': str_modif = str_printf(sym, " &%s volatile", ptr_modif); break; case 'P': str_modif = str_printf(sym, " *%s", ptr_modif); break; case 'Q': str_modif = str_printf(sym, " *%s const", ptr_modif); break; case 'R': str_modif = str_printf(sym, " *%s volatile", ptr_modif); break; case 'S': str_modif = str_printf(sym, " *%s const volatile", ptr_modif); break; case '?': str_modif = ""; break; default: return FALSE; } if (get_modifier(sym, &modifier, &ptr_modif)) { unsigned mark = sym->stack.num; struct datatype_t sub_ct; /* multidimensional arrays */ if (*sym->current == 'Y') { const char* n1; int num; sym->current++; if (!(n1 = get_number(sym))) return FALSE; num = atoi(n1); if (str_modif[0] == ' ' && !modifier) str_modif++; if (modifier) { str_modif = str_printf(sym, " (%s%s)", modifier, str_modif); modifier = NULL; } else str_modif = str_printf(sym, " (%s)", str_modif); while (num--) str_modif = str_printf(sym, "%s[%s]", str_modif, get_number(sym)); } /* Recurse to get the referred-to type */ if (!demangle_datatype(sym, &sub_ct, pmt_ref, FALSE)) return FALSE; if (modifier) ct->left = str_printf(sym, "%s %s%s", sub_ct.left, modifier, str_modif ); else { /* don't insert a space between duplicate '*' */ if (!in_args && str_modif[0] && str_modif[1] == '*' && sub_ct.left[strlen(sub_ct.left)-1] == '*') str_modif++; ct->left = str_printf(sym, "%s%s", sub_ct.left, str_modif ); } ct->right = sub_ct.right; sym->stack.num = mark; } return TRUE; } /****************************************************************** * get_literal_string * Gets the literal name from the current position in the mangled * symbol to the first '@' character. It pushes the parsed name to * the symbol names stack and returns a pointer to it or NULL in * case of an error. */ static char* get_literal_string(struct parsed_symbol* sym) { const char *ptr = sym->current; do { if (!((*sym->current >= 'A' && *sym->current <= 'Z') || (*sym->current >= 'a' && *sym->current <= 'z') || (*sym->current >= '0' && *sym->current <= '9') || *sym->current == '_' || *sym->current == '$')) { //TRACE("Failed at '%c' in %s\n", *sym->current, ptr); return NULL; } } while (*++sym->current != '@'); sym->current++; if (!str_array_push(sym, ptr, sym->current - 1 - ptr, &sym->names)) return NULL; return str_array_get_ref(&sym->names, sym->names.num - sym->names.start - 1); } /****************************************************************** * get_template_name * Parses a name with a template argument list and returns it as * a string. * In a template argument list the back reference to the names * table is separately created. '0' points to the class component * name with the template arguments. We use the same stack array * to hold the names but save/restore the stack state before/after * parsing the template argument list. */ static char* get_template_name(struct parsed_symbol* sym) { char *name, *args; unsigned num_mark = sym->names.num; unsigned start_mark = sym->names.start; unsigned stack_mark = sym->stack.num; struct array array_pmt; sym->names.start = sym->names.num; if (!(name = get_literal_string(sym))) return FALSE; str_array_init(&array_pmt); args = get_args(sym, &array_pmt, FALSE, '<', '>'); if (args != NULL) name = str_printf(sym, "%s%s", name, args); sym->names.num = num_mark; sym->names.start = start_mark; sym->stack.num = stack_mark; return name; } /****************************************************************** * get_class * Parses class as a list of parent-classes, terminated by '@' and stores the * result in 'a' array. Each parent-classes, as well as the inner element * (either field/method name or class name), are represented in the mangled * name by a literal name ([a-zA-Z0-9_]+ terminated by '@') or a back reference * ([0-9]) or a name with template arguments ('?$' literal name followed by the * template argument list). The class name components appear in the reverse * order in the mangled name, e.g aaa@bbb@ccc@@ will be demangled to * ccc::bbb::aaa * For each of these class name components a string will be allocated in the * array. */ static BOOL get_class(struct parsed_symbol* sym) { const char* name = NULL; while (*sym->current != '@') { switch (*sym->current) { case '\0': return FALSE; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': name = str_array_get_ref(&sym->names, *sym->current++ - '0'); break; case '?': switch (*++sym->current) { case '$': sym->current++; if ((name = get_template_name(sym)) && !str_array_push(sym, name, -1, &sym->names)) return FALSE; break; case '?': { struct array stack = sym->stack; unsigned int start = sym->names.start; unsigned int num = sym->names.num; str_array_init( &sym->stack ); if (symbol_demangle( sym )) name = str_printf( sym, "`%s'", sym->result ); sym->names.start = start; sym->names.num = num; sym->stack = stack; } break; default: if (!(name = get_number( sym ))) return FALSE; name = str_printf( sym, "`%s'", name ); break; } break; default: name = get_literal_string(sym); break; } if (!name || !str_array_push(sym, name, -1, &sym->stack)) return FALSE; } sym->current++; return TRUE; } /****************************************************************** * get_class_string * From an array collected by get_class in sym->stack, constructs the * corresponding (allocated) string */ static char* get_class_string(struct parsed_symbol* sym, int start) { int i; unsigned int len, sz; char* ret; struct array *a = &sym->stack; for (len = 0, i = start; i < a->num; i++) { assert(a->elts[i]); len += 2 + strlen(a->elts[i]); } if (!(ret = und_alloc(sym, len - 1))) return NULL; for (len = 0, i = a->num - 1; i >= start; i--) { sz = strlen(a->elts[i]); memcpy(ret + len, a->elts[i], sz); len += sz; if (i > start) { ret[len++] = ':'; ret[len++] = ':'; } } ret[len] = '\0'; return ret; } /****************************************************************** * get_class_name * Wrapper around get_class and get_class_string. */ static char* get_class_name(struct parsed_symbol* sym) { unsigned mark = sym->stack.num; char* s = NULL; if (get_class(sym)) s = get_class_string(sym, mark); sym->stack.num = mark; return s; } /****************************************************************** * get_calling_convention * Returns a static string corresponding to the calling convention described * by char 'ch'. Sets export to TRUE iff the calling convention is exported. */ static BOOL get_calling_convention(char ch, const char** call_conv, const char** exported, unsigned flags) { *call_conv = *exported = NULL; if (!(flags & (UNDNAME_NO_MS_KEYWORDS | UNDNAME_NO_ALLOCATION_LANGUAGE))) { if (flags & UNDNAME_NO_LEADING_UNDERSCORES) { if (((ch - 'A') % 2) == 1) *exported = "dll_export "; switch (ch) { case 'A': case 'B': *call_conv = "cdecl"; break; case 'C': case 'D': *call_conv = "pascal"; break; case 'E': case 'F': *call_conv = "thiscall"; break; case 'G': case 'H': *call_conv = "stdcall"; break; case 'I': case 'J': *call_conv = "fastcall"; break; case 'K': case 'L': break; case 'M': *call_conv = "clrcall"; break; default: printf("Unknown calling convention %c\n", ch); return FALSE; } } else { if (((ch - 'A') % 2) == 1) *exported = "__dll_export "; switch (ch) { case 'A': case 'B': *call_conv = "__cdecl"; break; case 'C': case 'D': *call_conv = "__pascal"; break; case 'E': case 'F': *call_conv = "__thiscall"; break; case 'G': case 'H': *call_conv = "__stdcall"; break; case 'I': case 'J': *call_conv = "__fastcall"; break; case 'K': case 'L': break; case 'M': *call_conv = "__clrcall"; break; default: printf("Unknown calling convention %c\n", ch); return FALSE; } } } return TRUE; } /******************************************************************* * get_simple_type * Return a string containing an allocated string for a simple data type */ static const char* get_simple_type(char c) { const char* type_string; switch (c) { case 'C': type_string = "signed char"; break; case 'D': type_string = "char"; break; case 'E': type_string = "unsigned char"; break; case 'F': type_string = "short"; break; case 'G': type_string = "unsigned short"; break; case 'H': type_string = "int"; break; case 'I': type_string = "unsigned int"; break; case 'J': type_string = "long"; break; case 'K': type_string = "unsigned long"; break; case 'M': type_string = "float"; break; case 'N': type_string = "double"; break; case 'O': type_string = "long double"; break; case 'X': type_string = "void"; break; case 'Z': type_string = "..."; break; default: type_string = NULL; break; } return type_string; } /******************************************************************* * get_extended_type * Return a string containing an allocated string for a simple data type */ static const char* get_extended_type(char c) { const char* type_string; switch (c) { case 'D': type_string = "__int8"; break; case 'E': type_string = "unsigned __int8"; break; case 'F': type_string = "__int16"; break; case 'G': type_string = "unsigned __int16"; break; case 'H': type_string = "__int32"; break; case 'I': type_string = "unsigned __int32"; break; case 'J': type_string = "__int64"; break; case 'K': type_string = "unsigned __int64"; break; case 'L': type_string = "__int128"; break; case 'M': type_string = "unsigned __int128"; break; case 'N': type_string = "bool"; break; case 'W': type_string = "wchar_t"; break; default: type_string = NULL; break; } return type_string; } /******************************************************************* * demangle_datatype * * Attempt to demangle a C++ data type, which may be datatype. * a datatype type is made up of a number of simple types. e.g: * char** = (pointer to (pointer to (char))) */ static BOOL demangle_datatype(struct parsed_symbol* sym, struct datatype_t* ct, struct array* pmt_ref, BOOL in_args) { char dt; BOOL add_pmt = TRUE; assert(ct); ct->left = ct->right = NULL; switch (dt = *sym->current++) { case '_': /* MS type: __int8,__int16 etc */ ct->left = get_extended_type(*sym->current++); break; case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'M': case 'N': case 'O': case 'X': case 'Z': /* Simple data types */ ct->left = get_simple_type(dt); add_pmt = FALSE; break; case 'T': /* union */ case 'U': /* struct */ case 'V': /* class */ case 'Y': /* cointerface */ /* Class/struct/union/cointerface */ { const char* struct_name = NULL; const char* type_name = NULL; if (!(struct_name = get_class_name(sym))) goto done; if (!(sym->flags & UNDNAME_NO_COMPLEX_TYPE)) { switch (dt) { case 'T': type_name = "union "; break; case 'U': type_name = "struct "; break; case 'V': type_name = "class "; break; case 'Y': type_name = "cointerface "; break; } } ct->left = str_printf(sym, "%s%s", type_name, struct_name); } break; case '?': /* not all the time is seems */ if (in_args) { const char* ptr; if (!(ptr = get_number(sym))) goto done; ct->left = str_printf(sym, "`template-parameter-%s'", ptr); } else { if (!get_modified_type(ct, sym, pmt_ref, '?', in_args)) goto done; } break; case 'A': /* reference */ case 'B': /* volatile reference */ if (!get_modified_type(ct, sym, pmt_ref, dt, in_args)) goto done; break; case 'Q': /* const pointer */ case 'R': /* volatile pointer */ case 'S': /* const volatile pointer */ if (!get_modified_type(ct, sym, pmt_ref, in_args ? dt : 'P', in_args)) goto done; break; case 'P': /* Pointer */ if (isdigit(*sym->current)) { /* FIXME: P6 = Function pointer, others who knows.. */ if (*sym->current++ == '6') { char* args = NULL; const char* call_conv; const char* exported; struct datatype_t sub_ct; unsigned mark = sym->stack.num; if (!get_calling_convention(*sym->current++, &call_conv, &exported, sym->flags & ~UNDNAME_NO_ALLOCATION_LANGUAGE) || !demangle_datatype(sym, &sub_ct, pmt_ref, FALSE)) goto done; args = get_args(sym, pmt_ref, TRUE, '(', ')'); if (!args) goto done; sym->stack.num = mark; ct->left = str_printf(sym, "%s%s (%s*", sub_ct.left, sub_ct.right, call_conv); ct->right = str_printf(sym, ")%s", args); } else goto done; } else if (!get_modified_type(ct, sym, pmt_ref, 'P', in_args)) goto done; break; case 'W': if (*sym->current == '4') { char* enum_name; sym->current++; if (!(enum_name = get_class_name(sym))) goto done; if (sym->flags & UNDNAME_NO_COMPLEX_TYPE) ct->left = enum_name; else ct->left = str_printf(sym, "enum %s", enum_name); } else goto done; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': /* Referring back to previously parsed type */ /* left and right are pushed as two separate strings */ ct->left = str_array_get_ref(pmt_ref, (dt - '0') * 2); ct->right = str_array_get_ref(pmt_ref, (dt - '0') * 2 + 1); if (!ct->left) goto done; add_pmt = FALSE; break; case '$': switch (*sym->current++) { case '0': if (!(ct->left = get_number(sym))) goto done; break; case 'D': { const char* ptr; if (!(ptr = get_number(sym))) goto done; ct->left = str_printf(sym, "`template-parameter%s'", ptr); } break; case 'F': { const char* p1; const char* p2; if (!(p1 = get_number(sym))) goto done; if (!(p2 = get_number(sym))) goto done; ct->left = str_printf(sym, "{%s,%s}", p1, p2); } break; case 'G': { const char* p1; const char* p2; const char* p3; if (!(p1 = get_number(sym))) goto done; if (!(p2 = get_number(sym))) goto done; if (!(p3 = get_number(sym))) goto done; ct->left = str_printf(sym, "{%s,%s,%s}", p1, p2, p3); } break; case 'Q': { const char* ptr; if (!(ptr = get_number(sym))) goto done; ct->left = str_printf(sym, "`non-type-template-parameter%s'", ptr); } break; case '$': if (*sym->current == 'C') { const char *ptr, *ptr_modif; sym->current++; if (!get_modifier(sym, &ptr, &ptr_modif)) goto done; if (!demangle_datatype(sym, ct, pmt_ref, in_args)) goto done; ct->left = str_printf(sym, "%s %s", ct->left, ptr); } break; } break; default : printf("Unknown type %c\n", dt); break; } if (add_pmt && pmt_ref && in_args) { /* left and right are pushed as two separate strings */ if (!str_array_push(sym, ct->left ? ct->left : "", -1, pmt_ref) || !str_array_push(sym, ct->right ? ct->right : "", -1, pmt_ref)) return FALSE; } done: return ct->left != NULL; } /****************************************************************** * handle_data * Does the final parsing and handling for a variable or a field in * a class. */ static BOOL handle_data(struct parsed_symbol* sym) { const char* access = NULL; const char* member_type = NULL; const char* modifier = NULL; const char* ptr_modif; struct datatype_t ct; char* name = NULL; BOOL ret = FALSE; /* 0 private static * 1 protected static * 2 public static * 3 private non-static * 4 protected non-static * 5 public non-static * 6 ?? static * 7 ?? static */ if (!(sym->flags & UNDNAME_NO_ACCESS_SPECIFIERS)) { /* we only print the access for static members */ switch (*sym->current) { case '0': access = "private: "; break; case '1': access = "protected: "; break; case '2': access = "public: "; break; } } if (!(sym->flags & UNDNAME_NO_MEMBER_TYPE)) { if (*sym->current >= '0' && *sym->current <= '2') member_type = "static "; } name = get_class_string(sym, 0); switch (*sym->current++) { case '0': case '1': case '2': case '3': case '4': case '5': { unsigned mark = sym->stack.num; struct array pmt; str_array_init(&pmt); if (!demangle_datatype(sym, &ct, &pmt, FALSE)) goto done; if (!get_modifier(sym, &modifier, &ptr_modif)) goto done; if (modifier && ptr_modif) modifier = str_printf(sym, "%s %s", modifier, ptr_modif); else if (!modifier) modifier = ptr_modif; sym->stack.num = mark; } break; case '6' : /* compiler generated static */ case '7' : /* compiler generated static */ ct.left = ct.right = NULL; if (!get_modifier(sym, &modifier, &ptr_modif)) goto done; if (*sym->current != '@') { char* cls = NULL; if (!(cls = get_class_name(sym))) goto done; ct.right = str_printf(sym, "{for `%s'}", cls); } break; case '8': case '9': modifier = ct.left = ct.right = NULL; break; default: goto done; } if (sym->flags & UNDNAME_NAME_ONLY) ct.left = ct.right = modifier = NULL; sym->result = str_printf(sym, "%s%s%s%s%s%s%s%s", access, member_type, ct.left, modifier && ct.left ? " " : NULL, modifier, modifier || ct.left ? " " : NULL, name, ct.right); ret = TRUE; done: return ret; } /****************************************************************** * handle_method * Does the final parsing and handling for a function or a method in * a class. */ static BOOL handle_method(struct parsed_symbol* sym, BOOL cast_op) { char accmem; const char* access = NULL; const char* member_type = NULL; struct datatype_t ct_ret; const char* call_conv; const char* modifier = NULL; const char* exported; const char* args_str = NULL; const char* name = NULL; BOOL ret = FALSE; unsigned mark; struct array array_pmt; /* FIXME: why 2 possible letters for each option? * 'A' private: * 'B' private: * 'C' private: static * 'D' private: static * 'E' private: virtual * 'F' private: virtual * 'G' private: thunk * 'H' private: thunk * 'I' protected: * 'J' protected: * 'K' protected: static * 'L' protected: static * 'M' protected: virtual * 'N' protected: virtual * 'O' protected: thunk * 'P' protected: thunk * 'Q' public: * 'R' public: * 'S' public: static * 'T' public: static * 'U' public: virtual * 'V' public: virtual * 'W' public: thunk * 'X' public: thunk * 'Y' * 'Z' */ accmem = *sym->current++; if (accmem < 'A' || accmem > 'Z') goto done; if (!(sym->flags & UNDNAME_NO_ACCESS_SPECIFIERS)) { switch ((accmem - 'A') / 8) { case 0: access = "private: "; break; case 1: access = "protected: "; break; case 2: access = "public: "; break; } } if (!(sym->flags & UNDNAME_NO_MEMBER_TYPE)) { if (accmem <= 'X') { switch ((accmem - 'A') % 8) { case 2: case 3: member_type = "static "; break; case 4: case 5: member_type = "virtual "; break; case 6: case 7: access = str_printf(sym, "[thunk]:%s", access); member_type = "virtual "; break; } } } name = get_class_string(sym, 0); if ((accmem - 'A') % 8 == 6 || (accmem - '8') % 8 == 7) /* a thunk */ name = str_printf(sym, "%s`adjustor{%s}' ", name, get_number(sym)); if (accmem <= 'X') { if (((accmem - 'A') % 8) != 2 && ((accmem - 'A') % 8) != 3) { const char *ptr_modif; /* Implicit 'this' pointer */ /* If there is an implicit this pointer, const modifier follows */ if (!get_modifier(sym, &modifier, &ptr_modif)) goto done; if (modifier || ptr_modif) modifier = str_printf(sym, "%s %s", modifier, ptr_modif); } } if (!get_calling_convention(*sym->current++, &call_conv, &exported, sym->flags)) goto done; str_array_init(&array_pmt); /* Return type, or @ if 'void' */ if (*sym->current == '@') { ct_ret.left = "void"; ct_ret.right = NULL; sym->current++; } else { if (!demangle_datatype(sym, &ct_ret, &array_pmt, FALSE)) goto done; } if (sym->flags & UNDNAME_NO_FUNCTION_RETURNS) ct_ret.left = ct_ret.right = NULL; if (cast_op) { name = str_printf(sym, "%s%s%s", name, ct_ret.left, ct_ret.right); ct_ret.left = ct_ret.right = NULL; } mark = sym->stack.num; if (!(args_str = get_args(sym, &array_pmt, TRUE, '(', ')'))) goto done; if (sym->flags & UNDNAME_NAME_ONLY) args_str = modifier = NULL; sym->stack.num = mark; /* Note: '()' after 'Z' means 'throws', but we don't care here * Yet!!! FIXME */ sym->result = str_printf(sym, "%s%s%s%s%s%s%s%s%s%s%s", access, member_type, ct_ret.left, (ct_ret.left && !ct_ret.right) ? " " : NULL, call_conv, call_conv ? " " : NULL, exported, name, args_str, modifier, ct_ret.right); ret = TRUE; done: return ret; } /****************************************************************** * handle_template * Does the final parsing and handling for a name with templates */ static BOOL handle_template(struct parsed_symbol* sym) { const char* name; const char* args; assert(*sym->current == '$'); sym->current++; if (!(name = get_literal_string(sym))) return FALSE; if (!(args = get_args(sym, NULL, FALSE, '<', '>'))) return FALSE; sym->result = str_printf(sym, "%s%s", name, args); return TRUE; } /******************************************************************* * symbol_demangle * Demangle a C++ linker symbol */ static BOOL symbol_demangle(struct parsed_symbol* sym) { BOOL ret = FALSE; unsigned do_after = 0; static CHAR dashed_null[] = "--null--"; /* FIXME seems wrong as name, as it demangles a simple data type */ if (sym->flags & UNDNAME_NO_ARGUMENTS) { struct datatype_t ct; if (demangle_datatype(sym, &ct, NULL, FALSE)) { sym->result = str_printf(sym, "%s%s", ct.left, ct.right); ret = TRUE; } goto done; } /* MS mangled names always begin with '?' */ if (*sym->current != '?') return FALSE; sym->current++; /* Then function name or operator code */ if (*sym->current == '?' && (sym->current[1] != '$' || sym->current[2] == '?')) { const char* function_name = NULL; if (sym->current[1] == '$') { do_after = 6; sym->current += 2; } /* C++ operator code (one character, or two if the first is '_') */ switch (*++sym->current) { case '0': do_after = 1; break; case '1': do_after = 2; break; case '2': function_name = "operator new"; break; case '3': function_name = "operator delete"; break; case '4': function_name = "operator="; break; case '5': function_name = "operator>>"; break; case '6': function_name = "operator<<"; break; case '7': function_name = "operator!"; break; case '8': function_name = "operator=="; break; case '9': function_name = "operator!="; break; case 'A': function_name = "operator[]"; break; case 'B': function_name = "operator "; do_after = 3; break; case 'C': function_name = "operator->"; break; case 'D': function_name = "operator*"; break; case 'E': function_name = "operator++"; break; case 'F': function_name = "operator--"; break; case 'G': function_name = "operator-"; break; case 'H': function_name = "operator+"; break; case 'I': function_name = "operator&"; break; case 'J': function_name = "operator->*"; break; case 'K': function_name = "operator/"; break; case 'L': function_name = "operator%"; break; case 'M': function_name = "operator<"; break; case 'N': function_name = "operator<="; break; case 'O': function_name = "operator>"; break; case 'P': function_name = "operator>="; break; case 'Q': function_name = "operator,"; break; case 'R': function_name = "operator()"; break; case 'S': function_name = "operator~"; break; case 'T': function_name = "operator^"; break; case 'U': function_name = "operator|"; break; case 'V': function_name = "operator&&"; break; case 'W': function_name = "operator||"; break; case 'X': function_name = "operator*="; break; case 'Y': function_name = "operator+="; break; case 'Z': function_name = "operator-="; break; case '_': switch (*++sym->current) { case '0': function_name = "operator/="; break; case '1': function_name = "operator%="; break; case '2': function_name = "operator>>="; break; case '3': function_name = "operator<<="; break; case '4': function_name = "operator&="; break; case '5': function_name = "operator|="; break; case '6': function_name = "operator^="; break; case '7': function_name = "`vftable'"; break; case '8': function_name = "`vbtable'"; break; case '9': function_name = "`vcall'"; break; case 'A': function_name = "`typeof'"; break; case 'B': function_name = "`local static guard'"; break; case 'C': function_name = "`string'"; do_after = 4; break; case 'D': function_name = "`vbase destructor'"; break; case 'E': function_name = "`vector deleting destructor'"; break; case 'F': function_name = "`default constructor closure'"; break; case 'G': function_name = "`scalar deleting destructor'"; break; case 'H': function_name = "`vector constructor iterator'"; break; case 'I': function_name = "`vector destructor iterator'"; break; case 'J': function_name = "`vector vbase constructor iterator'"; break; case 'K': function_name = "`virtual displacement map'"; break; case 'L': function_name = "`eh vector constructor iterator'"; break; case 'M': function_name = "`eh vector destructor iterator'"; break; case 'N': function_name = "`eh vector vbase constructor iterator'"; break; case 'O': function_name = "`copy constructor closure'"; break; case 'R': sym->flags |= UNDNAME_NO_FUNCTION_RETURNS; switch (*++sym->current) { case '0': { struct datatype_t ct; struct array pmt; sym->current++; str_array_init(&pmt); demangle_datatype(sym, &ct, &pmt, FALSE); function_name = str_printf(sym, "%s%s `RTTI Type Descriptor'", ct.left, ct.right); sym->current--; } break; case '1': { const char* n1, *n2, *n3, *n4; sym->current++; n1 = get_number(sym); n2 = get_number(sym); n3 = get_number(sym); n4 = get_number(sym); sym->current--; function_name = str_printf(sym, "`RTTI Base Class Descriptor at (%s,%s,%s,%s)'", n1, n2, n3, n4); } break; case '2': function_name = "`RTTI Base Class Array'"; break; case '3': function_name = "`RTTI Class Hierarchy Descriptor'"; break; case '4': function_name = "`RTTI Complete Object Locator'"; break; default: printf("Unknown RTTI operator: _R%c\n", *sym->current); break; } break; case 'S': function_name = "`local vftable'"; break; case 'T': function_name = "`local vftable constructor closure'"; break; case 'U': function_name = "operator new[]"; break; case 'V': function_name = "operator delete[]"; break; case 'X': function_name = "`placement delete closure'"; break; case 'Y': function_name = "`placement delete[] closure'"; break; default: printf("Unknown operator: _%c\n", *sym->current); return FALSE; } break; default: /* FIXME: Other operators */ printf("Unknown operator: %c\n", *sym->current); return FALSE; } sym->current++; switch (do_after) { case 1: case 2: if (!str_array_push(sym, dashed_null, -1, &sym->stack)) return FALSE; break; case 4: sym->result = (char*)function_name; ret = TRUE; goto done; case 6: { char *args; struct array array_pmt; str_array_init(&array_pmt); args = get_args(sym, &array_pmt, FALSE, '<', '>'); if (args != NULL) function_name = str_printf(sym, "%s%s", function_name, args); sym->names.num = 0; } /* fall through */ default: if (!str_array_push(sym, function_name, -1, &sym->stack)) return FALSE; break; } } else if (*sym->current == '$') { /* Strange construct, it's a name with a template argument list and that's all. */ sym->current++; ret = (sym->result = get_template_name(sym)) != NULL; goto done; } else if (*sym->current == '?' && sym->current[1] == '$') do_after = 5; /* Either a class name, or '@' if the symbol is not a class member */ switch (*sym->current) { case '@': sym->current++; break; case '$': break; default: /* Class the function is associated with, terminated by '@@' */ if (!get_class(sym)) goto done; break; } switch (do_after) { case 0: default: break; case 1: case 2: /* it's time to set the member name for ctor & dtor */ if (sym->stack.num <= 1) goto done; if (do_after == 1) sym->stack.elts[0] = sym->stack.elts[1]; else sym->stack.elts[0] = str_printf(sym, "~%s", sym->stack.elts[1]); /* ctors and dtors don't have return type */ sym->flags |= UNDNAME_NO_FUNCTION_RETURNS; break; case 3: sym->flags &= ~UNDNAME_NO_FUNCTION_RETURNS; break; case 5: sym->names.start++; break; } /* Function/Data type and access level */ if (*sym->current >= '0' && *sym->current <= '9') ret = handle_data(sym); else if (*sym->current >= 'A' && *sym->current <= 'Z') ret = handle_method(sym, do_after == 3); else if (*sym->current == '$') ret = handle_template(sym); else ret = FALSE; done: if (ret) assert(sym->result); // else WARN("Failed at %s\n", sym->current); return ret; } /********************************************************************* * __unDNameEx (MSVCRT.@) * * Demangle a C++ identifier. * * PARAMS * buffer [O] If not NULL, the place to put the demangled string * mangled [I] Mangled name of the function * buflen [I] Length of buffer * memget [I] Function to allocate memory with * memfree [I] Function to free memory with * unknown [?] Unknown, possibly a call back * flags [I] Flags determining demangled format * * RETURNS * Success: A string pointing to the unmangled name, allocated with memget. * Failure: NULL. */ char * __unDNameEx(char* buffer, const char* mangled, int buflen, malloc_func_t memget, free_func_t memfree, void* unknown, unsigned short int flags) { struct parsed_symbol sym; const char* result; //TRACE("(%p,%s,%d,%p,%p,%p,%x)\n", // buffer, mangled, buflen, memget, memfree, unknown, flags); /* The flags details is not documented by MS. However, it looks exactly * like the UNDNAME_ manifest constants from imagehlp.h and dbghelp.h * So, we copied those (on top of the file) */ memset(&sym, 0, sizeof(struct parsed_symbol)); if (flags & UNDNAME_NAME_ONLY) flags |= UNDNAME_NO_FUNCTION_RETURNS | UNDNAME_NO_ACCESS_SPECIFIERS | UNDNAME_NO_MEMBER_TYPE | UNDNAME_NO_ALLOCATION_LANGUAGE | UNDNAME_NO_COMPLEX_TYPE; sym.flags = flags; sym.mem_alloc_ptr = memget; sym.mem_free_ptr = memfree; sym.current = mangled; str_array_init( &sym.names ); str_array_init( &sym.stack ); result = symbol_demangle(&sym) ? sym.result : mangled; if (buffer && buflen) { strncpy( buffer, result, buflen); } else { buffer = (char*)memget(strlen(result) + 1); if (buffer) strcpy(buffer, result); } und_free_all(&sym); return buffer; } /********************************************************************* * __unDName (MSVCRT.@) */ char* __unDName(char* buffer, const char* mangled, int buflen, malloc_func_t memget, free_func_t memfree, unsigned short int flags) { return __unDNameEx(buffer, mangled, buflen, memget, memfree, NULL, flags); } char *undname(char *buffer, char *mangled, int buflen, unsigned short int flags) { return __unDName(buffer, mangled, buflen, malloc, free, flags); } // int main(int argc, char **argv) { // char buf[2048]; // char *out; // out = __unDName(buf, argv[1], 2048, malloc, free, UNDNAME_NO_LEADING_UNDERSCORES); // if(out) puts(buf); // return !!out; // } #pragma warning(pop)
33.476433
110
0.504585
[ "object", "vector" ]
cb6dfe4813fc4ad699e1d992aa30fecffa508e4f
293
cpp
C++
acmicpc/1292.cpp
juseongkr/BOJ
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
7
2020-02-03T10:00:19.000Z
2021-11-16T11:03:57.000Z
acmicpc/1292.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2021-01-03T06:58:24.000Z
2021-01-03T06:58:24.000Z
acmicpc/1292.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2020-01-22T14:34:03.000Z
2020-01-22T14:34:03.000Z
#include <iostream> #include <vector> using namespace std; int main() { int a, b, sum = 0; vector<int> num; cin >> a >> b; for (int i=0, k=1; i<b; ++i, ++k) for (int j=0; j<=i; ++j) num.push_back(k); for (int i=a-1; i<b; ++i) sum += num[i]; cout << sum << '\n'; return 0; }
13.318182
34
0.511945
[ "vector" ]
cb70210bf8d8d8d33af90e6af561fc2c6cfd80ec
622
cpp
C++
Dataset/Leetcode/valid/56/297.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/valid/56/297.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/valid/56/297.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<int>> XXX(vector<vector<int>>& intervals) { vector<vector<int>> res; sort(intervals.begin(),intervals.end()); res.push_back(intervals[0]); for(int i=1;i<intervals.size();i++){ if(intervals[i][0]>res.back()[1]) res.push_back(intervals[i]); else if(intervals[i][0]==res.back()[1]) res.back()[1] = intervals[i][1]; else{ if(intervals[i][1]>res.back()[1]) res.back()[1] = intervals[i][1]; } } return res; } };
29.619048
61
0.472669
[ "vector" ]
cb73790fb3b22b9f5176cd76579f10c31563a8de
32,390
cxx
C++
ivp/ivp_intern/ivp_sim_unit.cxx
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
252
2020-12-16T15:34:43.000Z
2022-03-31T23:21:37.000Z
ivp/ivp_intern/ivp_sim_unit.cxx
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
23
2020-12-20T18:02:54.000Z
2022-03-28T16:58:32.000Z
ivp/ivp_intern/ivp_sim_unit.cxx
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
42
2020-12-19T04:32:33.000Z
2022-03-30T06:00:28.000Z
// Copyright (C) Ipion Software GmbH 1999-2000. All rights reserved. #include <ivp_physics.hxx> #if !defined(WIN32) && !defined(PSXII) && !defined(GEKKO) # include <alloca.h> #endif #ifndef WIN32 # pragma implementation "ivp_sim_unit.hxx" #endif #include <ivp_controller.hxx> #include <ivp_mindist_intern.hxx> #include <ivp_friction.hxx> #include <ivp_core_macros.hxx> #include <ivp_sim_unit.hxx> #include <ivu_memory.hxx> #include <ivp_calc_next_psi_solver.hxx> #include <ivp_performancecounter.hxx> #include <ivp_time.hxx> IVP_U_Vector<IVP_Core> IVP_Controller_Independent::empty_list; #ifdef WIN32 extern long p_get_time(); #endif //the list of cores is valid, calculate the rest void IVP_Simulation_Unit::sim_unit_calc_redundants() { for (int i = sim_unit_cores.len()-1; i>=0; i--){ IVP_Core *my_core = sim_unit_cores.element_at(i); for (int k = my_core->controllers_of_core.len()-1; k>=0;k--){ IVP_Controller *my_controller = my_core->controllers_of_core.element_at(k); if( this->controller_is_known_to_sim_unit( my_controller ) == IVP_FALSE ) { this->add_controller_unit_sim( my_controller ); } this->add_controlled_core_for_controller( my_controller, my_core ); } } sim_unit_sort_controllers(); } IVP_BOOL IVP_Simulation_Unit::controller_is_known_to_sim_unit( IVP_Controller *my_controller ) { int i; for( i=controller_cores.len()-1; i>=0 ; i-- ) { if( controller_cores.element_at(i)->l_controller == my_controller ) { return IVP_TRUE; } } return IVP_FALSE; } // controller exists; add a core for this controller void IVP_Simulation_Unit::add_controlled_core_for_controller( IVP_Controller *cntrl, IVP_Core *my_core ) { int i; for( i=controller_cores.len()-1; i>=0 ; i-- ) { if( controller_cores.element_at(i)->l_controller == cntrl ) { break; } } IVP_ASSERT(i>=0); //IVP_ASSERT( controller_cores.element_at(i)->l_controller == cntrl ); controller_cores.element_at(i)->cores_controlled_by.add( my_core ); } void IVP_Simulation_Unit::add_controller_unit_sim( IVP_Controller *new_cntrl ) { //sim_unit_controllers.add( new_cntrl ); IVP_Sim_Unit_Controller_Core_List *core_list=new IVP_Sim_Unit_Controller_Core_List(); core_list->l_controller=new_cntrl; controller_cores.add(core_list); } void IVP_Simulation_Unit::split_sim_unit(IVP_Core *split_father) { IVP_ASSERT(split_father); IVP_Core *my_core; IVP_Core *next_split_father=NULL; IVP_BOOL next_split_necessary=IVP_FALSE; IVP_Simulation_Unit *split_new_unit=new IVP_Simulation_Unit(); split_new_unit->sim_unit_movement_type=IVP_MT_MOVING; IVP_Sim_Units_Manager *s_man; s_man= split_father->environment->get_sim_units_manager(); s_man->add_sim_unit_to_manager( split_new_unit ); //faster: operate directly on list, build two new lists -> only linear not quadratic int i; for(i=0;i<sim_unit_cores.len();i++) { my_core=sim_unit_cores.element_at(i); IVP_Core *test_core=my_core->union_find_get_father(); if( test_core != split_father ) { if( next_split_father != NULL ) { if( test_core!=next_split_father ) { next_split_necessary=IVP_TRUE; } } else { next_split_father=test_core; } } else { sim_unit_cores.remove_at(i); i--; //size of list is reduced split_new_unit->sim_unit_cores.add(my_core); my_core->sim_unit_of_core=split_new_unit; } } split_new_unit->sim_unit_calc_redundants(); #ifdef DEBUG IVP_IF(1) { split_new_unit->sim_unit_debug_consistency(); } #endif if(next_split_necessary==IVP_TRUE) { this->split_sim_unit(next_split_father); } } void IVP_Simulation_Unit::perform_test_and_split() { IVP_Core *father=sim_unit_union_find_test(); if(father) { this->clean_sim_unit(); split_sim_unit(father); this->sim_unit_calc_redundants(); #ifdef DEBUG this->sim_unit_debug_consistency(); #endif } } IVP_Core *IVP_Simulation_Unit::sim_unit_union_find_test() { IVP_Core *my_core; for (int i = sim_unit_cores.len()-1; i>=0;i--){ my_core = sim_unit_cores.element_at(i); my_core->tmp.union_find_father=NULL; } for(int i2=controller_cores.len()-1; i2>=0; i2-- ) { IVP_Controller *my_controller=controller_cores.element_at(i2)->l_controller; IVP_U_Vector<IVP_Core> *list_of_cores; list_of_cores=my_controller->get_associated_controlled_cores(); int j; j=list_of_cores->len()-1; if(j>=0) { IVP_Core *father_core=list_of_cores->element_at(0)->union_find_get_father(); for(;j>=0;j--) { IVP_Core *test_core=list_of_cores->element_at(j); IVP_Core *test_father=test_core->union_find_get_father(); if(father_core!=test_father) { test_father->tmp.union_find_father=father_core; } } } } #if 0 for(my_core=this->get_first_sim_unit_core();my_core;my_core=this->get_next_sim_unit_core()) { IVP_Core *father_core=my_core->union_find_get_father(); for(my_controller=my_core->get_first_core_controller();my_controller;my_controller=my_core->get_next_core_controller()) { IVP_U_Vector<IVP_Core> *controlled_cores; controlled_cores=my_controller->get_associated_controlled_cores(my_core); for(i=controlled_cores->len()-1;i>=0;i--) { IVP_Core *test_core=controlled_cores->element_at(i); IVP_Core *test_father=test_core->union_find_get_father(); if(father_core!=test_father) { test_core->tmp.union_find_father=father_core; } } } } #endif IVP_Core *first_father=this->sim_unit_cores.element_at(0)->union_find_get_father(); // find representative obj for second system (must not be a fixed obj) { int j; for (j = 0; j < sim_unit_cores.len(); j++){ IVP_Core *obj = sim_unit_cores.element_at(j); IVP_Core *test_father=obj->union_find_get_father(); if(test_father!=first_father) { return test_father; } } } return NULL; } //clear redundant part void IVP_Simulation_Unit::clean_sim_unit() { int i; for(i=controller_cores.len()-1;i>=0;i--) { IVP_Sim_Unit_Controller_Core_List *c_info=controller_cores.element_at(i); P_DELETE( c_info ); } //sim_unit_controllers.clear(); controller_cores.clear(); } void IVP_Simulation_Unit::throw_cores_into_my_sim_unit(IVP_Simulation_Unit *second_unit) { IVP_Environment *env=NULL; int i; for ( i=0; i<second_unit->sim_unit_cores.len(); i++){ IVP_Core *my_core = second_unit->sim_unit_cores.element_at(i); this->add_sim_unit_core( my_core ); env=my_core->environment; my_core->sim_unit_of_core=this; } env->get_sim_units_manager()->rem_sim_unit_from_manager( second_unit ); } // second_unit is destroyed void IVP_Simulation_Unit::fusion_simulation_unities(IVP_Simulation_Unit *second_unit) { this->clean_sim_unit(); throw_cores_into_my_sim_unit(second_unit); this->sim_unit_calc_redundants(); } int IVP_Simulation_Unit::get_pos_of_controller( IVP_Controller *contr ) { int i; for(i=controller_cores.len()-1;i>=0;i--) { if(controller_cores.element_at(i)->l_controller == contr) { break; } } return i; } void IVP_Simulation_Unit::sim_unit_remove_core( IVP_Core *del_core ) { rem_sim_unit_core( del_core ); int i; for (i = del_core->controllers_of_core.len()-1; i>=0;i--){ IVP_Controller *my_controller= del_core->controllers_of_core.element_at(i); int pos=get_pos_of_controller(my_controller); IVP_ASSERT(pos>=0); IVP_Sim_Unit_Controller_Core_List *c_info=controller_cores.element_at(pos); c_info->cores_controlled_by.remove(del_core); if( c_info->cores_controlled_by.len() == 0 ) { rem_sim_unit_controller( my_controller ); } } if(sim_unit_cores.len()==0) { del_core->environment->get_sim_units_manager()->rem_sim_unit_from_manager(this); P_DELETE_THIS(this); } } IVP_Simulation_Unit::~IVP_Simulation_Unit() { this->clean_sim_unit(); ;//printf("delete_simu %lx\n",(long)this&0x0000ffff); } IVP_Simulation_Unit::IVP_Simulation_Unit() { //printf("create_simu %lx\n",(long)this&0x0000ffff); union_find_needed_for_sim_unit = IVP_FALSE; sim_unit_movement_type = IVP_MT_NOT_SIM; sim_unit_just_slowed_down = IVP_FALSE; sim_unit_has_fast_objects = IVP_FALSE; } void IVP_Simulation_Unit::rem_sim_unit_controller( IVP_Controller *rem_controller ) { int pos=get_pos_of_controller( rem_controller ); IVP_ASSERT(pos>=0); IVP_Sim_Unit_Controller_Core_List *c_info=controller_cores.element_at(pos); P_DELETE(c_info); controller_cores.remove_at(pos); //sim_unit_controllers.delete_at(pos); } void IVP_Simulation_Unit::add_sim_unit_core( IVP_Core *add_core ) { sim_unit_cores.add( add_core ); } void IVP_Simulation_Unit::rem_sim_unit_core( IVP_Core *del_core ) { sim_unit_cores.remove( del_core ); } IVP_BOOL IVP_Simulation_Unit::sim_unit_core_exists(IVP_Core *core) { int i; for(i=sim_unit_cores.len()-1;i>=0;i--) { if(sim_unit_cores.element_at(i) == core) { return IVP_TRUE; } } return IVP_FALSE; } #ifdef DEBUG void IVP_Simulation_Unit::sim_unit_debug_out() { printf("sim_unit_cores:\n"); int i; for(i=sim_unit_cores.len()-1;i>=0;i--) { IVP_Core *my_core=sim_unit_cores.element_at(i); printf("%lx: ",(long)my_core); IVP_Controller *my_cnt; int j; for(j=my_core->controllers_of_core.len()-1;j>=0;j--) { my_cnt=my_core->controllers_of_core.element_at(j); printf("%lx ",(long)my_cnt); } printf("\n"); } for(i=controller_cores.len()-1;i>=0;i--) { printf(" controlr %lx: ",(long)controller_cores.element_at(i)->l_controller); int j; IVP_Sim_Unit_Controller_Core_List *c_info=controller_cores.element_at(i); for(j=c_info->cores_controlled_by.len()-1;j>=0;j--) { printf("%lx ",(long)c_info->cores_controlled_by.element_at(j)); } printf("\n"); } } #endif #ifdef DEBUG void IVP_Simulation_Unit::sim_unit_debug_consistency() { //every core has to occur only once int i,j; for(i=sim_unit_cores.len()-1;i>=0;i--) { IVP_Core *search_core=sim_unit_cores.element_at(i); for(j=i-1;j>=0;j--) { IVP_ASSERT( sim_unit_cores.element_at(j) != search_core ); } IVP_ASSERT( !search_core->physical_unmoveable ); IVP_ASSERT( search_core->sim_unit_of_core==this ); } //every controller has to occur only once for(i=controller_cores.len()-1;i>=0;i--) { IVP_Controller *search_controller=controller_cores.element_at(i)->l_controller; for(j=i-1;j>=0;j--) { IVP_ASSERT( controller_cores.element_at(j)->l_controller != search_controller ); } } //sim_unit_controllers and controller_cores are associated //IVP_ASSERT( sim_unit_controllers.len() == controller_cores.len() ); for(i=controller_cores.len()-1;i>=0;i--) { IVP_Sim_Unit_Controller_Core_List *c_info=controller_cores.element_at(i); //IVP_ASSERT( c_info->l_controller == sim_unit_controllers.element_at(i) ); //every core in controller list must exist for(j=c_info->cores_controlled_by.len()-1;j>=0;j--) { IVP_Core *test_core=c_info->cores_controlled_by.element_at(j); IVP_ASSERT( sim_unit_core_exists(test_core)==IVP_TRUE ); } } //all cores must have all their controllers in controller list for (int i1 = sim_unit_cores.len()-1; i1>=0; i1--){ IVP_Core *my_core = sim_unit_cores.element_at(i1); for (int i2 = my_core->controllers_of_core.len()-1;i2>=0; i2--){ IVP_Controller *my_controller = my_core->controllers_of_core.element_at(i2); IVP_ASSERT( controller_is_known_to_sim_unit( my_controller )==IVP_TRUE ); //for every core its via controllers associated cores must exist IVP_U_Vector<IVP_Core> *core_list = my_controller->get_associated_controlled_cores(); for(int i4=core_list->len()-1;i4>=0;i4--) { IVP_Core *test_core=core_list->element_at(i4); IVP_ASSERT( !test_core->physical_unmoveable ); IVP_ASSERT( sim_unit_core_exists( test_core ) == IVP_TRUE ); } //every core/controller pair must be represented in c_info int pos=get_pos_of_controller(my_controller); IVP_Sim_Unit_Controller_Core_List *c_info=controller_cores.element_at(pos); int found=0; for(int i5=c_info->cores_controlled_by.len()-1;i5>=0;i5--) { IVP_Core *tt_core=c_info->cores_controlled_by.element_at(i5); if(tt_core == my_core) { found=1; } //this controller must be found in my cores controller list int find_contr=0; for(int k=0;k<tt_core->controllers_of_core.len();k++) { if( tt_core->controllers_of_core.element_at(k) == my_controller ) { find_contr=1; } } IVP_ASSERT(find_contr==1); } IVP_ASSERT(found==1); } } } #endif void IVP_Controller_Manager::ensure_core_in_simulation(IVP_Core *core) { core->ensure_core_in_simulation_delayed(); } //only for Controllers that have all cores computed at the same time void IVP_Controller_Manager::remove_controller_from_environment( IVP_Controller_Dependent *cntrl, IVP_BOOL silently ) { IVP_U_Vector<IVP_Core> *controlled_cores=cntrl->get_associated_controlled_cores(); IVP_Simulation_Unit *reference_unit=NULL; int i; for(i=controlled_cores->len()-1;i>=0;i--) { IVP_Core *my_core=controlled_cores->element_at(i); my_core->rem_core_controller(cntrl); reference_unit=my_core->sim_unit_of_core; } if(reference_unit) { reference_unit->union_find_needed_for_sim_unit=IVP_TRUE; if(silently==IVP_FALSE) { reference_unit->sim_unit_ensure_in_simulation(); } } } void IVP_Controller_Manager::ensure_controller_in_simulation(IVP_Controller_Dependent *cntrl) { IVP_U_Vector<IVP_Core> *controlled_cores=cntrl->get_associated_controlled_cores(); IVP_ASSERT( controlled_cores->len() > 0); if(controlled_cores->len() > 0) { // #+# is this to avoid an assert ??? controlled_cores->element_at(0)->sim_unit_of_core->sim_unit_ensure_in_simulation(); } } void IVP_Controller_Manager::add_controller_to_core(IVP_Controller_Independent *cntrl, IVP_Core *core){ core->add_core_controller(cntrl); } void IVP_Controller_Manager::remove_controller_from_core(IVP_Controller_Independent *cntrl, IVP_Core *core){ core->rem_core_controller(cntrl); } //only for Controllers that have all cores computed at the same time void IVP_Controller_Manager::announce_controller_to_environment( IVP_Controller_Dependent *cntrl ) { IVP_U_Vector<IVP_Core> *controlled_cores=cntrl->get_associated_controlled_cores(); IVP_Simulation_Unit *reference_unit=NULL; IVP_BOOL did_fusion=IVP_FALSE; IVP_Movement_Type mtype=IVP_MT_NOT_SIM; int i; for(i=controlled_cores->len()-1;i>=0;i--) { IVP_Core *test_core=controlled_cores->element_at(i); if(!test_core->physical_unmoveable) { mtype=(IVP_Movement_Type)((int)mtype & (int)test_core->movement_state); IVP_Simulation_Unit *test_sim_unit=test_core->sim_unit_of_core; if(reference_unit!=NULL) { if(test_sim_unit!=reference_unit) { reference_unit->throw_cores_into_my_sim_unit(test_sim_unit); // P_DELETE(test_sim_unit); did_fusion=IVP_TRUE; } } else { reference_unit=test_sim_unit; } test_core->add_core_controller(cntrl); } } if(did_fusion==IVP_TRUE) { reference_unit->clean_sim_unit(); reference_unit->sim_unit_calc_redundants(); } if(mtype<IVP_MT_NOT_SIM) { reference_unit->sim_unit_revive_for_simulation(l_environment); //ensure in simulation is not enough (cannot handle mixture of simulated and not simulated objects) } } void IVP_Core::rem_core_controller( IVP_Controller *rem_cntrl ) { controllers_of_core.remove(rem_cntrl); this->sim_unit_of_core->remove_controller_of_core(this,rem_cntrl); } void IVP_Core::add_core_controller( IVP_Controller *add_cntrl ) { controllers_of_core.add(add_cntrl); sim_unit_of_core->add_controller_of_core(this,add_cntrl); } // e.g. a core enters a water pool void IVP_Simulation_Unit::add_controller_of_core( IVP_Core *my_core, IVP_Controller *cntrl ) { if( controller_is_known_to_sim_unit( cntrl ) ) { ; } else { add_controller_unit_sim( cntrl ); } add_controlled_core_for_controller( cntrl, my_core ); this->sim_unit_sort_controllers(); } // e.g. a core leaves a water pool void IVP_Simulation_Unit::remove_controller_of_core( IVP_Core *my_core, IVP_Controller *cntrl ) { int pos=get_pos_of_controller(cntrl); IVP_ASSERT(pos>=0); IVP_Sim_Unit_Controller_Core_List *c_info=controller_cores.element_at(pos); c_info->cores_controlled_by.remove(my_core); if( c_info->cores_controlled_by.len() <= 0 ) { P_DELETE(c_info); controller_cores.remove_at( pos ); //this controller no longer controlls any cores } //sim_unit_controllers.delete_at( pos ); } void IVP_Simulation_Unit::sim_unit_sort_controllers() { int contr_num=controller_cores.len(); int first=0; while(1) { int second=first+1; if( second >= contr_num ) { break; } IVP_CONTROLLER_PRIORITY second_prio = controller_cores.element_at(second)->l_controller->get_controller_priority(); if( controller_cores.element_at(first)->l_controller->get_controller_priority() > second_prio ) { sim_unit_exchange_controllers(first,second); int test_pos=first; while( (test_pos>0) && ( controller_cores.element_at(test_pos-1)->l_controller->get_controller_priority() > second_prio ) ) {//controller_cores.element_at(test_pos)->l_controller->get_controller_priority() ) ) { sim_unit_exchange_controllers(test_pos-1,test_pos); test_pos--; } } first=second; } IVP_IF(1) { for( int i=0; i<contr_num-1; i++ ) { IVP_ASSERT( !( controller_cores.element_at(i)->l_controller->get_controller_priority() > controller_cores.element_at(i+1)->l_controller->get_controller_priority() ) ); } } } void IVP_Simulation_Unit::sim_unit_exchange_controllers(int first,int second) { IVP_ASSERT(first>=0); IVP_ASSERT(second>=0); IVP_ASSERT(first<controller_cores.len()); IVP_ASSERT(second<controller_cores.len()); //sim_unit_controllers.exchange_vector_elems(first,second); controller_cores.swap_elems(first,second); } IVP_Sim_Units_Manager::IVP_Sim_Units_Manager(IVP_Environment *env) { l_environment=env; sim_units_slots[0]=NULL; still_slot=NULL; nb = IVP_Time(9.73f); bt = IVP_Time(0.3f); } void IVP_Sim_Units_Manager::add_unit_to_slot(IVP_Simulation_Unit *sim_u,IVP_Simulation_Unit **slot) { IVP_Simulation_Unit *s_u=*slot; sim_u->next_sim_unit=s_u; if(s_u) { s_u->prev_sim_unit=sim_u; } sim_u->prev_sim_unit=NULL; *slot=sim_u; } void IVP_Sim_Units_Manager::add_sim_unit_to_manager(IVP_Simulation_Unit *sim_u) { IVP_Simulation_Unit **slot; if( sim_u->get_unit_movement_type() < IVP_MT_NOT_SIM ) { slot=&sim_units_slots[0]; } else { slot=&still_slot; } add_unit_to_slot(sim_u,slot); } void IVP_Sim_Units_Manager::rem_unit_from_slot(IVP_Simulation_Unit *sim_u,IVP_Simulation_Unit **slot) { IVP_Simulation_Unit *prev_u,*next_u; prev_u=sim_u->prev_sim_unit; next_u=sim_u->next_sim_unit; if(prev_u) { prev_u->next_sim_unit=next_u; } else { *slot=next_u; } if(next_u) { next_u->prev_sim_unit=prev_u; } } void IVP_Sim_Units_Manager::rem_sim_unit_from_manager(IVP_Simulation_Unit *sim_u) { IVP_Simulation_Unit **slot; if( sim_u->get_unit_movement_type() < IVP_MT_NOT_SIM ) { slot=&sim_units_slots[0]; } else { slot=&still_slot; } rem_unit_from_slot(sim_u,slot); } //during reviving of unit all cores are processed //each core is revived and friction systems for that core are grown //that may lead to more Simulation_units are fusioned with mine //after a fusion is done, I have to restart the reviving of cores (Datastructure reassembly) void IVP_Simulation_Unit::sim_unit_revive_for_simulation(IVP_Environment *env) { revive_all_cores: { for (int i = sim_unit_cores.len()-1; i>=0;i--){ IVP_Core *my_core = sim_unit_cores.element_at(i); IVP_ASSERT( !my_core->physical_unmoveable ); if(my_core->movement_state>=IVP_MT_NOT_SIM) { IVP_BOOL fusion_was_done; fusion_was_done=my_core->revive_simulation_core(); if(fusion_was_done==IVP_TRUE) { goto revive_all_cores; } } } } if(sim_unit_movement_type==IVP_MT_NOT_SIM) { env->get_sim_units_manager()->rem_sim_unit_from_manager(this); sim_unit_movement_type=IVP_MT_MOVING; env->get_sim_units_manager()->add_sim_unit_to_manager(this); } } void IVP_Simulation_Unit::sim_unit_ensure_cores_movement() { IVP_Core *my_core; int i; for(i=sim_unit_cores.len()-1;i>=0;i--) { my_core=sim_unit_cores.element_at(i); my_core->reset_freeze_check_values(); } } void IVP_Standard_Gravity_Controller::set_standard_gravity(IVP_U_Point *gravity) { grav_vec.set(gravity); } void IVP_Standard_Gravity_Controller::do_simulation_controller(IVP_Event_Sim *es,IVP_U_Vector<IVP_Core> *core_list) { int i; for(i=core_list->len()-1;i>=0;i--) { IVP_Core *my_core=core_list->element_at(i); if(!my_core->pinned) //@@CB { my_core->global_damp_core(es->delta_time); my_core->commit_all_async_pushes(); my_core->speed.add_multiple( &this->grav_vec,es->delta_time ); } } } void IVP_Simulation_Unit::sim_unit_clear_movement_check_values() { for (int c = sim_unit_cores.len()-1; c>=0; c--) { IVP_Core *core = sim_unit_cores.element_at(c); core->reset_freeze_check_values(); } } void IVP_Simulation_Unit::do_sim_unit_union_find() { this->clean_sim_unit(); this->sim_unit_calc_redundants(); this->perform_test_and_split(); this->union_find_needed_for_sim_unit=IVP_FALSE; } IVP_BOOL IVP_Simulation_Unit::sim_unit_calc_movement_state(IVP_Environment *env) { #if !defined(IVP_DISABLE_FREEZING) IVP_Movement_Type whole_sys=IVP_MT_CALM; IVP_Time current_time=env->get_current_time(); for (int c = sim_unit_cores.len()-1; c>=0; c--) { IVP_Core *core = sim_unit_cores.element_at(c); core->movement_state=core->calc_movement_state(current_time); whole_sys=(IVP_Movement_Type)((int)whole_sys & (int)core->movement_state); } if( whole_sys == IVP_MT_CALM ) { for (int n = sim_unit_cores.len()-1; n>=0; n--){ IVP_Core *my_core = sim_unit_cores.element_at(n); my_core->freeze_simulation_core(); //make callbacks for controllers?? } env->get_sim_units_manager()->rem_sim_unit_from_manager(this); this->sim_unit_movement_type=IVP_MT_NOT_SIM; env->get_sim_units_manager()->add_sim_unit_to_manager(this); return IVP_TRUE; } #endif return IVP_FALSE; } void IVP_Simulation_Unit::init_moving_core_for_psi(IVP_Core *core, const IVP_Time &c_time) { //IVP_PREFETCH(this->objects.elems); // now using special vector IVP_IF(1) { IVP_Friction_Info_For_Core *info=core->moveable_core_has_friction_info(); IVP_Friction_System *fs=NULL; if(info) { fs=info->l_friction_system; } } IVP_ASSERT(core->physical_unmoveable==IVP_FALSE); // IVP_ASSERT ( c_time.get_time() == 0 || IVP_Inline_Math::fabsd( core->time_of_last_psi - c_time + 1.0f / core->i_delta_time ) < 10E-4f); IVP_DOUBLE d_time = c_time - core->time_of_last_psi; core->q_world_f_core_next_psi.set_matrix(&core->m_world_f_core_last_psi); IVP_PREFETCH(core->objects.element_at(0),0); core->m_world_f_core_last_psi.vv.add_multiple( &core->pos_world_f_core_last_psi, &core->delta_world_f_core_psis, d_time); } void IVP_Simulation_Unit::simulate_single_sim_unit_psi(IVP_Event_Sim *es, IVP_U_Vector<IVP_Core> *touched_cores) { #ifdef DEBUG IVP_IF(1) { this->sim_unit_debug_consistency(); } #endif es->sim_unit = this; es->environment->sim_unit_mem->start_memory_transaction(); int controller_num=controller_cores.len(); IVP_Time current_time = es->environment->get_current_time(); int fast_moving_flag = 0; union { int fast_moving_core; float fast_moving_core_p; }; //warning: 4 Byte of memory are used to store an integer and a float value to get access to sign bit for (int d = sim_unit_cores.len()-1; d>=1; d--){ IVP_Core *next_core = sim_unit_cores.element_at(d-1); this->prefetch0_init_moving_core_for_psi(next_core); IVP_Core *my_core = sim_unit_cores.element_at(d); this->init_moving_core_for_psi(my_core, current_time); IVP_IF(1) { for(int k=my_core->objects.len()-1;k>=0;k--) { IVP_ASSERT(my_core->objects.element_at(k)->get_movement_state()<IVP_MT_NOT_SIM); } } my_core->commit_all_async_pushes(); // @@@OS this happens very seldomly !!!!, remove !!!!this necessary as it may happen that core was temporarily_unmovable // TL: it is also used for delayed pushes and async_pushes fast_moving_core_p = IVP_OBJECT_MOVING_FAST * IVP_OBJECT_MOVING_FAST - my_core->speed.quad_length(); my_core->temporarily_unmovable = IVP_FALSE; my_core->impacts_since_last_PSI = 0; fast_moving_flag |= fast_moving_core; } { IVP_Core *my_core = sim_unit_cores.element_at(0); this->init_moving_core_for_psi(my_core, current_time); IVP_IF(1) { for(int k=my_core->objects.len()-1;k>=0;k--) { IVP_ASSERT(my_core->objects.element_at(k)->get_movement_state()<IVP_MT_NOT_SIM); } } my_core->commit_all_async_pushes(); // @@@OS this happens very seldomly !!!!, remove !!!!this necessary as it may happen that core was temporarily_unmovable fast_moving_core_p = IVP_OBJECT_MOVING_FAST*IVP_OBJECT_MOVING_FAST - my_core->speed.quad_length(); my_core->temporarily_unmovable=IVP_FALSE; my_core->impacts_since_last_PSI=0; fast_moving_flag |= fast_moving_core; } IVP_BOOL check_movement_state; if( fast_moving_flag < 0 ) { this->sim_unit_has_fast_objects = IVP_TRUE; check_movement_state = es->environment->must_perform_movement_check(); //do not always make movement check // check_movement_state = IVP_FALSE; // this might be wrong if flag is set to IVP_MT_SLOW } else { this->sim_unit_just_slowed_down = this->sim_unit_has_fast_objects; if(sim_unit_just_slowed_down) { this->sim_unit_clear_movement_check_values(); } sim_unit_has_fast_objects = IVP_FALSE; check_movement_state = es->environment->must_perform_movement_check(); //do not always make movement check } //controllers are sorted for(int j=controller_num-1;j>=0;j--) { IVP_CONTROLLER_PRIORITY debug_contr_prio; IVP_Controller *my_controller = controller_cores.element_at(j)->l_controller; IVP_IF(1) { debug_contr_prio=my_controller->get_controller_priority(); } my_controller->do_simulation_controller(es,&controller_cores.element_at(j)->cores_controlled_by); //speed dependent, real speed IVP_IF(1) { for (int c = sim_unit_cores.len()-1; c>=0; c--) { IVP_Core *tcore=sim_unit_cores.element_at(c); tcore->core_plausible_check(); } } } for (int c = sim_unit_cores.len()-1; c>=0; c--) { IVP_Core *core = sim_unit_cores.element_at(c); core->calc_next_PSI_matrix(touched_cores, es); IVP_IF(0) { core->debug_vec_movement_state(); } } if(check_movement_state==IVP_TRUE) { this->sim_unit_calc_movement_state(es->environment); } // #+# find a better solution for invalid mindists (hull is better) for (int k = sim_unit_cores.len()-1; k>=0; k--){ IVP_Core *my_core = sim_unit_cores.element_at(k); for(int c = my_core->objects.len()-1;c>=0;c--){ IVP_Real_Object *obj=my_core->objects.element_at(c); obj->recalc_invalid_mindists_of_object(); // maybe a more lazy approach would be more appropiate } } if(union_find_needed_for_sim_unit) { do_sim_unit_union_find(); } es->environment->sim_unit_mem->end_memory_transaction(); } void IVP_Simulation_Unit::reset_time( IVP_Time offset){ for(int j = controller_cores.len()-1;j>=0;j--) { IVP_Controller *my_controller = controller_cores.element_at(j)->l_controller; my_controller->reset_time(offset); //speed dependent, real speed } for (int c = sim_unit_cores.len()-1; c>=0; c--) { IVP_Core *core = sim_unit_cores.element_at(c); core->reset_time(offset); } } #define prefetch0_simulate_single_sim_unit_psi(this) IVP_PREFETCH_BLOCK(this, sizeof(*this)); #define prefetch1_simulate_single_sim_unit_psi(this ) IVP_IF_PREFETCH_ENABLED(IVP_TRUE){ \ IVP_PREFETCH(this->controller_cores.elems,0); \ IVP_PREFETCH(this->sim_unit_cores.elems,0); } #define prefetch2_simulate_single_sim_unit_psi(this) IVP_IF_PREFETCH_ENABLED(IVP_TRUE){ \ IVP_PREFETCH(this->controller_cores.element_at(this->controller_cores.len()-1),0); \ IVP_PREFETCH(this->controller_cores.element_at(0),0); \ IVP_PREFETCH(this->sim_unit_cores.element_at( this->sim_unit_cores.len()-1),0); \ this->prefetch0_init_moving_core_for_psi(this->sim_unit_cores.element_at(this->sim_unit_cores.len()-1)); \ } void IVP_Sim_Units_Manager::simulate_sim_units_psi(IVP_Environment *env, IVP_U_Vector<IVP_Core> *touched_cores) { IVP_Simulation_Unit *s_u; IVP_Simulation_Unit *n0_su; IVP_Simulation_Unit *n1_su; IVP_Simulation_Unit *n2_su; IVP_Sim_Units_Manager *sman = this; IVP_Event_Sim es(env); s_u = sman->sim_units_slots[0]; if (!s_u) goto sim_units_0; n0_su = s_u->next_sim_unit; if (!n0_su) goto sim_units_1; n1_su = n0_su->next_sim_unit; if (!n1_su) goto sim_units_2; n2_su = n1_su->next_sim_unit; while(n2_su) { prefetch0_simulate_single_sim_unit_psi(n2_su); prefetch1_simulate_single_sim_unit_psi(n1_su); prefetch2_simulate_single_sim_unit_psi(n0_su); s_u ->simulate_single_sim_unit_psi(&es,touched_cores); s_u = n0_su; n0_su = n1_su; n1_su = n2_su; n2_su = n2_su->next_sim_unit; } prefetch1_simulate_single_sim_unit_psi(s_u); prefetch2_simulate_single_sim_unit_psi(n0_su); n1_su ->simulate_single_sim_unit_psi(&es, touched_cores); sim_units_2: prefetch2_simulate_single_sim_unit_psi(s_u); n0_su->simulate_single_sim_unit_psi(&es, touched_cores); sim_units_1: s_u ->simulate_single_sim_unit_psi(&es, touched_cores); sim_units_0: ; #if 0 && defined(WIN32) unsigned long time = p_get_time(); //BLOCKING if( (time > 957460357 /*4may*/ + 60*60*24* (31+26) )) { IVP_Time now_time=env->get_current_time(); // IVP_BLOCKING if(this->nb-now_time < 0.0) { this->nb=now_time+9.73; IVP_Time_Event_N *n_event=new IVP_Time_Event_N(env->get_current_time()); env->get_time_manager()->insert_event(n_event,env->get_current_time()); P_DELETE(env->get_time_manager()->event_manager); env->get_time_manager()->event_manager=new IVP_Event_Manager_D(); env->get_time_manager()->event_manager->mode=1; for(int i=0;i<15;i++) { IVP_Time_Event_D *d_event=new IVP_Time_Event_D(env->get_current_time()); env->get_time_manager()->insert_event(d_event,env->get_current_time()); } } } #endif } void IVP_Sim_Units_Manager::reset_time( IVP_Time offset){ for ( IVP_Simulation_Unit *s = this->sim_units_slots[0]; s; s = s->next_sim_unit){ s->reset_time(offset); } }
35.016216
217
0.699259
[ "vector" ]
cb7633df3a412568a2600743f68d0dd98199c61d
8,015
cpp
C++
src/main.cpp
partypyro/cuberite
720dd1f1fafaf90bdf38455df6081947dfb2c2f4
[ "Apache-2.0" ]
null
null
null
src/main.cpp
partypyro/cuberite
720dd1f1fafaf90bdf38455df6081947dfb2c2f4
[ "Apache-2.0" ]
null
null
null
src/main.cpp
partypyro/cuberite
720dd1f1fafaf90bdf38455df6081947dfb2c2f4
[ "Apache-2.0" ]
null
null
null
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "main.h" #include "BuildInfo.h" #include "Logger.h" #include "MemorySettingsRepository.h" #include "OSSupport/NetworkSingleton.h" #include "OSSupport/MiniDumpWriter.h" #include "OSSupport/StartAsService.h" #include "Root.h" #include "tclap/CmdLine.h" #include <csignal> #include <cstdlib> bool g_ShouldLogCommIn; bool g_ShouldLogCommOut; bool g_RunAsService; /** Global that registers itself as a last chance exception handler to write a minidump on crash. */ static MiniDumpWriter g_MiniDumpWriter; // Because SIG_DFL or SIG_IGN could be NULL instead of nullptr, we need to disable the Clang warning here #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunknown-warning-option" #pragma clang diagnostic ignored "-Wunknown-pragmas" #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif // __clang__ static void NonCtrlHandler(int a_Signal) { LOGD("Terminate event raised from std::signal"); switch (a_Signal) { case SIGSEGV: { PrintStackTrace(); LOGERROR( "Failure report: \n\n" " :( | Cuberite has encountered an error and needs to close\n" " | SIGSEGV: Segmentation fault\n" " |\n" #ifdef BUILD_ID " | Cuberite " BUILD_SERIES_NAME " (id: " BUILD_ID ")\n" " | from commit " BUILD_COMMIT_ID "\n" #endif ); std::signal(SIGSEGV, SIG_DFL); return; } case SIGABRT: #ifdef SIGABRT_COMPAT case SIGABRT_COMPAT: #endif { PrintStackTrace(); LOGERROR( "Failure report: \n\n" " :( | Cuberite has encountered an error and needs to close\n" " | SIGABRT: Server self-terminated due to an internal fault\n" " |\n" #ifdef BUILD_ID " | Cuberite " BUILD_SERIES_NAME " (id: " BUILD_ID ")\n" " | from commit " BUILD_COMMIT_ID "\n" #endif ); std::signal(SIGSEGV, SIG_DFL); return; } case SIGINT: case SIGTERM: { // Server is shutting down, wait for it... cRoot::Get()->Stop(); return; } #ifdef SIGPIPE case SIGPIPE: { // Ignore (PR #2487) return; } #endif } } #ifdef __clang__ #pragma clang diagnostic pop #endif // __clang__ #ifdef _WIN32 // Handle CTRL events in windows, including console window close static BOOL CtrlHandler(DWORD fdwCtrlType) { cRoot::Get()->Stop(); LOGD("Terminate event raised from the Windows CtrlHandler"); // Delay as much as possible to try to get the server to shut down cleanly - 10 seconds given by Windows std::this_thread::sleep_for(std::chrono::seconds(10)); // Returning from main() automatically aborts this handler thread return TRUE; } #endif //////////////////////////////////////////////////////////////////////////////// // ParseArguments - Read the startup arguments and store into a settings object static void ParseArguments(int argc, char ** argv, cMemorySettingsRepository & repo) { // Parse the comand line args: TCLAP::CmdLine cmd("Cuberite"); TCLAP::ValueArg<int> slotsArg ("s", "max-players", "Maximum number of slots for the server to use, overrides setting in setting.ini", false, -1, "number", cmd); TCLAP::ValueArg<AString> confArg ("c", "config-file", "Config file to use", false, "settings.ini", "string", cmd); TCLAP::MultiArg<int> portsArg ("p", "port", "The port number the server should listen to", false, "port", cmd); TCLAP::SwitchArg commLogArg ("", "log-comm", "Log server client communications to file", cmd); TCLAP::SwitchArg commLogInArg ("", "log-comm-in", "Log inbound server client communications to file", cmd); TCLAP::SwitchArg commLogOutArg ("", "log-comm-out", "Log outbound server client communications to file", cmd); TCLAP::SwitchArg crashDumpFull ("", "crash-dump-full", "Crashdumps created by the server will contain full server memory", cmd); TCLAP::SwitchArg crashDumpGlobals("", "crash-dump-globals", "Crashdumps created by the server will contain the global variables' values", cmd); TCLAP::SwitchArg noBufArg ("", "no-output-buffering", "Disable output buffering", cmd); TCLAP::SwitchArg noFileLogArg ("", "no-log-file", "Disable logging to file", cmd); TCLAP::SwitchArg runAsServiceArg ("d", "service", "Run as a service on Windows, or daemon on UNIX like systems", cmd); cmd.parse(argc, argv); // Copy the parsed args' values into a settings repository: if (confArg.isSet()) { AString conf_file = confArg.getValue(); repo.AddValue("Server", "ConfigFile", conf_file); } if (slotsArg.isSet()) { int slots = slotsArg.getValue(); repo.AddValue("Server", "MaxPlayers", static_cast<Int64>(slots)); } if (portsArg.isSet()) { for (auto port: portsArg.getValue()) { repo.AddValue("Server", "Ports", std::to_string(port)); } } if (noFileLogArg.getValue()) { repo.AddValue("Server", "DisableLogFile", true); } if (commLogArg.getValue()) { g_ShouldLogCommIn = true; g_ShouldLogCommOut = true; } else { g_ShouldLogCommIn = commLogInArg.getValue(); g_ShouldLogCommOut = commLogOutArg.getValue(); } if (noBufArg.getValue()) { setvbuf(stdout, nullptr, _IONBF, 0); } repo.SetReadOnly(); if (runAsServiceArg.getValue()) { g_RunAsService = true; } // Apply the CrashDump flags for platforms that support them: if (crashDumpGlobals.getValue()) { g_MiniDumpWriter.AddDumpFlags(MiniDumpFlags::WithDataSegments); } if (crashDumpFull.getValue()) { g_MiniDumpWriter.AddDumpFlags(MiniDumpFlags::WithFullMemory); } } //////////////////////////////////////////////////////////////////////////////// // UniversalMain - Main startup logic for both standard running and as a service static int UniversalMain(int argc, char * argv[], bool RunningAsService) { // Initialize logging subsystem: cLogger::InitiateMultithreading(); struct NetworkRAII { NetworkRAII() { // Initialize LibEvent: cNetworkSingleton::Get().Initialise(); } ~NetworkRAII() { // Shutdown all of LibEvent: cNetworkSingleton::Get().Terminate(); } }; try { // Make sure g_RunAsService is set correctly before checking it's value cMemorySettingsRepository Settings; ParseArguments(argc, argv, Settings); // Attempt to run as a service if (!RunningAsService && g_RunAsService) { // This will either fork or call UniversalMain again: if (cStartAsService::MakeIntoService<&UniversalMain>()) { return EXIT_SUCCESS; } } while (true) { NetworkRAII LibEvent; cRoot Root; if (!Root.Run(Settings)) { break; } } return EXIT_SUCCESS; } catch (const fmt::format_error & Oops) { std::cerr << "Formatting exception: " << Oops.what() << '\n'; } catch (const TCLAP::ArgException & Oops) { std::cerr << fmt::sprintf("Error reading command line {} for argument {}\n", Oops.error(), Oops.argId()); } catch (const std::exception & Oops) { std::cerr << "Standard exception: " << Oops.what() << '\n'; } catch (...) { std::cerr << "Unknown exception!\n"; } return EXIT_FAILURE; } int main(int argc, char ** argv) { #if !defined(NDEBUG) && defined(_MSC_VER) _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); // _X: The simple built-in CRT leak finder - simply break when allocating the Nth block ({N} is listed in the leak output) // Only useful when the leak is in the same sequence all the time // _CrtSetBreakAlloc(85950); #endif // _DEBUG && _MSC_VER std::signal(SIGSEGV, NonCtrlHandler); std::signal(SIGTERM, NonCtrlHandler); std::signal(SIGINT, NonCtrlHandler); std::signal(SIGABRT, NonCtrlHandler); #ifdef SIGABRT_COMPAT std::signal(SIGABRT_COMPAT, NonCtrlHandler); #endif #ifdef SIGPIPE std::signal(SIGPIPE, SIG_IGN); #endif #ifdef _WIN32 VERIFY(SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(CtrlHandler), TRUE) == TRUE); #endif return UniversalMain(argc, argv, false); }
25.689103
172
0.67224
[ "object" ]
cb7a09fd919fe9c375c2cb9a16c64f903d4ab7c3
9,912
cpp
C++
Utils.cpp
viniman/labyrinth-search-algorithms
8e00380688d7f93195de61e8995aa48a1d43b474
[ "MIT" ]
1
2019-06-08T12:32:51.000Z
2019-06-08T12:32:51.000Z
Utils.cpp
viniman/labyrinth-search-algorithms
8e00380688d7f93195de61e8995aa48a1d43b474
[ "MIT" ]
null
null
null
Utils.cpp
viniman/labyrinth-search-algorithms
8e00380688d7f93195de61e8995aa48a1d43b474
[ "MIT" ]
1
2020-11-20T21:59:18.000Z
2020-11-20T21:59:18.000Z
// // Created by viniman on 07/06/19. // // https://stackoverflow.com/questions/15160889/how-can-i-make-an-unordered-set-of-pairs-of-integers-in-c // https://stackoverflow.com/questions/53796118/alternative-to-find-for-determining-whether-an-unordered-set-contains-a-key #include <iostream> #include <sstream> #include <fstream> #include <unordered_set> #include "Utils.h" #include "Maze.h" using namespace std; Maze Utils::instanceReader(const string &instancePathName) { } /** * Mazes generated with a depth-first search have a low branching factor and contain many long corridors, * because the algorithm explores as far as possible along each branch before backtracking. [Wikipedia] * https://en.wikipedia.org/wiki/Maze_generation_algorithm * @param m * @param n * @return */ Maze * Utils::mazeGeneratorRecursiveBacktracker(unsigned int m, unsigned int n, bool writeInstance) { //vector<char> operations = {'L', 'R', 'T', 'B'}; Maze* maze = new Maze(m, n, true); // Criacao com nenhuma porta, como se tivesse parede entre todos Maze* mazeGenerated = new Maze(m, n, false); stack<Node*> stackRooms; Node *currentCell = maze->getRoom(0); currentCell->setVisited(); mazeGenerated->setOrigin(currentCell->getId()); unsigned int countVisited = 1; while (countVisited < maze->getNumRooms()) { if (!currentCell->getRight()->isVisited() || !currentCell->getLeft()->isVisited() || !currentCell->getTop()->isVisited() || !currentCell->getBotton()->isVisited()) { vector<char> notVisited; if (currentCell->getRight() && !currentCell->getRight()->isVisited()) notVisited.push_back('R'); if (currentCell->getLeft() && !currentCell->getLeft()->isVisited()) notVisited.push_back('L'); if (currentCell->getTop() && !currentCell->getTop()->isVisited()) notVisited.push_back('T'); if (currentCell->getBotton() && !currentCell->getBotton()->isVisited()) notVisited.push_back('B'); unsigned long ranPos = rand() % notVisited.size(); Node *choosenCell = currentCell->roomDirectionReturn(notVisited[ranPos]); stackRooms.push(currentCell); mazeGenerated->addDoor(currentCell->getId(), choosenCell->getId()); //mazeGenerated->weightMatrix[currentCell->getId()/mazeGenerated->getMazeColumns()][choosenCell->getId()%mazeGenerated->getMazeColumns()] = 1; //mazeGenerated->weightMatrix[currentCell->getId()%mazeGenerated->getMazeColumns()][choosenCell->getId()/mazeGenerated->getMazeColumns()] = 1; currentCell = choosenCell; currentCell->setVisited(); ++countVisited; } else if (!stackRooms.empty()) { currentCell = stackRooms.top(); stackRooms.pop(); } } mazeGenerated->setDestination((m*n)-1); cout << "Labirinto gerado" << endl; ///Salva instancia em arquivo if(writeInstance) { auto hash = [](const std::pair<int, int> &p) { return p.first * 31 + p.second; }; std::unordered_set<std::pair<int, int>, decltype(hash)> set(8, hash); string saveFileName = "instance_" + to_string(m) + "_" + to_string(n) + "_" + to_string(mazeGenerated->getOrigin()->getId()) + "_" + to_string(mazeGenerated->getDestination()->getId()) + ".in"; stringstream ss; ss << m << " " << n << " " << mazeGenerated->getOrigin()->getId() << " " << to_string(mazeGenerated->getDestination()->getId()) << endl; for (const auto &it : mazeGenerated->getRooms()) { if (it->getBotton()) { int id1 = it->getId(), id2 = it->getBotton()->getId(); if (!set.count(make_pair(id1, id2)) && !set.count(make_pair(id2, id1))) { ss << id1 << " " << id2 << endl; set.insert(make_pair(id1, id2)); } } if (it->getTop()) { int id1 = it->getId(), id2 = it->getTop()->getId(); if (!set.count(make_pair(id1, id2)) && !set.count(make_pair(id2, id1))) { ss << id1 << " " << id2 << endl; set.insert(make_pair(id1, id2)); } } if (it->getRight()) { int id1 = it->getId(), id2 = it->getRight()->getId(); if (!set.count(make_pair(id1, id2)) && !set.count(make_pair(id2, id1))) { ss << id1 << " " << id2 << endl; set.insert(make_pair(id1, id2)); } } if (it->getLeft()) { int id1 = it->getId(), id2 = it->getLeft()->getId(); if (!set.count(make_pair(id1, id2)) && !set.count(make_pair(id2, id1))) { ss << id1 << " " << id2 << endl; set.insert(make_pair(id1, id2)); } } } writeToFile(ss.str(), saveFileName); } delete maze; return mazeGenerated; } ///long long int ??? bool Utils::emptyRoom(unsigned long long int& iterator, unsigned long long int& room, unsigned int& m, unsigned int& n, unsigned int& r){ if(r - room + 1 == n * m - iterator) return false; else return rand() % 100 < ((double) r/(m*n)) * 100 - 5; } /* namespace std { template <> struct hash<std::pair<int, int>> { inline size_t operator()(const std::pair<int, int> &v) const { std::hash<int> int_hasher; return int_hasher(v.first) ^ int_hasher(v.second); } }; } */ //auto hash = [](const std::pair<int, int>& p){ return p.first * 31 + p.second; }; //std::unordered_set<std::pair<int, int>, decltype(hash)> u_edge_(8, hash); void Utils::newGeneratorRandomized(unsigned int m, unsigned int n, unsigned int roomsWithDoor) { unsigned long long int * M = nullptr, room = 0, origin = 0, destination = 0; stringstream fileString; fstream file; srand(time(NULL)); M = new unsigned long long int[m * n]; for(unsigned long long int i = 0; i < m * n; ++i){ if(room > roomsWithDoor || emptyRoom(i, room, m, n, roomsWithDoor)) M[i] = 0; else { if(room == 0) origin = i; else if(room == roomsWithDoor-1) destination = i; M[i] = i; room++; } } fileString << "instance_" << m << "_" << n << "_" << origin << "_" << destination << ".in"; //roomsWithDoor file.open(fileString.str(), fstream::out); file << m << " " << n << " " << M[origin] << " " << M[destination] << "\n"; //roomsWithDoor << for(unsigned long long int i = 0; i < m * n; ++i) { cout << M[i] << " "; if((i+1)%n==0) cout << "\n"; } /////////////////////////////////////////////////////////////////////////////// long long int rooms = roomsWithDoor, currentPosition, i = 0, j = 0; //inputFile >> m >> n >> rooms >> origin >> destination; auto hash = [](const std::pair<int, int>& p){ return p.first * 31 + p.second; }; std::unordered_set<std::pair<int, int>, decltype(hash)> set(8, hash); //unordered_set <pair<int,int>> set; vector<long long int> matrix(m * n, 0); for(i = 0; i < m; i++) for(int j = 0; j < n; j++) matrix[i * n + j] = M[i * n + j]; for(i = 0; i < m; ++i){ for(j = 0; j < n; ++j){ currentPosition = i * n + j; if(!matrix[currentPosition]) continue; if(j != n - 1 && matrix[currentPosition + 1] && !set.count(make_pair(currentPosition + 1, currentPosition)) && !set.count(make_pair(currentPosition, currentPosition + 1))) { file << matrix[currentPosition] << " " << matrix[currentPosition + 1] << endl;//maze->addDoor(matrix[currentPosition], matrix[currentPosition + 1], 'R'); set.insert(make_pair(currentPosition, currentPosition + 1)); } if(j != 0 && matrix[currentPosition - 1] && !set.count(make_pair(currentPosition - 1, currentPosition)) && !set.count(make_pair(currentPosition, currentPosition - 1))) { file << matrix[currentPosition] << " " << matrix[currentPosition - 1] << endl;//maze->addDoor(matrix[currentPosition], matrix[currentPosition - 1], 'L'); set.insert(make_pair(currentPosition, currentPosition - 1)); } if(i != m - 1 && matrix[currentPosition + n] && !set.count(make_pair(currentPosition + n, currentPosition)) && !set.count(make_pair(currentPosition, currentPosition + n))) { file << matrix[currentPosition] << " " << matrix[currentPosition + n] << endl;//maze->addDoor(matrix[currentPosition], matrix[currentPosition + n], 'B'); set.insert(make_pair(currentPosition, currentPosition + n)); } if(i != 0 && matrix[currentPosition - n] && !set.count(make_pair(currentPosition - n, currentPosition)) && !set.count(make_pair(currentPosition, currentPosition - n))) { file << matrix[currentPosition] << " " << matrix[currentPosition - n] << endl;//maze->addDoor(matrix[currentPosition], matrix[currentPosition - n], 'T'); set.insert(make_pair(currentPosition, currentPosition - n)); } } } /////////////////////////////////////////////////////////////////////////////// file.close(); } void Utils::writeToFile(string strToWrite, string pathTosave) { fstream file; file.open(pathTosave, fstream::out); file << strToWrite; file.close(); }
37.545455
183
0.542877
[ "vector" ]
cb7d8c766287f55ca48813573e6059c7116cbc8e
725
cpp
C++
cpp/cpp/334. Increasing Triplet Subsequence.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
3
2021-08-07T07:01:34.000Z
2021-08-07T07:03:02.000Z
cpp/cpp/334. Increasing Triplet Subsequence.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
null
null
null
cpp/cpp/334. Increasing Triplet Subsequence.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/increasing-triplet-subsequence/ // Given an integer array nums, return true if there exists a triple of indices (i, // j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices // exists, return false. //////////////////////////////////////////////////////////////////////////////// // track smallest and secondSmallest class Solution { public: bool increasingTriplet(vector<int>& nums) { int smallest = INT_MAX, secondSmallest = INT_MAX; for (int& num : nums) { if (num <= smallest) smallest = num; else if (num <= secondSmallest) secondSmallest = num; else return true; } return false; } };
32.954545
83
0.554483
[ "vector" ]
cb7f51e3dc6937a27b9f39f8f926782f4ee48654
16,944
cpp
C++
opencl/test/unit_test/offline_compiler/ocloc_fatbinary_tests.cpp
sanjaymsh/compute-runtime
1bf270a804d47745dc6ee0bd2bf6232b2a4d835b
[ "MIT" ]
1
2020-09-03T17:10:38.000Z
2020-09-03T17:10:38.000Z
opencl/test/unit_test/offline_compiler/ocloc_fatbinary_tests.cpp
sanjaymsh/compute-runtime
1bf270a804d47745dc6ee0bd2bf6232b2a4d835b
[ "MIT" ]
null
null
null
opencl/test/unit_test/offline_compiler/ocloc_fatbinary_tests.cpp
sanjaymsh/compute-runtime
1bf270a804d47745dc6ee0bd2bf6232b2a4d835b
[ "MIT" ]
null
null
null
/* * Copyright (C) 2017-2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "opencl/test/unit_test/offline_compiler/ocloc_fatbinary_tests.h" #include "shared/source/helpers/hw_helper.h" #include <unordered_set> namespace NEO { TEST(OclocFatBinaryRequestedFatBinary, WhenDeviceArgMissingThenReturnsFalse) { const char *args[] = {"ocloc", "-aaa", "*", "-device", "*"}; EXPECT_FALSE(NEO::requestedFatBinary(0, nullptr)); EXPECT_FALSE(NEO::requestedFatBinary(1, args)); EXPECT_FALSE(NEO::requestedFatBinary(2, args)); EXPECT_FALSE(NEO::requestedFatBinary(3, args)); EXPECT_FALSE(NEO::requestedFatBinary(4, args)); } TEST(OclocFatBinaryRequestedFatBinary, WhenDeviceArgProvidedAndContainsFatbinaryArgFormatThenReturnsTrue) { const char *allPlatforms[] = {"ocloc", "-device", "*"}; const char *manyPlatforms[] = {"ocloc", "-device", "a,b"}; const char *manyGens[] = {"ocloc", "-device", "gen0,gen1"}; const char *gen[] = {"ocloc", "-device", "gen0"}; const char *rangePlatformFrom[] = {"ocloc", "-device", "skl-"}; const char *rangePlatformTo[] = {"ocloc", "-device", "-skl"}; const char *rangePlatformBounds[] = {"ocloc", "-device", "skl-icllp"}; const char *rangeGenFrom[] = {"ocloc", "-device", "gen0-"}; const char *rangeGenTo[] = {"ocloc", "-device", "-gen5"}; const char *rangeGenBounds[] = {"ocloc", "-device", "gen0-gen5"}; EXPECT_TRUE(NEO::requestedFatBinary(3, allPlatforms)); EXPECT_TRUE(NEO::requestedFatBinary(3, manyPlatforms)); EXPECT_TRUE(NEO::requestedFatBinary(3, manyGens)); EXPECT_TRUE(NEO::requestedFatBinary(3, gen)); EXPECT_TRUE(NEO::requestedFatBinary(3, rangePlatformFrom)); EXPECT_TRUE(NEO::requestedFatBinary(3, rangePlatformTo)); EXPECT_TRUE(NEO::requestedFatBinary(3, rangePlatformBounds)); EXPECT_TRUE(NEO::requestedFatBinary(3, rangeGenFrom)); EXPECT_TRUE(NEO::requestedFatBinary(3, rangeGenTo)); EXPECT_TRUE(NEO::requestedFatBinary(3, rangeGenBounds)); } TEST(OclocFatBinaryRequestedFatBinary, WhenDeviceArgProvidedButDoesnNotContainFatbinaryArgFormatThenReturnsFalse) { const char *skl[] = {"ocloc", "-device", "skl"}; EXPECT_FALSE(NEO::requestedFatBinary(3, skl)); } TEST(OclocFatBinaryGetAllSupportedTargetPlatforms, WhenRequestedThenReturnsAllPlatformsWithNonNullHardwarePrefixes) { auto platforms = NEO::getAllSupportedTargetPlatforms(); std::unordered_set<uint32_t> platformsSet(platforms.begin(), platforms.end()); for (unsigned int productId = 0; productId < IGFX_MAX_PRODUCT; ++productId) { if (nullptr != NEO::hardwarePrefix[productId]) { EXPECT_EQ(1U, platformsSet.count(static_cast<PRODUCT_FAMILY>(productId))) << productId; } else { EXPECT_EQ(0U, platformsSet.count(static_cast<PRODUCT_FAMILY>(productId))) << productId; } } } TEST(OclocFatBinaryToProductNames, GivenListOfProductIdsThenReturnsListOfHardwarePrefixes) { auto platforms = NEO::getAllSupportedTargetPlatforms(); auto names = NEO::toProductNames(platforms); EXPECT_EQ(names.size(), platforms.size()); } TEST(OclocFatBinaryAsProductId, GivenEnabledPlatformNameThenReturnsProperPlatformId) { auto platforms = NEO::getAllSupportedTargetPlatforms(); auto names = NEO::toProductNames(platforms); for (size_t i = 0; i < platforms.size(); ++i) { auto idByName = NEO::asProductId(names[i], platforms); EXPECT_EQ(idByName, platforms[i]) << names[i].data() << " : " << platforms[i] << " != " << idByName; } } TEST(OclocFatBinaryAsProductId, GivenDisabledPlatformNameThenReturnsUnknownPlatformId) { auto platforms = NEO::getAllSupportedTargetPlatforms(); auto names = NEO::toProductNames(platforms); platforms.clear(); for (size_t i = 0; i < platforms.size(); ++i) { auto idByName = NEO::asProductId(names[i], platforms); EXPECT_EQ(IGFX_UNKNOWN, platforms[i]) << names[i].data() << " : IGFX_UNKNOWN != " << idByName; } } TEST(OclocFatBinaryAsGfxCoreIdList, GivenEnabledGfxCoreNameThenReturnsNonEmptyList) { for (unsigned int coreId = 0; coreId < IGFX_MAX_CORE; ++coreId) { if (nullptr != NEO::familyName[coreId]) { EXPECT_FALSE(NEO::asGfxCoreIdList(ConstStringRef(NEO::familyName[coreId], strlen(NEO::familyName[coreId]))).empty()); std::string caseInsesitive = NEO::familyName[coreId]; caseInsesitive[0] = 'g'; EXPECT_FALSE(NEO::asGfxCoreIdList(caseInsesitive).empty()); } } } TEST(OclocFatBinaryAsGfxCoreIdList, GivenDisabledGfxCoreNameThenReturnsEmptyList) { EXPECT_TRUE(NEO::asGfxCoreIdList(ConstStringRef("genA")).empty()); EXPECT_TRUE(NEO::asGfxCoreIdList(ConstStringRef("gen0")).empty()); EXPECT_TRUE(NEO::asGfxCoreIdList(ConstStringRef("gen1")).empty()); EXPECT_TRUE(NEO::asGfxCoreIdList(ConstStringRef("gen2")).empty()); } TEST(OclocFatBinaryAppendPlatformsForGfxCore, GivenCoreIdThenAppendsEnabledProductIdsThatMatch) { auto allEnabledPlatforms = NEO::getAllSupportedTargetPlatforms(); auto platform0 = allEnabledPlatforms[0]; auto gfxCore0 = NEO::hardwareInfoTable[platform0]->platform.eRenderCoreFamily; std::vector<PRODUCT_FAMILY> appendedPlatforms; NEO::appendPlatformsForGfxCore(gfxCore0, allEnabledPlatforms, appendedPlatforms); std::unordered_set<uint32_t> appendedPlatformsSet(appendedPlatforms.begin(), appendedPlatforms.end()); EXPECT_EQ(1U, appendedPlatformsSet.count(platform0)); for (auto platformId : allEnabledPlatforms) { if (gfxCore0 == NEO::hardwareInfoTable[platformId]->platform.eRenderCoreFamily) { EXPECT_EQ(1U, appendedPlatformsSet.count(platformId)) << platformId; } else { EXPECT_EQ(0U, appendedPlatformsSet.count(platformId)) << platformId; } } NEO::appendPlatformsForGfxCore(gfxCore0, allEnabledPlatforms, appendedPlatforms); EXPECT_EQ(2 * appendedPlatformsSet.size(), appendedPlatforms.size()); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenAsterixThenReturnAllEnabledPlatforms) { auto allEnabledPlatformsIds = NEO::getAllSupportedTargetPlatforms(); auto expected = NEO::toProductNames(allEnabledPlatformsIds); auto got = NEO::getTargetPlatformsForFatbinary("*", oclocArgHelperWithoutInput.get()); EXPECT_EQ(expected, got); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenGenThenReturnAllEnabledPlatformsThatMatch) { auto allEnabledPlatforms = NEO::getAllSupportedTargetPlatforms(); auto platform0 = allEnabledPlatforms[0]; auto gfxCore0 = NEO::hardwareInfoTable[platform0]->platform.eRenderCoreFamily; std::string genName = NEO::familyName[gfxCore0]; genName[0] = 'g'; // ocloc uses lower case std::vector<PRODUCT_FAMILY> platformsForGen; NEO::appendPlatformsForGfxCore(gfxCore0, allEnabledPlatforms, platformsForGen); auto expected = NEO::toProductNames(platformsForGen); auto got = NEO::getTargetPlatformsForFatbinary(genName, oclocArgHelperWithoutInput.get()); EXPECT_EQ(expected, got); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenMutiplePlatformThenReturnThosePlatforms) { auto allEnabledPlatforms = NEO::getAllSupportedTargetPlatforms(); if (allEnabledPlatforms.size() < 2) { return; } auto platform0 = allEnabledPlatforms[0]; std::string platform0Name = NEO::hardwarePrefix[platform0]; auto platform1 = allEnabledPlatforms[1]; std::string platform1Name = NEO::hardwarePrefix[platform1]; std::vector<ConstStringRef> expected{platform0Name, platform1Name}; auto got = NEO::getTargetPlatformsForFatbinary(platform0Name + "," + platform1Name, oclocArgHelperWithoutInput.get()); EXPECT_EQ(expected, got); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenPlatformOpenRangeFromThenReturnAllEnabledPlatformsThatMatch) { auto allEnabledPlatforms = NEO::getAllSupportedTargetPlatforms(); if (allEnabledPlatforms.size() < 3) { return; } auto platform0 = allEnabledPlatforms[allEnabledPlatforms.size() / 2]; std::string platformName = NEO::hardwarePrefix[platform0]; std::vector<PRODUCT_FAMILY> expectedPlatforms; auto platformFrom = std::find(allEnabledPlatforms.begin(), allEnabledPlatforms.end(), platform0); expectedPlatforms.insert(expectedPlatforms.end(), platformFrom, allEnabledPlatforms.end()); auto expected = NEO::toProductNames(expectedPlatforms); auto got = NEO::getTargetPlatformsForFatbinary(platformName + "-", oclocArgHelperWithoutInput.get()); EXPECT_EQ(expected, got); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenPlatformOpenRangeToThenReturnAllEnabledPlatformsThatMatch) { auto allEnabledPlatforms = NEO::getAllSupportedTargetPlatforms(); if (allEnabledPlatforms.size() < 3) { return; } auto platform0 = allEnabledPlatforms[allEnabledPlatforms.size() / 2]; std::string platformName = NEO::hardwarePrefix[platform0]; std::vector<PRODUCT_FAMILY> expectedPlatforms; auto platformTo = std::find(allEnabledPlatforms.begin(), allEnabledPlatforms.end(), platform0); expectedPlatforms.insert(expectedPlatforms.end(), allEnabledPlatforms.begin(), platformTo + 1); auto expected = NEO::toProductNames(expectedPlatforms); auto got = NEO::getTargetPlatformsForFatbinary("-" + platformName, oclocArgHelperWithoutInput.get()); EXPECT_EQ(expected, got); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenPlatformClosedRangeThenReturnAllEnabledPlatformsThatMatch) { auto allEnabledPlatforms = NEO::getAllSupportedTargetPlatforms(); if (allEnabledPlatforms.size() < 4) { return; } auto platformFrom = allEnabledPlatforms[1]; auto platformTo = allEnabledPlatforms[allEnabledPlatforms.size() - 2]; std::string platformNameFrom = NEO::hardwarePrefix[platformFrom]; std::string platformNameTo = NEO::hardwarePrefix[platformTo]; std::vector<PRODUCT_FAMILY> expectedPlatforms; expectedPlatforms.insert(expectedPlatforms.end(), allEnabledPlatforms.begin() + 1, allEnabledPlatforms.begin() + allEnabledPlatforms.size() - 1); auto expected = NEO::toProductNames(expectedPlatforms); auto got = NEO::getTargetPlatformsForFatbinary(platformNameFrom + "-" + platformNameTo, oclocArgHelperWithoutInput.get()); EXPECT_EQ(expected, got); got = NEO::getTargetPlatformsForFatbinary(platformNameTo + "-" + platformNameFrom, oclocArgHelperWithoutInput.get()); // swap min with max implicitly EXPECT_EQ(expected, got); } std::vector<GFXCORE_FAMILY> getEnabledCores() { std::vector<GFXCORE_FAMILY> ret; for (unsigned int coreId = 0; coreId < IGFX_MAX_CORE; ++coreId) { if (nullptr != NEO::familyName[coreId]) { ret.push_back(static_cast<GFXCORE_FAMILY>(coreId)); } } return ret; } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenGenOpenRangeFromThenReturnAllEnabledPlatformsThatMatch) { auto allSupportedPlatforms = NEO::getAllSupportedTargetPlatforms(); auto allEnabledCores = getEnabledCores(); if (allEnabledCores.size() < 3) { return; } auto core0 = allEnabledCores[allEnabledCores.size() / 2]; std::string genName = NEO::familyName[core0]; genName[0] = 'g'; // ocloc uses lower case std::vector<PRODUCT_FAMILY> expectedPlatforms; unsigned int coreIt = core0; while (coreIt < static_cast<unsigned int>(IGFX_MAX_CORE)) { NEO::appendPlatformsForGfxCore(static_cast<GFXCORE_FAMILY>(coreIt), allSupportedPlatforms, expectedPlatforms); ++coreIt; } auto expected = NEO::toProductNames(expectedPlatforms); auto got = NEO::getTargetPlatformsForFatbinary(genName + "-", oclocArgHelperWithoutInput.get()); EXPECT_EQ(expected, got); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenGenOpenRangeToThenReturnAllEnabledPlatformsThatMatch) { auto allSupportedPlatforms = NEO::getAllSupportedTargetPlatforms(); auto allEnabledCores = getEnabledCores(); if (allEnabledCores.size() < 3) { return; } auto core0 = allEnabledCores[allEnabledCores.size() / 2]; std::string genName = NEO::familyName[core0]; genName[0] = 'g'; // ocloc uses lower case std::vector<PRODUCT_FAMILY> expectedPlatforms; unsigned int coreIt = IGFX_UNKNOWN_CORE; ++coreIt; while (coreIt <= static_cast<unsigned int>(core0)) { NEO::appendPlatformsForGfxCore(static_cast<GFXCORE_FAMILY>(coreIt), allSupportedPlatforms, expectedPlatforms); ++coreIt; } auto expected = NEO::toProductNames(expectedPlatforms); auto got = NEO::getTargetPlatformsForFatbinary("-" + genName, oclocArgHelperWithoutInput.get()); EXPECT_EQ(expected, got); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenGenClosedRangeThenReturnAllEnabledPlatformsThatMatch) { auto allEnabledPlatforms = NEO::getAllSupportedTargetPlatforms(); auto allEnabledCores = getEnabledCores(); if (allEnabledCores.size() < 4) { return; } auto genFrom = allEnabledCores[1]; auto genTo = allEnabledCores[allEnabledCores.size() - 2]; std::string genNameFrom = NEO::familyName[genFrom]; genNameFrom[0] = 'g'; std::string genNameTo = NEO::familyName[genTo]; genNameTo[0] = 'g'; std::vector<PRODUCT_FAMILY> expectedPlatforms; auto genIt = genFrom; while (genIt <= genTo) { NEO::appendPlatformsForGfxCore(static_cast<GFXCORE_FAMILY>(genIt), allEnabledPlatforms, expectedPlatforms); genIt = static_cast<GFXCORE_FAMILY>(static_cast<unsigned int>(genIt) + 1); } auto expected = NEO::toProductNames(expectedPlatforms); auto got = NEO::getTargetPlatformsForFatbinary(genNameFrom + "-" + genNameTo, oclocArgHelperWithoutInput.get()); EXPECT_EQ(expected, got); got = NEO::getTargetPlatformsForFatbinary(genNameTo + "-" + genNameFrom, oclocArgHelperWithoutInput.get()); // swap min with max implicitly EXPECT_EQ(expected, got); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenUnkownGenThenReturnEmptyList) { auto got = NEO::getTargetPlatformsForFatbinary("gen0", oclocArgHelperWithoutInput.get()); EXPECT_TRUE(got.empty()); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenMutiplePlatformWhenAnyOfPlatformsIsUnknownThenReturnEmptyList) { auto allEnabledPlatforms = NEO::getAllSupportedTargetPlatforms(); auto platform0 = allEnabledPlatforms[0]; std::string platform0Name = NEO::hardwarePrefix[platform0]; auto got = NEO::getTargetPlatformsForFatbinary(platform0Name + ",unk", oclocArgHelperWithoutInput.get()); EXPECT_TRUE(got.empty()); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenPlatformOpenRangeFromWhenPlatformsIsUnkownThenReturnEmptyList) { auto got = NEO::getTargetPlatformsForFatbinary("unk-", oclocArgHelperWithoutInput.get()); EXPECT_TRUE(got.empty()); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenPlatformOpenRangeToWhenPlatformsIsUnkownThenReturnEmptyList) { auto got = NEO::getTargetPlatformsForFatbinary("-unk", oclocArgHelperWithoutInput.get()); EXPECT_TRUE(got.empty()); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenPlatformClosedRangeWhenAnyOfPlatformsIsUnkownThenReturnEmptyList) { auto allEnabledPlatforms = NEO::getAllSupportedTargetPlatforms(); auto platform0 = allEnabledPlatforms[0]; std::string platform0Name = NEO::hardwarePrefix[platform0]; auto got = NEO::getTargetPlatformsForFatbinary("unk-" + platform0Name, oclocArgHelperWithoutInput.get()); EXPECT_TRUE(got.empty()); got = NEO::getTargetPlatformsForFatbinary(platform0Name + "-unk", oclocArgHelperWithoutInput.get()); EXPECT_TRUE(got.empty()); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenGenOpenRangeFromWhenGenIsUnknownTheReturnEmptyList) { auto got = NEO::getTargetPlatformsForFatbinary("gen2-", oclocArgHelperWithoutInput.get()); EXPECT_TRUE(got.empty()); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenGenOpenRangeToWhenGenIsUnknownTheReturnEmptyList) { auto got = NEO::getTargetPlatformsForFatbinary("-gen2", oclocArgHelperWithoutInput.get()); EXPECT_TRUE(got.empty()); } TEST_F(OclocFatBinaryGetTargetPlatformsForFatbinary, GivenGenClosedRangeWhenAnyOfGensIsUnknownThenReturnEmptyList) { auto allEnabledPlatforms = NEO::getAllSupportedTargetPlatforms(); auto platform0 = allEnabledPlatforms[0]; auto gfxCore0 = NEO::hardwareInfoTable[platform0]->platform.eRenderCoreFamily; std::string genName = NEO::familyName[gfxCore0]; genName[0] = 'g'; // ocloc uses lower case auto got = NEO::getTargetPlatformsForFatbinary("gen2-" + genName, oclocArgHelperWithoutInput.get()); EXPECT_TRUE(got.empty()); got = NEO::getTargetPlatformsForFatbinary(genName + "-gen2", oclocArgHelperWithoutInput.get()); EXPECT_TRUE(got.empty()); } } // namespace NEO
46.677686
153
0.744393
[ "vector" ]
cb81a09f58b49f5f9796000630f06e50af9e58c3
41,943
cpp
C++
hphp/runtime/base/tv-conversions.cpp
swtaarrs/hhvm
dfb8867363623d7d02d03a64691610f1289ef5ad
[ "PHP-3.01", "Zend-2.0" ]
1
2021-02-04T22:07:59.000Z
2021-02-04T22:07:59.000Z
hphp/runtime/base/tv-conversions.cpp
alisha/hhvm
523dc33b444bd5b59695eff2b64056629b0ed523
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/base/tv-conversions.cpp
alisha/hhvm
523dc33b444bd5b59695eff2b64056629b0ed523
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present 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 "hphp/runtime/base/array-data.h" #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/array-iterator.h" #include "hphp/runtime/base/collections.h" #include "hphp/runtime/base/datatype.h" #include "hphp/runtime/base/double-to-int64.h" #include "hphp/runtime/base/dummy-resource.h" #include "hphp/runtime/base/mixed-array.h" #include "hphp/runtime/base/object-data.h" #include "hphp/runtime/base/packed-array.h" #include "hphp/runtime/base/ref-data.h" #include "hphp/runtime/base/resource-data.h" #include "hphp/runtime/base/runtime-error.h" #include "hphp/runtime/base/runtime-option.h" #include "hphp/runtime/base/set-array.h" #include "hphp/runtime/base/string-data.h" #include "hphp/runtime/base/tv-mutate.h" #include "hphp/runtime/base/tv-refcount.h" #include "hphp/runtime/base/tv-variant.h" #include "hphp/runtime/base/type-array.h" #include "hphp/runtime/base/type-object.h" #include "hphp/runtime/base/type-string.h" #include "hphp/runtime/base/type-variant.h" #include "hphp/runtime/base/typed-value.h" #include "hphp/runtime/vm/func.h" #include "hphp/runtime/vm/vm-regs.h" #include "hphp/system/systemlib.h" #include "hphp/util/assertions.h" namespace HPHP { /////////////////////////////////////////////////////////////////////////////// void tvCastToBooleanInPlace(TypedValue* tv) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); bool b; do { switch (tv->m_type) { case KindOfUninit: case KindOfNull: b = false; continue; case KindOfBoolean: return; case KindOfInt64: b = (tv->m_data.num != 0LL); continue; case KindOfDouble: b = (tv->m_data.dbl != 0); continue; case KindOfPersistentString: b = tv->m_data.pstr->toBoolean(); continue; case KindOfString: b = tv->m_data.pstr->toBoolean(); tvDecRefStr(tv); continue; case KindOfPersistentVec: case KindOfPersistentDict: case KindOfPersistentKeyset: case KindOfPersistentArray: b = !tv->m_data.parr->empty(); continue; case KindOfVec: case KindOfDict: case KindOfKeyset: case KindOfArray: b = !tv->m_data.parr->empty(); tvDecRefArr(tv); continue; case KindOfObject: b = tv->m_data.pobj->toBoolean(); tvDecRefObj(tv); continue; case KindOfResource: b = tv->m_data.pres->data()->o_toBoolean(); tvDecRefRes(tv); continue; case KindOfFunc: b = funcToStringHelper(tv->m_data.pfunc)->toBoolean(); continue; case KindOfClass: b = classToStringHelper(tv->m_data.pclass)->toBoolean(); continue; case KindOfRef: break; } not_reached(); } while (0); tv->m_data.num = b; tv->m_type = KindOfBoolean; } bool tvCastToBoolean(TypedValue tv) { assertx(tvIsPlausible(tv)); if (isRefType(tv.m_type)) { tv = *tv.m_data.pref->tv(); } return cellToBool(tv); } void tvCastToDoubleInPlace(TypedValue* tv) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); double d; do { switch (tv->m_type) { case KindOfUninit: case KindOfNull: d = 0.0; continue; case KindOfBoolean: assertx(tv->m_data.num == 0LL || tv->m_data.num == 1LL); // fallthru case KindOfInt64: d = (double)(tv->m_data.num); continue; case KindOfDouble: return; case KindOfPersistentString: d = tv->m_data.pstr->toDouble(); continue; case KindOfString: d = tv->m_data.pstr->toDouble(); tvDecRefStr(tv); continue; case KindOfPersistentVec: case KindOfPersistentDict: case KindOfPersistentKeyset: case KindOfPersistentArray: d = tv->m_data.parr->empty() ? 0 : 1; continue; case KindOfVec: case KindOfDict: case KindOfKeyset: case KindOfArray: d = tv->m_data.parr->empty() ? 0 : 1; tvDecRefArr(tv); continue; case KindOfObject: d = tv->m_data.pobj->toDouble(); tvDecRefObj(tv); continue; case KindOfResource: d = tv->m_data.pres->data()->o_toDouble(); tvDecRefRes(tv); continue; case KindOfFunc: d = funcToStringHelper(tv->m_data.pfunc)->toDouble(); continue; case KindOfClass: d = classToStringHelper(tv->m_data.pclass)->toDouble(); continue; case KindOfRef: break; } not_reached(); } while (0); tv->m_data.dbl = d; tv->m_type = KindOfDouble; } void tvCastToInt64InPlace(TypedValue* tv) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); assertx(cellIsPlausible(*tv)); int64_t i; do { switch (tv->m_type) { case KindOfUninit: case KindOfNull: tv->m_data.num = 0LL; // fallthru case KindOfBoolean: assertx(tv->m_data.num == 0LL || tv->m_data.num == 1LL); tv->m_type = KindOfInt64; // fallthru case KindOfInt64: return; case KindOfDouble: i = double_to_int64(tv->m_data.dbl); continue; case KindOfPersistentString: i = tv->m_data.pstr->toInt64(); continue; case KindOfString: i = tv->m_data.pstr->toInt64(); tvDecRefStr(tv); continue; case KindOfPersistentVec: case KindOfPersistentDict: case KindOfPersistentKeyset: case KindOfPersistentArray: i = tv->m_data.parr->empty() ? 0 : 1; continue; case KindOfVec: case KindOfDict: case KindOfKeyset: case KindOfArray: i = tv->m_data.parr->empty() ? 0 : 1; tvDecRefArr(tv); continue; case KindOfObject: i = tv->m_data.pobj->toInt64(); tvDecRefObj(tv); continue; case KindOfResource: i = tv->m_data.pres->data()->o_toInt64(); tvDecRefRes(tv); continue; case KindOfFunc: i = funcToStringHelper(tv->m_data.pfunc)->toInt64(); continue; case KindOfClass: i = classToStringHelper(tv->m_data.pclass)->toInt64(); continue; case KindOfRef: break; } not_reached(); } while (0); tv->m_data.num = i; tv->m_type = KindOfInt64; } int64_t tvCastToInt64(TypedValue tv) { assertx(tvIsPlausible(tv)); if (isRefType(tv.m_type)) { tv = *tv.m_data.pref->tv(); } return cellToInt(tv); } double tvCastToDouble(TypedValue tv) { assertx(tvIsPlausible(tv)); if (isRefType(tv.m_type)) { tv = *tv.m_data.pref->tv(); } switch (tv.m_type) { case KindOfUninit: case KindOfNull: return 0; case KindOfBoolean: assertx(tv.m_data.num == 0LL || tv.m_data.num == 1LL); // fallthru case KindOfInt64: return (double)(tv.m_data.num); case KindOfDouble: return tv.m_data.dbl; case KindOfPersistentString: case KindOfString: return tv.m_data.pstr->toDouble(); case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfPersistentArray: case KindOfArray: return tv.m_data.parr->empty() ? 0.0 : 1.0; case KindOfObject: return tv.m_data.pobj->toDouble(); case KindOfResource: return tv.m_data.pres->data()->o_toDouble(); case KindOfFunc: return funcToStringHelper(tv.m_data.pfunc)->toDouble(); case KindOfClass: return classToStringHelper(tv.m_data.pclass)->toDouble(); case KindOfRef: break; } not_reached(); } const StaticString s_1("1"), s_scalar("scalar"); void tvCastToStringInPlace(TypedValue* tv) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); cellCastToStringInPlace(tv); } void cellCastToStringInPlace(tv_lval tv) { auto string = [&](StringData* s) { type(tv) = KindOfString; val(tv).pstr = s; }; auto persistentString = [&](StringData* s) { assertx(!s->isRefCounted()); type(tv) = KindOfPersistentString; val(tv).pstr = s; }; switch (type(tv)) { case KindOfUninit: case KindOfNull: return persistentString(staticEmptyString()); case KindOfBoolean: return persistentString(val(tv).num ? s_1.get() : staticEmptyString()); case KindOfInt64: return string(buildStringData(val(tv).num)); case KindOfDouble: return string(buildStringData(val(tv).dbl)); case KindOfPersistentString: case KindOfString: return; case KindOfVec: case KindOfPersistentVec: raise_notice("Vec to string conversion"); if (type(tv) == KindOfVec) tvDecRefArr(*tv); return persistentString(vec_string.get()); case KindOfDict: case KindOfPersistentDict: raise_notice("Dict to string conversion"); if (type(tv) == KindOfDict) tvDecRefArr(*tv); return persistentString(dict_string.get()); case KindOfKeyset: case KindOfPersistentKeyset: raise_notice("Keyset to string conversion"); if (type(tv) == KindOfKeyset) tvDecRefArr(*tv); return persistentString(keyset_string.get()); case KindOfArray: case KindOfPersistentArray: raise_notice("Array to string conversion"); if (type(tv) == KindOfArray) tvDecRefArr(*tv); return persistentString(array_string.get()); case KindOfObject: cellMove( make_tv<KindOfString>(val(tv).pobj->invokeToString().detach()), tv ); return; case KindOfResource: cellMove( make_tv<KindOfString>(val(tv).pres->data()->o_toString().detach()), tv ); return; case KindOfFunc: { auto const s = funcToStringHelper(val(tv).pfunc); return persistentString(const_cast<StringData*>(s)); } case KindOfClass: { auto const s = classToStringHelper(val(tv).pclass); return persistentString(const_cast<StringData*>(s)); } case KindOfRef: break; } not_reached(); } StringData* tvCastToStringData(TypedValue tv) { assertx(tvIsPlausible(tv)); if (isRefType(tv.m_type)) { tv = *tv.m_data.pref->tv(); } return cellCastToStringData(tv); } StringData* cellCastToStringData(Cell tv) { assert(tv.m_type != KindOfRef); switch (tv.m_type) { case KindOfUninit: case KindOfNull: return staticEmptyString(); case KindOfBoolean: return tv.m_data.num ? s_1.get() : staticEmptyString(); case KindOfInt64: return buildStringData(tv.m_data.num); case KindOfDouble: return buildStringData(tv.m_data.dbl); case KindOfPersistentString: return tv.m_data.pstr; case KindOfString: { auto s = tv.m_data.pstr; s->incRefCount(); return s; } case KindOfPersistentVec: case KindOfVec: raise_notice("Vec to string conversion"); return vec_string.get(); case KindOfPersistentDict: case KindOfDict: raise_notice("Dict to string conversion"); return dict_string.get(); case KindOfPersistentKeyset: case KindOfKeyset: raise_notice("Keyset to string conversion"); return keyset_string.get(); case KindOfPersistentArray: case KindOfArray: raise_notice("Array to string conversion"); return array_string.get(); case KindOfObject: return tv.m_data.pobj->invokeToString().detach(); case KindOfResource: return tv.m_data.pres->data()->o_toString().detach(); case KindOfFunc: { auto const s = funcToStringHelper(tv.m_data.pfunc); return const_cast<StringData*>(s); } case KindOfClass: { auto const s = classToStringHelper(tv.m_data.pclass); return const_cast<StringData*>(s); } case KindOfRef: not_reached(); } not_reached(); } String tvCastToString(TypedValue tv) { return String::attach(tvCastToStringData(tv)); } ArrayData* tvCastToArrayLikeData(TypedValue tv) { assertx(tvIsPlausible(tv)); if (isRefType(tv.m_type)) { tv = *tv.m_data.pref->tv(); } switch (tv.m_type) { case KindOfUninit: case KindOfNull: return ArrayData::Create(); case KindOfBoolean: case KindOfInt64: case KindOfDouble: case KindOfPersistentString: case KindOfString: case KindOfResource: case KindOfFunc: case KindOfClass: return ArrayData::Create(tv); case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfPersistentArray: case KindOfArray: { auto const ad = tv.m_data.parr; ad->incRefCount(); return ad; } case KindOfObject: { auto ad = tv.m_data.pobj->toArray(); assertx(ad->isPHPArray()); return ad.detach(); } case KindOfRef: break; } not_reached(); } Array tvCastToArrayLike(TypedValue tv) { return Array::attach(tvCastToArrayLikeData(tv)); } void tvCastToArrayInPlace(TypedValue* tv) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); ArrayData* a; do { switch (tv->m_type) { case KindOfUninit: case KindOfNull: a = ArrayData::Create(); continue; case KindOfBoolean: case KindOfInt64: case KindOfDouble: case KindOfPersistentString: a = ArrayData::Create(tvAsVariant(tv)); continue; case KindOfString: a = ArrayData::Create(tvAsVariant(tv)); tvDecRefStr(tv); continue; case KindOfPersistentVec: { auto* adIn = tv->m_data.parr; assertx(adIn->isVecArray()); a = PackedArray::ToPHPArrayVec(adIn, true); assertx(a != adIn); continue; } case KindOfVec: { auto* adIn = tv->m_data.parr; assertx(adIn->isVecArray()); a = PackedArray::ToPHPArrayVec(adIn, adIn->cowCheck()); if (a != adIn) tvDecRefArr(tv); continue; } case KindOfPersistentDict: { auto* adIn = tv->m_data.parr; assertx(adIn->isDict()); a = MixedArray::ToPHPArrayDict(adIn, true); assertx(a != adIn); continue; } case KindOfDict: { auto* adIn = tv->m_data.parr; assertx(adIn->isDict()); a = MixedArray::ToPHPArrayDict(adIn, adIn->cowCheck()); if (a != adIn) tvDecRefArr(tv); continue; } case KindOfPersistentKeyset: { auto* adIn = tv->m_data.parr; assertx(adIn->isKeyset()); a = SetArray::ToPHPArray(adIn, true); assertx(a != adIn); continue; } case KindOfKeyset: { auto* adIn = tv->m_data.parr; assertx(adIn->isKeyset()); a = SetArray::ToPHPArray(adIn, adIn->cowCheck()); if (a != adIn) tvDecRefArr(tv); continue; } case KindOfPersistentArray: { auto* adIn = tv->m_data.parr; assertx(adIn->isPHPArray()); if (adIn->isNotDVArray()) return; a = adIn->toPHPArray(true); assertx(a != adIn); continue; } case KindOfArray: { auto* adIn = tv->m_data.parr; assertx(adIn->isPHPArray()); if (adIn->isNotDVArray()) return; a = adIn->toPHPArray(adIn->cowCheck()); if (a != adIn) tvDecRefArr(tv); continue; } case KindOfObject: // For objects, we fall back on the Variant machinery tvAsVariant(tv) = tv->m_data.pobj->toArray(); return; case KindOfResource: a = ArrayData::Create(tvAsVariant(tv)); tvDecRefRes(tv); continue; case KindOfFunc: case KindOfClass: a = ArrayData::Create(tvAsVariant(tv)); continue; case KindOfRef: break; } not_reached(); } while (0); assertx(a->isPHPArray()); assertx(a->isNotDVArray()); tv->m_data.parr = a; tv->m_type = KindOfArray; assertx(cellIsPlausible(*tv)); } void tvCastToVecInPlace(TypedValue* tv) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); ArrayData* a; do { switch (tv->m_type) { case KindOfUninit: case KindOfNull: SystemLib::throwInvalidOperationExceptionObject( "Null to vec conversion" ); case KindOfBoolean: SystemLib::throwInvalidOperationExceptionObject( "Bool to vec conversion" ); case KindOfInt64: SystemLib::throwInvalidOperationExceptionObject( "Int to vec conversion" ); case KindOfDouble: SystemLib::throwInvalidOperationExceptionObject( "Double to vec conversion" ); case KindOfPersistentString: case KindOfString: SystemLib::throwInvalidOperationExceptionObject( "String to vec conversion" ); case KindOfResource: SystemLib::throwInvalidOperationExceptionObject( "Resource to vec conversion" ); case KindOfPersistentDict: case KindOfDict: { auto* adIn = tv->m_data.parr; assertx(adIn->isDict()); a = MixedArray::ToVecDict(adIn, adIn->cowCheck()); assertx(a != adIn); decRefArr(adIn); continue; } case KindOfPersistentKeyset: case KindOfKeyset: { auto* adIn = tv->m_data.parr; assertx(adIn->isKeyset()); a = SetArray::ToVec(adIn, adIn->cowCheck()); assertx(a != adIn); decRefArr(adIn); continue; } case KindOfPersistentArray: case KindOfArray: { auto* adIn = tv->m_data.parr; assertx(adIn->isPHPArray()); a = adIn->toVec(adIn->cowCheck()); if (a != adIn) decRefArr(adIn); continue; } case KindOfPersistentVec: case KindOfVec: assertx(tv->m_data.parr->isVecArray()); return; case KindOfObject: a = castObjToVec(tv->m_data.pobj); // We might have re-entered, so tv may not contain the object anymore. tvDecRefGen(tv); continue; case KindOfFunc: SystemLib::throwInvalidOperationExceptionObject( "Func to vec conversion" ); case KindOfClass: SystemLib::throwInvalidOperationExceptionObject( "Class to vec conversion" ); case KindOfRef: break; } not_reached(); } while (0); tv->m_data.parr = a; tv->m_type = KindOfVec; assertx(cellIsPlausible(*tv)); } void tvCastToDictInPlace(TypedValue* tv) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); ArrayData* a; do { switch (tv->m_type) { case KindOfUninit: case KindOfNull: SystemLib::throwInvalidOperationExceptionObject( "Null to dict conversion" ); case KindOfBoolean: SystemLib::throwInvalidOperationExceptionObject( "Bool to dict conversion" ); case KindOfInt64: SystemLib::throwInvalidOperationExceptionObject( "Int to dict conversion" ); case KindOfDouble: SystemLib::throwInvalidOperationExceptionObject( "Double to dict conversion" ); case KindOfPersistentString: case KindOfString: SystemLib::throwInvalidOperationExceptionObject( "String to dict conversion" ); case KindOfResource: SystemLib::throwInvalidOperationExceptionObject( "Resource to dict conversion" ); case KindOfPersistentVec: case KindOfVec: { auto* adIn = tv->m_data.parr; assertx(adIn->isVecArray()); a = PackedArray::ToDictVec(adIn, adIn->cowCheck()); assertx(a != adIn); decRefArr(adIn); continue; } case KindOfPersistentKeyset: case KindOfKeyset: { auto* adIn = tv->m_data.parr; assertx(adIn->isKeyset()); a = SetArray::ToDict(adIn, adIn->cowCheck()); if (a != adIn) decRefArr(adIn); continue; } case KindOfPersistentArray: case KindOfArray: { auto* adIn = tv->m_data.parr; assertx(adIn->isPHPArray()); a = adIn->toDict(adIn->cowCheck()); if (a != adIn) decRefArr(adIn); continue; } case KindOfPersistentDict: case KindOfDict: assertx(tv->m_data.parr->isDict()); return; case KindOfObject: a = castObjToDict(tv->m_data.pobj); // We might have re-entered, so tv may not contain the object anymore. tvDecRefGen(tv); continue; case KindOfFunc: SystemLib::throwInvalidOperationExceptionObject( "Func to dict conversion" ); case KindOfClass: SystemLib::throwInvalidArgumentExceptionObject( "Class to dict conversion" ); case KindOfRef: break; } not_reached(); } while (0); tv->m_data.parr = a; tv->m_type = KindOfDict; assertx(cellIsPlausible(*tv)); } void tvCastToKeysetInPlace(TypedValue* tv) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); ArrayData* a; do { switch (tv->m_type) { case KindOfUninit: case KindOfNull: SystemLib::throwInvalidOperationExceptionObject( "Null to keyset conversion" ); case KindOfBoolean: SystemLib::throwInvalidOperationExceptionObject( "Bool to keyset conversion" ); case KindOfInt64: SystemLib::throwInvalidOperationExceptionObject( "Int to keyset conversion" ); case KindOfDouble: SystemLib::throwInvalidOperationExceptionObject( "Double to keyset conversion" ); case KindOfPersistentString: case KindOfString: SystemLib::throwInvalidOperationExceptionObject( "String to keyset conversion" ); case KindOfResource: SystemLib::throwInvalidOperationExceptionObject( "Resource to keyset conversion" ); case KindOfPersistentVec: case KindOfVec: { auto* adIn = tv->m_data.parr; assertx(adIn->isVecArray()); a = PackedArray::ToKeysetVec(adIn, adIn->cowCheck()); assertx(a != adIn); decRefArr(adIn); continue; } case KindOfPersistentDict: case KindOfDict: { auto* adIn = tv->m_data.parr; assertx(adIn->isDict()); a = MixedArray::ToKeysetDict(adIn, adIn->cowCheck()); if (a != adIn) decRefArr(adIn); continue; } case KindOfPersistentArray: case KindOfArray: { auto* adIn = tv->m_data.parr; assertx(adIn->isPHPArray()); a = adIn->toKeyset(adIn->cowCheck()); if (a != adIn) decRefArr(adIn); continue; } case KindOfPersistentKeyset: case KindOfKeyset: assertx(tv->m_data.parr->isKeyset()); return; case KindOfObject: a = castObjToKeyset(tv->m_data.pobj); // We might have re-entered, so tv may not contain the object anymore. tvDecRefGen(tv); continue; case KindOfFunc: SystemLib::throwInvalidOperationExceptionObject( "Func to keyset conversion" ); case KindOfClass: SystemLib::throwInvalidOperationExceptionObject( "Class to keyset conversion" ); case KindOfRef: break; } not_reached(); } while (0); tv->m_data.parr = a; tv->m_type = KindOfKeyset; assertx(cellIsPlausible(*tv)); } void tvCastToVArrayInPlace(TypedValue* tv) { assertx(!RuntimeOption::EvalHackArrDVArrs); assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); ArrayData* a; do { switch (tv->m_type) { case KindOfUninit: case KindOfNull: SystemLib::throwInvalidOperationExceptionObject( "Null to varray conversion" ); case KindOfBoolean: SystemLib::throwInvalidOperationExceptionObject( "Bool to varray conversion" ); case KindOfInt64: SystemLib::throwInvalidOperationExceptionObject( "Int to varray conversion" ); case KindOfDouble: SystemLib::throwInvalidOperationExceptionObject( "Double to varray conversion" ); case KindOfPersistentString: case KindOfString: SystemLib::throwInvalidOperationExceptionObject( "String to varray conversion" ); case KindOfResource: SystemLib::throwInvalidOperationExceptionObject( "Resource to varray conversion" ); case KindOfPersistentVec: case KindOfVec: { auto* adIn = tv->m_data.parr; assertx(adIn->isVecArray()); a = PackedArray::ToVArrayVec(adIn, adIn->cowCheck()); if (a != adIn) decRefArr(adIn); continue; } case KindOfPersistentDict: case KindOfDict: { auto* adIn = tv->m_data.parr; assertx(adIn->isDict()); a = MixedArray::ToVArrayDict(adIn, adIn->cowCheck()); assertx(a != adIn); decRefArr(adIn); continue; } case KindOfPersistentKeyset: case KindOfKeyset: { auto* adIn = tv->m_data.parr; assertx(adIn->isKeyset()); a = SetArray::ToVArray(adIn, adIn->cowCheck()); assertx(a != adIn); decRefArr(adIn); continue; } case KindOfPersistentArray: case KindOfArray: { auto* adIn = tv->m_data.parr; assertx(adIn->isPHPArray()); if (adIn->isVArray()) return; a = adIn->toVArray(adIn->cowCheck()); assertx(a->isPacked()); assertx(a->isVArray()); if (a == adIn) return; decRefArr(adIn); continue; } case KindOfObject: a = castObjToVArray(tv->m_data.pobj); // We might have re-entered, so tv may not contain the object anymore. tvDecRefGen(tv); continue; case KindOfFunc: SystemLib::throwInvalidOperationExceptionObject( "Func to varray conversion" ); case KindOfClass: SystemLib::throwInvalidOperationExceptionObject( "Class to varray conversion" ); case KindOfRef: break; } not_reached(); } while (0); assertx(a->isPacked()); assertx(a->isVArray()); tv->m_data.parr = a; tv->m_type = KindOfArray; assertx(cellIsPlausible(*tv)); } void tvCastToDArrayInPlace(TypedValue* tv) { assertx(!RuntimeOption::EvalHackArrDVArrs); assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); ArrayData* a; do { switch (tv->m_type) { case KindOfUninit: case KindOfNull: SystemLib::throwInvalidOperationExceptionObject( "Null to darray conversion" ); case KindOfBoolean: SystemLib::throwInvalidOperationExceptionObject( "Bool to darray conversion" ); case KindOfInt64: SystemLib::throwInvalidOperationExceptionObject( "Int to darray conversion" ); case KindOfDouble: SystemLib::throwInvalidOperationExceptionObject( "Double to darray conversion" ); case KindOfPersistentString: case KindOfString: SystemLib::throwInvalidOperationExceptionObject( "String to darray conversion" ); case KindOfResource: SystemLib::throwInvalidOperationExceptionObject( "Resource to darray conversion" ); case KindOfPersistentVec: case KindOfVec: { auto* adIn = tv->m_data.parr; assertx(adIn->isVecArray()); a = PackedArray::ToDArrayVec(adIn, adIn->cowCheck()); assertx(a != adIn); decRefArr(adIn); continue; } case KindOfPersistentDict: case KindOfDict: { auto* adIn = tv->m_data.parr; assertx(adIn->isDict()); a = MixedArray::ToDArrayDict(adIn, adIn->cowCheck()); if (a != adIn) decRefArr(adIn); continue; } case KindOfPersistentKeyset: case KindOfKeyset: { auto* adIn = tv->m_data.parr; assertx(adIn->isKeyset()); a = SetArray::ToDArray(adIn, adIn->cowCheck()); assertx(a != adIn); decRefArr(adIn); continue; } case KindOfPersistentArray: case KindOfArray: { auto* adIn = tv->m_data.parr; assertx(adIn->isPHPArray()); if (adIn->isDArray()) return; a = adIn->toDArray(adIn->cowCheck()); assertx(a->isMixed()); assertx(a->isDArray()); if (a == adIn) return; decRefArr(adIn); continue; } case KindOfObject: a = castObjToDArray(tv->m_data.pobj); // We might have re-entered, so tv may not contain the object anymore. tvDecRefGen(tv); continue; case KindOfFunc: SystemLib::throwInvalidOperationExceptionObject( "Func to darray conversion" ); case KindOfClass: SystemLib::throwInvalidOperationExceptionObject( "Class to darray conversion" ); case KindOfRef: break; } not_reached(); } while (0); assertx(a->isMixed()); assertx(a->isDArray()); tv->m_data.parr = a; tv->m_type = KindOfArray; assertx(cellIsPlausible(*tv)); } ObjectData* tvCastToObjectData(TypedValue tv) { assertx(tvIsPlausible(tv)); if (isRefType(tv.m_type)) { tv = *tv.m_data.pref->tv(); } switch (tv.m_type) { case KindOfUninit: case KindOfNull: return SystemLib::AllocStdClassObject().detach(); case KindOfBoolean: case KindOfInt64: case KindOfDouble: case KindOfPersistentString: case KindOfString: case KindOfFunc: case KindOfClass: case KindOfResource: { ArrayInit props(1, ArrayInit::Map{}); props.set(s_scalar, tv); return ObjectData::FromArray(props.create()).detach(); } case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: { auto const arr = Array::attach(tv.m_data.parr->toPHPArray(true)); return ObjectData::FromArray(arr.get()).detach(); } case KindOfPersistentArray: case KindOfArray: return ObjectData::FromArray(tv.m_data.parr).detach(); case KindOfObject: tv.m_data.pobj->incRefCount(); return tv.m_data.pobj; case KindOfRef: break; } not_reached(); } Object tvCastToObject(TypedValue tv) { return Object::attach(tvCastToObjectData(tv)); } void tvCastToObjectInPlace(TypedValue* tv) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); ObjectData* o; do { switch (tv->m_type) { case KindOfUninit: case KindOfNull: o = SystemLib::AllocStdClassObject().detach(); continue; case KindOfBoolean: case KindOfInt64: case KindOfDouble: case KindOfPersistentString: case KindOfFunc: case KindOfClass: case KindOfResource: { ArrayInit props(1, ArrayInit::Map{}); props.set(s_scalar, *tv); o = ObjectData::FromArray(props.create()).detach(); continue; } case KindOfString: { ArrayInit props(1, ArrayInit::Map{}); props.set(s_scalar, *tv); o = ObjectData::FromArray(props.create()).detach(); tvDecRefStr(tv); continue; } case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: tvCastToArrayInPlace(tv); // Fall-through to array case case KindOfPersistentArray: case KindOfArray: // For arrays, we fall back on the Variant machinery tvAsVariant(tv) = ObjectData::FromArray(tv->m_data.parr); return; case KindOfObject: return; case KindOfRef: break; } not_reached(); } while (0); tv->m_data.pobj = o; tv->m_type = KindOfObject; assertx(cellIsPlausible(*tv)); } void tvCastToNullableObjectInPlace(TypedValue* tv) { if (isNullType(tv->m_type)) { // XXX(t3879280) This happens immediately before calling an extension // function that takes an optional Object argument. We want to end up // passing const Object& holding nullptr, so by clearing out m_data.pobj we // can unconditionally treat &tv->m_data.pobj as a const Object& in the // function being called. This violates the invariant that the value of // m_data doesn't matter in a KindOfNull TypedValue. tv->m_data.pobj = nullptr; } else { tvCastToObjectInPlace(tv); } } void tvCastToResourceInPlace(TypedValue* tv) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); do { switch (tv->m_type) { DT_UNCOUNTED_CASE: continue; case KindOfString: case KindOfVec: case KindOfDict: case KindOfKeyset: case KindOfArray: case KindOfObject: tvDecRefCountable(tv); continue; case KindOfResource: // no op, return return; case KindOfRef: break; } not_reached(); } while (0); tv->m_type = KindOfResource; tv->m_data.pres = req::make<DummyResource>().detach()->hdr(); assertx(cellIsPlausible(*tv)); } bool tvCoerceParamToBooleanInPlace(TypedValue* tv, bool builtin) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); switch (tv->m_type) { case KindOfNull: // In PHP 7 mode handling of null types is stricter if (RuntimeOption::PHP7_ScalarTypes && !builtin) return false; // fall-through case KindOfUninit: case KindOfBoolean: case KindOfInt64: case KindOfDouble: case KindOfPersistentString: case KindOfString: case KindOfFunc: case KindOfClass: tvCastToBooleanInPlace(tv); return true; case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfPersistentArray: case KindOfArray: case KindOfObject: case KindOfResource: return false; case KindOfRef: break; } not_reached(); } static bool tvCanBeCoercedToNumber(const TypedValue* tv, bool builtin) { switch (tv->m_type) { case KindOfUninit: case KindOfBoolean: case KindOfInt64: case KindOfDouble: return true; case KindOfNull: // In PHP 7 mode handling of null types is stricter return !RuntimeOption::PHP7_ScalarTypes || builtin; case KindOfPersistentString: case KindOfString: return tv->m_data.pstr->isNumeric(); case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfPersistentArray: case KindOfArray: case KindOfObject: case KindOfResource: case KindOfFunc: case KindOfClass: return false; case KindOfRef: break; } not_reached(); } bool tvCoerceParamToInt64InPlace(TypedValue* tv, bool builtin) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); if (!tvCanBeCoercedToNumber(tv, builtin)) { return false; } // In PHP 7 mode doubles only convert to integers when the conversion is non- // narrowing if (RuntimeOption::PHP7_ScalarTypes && tv->m_type == KindOfDouble) { if (tv->m_data.dbl < std::numeric_limits<int64_t>::min()) return false; if (tv->m_data.dbl > std::numeric_limits<int64_t>::max()) return false; if (std::isnan(tv->m_data.dbl)) return false; } tvCastToInt64InPlace(tv); return true; } bool tvCoerceParamToDoubleInPlace(TypedValue* tv, bool builtin) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); if (!tvCanBeCoercedToNumber(tv, builtin)) { return false; } tvCastToDoubleInPlace(tv); return true; } bool tvCoerceParamToStringInPlace(TypedValue* tv, bool builtin) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); switch (tv->m_type) { case KindOfNull: // In PHP 7 mode handling of null types is stricter if (RuntimeOption::PHP7_ScalarTypes && !builtin) { return false; } // fall-through case KindOfUninit: case KindOfBoolean: case KindOfInt64: case KindOfDouble: case KindOfPersistentString: case KindOfString: case KindOfFunc: case KindOfClass: tvCastToStringInPlace(tv); return true; case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfPersistentArray: case KindOfArray: return false; case KindOfObject: if (tv->m_data.pobj->hasToString()) { tvAsVariant(tv) = tv->m_data.pobj->invokeToString(); return true; } return false; case KindOfResource: return false; case KindOfRef: break; } not_reached(); } bool tvCoerceParamToArrayInPlace(TypedValue* tv, bool /*builtin*/) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); switch (tv->m_type) { case KindOfUninit: case KindOfNull: case KindOfBoolean: case KindOfInt64: case KindOfDouble: case KindOfPersistentString: case KindOfString: case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfFunc: case KindOfClass: return false; case KindOfPersistentArray: case KindOfArray: return true; case KindOfObject: if (LIKELY(tv->m_data.pobj->isCollection())) { tvAsVariant(tv) = tv->m_data.pobj->toArray(); return true; } return false; case KindOfResource: return false; case KindOfRef: break; } not_reached(); } bool tvCoerceParamToVecInPlace(TypedValue* tv, bool /*builtin*/) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); switch (tv->m_type) { case KindOfUninit: case KindOfNull: case KindOfBoolean: case KindOfInt64: case KindOfDouble: case KindOfPersistentString: case KindOfString: case KindOfObject: case KindOfResource: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfPersistentArray: case KindOfArray: case KindOfFunc: case KindOfClass: return false; case KindOfPersistentVec: case KindOfVec: return true; case KindOfRef: break; } not_reached(); } bool tvCoerceParamToDictInPlace(TypedValue* tv, bool /*builtin*/) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); switch (tv->m_type) { case KindOfUninit: case KindOfNull: case KindOfBoolean: case KindOfInt64: case KindOfDouble: case KindOfPersistentString: case KindOfString: case KindOfObject: case KindOfResource: case KindOfPersistentVec: case KindOfVec: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfPersistentArray: case KindOfArray: case KindOfFunc: case KindOfClass: return false; case KindOfPersistentDict: case KindOfDict: return true; case KindOfRef: break; } not_reached(); } bool tvCoerceParamToKeysetInPlace(TypedValue* tv, bool /*builtin*/) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); switch (tv->m_type) { case KindOfUninit: case KindOfNull: case KindOfBoolean: case KindOfInt64: case KindOfDouble: case KindOfPersistentString: case KindOfString: case KindOfObject: case KindOfResource: case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentArray: case KindOfArray: case KindOfFunc: case KindOfClass: return false; case KindOfPersistentKeyset: case KindOfKeyset: return true; case KindOfRef: break; } not_reached(); } bool tvCoerceParamToObjectInPlace(TypedValue* tv, bool /*builtin*/) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); return tv->m_type == KindOfObject; } bool tvCoerceParamToNullableObjectInPlace(TypedValue* tv, bool /*builtin*/) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); if (isNullType(tv->m_type)) { // See comment in tvCastToNullableObjectInPlace tv->m_data.pobj = nullptr; return true; } return tv->m_type == KindOfObject; } bool tvCoerceParamToResourceInPlace(TypedValue* tv, bool /*builtin*/) { assertx(tvIsPlausible(*tv)); tvUnboxIfNeeded(*tv); return tv->m_type == KindOfResource; } /////////////////////////////////////////////////////////////////////////////// }
24.789007
79
0.61493
[ "object" ]
cb84c17edf4984ceeb9c8cf86cc5263ca2fed185
649
cpp
C++
153.cpp
machinecc/leetcode
32bbf6c1f9124049c046a235c85b14ca9168daa8
[ "MIT" ]
null
null
null
153.cpp
machinecc/leetcode
32bbf6c1f9124049c046a235c85b14ca9168daa8
[ "MIT" ]
null
null
null
153.cpp
machinecc/leetcode
32bbf6c1f9124049c046a235c85b14ca9168daa8
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> #include <string> #include <unordered_set> #include <vector> #include <algorithm> #include <climits> #include <stack> #include <sstream> #include <numeric> #include <unordered_map> #include <array> using namespace std; class Solution { public: int findMin(vector<int>& nums) { int n = nums.size(); if (n == 1) return nums[0]; int left = 0; int right = n - 1; while (left < right) { int mid = (left + right) / 2; if (nums[left] < nums[mid]) { left = mid; } else { } } } }; int main() { return 0; }
12.72549
36
0.543914
[ "vector" ]
cb8d0c9ae858a294008be9419c4da33a56a0e2a4
1,930
hpp
C++
include/wip/expressions_algebra/quadratic_expression_algebra.hpp
fhamonic/mippp
5d06aacc3c57690f354220740ed03c3f810bf7fd
[ "BSL-1.0" ]
1
2021-09-23T11:56:33.000Z
2021-09-23T11:56:33.000Z
include/wip/expressions_algebra/quadratic_expression_algebra.hpp
fhamonic/mippp
5d06aacc3c57690f354220740ed03c3f810bf7fd
[ "BSL-1.0" ]
null
null
null
include/wip/expressions_algebra/quadratic_expression_algebra.hpp
fhamonic/mippp
5d06aacc3c57690f354220740ed03c3f810bf7fd
[ "BSL-1.0" ]
null
null
null
/** * @file solver_builder.hpp * @author François Hamonic (francois.hamonic@gmail.com) * @brief OSI_Builder class declaration * @version 0.1 * @date 2021-08-4 * * @copyright Copyright (c) 2020 */ #ifndef EXPRESSION_ALGEBRA_HPP #define EXPRESSION_ALGEBRA_HPP #include <numeric> #include <vector> #include <range/v3/view/zip.hpp> #include <range/v3/algorithm/for_each.hpp> #include "expressions/linear_expression.hpp" #include "expressions/quadratic_expression.hpp" #include "constraints/linear_constraints.hpp" #include "constraints/quadratic_constraints.hpp" #include "expressions_algebra/linear_expression_algebra.hpp" namespace Algebra { enum OptimizationSense { MIN=-1, MAX=1 }; constexpr double INFTY = std::numeric_limits<double>::max(); // LINEAR struct QuadraticTerm { int var1; int var2; double coef; constexpr QuadraticTerm(Var v1, Var v2, double c) : var1(v1.get()) , var2(v2.get()) , coef(c) {} constexpr QuadraticTerm& operator*(double c) { coef += c; return *this; } }; constexpr QuadraticTerm operator*(LinearTerm t, Var v) { return QuadraticTerm(t.var, v, t.coef); } inline QuadraticExpr& operator+(QuadraticExpr & e, double c) { return e.add(c); } inline QuadraticExpr& operator+(QuadraticExpr & e, LinearTerm t) { return e.add(t.var, t.coef); } inline QuadraticExpr& operator+(QuadraticExpr & e, QuadraticTerm t) { return e.add(t.var1, t.var2, t.coef); } inline QuadraticExpr operator+(QuadraticTerm t1, QuadraticTerm t2) { return std::forward<QuadraticExpr&&>(QuadraticExpr(t1) + t2); } inline QuadraticExpr operator+(LinearExpr&& le, QuadraticTerm t) { QuadraticExpr e(std::move(le)); e.add(t); return e; } } //Algebra #endif //EXPRESSION_ALGEBRA_HPP
27.183099
73
0.651813
[ "vector" ]
cb90b720f88a2b4ba0932e6ea894a772f932ee44
2,942
cpp
C++
component/oai-smf/src/api-server/model/ExemptionInd.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-smf/src/api-server/model/ExemptionInd.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-smf/src/api-server/model/ExemptionInd.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
/** * Nsmf_PDUSession * SMF PDU Session Service. © 2019, 3GPP Organizational Partners (ARIB, ATIS, * CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved. * * The version of the OpenAPI document: 1.1.0.alpha-1 * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ #include "ExemptionInd.h" namespace oai { namespace smf_server { namespace model { ExemptionInd::ExemptionInd() { m_DnnCongestion = false; m_DnnCongestionIsSet = false; m_SnssaiOnlyCongestion = false; m_SnssaiOnlyCongestionIsSet = false; m_SnssaiDnnCongestion = false; m_SnssaiDnnCongestionIsSet = false; } ExemptionInd::~ExemptionInd() {} void ExemptionInd::validate() { // TODO: implement validation } void to_json(nlohmann::json& j, const ExemptionInd& o) { j = nlohmann::json(); if (o.dnnCongestionIsSet()) j["dnnCongestion"] = o.m_DnnCongestion; if (o.snssaiOnlyCongestionIsSet()) j["snssaiOnlyCongestion"] = o.m_SnssaiOnlyCongestion; if (o.snssaiDnnCongestionIsSet()) j["snssaiDnnCongestion"] = o.m_SnssaiDnnCongestion; } void from_json(const nlohmann::json& j, ExemptionInd& o) { if (j.find("dnnCongestion") != j.end()) { j.at("dnnCongestion").get_to(o.m_DnnCongestion); o.m_DnnCongestionIsSet = true; } if (j.find("snssaiOnlyCongestion") != j.end()) { j.at("snssaiOnlyCongestion").get_to(o.m_SnssaiOnlyCongestion); o.m_SnssaiOnlyCongestionIsSet = true; } if (j.find("snssaiDnnCongestion") != j.end()) { j.at("snssaiDnnCongestion").get_to(o.m_SnssaiDnnCongestion); o.m_SnssaiDnnCongestionIsSet = true; } } bool ExemptionInd::isDnnCongestion() const { return m_DnnCongestion; } void ExemptionInd::setDnnCongestion(bool const value) { m_DnnCongestion = value; m_DnnCongestionIsSet = true; } bool ExemptionInd::dnnCongestionIsSet() const { return m_DnnCongestionIsSet; } void ExemptionInd::unsetDnnCongestion() { m_DnnCongestionIsSet = false; } bool ExemptionInd::isSnssaiOnlyCongestion() const { return m_SnssaiOnlyCongestion; } void ExemptionInd::setSnssaiOnlyCongestion(bool const value) { m_SnssaiOnlyCongestion = value; m_SnssaiOnlyCongestionIsSet = true; } bool ExemptionInd::snssaiOnlyCongestionIsSet() const { return m_SnssaiOnlyCongestionIsSet; } void ExemptionInd::unsetSnssaiOnlyCongestion() { m_SnssaiOnlyCongestionIsSet = false; } bool ExemptionInd::isSnssaiDnnCongestion() const { return m_SnssaiDnnCongestion; } void ExemptionInd::setSnssaiDnnCongestion(bool const value) { m_SnssaiDnnCongestion = value; m_SnssaiDnnCongestionIsSet = true; } bool ExemptionInd::snssaiDnnCongestionIsSet() const { return m_SnssaiDnnCongestionIsSet; } void ExemptionInd::unsetSnssaiDnnCongestion() { m_SnssaiDnnCongestionIsSet = false; } } // namespace model } // namespace smf_server } // namespace oai
28.843137
79
0.737254
[ "model" ]
cb90dc337fc7ebe2f81e2528f2247c0a0b4f677b
7,430
cc
C++
tensorflow/compiler/plugin/poplar/driver/ops/custom_ops/popops/expression_helpers.cc
DebeshJha/tensorflow-1
2b5a225c49d25273532d11c424d37ce394d7579a
[ "Apache-2.0" ]
2
2021-03-08T23:32:06.000Z
2022-01-13T03:43:49.000Z
tensorflow/compiler/plugin/poplar/driver/ops/custom_ops/popops/expression_helpers.cc
DebeshJha/tensorflow-1
2b5a225c49d25273532d11c424d37ce394d7579a
[ "Apache-2.0" ]
null
null
null
tensorflow/compiler/plugin/poplar/driver/ops/custom_ops/popops/expression_helpers.cc
DebeshJha/tensorflow-1
2b5a225c49d25273532d11c424d37ce394d7579a
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/plugin/poplar/driver/ops/custom_ops/popops/expression_helpers.h" #include "tensorflow/compiler/plugin/poplar/driver/tools/inplace_util.h" #include "tensorflow/core/util/bcast.h" namespace xla { namespace poplarplugin { namespace helper { std::vector<poplar::Tensor> GetTensorsFromExpressionInputs( ExpressionInputs& expression_inputs) { std::vector<poplar::Tensor> tensors; for (auto& expression_input : expression_inputs) { if (expression_input.tensor) { tensors.push_back(*expression_input.tensor); } } return tensors; } namespace { // Get the input tensor and create a PlaceHolder Expression. StatusOr<ExpressionInput> GetTensorInput(CompilerResources& res, const HloInstruction* inst, TensorMap& tensor_map, int64 operand_idx, int64 input_idx, poplar::program::Sequence& seq) { poplar::Tensor tensor; // Check whether this is the inplace input to the elementwise operation. bool inplace_input = false; HloInstructionDescription description(inst); if (description.IsInplaceType()) { const auto inplace_operands = description.GetInplaceOperandIndexes(); CHECK_EQ(inplace_operands.size(), 1); inplace_input = inplace_operands[0] == input_idx; } if (inplace_input && AreInplaceOutputTensorsWritable(tensor_map, res, inst)) { TF_ASSIGN_OR_RETURN( TensorVectors inputs, FindInplaceOutputTensors(tensor_map, res, inst, seq, false)); CHECK_EQ(inputs.size(), 1); CHECK_EQ(inputs[0].size(), 1); tensor = inputs[0][0]; } else { TF_ASSIGN_OR_RETURN(tensor, FindInstructionInput(tensor_map, res, inst, input_idx, seq, false)); } return ExpressionInput(tensor); } StatusOr<ExpressionInput> GetConstantInput(const HloInstruction* inst) { auto type = inst->shape().element_type(); switch (type) { #define GET_CONST_EXPRESSION(XLA_TYPE, NATIVE_TYPE) \ case XLA_TYPE: { \ TF_ASSIGN_OR_RETURN( \ auto val, LiteralScalarToNativeType<NATIVE_TYPE>(inst->literal())); \ return ExpressionInput(absl::make_unique<popops::expr::Const>(val)); \ } GET_CONST_EXPRESSION(PRED, bool) GET_CONST_EXPRESSION(S8, int8) GET_CONST_EXPRESSION(U8, uint8) GET_CONST_EXPRESSION(S16, int16) GET_CONST_EXPRESSION(U16, uint16) GET_CONST_EXPRESSION(S32, int32) GET_CONST_EXPRESSION(U32, uint32) GET_CONST_EXPRESSION(S64, int64) GET_CONST_EXPRESSION(U64, uint64) GET_CONST_EXPRESSION(F32, float) #undef GET_CONST_EXPRESSION case F16: { // Poplar doesn't support half as a native type, use the ConstHalf // expression. TF_ASSIGN_OR_RETURN(auto val, LiteralScalarToNativeType<float>(inst->literal())); return ExpressionInput(absl::make_unique<popops::expr::ConstHalf>(val)); } default: return xla::FailedPrecondition( "Unsupported primitive type %s.", primitive_util::LowercasePrimitiveTypeName(type).c_str()); } } StatusOr<ExpressionInput> GetElementwiseInput( CompilerResources& res, const HloInstruction* inst, TensorMap& tensor_map, int64 operand_idx, int64 input_idx, poplar::program::Sequence& seq) { if (inst->opcode() == HloOpcode::kFusion) { // Fusion indicates implicit broadcasting. const auto* root_inst = inst->fused_expression_root(); const auto* input = root_inst->operand(operand_idx); if (input->opcode() == HloOpcode::kBroadcast) { // We either have a broadcast of a constant or another tensor. if (input->operand(0)->opcode() == HloOpcode::kConstant) { // Input is a constant, create a constant popops expression. return GetConstantInput(input->operand(0)); } else { // Input is not constant. CHECK_EQ(input->operand(0)->opcode(), HloOpcode::kParameter); TF_ASSIGN_OR_RETURN( auto expr_input, GetTensorInput(res, inst, tensor_map, operand_idx, input_idx, seq)); // Broadcast the tensor internally to the right shape. TF_ASSIGN_OR_RETURN(expr_input.tensor, BroadcastTensor(*expr_input.tensor, input->shape(), input->dimensions())); return expr_input; } } else { // The input is not broadcasted - just get the tensor. CHECK_EQ(input->opcode(), HloOpcode::kParameter); return GetTensorInput(res, inst, tensor_map, operand_idx, input_idx, seq); } } else { // Explicit version - just get the tensor. return GetTensorInput(res, inst, tensor_map, operand_idx, input_idx, seq); } } } // namespace // Get the elementwise instruction when the instruction can be a fused // instruction indicating implicit broadcasting op. const HloInstruction* GetElementwiseOp(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kFusion ? inst->fused_expression_root() : inst; } // Get all the elementwise input expression and tensors. StatusOr<ExpressionInputs> GetElementwiseInputs( CompilerResources& res, const HloInstruction* inst, const std::vector<int64>& inputs_permutation, TensorMap& tensor_map, poplar::program::Sequence& seq) { auto operation = GetElementwiseOp(inst); // Go over all the inputs to the operation, and figure out what type they are. std::vector<ExpressionInput> expression_inputs; for (int64 operand_idx = 0, input_idx = 0; operand_idx != operation->operand_count(); ++operand_idx) { TF_ASSIGN_OR_RETURN(auto expression_input, GetElementwiseInput(res, inst, tensor_map, operand_idx, input_idx, seq)); expression_inputs.push_back(expression_input); if (expression_input.tensor) { input_idx++; } } // Now permute the expression and create placeholder expressions. // Note that popops placeholders start from 1. std::vector<ExpressionInput> permuted_expression_inputs; for (int64 i = 0, placeholder_idx = 1; i != operation->operand_count(); ++i) { ExpressionInput& input = expression_inputs[inputs_permutation[i]]; if (input.tensor) { input.expr = absl::make_unique<popops::expr::PlaceHolder>(placeholder_idx++); } permuted_expression_inputs.push_back(input); } return permuted_expression_inputs; } } // namespace helper } // namespace poplarplugin } // namespace xla
41.049724
94
0.663122
[ "shape", "vector" ]
cb922ba809b143f4b701147a1321ad3842a132cb
3,531
hpp
C++
include/osmium/io/reader_with_progress_bar.hpp
xipengwang/libosmium
c7f136fb9c6df1c98c166944f0ab9673683e47a8
[ "BSL-1.0" ]
null
null
null
include/osmium/io/reader_with_progress_bar.hpp
xipengwang/libosmium
c7f136fb9c6df1c98c166944f0ab9673683e47a8
[ "BSL-1.0" ]
null
null
null
include/osmium/io/reader_with_progress_bar.hpp
xipengwang/libosmium
c7f136fb9c6df1c98c166944f0ab9673683e47a8
[ "BSL-1.0" ]
null
null
null
#ifndef OSMIUM_IO_READER_WITH_PROGRESS_BAR_HPP #define OSMIUM_IO_READER_WITH_PROGRESS_BAR_HPP /* This file is part of Osmium (https://osmcode.org/libosmium). Copyright 2013-2021 Jochen Topf <jochen@topf.org> and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <osmium/io/input_iterator.hpp> #include <osmium/io/reader.hpp> #include <osmium/memory/buffer.hpp> #include <osmium/util/progress_bar.hpp> namespace osmium { namespace io { /** * Wraps an osmium::io::Reader and an osmium::ProgressBar into * one handy package. */ class ReaderWithProgressBar : public Reader { ProgressBar m_progress_bar; public: /** * Constructor. * * @param enable Enable flag for the progress bar. * * All other parameters are forwarded to the Reader. */ template <typename... TArgs> explicit ReaderWithProgressBar(bool enable, TArgs&&... args) : Reader(std::forward<TArgs>(args)...), m_progress_bar(file_size(), enable) { } /** * Read a buffer from the Reader updating the progress bar in * the process. */ osmium::memory::Buffer read() { auto buffer = Reader::read(); if (buffer) { m_progress_bar.update(offset()); } else { m_progress_bar.done(); } return buffer; } /// Get the underlying ProgressBar object. ProgressBar& progress_bar() noexcept { return m_progress_bar; } }; // class ReaderWithProgressBar inline InputIterator<ReaderWithProgressBar> begin(ReaderWithProgressBar& reader) { return InputIterator<ReaderWithProgressBar>(reader); } inline InputIterator<ReaderWithProgressBar> end(ReaderWithProgressBar& /*reader*/) { return InputIterator<ReaderWithProgressBar>(); } } // namespace io } // namespace osmium #endif // OSMIUM_IO_READER_WITH_PROGRESS_BAR_HPP
34.617647
92
0.661003
[ "object" ]
cb9488b136a353a97e2de64df15158dfabd6de1d
30,040
cxx
C++
Qt/Components/pqCompositeDataInformationTreeModel.cxx
julin/ParaView
9fef46947144411ac97da38b8101ae56e1f3cb3a
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Qt/Components/pqCompositeDataInformationTreeModel.cxx
julin/ParaView
9fef46947144411ac97da38b8101ae56e1f3cb3a
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Qt/Components/pqCompositeDataInformationTreeModel.cxx
julin/ParaView
9fef46947144411ac97da38b8101ae56e1f3cb3a
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: ParaView Module: pqCompositeDataInformationTreeModel.cxx Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc. All rights reserved. ParaView is a free software; you can redistribute it and/or modify it under the terms of the ParaView license version 1.2. See License_v1.2.txt for the full ParaView license. A copy of this license can be obtained by contacting Kitware Inc. 28 Corporate Drive Clifton Park, NY 12065 USA 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 AUTHORS 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 "pqCompositeDataInformationTreeModel.h" #include "vtkDataObjectTypes.h" #include "vtkPVCompositeDataInformation.h" #include "vtkPVDataInformation.h" #include "vtkTimerLog.h" #include <QList> #include <QSet> #include <QStringList> #include <QtDebug> #include <cassert> #include <unordered_map> #include <vector> namespace pqCompositeDataInformationTreeModelNS { inline bool isroot(const QModelIndex& idx) { return (idx.isValid() && idx.internalId() == 0); } class CNode { QString Name; unsigned int Index; unsigned int LeafIndex; int DataType; int NumberOfPieces; CNode* Parent; std::vector<CNode> Children; std::pair<Qt::CheckState, bool> CheckState; // bool is true if value was explicitly set, // false, if value is inherited. Qt::CheckState ForceSetState; // for non-leaf nodes, since check-state changes based on children state, // we may loose the value that was explicitly // set. This helps us keep track of it. This is // only needed to supported `checkStates()` API. std::vector<std::pair<QVariant, bool> > CustomColumnState; // bool is true if value was explicitly set, // false, if value is inherited. void setChildrenCheckState( Qt::CheckState state, bool force, pqCompositeDataInformationTreeModel* dmodel) { for (auto iter = this->Children.begin(); iter != this->Children.end(); ++iter) { if (force == true || iter->CheckState.second == false) { iter->CheckState.first = state; iter->CheckState.second = false; // flag value as inherited. iter->setChildrenCheckState(state, force, dmodel); } } if (this->Children.size() > 0) { dmodel->dataChanged( this->Children.front().createIndex(dmodel), this->Children.back().createIndex(dmodel)); } } void updateCheckState(pqCompositeDataInformationTreeModel* dmodel) { int state = 0; for (auto iter = this->Children.begin(); iter != this->Children.end(); ++iter) { switch (iter->CheckState.first) { case Qt::Unchecked: state |= 0x01; break; case Qt::PartiallyChecked: state |= 0x02; break; case Qt::Checked: state |= 0x04; break; } } Qt::CheckState target; switch (state) { case 0x01: case 0: target = Qt::Unchecked; break; case 0x04: target = Qt::Checked; break; case 0x02: default: target = Qt::PartiallyChecked; } if (this->CheckState.first != target) { this->CheckState.first = target; if (this->Parent) { this->Parent->updateCheckState(dmodel); } QModelIndex idx = this->createIndex(dmodel); dmodel->dataChanged(idx, idx); } } public: CNode() : Index(VTK_UNSIGNED_INT_MAX) , LeafIndex(VTK_UNSIGNED_INT_MAX) , DataType(0) , NumberOfPieces(-1) , Parent(nullptr) , CheckState(Qt::Unchecked, false) , ForceSetState(Qt::Unchecked) , CustomColumnState() { } ~CNode() {} static CNode& nullNode() { static CNode NullNode; return NullNode; } bool operator==(const CNode& other) const { return this->Name == other.Name && this->Index == other.Index && this->DataType == other.DataType && this->NumberOfPieces == other.NumberOfPieces && this->Parent == other.Parent && this->Children == other.Children; } bool operator!=(const CNode& other) const { return !(*this == other); } void reset() { (*this) = CNode::nullNode(); } int childrenCount() const { return this->NumberOfPieces >= 0 ? this->NumberOfPieces : static_cast<int>(this->Children.size()); } QModelIndex createIndex(const pqCompositeDataInformationTreeModel* dmodel, int col = 0) const { if (this->Parent) { return dmodel->createIndex( this->Parent->childIndex(*this), col, static_cast<quintptr>(this->flatIndex())); } else { return dmodel->createIndex(0, col, static_cast<quintptr>(0)); } } inline unsigned int flatIndex() const { return this->Index; } inline unsigned int leafIndex() const { return this->LeafIndex; } inline const QString& name() const { return this->Name; } QString dataTypeAsString() const { return this->DataType == -1 ? "Unknown" : vtkDataObjectTypes::GetClassNameFromTypeId(this->DataType); } CNode& child(int idx) { return idx < static_cast<int>(this->Children.size()) ? this->Children[idx] : CNode::nullNode(); } const CNode& child(int idx) const { return idx < static_cast<int>(this->Children.size()) ? this->Children[idx] : CNode::nullNode(); } int childIndex(const CNode& achild) const { for (size_t cc = 0, max = this->Children.size(); cc < max; ++cc) { if (this->Children[cc] == achild) { return static_cast<int>(cc); } } return 0; } const CNode& parent() const { return this->Parent ? *this->Parent : CNode::nullNode(); } Qt::CheckState checkState() const { return this->CheckState.first; } bool setChecked(bool val, bool force, pqCompositeDataInformationTreeModel* dmodel) { if ((val == true && this->CheckState.first != Qt::Checked) || (val == false && this->CheckState.first != Qt::Unchecked)) { if (force == true || this->CheckState.second == false) { this->CheckState.first = val ? Qt::Checked : Qt::Unchecked; this->ForceSetState = this->CheckState.first; this->CheckState.second = true; this->setChildrenCheckState(this->CheckState.first, force, dmodel); if (this->Parent) { this->Parent->updateCheckState(dmodel); } QModelIndex idx = this->createIndex(dmodel); dmodel->dataChanged(idx, idx); return true; } } return false; } void markCheckedStateAsInherited() { this->CheckState.second = false; } void checkedNodes(QSet<unsigned int>& set, bool leaves_only) const { if (this->checkState() == Qt::Unchecked) { // do nothing. } else if (this->checkState() == Qt::Checked && (leaves_only == false || this->Children.size() == 0)) { set.insert(this->flatIndex()); } else { // partially checked or (leaves_only==true and non-leaf node). for (auto iter = this->Children.begin(); iter != this->Children.end(); ++iter) { iter->checkedNodes(set, leaves_only); } } } void checkStates(QList<QPair<unsigned int, bool> >& states) const { // add any explicitly toggled nodes to the "states". if (this->CheckState.second) { states.push_back(QPair<unsigned int, bool>(this->flatIndex(), this->ForceSetState)); } for (auto iter = this->Children.begin(); iter != this->Children.end(); ++iter) { iter->checkStates(states); } } const QVariant& customColumnState(int col) const { Q_ASSERT(col >= 0 && col < static_cast<int>(this->CustomColumnState.size())); return this->CustomColumnState[col].first; } bool isCustomColumnStateInherited(int col) const { if (col >= 0 && col < static_cast<int>(this->CustomColumnState.size())) { return (this->CustomColumnState[col].second == false); } return true; } // Set custom column state for a specific node. If `value` is invalid, then // it's treated as unset (or default). Setting a value will propagate the // value to all children who haven't explicitly overridden the value // themselves. To force set on all children, pass `force` as true. If value it // set to `invalid` it acts are clearing the column state. void setCustomColumnState( int col, const QVariant& value, bool force, pqCompositeDataInformationTreeModel* dmodel) { Q_ASSERT(col >= 0 && col < static_cast<int>(this->CustomColumnState.size())); std::pair<QVariant, bool>& value_pair = this->CustomColumnState[col]; if (value_pair.first != value) { value_pair.first = value; QModelIndex idx = this->createIndex(dmodel, col + 1); dmodel->dataChanged(idx, idx); } // flag that this value was explicitly set, unless value is invalid -- which // acts as value being cleared. value_pair.second = value.isValid() ? true : false; // if value is invalid i.e. the value is being cleared then we // fetch the value from the parent. This makes sense since in such a case, // the value would indeed be inherited from the parent. if (!value.isValid() && this->Parent != nullptr) { value_pair.first = this->Parent->CustomColumnState[col].first; } // now, propagate over all children and pass this value. for (auto citer = this->Children.begin(); citer != this->Children.end(); ++citer) { CNode& child = (*citer); if (force == true || child.CustomColumnState[col].second == false) { child.setCustomColumnState(col, value_pair.first, force, dmodel); child.CustomColumnState[col].second = false; // since the value is inherited. } } } void customColumnStates(int col, QList<QPair<unsigned int, QVariant> >& values) const { Q_ASSERT(col >= 0 && col < static_cast<int>(this->CustomColumnState.size())); const std::pair<QVariant, bool>& value_pair = this->CustomColumnState[col]; // add explicitly set values. if (value_pair.first.isValid() && value_pair.second) { values.push_back(QPair<unsigned int, QVariant>(this->flatIndex(), value_pair.first)); } // iterate over children to do the same. for (auto iter = this->Children.begin(); iter != this->Children.end(); ++iter) { iter->customColumnStates(col, values); } } bool build(vtkPVDataInformation* info, bool expand_multi_piece, unsigned int& index, unsigned int& leaf_index, int custom_column_count, std::unordered_map<unsigned int, CNode*>& lookupMap) { this->reset(); this->Index = index++; lookupMap[this->Index] = this; if (info == nullptr || info->GetCompositeDataClassName() == 0) { this->Name = info != nullptr ? info->GetPrettyDataTypeString() : "(empty)"; this->DataType = info != nullptr ? info->GetDataSetType() : -1; this->CustomColumnState.resize(custom_column_count); this->LeafIndex = leaf_index++; return false; } this->Name = info->GetPrettyDataTypeString(); this->DataType = info->GetCompositeDataSetType(); this->CustomColumnState.resize(custom_column_count); vtkPVCompositeDataInformation* cinfo = info->GetCompositeDataInformation(); bool is_amr = (this->DataType == VTK_HIERARCHICAL_DATA_SET || this->DataType == VTK_HIERARCHICAL_BOX_DATA_SET || this->DataType == VTK_UNIFORM_GRID_AMR || this->DataType == VTK_NON_OVERLAPPING_AMR || this->DataType == VTK_OVERLAPPING_AMR); bool is_multipiece = cinfo->GetDataIsMultiPiece() != 0; if (!is_multipiece || expand_multi_piece) { this->Children.resize(cinfo->GetNumberOfChildren()); for (unsigned int cc = 0, max = cinfo->GetNumberOfChildren(); cc < max; ++cc) { CNode& childNode = this->Children[cc]; childNode.build(cinfo->GetDataInformation(cc), expand_multi_piece, index, leaf_index, custom_column_count, lookupMap); // note: build() will reset childNode, so don't set any ivars before calling it. childNode.Parent = this; // if Name for block was provided, use that instead of the data type. const char* name = cinfo->GetName(cc); if (name && name[0]) { childNode.Name = name; } else if (is_multipiece) { childNode.Name = QString("Dataset %1").arg(cc); } else if (is_amr) { childNode.Name = QString("Level %1").arg(cc); } } } else if (is_multipiece) { index += cinfo->GetNumberOfChildren(); this->LeafIndex = leaf_index; // move leaf_index forward by however many pieces this multipiece dataset // has. leaf_index += cinfo->GetNumberOfChildren(); } return true; } }; } using namespace pqCompositeDataInformationTreeModelNS; class pqCompositeDataInformationTreeModel::pqInternals { public: pqInternals() {} ~pqInternals() {} static CNode& nullNode() { return CNode::nullNode(); } CNode& find(const QModelIndex& idx) { if (!idx.isValid()) { return nullNode(); } unsigned int findex = static_cast<unsigned int>(idx.internalId()); return this->find(findex); } inline CNode& find(unsigned int findex) { auto iter = this->CNodeMap.find(findex); return (iter != this->CNodeMap.end()) ? (*iter->second) : nullNode(); } /** * Builds the data-structure using vtkPVDataInformation (may be null). * @returns true if the info refers to a composite dataset otherwise returns * false. */ bool build(vtkPVDataInformation* info, bool expand_multi_piece) { unsigned int index = 0; unsigned int leaf_index = 0; this->CNodeMap.clear(); bool retVal = this->Root.build( info, expand_multi_piece, index, leaf_index, this->CustomColumns.size(), this->CNodeMap); return retVal; } CNode& rootNode() { return this->Root; } void clearCheckState(pqCompositeDataInformationTreeModel* dmodel) { this->Root.setChecked(dmodel->defaultCheckState(), true, dmodel); this->Root .markCheckedStateAsInherited(); // this avoid us interpreting the value as explicitly set. } int addColumn(const QString& propertyName) { this->CustomColumns.push_back(propertyName); return this->CustomColumns.size() - 1; } const QStringList& customColumns() const { return this->CustomColumns; } void clearColumns() { this->CustomColumns.clear(); } int customColumnIndex(const QString& pname) const { return this->CustomColumns.indexOf(pname); } private: CNode Root; QStringList CustomColumns; std::unordered_map<unsigned int, CNode*> CNodeMap; }; //----------------------------------------------------------------------------- pqCompositeDataInformationTreeModel::pqCompositeDataInformationTreeModel(QObject* parentObject) : Superclass(parentObject) , Internals(new pqCompositeDataInformationTreeModel::pqInternals()) , UserCheckable(false) , ExpandMultiPiece(false) , Exclusivity(false) , DefaultCheckState(false) { } //----------------------------------------------------------------------------- pqCompositeDataInformationTreeModel::~pqCompositeDataInformationTreeModel() { } //----------------------------------------------------------------------------- int pqCompositeDataInformationTreeModel::columnCount(const QModelIndex&) const { pqInternals& internals = (*this->Internals); return 1 + internals.customColumns().size(); } //----------------------------------------------------------------------------- int pqCompositeDataInformationTreeModel::rowCount(const QModelIndex& parentIdx) const { if (!parentIdx.isValid()) { // return number of top-level items. return 1; } pqInternals& internals = (*this->Internals); const CNode& node = internals.find(parentIdx); assert(node.childrenCount() >= 0); return node.childrenCount(); } //----------------------------------------------------------------------------- QModelIndex pqCompositeDataInformationTreeModel::index( int row, int column, const QModelIndex& parentIdx) const { if (!parentIdx.isValid() && row == 0) { return this->createIndex(0, column, static_cast<quintptr>(0)); } if (row < 0 || column < 0 || column >= this->columnCount()) { return QModelIndex(); } pqInternals& internals = (*this->Internals); const CNode& node = internals.find(parentIdx); const CNode& child = node.child(row); return this->createIndex(row, column, static_cast<quintptr>(child.flatIndex())); } //----------------------------------------------------------------------------- QModelIndex pqCompositeDataInformationTreeModel::parent(const QModelIndex& idx) const { if (!idx.isValid() || isroot(idx)) { return QModelIndex(); } pqInternals& internals = (*this->Internals); const CNode& node = internals.find(idx); const CNode& parentNode = node.parent(); if (parentNode == CNode::nullNode()) { return QModelIndex(); } if (parentNode == internals.rootNode()) { return this->createIndex(0, 0, static_cast<quintptr>(0)); } const CNode& parentsParentNode = parentNode.parent(); return this->createIndex( parentsParentNode.childIndex(parentNode), 0, static_cast<quintptr>(parentNode.flatIndex())); } //----------------------------------------------------------------------------- QVariant pqCompositeDataInformationTreeModel::data(const QModelIndex& idx, int role) const { if (!idx.isValid()) { return QVariant(); } // short-circuit roles we don't care about. switch (role) { case Qt::DisplayRole: case Qt::ToolTipRole: case Qt::CheckStateRole: case ValueInheritedRole: case LeafIndexRole: break; case CompositeIndexRole: return this->compositeIndex(idx); default: return QVariant(); } pqInternals& internals = (*this->Internals); const CNode& node = internals.find(idx); if (node == CNode::nullNode()) { return QVariant(); } int col = idx.column(); if (col == 0) { switch (role) { case Qt::DisplayRole: return node.name(); case Qt::ToolTipRole: return QString("<b>Name</b>: %1<br/><b>Type</b>: %2") .arg(node.name()) .arg(node.dataTypeAsString()); case Qt::CheckStateRole: return this->UserCheckable ? QVariant(node.checkState()) : QVariant(); case LeafIndexRole: return node.leafIndex() != VTK_UNSIGNED_INT_MAX ? QVariant(node.leafIndex()) : QVariant(); } } else { col--; // since 0 is non-custom column. switch (role) { case Qt::DisplayRole: return node.customColumnState(col); case ValueInheritedRole: return node.isCustomColumnStateInherited(col); case LeafIndexRole: return node.leafIndex() != VTK_UNSIGNED_INT_MAX ? QVariant(node.leafIndex()) : QVariant(); } } return QVariant(); } //----------------------------------------------------------------------------- Qt::ItemFlags pqCompositeDataInformationTreeModel::flags(const QModelIndex& idx) const { Qt::ItemFlags pflags = this->Superclass::flags(idx); if (this->UserCheckable && idx.column() == 0) { pflags |= Qt::ItemIsUserCheckable | Qt::ItemIsTristate; } // can't use Qt::ItemIsAutoTristate till we drop support for Qt 4 :(. return pflags; } //----------------------------------------------------------------------------- bool pqCompositeDataInformationTreeModel::setData( const QModelIndex& idx, const QVariant& value, int role) { if (!idx.isValid()) { return false; } if ((idx.column() == 0 && role != Qt::CheckStateRole) || (idx.column() > 0 && role != Qt::DisplayRole)) { return false; } pqInternals& internals = (*this->Internals); CNode& node = internals.find(idx); if (node == CNode::nullNode()) { return false; } if (idx.column() == 0 && role == Qt::CheckStateRole) { Qt::CheckState checkState = value.value<Qt::CheckState>(); if (checkState == Qt::Checked && this->exclusivity()) { internals.clearCheckState(this); } node.setChecked(checkState == Qt::Checked, true, this); return true; } else if (idx.column() > 0 && role == Qt::DisplayRole) { int col = idx.column() - 1; node.setCustomColumnState(col, value, /*force=*/false, this); } return false; } //----------------------------------------------------------------------------- QVariant pqCompositeDataInformationTreeModel::headerData( int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && section == 0 && role == Qt::DisplayRole) { return this->HeaderLabel; } return this->Superclass::headerData(section, orientation, role); } //----------------------------------------------------------------------------- bool pqCompositeDataInformationTreeModel::setHeaderData( int section, Qt::Orientation orientation, const QVariant& value, int role) { if (orientation == Qt::Horizontal && section == 0 && role == Qt::DisplayRole) { this->HeaderLabel = value.toString(); emit this->headerDataChanged(orientation, section, section); return true; } return this->Superclass::setHeaderData(section, orientation, value, role); } //----------------------------------------------------------------------------- bool pqCompositeDataInformationTreeModel::reset(vtkPVDataInformation* info) { vtkTimerLogScope mark("pqCompositeDataInformationTreeModel::reset"); (void)mark; pqInternals& internals = (*this->Internals); this->beginResetModel(); bool retVal = internals.build(info, this->ExpandMultiPiece); internals.clearCheckState(this); this->endResetModel(); return retVal; } //----------------------------------------------------------------------------- void pqCompositeDataInformationTreeModel::setChecked(const QList<unsigned int>& indices) { pqInternals& internals = (*this->Internals); internals.clearCheckState(this); foreach (unsigned int findex, indices) { CNode& node = internals.find(findex); node.setChecked(true, true, this); } } //----------------------------------------------------------------------------- QList<unsigned int> pqCompositeDataInformationTreeModel::checkedNodes() const { QSet<unsigned int> indices; pqInternals& internals = (*this->Internals); internals.rootNode().checkedNodes(indices, false); return indices.toList(); } //----------------------------------------------------------------------------- QList<unsigned int> pqCompositeDataInformationTreeModel::checkedLeaves() const { QSet<unsigned int> indices; pqInternals& internals = (*this->Internals); internals.rootNode().checkedNodes(indices, true); return indices.toList(); } //----------------------------------------------------------------------------- QList<QPair<unsigned int, bool> > pqCompositeDataInformationTreeModel::checkStates() const { QList<QPair<unsigned int, bool> > states; pqInternals& internals = (*this->Internals); internals.rootNode().checkStates(states); return states; } //----------------------------------------------------------------------------- void pqCompositeDataInformationTreeModel::setCheckStates( const QList<QPair<unsigned int, bool> >& states) { pqInternals& internals = (*this->Internals); internals.clearCheckState(this); for (auto iter = states.begin(); iter != states.end(); ++iter) { CNode& node = internals.find(iter->first); if (node != CNode::nullNode()) { node.setChecked(iter->second, /*force=*/false, this); } } } //----------------------------------------------------------------------------- QList<unsigned int> pqCompositeDataInformationTreeModel::checkedLevels() const { QList<unsigned int> indices; pqInternals& internals = (*this->Internals); CNode& root = internals.rootNode(); for (int cc = 0; cc < root.childrenCount(); cc++) { if (root.child(cc).checkState() == Qt::Checked) { indices.push_back(static_cast<unsigned int>(cc)); } } return indices; } //----------------------------------------------------------------------------- void pqCompositeDataInformationTreeModel::setCheckedLevels(const QList<unsigned int>& indices) { pqInternals& internals = (*this->Internals); internals.clearCheckState(this); CNode& root = internals.rootNode(); unsigned int childrenCount = static_cast<unsigned int>(root.childrenCount()); foreach (unsigned int idx, indices) { if (idx < childrenCount) { root.child(idx).setChecked(true, true, this); } } } //----------------------------------------------------------------------------- QList<QPair<unsigned int, unsigned int> > pqCompositeDataInformationTreeModel::checkedLevelDatasets() const { QList<QPair<unsigned int, unsigned int> > indices; pqInternals& internals = (*this->Internals); CNode& root = internals.rootNode(); for (int level = 0; level < root.childrenCount(); ++level) { CNode& levelNode = root.child(level); for (int ds = 0; ds < levelNode.childrenCount(); ++ds) { if (levelNode.child(ds).checkState() == Qt::Checked) { indices.push_back(QPair<unsigned int, unsigned int>(level, ds)); } } } return indices; } //----------------------------------------------------------------------------- void pqCompositeDataInformationTreeModel::setCheckedLevelDatasets( const QList<QPair<unsigned int, unsigned int> >& indices) { pqInternals& internals = (*this->Internals); internals.clearCheckState(this); CNode& root = internals.rootNode(); unsigned int numLevels = static_cast<unsigned int>(root.childrenCount()); typedef QPair<unsigned int, unsigned int> IdxPair; foreach (const IdxPair& idx, indices) { if (idx.first < numLevels) { CNode& level = root.child(idx.first); if (idx.second < static_cast<unsigned int>(level.childrenCount())) { level.child(idx.second).setChecked(true, true, this); } } } } //----------------------------------------------------------------------------- unsigned int pqCompositeDataInformationTreeModel::compositeIndex(const QModelIndex& idx) const { if (idx.isValid() && idx.model() == this) { return static_cast<unsigned int>(idx.internalId()); } return 0; } //----------------------------------------------------------------------------- QModelIndex pqCompositeDataInformationTreeModel::find(unsigned int idx) const { pqInternals& internals = (*this->Internals); CNode& node = internals.find(idx); if (node != CNode::nullNode()) { return node.createIndex(this); } return QModelIndex(); } //----------------------------------------------------------------------------- const QModelIndex pqCompositeDataInformationTreeModel::rootIndex() const { return this->createIndex(0, 0, static_cast<quintptr>(0)); } //----------------------------------------------------------------------------- int pqCompositeDataInformationTreeModel::addColumn(const QString& propertyName) { pqInternals& internals = (*this->Internals); // since 1st column on the model is non-custom, we offset by 1. return internals.addColumn(propertyName) + 1; } //----------------------------------------------------------------------------- int pqCompositeDataInformationTreeModel::columnIndex(const QString& propertyName) { pqInternals& internals = (*this->Internals); int idx = internals.customColumnIndex(propertyName); return idx >= 0 ? (idx + 1) : -1; } //----------------------------------------------------------------------------- void pqCompositeDataInformationTreeModel::clearColumns() { pqInternals& internals = (*this->Internals); internals.clearColumns(); } //----------------------------------------------------------------------------- void pqCompositeDataInformationTreeModel::setColumnStates( const QString& pname, const QList<QPair<unsigned int, QVariant> >& values) { pqInternals& internals = (*this->Internals); int col = internals.customColumnIndex(pname); if (col < 0) { qCritical() << "Unknown property: " << pname; return; } typedef QPair<unsigned int, QVariant> PairT; CNode& root = internals.rootNode(); // clear all values. root.setCustomColumnState(col, QVariant(), /*force=*/true, this); foreach (const PairT& pair, values) { CNode& node = internals.find(pair.first); if (node != CNode::nullNode()) { if (pair.second.isValid()) // invalid value is treated as cleared. { node.setCustomColumnState(col, pair.second, /*force=*/false, this); } } } } //----------------------------------------------------------------------------- QList<QPair<unsigned int, QVariant> > pqCompositeDataInformationTreeModel::columnStates( const QString& pname) const { QList<QPair<unsigned int, QVariant> > value; pqInternals& internals = (*this->Internals); int col = internals.customColumnIndex(pname); if (col < 0) { qCritical() << "Unknown property: " << pname; return value; } internals.rootNode().customColumnStates(col, value); return value; }
30.969072
99
0.610652
[ "vector", "model" ]
cb949873cfe2e1f677b53ee731ba1fc0c3418297
841
cpp
C++
easy/21. Merge Two Sorted Lists.cpp
xuan-415/leetcode
3777b12e6f574947506ec358108937f8be975289
[ "MIT" ]
null
null
null
easy/21. Merge Two Sorted Lists.cpp
xuan-415/leetcode
3777b12e6f574947506ec358108937f8be975289
[ "MIT" ]
null
null
null
easy/21. Merge Two Sorted Lists.cpp
xuan-415/leetcode
3777b12e6f574947506ec358108937f8be975289
[ "MIT" ]
null
null
null
#include<vector> #include<map> #include<string> #include<algorithm> #include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(l1 == NULL) return l2; if(l2 == NULL) return l1; if(l1->val > l2 -> val) swap(l1,l2); ListNode *res = l1; while(l1 != NULL && l2 != NULL){ ListNode * temp = NULL; while(l1 != NULL && (l1->val <= l2 -> val)){ temp = l1; l1 = l1 -> next; } temp -> next = l2; swap(l1,l2); } return res; } };
25.484848
59
0.501784
[ "vector" ]
cb95a0b63875ba76934308351ad8bfd377373612
15,112
cc
C++
cc/hybrid/hybrid_key_templates_test.cc
erka/tink
78b908124efbb34acc4de3ae11b41112cb41adb2
[ "Apache-2.0" ]
1
2019-01-08T16:38:47.000Z
2019-01-08T16:38:47.000Z
cc/hybrid/hybrid_key_templates_test.cc
erka/tink
78b908124efbb34acc4de3ae11b41112cb41adb2
[ "Apache-2.0" ]
1
2020-08-18T16:42:11.000Z
2020-08-25T16:13:11.000Z
cc/hybrid/hybrid_key_templates_test.cc
erka/tink
78b908124efbb34acc4de3ae11b41112cb41adb2
[ "Apache-2.0" ]
1
2020-11-30T06:38:02.000Z
2020-11-30T06:38:02.000Z
// Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// #include "tink/hybrid/hybrid_key_templates.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "tink/aead/aead_key_templates.h" #include "tink/hybrid/ecies_aead_hkdf_private_key_manager.h" #include "tink/hybrid/hybrid_config.h" #include "tink/util/test_matchers.h" #include "proto/common.pb.h" #include "proto/ecies_aead_hkdf.pb.h" #include "proto/tink.pb.h" namespace crypto { namespace tink { namespace { using google::crypto::tink::EciesAeadHkdfKeyFormat; using google::crypto::tink::EcPointFormat; using google::crypto::tink::EllipticCurveType; using google::crypto::tink::HashType; using google::crypto::tink::KeyTemplate; using google::crypto::tink::OutputPrefixType; using ::crypto::tink::test::IsOk; class HybridKeyTemplatesTest : public ::testing::Test { protected: static void SetUpTestSuite() { // Initialize the registry, so that the templates can be tested. ASSERT_THAT(HybridConfig::Register(), IsOk()); } }; TEST_F(HybridKeyTemplatesTest, testEciesAeadHkdf) { std::string type_url = "type.googleapis.com/google.crypto.tink.EciesAeadHkdfPrivateKey"; { // Test EciesP256HkdfHmacSha256Aes128Gcm(). // Check that returned template is correct. const KeyTemplate& key_template = HybridKeyTemplates::EciesP256HkdfHmacSha256Aes128Gcm(); EXPECT_EQ(type_url, key_template.type_url()); EXPECT_EQ(OutputPrefixType::TINK, key_template.output_prefix_type()); EciesAeadHkdfKeyFormat key_format; EXPECT_TRUE(key_format.ParseFromString(key_template.value())); EXPECT_EQ(EcPointFormat::UNCOMPRESSED, key_format.params().ec_point_format()); auto dem_params = key_format.mutable_params()->mutable_dem_params(); auto expected_dem = AeadKeyTemplates::Aes128Gcm(); EXPECT_EQ(expected_dem.output_prefix_type(), dem_params->aead_dem().output_prefix_type()); EXPECT_EQ(expected_dem.type_url(), dem_params->aead_dem().type_url()); EXPECT_EQ(expected_dem.value(), dem_params->aead_dem().value()); auto kem_params = key_format.mutable_params()->mutable_kem_params(); EXPECT_EQ(EllipticCurveType::NIST_P256, kem_params->curve_type()); EXPECT_EQ(HashType::SHA256, kem_params->hkdf_hash_type()); EXPECT_EQ("", kem_params->hkdf_salt()); // Check that reference to the same object is returned. const KeyTemplate& key_template_2 = HybridKeyTemplates::EciesP256HkdfHmacSha256Aes128Gcm(); EXPECT_EQ(&key_template, &key_template_2); // Check that the template works with the key manager. EciesAeadHkdfPrivateKeyManager key_manager; EXPECT_EQ(key_manager.get_key_type(), key_template.type_url()); EXPECT_THAT(key_manager.ValidateKeyFormat(key_format), IsOk()); } { // Test EciesP256HkdfHmacSha256Aes128GcmCompressedWithoutPrefix(). // Check that returned template is correct. const KeyTemplate& key_template = HybridKeyTemplates:: EciesP256HkdfHmacSha256Aes128GcmCompressedWithoutPrefix(); EXPECT_EQ(type_url, key_template.type_url()); EXPECT_EQ(OutputPrefixType::RAW, key_template.output_prefix_type()); EciesAeadHkdfKeyFormat key_format; EXPECT_TRUE(key_format.ParseFromString(key_template.value())); EXPECT_EQ(EcPointFormat::COMPRESSED, key_format.params().ec_point_format()); auto dem_params = key_format.mutable_params()->mutable_dem_params(); auto expected_dem = AeadKeyTemplates::Aes128Gcm(); EXPECT_EQ(expected_dem.output_prefix_type(), dem_params->aead_dem().output_prefix_type()); EXPECT_EQ(expected_dem.type_url(), dem_params->aead_dem().type_url()); EXPECT_EQ(expected_dem.value(), dem_params->aead_dem().value()); auto kem_params = key_format.mutable_params()->mutable_kem_params(); EXPECT_EQ(EllipticCurveType::NIST_P256, kem_params->curve_type()); EXPECT_EQ(HashType::SHA256, kem_params->hkdf_hash_type()); EXPECT_EQ("", kem_params->hkdf_salt()); // Check that reference to the same object is returned. const KeyTemplate& key_template_2 = HybridKeyTemplates:: EciesP256HkdfHmacSha256Aes128GcmCompressedWithoutPrefix(); EXPECT_EQ(&key_template, &key_template_2); // Check that the template works with the key manager. EciesAeadHkdfPrivateKeyManager key_manager; EXPECT_EQ(key_manager.get_key_type(), key_template.type_url()); EXPECT_THAT(key_manager.ValidateKeyFormat(key_format), IsOk()); } { // Test EciesP256HkdfHmacSha256Aes128CtrHmacSha256(). // Check that returned template is correct. const KeyTemplate& key_template = HybridKeyTemplates::EciesP256HkdfHmacSha256Aes128CtrHmacSha256(); EXPECT_EQ(type_url, key_template.type_url()); EXPECT_EQ(OutputPrefixType::TINK, key_template.output_prefix_type()); EciesAeadHkdfKeyFormat key_format; EXPECT_TRUE(key_format.ParseFromString(key_template.value())); EXPECT_EQ(EcPointFormat::UNCOMPRESSED, key_format.params().ec_point_format()); auto dem_params = key_format.mutable_params()->mutable_dem_params(); auto expected_dem = AeadKeyTemplates::Aes128CtrHmacSha256(); EXPECT_EQ(expected_dem.output_prefix_type(), dem_params->aead_dem().output_prefix_type()); EXPECT_EQ(expected_dem.type_url(), dem_params->aead_dem().type_url()); EXPECT_EQ(expected_dem.value(), dem_params->aead_dem().value()); auto kem_params = key_format.mutable_params()->mutable_kem_params(); EXPECT_EQ(EllipticCurveType::NIST_P256, kem_params->curve_type()); EXPECT_EQ(HashType::SHA256, kem_params->hkdf_hash_type()); EXPECT_EQ("", kem_params->hkdf_salt()); // Check that reference to the same object is returned. const KeyTemplate& key_template_2 = HybridKeyTemplates::EciesP256HkdfHmacSha256Aes128CtrHmacSha256(); EXPECT_EQ(&key_template, &key_template_2); // Check that the template works with the key manager. EciesAeadHkdfPrivateKeyManager key_manager; EXPECT_EQ(key_manager.get_key_type(), key_template.type_url()); EXPECT_THAT(key_manager.ValidateKeyFormat(key_format), IsOk()); } { // Test EciesP256CompressedHkdfHmacSha256Aes128Gcm(). // Check that returned template is correct. const KeyTemplate& key_template = HybridKeyTemplates::EciesP256CompressedHkdfHmacSha256Aes128Gcm(); EXPECT_EQ(type_url, key_template.type_url()); EXPECT_EQ(OutputPrefixType::TINK, key_template.output_prefix_type()); EciesAeadHkdfKeyFormat key_format; EXPECT_TRUE(key_format.ParseFromString(key_template.value())); EXPECT_EQ(EcPointFormat::COMPRESSED, key_format.params().ec_point_format()); auto dem_params = key_format.mutable_params()->mutable_dem_params(); auto expected_dem = AeadKeyTemplates::Aes128Gcm(); EXPECT_EQ(expected_dem.output_prefix_type(), dem_params->aead_dem().output_prefix_type()); EXPECT_EQ(expected_dem.type_url(), dem_params->aead_dem().type_url()); EXPECT_EQ(expected_dem.value(), dem_params->aead_dem().value()); auto kem_params = key_format.mutable_params()->mutable_kem_params(); EXPECT_EQ(EllipticCurveType::NIST_P256, kem_params->curve_type()); EXPECT_EQ(HashType::SHA256, kem_params->hkdf_hash_type()); EXPECT_EQ("", kem_params->hkdf_salt()); // Check that reference to the same object is returned. const KeyTemplate& key_template_2 = HybridKeyTemplates::EciesP256CompressedHkdfHmacSha256Aes128Gcm(); EXPECT_EQ(&key_template, &key_template_2); // Check that the template works with the key manager. EciesAeadHkdfPrivateKeyManager key_manager; EXPECT_EQ(key_manager.get_key_type(), key_template.type_url()); EXPECT_THAT(key_manager.ValidateKeyFormat(key_format), IsOk()); } { // Test EciesP256CompressedHkdfHmacSha256Aes128CtrHmacSha256(). // Check that returned template is correct. const KeyTemplate& key_template = HybridKeyTemplates:: EciesP256CompressedHkdfHmacSha256Aes128CtrHmacSha256(); EXPECT_EQ(type_url, key_template.type_url()); EXPECT_EQ(OutputPrefixType::TINK, key_template.output_prefix_type()); EciesAeadHkdfKeyFormat key_format; EXPECT_TRUE(key_format.ParseFromString(key_template.value())); EXPECT_EQ(EcPointFormat::COMPRESSED, key_format.params().ec_point_format()); auto dem_params = key_format.mutable_params()->mutable_dem_params(); auto expected_dem = AeadKeyTemplates::Aes128CtrHmacSha256(); EXPECT_EQ(expected_dem.output_prefix_type(), dem_params->aead_dem().output_prefix_type()); EXPECT_EQ(expected_dem.type_url(), dem_params->aead_dem().type_url()); EXPECT_EQ(expected_dem.value(), dem_params->aead_dem().value()); auto kem_params = key_format.mutable_params()->mutable_kem_params(); EXPECT_EQ(EllipticCurveType::NIST_P256, kem_params->curve_type()); EXPECT_EQ(HashType::SHA256, kem_params->hkdf_hash_type()); EXPECT_EQ("", kem_params->hkdf_salt()); // Check that reference to the same object is returned. const KeyTemplate& key_template_2 = HybridKeyTemplates:: EciesP256CompressedHkdfHmacSha256Aes128CtrHmacSha256(); EXPECT_EQ(&key_template, &key_template_2); // Check that the template works with the key manager. EciesAeadHkdfPrivateKeyManager key_manager; EXPECT_EQ(key_manager.get_key_type(), key_template.type_url()); EXPECT_THAT(key_manager.ValidateKeyFormat(key_format), IsOk()); } { // Test EciesX25519HkdfHmacSha256Aes128Gcm(). // Check that returned template is correct. const KeyTemplate& key_template = HybridKeyTemplates::EciesX25519HkdfHmacSha256Aes128Gcm(); EXPECT_EQ(type_url, key_template.type_url()); EXPECT_EQ(OutputPrefixType::TINK, key_template.output_prefix_type()); EciesAeadHkdfKeyFormat key_format; EXPECT_TRUE(key_format.ParseFromString(key_template.value())); EXPECT_EQ(EcPointFormat::COMPRESSED, key_format.params().ec_point_format()); auto dem_params = key_format.mutable_params()->mutable_dem_params(); auto expected_dem = AeadKeyTemplates::Aes128Gcm(); EXPECT_EQ(expected_dem.output_prefix_type(), dem_params->aead_dem().output_prefix_type()); EXPECT_EQ(expected_dem.type_url(), dem_params->aead_dem().type_url()); EXPECT_EQ(expected_dem.value(), dem_params->aead_dem().value()); auto kem_params = key_format.mutable_params()->mutable_kem_params(); EXPECT_EQ(EllipticCurveType::CURVE25519, kem_params->curve_type()); EXPECT_EQ(HashType::SHA256, kem_params->hkdf_hash_type()); EXPECT_EQ("", kem_params->hkdf_salt()); // Check that reference to the same object is returned. const KeyTemplate& key_template_2 = HybridKeyTemplates::EciesX25519HkdfHmacSha256Aes128Gcm(); EXPECT_EQ(&key_template, &key_template_2); // Check that the template works with the key manager. EciesAeadHkdfPrivateKeyManager key_manager; EXPECT_EQ(key_manager.get_key_type(), key_template.type_url()); EXPECT_THAT(key_manager.ValidateKeyFormat(key_format), IsOk()); } { // Test EciesX25519HkdfHmacSha256Aes128CtrHmacSha256(). // Check that returned template is correct. const KeyTemplate& key_template = HybridKeyTemplates::EciesX25519HkdfHmacSha256Aes128CtrHmacSha256(); EXPECT_EQ(type_url, key_template.type_url()); EXPECT_EQ(OutputPrefixType::TINK, key_template.output_prefix_type()); EciesAeadHkdfKeyFormat key_format; EXPECT_TRUE(key_format.ParseFromString(key_template.value())); EXPECT_EQ(EcPointFormat::COMPRESSED, key_format.params().ec_point_format()); auto dem_params = key_format.mutable_params()->mutable_dem_params(); auto expected_dem = AeadKeyTemplates::Aes128CtrHmacSha256(); EXPECT_EQ(expected_dem.output_prefix_type(), dem_params->aead_dem().output_prefix_type()); EXPECT_EQ(expected_dem.type_url(), dem_params->aead_dem().type_url()); EXPECT_EQ(expected_dem.value(), dem_params->aead_dem().value()); auto kem_params = key_format.mutable_params()->mutable_kem_params(); EXPECT_EQ(EllipticCurveType::CURVE25519, kem_params->curve_type()); EXPECT_EQ(HashType::SHA256, kem_params->hkdf_hash_type()); EXPECT_EQ("", kem_params->hkdf_salt()); // Check that reference to the same object is returned. const KeyTemplate& key_template_2 = HybridKeyTemplates::EciesX25519HkdfHmacSha256Aes128CtrHmacSha256(); EXPECT_EQ(&key_template, &key_template_2); // Check that the template works with the key manager. EciesAeadHkdfPrivateKeyManager key_manager; EXPECT_EQ(key_manager.get_key_type(), key_template.type_url()); EXPECT_THAT(key_manager.ValidateKeyFormat(key_format), IsOk()); } { // Test EciesX25519HkdfHmacSha256XChaCha20Poly1305(). // Check that returned template is correct. const KeyTemplate& key_template = HybridKeyTemplates::EciesX25519HkdfHmacSha256XChaCha20Poly1305(); EXPECT_EQ(type_url, key_template.type_url()); EXPECT_EQ(OutputPrefixType::TINK, key_template.output_prefix_type()); EciesAeadHkdfKeyFormat key_format; EXPECT_TRUE(key_format.ParseFromString(key_template.value())); EXPECT_EQ(EcPointFormat::COMPRESSED, key_format.params().ec_point_format()); auto dem_params = key_format.mutable_params()->mutable_dem_params(); auto expected_dem = AeadKeyTemplates::XChaCha20Poly1305(); EXPECT_EQ(expected_dem.output_prefix_type(), dem_params->aead_dem().output_prefix_type()); EXPECT_EQ(expected_dem.type_url(), dem_params->aead_dem().type_url()); EXPECT_EQ(expected_dem.value(), dem_params->aead_dem().value()); auto kem_params = key_format.mutable_params()->mutable_kem_params(); EXPECT_EQ(EllipticCurveType::CURVE25519, kem_params->curve_type()); EXPECT_EQ(HashType::SHA256, kem_params->hkdf_hash_type()); EXPECT_EQ("", kem_params->hkdf_salt()); // Check that reference to the same object is returned. const KeyTemplate& key_template_2 = HybridKeyTemplates::EciesX25519HkdfHmacSha256XChaCha20Poly1305(); EXPECT_EQ(&key_template, &key_template_2); // Check that the template works with the key manager. EciesAeadHkdfPrivateKeyManager key_manager; EXPECT_EQ(key_manager.get_key_type(), key_template.type_url()); EXPECT_THAT(key_manager.ValidateKeyFormat(key_format), IsOk()); } } } // namespace } // namespace tink } // namespace crypto
47.822785
80
0.742721
[ "object" ]
cb95cf926f55be0e7bd7bc85c8fa493a07d32563
2,215
cpp
C++
src/xray/editor/world/sources/project_tab.cpp
ixray-team/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
3
2021-10-30T09:36:14.000Z
2022-03-26T17:00:06.000Z
src/xray/editor/world/sources/project_tab.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
null
null
null
src/xray/editor/world/sources/project_tab.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
//////////////////////////////////////////////////////////////////////////// // Created : 20.03.2009 // Author : Andrew Kolomiets // Copyright (C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include "project_tab.h" #include "project.h" #include "object_base.h" #include "project_items.h" #include "tool_base.h" #include "level_editor.h" using xray::editor::project_tab; void project_tab::in_constructor() { } Void project_tab::treeView_MouseDown(System::Object^, System::Windows::Forms::MouseEventArgs^) { System::Windows::Forms::TreeNode^ node = treeView->GetNodeAt(PointToClient(MousePosition)); if(node && node->Tag) { treeitem_wrapper^ wrp = safe_cast<treeitem_wrapper^>(node->Tag); wrp->on_mouse_down (); }else m_level_editor->get_project()->select_object((object_base^)nullptr, enum_selection_method_set); } System::Void project_tab::global_view_menu_Opening(System::Object^, System::ComponentModel::CancelEventArgs^ ce ) { Windows::Forms::TreeNode^ node = treeView->GetNodeAt(PointToClient( MousePosition) ); removeToolStripMenuItem->Enabled = (node!=nullptr); newFilterToolStripMenuItem->Enabled = (node!=nullptr) && (safe_cast<treeitem_wrapper^>(node->Tag)->type==0); } System::Void project_tab::newFilterToolStripMenuItem_Click(System::Object^, System::EventArgs^) { m_level_editor->get_project()->add_new_group (); } System::Void project_tab::removeToolStripMenuItem_Click(System::Object^, System::EventArgs^) { m_level_editor->delete_selected (); } System::Void project_tab::treeView_BeforeLabelEdit(System::Object^, System::Windows::Forms::NodeLabelEditEventArgs^ e) { treeitem_wrapper^ w = safe_cast<treeitem_wrapper^>(e->Node->Tag); if(w->type!=0) e->CancelEdit = true; } System::Void project_tab::treeView_AfterLabelEdit(System::Object^, System::Windows::Forms::NodeLabelEditEventArgs^ e) { if(e->Label==nullptr || e->Label->Length==0) { e->CancelEdit = true; return; } project_group_treeitem_wrapper^ w = safe_cast<project_group_treeitem_wrapper^>(e->Node->Tag); w->m_project_group->name = e->Label; }
32.101449
120
0.669074
[ "object" ]
cb96fac6f871cafb40e1f3108ad1b9821e202567
5,069
hpp
C++
include/ISOBMFF/IPMA.hpp
pokey909/ISOBMFF
2bceddf2e29d60dccb038bff9dd3ea02302c1565
[ "MIT" ]
1
2019-04-05T13:17:08.000Z
2019-04-05T13:17:08.000Z
include/ISOBMFF/IPMA.hpp
milos-pesic-sc/ISOBMFF
2bceddf2e29d60dccb038bff9dd3ea02302c1565
[ "MIT" ]
null
null
null
include/ISOBMFF/IPMA.hpp
milos-pesic-sc/ISOBMFF
2bceddf2e29d60dccb038bff9dd3ea02302c1565
[ "MIT" ]
1
2019-04-02T11:41:43.000Z
2019-04-02T11:41:43.000Z
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2017 DigiDNA - www.digidna.net * * 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. ******************************************************************************/ /*! * @header IPMA.hpp * @copyright (c) 2017, DigiDNA - www.digidna.net * @author Jean-David Gadina - www.digidna.net */ #ifndef ISOBMFF_IPMA_HPP #define ISOBMFF_IPMA_HPP #include <XS/PIMPL/Object.hpp> #include <ISOBMFF/Macros.hpp> #include <ISOBMFF/FullBox.hpp> #include <ISOBMFF/DisplayableObject.hpp> #include <ISOBMFF/DisplayableObjectContainer.hpp> #include <vector> #include <cstdint> namespace ISOBMFF { class ISOBMFF_EXPORT IPMA: public FullBox, public DisplayableObjectContainer, public XS::PIMPL::Object< IPMA > { public: using XS::PIMPL::Object< IPMA >::impl; IPMA( void ); void ReadData(IParser *parser, BinaryStream &stream) override; void WriteDescription( std::ostream & os, std::size_t indentLevel ) const override; std::vector< std::pair< std::string, std::string > > GetDisplayableProperties( void ) const override; std::vector< std::shared_ptr< DisplayableObject > > GetDisplayableObjects( void ) const override; class ISOBMFF_EXPORT Entry: public XS::PIMPL::Object< Entry >, public DisplayableObject, public DisplayableObjectContainer { public: using XS::PIMPL::Object< Entry >::impl; Entry( void ); Entry( BinaryStream & stream, const IPMA & ipma ); std::string GetName( void ) const override; uint32_t GetItemID( void ) const; void SetItemID( uint32_t value ); void WriteDescription( std::ostream & os, std::size_t indentLevel ) const override; std::vector< std::pair< std::string, std::string > > GetDisplayableProperties( void ) const override; std::vector< std::shared_ptr< DisplayableObject > > GetDisplayableObjects( void ) const override; class ISOBMFF_EXPORT Association: public XS::PIMPL::Object< Association >, public DisplayableObject { public: using XS::PIMPL::Object< Association >::impl; Association( void ); Association( BinaryStream & stream, const IPMA & ipma ); std::string GetName( void ) const override; bool GetEssential( void ) const; uint16_t GetPropertyIndex( void ) const; void SetEssential( bool value ); void SetPropertyIndex( uint16_t value ); std::vector< std::pair< std::string, std::string > > GetDisplayableProperties( void ) const override; }; std::vector< std::shared_ptr< Association > > GetAssociations( void ) const; void AddAssociation( std::shared_ptr< Association > association ); }; std::vector< std::shared_ptr< Entry > > GetEntries( void ) const; std::shared_ptr< Entry > GetEntry( uint32_t itemID ) const; void AddEntry( std::shared_ptr< Entry > entry ); }; } #endif /* ISOBMFF_IPMA_HPP */
46.935185
134
0.53916
[ "object", "vector" ]
ed8a62a9ff05344696111259cf1fa634663e188b
452
cpp
C++
OI2019/hello2019/a.cpp
JackBai0914/Competitive-Programming-Codebase
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
[ "MIT" ]
null
null
null
OI2019/hello2019/a.cpp
JackBai0914/Competitive-Programming-Codebase
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
[ "MIT" ]
null
null
null
OI2019/hello2019/a.cpp
JackBai0914/Competitive-Programming-Codebase
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <ctime> #include <vector> #include <map> #include <queue> using namespace std; string s; string t[5]; int main() { ios::sync_with_stdio(false); bool ans = 0; cin >> s; for (int i = 0; i < 5; i ++) { cin >> t[i]; if (t[i][0] == s[0] || t[i][1] == s[1]) ans = 1; } cout << (ans ? "YES" : "NO") << endl; return 0; }
16.142857
41
0.575221
[ "vector" ]
ed8b4819b9f6c6617766895c6191a04043111ec3
15,147
cpp
C++
BlueBerry/Bundles/org.blueberry.osgi/src/berryDebugUtil.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
1
2017-03-05T05:29:32.000Z
2017-03-05T05:29:32.000Z
BlueBerry/Bundles/org.blueberry.osgi/src/berryDebugUtil.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
null
null
null
BlueBerry/Bundles/org.blueberry.osgi/src/berryDebugUtil.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
2
2020-10-27T06:51:00.000Z
2020-10-27T06:51:01.000Z
/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryIDebugObjectListener.h" #include "berryDebugUtil.h" #include "berryObject.h" #include "berryLog.h" #include "berryPlatform.h" #include "berryDebugBreakpointManager.h" #include <Poco/Bugcheck.h> #include <Poco/NumberParser.h> #include <Poco/DOM/NodeList.h> #include <Poco/DOM/DOMParser.h> #include <Poco/DOM/Document.h> #include <Poco/DOM/Element.h> #include <Poco/DOM/DOMWriter.h> #include <Poco/SAX/InputSource.h> #include <Poco/SAX/SAXException.h> #include <Poco/FileStream.h> #include <sstream> #include <numeric> namespace berry { static IDebugObjectListener::Events _G_ObjectEvents; const std::string DebugUtil::DEBUG_UTIL_XML = "debugutil.xml"; const std::string DebugUtil::DEBUGUTIL_TAG = "debugutil"; const std::string DebugUtil::TRACEOBJECT_TAG = "traceObject"; const std::string DebugUtil::TRACECLASS_TAG = "traceClass"; const std::string DebugUtil::ID_ATTR = "id"; const std::string DebugUtil::NAME_ATTR = "name"; Poco::HashMap<Poco::UInt32, std::list<unsigned int> > DebugUtil::m_TraceIdToSmartPointerMap; Poco::HashMap<Poco::UInt32, const Object*> DebugUtil::m_TraceIdToObjectMap; std::set<unsigned int> DebugUtil::m_TracedObjects; std::set<std::string> DebugUtil::m_TracedClasses; class NotClassName: public std::unary_function<const Object*, bool> { std::string name; public: NotClassName(const std::string& s) : name(s) { } bool operator()(Poco::HashMapEntry<unsigned int, const Object*>& entry) const { return name != entry.second->GetClassName(); } }; class AccumulateClassNames: public std::binary_function<std::set<std::string>*, Poco::HashMapEntry<unsigned int, const Object*>&, std::set<std::string>*> { public: std::set<std::string>* operator()(std::set<std::string>* names, Poco::HashMapEntry<unsigned int, const Object*>& entry) { names->insert(entry.second->GetClassName()); return names; } }; DebugBreakpointManager* DebugUtil::GetBreakpointManager() { static DebugBreakpointManager breakpointManager; return &breakpointManager; } #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::TraceObject(const Object* object) { BERRY_INFO << "Tracing enabled for: " << object->GetTraceId() << std::endl; m_TracedObjects.insert(object->GetTraceId()); _G_ObjectEvents.objTracingEvent(object->GetTraceId(), true, object); } #else void DebugUtil::TraceObject(const Object* /*object*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::TraceObject(unsigned int traceId) { BERRY_INFO << "Tracing enabled for: " << traceId << std::endl; m_TracedObjects.insert(traceId); TraceIdToObjectType::ConstIterator i = m_TraceIdToObjectMap.find(traceId); if (i != m_TraceIdToObjectMap.end()) _G_ObjectEvents.objTracingEvent(traceId, true, i->second); else _G_ObjectEvents.objTracingEvent(traceId, true, 0); } #else void DebugUtil::TraceObject(unsigned int /*traceId*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::TraceClass(const std::string& className) { BERRY_INFO << "Tracing enabled for: " << className << std::endl; m_TracedClasses.insert(className); //_G_ObjectEvents.objTracingEvent(object->GetTraceId(), true, object); } #else void DebugUtil::TraceClass(const std::string& /*className*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::StopTracing(unsigned int traceId) { BERRY_INFO << "Tracing stopped for: " << traceId << std::endl; m_TracedObjects.erase(traceId); TraceIdToObjectType::ConstIterator i = m_TraceIdToObjectMap.find(traceId); if (i != m_TraceIdToObjectMap.end()) _G_ObjectEvents.objTracingEvent(traceId, false, i->second); else _G_ObjectEvents.objTracingEvent(traceId, false, 0); } #else void DebugUtil::StopTracing(unsigned int /*traceId*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::StopTracing(const Object* obj) { BERRY_INFO << "Tracing stopped for: " << obj->GetTraceId() << std::endl; m_TracedObjects.erase(obj->GetTraceId()); _G_ObjectEvents.objTracingEvent(obj->GetTraceId(), false, obj); } #else void DebugUtil::StopTracing(const Object* /*obj*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::StopTracing(const std::string& className) { BERRY_INFO << "Tracing stopped for: " << className << std::endl; m_TracedClasses.erase(className); //_G_ObjectEvents.objTracingEvent(obj->GetTraceId(), false, obj); } #else void DebugUtil::StopTracing(const std::string& /*className*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER bool DebugUtil::IsTraced(const Object* object) { if (m_TracedObjects.find(object->GetTraceId()) != m_TracedObjects.end()) return true; if (m_TracedClasses.find(object->GetClassName()) != m_TracedClasses.end()) return true; return false; } #else bool DebugUtil::IsTraced(const Object* /*object*/) { return false; } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER bool DebugUtil::IsTraced(unsigned int traceId) { if (m_TracedObjects.find(traceId) != m_TracedObjects.end()) return true; TraceIdToObjectType::Iterator it = m_TraceIdToObjectMap.find(traceId); if (it != m_TraceIdToObjectMap.end()) { if (m_TracedClasses.find(it->second->GetClassName()) != m_TracedClasses.end()) return true; } return false; } #else bool DebugUtil::IsTraced(unsigned int /*traceId*/) { return false; } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER bool DebugUtil::IsTraced(const std::string& className) { return m_TracedClasses.find(className) != m_TracedClasses.end(); } #else bool DebugUtil::IsTraced(const std::string& /*className*/) { return false; } #endif const std::set<unsigned int>& DebugUtil::GetTracedObjects() { return m_TracedObjects; } const Object* DebugUtil::GetObject(unsigned int traceId) { return m_TraceIdToObjectMap[traceId]; } #ifdef BLUEBERRY_DEBUG_SMARTPOINTER std::list<unsigned int> DebugUtil::GetSmartPointerIDs( const Object* objectPointer, const std::list<unsigned int>& excludeList) { poco_assert(objectPointer != 0); std::list<unsigned int> ids = m_TraceIdToSmartPointerMap[objectPointer->GetTraceId()]; for (std::list<unsigned int>::const_iterator iter = excludeList.begin(); iter != excludeList.end(); ++iter) ids.remove(*iter); return ids; } #else std::list<unsigned int> DebugUtil::GetSmartPointerIDs( const Object* /*objectPointer*/, const std::list<unsigned int>& /*excludeList*/) { return std::list<unsigned int>(); } #endif void DebugUtil::GetRegisteredObjects(std::vector<const Object*>& list) { for (TraceIdToObjectType::ConstIterator i = m_TraceIdToObjectMap.begin(); i != m_TraceIdToObjectMap.end(); ++i) { list.push_back(i->second); } } void DebugUtil::PrintSmartPointerIDs(const Object* objectPointer, std::ostream& stream, const std::list<unsigned int>& excludeList) { stream << "SmartPointer IDs [ "; if (IsTraced(objectPointer)) { std::list<unsigned int> ids = GetSmartPointerIDs(objectPointer, excludeList); for (std::list<unsigned int>::const_iterator iter = ids.begin(); iter != ids.end(); ++iter) { stream << *iter << " "; } } else { stream << "n/a "; } stream << "]\n"; } void DebugUtil::AddObjectListener(SmartPointer<IDebugObjectListener> listener) { _G_ObjectEvents.AddListener(listener); } void DebugUtil::RemoveObjectListener(SmartPointer<IDebugObjectListener> listener) { _G_ObjectEvents.RemoveListener(listener); } void DebugUtil::ResetObjectSummary() { m_TraceIdToObjectMap.clear(); m_TraceIdToSmartPointerMap.clear(); m_TracedObjects.clear(); } bool DebugUtil::PrintObjectSummary(bool details) { std::set<std::string> names; std::accumulate(m_TraceIdToObjectMap.begin(), m_TraceIdToObjectMap.end(), &names, AccumulateClassNames()); if (!names.empty()) { std::cout << std::endl << std::endl << "#########################################################" << std::endl; std::cout << "######## berry::Object leakage summary: ########" << std::endl << std::endl; for (std::set<std::string>::const_iterator i = names.begin(); i != names.end(); ++i) { PrintObjectSummary(*i, details); if (details) std::cout << std::endl; } std::cout << std::endl << "#########################################################" << std::endl << std::endl; } return !names.empty(); } bool DebugUtil::PrintObjectSummary(const std::string& className, bool details) { TraceIdToObjectType::ConstIterator endIter = std::remove_if(m_TraceIdToObjectMap.begin(), m_TraceIdToObjectMap.end(), NotClassName(className)); std::cout << "Class: " << className; if (details) std::cout << std::endl; std::size_t count = 0; for (TraceIdToObjectType::ConstIterator iter = m_TraceIdToObjectMap.begin(); iter != endIter; ++iter, ++count) { if (details) { std::cout << *(iter->second); PrintSmartPointerIDs(iter->second, std::cout); } } std::cout << " (" << count << " instances)" << std::endl; return (count!=0); } unsigned int& DebugUtil::GetSmartPointerCounter() { static unsigned int counter = 0; return counter; } #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::UnregisterSmartPointer(unsigned int smartPointerId, const Object* objectPointer) { poco_assert(objectPointer != 0); m_TraceIdToSmartPointerMap[objectPointer->GetTraceId()].remove(smartPointerId); _G_ObjectEvents.spDestroyedEvent(smartPointerId, objectPointer); } #else void DebugUtil::UnregisterSmartPointer(unsigned int /*smartPointerId*/, const Object* /*objectPointer*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::RegisterSmartPointer(unsigned int smartPointerId, const Object* objectPointer, bool /*recordStack*/) { poco_assert(objectPointer != 0); if (m_TracedClasses.find(objectPointer->GetClassName()) != m_TracedClasses.end() || m_TracedObjects.find(objectPointer->GetTraceId()) != m_TracedObjects.end()) { m_TraceIdToSmartPointerMap[objectPointer->GetTraceId()].push_back(smartPointerId); _G_ObjectEvents.spCreatedEvent(smartPointerId, objectPointer); } if (GetBreakpointManager()->BreakAtSmartpointer(smartPointerId)) poco_debugger_msg("SmartPointer Breakpoint reached"); } #else void DebugUtil::RegisterSmartPointer(unsigned int /*smartPointerId*/, const Object* /*objectPointer*/, bool /*recordStack*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::RegisterObject(const Object* objectPointer) { m_TraceIdToObjectMap.insert(std::make_pair(objectPointer->GetTraceId(), objectPointer)); _G_ObjectEvents.objCreatedEvent(objectPointer); if (GetBreakpointManager()->BreakAtObject(objectPointer->GetTraceId())) poco_debugger_msg("SmartPointer Breakpoint reached"); } #else void DebugUtil::RegisterObject(const Object* /*objectPointer*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::UnregisterObject(const Object* objectPointer) { m_TraceIdToObjectMap.erase(objectPointer->GetTraceId()); _G_ObjectEvents.objDestroyedEvent(objectPointer); } #else void DebugUtil::UnregisterObject(const Object* /*objectPointer*/) { } #endif bool DebugUtil::GetPersistencePath(Poco::Path& path) { return Platform::GetStatePath(path, Platform::GetBundle("system.bundle")); } void DebugUtil::SaveState() { Poco::Path path; if (!GetPersistencePath(path)) return; path.setFileName(DEBUG_UTIL_XML); Poco::XML::Document* doc = new Poco::XML::Document(); Poco::XML::Element* debugutil = doc->createElement(DEBUGUTIL_TAG); doc->appendChild(debugutil)->release(); for (std::set<unsigned int>::const_iterator i = m_TracedObjects.begin(); i != m_TracedObjects.end(); ++i) { Poco::XML::Element* traceObject = doc->createElement(TRACEOBJECT_TAG); debugutil->appendChild(traceObject)->release(); std::stringstream ss; ss << *i; traceObject->setAttribute(ID_ATTR, ss.str()); } for (std::set<std::string>::const_iterator i = m_TracedClasses.begin(); i != m_TracedClasses.end(); ++i) { Poco::XML::Element* traceClass = doc->createElement(TRACECLASS_TAG); debugutil->appendChild(traceClass)->release(); traceClass->setAttribute(NAME_ATTR, *i); } try { Poco::FileOutputStream writer(path.toString()); Poco::XML::DOMWriter out; out.setOptions(3); //write declaration and pretty print out.writeNode(writer, doc); doc->release(); // save BreakpointManager path.setFileName(DebugBreakpointManager::BREAKPOINTS_XML); GetBreakpointManager()->SaveState(path); } catch (Poco::FileException& e) { BERRY_WARN << e.displayText(); } } void DebugUtil::RestoreState() { Poco::Path path; if (!GetPersistencePath(path)) return; path.setFileName(DEBUG_UTIL_XML); try { Poco::XML::DOMParser parser; Poco::FileInputStream reader(path.toString()); Poco::XML::InputSource source(reader); //source.setSystemId(baseDir); Poco::XML::Document* doc = parser.parse(&source); Poco::XML::Element* debugutil = doc->documentElement(); if (debugutil) { // restore traced objects Poco::XML::NodeList* elementList = debugutil->getElementsByTagName(TRACEOBJECT_TAG); for (std::size_t i = 0; i < elementList->length(); i++) { Poco::XML::Element* elem = dynamic_cast<Poco::XML::Element*> (elementList->item(static_cast<unsigned long>(i))); if (!elem->hasAttribute(ID_ATTR)) continue; const std::string& attr = elem->getAttribute(ID_ATTR); int traceId = 0; try { traceId = Poco::NumberParser::parse(attr); } catch (const Poco::SyntaxException& e) { BERRY_WARN << e.displayText(); } DebugUtil::TraceObject(traceId); } elementList->release(); // restore traced classes elementList = debugutil->getElementsByTagName(TRACECLASS_TAG); for (std::size_t i = 0; i < elementList->length(); i++) { Poco::XML::Element* elem = dynamic_cast<Poco::XML::Element*> (elementList->item(static_cast<unsigned long>(i))); if (!elem->hasAttribute(NAME_ATTR)) continue; const std::string& traceClass = elem->getAttribute(NAME_ATTR); if (!traceClass.empty()) DebugUtil::TraceClass(traceClass); } elementList->release(); } doc->release(); } catch (Poco::XML::SAXParseException& e) { BERRY_WARN << e.displayText(); } catch (Poco::FileNotFoundException&) { } catch (Poco::FileException& e) { BERRY_WARN << e.displayText(); } // restore BreakpointManager path.setFileName(DebugBreakpointManager::BREAKPOINTS_XML); GetBreakpointManager()->RestoreState(path); } }
27.291892
131
0.700007
[ "object", "vector" ]
ed8cd949ac04e79198428e1092d56652fd188a43
41,147
cpp
C++
swisssystems/burstein.cpp
Flexinos/bbpPairings
e274d039915dbe6087b80309a28c71e03ca8e37a
[ "Apache-2.0" ]
null
null
null
swisssystems/burstein.cpp
Flexinos/bbpPairings
e274d039915dbe6087b80309a28c71e03ca8e37a
[ "Apache-2.0" ]
null
null
null
swisssystems/burstein.cpp
Flexinos/bbpPairings
e274d039915dbe6087b80309a28c71e03ca8e37a
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <deque> #include <iterator> #include <limits> #include <list> #include <ostream> #include <stdexcept> #include <string> #include <tuple> #include <vector> #include <matching/computer.h> #include <tournament/tournament.h> #include <utility/typesizes.h> #include <utility/uintstringconversion.h> #include <utility/uinttypes.h> #include "burstein.h" #include "common.h" #ifndef OMIT_BURSTEIN namespace swisssystems { namespace burstein { void BursteinInfo::updateAccelerations( tournament::Tournament &tournament, const tournament::round_index round_index ) const { if (round_index < 2) { tournament::player_index rankBound{ }; for ( const tournament::player_index player_index : tournament.playersByRank ) { const tournament::Player &player = tournament.players[player_index]; if (!player.matches.size() || player.matches[0].participatedInPairing) { ++rankBound; } } if (rankBound > 1u) { for ( const tournament::player_index player_index : tournament.playersByRank) { tournament::Player &player = tournament.players[player_index]; player.accelerations.push_back(tournament.pointsForWin); if ( !player.matches.size() || player.matches[0].participatedInPairing) { rankBound -= 2; if (rankBound <= 1u) { break; } } } } } } namespace { using namespace detail; constexpr unsigned int adjustedScoreSize = utility::typesizes ::bitsToRepresent<unsigned int>(tournament::maxRounds - 1u) + utility::typesizes::bitsToRepresent<unsigned int>( tournament::maxPoints); static_assert( adjustedScoreSize >= utility::typesizes ::bitsToRepresent<unsigned int>(tournament::maxPoints), "Overflow"); constexpr unsigned int pointsProductSize = adjustedScoreSize * 2u; static_assert(pointsProductSize / 2u >= adjustedScoreSize, "Overflow"); /** * A type big enough to hold a player's adjusted score, where unplayed * games are replaced with draws. */ typedef utility::uinttypes::uint_least<adjustedScoreSize> adjusted_score; /** * A type big enough to hold the product of a player's score and the sum * of his opponents' adjusted scores. */ typedef utility::uinttypes::uint_least<pointsProductSize> points_product; /** * Get the adjusted score for a game: an unplayed game counts as a draw. */ tournament::points getAdjustedPoints( const tournament::Player &player, const tournament::Match &match, const tournament::Tournament &tournament) { return match.gameWasPlayed ? tournament.getPoints(player, match) : tournament.pointsForDraw; } /** * Get the virtual score of the opponent in a non-played game. */ tournament::points getVirtualOpponentScore( const tournament::Player &player, const tournament::Match &match, const tournament::Tournament &tournament) { return match.matchScore == tournament::MATCH_SCORE_LOSS ? tournament.pointsForWin : match.matchScore == tournament::MATCH_SCORE_DRAW ? tournament.pointsForDraw : match.opponent == player.id && match.participatedInPairing && tournament.pointsForPairingAllocatedBye < tournament.pointsForWin ? tournament.pointsForPairingAllocatedBye < tournament.pointsForDraw ? tournament.pointsForWin : tournament.pointsForDraw : tournament.pointsForForfeitLoss; } points_product calculateSonnebornBerger( const tournament::Player &player, const tournament::Tournament &tournament, const std::vector<adjusted_score> &adjustedScores) { if (!player.isValid) { return 0; } points_product result{ }; const adjusted_score futureVirtualPoints = adjusted_score(tournament.playedRounds - 1u) * tournament.pointsForDraw; adjusted_score virtualPoints = futureVirtualPoints + player.acceleration(tournament); if ( virtualPoints < futureVirtualPoints || (tournament.playedRounds > 1u && futureVirtualPoints / (tournament.playedRounds - 1u) < tournament.pointsForDraw)) { assert( tournament.playedRounds > tournament::maxRounds || tournament.pointsForDraw > tournament::maxPoints); throw tournament::BuildLimitExceededException( "This build supports at most " + (tournament.playedRounds > tournament::maxRounds ? utility::uintstringconversion ::toString(tournament::maxRounds) + " rounds." : utility::uintstringconversion ::toString(tournament::maxPoints, 1) + " points per draw.")); } tournament::round_index roundIndex{ }; for (const tournament::Match &match : player.matches) { if (roundIndex >= tournament.playedRounds) { break; } if (match.gameWasPlayed) { const points_product addend = points_product{ adjustedScores[match.opponent] } * tournament.getPoints(player, match); result += addend; if ( result < addend || (adjustedScores[match.opponent] && addend / adjustedScores[match.opponent] < tournament.getPoints(player, match))) { assert( tournament.playedRounds > tournament::maxRounds || tournament.pointsForWin > tournament::maxPoints || tournament.pointsForDraw > tournament::maxPoints || tournament.pointsForLoss > tournament::maxPoints || tournament.pointsForForfeitLoss > tournament::maxPoints || tournament.pointsForZeroPointBye > tournament::maxPoints || tournament.pointsForPairingAllocatedBye > tournament::maxPoints); throw tournament::BuildLimitExceededException( "This build supports at most " + (tournament.playedRounds > tournament::maxRounds ? utility::uintstringconversion ::toString(tournament::maxRounds) + " rounds." : utility::uintstringconversion ::toString(tournament::maxPoints, 1) + "points per match.")); } } else { const adjusted_score virtualScore = virtualPoints + getVirtualOpponentScore(player, match, tournament); const points_product scaledScore = points_product{ tournament.getPoints(player, match) } * virtualScore; result += scaledScore; if ( result < scaledScore || virtualScore < virtualPoints || (virtualScore && scaledScore / virtualScore < tournament.getPoints(player, match))) { assert( tournament.playedRounds > tournament::maxRounds || tournament.pointsForWin > tournament::maxPoints || tournament.pointsForDraw > tournament::maxPoints || tournament.pointsForLoss > tournament::maxPoints || tournament.pointsForForfeitLoss > tournament::maxPoints || tournament.pointsForZeroPointBye > tournament::maxPoints || tournament.pointsForPairingAllocatedBye > tournament::maxPoints); throw tournament::BuildLimitExceededException( "This build supports at most " + (tournament.playedRounds > tournament::maxRounds ? utility::uintstringconversion ::toString(tournament::maxRounds) + " rounds." : utility::uintstringconversion ::toString(tournament::maxPoints, 1) + " points per match.")); } } virtualPoints += tournament.getPoints(player, match); if ( virtualPoints < tournament.getPoints(player, match) && virtualPoints >= tournament.pointsForDraw) { assert( tournament.playedRounds > tournament::maxRounds || tournament.pointsForWin > tournament::maxPoints || tournament.pointsForDraw > tournament::maxPoints || tournament.pointsForLoss > tournament::maxPoints || tournament.pointsForForfeitLoss > tournament::maxPoints || tournament.pointsForZeroPointBye > tournament::maxPoints || tournament.pointsForPairingAllocatedBye > tournament::maxPoints); throw tournament::BuildLimitExceededException( "This build supports at most " + (tournament.playedRounds > tournament::maxRounds ? utility::uintstringconversion ::toString(tournament::maxRounds) + " rounds." : utility::uintstringconversion ::toString(tournament::maxPoints, 1) + "points per match.")); } virtualPoints -= tournament.pointsForDraw; ++roundIndex; } return result; } points_product calculateBuchholzTiebreak( const tournament::Player &player, const tournament::Tournament &tournament, const std::vector<adjusted_score> &adjustedScores, const bool median = false) { if (!player.isValid || (median && tournament.playedRounds <= 2)) { return 0; } points_product result{ }; const adjusted_score futureVirtualPoints = adjusted_score(tournament.playedRounds - 1u) * tournament.pointsForDraw; adjusted_score virtualPoints = futureVirtualPoints + player.acceleration(tournament); if ( virtualPoints < futureVirtualPoints || (tournament.playedRounds > 1u && futureVirtualPoints / (tournament.playedRounds - 1u) < tournament.pointsForDraw)) { assert( tournament.playedRounds > tournament::maxRounds || tournament.pointsForDraw > tournament::maxPoints); throw tournament::BuildLimitExceededException( "This build supports at most " + (tournament.playedRounds > tournament::maxRounds ? utility::uintstringconversion ::toString(tournament::maxRounds) + " rounds." : utility::uintstringconversion ::toString(tournament::maxPoints, 1) + " points per draw.")); } adjusted_score min = std::numeric_limits<adjusted_score>::max(); adjusted_score max{ }; tournament::round_index roundIndex{ }; for (const tournament::Match &match : player.matches) { if (roundIndex >= tournament.playedRounds) { break; } adjusted_score adjustment; if (match.gameWasPlayed) { adjustment = adjustedScores[match.opponent]; } else { adjustment = virtualPoints + getVirtualOpponentScore(player, match, tournament); if (adjustment < virtualPoints) { assert( tournament.playedRounds > tournament::maxRounds || tournament.pointsForWin > tournament::maxPoints || tournament.pointsForDraw > tournament::maxPoints || tournament.pointsForLoss > tournament::maxPoints || tournament.pointsForForfeitLoss > tournament::maxPoints || tournament.pointsForZeroPointBye > tournament::maxPoints || tournament.pointsForPairingAllocatedBye > tournament::maxPoints); throw tournament::BuildLimitExceededException( "This build supports at most " + (tournament.playedRounds > tournament::maxRounds ? utility::uintstringconversion ::toString(tournament::maxRounds) + " rounds." : utility::uintstringconversion ::toString(tournament::maxPoints, 1) + " points per match.")); } } result += adjustment; if (result < adjustment) { assert( tournament.playedRounds > tournament::maxRounds || tournament.pointsForWin > tournament::maxPoints || tournament.pointsForDraw > tournament::maxPoints || tournament.pointsForLoss > tournament::maxPoints || tournament.pointsForForfeitLoss > tournament::maxPoints || tournament.pointsForZeroPointBye > tournament::maxPoints || tournament.pointsForPairingAllocatedBye > tournament::maxPoints); throw tournament::BuildLimitExceededException( "This build supports at most " + (tournament.playedRounds > tournament::maxRounds ? utility::uintstringconversion ::toString(tournament::maxRounds) + " rounds." : utility::uintstringconversion ::toString(tournament::maxPoints, 1) + " points per match.")); } min = std::min(min, adjustment); max = std::max(max, adjustment); virtualPoints += tournament.getPoints(player, match); if ( virtualPoints < tournament.getPoints(player, match) && virtualPoints >= tournament.pointsForDraw) { assert( tournament.playedRounds > tournament::maxRounds || tournament.pointsForWin > tournament::maxPoints || tournament.pointsForDraw > tournament::maxPoints || tournament.pointsForLoss > tournament::maxPoints || tournament.pointsForForfeitLoss > tournament::maxPoints || tournament.pointsForZeroPointBye > tournament::maxPoints || tournament.pointsForPairingAllocatedBye > tournament::maxPoints); throw tournament::BuildLimitExceededException( "This build supports at most " + (tournament.playedRounds > tournament::maxRounds ? utility::uintstringconversion ::toString(tournament::maxRounds) + " rounds." : utility::uintstringconversion ::toString(tournament::maxPoints, 1) + "points per match.")); } virtualPoints -= tournament.pointsForDraw; ++roundIndex; } if (median) { result -= min; result -= max; } return result; } /** * A class holding a player's accelerated score, rank index, and tiebreak * scores, used to order the players within a scoregroup (including a * floater from a higher scoregroup). */ struct MetricScores { const tournament::points playerScore; const points_product sonnebornBerger; const points_product buchholzTiebreak; const points_product medianTiebreak; const tournament::player_index rankIndex; MetricScores( const tournament::Player &player, const tournament::Tournament &tournament, const std::vector<adjusted_score> &adjustedScores) : playerScore(player.scoreWithAcceleration(tournament)), sonnebornBerger( calculateSonnebornBerger(player, tournament, adjustedScores)), buchholzTiebreak( calculateBuchholzTiebreak(player, tournament, adjustedScores)), medianTiebreak( calculateBuchholzTiebreak(player, tournament, adjustedScores, true ) ), rankIndex(player.rankIndex) { if ( playerScore && (buchholzScore() / playerScore < buchholzTiebreak || medianScore() / playerScore < medianTiebreak)) { assert( tournament.playedRounds > tournament::maxRounds || tournament.pointsForWin > tournament::maxPoints || tournament.pointsForDraw > tournament::maxPoints || tournament.pointsForLoss > tournament::maxPoints || tournament.pointsForForfeitLoss > tournament::maxPoints || tournament.pointsForZeroPointBye > tournament::maxPoints || tournament.pointsForPairingAllocatedBye > tournament::maxPoints || playerScore > tournament::maxPoints); throw tournament::BuildLimitExceededException( playerScore > tournament::maxPoints ? "This build does not support scores above " + utility::uintstringconversion ::toString(tournament::maxPoints, 1) + '.' : "This build supports at most " + (tournament.playedRounds > tournament::maxRounds ? utility::uintstringconversion ::toString(tournament::maxRounds) + " rounds." : utility::uintstringconversion ::toString(tournament::maxPoints, 1) + " points per match.")); } } /** * Compare two players in the same scoregroup (including a floater from * a higher scoregroup). */ bool operator<(const MetricScores &that) const { return playerScore == that.playerScore ? std::tie( sonnebornBerger, buchholzTiebreak, medianTiebreak, that.rankIndex ) < std::tie( that.sonnebornBerger, that.buchholzTiebreak, that.medianTiebreak, rankIndex) : std::make_tuple( sonnebornBerger, buchholzScore(), medianScore(), that.rankIndex ) < std::make_tuple( that.sonnebornBerger, that.buchholzScore(), that.medianScore(), rankIndex); } points_product buchholzScore() const { return buchholzTiebreak * playerScore; } points_product medianScore() const { return medianTiebreak * playerScore; } }; /** * Compute the weight of the edge to be passed to the matching algorithm. * useDueColor should be false for players with different scores. * The function assumes the two players are eligible to be paired (that * is, they are in the same scoregroup, or one could be floated into the * scoregroup of the other). The ranking of the player's opponents is not * incorporated. * * The edge weight is of the form 1 001 001 037 where the first 1 * indicates two players are compatible (have not met and do not violate * absolute color preferences), the second one indicates the players are * from the same scoregroup (after merging), the third one indicates that * the players have different due colors, and the last section is reserved * for use in ranking the player's opponents. */ matching_computer::edge_weight computeEdgeWeight( const tournament::Player &player0, const tournament::Player &player1, bool sameScoreGroup, bool useDueColor) { return player0.forbiddenPairs.count(player1.id) || (player0.absoluteColorPreference() && player1.absoluteColorPreference() && player0.colorPreference == player1.colorPreference) ? 0 : compatibleMultiplier + sameScoreGroup * sameScoreGroupMultiplier + ( sameScoreGroup && useDueColor && colorPreferencesAreCompatible( player0.colorPreference, player1.colorPreference) ) * colorMultiplier; } /** * Check, for all scoregroups in the tentative matching, that all players * are matched (except one in the lowest matched scoregroup) and that * there is at most one floater from each scoregroup. */ bool checkMatchingIsValid( const matching_computer &matchingComputer, const std::deque<tournament::player_index> &scoreGroups) { const std::vector<matching_computer::vertex_index> currentMatching = matchingComputer.getMatching(); std::deque<tournament::player_index>::const_iterator scoreGroupIterator = scoreGroups.begin(); assert(0 == *scoreGroupIterator); utility::uinttypes::uint_least_for_value<3> unmatchedPlayerCount{ }; tournament::player_index scoreGroupBegin; tournament::player_index vertexIndex{ }; for (const tournament::player_index matchedIndex : currentMatching) { if (vertexIndex >= scoreGroups.back()) { return true; } if (vertexIndex >= *scoreGroupIterator) { unmatchedPlayerCount = 0; scoreGroupBegin = vertexIndex; do { ++scoreGroupIterator; } while (vertexIndex >= *scoreGroupIterator); } if ( vertexIndex == matchedIndex && vertexIndex < *++scoreGroups.rbegin() ) { return false; } if ( vertexIndex == matchedIndex || matchedIndex < scoreGroupBegin || matchedIndex >= *scoreGroupIterator) { if (++unmatchedPlayerCount > (*scoreGroupIterator & 1 ? 2 : 1)) { return false; } } ++vertexIndex; } return true; } /** * A function to compute the color given to the first argument, whose * opponent is the second argument. */ tournament::Color choosePlayerColor( const tournament::Player &player, const tournament::Player &opponent, const tournament::Tournament &tournament, const std::vector<MetricScores> &metricScores) { const tournament::Color result = choosePlayerNeutralColor(player, opponent); return result == tournament::COLOR_NONE ? player.colorPreference == tournament::COLOR_NONE ? player.rankIndex < opponent.rankIndex ? player.rankIndex & 1u ? invert(tournament.initialColor) : tournament.initialColor : opponent.rankIndex & 1u ? tournament.initialColor : invert(tournament.initialColor) : metricScores[player.id] < metricScores[opponent.id] ? invert(opponent.colorPreference) : player.colorPreference : result; } void printChecklist( const tournament::Tournament &tournament, const std::list<const tournament::Player *> &sortedPlayers, std::ostream &ostream, std::vector<MetricScores> &metricScores, const tournament::Player *const bye = nullptr, const std::vector<const tournament::Player *> *const matching = nullptr) { swisssystems::printChecklist( ostream, std::deque<std::string>{ "Sonneborn-Berger", "Buchholz score", "Buchholz tiebreak", "Median score", "Median tiebreak", "Cur" }, [&metricScores, &matching, bye, &tournament] (const tournament::Player &player) { const MetricScores &metricScore = metricScores[player.id]; const tournament::Player *opponent = matching ? (*matching)[player.id] : nullptr; return std::deque<std::string>{ utility::uintstringconversion ::toString(metricScore.sonnebornBerger, 2), utility::uintstringconversion ::toString(metricScore.buchholzScore(), 2), utility::uintstringconversion ::toString(metricScore.buchholzTiebreak, 1), utility::uintstringconversion ::toString(metricScore.medianScore(), 2), utility::uintstringconversion ::toString(metricScore.medianTiebreak, 1), bye == &player ? "(bye)" : opponent ? '(' + utility::uintstringconversion ::toString(opponent->id + 1u) + (choosePlayerColor( player, *opponent, tournament, metricScores ) == tournament::COLOR_WHITE ? 'W' : 'B' ) + ')' : "" }; }, tournament, sortedPlayers ); } } /** * Return a list of the pairings (in arbitrary order) produced by running * the Burstein algorithm. This runs in theoretical time O(n^3 + nr) for n * players and r previous rounds. If ostream is nonnull, output a checklist * file. * * @throws NoValidPairingExists if no valid pairing exists. */ std::list<Pairing> computeMatching( tournament::Tournament &&tournament, std::ostream *const ostream) { // Compute tiebreak scores for each player, and sort them into scoregroups // and within scoregroups. std::list<const tournament::Player *> sortedPlayers; std::vector<adjusted_score> adjustedScores; for (tournament::Player &player : tournament.players) { adjusted_score adjustedScore{ }; if (player.isValid) { if (player.matches.size() <= tournament.playedRounds) { sortedPlayers.push_back(&player); } adjustedScore = player.acceleration(tournament); tournament::round_index matchIndex{ }; for (const tournament::Match &match : player.matches) { if (matchIndex++ < tournament.playedRounds) { adjustedScore += getAdjustedPoints(player, match, tournament); } if (match.gameWasPlayed) { player.forbiddenPairs.insert(match.opponent); } } } adjustedScores.push_back(adjustedScore); } if ( sortedPlayers.size() - (sortedPlayers.size() & 1u) > tournament::maxPlayers) { throw tournament::BuildLimitExceededException( "This build supports at most " + utility::uintstringconversion::toString(tournament::maxPlayers) + " players."); } std::vector<MetricScores> metricScores; for (const tournament::Player &player : tournament.players) { metricScores.emplace_back(player, tournament, adjustedScores); } sortedPlayers.sort( [&metricScores,&tournament]( const tournament::Player *const player0, const tournament::Player *const player1) { return std::make_tuple( player1->scoreWithAcceleration(tournament), metricScores[player1->id] ) < std::make_tuple( player0->scoreWithAcceleration(tournament), metricScores[player0->id]); } ); std::list<Pairing> result; // Choose the player to receive the bye, and add the bye to result. Do not // include the bye player in the vector of vertices. std::list<const tournament::Player *>::iterator byeIterator; const tournament::Player *bye{ }; if (sortedPlayers.size() & 1u) { std::list<const tournament::Player *>::iterator playerIterator = sortedPlayers.end(); bool eligibleForBye; do { --playerIterator; eligibleForBye = swisssystems::eligibleForBye(**playerIterator, tournament); } while (playerIterator != sortedPlayers.begin() && !eligibleForBye); if (!eligibleForBye) { if (ostream) { printChecklist( tournament, sortedPlayers, *ostream, metricScores); } throw NoValidPairingException( "No player is eligible for the pairing-allocated bye."); } result.emplace_back((*playerIterator)->id, (*playerIterator)->id); bye = *playerIterator; byeIterator = playerIterator; ++byeIterator; sortedPlayers.erase(playerIterator); } /** * The vector of players to be paired (not including the player receiving * the bye). */ std::vector<const tournament::Player *> vertexLabels( sortedPlayers.begin(), sortedPlayers.end()); if (bye) { sortedPlayers.insert(byeIterator, bye); --byeIterator; } matching_computer matchingComputer(vertexLabels.size(), maxEdgeWeight); if (vertexLabels.size() > ~matching_computer::size_type{ }) { throw std::length_error(""); } // Add the vertices to the matching computer. for ( tournament::player_index playerIndex{ }; playerIndex < vertexLabels.size(); ++playerIndex) { matchingComputer.addVertex(); } /** * The scoreGroups deque contains the vertex indices of the start of each * scoregroup in order. If a scoregroup can have no floaters to the next * scoregroup, the start index is included twice. */ std::deque<tournament::player_index> scoreGroups{ 0, 0 }; // Determine the scoregroups to be used for pairing, merging a scoregroup // and the one below it if the scoregroup cannot be paired. bool matchingIsValid = true; while (scoreGroups.back() < vertexLabels.size()) { // Assign players to one scoregroup. scoreGroups.push_back(scoreGroups.back()); do { // Keep merging with lower scoregroups as needed. const tournament::player_index scoreGroupBegin = scoreGroups.back(); do { // Add all the players with one score to a scoregroup. for ( tournament::player_index vertexIndex = *++++scoreGroups.rbegin(); vertexIndex < scoreGroups.back(); ++vertexIndex) { matchingComputer.setEdgeWeight( scoreGroups.back(), vertexIndex, computeEdgeWeight( *vertexLabels[vertexIndex], *vertexLabels[scoreGroups.back()], vertexIndex >= *++scoreGroups.rbegin(), false)); } ++scoreGroups.back(); } while ( scoreGroups.back() < vertexLabels.size() && vertexLabels[scoreGroupBegin] ->scoreWithAcceleration(tournament) == vertexLabels[scoreGroups.back()] ->scoreWithAcceleration(tournament) ); // Create a virtual opponent for players in the current scoregroup // to ensure that no player in higher scoregroup remains unpaired. if (scoreGroups.back() & 1u) { for ( tournament::player_index vertexIndex = *std::next(scoreGroups.rbegin(), 1); vertexIndex < scoreGroups.back(); ++vertexIndex) { matchingComputer.setEdgeWeight( scoreGroups.back(), vertexIndex, compatibleMultiplier); } } matchingComputer.computeMatching(); matchingIsValid = checkMatchingIsValid(matchingComputer, scoreGroups); } while (scoreGroups.back() < vertexLabels.size() && !matchingIsValid); if ( scoreGroups.back() < vertexLabels.size() && !(scoreGroups.back() & 1u) ) { scoreGroups.push_back(scoreGroups.back()); } } // If the last scoregroup cannot be paired and there is another scoregroup // above it, merge the two scoregroups. Repeat. while (scoreGroups.size() > 3u && !matchingIsValid) { scoreGroups.pop_back(); const tournament::player_index boundaryVertex = scoreGroups.back(); scoreGroups.pop_back(); const tournament::player_index scoreGroupBegin = scoreGroups.back(); scoreGroups.pop_back(); for ( tournament::player_index outerIndex = scoreGroups.back(); outerIndex < boundaryVertex; ++outerIndex) { for ( tournament::player_index innerIndex = boundaryVertex; innerIndex < vertexLabels.size(); ++innerIndex) { matchingComputer.setEdgeWeight( outerIndex, innerIndex, computeEdgeWeight( *vertexLabels[outerIndex], *vertexLabels[innerIndex], outerIndex >= scoreGroupBegin, false)); } } matchingComputer.computeMatching(); scoreGroups.push_back(scoreGroupBegin); scoreGroups.push_back(vertexLabels.size()); matchingIsValid = checkMatchingIsValid(matchingComputer, scoreGroups); } if (!matchingIsValid) { if (ostream) { printChecklist( tournament, sortedPlayers, *ostream, metricScores, bye); } throw NoValidPairingException( "The non-bye players cannot be simultaneously paired without " "violating the absolute criteria."); } // Optimize the matching so that players at the top of their scoregroup // play those at the bottom. std::vector<const tournament::Player *> matchingById(tournament.players.size()); std::deque<tournament::player_index>::iterator scoreGroupIterator = scoreGroups.begin(); tournament::player_index scoreGroupBegin = *scoreGroupIterator; tournament::player_index floaterIndex; bool isFloater{ }; // Iterate over the scoregroups. while (++scoreGroupIterator != scoreGroups.end()) { // Some scoregroup boundaries are repeated. if (scoreGroupBegin == *scoreGroupIterator) { continue; } // Collect the players to be paired in the scoregroup, including a // player floated from a higher scoregroup, ordered based on SB, etc. std::list<tournament::player_index> fullScoreGroup; for ( tournament::player_index playerIndex = scoreGroupBegin; playerIndex < *scoreGroupIterator; ++playerIndex) { fullScoreGroup.push_back(playerIndex); } if (isFloater) { fullScoreGroup.push_back(floaterIndex); isFloater = false; } fullScoreGroup.sort( [&metricScores, &vertexLabels](const tournament::player_index index0, const tournament::player_index index1) { return metricScores[vertexLabels[index1]->id] < metricScores[vertexLabels[index0]->id]; } ); // Update edge weights to include the floater as part of the scoregroup, // as well as accounting for due color. for (const tournament::player_index vertexIndex : fullScoreGroup) { for ( decltype(fullScoreGroup)::const_reverse_iterator neighborIterator = fullScoreGroup.rbegin(); *neighborIterator != vertexIndex; ++neighborIterator) { matchingComputer.setEdgeWeight( vertexIndex, *neighborIterator, computeEdgeWeight( *vertexLabels[vertexIndex], *vertexLabels[*neighborIterator], true, true)); } } // Starting with the highest player, find the lowest player that // preserves the matching. for ( decltype(fullScoreGroup)::const_iterator vertexIterator = fullScoreGroup.begin(); vertexIterator != fullScoreGroup.end(); ++vertexIterator) { if (!matchingById[vertexLabels[*vertexIterator]->id]) { matching_computer::edge_weight neighborPriority = 1; for ( decltype(fullScoreGroup)::const_iterator neighborIterator = std::next(vertexIterator, 1); neighborIterator != fullScoreGroup.end(); ++neighborIterator) { if (!matchingById[vertexLabels[*neighborIterator]->id]) { matching_computer::edge_weight edgeWeight = computeEdgeWeight( *vertexLabels[*vertexIterator], *vertexLabels[*neighborIterator], true, true); if (edgeWeight) { matchingComputer.setEdgeWeight( *vertexIterator, *neighborIterator, edgeWeight + neighborPriority++); } } } matchingComputer.computeMatching(); matching_computer::vertex_index match = matchingComputer.getMatching()[*vertexIterator]; if (match >= *scoreGroupIterator) { floaterIndex = *vertexIterator; isFloater = true; } else { // Finalize the match so the two players will not be reassigned. matchingById[vertexLabels[*vertexIterator]->id] = vertexLabels[match]; matchingById[vertexLabels[match]->id] = vertexLabels[*vertexIterator]; result.emplace_back( vertexLabels[*vertexIterator]->id, vertexLabels[match]->id, choosePlayerColor( *vertexLabels[*vertexIterator], *vertexLabels[match], tournament, metricScores)); finalizePair(*vertexIterator, match, matchingComputer); } } } scoreGroupBegin = *scoreGroupIterator; } if (ostream) { printChecklist( tournament, sortedPlayers, *ostream, metricScores, bye, &matchingById); } return result; } } } #endif
37.542883
80
0.548351
[ "vector" ]
ed8e5e69f2d349cb2a3d17957e869abbf2d63053
62,193
cc
C++
content/browser/devtools/devtools_url_loader_interceptor.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-11-16T13:10:29.000Z
2021-11-16T13:10:29.000Z
content/browser/devtools/devtools_url_loader_interceptor.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/devtools/devtools_url_loader_interceptor.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/devtools/devtools_url_loader_interceptor.h" #include <memory> #include "base/barrier_closure.h" #include "base/base64.h" #include "base/bind.h" #include "base/no_destructor.h" #include "base/strings/pattern.h" #include "base/strings/string_piece.h" #include "base/strings/stringprintf.h" #include "base/time/time.h" #include "base/unguessable_token.h" #include "content/browser/devtools/protocol/network.h" #include "content/browser/devtools/protocol/network_handler.h" #include "content/browser/loader/download_utils_impl.h" #include "content/browser/renderer_host/frame_tree_node.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/content_client.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "mojo/public/cpp/system/data_pipe_drainer.h" #include "net/base/load_flags.h" #include "net/base/mime_sniffer.h" #include "net/cookies/cookie_access_result.h" #include "net/cookies/cookie_util.h" #include "net/http/http_util.h" #include "net/url_request/redirect_info.h" #include "net/url_request/redirect_util.h" #include "net/url_request/referrer_policy.h" #include "services/network/public/cpp/cors/cors.h" #include "services/network/public/cpp/header_util.h" #include "services/network/public/cpp/resource_request_body.h" #include "services/network/public/mojom/early_hints.mojom.h" #include "services/network/public/mojom/network_context.mojom.h" #include "third_party/blink/public/platform/resource_request_blocked_reason.h" namespace content { InterceptedRequestInfo::InterceptedRequestInfo() = default; InterceptedRequestInfo::~InterceptedRequestInfo() = default; DevToolsURLLoaderInterceptor::AuthChallengeResponse::AuthChallengeResponse( ResponseType response_type) : response_type(response_type) { DCHECK_NE(kProvideCredentials, response_type); } DevToolsURLLoaderInterceptor::AuthChallengeResponse::AuthChallengeResponse( const std::u16string& username, const std::u16string& password) : response_type(kProvideCredentials), credentials(username, password) {} DevToolsURLLoaderInterceptor::FilterEntry::FilterEntry( const base::UnguessableToken& target_id, std::vector<Pattern> patterns, RequestInterceptedCallback callback) : target_id(target_id), patterns(std::move(patterns)), callback(std::move(callback)) {} DevToolsURLLoaderInterceptor::FilterEntry::FilterEntry(FilterEntry&&) = default; DevToolsURLLoaderInterceptor::FilterEntry::~FilterEntry() = default; DevToolsURLLoaderInterceptor::Modifications::Modifications() = default; DevToolsURLLoaderInterceptor::Modifications::Modifications( net::Error error_reason) : error_reason(error_reason) {} DevToolsURLLoaderInterceptor::Modifications::Modifications( scoped_refptr<net::HttpResponseHeaders> response_headers, scoped_refptr<base::RefCountedMemory> response_body) : response_headers(std::move(response_headers)), response_body(std::move(response_body)) {} DevToolsURLLoaderInterceptor::Modifications::Modifications( std::unique_ptr<AuthChallengeResponse> auth_challenge_response) : auth_challenge_response(std::move(auth_challenge_response)) {} DevToolsURLLoaderInterceptor::Modifications::Modifications( protocol::Maybe<std::string> modified_url, protocol::Maybe<std::string> modified_method, protocol::Maybe<protocol::Binary> modified_post_data, std::unique_ptr<HeadersVector> modified_headers, protocol::Maybe<bool> intercept_response) : modified_url(std::move(modified_url)), modified_method(std::move(modified_method)), modified_post_data(std::move(modified_post_data)), modified_headers(std::move(modified_headers)), intercept_response(std::move(intercept_response)) {} DevToolsURLLoaderInterceptor::Modifications::Modifications( absl::optional<net::Error> error_reason, scoped_refptr<net::HttpResponseHeaders> response_headers, scoped_refptr<base::RefCountedMemory> response_body, size_t body_offset, protocol::Maybe<std::string> modified_url, protocol::Maybe<std::string> modified_method, protocol::Maybe<protocol::Binary> modified_post_data, std::unique_ptr<HeadersVector> modified_headers, std::unique_ptr<AuthChallengeResponse> auth_challenge_response) : error_reason(std::move(error_reason)), response_headers(std::move(response_headers)), response_body(std::move(response_body)), body_offset(body_offset), modified_url(std::move(modified_url)), modified_method(std::move(modified_method)), modified_post_data(std::move(modified_post_data)), modified_headers(std::move(modified_headers)), auth_challenge_response(std::move(auth_challenge_response)) {} DevToolsURLLoaderInterceptor::Modifications::~Modifications() = default; DevToolsURLLoaderInterceptor::Pattern::~Pattern() = default; DevToolsURLLoaderInterceptor::Pattern::Pattern(const Pattern& other) = default; DevToolsURLLoaderInterceptor::Pattern::Pattern( const std::string& url_pattern, base::flat_set<blink::mojom::ResourceType> resource_types, InterceptionStage interception_stage) : url_pattern(url_pattern), resource_types(std::move(resource_types)), interception_stage(interception_stage) {} bool DevToolsURLLoaderInterceptor::Pattern::Matches( const std::string& url, blink::mojom::ResourceType resource_type) const { if (!resource_types.empty() && resource_types.find(resource_type) == resource_types.end()) { return false; } return base::MatchPattern(url, url_pattern); } struct CreateLoaderParameters { CreateLoaderParameters( int32_t request_id, uint32_t options, network::ResourceRequest request, net::MutableNetworkTrafficAnnotationTag traffic_annotation) : request_id(request_id), options(options), request(request), traffic_annotation(traffic_annotation) {} const int32_t request_id; const uint32_t options; network::ResourceRequest request; const net::MutableNetworkTrafficAnnotationTag traffic_annotation; }; namespace { using RequestInterceptedCallback = DevToolsURLLoaderInterceptor::RequestInterceptedCallback; using ContinueInterceptedRequestCallback = DevToolsURLLoaderInterceptor::ContinueInterceptedRequestCallback; using GetResponseBodyCallback = DevToolsURLLoaderInterceptor::GetResponseBodyForInterceptionCallback; using TakeResponseBodyPipeCallback = DevToolsURLLoaderInterceptor::TakeResponseBodyPipeCallback; using Modifications = DevToolsURLLoaderInterceptor::Modifications; using InterceptionStage = DevToolsURLLoaderInterceptor::InterceptionStage; using protocol::Response; using network::mojom::CredentialsMode; using network::mojom::FetchResponseType; class BodyReader : public mojo::DataPipeDrainer::Client { public: explicit BodyReader(base::OnceClosure download_complete_callback) : download_complete_callback_(std::move(download_complete_callback)), body_(base::MakeRefCounted<base::RefCountedString>()) {} void StartReading(mojo::ScopedDataPipeConsumerHandle body); void AddCallback(std::unique_ptr<GetResponseBodyCallback> callback) { if (data_complete_) { DCHECK(callbacks_.empty()); callback->sendSuccess(encoded_body_, true); return; } callbacks_.push_back(std::move(callback)); } bool data_complete() const { return data_complete_; } scoped_refptr<base::RefCountedMemory> body() const { DCHECK(data_complete_); return body_; } void CancelWithError(std::string error) { for (auto& cb : callbacks_) cb->sendFailure(Response::ServerError(error)); callbacks_.clear(); } private: void OnDataAvailable(const void* data, size_t num_bytes) override { DCHECK(!data_complete_); body_->data().append( std::string(static_cast<const char*>(data), num_bytes)); } void OnDataComplete() override; std::unique_ptr<mojo::DataPipeDrainer> body_pipe_drainer_; std::vector<std::unique_ptr<GetResponseBodyCallback>> callbacks_; base::OnceClosure download_complete_callback_; scoped_refptr<base::RefCountedString> body_; std::string encoded_body_; bool data_complete_ = false; }; void BodyReader::StartReading(mojo::ScopedDataPipeConsumerHandle body) { DCHECK(!callbacks_.empty()); DCHECK(!body_pipe_drainer_); DCHECK(!data_complete_); body_pipe_drainer_ = std::make_unique<mojo::DataPipeDrainer>(this, std::move(body)); } void BodyReader::OnDataComplete() { DCHECK(!data_complete_); data_complete_ = true; body_pipe_drainer_.reset(); // TODO(caseq): only encode if necessary. base::Base64Encode(body_->data(), &encoded_body_); for (auto& cb : callbacks_) cb->sendSuccess(encoded_body_, true); callbacks_.clear(); std::move(download_complete_callback_).Run(); } struct ResponseMetadata { ResponseMetadata() = default; explicit ResponseMetadata(network::mojom::URLResponseHeadPtr head) : head(std::move(head)) {} network::mojom::URLResponseHeadPtr head = network::mojom::URLResponseHead::New(); std::unique_ptr<net::RedirectInfo> redirect_info; mojo_base::BigBuffer cached_metadata; size_t encoded_length = 0; size_t transfer_size = 0; network::URLLoaderCompletionStatus status; }; } // namespace class InterceptionJob : public network::mojom::URLLoaderClient, public network::mojom::URLLoader { public: static InterceptionJob* FindByRequestId( const GlobalRequestID& global_req_id) { const auto& map = GetInterceptionJobMap(); auto it = map.find(global_req_id); return it == map.end() ? nullptr : it->second; } InterceptionJob( DevToolsURLLoaderInterceptor* interceptor, const std::string& id, const base::UnguessableToken& frame_token, int32_t process_id, const absl::optional<std::string>& renderer_request_id, std::unique_ptr<CreateLoaderParameters> create_loader_params, bool is_download, mojo::PendingReceiver<network::mojom::URLLoader> loader_receiver, mojo::PendingRemote<network::mojom::URLLoaderClient> client, mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory, mojo::PendingRemote<network::mojom::CookieManager> cookie_manager); InterceptionJob(const InterceptionJob&) = delete; InterceptionJob& operator=(const InterceptionJob&) = delete; void GetResponseBody(std::unique_ptr<GetResponseBodyCallback> callback); void TakeResponseBodyPipe(TakeResponseBodyPipeCallback callback); void ContinueInterceptedRequest( std::unique_ptr<Modifications> modifications, std::unique_ptr<ContinueInterceptedRequestCallback> callback); void Detach(); void OnAuthRequest( const net::AuthChallengeInfo& auth_info, DevToolsURLLoaderInterceptor::HandleAuthRequestCallback callback); private: static std::map<GlobalRequestID, InterceptionJob*>& GetInterceptionJobMap() { static base::NoDestructor<std::map<GlobalRequestID, InterceptionJob*>> inst; return *inst; } ~InterceptionJob() override { if (registered_in_global_request_map_) { size_t erased = GetInterceptionJobMap().erase(global_req_id_); DCHECK_EQ(1lu, erased); } } Response InnerContinueRequest(std::unique_ptr<Modifications> modifications); void ProcessAuthResponse( const DevToolsURLLoaderInterceptor::AuthChallengeResponse& auth_challenge_response); Response ProcessResponseOverride( scoped_refptr<net::HttpResponseHeaders> headers, scoped_refptr<base::RefCountedMemory> body, size_t response_body_offset); void ProcessRedirectByClient(const GURL& redirect_url); void ProcessSetCookies(const net::HttpResponseHeaders& response_headers, base::OnceClosure callback); void SendResponse(scoped_refptr<base::RefCountedMemory> body, size_t offset); void ApplyModificationsToRequest( std::unique_ptr<Modifications> modifications); void StartRequest(); void CancelRequest(); void CompleteRequest(const network::URLLoaderCompletionStatus& status); void Shutdown(); std::unique_ptr<InterceptedRequestInfo> BuildRequestInfo( const network::mojom::URLResponseHeadPtr& head); void NotifyClient(std::unique_ptr<InterceptedRequestInfo> request_info); void FetchCookies( network::mojom::CookieManager::GetCookieListCallback callback); void NotifyClientWithCookies( std::unique_ptr<InterceptedRequestInfo> request_info, const net::CookieAccessResultList& cookies_with_access_result, const net::CookieAccessResultList& excluded_cookies); void ResponseBodyComplete(); bool ShouldBypassForResponse() const { if (state_ == State::kResponseTaken) return false; DCHECK_EQ(!!response_metadata_, !!body_reader_); DCHECK_EQ(state_, State::kResponseReceived); return !response_metadata_; } // network::mojom::URLLoader methods void FollowRedirect( const std::vector<std::string>& removed_headers, const net::HttpRequestHeaders& modified_headers, const net::HttpRequestHeaders& modified_cors_exempt_headers, const absl::optional<GURL>& new_url) override; void SetPriority(net::RequestPriority priority, int32_t intra_priority_value) override; void PauseReadingBodyFromNet() override; void ResumeReadingBodyFromNet() override; // network::mojom::URLLoaderClient methods void OnReceiveEarlyHints(network::mojom::EarlyHintsPtr early_hints) override; void OnReceiveResponse(network::mojom::URLResponseHeadPtr head) override; void OnReceiveRedirect(const net::RedirectInfo& redirect_info, network::mojom::URLResponseHeadPtr head) override; void OnUploadProgress(int64_t current_position, int64_t total_size, OnUploadProgressCallback callback) override; void OnReceiveCachedMetadata(mojo_base::BigBuffer data) override; void OnTransferSizeUpdated(int32_t transfer_size_diff) override; void OnStartLoadingResponseBody( mojo::ScopedDataPipeConsumerHandle body) override; void OnComplete(const network::URLLoaderCompletionStatus& status) override; bool CanGetResponseBody(std::string* error_reason); bool StartJobAndMaybeNotify(); void UpdateCORSFlag(); network::mojom::FetchResponseType CalculateResponseTainting(); network::ResourceRequest GetResourceRequestForCookies(); const std::string id_prefix_; const GlobalRequestID global_req_id_; const base::UnguessableToken frame_token_; const bool report_upload_; DevToolsURLLoaderInterceptor* interceptor_; InterceptionStage stage_; std::unique_ptr<CreateLoaderParameters> create_loader_params_; const bool is_download_; mojo::Receiver<network::mojom::URLLoaderClient> client_receiver_{this}; mojo::Receiver<network::mojom::URLLoader> loader_receiver_{this}; mojo::Remote<network::mojom::URLLoaderClient> client_; mojo::Remote<network::mojom::URLLoader> loader_; mojo::Remote<network::mojom::URLLoaderFactory> target_factory_; mojo::Remote<network::mojom::CookieManager> cookie_manager_; enum State { kNotStarted, kRequestSent, kRedirectReceived, kFollowRedirect, kAuthRequired, kResponseReceived, kResponseTaken, }; State state_; base::TimeTicks start_ticks_; base::Time start_time_; bool waiting_for_resolution_; int redirect_count_; bool tainted_origin_ = false; bool fetch_cors_flag_ = false; std::string current_id_; std::unique_ptr<BodyReader> body_reader_; std::unique_ptr<ResponseMetadata> response_metadata_; bool registered_in_global_request_map_; absl::optional<std::pair<net::RequestPriority, int32_t>> priority_; DevToolsURLLoaderInterceptor::HandleAuthRequestCallback pending_auth_callback_; TakeResponseBodyPipeCallback pending_response_body_pipe_callback_; const absl::optional<std::string> renderer_request_id_; // List of URLs that have been redirected through. The last member is the // current request URL. Tracked for the purpose of computing the proper // SameSite cookies to return, which depends on the redirect chain. std::vector<GURL> url_chain_; }; void DevToolsURLLoaderInterceptor::CreateJob( const base::UnguessableToken& frame_token, int32_t process_id, bool is_download, const absl::optional<std::string>& renderer_request_id, std::unique_ptr<CreateLoaderParameters> create_params, mojo::PendingReceiver<network::mojom::URLLoader> loader_receiver, mojo::PendingRemote<network::mojom::URLLoaderClient> client, mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory, mojo::PendingRemote<network::mojom::CookieManager> cookie_manager) { DCHECK(!frame_token.is_empty()); static int last_id = 0; std::string id = base::StringPrintf("interception-job-%d", ++last_id); // This class will manage its own life time to match the loader client. new InterceptionJob( this, std::move(id), frame_token, process_id, renderer_request_id, std::move(create_params), is_download, std::move(loader_receiver), std::move(client), std::move(target_factory), std::move(cookie_manager)); } InterceptionStage DevToolsURLLoaderInterceptor::GetInterceptionStage( const GURL& url, blink::mojom::ResourceType resource_type) const { InterceptionStage stage = InterceptionStage::DONT_INTERCEPT; std::string unused; std::string url_str = protocol::NetworkHandler::ExtractFragment(url, &unused); for (const auto& pattern : patterns_) { if (pattern.Matches(url_str, resource_type)) stage |= pattern.interception_stage; } return stage; } class DevToolsURLLoaderFactoryProxy : public network::mojom::URLLoaderFactory { public: DevToolsURLLoaderFactoryProxy( const base::UnguessableToken& frame_token, int32_t process_id, bool is_download, mojo::PendingReceiver<network::mojom::URLLoaderFactory> loader_receiver, mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory_remote, mojo::PendingRemote<network::mojom::CookieManager> cookie_manager, base::WeakPtr<DevToolsURLLoaderInterceptor> interceptor); ~DevToolsURLLoaderFactoryProxy() override; private: // network::mojom::URLLoaderFactory implementation void CreateLoaderAndStart( mojo::PendingReceiver<network::mojom::URLLoader> loader, int32_t request_id, uint32_t options, const network::ResourceRequest& request, mojo::PendingRemote<network::mojom::URLLoaderClient> client, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) override; void Clone(mojo::PendingReceiver<network::mojom::URLLoaderFactory> receiver) override; void OnProxyBindingError(); void OnTargetFactoryError(); const base::UnguessableToken frame_token_; const int32_t process_id_; const bool is_download_; mojo::Remote<network::mojom::URLLoaderFactory> target_factory_; mojo::Remote<network::mojom::CookieManager> cookie_manager_; base::WeakPtr<DevToolsURLLoaderInterceptor> interceptor_; mojo::ReceiverSet<network::mojom::URLLoaderFactory> receivers_; SEQUENCE_CHECKER(sequence_checker_); }; // This class owns itself and will delete self when any mojo // connection is broken. DevToolsURLLoaderFactoryProxy::DevToolsURLLoaderFactoryProxy( const base::UnguessableToken& frame_token, int32_t process_id, bool is_download, mojo::PendingReceiver<network::mojom::URLLoaderFactory> loader_receiver, mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory_remote, mojo::PendingRemote<network::mojom::CookieManager> cookie_manager, base::WeakPtr<DevToolsURLLoaderInterceptor> interceptor) : frame_token_(frame_token), process_id_(process_id), is_download_(is_download), target_factory_(std::move(target_factory_remote)), interceptor_(std::move(interceptor)) { target_factory_.set_disconnect_handler( base::BindOnce(&DevToolsURLLoaderFactoryProxy::OnTargetFactoryError, base::Unretained(this))); receivers_.Add(this, std::move(loader_receiver)); receivers_.set_disconnect_handler( base::BindRepeating(&DevToolsURLLoaderFactoryProxy::OnProxyBindingError, base::Unretained(this))); cookie_manager_.Bind(std::move(cookie_manager)); cookie_manager_.set_disconnect_handler( base::BindOnce(&DevToolsURLLoaderFactoryProxy::OnTargetFactoryError, base::Unretained(this))); } DevToolsURLLoaderFactoryProxy::~DevToolsURLLoaderFactoryProxy() = default; void DevToolsURLLoaderFactoryProxy::CreateLoaderAndStart( mojo::PendingReceiver<network::mojom::URLLoader> loader, int32_t request_id, uint32_t options, const network::ResourceRequest& request, mojo::PendingRemote<network::mojom::URLLoaderClient> client, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DevToolsURLLoaderInterceptor* interceptor = interceptor_.get(); if (!interceptor_ || request.url.SchemeIs(url::kDataScheme)) { target_factory_->CreateLoaderAndStart(std::move(loader), request_id, options, request, std::move(client), traffic_annotation); return; } auto creation_params = std::make_unique<CreateLoaderParameters>( request_id, options, request, traffic_annotation); mojo::PendingRemote<network::mojom::URLLoaderFactory> factory_clone; target_factory_->Clone(factory_clone.InitWithNewPipeAndPassReceiver()); mojo::PendingRemote<network::mojom::CookieManager> cookie_manager_clone; cookie_manager_->CloneInterface( cookie_manager_clone.InitWithNewPipeAndPassReceiver()); interceptor->CreateJob( frame_token_, process_id_, is_download_, request.devtools_request_id, std::move(creation_params), std::move(loader), std::move(client), std::move(factory_clone), std::move(cookie_manager_clone)); } void DevToolsURLLoaderFactoryProxy::Clone( mojo::PendingReceiver<network::mojom::URLLoaderFactory> receiver) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); receivers_.Add(this, std::move(receiver)); } void DevToolsURLLoaderFactoryProxy::OnTargetFactoryError() { delete this; } void DevToolsURLLoaderFactoryProxy::OnProxyBindingError() { if (receivers_.empty()) delete this; } // static void DevToolsURLLoaderInterceptor::HandleAuthRequest( GlobalRequestID req_id, const net::AuthChallengeInfo& auth_info, HandleAuthRequestCallback callback) { if (auto* job = InterceptionJob::FindByRequestId(req_id)) job->OnAuthRequest(auth_info, std::move(callback)); else std::move(callback).Run(true, absl::nullopt); } DevToolsURLLoaderInterceptor::DevToolsURLLoaderInterceptor( RequestInterceptedCallback callback) : request_intercepted_callback_(std::move(callback)), weak_factory_(this) {} DevToolsURLLoaderInterceptor::~DevToolsURLLoaderInterceptor() { for (auto const& entry : jobs_) entry.second->Detach(); } void DevToolsURLLoaderInterceptor::SetPatterns( std::vector<DevToolsURLLoaderInterceptor::Pattern> patterns, bool handle_auth) { patterns_ = std::move(patterns); handle_auth_ = handle_auth; DCHECK(patterns_.size() || !handle_auth); } void DevToolsURLLoaderInterceptor::GetResponseBody( const std::string& interception_id, std::unique_ptr<GetResponseBodyCallback> callback) { if (InterceptionJob* job = FindJob(interception_id, &callback)) job->GetResponseBody(std::move(callback)); } void DevToolsURLLoaderInterceptor::TakeResponseBodyPipe( const std::string& interception_id, DevToolsURLLoaderInterceptor::TakeResponseBodyPipeCallback callback) { auto it = jobs_.find(interception_id); if (it == jobs_.end()) { std::move(callback).Run( protocol::Response::InvalidParams("Invalid InterceptionId."), mojo::ScopedDataPipeConsumerHandle(), base::EmptyString()); return; } it->second->TakeResponseBodyPipe(std::move(callback)); } void DevToolsURLLoaderInterceptor::ContinueInterceptedRequest( const std::string& interception_id, std::unique_ptr<Modifications> modifications, std::unique_ptr<ContinueInterceptedRequestCallback> callback) { if (InterceptionJob* job = FindJob(interception_id, &callback)) { job->ContinueInterceptedRequest(std::move(modifications), std::move(callback)); } } bool DevToolsURLLoaderInterceptor::CreateProxyForInterception( int process_id, StoragePartition* storage_partition, const base::UnguessableToken& frame_token, bool is_navigation, bool is_download, network::mojom::URLLoaderFactoryOverride* intercepting_factory) { DCHECK(storage_partition); if (patterns_.empty()) return false; // If we're the first interceptor to install an override, make a // remote/receiver pair, then handle this similarly to appending // a proxy to existing override. if (!intercepting_factory->overriding_factory) { DCHECK(!intercepting_factory->overridden_factory_receiver); intercepting_factory->overridden_factory_receiver = intercepting_factory->overriding_factory .InitWithNewPipeAndPassReceiver(); } mojo::PendingRemote<network::mojom::URLLoaderFactory> target_remote; auto overridden_factory_receiver = target_remote.InitWithNewPipeAndPassReceiver(); mojo::PendingRemote<network::mojom::CookieManager> cookie_manager; // TODO(ahemery): Using 0 as the process id for navigations can lead to // collisions between multiple navigations/service workers main script fetch. // It should be replaced by the more robust // GlobalRequestID::MakeBrowserInitiated(). int process_id_override = process_id; if (is_navigation) process_id_override = 0; storage_partition->GetNetworkContext()->GetCookieManager( cookie_manager.InitWithNewPipeAndPassReceiver()); new DevToolsURLLoaderFactoryProxy( frame_token, process_id_override, is_download, std::move(intercepting_factory->overridden_factory_receiver), std::move(target_remote), std::move(cookie_manager), weak_factory_.GetWeakPtr()); intercepting_factory->overridden_factory_receiver = std::move(overridden_factory_receiver); return true; } InterceptionJob::InterceptionJob( DevToolsURLLoaderInterceptor* interceptor, const std::string& id, const base::UnguessableToken& frame_token, int process_id, const absl::optional<std::string>& renderer_request_id, std::unique_ptr<CreateLoaderParameters> create_loader_params, bool is_download, mojo::PendingReceiver<network::mojom::URLLoader> loader_receiver, mojo::PendingRemote<network::mojom::URLLoaderClient> client, mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory, mojo::PendingRemote<network::mojom::CookieManager> cookie_manager) : id_prefix_(id), global_req_id_(process_id, create_loader_params->request_id), frame_token_(frame_token), report_upload_(!!create_loader_params->request.request_body), interceptor_(interceptor), create_loader_params_(std::move(create_loader_params)), is_download_(is_download), client_(std::move(client)), target_factory_(std::move(target_factory)), cookie_manager_(std::move(cookie_manager)), state_(kNotStarted), waiting_for_resolution_(false), redirect_count_(0), renderer_request_id_(renderer_request_id) { loader_receiver_.Bind(std::move(loader_receiver)); loader_receiver_.set_disconnect_handler( base::BindOnce(&InterceptionJob::Shutdown, base::Unretained(this))); auto& job_map = GetInterceptionJobMap(); // TODO(caseq): for now, all auth requests will go to the top-level job. // Figure out if we need anything smarter here. registered_in_global_request_map_ = job_map.emplace(global_req_id_, this).second; url_chain_.push_back(create_loader_params_->request.url); if (StartJobAndMaybeNotify()) return; StartRequest(); } bool InterceptionJob::StartJobAndMaybeNotify() { UpdateCORSFlag(); start_ticks_ = base::TimeTicks::Now(); start_time_ = base::Time::Now(); current_id_ = id_prefix_ + base::StringPrintf(".%d", redirect_count_); interceptor_->AddJob(current_id_, this); const network::ResourceRequest& request = create_loader_params_->request; stage_ = interceptor_->GetInterceptionStage( request.url, static_cast<blink::mojom::ResourceType>(request.resource_type)); if (!(stage_ & InterceptionStage::REQUEST)) return false; if (state_ == State::kRedirectReceived) state_ = State::kFollowRedirect; else DCHECK_EQ(State::kNotStarted, state_); NotifyClient(BuildRequestInfo(nullptr)); return true; } // FIXME(caseq): The logic in the three methods below is borrowed from // CorsURLLoader as a matter of a quick and mergeable fix for crbug.com/1022173. // This logic should be unified with CorsURLLoader. network::mojom::FetchResponseType InterceptionJob::CalculateResponseTainting() { if (fetch_cors_flag_) return FetchResponseType::kCors; if (create_loader_params_->request.mode == network::mojom::RequestMode::kNoCors && tainted_origin_) { return FetchResponseType::kOpaque; } return FetchResponseType::kBasic; } network::ResourceRequest InterceptionJob::GetResourceRequestForCookies() { FetchResponseType response_tainting = fetch_cors_flag_ ? FetchResponseType::kCors : FetchResponseType::kBasic; network::ResourceRequest result = create_loader_params_->request; result.credentials_mode = network::cors::CalculateCredentialsFlag( create_loader_params_->request.credentials_mode, response_tainting) ? CredentialsMode::kInclude : CredentialsMode::kOmit; return result; } void InterceptionJob::UpdateCORSFlag() { if (fetch_cors_flag_) return; const network::ResourceRequest& request = create_loader_params_->request; fetch_cors_flag_ = network::cors::ShouldCheckCors( request.url, request.request_initiator, request.mode); } bool InterceptionJob::CanGetResponseBody(std::string* error_reason) { if (!(stage_ & InterceptionStage::RESPONSE)) { *error_reason = "Can only get response body on HeadersReceived pattern matched " "requests."; return false; } if (state_ != State::kResponseReceived || !waiting_for_resolution_) { *error_reason = "Can only get response body on requests captured after headers " "received."; return false; } return true; } void InterceptionJob::GetResponseBody( std::unique_ptr<GetResponseBodyCallback> callback) { std::string error_reason; if (!CanGetResponseBody(&error_reason)) { callback->sendFailure(Response::ServerError(std::move(error_reason))); return; } if (!body_reader_) { body_reader_ = std::make_unique<BodyReader>(base::BindOnce( &InterceptionJob::ResponseBodyComplete, base::Unretained(this))); client_receiver_.Resume(); loader_->ResumeReadingBodyFromNet(); } body_reader_->AddCallback(std::move(callback)); } void InterceptionJob::TakeResponseBodyPipe( TakeResponseBodyPipeCallback callback) { std::string error_reason; if (!CanGetResponseBody(&error_reason)) { std::move(callback).Run(Response::ServerError(std::move(error_reason)), mojo::ScopedDataPipeConsumerHandle(), base::EmptyString()); return; } DCHECK_EQ(state_, State::kResponseReceived); DCHECK(!!response_metadata_); state_ = State::kResponseTaken; pending_response_body_pipe_callback_ = std::move(callback); client_receiver_.Resume(); loader_->ResumeReadingBodyFromNet(); } void InterceptionJob::ContinueInterceptedRequest( std::unique_ptr<Modifications> modifications, std::unique_ptr<ContinueInterceptedRequestCallback> callback) { Response response = InnerContinueRequest(std::move(modifications)); // |this| may be destroyed at this point. if (response.IsSuccess()) callback->sendSuccess(); else callback->sendFailure(std::move(response)); } void InterceptionJob::Detach() { stage_ = InterceptionStage::DONT_INTERCEPT; interceptor_ = nullptr; if (!waiting_for_resolution_) return; if (state_ == State::kAuthRequired) { state_ = State::kRequestSent; waiting_for_resolution_ = false; std::move(pending_auth_callback_).Run(true, absl::nullopt); return; } InnerContinueRequest(std::make_unique<Modifications>()); } Response InterceptionJob::InnerContinueRequest( std::unique_ptr<Modifications> modifications) { if (!waiting_for_resolution_) { return Response::ServerError( "Invalid state for continueInterceptedRequest"); } waiting_for_resolution_ = false; if (modifications->intercept_response.isJust()) { if (modifications->intercept_response.fromJust()) { if (stage_ == InterceptionStage::REQUEST) stage_ = InterceptionStage::BOTH; else stage_ = InterceptionStage::RESPONSE; } else { if (stage_ == InterceptionStage::BOTH) stage_ = InterceptionStage::REQUEST; else if (stage_ == InterceptionStage::RESPONSE) stage_ = InterceptionStage::DONT_INTERCEPT; } } if (state_ == State::kAuthRequired) { if (!modifications->auth_challenge_response) return Response::InvalidParams("authChallengeResponse required."); ProcessAuthResponse(*modifications->auth_challenge_response); return Response::Success(); } if (modifications->auth_challenge_response) return Response::InvalidParams("authChallengeResponse not expected."); if (modifications->error_reason) { network::URLLoaderCompletionStatus status( modifications->error_reason.value()); status.completion_time = base::TimeTicks::Now(); if (modifications->error_reason == net::ERR_BLOCKED_BY_CLIENT) { // So we know that these modifications originated from devtools // (also known as inspector), and can therefore annotate the // request. We only do this for one specific error code thus // far, to minimize risk of breaking other usages. status.extended_error_code = static_cast<int>(blink::ResourceRequestBlockedReason::kInspector); } CompleteRequest(status); return Response::Success(); } if (modifications->response_headers || modifications->response_body) { // If only intercepted response headers are overridden continue with // normal load of the original response body. if (response_metadata_ && !modifications->response_body) { network::mojom::URLResponseHeadPtr& head = response_metadata_->head; head->headers = std::move(modifications->response_headers); // TODO(caseq): we're cheating here a bit, raw_headers() have \0's // where real headers would have \r\n, but the sizes here // probably don't have to be exact. size_t headers_size = head->headers->raw_headers().size(); head->encoded_data_length = headers_size; } else { return ProcessResponseOverride(std::move(modifications->response_headers), std::move(modifications->response_body), modifications->body_offset); } } if (state_ == State::kFollowRedirect) { if (!modifications->modified_url.isJust()) { // TODO(caseq): report error modifications other than headers are present. state_ = State::kRequestSent; std::vector<std::string> removed_headers; net::HttpRequestHeaders modified_headers; if (modifications->modified_headers) { for (const auto& entry : *modifications->modified_headers) { if (entry.second.empty()) removed_headers.push_back(entry.first); else modified_headers.SetHeader(entry.first, entry.second); } } loader_->FollowRedirect(removed_headers, modified_headers, {}, absl::nullopt); return Response::Success(); } CancelRequest(); // Fall through to the generic logic of re-starting the request // at the bottom of the method. } if (state_ == State::kRedirectReceived) { // TODO(caseq): report error if other modifications are present. if (modifications->modified_url.isJust()) { std::string location = modifications->modified_url.fromJust(); CancelRequest(); response_metadata_->head->headers->SetHeader("location", location); GURL redirect_url = create_loader_params_->request.url.Resolve(location); if (!redirect_url.is_valid()) return Response::ServerError("Invalid modified URL"); ProcessRedirectByClient(redirect_url); return Response::Success(); } client_->OnReceiveRedirect(*response_metadata_->redirect_info, std::move(response_metadata_->head)); return Response::Success(); } if (body_reader_) { if (body_reader_->data_complete()) SendResponse(body_reader_->body(), 0); // There are read callbacks pending, so let the reader do its job and come // back when it's done. return Response::Success(); } if (response_metadata_) { if (state_ == State::kResponseTaken) { return Response::InvalidParams( "Unable to continue request as is after body is taken"); } // TODO(caseq): report error if other modifications are present. if (response_metadata_->status.error_code) { CompleteRequest(response_metadata_->status); return Response::Success(); } DCHECK_EQ(State::kResponseReceived, state_); DCHECK(!body_reader_); client_->OnReceiveResponse(std::move(response_metadata_->head)); response_metadata_.reset(); loader_->ResumeReadingBodyFromNet(); client_receiver_.Resume(); return Response::Success(); } DCHECK_EQ(State::kNotStarted, state_); ApplyModificationsToRequest(std::move(modifications)); StartRequest(); return Response::Success(); } void InterceptionJob::ApplyModificationsToRequest( std::unique_ptr<Modifications> modifications) { network::ResourceRequest* request = &create_loader_params_->request; // Note this redirect is not visible to the page by design. If they want a // visible redirect they can mock a response with a 302. if (modifications->modified_url.isJust()) request->url = GURL(modifications->modified_url.fromJust()); if (modifications->modified_method.isJust()) request->method = modifications->modified_method.fromJust(); if (modifications->modified_post_data.isJust()) { const auto& post_data = modifications->modified_post_data.fromJust(); request->request_body = network::ResourceRequestBody::CreateFromBytes( reinterpret_cast<const char*>(post_data.data()), post_data.size()); } if (modifications->modified_headers) { request->headers.Clear(); for (const auto& entry : *modifications->modified_headers) { if (base::EqualsCaseInsensitiveASCII(entry.first, net::HttpRequestHeaders::kReferer)) { request->referrer = GURL(entry.second); request->referrer_policy = net::ReferrerPolicy::NEVER_CLEAR; } else { request->headers.SetHeader(entry.first, entry.second); } } } } void InterceptionJob::ProcessAuthResponse( const DevToolsURLLoaderInterceptor::AuthChallengeResponse& response) { DCHECK_EQ(kAuthRequired, state_); switch (response.response_type) { case DevToolsURLLoaderInterceptor::AuthChallengeResponse::kDefault: std::move(pending_auth_callback_).Run(true, absl::nullopt); break; case DevToolsURLLoaderInterceptor::AuthChallengeResponse::kCancelAuth: std::move(pending_auth_callback_).Run(false, absl::nullopt); break; case DevToolsURLLoaderInterceptor::AuthChallengeResponse:: kProvideCredentials: std::move(pending_auth_callback_).Run(false, response.credentials); break; } state_ = kRequestSent; } Response InterceptionJob::ProcessResponseOverride( scoped_refptr<net::HttpResponseHeaders> headers, scoped_refptr<base::RefCountedMemory> body, size_t response_body_offset) { CancelRequest(); DCHECK_LE(response_body_offset, body ? body->size() : 0); size_t body_size = body ? body->size() - response_body_offset : 0; response_metadata_ = std::make_unique<ResponseMetadata>(); network::mojom::URLResponseHeadPtr& head = response_metadata_->head; head->request_time = start_time_; head->response_time = base::Time::Now(); // TODO(caseq): we're only doing this because some clients expect load timing // to be present with mocked responses. Consider removing this. const base::TimeTicks now_ticks = base::TimeTicks::Now(); head->load_timing.request_start_time = start_time_; head->load_timing.request_start = start_ticks_; head->load_timing.receive_headers_end = now_ticks; static const char kDummyHeaders[] = "HTTP/1.1 200 OK\0\0"; head->headers = std::move(headers); if (!head->headers) { head->headers = base::MakeRefCounted<net::HttpResponseHeaders>(kDummyHeaders); } head->headers->GetMimeTypeAndCharset(&head->mime_type, &head->charset); const GURL& url = create_loader_params_->request.url; if (create_loader_params_->options & network::mojom::kURLLoadOptionSniffMimeType) { if (body_size && network::ShouldSniffContent(url, *head)) { size_t bytes_to_sniff = std::min(body_size, static_cast<size_t>(net::kMaxBytesToSniff)); const std::string hint = head->mime_type; net::SniffMimeType( base::StringPiece(body->front_as<const char>() + response_body_offset, bytes_to_sniff), url, hint, net::ForceSniffFileUrlsForHtml::kDisabled, &head->mime_type); head->did_mime_sniff = true; } else if (head->mime_type.empty()) { head->mime_type.assign("text/plain"); } } // TODO(caseq): we're cheating here a bit, raw_headers() have \0's // where real headers would have \r\n, but the sizes here // probably don't have to be exact. size_t headers_size = head->headers->raw_headers().size(); head->content_length = body_size; head->encoded_data_length = headers_size; head->encoded_body_length = 0; head->request_start = start_ticks_; head->response_start = now_ticks; response_metadata_->transfer_size = body_size; response_metadata_->status.completion_time = base::TimeTicks::Now(); response_metadata_->status.encoded_data_length = headers_size + body_size; response_metadata_->status.encoded_body_length = body_size; response_metadata_->status.decoded_body_length = body_size; base::OnceClosure continue_after_cookies_set; std::string location; if (head->headers->IsRedirect(&location)) { GURL redirect_url = url.Resolve(location); if (redirect_url.is_valid()) { continue_after_cookies_set = base::BindOnce(&InterceptionJob::ProcessRedirectByClient, base::Unretained(this), std::move(redirect_url)); } } if (!continue_after_cookies_set) { continue_after_cookies_set = base::BindOnce(&InterceptionJob::SendResponse, base::Unretained(this), std::move(body), response_body_offset); } ProcessSetCookies(*head->headers, std::move(continue_after_cookies_set)); return Response::Success(); } void InterceptionJob::ProcessSetCookies(const net::HttpResponseHeaders& headers, base::OnceClosure callback) { if (!GetResourceRequestForCookies().SavesCookies()) { std::move(callback).Run(); return; } std::vector<std::unique_ptr<net::CanonicalCookie>> cookies; base::Time response_date; absl::optional<base::Time> server_time = absl::nullopt; if (headers.GetDateValue(&response_date)) server_time = absl::make_optional(response_date); base::Time now = base::Time::Now(); const base::StringPiece name("Set-Cookie"); std::string cookie_line; size_t iter = 0; while (headers.EnumerateHeader(&iter, name, &cookie_line)) { std::unique_ptr<net::CanonicalCookie> cookie = net::CanonicalCookie::Create( create_loader_params_->request.url, cookie_line, now, server_time, net::CookiePartitionKey::Todo()); if (cookie) cookies.emplace_back(std::move(cookie)); } net::CookieOptions options; options.set_include_httponly(); bool should_treat_as_first_party = GetContentClient() ->browser() ->ShouldIgnoreSameSiteCookieRestrictionsWhenTopLevel( create_loader_params_->request.site_for_cookies.scheme(), create_loader_params_->request.url.SchemeIsCryptographic()); DCHECK_EQ(create_loader_params_->request.url, url_chain_.back()); bool is_main_frame_navigation = create_loader_params_->request.trusted_params.has_value() && create_loader_params_->request.trusted_params->isolation_info .request_type() == net::IsolationInfo::RequestType::kMainFrame; options.set_same_site_cookie_context( net::cookie_util::ComputeSameSiteContextForResponse( url_chain_, create_loader_params_->request.site_for_cookies, create_loader_params_->request.request_initiator, is_main_frame_navigation, should_treat_as_first_party)); // |this| might be deleted here if |cookies| is empty! auto on_cookie_set = base::BindRepeating( [](base::RepeatingClosure closure, net::CookieAccessResult) { closure.Run(); }, base::BarrierClosure(cookies.size(), std::move(callback))); for (auto& cookie : cookies) { cookie_manager_->SetCanonicalCookie( *cookie, create_loader_params_->request.url, options, on_cookie_set); } } void InterceptionJob::ProcessRedirectByClient(const GURL& redirect_url) { DCHECK(redirect_url.is_valid()); const net::HttpResponseHeaders& headers = *response_metadata_->head->headers; const network::ResourceRequest& request = create_loader_params_->request; auto first_party_url_policy = request.update_first_party_url_on_redirect ? net::RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT : net::RedirectInfo::FirstPartyURLPolicy::NEVER_CHANGE_URL; response_metadata_->redirect_info = std::make_unique<net::RedirectInfo>( net::RedirectInfo::ComputeRedirectInfo( request.method, request.url, request.site_for_cookies, first_party_url_policy, request.referrer_policy, request.referrer.spec(), headers.response_code(), redirect_url, net::RedirectUtil::GetReferrerPolicyHeader(&headers), false /* insecure_scheme_was_upgraded */, true /* copy_fragment */)); client_->OnReceiveRedirect(*response_metadata_->redirect_info, std::move(response_metadata_->head)); } void InterceptionJob::SendResponse(scoped_refptr<base::RefCountedMemory> body, size_t offset) { client_->OnReceiveResponse(std::move(response_metadata_->head)); if (response_metadata_->cached_metadata.size() != 0) client_->OnReceiveCachedMetadata( std::move(response_metadata_->cached_metadata)); if (body) { DCHECK_LE(offset, body->size()); size_t body_size = body->size() - offset; // We shouldn't be able to transfer a string that big over the protocol, // but just in case... DCHECK_LE(body_size, UINT32_MAX) << "Response bodies larger than " << UINT32_MAX << " are not supported"; mojo::ScopedDataPipeProducerHandle producer_handle; mojo::ScopedDataPipeConsumerHandle consumer_handle; CHECK_EQ(mojo::CreateDataPipe(body_size, producer_handle, consumer_handle), MOJO_RESULT_OK); uint32_t num_bytes = body_size; MojoResult res = producer_handle->WriteData( body->front() + offset, &num_bytes, MOJO_WRITE_DATA_FLAG_NONE); DCHECK_EQ(0u, res); DCHECK_EQ(num_bytes, body_size); client_->OnStartLoadingResponseBody(std::move(consumer_handle)); } if (response_metadata_->transfer_size) client_->OnTransferSizeUpdated(response_metadata_->transfer_size); CompleteRequest(response_metadata_->status); } void InterceptionJob::ResponseBodyComplete() { if (waiting_for_resolution_) return; // We're here only if client has already told us to proceed with unmodified // response. SendResponse(body_reader_->body(), 0); } void InterceptionJob::StartRequest() { DCHECK_EQ(State::kNotStarted, state_); DCHECK(!response_metadata_); state_ = State::kRequestSent; target_factory_->CreateLoaderAndStart( loader_.BindNewPipeAndPassReceiver(), create_loader_params_->request_id, create_loader_params_->options, create_loader_params_->request, client_receiver_.BindNewPipeAndPassRemote(), create_loader_params_->traffic_annotation); client_receiver_.set_disconnect_handler( base::BindOnce(&InterceptionJob::Shutdown, base::Unretained(this))); if (priority_) loader_->SetPriority(priority_->first, priority_->second); } void InterceptionJob::CancelRequest() { if (state_ == State::kNotStarted) return; client_receiver_.reset(); loader_.reset(); if (body_reader_) { body_reader_->CancelWithError( "Another command has cancelled the fetch request"); body_reader_.reset(); } state_ = State::kNotStarted; } std::unique_ptr<InterceptedRequestInfo> InterceptionJob::BuildRequestInfo( const network::mojom::URLResponseHeadPtr& head) { auto result = std::make_unique<InterceptedRequestInfo>(); result->interception_id = current_id_; if (renderer_request_id_.has_value()) result->renderer_request_id = renderer_request_id_.value(); result->frame_id = frame_token_; blink::mojom::ResourceType resource_type = static_cast<blink::mojom::ResourceType>( create_loader_params_->request.resource_type); result->resource_type = resource_type; result->is_navigation = resource_type == blink::mojom::ResourceType::kMainFrame || resource_type == blink::mojom::ResourceType::kSubFrame; if (head && head->headers) result->response_headers = head->headers; return result; } void InterceptionJob::FetchCookies( network::mojom::CookieManager::GetCookieListCallback callback) { if (!GetResourceRequestForCookies().SendsCookies()) { std::move(callback).Run({}, {}); return; } net::CookieOptions options; options.set_include_httponly(); options.set_do_not_update_access_time(); const network::ResourceRequest& request = create_loader_params_->request; DCHECK_EQ(request.url, url_chain_.back()); bool should_treat_as_first_party = GetContentClient() ->browser() ->ShouldIgnoreSameSiteCookieRestrictionsWhenTopLevel( request.site_for_cookies.scheme(), request.url.SchemeIsCryptographic()); bool is_main_frame_navigation = request.trusted_params.has_value() && request.trusted_params->isolation_info.request_type() == net::IsolationInfo::RequestType::kMainFrame; options.set_same_site_cookie_context( net::cookie_util::ComputeSameSiteContextForRequest( request.method, url_chain_, request.site_for_cookies, request.request_initiator, is_main_frame_navigation, should_treat_as_first_party)); cookie_manager_->GetCookieList(request.url, options, net::CookiePartitionKeychain::Todo(), std::move(callback)); } void InterceptionJob::NotifyClient( std::unique_ptr<InterceptedRequestInfo> request_info) { DCHECK(!waiting_for_resolution_); FetchCookies(base::BindOnce(&InterceptionJob::NotifyClientWithCookies, base::Unretained(this), std::move(request_info))); } void InterceptionJob::NotifyClientWithCookies( std::unique_ptr<InterceptedRequestInfo> request_info, const net::CookieAccessResultList& cookies_with_access_result, const net::CookieAccessResultList& excluded_cookies) { if (!interceptor_) return; std::string cookie_line; if (!cookies_with_access_result.empty()) { cookie_line = net::CanonicalCookie::BuildCookieLine(cookies_with_access_result); } request_info->network_request = protocol::NetworkHandler::CreateRequestFromResourceRequest( create_loader_params_->request, cookie_line); waiting_for_resolution_ = true; interceptor_->request_intercepted_callback_.Run(std::move(request_info)); } void InterceptionJob::CompleteRequest( const network::URLLoaderCompletionStatus& status) { client_->OnComplete(status); Shutdown(); } void InterceptionJob::Shutdown() { if (interceptor_) interceptor_->RemoveJob(current_id_); delete this; } // URLLoader methods void InterceptionJob::FollowRedirect( const std::vector<std::string>& removed_headers, const net::HttpRequestHeaders& modified_headers, const net::HttpRequestHeaders& modified_cors_exempt_headers, const absl::optional<GURL>& new_url) { DCHECK(!new_url.has_value()) << "Redirect with modified url was not " "supported yet. crbug.com/845683"; DCHECK(!waiting_for_resolution_); network::ResourceRequest* request = &create_loader_params_->request; const net::RedirectInfo& info = *response_metadata_->redirect_info; const auto current_origin = url::Origin::Create(request->url); const auto new_origin = url::Origin::Create(info.new_url); if (request->request_initiator && (!new_origin.IsSameOriginWith(current_origin) && !request->request_initiator->IsSameOriginWith(current_origin))) { tainted_origin_ = true; } bool clear_body = false; net::RedirectUtil::UpdateHttpRequest(request->url, request->method, info, removed_headers, modified_headers, &request->headers, &clear_body); request->cors_exempt_headers.MergeFrom(modified_cors_exempt_headers); for (const std::string& name : removed_headers) request->cors_exempt_headers.RemoveHeader(name); if (clear_body) request->request_body = nullptr; request->method = info.new_method; request->url = info.new_url; request->site_for_cookies = info.new_site_for_cookies; request->referrer_policy = info.new_referrer_policy; request->referrer = GURL(info.new_referrer); if (request->trusted_params) { request->trusted_params->isolation_info = request->trusted_params->isolation_info.CreateForRedirect(new_origin); } response_metadata_.reset(); UpdateCORSFlag(); url_chain_.push_back(create_loader_params_->request.url); if (interceptor_) { // Pretend that each redirect hop is a new request -- this is for // compatibilty with URLRequestJob-based interception implementation. interceptor_->RemoveJob(current_id_); redirect_count_++; if (StartJobAndMaybeNotify()) return; } if (state_ == State::kRedirectReceived) { state_ = State::kRequestSent; loader_->FollowRedirect(removed_headers, modified_headers, modified_cors_exempt_headers, absl::nullopt /* new_url */); return; } DCHECK_EQ(State::kNotStarted, state_); StartRequest(); } void InterceptionJob::SetPriority(net::RequestPriority priority, int32_t intra_priority_value) { priority_ = std::make_pair(priority, intra_priority_value); if (loader_) loader_->SetPriority(priority, intra_priority_value); } void InterceptionJob::PauseReadingBodyFromNet() { if (!body_reader_ && loader_ && state_ != State::kResponseTaken) loader_->PauseReadingBodyFromNet(); } void InterceptionJob::ResumeReadingBodyFromNet() { if (!body_reader_ && loader_ && state_ != State::kResponseTaken) loader_->ResumeReadingBodyFromNet(); } // URLLoaderClient methods void InterceptionJob::OnReceiveEarlyHints( network::mojom::EarlyHintsPtr early_hints) { client_->OnReceiveEarlyHints(std::move(early_hints)); } void InterceptionJob::OnReceiveResponse( network::mojom::URLResponseHeadPtr head) { state_ = State::kResponseReceived; DCHECK(!response_metadata_); if (!(stage_ & InterceptionStage::RESPONSE)) { client_->OnReceiveResponse(std::move(head)); return; } loader_->PauseReadingBodyFromNet(); client_receiver_.Pause(); auto request_info = BuildRequestInfo(head); const network::ResourceRequest& request = create_loader_params_->request; request_info->is_download = request_info->is_navigation && (is_download_ || download_utils::IsDownload( request.url, head->headers.get(), head->mime_type)); response_metadata_ = std::make_unique<ResponseMetadata>(std::move(head)); NotifyClient(std::move(request_info)); } void InterceptionJob::OnReceiveRedirect( const net::RedirectInfo& redirect_info, network::mojom::URLResponseHeadPtr head) { DCHECK_EQ(State::kRequestSent, state_); state_ = State::kRedirectReceived; response_metadata_ = std::make_unique<ResponseMetadata>(head.Clone()); response_metadata_->redirect_info = std::make_unique<net::RedirectInfo>(redirect_info); if (!(stage_ & InterceptionStage::RESPONSE)) { client_->OnReceiveRedirect(redirect_info, std::move(head)); return; } std::unique_ptr<InterceptedRequestInfo> request_info = BuildRequestInfo(head); request_info->redirect_url = redirect_info.new_url.spec(); NotifyClient(std::move(request_info)); } void InterceptionJob::OnUploadProgress(int64_t current_position, int64_t total_size, OnUploadProgressCallback callback) { if (!report_upload_) return; client_->OnUploadProgress(current_position, total_size, std::move(callback)); } void InterceptionJob::OnReceiveCachedMetadata(mojo_base::BigBuffer data) { if (ShouldBypassForResponse()) client_->OnReceiveCachedMetadata(std::move(data)); else response_metadata_->cached_metadata = std::move(data); } void InterceptionJob::OnTransferSizeUpdated(int32_t transfer_size_diff) { if (ShouldBypassForResponse()) client_->OnTransferSizeUpdated(transfer_size_diff); else response_metadata_->transfer_size += transfer_size_diff; } void InterceptionJob::OnStartLoadingResponseBody( mojo::ScopedDataPipeConsumerHandle body) { if (pending_response_body_pipe_callback_) { DCHECK_EQ(State::kResponseTaken, state_); DCHECK(!body_reader_); std::move(pending_response_body_pipe_callback_) .Run(Response::Success(), std::move(body), response_metadata_->head->mime_type); return; } DCHECK_EQ(State::kResponseReceived, state_); if (ShouldBypassForResponse()) client_->OnStartLoadingResponseBody(std::move(body)); else body_reader_->StartReading(std::move(body)); } void InterceptionJob::OnComplete( const network::URLLoaderCompletionStatus& status) { // No need to listen to the channel any more, so just reset it, so if the pipe // is closed by the other end, |shutdown| isn't run. client_receiver_.reset(); loader_.reset(); if (!response_metadata_) { // If we haven't seen response and get an error completion, // treat it as a response and intercept (provided response are // being intercepted). if (!(stage_ & InterceptionStage::RESPONSE) || !status.error_code) { CompleteRequest(status); return; } response_metadata_ = std::make_unique<ResponseMetadata>(); response_metadata_->status = status; auto request_info = BuildRequestInfo(nullptr); request_info->response_error_code = status.error_code; NotifyClient(std::move(request_info)); return; } // Since we're not forwarding OnComplete right now, make sure // we're in the proper state. The completion is due upon client response. DCHECK(state_ == State::kResponseReceived || state_ == State::kResponseTaken); DCHECK(waiting_for_resolution_); response_metadata_->status = status; } void InterceptionJob::OnAuthRequest( const net::AuthChallengeInfo& auth_info, DevToolsURLLoaderInterceptor::HandleAuthRequestCallback callback) { DCHECK_EQ(kRequestSent, state_); DCHECK(pending_auth_callback_.is_null()); DCHECK(!waiting_for_resolution_); if (!(stage_ & InterceptionStage::REQUEST) || !interceptor_ || !interceptor_->handle_auth_) { std::move(callback).Run(true, absl::nullopt); return; } state_ = State::kAuthRequired; auto request_info = BuildRequestInfo(nullptr); request_info->auth_challenge = std::make_unique<net::AuthChallengeInfo>(auth_info); pending_auth_callback_ = std::move(callback); NotifyClient(std::move(request_info)); } DevToolsURLLoaderFactoryAdapter::DevToolsURLLoaderFactoryAdapter( mojo::PendingRemote<network::mojom::URLLoaderFactory> factory) : factory_(std::move(factory)) {} DevToolsURLLoaderFactoryAdapter::~DevToolsURLLoaderFactoryAdapter() = default; void DevToolsURLLoaderFactoryAdapter::CreateLoaderAndStart( mojo::PendingReceiver<network::mojom::URLLoader> loader, int32_t request_id, uint32_t options, const network::ResourceRequest& request, mojo::PendingRemote<network::mojom::URLLoaderClient> client, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) { factory_->CreateLoaderAndStart(std::move(loader), request_id, options, request, std::move(client), traffic_annotation); } void DevToolsURLLoaderFactoryAdapter::Clone( mojo::PendingReceiver<network::mojom::URLLoaderFactory> receiver) { factory_->Clone(std::move(receiver)); } } // namespace content
38.249077
80
0.735742
[ "vector" ]
ed9016ec11758febdf5c0890fc0e2454aadd0d07
1,477
cpp
C++
Sid's Levels/InterviewBit/Backtracking/N-Queens.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
Sid's Levels/InterviewBit/Backtracking/N-Queens.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
Sid's Levels/InterviewBit/Backtracking/N-Queens.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
class Solution { public: //OM GAN GANAPATHAYE NAMO NAMAH //JAI SHRI RAM //JAI BAJRANGBALI //AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA void solve(vector<string> &board, int r, int n, vector<bool> &col, vector<bool> &ud, vector<bool> &ld, vector<vector<string>> &res) { if(r == n) { res.push_back(board); } else { for(int i = 0; i < n; i++) { if(board[r][i] == '.' && ud[n-(r-i)] == false && col[i] == false && ld[r+i] == false) { board[r][i] = 'Q'; ud[n-(r-i)] = true; col[i] = true; ld[r+i] = true; solve(board, r+1, n, col, ud, ld, res); board[r][i] = '.'; ud[n-(r-i)] = false; col[i] = false; ld[r+i] = false; } } } return; } vector<vector<string>> solveNQueens(int n) { vector<string> board; vector<vector<string>> res; for(int i = 0; i < n; i++) { string s; for(int j = 0; j < n; j++) { s.push_back('.'); } board.push_back(s); } vector<bool> col(n, false), ld(n, false), ud(n, false); solve(board, 0, n, col, ud, ld, res); return res; } };
29.54
135
0.389303
[ "vector" ]
ed918af7177e95ca54038ab4c09e7b99cf975b17
4,824
cpp
C++
tests/DataStructures/VectorFloatUnitTest.cpp
torydebra/grt
6c3fe9e5ab470d840b1c3e613ee0356d209eef7b
[ "MIT", "Unlicense" ]
818
2015-01-03T05:21:04.000Z
2022-03-30T00:43:09.000Z
tests/DataStructures/VectorFloatUnitTest.cpp
torydebra/grt
6c3fe9e5ab470d840b1c3e613ee0356d209eef7b
[ "MIT", "Unlicense" ]
131
2015-01-26T08:50:57.000Z
2022-01-12T07:51:53.000Z
tests/DataStructures/VectorFloatUnitTest.cpp
torydebra/grt
6c3fe9e5ab470d840b1c3e613ee0356d209eef7b
[ "MIT", "Unlicense" ]
301
2015-01-15T12:36:54.000Z
2022-03-14T20:12:10.000Z
#include <GRT.h> #include "gtest/gtest.h" using namespace GRT; //Unit tests for the GRT Vector class // Tests the default c'tor. TEST(VectorFloat, DefaultConstructor) { VectorFloat vec; EXPECT_EQ(0, vec.getSize()); } // Tests the resize c'tor. TEST(VectorFloat, ResizeConstructor) { const UINT size = 100; VectorFloat vec(size); EXPECT_EQ(size, vec.getSize()); } // Tests the copy c'tor. TEST(VectorFloat, CopyConstructor) { const UINT size = 100; VectorFloat vec1(size); EXPECT_EQ(size, vec1.getSize()); VectorFloat vec2( vec1 ); EXPECT_EQ(vec1.getSize(), vec2.getSize()); } // Tests the equals operator. TEST(VectorFloat, EqualsConstructor) { const UINT size = 100; VectorFloat vec1(size); EXPECT_EQ(size, vec1.getSize()); VectorFloat vec2; vec2 = vec1; EXPECT_EQ(vec1.getSize(), vec2.getSize()); } // Tests the Vector< Float > equals operator. TEST(VectorFloat, VecFloatEqualsConstructor) { const UINT size = 100; Vector< Float > vec1(size); EXPECT_EQ(size, vec1.getSize()); VectorFloat vec2; vec2 = vec1; EXPECT_EQ(vec1.getSize(), vec2.getSize()); } // Tests the save and load methods. TEST(VectorFloat, SaveLoad) { const UINT size = 100; VectorFloat vec1(size); EXPECT_EQ(size, vec1.getSize()); for (UINT i=0; i<size; i++) { vec1[i] = i*1.0; } //Save the vector to a CSV file EXPECT_TRUE(vec1.save("vec.csv")); //Load the data from the file into another vector VectorFloat vec2; EXPECT_TRUE(vec2.load("vec.csv")); //Vector 2 should now be the same size as vector 1 EXPECT_EQ(vec1.getSize(), vec2.getSize()); //Check to make sure the values match for (UINT i=0; i<size; i++) { EXPECT_EQ(vec1[i], vec2[i]); } } // Tests the scale function TEST(VectorFloat, Scale) { const UINT size = 100; VectorFloat vec( size ); EXPECT_EQ(size, vec.getSize()); for (UINT i=0; i<size; i++) { vec[i] = i*1.0; } //Scale the contents in the vector const Float minTarget = -1.0f; const Float maxTarget = 1.0f; EXPECT_TRUE(vec.scale(minTarget,maxTarget)); EXPECT_EQ(vec.getMinValue(), minTarget); EXPECT_EQ(vec.getMaxValue(), maxTarget); } // Tests the min-max scale function TEST(VectorFloat, MinMaxScale) { const UINT size = 100; VectorFloat vec(size); EXPECT_EQ(size, vec.getSize()); for (UINT i=0; i<size; i++) { vec[i] = i*1.0; } //Scale the contents in the vector Float minSource = 10; //Deliberately set the min source to 10, even though the min value should be 0 Float maxSource = 90; //Deliberately set the max source to 90, even though the max value should be 100 Float minTarget = -1.0f; Float maxTarget = 1.0f; EXPECT_TRUE(vec.scale(minSource, maxSource, minTarget, maxTarget, true)); EXPECT_EQ(vec.getMinValue(), minTarget); EXPECT_EQ(vec.getMaxValue(), maxTarget); //Reset the data for (UINT i=0; i<size; i++) { vec[i] = i*1.0; } EXPECT_TRUE(vec.scale(minSource, maxSource, minTarget, maxTarget, false)); //Re-run the scaling with constraining off EXPECT_TRUE(fabs( vec.getMinValue() - minTarget ) > 0.01 ); //The min value should no longer match the min target EXPECT_TRUE(fabs( vec.getMaxValue() - maxTarget ) > 0.01 ); //The max value should no longer match the max target } // Tests the getMinValue TEST(VectorFloat, GetMin) { const UINT size = 100; VectorFloat vec(size); EXPECT_EQ(size, vec.getSize()); for (UINT i=0; i<size; i++) { vec[i] = i*1.0; } EXPECT_EQ(vec.getMinValue(), 0.0f); } // Tests the getMaxValue TEST(VectorFloat, GetMax) { const UINT size = 100; VectorFloat vec(size); EXPECT_EQ(size, vec.getSize()); for (UINT i=0; i<size; i++) { vec[i] = i*1.0; } EXPECT_EQ(vec.getMaxValue(), 99.0f); } // Tests the getMean TEST(VectorFloat, GetMean) { const UINT size = 100; VectorFloat vec(size); EXPECT_EQ(size, vec.getSize()); for (UINT i=0; i<size; i++) { vec[i] = i*1.0; } Float mean = 0.0; for (UINT i=0; i<size; i++) { mean += vec[i]; } mean /= size; EXPECT_EQ(vec.getMean(), mean); } // Tests the getStdDev TEST(VectorFloat, GetStdDev) { const UINT size = 100; VectorFloat vec(size); EXPECT_EQ(size, vec.getSize()); for (UINT i=0; i<size; i++) { vec[i] = i*1.0; } Float mean = 0.0; Float stddev = 0.0; for (UINT i=0; i<size; i++) { mean += vec[i]; } mean /= size; for (UINT i=0; i<size; i++) { stddev += grt_sqr(vec[i]-mean); } stddev = grt_sqrt(stddev / (size-1)); EXPECT_EQ(vec.getStdDev(), stddev); } // Tests the getMinMax TEST(VectorFloat, GetMinMax) { const UINT size = 100; VectorFloat vec(size); EXPECT_EQ(size, vec.getSize()); for (UINT i=0; i<size; i++) { vec[i] = i*1.0; } const Float expectedMin = 0.0; const Float expectedMax = size-1; const MinMax result = vec.getMinMax(); EXPECT_EQ(expectedMin, result.minValue); EXPECT_EQ(expectedMax, result.maxValue); } int main(int argc, char **argv) { ::testing::InitGoogleTest( &argc, argv ); return RUN_ALL_TESTS(); }
27.254237
118
0.683043
[ "vector" ]
ed996274d1b13be2fac24f27b50decefd6a9f98c
340
cpp
C++
framework/opengl_renderer/src/mm/opengl/render_tasks/clear.cpp
ford442/MushMachine
dc37ad54ec02aa4c1c30cca99d965cd705b3fa2f
[ "MIT" ]
20
2020-10-06T07:30:14.000Z
2022-03-31T14:00:33.000Z
framework/opengl_renderer/src/mm/opengl/render_tasks/clear.cpp
ford442/MushMachine
dc37ad54ec02aa4c1c30cca99d965cd705b3fa2f
[ "MIT" ]
null
null
null
framework/opengl_renderer/src/mm/opengl/render_tasks/clear.cpp
ford442/MushMachine
dc37ad54ec02aa4c1c30cca99d965cd705b3fa2f
[ "MIT" ]
2
2020-11-21T15:42:37.000Z
2021-11-07T07:12:02.000Z
#include "./clear.hpp" //#include <tracy/Tracy.hpp> namespace MM::OpenGL::RenderTasks { Clear::Clear(Engine&) { } Clear::~Clear(void) { } void Clear::render(Services::OpenGLRenderer& rs, Engine&) { //ZoneScopedN("MM::OpenGL::RenderTasks::Clear::render"); rs.targets[target_fbo]->clear(r,g,b,a,mask); } } // MM::OpenGL::RenderTasks
17
59
0.676471
[ "render" ]
ed9bd27bb34de753bf8a23eb9ac573ab487f491a
1,537
cpp
C++
dbms/src/Formats/ProtobufColumnMatcher.cpp
sunadm/ClickHouse
55903fbe23ef6dff8fc7ec25ae68e04919bc9b7f
[ "Apache-2.0" ]
7
2021-02-26T04:34:22.000Z
2021-12-31T08:15:47.000Z
dbms/src/Formats/ProtobufColumnMatcher.cpp
sunadm/ClickHouse
55903fbe23ef6dff8fc7ec25ae68e04919bc9b7f
[ "Apache-2.0" ]
3
2020-02-18T14:59:34.000Z
2020-02-19T10:42:18.000Z
dbms/src/Formats/ProtobufColumnMatcher.cpp
sunadm/ClickHouse
55903fbe23ef6dff8fc7ec25ae68e04919bc9b7f
[ "Apache-2.0" ]
3
2020-02-24T12:57:54.000Z
2021-10-04T13:29:00.000Z
#include "ProtobufColumnMatcher.h" #if USE_PROTOBUF #include <Common/Exception.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/descriptor.pb.h> #include <Poco/String.h> namespace DB { namespace ErrorCodes { extern const int NO_COMMON_COLUMNS_WITH_PROTOBUF_SCHEMA; } namespace { String columnNameToSearchableForm(const String & str) { return Poco::replace(Poco::toUpper(str), ".", "_"); } } namespace ProtobufColumnMatcher { namespace details { ColumnNameMatcher::ColumnNameMatcher(const std::vector<String> & column_names) : column_usage(column_names.size()) { column_usage.resize(column_names.size(), false); for (size_t i = 0; i != column_names.size(); ++i) column_name_to_index_map.emplace(columnNameToSearchableForm(column_names[i]), i); } size_t ColumnNameMatcher::findColumn(const String & field_name) { auto it = column_name_to_index_map.find(columnNameToSearchableForm(field_name)); if (it == column_name_to_index_map.end()) return -1; size_t column_index = it->second; if (column_usage[column_index]) return -1; column_usage[column_index] = true; return column_index; } void throwNoCommonColumns() { throw Exception("No common columns with provided protobuf schema", ErrorCodes::NO_COMMON_COLUMNS_WITH_PROTOBUF_SCHEMA); } } } } #endif
26.964912
131
0.648666
[ "vector" ]
ed9fa9cbc2f37ea2f5f91396af9e07cb6c11e967
21,559
cpp
C++
TeamT2_ARC2017_src/t2_robot_vision/src/cluster.cpp
warehouse-picking-automation-challenges/Team_T2
7cf4c211dcd5726fbe876ff555b76602148d21ad
[ "BSD-3-Clause" ]
2
2020-05-24T14:09:34.000Z
2021-01-27T08:01:39.000Z
TeamT2_ARC2017_src/t2_robot_vision/src/cluster.cpp
warehouse-picking-automation-challenges/Team_T2
7cf4c211dcd5726fbe876ff555b76602148d21ad
[ "BSD-3-Clause" ]
null
null
null
TeamT2_ARC2017_src/t2_robot_vision/src/cluster.cpp
warehouse-picking-automation-challenges/Team_T2
7cf4c211dcd5726fbe876ff555b76602148d21ad
[ "BSD-3-Clause" ]
1
2020-05-24T14:09:36.000Z
2020-05-24T14:09:36.000Z
/* * Software License Agreement (BSD License) * * Copyright (c) 2017, Toshiba Corporation, * Toshiba Infrastructure Systems & Solutions Corporation * 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 Toshiba Corporation, nor the Toshiba * Infrastructure Systems & Solutions Corporation, nor the names * of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <memory> #include <list> #include <opencv2/core/core.hpp> #include <opencv2/opencv.hpp> #include <limits.h> #include <time.h> #include "cluster.hpp" #ifdef LIB_CLUSTER #include "cluster_sub.hpp" #endif //LIB_CLUSTER #include "robot_vision_segment.h" #include <ros/package.h> #include <ros/console.h> #include <log4cxx/logger.h> #endif static void CalcDensityMap(cv::Mat pCloud, cv::Mat& iDens, int radius){ int w = pCloud.cols; int h = pCloud.rows; cv::Mat iIntvl(h, w, CV_8UC1); for(int j=0; j<h; j++){ for(int i=0; i<w; i++){ iIntvl.at<unsigned char>(j,i) = 1; } } cv::Mat iGrad(pCloud.rows, pCloud.cols, CV_32FC1); for(int j=0; j<pCloud.rows; j++){ for(int i=0; i<pCloud.cols; i++){ int interval = iIntvl.at<unsigned char>(j,i); int sx = i-interval; int ex = i+interval; int sy = j-interval; int ey = j+interval; if(sx<0){sx=0;} if(ex>=w){ex=w-1;} if(sy<0){sy=0;} if(ey>=h){ey=h-1;} double dx = pCloud.at<cv::Vec3f>(j,sx)[2]-pCloud.at<cv::Vec3f>(j,ex)[2]; double dy = pCloud.at<cv::Vec3f>(sy,i)[2]-pCloud.at<cv::Vec3f>(ey,i)[2]; iGrad.at<float>(j,i) = sqrt(dx*dx+dy*dy + 1); } } if(iDens.rows!=h || iDens.cols!=w){ iDens = cv::Mat(h,w,CV_32FC1); } double max = 0; for(int j=0; j<h; j++){ for(int i=0; i<w; i++){ double z = pCloud.at<cv::Vec3f>(j,i)[2]; if(z == 0){ iDens.at<float>(j,i) = 0; continue; } double denom = z*z*iGrad.at<float>(j,i); iDens.at<float>(j,i) = (radius*radius)/denom; if(max < iDens.at<float>(j,i)){ max = iDens.at<float>(j,i); } } } for(int j=0; j<h; j++){ for(int i=0; i<w; i++){ iDens.at<float>(j,i) = 1 - iDens.at<float>(j,i)*1/max; } } } static void UpdateClusterList(std::unique_ptr<CLUSTER[]>& clst, unsigned short int clst_num){ for(unsigned short int id = 0; id < clst_num; id++){ int cx = clst[id].cx; int cy = clst[id].cy; double r = clst[id].radius*2+1; //erase for(std::list<unsigned short int>::iterator itr = clst[id].id_list.begin(); itr != clst[id].id_list.end(); itr++){ unsigned short int id_n = *itr; int x = clst[id_n].cx; int y = clst[id_n].cy; if(abs(x-cx)>=r || abs(y-cy)>=r){ clst[id].id_list.erase(itr); } }//erase end //add for(unsigned short int i=0; i<clst_num; i++){ int x = clst[i].cx; int y = clst[i].cy; if(abs(x-cx)<r && abs(y-cy)<r){ clst[id].id_list.push_back(i); } }//add end clst[id].id_list.unique(); } } static void SetClstMat(cv::Mat pCloud, std::unique_ptr<CLUSTER[]>& clst, unsigned short int& clst_num, cv::Mat& clstMat){ int w = clstMat.cols; int h = clstMat.rows; for(int j=0; j<h; j++){ for(int i=0; i<w; i++){ if(clstMat.at<unsigned short int>(j,i)!=USHRT_MAX){ continue; } if(pCloud.at<cv::Vec3f>(j,i)[2] == 0){ clstMat.at<unsigned short int>(j,i) = USHRT_MAX; continue; } int min_id = USHRT_MAX; double min = w+h; for(unsigned short int id=0; id<clst_num; id++){ int cx = clst[id].cx; int cy = clst[id].cy; double r = clst[id].radius*8; if(abs(cx-i)>r || abs(cy-j)>r){ continue; } double len = (cx-i)*(cx-i)+(cy-j)*(cy-j); if(min > len){ min = len; min_id = id; } } if(min_id == USHRT_MAX){ for(unsigned short int id=0; id<clst_num; id++){ int cx = clst[id].cx; int cy = clst[id].cy; double len = (cx-i)*(cx-i)+(cy-j)*(cy-j); if(min > len){ min = len; min_id = id; } } } clstMat.at<unsigned short int>(j,i) = min_id; }//w }//h } static void SetClusterCenter(cv::Mat& iDens, int dens_th, cv::Mat pCloud, cv::Mat nvMat, cv::Mat iColor, std::unique_ptr<CLUSTER[]>& clst, unsigned short int& clst_num, cv::Mat& clstMat, double& mean_r){ int w = iDens.cols; int h = iDens.rows; typedef struct CLST_P CLST_P; struct CLST_P{ int cx; int cy; double radius; }; std::vector<CLST_P> c_vector; cv::Mat diMat(h+1, w+1, CV_64FC1); cv::Mat flgMat = cv::Mat::zeros(h,w,CV_8UC1); cv::integral(iDens, diMat, -1); for(int j=2; j<h-2; j++){ for(int i=2; i<w-2; i++){ if(flgMat.at<unsigned char>(j,i)!=0 || pCloud.at<cv::Vec3f>(j,i)[2] == 0){ continue; } if(c_vector.size() > USHRT_MAX/2){ break; } CLST_P clst_p; clst_p.cx = i; clst_p.cy = j; int r; for(r=2; r<20; r++){//3 if(i-r<0 || j-r<0 || i+r+1>=w || j+r+1>=h){ r--; break; } double score = diMat.at<double>(j+r+1,i+r+1) -diMat.at<double>(j-r,i+r+1) -diMat.at<double>(j+r+1,i-r) +diMat.at<double>(j-r,i-r); if(score > dens_th){ break; } } clst_p.radius = r; c_vector.push_back(clst_p); for(int q=j-r*2-1; q<j+r*2; q++){ if(q<0 || q>=h){ continue; } for(int p=i-r*2-1; p<i+r*2; p++){ if(p<0 || p>=w){ continue; } flgMat.at<unsigned char>(q,p) = 1; } } }//i }//j try{ std::unique_ptr<CLUSTER[]> buf(new CLUSTER[c_vector.size()]); clst = std::move(buf); clst_num = c_vector.size(); }catch(...){ clst_num = 0; return; } double total_radius = 0; clstMat = cv::Mat::ones(h, w, CV_16UC1)*USHRT_MAX; cv::Mat distMat = cv::Mat::ones(h,w,CV_16UC1)*USHRT_MAX; { unsigned short int i = 0; int c_flg = 0; for(std::vector<CLST_P>::iterator itr = c_vector.begin(); itr!=c_vector.end(); itr++){ if(i>= clst_num){ c_flg = 1; break; } CLST_P clst_p = *itr; int x = clst_p.cx; int y = clst_p.cy; double r = clst_p.radius; total_radius += r; clst[i].id = i; clst[i].cx = x; clst[i].cy = y; clst[i].radius = r; clst[i].position[0] = pCloud.at<cv::Vec3f>(y,x)[0]; clst[i].position[1] = pCloud.at<cv::Vec3f>(y,x)[1]; clst[i].position[2] = pCloud.at<cv::Vec3f>(y,x)[2]; clst[i].norm_v[0] = nvMat.at<cv::Vec3f>(y,x)[0]; clst[i].norm_v[1] = nvMat.at<cv::Vec3f>(y,x)[1]; clst[i].norm_v[2] = nvMat.at<cv::Vec3f>(y,x)[2]; clst[i].color[0] = iColor.at<cv::Vec3b>(y,x)[0]; clst[i].color[1] = iColor.at<cv::Vec3b>(y,x)[1]; clst[i].color[2] = iColor.at<cv::Vec3b>(y,x)[2]; clst[i].counter = 0; for(int q=y-r*4; q<=y+r*4; q++){ if(q<0 || q>=h){ continue; } for(int p=x-r*4; p<=x+r*4; p++){ if(p<0 || p>=w){ continue; } if(pCloud.at<cv::Vec3f>(q,p)[2] == 0){ continue; } unsigned short int d = abs(q-y)+abs(p-x); if(d < distMat.at<unsigned short int>(q,p)){ clstMat.at<unsigned short int>(q,p) = i; distMat.at<unsigned short int>(q,p) = d; } }//p }//q i++; } if(c_flg == 1){ clst_num = 0; return; } } if(clst_num>0){ mean_r = total_radius/clst_num; }else{ mean_r = 0; } SetClstMat(pCloud, clst, clst_num, clstMat); UpdateClusterList(clst, clst_num); } #ifndef LIB_CLUSTER static double LengthCluster(std::unique_ptr<CLUSTER[]>& clst, unsigned short int id, float p[3], float nv[3], float c[3]){ if(clst[id].position[2] == 0 && p[2]!=0){ return USHRT_MAX; } double p_diff = sqrt((clst[id].position[0]-p[0])*(clst[id].position[0]-p[0])+(clst[id].position[1]-p[1])*(clst[id].position[1]-p[1])+(clst[id].position[2]-p[2])*(clst[id].position[2]-p[2])); double nv_diff = 1-(clst[id].norm_v[0]*nv[0]+clst[id].norm_v[1]*nv[1]+clst[id].norm_v[2]*nv[2]); double c_diff = sqrt((clst[id].color[0]-c[0])*(clst[id].color[0]-c[0])+(clst[id].color[1]-c[1])*(clst[id].color[1]-c[1])+(clst[id].color[2]-c[2])*(clst[id].color[2]-c[2])); //return p_diff*50+nv_diff*2+c_diff/100; return p_diff*40+nv_diff*10+c_diff/10; } #endif //LIB_CLUSTER static bool LengthClusterMerge(std::unique_ptr<CLUSTER[]>& clst, unsigned short int id1, unsigned short int id2, double len_th, SegPrm seg_prm){ if(clst[id1].position[2] == 0 || clst[id2].position[2] == 0){ return false; } double nv_diff = (clst[id1].norm_v[0]*clst[id2].norm_v[0]+clst[id1].norm_v[1]*clst[id2].norm_v[1]+clst[id1].norm_v[2]*clst[id2].norm_v[2]); double p_diff = sqrt((clst[id1].position[0]-clst[id2].position[0])*(clst[id1].position[0]-clst[id2].position[0])+(clst[id1].position[1]-clst[id2].position[1])*(clst[id1].position[1]-clst[id2].position[1])+(clst[id1].position[2]-clst[id2].position[2])*(clst[id1].position[2]-clst[id2].position[2])); double plane_diff1 = (clst[id1].norm_v[0]*(clst[id2].position[0]-clst[id1].position[0])+clst[id1].norm_v[1]*(clst[id2].position[1]-clst[id1].position[1])+clst[id1].norm_v[2]*(clst[id2].position[2]-clst[id1].position[2])); double plane_diff2 = (clst[id2].norm_v[0]*(clst[id1].position[0]-clst[id2].position[0])+clst[id2].norm_v[1]*(clst[id1].position[1]-clst[id2].position[1])+clst[id2].norm_v[2]*(clst[id1].position[2]-clst[id2].position[2])); double c_diff = sqrt((clst[id1].color[0]-clst[id2].color[0])*(clst[id1].color[0]-clst[id2].color[0])+(clst[id1].color[1]-clst[id2].color[1])*(clst[id1].color[1]-clst[id2].color[1])+(clst[id1].color[2]-clst[id2].color[2])*(clst[id1].color[2]-clst[id2].color[2])); if(p_diff == 0){ return true; } if(p_diff > len_th){ return false; } double denom = 1; if(clst[id1].counter < 100){ denom = seg_prm.merge_nv_cos[0]; }else{ denom = seg_prm.merge_nv_cos[1]; } if(nv_diff < cos(M_PI/denom)){ return false; } double ph_ang = cos(M_PI/4); double c_ang = cos(M_PI/6); if(fabs(clst[id1].norm_v[2] < ph_ang) && fabs(clst[id2].norm_v[2]) < ph_ang){ return true; }else if(fabs(clst[id1].norm_v[2] < c_ang) && fabs(clst[id2].norm_v[2]) < c_ang){ denom = seg_prm.merge_plane_sin[0]; }else{ denom = seg_prm.merge_plane_sin[1]; } if((fabs(plane_diff1)/p_diff > sin(M_PI/denom) || fabs(plane_diff2)/p_diff > sin(M_PI/denom))){ return false; } if(c_diff > seg_prm.color_dist && nv_diff < seg_prm.color_nvdiff){ return false; } return true; } #ifndef LIB_CLUSTER static double MoveClstCenter(cv::Mat pCloud, cv::Mat nvMat, cv::Mat iColor, std::unique_ptr<CLUSTER[]>& clst, unsigned short int clst_num, cv::Mat& clstMat){ int w = pCloud.cols; int h = pCloud.rows; for(unsigned short int i=0; i<clst_num; i++){ clst[i].x_sum = 0; clst[i].y_sum = 0; clst[i].radius = w+h; for(int j=0; j<3; j++){ clst[i].p_sum[j] = 0; clst[i].n_sum[j] = 0; clst[i].c_sum[j] = 0; } clst[i].counter = 0; } double max_diff = 0; for(int j=0; j<h; j++){ for(int i=0; i<w; i++){ unsigned short int id = clstMat.at<unsigned short int>(j,i); if(id == USHRT_MAX){ continue; } float p[3]; float nv[3]; float c[3]; for(int k=0; k<3; k++){ p[k] = pCloud.at<cv::Vec3f>(j,i)[k]; nv[k] = nvMat.at<cv::Vec3f>(j,i)[k]; c[k] = iColor.at<cv::Vec3b>(j,i)[k]; } double min_len = USHRT_MAX; int min_id = id; for(std::list<unsigned short int>::iterator itr = clst[id].id_list.begin(); itr != clst[id].id_list.end(); itr++){ unsigned short int id_n = *itr; double len = LengthCluster(clst, id_n, p, nv, c); //double p_len = sqrt((p[0]-clst[id_n].position[0])*(p[0]-clst[id_n].position[0])+(p[1]-clst[id_n].position[1])*(p[1]-clst[id_n].position[1])+(p[2]-clst[id_n].position[2])*(p[2]-clst[id_n].position[2])); if(len < min_len){ if(min_len != USHRT_MAX && clst[min_id].radius > min_len && min_len > 0.005){ clst[min_id].radius = min_len; } min_len = len; min_id = id_n; }else if(id_n!=min_id){ double p_len = sqrt((p[0]-clst[id_n].position[0])*(p[0]-clst[id_n].position[0])+(p[1]-clst[id_n].position[1])*(p[1]-clst[id_n].position[1])+(p[2]-clst[id_n].position[2])*(p[2]-clst[id_n].position[2])); if(clst[id_n].radius > p_len && p_len > 0.005){ clst[id_n].radius = p_len; } } } clstMat.at<unsigned short int>(j,i) = min_id; clst[min_id].x_sum += i; clst[min_id].y_sum += j; for(int k=0; k<3; k++){ clst[min_id].p_sum[k] += p[k]; clst[min_id].n_sum[k] += nv[k]; clst[min_id].c_sum[k] += c[k]; } clst[min_id].counter++; if(min_len > max_diff){ max_diff = min_len; } }//i }//j for(unsigned short int i=0; i<clst_num; i++){ unsigned int denom = clst[i].counter; if(denom == 0){ continue; } clst[i].cx = clst[i].x_sum/denom; clst[i].cy = clst[i].y_sum/denom; for(int j=0; j<3; j++){ clst[i].position[j] = clst[i].p_sum[j]/denom; clst[i].norm_v[j] = clst[i].n_sum[j]/denom; clst[i].color[j] = clst[i].c_sum[j]/denom; } } return max_diff; } #endif //LIB_CLUSTER static void MergeCluster(std::unique_ptr<CLUSTER[]>& clst, unsigned short int clst_num, std::vector<CLST_SUB>& clst_mv, double mean_r, SegPrm seg_prm){ double len_th = 12; if(seg_prm.merge_len_th > 0){ len_th = mean_r * seg_prm.merge_len_th; }else{ len_th = mean_r * fabs(seg_prm.merge_len_th); } std::unique_ptr<unsigned short int[]> link; try{ std::unique_ptr<unsigned short int[]> buf(new unsigned short int[clst_num]); link = std::move(buf); }catch(...){ return; } for(unsigned short int i=0; i<clst_num; i++){ link[i] = i; } for(unsigned short int i=0; i<clst_num; i++){ double r_th = clst[i].radius*3; if(len_th < r_th){ r_th = len_th; } for(std::list<unsigned short int>::iterator itr = clst[i].id_list.begin(); itr != clst[i].id_list.end(); itr++){ unsigned short int j = *itr; bool flg = LengthClusterMerge(clst, i, j, r_th, seg_prm); if(flg){ unsigned short int buf = link[i]; while(buf!=i && buf!=j){ buf = link[buf]; } if(buf == i){ buf = link[i]; link[i] = link[j]; link[j] = buf; } }// len < th }// list }// clst_num std::unique_ptr<unsigned short int[]> table; try{ std::unique_ptr<unsigned short int[]> buf(new unsigned short int[clst_num]); table = std::move(buf); }catch(...){ return; } clst_mv.clear(); for(unsigned short int i=0; i<clst_num; i++){ table[i] = 0; } unsigned short int clst_num_new = 1; for(unsigned short int i=0; i<clst_num; i++){ if(table[i]!=0){ continue; } CLST_SUB clst_sub; clst_sub.id = clst_num_new; clst_sub.size = clst[i].counter; table[i] = clst_num_new; clst[i].id = table[i]; unsigned short int j = link[i]; while(j!=i){ table[j] = clst_num_new; clst[j].id = clst_num_new; clst_sub.size += clst[j].counter; j = link[j]; } clst_mv.push_back(clst_sub); clst_num_new++; } for(unsigned short int i=0; i<clst_num; i++){ if(link[i]!=i){ continue; } unsigned short int area_max = 0; unsigned short int id_max = USHRT_MAX; unsigned short int id_count = 0; unsigned short int n_count = 0; for(std::list<unsigned short int>::iterator itr = clst[i].id_list.begin(); itr != clst[i].id_list.end(); itr++){ unsigned short int j = *itr; n_count++; if(id_max == table[j]){ id_count++; continue; } if(area_max < clst_mv[table[j]-1].size){ area_max = clst_mv[table[j]-1].size; id_max = table[j]; id_count = 1; } } if(id_count*3 >= n_count){ clst[i].id = id_max; clst_mv[id_max-1].size += clst[i].counter; } } } void ClustSegment(cv::Mat pCloud, cv::Mat nvMat, cv::Mat iColor, SegPrm seg_prm, std::vector<SegmentMask>& seg_mask_v){ int w = pCloud.cols; int h = pCloud.rows; int radius = 80; cv::Mat iDens(h,w, CV_32FC1); CalcDensityMap(pCloud, iDens, radius); std::unique_ptr<CLUSTER[]> clst; unsigned short int clst_num; double mean_r; int dens_th = seg_prm.clst_init; cv::Mat clstMat(h, w, CV_16UC1); SetClusterCenter(iDens, dens_th, pCloud, nvMat, iColor, clst, clst_num, clstMat, mean_r); #ifndef LIB_CLUSTER double old_diff = 0; for(int i=0; i<5; i++){ double max_diff = MoveClstCenter(pCloud, nvMat, iColor, clst, clst_num, clstMat); if(max_diff < 5){ break; } if(max_diff == old_diff){ break; } old_diff = max_diff; } #else MoveClstLoop(pCloud, nvMat, iColor, clst, clst_num, clstMat, 5); #endif //LIB_CLUSTER std::vector<CLST_SUB> clst_mv; MergeCluster(clst, clst_num, clst_mv, mean_r, seg_prm); for(int j=0; j<h; j++){ for(int i=0; i<w; i++){ unsigned short int id_i = clstMat.at<unsigned short int>(j,i); if(id_i == USHRT_MAX){ continue; } if(clst[id_i].id==0){ continue; } unsigned short int id = clst[id_i].id-1; if(clst_mv[id].sx > i){ clst_mv[id].sx = i; } if(clst_mv[id].ex < i){ clst_mv[id].ex = i; } if(clst_mv[id].sy > j){ clst_mv[id].sy = j; } if(clst_mv[id].ey < j){ clst_mv[id].ey = j; } } } std::sort(clst_mv.begin(), clst_mv.end()); seg_mask_v.clear(); int counter = 0; for(unsigned int i=0; i<clst_mv.size(); i++){ if(clst_mv[i].size > seg_prm.area_max_th){ continue; } if(clst_mv[i].size < seg_prm.area_min_th){ break; } if(counter >= seg_prm.seg_max){ break; } counter++; SegmentMask seg_mask; int w_w = clst_mv[i].ex-clst_mv[i].sx+1; int h_w = clst_mv[i].ey-clst_mv[i].sy+1; int sx = clst_mv[i].sx; int sy = clst_mv[i].sy; seg_mask.sx = sx; seg_mask.sy = sy; seg_mask.ex = clst_mv[i].ex; seg_mask.ey = clst_mv[i].ey; seg_mask.mask = cv::Mat::zeros(h_w, w_w, CV_8UC1); for(int q=0; q<h_w; q++){ for(int p=0; p<w_w; p++){ unsigned short int id_i = clstMat.at<unsigned short int>(q+sy,p+sx); if(id_i == USHRT_MAX){ continue; } if(clst[id_i].id == 0){ continue; } unsigned short int id = clst[id_i].id; if(id == clst_mv[i].id){ seg_mask.mask.at<unsigned char>(q, p) = 255; } }//p }//q seg_mask_v.push_back(seg_mask); }//i seg_max { srand(seg_prm.rand_seed); unsigned char color[1024*1000][3] = {{0}}; for(int i=0; i<clst_num; i++){ color[i][0] = rand()%196 + 60; color[i][1] = rand()%196 + 60; color[i][2] = rand()%196 + 60; } cv::Mat I_cl = cv::Mat::zeros(clstMat.rows, clstMat.cols, CV_8UC3); cv::Mat I_cn = cv::Mat::zeros(clstMat.rows, clstMat.cols, CV_8UC3); cv::Mat I_cc = cv::Mat::zeros(clstMat.rows, clstMat.cols, CV_8UC3); cv::Mat I_lb = cv::Mat::zeros(clstMat.rows, clstMat.cols, CV_8UC3); for(int j=0; j<clstMat.rows; j++){ for(int i=0; i<clstMat.cols; i++){ unsigned short int id_i = clstMat.at<unsigned short int>(j,i); if(id_i == USHRT_MAX){ continue; } #ifndef DEMO_OUTPUT I_cl.at<cv::Vec3b>(j,i) = cv::Vec3b(color[id_i][0], color[id_i][1], color[id_i][2]); I_cn.at<cv::Vec3b>(j,i) = cv::Vec3b(clst[id_i].norm_v[2]*127+128,clst[id_i].norm_v[1]*127+128,clst[id_i].norm_v[0]*127+128); I_cc.at<cv::Vec3b>(j,i) = cv::Vec3b(clst[id_i].color[0],clst[id_i].color[1],clst[id_i].color[2]); int id = clst[id_i].id; if(id == 0){ continue; } I_lb.at<cv::Vec3b>(j,i) = cv::Vec3b(color[id][0], color[id][1], color[id][2]); #else //DEMO_OUTPUT int id = clst[id_i].id; if(id == 0){ continue; } I_lb.at<cv::Vec3b>(j,w-i-1) = cv::Vec3b(color[id][0], color[id][1], color[id][2]); #endif //DEMO_OUTPUT } } cv::imwrite("./debug/sample_clst.jpg", I_cl); cv::imwrite("./debug/sample_clst_result_norm.jpg", I_cn); cv::imwrite("./debug/sample_clst_result_color.jpg", I_cc); cv::imwrite("./debug/sample_clst_merge.jpg", I_lb); } return; }
28.218586
300
0.5914
[ "vector" ]
edb12bea891e5aab8337bd9501828ba6211c80da
4,204
cpp
C++
openstudiocore/src/energyplus/Test/SubSurface_GTest.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-04-21T15:38:54.000Z
2019-04-21T15:38:54.000Z
openstudiocore/src/energyplus/Test/SubSurface_GTest.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
null
null
null
openstudiocore/src/energyplus/Test/SubSurface_GTest.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-07-18T06:52:29.000Z
2019-07-18T06:52:29.000Z
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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, THE UNITED STATES GOVERNMENT, OR ANY 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 <gtest/gtest.h> #include "EnergyPlusFixture.hpp" #include "../ForwardTranslator.hpp" #include "../ReverseTranslator.hpp" #include "../../model/Model.hpp" #include "../../model/SubSurface.hpp" #include "../../model/SubSurface_Impl.hpp" #include "../../model/Surface.hpp" #include "../../model/Surface_Impl.hpp" #include <utilities/idd/Daylighting_Controls_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> #include <resources.hxx> #include <sstream> using namespace openstudio::energyplus; using namespace openstudio::model; using namespace openstudio; TEST_F(EnergyPlusFixture,ReverseTranslator_GlassDoorToSubSurface) { std::string text = "\ FenestrationSurface:Detailed,\n\ Perimeter_ZN_1_wall_south_door, !- Name\n\ GlassDoor, !- Surface Type\n\ window_south, !- Construction Name\n\ Perimeter_ZN_1_wall_south, !- Building Surface Name\n\ , !- Outside Boundary Condition Object\n\ AutoCalculate, !- View Factor to Ground\n\ , !- Shading Control Name\n\ , !- Frame and Divider Name\n\ 1.0000, !- Multiplier\n\ 4, !- Number of Vertices\n\ 12.930,0.0000,2.1340, !- X,Y,Z ==> Vertex 1 {m}\n\ 12.930,0.0000,0.0000, !- X,Y,Z ==> Vertex 2 {m}\n\ 14.760,0.0000,0.0000, !- X,Y,Z ==> Vertex 3 {m}\n\ 14.760,0.0000,2.1340; !- X,Y,Z ==> Vertex 4 {m}"; IdfObject idfObject = IdfObject::load(text).get(); Workspace ws(StrictnessLevel::Draft,IddFileType::EnergyPlus); OptionalWorkspaceObject owo = ws.addObject(idfObject); ASSERT_TRUE(owo); ReverseTranslator rt; Model model = rt.translateWorkspace(ws); SubSurfaceVector subSurfaces = model.getModelObjects<SubSurface>(); ASSERT_EQ(1u,subSurfaces.size()); EXPECT_EQ("GlassDoor",subSurfaces[0].subSurfaceType()); } TEST_F(EnergyPlusFixture,ForwardTranslator_SubSurface) { Model model; }
47.235955
120
0.672455
[ "object", "model" ]
edb152d388a24e241d7ce68a9a35d78f4081a026
12,518
cpp
C++
Source/Server/Server/GameService/GameManagers/PlayerData/PlayerDataManager.cpp
YouZiliCC/nnn
09e6430cd4118d52966524a11d79b6d35a767597
[ "MIT" ]
null
null
null
Source/Server/Server/GameService/GameManagers/PlayerData/PlayerDataManager.cpp
YouZiliCC/nnn
09e6430cd4118d52966524a11d79b6d35a767597
[ "MIT" ]
1
2022-02-01T20:54:35.000Z
2022-02-01T20:54:35.000Z
Source/Server/Server/GameService/GameManagers/PlayerData/PlayerDataManager.cpp
YouZiliCC/nnn
09e6430cd4118d52966524a11d79b6d35a767597
[ "MIT" ]
null
null
null
/* * Dark Souls 3 - Open Server * Copyright (C) 2021 Tim Leonard * * This program is free software; licensed under the MIT license. * You should have received a copy of the license along with this program. * If not, see <https://opensource.org/licenses/MIT>. */ #include "Server/GameService/GameManagers/PlayerData/PlayerDataManager.h" #include "Server/GameService/GameClient.h" #include "Server/Streams/Frpg2ReliableUdpMessage.h" #include "Server/Streams/Frpg2ReliableUdpMessageStream.h" #include "Config/RuntimeConfig.h" #include "Server/Server.h" #include "Core/Utils/Logging.h" #include "Core/Utils/Strings.h" #include "Core/Network/NetConnection.h" PlayerDataManager::PlayerDataManager(Server* InServerInstance) : ServerInstance(InServerInstance) { } MessageHandleResult PlayerDataManager::OnMessageRecieved(GameClient* Client, const Frpg2ReliableUdpMessage& Message) { if (Message.Header.msg_type == Frpg2ReliableUdpMessageType::RequestUpdateLoginPlayerCharacter) { return Handle_RequestUpdateLoginPlayerCharacter(Client, Message); } else if (Message.Header.msg_type == Frpg2ReliableUdpMessageType::RequestUpdatePlayerStatus) { return Handle_RequestUpdatePlayerStatus(Client, Message); } else if (Message.Header.msg_type == Frpg2ReliableUdpMessageType::RequestUpdatePlayerCharacter) { return Handle_RequestUpdatePlayerCharacter(Client, Message); } else if (Message.Header.msg_type == Frpg2ReliableUdpMessageType::RequestGetPlayerCharacter) { return Handle_RequestGetPlayerCharacter(Client, Message); } else if (Message.Header.msg_type == Frpg2ReliableUdpMessageType::RequestGetLoginPlayerCharacter) { return Handle_RequestGetLoginPlayerCharacter(Client, Message); } else if (Message.Header.msg_type == Frpg2ReliableUdpMessageType::RequestGetPlayerCharacterList) { return Handle_RequestGetPlayerCharacterList(Client, Message); } return MessageHandleResult::Unhandled; } MessageHandleResult PlayerDataManager::Handle_RequestUpdateLoginPlayerCharacter(GameClient* Client, const Frpg2ReliableUdpMessage& Message) { ServerDatabase& Database = ServerInstance->GetDatabase(); PlayerState& State = Client->GetPlayerState(); Frpg2RequestMessage::RequestUpdateLoginPlayerCharacter* Request = (Frpg2RequestMessage::RequestUpdateLoginPlayerCharacter*)Message.Protobuf.get(); std::shared_ptr<Character> Character = Database.FindCharacter(State.PlayerId, Request->character_id()); if (!Character) { std::vector<uint8_t> Data; if (!Database.CreateOrUpdateCharacter(State.PlayerId, Request->character_id(), Data)) { WarningS(Client->GetName().c_str(), "Disconnecting client as failed to find or update character %i.", Request->character_id()); return MessageHandleResult::Error; } Character = Database.FindCharacter(State.PlayerId, Request->character_id()); Ensure(Character); } Frpg2RequestMessage::RequestUpdateLoginPlayerCharacterResponse Response; Response.set_character_id(Request->character_id()); Frpg2RequestMessage::QuickMatchRank* Rank = Response.mutable_quickmatch_brawl_rank(); Rank->set_rank(Character->QuickMatchBrawlRank); Rank->set_xp(Character->QuickMatchBrawlXp); Rank = Response.mutable_quickmatch_dual_rank(); Rank->set_rank(Character->QuickMatchDuelRank); Rank->set_xp(Character->QuickMatchDuelXp); if (!Client->MessageStream->Send(&Response, &Message)) { WarningS(Client->GetName().c_str(), "Disconnecting client as failed to send RequestUpdateLoginPlayerCharacterResponse response."); return MessageHandleResult::Error; } return MessageHandleResult::Handled; } MessageHandleResult PlayerDataManager::Handle_RequestUpdatePlayerStatus(GameClient* Client, const Frpg2ReliableUdpMessage& Message) { Frpg2RequestMessage::RequestUpdatePlayerStatus* Request = (Frpg2RequestMessage::RequestUpdatePlayerStatus*)Message.Protobuf.get(); PlayerState& State = Client->GetPlayerState(); // Merge the delta into the current state. std::string bytes = Request->status(); Frpg2PlayerData::AllStatus status; if (!status.ParseFromArray(bytes.data(), (int)bytes.size())) { WarningS(Client->GetName().c_str(), "Failed to parse Frpg2PlayerData::AllStatus from RequestUpdatePlayerStatus."); // Don't take this as an error, it will resolve itself on next send. return MessageHandleResult::Handled; } State.PlayerStatus.MergeFrom(status); // Keep track of the players character id. if (State.PlayerStatus.player_status().has_character_id()) { State.CharacterId = State.PlayerStatus.player_status().character_id(); } // Keep track of the players character name, useful for logging. if (State.PlayerStatus.player_status().has_name()) { std::string NewCharacterName = State.PlayerStatus.player_status().name(); if (State.CharacterName != NewCharacterName) { State.CharacterName = NewCharacterName; std::string NewConnectionName = StringFormat("%i:%s", State.PlayerId, State.CharacterName.c_str()); LogS(Client->GetName().c_str(), "Renaming connection to '%s'.", NewConnectionName.c_str()); // Rename connection after this point as it easier to keep track of than ip:port pairs. Client->Connection->Rename(NewConnectionName); } } // Print a log if user has changed online location. if (State.PlayerStatus.has_player_location()) { OnlineAreaId AreaId = static_cast<OnlineAreaId>(State.PlayerStatus.player_location().online_area_id()); if (AreaId != State.CurrentArea && AreaId != OnlineAreaId::None) { LogS(Client->GetName().c_str(), "User has entered '%s'", GetEnumString(AreaId).c_str()); State.CurrentArea = AreaId; } } // Grab some matchmaking values. if (State.PlayerStatus.has_player_status()) { // Grab invadability state. if (State.PlayerStatus.player_status().has_is_invadable()) { bool NewState = State.PlayerStatus.player_status().is_invadable(); if (NewState != State.IsInvadable) { LogS(Client->GetName().c_str(), "User is now %s", NewState ? "invadable" : "no longer invadable"); State.IsInvadable = NewState; } } // Grab soul level / weapon level. if (State.PlayerStatus.player_status().has_soul_level()) { State.SoulLevel = State.PlayerStatus.player_status().soul_level(); } if (State.PlayerStatus.player_status().has_max_weapon_level()) { State.MaxWeaponLevel = State.PlayerStatus.player_status().max_weapon_level(); } // Grab whatever visitor pool they should be in. Frpg2RequestMessage::VisitorPool NewVisitorPool = Frpg2RequestMessage::VisitorPool::VisitorPool_None; if (State.PlayerStatus.player_status().has_can_summon_for_way_of_blue() && State.PlayerStatus.player_status().can_summon_for_way_of_blue()) { NewVisitorPool = Frpg2RequestMessage::VisitorPool::VisitorPool_Way_of_Blue; } if (State.PlayerStatus.player_status().has_can_summon_for_watchdog_of_farron() && State.PlayerStatus.player_status().can_summon_for_watchdog_of_farron()) { NewVisitorPool = Frpg2RequestMessage::VisitorPool::VisitorPool_Watchdog_of_Farron; } if (State.PlayerStatus.player_status().has_can_summon_for_aldritch_faithful() && State.PlayerStatus.player_status().can_summon_for_aldritch_faithful()) { NewVisitorPool = Frpg2RequestMessage::VisitorPool::VisitorPool_Aldrich_Faithful; } if (State.PlayerStatus.player_status().has_can_summon_for_spear_of_church() && State.PlayerStatus.player_status().can_summon_for_spear_of_church()) { NewVisitorPool = Frpg2RequestMessage::VisitorPool::VisitorPool_Spear_of_the_Church; } if (NewVisitorPool != State.VisitorPool) { State.VisitorPool = NewVisitorPool; } } Frpg2RequestMessage::RequestUpdatePlayerStatusResponse Response; if (!Client->MessageStream->Send(&Response, &Message)) { WarningS(Client->GetName().c_str(), "Disconnecting client as failed to send RequestUpdatePlayerStatusResponse response."); return MessageHandleResult::Error; } return MessageHandleResult::Handled; } MessageHandleResult PlayerDataManager::Handle_RequestUpdatePlayerCharacter(GameClient* Client, const Frpg2ReliableUdpMessage& Message) { ServerDatabase& Database = ServerInstance->GetDatabase(); PlayerState& State = Client->GetPlayerState(); Frpg2RequestMessage::RequestUpdatePlayerCharacter* Request = (Frpg2RequestMessage::RequestUpdatePlayerCharacter*)Message.Protobuf.get(); std::vector<uint8_t> Data; Data.assign(Request->character_data().data(), Request->character_data().data() + Request->character_data().size()); if (!Database.CreateOrUpdateCharacter(State.PlayerId, Request->character_id(), Data)) { WarningS(Client->GetName().c_str(), "Disconnecting client as failed to find or update character %i.", Request->character_id()); return MessageHandleResult::Error; } Frpg2RequestMessage::RequestUpdatePlayerCharacterResponse Response; if (!Client->MessageStream->Send(&Response, &Message)) { WarningS(Client->GetName().c_str(), "Disconnecting client as failed to send RequestUpdatePlayerCharacterResponse response."); return MessageHandleResult::Error; } return MessageHandleResult::Handled; } MessageHandleResult PlayerDataManager::Handle_RequestGetPlayerCharacter(GameClient* Client, const Frpg2ReliableUdpMessage& Message) { ServerDatabase& Database = ServerInstance->GetDatabase(); PlayerState& State = Client->GetPlayerState(); Frpg2RequestMessage::RequestGetPlayerCharacter* Request = (Frpg2RequestMessage::RequestGetPlayerCharacter*)Message.Protobuf.get(); Frpg2RequestMessage::RequestGetPlayerCharacterResponse Response; std::vector<uint8_t> CharacterData; std::shared_ptr<Character> Character = Database.FindCharacter(Request->player_id(), Request->character_id()); if (Character) { CharacterData = Character->Data; } Response.set_player_id(Request->player_id()); Response.set_character_id(Request->character_id()); Response.set_character_data(CharacterData.data(), CharacterData.size()); if (!Client->MessageStream->Send(&Response, &Message)) { WarningS(Client->GetName().c_str(), "Disconnecting client as failed to send RequestGetPlayerCharacterResponse response."); return MessageHandleResult::Error; } return MessageHandleResult::Handled; } MessageHandleResult PlayerDataManager::Handle_RequestGetLoginPlayerCharacter(GameClient* Client, const Frpg2ReliableUdpMessage& Message) { Frpg2RequestMessage::RequestGetLoginPlayerCharacter* Request = (Frpg2RequestMessage::RequestGetLoginPlayerCharacter*)Message.Protobuf.get(); // TODO: Implement Ensure(false); // Never seen this in use. Frpg2RequestMessage::RequestGetLoginPlayerCharacterResponse Response; if (!Client->MessageStream->Send(&Response, &Message)) { WarningS(Client->GetName().c_str(), "Disconnecting client as failed to send RequestGetLoginPlayerCharacterResponse response."); return MessageHandleResult::Error; } return MessageHandleResult::Handled; } MessageHandleResult PlayerDataManager::Handle_RequestGetPlayerCharacterList(GameClient* Client, const Frpg2ReliableUdpMessage& Message) { Frpg2RequestMessage::RequestGetPlayerCharacterList* Request = (Frpg2RequestMessage::RequestGetPlayerCharacterList*)Message.Protobuf.get(); // TODO: Implement Ensure(false); // Never seen this in use. Frpg2RequestMessage::RequestGetPlayerCharacterListResponse Response; if (!Client->MessageStream->Send(&Response, &Message)) { WarningS(Client->GetName().c_str(), "Disconnecting client as failed to send RequestGetPlayerCharacterListResponse response."); return MessageHandleResult::Error; } return MessageHandleResult::Handled; } std::string PlayerDataManager::GetName() { return "Player Data"; }
41.177632
161
0.725276
[ "vector" ]
edb2223a4bc5902258a839de127ceb386b545663
2,368
cpp
C++
Source/platform/exported/WebServiceWorkerResponse.cpp
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
20e637e67a0c272870ae4d78466a68bcb77af041
[ "BSD-3-Clause" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Source/platform/exported/WebServiceWorkerResponse.cpp
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
20e637e67a0c272870ae4d78466a68bcb77af041
[ "BSD-3-Clause" ]
null
null
null
Source/platform/exported/WebServiceWorkerResponse.cpp
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
20e637e67a0c272870ae4d78466a68bcb77af041
[ "BSD-3-Clause" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "public/platform/WebServiceWorkerResponse.h" #include "platform/blob/BlobData.h" namespace blink { class WebServiceWorkerResponsePrivate : public RefCounted<WebServiceWorkerResponsePrivate> { public: unsigned short status; WebString statusText; HashMap<String, String> headers; RefPtr<WebCore::BlobDataHandle> blobDataHandle; }; WebServiceWorkerResponse::WebServiceWorkerResponse() : m_private(adoptRef(new WebServiceWorkerResponsePrivate)) { } void WebServiceWorkerResponse::reset() { m_private.reset(); } void WebServiceWorkerResponse::assign(const WebServiceWorkerResponse& other) { m_private = other.m_private; } void WebServiceWorkerResponse::setStatus(unsigned short status) { m_private->status = status; } unsigned short WebServiceWorkerResponse::status() const { return m_private->status; } void WebServiceWorkerResponse::setStatusText(const WebString& statusText) { m_private->statusText = statusText; } WebString WebServiceWorkerResponse::statusText() const { return m_private->statusText; } void WebServiceWorkerResponse::setHeader(const WebString& key, const WebString& value) { m_private->headers.set(key, value); } WebVector<WebString> WebServiceWorkerResponse::getHeaderKeys() const { Vector<String> keys; copyKeysToVector(m_private->headers, keys); return keys; } WebString WebServiceWorkerResponse::getHeader(const WebString& key) const { return m_private->headers.get(key); } WebString WebServiceWorkerResponse::blobUUID() const { if (!m_private->blobDataHandle) return WebString(); return m_private->blobDataHandle->uuid(); } void WebServiceWorkerResponse::setHeaders(const HashMap<String, String>& headers) { m_private->headers = headers; } const HashMap<String, String>& WebServiceWorkerResponse::headers() const { return m_private->headers; } void WebServiceWorkerResponse::setBlobDataHandle(PassRefPtr<WebCore::BlobDataHandle> blobDataHandle) { m_private->blobDataHandle = blobDataHandle; } PassRefPtr<WebCore::BlobDataHandle> WebServiceWorkerResponse::blobDataHandle() const { return m_private->blobDataHandle; } } // namespace blink
23.68
100
0.769426
[ "vector" ]
edb53a37e5084d107311a4f5a01e840124f8ecbd
8,196
cc
C++
src/s2/s2builderutil_s2polyline_layer_test.cc
qcraftai/s2geometry
2f4548695d0f2b2f9c7601eb1a68ee100ec70531
[ "Apache-2.0" ]
null
null
null
src/s2/s2builderutil_s2polyline_layer_test.cc
qcraftai/s2geometry
2f4548695d0f2b2f9c7601eb1a68ee100ec70531
[ "Apache-2.0" ]
null
null
null
src/s2/s2builderutil_s2polyline_layer_test.cc
qcraftai/s2geometry
2f4548695d0f2b2f9c7601eb1a68ee100ec70531
[ "Apache-2.0" ]
null
null
null
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: ericv@google.com (Eric Veach) #include "s2/s2builderutil_s2polyline_layer.h" #include <string> #include "s2/base/casts.h" #include "s2/base/integral_types.h" #include <gtest/gtest.h> #include "s2/third_party/absl/memory/memory.h" #include "s2/s2builderutil_snap_functions.h" #include "s2/s2debug.h" #include "s2/s2text_format.h" using s2_absl::make_unique; using s2builderutil::IndexedS2PolylineLayer; using s2builderutil::S2PolylineLayer; using s2textformat::MakePolylineOrDie; using std::vector; using EdgeType = S2Builder::EdgeType; namespace { void TestS2Polyline( const vector<const char*>& input_strs, const char* expected_str, EdgeType edge_type, const S2Builder::Options& options = S2Builder::Options()) { SCOPED_TRACE(edge_type == EdgeType::DIRECTED ? "DIRECTED" : "UNDIRECTED"); S2Builder builder(options); S2Polyline output; builder.StartLayer(make_unique<S2PolylineLayer>( &output, S2PolylineLayer::Options(edge_type))); for (auto input_str : input_strs) { builder.AddPolyline(*MakePolylineOrDie(input_str)); } S2Error error; ASSERT_TRUE(builder.Build(&error)); EXPECT_EQ(expected_str, s2textformat::ToString(output)); } // Convenience function that tests both directed and undirected edges. void TestS2Polyline( const vector<const char*>& input_strs, const char* expected_str, const S2Builder::Options& options = S2Builder::Options()) { TestS2Polyline(input_strs, expected_str, EdgeType::DIRECTED, options); TestS2Polyline(input_strs, expected_str, EdgeType::UNDIRECTED, options); } void TestS2PolylineUnchanged(const char* input_str) { TestS2Polyline(vector<const char*>{input_str}, input_str); } TEST(S2PolylineLayer, NoEdges) { TestS2Polyline({}, ""); } TEST(S2PolylineLayer, OneEdge) { // Even with undirected edges, S2PolylineLayer prefers to reconstruct edges // in their original direction. TestS2PolylineUnchanged("3:4, 1:1"); TestS2PolylineUnchanged("1:1, 3:4"); } TEST(S2PolylineLayer, StraightLineWithBacktracking) { TestS2PolylineUnchanged("0:0, 1:0, 2:0, 3:0, 2:0, 1:0, 2:0, 3:0, 4:0"); } TEST(S2PolylineLayer, EarlyWalkTerminationWithEndLoop1) { // Test that the "early walk termination" code (which is needed by // S2PolylineVectorLayer in order to implement idempotency) does not create // two polylines when it is possible to assemble the edges into one. // // This example tests a code path where the early walk termination code // should not be triggered at all (but was at one point due to a bug). S2Builder::Options options; options.set_snap_function(s2builderutil::IntLatLngSnapFunction(2)); TestS2Polyline({"0:0, 0:2, 0:1"}, "0:0, 0:1, 0:2, 0:1", options); } TEST(S2PolylineLayer, EarlyWalkTerminationWithEndLoop2) { // This tests a different code path where the walk is terminated early // (yield a polyline with one edge), and then the walk is "maximimzed" by // appending a two-edge loop to the end. TestS2Polyline({"0:0, 0:1", "0:2, 0:1", "0:1, 0:2"}, "0:0, 0:1, 0:2, 0:1"); } TEST(S2PolylineLayer, SimpleLoop) { TestS2PolylineUnchanged("0:0, 0:5, 5:5, 5:0, 0:0"); } TEST(S2PolylineLayer, ManyLoops) { // This polyline consists of many overlapping loops that keep returning to // the same starting vertex (2:2). This tests whether the implementation is // able to assemble the polyline in the original order. TestS2PolylineUnchanged( "0:0, 2:2, 2:4, 2:2, 2:4, 4:4, 4:2, 2:2, 4:4, 4:2, 2:2, 2:0, 2:2, " "2:0, 4:0, 2:2, 4:2, 2:2, 0:2, 0:4, 2:2, 0:4, 0:2, 2:2, 0:4, 2:2, " "0:2, 2:2, 0:0, 0:2, 2:2, 0:0"); } TEST(S2PolylineLayer, UnorderedLoops) { // This test consists of 5 squares that touch diagonally, similar to the 5 // white squares of a 3x3 chessboard. The edges of these squares need to be // reordered to assemble them into a single unbroken polyline. TestS2Polyline({ "3:3, 3:2, 2:2, 2:3, 3:3", "1:0, 0:0, 0:1, 1:1, 1:0", "3:1, 3:0, 2:0, 2:1, 3:1", "1:3, 1:2, 0:2, 0:1, 1:3", "1:1, 1:2, 2:2, 2:1, 1:1", // Central square }, "3:3, 3:2, 2:2, 2:1, 3:1, 3:0, 2:0, 2:1, 1:1, 1:0, 0:0, " "0:1, 1:1, 1:2, 0:2, 0:1, 1:3, 1:2, 2:2, 2:3, 3:3"); } TEST(S2PolylineLayer, SplitEdges) { // Test reconstruction of a polyline where two edges have been split into // many pieces by crossing edges. This example is particularly challenging // because (1) the edges form a loop, and (2) the first and last edges are // identical (but reversed). This is designed to test the heuristics that // attempt to find the first edge of the input polyline. S2Builder::Options options; options.set_split_crossing_edges(true); options.set_snap_function(s2builderutil::IntLatLngSnapFunction(7)); TestS2Polyline( {"0:10, 0:0, 1:0, -1:2, 1:4, -1:6, 1:8, -1:10, -5:0, 0:0, 0:10"}, "0:10, 0:9, 0:7, 0:5, 0:3, 0:1, 0:0, 1:0, 0:1, -1:2, 0:3, 1:4, 0:5, " "-1:6, 0:7, 1:8, 0:9, -1:10, -5:0, 0:0, 0:1, 0:3, 0:5, 0:7, 0:9, 0:10", options); } TEST(S2PolylineLayer, SimpleEdgeLabels) { S2Builder builder{S2Builder::Options()}; S2Polyline output; S2PolylineLayer::LabelSetIds label_set_ids; IdSetLexicon label_set_lexicon; builder.StartLayer(make_unique<S2PolylineLayer>( &output, &label_set_ids, &label_set_lexicon, S2PolylineLayer::Options(EdgeType::UNDIRECTED))); builder.set_label(5); builder.AddPolyline(*MakePolylineOrDie("0:0, 0:1, 0:2")); builder.push_label(7); builder.AddPolyline(*MakePolylineOrDie("0:3, 0:2")); builder.clear_labels(); builder.AddPolyline(*MakePolylineOrDie("0:3, 0:4, 0:5")); builder.set_label(11); builder.AddPolyline(*MakePolylineOrDie("0:6, 0:5")); S2Error error; ASSERT_TRUE(builder.Build(&error)); vector<vector<int32>> expected = {{5}, {5}, {5, 7}, {}, {}, {11}}; ASSERT_EQ(expected.size(), label_set_ids.size()); for (int i = 0; i < expected.size(); ++i) { ASSERT_EQ(expected[i].size(), label_set_lexicon.id_set(label_set_ids[i]).size()); int j = 0; for (int32 label : label_set_lexicon.id_set(label_set_ids[i])) { EXPECT_EQ(expected[i][j++], label); } } } TEST(S2PolylineLayer, InvalidPolyline) { S2Builder builder{S2Builder::Options()}; S2Polyline output; S2PolylineLayer::Options options; options.set_validate(true); builder.StartLayer(make_unique<S2PolylineLayer>(&output, options)); vector<S2Point> vertices; vertices.push_back(S2Point(1, 0, 0)); vertices.push_back(S2Point(-1, 0, 0)); S2Polyline input(vertices, S2Debug::DISABLE); builder.AddPolyline(input); S2Error error; EXPECT_FALSE(builder.Build(&error)); EXPECT_EQ(S2Error::ANTIPODAL_VERTICES, error.code()); } TEST(IndexedS2PolylineLayer, AddsShape) { S2Builder builder{S2Builder::Options()}; MutableS2ShapeIndex index; builder.StartLayer(make_unique<IndexedS2PolylineLayer>(&index)); const string& polyline_str = "0:0, 0:10"; builder.AddPolyline(*MakePolylineOrDie(polyline_str)); S2Error error; ASSERT_TRUE(builder.Build(&error)); EXPECT_EQ(1, index.num_shape_ids()); const S2Polyline* polyline = down_cast<const S2Polyline::Shape*>( index.shape(0))->polyline(); EXPECT_EQ(polyline_str, s2textformat::ToString(*polyline)); } TEST(IndexedS2PolylineLayer, AddsEmptyShape) { S2Builder builder{S2Builder::Options()}; MutableS2ShapeIndex index; builder.StartLayer(make_unique<IndexedS2PolylineLayer>(&index)); S2Polyline line; builder.AddPolyline(line); S2Error error; ASSERT_TRUE(builder.Build(&error)); EXPECT_EQ(0, index.num_shape_ids()); } } // namespace
37.085973
78
0.699854
[ "shape", "vector" ]
edb657544548f5c48243cbc5b557d59f26c3a2f0
5,308
cpp
C++
src/kvstore/wal/test/AtomicLogBufferTest.cpp
pengweisong/nebula
56856e76a80785da0ec96c3a32f9bf6feb02c740
[ "Apache-2.0" ]
null
null
null
src/kvstore/wal/test/AtomicLogBufferTest.cpp
pengweisong/nebula
56856e76a80785da0ec96c3a32f9bf6feb02c740
[ "Apache-2.0" ]
null
null
null
src/kvstore/wal/test/AtomicLogBufferTest.cpp
pengweisong/nebula
56856e76a80785da0ec96c3a32f9bf6feb02c740
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2019 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include <gtest/gtest.h> #include <utility> #include "common/base/Base.h" #include "kvstore/wal/AtomicLogBuffer.h" namespace nebula { namespace wal { void checkIterator(std::shared_ptr<AtomicLogBuffer> logBuffer, LogID from, LogID to, LogID expected) { auto iter = logBuffer->iterator(from, to); for (; iter->valid(); ++(*iter)) { auto log = iter->logMsg(); ASSERT_EQ(folly::stringPrintf("str_%ld", from), log); from++; } EXPECT_EQ(expected, from); } TEST(AtomicLogBufferTest, ReadWriteTest) { auto logBuffer = AtomicLogBuffer::instance(); for (LogID logId = 0; logId < 1000L; logId++) { logBuffer->push(logId, Record(0, 0, folly::stringPrintf("str_%ld", logId))); } checkIterator(logBuffer, 200, 1000, 1000); checkIterator(logBuffer, 200, 1500, 1000); checkIterator(logBuffer, 200, 800, 801); { LogID from = 1200; auto iter = logBuffer->iterator(from, 1800); CHECK(!iter->valid()); } } TEST(AtomicLogBufferTest, OverflowTest) { auto logBuffer = AtomicLogBuffer::instance(128); for (LogID logId = 0; logId < 1000L; logId++) { logBuffer->push(logId, Record(0, 0, folly::stringPrintf("str_%ld", logId))); } { LogID from = 100; auto iter = logBuffer->iterator(from, 1800); CHECK(!iter->valid()); } } TEST(AtomicLogBufferTest, SingleWriterMultiReadersTest) { // The default size is 100K auto logBuffer = AtomicLogBuffer::instance(100 * 1024); std::atomic<LogID> writePoint{0}; std::thread writer([logBuffer, &writePoint] { LOG(INFO) << "Begin write 1M records"; for (LogID logId = 0; logId < 1000000L; logId++) { logBuffer->push(logId, Record(0, 0, folly::stringPrintf("str_%ld", logId))); writePoint.store(logId, std::memory_order_release); } LOG(INFO) << "Finish writer"; }); std::vector<std::thread> readers; for (int i = 0; i < 5; i++) { readers.emplace_back([i, logBuffer, &writePoint] { usleep(10); LOG(INFO) << "Start reader " << i; int times = 10000; int validSeek = 0; while (times-- > 0) { auto wp = writePoint.load(std::memory_order_acquire) - 1; auto start = folly::Random::rand32(logBuffer->firstLogId(), wp); auto end = start + folly::Random::rand32(1000); auto iter = logBuffer->iterator(start, end); if (!iter->valid()) { continue; } validSeek++; size_t num = start; for (; iter->valid(); ++(*iter)) { const auto* rec = iter->record(); auto logId = iter->logId(); auto* node = iter->currNode(); CHECK_NOTNULL(rec); auto expected = folly::stringPrintf("str_%ld", num); EXPECT_EQ(num, logId); EXPECT_EQ(expected.size(), rec->msg_.size()) << "wp " << wp << ", start " << start << ", logId " << logId << ", end " << end << ", curr node " << node->firstLogId_ << ", pos " << node->pos_ << ", curr index " << iter->currIndex() << ", head lastLogId " << logBuffer->lastLogId(); EXPECT_EQ(expected, rec->msg_) << "expected size " << expected.size() << ", actual size " << rec->msg_.size(); num++; } } LOG(INFO) << "End reader " << i << ", valid seek times " << validSeek; }); } writer.join(); for (auto& r : readers) { r.join(); } } TEST(AtomicLogBufferTest, ResetThenPushExceedLimit) { int32_t capacity = 24 * (kMaxLength + 1); auto logBuffer = AtomicLogBuffer::instance(capacity); // One node would save at most kMaxLength logs, so there will be 2 node. LogID logId = 0; for (; logId <= kMaxLength; logId++) { // The actual size of one record would be sizeof(ClusterID) + sizeof(TermID) // + msg_.size(), in this case, it would be 8 + 8 + 8 = 24, total size would // be 24 * (kMaxLength + 1) logBuffer->push(logId, Record(0, 0, std::string(8, 'a'))); } // Mark all two node as deleted, log buffer size would be reset to 0 logBuffer->reset(); CHECK(logBuffer->seek(0) == nullptr); CHECK(logBuffer->seek(kMaxLength) == nullptr); // Because head has been marked as deleted, this would save in a new node. // The record size will be exactly same with capacity of log buffer. std::string logMakeBufferFull(capacity - sizeof(ClusterID) - sizeof(TermID), 'a'); logBuffer->push(logId, Record(0, 0, std::move(logMakeBufferFull))); // Before this PR, the logId will be 0 when buffer has been reset, and push a // new log CHECK_EQ(logId, logBuffer->firstLogId_); CHECK_EQ(capacity, logBuffer->size_); CHECK(logBuffer->seek(logId) != nullptr); logId++; // At this point, buffer will have three node, head contain the // logMakeBufferFull, others are marked as deleted, tail != head. Let's push // another log logBuffer->push(logId, Record(0, 0, std::string(8, 'a'))); CHECK(logBuffer->seek(logId) != nullptr); } } // namespace wal } // namespace nebula int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); folly::init(&argc, &argv, true); google::SetStderrLogging(google::INFO); return RUN_ALL_TESTS(); }
33.383648
97
0.614732
[ "vector" ]
edba8d1462e751da252a6316f58f9df1103e560d
3,898
cpp
C++
src/pattern.cpp
Nico-Curti/rSGD
b1f72c06a7f68c04fc97aaeae45d75852b541d42
[ "MIT" ]
1
2020-10-22T02:10:06.000Z
2020-10-22T02:10:06.000Z
src/pattern.cpp
Nico-Curti/rSGD
b1f72c06a7f68c04fc97aaeae45d75852b541d42
[ "MIT" ]
null
null
null
src/pattern.cpp
Nico-Curti/rSGD
b1f72c06a7f68c04fc97aaeae45d75852b541d42
[ "MIT" ]
null
null
null
#include <pattern.h> Patterns :: Patterns () : Nrow(0L), Ncol(0L), Nout(0L), output(nullptr), input(nullptr) { } Patterns :: Patterns (const std :: string & filename, bool bin, const std :: string & del) { if (bin) { std::ifstream is(filename, std::ios::binary); if (!is) error_pattern(filename); is.read(reinterpret_cast <char * >(&Nrow), sizeof(long int)); is.read(reinterpret_cast <char * >(&Ncol), sizeof(long int)); Nout = Nrow; input = new double[Nrow * Ncol]; output = new long int[Nout]; is.read(reinterpret_cast < char * >(output), sizeof(long int) * Nout); is.read(reinterpret_cast < char * >(input), sizeof(double) * Nrow * Ncol); is.close(); } else { std :: vector < std :: string > row_; std :: ifstream is(filename); if ( !is ) error_pattern(filename); std::stringstream buff; buff << is.rdbuf(); is.close(); // Get M std :: string row; std :: getline(buff, row); row_ = split(row, del); Nout = row_.size(); Nrow = Nout; // Read outputs output = new long int [Nout]; std :: transform( row_.begin(), row_.end(), output, [](const std :: string & i){return std :: stod(i);} ); // Get N std :: getline(buff, row); row_ = split(row, del); Ncol = row_.size(); input = new double[Nrow * Ncol]; // Read first pattern std :: transform( row_.begin(), row_.end(), input, [](const std :: string & i){return std :: stod(i);} ); // Read all others for (long int i = Ncol; i < Nrow * Ncol; ++i) { std :: getline(buff, row); row_ = split(row, del); std :: transform( row_.begin(), row_.end(), input + i * Ncol, [](const std :: string & rr){return std :: stod(rr);} ); } } #ifdef DEBUG check_binary(); #endif } Patterns :: Patterns(const long int & N, const long int & M) : Nrow (N), Ncol (M), Nout (N) { input = new double[Nrow * Ncol]; output = new long int [Nrow]; std :: default_random_engine engine; std :: bernoulli_distribution dist(.5); std :: fill_n(output, Nout, 1L); std :: generate_n(input, Nrow * Ncol, [&]() { return (dist(engine)) ? 1. : -1.; }); } Patterns :: Patterns (long double ** data, long int * label, const int & Nrow, const int & Ncol) : Nrow (Nrow), Ncol (Ncol), Nout (Nrow) { input = new double[Nrow * Ncol]; output = new long int[Nrow]; for (int i = 0; i < Nrow; ++i) std :: copy_n(data[i], Ncol, input + i * Ncol); std :: copy_n(label, Nrow, output); } Patterns & Patterns :: operator = (const Patterns & p) { Nrow = p.Nrow; Ncol = p.Ncol; Nout = p.Nrow; input = new double[Nrow * Ncol]; output = new long int[Nrow]; std :: copy_n(p.input, Nrow * Ncol, input); std :: copy_n(p.output, Nrow, output); return *this; } Patterns :: Patterns (const Patterns & p) { Nrow = p.Nrow; Ncol = p.Ncol; Nout = p.Nrow; input = new double[Nrow * Ncol]; output = new long int[Nrow]; std :: copy_n(p.input, Nrow * Ncol, input); std :: copy_n(p.output, Nrow, output); } Patterns :: ~Patterns () { if (Nrow) { delete[] input; } if (Nout) delete[] output; } #ifdef DEBUG void Patterns :: check_binary () { assert(Nout == Nrow); int cnt = 0; for (long int i = 0L; i < Nrow; ++i) cnt += std :: count_if(input + i * Ncol, input + i * Ncol + Ncol, [](const double & v) { return std :: abs(v); }); assert(cnt == Nrow * Ncol); cnt = std :: accumulate(output, output + Nout, 0, [](const int & res, const long int & v) { return res + static_cast < int >(std :: abs(v)); }); assert(cnt == Nout); } #endif
26.337838
136
0.534377
[ "vector", "transform" ]
edbd95b86d55fbc5518341360b3d7f303d381b0e
11,038
cpp
C++
hals/oemlock/test/test.cpp
jingpad-bsp/android_external_nos_host_android
a37b9e60f71cb638cb9069003d09af5a8f26b55c
[ "Apache-2.0" ]
null
null
null
hals/oemlock/test/test.cpp
jingpad-bsp/android_external_nos_host_android
a37b9e60f71cb638cb9069003d09af5a8f26b55c
[ "Apache-2.0" ]
null
null
null
hals/oemlock/test/test.cpp
jingpad-bsp/android_external_nos_host_android
a37b9e60f71cb638cb9069003d09af5a8f26b55c
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <android-base/endian.h> #include <MockAvb.client.h> #include <OemLock.h> #include <avb.h> #include <gtest/gtest.h> using ::testing::_; using ::testing::DoAll; using ::testing::ElementsAreArray; using ::testing::Eq; using ::testing::Return; using ::testing::SetArgPointee; using ::android::hardware::hidl_string; using ::android::hardware::hidl_vec; using ::android::hardware::oemlock::OemLock; using ::android::hardware::oemlock::OemLockStatus; using ::android::hardware::oemlock::OemLockSecureStatus; using ::nugget::app::avb::MockAvb; using ::nugget::app::avb::CarrierUnlock; using ::nugget::app::avb::CarrierUnlockRequest; using ::nugget::app::avb::GetLockRequest; using ::nugget::app::avb::GetLockResponse; using ::nugget::app::avb::LockIndex; using ::nugget::app::avb::SetDeviceLockRequest; namespace { /** * The signature from the server is a concatenation of a few values. This is a * helper to do the concatenation. */ hidl_vec<uint8_t> makeSignature(uint64_t version, uint64_t nonce, const std::vector<uint8_t>& token) { const uint64_t token_offset = sizeof(uint64_t) * 2; hidl_vec<uint8_t> signature(token_offset + token.size()); // Little-endian in the first 8 bytes const uint64_t version_le = htole64(version); memcpy(signature.data(), &version_le, sizeof(uint64_t)); // Little-endian in the second 8 bytes const uint64_t nonce_le = htole64(nonce); memcpy(signature.data() + sizeof(uint64_t), &nonce_le, sizeof(uint64_t)); // Remaining data is the token memcpy(signature.data() + token_offset, token.data(), token.size()); return signature; } } // namespace // getName TEST(OemLockHalTest, getNameReports01) { MockAvb mockService; // This doesn't need to go to the AVB app OemLock hal{mockService}; hal.getName([](OemLockStatus status, const hidl_string& name) { ASSERT_THAT(status, Eq(OemLockStatus::OK)); EXPECT_THAT(name, Eq("01")); }); } // setOemUnlockAllowedByCarrier MATCHER_P(CarrierUnlockEq, msg, "") { const auto& argToken = arg.token(); const auto& msgToken = msg.token(); return argToken.version() == msgToken.version() && argToken.nonce() == msgToken.nonce() && argToken.signature() == msgToken.signature(); } TEST(OemLockHalTest, setOemUnlockAllowedByCarrierSendsUnlockSignatureToAvb) { constexpr uint64_t version = 93; constexpr uint64_t nonce = 3486438654; const std::vector<uint8_t> token { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 2, 4, 6, 8, 1, 3, 5, 7, 9, }; MockAvb mockService; auto unlock = std::make_unique<CarrierUnlock>(); unlock->set_version(version); unlock->set_nonce(nonce); unlock->set_signature(token.data(), token.size()); CarrierUnlockRequest request; request.set_allocated_token(unlock.release()); EXPECT_CALL(mockService, CarrierUnlock(CarrierUnlockEq(request), _)) .WillOnce(Return(APP_SUCCESS)); OemLock hal{mockService}; ASSERT_THAT(hal.setOemUnlockAllowedByCarrier(true, makeSignature(version, nonce, token)), Eq(OemLockSecureStatus::OK)); } TEST(OemLockHalTest, setOemUnlockAllowedByCarrierInvalidSignatureIfUnauthorizedByApp) { MockAvb mockService; EXPECT_CALL(mockService, CarrierUnlock(_, _)).WillOnce(Return(APP_ERROR_AVB_AUTHORIZATION)); OemLock hal{mockService}; ASSERT_THAT(hal.setOemUnlockAllowedByCarrier(true, makeSignature(1, 2, {3, 4, 5})), Eq(OemLockSecureStatus::INVALID_SIGNATURE)); } TEST(OemLockHalTest, setOemUnlockAllowedByCarrierFailsOnAvbError) { MockAvb mockService; EXPECT_CALL(mockService, CarrierUnlock(_, _)).WillOnce(Return(APP_ERROR_INTERNAL)); OemLock hal{mockService}; ASSERT_THAT(hal.setOemUnlockAllowedByCarrier(true, makeSignature(1, 2, {3, 4, 5})), Eq(OemLockSecureStatus::FAILED)); } TEST(OemLockHalTest, setOemUnlockAllowedByCarrierShortSignatureIsInvalid) { MockAvb mockService; OemLock hal{mockService}; ASSERT_THAT(hal.setOemUnlockAllowedByCarrier(true, hidl_vec<uint8_t>{}), Eq(OemLockSecureStatus::INVALID_SIGNATURE)); } TEST(OemLockHalTest, setOemUnlockAllowedByCarrierFailsToDisallow) { MockAvb mockService; OemLock hal{mockService}; ASSERT_THAT(hal.setOemUnlockAllowedByCarrier(false, hidl_vec<uint8_t>{}), Eq(OemLockSecureStatus::FAILED)); } // isOemUnlockAllowedByCarrier MATCHER_P(GetLockEq, msg, "") { return arg.lock() == msg.lock(); } TEST(OemLockHalTest, isOemUnlockAllowedByCarrierChecksCarrierLock) { MockAvb mockService; GetLockRequest request; request.set_lock(LockIndex::CARRIER); EXPECT_CALL(mockService, GetLock(GetLockEq(request), _)).WillOnce(Return(APP_ERROR_RPC)); OemLock hal{mockService}; hal.isOemUnlockAllowedByCarrier([](OemLockStatus status, bool allowed) { ASSERT_THAT(status, Eq(OemLockStatus::FAILED)); (void) allowed; }); } TEST(OemLockHalTest, isOemUnlockAllowedByCarrierWhenAllowed) { MockAvb mockService; GetLockResponse response; response.set_locked(0); EXPECT_CALL(mockService, GetLock(_, _)) .WillOnce(DoAll(SetArgPointee<1>(response), Return(APP_SUCCESS))); OemLock hal{mockService}; hal.isOemUnlockAllowedByCarrier([](OemLockStatus status, bool allowed) { ASSERT_THAT(status, Eq(OemLockStatus::OK)); ASSERT_TRUE(allowed); }); } TEST(OemLockHalTest, isOemUnlockAllowedByCarrierWhenNotAllowed) { MockAvb mockService; GetLockResponse response; response.set_locked(1); EXPECT_CALL(mockService, GetLock(_, _)) .WillOnce(DoAll(SetArgPointee<1>(response), Return(APP_SUCCESS))); OemLock hal{mockService}; hal.isOemUnlockAllowedByCarrier([](OemLockStatus status, bool allowed) { ASSERT_THAT(status, Eq(OemLockStatus::OK)); ASSERT_FALSE(allowed); }); } TEST(OemLockHalTest, isOemUnlockAllowedByCarrierFailsonAvbError) { MockAvb mockService; EXPECT_CALL(mockService, GetLock(_, _)).WillOnce(Return(APP_ERROR_INTERNAL)); OemLock hal{mockService}; hal.isOemUnlockAllowedByCarrier([](OemLockStatus status, bool allowed) { ASSERT_THAT(status, Eq(OemLockStatus::FAILED)); (void) allowed; }); } // setOemUnlockAllowedByDevice MATCHER_P(SetDeviceLockEq, msg, "") { return arg.locked() == msg.locked(); } TEST(OemLockHalTest, setOemUnlockAllowedByDevice) { MockAvb mockService; SetDeviceLockRequest request; request.set_locked(0); EXPECT_CALL(mockService, SetDeviceLock(SetDeviceLockEq(request), _)) .WillOnce(Return(APP_SUCCESS)); OemLock hal{mockService}; ASSERT_THAT(hal.setOemUnlockAllowedByDevice(true), Eq(OemLockStatus::OK)); } TEST(OemLockHalTest, setOemUnlockNotAllowedByDevice) { MockAvb mockService; SetDeviceLockRequest request; request.set_locked(1); EXPECT_CALL(mockService, SetDeviceLock(SetDeviceLockEq(request), _)) .WillOnce(Return(APP_SUCCESS)); OemLock hal{mockService}; ASSERT_THAT(hal.setOemUnlockAllowedByDevice(false), Eq(OemLockStatus::OK)); } TEST(OemLockHalTest, setOemUnlockAllowedByDeviceFailsOnAppError) { MockAvb mockService; EXPECT_CALL(mockService, SetDeviceLock(_, _)).WillOnce(Return(APP_ERROR_INTERNAL)); OemLock hal{mockService}; ASSERT_THAT(hal.setOemUnlockAllowedByDevice(true), Eq(OemLockStatus::FAILED)); } // isOemUnlockAllowedByDevice TEST(OemLockHalTest, isOemUnlockAllowedByDeviceChecksDeviceLock) { MockAvb mockService; GetLockRequest request; request.set_lock(LockIndex::DEVICE); EXPECT_CALL(mockService, GetLock(GetLockEq(request), _)).WillOnce(Return(APP_ERROR_RPC)); OemLock hal{mockService}; hal.isOemUnlockAllowedByDevice([](OemLockStatus status, bool allowed) { ASSERT_THAT(status, Eq(OemLockStatus::FAILED)); (void) allowed; }); } TEST(OemLockHalTest, isOemUnlockAllowedByDeviceWhenAllowed) { MockAvb mockService; GetLockResponse response; response.set_locked(0); EXPECT_CALL(mockService, GetLock(_, _)) .WillOnce(DoAll(SetArgPointee<1>(response), Return(APP_SUCCESS))); OemLock hal{mockService}; hal.isOemUnlockAllowedByDevice([](OemLockStatus status, bool allowed) { ASSERT_THAT(status, Eq(OemLockStatus::OK)); ASSERT_TRUE(allowed); }); } TEST(OemLockHalTest, isOemUnlockAllowedByDeviceWhenNotAllowed) { MockAvb mockService; GetLockResponse response; response.set_locked(1); EXPECT_CALL(mockService, GetLock(_, _)) .WillOnce(DoAll(SetArgPointee<1>(response), Return(APP_SUCCESS))); OemLock hal{mockService}; hal.isOemUnlockAllowedByDevice([](OemLockStatus status, bool allowed) { ASSERT_THAT(status, Eq(OemLockStatus::OK)); ASSERT_FALSE(allowed); }); } TEST(OemLockHalTest, isOemUnlockAllowedByDeviceFailsonAvbError) { MockAvb mockService; EXPECT_CALL(mockService, GetLock(_, _)).WillOnce(Return(APP_ERROR_INTERNAL)); OemLock hal{mockService}; hal.isOemUnlockAllowedByDevice([](OemLockStatus status, bool allowed) { ASSERT_THAT(status, Eq(OemLockStatus::FAILED)); (void) allowed; }); } // carrierUnlockFromSignature TEST(OemLockHalTest, carrierUnlockFromSignatureParsesFields) { constexpr uint64_t version = 0x1234567890abcdef; constexpr uint64_t nonce = 0x24680ace13579bdf; const std::vector<uint8_t> token { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 2, 4, 6, 8, 1, 3, 5, 7, 9, }; const auto signature = makeSignature(version, nonce, token); CarrierUnlock unlock; ASSERT_TRUE(OemLock::carrierUnlockFromSignature(signature, &unlock)); EXPECT_THAT(unlock.version(), Eq(version)); EXPECT_THAT(unlock.nonce(), Eq(nonce)); EXPECT_THAT(unlock.signature().size(), Eq(token.size())); EXPECT_THAT(unlock.signature(), ElementsAreArray(token)); } TEST(OemLockHalTest, carrierUnlockFromSignatureCrashesOnNullptr) { hidl_vec<uint8_t> signature(sizeof(uint64_t) * 2); ASSERT_DEATH(OemLock::carrierUnlockFromSignature(signature, nullptr), ""); } TEST(OemLockHalTest, carrierUnlockFromSignatureFailsOnShortSignature) { hidl_vec<uint8_t> signature((sizeof(uint64_t) * 2) - 1); CarrierUnlock unlock; ASSERT_FALSE(OemLock::carrierUnlockFromSignature(signature, &unlock)); }
32.087209
96
0.717068
[ "vector" ]
edc05bf60484913b968d9817dab20c2e8c4a2e7a
8,479
cpp
C++
src/finder-sync/finder-sync-host.cpp
duzhanyuan/seafile-client
19334590d6e9557a9107af1307a0d09e351005dc
[ "Apache-2.0" ]
null
null
null
src/finder-sync/finder-sync-host.cpp
duzhanyuan/seafile-client
19334590d6e9557a9107af1307a0d09e351005dc
[ "Apache-2.0" ]
null
null
null
src/finder-sync/finder-sync-host.cpp
duzhanyuan/seafile-client
19334590d6e9557a9107af1307a0d09e351005dc
[ "Apache-2.0" ]
null
null
null
#include "finder-sync/finder-sync-host.h" #include <vector> #include <mutex> #include <memory> #include <QDir> #include <QFileInfo> #include "account.h" #include "account-mgr.h" #include "auto-login-service.h" #include "settings-mgr.h" #include "seafile-applet.h" #include "daemon-mgr.h" #include "rpc/local-repo.h" #include "rpc/rpc-client.h" #include "filebrowser/file-browser-requests.h" #include "filebrowser/sharedlink-dialog.h" #include "filebrowser/seafilelink-dialog.h" #include "utils/utils.h" enum PathStatus { SYNC_STATUS_NONE = 0, SYNC_STATUS_SYNCING, SYNC_STATUS_ERROR, SYNC_STATUS_IGNORED, SYNC_STATUS_SYNCED, SYNC_STATUS_READONLY, SYNC_STATUS_PAUSED, SYNC_STATUS_LOCKED, SYNC_STATUS_LOCKED_BY_ME, MAX_SYNC_STATUS, }; namespace { struct QtLaterDeleter { public: void operator()(QObject *ptr) { ptr->deleteLater(); } }; } // anonymous namespace static const char *const kPathStatus[] = { "none", "syncing", "error", "ignored", "synced", "readonly", "paused", "locked", "locked_by_me", NULL, }; static inline PathStatus getPathStatusFromString(const QString &status) { for (int p = SYNC_STATUS_NONE; p < MAX_SYNC_STATUS; ++p) if (kPathStatus[p] == status) return static_cast<PathStatus>(p); return SYNC_STATUS_NONE; } inline static bool isContainsPrefix(const QString &path, const QString &prefix) { if (prefix.size() > path.size()) return false; if (!path.startsWith(prefix)) return false; if (prefix.size() < path.size() && path[prefix.size()] != '/') return false; return true; } static std::mutex update_mutex_; static std::vector<LocalRepo> watch_set_; static std::unique_ptr<GetSharedLinkRequest, QtLaterDeleter> get_shared_link_req_; static std::unique_ptr<LockFileRequest, QtLaterDeleter> lock_file_req_; FinderSyncHost::FinderSyncHost() : rpc_client_(new SeafileRpcClient) { rpc_client_->tryConnectDaemon(); connect(seafApplet->daemonManager(), SIGNAL(daemonRestarted()), this, SLOT(onDaemonRestarted())); } FinderSyncHost::~FinderSyncHost() { get_shared_link_req_.reset(); lock_file_req_.reset(); } void FinderSyncHost::onDaemonRestarted() { qDebug("reviving rpc client when daemon is restarted"); if (rpc_client_) { delete rpc_client_; } rpc_client_ = new SeafileRpcClient(); rpc_client_->tryConnectDaemon(); } utils::BufferArray FinderSyncHost::getWatchSet(size_t header_size, int max_size) { updateWatchSet(); // lock is inside std::unique_lock<std::mutex> lock(update_mutex_); std::vector<QByteArray> array; size_t byte_count = header_size; unsigned count = (max_size >= 0 && watch_set_.size() > (unsigned)max_size) ? max_size : watch_set_.size(); for (unsigned i = 0; i < count; ++i) { array.emplace_back(watch_set_[i].worktree.toUtf8()); byte_count += 36 + array.back().size() + 3; } // rount byte_count to longword-size size_t round_end = byte_count & 3; if (round_end) byte_count += 4 - round_end; utils::BufferArray retval; retval.resize(byte_count); // zeroize rounds switch (round_end) { case 1: retval[byte_count - 3] = '\0'; case 2: retval[byte_count - 2] = '\0'; case 3: retval[byte_count - 1] = '\0'; default: break; } assert(retval.size() == byte_count); char *pos = retval.data() + header_size; for (unsigned i = 0; i != count; ++i) { // copy repo_id memcpy(pos, watch_set_[i].id.toUtf8().data(), 36); pos += 36; // copy worktree memcpy(pos, array[i].data(), array[i].size() + 1); pos += array[i].size() + 1; // copy status *pos++ = watch_set_[i].sync_state; *pos++ = '\0'; } return retval; } void FinderSyncHost::updateWatchSet() { std::unique_lock<std::mutex> lock(update_mutex_); // update watch_set_ if (rpc_client_->listLocalRepos(&watch_set_)) { qWarning("[FinderSync] update watch set failed"); watch_set_.clear(); return; } for (LocalRepo &repo : watch_set_) rpc_client_->getSyncStatus(repo); lock.unlock(); } uint32_t FinderSyncHost::getFileStatus(const char *repo_id, const char *path) { std::unique_lock<std::mutex> lock(update_mutex_); QString repo = QString::fromUtf8(repo_id, 36); QString path_in_repo = path; QString status; bool isDirectory = path_in_repo.endsWith('/'); if (isDirectory) path_in_repo.resize(path_in_repo.size() - 1); if (rpc_client_->getRepoFileStatus( repo, path_in_repo, isDirectory, &status) != 0) { return PathStatus::SYNC_STATUS_NONE; } return getPathStatusFromString(status); } void FinderSyncHost::doShareLink(const QString &path) { QString repo_id; Account account; QString path_in_repo; if (!lookUpFileInformation(path, &repo_id, &account, &path_in_repo)) { qWarning("[FinderSync] invalid path %s", path.toUtf8().data()); return; } get_shared_link_req_.reset(new GetSharedLinkRequest( account, repo_id, QString("/").append(path_in_repo), QFileInfo(path).isFile())); connect(get_shared_link_req_.get(), SIGNAL(success(const QString &, const QString&)), this, SLOT(onShareLinkGenerated(const QString &))); get_shared_link_req_->send(); } void FinderSyncHost::doInternalLink(const QString &path) { QString repo_id; Account account; QString path_in_repo; if (!lookUpFileInformation(path, &repo_id, &account, &path_in_repo)) { qWarning("[FinderSync] invalid path %s", path.toUtf8().data()); return; } SeafileLinkDialog(repo_id, account, path_in_repo).exec(); } void FinderSyncHost::doLockFile(const QString &path, bool lock) { QString repo_id; Account account; QString path_in_repo; if (!lookUpFileInformation(path, &repo_id, &account, &path_in_repo)) { qWarning("[FinderSync] invalid path %s", path.toUtf8().data()); return; } lock_file_req_.reset(new LockFileRequest(account, repo_id, path_in_repo, lock)); connect(lock_file_req_.get(), SIGNAL(success()), this, SLOT(onLockFileSuccess())); lock_file_req_->send(); } void FinderSyncHost::onShareLinkGenerated(const QString &link) { SharedLinkDialog *dialog = new SharedLinkDialog(link, NULL); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); dialog->raise(); dialog->activateWindow(); } void FinderSyncHost::onLockFileSuccess() { LockFileRequest* req = qobject_cast<LockFileRequest*>(sender()); if (!req) return; rpc_client_->markFileLockState(req->repoId(), req->path(), req->lock()); } bool FinderSyncHost::lookUpFileInformation(const QString &path, QString *repo_id, Account *account, QString *path_in_repo) { QString worktree; // work in a mutex { std::unique_lock<std::mutex> watch_set_lock(update_mutex_); for (const LocalRepo &repo : watch_set_) if (isContainsPrefix(path, repo.worktree)) { *repo_id = repo.id; worktree = repo.worktree; break; } } if (worktree.isEmpty() || repo_id->isEmpty()) return false; *path_in_repo = QDir(worktree).relativeFilePath(path); if (!path_in_repo->startsWith("/")) *path_in_repo = "/" + *path_in_repo; if (path.endsWith("/")) *path_in_repo += "/"; // we have a empty path_in_repo representing the root of the directory, // and we are okay! if (path_in_repo->startsWith(".")) return false; *account = seafApplet->accountManager()->getAccountByRepo(*repo_id); if (!account->isValid()) return false; return true; } void FinderSyncHost::doShowFileHistory(const QString &path) { QString repo_id; Account account; QString path_in_repo; if (!lookUpFileInformation(path, &repo_id, &account, &path_in_repo)) { qWarning("[FinderSync] invalid path %s", path.toUtf8().data()); return; } QUrl url = "/repo/file_revisions/" + repo_id + "/"; url = ::includeQueryParams(url, {{"p", path_in_repo}}); AutoLoginService::instance()->startAutoLogin(url.toString()); }
29.3391
122
0.645713
[ "vector" ]
edc3ff588f0b5c12ee14ece36c17668b4ce14ad9
708
cpp
C++
pat/pat1071.cpp
zofvbeaf/algorithm-practices
9772808fdf1b73ac55887291d9fb680e90b60958
[ "MIT" ]
null
null
null
pat/pat1071.cpp
zofvbeaf/algorithm-practices
9772808fdf1b73ac55887291d9fb680e90b60958
[ "MIT" ]
null
null
null
pat/pat1071.cpp
zofvbeaf/algorithm-practices
9772808fdf1b73ac55887291d9fb680e90b60958
[ "MIT" ]
null
null
null
#include<cstdio> #include<iostream> #include<algorithm> #include<string> #include<vector> #include<math.h> using namespace std; string s[2000000]; char a,b; int tot=0; bool check(char x){ return x>='a'&& x<='z' || x>='0'&& x<='9' || x>='A'&& x<='Z'; } int main(){ b = '\n'; while((a = getchar()) != '\n'){ if(check(a)) { if(a>='A'&&a<='Z') a += 32; s[tot] += a; } else if(check(b)) tot++; b = a; } if(s[tot]!="") tot++; sort(s, s+tot); int ans = 1, id = 0; for(int i=1,k=1; i<tot; i++){ if(s[i]==s[i-1]) k++; if(i==tot-1 || s[i] != s[i-1]){ if(ans < k) ans = k, id = i-1; k = 1; } } cout<<s[id]<<" "<<ans<<endl; return 0; }
17.7
63
0.451977
[ "vector" ]
edc5f7f949672e5627a7304315f1bb03973c2bfa
15,072
cpp
C++
fdbserver/workloads/BackupToDBUpgrade.actor.cpp
wangmeng99/foundationdb
50d303867b1b05070611deaef03ea4d84cf74e34
[ "Apache-2.0" ]
null
null
null
fdbserver/workloads/BackupToDBUpgrade.actor.cpp
wangmeng99/foundationdb
50d303867b1b05070611deaef03ea4d84cf74e34
[ "Apache-2.0" ]
null
null
null
fdbserver/workloads/BackupToDBUpgrade.actor.cpp
wangmeng99/foundationdb
50d303867b1b05070611deaef03ea4d84cf74e34
[ "Apache-2.0" ]
null
null
null
/* * BackupToDBUpgrade.actor.cpp * * This source file is part of the FoundationDB open source project * * Copyright 2013-2018 Apple Inc. and the FoundationDB project authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "flow/actorcompiler.h" #include "fdbrpc/simulator.h" #include "fdbclient/BackupAgent.h" #include "workloads.h" #include "BulkSetup.actor.h" //A workload which test the correctness of upgrading DR from 5.1 to 5.2 struct BackupToDBUpgradeWorkload : TestWorkload { double backupAfter, stopDifferentialAfter; Key backupTag, restoreTag, backupPrefix, extraPrefix; int backupRangesCount, backupRangeLengthMax; Standalone<VectorRef<KeyRangeRef>> backupRanges; Database extraDB; bool shareLogRange; BackupToDBUpgradeWorkload(WorkloadContext const& wcx) : TestWorkload(wcx) { backupAfter = getOption(options, LiteralStringRef("backupAfter"), g_random->random01() * 10.0); backupPrefix = getOption(options, LiteralStringRef("backupPrefix"), StringRef()); backupRangeLengthMax = getOption(options, LiteralStringRef("backupRangeLengthMax"), 1); stopDifferentialAfter = getOption(options, LiteralStringRef("stopDifferentialAfter"), 60.0); backupTag = getOption(options, LiteralStringRef("backupTag"), BackupAgentBase::getDefaultTag()); restoreTag = getOption(options, LiteralStringRef("restoreTag"), LiteralStringRef("restore")); backupRangesCount = getOption(options, LiteralStringRef("backupRangesCount"), 5); extraPrefix = backupPrefix.withPrefix(LiteralStringRef("\xfe\xff\xfe")); backupPrefix = backupPrefix.withPrefix(LiteralStringRef("\xfe\xff\xff")); ASSERT(backupPrefix != StringRef()); KeyRef beginRange; KeyRef endRange; if(backupRangesCount <= 0) { backupRanges.push_back_deep(backupRanges.arena(), KeyRangeRef(normalKeys.begin, std::min(backupPrefix, extraPrefix))); } else { // Add backup ranges for (int rangeLoop = 0; rangeLoop < backupRangesCount; rangeLoop++) { // Get a random range of a random sizes beginRange = KeyRef(backupRanges.arena(), g_random->randomAlphaNumeric(g_random->randomInt(1, backupRangeLengthMax + 1))); endRange = KeyRef(backupRanges.arena(), g_random->randomAlphaNumeric(g_random->randomInt(1, backupRangeLengthMax + 1))); // Add the range to the array backupRanges.push_back_deep(backupRanges.arena(), (beginRange < endRange) ? KeyRangeRef(beginRange, endRange) : KeyRangeRef(endRange, beginRange)); // Track the added range TraceEvent("DRU_backup_range").detail("rangeBegin", (beginRange < endRange) ? printable(beginRange) : printable(endRange)) .detail("rangeEnd", (beginRange < endRange) ? printable(endRange) : printable(beginRange)); } } Reference<ClusterConnectionFile> extraFile(new ClusterConnectionFile(*g_simulator.extraDB)); Reference<Cluster> extraCluster = Cluster::createCluster(extraFile, -1); extraDB = extraCluster->createDatabase(LiteralStringRef("DB")).get(); TraceEvent("DRU_start"); } virtual std::string description() { return "BackupToDBUpgrade"; } virtual Future<Void> setup(Database const& cx) { if (clientId != 0) return Void(); return _setup(cx, this); } virtual Future<Void> start(Database const& cx) { if (clientId != 0) return Void(); return _start(cx, this); } virtual Future<bool> check(Database const& cx) { return true; } virtual void getMetrics(vector<PerfMetric>& m) { } ACTOR static Future<Void> doBackup(BackupToDBUpgradeWorkload* self, DatabaseBackupAgent* backupAgent, Database cx, Key tag, Standalone<VectorRef<KeyRangeRef>> backupRanges) { try { state Reference<ReadYourWritesTransaction> tr(new ReadYourWritesTransaction(self->extraDB)); loop{ try { for (auto r : self->backupRanges) { if (!r.empty()) { auto targetRange = r.withPrefix(self->backupPrefix); printf("Clearing %s in destination\n", printable(targetRange).c_str()); tr->addReadConflictRange(targetRange); tr->clear(targetRange); } } Void _ = wait(backupAgent->submitBackup(tr, tag, backupRanges, false, self->backupPrefix, StringRef())); Void _ = wait(tr->commit()); break; } catch (Error &e) { Void _ = wait(tr->onError(e)); } } TraceEvent("DRU_doBackupInDifferentialMode").detail("tag", printable(tag)); } catch (Error &e) { TraceEvent("DRU_doBackupSubmitBackupError").detail("tag", printable(tag)).error(e); if (e.code() != error_code_backup_unneeded && e.code() != error_code_backup_duplicate) { throw e; } } int _ = wait( backupAgent->waitBackup(self->extraDB, tag, false) ); return Void(); } ACTOR static Future<Void> checkData(Database cx, UID logUid, UID destUid, Key tag, DatabaseBackupAgent* backupAgent, bool shareLogRange) { state Key backupAgentKey = uidPrefixKey(logRangesRange.begin, logUid); state Key backupLogValuesKey = uidPrefixKey(backupLogKeys.begin, destUid); state Key backupLatestVersionsPath = uidPrefixKey(backupLatestVersionsPrefix, destUid); state Key backupLatestVersionsKey = uidPrefixKey(backupLatestVersionsPath, logUid); state int displaySystemKeys = 0; ASSERT(destUid.isValid()); // Ensure that there is no left over key within the backup subspace loop { state Reference<ReadYourWritesTransaction> tr(new ReadYourWritesTransaction(cx)); TraceEvent("DRU_checkLeftoverkeys").detail("backupTag", printable(tag)); try { tr->setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS); // Check the left over tasks // We have to wait for the list to empty since an abort and get status // can leave extra tasks in the queue TraceEvent("DRU_checkLeftovertasks").detail("backupTag", printable(tag)); state int64_t taskCount = wait( backupAgent->getTaskCount(tr) ); state int waitCycles = 0; if ((taskCount) && (0)) { TraceEvent("DRU_EndingNonzeroTaskCount").detail("backupTag", printable(tag)).detail("taskCount", taskCount).detail("waitCycles", waitCycles); printf("EndingNonZeroTasks: %ld\n", (long) taskCount); Void _ = wait(TaskBucket::debugPrintRange(cx, LiteralStringRef("\xff"), StringRef())); } loop { waitCycles ++; TraceEvent("DRU_NonzeroTaskWait").detail("backupTag", printable(tag)).detail("taskCount", taskCount).detail("waitCycles", waitCycles); printf("%.6f Wait #%4d for %lld tasks to end\n", now(), waitCycles, (long long) taskCount); Void _ = wait(delay(20.0)); tr->commit(); tr = Reference<ReadYourWritesTransaction>(new ReadYourWritesTransaction(cx)); int64_t _taskCount = wait( backupAgent->getTaskCount(tr) ); taskCount = _taskCount; if (!taskCount) { break; } } if (taskCount) { displaySystemKeys ++; TraceEvent(SevError, "DRU_NonzeroTaskCount").detail("backupTag", printable(tag)).detail("taskCount", taskCount).detail("waitCycles", waitCycles); printf("BackupCorrectnessLeftOverLogTasks: %ld\n", (long) taskCount); } Standalone<RangeResultRef> agentValues = wait(tr->getRange(KeyRange(KeyRangeRef(backupAgentKey, strinc(backupAgentKey))), 100)); // Error if the system keyspace for the backup tag is not empty if (agentValues.size() > 0) { displaySystemKeys++; printf("BackupCorrectnessLeftOverMutationKeys: (%d) %s\n", agentValues.size(), printable(backupAgentKey).c_str()); TraceEvent(SevError, "BackupCorrectnessLeftOverMutationKeys").detail("backupTag", printable(tag)) .detail("LeftOverKeys", agentValues.size()).detail("keySpace", printable(backupAgentKey)); for (auto & s : agentValues) { TraceEvent("DRU_LeftOverKey").detail("key", printable(StringRef(s.key.toString()))).detail("value", printable(StringRef(s.value.toString()))); printf(" Key: %-50s Value: %s\n", printable(StringRef(s.key.toString())).c_str(), printable(StringRef(s.value.toString())).c_str()); } } else { printf("No left over backup agent configuration keys\n"); } Optional<Value> latestVersion = wait(tr->get(backupLatestVersionsKey)); if (latestVersion.present()) { TraceEvent(SevError, "BackupCorrectnessLeftOverVersionKey").detail("backupTag", printable(tag)).detail("key", backupLatestVersionsKey.printable()).detail("value", BinaryReader::fromStringRef<Version>(latestVersion.get(), Unversioned())); } else { printf("No left over backup version key\n"); } Standalone<RangeResultRef> versions = wait(tr->getRange(KeyRange(KeyRangeRef(backupLatestVersionsPath, strinc(backupLatestVersionsPath))), 1)); if (!shareLogRange || !versions.size()) { Standalone<RangeResultRef> logValues = wait(tr->getRange(KeyRange(KeyRangeRef(backupLogValuesKey, strinc(backupLogValuesKey))), 100)); // Error if the log/mutation keyspace for the backup tag is not empty if (logValues.size() > 0) { displaySystemKeys++; printf("BackupCorrectnessLeftOverLogKeys: (%d) %s\n", logValues.size(), printable(backupLogValuesKey).c_str()); TraceEvent(SevError, "BackupCorrectnessLeftOverLogKeys").detail("backupTag", printable(tag)) .detail("LeftOverKeys", logValues.size()).detail("keySpace", printable(backupLogValuesKey)).detail("version", decodeBKMutationLogKey(logValues[0].key).first); for (auto & s : logValues) { TraceEvent("DRU_LeftOverKey").detail("key", printable(StringRef(s.key.toString()))).detail("value", printable(StringRef(s.value.toString()))); printf(" Key: %-50s Value: %s\n", printable(StringRef(s.key.toString())).c_str(), printable(StringRef(s.value.toString())).c_str()); } } else { printf("No left over backup log keys\n"); } } break; } catch (Error &e) { TraceEvent("DRU_checkError").error(e); Void _ = wait(tr->onError(e)); } } if (displaySystemKeys) { Void _ = wait(TaskBucket::debugPrintRange(cx, LiteralStringRef("\xff"), StringRef())); } return Void(); } ACTOR static Future<Void> _setup(Database cx, BackupToDBUpgradeWorkload* self) { state DatabaseBackupAgent backupAgent(cx); try{ Void _ = wait(delay(self->backupAfter)); TraceEvent("DRU_doBackup").detail("tag", printable(self->backupTag)); state Future<Void> b = doBackup(self, &backupAgent, self->extraDB, self->backupTag, self->backupRanges); TraceEvent("DRU_doBackupWait").detail("backupTag", printable(self->backupTag)); Void _ = wait(b); TraceEvent("DRU_doBackupWaitEnd").detail("backupTag", printable(self->backupTag)); } catch (Error& e) { TraceEvent(SevError, "BackupToDBUpgradeSetuEerror").error(e); throw; } return Void(); } ACTOR static Future<Void> _start(Database cx, BackupToDBUpgradeWorkload* self) { state DatabaseBackupAgent backupAgent(cx); state DatabaseBackupAgent restoreAgent(self->extraDB); state Future<Void> disabler = disableConnectionFailuresAfter(300, "BackupToDBUpgradeStart"); state Standalone<VectorRef<KeyRangeRef>> prevBackupRanges; state UID logUid; state Future<Void> stopDifferential = delay(self->stopDifferentialAfter); state Future<Void> waitUpgrade = backupAgent.waitUpgradeToLatestDrVersion(self->extraDB, self->backupTag); Void _ = wait(success(stopDifferential) && success(waitUpgrade)); TraceEvent("DRU_waitDifferentialEnd").detail("tag", printable(self->backupTag)); try { // Get restore ranges before aborting state Reference<ReadYourWritesTransaction> tr(new ReadYourWritesTransaction(self->extraDB)); loop { try { // Get backup ranges tr->setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS); UID _logUid = wait(backupAgent.getLogUid(tr, self->backupTag)); logUid = _logUid; Optional<Key> backupKeysPacked = wait(tr->get(backupAgent.config.get(BinaryWriter::toValue(logUid, Unversioned())).pack(BackupAgentBase::keyConfigBackupRanges))); ASSERT(backupKeysPacked.present()); BinaryReader br(backupKeysPacked.get(), IncludeVersion()); br >> prevBackupRanges; break; } catch( Error &e ) { Void _ = wait( tr->onError(e) ); } } // abort backup TraceEvent("DRU_abortBackup").detail("tag", printable(self->backupTag)); Void _ = wait(backupAgent.abortBackup(self->extraDB, self->backupTag)); // restore database TraceEvent("DRU_prepareRestore").detail("restoreTag", printable(self->restoreTag)); state Reference<ReadYourWritesTransaction> tr2(new ReadYourWritesTransaction(cx)); loop{ try{ tr2->setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS); tr2->setOption(FDBTransactionOptions::LOCK_AWARE); for (auto r : prevBackupRanges) { if(!r.empty()) { std::cout << "r: " << r.begin.printable() << " - " << r.end.printable() << std::endl; tr2->addReadConflictRange(r); tr2->clear(r); } } Void _ = wait( tr2->commit() ); break; } catch( Error &e ) { TraceEvent("DRU_restoreSetupError").error(e, true); Void _ = wait( tr2->onError(e) ); } } state Standalone<VectorRef<KeyRangeRef>> restoreRanges; for (auto r : prevBackupRanges) { restoreRanges.push_back_deep(restoreRanges.arena(), KeyRangeRef( r.begin.withPrefix(self->backupPrefix), r.end.withPrefix(self->backupPrefix) ) ); } // start restoring db try { TraceEvent("DRU_restoreDb").detail("restoreTag", printable(self->restoreTag)); Void _ = wait(restoreAgent.submitBackup(cx, self->restoreTag, restoreRanges, true, StringRef(), self->backupPrefix)); } catch (Error& e) { TraceEvent("DRU_restoreSubmitBackupError").detail("tag", printable(self->restoreTag)).error(e); if (e.code() != error_code_backup_unneeded && e.code() != error_code_backup_duplicate) throw; } int _ = wait(restoreAgent.waitBackup(cx, self->restoreTag)); Void _ = wait(restoreAgent.unlockBackup(cx, self->restoreTag)); Void _ = wait(checkData(self->extraDB, logUid, logUid, self->backupTag, &backupAgent, self->shareLogRange)); state UID restoreUid = wait(restoreAgent.getLogUid(cx, self->restoreTag)); Void _ = wait(checkData(cx, restoreUid, restoreUid, self->restoreTag, &restoreAgent, self->shareLogRange)); TraceEvent("DRU_complete").detail("backupTag", printable(self->backupTag)); if (g_simulator.drAgents == ISimulator::BackupToDB) { g_simulator.drAgents = ISimulator::NoBackupAgents; } } catch (Error& e) { TraceEvent(SevError, "BackupAndRestoreCorrectnessError").error(e); throw; } return Void(); } }; WorkloadFactory<BackupToDBUpgradeWorkload> BackupToDBUpgradeWorkloadFactory("BackupToDBUpgrade");
41.180328
242
0.713575
[ "vector" ]
edc5ff9b52444d3a72db4302ec8d8b62dfad0f01
2,048
cpp
C++
src/graph/qfacebookgraphconnectionmediabase.cpp
heliocastro/QFacebookGraph
39cfdaecd70ebb0b7617013cd47737939c71a00c
[ "Apache-2.0" ]
1
2019-03-01T23:08:24.000Z
2019-03-01T23:08:24.000Z
src/graph/qfacebookgraphconnectionmediabase.cpp
heliocastro/QFacebookGraph
39cfdaecd70ebb0b7617013cd47737939c71a00c
[ "Apache-2.0" ]
null
null
null
src/graph/qfacebookgraphconnectionmediabase.cpp
heliocastro/QFacebookGraph
39cfdaecd70ebb0b7617013cd47737939c71a00c
[ "Apache-2.0" ]
null
null
null
#include <QDebug> #include <graph/qfacebookgraphconnectionmediabase.h> #include <graph/qfacebookgraphcommonmediamodel.h> QFacebookGraphConnectionMediaBase::QFacebookGraphConnectionMediaBase(QString fbid, QObject *parent) : QFacebookGraph( parent ) { m_fbid = fbid; m_model = QList<QObject*>(); } QList<QObject*> QFacebookGraphConnectionMediaBase::model() { return m_model; } void QFacebookGraphConnectionMediaBase::update(int howMany) { Q_UNUSED(howMany) } void QFacebookGraphConnectionMediaBase::requestDone(bool ok) { m_model.clear(); if (ok) { if(result().contains("data")) populateModel(); emit modelPopulated(); } else qDebug() << "Request failed"; } void QFacebookGraphConnectionMediaBase::populateModel() { QFacebookGraphCommonMediaModel *obj = new QFacebookGraphCommonMediaModel(); QVariantList list = result().value("data").toList(); QVariantList::const_iterator i; for (i = list.constBegin(); i != list.constEnd(); ++i) { QVariantMap::const_iterator j; for(j = (*i).toMap().constBegin(); j != (*i).toMap().constEnd(); ++j) { if(j.key() == "name") obj->setName(j.value().toString()); if(j.key() == "created_time") obj->setCreatedTime( QDateTime::fromString( j.value().toString(), "yyyy-MM-dd'T'hh:mm:ss+0000") ); if(j.key() == "id") obj->setFbid(j.value().toString()); if(j.key() == "category") obj->setCategory(j.value().toString()); } append(obj); obj = new QFacebookGraphCommonMediaModel(); } } void QFacebookGraphConnectionMediaBase::setFbid(const QString &fbid) { if(m_fbid != fbid) m_fbid = fbid; } QString QFacebookGraphConnectionMediaBase::fbid() const { return m_fbid; } void QFacebookGraphConnectionMediaBase::append(QFacebookGraphCommonMediaModel *obj) { m_model.append(obj); }
28.84507
101
0.617676
[ "model" ]
edc83debc0cec314795c3d1f293dadae4237cddb
4,560
cpp
C++
src/scomponents/graphics/meshes.cpp
guillaume-haerinck/voxel-editor
78c2db3e7f33a1944ef6202c8ae33f4008695153
[ "MIT" ]
7
2019-12-30T21:01:06.000Z
2022-02-24T07:41:52.000Z
src/scomponents/graphics/meshes.cpp
guillaume-haerinck/voxel-editor
78c2db3e7f33a1944ef6202c8ae33f4008695153
[ "MIT" ]
null
null
null
src/scomponents/graphics/meshes.cpp
guillaume-haerinck/voxel-editor
78c2db3e7f33a1944ef6202c8ae33f4008695153
[ "MIT" ]
1
2020-04-26T22:02:29.000Z
2020-04-26T22:02:29.000Z
#include "meshes.h" #include "graphics/render-command.h" #include "graphics/primitive-data.h" void Meshes::init(RenderCommand& rcommand) { // Init Plane Mesh { // Attributes AttributeBuffer positionBuffer = rcommand.createAttributeBuffer(&squareData::positions, static_cast<unsigned int>(std::size(squareData::positions)), sizeof(glm::vec3)); AttributeBuffer texCoordBuffer = rcommand.createAttributeBuffer(&squareData::texCoords, static_cast<unsigned int>(std::size(squareData::texCoords)), sizeof(glm::vec2)); // Vertex & Index buffers PipelineInputDescription inputDescription = { { ShaderDataType::Float3, "Position" }, { ShaderDataType::Float2, "TexCoord" } }; AttributeBuffer attributeBuffers[] = { positionBuffer, texCoordBuffer }; VertexBuffer vb = rcommand.createVertexBuffer(inputDescription, attributeBuffers); IndexBuffer ib = rcommand.createIndexBuffer(squareData::indices, static_cast<unsigned int>(std::size(squareData::indices)), IndexBuffer::dataType::UNSIGNED_BYTE); // Save data Mesh mesh; mesh.ib = ib; mesh.vb = vb; m_plane = mesh; } // Init CubeMesh { // Attributes AttributeBuffer positionBuffer = rcommand.createAttributeBuffer(&cubeData::positions, static_cast<unsigned int>(std::size(cubeData::positions)), sizeof(glm::vec3)); AttributeBuffer normalBuffer = rcommand.createAttributeBuffer(&cubeData::normals, static_cast<unsigned int>(std::size(cubeData::normals)), sizeof(glm::vec3)); std::array<glm::vec3, 15> translations; // TODO set to scene size AttributeBuffer translationInstanceBuffer = rcommand.createAttributeBuffer(translations.data(), static_cast<unsigned int>(translations.size()), sizeof(glm::vec3), AttributeBufferUsage::DYNAMIC_DRAW, AttributeBufferType::PER_INSTANCE_TRANSLATION); std::array<glm::vec3, 15> entityIds; AttributeBuffer entityInstanceBuffer = rcommand.createAttributeBuffer(entityIds.data(), static_cast<unsigned int>(entityIds.size()), sizeof(glm::vec3), AttributeBufferUsage::DYNAMIC_DRAW, AttributeBufferType::PER_INSTANCE_ENTITY_ID); std::array<unsigned int, 15> materialIndices; AttributeBuffer materialInstanceBuffer = rcommand.createAttributeBuffer(materialIndices.data(), static_cast<unsigned int>(materialIndices.size()), sizeof(unsigned int), AttributeBufferUsage::DYNAMIC_DRAW, AttributeBufferType::PER_INSTANCE_MATERIAL); // Vertex & Index buffers PipelineInputDescription inputDescription = { { ShaderDataType::Float3, "Position" }, { ShaderDataType::Float3, "Translation", BufferElementUsage::PerInstance }, { ShaderDataType::Float3, "Normal" }, { ShaderDataType::Float3, "EntityId", BufferElementUsage::PerInstance }, { ShaderDataType::UInt, "MaterialIndex", BufferElementUsage::PerInstance } }; AttributeBuffer attributeBuffers[] = { positionBuffer, translationInstanceBuffer, normalBuffer, entityInstanceBuffer, materialInstanceBuffer }; VertexBuffer vb = rcommand.createVertexBuffer(inputDescription, attributeBuffers); IndexBuffer ib = rcommand.createIndexBuffer(cubeData::indices, static_cast<unsigned int>(std::size(cubeData::indices)), IndexBuffer::dataType::UNSIGNED_BYTE); // Save data Mesh mesh; mesh.ib = ib; mesh.vb = vb; m_cube = mesh; } // Init Inverted CubeMesh { // Attributes AttributeBuffer positionBuffer = rcommand.createAttributeBuffer(&cubeData::positions, static_cast<unsigned int>(std::size(cubeData::positions)), sizeof(glm::vec3)); AttributeBuffer texCoordBuffer = rcommand.createAttributeBuffer(&cubeData::texCoords, static_cast<unsigned int>(std::size(cubeData::texCoords)), sizeof(glm::vec2)); // Vertex & Index buffers PipelineInputDescription inputDescription = { { ShaderDataType::Float3, "Position" }, { ShaderDataType::Float2, "TexCoord" } }; AttributeBuffer attributeBuffers[] = { positionBuffer, texCoordBuffer }; VertexBuffer vb = rcommand.createVertexBuffer(inputDescription, attributeBuffers); IndexBuffer ib = rcommand.createIndexBuffer(cubeData::invertIndices, static_cast<unsigned int>(std::size(cubeData::invertIndices)), IndexBuffer::dataType::UNSIGNED_BYTE); // Save data Mesh mesh; mesh.ib = ib; mesh.vb = vb; m_invertCube = mesh; } } void Meshes::destroy(RenderCommand& rcommand) { // Cube rcommand.deleteVertexBuffer(m_cube.vb); rcommand.deleteIndexBuffer(m_cube.ib); // Plane rcommand.deleteVertexBuffer(m_plane.vb); rcommand.deleteIndexBuffer(m_plane.ib); // InvertedCube rcommand.deleteVertexBuffer(m_invertCube.vb); rcommand.deleteIndexBuffer(m_invertCube.ib); }
44.705882
251
0.76886
[ "mesh", "render" ]
edc92c6e49718f61f5d2038ad6276809de1d9271
115,087
cc
C++
test/cctest/compiler/test-run-bytecode-graph-builder.cc
adblockplus/v8-googlesource
f318f9835fb4c3f509fe2530cf72c08c56b74ee5
[ "BSD-3-Clause" ]
3
2015-11-15T05:58:32.000Z
2019-03-19T11:29:44.000Z
test/cctest/compiler/test-run-bytecode-graph-builder.cc
ConnectionMaster/v8-googlesource
f318f9835fb4c3f509fe2530cf72c08c56b74ee5
[ "BSD-3-Clause" ]
null
null
null
test/cctest/compiler/test-run-bytecode-graph-builder.cc
ConnectionMaster/v8-googlesource
f318f9835fb4c3f509fe2530cf72c08c56b74ee5
[ "BSD-3-Clause" ]
10
2015-10-15T06:16:55.000Z
2019-06-23T18:52:25.000Z
// Copyright 2015 the V8 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. #include <utility> #include "src/api.h" #include "src/compiler/pipeline.h" #include "src/debug/debug-interface.h" #include "src/execution.h" #include "src/handles.h" #include "src/interpreter/bytecode-array-builder.h" #include "src/interpreter/interpreter.h" #include "src/objects-inl.h" #include "src/optimized-compilation-info.h" #include "src/parsing/parse-info.h" #include "test/cctest/cctest.h" namespace v8 { namespace internal { namespace compiler { #define SHARD_TEST_BY_2(x) \ TEST(x##_0) { Test##x(0); } \ TEST(x##_1) { Test##x(1); } #define SHARD_TEST_BY_4(x) \ TEST(x##_0) { Test##x(0); } \ TEST(x##_1) { Test##x(1); } \ TEST(x##_2) { Test##x(2); } \ TEST(x##_3) { Test##x(3); } static const char kFunctionName[] = "f"; static const Token::Value kCompareOperators[] = { Token::Value::EQ, Token::Value::NE, Token::Value::EQ_STRICT, Token::Value::NE_STRICT, Token::Value::LT, Token::Value::LTE, Token::Value::GT, Token::Value::GTE}; static const int SMI_MAX = (1 << 30) - 1; static const int SMI_MIN = -(1 << 30); static MaybeHandle<Object> CallFunction(Isolate* isolate, Handle<JSFunction> function) { return Execution::Call(isolate, function, isolate->factory()->undefined_value(), 0, nullptr); } template <class... A> static MaybeHandle<Object> CallFunction(Isolate* isolate, Handle<JSFunction> function, A... args) { Handle<Object> argv[] = {args...}; return Execution::Call(isolate, function, isolate->factory()->undefined_value(), sizeof...(args), argv); } template <class... A> class BytecodeGraphCallable { public: BytecodeGraphCallable(Isolate* isolate, Handle<JSFunction> function) : isolate_(isolate), function_(function) {} virtual ~BytecodeGraphCallable() {} MaybeHandle<Object> operator()(A... args) { return CallFunction(isolate_, function_, args...); } private: Isolate* isolate_; Handle<JSFunction> function_; }; class BytecodeGraphTester { public: BytecodeGraphTester(Isolate* isolate, const char* script, const char* filter = kFunctionName) : isolate_(isolate), script_(script) { i::FLAG_always_opt = false; i::FLAG_allow_natives_syntax = true; } virtual ~BytecodeGraphTester() {} template <class... A> BytecodeGraphCallable<A...> GetCallable( const char* functionName = kFunctionName) { return BytecodeGraphCallable<A...>(isolate_, GetFunction(functionName)); } Local<Message> CheckThrowsReturnMessage() { TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate_)); auto callable = GetCallable<>(); MaybeHandle<Object> no_result = callable(); CHECK(isolate_->has_pending_exception()); CHECK(try_catch.HasCaught()); CHECK(no_result.is_null()); isolate_->OptionalRescheduleException(true); CHECK(!try_catch.Message().IsEmpty()); return try_catch.Message(); } static Handle<Object> NewObject(const char* script) { return v8::Utils::OpenHandle(*CompileRun(script)); } private: Isolate* isolate_; const char* script_; Handle<JSFunction> GetFunction(const char* functionName) { CompileRun(script_); Local<Function> api_function = Local<Function>::Cast( CcTest::global() ->Get(CcTest::isolate()->GetCurrentContext(), v8_str(functionName)) .ToLocalChecked()); Handle<JSFunction> function = Handle<JSFunction>::cast(v8::Utils::OpenHandle(*api_function)); CHECK(function->shared()->HasBytecodeArray()); Zone zone(isolate_->allocator(), ZONE_NAME); Handle<SharedFunctionInfo> shared(function->shared()); OptimizedCompilationInfo compilation_info(&zone, isolate_, shared, function); // Compiler relies on canonicalized handles, let's create // a canonicalized scope and migrate existing handles there. CanonicalHandleScope canonical(isolate_); compilation_info.ReopenHandlesInNewHandleScope(); Handle<Code> code = Pipeline::GenerateCodeForTesting(&compilation_info, isolate_) .ToHandleChecked(); function->set_code(*code); return function; } DISALLOW_COPY_AND_ASSIGN(BytecodeGraphTester); }; #define SPACE() #define REPEAT_2(SEP, ...) __VA_ARGS__ SEP() __VA_ARGS__ #define REPEAT_4(SEP, ...) \ REPEAT_2(SEP, __VA_ARGS__) SEP() REPEAT_2(SEP, __VA_ARGS__) #define REPEAT_8(SEP, ...) \ REPEAT_4(SEP, __VA_ARGS__) SEP() REPEAT_4(SEP, __VA_ARGS__) #define REPEAT_16(SEP, ...) \ REPEAT_8(SEP, __VA_ARGS__) SEP() REPEAT_8(SEP, __VA_ARGS__) #define REPEAT_32(SEP, ...) \ REPEAT_16(SEP, __VA_ARGS__) SEP() REPEAT_16(SEP, __VA_ARGS__) #define REPEAT_64(SEP, ...) \ REPEAT_32(SEP, __VA_ARGS__) SEP() REPEAT_32(SEP, __VA_ARGS__) #define REPEAT_128(SEP, ...) \ REPEAT_64(SEP, __VA_ARGS__) SEP() REPEAT_64(SEP, __VA_ARGS__) #define REPEAT_256(SEP, ...) \ REPEAT_128(SEP, __VA_ARGS__) SEP() REPEAT_128(SEP, __VA_ARGS__) #define REPEAT_127(SEP, ...) \ REPEAT_64(SEP, __VA_ARGS__) \ SEP() \ REPEAT_32(SEP, __VA_ARGS__) \ SEP() \ REPEAT_16(SEP, __VA_ARGS__) \ SEP() \ REPEAT_8(SEP, __VA_ARGS__) \ SEP() \ REPEAT_4(SEP, __VA_ARGS__) SEP() REPEAT_2(SEP, __VA_ARGS__) SEP() __VA_ARGS__ template <int N, typename T = Handle<Object>> struct ExpectedSnippet { const char* code_snippet; T return_value_and_parameters[N + 1]; inline T return_value() const { return return_value_and_parameters[0]; } inline T parameter(int i) const { CHECK_GE(i, 0); CHECK_LT(i, N); return return_value_and_parameters[1 + i]; } }; TEST(BytecodeGraphBuilderReturnStatements) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"return;", {factory->undefined_value()}}, {"return null;", {factory->null_value()}}, {"return true;", {factory->true_value()}}, {"return false;", {factory->false_value()}}, {"return 0;", {factory->NewNumberFromInt(0)}}, {"return +1;", {factory->NewNumberFromInt(1)}}, {"return -1;", {factory->NewNumberFromInt(-1)}}, {"return +127;", {factory->NewNumberFromInt(127)}}, {"return -128;", {factory->NewNumberFromInt(-128)}}, {"return 0.001;", {factory->NewNumber(0.001)}}, {"return 3.7e-60;", {factory->NewNumber(3.7e-60)}}, {"return -3.7e60;", {factory->NewNumber(-3.7e60)}}, {"return '';", {factory->NewStringFromStaticChars("")}}, {"return 'catfood';", {factory->NewStringFromStaticChars("catfood")}}, {"return NaN;", {factory->nan_value()}}}; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderPrimitiveExpressions) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"return 1 + 1;", {factory->NewNumberFromInt(2)}}, {"return 20 - 30;", {factory->NewNumberFromInt(-10)}}, {"return 4 * 100;", {factory->NewNumberFromInt(400)}}, {"return 100 / 5;", {factory->NewNumberFromInt(20)}}, {"return 25 % 7;", {factory->NewNumberFromInt(4)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderTwoParameterTests) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<2> snippets[] = { // Integers {"return p1 + p2;", {factory->NewNumberFromInt(-70), factory->NewNumberFromInt(3), factory->NewNumberFromInt(-73)}}, {"return p1 + p2 + 3;", {factory->NewNumberFromInt(1139044), factory->NewNumberFromInt(300), factory->NewNumberFromInt(1138741)}}, {"return p1 - p2;", {factory->NewNumberFromInt(1100), factory->NewNumberFromInt(1000), factory->NewNumberFromInt(-100)}}, {"return p1 * p2;", {factory->NewNumberFromInt(-100000), factory->NewNumberFromInt(1000), factory->NewNumberFromInt(-100)}}, {"return p1 / p2;", {factory->NewNumberFromInt(-10), factory->NewNumberFromInt(1000), factory->NewNumberFromInt(-100)}}, {"return p1 % p2;", {factory->NewNumberFromInt(5), factory->NewNumberFromInt(373), factory->NewNumberFromInt(16)}}, // Doubles {"return p1 + p2;", {factory->NewHeapNumber(9.999), factory->NewHeapNumber(3.333), factory->NewHeapNumber(6.666)}}, {"return p1 - p2;", {factory->NewHeapNumber(-3.333), factory->NewHeapNumber(3.333), factory->NewHeapNumber(6.666)}}, {"return p1 * p2;", {factory->NewHeapNumber(3.333 * 6.666), factory->NewHeapNumber(3.333), factory->NewHeapNumber(6.666)}}, {"return p1 / p2;", {factory->NewHeapNumber(2.25), factory->NewHeapNumber(9), factory->NewHeapNumber(4)}}, // Strings {"return p1 + p2;", {factory->NewStringFromStaticChars("abcdef"), factory->NewStringFromStaticChars("abc"), factory->NewStringFromStaticChars("def")}}}; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s(p1, p2) { %s }\n%s(0, 0);", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>, Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0), snippets[i].parameter(1)) .ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderNamedLoad) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<1> snippets[] = { {"return p1.val;", {factory->NewNumberFromInt(10), BytecodeGraphTester::NewObject("({val : 10})")}}, {"return p1[\"name\"];", {factory->NewStringFromStaticChars("abc"), BytecodeGraphTester::NewObject("({name : 'abc'})")}}, {"'use strict'; return p1.val;", {factory->NewNumberFromInt(10), BytecodeGraphTester::NewObject("({val : 10 })")}}, {"'use strict'; return p1[\"val\"];", {factory->NewNumberFromInt(10), BytecodeGraphTester::NewObject("({val : 10, name : 'abc'})")}}, {"var b;\n" REPEAT_127(SPACE, " b = p1.name; ") " return p1.name;\n", {factory->NewStringFromStaticChars("abc"), BytecodeGraphTester::NewObject("({name : 'abc'})")}}, {"'use strict'; var b;\n" REPEAT_127(SPACE, " b = p1.name; ") "return p1.name;\n", {factory->NewStringFromStaticChars("abc"), BytecodeGraphTester::NewObject("({ name : 'abc'})")}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(2048); SNPrintF(script, "function %s(p1) { %s };\n%s(0);", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderKeyedLoad) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<2> snippets[] = { {"return p1[p2];", {factory->NewNumberFromInt(10), BytecodeGraphTester::NewObject("({val : 10})"), factory->NewStringFromStaticChars("val")}}, {"return p1[100];", {factory->NewStringFromStaticChars("abc"), BytecodeGraphTester::NewObject("({100 : 'abc'})"), factory->NewNumberFromInt(0)}}, {"var b = 100; return p1[b];", {factory->NewStringFromStaticChars("abc"), BytecodeGraphTester::NewObject("({100 : 'abc'})"), factory->NewNumberFromInt(0)}}, {"'use strict'; return p1[p2];", {factory->NewNumberFromInt(10), BytecodeGraphTester::NewObject("({val : 10 })"), factory->NewStringFromStaticChars("val")}}, {"'use strict'; return p1[100];", {factory->NewNumberFromInt(10), BytecodeGraphTester::NewObject("({100 : 10})"), factory->NewNumberFromInt(0)}}, {"'use strict'; var b = p2; return p1[b];", {factory->NewStringFromStaticChars("abc"), BytecodeGraphTester::NewObject("({100 : 'abc'})"), factory->NewNumberFromInt(100)}}, {"var b;\n" REPEAT_127(SPACE, " b = p1[p2]; ") " return p1[p2];\n", {factory->NewStringFromStaticChars("abc"), BytecodeGraphTester::NewObject("({100 : 'abc'})"), factory->NewNumberFromInt(100)}}, {"'use strict'; var b;\n" REPEAT_127(SPACE, " b = p1[p2]; ") "return p1[p2];\n", {factory->NewStringFromStaticChars("abc"), BytecodeGraphTester::NewObject("({ 100 : 'abc'})"), factory->NewNumberFromInt(100)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(2048); SNPrintF(script, "function %s(p1, p2) { %s };\n%s(0);", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>, Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0), snippets[i].parameter(1)) .ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } void TestBytecodeGraphBuilderNamedStore(size_t shard) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<1> snippets[] = { {"return p1.val = 20;", {factory->NewNumberFromInt(20), BytecodeGraphTester::NewObject("({val : 10})")}}, {"p1.type = 'int'; return p1.type;", {factory->NewStringFromStaticChars("int"), BytecodeGraphTester::NewObject("({val : 10})")}}, {"p1.name = 'def'; return p1[\"name\"];", {factory->NewStringFromStaticChars("def"), BytecodeGraphTester::NewObject("({name : 'abc'})")}}, {"'use strict'; p1.val = 20; return p1.val;", {factory->NewNumberFromInt(20), BytecodeGraphTester::NewObject("({val : 10 })")}}, {"'use strict'; return p1.type = 'int';", {factory->NewStringFromStaticChars("int"), BytecodeGraphTester::NewObject("({val : 10})")}}, {"'use strict'; p1.val = 20; return p1[\"val\"];", {factory->NewNumberFromInt(20), BytecodeGraphTester::NewObject("({val : 10, name : 'abc'})")}}, {"var b = 'abc';\n" REPEAT_127( SPACE, " p1.name = b; ") " p1.name = 'def'; return p1.name;\n", {factory->NewStringFromStaticChars("def"), BytecodeGraphTester::NewObject("({name : 'abc'})")}}, {"'use strict'; var b = 'def';\n" REPEAT_127( SPACE, " p1.name = 'abc'; ") "p1.name = b; return p1.name;\n", {factory->NewStringFromStaticChars("def"), BytecodeGraphTester::NewObject("({ name : 'abc'})")}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { if ((i % 2) != shard) continue; ScopedVector<char> script(3072); SNPrintF(script, "function %s(p1) { %s };\n%s({});", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } SHARD_TEST_BY_2(BytecodeGraphBuilderNamedStore) void TestBytecodeGraphBuilderKeyedStore(size_t shard) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<2> snippets[] = { {"p1[p2] = 20; return p1[p2];", {factory->NewNumberFromInt(20), BytecodeGraphTester::NewObject("({val : 10})"), factory->NewStringFromStaticChars("val")}}, {"return p1[100] = 'def';", {factory->NewStringFromStaticChars("def"), BytecodeGraphTester::NewObject("({100 : 'abc'})"), factory->NewNumberFromInt(0)}}, {"var b = 100; p1[b] = 'def'; return p1[b];", {factory->NewStringFromStaticChars("def"), BytecodeGraphTester::NewObject("({100 : 'abc'})"), factory->NewNumberFromInt(0)}}, {"'use strict'; p1[p2] = 20; return p1[p2];", {factory->NewNumberFromInt(20), BytecodeGraphTester::NewObject("({val : 10 })"), factory->NewStringFromStaticChars("val")}}, {"'use strict'; return p1[100] = 20;", {factory->NewNumberFromInt(20), BytecodeGraphTester::NewObject("({100 : 10})"), factory->NewNumberFromInt(0)}}, {"'use strict'; var b = p2; p1[b] = 'def'; return p1[b];", {factory->NewStringFromStaticChars("def"), BytecodeGraphTester::NewObject("({100 : 'abc'})"), factory->NewNumberFromInt(100)}}, {"var b;\n" REPEAT_127( SPACE, " b = p1[p2]; ") " p1[p2] = 'def'; return p1[p2];\n", {factory->NewStringFromStaticChars("def"), BytecodeGraphTester::NewObject("({100 : 'abc'})"), factory->NewNumberFromInt(100)}}, {"'use strict'; var b;\n" REPEAT_127( SPACE, " b = p1[p2]; ") " p1[p2] = 'def'; return p1[p2];\n", {factory->NewStringFromStaticChars("def"), BytecodeGraphTester::NewObject("({ 100 : 'abc'})"), factory->NewNumberFromInt(100)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { if ((i % 2) != shard) continue; ScopedVector<char> script(2048); SNPrintF(script, "function %s(p1, p2) { %s };\n%s({});", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } SHARD_TEST_BY_2(BytecodeGraphBuilderKeyedStore) TEST(BytecodeGraphBuilderPropertyCall) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<1> snippets[] = { {"return p1.func();", {factory->NewNumberFromInt(25), BytecodeGraphTester::NewObject("({func() { return 25; }})")}}, {"return p1.func('abc');", {factory->NewStringFromStaticChars("abc"), BytecodeGraphTester::NewObject("({func(a) { return a; }})")}}, {"return p1.func(1, 2, 3, 4, 5, 6, 7, 8);", {factory->NewNumberFromInt(36), BytecodeGraphTester::NewObject( "({func(a, b, c, d, e, f, g, h) {\n" " return a + b + c + d + e + f + g + h;}})")}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(2048); SNPrintF(script, "function %s(p1) { %s };\n%s({func() {}});", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderCallNew) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"function counter() { this.count = 20; }\n" "function f() {\n" " var c = new counter();\n" " return c.count;\n" "}; f()", {factory->NewNumberFromInt(20)}}, {"function counter(arg0) { this.count = 17; this.x = arg0; }\n" "function f() {\n" " var c = new counter(6);\n" " return c.count + c.x;\n" "}; f()", {factory->NewNumberFromInt(23)}}, {"function counter(arg0, arg1) {\n" " this.count = 17; this.x = arg0; this.y = arg1;\n" "}\n" "function f() {\n" " var c = new counter(3, 5);\n" " return c.count + c.x + c.y;\n" "}; f()", {factory->NewNumberFromInt(25)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { BytecodeGraphTester tester(isolate, snippets[i].code_snippet); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderCreateClosure) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"function f() {\n" " function counter() { this.count = 20; }\n" " var c = new counter();\n" " return c.count;\n" "}; f()", {factory->NewNumberFromInt(20)}}, {"function f() {\n" " function counter(arg0) { this.count = 17; this.x = arg0; }\n" " var c = new counter(6);\n" " return c.count + c.x;\n" "}; f()", {factory->NewNumberFromInt(23)}}, {"function f() {\n" " function counter(arg0, arg1) {\n" " this.count = 17; this.x = arg0; this.y = arg1;\n" " }\n" " var c = new counter(3, 5);\n" " return c.count + c.x + c.y;\n" "}; f()", {factory->NewNumberFromInt(25)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { BytecodeGraphTester tester(isolate, snippets[i].code_snippet); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderCallRuntime) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<1> snippets[] = { {"function f(arg0) { return %MaxSmi(); }\nf()", {factory->NewNumberFromInt(Smi::kMaxValue), factory->undefined_value()}}, {"function f(arg0) { return %IsArray(arg0) }\nf(undefined)", {factory->true_value(), BytecodeGraphTester::NewObject("[1, 2, 3]")}}, {"function f(arg0) { return %Add(arg0, 2) }\nf(1)", {factory->NewNumberFromInt(5), factory->NewNumberFromInt(3)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { BytecodeGraphTester tester(isolate, snippets[i].code_snippet); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderInvokeIntrinsic) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<1> snippets[] = { {"function f(arg0) { return %_IsJSReceiver(arg0); }\nf()", {factory->false_value(), factory->NewNumberFromInt(1)}}, {"function f(arg0) { return %_IsArray(arg0) }\nf(undefined)", {factory->true_value(), BytecodeGraphTester::NewObject("[1, 2, 3]")}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { BytecodeGraphTester tester(isolate, snippets[i].code_snippet); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } void TestBytecodeGraphBuilderGlobals(size_t shard) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"var global = 321;\n function f() { return global; };\n f();", {factory->NewNumberFromInt(321)}}, {"var global = 321;\n" "function f() { global = 123; return global };\n f();", {factory->NewNumberFromInt(123)}}, {"var global = function() { return 'abc'};\n" "function f() { return global(); };\n f();", {factory->NewStringFromStaticChars("abc")}}, {"var global = 456;\n" "function f() { 'use strict'; return global; };\n f();", {factory->NewNumberFromInt(456)}}, {"var global = 987;\n" "function f() { 'use strict'; global = 789; return global };\n f();", {factory->NewNumberFromInt(789)}}, {"var global = function() { return 'xyz'};\n" "function f() { 'use strict'; return global(); };\n f();", {factory->NewStringFromStaticChars("xyz")}}, {"var global = 'abc'; var global_obj = {val:123};\n" "function f() {\n" REPEAT_127( SPACE, " var b = global_obj.name;\n") "return global; };\n f();\n", {factory->NewStringFromStaticChars("abc")}}, {"var global = 'abc'; var global_obj = {val:123};\n" "function f() { 'use strict';\n" REPEAT_127( SPACE, " var b = global_obj.name;\n") "global = 'xyz'; return " "global };\n f();\n", {factory->NewStringFromStaticChars("xyz")}}, {"function f() { return typeof(undeclared_var); }\n; f();\n", {factory->NewStringFromStaticChars("undefined")}}, {"var defined_var = 10; function f() { return typeof(defined_var); }\n; " "f();\n", {factory->NewStringFromStaticChars("number")}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { if ((i % 2) != shard) continue; BytecodeGraphTester tester(isolate, snippets[i].code_snippet); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } SHARD_TEST_BY_2(BytecodeGraphBuilderGlobals) TEST(BytecodeGraphBuilderToObject) { // TODO(mythria): tests for ToObject. Needs ForIn. } TEST(BytecodeGraphBuilderToName) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"var a = 'val'; var obj = {[a] : 10}; return obj.val;", {factory->NewNumberFromInt(10)}}, {"var a = 20; var obj = {[a] : 10}; return obj['20'];", {factory->NewNumberFromInt(10)}}, {"var a = 20; var obj = {[a] : 10}; return obj[20];", {factory->NewNumberFromInt(10)}}, {"var a = {val:23}; var obj = {[a] : 10}; return obj[a];", {factory->NewNumberFromInt(10)}}, {"var a = {val:23}; var obj = {[a] : 10}; return obj['[object Object]'];", {factory->NewNumberFromInt(10)}}, {"var a = {toString : function() { return 'x'}};\n" "var obj = {[a] : 10};\n" "return obj.x;", {factory->NewNumberFromInt(10)}}, {"var a = {valueOf : function() { return 'x'}};\n" "var obj = {[a] : 10};\n" "return obj.x;", {factory->undefined_value()}}, {"var a = {[Symbol.toPrimitive] : function() { return 'x'}};\n" "var obj = {[a] : 10};\n" "return obj.x;", {factory->NewNumberFromInt(10)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s({});", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderLogicalNot) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<1> snippets[] = { {"return !p1;", {factory->false_value(), BytecodeGraphTester::NewObject("({val : 10})")}}, {"return !p1;", {factory->true_value(), factory->NewNumberFromInt(0)}}, {"return !p1;", {factory->true_value(), factory->undefined_value()}}, {"return !p1;", {factory->false_value(), factory->NewNumberFromInt(10)}}, {"return !p1;", {factory->false_value(), factory->true_value()}}, {"return !p1;", {factory->false_value(), factory->NewStringFromStaticChars("abc")}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s(p1) { %s }\n%s({});", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderTypeOf) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<1> snippets[] = { {"return typeof p1;", {factory->NewStringFromStaticChars("object"), BytecodeGraphTester::NewObject("({val : 10})")}}, {"return typeof p1;", {factory->NewStringFromStaticChars("undefined"), factory->undefined_value()}}, {"return typeof p1;", {factory->NewStringFromStaticChars("number"), factory->NewNumberFromInt(10)}}, {"return typeof p1;", {factory->NewStringFromStaticChars("boolean"), factory->true_value()}}, {"return typeof p1;", {factory->NewStringFromStaticChars("string"), factory->NewStringFromStaticChars("abc")}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s(p1) { %s }\n%s({});", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderCompareTypeOf) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<1> snippets[] = { {"return typeof p1 === 'number';", {factory->true_value(), factory->NewNumber(1.1)}}, {"return typeof p1 === 'string';", {factory->false_value(), factory->NewNumber(1.1)}}, {"return typeof p1 === 'string';", {factory->true_value(), factory->NewStringFromStaticChars("string")}}, {"return typeof p1 === 'string';", {factory->false_value(), factory->undefined_value()}}, {"return typeof p1 === 'undefined';", {factory->true_value(), factory->undefined_value()}}, {"return typeof p1 === 'object';", {factory->true_value(), factory->null_value()}}, {"return typeof p1 === 'object';", {factory->true_value(), BytecodeGraphTester::NewObject("({val : 10})")}}, {"return typeof p1 === 'function';", {factory->false_value(), BytecodeGraphTester::NewObject("({val : 10})")}}, {"return typeof p1 === 'symbol';", {factory->true_value(), factory->NewSymbol()}}, {"return typeof p1 === 'symbol';", {factory->false_value(), factory->NewStringFromStaticChars("string")}}, {"return typeof p1 === 'other';", {factory->false_value(), factory->NewNumber(1.1)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s(p1) { %s }\n%s({});", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderCountOperation) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<1> snippets[] = { {"return ++p1;", {factory->NewNumberFromInt(11), factory->NewNumberFromInt(10)}}, {"return p1++;", {factory->NewNumberFromInt(10), factory->NewNumberFromInt(10)}}, {"return p1++ + 10;", {factory->NewHeapNumber(15.23), factory->NewHeapNumber(5.23)}}, {"return 20 + ++p1;", {factory->NewHeapNumber(27.23), factory->NewHeapNumber(6.23)}}, {"return --p1;", {factory->NewHeapNumber(9.8), factory->NewHeapNumber(10.8)}}, {"return p1--;", {factory->NewHeapNumber(10.8), factory->NewHeapNumber(10.8)}}, {"return p1-- + 10;", {factory->NewNumberFromInt(20), factory->NewNumberFromInt(10)}}, {"return 20 + --p1;", {factory->NewNumberFromInt(29), factory->NewNumberFromInt(10)}}, {"return p1.val--;", {factory->NewNumberFromInt(10), BytecodeGraphTester::NewObject("({val : 10})")}}, {"return ++p1['val'];", {factory->NewNumberFromInt(11), BytecodeGraphTester::NewObject("({val : 10})")}}, {"return ++p1[1];", {factory->NewNumberFromInt(11), BytecodeGraphTester::NewObject("({1 : 10})")}}, {" function inner() { return p1 } return --p1;", {factory->NewNumberFromInt(9), factory->NewNumberFromInt(10)}}, {" function inner() { return p1 } return p1--;", {factory->NewNumberFromInt(10), factory->NewNumberFromInt(10)}}, {"return ++p1;", {factory->nan_value(), factory->NewStringFromStaticChars("String")}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s(p1) { %s }\n%s({});", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderDelete) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<1> snippets[] = { {"return delete p1.val;", {factory->true_value(), BytecodeGraphTester::NewObject("({val : 10})")}}, {"delete p1.val; return p1.val;", {factory->undefined_value(), BytecodeGraphTester::NewObject("({val : 10})")}}, {"delete p1.name; return p1.val;", {factory->NewNumberFromInt(10), BytecodeGraphTester::NewObject("({val : 10, name:'abc'})")}}, {"'use strict'; return delete p1.val;", {factory->true_value(), BytecodeGraphTester::NewObject("({val : 10})")}}, {"'use strict'; delete p1.val; return p1.val;", {factory->undefined_value(), BytecodeGraphTester::NewObject("({val : 10})")}}, {"'use strict'; delete p1.name; return p1.val;", {factory->NewNumberFromInt(10), BytecodeGraphTester::NewObject("({val : 10, name:'abc'})")}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s(p1) { %s }\n%s({});", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderDeleteGlobal) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"var obj = {val : 10, type : 'int'};" "function f() {return delete obj;};", {factory->false_value()}}, {"function f() {return delete this;};", {factory->true_value()}}, {"var obj = {val : 10, type : 'int'};" "function f() {return delete obj.val;};", {factory->true_value()}}, {"var obj = {val : 10, type : 'int'};" "function f() {'use strict'; return delete obj.val;};", {factory->true_value()}}, {"var obj = {val : 10, type : 'int'};" "function f() {delete obj.val; return obj.val;};", {factory->undefined_value()}}, {"var obj = {val : 10, type : 'int'};" "function f() {'use strict'; delete obj.val; return obj.val;};", {factory->undefined_value()}}, {"var obj = {1 : 10, 2 : 20};" "function f() { return delete obj[1]; };", {factory->true_value()}}, {"var obj = {1 : 10, 2 : 20};" "function f() { 'use strict'; return delete obj[1];};", {factory->true_value()}}, {"obj = {1 : 10, 2 : 20};" "function f() { delete obj[1]; return obj[2];};", {factory->NewNumberFromInt(20)}}, {"function f() {" " var obj = {1 : 10, 2 : 20};" " function inner() { return obj[1]; };" " return delete obj[1];" "}", {factory->true_value()}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "%s %s({});", snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderDeleteLookupSlot) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); // TODO(mythria): Add more tests when we have support for LdaLookupSlot. const char* function_prologue = "var f;" "var x = 1;" "y = 10;" "var obj = {val:10};" "var z = 30;" "function f1() {" " var z = 20;" " eval(\"function t() {"; const char* function_epilogue = " }; f = t; t();\");" "}" "f1();"; ExpectedSnippet<0> snippets[] = { {"return delete y;", {factory->true_value()}}, {"return delete z;", {factory->false_value()}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "%s %s %s", function_prologue, snippets[i].code_snippet, function_epilogue); BytecodeGraphTester tester(isolate, script.start(), "t"); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderLookupSlot) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); const char* function_prologue = "var f;" "var x = 12;" "y = 10;" "var obj = {val:3.1414};" "var z = 30;" "function f1() {" " var z = 20;" " eval(\"function t() {"; const char* function_epilogue = " }; f = t; t();\");" "}" "f1();"; ExpectedSnippet<0> snippets[] = { {"return x;", {factory->NewNumber(12)}}, {"return obj.val;", {factory->NewNumber(3.1414)}}, {"return typeof x;", {factory->NewStringFromStaticChars("number")}}, {"return typeof dummy;", {factory->NewStringFromStaticChars("undefined")}}, {"x = 23; return x;", {factory->NewNumber(23)}}, {"'use strict'; obj.val = 23.456; return obj.val;", {factory->NewNumber(23.456)}}}; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "%s %s %s", function_prologue, snippets[i].code_snippet, function_epilogue); BytecodeGraphTester tester(isolate, script.start(), "t"); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderLookupContextSlot) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); // Testing with eval called in the current context. const char* inner_eval_prologue = "var x = 0; function inner() {"; const char* inner_eval_epilogue = "}; return inner();"; ExpectedSnippet<0> inner_eval_snippets[] = { {"eval(''); return x;", {factory->NewNumber(0)}}, {"eval('var x = 1'); return x;", {factory->NewNumber(1)}}, {"'use strict'; eval('var x = 1'); return x;", {factory->NewNumber(0)}}}; for (size_t i = 0; i < arraysize(inner_eval_snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s(p1) { %s %s %s } ; %s() ;", kFunctionName, inner_eval_prologue, inner_eval_snippets[i].code_snippet, inner_eval_epilogue, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*inner_eval_snippets[i].return_value())); } // Testing with eval called in a parent context. const char* outer_eval_prologue = ""; const char* outer_eval_epilogue = "function inner() { return x; }; return inner();"; ExpectedSnippet<0> outer_eval_snippets[] = { {"var x = 0; eval('');", {factory->NewNumber(0)}}, {"var x = 0; eval('var x = 1');", {factory->NewNumber(1)}}, {"'use strict'; var x = 0; eval('var x = 1');", {factory->NewNumber(0)}}}; for (size_t i = 0; i < arraysize(outer_eval_snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s %s %s } ; %s() ;", kFunctionName, outer_eval_prologue, outer_eval_snippets[i].code_snippet, outer_eval_epilogue, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*outer_eval_snippets[i].return_value())); } } TEST(BytecodeGraphBuilderLookupGlobalSlot) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); // Testing with eval called in the current context. const char* inner_eval_prologue = "x = 0; function inner() {"; const char* inner_eval_epilogue = "}; return inner();"; ExpectedSnippet<0> inner_eval_snippets[] = { {"eval(''); return x;", {factory->NewNumber(0)}}, {"eval('var x = 1'); return x;", {factory->NewNumber(1)}}, {"'use strict'; eval('var x = 1'); return x;", {factory->NewNumber(0)}}}; for (size_t i = 0; i < arraysize(inner_eval_snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s(p1) { %s %s %s } ; %s() ;", kFunctionName, inner_eval_prologue, inner_eval_snippets[i].code_snippet, inner_eval_epilogue, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*inner_eval_snippets[i].return_value())); } // Testing with eval called in a parent context. const char* outer_eval_prologue = ""; const char* outer_eval_epilogue = "function inner() { return x; }; return inner();"; ExpectedSnippet<0> outer_eval_snippets[] = { {"x = 0; eval('');", {factory->NewNumber(0)}}, {"x = 0; eval('var x = 1');", {factory->NewNumber(1)}}, {"'use strict'; x = 0; eval('var x = 1');", {factory->NewNumber(0)}}}; for (size_t i = 0; i < arraysize(outer_eval_snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s %s %s } ; %s() ;", kFunctionName, outer_eval_prologue, outer_eval_snippets[i].code_snippet, outer_eval_epilogue, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*outer_eval_snippets[i].return_value())); } } TEST(BytecodeGraphBuilderLookupSlotWide) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); const char* function_prologue = "var f;" "var x = 12;" "y = 10;" "var obj = {val:3.1414};" "var z = 30;" "function f1() {" " var z = 20;" " eval(\"function t() {"; const char* function_epilogue = " }; f = t; t();\");" "}" "f1();"; ExpectedSnippet<0> snippets[] = { {"var y = 2.3;" REPEAT_256(SPACE, "y = 2.3;") "return x;", {factory->NewNumber(12)}}, {"var y = 2.3;" REPEAT_256(SPACE, "y = 2.3;") "return typeof x;", {factory->NewStringFromStaticChars("number")}}, {"var y = 2.3;" REPEAT_256(SPACE, "y = 2.3;") "return x = 23;", {factory->NewNumber(23)}}, {"'use strict';" REPEAT_256(SPACE, "y = 2.3;") "return obj.val = 23.456;", {factory->NewNumber(23.456)}}}; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(3072); SNPrintF(script, "%s %s %s", function_prologue, snippets[i].code_snippet, function_epilogue); BytecodeGraphTester tester(isolate, script.start(), "t"); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderCallLookupSlot) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); ExpectedSnippet<0> snippets[] = { {"g = function(){ return 2 }; eval(''); return g();", {handle(Smi::FromInt(2), isolate)}}, {"g = function(){ return 2 }; eval('g = function() {return 3}');\n" "return g();", {handle(Smi::FromInt(3), isolate)}}, {"g = { x: function(){ return this.y }, y: 20 };\n" "eval('g = { x: g.x, y: 30 }');\n" "return g.x();", {handle(Smi::FromInt(30), isolate)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderEval) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"return eval('1;');", {handle(Smi::FromInt(1), isolate)}}, {"return eval('100 * 20;');", {handle(Smi::FromInt(2000), isolate)}}, {"var x = 10; return eval('x + 20;');", {handle(Smi::FromInt(30), isolate)}}, {"var x = 10; eval('x = 33;'); return x;", {handle(Smi::FromInt(33), isolate)}}, {"'use strict'; var x = 20; var z = 0;\n" "eval('var x = 33; z = x;'); return x + z;", {handle(Smi::FromInt(53), isolate)}}, {"eval('var x = 33;'); eval('var y = x + 20'); return x + y;", {handle(Smi::FromInt(86), isolate)}}, {"var x = 1; eval('for(i = 0; i < 10; i++) x = x + 1;'); return x", {handle(Smi::FromInt(11), isolate)}}, {"var x = 10; eval('var x = 20;'); return x;", {handle(Smi::FromInt(20), isolate)}}, {"var x = 1; eval('\"use strict\"; var x = 2;'); return x;", {handle(Smi::FromInt(1), isolate)}}, {"'use strict'; var x = 1; eval('var x = 2;'); return x;", {handle(Smi::FromInt(1), isolate)}}, {"var x = 10; eval('x + 20;'); return typeof x;", {factory->NewStringFromStaticChars("number")}}, {"eval('var y = 10;'); return typeof unallocated;", {factory->NewStringFromStaticChars("undefined")}}, {"'use strict'; eval('var y = 10;'); return typeof unallocated;", {factory->NewStringFromStaticChars("undefined")}}, {"eval('var x = 10;'); return typeof x;", {factory->NewStringFromStaticChars("number")}}, {"var x = {}; eval('var x = 10;'); return typeof x;", {factory->NewStringFromStaticChars("number")}}, {"'use strict'; var x = {}; eval('var x = 10;'); return typeof x;", {factory->NewStringFromStaticChars("object")}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderEvalParams) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); ExpectedSnippet<1> snippets[] = { {"var x = 10; return eval('x + p1;');", {handle(Smi::FromInt(30), isolate), handle(Smi::FromInt(20), isolate)}}, {"var x = 10; eval('p1 = x;'); return p1;", {handle(Smi::FromInt(10), isolate), handle(Smi::FromInt(20), isolate)}}, {"var a = 10;" "function inner() { return eval('a + p1;');}" "return inner();", {handle(Smi::FromInt(30), isolate), handle(Smi::FromInt(20), isolate)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s(p1) { %s }\n%s(0);", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderEvalGlobal) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"function add_global() { eval('function f() { z = 33; }; f()'); };" "function f() { add_global(); return z; }; f();", {handle(Smi::FromInt(33), isolate)}}, {"function add_global() {\n" " eval('\"use strict\"; function f() { y = 33; };" " try { f() } catch(e) {}');\n" "}\n" "function f() { add_global(); return typeof y; } f();", {factory->NewStringFromStaticChars("undefined")}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { BytecodeGraphTester tester(isolate, snippets[i].code_snippet); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } bool get_compare_result(Token::Value opcode, Handle<Object> lhs_value, Handle<Object> rhs_value) { switch (opcode) { case Token::Value::EQ: return Object::Equals(lhs_value, rhs_value).FromJust(); case Token::Value::NE: return !Object::Equals(lhs_value, rhs_value).FromJust(); case Token::Value::EQ_STRICT: return lhs_value->StrictEquals(*rhs_value); case Token::Value::NE_STRICT: return !lhs_value->StrictEquals(*rhs_value); case Token::Value::LT: return Object::LessThan(lhs_value, rhs_value).FromJust(); case Token::Value::LTE: return Object::LessThanOrEqual(lhs_value, rhs_value).FromJust(); case Token::Value::GT: return Object::GreaterThan(lhs_value, rhs_value).FromJust(); case Token::Value::GTE: return Object::GreaterThanOrEqual(lhs_value, rhs_value).FromJust(); default: UNREACHABLE(); } } const char* get_code_snippet(Token::Value opcode) { switch (opcode) { case Token::Value::EQ: return "return p1 == p2;"; case Token::Value::NE: return "return p1 != p2;"; case Token::Value::EQ_STRICT: return "return p1 === p2;"; case Token::Value::NE_STRICT: return "return p1 !== p2;"; case Token::Value::LT: return "return p1 < p2;"; case Token::Value::LTE: return "return p1 <= p2;"; case Token::Value::GT: return "return p1 > p2;"; case Token::Value::GTE: return "return p1 >= p2;"; default: UNREACHABLE(); } } TEST(BytecodeGraphBuilderCompare) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); Handle<Object> lhs_values[] = { factory->NewNumberFromInt(10), factory->NewHeapNumber(3.45), factory->NewStringFromStaticChars("abc"), factory->NewNumberFromInt(SMI_MAX), factory->NewNumberFromInt(SMI_MIN)}; Handle<Object> rhs_values[] = {factory->NewNumberFromInt(10), factory->NewStringFromStaticChars("10"), factory->NewNumberFromInt(20), factory->NewStringFromStaticChars("abc"), factory->NewHeapNumber(3.45), factory->NewNumberFromInt(SMI_MAX), factory->NewNumberFromInt(SMI_MIN)}; for (size_t i = 0; i < arraysize(kCompareOperators); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s(p1, p2) { %s }\n%s({}, {});", kFunctionName, get_code_snippet(kCompareOperators[i]), kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>, Handle<Object>>(); for (size_t j = 0; j < arraysize(lhs_values); j++) { for (size_t k = 0; k < arraysize(rhs_values); k++) { Handle<Object> return_value = callable(lhs_values[j], rhs_values[k]).ToHandleChecked(); bool result = get_compare_result(kCompareOperators[i], lhs_values[j], rhs_values[k]); CHECK(return_value->SameValue(*factory->ToBoolean(result))); } } } } TEST(BytecodeGraphBuilderTestIn) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<2> snippets[] = { {"return p2 in p1;", {factory->true_value(), BytecodeGraphTester::NewObject("({val : 10})"), factory->NewStringFromStaticChars("val")}}, {"return p2 in p1;", {factory->true_value(), BytecodeGraphTester::NewObject("[]"), factory->NewStringFromStaticChars("length")}}, {"return p2 in p1;", {factory->true_value(), BytecodeGraphTester::NewObject("[]"), factory->NewStringFromStaticChars("toString")}}, {"return p2 in p1;", {factory->true_value(), BytecodeGraphTester::NewObject("({val : 10})"), factory->NewStringFromStaticChars("toString")}}, {"return p2 in p1;", {factory->false_value(), BytecodeGraphTester::NewObject("({val : 10})"), factory->NewStringFromStaticChars("abc")}}, {"return p2 in p1;", {factory->false_value(), BytecodeGraphTester::NewObject("({val : 10})"), factory->NewNumberFromInt(10)}}, {"return p2 in p1;", {factory->true_value(), BytecodeGraphTester::NewObject("({10 : 'val'})"), factory->NewNumberFromInt(10)}}, {"return p2 in p1;", {factory->false_value(), BytecodeGraphTester::NewObject("({10 : 'val'})"), factory->NewNumberFromInt(1)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s(p1, p2) { %s }\n%s({}, {});", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>, Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0), snippets[i].parameter(1)) .ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderTestInstanceOf) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<1> snippets[] = { {"return p1 instanceof Object;", {factory->true_value(), BytecodeGraphTester::NewObject("({val : 10})")}}, {"return p1 instanceof String;", {factory->false_value(), factory->NewStringFromStaticChars("string")}}, {"var cons = function() {};" "var obj = new cons();" "return obj instanceof cons;", {factory->true_value(), factory->undefined_value()}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s(p1) { %s }\n%s({});", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderTryCatch) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); ExpectedSnippet<0> snippets[] = { {"var a = 1; try { a = 2 } catch(e) { a = 3 }; return a;", {handle(Smi::FromInt(2), isolate)}}, {"var a; try { undef.x } catch(e) { a = 2 }; return a;", {handle(Smi::FromInt(2), isolate)}}, {"var a; try { throw 1 } catch(e) { a = e + 2 }; return a;", {handle(Smi::FromInt(3), isolate)}}, {"var a; try { throw 1 } catch(e) { a = e + 2 };" " try { throw a } catch(e) { a = e + 3 }; return a;", {handle(Smi::FromInt(6), isolate)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderTryFinally1) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); ExpectedSnippet<0> snippets[] = { {"var a = 1; try { a = a + 1; } finally { a = a + 2; }; return a;", {handle(Smi::FromInt(4), isolate)}}, {"var a = 1; try { a = 2; return 23; } finally { a = 3 }; return a;", {handle(Smi::FromInt(23), isolate)}}, {"var a = 1; try { a = 2; throw 23; } finally { return a; };", {handle(Smi::FromInt(2), isolate)}}, {"var a = 1; for (var i = 10; i < 20; i += 5) {" " try { a = 2; break; } finally { a = 3; }" "} return a + i;", {handle(Smi::FromInt(13), isolate)}}, {"var a = 1; for (var i = 10; i < 20; i += 5) {" " try { a = 2; continue; } finally { a = 3; }" "} return a + i;", {handle(Smi::FromInt(23), isolate)}}, {"var a = 1; try { a = 2;" " try { a = 3; throw 23; } finally { a = 4; }" "} catch(e) { a = a + e; } return a;", {handle(Smi::FromInt(27), isolate)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderTryFinally2) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); ExpectedSnippet<0, const char*> snippets[] = { {"var a = 1; try { a = 2; throw 23; } finally { a = 3 }; return a;", {"Uncaught 23"}}, {"var a = 1; try { a = 2; throw 23; } finally { throw 42; };", {"Uncaught 42"}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); v8::Local<v8::String> message = tester.CheckThrowsReturnMessage()->Get(); v8::Local<v8::String> expected_string = v8_str(snippets[i].return_value()); CHECK( message->Equals(CcTest::isolate()->GetCurrentContext(), expected_string) .FromJust()); } } TEST(BytecodeGraphBuilderThrow) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); // TODO(mythria): Add more tests when real try-catch and deoptimization // information are supported. ExpectedSnippet<0, const char*> snippets[] = { {"throw undefined;", {"Uncaught undefined"}}, {"throw 1;", {"Uncaught 1"}}, {"throw 'Error';", {"Uncaught Error"}}, {"throw 'Error1'; throw 'Error2'", {"Uncaught Error1"}}, {"var a = true; if (a) { throw 'Error'; }", {"Uncaught Error"}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); v8::Local<v8::String> message = tester.CheckThrowsReturnMessage()->Get(); v8::Local<v8::String> expected_string = v8_str(snippets[i].return_value()); CHECK( message->Equals(CcTest::isolate()->GetCurrentContext(), expected_string) .FromJust()); } } TEST(BytecodeGraphBuilderContext) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"var x = 'outer';" "function f() {" " 'use strict';" " {" " let x = 'inner';" " (function() {x});" " }" "return(x);" "}" "f();", {factory->NewStringFromStaticChars("outer")}}, {"var x = 'outer';" "function f() {" " 'use strict';" " {" " let x = 'inner ';" " var innerFunc = function() {return x};" " }" "return(innerFunc() + x);" "}" "f();", {factory->NewStringFromStaticChars("inner outer")}}, {"var x = 'outer';" "function f() {" " 'use strict';" " {" " let x = 'inner ';" " var innerFunc = function() {return x;};" " {" " let x = 'innermost ';" " var innerMostFunc = function() {return x + innerFunc();};" " }" " x = 'inner_changed ';" " }" " return(innerMostFunc() + x);" "}" "f();", {factory->NewStringFromStaticChars("innermost inner_changed outer")}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "%s", snippets[i].code_snippet); BytecodeGraphTester tester(isolate, script.start(), "f"); auto callable = tester.GetCallable<>("f"); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderLoadContext) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<1> snippets[] = { {"function Outer() {" " var outerVar = 2;" " function Inner(innerArg) {" " this.innerFunc = function () {" " return outerVar * innerArg;" " };" " };" " this.getInnerFunc = function GetInner() {" " return new Inner(3).innerFunc;" " }" "}" "var f = new Outer().getInnerFunc();" "f();", {factory->NewNumberFromInt(6), factory->undefined_value()}}, {"function Outer() {" " var outerVar = 2;" " function Inner(innerArg) {" " this.innerFunc = function () {" " outerVar = innerArg; return outerVar;" " };" " };" " this.getInnerFunc = function GetInner() {" " return new Inner(10).innerFunc;" " }" "}" "var f = new Outer().getInnerFunc();" "f();", {factory->NewNumberFromInt(10), factory->undefined_value()}}, {"function testOuter(outerArg) {" " this.testinnerFunc = function testInner(innerArg) {" " return innerArg + outerArg;" " }" "}" "var f = new testOuter(10).testinnerFunc;" "f(0);", {factory->NewNumberFromInt(14), factory->NewNumberFromInt(4)}}, {"function testOuter(outerArg) {" " var outerVar = outerArg * 2;" " this.testinnerFunc = function testInner(innerArg) {" " outerVar = outerVar + innerArg; return outerVar;" " }" "}" "var f = new testOuter(10).testinnerFunc;" "f(0);", {factory->NewNumberFromInt(24), factory->NewNumberFromInt(4)}}}; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "%s", snippets[i].code_snippet); BytecodeGraphTester tester(isolate, script.start(), "*"); auto callable = tester.GetCallable<Handle<Object>>("f"); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderCreateArgumentsNoParameters) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"function f() {return arguments[0];}", {factory->undefined_value()}}, {"function f(a) {return arguments[0];}", {factory->undefined_value()}}, {"function f() {'use strict'; return arguments[0];}", {factory->undefined_value()}}, {"function f(a) {'use strict'; return arguments[0];}", {factory->undefined_value()}}, {"function f(...restArgs) {return restArgs[0];}", {factory->undefined_value()}}, {"function f(a, ...restArgs) {return restArgs[0];}", {factory->undefined_value()}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "%s\n%s();", snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderCreateArguments) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<3> snippets[] = { {"function f(a, b, c) {return arguments[0];}", {factory->NewNumberFromInt(1), factory->NewNumberFromInt(1), factory->NewNumberFromInt(2), factory->NewNumberFromInt(3)}}, {"function f(a, b, c) {return arguments[3];}", {factory->undefined_value(), factory->NewNumberFromInt(1), factory->NewNumberFromInt(2), factory->NewNumberFromInt(3)}}, {"function f(a, b, c) { b = c; return arguments[1];}", {factory->NewNumberFromInt(3), factory->NewNumberFromInt(1), factory->NewNumberFromInt(2), factory->NewNumberFromInt(3)}}, {"function f(a, b, c) {'use strict'; return arguments[0];}", {factory->NewNumberFromInt(1), factory->NewNumberFromInt(1), factory->NewNumberFromInt(2), factory->NewNumberFromInt(3)}}, {"function f(a, b, c) {'use strict'; return arguments[3];}", {factory->undefined_value(), factory->NewNumberFromInt(1), factory->NewNumberFromInt(2), factory->NewNumberFromInt(3)}}, {"function f(a, b, c) {'use strict'; b = c; return arguments[1];}", {factory->NewNumberFromInt(2), factory->NewNumberFromInt(1), factory->NewNumberFromInt(2), factory->NewNumberFromInt(3)}}, {"function inline_func(a, b) { return arguments[0] }" "function f(a, b, c) {return inline_func(b, c) + arguments[0];}", {factory->NewNumberFromInt(3), factory->NewNumberFromInt(1), factory->NewNumberFromInt(2), factory->NewNumberFromInt(30)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "%s\n%s();", snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>, Handle<Object>, Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0), snippets[i].parameter(1), snippets[i].parameter(2)) .ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderCreateRestArguments) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<3> snippets[] = { {"function f(...restArgs) {return restArgs[0];}", {factory->NewNumberFromInt(1), factory->NewNumberFromInt(1), factory->NewNumberFromInt(2), factory->NewNumberFromInt(3)}}, {"function f(a, b, ...restArgs) {return restArgs[0];}", {factory->NewNumberFromInt(3), factory->NewNumberFromInt(1), factory->NewNumberFromInt(2), factory->NewNumberFromInt(3)}}, {"function f(a, b, ...restArgs) {return arguments[2];}", {factory->NewNumberFromInt(3), factory->NewNumberFromInt(1), factory->NewNumberFromInt(2), factory->NewNumberFromInt(3)}}, {"function f(a, ...restArgs) { return restArgs[2];}", {factory->undefined_value(), factory->NewNumberFromInt(1), factory->NewNumberFromInt(2), factory->NewNumberFromInt(3)}}, {"function f(a, ...restArgs) { return arguments[0] + restArgs[1];}", {factory->NewNumberFromInt(4), factory->NewNumberFromInt(1), factory->NewNumberFromInt(2), factory->NewNumberFromInt(3)}}, {"function inline_func(a, ...restArgs) { return restArgs[0] }" "function f(a, b, c) {return inline_func(b, c) + arguments[0];}", {factory->NewNumberFromInt(31), factory->NewNumberFromInt(1), factory->NewNumberFromInt(2), factory->NewNumberFromInt(30)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "%s\n%s();", snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>, Handle<Object>, Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0), snippets[i].parameter(1), snippets[i].parameter(2)) .ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderRegExpLiterals) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"return /abd/.exec('cccabbdd');", {factory->null_value()}}, {"return /ab+d/.exec('cccabbdd')[0];", {factory->NewStringFromStaticChars("abbd")}}, {"var a = 3.1414;" REPEAT_256(SPACE, "a = 3.1414;") "return /ab+d/.exec('cccabbdd')[0];", {factory->NewStringFromStaticChars("abbd")}}, {"return /ab+d/.exec('cccabbdd')[1];", {factory->undefined_value()}}, {"return /AbC/i.exec('ssaBC')[0];", {factory->NewStringFromStaticChars("aBC")}}, {"return 'ssaBC'.match(/AbC/i)[0];", {factory->NewStringFromStaticChars("aBC")}}, {"return 'ssaBCtAbC'.match(/(AbC)/gi)[1];", {factory->NewStringFromStaticChars("AbC")}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(4096); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderArrayLiterals) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"return [][0];", {factory->undefined_value()}}, {"return [1, 3, 2][1];", {factory->NewNumberFromInt(3)}}, {"var a;" REPEAT_256(SPACE, "a = 9.87;") "return [1, 3, 2][1];", {factory->NewNumberFromInt(3)}}, {"return ['a', 'b', 'c'][2];", {factory->NewStringFromStaticChars("c")}}, {"var a = 100; return [a, a++, a + 2, a + 3][2];", {factory->NewNumberFromInt(103)}}, {"var a = 100; return [a, ++a, a + 2, a + 3][1];", {factory->NewNumberFromInt(101)}}, {"var a = 9.2;" REPEAT_256(SPACE, "a = 9.34;") "return [a, ++a, a + 2, a + 3][2];", {factory->NewHeapNumber(12.34)}}, {"return [[1, 2, 3], ['a', 'b', 'c']][1][0];", {factory->NewStringFromStaticChars("a")}}, {"var t = 't'; return [[t, t + 'est'], [1 + t]][0][1];", {factory->NewStringFromStaticChars("test")}}, {"var t = 't'; return [[t, t + 'est'], [1 + t]][1][0];", {factory->NewStringFromStaticChars("1t")}}}; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(4096); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderObjectLiterals) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"return { }.name;", {factory->undefined_value()}}, {"return { name: 'string', val: 9.2 }.name;", {factory->NewStringFromStaticChars("string")}}, {"var a;\n" REPEAT_256(SPACE, "a = 1.23;\n") "return { name: 'string', val: 9.2 }.name;", {factory->NewStringFromStaticChars("string")}}, {"return { name: 'string', val: 9.2 }['name'];", {factory->NewStringFromStaticChars("string")}}, {"var a = 15; return { name: 'string', val: a }.val;", {factory->NewNumberFromInt(15)}}, {"var a;" REPEAT_256(SPACE, "a = 1.23;") "return { name: 'string', val: a }.val;", {factory->NewHeapNumber(1.23)}}, {"var a = 15; var b = 'val'; return { name: 'string', val: a }[b];", {factory->NewNumberFromInt(15)}}, {"var a = 5; return { val: a, val: a + 1 }.val;", {factory->NewNumberFromInt(6)}}, {"return { func: function() { return 'test' } }.func();", {factory->NewStringFromStaticChars("test")}}, {"return { func(a) { return a + 'st'; } }.func('te');", {factory->NewStringFromStaticChars("test")}}, {"return { get a() { return 22; } }.a;", {factory->NewNumberFromInt(22)}}, {"var a = { get b() { return this.x + 't'; },\n" " set b(val) { this.x = val + 's' } };\n" "a.b = 'te';\n" "return a.b;", {factory->NewStringFromStaticChars("test")}}, {"var a = 123; return { 1: a }[1];", {factory->NewNumberFromInt(123)}}, {"return Object.getPrototypeOf({ __proto__: null });", {factory->null_value()}}, {"var a = 'test'; return { [a]: 1 }.test;", {factory->NewNumberFromInt(1)}}, {"var a = 'test'; return { b: a, [a]: a + 'ing' }['test']", {factory->NewStringFromStaticChars("testing")}}, {"var a = 'proto_str';\n" "var b = { [a]: 1, __proto__: { var : a } };\n" "return Object.getPrototypeOf(b).var", {factory->NewStringFromStaticChars("proto_str")}}, {"var n = 'name';\n" "return { [n]: 'val', get a() { return 987 } }['a'];", {factory->NewNumberFromInt(987)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(4096); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderIf) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<1> snippets[] = { {"if (p1 > 1) return 1;\n" "return -1;", {factory->NewNumberFromInt(1), factory->NewNumberFromInt(2)}}, {"if (p1 > 1) return 1;\n" "return -1;", {factory->NewNumberFromInt(-1), factory->NewNumberFromInt(1)}}, {"if (p1 > 1) { return 1; } else { return -1; }", {factory->NewNumberFromInt(1), factory->NewNumberFromInt(2)}}, {"if (p1 > 1) { return 1; } else { return -1; }", {factory->NewNumberFromInt(-1), factory->NewNumberFromInt(1)}}, {"if (p1 > 50) {\n" " return 1;\n" "} else if (p1 < 10) {\n" " return 10;\n" "} else {\n" " return -10;\n" "}", {factory->NewNumberFromInt(1), factory->NewNumberFromInt(51)}}, {"if (p1 > 50) {\n" " return 1;\n" "} else if (p1 < 10) {\n" " return 10;\n" "} else {\n" " return 100;\n" "}", {factory->NewNumberFromInt(10), factory->NewNumberFromInt(9)}}, {"if (p1 > 50) {\n" " return 1;\n" "} else if (p1 < 10) {\n" " return 10;\n" "} else {\n" " return 100;\n" "}", {factory->NewNumberFromInt(100), factory->NewNumberFromInt(10)}}, {"if (p1 >= 0) {\n" " if (p1 > 10) { return 2; } else { return 1; }\n" "} else {\n" " if (p1 < -10) { return -2; } else { return -1; }\n" "}", {factory->NewNumberFromInt(2), factory->NewNumberFromInt(100)}}, {"if (p1 >= 0) {\n" " if (p1 > 10) { return 2; } else { return 1; }\n" "} else {\n" " if (p1 < -10) { return -2; } else { return -1; }\n" "}", {factory->NewNumberFromInt(1), factory->NewNumberFromInt(10)}}, {"if (p1 >= 0) {\n" " if (p1 > 10) { return 2; } else { return 1; }\n" "} else {\n" " if (p1 < -10) { return -2; } else { return -1; }\n" "}", {factory->NewNumberFromInt(-2), factory->NewNumberFromInt(-11)}}, {"if (p1 >= 0) {\n" " if (p1 > 10) { return 2; } else { return 1; }\n" "} else {\n" " if (p1 < -10) { return -2; } else { return -1; }\n" "}", {factory->NewNumberFromInt(-1), factory->NewNumberFromInt(-10)}}, {"var b = 20, c;" "if (p1 >= 0) {\n" " if (b > 0) { c = 2; } else { c = 3; }\n" "} else {\n" " if (b < -10) { c = -2; } else { c = -1; }\n" "}" "return c;", {factory->NewNumberFromInt(-1), factory->NewNumberFromInt(-1)}}, {"var b = 20, c = 10;" "if (p1 >= 0) {\n" " if (b < 0) { c = 2; }\n" "} else {\n" " if (b < -10) { c = -2; } else { c = -1; }\n" "}" "return c;", {factory->NewNumberFromInt(10), factory->NewNumberFromInt(1)}}, {"var x = 2, a = 10, b = 20, c, d;" "x = 0;" "if (a) {\n" " b = x;" " if (b > 0) { c = 2; } else { c = 3; }\n" " x = 4; d = 2;" "} else {\n" " d = 3;\n" "}" "x = d;" "function f1() {x}" "return x + c;", {factory->NewNumberFromInt(5), factory->NewNumberFromInt(-1)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(2048); SNPrintF(script, "function %s(p1) { %s };\n%s(0);", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderConditionalOperator) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<1> snippets[] = { {"return (p1 > 1) ? 1 : -1;", {factory->NewNumberFromInt(1), factory->NewNumberFromInt(2)}}, {"return (p1 > 1) ? 1 : -1;", {factory->NewNumberFromInt(-1), factory->NewNumberFromInt(0)}}, {"return (p1 > 50) ? 1 : ((p1 < 10) ? 10 : -10);", {factory->NewNumberFromInt(10), factory->NewNumberFromInt(2)}}, {"return (p1 > 50) ? 1 : ((p1 < 10) ? 10 : -10);", {factory->NewNumberFromInt(-10), factory->NewNumberFromInt(20)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(2048); SNPrintF(script, "function %s(p1) { %s };\n%s(0);", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderSwitch) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); const char* switch_code = "switch (p1) {\n" " case 1: return 0;\n" " case 2: return 1;\n" " case 3:\n" " case 4: return 2;\n" " case 9: break;\n" " default: return 3;\n" "}\n" "return 9;"; ExpectedSnippet<1> snippets[] = { {switch_code, {factory->NewNumberFromInt(0), factory->NewNumberFromInt(1)}}, {switch_code, {factory->NewNumberFromInt(1), factory->NewNumberFromInt(2)}}, {switch_code, {factory->NewNumberFromInt(2), factory->NewNumberFromInt(3)}}, {switch_code, {factory->NewNumberFromInt(2), factory->NewNumberFromInt(4)}}, {switch_code, {factory->NewNumberFromInt(9), factory->NewNumberFromInt(9)}}, {switch_code, {factory->NewNumberFromInt(3), factory->NewNumberFromInt(5)}}, {switch_code, {factory->NewNumberFromInt(3), factory->NewNumberFromInt(6)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(2048); SNPrintF(script, "function %s(p1) { %s };\n%s(0);", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderSwitchMerge) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); const char* switch_code = "var x = 10;" "switch (p1) {\n" " case 1: x = 0;\n" " case 2: x = 1;\n" " case 3:\n" " case 4: x = 2; break;\n" " case 5: x = 3;\n" " case 9: break;\n" " default: x = 4;\n" "}\n" "return x;"; ExpectedSnippet<1> snippets[] = { {switch_code, {factory->NewNumberFromInt(2), factory->NewNumberFromInt(1)}}, {switch_code, {factory->NewNumberFromInt(2), factory->NewNumberFromInt(2)}}, {switch_code, {factory->NewNumberFromInt(2), factory->NewNumberFromInt(3)}}, {switch_code, {factory->NewNumberFromInt(2), factory->NewNumberFromInt(4)}}, {switch_code, {factory->NewNumberFromInt(3), factory->NewNumberFromInt(5)}}, {switch_code, {factory->NewNumberFromInt(10), factory->NewNumberFromInt(9)}}, {switch_code, {factory->NewNumberFromInt(4), factory->NewNumberFromInt(6)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(2048); SNPrintF(script, "function %s(p1) { %s };\n%s(0);", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0)).ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderNestedSwitch) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); const char* switch_code = "switch (p1) {\n" " case 0: {" " switch (p2) { case 0: return 0; case 1: return 1; case 2: break; }\n" " return -1;" " }\n" " case 1: {" " switch (p2) { case 0: return 2; case 1: return 3; }\n" " }\n" " case 2: break;" " }\n" "return -2;"; ExpectedSnippet<2> snippets[] = { {switch_code, {factory->NewNumberFromInt(0), factory->NewNumberFromInt(0), factory->NewNumberFromInt(0)}}, {switch_code, {factory->NewNumberFromInt(1), factory->NewNumberFromInt(0), factory->NewNumberFromInt(1)}}, {switch_code, {factory->NewNumberFromInt(-1), factory->NewNumberFromInt(0), factory->NewNumberFromInt(2)}}, {switch_code, {factory->NewNumberFromInt(-1), factory->NewNumberFromInt(0), factory->NewNumberFromInt(3)}}, {switch_code, {factory->NewNumberFromInt(2), factory->NewNumberFromInt(1), factory->NewNumberFromInt(0)}}, {switch_code, {factory->NewNumberFromInt(3), factory->NewNumberFromInt(1), factory->NewNumberFromInt(1)}}, {switch_code, {factory->NewNumberFromInt(-2), factory->NewNumberFromInt(1), factory->NewNumberFromInt(2)}}, {switch_code, {factory->NewNumberFromInt(-2), factory->NewNumberFromInt(2), factory->NewNumberFromInt(0)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(2048); SNPrintF(script, "function %s(p1, p2) { %s };\n%s(0, 0);", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<Handle<Object>, Handle<Object>>(); Handle<Object> return_value = callable(snippets[i].parameter(0), snippets[i].parameter(1)) .ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderBreakableBlocks) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"var x = 0;\n" "my_heart: {\n" " x = x + 1;\n" " break my_heart;\n" " x = x + 2;\n" "}\n" "return x;\n", {factory->NewNumberFromInt(1)}}, {"var sum = 0;\n" "outta_here: {\n" " for (var x = 0; x < 10; ++x) {\n" " for (var y = 0; y < 3; ++y) {\n" " ++sum;\n" " if (x + y == 12) { break outta_here; }\n" " }\n" " }\n" "}\n" "return sum;", {factory->NewNumber(30)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderWhile) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"var x = 1; while (x < 1) { x *= 100; } return x;", {factory->NewNumberFromInt(1)}}, {"var x = 1, y = 0; while (x < 7) { y += x * x; x += 1; } return y;", {factory->NewNumberFromInt(91)}}, {"var x = 1; while (true) { x += 1; if (x == 10) break; } return x;", {factory->NewNumberFromInt(10)}}, {"var x = 1; while (false) { x += 1; } return x;", {factory->NewNumberFromInt(1)}}, {"var x = 0;\n" "while (true) {\n" " while (x < 10) {\n" " x = x * x + 1;\n" " }" " x += 1;\n" " break;\n" "}\n" "return x;", {factory->NewNumberFromInt(27)}}, {"var x = 1, y = 0;\n" "while (x < 7) {\n" " x += 1;\n" " if (x == 2) continue;\n" " if (x == 3) continue;\n" " y += x * x;\n" " if (x == 4) break;\n" "}\n" "return y;", {factory->NewNumberFromInt(16)}}}; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderDo) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"var x = 1; do { x *= 100; } while (x < 100); return x;", {factory->NewNumberFromInt(100)}}, {"var x = 1; do { x = x * x + 1; } while (x < 7) return x;", {factory->NewNumberFromInt(26)}}, {"var x = 1; do { x += 1; } while (false); return x;", {factory->NewNumberFromInt(2)}}, {"var x = 1, y = 0;\n" "do {\n" " x += 1;\n" " if (x == 2) continue;\n" " if (x == 3) continue;\n" " y += x * x;\n" " if (x == 4) break;\n" "} while (x < 7);\n" "return y;", {factory->NewNumberFromInt(16)}}, {"var x = 0, sum = 0;\n" "do {\n" " do {\n" " ++sum;\n" " ++x;\n" " } while (sum < 1 || x < 2)\n" " do {\n" " ++x;\n" " } while (x < 1)\n" "} while (sum < 3)\n" "return sum;", {factory->NewNumber(3)}}}; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderFor) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"for (var x = 0;; x = 2 * x + 1) { if (x > 10) return x; }", {factory->NewNumberFromInt(15)}}, {"for (var x = 0; true; x = 2 * x + 1) { if (x > 100) return x; }", {factory->NewNumberFromInt(127)}}, {"for (var x = 0; false; x = 2 * x + 1) { if (x > 100) return x; } " "return 0;", {factory->NewNumberFromInt(0)}}, {"for (var x = 0; x < 200; x = 2 * x + 1) { x = x; } return x;", {factory->NewNumberFromInt(255)}}, {"for (var x = 0; x < 200; x = 2 * x + 1) {} return x;", {factory->NewNumberFromInt(255)}}, {"var sum = 0;\n" "for (var x = 0; x < 200; x += 1) {\n" " if (x % 2) continue;\n" " if (sum > 10) break;\n" " sum += x;\n" "}\n" "return sum;", {factory->NewNumberFromInt(12)}}, {"var sum = 0;\n" "for (var w = 0; w < 2; w++) {\n" " for (var x = 0; x < 200; x += 1) {\n" " if (x % 2) continue;\n" " if (x > 4) break;\n" " sum += x + w;\n" " }\n" "}\n" "return sum;", {factory->NewNumberFromInt(15)}}, {"var sum = 0;\n" "for (var w = 0; w < 2; w++) {\n" " if (w == 1) break;\n" " for (var x = 0; x < 200; x += 1) {\n" " if (x % 2) continue;\n" " if (x > 4) break;\n" " sum += x + w;\n" " }\n" "}\n" "return sum;", {factory->NewNumberFromInt(6)}}, {"var sum = 0;\n" "for (var w = 0; w < 3; w++) {\n" " if (w == 1) continue;\n" " for (var x = 0; x < 200; x += 1) {\n" " if (x % 2) continue;\n" " if (x > 4) break;\n" " sum += x + w;\n" " }\n" "}\n" "return sum;", {factory->NewNumberFromInt(18)}}, {"var sum = 0;\n" "for (var x = 1; x < 10; x += 2) {\n" " for (var y = x; y < x + 2; y++) {\n" " sum += y * y;\n" " }\n" "}\n" "return sum;", {factory->NewNumberFromInt(385)}}, {"var sum = 0;\n" "for (var x = 0; x < 5; x++) {\n" " for (var y = 0; y < 5; y++) {\n" " ++sum;\n" " }\n" "}\n" "for (var x = 0; x < 5; x++) {\n" " for (var y = 0; y < 5; y++) {\n" " ++sum;\n" " }\n" "}\n" "return sum;", {factory->NewNumberFromInt(50)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderForIn) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"var sum = 0;\n" "var empty = null;\n" "for (var x in empty) { sum++; }\n" "return sum;", {factory->NewNumberFromInt(0)}}, {"var sum = 100;\n" "var empty = 1;\n" "for (var x in empty) { sum++; }\n" "return sum;", {factory->NewNumberFromInt(100)}}, {"for (var x in [ 10, 20, 30 ]) {}\n" "return 2;", {factory->NewNumberFromInt(2)}}, {"var last = 0;\n" "for (var x in [ 10, 20, 30 ]) {\n" " last = x;\n" "}\n" "return +last;", {factory->NewNumberFromInt(2)}}, {"var first = -1;\n" "for (var x in [ 10, 20, 30 ]) {\n" " first = +x;\n" " if (first > 0) break;\n" "}\n" "return first;", {factory->NewNumberFromInt(1)}}, {"var first = -1;\n" "for (var x in [ 10, 20, 30 ]) {\n" " if (first >= 0) continue;\n" " first = x;\n" "}\n" "return +first;", {factory->NewNumberFromInt(0)}}, {"var sum = 0;\n" "for (var x in [ 10, 20, 30 ]) {\n" " for (var y in [ 11, 22, 33, 44, 55, 66, 77 ]) {\n" " sum += 1;\n" " }\n" "}\n" "return sum;", {factory->NewNumberFromInt(21)}}, {"var sum = 0;\n" "for (var x in [ 10, 20, 30 ]) {\n" " for (var y in [ 11, 22, 33, 44, 55, 66, 77 ]) {\n" " if (sum == 7) break;\n" " if (sum == 6) continue;\n" " sum += 1;\n" " }\n" "}\n" "return sum;", {factory->NewNumberFromInt(6)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderForOf) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {" var r = 0;\n" " for (var a of [0,6,7,9]) { r += a; }\n" " return r;\n", {handle(Smi::FromInt(22), isolate)}}, {" var r = '';\n" " for (var a of 'foobar') { r = a + r; }\n" " return r;\n", {factory->NewStringFromStaticChars("raboof")}}, {" var a = [1, 2, 3];\n" " a.name = 4;\n" " var r = 0;\n" " for (var x of a) { r += x; }\n" " return r;\n", {handle(Smi::FromInt(6), isolate)}}, {" var r = '';\n" " var data = [1, 2, 3]; \n" " for (a of data) { delete data[0]; r += a; } return r;", {factory->NewStringFromStaticChars("123")}}, {" var r = '';\n" " var data = [1, 2, 3]; \n" " for (a of data) { delete data[2]; r += a; } return r;", {factory->NewStringFromStaticChars("12undefined")}}, {" var r = '';\n" " var data = [1, 2, 3]; \n" " for (a of data) { delete data; r += a; } return r;", {factory->NewStringFromStaticChars("123")}}, {" var r = '';\n" " var input = 'foobar';\n" " for (var a of input) {\n" " if (a == 'b') break;\n" " r += a;\n" " }\n" " return r;\n", {factory->NewStringFromStaticChars("foo")}}, {" var r = '';\n" " var input = 'foobar';\n" " for (var a of input) {\n" " if (a == 'b') continue;\n" " r += a;\n" " }\n" " return r;\n", {factory->NewStringFromStaticChars("fooar")}}, {" var r = '';\n" " var data = [1, 2, 3, 4]; \n" " for (a of data) { data[2] = 567; r += a; }\n" " return r;\n", {factory->NewStringFromStaticChars("125674")}}, {" var r = '';\n" " var data = [1, 2, 3, 4]; \n" " for (a of data) { data[4] = 567; r += a; }\n" " return r;\n", {factory->NewStringFromStaticChars("1234567")}}, {" var r = '';\n" " var data = [1, 2, 3, 4]; \n" " for (a of data) { data[5] = 567; r += a; }\n" " return r;\n", {factory->NewStringFromStaticChars("1234undefined567")}}, {" var r = '';\n" " var obj = new Object();\n" " obj[Symbol.iterator] = function() { return {\n" " index: 3,\n" " data: ['a', 'b', 'c', 'd']," " next: function() {" " return {" " done: this.index == -1,\n" " value: this.index < 0 ? undefined : this.data[this.index--]\n" " }\n" " }\n" " }}\n" " for (a of obj) { r += a }\n" " return r;\n", {factory->NewStringFromStaticChars("dcba")}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } void TestJumpWithConstantsAndWideConstants(size_t shard) { const int kStep = 46; int start = static_cast<int>(7 + 17 * shard); for (int constants = start; constants < 300; constants += kStep) { std::stringstream filler_os; // Generate a string that consumes constant pool entries and // spread out branch distances in script below. for (int i = 0; i < constants; i++) { filler_os << "var x_ = 'x_" << i << "';\n"; } std::string filler(filler_os.str()); std::stringstream script_os; script_os << "function " << kFunctionName << "(a) {\n"; script_os << " " << filler; script_os << " for (var i = a; i < 2; i++) {\n"; script_os << " " << filler; script_os << " if (i == 0) { " << filler << "i = 10; continue; }\n"; script_os << " else if (i == a) { " << filler << "i = 12; break; }\n"; script_os << " else { " << filler << " }\n"; script_os << " }\n"; script_os << " return i;\n"; script_os << "}\n"; script_os << kFunctionName << "(0);\n"; std::string script(script_os.str()); HandleAndZoneScope scope; auto isolate = scope.main_isolate(); auto factory = isolate->factory(); BytecodeGraphTester tester(isolate, script.c_str()); auto callable = tester.GetCallable<Handle<Object>>(); for (int a = 0; a < 3; a++) { Handle<Object> return_val = callable(factory->NewNumberFromInt(a)).ToHandleChecked(); static const int results[] = {11, 12, 2}; CHECK_EQ(Handle<Smi>::cast(return_val)->value(), results[a]); } } } SHARD_TEST_BY_4(JumpWithConstantsAndWideConstants) TEST(BytecodeGraphBuilderDoExpressions) { bool old_flag = FLAG_harmony_do_expressions; FLAG_harmony_do_expressions = true; HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"var a = do {}; return a;", {factory->undefined_value()}}, {"var a = do { var x = 100; }; return a;", {factory->undefined_value()}}, {"var a = do { var x = 100; }; return a;", {factory->undefined_value()}}, {"var a = do { var x = 100; x++; }; return a;", {handle(Smi::FromInt(100), isolate)}}, {"var i = 0; for (; i < 5;) { i = do { if (i == 3) { break; }; i + 1; }};" "return i;", {handle(Smi::FromInt(3), isolate)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } FLAG_harmony_do_expressions = old_flag; } TEST(BytecodeGraphBuilderWithStatement) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); ExpectedSnippet<0> snippets[] = { {"with({x:42}) return x;", {handle(Smi::FromInt(42), isolate)}}, {"with({}) { var y = 10; return y;}", {handle(Smi::FromInt(10), isolate)}}, {"var y = {x:42};" " function inner() {" " var x = 20;" " with(y) return x;" "}" "return inner();", {handle(Smi::FromInt(42), isolate)}}, {"var y = {x:42};" " function inner(o) {" " var x = 20;" " with(o) return x;" "}" "return inner(y);", {handle(Smi::FromInt(42), isolate)}}, }; for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderConstDeclaration) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"const x = 3; return x;", {handle(Smi::FromInt(3), isolate)}}, {"let x = 10; x = x + 20; return x;", {handle(Smi::FromInt(30), isolate)}}, {"let x = 10; x = 20; return x;", {handle(Smi::FromInt(20), isolate)}}, {"let x; x = 20; return x;", {handle(Smi::FromInt(20), isolate)}}, {"let x; return x;", {factory->undefined_value()}}, {"var x = 10; { let x = 30; } return x;", {handle(Smi::FromInt(10), isolate)}}, {"let x = 10; { let x = 20; } return x;", {handle(Smi::FromInt(10), isolate)}}, {"var x = 10; eval('let x = 20;'); return x;", {handle(Smi::FromInt(10), isolate)}}, {"var x = 10; eval('const x = 20;'); return x;", {handle(Smi::FromInt(10), isolate)}}, {"var x = 10; { const x = 20; } return x;", {handle(Smi::FromInt(10), isolate)}}, {"var x = 10; { const x = 20; return x;} return -1;", {handle(Smi::FromInt(20), isolate)}}, {"var a = 10;\n" "for (var i = 0; i < 10; ++i) {\n" " const x = i;\n" // const declarations are block scoped. " a = a + x;\n" "}\n" "return a;\n", {handle(Smi::FromInt(55), isolate)}}, }; // Tests for sloppy mode. for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } // Tests for strict mode. for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() {'use strict'; %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderConstDeclarationLookupSlots) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); Factory* factory = isolate->factory(); ExpectedSnippet<0> snippets[] = { {"const x = 3; function f1() {return x;}; return x;", {handle(Smi::FromInt(3), isolate)}}, {"let x = 10; x = x + 20; function f1() {return x;}; return x;", {handle(Smi::FromInt(30), isolate)}}, {"let x; x = 20; function f1() {return x;}; return x;", {handle(Smi::FromInt(20), isolate)}}, {"let x; function f1() {return x;}; return x;", {factory->undefined_value()}}, }; // Tests for sloppy mode. for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } // Tests for strict mode. for (size_t i = 0; i < arraysize(snippets); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() {'use strict'; %s }\n%s();", kFunctionName, snippets[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*snippets[i].return_value())); } } TEST(BytecodeGraphBuilderConstInLookupContextChain) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); const char* prologue = "function OuterMost() {\n" " const outerConst = 10;\n" " let outerLet = 20;\n" " function Outer() {\n" " function Inner() {\n" " this.innerFunc = function() { "; const char* epilogue = " }\n" " }\n" " this.getInnerFunc =" " function() {return new Inner().innerFunc;}\n" " }\n" " this.getOuterFunc =" " function() {return new Outer().getInnerFunc();}" "}\n" "var f = new OuterMost().getOuterFunc();\n" "f();\n"; // Tests for let / constant. ExpectedSnippet<0> const_decl[] = { {"return outerConst;", {handle(Smi::FromInt(10), isolate)}}, {"return outerLet;", {handle(Smi::FromInt(20), isolate)}}, {"outerLet = 30; return outerLet;", {handle(Smi::FromInt(30), isolate)}}, {"var outerLet = 40; return outerLet;", {handle(Smi::FromInt(40), isolate)}}, {"var outerConst = 50; return outerConst;", {handle(Smi::FromInt(50), isolate)}}, {"try { outerConst = 30 } catch(e) { return -1; }", {handle(Smi::FromInt(-1), isolate)}}}; for (size_t i = 0; i < arraysize(const_decl); i++) { ScopedVector<char> script(1024); SNPrintF(script, "%s %s %s", prologue, const_decl[i].code_snippet, epilogue); BytecodeGraphTester tester(isolate, script.start(), "*"); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); CHECK(return_value->SameValue(*const_decl[i].return_value())); } } TEST(BytecodeGraphBuilderIllegalConstDeclaration) { HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); ExpectedSnippet<0, const char*> illegal_const_decl[] = { {"const x = x = 10 + 3; return x;", {"Uncaught ReferenceError: x is not defined"}}, {"const x = 10; x = 20; return x;", {"Uncaught TypeError: Assignment to constant variable."}}, {"const x = 10; { x = 20; } return x;", {"Uncaught TypeError: Assignment to constant variable."}}, {"const x = 10; eval('x = 20;'); return x;", {"Uncaught TypeError: Assignment to constant variable."}}, {"let x = x + 10; return x;", {"Uncaught ReferenceError: x is not defined"}}, {"'use strict'; (function f1() { f1 = 123; })() ", {"Uncaught TypeError: Assignment to constant variable."}}, }; // Tests for sloppy mode. for (size_t i = 0; i < arraysize(illegal_const_decl); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() { %s }\n%s();", kFunctionName, illegal_const_decl[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); v8::Local<v8::String> message = tester.CheckThrowsReturnMessage()->Get(); v8::Local<v8::String> expected_string = v8_str(illegal_const_decl[i].return_value()); CHECK( message->Equals(CcTest::isolate()->GetCurrentContext(), expected_string) .FromJust()); } // Tests for strict mode. for (size_t i = 0; i < arraysize(illegal_const_decl); i++) { ScopedVector<char> script(1024); SNPrintF(script, "function %s() {'use strict'; %s }\n%s();", kFunctionName, illegal_const_decl[i].code_snippet, kFunctionName); BytecodeGraphTester tester(isolate, script.start()); v8::Local<v8::String> message = tester.CheckThrowsReturnMessage()->Get(); v8::Local<v8::String> expected_string = v8_str(illegal_const_decl[i].return_value()); CHECK( message->Equals(CcTest::isolate()->GetCurrentContext(), expected_string) .FromJust()); } } class CountBreakDebugDelegate : public v8::debug::DebugDelegate { public: void BreakProgramRequested(v8::Local<v8::Context> paused_context, const std::vector<int>&) override { debug_break_count++; } int debug_break_count = 0; }; TEST(BytecodeGraphBuilderDebuggerStatement) { CountBreakDebugDelegate delegate; HandleAndZoneScope scope; Isolate* isolate = scope.main_isolate(); v8::debug::SetDebugDelegate(CcTest::isolate(), &delegate); ExpectedSnippet<0> snippet = { "function f() {" " debugger;" "}" "f();", {isolate->factory()->undefined_value()}}; BytecodeGraphTester tester(isolate, snippet.code_snippet); auto callable = tester.GetCallable<>(); Handle<Object> return_value = callable().ToHandleChecked(); v8::debug::SetDebugDelegate(CcTest::isolate(), nullptr); CHECK(return_value.is_identical_to(snippet.return_value())); CHECK_EQ(2, delegate.debug_break_count); } #undef SHARD_TEST_BY_2 #undef SHARD_TEST_BY_4 #undef SPACE #undef REPEAT_2 #undef REPEAT_4 #undef REPEAT_8 #undef REPEAT_16 #undef REPEAT_32 #undef REPEAT_64 #undef REPEAT_128 #undef REPEAT_256 #undef REPEAT_127 } // namespace compiler } // namespace internal } // namespace v8
38.15882
80
0.585514
[ "object", "vector" ]
edca427657cc94ffefa5277e9ae71e9a21b4bc2e
6,254
hpp
C++
cpp/IMC/Spec/HistoricSonarData.hpp
arthur-bit-monnot/fire-rs-saop
321e16fceebf44e8e97b482c24f37fbf6dd7d162
[ "BSD-2-Clause" ]
13
2018-11-19T15:51:23.000Z
2022-01-16T11:24:21.000Z
cpp/IMC/Spec/HistoricSonarData.hpp
fire-rs-laas/fire-rs-saop
321e16fceebf44e8e97b482c24f37fbf6dd7d162
[ "BSD-2-Clause" ]
14
2017-10-12T16:19:19.000Z
2018-03-12T12:07:56.000Z
cpp/IMC/Spec/HistoricSonarData.hpp
fire-rs-laas/fire-rs-saop
321e16fceebf44e8e97b482c24f37fbf6dd7d162
[ "BSD-2-Clause" ]
4
2018-03-12T12:28:55.000Z
2021-07-07T18:32:17.000Z
//*************************************************************************** // Copyright 2017 OceanScan - Marine Systems & Technology, Lda. * //*************************************************************************** // Licensed under the Apache License, Version 2.0 (the "License"); * // you may not use this file except in compliance with the License. * // You may obtain a copy of the License at * // * // http://www.apache.org/licenses/LICENSE-2.0 * // * // Unless required by applicable law or agreed to in writing, software * // distributed under the License is distributed on an "AS IS" BASIS, * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * // See the License for the specific language governing permissions and * // limitations under the License. * //*************************************************************************** // Author: Ricardo Martins * //*************************************************************************** // Automatically generated. * //*************************************************************************** // IMC XML MD5: 4d8734a1111656aac56f803acdc90c22 * //*************************************************************************** #ifndef IMC_HISTORICSONARDATA_HPP_INCLUDED_ #define IMC_HISTORICSONARDATA_HPP_INCLUDED_ // ISO C++ 98 headers. #include <ostream> #include <string> #include <vector> // IMC headers. #include "../Base/Config.hpp" #include "../Base/Message.hpp" #include "../Base/InlineMessage.hpp" #include "../Base/MessageList.hpp" #include "../Base/JSON.hpp" #include "../Base/Serialization.hpp" #include "../Spec/Enumerations.hpp" #include "../Spec/Bitfields.hpp" namespace IMC { //! Historic Sonar Data. class HistoricSonarData: public Message { public: //! Encoding. enum EncodingEnum { //! One Byte Per Pixel. ENC_ONE_BYTE_PER_PIXEL = 0, //! PNG compressed image. ENC_PNG = 1, //! JPEG compressed image. ENC_JPEG = 2 }; //! Altitude. float altitude; //! Width. float width; //! Length. float length; //! Bearing. float bearing; //! Pixels Per Line. int16_t pxl; //! Encoding. uint8_t encoding; //! SonarData. std::vector<char> sonar_data; static uint16_t getIdStatic(void) { return 109; } static HistoricSonarData* cast(Message* msg__) { return (HistoricSonarData*)msg__; } HistoricSonarData(void) { m_header.mgid = HistoricSonarData::getIdStatic(); clear(); } HistoricSonarData* clone(void) const { return new HistoricSonarData(*this); } void clear(void) { altitude = 0; width = 0; length = 0; bearing = 0; pxl = 0; encoding = 0; sonar_data.clear(); } bool fieldsEqual(const Message& msg__) const { const IMC::HistoricSonarData& other__ = static_cast<const HistoricSonarData&>(msg__); if (altitude != other__.altitude) return false; if (width != other__.width) return false; if (length != other__.length) return false; if (bearing != other__.bearing) return false; if (pxl != other__.pxl) return false; if (encoding != other__.encoding) return false; if (sonar_data != other__.sonar_data) return false; return true; } uint8_t* serializeFields(uint8_t* bfr__) const { uint8_t* ptr__ = bfr__; ptr__ += IMC::serialize(altitude, ptr__); ptr__ += IMC::serialize(width, ptr__); ptr__ += IMC::serialize(length, ptr__); ptr__ += IMC::serialize(bearing, ptr__); ptr__ += IMC::serialize(pxl, ptr__); ptr__ += IMC::serialize(encoding, ptr__); ptr__ += IMC::serialize(sonar_data, ptr__); return ptr__; } size_t deserializeFields(const uint8_t* bfr__, size_t size__) { const uint8_t* start__ = bfr__; bfr__ += IMC::deserialize(altitude, bfr__, size__); bfr__ += IMC::deserialize(width, bfr__, size__); bfr__ += IMC::deserialize(length, bfr__, size__); bfr__ += IMC::deserialize(bearing, bfr__, size__); bfr__ += IMC::deserialize(pxl, bfr__, size__); bfr__ += IMC::deserialize(encoding, bfr__, size__); bfr__ += IMC::deserialize(sonar_data, bfr__, size__); return bfr__ - start__; } size_t reverseDeserializeFields(const uint8_t* bfr__, size_t size__) { const uint8_t* start__ = bfr__; bfr__ += IMC::reverseDeserialize(altitude, bfr__, size__); bfr__ += IMC::reverseDeserialize(width, bfr__, size__); bfr__ += IMC::reverseDeserialize(length, bfr__, size__); bfr__ += IMC::reverseDeserialize(bearing, bfr__, size__); bfr__ += IMC::reverseDeserialize(pxl, bfr__, size__); bfr__ += IMC::deserialize(encoding, bfr__, size__); bfr__ += IMC::reverseDeserialize(sonar_data, bfr__, size__); return bfr__ - start__; } uint16_t getId(void) const { return HistoricSonarData::getIdStatic(); } const char* getName(void) const { return "HistoricSonarData"; } size_t getFixedSerializationSize(void) const { return 19; } size_t getVariableSerializationSize(void) const { return IMC::getSerializationSize(sonar_data); } void fieldsToJSON(std::ostream& os__, unsigned nindent__) const { IMC::toJSON(os__, "altitude", altitude, nindent__); IMC::toJSON(os__, "width", width, nindent__); IMC::toJSON(os__, "length", length, nindent__); IMC::toJSON(os__, "bearing", bearing, nindent__); IMC::toJSON(os__, "pxl", pxl, nindent__); IMC::toJSON(os__, "encoding", encoding, nindent__); IMC::toJSON(os__, "sonar_data", sonar_data, nindent__); } }; } #endif
30.656863
91
0.547969
[ "vector" ]
edd05ea13d5af9dc30fbccdd61a686696f583c91
71,304
cpp
C++
src/hip_graph.cpp
neqochan/hipamd
a97f7e4214c4111723d1476942106022d1186c70
[ "MIT" ]
null
null
null
src/hip_graph.cpp
neqochan/hipamd
a97f7e4214c4111723d1476942106022d1186c70
[ "MIT" ]
null
null
null
src/hip_graph.cpp
neqochan/hipamd
a97f7e4214c4111723d1476942106022d1186c70
[ "MIT" ]
null
null
null
/* Copyright (c) 2021 - 2021 Advanced Micro Devices, Inc. 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 "hip_graph_internal.hpp" #include "platform/command.hpp" #include "hip_conversions.hpp" #include "hip_platform.hpp" #include "hip_event.hpp" thread_local std::vector<hipStream_t> g_captureStreams; inline hipError_t ihipGraphAddNode(hipGraphNode_t graphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies) { graph->AddNode(graphNode); for (size_t i = 0; i < numDependencies; i++) { if (!hipGraphNode::isNodeValid(pDependencies[i])) { return hipErrorInvalidValue; } pDependencies[i]->AddEdge(graphNode); } return hipSuccess; } hipError_t ihipValidateKernelParams(const hipKernelNodeParams* pNodeParams) { if (pNodeParams->kernelParams == nullptr) { return hipErrorInvalidValue; } hipFunction_t func = nullptr; hipError_t status = hipGraphKernelNode::getFunc(&func, *pNodeParams, ihipGetDevice()); if (status != hipSuccess) { return hipErrorInvalidDeviceFunction; } size_t globalWorkSizeX = static_cast<size_t>(pNodeParams->gridDim.x) * pNodeParams->blockDim.x; size_t globalWorkSizeY = static_cast<size_t>(pNodeParams->gridDim.y) * pNodeParams->blockDim.y; size_t globalWorkSizeZ = static_cast<size_t>(pNodeParams->gridDim.z) * pNodeParams->blockDim.z; if (globalWorkSizeX > std::numeric_limits<uint32_t>::max() || globalWorkSizeY > std::numeric_limits<uint32_t>::max() || globalWorkSizeZ > std::numeric_limits<uint32_t>::max()) { return hipErrorInvalidConfiguration; } status = ihipLaunchKernel_validate( func, static_cast<uint32_t>(globalWorkSizeX), static_cast<uint32_t>(globalWorkSizeY), static_cast<uint32_t>(globalWorkSizeZ), pNodeParams->blockDim.x, pNodeParams->blockDim.y, pNodeParams->blockDim.z, pNodeParams->sharedMemBytes, pNodeParams->kernelParams, pNodeParams->extra, ihipGetDevice(), 0); if (status != hipSuccess) { return status; } return hipSuccess; } hipError_t ihipGraphAddKernelNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies, const hipKernelNodeParams* pNodeParams) { if (pGraphNode == nullptr || graph == nullptr || (numDependencies > 0 && pDependencies == nullptr) || pNodeParams == nullptr || pNodeParams->func == nullptr) { return hipErrorInvalidValue; } if (!ihipGraph::isGraphValid(graph)) { return hipErrorInvalidValue; } hipError_t status = ihipValidateKernelParams(pNodeParams); if (hipSuccess != status) { return status; } hipFunction_t func = nullptr; status = hipGraphKernelNode::getFunc(&func, *pNodeParams, ihipGetDevice()); if (status != hipSuccess) { return hipErrorInvalidDeviceFunction; } *pGraphNode = new hipGraphKernelNode(pNodeParams, func); status = ihipGraphAddNode(*pGraphNode, graph, pDependencies, numDependencies); return status; } hipError_t ihipGraphAddMemcpyNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies, const hipMemcpy3DParms* pCopyParams) { if (pGraphNode == nullptr || graph == nullptr || (numDependencies > 0 && pDependencies == nullptr) || pCopyParams == nullptr) { return hipErrorInvalidValue; } hipError_t status = ihipMemcpy3D_validate(pCopyParams); if (status != hipSuccess) { return status; } *pGraphNode = new hipGraphMemcpyNode(pCopyParams); status = ihipGraphAddNode(*pGraphNode, graph, pDependencies, numDependencies); return status; } hipError_t ihipGraphAddMemcpyNode1D(hipGraphNode_t* pGraphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies, void* dst, const void* src, size_t count, hipMemcpyKind kind) { if (pGraphNode == nullptr || graph == nullptr || (numDependencies > 0 && pDependencies == nullptr)) { return hipErrorInvalidValue; } hipError_t status = ihipMemcpy_validate(dst, src, count, kind); if (status != hipSuccess) { return status; } *pGraphNode = new hipGraphMemcpyNode1D(dst, src, count, kind); status = ihipGraphAddNode(*pGraphNode, graph, pDependencies, numDependencies); return status; } hipError_t ihipGraphAddMemsetNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies, const hipMemsetParams* pMemsetParams) { if (pGraphNode == nullptr || graph == nullptr || pMemsetParams == nullptr || (numDependencies > 0 && pDependencies == nullptr) || pMemsetParams->height == 0) { return hipErrorInvalidValue; } // The element size must be 1, 2, or 4 bytes if (pMemsetParams->elementSize != sizeof(int8_t) && pMemsetParams->elementSize != sizeof(int16_t) && pMemsetParams->elementSize != sizeof(int32_t)) { return hipErrorInvalidValue; } hipError_t status; status = ihipGraphMemsetParams_validate(pMemsetParams); if (status != hipSuccess) { return status; } if (pMemsetParams->height == 1) { status = ihipMemset_validate(pMemsetParams->dst, pMemsetParams->value, pMemsetParams->elementSize, pMemsetParams->width * pMemsetParams->elementSize); } else { auto sizeBytes = pMemsetParams->width * pMemsetParams->height * 1; status = ihipMemset3D_validate( {pMemsetParams->dst, pMemsetParams->pitch, pMemsetParams->width, pMemsetParams->height}, pMemsetParams->value, {pMemsetParams->width, pMemsetParams->height, 1}, sizeBytes); } if (status != hipSuccess) { return status; } *pGraphNode = new hipGraphMemsetNode(pMemsetParams); status = ihipGraphAddNode(*pGraphNode, graph, pDependencies, numDependencies); return status; } hipError_t capturehipLaunchKernel(hipStream_t& stream, const void*& hostFunction, dim3& gridDim, dim3& blockDim, void**& args, size_t& sharedMemBytes) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node kernel launch on stream : %p", stream); if (!hip::isValid(stream)) { return hipErrorInvalidValue; } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hipKernelNodeParams nodeParams; nodeParams.func = const_cast<void*>(hostFunction); nodeParams.blockDim = blockDim; nodeParams.extra = nullptr; nodeParams.gridDim = gridDim; nodeParams.kernelParams = args; nodeParams.sharedMemBytes = sharedMemBytes; hipGraphNode_t pGraphNode; hipError_t status = ihipGraphAddKernelNode(&pGraphNode, s->GetCaptureGraph(), s->GetLastCapturedNodes().data(), s->GetLastCapturedNodes().size(), &nodeParams); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(pGraphNode); return hipSuccess; } hipError_t capturehipMemcpy3DAsync(hipStream_t& stream, const hipMemcpy3DParms*& p) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node Memcpy3D on stream : %p", stream); if (!hip::isValid(stream)) { return hipErrorInvalidValue; } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hipGraphNode_t pGraphNode; hipError_t status = ihipGraphAddMemcpyNode(&pGraphNode, s->GetCaptureGraph(), s->GetLastCapturedNodes().data(), s->GetLastCapturedNodes().size(), p); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(pGraphNode); return hipSuccess; } hipError_t capturehipMemcpy2DAsync(hipStream_t& stream, void*& dst, size_t& dpitch, const void*& src, size_t& spitch, size_t& width, size_t& height, hipMemcpyKind& kind) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node Memcpy2D on stream : %p", stream); if (dst == nullptr || src == nullptr || !hip::isValid(stream)) { return hipErrorInvalidValue; } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hipGraphNode_t pGraphNode; hipMemcpy3DParms p = {}; memset(&p, 0, sizeof(p)); p.kind = kind; p.srcPtr.ptr = const_cast<void*>(src); p.srcPtr.pitch = spitch; p.srcArray = nullptr; // Ignored. p.dstPtr.ptr = const_cast<void*>(dst); p.dstPtr.pitch = dpitch; p.dstArray = nullptr; // Ignored. p.extent = {width, height, 1}; hipError_t status = ihipGraphAddMemcpyNode(&pGraphNode, s->GetCaptureGraph(), s->GetLastCapturedNodes().data(), s->GetLastCapturedNodes().size(), &p); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(pGraphNode); return hipSuccess; } hipError_t capturehipMemcpy2DFromArrayAsync(hipStream_t& stream, void*& dst, size_t& dpitch, hipArray_const_t& src, size_t& wOffsetSrc, size_t& hOffsetSrc, size_t& width, size_t& height, hipMemcpyKind& kind) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node Memcpy2DFromArray on stream : %p", stream); if (src == nullptr || dst == nullptr || !hip::isValid(stream)) { return hipErrorInvalidValue; } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hipGraphNode_t pGraphNode; hipMemcpy3DParms p = {}; memset(&p, 0, sizeof(p)); p.srcPos = {wOffsetSrc, hOffsetSrc, 0}; p.kind = kind; p.srcPtr.ptr = nullptr; p.srcArray = const_cast<hipArray*>(src); // Ignored. p.kind = kind; p.dstPtr.ptr = dst; p.dstArray = nullptr; // Ignored. p.dstPtr.pitch = dpitch; p.extent = {width / hip::getElementSize(p.srcArray), height, 1}; hipError_t status = ihipGraphAddMemcpyNode(&pGraphNode, s->GetCaptureGraph(), s->GetLastCapturedNodes().data(), s->GetLastCapturedNodes().size(), &p); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(pGraphNode); return hipSuccess; } hipError_t capturehipMemcpyFromArrayAsync(hipStream_t& stream, void*& dst, hipArray_const_t& src, size_t& wOffsetSrc, size_t& hOffsetSrc, size_t& count, hipMemcpyKind& kind) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node Memcpy2DFromArray on stream : %p", stream); if (src == nullptr || dst == nullptr || !hip::isValid(stream)) { return hipErrorInvalidValue; } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hipGraphNode_t pGraphNode; hipMemcpy3DParms p = {}; memset(&p, 0, sizeof(p)); p.srcPos = {wOffsetSrc, hOffsetSrc, 0}; p.kind = kind; p.srcPtr.ptr = nullptr; p.srcArray = const_cast<hipArray*>(src); p.kind = kind; p.dstPtr.ptr = dst; p.dstArray = nullptr; // Ignored. p.dstPtr.pitch = 0; const size_t arrayHeight = (src->height != 0) ? src->height : 1; const size_t widthInBytes = count / arrayHeight; const size_t height = (count / src->width) / hip::getElementSize(src); p.extent = {widthInBytes / hip::getElementSize(p.srcArray), height, 1}; hipError_t status = ihipGraphAddMemcpyNode(&pGraphNode, s->GetCaptureGraph(), s->GetLastCapturedNodes().data(), s->GetLastCapturedNodes().size(), &p); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(pGraphNode); return hipSuccess; } hipError_t capturehipMemcpy2DToArrayAsync(hipStream_t& stream, hipArray*& dst, size_t& wOffset, size_t& hOffset, const void*& src, size_t& spitch, size_t& width, size_t& height, hipMemcpyKind& kind) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node Memcpy2DFromArray on stream : %p", stream); if (src == nullptr || dst == nullptr || !hip::isValid(stream)) { return hipErrorInvalidValue; } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hipGraphNode_t pGraphNode; hipMemcpy3DParms p = {}; memset(&p, 0, sizeof(p)); p.dstPos = {wOffset, hOffset, 0}; p.kind = kind; p.dstPtr.ptr = nullptr; p.dstArray = dst; // Ignored. p.kind = kind; p.srcPtr.ptr = const_cast<void*>(src); p.srcArray = nullptr; // Ignored. p.srcPtr.pitch = spitch; p.extent = {width / hip::getElementSize(p.dstArray), height, 1}; hipError_t status = ihipGraphAddMemcpyNode(&pGraphNode, s->GetCaptureGraph(), s->GetLastCapturedNodes().data(), s->GetLastCapturedNodes().size(), &p); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(pGraphNode); return hipSuccess; } hipError_t capturehipMemcpyToArrayAsync(hipStream_t& stream, hipArray_t& dst, size_t& wOffset, size_t& hOffset, const void*& src, size_t& count, hipMemcpyKind& kind) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node Memcpy2DFromArray on stream : %p", stream); if (src == nullptr || dst == nullptr || !hip::isValid(stream)) { return hipErrorInvalidValue; } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hipGraphNode_t pGraphNode; hipMemcpy3DParms p = {}; memset(&p, 0, sizeof(p)); p.dstPos = {wOffset, hOffset, 0}; p.kind = kind; p.dstPtr.ptr = nullptr; p.dstArray = dst; // Ignored. p.kind = kind; p.srcPtr.ptr = const_cast<void*>(src); p.srcArray = nullptr; // Ignored. p.srcPtr.pitch = 0; const size_t arrayHeight = (dst->height != 0) ? dst->height : 1; const size_t widthInBytes = count / arrayHeight; const size_t height = (count / dst->width) / hip::getElementSize(dst); p.extent = {widthInBytes / hip::getElementSize(p.dstArray), height, 1}; hipError_t status = ihipGraphAddMemcpyNode(&pGraphNode, s->GetCaptureGraph(), s->GetLastCapturedNodes().data(), s->GetLastCapturedNodes().size(), &p); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(pGraphNode); return hipSuccess; } hipError_t capturehipMemcpyParam2DAsync(hipStream_t& stream, const hip_Memcpy2D*& pCopy) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node MemcpyParam2D on stream : %p", stream); if (!hip::isValid(stream)) { return hipErrorInvalidValue; } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hipGraphNode_t pGraphNode; hipMemcpy3DParms p = {}; memset(&p, 0, sizeof(p)); p.srcArray = pCopy->srcArray; p.srcPos = {pCopy->srcXInBytes, pCopy->srcY, 0}; p.srcPtr.pitch = pCopy->srcPitch; if (pCopy->srcDevice != nullptr) { p.srcPtr.ptr = pCopy->srcDevice; } if (pCopy->srcHost != nullptr) { p.srcPtr.ptr = const_cast<void*>(pCopy->srcHost); } p.dstArray = pCopy->dstArray; p.dstPos = {pCopy->dstXInBytes, pCopy->dstY, 0}; p.dstPtr.pitch = pCopy->srcPitch; if (pCopy->dstDevice != nullptr) { p.dstPtr.ptr = pCopy->dstDevice; } if (pCopy->dstHost != nullptr) { p.dstPtr.ptr = const_cast<void*>(pCopy->dstHost); } p.extent = {pCopy->WidthInBytes, pCopy->Height, 1}; if (pCopy->srcMemoryType == hipMemoryTypeHost && pCopy->dstMemoryType == hipMemoryTypeDevice) { p.kind = hipMemcpyHostToDevice; } else if (pCopy->srcMemoryType == hipMemoryTypeDevice && pCopy->dstMemoryType == hipMemoryTypeHost) { p.kind = hipMemcpyDeviceToHost; } else if (pCopy->srcMemoryType == hipMemoryTypeDevice && pCopy->dstMemoryType == hipMemoryTypeDevice) { p.kind = hipMemcpyDeviceToDevice; } hipError_t status = ihipGraphAddMemcpyNode(&pGraphNode, s->GetCaptureGraph(), s->GetLastCapturedNodes().data(), s->GetLastCapturedNodes().size(), &p); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(pGraphNode); return hipSuccess; } hipError_t capturehipMemcpyAtoHAsync(hipStream_t& stream, void*& dstHost, hipArray*& srcArray, size_t& srcOffset, size_t& ByteCount) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node MemcpyParam2D on stream : %p", stream); if (srcArray == nullptr || dstHost == nullptr || !hip::isValid(stream)) { return hipErrorInvalidValue; } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hipGraphNode_t pGraphNode; hipMemcpy3DParms p = {}; memset(&p, 0, sizeof(p)); p.srcArray = srcArray; p.srcPos = {srcOffset, 0, 0}; p.dstPtr.ptr = dstHost; p.extent = {ByteCount / hip::getElementSize(p.srcArray), 1, 1}; hipError_t status = ihipGraphAddMemcpyNode(&pGraphNode, s->GetCaptureGraph(), s->GetLastCapturedNodes().data(), s->GetLastCapturedNodes().size(), &p); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(pGraphNode); return hipSuccess; } hipError_t capturehipMemcpyHtoAAsync(hipStream_t& stream, hipArray*& dstArray, size_t& dstOffset, const void*& srcHost, size_t& ByteCount) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node MemcpyParam2D on stream : %p", stream); if (dstArray == nullptr || srcHost == nullptr || !hip::isValid(stream)) { return hipErrorInvalidValue; } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hipGraphNode_t pGraphNode; hipMemcpy3DParms p = {}; memset(&p, 0, sizeof(p)); p.dstArray = dstArray; p.dstPos = {dstOffset, 0, 0}; p.srcPtr.ptr = const_cast<void*>(srcHost); p.extent = {ByteCount / hip::getElementSize(p.dstArray), 1, 1}; hipError_t status = ihipGraphAddMemcpyNode(&pGraphNode, s->GetCaptureGraph(), s->GetLastCapturedNodes().data(), s->GetLastCapturedNodes().size(), &p); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(pGraphNode); return hipSuccess; } hipError_t capturehipMemcpy(hipStream_t stream, void* dst, const void* src, size_t sizeBytes, hipMemcpyKind kind) { if (!hip::isValid(stream)) { return hipErrorInvalidValue; } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); std::vector<hipGraphNode_t> pDependencies = s->GetLastCapturedNodes(); size_t numDependencies = s->GetLastCapturedNodes().size(); hipGraph_t graph = s->GetCaptureGraph(); hipError_t status = ihipMemcpy_validate(dst, src, sizeBytes, kind); if (status != hipSuccess) { return status; } hipGraphNode_t node = new hipGraphMemcpyNode1D(dst, src, sizeBytes, kind); status = ihipGraphAddNode(node, graph, pDependencies.data(), numDependencies); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(node); return hipSuccess; } hipError_t capturehipMemcpyAsync(hipStream_t& stream, void*& dst, const void*& src, size_t& sizeBytes, hipMemcpyKind& kind) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node Memcpy1D on stream : %p", stream); if (!hip::isValid(stream)) { return hipErrorInvalidValue; } return capturehipMemcpy(stream, dst, src, sizeBytes, kind); } hipError_t capturehipMemcpyHtoDAsync(hipStream_t& stream, hipDeviceptr_t& dstDevice, void*& srcHost, size_t& ByteCount, hipMemcpyKind& kind) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node MemcpyHtoD on stream : %p", stream); if (!hip::isValid(stream)) { return hipErrorInvalidValue; } return capturehipMemcpy(stream, dstDevice, srcHost, ByteCount, kind); } hipError_t capturehipMemcpyDtoDAsync(hipStream_t& stream, hipDeviceptr_t& dstDevice, hipDeviceptr_t& srcDevice, size_t& ByteCount, hipMemcpyKind& kind) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node hipMemcpyDtoD on stream : %p", stream); if (!hip::isValid(stream)) { return hipErrorInvalidValue; } return capturehipMemcpy(stream, dstDevice, srcDevice, ByteCount, kind); } hipError_t capturehipMemcpyDtoHAsync(hipStream_t& stream, void*& dstHost, hipDeviceptr_t& srcDevice, size_t& ByteCount, hipMemcpyKind& kind) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node hipMemcpyDtoH on stream : %p", stream); if (!hip::isValid(stream)) { return hipErrorInvalidValue; } return capturehipMemcpy(stream, dstHost, srcDevice, ByteCount, kind); } hipError_t capturehipMemcpyFromSymbolAsync(hipStream_t& stream, void*& dst, const void*& symbol, size_t& sizeBytes, size_t& offset, hipMemcpyKind& kind) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node MemcpyFromSymbolNode on stream : %p", stream); if (!hip::isValid(stream)) { return hipErrorInvalidValue; } size_t sym_size = 0; hipDeviceptr_t device_ptr = nullptr; hipError_t status = ihipMemcpySymbol_validate(symbol, sizeBytes, offset, sym_size, device_ptr); if (status != hipSuccess) { HIP_RETURN(status); } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hipGraphNode_t pGraphNode = new hipGraphMemcpyNodeFromSymbol(dst, symbol, sizeBytes, offset, kind); status = ihipGraphAddNode(pGraphNode, s->GetCaptureGraph(), s->GetLastCapturedNodes().data(), s->GetLastCapturedNodes().size()); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(pGraphNode); return hipSuccess; } hipError_t capturehipMemcpyToSymbolAsync(hipStream_t& stream, const void*& symbol, const void*& src, size_t& sizeBytes, size_t& offset, hipMemcpyKind& kind) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node MemcpyToSymbolNode on stream : %p", stream); if (!hip::isValid(stream)) { return hipErrorInvalidValue; } size_t sym_size = 0; hipDeviceptr_t device_ptr = nullptr; hipError_t status = ihipMemcpySymbol_validate(symbol, sizeBytes, offset, sym_size, device_ptr); if (status != hipSuccess) { HIP_RETURN(status); } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hipGraphNode_t pGraphNode = new hipGraphMemcpyNodeToSymbol(symbol, src, sizeBytes, offset, kind); status = ihipGraphAddNode(pGraphNode, s->GetCaptureGraph(), s->GetLastCapturedNodes().data(), s->GetLastCapturedNodes().size()); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(pGraphNode); return hipSuccess; } hipError_t capturehipMemsetAsync(hipStream_t& stream, void*& dst, int& value, size_t& valueSize, size_t& sizeBytes) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node Memset1D on stream : %p", stream); if (!hip::isValid(stream)) { return hipErrorInvalidValue; } hipMemsetParams memsetParams = {0}; memsetParams.dst = dst; memsetParams.value = value; memsetParams.elementSize = valueSize; memsetParams.width = sizeBytes / valueSize; memsetParams.height = 1; hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hipGraphNode_t pGraphNode; hipError_t status = ihipGraphAddMemsetNode(&pGraphNode, s->GetCaptureGraph(), s->GetLastCapturedNodes().data(), s->GetLastCapturedNodes().size(), &memsetParams); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(pGraphNode); return hipSuccess; } hipError_t capturehipMemset2DAsync(hipStream_t& stream, void*& dst, size_t& pitch, int& value, size_t& width, size_t& height) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node Memset2D on stream : %p", stream); hipMemsetParams memsetParams = {0}; if (!hip::isValid(stream)) { return hipErrorInvalidValue; } memsetParams.dst = dst; memsetParams.value = value; memsetParams.width = width; memsetParams.height = height; memsetParams.pitch = pitch; hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hipGraphNode_t pGraphNode; hipError_t status = ihipGraphAddMemsetNode(&pGraphNode, s->GetCaptureGraph(), s->GetLastCapturedNodes().data(), s->GetLastCapturedNodes().size(), &memsetParams); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(pGraphNode); return hipSuccess; } hipError_t capturehipMemset3DAsync(hipStream_t& stream, hipPitchedPtr& pitchedDevPtr, int& value, hipExtent& extent) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node Memset3D on stream : %p", stream); if (!hip::isValid(stream)) { return hipErrorInvalidValue; } return hipSuccess; } hipError_t capturehipEventRecord(hipStream_t& stream, hipEvent_t& event) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node EventRecord on stream : %p, Event %p", stream, event); if (event == nullptr) { return hipErrorInvalidHandle; } if (!hip::isValid(stream)) { return hipErrorInvalidValue; } hip::Event* e = reinterpret_cast<hip::Event*>(event); e->StartCapture(stream); hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); s->SetCaptureEvent(event); std::vector<hipGraphNode_t> lastCapturedNodes = s->GetLastCapturedNodes(); if (!lastCapturedNodes.empty()) { e->SetNodesPrevToRecorded(lastCapturedNodes); } return hipSuccess; } hipError_t capturehipStreamWaitEvent(hipEvent_t& event, hipStream_t& stream, unsigned int& flags) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node StreamWaitEvent on stream : %p, Event %p", stream, event); if (!hip::isValid(stream)) { return hipErrorInvalidValue; } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hip::Event* e = reinterpret_cast<hip::Event*>(event); if (event == nullptr || stream == nullptr) { return hipErrorInvalidValue; } if (!s->IsOriginStream()) { s->SetCaptureGraph(reinterpret_cast<hip::Stream*>(e->GetCaptureStream())->GetCaptureGraph()); s->SetCaptureMode(reinterpret_cast<hip::Stream*>(e->GetCaptureStream())->GetCaptureMode()); s->SetParentStream(e->GetCaptureStream()); s->SetParallelCaptureStream(stream); } else { assert(std::find(g_captureStreams.begin(), g_captureStreams.end(), stream) != g_captureStreams.end() && "capturing stream should be present"); } s->AddCrossCapturedNode(e->GetNodesPrevToRecorded()); return hipSuccess; } hipError_t capturehipLaunchHostFunc(hipStream_t& stream, hipHostFn_t& fn, void*& userData) { ClPrint(amd::LOG_INFO, amd::LOG_API, "[hipGraph] current capture node Memset2D on stream : %p", stream); if (fn == nullptr || userData == nullptr || !hip::isValid(stream)) { return hipErrorInvalidValue; } hipHostNodeParams hostParams = {0}; hostParams.fn = fn; hostParams.userData = userData; hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); hipGraphNode_t pGraphNode = new hipGraphHostNode(&hostParams); hipError_t status = ihipGraphAddNode(pGraphNode, s->GetCaptureGraph(), s->GetLastCapturedNodes().data(), s->GetLastCapturedNodes().size()); if (status != hipSuccess) { return status; } s->SetLastCapturedNode(pGraphNode); return hipSuccess; } hipError_t hipStreamIsCapturing(hipStream_t stream, hipStreamCaptureStatus* pCaptureStatus) { HIP_INIT_API(hipStreamIsCapturing, stream, pCaptureStatus); if (pCaptureStatus == nullptr || !hip::isValid(stream)) { HIP_RETURN(hipErrorInvalidValue); } if (stream == nullptr) { *pCaptureStatus = hipStreamCaptureStatusNone; } else { *pCaptureStatus = reinterpret_cast<hip::Stream*>(stream)->GetCaptureStatus(); } HIP_RETURN(hipSuccess); } hipError_t hipThreadExchangeStreamCaptureMode(hipStreamCaptureMode* mode) { HIP_INIT_API(hipThreadExchangeStreamCaptureMode, mode); if (mode == nullptr || *mode < hipStreamCaptureModeGlobal || *mode > hipStreamCaptureModeRelaxed || g_captureStreams.size() == 0) { HIP_RETURN(hipErrorInvalidValue); } hipStreamCaptureMode oldMode = reinterpret_cast<hip::Stream*>(g_captureStreams[0])->GetCaptureMode(); reinterpret_cast<hip::Stream*>(g_captureStreams[0])->SetCaptureMode(*mode); *mode = oldMode; HIP_RETURN_DURATION(hipSuccess); } hipError_t hipStreamBeginCapture(hipStream_t stream, hipStreamCaptureMode mode) { HIP_INIT_API(hipStreamBeginCapture, stream, mode); if (!hip::isValid(stream)) { HIP_RETURN(hipErrorInvalidValue); } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); // capture cannot be initiated on legacy stream // It can be initiated if the stream is not already in capture mode if (stream == nullptr || (mode < hipStreamCaptureModeGlobal || mode > hipStreamCaptureModeRelaxed) || s->GetCaptureStatus() == hipStreamCaptureStatusActive) { HIP_RETURN(hipErrorInvalidValue); } s->SetCaptureGraph(new ihipGraph()); s->SetCaptureMode(mode); s->SetOriginStream(); g_captureStreams.push_back(stream); HIP_RETURN_DURATION(hipSuccess); } hipError_t hipStreamEndCapture(hipStream_t stream, hipGraph_t* pGraph) { HIP_INIT_API(hipStreamEndCapture, stream, pGraph); if (pGraph == nullptr || stream == nullptr || !hip::isValid(stream)) { HIP_RETURN(hipErrorInvalidValue); } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); // Capture must be ended on the same stream in which it was initiated if (!s->IsOriginStream()) { HIP_RETURN(hipErrorStreamCaptureUnmatched); } // If mode is not hipStreamCaptureModeRelaxed, hipStreamEndCapture must be called on the stream // from the same thread const auto& it = std::find(g_captureStreams.begin(), g_captureStreams.end(), stream); if (s->GetCaptureMode() != hipStreamCaptureModeRelaxed && it == g_captureStreams.end()) { HIP_RETURN(hipErrorStreamCaptureWrongThread); } // If capture was invalidated, due to a violation of the rules of stream capture if (s->GetCaptureStatus() == hipStreamCaptureStatusInvalidated) { *pGraph = nullptr; HIP_RETURN(hipErrorStreamCaptureInvalidated); } // check if all parallel streams have joined // Nodes that are removed from the dependency set via API hipStreamUpdateCaptureDependencies do // not result in hipErrorStreamCaptureUnjoined if (s->GetCaptureGraph()->GetLeafNodeCount() > 1) { std::vector<hipGraphNode_t> leafNodes = s->GetCaptureGraph()->GetLeafNodes(); const std::vector<hipGraphNode_t>& removedDepNodes = s->GetRemovedDependencies(); bool foundInRemovedDep = false; for (auto leafNode : leafNodes) { for (auto node : removedDepNodes) { if (node == leafNode) { foundInRemovedDep = true; } } } if (foundInRemovedDep == false) { HIP_RETURN(hipErrorStreamCaptureUnjoined); } } *pGraph = s->GetCaptureGraph(); // erase the stream and move the elements to the erased spot g_captureStreams.erase(it); // end capture on all streams/events part of graph capture HIP_RETURN_DURATION(s->EndCapture()); } hipError_t hipGraphCreate(hipGraph_t* pGraph, unsigned int flags) { HIP_INIT_API(hipGraphCreate, pGraph, flags); if ((pGraph == nullptr) || (flags != 0)) { HIP_RETURN(hipErrorInvalidValue); } *pGraph = new ihipGraph(); HIP_RETURN(hipSuccess); } hipError_t hipGraphDestroy(hipGraph_t graph) { HIP_INIT_API(hipGraphDestroy, graph); if (graph == nullptr) { HIP_RETURN(hipErrorInvalidValue); } // if graph is not valid its destroyed already if (!ihipGraph::isGraphValid(graph)) { HIP_RETURN(hipErrorInvalidValue); } delete graph; HIP_RETURN(hipSuccess); } hipError_t hipGraphAddKernelNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies, const hipKernelNodeParams* pNodeParams) { HIP_INIT_API(hipGraphAddKernelNode, pGraphNode, graph, pDependencies, numDependencies, pNodeParams); if (pGraphNode == nullptr || graph == nullptr || pNodeParams == nullptr || (numDependencies > 0 && pDependencies == nullptr)) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN_DURATION( ihipGraphAddKernelNode(pGraphNode, graph, pDependencies, numDependencies, pNodeParams)); } hipError_t hipGraphAddMemcpyNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies, const hipMemcpy3DParms* pCopyParams) { HIP_INIT_API(hipGraphAddMemcpyNode, pGraphNode, graph, pDependencies, numDependencies, pCopyParams); if (pGraphNode == nullptr || graph == nullptr || pCopyParams == nullptr || (numDependencies > 0 && pDependencies == nullptr)) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN_DURATION( ihipGraphAddMemcpyNode(pGraphNode, graph, pDependencies, numDependencies, pCopyParams)); } hipError_t hipGraphAddMemcpyNode1D(hipGraphNode_t* pGraphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies, void* dst, const void* src, size_t count, hipMemcpyKind kind) { HIP_INIT_API(hipGraphAddMemcpyNode1D, pGraphNode, graph, pDependencies, numDependencies, dst, src, count, kind); if (pGraphNode == nullptr || graph == nullptr || (numDependencies > 0 && pDependencies == nullptr)) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN_DURATION(ihipGraphAddMemcpyNode1D(pGraphNode, graph, pDependencies, numDependencies, dst, src, count, kind)); } hipError_t hipGraphMemcpyNodeSetParams1D(hipGraphNode_t node, void* dst, const void* src, size_t count, hipMemcpyKind kind) { HIP_INIT_API(hipGraphMemcpyNodeSetParams1D, node, dst, src, count, kind); if (node == nullptr || dst == nullptr || src == nullptr || count == 0 || src == dst ) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphMemcpyNode1D*>(node)->SetParams(dst, src, count, kind)); } hipError_t hipGraphExecMemcpyNodeSetParams1D(hipGraphExec_t hGraphExec, hipGraphNode_t node, void* dst, const void* src, size_t count, hipMemcpyKind kind) { HIP_INIT_API(hipGraphExecMemcpyNodeSetParams1D, hGraphExec, node, dst, src, count, kind); if (hGraphExec == nullptr || node == nullptr || dst == nullptr || src == nullptr || count == 0 || src == dst ) { HIP_RETURN(hipErrorInvalidValue); } hipGraphNode_t clonedNode = hGraphExec->GetClonedNode(node); if (clonedNode == nullptr) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphMemcpyNode1D*>(clonedNode)->SetParams(dst, src, count, kind)); } hipError_t hipGraphAddMemsetNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies, const hipMemsetParams* pMemsetParams) { HIP_INIT_API(hipGraphAddMemsetNode, pGraphNode, graph, pDependencies, numDependencies, pMemsetParams); if (pGraphNode == nullptr || graph == nullptr || (numDependencies > 0 && pDependencies == nullptr)) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN_DURATION( ihipGraphAddMemsetNode(pGraphNode, graph, pDependencies, numDependencies, pMemsetParams)); } hipError_t hipGraphAddEmptyNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies) { HIP_INIT_API(hipGraphAddEmptyNode, pGraphNode, graph, pDependencies, numDependencies); if (pGraphNode == nullptr || graph == nullptr || (numDependencies > 0 && pDependencies == nullptr)) { HIP_RETURN(hipErrorInvalidValue); } *pGraphNode = new hipGraphEmptyNode(); hipError_t status = ihipGraphAddNode(*pGraphNode, graph, pDependencies, numDependencies); HIP_RETURN(status); } hipError_t hipGraphAddChildGraphNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies, hipGraph_t childGraph) { HIP_INIT_API(hipGraphAddChildGraphNode, pGraphNode, pDependencies, numDependencies, childGraph); if (pGraphNode == nullptr || graph == nullptr || (numDependencies > 0 && pDependencies == nullptr) || childGraph == nullptr) { HIP_RETURN(hipErrorInvalidValue); } *pGraphNode = new hipChildGraphNode(childGraph); hipError_t status = ihipGraphAddNode(*pGraphNode, graph, pDependencies, numDependencies); HIP_RETURN(status); } hipError_t ihipGraphInstantiate(hipGraphExec_t* pGraphExec, hipGraph_t graph) { if (pGraphExec == nullptr || graph == nullptr) { HIP_RETURN(hipErrorInvalidValue); } std::unordered_map<Node, Node> clonedNodes; hipGraph_t clonedGraph = graph->clone(clonedNodes); if (clonedGraph == nullptr) { HIP_RETURN(hipErrorInvalidValue); } std::vector<std::vector<Node>> parallelLists; std::unordered_map<Node, std::vector<Node>> nodeWaitLists; clonedGraph->GetRunList(parallelLists, nodeWaitLists); std::vector<Node> levelOrder; clonedGraph->LevelOrder(levelOrder); *pGraphExec = new hipGraphExec(levelOrder, parallelLists, nodeWaitLists, clonedNodes); if (*pGraphExec != nullptr) { return (*pGraphExec)->Init(); } else { return hipErrorOutOfMemory; } } hipError_t hipGraphInstantiate(hipGraphExec_t* pGraphExec, hipGraph_t graph, hipGraphNode_t* pErrorNode, char* pLogBuffer, size_t bufferSize) { HIP_INIT_API(hipGraphInstantiate, pGraphExec, graph); HIP_RETURN_DURATION(ihipGraphInstantiate(pGraphExec, graph)); } hipError_t hipGraphInstantiateWithFlags(hipGraphExec_t* pGraphExec, hipGraph_t graph, unsigned long long flags) { HIP_INIT_API(hipGraphInstantiateWithFlags, pGraphExec, graph, flags); if (pGraphExec == nullptr || graph == nullptr) { HIP_RETURN(hipErrorInvalidValue); } //invalid flag check if (flags != hipGraphInstantiateFlagAutoFreeOnLaunch){ HIP_RETURN(hipErrorInvalidValue); } // enable when change is merged to hip // if (flags == hipGraphInstantiateFlagAutoFreeOnLaunch) { // Free any unfreed memory allocations before the graph is relaunched //} HIP_RETURN_DURATION(ihipGraphInstantiate(pGraphExec, graph)); } hipError_t hipGraphExecDestroy(hipGraphExec_t pGraphExec) { HIP_INIT_API(hipGraphExecDestroy, pGraphExec); if (pGraphExec == nullptr) { HIP_RETURN(hipErrorInvalidValue); } delete pGraphExec; HIP_RETURN(hipSuccess); } hipError_t ihipGraphLaunch(hipGraphExec_t graphExec, hipStream_t stream) { if (!hip::isValid(stream)) { return hipErrorInvalidValue; } return graphExec->Run(stream); } hipError_t hipGraphLaunch(hipGraphExec_t graphExec, hipStream_t stream) { HIP_INIT_API(hipGraphLaunch, graphExec, stream); if (graphExec == nullptr || !hip::isValid(stream) || !hipGraphExec::isGraphExecValid(graphExec)) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN_DURATION(ihipGraphLaunch(graphExec, stream)); } hipError_t hipGraphGetNodes(hipGraph_t graph, hipGraphNode_t* nodes, size_t* numNodes) { HIP_INIT_API(hipGraphGetNodes, graph, nodes, numNodes); if (graph == nullptr || numNodes == nullptr) { HIP_RETURN(hipErrorInvalidValue); } const std::vector<hipGraphNode_t>& graphNodes = graph->GetNodes(); if (nodes == nullptr) { *numNodes = graphNodes.size(); HIP_RETURN(hipSuccess); } else if (*numNodes <= graphNodes.size()) { for (int i = 0; i < *numNodes; i++) { nodes[i] = graphNodes[i]; } } else { for (int i = 0; i < graphNodes.size(); i++) { nodes[i] = graphNodes[i]; } for (int i = graphNodes.size(); i < *numNodes; i++) { nodes[i] = nullptr; } *numNodes = graphNodes.size(); } HIP_RETURN(hipSuccess); } hipError_t hipGraphGetRootNodes(hipGraph_t graph, hipGraphNode_t* pRootNodes, size_t* pNumRootNodes) { HIP_INIT_API(hipGraphGetRootNodes, graph, pRootNodes, pNumRootNodes); if (graph == nullptr || pNumRootNodes == nullptr) { HIP_RETURN(hipErrorInvalidValue); } const std::vector<hipGraphNode_t> nodes = graph->GetRootNodes(); if (pRootNodes == nullptr) { *pNumRootNodes = nodes.size(); HIP_RETURN(hipSuccess); } else if (*pNumRootNodes <= nodes.size()) { for (int i = 0; i < *pNumRootNodes; i++) { pRootNodes[i] = nodes[i]; } } else { for (int i = 0; i < nodes.size(); i++) { pRootNodes[i] = nodes[i]; } for (int i = nodes.size(); i < *pNumRootNodes; i++) { pRootNodes[i] = nullptr; } *pNumRootNodes = nodes.size(); } HIP_RETURN(hipSuccess); } hipError_t hipGraphKernelNodeGetParams(hipGraphNode_t node, hipKernelNodeParams* pNodeParams) { HIP_INIT_API(hipGraphKernelNodeGetParams, node, pNodeParams); if (node == nullptr || pNodeParams == nullptr) { HIP_RETURN(hipErrorInvalidValue); } reinterpret_cast<hipGraphKernelNode*>(node)->GetParams(pNodeParams); HIP_RETURN(hipSuccess); } hipError_t hipGraphKernelNodeSetParams(hipGraphNode_t node, const hipKernelNodeParams* pNodeParams) { HIP_INIT_API(hipGraphKernelNodeSetParams, node, pNodeParams); if (node == nullptr || pNodeParams == nullptr || pNodeParams->func == nullptr) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphKernelNode*>(node)->SetParams(pNodeParams)); } hipError_t hipGraphMemcpyNodeGetParams(hipGraphNode_t node, hipMemcpy3DParms* pNodeParams) { HIP_INIT_API(hipGraphMemcpyNodeGetParams, node, pNodeParams); if (node == nullptr || pNodeParams == nullptr) { HIP_RETURN(hipErrorInvalidValue); } reinterpret_cast<hipGraphMemcpyNode*>(node)->GetParams(pNodeParams); HIP_RETURN(hipSuccess); } hipError_t hipGraphMemcpyNodeSetParams(hipGraphNode_t node, const hipMemcpy3DParms* pNodeParams) { HIP_INIT_API(hipGraphMemcpyNodeSetParams, node, pNodeParams); if (node == nullptr || pNodeParams == nullptr) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphMemcpyNode*>(node)->SetParams(pNodeParams)); } hipError_t hipGraphExecMemcpyNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t node, hipMemcpy3DParms* pNodeParams) { HIP_INIT_API(hipGraphExecMemcpyNodeSetParams, hGraphExec, node, pNodeParams); if (hGraphExec == nullptr || node == nullptr) { HIP_RETURN(hipErrorInvalidValue); } if (ihipMemcpy3D_validate(pNodeParams) != hipSuccess) { HIP_RETURN(hipErrorInvalidValue); } // Check if pNodeParams passed is a empty struct if (((pNodeParams->srcArray == 0) && (pNodeParams->srcPtr.ptr == nullptr)) || ((pNodeParams->dstArray == 0) && (pNodeParams->dstPtr.ptr == nullptr))) { HIP_RETURN(hipErrorInvalidValue); } hipGraphNode_t clonedNode = hGraphExec->GetClonedNode(node); if (clonedNode == nullptr) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphMemcpyNode*>(clonedNode)->SetParams(pNodeParams)); } hipError_t hipGraphMemsetNodeGetParams(hipGraphNode_t node, hipMemsetParams* pNodeParams) { HIP_INIT_API(hipGraphMemsetNodeGetParams, node, pNodeParams); if (node == nullptr || pNodeParams == nullptr) { HIP_RETURN(hipErrorInvalidValue); } reinterpret_cast<hipGraphMemsetNode*>(node)->GetParams(pNodeParams); HIP_RETURN(hipSuccess); } hipError_t hipGraphMemsetNodeSetParams(hipGraphNode_t node, const hipMemsetParams* pNodeParams) { HIP_INIT_API(hipGraphMemsetNodeSetParams, node, pNodeParams); if (node == nullptr || pNodeParams == nullptr) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphMemsetNode*>(node)->SetParams(pNodeParams)); } hipError_t hipGraphExecMemsetNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t node, const hipMemsetParams* pNodeParams) { HIP_INIT_API(hipGraphExecMemsetNodeSetParams, hGraphExec, node, pNodeParams); if (hGraphExec == nullptr || node == nullptr || pNodeParams == nullptr || pNodeParams->dst == nullptr) { HIP_RETURN(hipErrorInvalidValue); } if (ihipGraphMemsetParams_validate(pNodeParams) != hipSuccess) { HIP_RETURN(hipErrorInvalidValue); } hipGraphNode_t clonedNode = hGraphExec->GetClonedNode(node); if (clonedNode == nullptr) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphMemsetNode*>(clonedNode)->SetParams(pNodeParams)); } hipError_t hipGraphAddDependencies(hipGraph_t graph, const hipGraphNode_t* from, const hipGraphNode_t* to, size_t numDependencies) { HIP_INIT_API(hipGraphAddDependencies, graph, from, to, numDependencies); if (graph == nullptr) { HIP_RETURN(hipErrorInvalidValue); } if (numDependencies == 0) { HIP_RETURN(hipSuccess); } else if (from == nullptr || to == nullptr) { HIP_RETURN(hipErrorInvalidValue); } for (size_t i = 0; i < numDependencies; i++) { // When the same node is specified for both from and to if (from[i] == to[i]) { HIP_RETURN(hipErrorInvalidValue); } // When the same edge added from->to return invalid value const std::vector<Node>& edges = from[i]->GetEdges(); for (auto edge : edges) { if (edge == to[i]) { HIP_RETURN(hipErrorInvalidValue); } } from[i]->AddEdge(to[i]); } HIP_RETURN(hipSuccess); } hipError_t hipGraphExecKernelNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t node, const hipKernelNodeParams* pNodeParams) { HIP_INIT_API(hipGraphExecKernelNodeSetParams, hGraphExec, node, pNodeParams); if (hGraphExec == nullptr || node == nullptr || pNodeParams == nullptr || pNodeParams->func == nullptr) { HIP_RETURN(hipErrorInvalidValue); } hipGraphNode_t clonedNode = hGraphExec->GetClonedNode(node); if (clonedNode == nullptr) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphKernelNode*>(clonedNode)->SetParams(pNodeParams)); } hipError_t hipGraphChildGraphNodeGetGraph(hipGraphNode_t node, hipGraph_t* pGraph) { HIP_INIT_API(hipGraphChildGraphNodeGetGraph, node, pGraph); if (node == nullptr || pGraph == nullptr) { HIP_RETURN(hipErrorInvalidValue); } *pGraph = reinterpret_cast<hipChildGraphNode*>(node)->GetChildGraph(); //if the node count is larger than 0, the current node is a parent if (*pGraph == nullptr || reinterpret_cast<ihipGraph*>(pGraph)->GetNodeCount() > 0) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(hipSuccess); } hipError_t hipGraphExecChildGraphNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t node, hipGraph_t childGraph) { HIP_INIT_API(hipGraphExecChildGraphNodeSetParams, hGraphExec, node, childGraph); if (hGraphExec == nullptr || node == nullptr || childGraph == nullptr || !ihipGraph::isGraphValid(childGraph)) { HIP_RETURN(hipErrorInvalidValue); } if (childGraph == node->GetParentGraph()) { HIP_RETURN(hipErrorUnknown); } hipGraphNode_t hipErrorNode_out; hipGraphExecUpdateResult updateResult_out; // Check if this instantiated graph is updatable. All restrictions in hipGraphExecUpdate() apply. if (hipGraphExecUpdate(hGraphExec, childGraph, &hipErrorNode_out, &updateResult_out) == hipErrorGraphExecUpdateFailure) { HIP_RETURN(hipErrorUnknown); } hipGraphNode_t clonedNode = hGraphExec->GetClonedNode(node); if (clonedNode == nullptr) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipChildGraphNode*>(clonedNode)->SetParams(childGraph)); } hipError_t hipStreamGetCaptureInfo(hipStream_t stream, hipStreamCaptureStatus* pCaptureStatus, unsigned long long* pId) { HIP_INIT_API(hipStreamGetCaptureInfo, stream, pCaptureStatus, pId); if (pCaptureStatus == nullptr || !hip::isValid(stream)) { HIP_RETURN(hipErrorInvalidValue); } if (stream == nullptr) { HIP_RETURN(hipErrorUnknown); } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); *pCaptureStatus = s->GetCaptureStatus(); if (*pCaptureStatus == hipStreamCaptureStatusActive) { pId = reinterpret_cast<unsigned long long*>(s->GetCaptureID()); } HIP_RETURN(hipSuccess); } hipError_t hipStreamGetCaptureInfo_v2(hipStream_t stream, hipStreamCaptureStatus* captureStatus_out, unsigned long long* id_out, hipGraph_t* graph_out, const hipGraphNode_t** dependencies_out, size_t* numDependencies_out) { HIP_INIT_API(hipStreamGetCaptureInfo_v2, stream, captureStatus_out, id_out, graph_out, dependencies_out, numDependencies_out); if (captureStatus_out == nullptr) { HIP_RETURN(hipErrorInvalidValue); } if (stream == nullptr) { HIP_RETURN(hipErrorUnknown); } if (!hip::isValid(stream)) { HIP_RETURN(hipErrorInvalidValue); } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); *captureStatus_out = s->GetCaptureStatus(); if (*captureStatus_out == hipStreamCaptureStatusActive) { if (id_out != nullptr) { *id_out = s->GetCaptureID(); } if (graph_out != nullptr) { *graph_out = s->GetCaptureGraph(); } if (dependencies_out != nullptr && numDependencies_out != nullptr) { auto t= s->GetLastCapturedNodes().data(); *dependencies_out = s->GetLastCapturedNodes().data(); *numDependencies_out = s->GetLastCapturedNodes().size(); } } HIP_RETURN(hipSuccess); } hipError_t hipStreamUpdateCaptureDependencies(hipStream_t stream, hipGraphNode_t* dependencies, size_t numDependencies, unsigned int flags) { HIP_INIT_API(hipStreamUpdateCaptureDependencies, stream, dependencies, numDependencies, flags); if (!hip::isValid(stream)) { HIP_RETURN(hipErrorInvalidValue); } hip::Stream* s = reinterpret_cast<hip::Stream*>(stream); if (s->GetCaptureStatus() == hipStreamCaptureStatusActive) { HIP_RETURN(hipErrorIllegalState); } if (numDependencies > 0 && dependencies == nullptr) { HIP_RETURN(hipErrorInvalidValue); } std::vector<hipGraphNode_t> depNodes; for (int i = 0; i < numDependencies; i++) { depNodes.push_back(dependencies[i]); } if (flags == hipStreamAddCaptureDependencies) { s->AddCrossCapturedNode(depNodes); } else if (flags == hipStreamSetCaptureDependencies) { bool replace = true; s->AddCrossCapturedNode(depNodes, replace); } HIP_RETURN(hipSuccess); } hipError_t hipGraphRemoveDependencies(hipGraph_t graph, const hipGraphNode_t* from, const hipGraphNode_t* to, size_t numDependencies) { HIP_INIT_API(hipGraphRemoveDependencies, graph, from, to, numDependencies); if (graph == nullptr || from == nullptr || to == nullptr) { HIP_RETURN(hipErrorInvalidValue); } for (size_t i = 0; i < numDependencies; i++) { if (from[i]->RemoveEdge(to[i]) == false) { HIP_RETURN(hipErrorInvalidValue); } } HIP_RETURN(hipSuccess); } hipError_t hipGraphGetEdges(hipGraph_t graph, hipGraphNode_t* from, hipGraphNode_t* to, size_t* numEdges) { HIP_INIT_API(hipGraphGetEdges, graph, from, to, numEdges); if (graph == nullptr || numEdges == nullptr || (from == nullptr && to != nullptr) || (to == nullptr && from != nullptr)) { HIP_RETURN(hipErrorInvalidValue); } const std::vector<std::pair<Node, Node>> edges = graph->GetEdges(); // returns only the number of edges in numEdges when from and to are null if (from == nullptr && to == nullptr) { *numEdges = edges.size(); HIP_RETURN(hipSuccess); } else if (*numEdges <= edges.size()) { for (int i = 0; i < *numEdges; i++) { from[i] = edges[i].first; to[i] = edges[i].second; } } else { for (int i = 0; i < edges.size(); i++) { from[i] = edges[i].first; to[i] = edges[i].second; } // If numEdges > actual number of edges, the remaining entries in from and to will be set to // NULL for (int i = edges.size(); i < *numEdges; i++) { from[i] = nullptr; to[i] = nullptr; } *numEdges = edges.size(); } HIP_RETURN(hipSuccess); } hipError_t hipGraphNodeGetDependencies(hipGraphNode_t node, hipGraphNode_t* pDependencies, size_t* pNumDependencies) { HIP_INIT_API(hipGraphNodeGetDependencies, node, pDependencies, pNumDependencies); if (node == nullptr || pNumDependencies == nullptr) { HIP_RETURN(hipErrorInvalidValue); } const std::vector<hipGraphNode_t>& dependencies = node->GetDependencies(); if (pDependencies == NULL) { *pNumDependencies = dependencies.size(); HIP_RETURN(hipSuccess); } else if (*pNumDependencies <= dependencies.size()) { for (int i = 0; i < *pNumDependencies; i++) { pDependencies[i] = dependencies[i]; } } else { for (int i = 0; i < dependencies.size(); i++) { pDependencies[i] = dependencies[i]; } // pNumDependencies > actual number of dependencies, the remaining entries in pDependencies will // be set to NULL for (int i = dependencies.size(); i < *pNumDependencies; i++) { pDependencies[i] = nullptr; } *pNumDependencies = dependencies.size(); } HIP_RETURN(hipSuccess); } hipError_t hipGraphNodeGetDependentNodes(hipGraphNode_t node, hipGraphNode_t* pDependentNodes, size_t* pNumDependentNodes) { HIP_INIT_API(hipGraphNodeGetDependentNodes, node, pDependentNodes, pNumDependentNodes); if (node == nullptr || pNumDependentNodes == nullptr) { HIP_RETURN(hipErrorInvalidValue); } const std::vector<hipGraphNode_t>& dependents = node->GetEdges(); if (pDependentNodes == NULL) { *pNumDependentNodes = dependents.size(); HIP_RETURN(hipSuccess); } else if (*pNumDependentNodes <= dependents.size()) { for (int i = 0; i < *pNumDependentNodes; i++) { pDependentNodes[i] = dependents[i]; } } else { for (int i = 0; i < dependents.size(); i++) { pDependentNodes[i] = dependents[i]; } // pNumDependentNodes > actual number of dependents, the remaining entries in pDependentNodes // will be set to NULL for (int i = dependents.size(); i < *pNumDependentNodes; i++) { pDependentNodes[i] = nullptr; } *pNumDependentNodes = dependents.size(); } HIP_RETURN(hipSuccess); } hipError_t hipGraphNodeGetType(hipGraphNode_t node, hipGraphNodeType* pType) { HIP_INIT_API(hipGraphNodeGetType, node, pType); if (node == nullptr || pType == nullptr) { HIP_RETURN(hipErrorInvalidValue); } *pType = node->GetType(); HIP_RETURN(hipSuccess); } hipError_t hipGraphDestroyNode(hipGraphNode_t node) { HIP_INIT_API(hipGraphDestroyNode, node); if (node == nullptr || !hipGraphNode::isNodeValid(node)) { HIP_RETURN(hipErrorInvalidValue); } node->GetParentGraph()->RemoveNode(node); // Takescare of removing its dependencies and dependent nodes delete node; HIP_RETURN(hipSuccess); } hipError_t hipGraphClone(hipGraph_t* pGraphClone, hipGraph_t originalGraph) { HIP_INIT_API(hipGraphClone, pGraphClone, originalGraph); if (originalGraph == nullptr || pGraphClone == nullptr) { HIP_RETURN(hipErrorInvalidValue); } if (!ihipGraph::isGraphValid(originalGraph)) { HIP_RETURN(hipErrorInvalidValue); } *pGraphClone = originalGraph->clone(); HIP_RETURN(hipSuccess); } hipError_t hipGraphNodeFindInClone(hipGraphNode_t* pNode, hipGraphNode_t originalNode, hipGraph_t clonedGraph) { HIP_INIT_API(hipGraphNodeFindInClone, pNode, originalNode, clonedGraph); if (pNode == nullptr || originalNode == nullptr || clonedGraph == nullptr) { HIP_RETURN(hipErrorInvalidValue); } if (clonedGraph->getOriginalGraph() == nullptr) { HIP_RETURN(hipErrorInvalidValue); } for (auto node : clonedGraph->GetNodes()) { if (node->GetID() == originalNode->GetID()) { *pNode = node; HIP_RETURN(hipSuccess); } } HIP_RETURN(hipErrorInvalidValue); } hipError_t hipGraphAddMemcpyNodeFromSymbol(hipGraphNode_t* pGraphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies, void* dst, const void* symbol, size_t count, size_t offset, hipMemcpyKind kind) { HIP_INIT_API(hipGraphAddMemcpyNodeFromSymbol, pGraphNode, graph, pDependencies, numDependencies, dst, symbol, count, offset, kind); size_t sym_size = 0; hipDeviceptr_t device_ptr = nullptr; hipError_t status = ihipMemcpySymbol_validate(symbol, count, offset, sym_size, device_ptr); if (status != hipSuccess) { HIP_RETURN(status); } *pGraphNode = new hipGraphMemcpyNodeFromSymbol(dst, symbol, count, offset, kind); status = ihipGraphAddNode(*pGraphNode, graph, pDependencies, numDependencies); HIP_RETURN(status); } hipError_t hipGraphMemcpyNodeSetParamsFromSymbol(hipGraphNode_t node, void* dst, const void* symbol, size_t count, size_t offset, hipMemcpyKind kind) { HIP_INIT_API(hipGraphMemcpyNodeSetParamsFromSymbol, node, dst, symbol, count, offset, kind); if (symbol == nullptr) { HIP_RETURN(hipErrorInvalidSymbol); } if (node == nullptr || dst == nullptr || count == 0 || symbol == dst) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphMemcpyNodeFromSymbol*>(node)->SetParams(dst, symbol, count, offset, kind)); } hipError_t hipGraphExecMemcpyNodeSetParamsFromSymbol(hipGraphExec_t hGraphExec, hipGraphNode_t node, void* dst, const void* symbol, size_t count, size_t offset, hipMemcpyKind kind) { HIP_INIT_API(hipGraphExecMemcpyNodeSetParamsFromSymbol, hGraphExec, node, dst, symbol, count, offset, kind); if (symbol == nullptr) { HIP_RETURN(hipErrorInvalidSymbol); } if (hGraphExec == nullptr || node == nullptr || dst == nullptr || count == 0 || symbol == dst) { HIP_RETURN(hipErrorInvalidValue); } hipGraphNode_t clonedNode = hGraphExec->GetClonedNode(node); if (clonedNode == nullptr) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphMemcpyNodeFromSymbol*>(clonedNode) ->SetParams(dst, symbol, count, offset, kind)); } hipError_t hipGraphAddMemcpyNodeToSymbol(hipGraphNode_t* pGraphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies, const void* symbol, const void* src, size_t count, size_t offset, hipMemcpyKind kind) { HIP_INIT_API(hipGraphAddMemcpyNodeToSymbol, pGraphNode, graph, pDependencies, numDependencies, symbol, src, count, offset, kind); if (pGraphNode == nullptr || graph == nullptr || src == nullptr || !ihipGraph::isGraphValid(graph) || (pDependencies == nullptr && numDependencies > 0)) { HIP_RETURN(hipErrorInvalidValue); } size_t sym_size = 0; hipDeviceptr_t device_ptr = nullptr; hipError_t status = ihipMemcpySymbol_validate(symbol, count, offset, sym_size, device_ptr); if (status != hipSuccess) { HIP_RETURN(status); } *pGraphNode = new hipGraphMemcpyNodeToSymbol(symbol, src, count, offset, kind); if (*pGraphNode == nullptr) { HIP_RETURN(hipErrorInvalidValue); } status = ihipGraphAddNode(*pGraphNode, graph, pDependencies, numDependencies); HIP_RETURN(status); } hipError_t hipGraphMemcpyNodeSetParamsToSymbol(hipGraphNode_t node, const void* symbol, const void* src, size_t count, size_t offset, hipMemcpyKind kind) { HIP_INIT_API(hipGraphMemcpyNodeSetParamsToSymbol, symbol, src, count, offset, kind); if (symbol == nullptr) { HIP_RETURN(hipErrorInvalidSymbol); } if (node == nullptr || src == nullptr || count == 0 || symbol == src) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphMemcpyNodeToSymbol*>(node)->SetParams(symbol, src, count, offset, kind)); } hipError_t hipGraphExecMemcpyNodeSetParamsToSymbol(hipGraphExec_t hGraphExec, hipGraphNode_t node, const void* symbol, const void* src, size_t count, size_t offset, hipMemcpyKind kind) { HIP_INIT_API(hipGraphExecMemcpyNodeSetParamsToSymbol, hGraphExec, node, symbol, src, count, offset, kind); if (symbol == nullptr) { HIP_RETURN(hipErrorInvalidSymbol); } if (hGraphExec == nullptr || src == nullptr || node == nullptr || count == 0 || src == symbol) { HIP_RETURN(hipErrorInvalidValue); } hipGraphNode_t clonedNode = hGraphExec->GetClonedNode(node); if (clonedNode == nullptr) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphMemcpyNodeToSymbol*>(clonedNode) ->SetParams(symbol, src, count, offset, kind)); } hipError_t hipGraphAddEventRecordNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies, hipEvent_t event) { HIP_INIT_API(hipGraphAddEventRecordNode, pGraphNode, graph, pDependencies, numDependencies, event); if (graph == nullptr || (numDependencies > 0 && pDependencies == nullptr) || event == nullptr) { HIP_RETURN(hipErrorInvalidValue); } *pGraphNode = new hipGraphEventRecordNode(event); hipError_t status = ihipGraphAddNode(*pGraphNode, graph, pDependencies, numDependencies); HIP_RETURN(status); } hipError_t hipGraphEventRecordNodeGetEvent(hipGraphNode_t node, hipEvent_t* event_out) { HIP_INIT_API(hipGraphEventRecordNodeGetEvent, node, event_out); if (node == nullptr || event_out == nullptr) { HIP_RETURN(hipErrorInvalidValue); } reinterpret_cast<hipGraphEventRecordNode*>(node)->GetParams(event_out); HIP_RETURN(hipSuccess); } hipError_t hipGraphEventRecordNodeSetEvent(hipGraphNode_t node, hipEvent_t event) { HIP_INIT_API(hipGraphEventRecordNodeSetEvent, node, event); if (node == nullptr || event == nullptr) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphEventRecordNode*>(node)->SetParams(event)); } hipError_t hipGraphExecEventRecordNodeSetEvent(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, hipEvent_t event) { HIP_INIT_API(hipGraphExecEventRecordNodeSetEvent, hGraphExec, hNode, event); if (hGraphExec == nullptr || hNode == nullptr || event == nullptr) { HIP_RETURN(hipErrorInvalidValue); } hipGraphNode_t clonedNode = hGraphExec->GetClonedNode(hNode); if (clonedNode == nullptr) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphEventRecordNode*>(clonedNode)->SetParams(event)); } hipError_t hipGraphAddEventWaitNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies, hipEvent_t event) { HIP_INIT_API(hipGraphAddEventWaitNode, pGraphNode, graph, pDependencies, numDependencies, event); if (pGraphNode == nullptr || graph == nullptr || (numDependencies > 0 && pDependencies == nullptr) || event == nullptr) { HIP_RETURN(hipErrorInvalidValue); } *pGraphNode = new hipGraphEventWaitNode(event); hipError_t status = ihipGraphAddNode(*pGraphNode, graph, pDependencies, numDependencies); HIP_RETURN(status); } hipError_t hipGraphEventWaitNodeGetEvent(hipGraphNode_t node, hipEvent_t* event_out) { HIP_INIT_API(hipGraphEventWaitNodeGetEvent, node, event_out); if (node == nullptr || *event_out == nullptr) { HIP_RETURN(hipErrorInvalidValue); } reinterpret_cast<hipGraphEventWaitNode*>(node)->GetParams(event_out); HIP_RETURN(hipSuccess); } hipError_t hipGraphEventWaitNodeSetEvent(hipGraphNode_t node, hipEvent_t event) { HIP_INIT_API(hipGraphEventWaitNodeSetEvent, node, event); if (node == nullptr || event == nullptr || node->GetType() != hipGraphNodeTypeWaitEvent) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphEventWaitNode*>(node)->SetParams(event)); } hipError_t hipGraphExecEventWaitNodeSetEvent(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, hipEvent_t event) { HIP_INIT_API(hipGraphExecEventWaitNodeSetEvent, hGraphExec, hNode, event); if (hGraphExec == nullptr || hNode == nullptr || event == nullptr) { HIP_RETURN(hipErrorInvalidValue); } hipGraphNode_t clonedNode = hGraphExec->GetClonedNode(hNode); if (clonedNode == nullptr) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphEventRecordNode*>(clonedNode)->SetParams(event)); } hipError_t hipGraphAddHostNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, const hipGraphNode_t* pDependencies, size_t numDependencies, const hipHostNodeParams* pNodeParams) { HIP_INIT_API(hipGraphAddHostNode, pGraphNode, graph, pDependencies, numDependencies, pNodeParams); if (pGraphNode == nullptr || graph == nullptr || pNodeParams == nullptr || (numDependencies > 0 && pDependencies == nullptr)) { HIP_RETURN(hipErrorInvalidValue); } if (pNodeParams->fn == nullptr || pNodeParams->userData == nullptr) { HIP_RETURN(hipErrorInvalidValue); } *pGraphNode = new hipGraphHostNode(pNodeParams); hipError_t status = ihipGraphAddNode(*pGraphNode, graph, pDependencies, numDependencies); HIP_RETURN(status); } hipError_t hipGraphHostNodeGetParams(hipGraphNode_t node, hipHostNodeParams* pNodeParams) { HIP_INIT_API(hipGraphHostNodeGetParams, node, pNodeParams); if (node == nullptr || pNodeParams == nullptr || !hipGraphNode::isNodeValid(node)) { HIP_RETURN(hipErrorInvalidValue); } reinterpret_cast<hipGraphHostNode*>(node)->GetParams(pNodeParams); HIP_RETURN(hipSuccess); } hipError_t hipGraphHostNodeSetParams(hipGraphNode_t node, const hipHostNodeParams* pNodeParams) { HIP_INIT_API(hipGraphHostNodeSetParams, node, pNodeParams); if (pNodeParams->fn == nullptr || pNodeParams->userData == nullptr) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphHostNode*>(node)->SetParams(pNodeParams)); } hipError_t hipGraphExecHostNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t node, const hipHostNodeParams* pNodeParams) { HIP_INIT_API(hipGraphExecHostNodeSetParams, hGraphExec, node, pNodeParams); if (hGraphExec == nullptr || pNodeParams == nullptr || pNodeParams->fn == nullptr || pNodeParams->userData == nullptr) { HIP_RETURN(hipErrorInvalidValue); } hipGraphNode_t clonedNode = hGraphExec->GetClonedNode(node); if (clonedNode == nullptr) { HIP_RETURN(hipErrorInvalidValue); } HIP_RETURN(reinterpret_cast<hipGraphHostNode*>(clonedNode)->SetParams(pNodeParams)); } hipError_t hipGraphExecUpdate(hipGraphExec_t hGraphExec, hipGraph_t hGraph, hipGraphNode_t* hErrorNode_out, hipGraphExecUpdateResult* updateResult_out) { HIP_INIT_API(hipGraphExecUpdate, hGraphExec, hGraph, hErrorNode_out, updateResult_out); // parameter check if (hGraphExec == nullptr || hGraph == nullptr || hErrorNode_out == nullptr || updateResult_out == nullptr) { HIP_RETURN(hipErrorInvalidValue); } std::vector<Node> newGraphNodes; hGraph->LevelOrder(newGraphNodes); std::vector<Node>& oldGraphExecNodes = hGraphExec->GetNodes(); if (newGraphNodes.size() != oldGraphExecNodes.size()) { *updateResult_out = hipGraphExecUpdateErrorTopologyChanged; HIP_RETURN(hipErrorGraphExecUpdateFailure); } for (std::vector<Node>::size_type i = 0; i != newGraphNodes.size(); i++) { if (newGraphNodes[i]->GetType() == oldGraphExecNodes[i]->GetType()) { hipError_t status = oldGraphExecNodes[i]->SetParams(newGraphNodes[i]); if (status != hipSuccess) { *hErrorNode_out = newGraphNodes[i]; if (status == hipErrorInvalidDeviceFunction) { *updateResult_out = hipGraphExecUpdateErrorUnsupportedFunctionChange; } else if (status == hipErrorInvalidValue || status == hipErrorInvalidDevicePointer) { *updateResult_out = hipGraphExecUpdateErrorParametersChanged; } else { *updateResult_out = hipGraphExecUpdateErrorNotSupported; } HIP_RETURN(hipErrorGraphExecUpdateFailure); } } else { *hErrorNode_out = newGraphNodes[i]; *updateResult_out = hipGraphExecUpdateErrorNodeTypeChanged; HIP_RETURN(hipErrorGraphExecUpdateFailure); } } *updateResult_out = hipGraphExecUpdateSuccess; HIP_RETURN(hipSuccess); }
40.513636
106
0.682612
[ "vector" ]
edd22f783f03b1fbd34039cd7b00f08d34ca9fc6
10,100
cc
C++
tensorflow/contrib/lite/toco/tflite/import_test.cc
tianyapiaozi/tensorflow
fb3ce0467766a8e91f1da0ad7ada7c24fde7a73a
[ "Apache-2.0" ]
71
2017-05-25T16:02:15.000Z
2021-06-09T16:08:08.000Z
tensorflow/contrib/lite/toco/tflite/import_test.cc
shrikunjsarda/tensorflow
7e8927e7af0c51ac20a63bd4eab6ff83df1a39ae
[ "Apache-2.0" ]
133
2017-04-26T16:49:49.000Z
2019-10-15T11:39:26.000Z
tensorflow/contrib/lite/toco/tflite/import_test.cc
shrikunjsarda/tensorflow
7e8927e7af0c51ac20a63bd4eab6ff83df1a39ae
[ "Apache-2.0" ]
31
2018-09-11T02:17:17.000Z
2021-12-15T10:33:35.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/contrib/lite/toco/tflite/import.h" #include "flatbuffers/flexbuffers.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorflow/contrib/lite/schema/schema_generated.h" #include "tensorflow/contrib/lite/version.h" namespace toco { namespace tflite { namespace { using ::testing::ElementsAre; using flatbuffers::Offset; using flatbuffers::Vector; class ImportTest : public ::testing::Test { protected: template <typename T> Offset<Vector<unsigned char>> CreateDataVector(const std::vector<T>& data) { return builder_.CreateVector(reinterpret_cast<const uint8_t*>(data.data()), sizeof(T) * data.size()); } Offset<Vector<Offset<::tflite::Buffer>>> BuildBuffers() { auto buf0 = ::tflite::CreateBuffer(builder_, CreateDataVector<float>({})); auto buf1 = ::tflite::CreateBuffer( builder_, CreateDataVector<float>({1.0f, 2.0f, 3.0f, 4.0f})); auto buf2 = ::tflite::CreateBuffer(builder_, CreateDataVector<float>({3.0f, 4.0f})); return builder_.CreateVector( std::vector<Offset<::tflite::Buffer>>({buf0, buf1, buf2})); } Offset<Vector<Offset<::tflite::Tensor>>> BuildTensors() { auto q = ::tflite::CreateQuantizationParameters( builder_, /*min=*/builder_.CreateVector<float>({0.1f}), /*max=*/builder_.CreateVector<float>({0.2f}), /*scale=*/builder_.CreateVector<float>({0.3f}), /*zero_point=*/builder_.CreateVector<int64_t>({100ll})); auto t1 = ::tflite::CreateTensor(builder_, builder_.CreateVector<int>({1, 2, 2}), ::tflite::TensorType_FLOAT32, 1, builder_.CreateString("tensor_one"), q); auto t2 = ::tflite::CreateTensor(builder_, builder_.CreateVector<int>({2, 1}), ::tflite::TensorType_FLOAT32, 2, builder_.CreateString("tensor_two"), q); return builder_.CreateVector( std::vector<Offset<::tflite::Tensor>>({t1, t2})); } Offset<Vector<Offset<::tflite::OperatorCode>>> BuildOpCodes( std::initializer_list<::tflite::BuiltinOperator> op_codes) { std::vector<Offset<::tflite::OperatorCode>> op_codes_vector; for (auto op : op_codes) { op_codes_vector.push_back(::tflite::CreateOperatorCode(builder_, op, 0)); } return builder_.CreateVector(op_codes_vector); } Offset<Vector<Offset<::tflite::OperatorCode>>> BuildOpCodes() { return BuildOpCodes({::tflite::BuiltinOperator_MAX_POOL_2D, ::tflite::BuiltinOperator_CONV_2D}); } Offset<Vector<Offset<::tflite::Operator>>> BuildOperators( std::initializer_list<int> inputs, std::initializer_list<int> outputs) { auto is = builder_.CreateVector<int>(inputs); if (inputs.size() == 0) is = 0; auto os = builder_.CreateVector<int>(outputs); if (outputs.size() == 0) os = 0; auto op = ::tflite::CreateOperator( builder_, 0, is, os, ::tflite::BuiltinOptions_Conv2DOptions, ::tflite::CreateConv2DOptions(builder_, ::tflite::Padding_VALID, 1, 1, ::tflite::ActivationFunctionType_NONE) .Union(), /*custom_options=*/0, ::tflite::CustomOptionsFormat_FLEXBUFFERS); return builder_.CreateVector(std::vector<Offset<::tflite::Operator>>({op})); } Offset<Vector<Offset<::tflite::Operator>>> BuildOperators() { return BuildOperators({0}, {1}); } Offset<Vector<Offset<::tflite::SubGraph>>> BuildSubGraphs( Offset<Vector<Offset<::tflite::Tensor>>> tensors, Offset<Vector<Offset<::tflite::Operator>>> operators, int num_sub_graphs = 1) { std::vector<int32_t> inputs = {0}; std::vector<int32_t> outputs = {1}; std::vector<Offset<::tflite::SubGraph>> v; for (int i = 0; i < num_sub_graphs; ++i) { v.push_back(::tflite::CreateSubGraph( builder_, tensors, builder_.CreateVector(inputs), builder_.CreateVector(outputs), operators, builder_.CreateString("subgraph"))); } return builder_.CreateVector(v); } // This is a very simplistic model. We are not interested in testing all the // details here, since tf.mini's testing framework will be exercising all the // conversions multiple times, and the conversion of operators is tested by // separate unittests. void BuildTestModel() { auto buffers = BuildBuffers(); auto tensors = BuildTensors(); auto opcodes = BuildOpCodes(); auto operators = BuildOperators(); auto subgraphs = BuildSubGraphs(tensors, operators); auto s = builder_.CreateString(""); ::tflite::FinishModelBuffer( builder_, ::tflite::CreateModel(builder_, TFLITE_SCHEMA_VERSION, opcodes, subgraphs, s, buffers)); input_model_ = ::tflite::GetModel(builder_.GetBufferPointer()); } string InputModelAsString() { return string(reinterpret_cast<char*>(builder_.GetBufferPointer()), builder_.GetSize()); } flatbuffers::FlatBufferBuilder builder_; const ::tflite::Model* input_model_ = nullptr; }; TEST_F(ImportTest, LoadTensorsTable) { BuildTestModel(); details::TensorsTable tensors; details::LoadTensorsTable(*input_model_, &tensors); EXPECT_THAT(tensors, ElementsAre("tensor_one", "tensor_two")); } TEST_F(ImportTest, LoadOperatorsTable) { BuildTestModel(); details::OperatorsTable operators; details::LoadOperatorsTable(*input_model_, &operators); EXPECT_THAT(operators, ElementsAre("MAX_POOL_2D", "CONV_2D")); } TEST_F(ImportTest, Tensors) { BuildTestModel(); auto model = Import(ModelFlags(), InputModelAsString()); ASSERT_GT(model->HasArray("tensor_one"), 0); Array& a1 = model->GetArray("tensor_one"); EXPECT_EQ(ArrayDataType::kFloat, a1.data_type); EXPECT_THAT(a1.GetBuffer<ArrayDataType::kFloat>().data, ElementsAre(1.0f, 2.0f, 3.0f, 4.0f)); ASSERT_TRUE(a1.has_shape()); EXPECT_THAT(a1.shape().dims(), ElementsAre(1, 2, 2)); const auto& mm = a1.minmax; ASSERT_TRUE(mm.get()); EXPECT_FLOAT_EQ(0.1, mm->min); EXPECT_FLOAT_EQ(0.2, mm->max); const auto& q = a1.quantization_params; ASSERT_TRUE(q.get()); EXPECT_FLOAT_EQ(0.3, q->scale); EXPECT_EQ(100, q->zero_point); } TEST_F(ImportTest, NoBuffers) { auto buffers = 0; auto tensors = BuildTensors(); auto opcodes = BuildOpCodes(); auto operators = BuildOperators(); auto subgraphs = BuildSubGraphs(tensors, operators); auto comment = builder_.CreateString(""); ::tflite::FinishModelBuffer( builder_, ::tflite::CreateModel(builder_, TFLITE_SCHEMA_VERSION, opcodes, subgraphs, comment, buffers)); EXPECT_DEATH(Import(ModelFlags(), InputModelAsString()), "Missing 'buffers' section."); } TEST_F(ImportTest, NoInputs) { auto buffers = BuildBuffers(); auto tensors = BuildTensors(); auto opcodes = BuildOpCodes(); auto operators = BuildOperators({}, {1}); auto subgraphs = BuildSubGraphs(tensors, operators); auto comment = builder_.CreateString(""); ::tflite::FinishModelBuffer( builder_, ::tflite::CreateModel(builder_, TFLITE_SCHEMA_VERSION, opcodes, subgraphs, comment, buffers)); EXPECT_DEATH(Import(ModelFlags(), InputModelAsString()), "Missing 'inputs' for operator."); } TEST_F(ImportTest, NoOutputs) { auto buffers = BuildBuffers(); auto tensors = BuildTensors(); auto opcodes = BuildOpCodes(); auto operators = BuildOperators({0}, {}); auto subgraphs = BuildSubGraphs(tensors, operators); auto comment = builder_.CreateString(""); ::tflite::FinishModelBuffer( builder_, ::tflite::CreateModel(builder_, TFLITE_SCHEMA_VERSION, opcodes, subgraphs, comment, buffers)); EXPECT_DEATH(Import(ModelFlags(), InputModelAsString()), "Missing 'outputs' for operator."); } TEST_F(ImportTest, InvalidOpCode) { auto buffers = BuildBuffers(); auto tensors = BuildTensors(); auto opcodes = BuildOpCodes({static_cast<::tflite::BuiltinOperator>(-1), ::tflite::BuiltinOperator_CONV_2D}); auto operators = BuildOperators(); auto subgraphs = BuildSubGraphs(tensors, operators); auto comment = builder_.CreateString(""); ::tflite::FinishModelBuffer( builder_, ::tflite::CreateModel(builder_, TFLITE_SCHEMA_VERSION, opcodes, subgraphs, comment, buffers)); EXPECT_DEATH(Import(ModelFlags(), InputModelAsString()), "Operator id '-1' is out of range."); } TEST_F(ImportTest, MultipleSubGraphs) { auto buffers = BuildBuffers(); auto tensors = BuildTensors(); auto opcodes = BuildOpCodes(); auto operators = BuildOperators(); auto subgraphs = BuildSubGraphs(tensors, operators, 2); auto comment = builder_.CreateString(""); ::tflite::FinishModelBuffer( builder_, ::tflite::CreateModel(builder_, TFLITE_SCHEMA_VERSION, opcodes, subgraphs, comment, buffers)); input_model_ = ::tflite::GetModel(builder_.GetBufferPointer()); EXPECT_DEATH(Import(ModelFlags(), InputModelAsString()), "Number of subgraphs in tflite should be exactly 1."); } // TODO(ahentz): still need tests for Operators and IOTensors. } // namespace } // namespace tflite } // namespace toco
38.113208
80
0.662475
[ "shape", "vector", "model" ]
edd4a0d18399056d43f1c77143d7eeca411d6f08
5,560
cc
C++
chrome/browser/ui/webui/chromeos/mobile_setup_dialog.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-16T03:57:28.000Z
2021-01-23T15:29:45.000Z
chrome/browser/ui/webui/chromeos/mobile_setup_dialog.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/webui/chromeos/mobile_setup_dialog.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2017-03-15T13:21:38.000Z
2017-03-15T13:21:38.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/chromeos/mobile_setup_dialog.h" #include "base/bind.h" #include "base/memory/singleton.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/browser_shutdown.h" #include "chrome/browser/chromeos/login/login_display_host_impl.h" #include "chrome/browser/chromeos/login/webui_login_view.h" #include "chrome/browser/chromeos/mobile/mobile_activator.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/simple_message_box.h" #include "chrome/common/url_constants.h" #include "content/public/browser/browser_thread.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/size.h" #include "ui/views/widget/widget.h" #include "ui/web_dialogs/web_dialog_delegate.h" using chromeos::MobileActivator; using content::BrowserThread; using content::WebContents; using content::WebUIMessageHandler; using ui::WebDialogDelegate; class MobileSetupDialogDelegate : public WebDialogDelegate { public: static MobileSetupDialogDelegate* GetInstance(); void ShowDialog(const std::string& service_path); protected: friend struct DefaultSingletonTraits<MobileSetupDialogDelegate>; MobileSetupDialogDelegate(); virtual ~MobileSetupDialogDelegate(); void OnCloseDialog(); // WebDialogDelegate overrides. virtual ui::ModalType GetDialogModalType() const OVERRIDE; virtual base::string16 GetDialogTitle() const OVERRIDE; virtual GURL GetDialogContentURL() const OVERRIDE; virtual void GetWebUIMessageHandlers( std::vector<WebUIMessageHandler*>* handlers) const OVERRIDE; virtual void GetDialogSize(gfx::Size* size) const OVERRIDE; virtual std::string GetDialogArgs() const OVERRIDE; virtual void OnDialogClosed(const std::string& json_retval) OVERRIDE; virtual void OnCloseContents(WebContents* source, bool* out_close_dialog) OVERRIDE; virtual bool ShouldShowDialogTitle() const OVERRIDE; virtual bool HandleContextMenu( const content::ContextMenuParams& params) OVERRIDE; private: gfx::NativeWindow dialog_window_; // Cellular network service path. std::string service_path_; DISALLOW_COPY_AND_ASSIGN(MobileSetupDialogDelegate); }; // static void MobileSetupDialog::Show(const std::string& service_path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); MobileSetupDialogDelegate::GetInstance()->ShowDialog(service_path); } // static MobileSetupDialogDelegate* MobileSetupDialogDelegate::GetInstance() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return Singleton<MobileSetupDialogDelegate>::get(); } MobileSetupDialogDelegate::MobileSetupDialogDelegate() : dialog_window_(NULL) { } MobileSetupDialogDelegate::~MobileSetupDialogDelegate() { } void MobileSetupDialogDelegate::ShowDialog(const std::string& service_path) { service_path_ = service_path; gfx::NativeWindow parent = NULL; // If we're on the login screen. if (chromeos::LoginDisplayHostImpl::default_host()) { chromeos::LoginDisplayHostImpl* webui_host = static_cast<chromeos::LoginDisplayHostImpl*>( chromeos::LoginDisplayHostImpl::default_host()); chromeos::WebUILoginView* login_view = webui_host->GetWebUILoginView(); if (login_view) parent = login_view->GetNativeWindow(); } // Only the primary user can change this. dialog_window_ = chrome::ShowWebDialog( parent, ProfileManager::GetPrimaryUserProfile(), this); } ui::ModalType MobileSetupDialogDelegate::GetDialogModalType() const { return ui::MODAL_TYPE_SYSTEM; } base::string16 MobileSetupDialogDelegate::GetDialogTitle() const { return l10n_util::GetStringUTF16(IDS_MOBILE_SETUP_TITLE); } GURL MobileSetupDialogDelegate::GetDialogContentURL() const { std::string url(chrome::kChromeUIMobileSetupURL); url.append(service_path_); return GURL(url); } void MobileSetupDialogDelegate::GetWebUIMessageHandlers( std::vector<WebUIMessageHandler*>* handlers) const { } void MobileSetupDialogDelegate::GetDialogSize(gfx::Size* size) const { size->SetSize(850, 650); } std::string MobileSetupDialogDelegate::GetDialogArgs() const { return std::string(); } void MobileSetupDialogDelegate::OnDialogClosed(const std::string& json_retval) { dialog_window_ = NULL; } void MobileSetupDialogDelegate::OnCloseContents(WebContents* source, bool* out_close_dialog) { // If we're exiting, popping up the confirmation dialog can cause a // crash. Note: IsTryingToQuit can be cancelled on other platforms by the // onbeforeunload handler, except on ChromeOS. So IsTryingToQuit is the // appropriate check to use here. if (!dialog_window_ || !MobileActivator::GetInstance()->RunningActivation() || browser_shutdown::IsTryingToQuit()) { *out_close_dialog = true; return; } *out_close_dialog = chrome::ShowMessageBox(dialog_window_, l10n_util::GetStringUTF16(IDS_MOBILE_SETUP_TITLE), l10n_util::GetStringUTF16(IDS_MOBILE_CANCEL_ACTIVATION), chrome::MESSAGE_BOX_TYPE_QUESTION); } bool MobileSetupDialogDelegate::ShouldShowDialogTitle() const { return true; } bool MobileSetupDialogDelegate::HandleContextMenu( const content::ContextMenuParams& params) { return true; }
34.320988
80
0.767266
[ "vector" ]
edd530b64a82c6653597aa870db9a0f7c39c2779
1,832
cc
C++
src/tests/source/Test51.cc
venkate5hgunda/CSE598-Spring22-Group22-NetsDB
6c2dabd1a3b3f5901a97c788423fdd93cc0015d4
[ "Apache-2.0" ]
13
2022-01-17T16:14:26.000Z
2022-03-30T02:06:04.000Z
src/tests/source/Test51.cc
venkate5hgunda/CSE598-Spring22-Group22-NetsDB
6c2dabd1a3b3f5901a97c788423fdd93cc0015d4
[ "Apache-2.0" ]
1
2022-01-28T23:17:14.000Z
2022-01-28T23:17:14.000Z
src/tests/source/Test51.cc
venkate5hgunda/CSE598-Spring22-Group22-NetsDB
6c2dabd1a3b3f5901a97c788423fdd93cc0015d4
[ "Apache-2.0" ]
3
2022-01-18T02:13:53.000Z
2022-03-06T19:28:19.000Z
#ifndef TEST_50_H #define TEST_50_H #include "PDBString.h" #include "DistributedStorageManagerClient.h" #include "Supervisor.h" #include "Employee.h" #include "DataTypes.h" #include <ctime> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <chrono> #include <fcntl.h> /* This test uses data and selection of builtInType to demonstrate a distributed query with * distributed storage */ using namespace pdb; int main(int argc, char* argv[]) { pdb::PDBLoggerPtr clientLogger = make_shared<pdb::PDBLogger>("clientLog"); // Step 1. Create Database and Set pdb::DistributedStorageManagerClient temp(8108, "localhost", clientLogger); string errMsg; // now, create a new database if (!temp.createDatabase("chris_db", errMsg)) { cout << "Not able to create database: " + errMsg; exit(-1); } else { cout << "Created database.\n"; } // now, create a new set in that database if (!temp.createSet("chris_db", "chris_set", "pdb::Supervisor", errMsg)) { cout << "Not able to create set: " + errMsg; exit(-1); } else { cout << "Created set.\n"; } // now, create a new set in that database if (!temp.createSet<pdb::Vector<pdb::Handle<pdb::Employee>>>( "chris_db", "output_set1", errMsg)) { cout << "Not able to create set: " + errMsg; exit(-1); } else { cout << "Created set.\n"; } if (!temp.removeSet("chris_db", "output_set1", errMsg)) { cout << "Not able to remove set: " + errMsg; exit(-1); } else { cout << "Removed set.\n"; } if (!temp.removeSet("chris_db", "chris_set", errMsg)) { cout << "Not able to remove set: " + errMsg; exit(-1); } else { cout << "Removed set.\n"; } } #endif
25.09589
91
0.599891
[ "vector" ]
edda95fa0de1f75152456c36abd88e8b4114694b
34,561
cc
C++
depends/dbcommon/src/dbcommon/function/string-function.cc
YangHao666666/hawq
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
[ "Artistic-1.0-Perl", "ISC", "bzip2-1.0.5", "TCL", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "PostgreSQL", "BSD-3-Clause" ]
1
2020-05-11T01:39:13.000Z
2020-05-11T01:39:13.000Z
depends/dbcommon/src/dbcommon/function/string-function.cc
YangHao666666/hawq
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
[ "Artistic-1.0-Perl", "ISC", "bzip2-1.0.5", "TCL", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "PostgreSQL", "BSD-3-Clause" ]
1
2021-03-01T02:57:26.000Z
2021-03-01T02:57:26.000Z
depends/dbcommon/src/dbcommon/function/string-function.cc
YangHao666666/hawq
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
[ "Artistic-1.0-Perl", "ISC", "bzip2-1.0.5", "TCL", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "PostgreSQL", "BSD-3-Clause" ]
1
2020-05-03T07:29:21.000Z
2020-05-03T07:29:21.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 <cstring> #include "dbcommon/common/vector-transformer.h" #include "dbcommon/common/vector/variable-length-vector.h" #include "dbcommon/function/function.h" #include "dbcommon/function/string-binary-function.h" #include "dbcommon/utils/string-util.h" namespace dbcommon { inline void bpcharTrim(Datum *params, uint64_t size) { for (uint64_t i = 1; i < size; i++) { Object *para = DatumGetValue<Object *>(params[i]); if (dynamic_cast<Scalar *>(para)) { Scalar *temp = params[i]; if (temp->isnull) continue; char *str = temp->value; int32_t lenth = temp->length; while (--lenth >= 0) if (str[lenth] != ' ') break; temp->length = lenth + 1; } } } template <bool expetedMatch> Datum string_like_proto(Datum *params, uint64_t size) { assert(size == 3); Scalar *scalarPattern = DatumGetValue<Scalar *>(params[2]); auto patternSrc = DatumGetValue<char *>(scalarPattern->value); auto patternLen = scalarPattern->length; Object *para = DatumGetValue<Object *>(params[1]); Scalar *scalar = dynamic_cast<Scalar *>(para); bool noUnderScore = true; // intend for optimization for (auto i = 0; i < patternLen; i++) if (patternSrc[i] == '_') noUnderScore = false; if (StringUtil::isAsciiEncoding(patternSrc, patternLen) && noUnderScore) { // ASCII pattern if (scalar) { Scalar *ret = DatumGetValue<Scalar *>(params[0]); if (scalar->isnull) { ret->isnull = true; } else { ret->isnull = false; auto str = DatumGetValue<char *>(scalar->value); bool matched = StringUtil::MatchAsciiPattern(str, scalar->length, patternSrc, patternLen); ret->value = CreateDatum(static_cast<bool>(matched == expetedMatch)); } return CreateDatum(ret); } else { SelectList *ret = DatumGetValue<SelectList *>(params[0]); ret->resize(0); Vector *vec = dynamic_cast<Vector *>(para); assert(vec->getTypeKind() == VARCHARID || vec->getTypeKind() == STRINGID); auto valPtrs = vec->getValPtrs(); auto lens = vec->getLengths(); if (vec->hasNullValue()) { auto nulls = vec->getNullBuffer()->getBools(); if (vec->getSelected()) { auto sel = vec->getSelected(); for (auto i = 0; i < vec->getNumOfRows(); i++) { auto idx = (*sel)[i]; if (nulls[idx]) continue; bool matched = StringUtil::MatchAsciiPattern( valPtrs[idx], lens[idx], patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } else { for (auto i = 0; i < vec->getNumOfRowsPlain(); i++) { auto idx = i; if (nulls[idx]) continue; bool matched = StringUtil::MatchAsciiPattern( valPtrs[idx], lens[idx], patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } } else { if (vec->getSelected()) { auto sel = vec->getSelected(); for (auto i = 0; i < vec->getNumOfRows(); i++) { auto idx = (*sel)[i]; bool matched = StringUtil::MatchAsciiPattern( valPtrs[idx], lens[idx], patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } else { for (auto i = 0; i < vec->getNumOfRowsPlain(); i++) { auto idx = i; bool matched = StringUtil::MatchAsciiPattern( valPtrs[idx], lens[idx], patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } } return CreateDatum(ret); } } else { // UTF8 pattern if (scalar) { Scalar *ret = DatumGetValue<Scalar *>(params[0]); if (scalar->isnull) { ret->isnull = true; } else { ret->isnull = false; auto str = DatumGetValue<char *>(scalar->value); bool matched = StringUtil::MatchUtf8Pattern(str, scalar->length, patternSrc, patternLen); ret->value = CreateDatum(static_cast<bool>(matched == expetedMatch)); } return CreateDatum(ret); } else { SelectList *ret = DatumGetValue<SelectList *>(params[0]); ret->resize(0); Vector *vec = dynamic_cast<Vector *>(para); assert(vec->getTypeKind() == VARCHARID || vec->getTypeKind() == STRINGID); auto valPtrs = vec->getValPtrs(); auto lens = vec->getLengths(); if (vec->hasNullValue()) { auto nulls = vec->getNullBuffer()->getBools(); if (vec->getSelected()) { auto sel = vec->getSelected(); for (auto i = 0; i < vec->getNumOfRows(); i++) { auto idx = (*sel)[i]; if (nulls[idx]) continue; bool matched = StringUtil::MatchUtf8Pattern(valPtrs[idx], lens[idx], patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } else { for (auto i = 0; i < vec->getNumOfRowsPlain(); i++) { auto idx = i; if (nulls[idx]) continue; bool matched = StringUtil::MatchUtf8Pattern(valPtrs[idx], lens[idx], patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } } else { if (vec->getSelected()) { auto sel = vec->getSelected(); for (auto i = 0; i < vec->getNumOfRows(); i++) { auto idx = (*sel)[i]; bool matched = StringUtil::MatchUtf8Pattern(valPtrs[idx], lens[idx], patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } else { for (auto i = 0; i < vec->getNumOfRowsPlain(); i++) { auto idx = i; bool matched = StringUtil::MatchUtf8Pattern(valPtrs[idx], lens[idx], patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } } return CreateDatum(ret); } } } template <bool expetedMatch> Datum bpchar_like_proto(Datum *params, uint64_t size) { assert(size == 3); Scalar *scalarPattern = DatumGetValue<Scalar *>(params[2]); auto patternSrc = DatumGetValue<char *>(scalarPattern->value); auto patternLen = scalarPattern->length; Object *para = DatumGetValue<Object *>(params[1]); Scalar *scalar = dynamic_cast<Scalar *>(para); bool noUnderScore = true; // intend for optimization for (auto i = 0; i < patternLen; i++) if (patternSrc[i] == '_') noUnderScore = false; if (StringUtil::isAsciiEncoding(patternSrc, patternLen) && noUnderScore) { // ASCII pattern if (scalar) { Scalar *ret = DatumGetValue<Scalar *>(params[0]); if (scalar->isnull) { ret->isnull = true; } else { ret->isnull = false; auto str = DatumGetValue<char *>(scalar->value); auto strLen = scalar->length; bool matched = StringUtil::MatchAsciiPattern(str, strLen, patternSrc, patternLen); ret->value = CreateDatum(static_cast<bool>(matched == expetedMatch)); } return CreateDatum(ret); } else { SelectList *ret = DatumGetValue<SelectList *>(params[0]); ret->resize(0); BlankPaddedCharVector *vec = dynamic_cast<BlankPaddedCharVector *>(para); assert(vec); auto len = vec->getMaxLenModifier(); auto valPtrs = vec->getValPtrs(); if (vec->hasNullValue()) { auto nulls = vec->getNullBuffer()->getBools(); if (vec->getSelected()) { auto sel = vec->getSelected(); for (auto i = 0; i < vec->getNumOfRows(); i++) { auto idx = (*sel)[i]; if (nulls[idx]) continue; bool matched = StringUtil::MatchAsciiPattern( valPtrs[idx], len, patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } else { for (auto i = 0; i < vec->getNumOfRowsPlain(); i++) { auto idx = i; if (nulls[idx]) continue; bool matched = StringUtil::MatchAsciiPattern( valPtrs[idx], len, patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } } else { if (vec->getSelected()) { auto sel = vec->getSelected(); for (auto i = 0; i < vec->getNumOfRows(); i++) { auto idx = (*sel)[i]; bool matched = StringUtil::MatchAsciiPattern( valPtrs[idx], len, patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } else { for (auto i = 0; i < vec->getNumOfRowsPlain(); i++) { auto idx = i; bool matched = StringUtil::MatchAsciiPattern( valPtrs[idx], len, patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } } return CreateDatum(ret); } } else { // UTF8 pattern if (scalar) { Scalar *ret = DatumGetValue<Scalar *>(params[0]); if (scalar->isnull) { ret->isnull = true; } else { ret->isnull = false; auto str = DatumGetValue<char *>(scalar->value); auto strLen = scalar->length; bool matched = StringUtil::MatchUtf8Pattern(str, strLen, patternSrc, patternLen); ret->value = CreateDatum(static_cast<bool>(matched == expetedMatch)); } return CreateDatum(ret); } else { SelectList *ret = DatumGetValue<SelectList *>(params[0]); ret->resize(0); BlankPaddedCharVector *vec = dynamic_cast<BlankPaddedCharVector *>(para); assert(vec); auto len = vec->getMaxLenModifier(); auto valPtrs = vec->getValPtrs(); if (vec->hasNullValue()) { auto nulls = vec->getNullBuffer()->getBools(); if (vec->getSelected()) { auto sel = vec->getSelected(); for (auto i = 0; i < vec->getNumOfRows(); i++) { auto idx = (*sel)[i]; if (nulls[idx]) continue; bool matched = StringUtil::MatchUtf8Pattern(valPtrs[idx], len, patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } else { for (auto i = 0; i < vec->getNumOfRowsPlain(); i++) { auto idx = i; if (nulls[idx]) continue; bool matched = StringUtil::MatchUtf8Pattern(valPtrs[idx], len, patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } } else { if (vec->getSelected()) { auto sel = vec->getSelected(); for (auto i = 0; i < vec->getNumOfRows(); i++) { auto idx = (*sel)[i]; bool matched = StringUtil::MatchUtf8Pattern(valPtrs[idx], len, patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } else { for (auto i = 0; i < vec->getNumOfRowsPlain(); i++) { auto idx = i; bool matched = StringUtil::MatchUtf8Pattern(valPtrs[idx], len, patternSrc, patternLen); if (matched == expetedMatch) ret->push_back(idx); } } } return CreateDatum(ret); } } } Datum string_like(Datum *params, uint64_t size) { return string_like_proto<true>(params, size); } Datum bpchar_like(Datum *params, uint64_t size) { return bpchar_like_proto<true>(params, size); } Datum string_not_like(Datum *params, uint64_t size) { return string_like_proto<false>(params, size); } Datum bpchar_not_like(Datum *params, uint64_t size) { return bpchar_like_proto<false>(params, size); } class utf8ptr { public: explicit utf8ptr(const char *p) : p_(p) {} operator const char *() { return p_; } utf8ptr &operator++() { p_ += utf8_mblen(p_); return *this; } utf8ptr &operator+=(const int32_t &len) { int32_t times = len; while (times--) p_ += utf8_mblen(p_); return *this; } utf8ptr &operator=(const char *p) { if (p_ != p) p_ = p; return *this; } bool operator==(const utf8ptr &tmp) { int32_t len = utf8_mblen(p_); const char *tmp_ = p_; const char *cmp_ = tmp.p_; while (len && *tmp_++ == *cmp_++) len--; if (len) return false; return true; } char *get() { return const_cast<char *>(p_); } int32_t characterLength(const char *p) { int32_t len = 0; const char *tmp = p_; while (tmp != p) { tmp += utf8_mblen(tmp); len++; } return len; } int32_t characterLength(const int32_t &len) { int32_t ret = 0, lenth = len; const char *tmp = p_; while (lenth > 0) { int32_t tLen = utf8_mblen(tmp); lenth -= tLen; tmp += tLen; ret++; } return ret; } int32_t byteLength(const int32_t &len) { int32_t ret = 0; int32_t times = len; const char *tmp = p_; while (times--) { int32_t tLen = utf8_mblen(tmp); tmp += tLen; ret += tLen; } return ret; } private: const char *p_; }; Datum string_char_length(Datum *params, uint64_t size) { auto charLength = [](ByteBuffer &buf, text str) -> int32_t { utf8ptr p(str.val); uint64_t len = 0; while (p < str.val + str.length) { ++p; ++len; } return len; }; return one_param_bind<int32_t, text>(params, size, charLength); } Datum bpchar_char_length(Datum *params, uint64_t size) { bpcharTrim(params, size); return string_char_length(params, size); } Datum string_lower(Datum *params, uint64_t size) { auto lower = [](ByteBuffer &buf, text str) { buf.resize(buf.size() + str.length); std::transform(str.val, str.val + str.length, const_cast<char *>(buf.tail()) - str.length, [](char c) { return 'A' <= c && c <= 'Z' ? c - ('A' - 'a') : c; }); return text(nullptr, str.length); }; return one_param_bind<text, text>(params, size, lower); } Datum string_upper(Datum *params, uint64_t size) { auto upper = [](ByteBuffer &buf, text str) { buf.resize(buf.size() + str.length); std::transform(str.val, str.val + str.length, const_cast<char *>(buf.tail()) - str.length, [](char c) { return 'a' <= c && c <= 'z' ? c + ('A' - 'a') : c; }); return text(nullptr, str.length); }; return one_param_bind<text, text>(params, size, upper); } Datum string_concat(Datum *params, uint64_t size) { auto concat = [](ByteBuffer &buf, text str1, text str2) { buf.resize(buf.size() + str1.length + str2.length); char *ret = const_cast<char *>(buf.tail() - str1.length - str2.length); std::transform(str1.val, str1.val + str1.length, ret, [](char tmp) { return tmp; }); std::transform(str2.val, str2.val + str2.length, ret + str1.length, [](char tmp) { return tmp; }); return text(nullptr, str1.length + str2.length); }; return two_params_bind<text, text, text>(params, size, concat); } int32_t kmpPos(const char *str, const char *subStr, uint64_t len, uint64_t subLen, dbcommon::ByteBuffer *kmpPosBuf) { if (len < subLen) return 0; kmpPosBuf->resize(subLen * sizeof(int32_t)); int32_t *__restrict__ next = reinterpret_cast<int32_t *>(kmpPosBuf->data()); next[0] = -1; int32_t i = 0, j = -1; while (i < subLen - 1) { if (j == -1 || subStr[i] == subStr[j]) next[++i] = ++j; else j = next[j]; } i = 0; j = 0; int32_t lLen = len, sLen = subLen; while (i < lLen && j < sLen) { if (j == -1 || subStr[j] == str[i]) { i++; j++; } else { j = next[j]; } } if (j == sLen) return i - j + 1; else return 0; } int32_t naivePos(const char *str, const char *subStr, uint64_t len, uint64_t subLen) { if (len < subLen) return 0; int32_t times = len - subLen; for (int32_t i = 0; i <= times; i++) { bool flag = true; for (int32_t j = 0; j < subLen; j++) if (str[i + j] != subStr[j]) { flag = false; break; } if (flag) return i + 1; } return 0; } Datum string_position(Datum *params, uint64_t size) { const uint32_t KMP_LIMIT = 30; auto subpos = [](ByteBuffer &buf, text src, text sub) -> int32_t { int32_t byteLen = 0; if (sub.length < KMP_LIMIT) { byteLen = naivePos(src.val, sub.val, src.length, sub.length); } else { dbcommon::ByteBuffer kmpPosBuf(true); byteLen = kmpPos(src.val, sub.val, src.length, sub.length, &kmpPosBuf); } utf8ptr utfStrPtr(src.val); return byteLen ? utfStrPtr.characterLength(byteLen - 1) + 1 : 0; }; return two_params_bind<int32_t, text, text>(params, size, subpos); } Datum string_initcap(Datum *params, uint64_t size) { auto initcap = [](ByteBuffer &buf, text str) { buf.resize(buf.size() + str.length); char *ret = const_cast<char *>(buf.tail() - str.length); char last = ' '; int32_t times = str.length; while (times--) { if (((unsigned int)((last | 0x20) - 'a') >= 26u && (unsigned int)(last - '0') >= 10u) && !(last & ~0x7F)) { auto low2up = [](char c) { return 'a' <= c && c <= 'z' ? c + ('A' - 'a') : c; }; *ret++ = low2up(*str.val); last = *str.val++; } else { auto up2low = [](char c) { return 'A' <= c && c <= 'Z' ? c - ('A' - 'a') : c; }; *ret++ = up2low(*str.val); last = *str.val++; } } return text(nullptr, str.length); }; return one_param_bind<text, text>(params, size, initcap); } inline void fixRange(int32_t strlen, int32_t *subpos, int32_t *sublen) { int32_t zero = 0; *subpos = *subpos - 1; if (*subpos < zero) { *subpos += *sublen; if (*subpos < zero) { *subpos = zero; *sublen = zero; } else { *sublen = *subpos; *subpos = zero; } } if (*subpos + *sublen > strlen) *sublen = strlen - *subpos; if (*sublen < zero) *sublen = zero; } // only support utf-8 now Datum string_substring(Datum *params, uint64_t size) { auto substr = [](ByteBuffer &buf, text src, int32_t pos, int32_t len) { if (len < 0) { LOG_ERROR(ERRCODE_SUBSTRING_ERROR, "negative substring length not allowed"); } utf8ptr utfStrPtr(src.val); int32_t utfStrLen = utfStrPtr.characterLength(src.val + src.length); fixRange(utfStrLen, &pos, &len); utfStrPtr += pos; char *srcBegin = utfStrPtr.get(); utfStrPtr += len; int32_t retByteLen = utfStrPtr.get() - srcBegin; buf.resize(buf.size() + retByteLen); char *ret = const_cast<char *>(buf.tail() - retByteLen); std::transform(srcBegin, srcBegin + retByteLen, ret, [](char tmp) { return tmp; }); return text(nullptr, retByteLen); }; return three_params_bind<text, text, int32_t, int32_t>(params, size, substr); } Datum string_substring_nolen(Datum *params, uint64_t size) { auto substrnolen = [](ByteBuffer &buf, text str, int32_t pos) { if (--pos < 0) pos = 0; utf8ptr utfStrPtr(str.val); utfStrPtr += pos; char *strBegin = utfStrPtr.get(); int32_t len = str.val + str.length - strBegin; if (len < 0) len = 0; buf.resize(buf.size() + len); char *ret = const_cast<char *>(buf.tail() - len); std::transform(strBegin, strBegin + len, ret, [](char tmp) { return tmp; }); return text(nullptr, len); }; return two_params_bind<text, text, int32_t>(params, size, substrnolen); } inline int32_t myAscii(const unsigned char *data) { int32_t retval = 0; if (*data > 0x7F) { int32_t tsize = 0; if (*data >= 0xF0) { retval = *data & 0x07; tsize = 3; } else if (*data >= 0xE0) { retval = *data & 0x0F; tsize = 2; } else { assert(*data > 0xC0); retval = *data & 0x1F; tsize = 1; } while (tsize--) { retval = (retval << 6) + (*++data & 0x3F); } } else { retval = (int32_t)*data; } return retval; } Datum string_ascii(Datum *params, uint64_t size) { auto ascii = [](ByteBuffer &buf, text str) -> int32_t { unsigned char *srcval = (unsigned char *)const_cast<char *>(str.val); if (str.length > 0) return myAscii(srcval); else return 0; }; return one_param_bind<int32_t, text>(params, size, ascii); } /* * Convert a VARCHAR type to the specified size. * * N.B. currently does not handle the toast string */ Datum string_varchar(Datum *params, uint64_t size) { auto varchar = [](ByteBuffer &buf, text str, int32_t len, bool exp) { len = TypeModifierUtil::getMaxLen(len); utf8ptr utfStrPtr(str.val); int32_t utfStrLen = utfStrPtr.characterLength(str.val + str.length); if (utfStrLen > len) { if (exp == false) { auto p = str.length - 1; int32_t retByteLen = utfStrPtr.byteLength(len); while (p >= retByteLen) { if (str.val[p--] != ' ') { LOG_ERROR(ERRCODE_STRING_DATA_RIGHT_TRUNCATION, "value too long for type character varying(%d)", len); } } } } else { len = utfStrLen; } int32_t retByteLen = utfStrPtr.byteLength(len); buf.resize(buf.size() + retByteLen); char *ret = const_cast<char *>(buf.tail() - retByteLen); std::transform(utfStrPtr.get(), utfStrPtr.get() + retByteLen, ret, [](char c) { return c; }); return text(nullptr, retByteLen); }; return three_params_bind<text, text, int32_t, bool>(params, size, varchar); } enum direction { left = 0, right, both }; template <direction dir> Datum string_trim_blank(Datum *params, uint64_t size) { auto trim = [](ByteBuffer &buf, text str) { int32_t l = 0, r = str.length - 1; if (dir == direction::left || dir == direction::both) { while (l <= r && str.val[l] == ' ') l++; } if (dir == direction::right || dir == direction::both) { while (l <= r && str.val[r] == ' ') r--; } int32_t len = r - l + 1; if (len < 0) len = 0; buf.resize(buf.size() + len); char *ret = const_cast<char *>(buf.tail() - len); std::transform(str.val + l, str.val + r + 1, ret, [](char c) { return c; }); return text(nullptr, len); }; return one_param_bind<text, text>(params, size, trim); } template <direction dir> Datum string_trim_chars(Datum *params, uint64_t size) { auto trim = [](ByteBuffer &buf, text str, text chr) { int32_t l = 0, r = str.length - 1; if (dir == direction::left || dir == direction::both) { std::string s(const_cast<char *>(chr.val), chr.length); while (l <= r && s.find(str.val[l]) != std::string::npos) l++; } if (dir == direction::right || dir == direction::both) { std::string s(const_cast<char *>(chr.val), chr.length); while (l <= r && s.find(str.val[r]) != std::string::npos) r--; } int32_t len = r - l + 1; if (len < 0) len = 0; buf.resize(buf.size() + len); char *ret = const_cast<char *>(buf.tail() - len); std::transform(str.val + l, str.val + r + 1, ret, [](char c) { return c; }); return text(nullptr, len); }; return two_params_bind<text, text, text>(params, size, trim); } // CASE 1: trim left blank Datum string_ltrim_blank(Datum *params, uint64_t size) { return string_trim_blank<direction::left>(params, size); } // CASE 2: trim left character Datum string_ltrim_chars(Datum *params, uint64_t size) { return string_trim_chars<direction::left>(params, size); } // CASE 3: trim right blank Datum string_rtrim_blank(Datum *params, uint64_t size) { return string_trim_blank<direction::right>(params, size); } // CASE 4: trim right character Datum string_rtrim_chars(Datum *params, uint64_t size) { return string_trim_chars<direction::right>(params, size); } // CASE 5: trim both blank Datum string_btrim_blank(Datum *params, uint64_t size) { return string_trim_blank<direction::both>(params, size); } // CASE 6: trim both character Datum string_btrim_chars(Datum *params, uint64_t size) { return string_trim_chars<direction::both>(params, size); } Datum string_repeat(Datum *params, uint64_t size) { auto demo_func = [](ByteBuffer &buf, text str, int32_t dupLen) { int32_t retLen = str.length * dupLen; if (dupLen && (retLen / dupLen) != str.length) { LOG_ERROR(ERRCODE_PROGRAM_LIMIT_EXCEEDED, "requested length too large"); } buf.resize(buf.size() + retLen); char *retBufPtr = const_cast<char *>(buf.tail() - retLen); while (dupLen--) { std::transform(str.val, str.val + str.length, retBufPtr, [](char c) { return c; }); retBufPtr += str.length; } return text(nullptr, retLen); }; return two_params_bind<text, text, int32_t>(params, size, demo_func); } Datum string_chr(Datum *params, uint64_t size) { auto chr = [](ByteBuffer &buf, int32_t val) { int32_t len = 0; char wch[4]; if (val > 0x7F) { if (val > 0x001fffff) { LOG_ERROR(ERRCODE_PROGRAM_LIMIT_EXCEEDED, "requested character too large for encoding: %u", val); } if (val > 0xffff) { len = 4; } else if (val > 0x07ff) { len = 3; } else { len = 2; } if (len == 2) { wch[0] = 0xC0 | ((val >> 6) & 0x1F); wch[1] = 0x80 | (val & 0x3F); } else if (len == 3) { wch[0] = 0xE0 | ((val >> 12) & 0x0F); wch[1] = 0x80 | ((val >> 6) & 0x3F); wch[2] = 0x80 | (val & 0x3F); } else { wch[0] = 0xF0 | ((val >> 18) & 0x07); wch[1] = 0x80 | ((val >> 12) & 0x3F); wch[2] = 0x80 | ((val >> 6) & 0x3F); wch[3] = 0x80 | (val & 0x3F); } } else { if (val == 0) { LOG_ERROR(ERRCODE_PROGRAM_LIMIT_EXCEEDED, "null character not permitted"); } bool isMB = true; if ((isMB && (val > 127)) || (!isMB && (val > 255))) { // TODO(zdh): error for Multi-byte encoding except utf8 // LOG_ERROR(ERRCODE_PROGRAM_LIMIT_EXCEEDED, // "requested character too large for encoding: %d", val); } len = 1; wch[0] = static_cast<char>(val); } buf.resize(buf.size() + len); char *ret = const_cast<char *>(buf.tail() - len); strncpy(ret, wch, len); return text(nullptr, len); }; return one_param_bind<text, int32_t>(params, size, chr); } Datum string_bpchar(Datum *params, uint64_t size) { auto bpchar = [](ByteBuffer &buf, text str, int32_t len, bool exp) { len = TypeModifierUtil::getMaxLen(len); utf8ptr utfStrPtr(str.val); int32_t characterLen = utfStrPtr.characterLength(str.val + str.length); if (characterLen > len) { if (exp == false) { auto p = str.length - 1; int32_t byteLen = utfStrPtr.byteLength(len); while (p >= len) { if (str.val[p--] != ' ') { LOG_ERROR(ERRCODE_STRING_DATA_RIGHT_TRUNCATION, "value too long for type character(%d)", len); } } } } int32_t copyLen = characterLen > len ? utfStrPtr.byteLength(len) : str.length; int32_t retByteLen = characterLen > len ? utfStrPtr.byteLength(len) : str.length + len - characterLen; buf.resize(buf.size() + retByteLen); char *ret = const_cast<char *>(buf.tail() - retByteLen); std::transform(str.val, str.val + copyLen, ret, [](char c) { return c; }); ret += copyLen; while (copyLen++ < retByteLen) *ret++ = ' '; return text(nullptr, retByteLen); }; return three_params_bind<text, text, int32_t, bool>(params, size, bpchar); } template <direction dir> Datum string_pad_blank(Datum *params, uint64_t size) { auto pad = [](ByteBuffer &buf, text str, int32_t len) { utf8ptr utfStrPtr(str.val); int32_t characterLen = utfStrPtr.characterLength(str.val + str.length); int32_t retByteLen = str.length; if (characterLen < len) retByteLen += len - characterLen; else retByteLen = utfStrPtr.byteLength(len); buf.resize(buf.size() + retByteLen); char *ret = const_cast<char *>(buf.tail() - retByteLen); if (dir == direction::left) { int32_t remainder = retByteLen - str.length; remainder = remainder < 0 ? 0 : remainder; std::memset(ret, ' ', remainder); ret += remainder; } int32_t writeLen = str.length < retByteLen ? str.length : retByteLen; for (int32_t i = 0; i < writeLen; i++) *ret++ = str.val[i]; if (dir == direction::right) { int32_t remainder = retByteLen - str.length; remainder = remainder < 0 ? 0 : remainder; std::memset(ret, ' ', remainder); } return text(nullptr, retByteLen); }; return two_params_bind<text, text, int32_t>(params, size, pad); } Datum string_lpad_nofill(Datum *params, uint64_t size) { return string_pad_blank<direction::left>(params, size); } Datum string_rpad_nofill(Datum *params, uint64_t size) { return string_pad_blank<direction::right>(params, size); } template <direction dir> Datum string_pad_chars(Datum *params, uint64_t size) { auto pad = [](ByteBuffer &buf, text str, int32_t len, text fil) { utf8ptr utfStrPtr(str.val); utf8ptr utfFilPtr(fil.val); int32_t strCharLen = utfStrPtr.characterLength(str.val + str.length); int32_t filCharLen = utfFilPtr.characterLength(fil.val + fil.length); int32_t retByteLen = str.length; if (strCharLen >= len) { retByteLen = utfStrPtr.byteLength(len); } else { int32_t rem = len - strCharLen; while (rem >= filCharLen) { retByteLen += fil.length; rem -= filCharLen; } retByteLen += utfFilPtr.byteLength(rem); } buf.resize(buf.size() + retByteLen); char *ret = const_cast<char *>(buf.tail() - retByteLen); if (dir == direction::left) { int32_t remainder = len - strCharLen; if (fil.length == 1 && remainder > 0) { std::memset(ret, *fil.val, remainder); ret += remainder; } else { while (remainder > 0) { if (remainder >= filCharLen) { for (int32_t i = 0; i < fil.length; i++) *ret++ = fil.val[i]; } else { int32_t fillLen = utfFilPtr.byteLength(remainder); for (int32_t i = 0; i < fil.length; i++) *ret++ = str.val[i]; } remainder -= filCharLen; } } } int32_t writeLen = str.length < retByteLen ? str.length : retByteLen; for (int32_t i = 0; i < writeLen; i++) *ret++ = str.val[i]; if (dir == direction::right) { int32_t remainder = len - strCharLen; if (fil.length == 1 && remainder > 0) { std::memset(ret, *fil.val, remainder); ret += remainder; } else { while (remainder > 0) { if (remainder >= filCharLen) { for (int32_t i = 0; i < fil.length; i++) *ret++ = fil.val[i]; } else { int32_t fillLen = utfFilPtr.byteLength(remainder); for (int32_t i = 0; i < fillLen; i++) *ret++ = fil.val[i]; } remainder -= filCharLen; } } } return text(nullptr, retByteLen); }; return three_params_bind<text, text, int32_t, text>(params, size, pad); } Datum string_lpad(Datum *params, uint64_t size) { return string_pad_chars<direction::left>(params, size); } Datum string_rpad(Datum *params, uint64_t size) { return string_pad_chars<direction::right>(params, size); } Datum string_translate(Datum *params, uint64_t size) { auto translate = [](ByteBuffer &buf, text str, text from, text to) { utf8ptr utfStrPtr(str.val); utf8ptr utfFromPtr(from.val); utf8ptr utfToPtr(to.val); int32_t strCharLen = utfStrPtr.characterLength(str.val + str.length); int32_t fromCharLen = utfFromPtr.characterLength(from.val + from.length); int32_t toCharLen = utfToPtr.characterLength(to.val + to.length); int32_t retByteLen = 0; int32_t worstLen = strCharLen * 4; // if (worstLen / 4 != strCharLen) { // it won't appear one number which has int32_t length; // LOG_ERROR(ERRCODE_PROGRAM_LIMIT_EXCEEDED, // "requested length too large"); // } buf.resize(buf.size() + worstLen); char *ret = const_cast<char *>(buf.tail() - worstLen); auto writeByte = [&](utf8ptr src) { char *tmp = src.get(); int32_t len = utf8_mblen(tmp); retByteLen += len; for (int32_t k = 0; k < len; k++) *ret++ = *tmp++; }; for (int32_t i = 0; i < strCharLen; i++) { int32_t j = 0; utfFromPtr = from.val; utfToPtr = to.val; for (; j < fromCharLen; j++) { if (utfStrPtr == utfFromPtr) { if (j < toCharLen) { utfToPtr += j; writeByte(utfToPtr); } break; } ++utfFromPtr; } if (j == fromCharLen) { writeByte(utfStrPtr); } ++utfStrPtr; } buf.resize(buf.size() - (worstLen - retByteLen)); return text(nullptr, retByteLen); }; return three_params_bind<text, text, text, text>(params, size, translate); } } // namespace dbcommon
32.790323
80
0.571685
[ "object", "vector", "transform" ]
eddafe08603a420c68e968242f3f5ad52b75cfa1
34,637
cpp
C++
Source/Falcor/Scene/Importers/USDImporter/PreviewSurfaceConverter.cpp
mistralk/Falcor
49621cc8484bdd5887886b191c2dbde91693ec6a
[ "BSD-3-Clause" ]
null
null
null
Source/Falcor/Scene/Importers/USDImporter/PreviewSurfaceConverter.cpp
mistralk/Falcor
49621cc8484bdd5887886b191c2dbde91693ec6a
[ "BSD-3-Clause" ]
null
null
null
Source/Falcor/Scene/Importers/USDImporter/PreviewSurfaceConverter.cpp
mistralk/Falcor
49621cc8484bdd5887886b191c2dbde91693ec6a
[ "BSD-3-Clause" ]
null
null
null
/*************************************************************************** # Copyright (c) 2015-21, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 "AS IS" AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **************************************************************************/ #include "stdafx.h" #pragma warning(push) #pragma warning(disable : 4244) // Conversion possible loss of data #pragma warning(disable : 4267) // Conversion possible loss of data #pragma warning(disable : 4305) // Truncation double to float #pragma warning(disable : 5033) // 'register' storage class specifier deprecated #include "PreviewSurfaceConverter.h" #include "pxr/usd/usdGeom/xformCommonAPI.h" #include "pxr/usd/usdRender/tokens.h" #include "pxr/usdImaging/usdImaging/tokens.h" #include "pxr/usd/ar/resolver.h" #include "pxr/usd/sdf/layerUtils.h" #pragma warning(pop) #include "Utils.h" using namespace pxr; namespace Falcor { namespace { const char kSpecTransShaderFile[]("Scene/Importers/USDImporter/CreateSpecularTransmissionTexture.cs.slang"); const char kSpecTransShaderEntry[]("createSpecularTransmissionTexture"); const char kPackAlphaShaderFile[]("Scene/Importers/USDImporter/PackBaseColorAlpha.cs.slang"); const char kPackAlphaShaderEntry[]("packBaseColorAlpha"); const char kSpecularShaderFile[]("Scene/Importers/USDImporter/CreateSpecularTexture.cs.slang"); const char kSpecularShaderEntry[]("createSpecularTexture"); inline int32_t getChannelIndex(TextureChannelFlags flags) { switch (flags) { case TextureChannelFlags::None: return -1; case TextureChannelFlags::Red: return 0; case TextureChannelFlags::Green: return 1; case TextureChannelFlags::Blue: return 2; case TextureChannelFlags::Alpha: return 3; default: FALCOR_UNREACHABLE(); } return -1; } // Return the ultimate source of the given input. UsdShadeInput getSourceInput(UsdShadeInput input) { if (input && input.HasConnectedSource()) { UsdShadeConnectableAPI source; TfToken sourceName; UsdShadeAttributeType sourceType; if (input.GetConnectedSource(&source, &sourceName, &sourceType)) { auto inputs = source.GetInputs(); // If there's a connected source of type asset, return it. for (uint32_t i = 0; i < inputs.size(); ++i) { logDebug("Input '{}' has source '{}'.", input.GetBaseName().GetString(), inputs[i].GetBaseName().GetString()); SdfValueTypeName typeName(inputs[i].GetTypeName()); if (typeName == SdfValueTypeNames->Asset) { return inputs[i]; } } // Otherwise, if there's no input of type asset, use the first connected source. return inputs[0]; } } return input; } // Get the layer in which the given authored attribute is defined, if any. SdfLayerHandle getLayerHandle(const UsdAttribute& attr, const UsdTimeCode& time) { for (auto& spec : attr.GetPropertyStack(time)) { if (spec->HasDefaultValue() || spec->GetLayer()->GetNumTimeSamplesForPath(spec->GetPath()) > 0) { return spec->GetLayer(); } } return SdfLayerHandle(); } } StandardMaterial::SharedPtr PreviewSurfaceConverter::getCachedMaterial(const UsdShadeShader& shader) { std::unique_lock lock(mCacheMutex); std::string shaderName = shader.GetPath().GetString(); while (true) { auto iter = mMaterialCache.find(shader.GetPrim()); if (iter == mMaterialCache.end()) { // No entry for this shader. Add one, with a nullptr Falcor material instance, to indicate that work is underway. logDebug("No cached material for UsdPreviewSurface '{}'; starting conversion.", shaderName); mMaterialCache.insert(std::make_pair(shader.GetPrim(), nullptr)); return nullptr; } if (iter->second != nullptr) { // Found a valid entry logDebug("Found a cached material for UsdPreviewSurface '{}'.", shaderName); return iter->second; } // There is an dictionary entry, but it is null, indicating that another thread is current performing conversion. // Wait until we are signaled that a new entry has been added to the dictionary, and check again. // Note that this mechanism requires that conversion never fail to create an entry in the dictionary after calling this function. logDebug("In-progressed cached entry for UsdPreviewSurface '{}' detected. Waiting.", shaderName); mCacheUpdated.wait(lock); } FALCOR_UNREACHABLE(); return nullptr; } void PreviewSurfaceConverter::cacheMaterial(const UsdShadeShader& shader, StandardMaterial::SharedPtr pMaterial) { { std::unique_lock lock(mCacheMutex); if (mMaterialCache.find(shader.GetPrim()) == mMaterialCache.end()) { throw RuntimeError("Expected PreviewSurfaceConverter cache entry for '{}' not found.", shader.GetPath().GetString()); } mMaterialCache[shader.GetPrim()] = pMaterial; } mCacheUpdated.notify_all(); } bool isUniformFloat4(const UsdShadeInput& input, const float4& uniformValue) { auto typeName = input.GetTypeName(); if (typeName == SdfValueTypeNames->Float4) { GfVec4f v; input.Get<GfVec4f>(&v, UsdTimeCode::EarliestTime()); float4 value(v[0], v[1], v[2], v[3]); return value == uniformValue; } return false; } PreviewSurfaceConverter::ConvertedInput PreviewSurfaceConverter::convertTexture(const UsdShadeInput& input, bool assumeSrgb) { const TfToken fallbackToken("fallback"); const TfToken fileToken("file"); const TfToken float2PrimvarReaderToken("UsdPrimvarReader_float2"); const TfToken sRGBToken("sRGB"); const TfToken sourceColorSpaceToken("sourceColorSpace"); const TfToken stToken("st"); const TfToken wrapSToken("wrapS"); const TfToken wrapTToken("wrapT"); const TfToken biasToken("bias"); const TfToken scaleToken("scale"); ConvertedInput ret; // Note that the wrapS, wrapT, scale, and bias inputs are unsupported, and are ignored. UsdPrim prim(input.GetPrim()); if (!prim.IsA<UsdShadeShader>()) { logWarning("Expected UsdUVTexture node '{}' is not a UsdShadeShader.", prim.GetPath().GetString()); return ret; } UsdShadeShader shader(prim); TfToken id = getAttribute(prim.GetAttribute(UsdShadeTokens->infoId), TfToken()); if (id != UsdImagingTokens->UsdUVTexture) { logWarning("Expected UsdUVTexture node '{}' is not a UsdUVTexture.", prim.GetPath().GetString()); return ret; } if (shader.GetInput(wrapSToken) || shader.GetInput(wrapTToken)) { // Issue a low-priorty message, under the assumption that wrap modes most often don't matter. logInfo("UsdUvTexture node '{}' specifies a wrap mode, which is not supported.", prim.GetPath().GetString()); } if (shader.GetInput(biasToken)) { if (!isUniformFloat4(shader.GetInput(biasToken), float4(0.f, 0.f, 0.f, 0.f))) { logWarning("UsdUvTexture node '{}' specifies a non-zero bias, which is not supported.", prim.GetPath().GetString()); } } if (shader.GetInput(scaleToken)) { if (!isUniformFloat4(shader.GetInput(scaleToken), float4(1.f, 1.f, 1.f, 1.f))) { logWarning("UsdUvTexture node '{}' specifies a non-unity scale, which is not supported.", prim.GetPath().GetString()); } } UsdShadeInput stInput(getSourceInput(shader.GetInput(stToken))); if (stInput) { // Check the primvar reader associated with the st input to ensure it's of the expected type. // Note that we only issue a warning here, and use the associated geometry's texcoords for lookup in any case. UsdPrim stPrim(stInput.GetPrim()); id = getAttribute(stPrim.GetAttribute(UsdShadeTokens->infoId), TfToken()); if (id != float2PrimvarReaderToken) { logWarning("UsdUVTexture node '{}' defines an st primvar reader of an unexpected type: '{}'.", prim.GetPath().GetString(), id.GetString()); } } else { // Issue a lower priority message if there is simply no st input defined, under the assumption that the default behavior is expected. logInfo("UsdUVTexture node '{}' does not define an st input.", prim.GetPath().GetString()); } // Initialize the uniform converted value using the fallback value, if any. GfVec4f fallbackValue = getAttribute(prim.GetAttribute(fallbackToken), GfVec4f(0.f, 0.f, 0.f, 1.f)); ret.uniformValue = float4(fallbackValue[0], fallbackValue[1], fallbackValue[2], fallbackValue[3]); // Color space may be specified in USD either as an attribute of the input connection, which we check here, or directly on the the asset, // which we check below, and which takes precedence. bool loadSRGB = assumeSrgb; TfToken colorSpace = getAttribute(prim.GetAttribute(sourceColorSpaceToken), TfToken()); if (colorSpace == sRGBToken) loadSRGB = true; // Convert output specification to texture channel flag. ret.channels = TextureChannelFlags::None; for (auto& output : shader.GetOutputs()) { if (output.GetBaseName() == TfToken("r")) { ret.channels |= TextureChannelFlags::Red; } if (output.GetBaseName() == TfToken("g")) { ret.channels |= TextureChannelFlags::Green; } if (output.GetBaseName() == TfToken("b")) { ret.channels |= TextureChannelFlags::Blue; } if (output.GetBaseName() == TfToken("a")) { ret.channels |= TextureChannelFlags::Alpha; } if (output.GetBaseName() == TfToken("rgb")) { ret.channels |= TextureChannelFlags::Red; ret.channels |= TextureChannelFlags::Green; ret.channels |= TextureChannelFlags::Blue; } } if (ret.channels == TextureChannelFlags::None) { logWarning("No valid output specified by UsdUVTexture '{}'.", prim.GetName().GetString()); return ret; } UsdShadeInput fileInput(getSourceInput(shader.GetInput(fileToken))); if (fileInput) { SdfAssetPath path; UsdPrim prim(fileInput.GetPrim()); UsdAttribute fileAttrib = prim.GetAttribute(TfToken("inputs:file")); TfToken colorSpace = fileAttrib.GetColorSpace(); if (colorSpace == sRGBToken) loadSRGB = true; fileInput.Get<SdfAssetPath>(&path, UsdTimeCode::EarliestTime()); std::string filename = path.GetResolvedPath().empty() ? path.GetAssetPath() : path.GetResolvedPath(); // If the filename contains <UDIM>, the asset refers to a UDIM texture set, which Falcor does not support. // Replace <UDIM> with 1001 in an attempt to at least load one texture from the set. auto udimPos = filename.find("<UDIM>"); std::string replacedFilename = filename; if (udimPos != std::string::npos) { filename.replace(udimPos, 6, "1001"); // This hoop-jumping is required because we need to resolve the given path relative to the // layer in which it is defined, to ensure that e.g., "../../Textures/foo.dds" resolves properly. SdfLayerHandle layerHandle(getLayerHandle(fileAttrib, UsdTimeCode::EarliestTime())); filename = SdfComputeAssetPathRelativeToLayer(layerHandle, filename); if (filename.empty()) { filename = path.GetAssetPath(); } } // Create the texture by first reading the image (which is relatively slow) outside of the mutex, // and then creating the texture itself inside it. Bitmap::UniqueConstPtr pBitmap(Bitmap::createFromFile(filename, false)); if (pBitmap) { ResourceFormat format = loadSRGB ? linearToSrgbFormat(pBitmap->getFormat()) : pBitmap->getFormat(); { std::scoped_lock lock(mMutex); ret.pTexture = Texture::create2D(pBitmap->getWidth(), pBitmap->getHeight(), format, 1, Texture::kMaxPossible, pBitmap->getData()); } } // Else, a warning will have been emitted by Bitmap::createFromFile(), and the fallback value will be used. } else { logWarning("UsdUVTexture '{}' does not specify a file input.", prim.GetName().GetString()); } return ret; } PreviewSurfaceConverter::ConvertedInput PreviewSurfaceConverter::convertFloat(const UsdShadeInput& input) { ConvertedInput ret; SdfValueTypeName typeName(input.GetTypeName()); if (typeName == SdfValueTypeNames->Asset) { ret = convertTexture(input); } else if (typeName == SdfValueTypeNames->Float) { input.Get<float>(&ret.uniformValue.r, UsdTimeCode::EarliestTime()); } else { logWarning("Unexpected value type when converting float input: '{}'.", typeName.GetAsToken().GetString()); } return ret; } PreviewSurfaceConverter::ConvertedInput PreviewSurfaceConverter::convertColor(const UsdShadeInput& input, bool assumeSrgb) { ConvertedInput ret; SdfValueTypeName typeName(input.GetTypeName()); ret.uniformValue = float4(0.f, 0.f, 0.f, 1.f); if (typeName == SdfValueTypeNames->Color3f) { GfVec3f v; input.Get<GfVec3f>(&v, UsdTimeCode::EarliestTime()); ret.uniformValue = float4(v[0], v[1], v[2], 1.f); } else if (typeName == SdfValueTypeNames->Asset) { ret = convertTexture(input, assumeSrgb); } else { logWarning("Unexpected value type when converting color input: '{}'.", typeName.GetAsToken().GetString()); } return ret; } PreviewSurfaceConverter::PreviewSurfaceConverter() { mpSpecTransPass = ComputePass::create(kSpecTransShaderFile, kSpecTransShaderEntry); mpPackAlphaPass = ComputePass::create(kPackAlphaShaderFile, kPackAlphaShaderEntry); mpSpecularPass = ComputePass::create(kSpecularShaderFile, kSpecularShaderEntry); Sampler::Desc samplerDesc; samplerDesc.setFilterMode(Sampler::Filter::Linear, Sampler::Filter::Linear, Sampler::Filter::Point); samplerDesc.setAddressingMode(Sampler::AddressMode::Clamp, Sampler::AddressMode::Clamp, Sampler::AddressMode::Clamp); mpSampler = Sampler::create(samplerDesc); } // Convert textured opacity to textured specular transparency. Texture::SharedPtr PreviewSurfaceConverter::createSpecularTransmissionTexture(ConvertedInput& opacity, RenderContext* pRenderContext) { std::scoped_lock lock(mMutex); if (popcount((uint32_t)opacity.channels) > 1) { logWarning("Cannot create transmission texture; opacity texture provides more than one channel of data."); return nullptr; } uint2 resolution(opacity.pTexture->getWidth(), opacity.pTexture->getHeight()); Texture::SharedPtr pTexture = Texture::create2D(resolution.x, resolution.y, ResourceFormat::RGBA8Unorm, 1, Texture::kMaxPossible, nullptr, Resource::BindFlags::ShaderResource | Resource::BindFlags::UnorderedAccess | Resource::BindFlags::RenderTarget); mpSpecTransPass["CB"]["outDim"] = resolution; mpSpecTransPass["CB"]["opacityChannel"] = getChannelIndex(opacity.channels); mpSpecTransPass["opacityTexture"] = opacity.pTexture; mpSpecTransPass["outputTexture"] = pTexture; mpSpecTransPass->execute(pRenderContext, resolution.x, resolution.y); pTexture->generateMips(pRenderContext); return pTexture; } // Combine base color and alpha, one or both of which may be textured, into a single texture. // If both are textured, they may be of different resolutions. // This is only performed when a material makes use of cutout opacity. Texture::SharedPtr PreviewSurfaceConverter::packBaseColorAlpha(ConvertedInput& baseColor, ConvertedInput& opacity, RenderContext* pRenderContext) { std::scoped_lock lock(mMutex); if (opacity.pTexture && popcount((uint32_t)opacity.channels) > 1) { logWarning("Cannot set alpha channel; opacity texture provides more than one channel."); return nullptr; } // Set output resolution to the maxium of the input dimensions uint32_t width = std::max<uint32_t>((opacity.pTexture ? opacity.pTexture->getWidth() : 0), (baseColor.pTexture ? baseColor.pTexture->getWidth() : 0)); uint32_t height = std::max<uint32_t>((opacity.pTexture ? opacity.pTexture->getHeight() : 0), (baseColor.pTexture ? baseColor.pTexture->getHeight() : 0)); uint2 resolution(width, height); // sRGB format textures can't be bound as UAVs. Render to an RGBA32Float intermediate texture, and then blit to RGBA8UnormSrgb to preserve precision near zero. Texture::SharedPtr pTexture = Texture::create2D(resolution.x, resolution.y, ResourceFormat::RGBA32Float, 1, 1, nullptr, Resource::BindFlags::ShaderResource | Resource::BindFlags::UnorderedAccess); mpPackAlphaPass["CB"]["opacityChannel"] = opacity.pTexture ? getChannelIndex(opacity.channels) : -1; mpPackAlphaPass["CB"]["opacityValue"] = opacity.uniformValue.r; mpPackAlphaPass["CB"]["baseColorTextureValid"] = baseColor.pTexture ? 1 : 0; mpPackAlphaPass["CB"]["baseColorValue"] = baseColor.uniformValue; mpPackAlphaPass["CB"]["outDim"] = resolution; mpPackAlphaPass["opacityTexture"] = opacity.pTexture; mpPackAlphaPass["baseColorTexture"] = baseColor.pTexture; mpPackAlphaPass["sampler"] = mpSampler; mpPackAlphaPass["outputTexture"] = pTexture; mpPackAlphaPass->execute(pRenderContext, resolution.x, resolution.y); // Create the output mipmapped sRGB texture Texture::SharedPtr pFinal = Texture::create2D(resolution.x, resolution.y, ResourceFormat::RGBA8UnormSrgb, 1, Texture::kMaxPossible, nullptr, Resource::BindFlags::ShaderResource | Resource::BindFlags::RenderTarget); // Blit the intermediate texture to the output texture to perform format conversion pRenderContext->blit(pTexture->getSRV(), pFinal->getRTV()); pFinal->generateMips(pRenderContext); return pFinal; } // Combine roughness and metallic parameters, one or both of which are textured, into a specular/ORM texture. // If both are textured, they may be of different resolutions. Texture::SharedPtr PreviewSurfaceConverter::createSpecularTexture(ConvertedInput& roughness, ConvertedInput& metallic, RenderContext* pRenderContext) { std::scoped_lock lock(mMutex); if (roughness.pTexture && popcount((uint32_t)roughness.channels) > 1) { logWarning("Cannot create specular texture; roughness texture provides more than one channel."); return nullptr; } if (metallic.pTexture && popcount((uint32_t)metallic.channels) > 1) { logWarning("Cannot create specular texture; metallic texture provides more than one channel."); return nullptr; } // Set output resolution to the maxium of the input dimensions uint32_t width = std::max<uint32_t>((roughness.pTexture ? roughness.pTexture->getWidth() : 0), (metallic.pTexture ? metallic.pTexture->getWidth() : 0)); uint32_t height = std::max<uint32_t>((roughness.pTexture ? roughness.pTexture->getHeight() : 0), (metallic.pTexture ? metallic.pTexture->getHeight() : 0)); uint2 resolution(width, height); Texture::SharedPtr pTexture = Texture::create2D(width, height, ResourceFormat::RGBA8Unorm, 1, Texture::kMaxPossible, nullptr, Resource::BindFlags::ShaderResource | Resource::BindFlags::UnorderedAccess | Resource::BindFlags::RenderTarget); mpSpecularPass["CB"]["roughnessChannel"] = roughness.pTexture ? getChannelIndex(roughness.channels) : -1; mpSpecularPass["CB"]["roughnessValue"] = roughness.uniformValue.r; mpSpecularPass["CB"]["metallicChannel"] = metallic.pTexture ? getChannelIndex(metallic.channels) : -1; mpSpecularPass["CB"]["metallicValue"] = metallic.uniformValue.r; mpSpecularPass["CB"]["outDim"] = resolution; mpSpecularPass["metallicTexture"] = metallic.pTexture; mpSpecularPass["roughnessTexture"] = roughness.pTexture; mpSpecularPass["sampler"] = mpSampler; mpSpecularPass["outputTexture"] = pTexture; mpSpecularPass->execute(pRenderContext, resolution.x, resolution.y); pTexture->generateMips(pRenderContext); return pTexture; } Material::SharedPtr PreviewSurfaceConverter::convert(const UsdShadeMaterial& material, const std::string& primName, RenderContext* pRenderContext) { UsdShadeOutput surface(material.GetOutput(TfToken("surface"))); if (!surface.IsDefined()) { logDebug("Material '{}' does not define a surface output.", primName); return nullptr; } // Get the UsdShadeShader that provides the surface output UsdShadeShader shader; UsdPrim surfacePrim(surface.GetPrim()); if (surfacePrim.IsDefined()) { UsdShadeConnectableAPI source; TfToken sourceName; UsdShadeAttributeType sourceType; if (UsdShadeConnectableAPI::GetConnectedSource(surface, &source, &sourceName, &sourceType)) { UsdPrim prim(source.GetPrim()); if (prim.IsA<UsdShadeShader>()) { shader = UsdShadeShader(prim); } } } if (!shader) { logDebug("Material '{}' surface output is not a UsdShadeShader.", primName); return nullptr; } TfToken id = getAttribute(shader.GetPrim().GetAttribute(UsdShadeTokens->infoId), TfToken()); if (id != UsdImagingTokens->UsdPreviewSurface) { logDebug("Material '{}' has a surface output node of type '{}', not UsdPreviewSurface.", primName, id.GetString()); return nullptr; } logDebug("Material '{}' has UsdPreviewSurface output '{}'.", primName, shader.GetPath().GetString()); // Is there a valid cached instance for this UsdPreviewSurface? If so, simply return it. // Note that this call will block if another thread is concurrently converting the same shader. StandardMaterial::SharedPtr pMaterial = getCachedMaterial(shader); if (pMaterial) { return pMaterial; } // Get material name. std::string materialName(material.GetPrim().GetPath().GetString()); // Create the output material pMaterial = StandardMaterial::create(materialName); ConvertedInput baseColor; ConvertedInput metallic; ConvertedInput roughness(0.5f); ConvertedInput opacity(1.f); float opacityThreshold = 0.f; float ior = 1.5f; // Traverse the UsdPreviewSurface node inputs for (auto& curInput : shader.GetInputs()) { logDebug("UsdPreviewSurface '{}' has input: {}", shader.GetPath().GetString(), curInput.GetBaseName().GetString()); // Convert the input name to lowercase to allow for mixed capitalization std::string inputName = curInput.GetBaseName(); std::transform(inputName.begin(), inputName.end(), inputName.begin(), ::tolower); // Get the most-upstream source of the input. UsdShadeInput input = getSourceInput(curInput); SdfValueTypeName typeName(input.GetTypeName()); logDebug("UsdPreviewSurface '{}' input '{}' has type '{}'.", shader.GetPath().GetString(), inputName, typeName.GetAsToken().GetString()); if (inputName == "diffusecolor") { // Get diffuse color value(s), assume that textures are sRGB by default. baseColor = convertColor(input, true); } else if (inputName == "emissivecolor") { // Get color value(s), assume that textures are sRGB by default. ConvertedInput emissive = convertColor(input, true); if (emissive.pTexture) { pMaterial->setEmissiveTexture(emissive.pTexture); } else { pMaterial->setEmissiveColor(emissive.uniformValue); } } else if (inputName == "usespecularworkflow") { if (typeName == SdfValueTypeNames->Int) { int specularWorkflow; input.Get<int>(&specularWorkflow, UsdTimeCode::EarliestTime()); if (specularWorkflow) { logWarning("Specular workflow is not supported."); } } else { logWarning("Unsupported specular workflow value type: '{}'.", typeName.GetAsToken().GetString()); } } else if (inputName == "metallic") { metallic = convertFloat(input); } else if (inputName == "specularcolor") { if (typeName == SdfValueTypeNames->Color3f) { logInfo("Ignoring specular color."); } else if (typeName == SdfValueTypeNames->Asset) { logInfo("Ignoring specular texture."); } else { logInfo("Unsupported specular color value type: '{}'.", typeName.GetAsToken().GetString()); } } else if (inputName == "roughness") { roughness = convertFloat(input); } else if (inputName == "clearcoat") { logWarning("Falcor does not support clearcoat."); } else if (inputName == "clearcoatroughness") { logWarning("Falcor does not support clearcoat roughness."); } else if (inputName == "opacity") { opacity = convertFloat(input); } else if (inputName == "opacitythreshold") { if (typeName == SdfValueTypeNames->Float) { input.Get<float>(&opacityThreshold, UsdTimeCode::EarliestTime()); } else if (typeName == SdfValueTypeNames->Asset) { logWarning("Falcor does not support textured opacity threshold."); } else { logWarning("Unsupported opacity threshold value type: '{}'.", typeName.GetAsToken().GetString()); } } else if (inputName == "ior") { if (typeName == SdfValueTypeNames->Float) { input.Get<float>(&ior, UsdTimeCode::EarliestTime()); } else if (typeName == SdfValueTypeNames->Asset) { logWarning("Falcor does not support textured IoR."); } else { logWarning("Unsupported ior value type: '{}'.", typeName.GetAsToken().GetString()); } } else if (inputName == "normal") { if (typeName == SdfValueTypeNames->Normal3f) { logWarning("Falcor does not support uniform normal values."); } else if (typeName == SdfValueTypeNames->Asset) { ConvertedInput norm = convertTexture(input); if (norm.pTexture) { pMaterial->setNormalMap(norm.pTexture); } } else { logWarning("Unsupported normal value type: '{}'.", typeName.GetAsToken().GetString()); } } else if (inputName == "displacement") { ConvertedInput disp = convertFloat(input); if (disp.channels == TextureChannelFlags::None) { logWarning("Falcor does not support uniform displacement."); } else if (disp.pTexture) { pMaterial->setDisplacementMap(disp.pTexture); } } else if (inputName == "occlusion") { logWarning("Falcor does not support occlusion material parameter."); } else { logWarning("Unsupported UsdPreviewSurface input '{}'.", inputName); } } pMaterial->setIndexOfRefraction(ior); // If there is either a roughness or metallic texture, convert texture(s) and constant (if any) to an ORM texture. if (metallic.pTexture || roughness.pTexture) { Texture::SharedPtr pSpecularTex = createSpecularTexture(roughness, metallic, pRenderContext); pMaterial->setSpecularTexture(pSpecularTex); } else { pMaterial->setSpecularParams(float4(0.f, roughness.uniformValue.r, metallic.uniformValue.r, 1.f)); } if (opacity.uniformValue.r < 1.f || opacity.pTexture) { // Handle non-unit opacity if (opacityThreshold > 0.f) { // Opacity encodes cutout values // Pack opacity into the alpha channel if (baseColor.pTexture|| opacity.pTexture) { baseColor.pTexture = packBaseColorAlpha(baseColor, opacity, pRenderContext); } else { baseColor.uniformValue = float4(baseColor.uniformValue.rgb, opacity.uniformValue.r); } pMaterial->setAlphaThreshold(opacityThreshold); } else if (opacity.pTexture) { // Opacity encodes (1 - specular-transmission) // Create a greyscale specular transmission color texture using (1-opacity), as a slightly hacky means of supporting textured specular transmission. Texture::SharedPtr pTransmissionTexture = createSpecularTransmissionTexture(opacity, pRenderContext); pMaterial->setTransmissionTexture(pTransmissionTexture); pMaterial->setSpecularTransmission(1.f); } else { pMaterial->setSpecularTransmission(1.f - opacity.uniformValue.r); } } if (baseColor.pTexture) { pMaterial->setBaseColorTexture(baseColor.pTexture); } else { pMaterial->setBaseColor(baseColor.uniformValue); } // Cache the result of the conversion cacheMaterial(shader, pMaterial); return pMaterial; } }
43.844304
259
0.593874
[ "geometry", "render", "transform" ]
eddc67d6f9d75f2665f663f9c06a312af037e104
4,556
cpp
C++
android-31/android/app/appsearch/GenericDocument.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/app/appsearch/GenericDocument.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-31/android/app/appsearch/GenericDocument.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../../JByteArray.hpp" #include "../../../JDoubleArray.hpp" #include "../../../JLongArray.hpp" #include "../../../JArray.hpp" #include "../../../JArray.hpp" #include "../../../JBooleanArray.hpp" #include "../../../JArray.hpp" #include "../../../JObject.hpp" #include "../../../JString.hpp" #include "./GenericDocument.hpp" namespace android::app::appsearch { // Fields // QJniObject forward GenericDocument::GenericDocument(QJniObject obj) : JObject(obj) {} // Constructors // Methods jint GenericDocument::getMaxIndexedProperties() { return callStaticMethod<jint>( "android.app.appsearch.GenericDocument", "getMaxIndexedProperties", "()I" ); } jboolean GenericDocument::equals(JObject arg0) const { return callMethod<jboolean>( "equals", "(Ljava/lang/Object;)Z", arg0.object<jobject>() ); } jlong GenericDocument::getCreationTimestampMillis() const { return callMethod<jlong>( "getCreationTimestampMillis", "()J" ); } JString GenericDocument::getId() const { return callObjectMethod( "getId", "()Ljava/lang/String;" ); } JString GenericDocument::getNamespace() const { return callObjectMethod( "getNamespace", "()Ljava/lang/String;" ); } JObject GenericDocument::getProperty(JString arg0) const { return callObjectMethod( "getProperty", "(Ljava/lang/String;)Ljava/lang/Object;", arg0.object<jstring>() ); } jboolean GenericDocument::getPropertyBoolean(JString arg0) const { return callMethod<jboolean>( "getPropertyBoolean", "(Ljava/lang/String;)Z", arg0.object<jstring>() ); } JBooleanArray GenericDocument::getPropertyBooleanArray(JString arg0) const { return callObjectMethod( "getPropertyBooleanArray", "(Ljava/lang/String;)[Z", arg0.object<jstring>() ); } JByteArray GenericDocument::getPropertyBytes(JString arg0) const { return callObjectMethod( "getPropertyBytes", "(Ljava/lang/String;)[B", arg0.object<jstring>() ); } JArray GenericDocument::getPropertyBytesArray(JString arg0) const { return callObjectMethod( "getPropertyBytesArray", "(Ljava/lang/String;)[[B", arg0.object<jstring>() ); } android::app::appsearch::GenericDocument GenericDocument::getPropertyDocument(JString arg0) const { return callObjectMethod( "getPropertyDocument", "(Ljava/lang/String;)Landroid/app/appsearch/GenericDocument;", arg0.object<jstring>() ); } JArray GenericDocument::getPropertyDocumentArray(JString arg0) const { return callObjectMethod( "getPropertyDocumentArray", "(Ljava/lang/String;)[Landroid/app/appsearch/GenericDocument;", arg0.object<jstring>() ); } jdouble GenericDocument::getPropertyDouble(JString arg0) const { return callMethod<jdouble>( "getPropertyDouble", "(Ljava/lang/String;)D", arg0.object<jstring>() ); } JDoubleArray GenericDocument::getPropertyDoubleArray(JString arg0) const { return callObjectMethod( "getPropertyDoubleArray", "(Ljava/lang/String;)[D", arg0.object<jstring>() ); } jlong GenericDocument::getPropertyLong(JString arg0) const { return callMethod<jlong>( "getPropertyLong", "(Ljava/lang/String;)J", arg0.object<jstring>() ); } JLongArray GenericDocument::getPropertyLongArray(JString arg0) const { return callObjectMethod( "getPropertyLongArray", "(Ljava/lang/String;)[J", arg0.object<jstring>() ); } JObject GenericDocument::getPropertyNames() const { return callObjectMethod( "getPropertyNames", "()Ljava/util/Set;" ); } JString GenericDocument::getPropertyString(JString arg0) const { return callObjectMethod( "getPropertyString", "(Ljava/lang/String;)Ljava/lang/String;", arg0.object<jstring>() ); } JArray GenericDocument::getPropertyStringArray(JString arg0) const { return callObjectMethod( "getPropertyStringArray", "(Ljava/lang/String;)[Ljava/lang/String;", arg0.object<jstring>() ); } JString GenericDocument::getSchemaType() const { return callObjectMethod( "getSchemaType", "()Ljava/lang/String;" ); } jint GenericDocument::getScore() const { return callMethod<jint>( "getScore", "()I" ); } jlong GenericDocument::getTtlMillis() const { return callMethod<jlong>( "getTtlMillis", "()J" ); } jint GenericDocument::hashCode() const { return callMethod<jint>( "hashCode", "()I" ); } JString GenericDocument::toString() const { return callObjectMethod( "toString", "()Ljava/lang/String;" ); } } // namespace android::app::appsearch
22.009662
98
0.690299
[ "object" ]