hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
b4bd7b2898a364459917651140396212213c1234
17,964
hpp
C++
include/universal/verification/bfloat_test_suite.hpp
jtodd440/universal
3d8c946691be0dca091579da34f91ced82e1136a
[ "MIT" ]
null
null
null
include/universal/verification/bfloat_test_suite.hpp
jtodd440/universal
3d8c946691be0dca091579da34f91ced82e1136a
[ "MIT" ]
null
null
null
include/universal/verification/bfloat_test_suite.hpp
jtodd440/universal
3d8c946691be0dca091579da34f91ced82e1136a
[ "MIT" ]
null
null
null
#pragma once // real_test_helpers.hpp : arbitrary real verification functions // // Copyright (C) 2017-2021 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <vector> #include <iostream> #include <typeinfo> #include <random> #include <limits> namespace sw::universal { template<typename SrcType, typename TestType> void ReportConversionError(const std::string& test_case, const std::string& op, SrcType input, const TestType& reference, const TestType& result) { // constexpr size_t nbits = TestType::nbits; // number system concept requires a static member indicating its size in bits auto old_precision = std::cerr.precision(); std::cerr << test_case << " " << op << " " << std::setw(NUMBER_COLUMN_WIDTH) << input << " did not convert to " << std::setw(NUMBER_COLUMN_WIDTH) << reference << " instead it yielded " << std::setw(NUMBER_COLUMN_WIDTH) << result << " raw " << to_binary(result) << std::setprecision(old_precision) << std::endl; } template<typename SrcType, typename TestType> void ReportConversionSuccess(const std::string& test_case, const std::string& op, SrcType input, const TestType& reference, const TestType& result) { constexpr size_t nbits = TestType::nbits; // number system concept requires a static member indicating its size in bits std::cerr << test_case << " " << op << " " << std::setw(NUMBER_COLUMN_WIDTH) << input << " success " << std::setw(NUMBER_COLUMN_WIDTH) << result << " golden reference is " << std::setw(NUMBER_COLUMN_WIDTH) << reference << " raw " << std::setw(nbits) << to_binary(result) << std::endl; } template<typename SrcType, typename TestType> int Compare(SrcType input, const TestType& testValue, const TestType& reference, bool bReportIndividualTestCases) { int fail = 0; if (testValue != reference) { fail++; if (bReportIndividualTestCases) ReportConversionError("FAIL", "=", input, reference, testValue); } else { if (bReportIndividualTestCases) ReportConversionSuccess("PASS", "=", input, reference, testValue); } return fail; } /////////////////////////////// VERIFICATION TEST SUITES //////////////////////////////// /* 0: b0000 0 -1 b00 b0 0 4.2x0x0r 1: b0001 0 -1 b00 b1 0.5 4.2x0x1r 2: b0010 0 0 b01 b0 1 4.2x0x2r 3: b0011 0 0 b01 b1 1.5 4.2x0x3r 4: b0100 0 1 b10 b0 2 4.2x0x4r 5: b0101 0 1 b10 b1 3 4.2x0x5r 6: b0110 0 2 b11 b0 inf 4.2x0x6r 7: b0111 0 2 b11 b1 nan 4.2x0x7r 8: b1000 1 -1 b00 b0 0 4.2x0x8r 0: b00000 0 -2 b0 b000 0 5.1x0x00r 1: b00001 0 -2 b0 b001 0.25 5.1x0x01r 2: b00010 0 -1 b0 b010 0.5 5.1x0x02r 3: b00011 0 -1 b0 b011 0.75 5.1x0x03r 4: b00100 0 0 b0 b100 1 5.1x0x04r 5: b00101 0 0 b0 b101 1.25 5.1x0x05r 6: b00110 0 0 b0 b110 1.5 5.1x0x06r 7: b00111 0 0 b0 b111 1.75 5.1x0x07r 8: b01000 0 1 b1 b000 2 5.1x0x08r 9: b01001 0 1 b1 b001 2.25 5.1x0x09r 10: b01010 0 1 b1 b010 2.5 5.1x0x0Ar 11: b01011 0 1 b1 b011 2.75 5.1x0x0Br 12: b01100 0 1 b1 b100 3 5.1x0x0Cr 13: b01101 0 1 b1 b101 3.25 5.1x0x0Dr 14: b01110 0 1 b1 b110 inf 5.1x0x0Er 15: b01111 0 1 b1 b111 nan 5.1x0x0Fr 16: b10000 1 -2 b0 b000 0 5.1x0x10r 0: b0000-0 0 -2 b0 b000 0 5.1x0x00r <---- 4.1x0x0r 1: b0000-1 0 -2 b0 b001 0.25 5.1x0x01r 2: b0001-0 0 -1 b0 b010 0.5 5.1x0x02r <---- 4.1x0x1r 3: b0001-1 0 -1 b0 b011 0.75 5.1x0x03r 4: b0010-0 0 0 b0 b100 1 5.1x0x04r <---- 4.1x0x2r 5: b0010-1 0 0 b0 b101 1.25 5.1x0x05r 6: b0011-0 0 0 b0 b110 1.5 5.1x0x06r <---- 4.1x0x3r 7: b0011-1 0 0 b0 b111 1.75 5.1x0x07r 8: b0100-0 0 1 b1 b000 2 5.1x0x08r <---- 4.1x0x4r 9: b0100-1 0 1 b1 b001 2.25 5.1x0x09r 10: b0101-0 0 1 b1 b010 2.5 5.1x0x0Ar <---- 4.1x0x4r 11: b0101-1 0 1 b1 b011 2.75 5.1x0x0Br 12: b0110-0 0 1 b1 b100 3 5.1x0x0Cr <---- 4.1x0x4r 13: b0110-1 0 1 b1 b101 3.25 5.1x0x0Dr 14: b0111-0 0 1 b1 b110 inf 5.1x0x0Er <---- 4.1x0x7r 15: b0111-1 0 1 b1 b111 nan 5.1x0x0Fr 16: b1000-0 1 -2 b0 b000 0 5.1x0x10r <---- 4.1x0x7r VerifyConversion algorithm: enumerate bfloat<nbits+1, es> and create minus and plus deltas that you a priori know which way they round 1.00 - delta round up 4: b0010-0 0 0 b0 b100 1 5.1x0x04r <---- 4.1x0x2r 1.00 + delta round down 1.25 - delta round up 5: b0010-1 0 0 b0 b101 1.25 5.1x0x05r 1.25 + delta round down 1.50 - delta round up 6: b0011-0 0 0 b0 b110 1.5 5.1x0x06r <---- 4.1x0x3r 1.50 + delta round down 1.75 - delta round up 7: b0011-1 0 0 b0 b111 1.75 5.1x0x07r 1.75 + delta round down 8: b0100-0 0 1 b1 b000 2 5.1x0x08r <---- 4.1x0x4r */ /// <summary> /// enumerate all conversion cases for a TestType /// </summary> /// <typeparam name="TestType">the test configuration</typeparam> /// <typeparam name="RefType">the reference configuration</typeparam> /// <param name="tag">string to indicate what is being tested</param> /// <param name="bReportIndividualTestCases">if true print results of each test case. Default is false.</param> /// <returns>number of failed test cases</returns> template<typename TestType, typename SrcType = double> int VerifyBfloatConversion(bool bReportIndividualTestCases) { // we are going to generate a test set that consists of all configs and their midpoints // we do this by enumerating a configuration that is 1-bit larger than the test configuration // with the extra bit allocated to the fraction. // The sample values of the larger configuration will be at the mid-point between the smaller // configuration sample values thus creating a full cover test set for value conversions. // The precondition for this type of test is that the value conversion is verified. // To generate the three test cases, we'll enumerate the exact value, and a perturbation slightly // smaller from the midpoint that will round down, and one slightly larger that will round up, // to test the rounding logic of the conversion. constexpr size_t nbits = TestType::nbits; constexpr size_t es = TestType::es; using BlockType = typename TestType::BlockType; using RefType = bfloat<nbits + 1, es, BlockType>; constexpr size_t NR_TEST_CASES = (size_t(1) << (nbits + 1)); constexpr size_t HALF = (size_t(1) << nbits); // For example: // TestType: fixpnt<nbits,rbits,Saturating,uint8_t> needs RefType fixpnt<nbits+1, rbits+1, Saturating,uint8_t> // TestType: bfloat<nbits, es, uint8_t> needs RefType bfloat<nbits + 1, es, uint8_t> // TestType: posit<nbits, es, uint8_t> needs RefType posit<nbits + 1, es, uint8_t> const unsigned max = nbits > 20 ? 20 : nbits + 1; size_t max_tests = (size_t(1) << max); if (max_tests < NR_TEST_CASES) { std::cout << "VerifyConversion " << typeid(TestType).name() << ": NR_TEST_CASES = " << NR_TEST_CASES << " clipped by " << max_tests << std::endl; } // execute the test int nrOfFailedTests = 0; RefType positive_minimum; double dminpos = double(minpos(positive_minimum)); // NUT: number under test TestType nut, golden; for (size_t i = 0; i < NR_TEST_CASES && i < max_tests; ++i) { RefType ref, prev, next; SrcType testValue{ 0.0 }; ref.set_raw_bits(i); SrcType da = SrcType(ref); int old = nrOfFailedTests; SrcType oneULP = ulp(da); if (i % 2) { if (i == 1) { // special case of a tie that needs to round to even -> 0 testValue = da; nut = testValue; golden = 0.0f; nrOfFailedTests += Compare(testValue, nut, golden, bReportIndividualTestCases); // this rounds up testValue = SrcType(da + oneULP); // the test value between 0 and minpos nut = testValue; next.set_raw_bits(i + 1); golden = double(next); nrOfFailedTests += Compare(testValue, nut, golden, bReportIndividualTestCases); } else if (i == HALF - 3) { // encoding of maxpos // ignore if (bReportIndividualTestCases) std::cout << i << " : >" << da << " ignored\n"; } else if (i == HALF - 1) { // encoding of qNaN // ignore if (bReportIndividualTestCases) std::cout << i << " : >" << da << " ignored\n"; } else if (i == HALF + 1) { // special case of projecting to -0 testValue = SrcType(da - oneULP); nut = testValue; golden = 0.0f; golden = -golden; nrOfFailedTests += Compare(testValue, nut, golden, bReportIndividualTestCases); } else if (i == NR_TEST_CASES - 3) { // encoding of maxneg // ignore if (bReportIndividualTestCases) std::cout << i << " : < " << da << " ignored\n"; } else if (i == NR_TEST_CASES - 1) { // encoding of SIGNALLING NAN // ignore if (bReportIndividualTestCases) std::cout << i << " : < " << da << " ignored\n"; } else { // for odd values of i, we are between sample values of the NUT // create the round-up and round-down cases // round-down testValue = SrcType(da - oneULP); nut = testValue; prev.set_raw_bits(i - 1); golden = double(prev); nrOfFailedTests += Compare(testValue, nut, golden, bReportIndividualTestCases); // round-up if (i == HALF - 5 || i == NR_TEST_CASES - 5) { if (bReportIndividualTestCases) std::cout << i << " : >" << da << " ignored\n"; } else { testValue = SrcType(da + oneULP); nut = testValue; next.set_raw_bits(i + 1); golden = double(next); nrOfFailedTests += Compare(testValue, nut, golden, bReportIndividualTestCases); } } } else { // for the even values, we generate the round-to-actual cases if (i == 0) { // ref = 0 // 0 -> value = 0 // half of next -> value = 0 // special case of assigning to 0 testValue = da; nut = testValue; golden.setzero(); // make certain we are +0 nrOfFailedTests += Compare(testValue, nut, golden, bReportIndividualTestCases); // half of next rounds down to 0 testValue = SrcType(dminpos / 2.0); nut = testValue; nrOfFailedTests += Compare(testValue, nut, golden, bReportIndividualTestCases); } else if (i == HALF) { // ref = -0 // 0 -> value = 0 // half of next -> value = 0 // special case of assigning to 0 /* ignore testValue = da; // the optimizer removes the sign on -0 nut = testValue; golden.setzero(); golden = -golden; // make certain we are -0 std::cout << i << " : " << to_binary(nut) << " : " << to_binary(golden) << std::endl; nrOfFailedTests += Compare(testValue, nut, golden, bReportIndividualTestCases); */ // half of next rounds down to -0 testValue = SrcType(-dminpos / 2.0); nut = testValue; golden.setzero(); golden = -golden; // make certain we are -0 nrOfFailedTests += Compare(testValue, nut, golden, bReportIndividualTestCases); } else if (i == HALF - 4) { if (bReportIndividualTestCases) std::cout << i << " : > " << da << " ignored\n"; } else if (i == HALF - 2) { // encoding of INF // ignore if (bReportIndividualTestCases) std::cout << i << " : " << da << " ignored\n"; } else if (i == NR_TEST_CASES - 4) { // encoding of maxneg // ignore if (bReportIndividualTestCases) std::cout << i << " : < " << da << " ignored\n"; } else if (i == NR_TEST_CASES - 2) { // encoding of -INF // ignore if (bReportIndividualTestCases) std::cout << i << " : " << da << " ignored\n"; } else { // for even values, we are on actual representable values, so we create the round-up and round-down cases // round-up testValue = SrcType(da - oneULP); nut = testValue; golden = da; nrOfFailedTests += Compare(testValue, nut, golden, bReportIndividualTestCases); // round-down testValue = SrcType(da + oneULP); nut = testValue; nrOfFailedTests += Compare(testValue, nut, golden, bReportIndividualTestCases); } } if (bReportIndividualTestCases && nrOfFailedTests > old) { std::cout << to_binary(oneULP, true) << " : " << oneULP << '\n'; std::cout << to_binary(da - oneULP, true) << " : " << da - oneULP << '\n'; std::cout << to_binary(da, true) << " : " << da << '\n'; std::cout << to_binary(da + oneULP, true) << " : " << da + oneULP << '\n'; std::cout << "[" << i << "]\n"; } } return nrOfFailedTests; } // validate the increment operator++ template<size_t nbits, size_t es> int VerifyIncrement(bool bReportIndividualTestCases) { std::vector< bfloat<nbits, es> > set; // GenerateOrderedPositSet(set); // [NaR, -maxpos, ..., -minpos, 0, minpos, ..., maxpos] int nrOfFailedTestCases = 0; bfloat<nbits, es> p, ref; // starting from NaR iterating from -maxpos to maxpos through zero for (typename std::vector < bfloat<nbits, es> >::iterator it = set.begin(); it != set.end() - 1; ++it) { p = *it; p++; ref = *(it + 1); if (p != ref) { if (bReportIndividualTestCases) std::cout << " FAIL " << p << " != " << ref << std::endl; nrOfFailedTestCases++; } } return nrOfFailedTestCases; } // validate the decrement operator-- template<size_t nbits, size_t es> int VerifyDecrement(bool bReportIndividualTestCases) { std::vector< bfloat<nbits, es> > set; // GenerateOrderedPositSet(set); // [NaR, -maxpos, ..., -minpos, 0, minpos, ..., maxpos] int nrOfFailedTestCases = 0; bfloat<nbits, es> p, ref; // starting from maxpos iterating to -maxpos, and finally NaR via zero for (typename std::vector < bfloat<nbits, es> >::iterator it = set.end() - 1; it != set.begin(); --it) { p = *it; p--; ref = *(it - 1); if (p != ref) { if (bReportIndividualTestCases) std::cout << " FAIL " << p << " != " << ref << std::endl; nrOfFailedTestCases++; } } return nrOfFailedTestCases; } } // namespace sw::universal
48.948229
150
0.488032
jtodd440
b4c0c367220e00b5bd7deb307dddbb7b3c46d97f
3,403
cpp
C++
src/picotorrent/mainmenu.cpp
kk7945287/pictorr
09bf9ccbd89f0b459cb07e3012ced9c35bea005c
[ "MIT" ]
null
null
null
src/picotorrent/mainmenu.cpp
kk7945287/pictorr
09bf9ccbd89f0b459cb07e3012ced9c35bea005c
[ "MIT" ]
null
null
null
src/picotorrent/mainmenu.cpp
kk7945287/pictorr
09bf9ccbd89f0b459cb07e3012ced9c35bea005c
[ "MIT" ]
null
null
null
#include "mainmenu.hpp" #include "addtorrentdlg.hpp" #include "addtorrentproc.hpp" #include "applicationupdater.hpp" #include "buildinfo.hpp" #include "config.hpp" #include "environment.hpp" #include "preferencesdlg.hpp" #include "sessionstate.hpp" #include "taskbaricon.hpp" #include "translator.hpp" #include "http/httpclient.hpp" #include <libtorrent/add_torrent_params.hpp> #include <libtorrent/session.hpp> #include <libtorrent/torrent_info.hpp> #include <wx/aboutdlg.h> using pt::MainMenu; wxBEGIN_EVENT_TABLE(MainMenu, wxMenuBar) EVT_MENU(wxID_ABOUT, MainMenu::OnAbout) EVT_MENU(ptID_ADD_TORRENTS, MainMenu::OnAddTorrents) EVT_MENU(ptID_ADD_MAGNET_LINK, MainMenu::OnAddMagnetLink) EVT_MENU(ptID_VIEW_PREFERENCES, MainMenu::OnViewPreferences) EVT_MENU(ptID_CHECK_FOR_UPDATES, MainMenu::OnCheckForUpdates) EVT_MENU(wxID_EXIT, MainMenu::OnExit) wxEND_EVENT_TABLE() MainMenu::MainMenu(std::shared_ptr<pt::SessionState> state, std::shared_ptr<pt::Configuration> cfg, std::shared_ptr<pt::Environment> env, std::shared_ptr<pt::ApplicationUpdater> updater, std::shared_ptr<pt::TaskBarIcon> taskBarIcon, std::shared_ptr<pt::Translator> translator) : wxMenuBar(), m_state(state), m_cfg(cfg), m_env(env), m_taskBarIcon(taskBarIcon), m_trans(translator), m_updater(updater) { wxMenu* menuFile = new wxMenu(); menuFile->Append(ptID_ADD_TORRENTS, i18n(m_trans, "amp_add_torrent")); menuFile->Append(ptID_ADD_MAGNET_LINK, i18n(m_trans, "amp_add_magnet_link_s")); /*menuFile->AppendSeparator(); menuFile->Append(wxID_ANY, i18n(m_trans, "amp_create_torrent"));*/ menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT, i18n(m_trans, "amp_exit")); wxMenu* menuView = new wxMenu(); menuView->Append(ptID_VIEW_PREFERENCES, i18n(m_trans, "amp_preferences")); wxMenu* menuHelp = new wxMenu(); menuHelp->Append(ptID_CHECK_FOR_UPDATES, i18n(m_trans, "amp_check_for_update")); menuHelp->AppendSeparator(); menuHelp->Append(wxID_ABOUT, i18n(m_trans, "amp_about")); Append(menuFile, i18n(m_trans, "amp_file")); Append(menuView, i18n(m_trans, "amp_view")); Append(menuHelp, i18n(m_trans, "amp_help")); } void MainMenu::OnAbout(wxCommandEvent& WXUNUSED(event)) { wxAboutDialogInfo aboutInfo; aboutInfo.SetName("PicoTorrent"); aboutInfo.SetVersion(BuildInfo::Version()); aboutInfo.SetDescription(m_trans->Translate("picotorrent_description")); aboutInfo.SetCopyright("(C) 2015-2018"); aboutInfo.SetWebSite("https://picotorrent.org"); aboutInfo.AddDeveloper("Viktor Elofsson"); wxAboutBox(aboutInfo, this->GetFrame()); } void MainMenu::OnAddMagnetLink(wxCommandEvent& event) { AddTorrentProcedure proc(this->GetFrame(), m_cfg, m_trans, m_state); proc.ExecuteMagnet(); } void MainMenu::OnAddTorrents(wxCommandEvent& event) { AddTorrentProcedure proc(this->GetFrame(), m_cfg, m_trans, m_state); proc.Execute(); } void MainMenu::OnCheckForUpdates(wxCommandEvent& event) { m_updater->Check(true); } void MainMenu::OnExit(wxCommandEvent& WXUNUSED(event)) { this->GetFrame()->Close(true); } void MainMenu::OnViewPreferences(wxCommandEvent& WXUNUSED(event)) { PreferencesDialog dlg( this->GetFrame(), m_env, m_cfg, m_state, m_taskBarIcon, m_trans); dlg.ShowModal(); }
29.850877
84
0.727887
kk7945287
b4c1cd8abe323938cc2d3cf894217390128fccb6
7,726
cpp
C++
src/pitts_tensortrain_operator_pybind.cpp
melven/pitts
491f503a99a7d1161a27672955ae53ca6b5d3412
[ "BSD-3-Clause" ]
2
2021-12-31T08:28:17.000Z
2022-01-12T14:48:49.000Z
src/pitts_tensortrain_operator_pybind.cpp
melven/pitts
491f503a99a7d1161a27672955ae53ca6b5d3412
[ "BSD-3-Clause" ]
null
null
null
src/pitts_tensortrain_operator_pybind.cpp
melven/pitts
491f503a99a7d1161a27672955ae53ca6b5d3412
[ "BSD-3-Clause" ]
null
null
null
/*! @file pitts_tensortrain_operator_pybind.cpp * @brief python binding for PITTS::TensorTrainOperator * @author Melven Roehrig-Zoellner <Melven.Roehrig-Zoellner@DLR.de> * @date 2021-02-12 * @copyright Deutsches Zentrum fuer Luft- und Raumfahrt e. V. (DLR), German Aerospace Center * **/ // includes #include <pybind11/pybind11.h> #include <pybind11/stl.h> //#include <pybind11/complex.h> #include <pybind11/numpy.h> #include <string> #include <exception> #include "pitts_tensortrain_operator.hpp" #include "pitts_tensortrain_operator_apply.hpp" #include "pitts_tensortrain_operator_pybind.hpp" #include "pitts_scope_info.hpp" namespace py = pybind11; //! namespace for the library PITTS (parallel iterative tensor train solvers) namespace PITTS { //! namespace for python bindings namespace pybind { //! internal namespace for helper functions namespace { //! helper function for converting an array to a string template<typename T> std::string to_string(const std::vector<T>& v) { std::string result = "["; for(int i = 0; i < v.size(); i++) { if( i > 0 ) result += ", "; result += std::to_string(v[i]); } result += "]"; return result; } //! helper function to obtain a sub-tensor from a TensorTrainOperator template<typename T> py::array_t<T> TensorTrainOperator_getSubTensor(const TensorTrainOperator<T>& TTOp, int d) { const auto& subT = TTOp.tensorTrain().subTensors().at(d); py::array_t<T> array({subT.r1(), TTOp.row_dimensions().at(d), TTOp.column_dimensions().at(d), subT.r2()}); for(int i = 0; i < subT.r1(); i++) for(int j = 0; j < TTOp.row_dimensions()[d]; j++) for(int k = 0; k < TTOp.column_dimensions()[d]; k++) for(int l = 0; l < subT.r2(); l++) *array.mutable_data(i,j,k,l) = subT(i,TTOp.index(d, j, k), l); return array; } //! helper function to set a sub-tensor in a TensorTrainOperator template<typename T> void TensorTrainOperator_setSubTensor(TensorTrainOperator<T>& TTOp, int d, py::array_t<T> array) { auto& subT = TTOp.tensorTrain().editableSubTensors().at(d); if( array.ndim() != 4 ) throw std::invalid_argument("array must have 4 dimensions"); const std::vector<int> required_shape = {subT.r1(), TTOp.row_dimensions().at(d), TTOp.column_dimensions().at(d), subT.r2()}; const std::vector<int> shape = {array.shape(), array.shape()+array.ndim()}; if( shape != required_shape ) throw std::invalid_argument("array has incompatible shape, expected " + to_string<int>(required_shape) + ", got " + to_string<int>(shape)); for(int i = 0; i < shape[0]; i++) for(int j = 0; j < shape[1]; j++) for(int k = 0; k < shape[2]; k++) for(int l = 0; l < shape[3]; l++) subT(i,TTOp.index(d, j, k), l) = *array.data(i,j,k,l); } //! helper function to print the attributes of the TensorTrainOperator object nicely template<typename T> std::string TensorTrainOperator_toString(const TensorTrainOperator<T>& TT) { // helper for getting the template type nicely formatted constexpr auto scope = internal::ScopeInfo::current<T>(); std::string result; result += "PITTS::TensorTrainOperator" + std::string(scope.type_name()) + "\n"; result += " with row dimensions = " + to_string(TT.row_dimensions()) + "\n"; result += " col dimensions = " + to_string(TT.column_dimensions()) + "\n"; result += " ranks = " + to_string(TT.getTTranks()); return result; } //! provide all TensorTrain<T> related classes and functions template<typename T> void init_TensorTrainOperator_helper(py::module& m, const std::string& type_name) { const std::string className = "TensorTrainOperator_" + type_name; py::class_<TensorTrainOperator<T>>(m, className.c_str(), "Simple tensor train operator class") .def(py::init< const std::vector<int>& , const std::vector<int>& >(), py::arg("row_dimensions"), py::arg("col_dimensions"), "Create TensorTrainOperator with given dimensions") .def("row_dimensions", &TensorTrainOperator<T>::row_dimensions, "output tensor dimensions (immutable)") .def("col_dimensions", &TensorTrainOperator<T>::column_dimensions, "input tensor dimensions (immutable)") .def("getSubTensor", &TensorTrainOperator_getSubTensor<T>, py::arg("d"), "Return the rank-4 sub-tensor for dimension 'd'") .def("setSubTensor", &TensorTrainOperator_setSubTensor<T>, py::arg("d"), py::arg("array"), "Set the rank-4 sub-tensor for dimension 'd'") .def("setTTranks", py::overload_cast<int>(&TensorTrainOperator<T>::setTTranks), py::arg("tt_rank"), "set sub-tensor dimensions (TT-ranks), destroying all existing data") .def("setTTranks", py::overload_cast<const std::vector<int>& >(&TensorTrainOperator<T>::setTTranks), py::arg("tt_ranks"), "set sub-tensor dimensions (TT-ranks), destroying all existing data") .def("getTTranks", &TensorTrainOperator<T>::getTTranks, "get current sub-tensor dimensions (TT-ranks)") .def("setZero", &TensorTrainOperator<T>::setZero, "make this a tensor of zeros") .def("setOnes", &TensorTrainOperator<T>::setOnes, "make this a tensor of ones") .def("setEye", &TensorTrainOperator<T>::setEye, "make this an identity operator (if square)") .def("__str__", &TensorTrainOperator_toString<T>, "Print the attributes of the given TensorTrainOperator object"); m.def("copy", py::overload_cast< const TensorTrainOperator<T>&, TensorTrainOperator<T>& >(&copy<T>), py::arg("source"), py::arg("destination"), "explicitly copy a TensorTrainOperator object"); m.def("axpby", py::overload_cast< T, const TensorTrainOperator<T>&, T, TensorTrainOperator<T>&, T>(&axpby<T>), py::arg("alpha"), py::arg("TTOpx"), py::arg("beta"), py::arg("TTOpy"), py::arg("rankTolerance")=std::sqrt(std::numeric_limits<T>::epsilon()), "Scale and add one tensor train operator to another\n\nCalculate TTOpy <- alpha*TTOpx + beta*TTOpy\n\nBoth tensors must be leftNormalized"); m.def("randomize", py::overload_cast< TensorTrainOperator<T>& >(&randomize<T>), py::arg("TT"), "fill a tensor train operator format with random values (keeping current TT-ranks)"); m.def("normalize", py::overload_cast< TensorTrainOperator<T>&, T, int >(&normalize<T>), py::arg("TT"), py::arg("rankTolerance")=std::sqrt(std::numeric_limits<T>::epsilon()), py::arg("maxRank")=std::numeric_limits<int>::max(), "TT-rounting: truncate tensor train by two normalization sweeps (first right to left, then left to right)"); m.def("apply", py::overload_cast< const TensorTrainOperator<T>&, const TensorTrain<T>&, TensorTrain<T>& >(&apply<T>), py::arg("TTOp"), py::arg("TTx"), py::arg("TTy"), "Apply a tensor train operator\n\nCalculate TTy <- TTOp * TTx"); } } // create pybind11-wrapper for PITTS::TensorTrain void init_TensorTrainOperator(py::module& m) { init_TensorTrainOperator_helper<float>(m, "float"); init_TensorTrainOperator_helper<double>(m, "double"); //init_TensorTrain_helper<std::complex<float>>(m, "float_complex"); //init_TensorTrain_helper<std::complex<double>>(m, "double_complex"); } } }
49.845161
201
0.631504
melven
b4c2f78c5fba2ddf48c12f86064df1daf823b796
322
cpp
C++
CookieEngine/src/ECS/ComponentScript.cpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/src/ECS/ComponentScript.cpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/src/ECS/ComponentScript.cpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
#include "ECS/ComponentScript.hpp" using namespace Cookie::ECS; void ComponentScript::ToDefault() { scripts.clear(); } void ComponentScript::Start() { for (int i = 0; i < scripts.size(); ++i) scripts[i].Start(); } void ComponentScript::Update() { for (int i = 0; i < scripts.size(); ++i) scripts[i].Update(); }
16.947368
41
0.649068
qbleuse
b4c4a9dd0fb9cab56374be204c37ac7a7600943d
14,129
cpp
C++
Extensions/ZilchShaders/ArithmeticInstructions.cpp
jayrulez/ZeroCore
5da0e2537bc520c3b7ad461e676482382dd5a3e8
[ "MIT" ]
1
2022-03-26T21:08:19.000Z
2022-03-26T21:08:19.000Z
Extensions/ZilchShaders/ArithmeticInstructions.cpp
jodavis42/PhysicsSandbox
3119caaa77721041440cdc1b3cf96d4bd9e2d98b
[ "MIT" ]
null
null
null
Extensions/ZilchShaders/ArithmeticInstructions.cpp
jodavis42/PhysicsSandbox
3119caaa77721041440cdc1b3cf96d4bd9e2d98b
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// /// /// Authors: Joshua Davis /// Copyright 2018, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #include "Precompiled.hpp" namespace Zero { // Resolves a binary operator node given the expected return type. void ResolveBinaryOp(ZilchSpirVFrontEnd* translator, Zilch::BinaryOperatorNode* binaryOpNode, OpType opType, ZilchSpirVFrontEndContext* context) { if(binaryOpNode->OperatorInfo.Io & Zilch::IoMode::WriteLValue) translator->PerformBinaryAssignmentOp(binaryOpNode, opType, context); else translator->PerformBinaryOp(binaryOpNode, opType, context); } // Resolves a binary operator node where the lhs and rhs of the node have already been resolved. // This can be necessary when one of the sides in the node has to undergo a transformation first // (e.g vector / scalar has to first promote the scalar to a vector) void ResolveBinaryOp(ZilchSpirVFrontEnd* translator, Zilch::BinaryOperatorNode* binaryOpNode, OpType opType, IZilchShaderIR* lhs, IZilchShaderIR* rhs, ZilchSpirVFrontEndContext* context) { if(binaryOpNode->OperatorInfo.Io & Zilch::IoMode::WriteLValue) translator->PerformBinaryAssignmentOp(binaryOpNode, opType, lhs, rhs, context); else translator->PerformBinaryOp(binaryOpNode, opType, lhs, rhs, context); } template <OpType opType> void ResolveIntIncDecUnaryOperator(ZilchSpirVFrontEnd* translator, Zilch::UnaryOperatorNode* unaryOpNode, ZilchSpirVFrontEndContext* context) { // Create the int literal '1' IZilchShaderIR* constantOne = translator->GetIntegerConstant(1, context); translator->PerformUnaryIncDecOp(unaryOpNode, constantOne, opType, context); } template <OpType opType> void ResolveFloatIncDecUnaryOperator(ZilchSpirVFrontEnd* translator, Zilch::UnaryOperatorNode* unaryOpNode, ZilchSpirVFrontEndContext* context) { // Create the float literal '1' ZilchShaderIRType* floatType = translator->FindType(ZilchTypeId(float), unaryOpNode, context); IZilchShaderIR* constantOne = translator->GetConstant(floatType, 1.0f, context); translator->PerformUnaryIncDecOp(unaryOpNode, constantOne, opType, context); } void ResolveFMod(ZilchSpirVFrontEnd* translator, Zilch::FunctionCallNode* functionCallNode, Zilch::MemberAccessNode* memberAccessNode, ZilchSpirVFrontEndContext* context) { ResolveStaticBinaryFunctionOp(translator, functionCallNode, spv::OpFMod, context); } void ResolveDot(ZilchSpirVFrontEnd* translator, Zilch::FunctionCallNode* functionCallNode, Zilch::MemberAccessNode* memberAccessNode, ZilchSpirVFrontEndContext* context) { ResolveStaticBinaryFunctionOp(translator, functionCallNode, spv::OpDot, context); } // Resolves vector op vector(scalar). Needed for some operations like vector / scalar which has to // turn into vector / vector(scalar) since the componentized operations don't exist. template <OpType opType> void ResolveVectorOpSplatScalar(ZilchSpirVFrontEnd* translator, Zilch::BinaryOperatorNode* binaryOpNode, ZilchSpirVFrontEndContext* context) { BasicBlock* currentBlock = context->GetCurrentBlock(); // Get the vector operand IZilchShaderIR* vectorOperand = translator->WalkAndGetResult(binaryOpNode->LeftOperand, context); // Convert the scalar operand into a vector of the same type as the left hand side ZilchShaderIRType* vectorType = translator->FindType(binaryOpNode->LeftOperand->ResultType, binaryOpNode); ZilchShaderIROp* scalarOperand = translator->WalkAndGetValueTypeResult(binaryOpNode->RightOperand, context); ZilchShaderIROp* splattedScalarOperand = translator->ConstructCompositeFromScalar(currentBlock, vectorType, scalarOperand, context); // Perform the op ResolveBinaryOp(translator, binaryOpNode, opType, vectorOperand, splattedScalarOperand, context); } template <OpType opType> void ResolveSimpleStaticBinaryFunctionOp(ZilchSpirVFrontEnd* translator, Zilch::FunctionCallNode* functionCallNode, Zilch::MemberAccessNode* memberAccessNode, ZilchSpirVFrontEndContext* context) { ResolveStaticBinaryFunctionOp(translator, functionCallNode, opType, context); } // Some binary functions are special and have to be flipped due to the column vs. row major differences of zilch and spirv. void ResolveFlippedStaticBinaryFunctionOp(ZilchSpirVFrontEnd* translator, Zilch::FunctionCallNode* functionCallNode, OpType opType, ZilchSpirVFrontEndContext* context) { // Get the result type ZilchShaderIRType* resultType = translator->FindType(functionCallNode->ResultType, functionCallNode); // Walk each operand IZilchShaderIR* operand1 = translator->WalkAndGetValueTypeResult(functionCallNode->Arguments[0], context); IZilchShaderIR* operand2 = translator->WalkAndGetValueTypeResult(functionCallNode->Arguments[1], context); // Generate the fmod op IZilchShaderIR* operationOp = translator->BuildCurrentBlockIROp(opType, resultType, operand2, operand1, context); context->PushIRStack(operationOp); } void ResolveMatrixTimesVector(ZilchSpirVFrontEnd* translator, Zilch::FunctionCallNode* functionCallNode, Zilch::MemberAccessNode* memberAccessNode, ZilchSpirVFrontEndContext* context) { ResolveFlippedStaticBinaryFunctionOp(translator, functionCallNode, OpType::OpVectorTimesMatrix, context); } void ResolveMatrixTimesMatrix(ZilchSpirVFrontEnd* translator, Zilch::FunctionCallNode* functionCallNode, Zilch::MemberAccessNode* memberAccessNode, ZilchSpirVFrontEndContext* context) { ResolveFlippedStaticBinaryFunctionOp(translator, functionCallNode, OpType::OpMatrixTimesMatrix, context); } void ResolveMatrixTranspose(ZilchSpirVFrontEnd* translator, Zilch::FunctionCallNode* functionCallNode, Zilch::MemberAccessNode* memberAccessNode, ZilchSpirVFrontEndContext* context) { // Get the result type ZilchShaderIRType* resultType = translator->FindType(functionCallNode->ResultType, functionCallNode); // Walk each operand IZilchShaderIR* operand = translator->WalkAndGetValueTypeResult(functionCallNode->Arguments[0], context); // Generate the transpose op IZilchShaderIR* operationOp = translator->BuildCurrentBlockIROp(OpType::OpTranspose, resultType, operand, context); context->PushIRStack(operationOp); } // Register function callbacks for the various arithmetic operators (see Arithmetic Instructions in the spir-v spec). void RegisterArithmeticOps(ZilchSpirVFrontEnd* translator, ZilchShaderIRLibrary* shaderLibrary, ZilchTypeGroups& types) { Zilch::Core& core = Zilch::Core::GetInstance(); Zilch::BoundType* mathType = core.MathType; TypeResolvers& mathTypeResolver = shaderLibrary->mTypeResolvers[mathType]; OperatorResolvers& opResolvers = shaderLibrary->mOperatorResolvers; Zilch::BoundType* realType = core.RealType; Zilch::BoundType* intType = core.IntegerType; opResolvers.RegisterUnaryOpResolver(intType, Zilch::Grammar::Increment, ResolveIntIncDecUnaryOperator<OpType::OpIAdd>); opResolvers.RegisterUnaryOpResolver(intType, Zilch::Grammar::Decrement, ResolveIntIncDecUnaryOperator<OpType::OpISub>); opResolvers.RegisterUnaryOpResolver(realType, Zilch::Grammar::Increment, ResolveFloatIncDecUnaryOperator<OpType::OpFAdd>); opResolvers.RegisterUnaryOpResolver(realType, Zilch::Grammar::Decrement, ResolveFloatIncDecUnaryOperator<OpType::OpFSub>); // Register ops that are on all float vector types for(size_t i = 0; i < types.mRealVectorTypes.Size(); ++i) { Zilch::BoundType* zilchType = types.mRealVectorTypes[i]; String zilchTypeName = zilchType->ToString(); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::AssignmentAdd, ResolveBinaryOperator<spv::OpFAdd>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::AssignmentSubtract, ResolveBinaryOperator<OpType::OpFSub>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::AssignmentMultiply, ResolveBinaryOperator<OpType::OpFMul>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::AssignmentDivide, ResolveBinaryOperator<OpType::OpFDiv>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::AssignmentModulo, ResolveBinaryOperator<OpType::OpFMod>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::Add, ResolveBinaryOperator<spv::OpFAdd>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::Subtract, ResolveBinaryOperator<OpType::OpFSub>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::Multiply, ResolveBinaryOperator<OpType::OpFMul>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::Divide, ResolveBinaryOperator<OpType::OpFDiv>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::Modulo, ResolveBinaryOperator<OpType::OpFMod>); opResolvers.RegisterUnaryOpResolver(zilchType, Zilch::Grammar::Subtract, ResolveUnaryOperator<OpType::OpFNegate>); mathTypeResolver.RegisterFunctionResolver(GetStaticFunction(mathType, "FMod", zilchTypeName, zilchTypeName), ResolveFMod); } // Register ops that are only on float vector types (no scalars). Some of these are because of zilch and not spirv. for(size_t i = 1; i < types.mRealVectorTypes.Size(); ++i) { Zilch::BoundType* zilchType = types.mRealVectorTypes[i]; String zilchTypeName = zilchType->ToString(); mathTypeResolver.RegisterFunctionResolver(GetStaticFunction(mathType, "Dot", zilchTypeName, zilchTypeName), ResolveDot); opResolvers.RegisterBinaryOpResolver(zilchType, realType, Zilch::Grammar::Multiply, ResolveBinaryOperator<spv::OpVectorTimesScalar>); opResolvers.RegisterBinaryOpResolver(zilchType, realType, Zilch::Grammar::AssignmentMultiply, ResolveBinaryOperator<OpType::OpVectorTimesScalar>); opResolvers.RegisterBinaryOpResolver(zilchType, realType, Zilch::Grammar::Divide, ResolveVectorOpSplatScalar<OpType::OpFDiv>); opResolvers.RegisterBinaryOpResolver(zilchType, realType, Zilch::Grammar::AssignmentDivide, ResolveVectorOpSplatScalar<OpType::OpFDiv>); } // Register ops that are on all integer vector types for(size_t i = 0; i < types.mIntegerVectorTypes.Size(); ++i) { Zilch::BoundType* zilchType = types.mIntegerVectorTypes[i]; String zilchTypeName = zilchType->ToString(); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::AssignmentAdd, ResolveBinaryOperator<spv::OpIAdd>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::AssignmentSubtract, ResolveBinaryOperator<OpType::OpISub>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::AssignmentMultiply, ResolveBinaryOperator<OpType::OpIMul>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::AssignmentDivide, ResolveBinaryOperator<OpType::OpSDiv>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::AssignmentModulo, ResolveBinaryOperator<OpType::OpSMod>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::Add, ResolveBinaryOperator<spv::OpIAdd>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::Subtract, ResolveBinaryOperator<OpType::OpISub>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::Multiply, ResolveBinaryOperator<OpType::OpIMul>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::Divide, ResolveBinaryOperator<OpType::OpSDiv>); opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::Modulo, ResolveBinaryOperator<OpType::OpSMod>); opResolvers.RegisterUnaryOpResolver(zilchType, Zilch::Grammar::Subtract, ResolveUnaryOperator<OpType::OpSNegate>); } // Register ops that are only on int vector types (no scalars). Some of these are because of zilch and not spirv. // @JoshD: SpirV doesn't have any actual vector operations on integers. // Some could be supported using more complicated instructions (e.g. vector * scalar = vector * vector(scalar)) for(size_t i = 1; i < types.mIntegerVectorTypes.Size(); ++i) { Zilch::BoundType* zilchType = types.mIntegerVectorTypes[i]; String zilchTypeName = zilchType->ToString(); // VectorTimesScalar is only on real types //ZilchTypePair vectorScalarTypePair(zilchType, intType); //translator->mBinaryOpInstructions[BinaryOpTypeId(vectorScalarTypePair, Zilch::Grammar::Multiply)] = OpType::OpVectorTimesScalar; //translator->mBinaryOpInstructions[BinaryOpTypeId(vectorScalarTypePair, Zilch::Grammar::AssignmentMultiply)] = OpType::OpVectorTimesScalar; } // Register all real matrix instructions. for(size_t y = 2; y <= 4; ++y) { for(size_t x = 2; x <= 4; ++x) { Zilch::BoundType* zilchType = types.GetMatrixType(y, x); String zilchTypeName = zilchType->ToString(); Zilch::BoundType* vectorType = types.mRealVectorTypes[x - 1]; opResolvers.RegisterBinaryOpResolver(zilchType, zilchType, Zilch::Grammar::Multiply, ResolveBinaryOperator<spv::OpMatrixTimesScalar>); mathTypeResolver.RegisterFunctionResolver(GetStaticFunction(mathType, "Transpose", zilchTypeName), ResolveMatrixTranspose); // Matrix times vector mathTypeResolver.RegisterFunctionResolver(GetStaticFunction(mathType, "Multiply", zilchTypeName, vectorType->ToString()), ResolveMatrixTimesVector); // Iterate over all of the other matrix dimensions to make the multiplication functions // (e.g. Real2x3 * real3x2, Real2x3 * Real3x3, etc...) for(size_t z = 2; z <= 4; ++z) { Zilch::BoundType* rhsMatrixType = types.GetMatrixType(x, z); mathTypeResolver.RegisterFunctionResolver(GetStaticFunction(mathType, "Multiply", zilchTypeName, rhsMatrixType->ToString()), ResolveMatrixTimesMatrix); } } } } }//namespace Zero
59.868644
195
0.774011
jayrulez
b4c66782bb52ce3940309a465d2528c56109347a
19,490
hpp
C++
sources/Common/Xml.hpp
palchukovsky/TunnelEx
ec645271ab8b79225e378345ff108795110c57de
[ "Apache-2.0" ]
null
null
null
sources/Common/Xml.hpp
palchukovsky/TunnelEx
ec645271ab8b79225e378345ff108795110c57de
[ "Apache-2.0" ]
null
null
null
sources/Common/Xml.hpp
palchukovsky/TunnelEx
ec645271ab8b79225e378345ff108795110c57de
[ "Apache-2.0" ]
null
null
null
/************************************************************************** * Created: 2007/10/29 13:38 * Author: Eugene V. Palchukovsky * E-mail: eugene@palchukovsky.com * ------------------------------------------------------------------- * Project: TunnelEx * URL: http://tunnelex.net **************************************************************************/ #ifndef INCLUDED_FILE__TUNNELEX__XmlDocument_h__0710291338 #define INCLUDED_FILE__TUNNELEX__XmlDocument_h__0710291338 #include "Format.hpp" #include "StringFwd.hpp" #include <libxml/tree.h> #include <libxml/xmlschemas.h> #include <libxml/xpath.h> #include <libxml/xmlsave.h> #include "CompileWarningsBoost.h" # include <boost/noncopyable.hpp> # include <boost/shared_ptr.hpp> # include <boost/algorithm/string.hpp> #include "CompileWarningsBoost.h" #include <string> #include <vector> #ifdef _DEBUG # pragma comment(lib, "libxml2_dbg.lib") #else // _DEBUG # pragma comment(lib, "libxml2.lib") #endif // _DEBUG namespace TunnelEx { namespace Helpers { namespace Xml { class Exception : public std::exception { public: explicit Exception(const char *what) : std::exception(what) { //...// } }; inline void Free(void *mem) { xmlFree(mem); } struct DebugData { static bool & GetErrorDisablingResetFlag() { static bool isReseted = false; return isReseted; } static bool CheckErrorDisablingResetFlag() { bool &isReseted = GetErrorDisablingResetFlag(); const bool result = isReseted; isReseted = true; return result; } }; inline void SetErrorsHandler(void(*func)(void *ctx, const char *msg, ...)) { assert(func); assert(!DebugData::CheckErrorDisablingResetFlag()); initGenericErrorDefaultFunc(&func); } class Node; //! XML document implementation. class Document { friend class Schema; friend class XPath; public: class Handler { public: explicit Handler(xmlDocPtr doc) : m_doc(doc) { assert(m_doc != NULL); } Handler(const Handler &rhs) : m_doc(xmlCopyDoc(rhs.m_doc, true)) { assert(m_doc != NULL); } ~Handler() { xmlFreeDoc(m_doc); } xmlDocPtr Get() { return m_doc; } private: const Handler & operator =(const Handler &); private: xmlDocPtr m_doc; }; class ParseException : public Exception { public: explicit ParseException(const char *what) : Exception(what) { //...// } }; protected: //! Protected, use Document::CreateNew, Document::LoadFromMemory and Document::LoadFromFile. explicit Document(boost::shared_ptr<Handler> handle) : m_handler(handle) { // assert(DebugData::GetErrorDisablingResetFlag()); } public: explicit Document(const Document &rhs) : m_handler(rhs.m_handler) { // assert(DebugData::GetErrorDisablingResetFlag()); } const Document & operator =(const Document &rhs) { Document(rhs).Swap(*this); } void Swap(Document &rhs) throw () { boost::shared_ptr<Handler> tmpHandler(m_handler); m_handler = rhs.m_handler; rhs.m_handler = tmpHandler; } //! Creates new empty document with root element. static boost::shared_ptr<Document> CreateNew(const char *rootElemenName) { boost::shared_ptr<Handler> handler( new Handler(xmlNewDoc(reinterpret_cast<xmlChar *>("1.0")))); xmlDocSetRootElement( handler->Get(), xmlNewNode(NULL, reinterpret_cast<const xmlChar *>(rootElemenName))); return boost::shared_ptr<Document>(new Document(handler)); } //! Creates new document, duplicate. static boost::shared_ptr<Document> CreateDuplicate(Document &doc) { boost::shared_ptr<Handler> handler( new Handler(xmlCopyDoc(doc.m_handler->Get(), 1))); return boost::shared_ptr<Document>(new Document(handler)); } template<class XmlString> static boost::shared_ptr<Document> LoadFromString(const XmlString &xmlString) { # pragma warning(push) # pragma warning(disable: 4244) xmlDocPtr docPtr = xmlReadMemory( reinterpret_cast<const char *>(xmlString.GetCStr()), xmlString.GetLength() * sizeof(XmlString::value_type), NULL, NULL, 0); # pragma warning(pop) if (docPtr == NULL) { throw ParseException( "Could not parse XML-string, " "string has an invalid format or empty."); } boost::shared_ptr<Handler> handler(new Handler(docPtr)); return boost::shared_ptr<Document>(new Document(handler)); } template<> static boost::shared_ptr<Document> LoadFromString<std::string>( const std::string &xmlString) { xmlDocPtr docPtr = xmlReadMemory( reinterpret_cast<const char *>(xmlString.c_str()), int(xmlString.size() * sizeof(std::string::value_type)), NULL, NULL, 0); if (docPtr == NULL) { throw ParseException( "Could not parse XML-string, " "string has an invalid format or empty."); } boost::shared_ptr<Handler> handler(new Handler(docPtr)); return boost::shared_ptr<Document>(new Document(handler)); } static boost::shared_ptr<Document> LoadFromFile(const std::string &); static boost::shared_ptr<Document> LoadFromFile(const std::wstring &); void Dump(std::wstring &buffer) const; void Dump(TunnelEx::UString &) const; void Dump(TunnelEx::WString &buffer) const; bool Save(const std::string &fileName) const; bool Save(const std::wstring &fileName) const; boost::shared_ptr<Node> GetRoot(); boost::shared_ptr<const Node> GetRoot() const { return (const_cast<Document *>(this))->GetRoot(); } void SetRoot(boost::shared_ptr<Node>); boost::shared_ptr<XPath> GetXPath(); boost::shared_ptr<const XPath> GetXPath() const { return (const_cast<Document *>(this))->GetXPath(); } private: boost::shared_ptr<Handler> m_handler; }; ////////////////////////////////////////////////////////////////////////// typedef std::vector<boost::shared_ptr<Node> > NodeCollection; typedef std::vector<boost::shared_ptr<const Node> > ConstNodeCollection; //! XML-node implementation. class Node : private boost::noncopyable { friend class Schema; friend class XPath; public: explicit Node( boost::shared_ptr<Document::Handler> doc, xmlNodePtr node) : m_node(node), m_doc(doc) { //...// } ~Node() throw() { //...// } public: boost::shared_ptr<XPath> Node::GetXPath(); boost::shared_ptr<const XPath> GetXPath() const { return (const_cast<Node *>(this))->GetXPath(); } template<class String> String & GetName(String &destinationBuffer) const { destinationBuffer = reinterpret_cast<const String::value_type *>(m_node->name); return destinationBuffer; } template<> TunnelEx::WString & GetName(WString &destinationBuffer) const; template<> std::wstring & GetName(std::wstring &destinationBuffer) const; template<class String> String & GetContent(String &destinationBuffer) const { xmlChar *contentPtr = xmlNodeGetContent(m_node); boost::shared_ptr<xmlChar> content(contentPtr, &Free); destinationBuffer = reinterpret_cast<String::value_type *>(contentPtr); return destinationBuffer; } template<> TunnelEx::WString & GetContent(TunnelEx::WString &destinationBuffer) const; template<> std::wstring & GetContent(std::wstring &destinationBuffer) const; void SetContent(const xmlChar *const value) { xmlChar *const encodedValuePtr = xmlEncodeEntitiesReentrant( m_doc->Get(), value); assert(encodedValuePtr != 0); boost::shared_ptr<xmlChar> encodedValue(encodedValuePtr, &Free); xmlNodeSetContent(m_node, encodedValuePtr); } void SetContent(const TunnelEx::String &); void SetContent(const TunnelEx::UString &); void SetContent(const TunnelEx::WString &); void SetContent(const char *); void SetContent(const wchar_t *); void SetContent(const std::string &); void SetContent(const std::wstring &); bool HasAttribute(const char *attributeName) const { return xmlHasProp( m_node, reinterpret_cast<const xmlChar *>(attributeName)) != NULL; } template<class String> String & GetAttribute( const char *attributeName, String &destinationBuffer) const { xmlChar *attributeValPtr = xmlGetProp( m_node, reinterpret_cast<const xmlChar *>(attributeName)); if (attributeValPtr == NULL) { throw Exception("Unknown XML-attribute."); } boost::shared_ptr<xmlChar> attributeVal(attributeValPtr, &Free); destinationBuffer = reinterpret_cast<String::value_type *>(attributeValPtr); return destinationBuffer; } template<> TunnelEx::WString & GetAttribute( const char *attributeName, TunnelEx::WString &destinationBuffer) const; template<> std::wstring & GetAttribute( const char *attributeName, std::wstring &destinationBuffer) const; template<typename T> void SetAttribute(const char *attributeName, const T &value) { xmlSetProp( m_node, reinterpret_cast<const xmlChar *>(attributeName), reinterpret_cast<const xmlChar *>(value)); } template<> void SetAttribute(const char *attributeName, const TunnelEx::UString &value); template<> void SetAttribute(const char *attributeName, const std::wstring &value); template<> void SetAttribute(const char *attributeName, const TunnelEx::WString &value); template<> void SetAttribute(const char *attributeName, const std::string &value) { SetAttribute(attributeName, value.c_str()); } //! Returns first child element element or empty pointer with NULL //! if not exists. boost::shared_ptr<const Node> GetChildElement() const { return (const_cast<Node *>(this))->GetChildElement(); } //! Returns first child element element or empty pointer with NULL //! if not exists. boost::shared_ptr<Node> GetChildElement() { for (xmlNodePtr i = m_node->children; i; i = i->next) { if (i->type == XML_ELEMENT_NODE) { return boost::shared_ptr<Node>(new Node(m_doc, i)); } } return boost::shared_ptr<Node>(); } //! Returns next element or empty pointer with NULL if not exists. boost::shared_ptr<Node> GetNextElement() { for (xmlNodePtr i = m_node->next; i; i = i->next) { if (i->type == XML_ELEMENT_NODE) { return boost::shared_ptr<Node>(new Node(m_doc, i)); } } return boost::shared_ptr<Node>(); } //! Returns next element or empty pointer with NULL if not exists. boost::shared_ptr<const Node> GetNextElement() const { return (const_cast<Node *>(this))->GetNextElement(); } boost::shared_ptr<Node> GetParent() { if (!m_node->parent) { return boost::shared_ptr<Node>(); } assert(m_node->parent->type == XML_ELEMENT_NODE); return boost::shared_ptr<Node>(new Node(m_doc, m_node->parent)); } boost::shared_ptr<const Node> GetParent() const { return (const_cast<Node *>(this))->GetParent(); } boost::shared_ptr<Node> CreateNewChild(const char *name) { return boost::shared_ptr<Node>(new Node( m_doc, xmlNewChild( m_node, NULL, reinterpret_cast<const xmlChar *>(name), NULL))); } private: mutable xmlNodePtr m_node; boost::shared_ptr<Document::Handler> m_doc; }; ////////////////////////////////////////////////////////////////////////// void DumpSchemaValidityError(void *, const char *, ...); void DumpSchemaParseError(void *, const char *, ...); //! XML-Schema implementation. class Schema : private boost::noncopyable { public: class ParseException : public Document::ParseException { public: explicit ParseException(const char *what) : Document::ParseException(what) { //...// } }; public: Schema(const std::string &schemaFile) { try { m_schemaDoc = Document::LoadFromFile(schemaFile); } catch (const Document::ParseException &ex) { TunnelEx::Format exceptionWhat( "Could not load schema document: \"%1%\"."); exceptionWhat % ex.what(); throw ParseException(exceptionWhat.str().c_str()); } m_parserContext = xmlSchemaNewDocParserCtxt( m_schemaDoc->m_handler->Get()); assert(m_parserContext); xmlSchemaSetParserErrors( m_parserContext, &DumpSchemaParseError, &DumpSchemaParseError, NULL); m_schema = xmlSchemaParse(m_parserContext); assert(m_schema); m_validateContext = xmlSchemaNewValidCtxt(m_schema); assert(m_validateContext); } ~Schema() { xmlSchemaFreeValidCtxt(m_validateContext); xmlSchemaFree(m_schema); xmlSchemaFreeParserCtxt(m_parserContext); } public: bool Validate( Document &doc, std::string *validateError = NULL) const { SetValidateErrorHandler(validateError); return xmlSchemaValidateDoc(m_validateContext, doc.m_handler->Get()) == 0; } bool Validate(Node &node, std::string *validateError = NULL) const { SetValidateErrorHandler(validateError); return xmlSchemaValidateOneElement(m_validateContext, node.m_node) == 0; } protected: void SetValidateErrorHandler(std::string *validateError = NULL) const { if (validateError) { validateError->clear(); } xmlSchemaSetValidErrors( m_validateContext, &DumpSchemaValidityError, &DumpSchemaValidityError, validateError); } private: //! \todo: try to implement with xmlSchemaNewParserCtxt(URL) boost::shared_ptr<Document> m_schemaDoc; xmlSchemaParserCtxtPtr m_parserContext; xmlSchemaPtr m_schema; xmlSchemaValidCtxtPtr m_validateContext; }; //! \todo: move to cpp-file when it will be a lib-project inline void DumpSchemaValidityError(void *ctx, const char *msg, ...) { # ifndef _DEBUG if (!ctx) { return; } # endif // _DEBUG va_list vl; int i; va_start(vl, msg); union Printable_t { int i; double f; char c; char *s; } Printable; try { TunnelEx::Format messagef(msg); for (i = 1; msg[i] != '\0'; ++i) { switch (msg[i]) { case 'i': Printable.i = va_arg(vl, int); messagef % Printable.i; break; case 'f': Printable.f = va_arg(vl, double); messagef % Printable.f; break; case 'c': Printable.c = va_arg(vl, char); messagef % Printable.c; break; case 's': Printable.s = va_arg(vl, char*); messagef % Printable.s; break; default: break; } } std::string message = messagef.str(); boost::trim(message); # ifndef _DEBUG *(reinterpret_cast<std::string*>(ctx)) = message; # else // _DEBUG if (ctx) { *(reinterpret_cast<std::string *>(ctx)) = message; } # endif // _DEBUG } catch (...) { assert(false); } va_end(vl); } //! \todo: move to cpp-file when it will be a lib-project inline void DumpSchemaParseError(void *, const char *msg, ...) { va_list vl; int i; va_start(vl, msg); union Printable_t { int i; double f; char c; char *s; } Printable; std::string message; try { TunnelEx::Format messagef(msg); for (i = 1; msg[i] != '\0'; ++i) { switch (msg[i]) { case 'i': Printable.i = va_arg(vl, int); messagef % Printable.i; break; case 'f': Printable.f = va_arg(vl, double); messagef % Printable.f; break; case 'c': Printable.c = va_arg(vl, char); messagef % Printable.c; break; case 's': Printable.s = va_arg(vl, char*); messagef % Printable.s; break; default: break; } } message = messagef.str(); boost::trim(message); } catch (...) { assert(false); } va_end(vl); throw Schema::ParseException(message.c_str()); } ////////////////////////////////////////////////////////////////////////// //! XPath implementation. class XPath : private boost::noncopyable { public: explicit XPath(boost::shared_ptr<Document::Handler> docHandler) : m_doc(docHandler), m_context(xmlXPathNewContext(m_doc->Get())) { assert(m_context); } explicit XPath(Node &node) : m_doc(node.m_doc), m_context(xmlXPathNewContext(m_doc->Get())) { assert(m_context); m_context->node = node.m_node; } ~XPath() { xmlXPathFreeContext(m_context); } public: //! Returns first node or nil if nothing found. boost::shared_ptr<const Node> Query(const char *xpathExpression) const { return (const_cast<XPath *>(this))->Query(xpathExpression); } //! Returns first node or nil if nothing found. boost::shared_ptr<Node> Query(const char *xpathExpression) { boost::shared_ptr<Node> result; boost::shared_ptr<xmlXPathObject> xpathObj( EvalExpression(xpathExpression)); const xmlNodeSet *const nodeSetVal = xpathObj->nodesetval; if (xmlXPathNodeSetIsEmpty(nodeSetVal)) { return result; } for (int i = 0; i < nodeSetVal->nodeNr; ++i) { xmlNode *const nodeTab = nodeSetVal->nodeTab[i]; assert(nodeTab); if ( nodeTab->type == XML_ELEMENT_NODE || nodeTab->type == XML_ATTRIBUTE_NODE) { result.reset(new Node(m_doc, nodeTab)); break; } } return result; } void Query( const char *xpathExpression, ConstNodeCollection &result, int nodesLimit = 0) const { (const_cast<XPath *>(this)) ->QueryCollectionImpl(xpathExpression, result, nodesLimit); } void Query( const char *xpathExpression, NodeCollection &result, int nodesLimit = 0) { QueryCollectionImpl(xpathExpression, result, nodesLimit); } protected: boost::shared_ptr<xmlXPathObject> EvalExpression( const char *xpathExpression) const { xmlXPathObjectPtr xpathObjPtr = xmlXPathEvalExpression( reinterpret_cast<const xmlChar *>(xpathExpression), m_context); if (xpathObjPtr == NULL) { TunnelEx::Format exceptionWhat( "Unable to evaluate XPath expression \"%1%\"."); exceptionWhat % xpathExpression; throw Exception(exceptionWhat.str().c_str()); } return boost::shared_ptr<xmlXPathObject>( xpathObjPtr, &xmlXPathFreeObject); } template<class Collection> void QueryCollectionImpl( const char *xpathExpression, Collection &result, int nodesLimit = 0) { Collection resultTmp; boost::shared_ptr<xmlXPathObject> xpathObj( EvalExpression(xpathExpression)); const xmlNodeSet *const nodeSetVal = xpathObj->nodesetval; if (xmlXPathNodeSetIsEmpty(nodeSetVal)) { result.resize(0); return; } if (!nodesLimit || nodesLimit > nodeSetVal->nodeNr) { nodesLimit = nodeSetVal->nodeNr; } resultTmp.reserve(nodesLimit); for (int i = 0; i < nodesLimit; ++i) { xmlNode *const nodeTab = nodeSetVal->nodeTab[i]; assert(nodeTab); if ( nodeTab->type == XML_ELEMENT_NODE || nodeTab->type == XML_ATTRIBUTE_NODE) { resultTmp.push_back( Collection::value_type(new Node(m_doc, nodeTab))); } } resultTmp.swap(result); } private: boost::shared_ptr<Document::Handler> m_doc; xmlXPathContextPtr m_context; }; ////////////////////////////////////////////////////////////////////////// //! \todo: move to cpp-file when it will be a lib-project inline boost::shared_ptr<Node> Document::GetRoot() { xmlNodePtr ptr = xmlDocGetRootElement(m_handler->Get()); if (ptr == NULL) { throw ParseException("XML-document has not root element."); } return boost::shared_ptr<Node>(new Node(m_handler, ptr)); } inline boost::shared_ptr<XPath> Document::GetXPath() { return boost::shared_ptr<XPath>(new XPath(m_handler)); } inline boost::shared_ptr<XPath> Node::GetXPath() { return boost::shared_ptr<XPath>(new XPath(*this)); } } } } #endif // INCLUDED_FILE__TUNNELEX__XmlDocument_h__0710291338
26.091031
94
0.659877
palchukovsky
b4c7daef89d1e3a7b5d3138023e1f9173c0681a0
6,554
cc
C++
engines/ep/src/connmap.cc
paolococchi/kv_engine
40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45
[ "BSD-3-Clause" ]
1
2019-06-13T07:33:09.000Z
2019-06-13T07:33:09.000Z
engines/ep/src/connmap.cc
paolococchi/kv_engine
40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45
[ "BSD-3-Clause" ]
null
null
null
engines/ep/src/connmap.cc
paolococchi/kv_engine
40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45
[ "BSD-3-Clause" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> #include <limits> #include <queue> #include <set> #include <string> #include <vector> #include <daemon/tracing.h> #include <phosphor/phosphor.h> #include "conn_notifier.h" #include "connhandler.h" #include "connmap.h" #include "dcp/backfill-manager.h" #include "dcp/consumer.h" #include "dcp/producer.h" #include "executorpool.h" size_t ConnMap::vbConnLockNum = 32; /** * A task to manage connections. */ class ConnManager : public GlobalTask { public: ConnManager(EventuallyPersistentEngine *e, ConnMap *cmap) : GlobalTask(e, TaskId::ConnManager, e->getConfiguration().getConnectionManagerInterval(), true), engine(e), connmap(cmap), snoozeTime(e->getConfiguration().getConnectionManagerInterval()) { } /** * The ConnManager task is used to run the manageConnections function * once a second. This is required for two reasons: * (1) To clean-up dead connections * (2) To notify idle connections; either for connections that need to be * closed or to ensure dcp noop messages are sent once a second. */ bool run(void) { TRACE_EVENT0("ep-engine/task", "ConnManager"); connmap->manageConnections(); snooze(snoozeTime); return !engine->getEpStats().isShutdown || connmap->isConnections() || !connmap->isDeadConnectionsEmpty(); } std::string getDescription() { return "Connection Manager"; } std::chrono::microseconds maxExpectedDuration() { // In *theory* this should run very quickly (p50 of <1ms); however // there's evidence it sometimes takes much longer than that - p99.99 // of 10s. // Set slow limit to 1s initially to highlight the worst runtimes; // consider reducing further when they are solved. return std::chrono::seconds(1); } private: EventuallyPersistentEngine *engine; ConnMap *connmap; size_t snoozeTime; }; ConnMap::ConnMap(EventuallyPersistentEngine &theEngine) : vbConnLocks(vbConnLockNum), engine(theEngine), connNotifier_(nullptr) { Configuration &config = engine.getConfiguration(); size_t max_vbs = config.getMaxVbuckets(); for (size_t i = 0; i < max_vbs; ++i) { vbConns.push_back(std::list<std::weak_ptr<ConnHandler>>()); } } void ConnMap::initialize() { connNotifier_ = std::make_shared<ConnNotifier>(*this); connNotifier_->start(); ExTask connMgr = std::make_shared<ConnManager>(&engine, this); ExecutorPool::get()->schedule(connMgr); } ConnMap::~ConnMap() { if (connNotifier_) { connNotifier_->stop(); } } void ConnMap::notifyPausedConnection(const std::shared_ptr<ConnHandler>& conn) { if (engine.getEpStats().isShutdown) { return; } { LockHolder rlh(releaseLock); if (conn.get() && conn->isPaused() && conn->isReserved()) { engine.notifyIOComplete(conn->getCookie(), ENGINE_SUCCESS); } } } void ConnMap::addConnectionToPending(const std::shared_ptr<ConnHandler>& conn) { if (engine.getEpStats().isShutdown) { return; } if (conn.get() && conn->isPaused() && conn->isReserved()) { pendingNotifications.push(conn); if (connNotifier_) { // Wake up the connection notifier so that // it can notify the event to a given paused connection. connNotifier_->notifyMutationEvent(); } } } void ConnMap::processPendingNotifications() { std::queue<std::weak_ptr<ConnHandler>> queue; pendingNotifications.getAll(queue); TRACE_EVENT1("ep-engine/ConnMap", "processPendingNotifications", "#pending", queue.size()); TRACE_LOCKGUARD_TIMED(releaseLock, "mutex", "ConnMap::processPendingNotifications::releaseLock", SlowMutexThreshold); while (!queue.empty()) { auto conn = queue.front().lock(); if (conn && conn->isPaused() && conn->isReserved()) { engine.notifyIOComplete(conn->getCookie(), ENGINE_SUCCESS); } queue.pop(); } } void ConnMap::addVBConnByVBId(std::shared_ptr<ConnHandler> conn, Vbid vbid) { if (!conn.get()) { return; } size_t lock_num = vbid.get() % vbConnLockNum; std::lock_guard<std::mutex> lh(vbConnLocks[lock_num]); vbConns[vbid.get()].emplace_back(std::move(conn)); } void ConnMap::removeVBConnByVBId_UNLOCKED(const void* connCookie, Vbid vbid) { std::list<std::weak_ptr<ConnHandler>>& vb_conns = vbConns[vbid.get()]; for (auto itr = vb_conns.begin(); itr != vb_conns.end();) { auto connection = (*itr).lock(); if (!connection) { // ConnHandler no longer exists, cleanup. itr = vb_conns.erase(itr); } else if (connection->getCookie() == connCookie) { // Found conn with matching cookie, done. vb_conns.erase(itr); break; } else { ++itr; } } } void ConnMap::removeVBConnByVBId(const void* connCookie, Vbid vbid) { size_t lock_num = vbid.get() % vbConnLockNum; std::lock_guard<std::mutex> lh(vbConnLocks[lock_num]); removeVBConnByVBId_UNLOCKED(connCookie, vbid); } bool ConnMap::vbConnectionExists(ConnHandler* conn, Vbid vbid) { size_t lock_num = vbid.get() % vbConnLockNum; std::lock_guard<std::mutex> lh(vbConnLocks[lock_num]); auto& connsForVb = vbConns[vbid.get()]; // Check whether the connhandler already exists in vbConns for the // provided vbid for (const auto& existingConn : connsForVb) { if (conn == existingConn.lock().get()) { return true; } } return false; }
31.509615
80
0.632438
paolococchi
b4c82553d1ae5d3f4e0fd9a708b68d10df9a68cc
11,595
cpp
C++
LifeBrush/Source/LifeBrush/Visualization/EventVisualizationTool.cpp
timdecode/LifeBrush
dbc65bcc0ec77f9168e08cf7b39539af94420725
[ "MIT" ]
33
2019-04-23T23:00:09.000Z
2021-11-09T11:44:09.000Z
LifeBrush/Source/LifeBrush/Visualization/EventVisualizationTool.cpp
MyelinsheathXD/LifeBrush
dbc65bcc0ec77f9168e08cf7b39539af94420725
[ "MIT" ]
1
2019-10-09T15:57:56.000Z
2020-03-05T20:01:01.000Z
LifeBrush/Source/LifeBrush/Visualization/EventVisualizationTool.cpp
MyelinsheathXD/LifeBrush
dbc65bcc0ec77f9168e08cf7b39539af94420725
[ "MIT" ]
6
2019-04-25T00:10:55.000Z
2021-04-12T05:16:28.000Z
// Copyright (c) 2018 Timothy Davison. All rights reserved. #include "LifeBrush.h" #include "Simulation/FlexElements.h" #include "Visualization/Timeline.h" #include "EventVisualizationTool.h" void UEventVisualizationTool::gainFocus() { Super::gainFocus(); UTimelineSimulation * timeline = _flexSimulation->simulationManager.simulation<UTimelineSimulation>(); timeline->setGlyphVisibility(true); } void UEventVisualizationTool::loseFocus() { Super::loseFocus(); UTimelineSimulation * timeline = _flexSimulation->simulationManager.simulation<UTimelineSimulation>(); timeline->setGlyphVisibility(false); } void UEventVisualizationTool::oneHandStart(UPrimitiveComponent * hand) { Super::oneHandStart(hand); _selection.Empty(); } void UEventVisualizationTool::oneHandEnd(UPrimitiveComponent * hand) { Super::oneHandEnd(hand); if( _selection.Num() ) _traceSelection(_selection); else { UTimelineSimulation * timeline = _flexSimulation->simulationManager.simulation<UTimelineSimulation>(); int32 currentFrame = _flexSimulation->graphSimulation.tickCount; // show the last 10 seconds of events timeline->showAllEvents(); UVisualization_AgentPathLines * pathlines = _flexSimulation->simulationManager.simulation<UVisualization_AgentPathLines>(); pathlines->hideTotalHistory(); } } void UEventVisualizationTool::tick(float dt) { } void UEventVisualizationTool::tickOneHand(float dt, UPrimitiveComponent * hand, FTransform lastTransform) { Super::tickOneHand(dt, hand, lastTransform); _selectEvent(dt, hand, lastTransform); } void UEventVisualizationTool::faceDown_released() { if (_flexSimulation->isPlaying()) _flexSimulation->pause(); else _flexSimulation->play(); } void UEventVisualizationTool::faceUp_released(USceneComponent * interactionPoint /* = nullptr */) { physicalInteraction = !physicalInteraction; } void UEventVisualizationTool::_selectEvent(float dt, UPrimitiveComponent * hand, FTransform lastTransform) { UTimelineSimulation * timeline = _flexSimulation->simulationManager.simulation<UTimelineSimulation>(); FTransform toLocal = _flexSimulation->owner->GetRootComponent()->GetComponentTransform(); FVector localHandPosition = toLocal.InverseTransformPosition(hand->GetComponentLocation()); auto overlappingEvents = timeline->eventsOverlappingPosition(localHandPosition, _brushRadius()); for (USEGraphEvent * graphEvent : overlappingEvents) { _selection.Add(graphEvent); } } void UEventVisualizationTool::_traceSelection(TSet<USEGraphEvent*>& selection) { std::vector<USEGraphEvent*> events; for (USEGraphEvent* e : selection) events.push_back(e); UTimelineSimulation * timeline = _flexSimulation->simulationManager.simulation<UTimelineSimulation>(); timeline->traceEvents(events, maxHops); } void UAgentPathlineTool::gainFocus() { Super::gainFocus(); } void UAgentPathlineTool::loseFocus() { Super::loseFocus(); } void UAgentPathlineTool::oneHandStart(UPrimitiveComponent * hand) { Super::oneHandStart(hand); _selection.Empty(); } void UAgentPathlineTool::oneHandEnd(UPrimitiveComponent * hand) { Super::oneHandEnd(hand); if (_selection.Num()) _pathlinesForSelection(_selection); else { UTimelineSimulation * timeline = _flexSimulation->simulationManager.simulation<UTimelineSimulation>(); // show the last 10 seconds of events timeline->showAllEvents(); UVisualization_AgentPathLines * pathlines = _flexSimulation->simulationManager.simulation<UVisualization_AgentPathLines>(); pathlines->hideTotalHistory(); } } void UAgentPathlineTool::tick(float dt) { } void UAgentPathlineTool::tickOneHand(float dt, UPrimitiveComponent * hand, FTransform lastTransform) { Super::tickOneHand(dt, hand, lastTransform); _selectAgent(dt, hand, lastTransform); } void UAgentPathlineTool::faceDown_released() { if (_flexSimulation->isPlaying()) _flexSimulation->pause(); else _flexSimulation->play(); } void UAgentPathlineTool::faceUp_released(USceneComponent * interactionPoint /* = nullptr */) { physicalInteraction = !physicalInteraction; } void UAgentPathlineTool::_selectAgent(float dt, UPrimitiveComponent * hand, FTransform lastTransform) { UTimelineSimulation * timeline = _flexSimulation->simulationManager.simulation<UTimelineSimulation>(); FTransform toLocal = _flexSimulation->owner->GetRootComponent()->GetComponentTransform(); FVector localHandPosition = toLocal.InverseTransformPosition(hand->GetComponentLocation()); float brushSqrd = _brushRadius() * _brushRadius(); for (FGraphNode& node : _flexSimulation->graphSimulation.allNodes) { if (!node.isValid()) continue; float distSqrd = FVector::DistSquared(localHandPosition, node.position); if (distSqrd < brushSqrd) _selection.Add(FGraphNodeHandle(node)); } } void UAgentPathlineTool::_pathlinesForSelection(TSet<FGraphNodeHandle>& selection) { std::vector<FGraphNodeHandle> agents; for( FGraphNodeHandle& handle : selection) agents.push_back(handle); UVisualization_AgentPathLines * pathlines = _flexSimulation->simulationManager.simulation<UVisualization_AgentPathLines>(); UTimelineSimulation * timeline = _flexSimulation->simulationManager.simulation<UTimelineSimulation>(); int32 curFrame = _flexSimulation->graphSimulation.tickCount; pathlines->showTotalHistoryForAgents(agents, 0, curFrame); } void UPhysicalInteractionTool::loseFocus() { Super::loseFocus(); _grabbedNode = FGraphNodeHandle::null; } void UPhysicalInteractionTool::faceDown_released() { if (_flexSimulation->isPlaying()) _flexSimulation->pause(); else _flexSimulation->play(); } void UPhysicalInteractionTool::oneHandStart(UPrimitiveComponent * handComponent) { Super::oneHandStart(handComponent); FVector hand = _flexSimulation->owner->GetTransform().InverseTransformPosition(handComponent->GetComponentLocation()); if (interactionMode == EPhysicalInteractionType::Grab) { _grabbedNode = FGraphNodeHandle::null; FGraph& graph = _flexSimulation->graphSimulation; const float interactionDistanceSqrd = std::pow(2.0f, 2.0f); float nearestDistanceSqrd = std::numeric_limits<float>::max(); FGraphNodeHandle nearestHandle; for (auto& node : graph.allNodes) { if (!node.isValid()) continue; float distSqrd = (node.position - hand).SizeSquared(); if (distSqrd < nearestDistanceSqrd) { nearestDistanceSqrd = distSqrd; nearestHandle = node.handle(); } } if (nearestHandle && nearestDistanceSqrd < interactionDistanceSqrd ) { //// for whatever reason, grabbing a non rigid handle blows things up //if (FGraphNodeHandle rigidHandle = FFlexRigidBodyObject::getRigidBodyHandle(graph, nearestHandle)) //{ // _grabbedNode = rigidHandle; //} //else _grabbedNode = nearestHandle; FGraphNode& theNode = _grabbedNode(graph); _grabbedIdentityMatrix = FRotationMatrix::Make(theNode.orientation.Inverse()) * FTranslationMatrix::Make(-theNode.position); _grabbedTransform = FTransform(theNode.orientation, theNode.position, FVector(theNode.scale)); const FTransform toLocal = _flexSimulation->owner->GetTransform().Inverse(); _startHand = handComponent->GetComponentTransform() * toLocal; } } } void UPhysicalInteractionTool::oneHandEnd(UPrimitiveComponent * handComponent) { Super::oneHandEnd(handComponent); if (!_flexSimulation) return; // put it somewhere far away if (interactionMode == EPhysicalInteractionType::Punch) _flexSimulation->updateSphereWorldSpace(FVector(10000.0f, 0.0f, 0.0f), 0.1f); else if (interactionMode == EPhysicalInteractionType::Grab && _grabbedNode) { FGraph& graph = _flexSimulation->graphSimulation; FVector releaseVelocity = _releaseVelocity; FGraphNodeHandle grabbedNode = _grabbedNode; _flexSimulation->addTickWork([&graph, grabbedNode, releaseVelocity] { FGraphNode& node = graph.node(grabbedNode); if (FGraphNodeHandle rigidHandle = FFlexRigidBodyObject::getRigidBodyHandle(graph, node.handle())) { rigidHandle(graph).each<FFlexRigidBodyConnection>(graph, [&](FGraphNodeHandle subRigidHandle, FFlexRigidBodyConnection& rigidConnection) { FGraphNode& subNode = subRigidHandle(graph); // while we're holding it, kill velocity if (subNode.hasComponent<FVelocityGraphObject>()) { subNode.component<FVelocityGraphObject>(graph).linearVelocity = FVector::ZeroVector; subNode.component<FVelocityGraphObject>(graph).angularVelocity = FVector::ZeroVector; } }); } else { if (node.hasComponent<FVelocityGraphObject>()) node.component<FVelocityGraphObject>(graph).linearVelocity = releaseVelocity; } }); } } void UPhysicalInteractionTool::tickOneHand(float dt, UPrimitiveComponent * handComponent, FTransform lastTransform) { Super::tickOneHand(dt, handComponent, lastTransform); const FTransform toLocal = _flexSimulation->owner->GetTransform().Inverse(); const FTransform lastLocal = lastTransform * toLocal; const FTransform local = handComponent->GetComponentTransform() * toLocal; const FVector hand = local.GetLocation(); const FVector lastHand = lastLocal.GetLocation(); const float invDt = 1.0f / dt; if (!_flexSimulation) return; if (interactionMode == EPhysicalInteractionType::Punch) _flexSimulation->updateSphereWorldSpace(handComponent->GetComponentLocation(), _brushRadius()); else if (interactionMode == EPhysicalInteractionType::Grab) { if (!_grabbedNode) return; FGraph& graph = _flexSimulation->graphSimulation; FGraphNodeHandle grabbedNode = _grabbedNode; FVector velocity = (hand - lastHand) / (dt > 0.0f ? dt : 1.0f); _releaseVelocity = velocity; FVector offset = (local.GetRotation() * _startHand.GetRotation().Inverse()).RotateVector(_grabbedTransform.GetLocation() - _startHand.GetLocation()); FVector pr = grabbedNode(graph).position; FVector pr_ = hand + offset; FQuat rotationalDiff = local.GetRotation() * lastLocal.GetRotation().Inverse(); _flexSimulation->addTickWork([&graph, grabbedNode, velocity, invDt, pr, pr_, rotationalDiff] { FGraphNode& node = graph.node(grabbedNode); if (!node.isValid()) return; auto translate = [&](FVector p) -> FVector { return rotationalDiff.RotateVector(p - pr) + pr_; }; auto rotate = [&](FQuat rotation) -> FQuat { return rotationalDiff * rotation; }; if (FGraphNodeHandle rigidHandle = FFlexRigidBodyObject::getRigidBodyHandle(graph, node.handle())) { rigidHandle(graph).each<FFlexRigidBodyConnection>(graph, [&](FGraphNodeHandle subRigidHandle, FFlexRigidBodyConnection& rigidConnection) { FGraphNode& subNode = subRigidHandle(graph); const FVector newPosition = translate(subNode.position); // while we're holding it, kill velocity if (subNode.hasComponent<FVelocityGraphObject>()) { subNode.component<FVelocityGraphObject>(graph).linearVelocity = FVector::ZeroVector; subNode.component<FVelocityGraphObject>(graph).angularVelocity = FVector::ZeroVector; } subNode.position = newPosition; subNode.orientation = rotate(subNode.orientation); }); } else { if (node.hasComponent<FVelocityGraphObject>()) { node.component<FVelocityGraphObject>(graph).linearVelocity = FVector::ZeroVector; node.component<FVelocityGraphObject>(graph).angularVelocity = FVector::ZeroVector; } node.position = translate(node.position); node.orientation = rotate(node.orientation); } }); } } bool UPhysicalInteractionTool::shouldShowBrush() { return interactionMode == EPhysicalInteractionType::Punch; }
27.091121
151
0.759983
timdecode
b4cbdb72b04e32b49b299cd8c896f7555ce9d822
59,458
cpp
C++
src/Core/BlockChain.cpp
VaultB/vaultb
de41b954ea4d8a4f54a5ab95adf14af85809f55e
[ "MIT" ]
null
null
null
src/Core/BlockChain.cpp
VaultB/vaultb
de41b954ea4d8a4f54a5ab95adf14af85809f55e
[ "MIT" ]
null
null
null
src/Core/BlockChain.cpp
VaultB/vaultb
de41b954ea4d8a4f54a5ab95adf14af85809f55e
[ "MIT" ]
null
null
null
<<<<<<< HEAD // Copyright (c) 2012-2018, The CryptoNote developers, The Bytecoin developers, [ ] developers. // Licensed under the GNU Lesser General Public License. See LICENSE for details. #include "BlockChain.hpp" #include <boost/lexical_cast.hpp> #include <chrono> #include <iostream> #include "CryptoNoteTools.hpp" #include "TransactionExtra.hpp" #include "common/StringTools.hpp" #include "common/Varint.hpp" #include "rpc_api.hpp" #include "seria/BinaryInputStream.hpp" #include "seria/BinaryOutputStream.hpp" using namespace cryptonote; using namespace platform; static const std::string previous_versions[] = {"B"}; // most recent previous version should be first in list static const std::string version_current = "1"; // We increment when making incompatible changes to indices. // We use suffixes so all keys related to the same block are close to each other // in DB static const std::string BLOCK_PREFIX = "b"; static const std::string BLOCK_SUFFIX = "b"; static const std::string HEADER_PREFIX = "b"; static const std::string HEADER_SUFFIX = "h"; static const std::string TRANSATION_PREFIX = "t"; static const size_t TRANSACTION_PREFIX_BYTES = 5; // We store only first bytes of tx hash in index static const std::string TIP_CHAIN_PREFIX = "c"; static const std::string TIMESTAMP_BLOCK_PREFIX = "T"; static const std::string CHILDREN_PREFIX = "x-ch/"; static const std::string CD_TIPS_PREFIX = "x-tips/"; // We store bid->children counter, with counter=1 default (absent from index) // We store cumulative_difficulty->bid for bids with no children bool Block::from_raw_block(const RawBlock &raw_block) { try { BlockTemplate &bheader = header; seria::from_binary(bheader, raw_block.block); transactions.resize(0); transactions.reserve(raw_block.transactions.size()); for (auto &&raw_transaction : raw_block.transactions) { Transaction transaction; seria::from_binary(transaction, raw_transaction); transactions.push_back(std::move(transaction)); } } catch (...) { return false; } return true; } bool Block::to_raw_block(RawBlock &raw_block) const { try { const BlockTemplate &bheader = header; raw_block.block = seria::to_binary(bheader); raw_block.transactions.resize(0); raw_block.transactions.reserve(transactions.size()); for (auto &&transaction : transactions) { BinaryArray raw_transaction = seria::to_binary(transaction); raw_block.transactions.push_back(std::move(raw_transaction)); } } catch (...) { return false; } return true; } PreparedBlock::PreparedBlock(BinaryArray &&ba, crypto::CryptoNightContext *context) : block_data(std::move(ba)) { seria::from_binary(raw_block, block_data); if (block.from_raw_block(raw_block)) bid = cryptonote::get_block_hash(block.header); if (block.header.major_version >= 2) parent_block_size = seria::binary_size(block.header.parent_block); coinbase_tx_size = seria::binary_size(block.header.base_transaction); base_transaction_hash = get_transaction_hash(block.header.base_transaction); if (context) long_block_hash = cryptonote::get_block_long_hash(block.header, *context); } PreparedBlock::PreparedBlock(RawBlock &&rba, crypto::CryptoNightContext *context) : raw_block(rba) { block_data = seria::to_binary(raw_block); if (block.from_raw_block(raw_block)) bid = cryptonote::get_block_hash(block.header); if (block.header.major_version >= 2) parent_block_size = seria::binary_size(block.header.parent_block); coinbase_tx_size = seria::binary_size(block.header.base_transaction); base_transaction_hash = get_transaction_hash(block.header.base_transaction); if (context) long_block_hash = cryptonote::get_block_long_hash(block.header, *context); } BlockChain::BlockChain(const Hash &genesis_bid, const std::string &coin_folder) : m_genesis_bid(genesis_bid), m_coin_folder(coin_folder), m_db(coin_folder + "/blockchain") { std::string version; m_db.get("$version", version); if (version != version_current) { std::cout << "Data format changed, old version=" << version << " current version=" << version_current << ", deleting cryptonoted cache..." << std::endl; std::set<Hash> main_chain_bids; for (Height ha = 1;; ha += 1) { BinaryArray ba; if (!m_db.get(TIP_CHAIN_PREFIX + previous_versions[0] + "/" + common::write_varint_sqlite4(ha), ba)) break; Hash bid; seria::from_binary(bid, ba); main_chain_bids.insert(bid); } std::cout << "Found " << main_chain_bids.size() << " blocks from main chain" << std::endl; size_t erased = 0, skipped = 0; size_t total_items = m_db.get_approximate_items_count(); for (DB::Cursor cur = m_db.rbegin(std::string()); !cur.end();) { if ((erased + skipped) % 1000000 == 0) std::cout << "Processed " << (erased + skipped) / 1000000 << "/" << (total_items + 999999) / 1000000 << " million DB records" << std::endl; if (cur.get_suffix().find(TIP_CHAIN_PREFIX + previous_versions[0] + "/") == 0) { cur.next(); skipped += 1; continue; // chain } if (cur.get_suffix().find(BLOCK_PREFIX) == 0 && cur.get_suffix().substr(cur.get_suffix().size() - BLOCK_SUFFIX.size()) == BLOCK_SUFFIX) { Hash bid; DB::from_binary_key(cur.get_suffix(), BLOCK_PREFIX.size(), bid.data, sizeof(bid.data)); if (main_chain_bids.count(bid) != 0) { cur.next(); skipped += 1; continue; // block in main chain } } cur.erase(); erased += 1; } m_db.put("$version", version_current, true); std::cout << "Deleted " << erased << " records, skipped " << skipped << " records" << std::endl; db_commit(); } Hash stored_genesis_bid; if (read_chain(0, stored_genesis_bid)) { if (stored_genesis_bid != genesis_bid) throw std::runtime_error("Database starts with different genesis_block"); read_tip(); } DB::Cursor cur2 = m_db.rbegin(TIP_CHAIN_PREFIX + previous_versions[0] + "/"); m_internal_import_known_height = cur2.end() ? 0 : boost::lexical_cast<Height>(common::read_varint_sqlite4(cur2.get_suffix())); // test_print_structure(); } void BlockChain::db_commit() { std::cout << "BlockChain::db_commit started... tip_height=" << m_tip_height << std::endl; m_db.commit_db_txn(); std::cout << "BlockChain::db_commit finished..." << std::endl; } BroadcastAction BlockChain::add_block(const PreparedBlock &pb, api::BlockHeader &info) { info = api::BlockHeader(); bool have_header = read_header(pb.bid, info); bool have_block = has_block(pb.bid); if (have_block && have_header) return BroadcastAction::NOTHING; api::BlockHeader prev_info; prev_info.height = -1; if (pb.bid != m_genesis_bid && !read_header(pb.block.header.previous_block_hash, prev_info)) return BroadcastAction::NOTHING; // Not interested in orphan headers // std::cout << "pb.ph=" << common::pod_to_hex(pb.block.header.parent_block.previous_block_hash) << std::endl; info.major_version = pb.block.header.major_version; info.minor_version = pb.block.header.minor_version; info.timestamp = pb.block.header.timestamp; info.previous_block_hash = pb.block.header.previous_block_hash; info.nonce = pb.block.header.nonce; info.hash = pb.bid; info.height = prev_info.height + 1; // Rest fields are filled by check_standalone_consensus if (!check_standalone_consensus(pb, info, prev_info)) return BroadcastAction::BAN; try { if (!have_block) store_block(pb.bid, pb.block_data); // Do not commit between here and // reorganize_blocks or invariant // might be dead store_header(pb.bid, info); if (pb.bid == m_genesis_bid) { if (!redo_block(pb.bid, pb.raw_block, pb.block, info, pb.base_transaction_hash)) throw std::logic_error("Failed to apply genesis block"); push_chain(pb.bid, info.cumulative_difficulty); } else { modify_children_counter(prev_info.cumulative_difficulty, pb.block.header.previous_block_hash, 1); } check_children_counter(info.cumulative_difficulty, pb.bid, 1); modify_children_counter(info.cumulative_difficulty, pb.bid, -1); // -1 from default 1 gives 0 if (info.cumulative_difficulty > m_tip_cumulative_difficulty) { if (get_tip_bid() == pb.block.header.previous_block_hash) { // most common case optimization if (!redo_block(pb.bid, pb.raw_block, pb.block, info, pb.base_transaction_hash)) return BroadcastAction::BAN; push_chain(pb.bid, info.cumulative_difficulty); } else reorganize_blocks(pb.bid, pb, info); } } catch (const std::exception &ex) { std::cout << "Exception while reorganizing blockchain, probably out of " "disk space ex.what=" << ex.what() << std::endl; std::exit(api::CRYPTONOTED_DATABASE_ERROR); } if (get_tip_height() % 50000 == 0) db_commit(); return BroadcastAction::BROADCAST_ALL; } bool BlockChain::reorganize_blocks(const Hash &switch_to_chain, const PreparedBlock &recent_pb, const api::BlockHeader &recent_info) { // Header chain is better than block chain, undo upto splitting block std::vector<Hash> chain1, chain2; Hash common = get_common_block(m_tip_bid, switch_to_chain, &chain1, &chain2); for (auto &&chha : chain2) if (!has_block(chha)) return false; // Full new chain not yet downloaded while (m_tip_bid != common) { RawBlock raw_block; Block block; if (!read_block(m_tip_bid, raw_block) || !block.from_raw_block(raw_block)) throw std::logic_error("Block to undo not found or failed to convert" + common::pod_to_hex(m_tip_bid)); undo_block(m_tip_bid, raw_block, block, m_tip_height); pop_chain(); m_tip_bid = block.header.previous_block_hash; api::BlockHeader info = get_tip(); m_tip_cumulative_difficulty = info.cumulative_difficulty; if (read_chain(m_tip_height) != m_tip_bid) throw std::logic_error( "Invariant dead - after undo tip does not match read_chain" + common::pod_to_hex(m_tip_bid)); } // Now redo all blocks we have in storage, will ask for the rest of blocks while (!chain2.empty()) { Hash chha = chain2.back(); chain2.pop_back(); if (chha == recent_pb.bid) { if (recent_pb.block.header.previous_block_hash != m_tip_bid) throw std::logic_error("Unexpected block prev, invariant dead"); if (!redo_block( recent_pb.bid, recent_pb.raw_block, recent_pb.block, recent_info, recent_pb.base_transaction_hash)) // invalid block on longest subchain, make no attempt to download the // rest // we will forever stuck on this block until longer chain appears, that // does not include it return false; push_chain(chha, recent_info.cumulative_difficulty); } else { RawBlock raw_block; Block block; if (!read_block(chha, raw_block) || !block.from_raw_block(raw_block)) return false; // Strange, we checked has_block, somehow "bad block" got // into DB. TODO - throw? if (block.header.previous_block_hash != m_tip_bid) throw std::logic_error("Unexpected block prev, invariant dead"); api::BlockHeader info = read_header(chha); // if redo fails, we will forever stuck on this block until longer chain // appears, that does not include it if (!redo_block(chha, raw_block, block, info, get_transaction_hash(block.header.base_transaction))) return false; push_chain(chha, info.cumulative_difficulty); } } return true; } Hash BlockChain::get_common_block( const Hash &bid1, const Hash &bid2, std::vector<Hash> *chain1, std::vector<Hash> *chain2) const { Hash hid1 = bid1; Hash hid2 = bid2; api::BlockHeader ha1 = read_header(hid1); api::BlockHeader ha2 = read_header(hid2); if (chain1) chain1->clear(); if (chain2) chain2->clear(); while (ha1.height > ha2.height) { if (chain1) chain1->push_back(hid1); hid1 = ha1.previous_block_hash; ha1 = read_header(hid1); } while (ha2.height > ha1.height) { if (chain2) chain2->push_back(hid2); hid2 = ha2.previous_block_hash; ha2 = read_header(hid2); } while (hid1 != hid2) { if (chain1) chain1->push_back(hid1); hid1 = ha1.previous_block_hash; ha1 = read_header(hid1); if (chain2) chain2->push_back(hid2); hid2 = ha2.previous_block_hash; ha2 = read_header(hid2); } return hid1; } std::vector<Hash> BlockChain::get_sparse_chain() const { std::vector<Hash> tip_path; uint32_t jump = 0; while (m_tip_height >= jump) { tip_path.push_back(read_chain(m_tip_height - jump)); if (tip_path.size() <= 10) jump += 1; else jump += (1 << (tip_path.size() - 10)); } if (tip_path.back() != m_genesis_bid) tip_path.push_back(m_genesis_bid); return tip_path; } std::vector<api::BlockHeader> BlockChain::get_sync_headers(const std::vector<Hash> &locator, size_t max_count) const { std::vector<api::BlockHeader> result; Height start_height = 0; std::vector<Hash> chain = get_sync_headers_chain(locator, start_height, max_count); result.reserve(chain.size()); for (auto &&c : chain) { result.push_back(read_header(c)); } return result; } uint32_t BlockChain::find_blockchain_supplement(const std::vector<Hash> &remote_block_ids) const { for (auto &&lit : remote_block_ids) { api::BlockHeader header; if (!read_header(lit, header)) continue; if (header.height > m_tip_height) continue; return header.height; } return 0; // Not possible if genesis blocks match } Height BlockChain::get_timestamp_lower_bound_block_index(Timestamp ts) const { auto middle = common::write_varint_sqlite4(ts); DB::Cursor cur = m_db.begin(TIMESTAMP_BLOCK_PREFIX, middle); if (cur.end()) return m_tip_height; const char *be = cur.get_suffix().data(); const char *en = be + cur.get_suffix().size(); common::read_varint_sqlite4(be, en); // We ignore result, auto actual_ts = return boost::lexical_cast<Height>(common::read_varint_sqlite4(be, en)); } std::vector<Hash> BlockChain::get_sync_headers_chain(const std::vector<Hash> &locator, Height &start_height, size_t max_count) const { std::vector<Hash> result; for (auto &&lit : locator) { api::BlockHeader header; if (!read_header(lit, header)) continue; if (header.height > m_tip_height) { // Asker has better chain then we do start_height = m_tip_height + 1; return result; } uint32_t min_height = header.height; Hash loc_ha = lit; for (; min_height != 0; min_height -= 1) { Hash ha = read_chain(min_height); if (ha == loc_ha) break; loc_ha = header.previous_block_hash; header = read_header(loc_ha); } start_height = min_height; for (; result.size() < max_count && min_height <= m_tip_height; min_height += 1) { result.push_back(read_chain(min_height)); } return result; } start_height = m_tip_height + 1; return result; } struct APIRawBlockHeightDifficulty { RawBlock &raw_block; Height &height; Difficulty &cd; APIRawBlockHeightDifficulty(RawBlock &raw_block, Height &height, Difficulty &cd) : raw_block(raw_block), height(height), cd(cd) {} }; namespace seria { void ser_members(APIRawBlockHeightDifficulty &v, ISeria &s) { seria_kv("height", v.height, s); seria_kv("cd", v.cd, s); seria_kv("raw_block", v.raw_block, s); } } // namespace seria struct APITransactionPos { Hash bid{}; uint32_t index = 0; size_t pos = 0; size_t size = 0; }; namespace seria { void ser_members(APITransactionPos &v, ISeria &s) { seria_kv("bid", v.bid, s); seria_kv("index", v.index, s); seria_kv("pos", v.pos, s); seria_kv("size", v.size, s); } } // namespace seria bool BlockChain::read_transaction(const Hash &tid, Transaction &tx, Height &height, size_t &index_in_block) const { auto txkey = TRANSATION_PREFIX + DB::to_binary_key(tid.data, TRANSACTION_PREFIX_BYTES); for (DB::Cursor cur = m_db.begin(txkey); !cur.end(); cur.next()) { const std::string &suf = cur.get_suffix(); const char *be = suf.data(); const char *en = be + suf.size(); height = boost::lexical_cast<Height>(common::read_varint_sqlite4(be, en)); index_in_block = boost::lexical_cast<size_t>(common::read_varint_sqlite4(be, en)); Hash bid; if (!read_chain(height, bid)) throw std::logic_error("transaction index corrupted while reading tid=" + common::pod_to_hex(tid)); RawBlock rb; Block block; if (!read_block(bid, rb) || !block.from_raw_block(rb)) throw std::logic_error("transaction index corrupted while reading bid=" + common::pod_to_hex(bid)); if (index_in_block == 0) { if (get_transaction_hash(block.header.base_transaction) != tid) continue; tx = block.header.base_transaction; return true; } if (block.header.transaction_hashes.at(index_in_block - 1) != tid) continue; tx = block.transactions.at(index_in_block - 1); return true; } return false; } bool BlockChain::redo_block(const Hash &bhash, const RawBlock &, const Block &block, const api::BlockHeader &info, const Hash &base_transaction_hash) { if (!redo_block(bhash, block, info)) return false; auto tikey = TIMESTAMP_BLOCK_PREFIX + common::write_varint_sqlite4(info.timestamp) + common::write_varint_sqlite4(info.height); m_db.put(tikey, std::string(), true); auto bkey = TRANSATION_PREFIX + DB::to_binary_key(base_transaction_hash.data, TRANSACTION_PREFIX_BYTES) + common::write_varint_sqlite4(info.height) + common::write_varint_sqlite4(0); m_db.put(bkey, std::string(), true); for (size_t tx_index = 0; tx_index != block.transactions.size(); ++tx_index) { Hash tid = block.header.transaction_hashes.at(tx_index); bkey = TRANSATION_PREFIX + DB::to_binary_key(tid.data, TRANSACTION_PREFIX_BYTES) + common::write_varint_sqlite4(info.height) + common::write_varint_sqlite4(tx_index + 1); m_db.put(bkey, std::string(), true); } m_tip_segment.push_back(info); if (m_tip_segment.size() > 2048) // TODO - should be enough for all block windows we use m_tip_segment.pop_front(); return true; } void BlockChain::undo_block(const Hash &bhash, const RawBlock &, const Block &block, Height height) { if (!m_tip_segment.empty()) m_tip_segment.pop_back(); undo_block(bhash, block, height); auto tikey = TIMESTAMP_BLOCK_PREFIX + common::write_varint_sqlite4(block.header.timestamp) + common::write_varint_sqlite4(height); m_db.del(tikey, true); Hash tid = get_transaction_hash(block.header.base_transaction); auto bkey = TRANSATION_PREFIX + DB::to_binary_key(tid.data, TRANSACTION_PREFIX_BYTES) + common::write_varint_sqlite4(height) + common::write_varint_sqlite4(0); m_db.del(bkey, true); for (size_t tx_index = 0; tx_index != block.transactions.size(); ++tx_index) { tid = block.header.transaction_hashes.at(tx_index); bkey = TRANSATION_PREFIX + DB::to_binary_key(tid.data, TRANSACTION_PREFIX_BYTES) + common::write_varint_sqlite4(height) + common::write_varint_sqlite4(tx_index + 1); m_db.del(bkey, true); } } void BlockChain::store_block(const Hash &bid, const BinaryArray &block_data) { auto key = BLOCK_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)) + BLOCK_SUFFIX; m_db.put(key, block_data, true); } bool BlockChain::read_block(const Hash &bid, RawBlock &raw_block) const { BinaryArray rb; auto key = BLOCK_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)) + BLOCK_SUFFIX; if (!m_db.get(key, rb)) return false; seria::from_binary(raw_block, rb); return true; } bool BlockChain::has_block(const Hash &bid) const { platform::DB::Value ms; auto key = BLOCK_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)) + BLOCK_SUFFIX; if (!m_db.get(key, ms)) return false; return true; } void BlockChain::store_header(const Hash &bid, const api::BlockHeader &header) { auto key = HEADER_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)) + HEADER_SUFFIX; BinaryArray ba = seria::to_binary(header); m_db.put(key, ba, true); } bool BlockChain::read_header(const Hash &bid, api::BlockHeader &header) const { if (bid == m_tip_bid && !m_tip_segment.empty()) { header = m_tip_segment.back(); return true; } BinaryArray rb; auto key = HEADER_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)) + HEADER_SUFFIX; if (!m_db.get(key, rb)) return false; seria::from_binary(header, rb); return true; } api::BlockHeader BlockChain::read_header(const Hash &bid) const { api::BlockHeader result; if (!read_header(bid, result)) throw std::logic_error("Expected header was not found" + common::pod_to_hex(bid)); return result; } const api::BlockHeader &BlockChain::get_tip() const { if (m_tip_segment.empty()) m_tip_segment.push_back(read_header(get_tip_bid())); return m_tip_segment.back(); } std::pair<std::deque<api::BlockHeader>::const_iterator, std::deque<api::BlockHeader>::const_iterator> BlockChain::get_tip_segment(Height height_delta, Height window, bool add_genesis) const { if (get_tip_height() == (Height)-1 || height_delta > get_tip_height()) return std::make_pair(m_tip_segment.end(), m_tip_segment.end()); while (m_tip_segment.size() < height_delta + window && m_tip_segment.size() < m_tip_height + 1) { Hash ha = read_chain(static_cast<uint32_t>(m_tip_height - m_tip_segment.size())); m_tip_segment.push_front(read_header(ha)); } if (m_tip_height + 1 <= height_delta + window) { // if( m_tip_segment.size() == m_tip_height + 1 ) { // if (height_delta + window >= m_tip_segment.size()) { return std::make_pair(m_tip_segment.begin() + (add_genesis ? 0 : 1), m_tip_segment.end() - height_delta); } return std::make_pair(m_tip_segment.end() - window - height_delta, m_tip_segment.end() - height_delta); } void BlockChain::read_tip() { DB::Cursor cur2 = m_db.rbegin(TIP_CHAIN_PREFIX + version_current + "/"); m_tip_height = cur2.end() ? -1 : boost::lexical_cast<Height>(common::read_varint_sqlite4(cur2.get_suffix())); seria::from_binary(m_tip_bid, cur2.get_value_array()); api::BlockHeader tip_block = read_header(m_tip_bid); m_tip_cumulative_difficulty = tip_block.cumulative_difficulty; } void BlockChain::push_chain(Hash bid, Difficulty cumulative_difficulty) { m_tip_height += 1; BinaryArray ba = seria::to_binary(bid); m_db.put(TIP_CHAIN_PREFIX + version_current + "/" + common::write_varint_sqlite4(m_tip_height), ba, true); m_tip_bid = bid; m_tip_cumulative_difficulty = cumulative_difficulty; tip_changed(); } void BlockChain::pop_chain() { if (m_tip_height == 0) throw std::logic_error("pop_chain tip_height == 0"); m_db.del(TIP_CHAIN_PREFIX + version_current + "/" + common::write_varint_sqlite4(m_tip_height), true); m_tip_height -= 1; tip_changed(); } bool BlockChain::read_chain(uint32_t height, Hash &bid) const { BinaryArray ba; if (!m_db.get(TIP_CHAIN_PREFIX + version_current + "/" + common::write_varint_sqlite4(height), ba)) return false; seria::from_binary(bid, ba); return true; } Hash BlockChain::read_chain(uint32_t height) const { Hash ha; if (!read_chain(height, ha)) throw std::logic_error("read_header_chain failed"); return ha; } void BlockChain::check_children_counter(Difficulty cd, const Hash &bid, int value) { auto key = CHILDREN_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)); auto cd_key = CD_TIPS_PREFIX + common::write_varint_sqlite4(cd) + DB::to_binary_key(bid.data, sizeof(bid.data)); int counter = 1; // default is 1 when not stored in db BinaryArray rb; if (m_db.get(key, rb)) seria::from_binary(counter, rb); if (counter != value) throw std::logic_error("check_children_counter index corrupted"); if (counter == 0 && !m_db.get(cd_key, rb)) throw std::logic_error("check_children_counter tip is not in index"); if (counter != 0 && m_db.get(cd_key, rb)) throw std::logic_error("check_children_counter non-tip is in index"); } void BlockChain::modify_children_counter(Difficulty cd, const Hash &bid, int delta) { auto key = CHILDREN_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)); auto cd_key = CD_TIPS_PREFIX + common::write_varint_sqlite4(cd) + DB::to_binary_key(bid.data, sizeof(bid.data)); uint32_t counter = 1; // default is 1 when not stored in db BinaryArray rb; if (m_db.get(key, rb)) seria::from_binary(counter, rb); counter += delta; if (counter == 1) { m_db.del(key, false); } else { BinaryArray ba = seria::to_binary(counter); m_db.put(key, ba, false); } if (counter == 0) { m_db.put(cd_key, std::string(), false); } else { m_db.del(cd_key, false); } } bool BlockChain::get_oldest_tip(Difficulty &cd, Hash &bid) const { DB::Cursor cur = m_db.begin(CD_TIPS_PREFIX); if (cur.end()) return false; const std::string &suf = cur.get_suffix(); const char *be = suf.data(); const char *en = be + suf.size(); cd = common::read_varint_sqlite4(be, en); if (en - be != sizeof(bid.data)) throw std::logic_error("CD_TIPS_PREFIX corrupted"); DB::from_binary_key(cur.get_suffix(), cur.get_suffix().size() - sizeof(bid.data), bid.data, sizeof(bid.data)); return true; } bool BlockChain::prune_branch(Difficulty cd, Hash bid) { if (bid == m_tip_bid) return false; check_children_counter(cd, bid, 0); api::BlockHeader me = read_header(bid); api::BlockHeader pa = read_header(me.previous_block_hash); modify_children_counter(cd, bid, 1); modify_children_counter(pa.cumulative_difficulty, me.previous_block_hash, -1); auto key = BLOCK_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)) + BLOCK_SUFFIX; m_db.del(key, true); auto key2 = HEADER_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)) + HEADER_SUFFIX; m_db.del(key2, true); return true; } void BlockChain::test_prune_oldest() { for (int i = 0; i != 10; ++i) { Difficulty cd = 0; Hash bid; if (!get_oldest_tip(cd, bid)) return; prune_branch(cd, bid); } } void BlockChain::test_print_structure() const { Difficulty ocd; Hash obid; if (get_oldest_tip(ocd, obid)) std::cout << "oldest tip cd=" << ocd << " bid=" << common::pod_to_hex(obid) << std::endl; for (DB::Cursor cur = m_db.begin(CD_TIPS_PREFIX); !cur.end(); cur.next()) { const std::string &suf = cur.get_suffix(); const char *be = suf.data(); const char *en = be + suf.size(); Difficulty cd = common::read_varint_sqlite4(be, en); Hash bid; if (en - be != sizeof(bid.data)) throw std::logic_error("CD_TIPS_PREFIX corrupted"); DB::from_binary_key(cur.get_suffix(), cur.get_suffix().size() - sizeof(bid.data), bid.data, sizeof(bid.data)); std::cout << "tip cd=" << cd << " bid=" << common::pod_to_hex(bid) << std::endl; } for (DB::Cursor cur = m_db.begin(CHILDREN_PREFIX); !cur.end(); cur.next()) { Hash bid; DB::from_binary_key(cur.get_suffix(), 0, bid.data, sizeof(bid.data)); uint32_t counter = 1; seria::from_binary(counter, cur.get_value_array()); std::cout << "children counter=" << counter << " bid=" << common::pod_to_hex(bid) << std::endl; } } bool BlockChain::read_next_internal_block(Hash &bid) const { BinaryArray ba; if (!m_db.get( TIP_CHAIN_PREFIX + previous_versions[0] + "/" + common::write_varint_sqlite4(get_tip_height() + 1), ba)) return false; seria::from_binary(bid, ba); return true; } bool BlockChain::internal_import() { auto idea_start = std::chrono::high_resolution_clock::now(); while (true) { Hash bid; if (!read_next_internal_block(bid)) break; RawBlock rb; if (!read_block(bid, rb)) break; PreparedBlock pb(std::move(rb), nullptr); api::BlockHeader info; if (add_block(pb, info) != BroadcastAction::BROADCAST_ALL) { std::cout << "internal_import block_chain.add_block !BROADCAST_ALL block=" << get_tip_height() + 1 << std::endl; break; } if (get_tip_height() % 50000 == 0) db_commit(); auto idea_ms = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - idea_start); if (idea_ms.count() > 100) return true; // continue importing } std::cout << "Finished internal importing of blocks, clearing chains..." << std::endl; size_t erased = 0; for (DB::Cursor cur = m_db.begin(TIP_CHAIN_PREFIX + previous_versions[0] + "/"); !cur.end(); cur.erase()) { erased += 1; } std::cout << "Items erased " << erased << std::endl; m_internal_import_known_height = 0; db_commit(); return false; } void BlockChain::test_undo_everything() { while (true) { RawBlock raw_block; Block block; if (!read_block(get_tip_bid(), raw_block) || !block.from_raw_block(raw_block)) break; undo_block(get_tip_bid(), raw_block, block, m_tip_height); if (get_tip_bid() == m_genesis_bid) break; pop_chain(); api::BlockHeader info = get_tip(); m_tip_bid = block.header.previous_block_hash; m_tip_cumulative_difficulty -= info.cumulative_difficulty; if (get_tip_height() % 50000 == 1) db_commit(); } std::cout << "---- After undo everything ---- " << std::endl; int counter = 0; for (DB::Cursor cur = m_db.begin(std::string()); !cur.end(); cur.next()) { if (cur.get_suffix().find(BLOCK_PREFIX) == 0) continue; if (cur.get_suffix().find(HEADER_PREFIX) == 0) continue; if (cur.get_suffix().find("f") == 0) continue; std::cout << DB::clean_key(cur.get_suffix()) << std::endl; if (counter++ > 2000) break; } } ======= // Copyright (c) 2012-2018, The CryptoNote developers, The Bytecoin developers, [ ] developers. // Licensed under the GNU Lesser General Public License. See LICENSE for details. #include "BlockChain.hpp" #include <boost/lexical_cast.hpp> #include <chrono> #include <iostream> #include "CryptoNoteTools.hpp" #include "TransactionExtra.hpp" #include "common/StringTools.hpp" #include "common/Varint.hpp" #include "rpc_api.hpp" #include "seria/BinaryInputStream.hpp" #include "seria/BinaryOutputStream.hpp" using namespace cryptonote; using namespace platform; static const std::string previous_versions[] = {"B"}; // most recent previous version should be first in list static const std::string version_current = "1"; // We increment when making incompatible changes to indices. // We use suffixes so all keys related to the same block are close to each other // in DB static const std::string BLOCK_PREFIX = "b"; static const std::string BLOCK_SUFFIX = "b"; static const std::string HEADER_PREFIX = "b"; static const std::string HEADER_SUFFIX = "h"; static const std::string TRANSATION_PREFIX = "t"; static const size_t TRANSACTION_PREFIX_BYTES = 5; // We store only first bytes of tx hash in index static const std::string TIP_CHAIN_PREFIX = "c"; static const std::string TIMESTAMP_BLOCK_PREFIX = "T"; static const std::string CHILDREN_PREFIX = "x-ch/"; static const std::string CD_TIPS_PREFIX = "x-tips/"; // We store bid->children counter, with counter=1 default (absent from index) // We store cumulative_difficulty->bid for bids with no children bool Block::from_raw_block(const RawBlock &raw_block) { try { BlockTemplate &bheader = header; seria::from_binary(bheader, raw_block.block); transactions.resize(0); transactions.reserve(raw_block.transactions.size()); for (auto &&raw_transaction : raw_block.transactions) { Transaction transaction; seria::from_binary(transaction, raw_transaction); transactions.push_back(std::move(transaction)); } } catch (...) { return false; } return true; } bool Block::to_raw_block(RawBlock &raw_block) const { try { const BlockTemplate &bheader = header; raw_block.block = seria::to_binary(bheader); raw_block.transactions.resize(0); raw_block.transactions.reserve(transactions.size()); for (auto &&transaction : transactions) { BinaryArray raw_transaction = seria::to_binary(transaction); raw_block.transactions.push_back(std::move(raw_transaction)); } } catch (...) { return false; } return true; } PreparedBlock::PreparedBlock(BinaryArray &&ba, crypto::CryptoNightContext *context) : block_data(std::move(ba)) { seria::from_binary(raw_block, block_data); if (block.from_raw_block(raw_block)) bid = cryptonote::get_block_hash(block.header); if (block.header.major_version >= 2) parent_block_size = seria::binary_size(block.header.parent_block); coinbase_tx_size = seria::binary_size(block.header.base_transaction); base_transaction_hash = get_transaction_hash(block.header.base_transaction); if (context) long_block_hash = cryptonote::get_block_long_hash(block.header, *context); } PreparedBlock::PreparedBlock(RawBlock &&rba, crypto::CryptoNightContext *context) : raw_block(rba) { block_data = seria::to_binary(raw_block); if (block.from_raw_block(raw_block)) bid = cryptonote::get_block_hash(block.header); if (block.header.major_version >= 2) parent_block_size = seria::binary_size(block.header.parent_block); coinbase_tx_size = seria::binary_size(block.header.base_transaction); base_transaction_hash = get_transaction_hash(block.header.base_transaction); if (context) long_block_hash = cryptonote::get_block_long_hash(block.header, *context); } BlockChain::BlockChain(const Hash &genesis_bid, const std::string &coin_folder) : m_genesis_bid(genesis_bid), m_coin_folder(coin_folder), m_db(coin_folder + "/blockchain") { std::string version; m_db.get("$version", version); if (version != version_current) { std::cout << "Data format changed, old version=" << version << " current version=" << version_current << ", deleting cryptonoted cache..." << std::endl; std::set<Hash> main_chain_bids; for (Height ha = 1;; ha += 1) { BinaryArray ba; if (!m_db.get(TIP_CHAIN_PREFIX + previous_versions[0] + "/" + common::write_varint_sqlite4(ha), ba)) break; Hash bid; seria::from_binary(bid, ba); main_chain_bids.insert(bid); } std::cout << "Found " << main_chain_bids.size() << " blocks from main chain" << std::endl; size_t erased = 0, skipped = 0; size_t total_items = m_db.get_approximate_items_count(); for (DB::Cursor cur = m_db.rbegin(std::string()); !cur.end();) { if ((erased + skipped) % 1000000 == 0) std::cout << "Processed " << (erased + skipped) / 1000000 << "/" << (total_items + 999999) / 1000000 << " million DB records" << std::endl; if (cur.get_suffix().find(TIP_CHAIN_PREFIX + previous_versions[0] + "/") == 0) { cur.next(); skipped += 1; continue; // chain } if (cur.get_suffix().find(BLOCK_PREFIX) == 0 && cur.get_suffix().substr(cur.get_suffix().size() - BLOCK_SUFFIX.size()) == BLOCK_SUFFIX) { Hash bid; DB::from_binary_key(cur.get_suffix(), BLOCK_PREFIX.size(), bid.data, sizeof(bid.data)); if (main_chain_bids.count(bid) != 0) { cur.next(); skipped += 1; continue; // block in main chain } } cur.erase(); erased += 1; } m_db.put("$version", version_current, true); std::cout << "Deleted " << erased << " records, skipped " << skipped << " records" << std::endl; db_commit(); } Hash stored_genesis_bid; if (read_chain(0, stored_genesis_bid)) { if (stored_genesis_bid != genesis_bid) throw std::runtime_error("Database starts with different genesis_block"); read_tip(); } DB::Cursor cur2 = m_db.rbegin(TIP_CHAIN_PREFIX + previous_versions[0] + "/"); m_internal_import_known_height = cur2.end() ? 0 : boost::lexical_cast<Height>(common::read_varint_sqlite4(cur2.get_suffix())); // test_print_structure(); } void BlockChain::db_commit() { std::cout << "BlockChain::db_commit started... tip_height=" << m_tip_height << std::endl; m_db.commit_db_txn(); std::cout << "BlockChain::db_commit finished..." << std::endl; } BroadcastAction BlockChain::add_block(const PreparedBlock &pb, api::BlockHeader &info) { info = api::BlockHeader(); bool have_header = read_header(pb.bid, info); bool have_block = has_block(pb.bid); if (have_block && have_header) return BroadcastAction::NOTHING; api::BlockHeader prev_info; prev_info.height = -1; if (pb.bid != m_genesis_bid && !read_header(pb.block.header.previous_block_hash, prev_info)) return BroadcastAction::NOTHING; // Not interested in orphan headers // std::cout << "pb.ph=" << common::pod_to_hex(pb.block.header.parent_block.previous_block_hash) << std::endl; info.major_version = pb.block.header.major_version; info.minor_version = pb.block.header.minor_version; info.timestamp = pb.block.header.timestamp; info.previous_block_hash = pb.block.header.previous_block_hash; info.nonce = pb.block.header.nonce; info.hash = pb.bid; info.height = prev_info.height + 1; // Rest fields are filled by check_standalone_consensus if (!check_standalone_consensus(pb, info, prev_info)) return BroadcastAction::BAN; try { if (!have_block) store_block(pb.bid, pb.block_data); // Do not commit between here and // reorganize_blocks or invariant // might be dead store_header(pb.bid, info); if (pb.bid == m_genesis_bid) { if (!redo_block(pb.bid, pb.raw_block, pb.block, info, pb.base_transaction_hash)) throw std::logic_error("Failed to apply genesis block"); push_chain(pb.bid, info.cumulative_difficulty); } else { modify_children_counter(prev_info.cumulative_difficulty, pb.block.header.previous_block_hash, 1); } check_children_counter(info.cumulative_difficulty, pb.bid, 1); modify_children_counter(info.cumulative_difficulty, pb.bid, -1); // -1 from default 1 gives 0 if (info.cumulative_difficulty > m_tip_cumulative_difficulty) { if (get_tip_bid() == pb.block.header.previous_block_hash) { // most common case optimization if (!redo_block(pb.bid, pb.raw_block, pb.block, info, pb.base_transaction_hash)) return BroadcastAction::BAN; push_chain(pb.bid, info.cumulative_difficulty); } else reorganize_blocks(pb.bid, pb, info); } } catch (const std::exception &ex) { std::cout << "Exception while reorganizing blockchain, probably out of " "disk space ex.what=" << ex.what() << std::endl; std::exit(api::CRYPTONOTED_DATABASE_ERROR); } if (get_tip_height() % 50000 == 0) db_commit(); return BroadcastAction::BROADCAST_ALL; } bool BlockChain::reorganize_blocks(const Hash &switch_to_chain, const PreparedBlock &recent_pb, const api::BlockHeader &recent_info) { // Header chain is better than block chain, undo upto splitting block std::vector<Hash> chain1, chain2; Hash common = get_common_block(m_tip_bid, switch_to_chain, &chain1, &chain2); for (auto &&chha : chain2) if (!has_block(chha)) return false; // Full new chain not yet downloaded while (m_tip_bid != common) { RawBlock raw_block; Block block; if (!read_block(m_tip_bid, raw_block) || !block.from_raw_block(raw_block)) throw std::logic_error("Block to undo not found or failed to convert" + common::pod_to_hex(m_tip_bid)); undo_block(m_tip_bid, raw_block, block, m_tip_height); pop_chain(); m_tip_bid = block.header.previous_block_hash; api::BlockHeader info = get_tip(); m_tip_cumulative_difficulty = info.cumulative_difficulty; if (read_chain(m_tip_height) != m_tip_bid) throw std::logic_error( "Invariant dead - after undo tip does not match read_chain" + common::pod_to_hex(m_tip_bid)); } // Now redo all blocks we have in storage, will ask for the rest of blocks while (!chain2.empty()) { Hash chha = chain2.back(); chain2.pop_back(); if (chha == recent_pb.bid) { if (recent_pb.block.header.previous_block_hash != m_tip_bid) throw std::logic_error("Unexpected block prev, invariant dead"); if (!redo_block( recent_pb.bid, recent_pb.raw_block, recent_pb.block, recent_info, recent_pb.base_transaction_hash)) // invalid block on longest subchain, make no attempt to download the // rest // we will forever stuck on this block until longer chain appears, that // does not include it return false; push_chain(chha, recent_info.cumulative_difficulty); } else { RawBlock raw_block; Block block; if (!read_block(chha, raw_block) || !block.from_raw_block(raw_block)) return false; // Strange, we checked has_block, somehow "bad block" got // into DB. TODO - throw? if (block.header.previous_block_hash != m_tip_bid) throw std::logic_error("Unexpected block prev, invariant dead"); api::BlockHeader info = read_header(chha); // if redo fails, we will forever stuck on this block until longer chain // appears, that does not include it if (!redo_block(chha, raw_block, block, info, get_transaction_hash(block.header.base_transaction))) return false; push_chain(chha, info.cumulative_difficulty); } } return true; } Hash BlockChain::get_common_block( const Hash &bid1, const Hash &bid2, std::vector<Hash> *chain1, std::vector<Hash> *chain2) const { Hash hid1 = bid1; Hash hid2 = bid2; api::BlockHeader ha1 = read_header(hid1); api::BlockHeader ha2 = read_header(hid2); if (chain1) chain1->clear(); if (chain2) chain2->clear(); while (ha1.height > ha2.height) { if (chain1) chain1->push_back(hid1); hid1 = ha1.previous_block_hash; ha1 = read_header(hid1); } while (ha2.height > ha1.height) { if (chain2) chain2->push_back(hid2); hid2 = ha2.previous_block_hash; ha2 = read_header(hid2); } while (hid1 != hid2) { if (chain1) chain1->push_back(hid1); hid1 = ha1.previous_block_hash; ha1 = read_header(hid1); if (chain2) chain2->push_back(hid2); hid2 = ha2.previous_block_hash; ha2 = read_header(hid2); } return hid1; } std::vector<Hash> BlockChain::get_sparse_chain() const { std::vector<Hash> tip_path; uint32_t jump = 0; while (m_tip_height >= jump) { tip_path.push_back(read_chain(m_tip_height - jump)); if (tip_path.size() <= 10) jump += 1; else jump += (1 << (tip_path.size() - 10)); } if (tip_path.back() != m_genesis_bid) tip_path.push_back(m_genesis_bid); return tip_path; } std::vector<api::BlockHeader> BlockChain::get_sync_headers(const std::vector<Hash> &locator, size_t max_count) const { std::vector<api::BlockHeader> result; Height start_height = 0; std::vector<Hash> chain = get_sync_headers_chain(locator, start_height, max_count); result.reserve(chain.size()); for (auto &&c : chain) { result.push_back(read_header(c)); } return result; } uint32_t BlockChain::find_blockchain_supplement(const std::vector<Hash> &remote_block_ids) const { for (auto &&lit : remote_block_ids) { api::BlockHeader header; if (!read_header(lit, header)) continue; if (header.height > m_tip_height) continue; return header.height; } return 0; // Not possible if genesis blocks match } Height BlockChain::get_timestamp_lower_bound_block_index(Timestamp ts) const { auto middle = common::write_varint_sqlite4(ts); DB::Cursor cur = m_db.begin(TIMESTAMP_BLOCK_PREFIX, middle); if (cur.end()) return m_tip_height; const char *be = cur.get_suffix().data(); const char *en = be + cur.get_suffix().size(); common::read_varint_sqlite4(be, en); // We ignore result, auto actual_ts = return boost::lexical_cast<Height>(common::read_varint_sqlite4(be, en)); } std::vector<Hash> BlockChain::get_sync_headers_chain(const std::vector<Hash> &locator, Height &start_height, size_t max_count) const { std::vector<Hash> result; for (auto &&lit : locator) { api::BlockHeader header; if (!read_header(lit, header)) continue; if (header.height > m_tip_height) { // Asker has better chain then we do start_height = m_tip_height + 1; return result; } uint32_t min_height = header.height; Hash loc_ha = lit; for (; min_height != 0; min_height -= 1) { Hash ha = read_chain(min_height); if (ha == loc_ha) break; loc_ha = header.previous_block_hash; header = read_header(loc_ha); } start_height = min_height; for (; result.size() < max_count && min_height <= m_tip_height; min_height += 1) { result.push_back(read_chain(min_height)); } return result; } start_height = m_tip_height + 1; return result; } struct APIRawBlockHeightDifficulty { RawBlock &raw_block; Height &height; Difficulty &cd; APIRawBlockHeightDifficulty(RawBlock &raw_block, Height &height, Difficulty &cd) : raw_block(raw_block), height(height), cd(cd) {} }; namespace seria { void ser_members(APIRawBlockHeightDifficulty &v, ISeria &s) { seria_kv("height", v.height, s); seria_kv("cd", v.cd, s); seria_kv("raw_block", v.raw_block, s); } } // namespace seria struct APITransactionPos { Hash bid{}; uint32_t index = 0; size_t pos = 0; size_t size = 0; }; namespace seria { void ser_members(APITransactionPos &v, ISeria &s) { seria_kv("bid", v.bid, s); seria_kv("index", v.index, s); seria_kv("pos", v.pos, s); seria_kv("size", v.size, s); } } // namespace seria bool BlockChain::read_transaction(const Hash &tid, Transaction &tx, Height &height, size_t &index_in_block) const { auto txkey = TRANSATION_PREFIX + DB::to_binary_key(tid.data, TRANSACTION_PREFIX_BYTES); for (DB::Cursor cur = m_db.begin(txkey); !cur.end(); cur.next()) { const std::string &suf = cur.get_suffix(); const char *be = suf.data(); const char *en = be + suf.size(); height = boost::lexical_cast<Height>(common::read_varint_sqlite4(be, en)); index_in_block = boost::lexical_cast<size_t>(common::read_varint_sqlite4(be, en)); Hash bid; if (!read_chain(height, bid)) throw std::logic_error("transaction index corrupted while reading tid=" + common::pod_to_hex(tid)); RawBlock rb; Block block; if (!read_block(bid, rb) || !block.from_raw_block(rb)) throw std::logic_error("transaction index corrupted while reading bid=" + common::pod_to_hex(bid)); if (index_in_block == 0) { if (get_transaction_hash(block.header.base_transaction) != tid) continue; tx = block.header.base_transaction; return true; } if (block.header.transaction_hashes.at(index_in_block - 1) != tid) continue; tx = block.transactions.at(index_in_block - 1); return true; } return false; } bool BlockChain::redo_block(const Hash &bhash, const RawBlock &, const Block &block, const api::BlockHeader &info, const Hash &base_transaction_hash) { if (!redo_block(bhash, block, info)) return false; auto tikey = TIMESTAMP_BLOCK_PREFIX + common::write_varint_sqlite4(info.timestamp) + common::write_varint_sqlite4(info.height); m_db.put(tikey, std::string(), true); auto bkey = TRANSATION_PREFIX + DB::to_binary_key(base_transaction_hash.data, TRANSACTION_PREFIX_BYTES) + common::write_varint_sqlite4(info.height) + common::write_varint_sqlite4(0); m_db.put(bkey, std::string(), true); for (size_t tx_index = 0; tx_index != block.transactions.size(); ++tx_index) { Hash tid = block.header.transaction_hashes.at(tx_index); bkey = TRANSATION_PREFIX + DB::to_binary_key(tid.data, TRANSACTION_PREFIX_BYTES) + common::write_varint_sqlite4(info.height) + common::write_varint_sqlite4(tx_index + 1); m_db.put(bkey, std::string(), true); } m_tip_segment.push_back(info); if (m_tip_segment.size() > 2048) // TODO - should be enough for all block windows we use m_tip_segment.pop_front(); return true; } void BlockChain::undo_block(const Hash &bhash, const RawBlock &, const Block &block, Height height) { if (!m_tip_segment.empty()) m_tip_segment.pop_back(); undo_block(bhash, block, height); auto tikey = TIMESTAMP_BLOCK_PREFIX + common::write_varint_sqlite4(block.header.timestamp) + common::write_varint_sqlite4(height); m_db.del(tikey, true); Hash tid = get_transaction_hash(block.header.base_transaction); auto bkey = TRANSATION_PREFIX + DB::to_binary_key(tid.data, TRANSACTION_PREFIX_BYTES) + common::write_varint_sqlite4(height) + common::write_varint_sqlite4(0); m_db.del(bkey, true); for (size_t tx_index = 0; tx_index != block.transactions.size(); ++tx_index) { tid = block.header.transaction_hashes.at(tx_index); bkey = TRANSATION_PREFIX + DB::to_binary_key(tid.data, TRANSACTION_PREFIX_BYTES) + common::write_varint_sqlite4(height) + common::write_varint_sqlite4(tx_index + 1); m_db.del(bkey, true); } } void BlockChain::store_block(const Hash &bid, const BinaryArray &block_data) { auto key = BLOCK_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)) + BLOCK_SUFFIX; m_db.put(key, block_data, true); } bool BlockChain::read_block(const Hash &bid, RawBlock &raw_block) const { BinaryArray rb; auto key = BLOCK_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)) + BLOCK_SUFFIX; if (!m_db.get(key, rb)) return false; seria::from_binary(raw_block, rb); return true; } bool BlockChain::has_block(const Hash &bid) const { platform::DB::Value ms; auto key = BLOCK_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)) + BLOCK_SUFFIX; if (!m_db.get(key, ms)) return false; return true; } void BlockChain::store_header(const Hash &bid, const api::BlockHeader &header) { auto key = HEADER_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)) + HEADER_SUFFIX; BinaryArray ba = seria::to_binary(header); m_db.put(key, ba, true); } bool BlockChain::read_header(const Hash &bid, api::BlockHeader &header) const { if (bid == m_tip_bid && !m_tip_segment.empty()) { header = m_tip_segment.back(); return true; } BinaryArray rb; auto key = HEADER_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)) + HEADER_SUFFIX; if (!m_db.get(key, rb)) return false; seria::from_binary(header, rb); return true; } api::BlockHeader BlockChain::read_header(const Hash &bid) const { api::BlockHeader result; if (!read_header(bid, result)) throw std::logic_error("Expected header was not found" + common::pod_to_hex(bid)); return result; } const api::BlockHeader &BlockChain::get_tip() const { if (m_tip_segment.empty()) m_tip_segment.push_back(read_header(get_tip_bid())); return m_tip_segment.back(); } std::pair<std::deque<api::BlockHeader>::const_iterator, std::deque<api::BlockHeader>::const_iterator> BlockChain::get_tip_segment(Height height_delta, Height window, bool add_genesis) const { if (get_tip_height() == (Height)-1 || height_delta > get_tip_height()) return std::make_pair(m_tip_segment.end(), m_tip_segment.end()); while (m_tip_segment.size() < height_delta + window && m_tip_segment.size() < m_tip_height + 1) { Hash ha = read_chain(static_cast<uint32_t>(m_tip_height - m_tip_segment.size())); m_tip_segment.push_front(read_header(ha)); } if (m_tip_height + 1 <= height_delta + window) { // if( m_tip_segment.size() == m_tip_height + 1 ) { // if (height_delta + window >= m_tip_segment.size()) { return std::make_pair(m_tip_segment.begin() + (add_genesis ? 0 : 1), m_tip_segment.end() - height_delta); } return std::make_pair(m_tip_segment.end() - window - height_delta, m_tip_segment.end() - height_delta); } void BlockChain::read_tip() { DB::Cursor cur2 = m_db.rbegin(TIP_CHAIN_PREFIX + version_current + "/"); m_tip_height = cur2.end() ? -1 : boost::lexical_cast<Height>(common::read_varint_sqlite4(cur2.get_suffix())); seria::from_binary(m_tip_bid, cur2.get_value_array()); api::BlockHeader tip_block = read_header(m_tip_bid); m_tip_cumulative_difficulty = tip_block.cumulative_difficulty; } void BlockChain::push_chain(Hash bid, Difficulty cumulative_difficulty) { m_tip_height += 1; BinaryArray ba = seria::to_binary(bid); m_db.put(TIP_CHAIN_PREFIX + version_current + "/" + common::write_varint_sqlite4(m_tip_height), ba, true); m_tip_bid = bid; m_tip_cumulative_difficulty = cumulative_difficulty; tip_changed(); } void BlockChain::pop_chain() { if (m_tip_height == 0) throw std::logic_error("pop_chain tip_height == 0"); m_db.del(TIP_CHAIN_PREFIX + version_current + "/" + common::write_varint_sqlite4(m_tip_height), true); m_tip_height -= 1; tip_changed(); } bool BlockChain::read_chain(uint32_t height, Hash &bid) const { BinaryArray ba; if (!m_db.get(TIP_CHAIN_PREFIX + version_current + "/" + common::write_varint_sqlite4(height), ba)) return false; seria::from_binary(bid, ba); return true; } Hash BlockChain::read_chain(uint32_t height) const { Hash ha; if (!read_chain(height, ha)) throw std::logic_error("read_header_chain failed"); return ha; } void BlockChain::check_children_counter(Difficulty cd, const Hash &bid, int value) { auto key = CHILDREN_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)); auto cd_key = CD_TIPS_PREFIX + common::write_varint_sqlite4(cd) + DB::to_binary_key(bid.data, sizeof(bid.data)); int counter = 1; // default is 1 when not stored in db BinaryArray rb; if (m_db.get(key, rb)) seria::from_binary(counter, rb); if (counter != value) throw std::logic_error("check_children_counter index corrupted"); if (counter == 0 && !m_db.get(cd_key, rb)) throw std::logic_error("check_children_counter tip is not in index"); if (counter != 0 && m_db.get(cd_key, rb)) throw std::logic_error("check_children_counter non-tip is in index"); } void BlockChain::modify_children_counter(Difficulty cd, const Hash &bid, int delta) { auto key = CHILDREN_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)); auto cd_key = CD_TIPS_PREFIX + common::write_varint_sqlite4(cd) + DB::to_binary_key(bid.data, sizeof(bid.data)); uint32_t counter = 1; // default is 1 when not stored in db BinaryArray rb; if (m_db.get(key, rb)) seria::from_binary(counter, rb); counter += delta; if (counter == 1) { m_db.del(key, false); } else { BinaryArray ba = seria::to_binary(counter); m_db.put(key, ba, false); } if (counter == 0) { m_db.put(cd_key, std::string(), false); } else { m_db.del(cd_key, false); } } bool BlockChain::get_oldest_tip(Difficulty &cd, Hash &bid) const { DB::Cursor cur = m_db.begin(CD_TIPS_PREFIX); if (cur.end()) return false; const std::string &suf = cur.get_suffix(); const char *be = suf.data(); const char *en = be + suf.size(); cd = common::read_varint_sqlite4(be, en); if (en - be != sizeof(bid.data)) throw std::logic_error("CD_TIPS_PREFIX corrupted"); DB::from_binary_key(cur.get_suffix(), cur.get_suffix().size() - sizeof(bid.data), bid.data, sizeof(bid.data)); return true; } bool BlockChain::prune_branch(Difficulty cd, Hash bid) { if (bid == m_tip_bid) return false; check_children_counter(cd, bid, 0); api::BlockHeader me = read_header(bid); api::BlockHeader pa = read_header(me.previous_block_hash); modify_children_counter(cd, bid, 1); modify_children_counter(pa.cumulative_difficulty, me.previous_block_hash, -1); auto key = BLOCK_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)) + BLOCK_SUFFIX; m_db.del(key, true); auto key2 = HEADER_PREFIX + DB::to_binary_key(bid.data, sizeof(bid.data)) + HEADER_SUFFIX; m_db.del(key2, true); return true; } void BlockChain::test_prune_oldest() { for (int i = 0; i != 10; ++i) { Difficulty cd = 0; Hash bid; if (!get_oldest_tip(cd, bid)) return; prune_branch(cd, bid); } } void BlockChain::test_print_structure() const { Difficulty ocd; Hash obid; if (get_oldest_tip(ocd, obid)) std::cout << "oldest tip cd=" << ocd << " bid=" << common::pod_to_hex(obid) << std::endl; for (DB::Cursor cur = m_db.begin(CD_TIPS_PREFIX); !cur.end(); cur.next()) { const std::string &suf = cur.get_suffix(); const char *be = suf.data(); const char *en = be + suf.size(); Difficulty cd = common::read_varint_sqlite4(be, en); Hash bid; if (en - be != sizeof(bid.data)) throw std::logic_error("CD_TIPS_PREFIX corrupted"); DB::from_binary_key(cur.get_suffix(), cur.get_suffix().size() - sizeof(bid.data), bid.data, sizeof(bid.data)); std::cout << "tip cd=" << cd << " bid=" << common::pod_to_hex(bid) << std::endl; } for (DB::Cursor cur = m_db.begin(CHILDREN_PREFIX); !cur.end(); cur.next()) { Hash bid; DB::from_binary_key(cur.get_suffix(), 0, bid.data, sizeof(bid.data)); uint32_t counter = 1; seria::from_binary(counter, cur.get_value_array()); std::cout << "children counter=" << counter << " bid=" << common::pod_to_hex(bid) << std::endl; } } bool BlockChain::read_next_internal_block(Hash &bid) const { BinaryArray ba; if (!m_db.get( TIP_CHAIN_PREFIX + previous_versions[0] + "/" + common::write_varint_sqlite4(get_tip_height() + 1), ba)) return false; seria::from_binary(bid, ba); return true; } bool BlockChain::internal_import() { auto idea_start = std::chrono::high_resolution_clock::now(); while (true) { Hash bid; if (!read_next_internal_block(bid)) break; RawBlock rb; if (!read_block(bid, rb)) break; PreparedBlock pb(std::move(rb), nullptr); api::BlockHeader info; if (add_block(pb, info) != BroadcastAction::BROADCAST_ALL) { std::cout << "internal_import block_chain.add_block !BROADCAST_ALL block=" << get_tip_height() + 1 << std::endl; break; } if (get_tip_height() % 50000 == 0) db_commit(); auto idea_ms = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - idea_start); if (idea_ms.count() > 100) return true; // continue importing } std::cout << "Finished internal importing of blocks, clearing chains..." << std::endl; size_t erased = 0; for (DB::Cursor cur = m_db.begin(TIP_CHAIN_PREFIX + previous_versions[0] + "/"); !cur.end(); cur.erase()) { erased += 1; } std::cout << "Items erased " << erased << std::endl; m_internal_import_known_height = 0; db_commit(); return false; } void BlockChain::test_undo_everything() { while (true) { RawBlock raw_block; Block block; if (!read_block(get_tip_bid(), raw_block) || !block.from_raw_block(raw_block)) break; undo_block(get_tip_bid(), raw_block, block, m_tip_height); if (get_tip_bid() == m_genesis_bid) break; pop_chain(); api::BlockHeader info = get_tip(); m_tip_bid = block.header.previous_block_hash; m_tip_cumulative_difficulty -= info.cumulative_difficulty; if (get_tip_height() % 50000 == 1) db_commit(); } std::cout << "---- After undo everything ---- " << std::endl; int counter = 0; for (DB::Cursor cur = m_db.begin(std::string()); !cur.end(); cur.next()) { if (cur.get_suffix().find(BLOCK_PREFIX) == 0) continue; if (cur.get_suffix().find(HEADER_PREFIX) == 0) continue; if (cur.get_suffix().find("f") == 0) continue; std::cout << DB::clean_key(cur.get_suffix()) << std::endl; if (counter++ > 2000) break; } } >>>>>>> 15c463360ec17ef10da96da016f30bce13467f24
38.114103
119
0.690874
VaultB
b4ce0fb6e22ba67e30700744a0a1cc7076f8171f
323
cpp
C++
08_abstract_class/main.cpp
acc-cosc-1337-spring-2019/final-exam-spring-2019-carolinekim510
78f4b05d76feaa9d2dba9af2c457ea5c15654057
[ "MIT" ]
null
null
null
08_abstract_class/main.cpp
acc-cosc-1337-spring-2019/final-exam-spring-2019-carolinekim510
78f4b05d76feaa9d2dba9af2c457ea5c15654057
[ "MIT" ]
null
null
null
08_abstract_class/main.cpp
acc-cosc-1337-spring-2019/final-exam-spring-2019-carolinekim510
78f4b05d76feaa9d2dba9af2c457ea5c15654057
[ "MIT" ]
null
null
null
#include "08_abstract_class/checking_account.h" #include "08_abstract_class/savings_account.h" #include<vector> #include<iostream> int main() { std::vector<Account*> accounts = { new CheckingAccount(50), new SavingsAccount(100) }; for (auto& a : accounts) { std::cout << a->get_balance() << "\n"; } return 0; }
19
60
0.690402
acc-cosc-1337-spring-2019
b4d5877b5a40c89db6a1b395035e4b1408f99e63
2,605
hpp
C++
src/holosuite-lib/holoutils/HoloUtils.hpp
itsermo/holosuite
16659efec910a4050ddd6548b1310e3ed09636e0
[ "BSD-3-Clause" ]
null
null
null
src/holosuite-lib/holoutils/HoloUtils.hpp
itsermo/holosuite
16659efec910a4050ddd6548b1310e3ed09636e0
[ "BSD-3-Clause" ]
null
null
null
src/holosuite-lib/holoutils/HoloUtils.hpp
itsermo/holosuite
16659efec910a4050ddd6548b1310e3ed09636e0
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "../holocommon/CommonDefs.hpp" namespace holo { namespace utils { //converts rgba + z pictures into a point cloud and reprojects to real-world coordinates quickly void ReprojectToRealWorld(HoloCloudPtr& cloudOut, HoloRGBAZMat& rgbaz, holo::capture::WorldConvertCache& worldConvertCache); //converts rgb888 to rgba8888, (aka rgb to rgba) void ConvertRGBToRGBA(cv::Mat& rgbMat, cv::Mat& rgbaMatOut); // Following files were copied from /* * transforms.h * Dblfrustum * * Created by HoloVideo Bove Lab on 6/11/08. * Copyright 2008 __MyCompanyName__. All rights reserved. * */ void BuildShearOrthographicMatrix(double Xleft, double Xright, double Ybot, double Ytop, double n, double f, double q, float m[16]); void BuildShearOrthographicMatrix2(double Xleft, double Xright, double Ybot, double Ytop, double n, double f, double q, float m[16]); void BuildDblPerspectiveMatrix(double Xleft, double Xright, double Ybot, double Ytop, double n, double f, double p, float m[16]); void BuildDblPerspectiveMatrix2(double Xleft, double Xright, double Ybot, double Ytop, double n, double f, double p, float m[16]); void BuildPerspectiveMatrix(double fieldOfView, double aspectRatio, double zNear, double zFar, float m[16]); /* Build a row-major (C-style) 4x4 matrix transform based on the parameters for gluLookAt. */ void BuildLookAtMatrix(double eyex, double eyey, double eyez, double centerx, double centery, double centerz, double upx, double upy, double upz, float m[16]); /* Build a row-major (C-style) 4x4 matrix transform based on the parameters for glRotatef. */ void MakeRotateMatrix(float angle, float ax, float ay, float az, float m[16]); /* Build a row-major (C-style) 4x4 matrix transform based on the parameters for glTranslatef. */ void MakeTranslateMatrix(float x, float y, float z, float m[16]); /* Build a row-major (C-style) 4x4 matrix transform based on the parameters for glTranslatef. */ void MakeScaleMatrix(float x, float y, float z, float m[16]); /* Simple 4x4 matrix by 4x4 matrix multiply. */ void MultMatrix(float dst[16], const float src1[16], const float src2[16]); /*Invert a row-major (C-style) 4x4 model (trans,rot) matrix */ void TransposeMatrix(float *out, const float *m); /* Invert a row-major (C-style) 4x4 matrix. */ void InvertMatrix(float *out, const float *m); /* Simple 4x4 matrix by 4-component column vector multiply. */ void Transform(float dst[4], const float mat[16], const float vec[4]); } }
31.768293
126
0.714012
itsermo
b4d6910812849c32f57cf07f6bbf3711ca2f0fcf
13,957
cc
C++
src/atlas/redistribution/detail/StructuredColumnsToStructuredColumns.cc
wdeconinck/atlas
8949d2b362b9b5431023a967bcf4ca84f6b8ce05
[ "Apache-2.0" ]
null
null
null
src/atlas/redistribution/detail/StructuredColumnsToStructuredColumns.cc
wdeconinck/atlas
8949d2b362b9b5431023a967bcf4ca84f6b8ce05
[ "Apache-2.0" ]
null
null
null
src/atlas/redistribution/detail/StructuredColumnsToStructuredColumns.cc
wdeconinck/atlas
8949d2b362b9b5431023a967bcf4ca84f6b8ce05
[ "Apache-2.0" ]
null
null
null
/* * (C) Crown Copyright 2021 Met Office * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ #include <algorithm> #include <numeric> #include "atlas/array/MakeView.h" #include "atlas/field.h" #include "atlas/field/FieldSet.h" #include "atlas/parallel/mpi/mpi.h" #include "atlas/redistribution/detail/RedistributionUtils.h" #include "atlas/redistribution/detail/StructuredColumnsToStructuredColumns.h" // Exception handling macros. #define TRY_CAST( a, b ) tryCast<a>( b, #b, Here() ) #define CHECK_GRIDS( a, b, c ) checkGrids<a>( b, c, #b, #c, Here() ) #define CHECK_FIELD_DATA_TYPE( a, b ) checkFieldDataType( a, b, #a, #b, Here() ) #define CHECK_FIELD_SET_SIZE( a, b ) checkFieldSetSize( a, b, #a, #b, Here() ) namespace atlas { namespace redistribution { namespace detail { // Anonymous name space for helper functions. namespace { // Transform a vector element-by-element with a functor. template <typename outType, typename inType, typename functorType> std::vector<outType> transformVector( const std::vector<inType>& inVector, const functorType& functor ) { // Declare result. auto outVector = std::vector<outType>{}; outVector.reserve( inVector.size() ); // Transform vector. std::transform( inVector.begin(), inVector.end(), std::back_inserter( outVector ), functor ); return outVector; } // Visit each index in a StructuredIndexRangeVector. template <typename functorType> void forEachIndex( const StructuredIndexRangeVector& ranges, const functorType& functor ) { // Loop over all ranges. std::for_each( ranges.cbegin(), ranges.cend(), [&]( const StructuredIndexRange& range ) { range.forEach( functor ); return; } ); return; } } // namespace //======================================================================== // Class public methods implementation. //======================================================================== // Constructor. StructuredColumnsToStructuredColumns::StructuredColumnsToStructuredColumns( const FunctionSpace& sourceFunctionSpace, const FunctionSpace& targetFunctionSpace ) : RedistributionImpl( sourceFunctionSpace, targetFunctionSpace ), sourceStructuredColumnsPtr_( source()->cast<StructuredColumns>() ), targetStructuredColumnsPtr_( target()->cast<StructuredColumns>() ) { // Check casts. TRY_CAST( StructuredColumns, sourceStructuredColumnsPtr_ ); TRY_CAST( StructuredColumns, targetStructuredColumnsPtr_ ); // Check that grids match. CHECK_GRIDS( StructuredColumns, sourceStructuredColumnsPtr_, targetStructuredColumnsPtr_ ); // Get source and target range of this function space. const auto sourceRange = StructuredIndexRange( sourceStructuredColumnsPtr_ ); const auto targetRange = StructuredIndexRange( targetStructuredColumnsPtr_ ); // Get source and target ranges over all PEs. const auto sourceRanges = sourceRange.getStructuredIndexRanges(); const auto targetRanges = targetRange.getStructuredIndexRanges(); // Get intersections between sourceRange and targetRanges. auto getIntersections = []( const StructuredIndexRange& range, const StructuredIndexRangeVector& ranges ) { return transformVector<StructuredIndexRange>( ranges, [&]( const StructuredIndexRange& rangesElem ) { return range & rangesElem; } ); }; sendIntersections_ = getIntersections( sourceRange, targetRanges ); recvIntersections_ = getIntersections( targetRange, sourceRanges ); // Get counts and displacements for MPI communication. auto getCountsDisplacements = []( const StructuredIndexRangeVector& intersections, const idx_t levels ) { const auto counts = transformVector<int>( intersections, [&]( const StructuredIndexRange& intersection ) { return static_cast<int>( intersection.getElemCount() * levels ); } ); auto displacements = std::vector<int>{0}; std::partial_sum( counts.cbegin(), counts.cend() - 1, std::back_inserter( displacements ) ); return std::make_pair( counts, displacements ); }; std::tie( sendCounts_, sendDisplacements_ ) = getCountsDisplacements( sendIntersections_, sourceStructuredColumnsPtr_->levels() ); std::tie( recvCounts_, recvDisplacements_ ) = getCountsDisplacements( recvIntersections_, targetStructuredColumnsPtr_->levels() ); // Trim off invalid intersections. auto trimIntersections = []( StructuredIndexRangeVector& intersections ) { intersections.erase( std::remove_if( intersections.begin(), intersections.end(), []( const StructuredIndexRange& intersection ) { return !( intersection.getElemCount() ); } ), intersections.end() ); return; }; trimIntersections( sendIntersections_ ); trimIntersections( recvIntersections_ ); return; } void StructuredColumnsToStructuredColumns::execute( const Field& sourceField, Field& targetField ) const { // Check functionspace casts. TRY_CAST( StructuredColumns, sourceField.functionspace().get() ); TRY_CAST( StructuredColumns, targetField.functionspace().get() ); // Check source grids match. CHECK_GRIDS( StructuredColumns, sourceField.functionspace().get(), sourceStructuredColumnsPtr_ ); // Check target grids match. CHECK_GRIDS( StructuredColumns, targetField.functionspace().get(), targetStructuredColumnsPtr_ ); // Check data types match. CHECK_FIELD_DATA_TYPE( sourceField, targetField ); // Determine data type of field and execute. switch ( sourceField.datatype().kind() ) { case array::DataType::KIND_REAL64: doExecute<double>( sourceField, targetField ); break; case array::DataType::KIND_REAL32: doExecute<float>( sourceField, targetField ); break; case array::DataType::KIND_INT32: doExecute<int>( sourceField, targetField ); break; case array::DataType::KIND_INT64: doExecute<long>( sourceField, targetField ); break; default: throw eckit::NotImplemented( "No implementation for data type " + sourceField.datatype().str(), Here() ); } return; } void StructuredColumnsToStructuredColumns::execute( const FieldSet& sourceFieldSet, FieldSet& targetFieldSet ) const { // Check that both FieldSets are the same size. CHECK_FIELD_SET_SIZE( sourceFieldSet, targetFieldSet ); auto targetFieldSetIt = targetFieldSet.begin(); std::for_each( sourceFieldSet.cbegin(), sourceFieldSet.cend(), [&]( const Field& sourceField ) { execute( sourceField, *targetFieldSetIt++ ); return; } ); return; } //======================================================================== // Class private methods implementation. //======================================================================== template <typename fieldType> void StructuredColumnsToStructuredColumns::doExecute( const Field& sourceField, Field& targetField ) const { // Make Atlas view objects. const auto sourceView = array::make_view<fieldType, 2>( sourceField ); auto targetView = array::make_view<fieldType, 2>( targetField ); // Get buffer sizes. const auto nSend = sendCounts_.back() + sendDisplacements_.back(); const auto nRecv = recvCounts_.back() + recvDisplacements_.back(); // Allocate send and receive buffers. auto sendBuffer = std::vector<fieldType>( static_cast<size_t>( nSend ) ); auto recvBuffer = std::vector<fieldType>( static_cast<size_t>( nRecv ) ); // Set send functor. auto sendBufferIt = sendBuffer.begin(); auto sendFunctor = [&]( const idx_t i, const idx_t j ) { // Loop over levels const auto iNode = sourceStructuredColumnsPtr_->index( i, j ); const auto kEnd = sourceStructuredColumnsPtr_->levels(); for ( idx_t k = 0; k < kEnd; ++k ) { *sendBufferIt++ = sourceView( iNode, k ); } return; }; // Set receive functor. auto recvBufferIt = recvBuffer.cbegin(); auto recvFunctor = [&]( const idx_t i, const idx_t j ) { // Loop over levels const auto iNode = targetStructuredColumnsPtr_->index( i, j ); const auto kEnd = targetStructuredColumnsPtr_->levels(); for ( idx_t k = 0; k < kEnd; ++k ) { targetView( iNode, k ) = *recvBufferIt++; } return; }; // Write data to buffer. forEachIndex( sendIntersections_, sendFunctor ); // Communicate. mpi::comm().allToAllv( sendBuffer.data(), sendCounts_.data(), sendDisplacements_.data(), recvBuffer.data(), recvCounts_.data(), recvDisplacements_.data() ); // Read data from buffer. forEachIndex( recvIntersections_, recvFunctor ); return; } //======================================================================== // Index range methods. //======================================================================== // Constructor. StructuredIndexRange::StructuredIndexRange( const StructuredColumns* const structuredColumnsPtr ) { jBeginEnd_ = std::make_pair( structuredColumnsPtr->j_begin(), structuredColumnsPtr->j_end() ); for ( auto j = jBeginEnd_.first; j < jBeginEnd_.second; ++j ) { iBeginEnd_.push_back( std::make_pair( structuredColumnsPtr->i_begin( j ), structuredColumnsPtr->i_end( j ) ) ); } return; } // Get index ranges from all PEs. StructuredIndexRangeVector StructuredIndexRange::getStructuredIndexRanges() const { // Get MPI communicator size. const auto mpiSize = static_cast<size_t>( atlas::mpi::comm().size() ); // Set recv buffer for j range. auto jRecvBuffer = idxPairVector( mpiSize ); // Perform all gather. atlas::mpi::comm().allGather( jBeginEnd_, jRecvBuffer.begin(), jRecvBuffer.end() ); // Set i receive counts. auto iRecvCounts = transformVector<int>( jRecvBuffer, []( const idxPair& jElem ) { return static_cast<int>( jElem.second - jElem.first ); } ); // Set recv displacements for i range. auto iRecvDisplacements = std::vector<int>{0}; std::partial_sum( iRecvCounts.cbegin(), iRecvCounts.cend() - 1, std::back_inserter( iRecvDisplacements ) ); // Set recv buffer for i range. auto irecvBuffer = idxPairVector( static_cast<size_t>( iRecvDisplacements.back() + iRecvCounts.back() ) ); // Perform all gather. atlas::mpi::comm().allGatherv( iBeginEnd_.cbegin(), iBeginEnd_.cend(), irecvBuffer.begin(), iRecvCounts.data(), iRecvDisplacements.data() ); // Make vector of indexRange structs. auto indexRanges = StructuredIndexRangeVector{}; for ( size_t i = 0; i < mpiSize; ++i ) { auto indexRange = StructuredIndexRange{}; indexRange.jBeginEnd_ = jRecvBuffer[i]; const auto iBegin = irecvBuffer.cbegin() + iRecvDisplacements[i]; const auto iEnd = iBegin + iRecvCounts[i]; std::copy( iBegin, iEnd, std::back_inserter( indexRange.iBeginEnd_ ) ); indexRanges.push_back( indexRange ); } return indexRanges; } // Count number of elements in index range. idx_t StructuredIndexRange::getElemCount() const { // Accumulate size of positive i range. const auto count = std::accumulate( iBeginEnd_.cbegin(), iBeginEnd_.cend(), 0, []( const idx_t cumulant, const idxPair iElem ) { // Only count positive differences. return cumulant + static_cast<idx_t>( std::max( iElem.second - iElem.first, idx_t( 0 ) ) ); } ); return count; } // Return the intersection between two index ranges. StructuredIndexRange StructuredIndexRange::operator&( const StructuredIndexRange& indexRange ) const { // Declare result. auto intersection = StructuredIndexRange{}; // get j intersection range. intersection.jBeginEnd_ = std::make_pair( std::max( jBeginEnd_.first, indexRange.jBeginEnd_.first ), std::min( jBeginEnd_.second, indexRange.jBeginEnd_.second ) ); // get i intersection range. if ( intersection.jBeginEnd_.first < intersection.jBeginEnd_.second ) { // get iterators. const auto iBeginA = iBeginEnd_.cbegin() + intersection.jBeginEnd_.first - jBeginEnd_.first; const auto iBeginB = indexRange.iBeginEnd_.cbegin() + intersection.jBeginEnd_.first - indexRange.jBeginEnd_.first; const auto iEndA = iBeginEnd_.cend() + intersection.jBeginEnd_.second - jBeginEnd_.second; std::transform( iBeginA, iEndA, iBeginB, std::back_inserter( intersection.iBeginEnd_ ), []( const idxPair iElemA, const idxPair iElemB ) { return std::make_pair( std::max( iElemA.first, iElemB.first ), std::min( iElemA.second, iElemB.second ) ); } ); } return intersection; } // Loop over all indices. Functor should have signature // functor(const idx_t i, const idx_t j). template <typename functorType> void StructuredIndexRange::forEach( const functorType& functor ) const { auto iBeginEndIt = iBeginEnd_.begin(); // Loop over j. for ( auto j = jBeginEnd_.first; j < jBeginEnd_.second; ++j ) { const auto iBeginEnd = *iBeginEndIt++; // Loop over i. for ( auto i = iBeginEnd.first; i < iBeginEnd.second; ++i ) { // Call functor. functor( i, j ); } } return; } } // namespace detail } // namespace redistribution } // namespace atlas
38.769444
120
0.643978
wdeconinck
b4d6ee1e5b1961d1aa0c6c0fdf106d3db28ee615
15,867
hpp
C++
vertex/test/TestOffLatticeSimulationWithMinimumMaximumCellCount.hpp
ThomasPak/cell-competition
bb058d67e297d95c4c8ff2a0aea5b1fe5a82be09
[ "BSD-3-Clause" ]
null
null
null
vertex/test/TestOffLatticeSimulationWithMinimumMaximumCellCount.hpp
ThomasPak/cell-competition
bb058d67e297d95c4c8ff2a0aea5b1fe5a82be09
[ "BSD-3-Clause" ]
null
null
null
vertex/test/TestOffLatticeSimulationWithMinimumMaximumCellCount.hpp
ThomasPak/cell-competition
bb058d67e297d95c4c8ff2a0aea5b1fe5a82be09
[ "BSD-3-Clause" ]
null
null
null
#ifndef TESTOFFLATTICESIMULATIONWITHCELLCOUNTLIMIT_HPP #define TESTOFFLATTICESIMULATIONWITHCELLCOUNTLIMIT_HPP #include <cxxtest/TestSuite.h> #include <cstdio> #include <cmath> #include <unordered_map> #include "CheckpointArchiveTypes.hpp" #include "OffLatticeSimulation.hpp" #include "HoneycombVertexMeshGenerator.hpp" #include "MutableVertexMesh.hpp" #include "VertexBasedCellPopulation.hpp" #include "CellsGenerator.hpp" #include "CustomUniformG1GenerationalCellCycleModel.hpp" #include "AbstractCellBasedWithTimingsTestSuite.hpp" #include "WildTypeCellMutationState.hpp" #include "OffLatticeSimulationWithMinimumMaximumCellCount.hpp" #include "TransitCellProliferativeType.hpp" #include "SmartPointers.hpp" #include "FarhadifarForce.hpp" #include "SimpleTargetAreaModifier.hpp" #include "LogFile.hpp" #include "TargetedCellKiller.hpp" #include "CellAncestor.hpp" #include "PetscSetupAndFinalize.hpp" class TestOffLatticeSimulation : public AbstractCellBasedWithTimingsTestSuite { public: void TestOffLatticeSimulationWithMaximumCellCount() { EXIT_IF_PARALLEL; // HoneycombMeshGenerator does not work in parallel unsigned max_cell_count = 7; HoneycombVertexMeshGenerator generator(2, 2); MutableVertexMesh<2,2>* p_mesh = generator.GetMesh(); // Define mutation state and proliferative type MAKE_PTR(WildTypeCellMutationState, p_state); MAKE_PTR(TransitCellProliferativeType, p_transit_type); // Create cells std::vector<CellPtr> cells; std::vector<double> birth_times = { -10.0, -13.2, -50.0, -50.0 }; for (const auto& birth_time : birth_times) { // Get individual parameters double g1_duration = 50.0; double g2_duration = 50.0; double uniform_g1_range = 0.0; unsigned max_transit_generation = static_cast<unsigned>(-1); // Create cell cycle model CustomUniformG1GenerationalCellCycleModel* p_cell_cycle_model = new CustomUniformG1GenerationalCellCycleModel(); // Set cell cycle phase durations p_cell_cycle_model->SetMDuration(1e-12); p_cell_cycle_model->SetSDuration(1e-12); p_cell_cycle_model->SetTransitCellG1Duration(g1_duration); p_cell_cycle_model->SetG2Duration(g2_duration); p_cell_cycle_model->SetRange(uniform_g1_range); // Set max transit generations p_cell_cycle_model->SetMaxTransitGenerations(max_transit_generation); // Create cell CellPtr p_cell(new Cell(p_state, p_cell_cycle_model)); // Set cell proliferative type p_cell->SetCellProliferativeType(p_transit_type); // Set cell birth time p_cell->SetBirthTime(birth_time); // Push cell cells.push_back(p_cell); } // Define cell population VertexBasedCellPopulation<2> cell_population(*p_mesh, cells); // Define simulation OffLatticeSimulationWithMinimumMaximumCellCount simulator(cell_population, 0, max_cell_count); simulator.SetOutputDirectory("TestCellPopulationSimWithMaximumCellCount"); TS_ASSERT_EQUALS(simulator.GetMaximumCellCount(), max_cell_count); // Set the end time to 100h, the stopping event occurs at t = 86.8 // hours however simulator.SetEndTime(100.0); simulator.SetDt(0.01); simulator.SetSamplingTimestepMultiple(100); // Run cell-based simulation simulator.Solve(); double time = SimulationTime::Instance()->GetTime(); TS_ASSERT_DELTA(time, 87.0, 1e-1); // The number of cells should be greater than or equal to the maximum // cell count unsigned cell_count = 0; for (auto cell_ptr = simulator.rGetCellPopulation().Begin(); cell_ptr != simulator.rGetCellPopulation().End(); ++cell_ptr) { cell_count++; } TS_ASSERT_LESS_THAN_EQUALS(max_cell_count, cell_count); } void TestOffLatticeSimulationWithMinimumCellCount() { EXIT_IF_PARALLEL; // HoneycombMeshGenerator does not work in parallel unsigned min_cell_count = 1; HoneycombVertexMeshGenerator generator(2, 2); MutableVertexMesh<2,2>* p_mesh = generator.GetMesh(); // Define mutation state and proliferative type MAKE_PTR(WildTypeCellMutationState, p_state); MAKE_PTR(TransitCellProliferativeType, p_transit_type); // Create cells std::vector<CellPtr> cells; std::vector<double> birth_times = { -10.0, -13.2, -50.0, -50.0 }; for (const auto& birth_time : birth_times) { // Get individual parameters double g1_duration = 50.0; double g2_duration = 50.0; double uniform_g1_range = 0.0; unsigned max_transit_generation = static_cast<unsigned>(-1); // Create cell cycle model CustomUniformG1GenerationalCellCycleModel* p_cell_cycle_model = new CustomUniformG1GenerationalCellCycleModel(); // Set cell cycle phase durations p_cell_cycle_model->SetMDuration(1e-12); p_cell_cycle_model->SetSDuration(1e-12); p_cell_cycle_model->SetTransitCellG1Duration(g1_duration); p_cell_cycle_model->SetG2Duration(g2_duration); p_cell_cycle_model->SetRange(uniform_g1_range); // Set max transit generations p_cell_cycle_model->SetMaxTransitGenerations(max_transit_generation); // Create cell CellPtr p_cell(new Cell(p_state, p_cell_cycle_model)); // Set cell proliferative type p_cell->SetCellProliferativeType(p_transit_type); // Set cell birth time p_cell->SetBirthTime(birth_time); // Push cell cells.push_back(p_cell); } // Define cell population VertexBasedCellPopulation<2> cell_population(*p_mesh, cells); // Define simulation OffLatticeSimulationWithMinimumMaximumCellCount simulator(cell_population, min_cell_count); simulator.SetOutputDirectory("TestCellPopulationSimWithMinimumCellCount"); TS_ASSERT_EQUALS(simulator.GetMinimumCellCount(), min_cell_count); // Set the end time to 100h, the stopping event occurs at t = 0.01 // hours however simulator.SetEndTime(100.0); simulator.SetDt(0.01); simulator.SetSamplingTimestepMultiple(100); MAKE_PTR_ARGS(TargetedCellKiller<2>, p_killer_1, (&cell_population, 3u)); MAKE_PTR_ARGS(TargetedCellKiller<2>, p_killer_2, (&cell_population, 2u)); MAKE_PTR_ARGS(TargetedCellKiller<2>, p_killer_3, (&cell_population, 1u)); simulator.AddCellKiller(p_killer_1); simulator.AddCellKiller(p_killer_2); simulator.AddCellKiller(p_killer_3); // Run cell-based simulation simulator.Solve(); double time = SimulationTime::Instance()->GetTime(); TS_ASSERT_DELTA(time, 1, 1e-1); // The number of cells should be less or equal to the cell count limit unsigned cell_count = 0; for (auto cell_ptr = simulator.rGetCellPopulation().Begin(); cell_ptr != simulator.rGetCellPopulation().End(); ++cell_ptr) { cell_count++; } TS_ASSERT_LESS_THAN_EQUALS(cell_count, min_cell_count); } void TestOffLatticeSimulationWithMaximumCellCountForAncestor() { EXIT_IF_PARALLEL; // HoneycombMeshGenerator does not work in parallel std::unordered_map<unsigned, unsigned> min_cell_count_for_ancestor; std::unordered_map<unsigned, unsigned> max_cell_count_for_ancestor; max_cell_count_for_ancestor[0] = 3; HoneycombVertexMeshGenerator generator(2, 2); MutableVertexMesh<2,2>* p_mesh = generator.GetMesh(); // Define mutation state and proliferative type MAKE_PTR(WildTypeCellMutationState, p_state); MAKE_PTR(TransitCellProliferativeType, p_transit_type); // Create cells std::vector<CellPtr> cells; std::vector<double> birth_times = { -10.0, -13.2, -50.0, -50.0 }; for (const auto& birth_time : birth_times) { // Get individual parameters double g1_duration = 50.0; double g2_duration = 50.0; double uniform_g1_range = 0.0; unsigned max_transit_generation = static_cast<unsigned>(-1); // Create cell cycle model CustomUniformG1GenerationalCellCycleModel* p_cell_cycle_model = new CustomUniformG1GenerationalCellCycleModel(); // Set cell cycle phase durations p_cell_cycle_model->SetMDuration(1e-12); p_cell_cycle_model->SetSDuration(1e-12); p_cell_cycle_model->SetTransitCellG1Duration(g1_duration); p_cell_cycle_model->SetG2Duration(g2_duration); p_cell_cycle_model->SetRange(uniform_g1_range); // Set max transit generations p_cell_cycle_model->SetMaxTransitGenerations(max_transit_generation); // Create cell CellPtr p_cell(new Cell(p_state, p_cell_cycle_model)); // Set cell proliferative type p_cell->SetCellProliferativeType(p_transit_type); // Set cell birth time p_cell->SetBirthTime(birth_time); // Push cell cells.push_back(p_cell); } MAKE_PTR_ARGS(CellAncestor, p_cell_ancestor_0, (0)); MAKE_PTR_ARGS(CellAncestor, p_cell_ancestor_1, (1)); cells[0]->SetAncestor(p_cell_ancestor_0); cells[1]->SetAncestor(p_cell_ancestor_0); cells[2]->SetAncestor(p_cell_ancestor_1); cells[3]->SetAncestor(p_cell_ancestor_1); // Define cell population VertexBasedCellPopulation<2> cell_population(*p_mesh, cells); // Define simulation OffLatticeSimulationWithMinimumMaximumCellCount simulator(cell_population, 0, static_cast<unsigned>(-1), min_cell_count_for_ancestor, max_cell_count_for_ancestor); simulator.SetOutputDirectory("TestCellPopulationSimWithMaximumCellCountForAncestor"); TS_ASSERT_EQUALS(simulator.GetMaximumCellCountForAncestor(0), max_cell_count_for_ancestor[0]); // Set the end time to 100h, the stopping event occurs at t = 86.8 // hours however simulator.SetEndTime(100.0); simulator.SetDt(0.01); simulator.SetSamplingTimestepMultiple(100); // Run cell-based simulation simulator.Solve(); double time = SimulationTime::Instance()->GetTime(); TS_ASSERT_DELTA(time, 87.0, 1e-1); // The number of cells of ancestor 0 should be greater than or equal to // the maximum cell count unsigned cell_count_for_ancestor_0 = 0; for (auto cell_ptr = simulator.rGetCellPopulation().Begin(); cell_ptr != simulator.rGetCellPopulation().End(); ++cell_ptr) { if (cell_ptr->GetAncestor() == 0) { cell_count_for_ancestor_0++; } } TS_ASSERT_LESS_THAN_EQUALS(max_cell_count_for_ancestor[0], cell_count_for_ancestor_0); } void TestOffLatticeSimulationWithMinimumCellCountForAncestor() { EXIT_IF_PARALLEL; // HoneycombMeshGenerator does not work in parallel std::unordered_map<unsigned, unsigned> min_cell_count_for_ancestor; std::unordered_map<unsigned, unsigned> max_cell_count_for_ancestor; min_cell_count_for_ancestor[1] = 0; HoneycombVertexMeshGenerator generator(2, 2); MutableVertexMesh<2,2>* p_mesh = generator.GetMesh(); // Define mutation state and proliferative type MAKE_PTR(WildTypeCellMutationState, p_state); MAKE_PTR(TransitCellProliferativeType, p_transit_type); // Create cells std::vector<CellPtr> cells; std::vector<double> birth_times = { -10.0, -13.2, -50.0, -50.0 }; for (const auto& birth_time : birth_times) { // Get individual parameters double g1_duration = 50.0; double g2_duration = 50.0; double uniform_g1_range = 0.0; unsigned max_transit_generation = static_cast<unsigned>(-1); // Create cell cycle model CustomUniformG1GenerationalCellCycleModel* p_cell_cycle_model = new CustomUniformG1GenerationalCellCycleModel(); // Set cell cycle phase durations p_cell_cycle_model->SetMDuration(1e-12); p_cell_cycle_model->SetSDuration(1e-12); p_cell_cycle_model->SetTransitCellG1Duration(g1_duration); p_cell_cycle_model->SetG2Duration(g2_duration); p_cell_cycle_model->SetRange(uniform_g1_range); // Set max transit generations p_cell_cycle_model->SetMaxTransitGenerations(max_transit_generation); // Create cell CellPtr p_cell(new Cell(p_state, p_cell_cycle_model)); // Set cell proliferative type p_cell->SetCellProliferativeType(p_transit_type); // Set cell birth time p_cell->SetBirthTime(birth_time); // Push cell cells.push_back(p_cell); } MAKE_PTR_ARGS(CellAncestor, p_cell_ancestor_0, (0)); MAKE_PTR_ARGS(CellAncestor, p_cell_ancestor_1, (1)); cells[0]->SetAncestor(p_cell_ancestor_0); cells[1]->SetAncestor(p_cell_ancestor_0); cells[2]->SetAncestor(p_cell_ancestor_1); cells[3]->SetAncestor(p_cell_ancestor_1); // Define cell population VertexBasedCellPopulation<2> cell_population(*p_mesh, cells); // Define simulation OffLatticeSimulationWithMinimumMaximumCellCount simulator(cell_population, 0, static_cast<unsigned>(-1), min_cell_count_for_ancestor, max_cell_count_for_ancestor); simulator.SetOutputDirectory("TestCellPopulationSimWithMinimumCellCountForAncestor"); TS_ASSERT_EQUALS(simulator.GetMinimumCellCountForAncestor(1), min_cell_count_for_ancestor[1]); // Set the end time to 100h, the stopping event occurs at t = 0.01 // hours however simulator.SetEndTime(100.0); simulator.SetDt(0.01); simulator.SetSamplingTimestepMultiple(100); MAKE_PTR_ARGS(TargetedCellKiller<2>, p_killer_1, (&cell_population, 3u)); MAKE_PTR_ARGS(TargetedCellKiller<2>, p_killer_2, (&cell_population, 2u)); MAKE_PTR_ARGS(TargetedCellKiller<2>, p_killer_3, (&cell_population, 1u)); simulator.AddCellKiller(p_killer_1); simulator.AddCellKiller(p_killer_2); simulator.AddCellKiller(p_killer_3); // Run cell-based simulation simulator.Solve(); double time = SimulationTime::Instance()->GetTime(); TS_ASSERT_DELTA(time, 1, 1e-1); // The number of cells of ancestor 1 should be less or equal to the // cell count limit unsigned cell_count_for_ancestor_1 = 0; for (auto cell_ptr = simulator.rGetCellPopulation().Begin(); cell_ptr != simulator.rGetCellPopulation().End(); ++cell_ptr) { if (cell_ptr->GetAncestor() == 1) { cell_count_for_ancestor_1++; } } TS_ASSERT_LESS_THAN_EQUALS(cell_count_for_ancestor_1, min_cell_count_for_ancestor[1]); } }; #endif // TESTOFFLATTICESIMULATIONWITHCELLCOUNTLIMIT_HPP
36.559908
102
0.659671
ThomasPak
b4d7a12efbbaada1e8d1842b602c2236557a9e63
4,304
cpp
C++
sources/middle_layer/dispatcher/hw_dispatcher.cpp
jinjunzh/DML
0c5103dce053fc75f007bc4761359b03cff0c1dc
[ "MIT" ]
null
null
null
sources/middle_layer/dispatcher/hw_dispatcher.cpp
jinjunzh/DML
0c5103dce053fc75f007bc4761359b03cff0c1dc
[ "MIT" ]
null
null
null
sources/middle_layer/dispatcher/hw_dispatcher.cpp
jinjunzh/DML
0c5103dce053fc75f007bc4761359b03cff0c1dc
[ "MIT" ]
null
null
null
/* * Copyright 2021 Intel Corporation. * * This software and the related documents are Intel copyrighted materials, * and your use of them is governed by the express license under which they * were provided to you ("License"). Unless the License provides otherwise, * you may not use, modify, copy, publish, distribute, disclose or transmit * this software or the related documents without Intel's prior written * permission. * * This software and the related documents are provided as is, with no * express or implied warranties, other than those that are expressly * stated in the License. * */ #include "hw_dispatcher.hpp" #ifdef LOG_HW_INIT #include <iostream> #endif #if defined(DML_HW) && defined(linux) #include "libaccel_config.h" #endif // TODO should be removed at all #define DML_HWSTS_RET(expr, err_code) { if( expr ) { return( err_code ); }} namespace dml::ml::dispatcher { hw_dispatcher::hw_dispatcher() noexcept { #ifdef DML_HW hw_init_status_ = hw_dispatcher::initialize_hw(); hw_support_ = hw_init_status_ == DML_STATUS_OK; #else hw_support_ = false; #endif } #ifdef DML_HW auto hw_dispatcher::initialize_hw() noexcept -> dsahw_status_t { accfg_ctx *ctx_ptr = nullptr; dsahw_status_t status = dsa_initialize_accelerator_driver(&hw_driver_); DML_HWSTS_RET(status != DML_STATUS_OK, status); int32_t context_creation_status = dsa_driver_new_context(&ctx_ptr); DML_HWSTS_RET(0u != context_creation_status, DML_STATUS_HARDWARE_CONNECTION_ERROR); // Retrieve first device in the system given the passed in context auto *dev_tmp_ptr = dsa_context_get_first_device(ctx_ptr); auto device_it = devices_.begin(); while (nullptr != dev_tmp_ptr) { if (DML_STATUS_OK == device_it->initialize_new_device(dev_tmp_ptr)) { device_it++; } // Retrieve the "next" device in the system based on given device dev_tmp_ptr = dsa_device_get_next(dev_tmp_ptr); } device_count_ = std::distance(devices_.begin(), device_it); if (device_count_ <= 0) { return DML_STATUS_HARDWARE_CONNECTION_ERROR; } #ifdef LOG_HW_INIT std::cout << "--------------------------------\n"; std::cout << "Number of discovered devices: " << device_count_ << "\n"; std::cout << "--------------------------------\n"; for (size_t i = 0; i < device_count_; i++) { std::cout << "Device #" << i << " : " << devices_[i].size() << " work queues\n"; } std::cout << "--------------------------------\n" << std::endl; #endif hw_context_.set_driver_context_ptr(ctx_ptr); return DML_STATUS_OK; } #endif hw_dispatcher::~hw_dispatcher() noexcept { #ifdef DML_HW // Variables auto *context_ptr = hw_context_.get_driver_context_ptr(); if (context_ptr != nullptr) { dsa_context_close(context_ptr); } dsa_finalize_accelerator_driver(&hw_driver_); // Zeroing values hw_context_.set_driver_context_ptr(nullptr); #endif } auto hw_dispatcher::get_instance() noexcept -> hw_dispatcher & { static hw_dispatcher instance{}; return instance; } auto hw_dispatcher::is_hw_support() const noexcept -> bool { return hw_support_; } #ifdef DML_HW void hw_dispatcher::fill_hw_context(dsahw_context_t *const hw_context_ptr) noexcept { #if defined(linux) // Restore context hw_context_ptr->dsa_context_ptr = hw_context_.get_driver_context_ptr(); // Restore device properties // We take the first one as all configurations across the platform should be the same for all devices devices_[0].fill_hw_context(hw_context_ptr); #endif } auto hw_dispatcher::get_hw_init_status() const noexcept -> dsahw_status_t { return hw_init_status_; } #ifdef DML_HW auto hw_dispatcher::begin() const noexcept -> device_container_t::const_iterator { return devices_.cbegin(); } auto hw_dispatcher::end() const noexcept -> device_container_t::const_iterator { return devices_.cbegin() + device_count_; } void hw_dispatcher::hw_context::set_driver_context_ptr(accfg_ctx *driver_context_ptr) noexcept { driver_context_ptr_ = driver_context_ptr; } [[nodiscard]] auto hw_dispatcher::hw_context::get_driver_context_ptr() noexcept -> accfg_ctx * { return driver_context_ptr_; } #endif #endif }
26.9
105
0.701208
jinjunzh
b4d921f31528318194bea3a8a82fea4b174ff952
12,241
cpp
C++
backend/applications/utilities/sheep-cl.cpp
vkurilin/SHEEP
2ccaef32c16efcf5dbc8eefd1dc243bed4ac2fbb
[ "MIT" ]
40
2018-12-03T13:01:06.000Z
2022-02-23T13:04:12.000Z
backend/applications/utilities/sheep-cl.cpp
vkurilin/SHEEP
2ccaef32c16efcf5dbc8eefd1dc243bed4ac2fbb
[ "MIT" ]
63
2018-09-11T14:13:31.000Z
2020-01-14T16:12:39.000Z
backend/applications/utilities/sheep-cl.cpp
vkurilin/SHEEP
2ccaef32c16efcf5dbc8eefd1dc243bed4ac2fbb
[ "MIT" ]
7
2019-07-10T14:48:31.000Z
2022-03-23T09:12:11.000Z
//////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /// This is the main executable that is used by the frontend to: /// 1) run a benchmark test on a specified circuit file /// ./benchmark <circuit_file> <context_name> <input_type> <inputs_file> /// [<params_file>] /// 2) print out the paramaters for a given context /// ./benchmark PARAMS <context_name> <input_type> [<params_file>] /// 3) print out the key and ciphertext sizes for a given context. /// ./benchmark SIZES <context_name> <input_type> [<params_file>] /// #include <stdio.h> #include <string.h> #include <fstream> #include <map> #include <memory> #include "context-clear.hpp" #ifdef HAVE_HElib #include "context-helib.hpp" #endif #ifdef HAVE_TFHE #include "context-tfhe.hpp" #endif #ifdef HAVE_SEAL #include "context-seal.hpp" #endif #ifdef HAVE_LP #include "context-lp.hpp" #endif using namespace SHEEP; typedef std::chrono::duration<double, std::micro> DurationT; template <typename PlaintextT> std::unique_ptr<BaseContext<PlaintextT>> make_context( std::string context_type, std::string context_params = "") { if (context_type == "Clear") { return std::make_unique<ContextClear<PlaintextT>>(); #ifdef HAVE_HElib } else if (context_type == "HElib_F2") { auto ctx = std::make_unique<ContextHElib_F2<PlaintextT>>(); if (context_params.length() > 0) ctx->read_params_from_file(context_params); return ctx; } else if (context_type == "HElib_Fp") { auto ctx = std::make_unique<ContextHElib_Fp<PlaintextT>>(); if (context_params.length() > 0) ctx->read_params_from_file(context_params); return ctx; #endif #ifdef HAVE_TFHE } else if (context_type == "TFHE") { auto ctx = std::make_unique<ContextTFHE<PlaintextT>>(); if (context_params.length() > 0) ctx->read_params_from_file(context_params); return ctx; #endif #ifdef HAVE_SEAL } else if (context_type == "SEAL") { auto ctx = std::make_unique<ContextSeal<PlaintextT>>(); if (context_params.length() > 0) ctx->read_params_from_file(context_params); return ctx; #endif #ifdef HAVE_LP } else if (context_type == "LP") { auto ctx = std::make_unique<ContextLP<PlaintextT>>(); if (context_params.length() > 0) ctx->read_params_from_file(context_params); return ctx; #endif } else { throw std::runtime_error("Unknown context requested"); } } template <typename T> std::map<std::string, T> read_inputs_file(std::string filename) { std::vector<T> inputs_list; std::map<std::string, T> inputs_map; std::ifstream inputstream(filename); if (inputstream.bad()) { std::cout << "Empty or non-existent input file" << std::endl; } /// loop over all lines in the input file std::string line; while (std::getline(inputstream, line)) { /// remove comments (lines starting with #) and empty lines int found = line.find_first_not_of(" \t"); if (found != std::string::npos) { if (line[found] == '#') continue; /// split up by whitespace std::string buffer; std::vector<std::string> tokens; std::stringstream ss(line); while (ss >> buffer) tokens.push_back(buffer); if (tokens.size() == 2) { /// assume we have param_name param_value std::string input_name = (std::string)(tokens[0]); long input_val_long = stol(tokens[1]); T input_val = (T)(input_val_long); inputs_map.insert({input_name, input_val}); inputs_list.push_back(input_val); } } } // end of loop over lines return inputs_map; } template <typename PlaintextT> bool check_correct(std::vector<std::vector<PlaintextT>> test_results, std::vector<std::vector<PlaintextT>> plaintext_results) { if (test_results.size() != plaintext_results.size()) throw std::runtime_error("outputs have different sizes"); if (test_results.size() == 0) throw std::runtime_error("zero length output"); bool all_correct = true; auto test_iter = test_results.begin(); auto plaintext_iter = plaintext_results.begin(); while (test_iter != test_results.end()) { all_correct &= (*test_iter == *plaintext_iter); test_iter++; plaintext_iter++; } return all_correct; } template <typename PlaintextT> void print_outputs(Circuit C, std::vector<std::vector<PlaintextT>> test_results, std::vector<std::vector<PlaintextT>> cleartext_results, DurationContainer& durations) { std::cout << std::endl << "===============" << std::endl; std::cout << "=== RESULTS ===" << std::endl << std::endl; std::cout << "== Processing times: ==" << std::endl; std::cout << "setup: " << durations.first[0].count() << std::endl; std::cout << "encryption: " << durations.first[1].count() << std::endl; std::cout << "circuit_evaluation: " << durations.first[2].count() << std::endl; std::cout << "decryption: " << durations.first[3].count() << std::endl; std::cout << std::endl; std::vector<Wire> circuit_outputs = C.get_outputs(); if (circuit_outputs.size() != test_results.size()) throw std::runtime_error("outputs have different sizes"); std::cout << "== Output values ==" << std::endl; auto test_iter = test_results.begin(); auto wire_iter = circuit_outputs.begin(); while (test_iter != test_results.end()) { std::cout << wire_iter->get_name() << ": " << std::endl; // TODO: fix the to_string to print the list! // std::to_string(*test_iter)<<std::endl; wire_iter++; test_iter++; } //// comparison with the same circuit+inputs evaluated in clear context std::cout << std::endl << "== Check against cleartext context ==" << std::endl; bool matches = check_correct<PlaintextT>(test_results, cleartext_results); if (matches) std::cout << "Cleartext check passed OK" << std::endl; else std::cout << "Cleartext check failed" << std::endl; std::cout << std::endl << "==== END RESULTS ===" << std::endl; } template <typename T> std::vector<std::vector<T>> match_inputs_to_circuit( Circuit C, std::map<std::string, T> inputs_map) { std::vector<std::vector<T>> ordered_inputs; for (auto input : C.get_inputs()) { if (inputs_map.find(input.get_name()) != inputs_map.end()) { ordered_inputs.push_back({inputs_map.find(input.get_name())->second}); } } return ordered_inputs; } template <typename PlaintextT> void param_print(std::string context_name, std::string parameter_file = "") { std::unique_ptr<BaseContext<PlaintextT>> test_ctx = make_context<PlaintextT>(context_name, parameter_file); std::cout << " made context for " << context_name << std::endl; test_ctx->print_parameters(); } template <typename PlaintextT> bool benchmark_run(std::string context_name, std::string parameter_file, Circuit C, std::string input_filename, EvaluationStrategy eval_strategy) { std::vector<DurationT> totalDurations; typedef std::chrono::duration<double, std::micro> microsecond; typedef std::chrono::high_resolution_clock high_res_clock; auto setup_start_time = high_res_clock::now(); std::map<std::string, DurationT> perGateDurations; DurationContainer durations = std::make_pair(totalDurations, perGateDurations); std::unique_ptr<BaseContext<PlaintextT>> test_ctx = make_context<PlaintextT>(context_name, parameter_file); std::cout << " === Made context " << context_name << std::endl; auto setup_end_time = high_res_clock::now(); durations.first.push_back(microsecond(setup_end_time - setup_start_time)); std::unique_ptr<BaseContext<PlaintextT>> clear_ctx = make_context<PlaintextT>("Clear"); // read in inputs from input_filename std::map<std::string, PlaintextT> inputs = read_inputs_file<PlaintextT>(input_filename); std::cout << " === Read inputs file - found " << inputs.size() << " values." << std::endl; std::vector<std::vector<PlaintextT>> ordered_inputs = match_inputs_to_circuit(C, inputs); std::cout << " === Matched inputs from file with circuit inputs" << std::endl; std::vector<std::vector<PlaintextT>> result_bench = test_ctx->eval_with_plaintexts(C, ordered_inputs, durations, eval_strategy); std::cout << " === Ran benchmark test. " << std::endl; test_ctx->print_parameters(); test_ctx->print_sizes(); std::vector<std::vector<PlaintextT>> result_clear = clear_ctx->eval_with_plaintexts(C, ordered_inputs); print_outputs(C, result_bench, result_clear, durations); return true; } int main(int argc, const char** argv) { if (argc < 3) { std::cout << "Usage: \n ./benchmark <circuit_file> <context_name> " "<input_type> <inputs_file> <eval_strategy> [<params_file>]" << std::endl; std::cout << "OR: \n ./benchmark PARAMS <context_name> <input_type> " "[<params_file>]" << std::endl; return 0; } if (strncmp(argv[1], "PARAMS", 5) == 0) { std::string context_name = argv[2]; std::string input_type = argv[3]; std::string param_file = ""; if (argc == 5) param_file = argv[4]; if (input_type == "bool") param_print<bool>(context_name, param_file); else if (input_type == "int8_t") param_print<int8_t>(context_name, param_file); else if (input_type == "uint8_t") param_print<uint8_t>(context_name, param_file); else if (input_type == "int16_t") param_print<int16_t>(context_name, param_file); else if (input_type == "uint16_t") param_print<uint16_t>(context_name, param_file); else if (input_type == "int32_t") param_print<int32_t>(context_name, param_file); else if (input_type == "uint32_t") param_print<uint32_t>(context_name, param_file); return 0; } /// read the circuit std::ifstream input_circuit(argv[1]); Circuit C; input_circuit >> C; std::cout << C; /// read the other input args std::string context_name = argv[2]; std::string input_type = argv[3]; std::string inputs_file = argv[4]; std::string eval_strategy_string = argv[5]; std::string parameter_file = ""; if (argc == 7) parameter_file = argv[6]; EvaluationStrategy eval_strategy; std::string eval_strategy_used; if (eval_strategy_string == "parallel") { eval_strategy = EvaluationStrategy::parallel; eval_strategy_used = "parallel"; } else { eval_strategy = EvaluationStrategy::serial; eval_strategy_used = "serial"; } std::cout << "====== Running benchmark test with: =======" << std::endl << "Circuit file: " << argv[1] << std::endl << "Context: " << context_name << std::endl << "Input type: " << input_type << std::endl << "Inputs_file " << inputs_file << std::endl << "Evaluation strategy: " << eval_strategy_used << std::endl << "Parameter file: " << parameter_file << std::endl; /// run the benchmark bool isOK = false; if (input_type == "bool") { isOK = benchmark_run<bool>(context_name, parameter_file, C, inputs_file, eval_strategy); } else if (input_type == "uint8_t") { isOK = benchmark_run<uint8_t>(context_name, parameter_file, C, inputs_file, eval_strategy); } else if (input_type == "int8_t") { isOK = benchmark_run<int8_t>(context_name, parameter_file, C, inputs_file, eval_strategy); } else if (input_type == "uint16_t") { isOK = benchmark_run<uint16_t>(context_name, parameter_file, C, inputs_file, eval_strategy); } else if (input_type == "int16_t") { isOK = benchmark_run<int16_t>(context_name, parameter_file, C, inputs_file, eval_strategy); } else if (input_type == "uint32_t") { isOK = benchmark_run<int32_t>(context_name, parameter_file, C, inputs_file, eval_strategy); } else if (input_type == "int32_t") { isOK = benchmark_run<int32_t>(context_name, parameter_file, C, inputs_file, eval_strategy); } return isOK; }
36.870482
81
0.642921
vkurilin
b4d9434d4fdd48b603a27783dfe62abcd8a8af45
5,273
cc
C++
tensorflow/core/util/util.cc
massimobernava/tensorflow
0a68ff9a205e14dd80fa0c51a0f6954d965f825e
[ "Apache-2.0" ]
1
2022-03-29T11:36:50.000Z
2022-03-29T11:36:50.000Z
tensorflow/core/util/util.cc
massimobernava/tensorflow
0a68ff9a205e14dd80fa0c51a0f6954d965f825e
[ "Apache-2.0" ]
1
2020-08-01T05:40:12.000Z
2020-08-01T05:40:12.000Z
tensorflow/core/util/util.cc
massimobernava/tensorflow
0a68ff9a205e14dd80fa0c51a0f6954d965f825e
[ "Apache-2.0" ]
null
null
null
/* Copyright 2015 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/core/util/util.h" #include <string> #include <vector> #include "absl/base/call_once.h" #include "tensorflow/core/framework/device_factory.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/cpu_info.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/util/env_var.h" namespace tensorflow { StringPiece NodeNamePrefix(const StringPiece& op_name) { StringPiece sp(op_name); auto p = sp.find('/'); if (p == StringPiece::npos || p == 0) { return ""; } else { return StringPiece(sp.data(), p); } } StringPiece NodeNameFullPrefix(const StringPiece& op_name) { StringPiece sp(op_name); auto p = sp.rfind('/'); if (p == StringPiece::npos || p == 0) { return ""; } else { return StringPiece(sp.data(), p); } } MovingAverage::MovingAverage(int window) : window_(window), sum_(0.0), data_(new double[window_]), head_(0), count_(0) { CHECK_GE(window, 1); } MovingAverage::~MovingAverage() { delete[] data_; } void MovingAverage::Clear() { count_ = 0; head_ = 0; sum_ = 0; } double MovingAverage::GetAverage() const { if (count_ == 0) { return 0; } else { return static_cast<double>(sum_) / count_; } } void MovingAverage::AddValue(double v) { if (count_ < window_) { // This is the warmup phase. We don't have a full window's worth of data. head_ = count_; data_[count_++] = v; } else { if (window_ == ++head_) { head_ = 0; } // Toss the oldest element sum_ -= data_[head_]; // Add the newest element data_[head_] = v; } sum_ += v; } static char hex_char[] = "0123456789abcdef"; string PrintMemory(const char* ptr, size_t n) { string ret; ret.resize(n * 3); for (int i = 0; i < n; ++i) { ret[i * 3] = ' '; ret[i * 3 + 1] = hex_char[ptr[i] >> 4]; ret[i * 3 + 2] = hex_char[ptr[i] & 0xf]; } return ret; } string SliceDebugString(const TensorShape& shape, const int64_t flat) { // Special case rank 0 and 1 const int dims = shape.dims(); if (dims == 0) return ""; if (dims == 1) return strings::StrCat("[", flat, "]"); // Compute strides gtl::InlinedVector<int64_t, 32> strides(dims); strides.back() = 1; for (int i = dims - 2; i >= 0; i--) { strides[i] = strides[i + 1] * shape.dim_size(i + 1); } // Unflatten index int64_t left = flat; string result; for (int i = 0; i < dims; i++) { strings::StrAppend(&result, i ? "," : "[", left / strides[i]); left %= strides[i]; } strings::StrAppend(&result, "]"); return result; } bool IsMKLEnabled() { #ifndef INTEL_MKL return false; #endif // !INTEL_MKL static absl::once_flag once; #ifdef ENABLE_MKL // Keeping TF_DISABLE_MKL env variable for legacy reasons. static bool oneDNN_disabled = false; absl::call_once(once, [&] { TF_CHECK_OK(ReadBoolFromEnvVar("TF_DISABLE_MKL", false, &oneDNN_disabled)); if (oneDNN_disabled) VLOG(2) << "TF-MKL: Disabling oneDNN"; }); return (!oneDNN_disabled); #else static bool oneDNN_enabled = false; absl::call_once(once, [&] { int64_t oneDNN_env = -1; auto status = ReadInt64FromEnvVar("TF_ENABLE_ONEDNN_OPTS", -1, &oneDNN_env); if (!status.ok() || oneDNN_env < -1 || 1 < oneDNN_env) { LOG(WARNING) << "TF_ENABLE_ONEDNN_OPTS is not set to either 0 (off), " << "1 (on), or -1 (default). Using default setting."; oneDNN_env = -1; } if (oneDNN_env == -1) { // Default setting: Turns oneDNN on for CPUs with neural network features. oneDNN_enabled = port::TestCPUFeature(port::CPUFeature::AVX512_VNNI) || port::TestCPUFeature(port::CPUFeature::AVX512_BF16) || port::TestCPUFeature(port::CPUFeature::AVX_VNNI) || port::TestCPUFeature(port::CPUFeature::AMX_TILE) || port::TestCPUFeature(port::CPUFeature::AMX_INT8) || port::TestCPUFeature(port::CPUFeature::AMX_BF16); } else if (oneDNN_env == 1) { oneDNN_enabled = true; } if (oneDNN_enabled) { LOG(INFO) << "oneDNN custom operations are on. " << "You may see slightly different numerical results due to " << "floating-point round-off errors from different computation " << "orders. To turn them off, set the environment variable " << "`TF_ENABLE_ONEDNN_OPTS=0`."; } }); return oneDNN_enabled; #endif // ENABLE_MKL } } // namespace tensorflow
29.623596
80
0.626019
massimobernava
b4db6998ace96669f00f870874526c7c12a44618
164
cpp
C++
GraphicsProject/main.cpp
JosephPena1/BootstrapPhysics
ce8d9ed1a7bcbc7160c37c41f9033eb68ba3acd6
[ "MIT" ]
null
null
null
GraphicsProject/main.cpp
JosephPena1/BootstrapPhysics
ce8d9ed1a7bcbc7160c37c41f9033eb68ba3acd6
[ "MIT" ]
null
null
null
GraphicsProject/main.cpp
JosephPena1/BootstrapPhysics
ce8d9ed1a7bcbc7160c37c41f9033eb68ba3acd6
[ "MIT" ]
null
null
null
#include "Application.h" int main() { Application* game = new Application(1280,720,"Graphics"); int exitCode = game->run(); delete game; return exitCode; }
12.615385
58
0.682927
JosephPena1
b4ddf5c63f0ac5b0157cee68dd6db431040e5d7b
2,621
cc
C++
elements/grid/lirmetric.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
129
2015-10-08T14:38:35.000Z
2022-03-06T14:54:44.000Z
elements/grid/lirmetric.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
241
2016-02-17T16:17:58.000Z
2022-03-15T09:08:33.000Z
elements/grid/lirmetric.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
61
2015-12-17T01:46:58.000Z
2022-02-07T22:25:19.000Z
/* * lirmetric.{cc,hh} -- end-to-end delivery ratio metric * * Copyright (c) 2003 Massachusetts Institute of Technology * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #include <click/args.hh> #include <click/error.hh> #include "elements/grid/lirmetric.hh" #include "elements/grid/linkstat.hh" #include "elements/grid/gridgenericrt.hh" CLICK_DECLS LIRMetric::LIRMetric() : _rt(0) { } LIRMetric::~LIRMetric() { } void * LIRMetric::cast(const char *n) { if (strcmp(n, "LIRMetric") == 0) return (LIRMetric *) this; else if (strcmp(n, "GridGenericMetric") == 0) return (GridGenericMetric *) this; else return 0; } int LIRMetric::configure(Vector<String> &conf, ErrorHandler *errh) { return Args(conf, this, errh) .read_mp("GRIDROUTES", ElementCastArg("GridGenericRouteTable"), _rt) .complete(); } bool LIRMetric::metric_val_lt(const metric_t &m1, const metric_t &m2) const { return m1.val() < m2.val(); } GridGenericMetric::metric_t LIRMetric::get_link_metric(const EtherAddress &, bool) const { // XXX number of nbrs of senders, or number of neighbors of // receivers. that is, for a an n+1 node route with n hops, do we // care about all n+1 nodes, or do we ignore the number of neighbors // of either the first or last node? return metric_t(_rt->get_number_direct_neigbors()); } GridGenericMetric::metric_t LIRMetric::append_metric(const metric_t &r, const metric_t &l) const { if (!r.good() || !l.good()) return _bad_metric; // every node must have at least one 1-hop neighbor, or it wouldn't // be part of the network! if (r.val() < 1) click_chatter("LIRMetric %s: append_metric WARNING: metric %u%% neighbors is too low for route metric", name().c_str(), r.val()); if (l.val() < 1) click_chatter("LIRMetric %s: append_metric WARNING: metric %u%% neighbors is too low for link metric", name().c_str(), r.val()); return metric_t(r.val() + l.val()); } ELEMENT_PROVIDES(GridGenericMetric) EXPORT_ELEMENT(LIRMetric) CLICK_ENDDECLS
28.48913
107
0.716139
MacWR
b4dfc211b6432a00e68ea5c188b80cdde97333b6
5,112
cpp
C++
deploy_test/road_finder_dlcrf/src/DlcrfCore.cpp
caolele/road-discovery
9f810dd9fe876369a86a3ba4897595579ad6d3c3
[ "MIT" ]
10
2018-06-04T20:59:11.000Z
2021-12-24T09:34:02.000Z
deploy_test/road_finder_dlcrf/src/DlcrfCore.cpp
caolele/road-discovery
9f810dd9fe876369a86a3ba4897595579ad6d3c3
[ "MIT" ]
1
2021-05-27T11:30:40.000Z
2021-05-27T11:30:40.000Z
deploy_test/road_finder_dlcrf/src/DlcrfCore.cpp
caolele/road-discovery
9f810dd9fe876369a86a3ba4897595579ad6d3c3
[ "MIT" ]
1
2021-09-01T12:05:10.000Z
2021-09-01T12:05:10.000Z
// // DlcrfCore.cpp // road-discovery: deploy_test // // Created by Larry Cao on 18/3/8. // #include "DlcrfCore.hpp" const UInt DlcrfCore::channels = 3; const float DlcrfCore::meanval_ch1 = 104.008; const float DlcrfCore::meanval_ch2 = 116.669; const float DlcrfCore::meanval_ch3 = 122.675; DlcrfCore::DlcrfCore(const string& model, const string& weights){ // Init. model net.reset(new Net<float>(model, TEST)); net->CopyTrainedLayersFrom(weights); inputLayer = net->input_blobs()[0]; batchSize = inputLayer->num(); dim = inputLayer->width(); // check if channels == 3 if(channels != inputLayer->channels()) throw "illegal number of channels"; // check if the input image is a square if(inputLayer->width() != inputLayer->height()) throw "illegal input size"; // get the total number of classes int upsampleLayerId = getBlobIndByName("upscore"); if(upsampleLayerId < 0) throw "illegal model definition"; boost::shared_ptr<Blob<float>> upsampleLayer = net->blobs()[upsampleLayerId]; cls = upsampleLayer->channels(); // initialize mean _mean = Mat(1, channels, CV_64F); _mean.row(0).col(0) = meanval_ch1; _mean.row(0).col(1) = meanval_ch2; _mean.row(0).col(2) = meanval_ch3; // batch wrap input layer inputLayer->Reshape(batchSize, channels, dim, dim); if(!wrapBatchInputLayer(&inputBatch)) throw "DlcrfCore wrap error"; } DlcrfCore::~DlcrfCore(){} UInt DlcrfCore::getDim(){ return dim; } UInt DlcrfCore::getBatchSize(){ return batchSize; } int DlcrfCore::getBlobIndByName(string blobName){ vector<string> const & blob_names = net->blob_names(); for(int i = 0; i < blob_names.size(); i++){ if(blobName == blob_names[i]) return i; } return -1; } bool DlcrfCore::wrapBatchInputLayer(vector<vector<Mat>> *_inputBatch){ // health check if(inputBatch.size() > 0) return false; float* input_data = inputLayer->mutable_cpu_data(); for(int j = 0; j < batchSize; j++){ vector<Mat> input_channels; for (int i = 0; i < channels; ++i){ Mat channel(dim, dim, CV_32FC1, input_data); input_channels.push_back(channel); input_data += dim * dim; } _inputBatch->push_back(vector<Mat>(input_channels)); } return true; } vector<Mat> DlcrfCore::predictBatch(const vector<Mat>& imgs, const UInt fs, const string mode){ vector<Mat> probimgs; // health check if(imgs.size() != batchSize || inputLayer == NULL || net->output_blobs().size() != 2 || cls < 2) return probimgs; // In GPU mode, InputLayer needs to be wrapped for every batch if(Caffe::mode() == Caffe::GPU){ inputBatch.clear(); if(!wrapBatchInputLayer(&inputBatch)) throw "DlcrfCore wrap error"; } // predict each image patch in a batch for(int i = 0; i < batchSize; i++){ // health check per image if(imgs[i].empty() || imgs[i].cols != dim || imgs[i].rows != dim) return probimgs; // filter operation Mat patch = imgs[i].clone(); if(fs > 0) bilateralFilter(imgs[i], patch, fs, fs*2, fs/2); // convert input to float Mat patchFloat; patch.convertTo(patchFloat, CV_32FC3); // subtract the means from sample value Mat patchFloatNorm; subtract(patchFloat, _mean, patchFloatNorm); // write data to input layer vector<Mat> *input_channels = &(inputBatch.at(i)); /* This operation will write the separate BGR planes directly to the * input layer of the network because it is wrapped by the cv::Mat * objects in input_channels. */ split(patchFloatNorm, *input_channels); if(i == 0){ // this check step may be dummy CHECK(reinterpret_cast<float*>(input_channels->at(0).data) == inputLayer->cpu_data()) << "Input channels are not wrapping the input layer"; } }//end of for // predict this batch net->ForwardFrom(0); // cast output values to probimgs const float* headPtrA = net->output_blobs()[0]->cpu_data(); const float* headPtrB = net->output_blobs()[1]->cpu_data(); Mat ctm; for(int i = 1; i < batchSize * cls; i += cls){ if(mode == "A"){ ctm = Mat(dim, dim, CV_32FC1, const_cast<float *>(headPtrA + i*dim*dim)); }else if(mode == "B"){ ctm = Mat(dim, dim, CV_32FC1, const_cast<float *>(headPtrB + i*dim*dim)); }else{ add(Mat(dim, dim, CV_32FC1, const_cast<float *>(headPtrA + i*dim*dim)), Mat(dim, dim, CV_32FC1, const_cast<float *>(headPtrB + i*dim*dim)), ctm); } probimgs.push_back(ctm); ctm.release(); } return probimgs; }
29.894737
81
0.581182
caolele
b4e0263378b26ddfa369ef18a1ebc80bdb59ba6a
6,328
hpp
C++
Lib/Chip/CM4/Freescale/MK21D5WS/RFVBAT.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
Lib/Chip/CM4/Freescale/MK21D5WS/RFVBAT.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
Lib/Chip/CM4/Freescale/MK21D5WS/RFVBAT.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
#pragma once #include <Register/Utility.hpp> namespace Kvasir { //VBAT register file namespace RfvbatReg0{ ///<VBAT register file register using Addr = Register::Address<0x4003e000,0x00000000,0x00000000,std::uint32_t>; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> ll{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> lh{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> hl{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::ReadWriteAccess,unsigned> hh{}; } namespace RfvbatReg1{ ///<VBAT register file register using Addr = Register::Address<0x4003e004,0x00000000,0x00000000,std::uint32_t>; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> ll{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> lh{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> hl{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::ReadWriteAccess,unsigned> hh{}; } namespace RfvbatReg2{ ///<VBAT register file register using Addr = Register::Address<0x4003e008,0x00000000,0x00000000,std::uint32_t>; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> ll{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> lh{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> hl{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::ReadWriteAccess,unsigned> hh{}; } namespace RfvbatReg3{ ///<VBAT register file register using Addr = Register::Address<0x4003e00c,0x00000000,0x00000000,std::uint32_t>; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> ll{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> lh{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> hl{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::ReadWriteAccess,unsigned> hh{}; } namespace RfvbatReg4{ ///<VBAT register file register using Addr = Register::Address<0x4003e010,0x00000000,0x00000000,std::uint32_t>; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> ll{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> lh{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> hl{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::ReadWriteAccess,unsigned> hh{}; } namespace RfvbatReg5{ ///<VBAT register file register using Addr = Register::Address<0x4003e014,0x00000000,0x00000000,std::uint32_t>; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> ll{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> lh{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> hl{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::ReadWriteAccess,unsigned> hh{}; } namespace RfvbatReg6{ ///<VBAT register file register using Addr = Register::Address<0x4003e018,0x00000000,0x00000000,std::uint32_t>; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> ll{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> lh{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> hl{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::ReadWriteAccess,unsigned> hh{}; } namespace RfvbatReg7{ ///<VBAT register file register using Addr = Register::Address<0x4003e01c,0x00000000,0x00000000,std::uint32_t>; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> ll{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> lh{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> hl{}; ///no description available constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::ReadWriteAccess,unsigned> hh{}; } }
67.319149
120
0.719659
operativeF
b4e0e92d35ddb386fcbe11133539c4c69aab2f81
1,037
hpp
C++
lib/lib/iterator.hpp
XzoRit/cpp_test_eq_op
32abe7949499fd81bd82aefccc6b4ccf550f0628
[ "BSL-1.0" ]
null
null
null
lib/lib/iterator.hpp
XzoRit/cpp_test_eq_op
32abe7949499fd81bd82aefccc6b4ccf550f0628
[ "BSL-1.0" ]
null
null
null
lib/lib/iterator.hpp
XzoRit/cpp_test_eq_op
32abe7949499fd81bd82aefccc6b4ccf550f0628
[ "BSL-1.0" ]
null
null
null
#pragma once #include <lib/tuple.hpp> #include <iterator> #include <utility> namespace xzr { namespace iterator { template <typename Container> class back_emplace_iterator : public std::iterator<std::output_iterator_tag, void, void, void, void> { public: using container_type = Container; explicit back_emplace_iterator(Container& c) : container{c} { } template <class Args> back_emplace_iterator& operator=(Args&& args) { xzr::tuple::emplace_back_from_tuple(container, std::forward<Args>(args)); return *this; } back_emplace_iterator& operator*() { return *this; } back_emplace_iterator& operator++() { return *this; } back_emplace_iterator operator++(int) { return *this; } private: Container& container; }; template <typename Container> inline back_emplace_iterator<Container> back_emplacer(Container& c) { return back_emplace_iterator<Container>{c}; } } // namespace iterator } // namespace xzr
18.517857
100
0.66731
XzoRit
b4e223452d6207add24ef4824e8b8ed3c12cb40b
12,212
hpp
C++
src/ArraySlice.hpp
GEOSX/LvArray
3ad0795f10023bd9a2fd8a41f0de0caa376845c0
[ "BSD-3-Clause" ]
16
2020-07-10T00:04:08.000Z
2022-03-28T03:59:51.000Z
src/ArraySlice.hpp
GEOSX/LvArray
3ad0795f10023bd9a2fd8a41f0de0caa376845c0
[ "BSD-3-Clause" ]
55
2020-06-30T06:26:49.000Z
2022-03-29T18:21:47.000Z
src/ArraySlice.hpp
GEOSX/LvArray
3ad0795f10023bd9a2fd8a41f0de0caa376845c0
[ "BSD-3-Clause" ]
5
2021-02-03T02:00:20.000Z
2022-03-21T20:37:51.000Z
/* * Copyright (c) 2021, Lawrence Livermore National Security, LLC and LvArray contributors. * All rights reserved. * See the LICENSE file for details. * SPDX-License-Identifier: (BSD-3-Clause) */ /** * @file ArraySlice.hpp * @brief Contains the implementation of LvArray::ArraySlice */ #pragma once #if !defined( NDEBUG ) && !defined( __APPLE__ ) && !defined( __ibmxl__ ) /** * @brief Add GDB pretty printers the given script. * @param script_name The python script that contains the gdb hooks. * @note Taken from https://sourceware.org/gdb/onlinedocs/gdb/dotdebug_005fgdb_005fscripts-section.html */ #define DEFINE_GDB_PY_SCRIPT( script_name ) \ asm (".pushsection \".debug_gdb_scripts\", \"MS\",@progbits,1\n \ .byte 1 /* Python */\n \ .asciz \"" script_name "\"\n \ .popsection \n" ); #else /** * @brief Add GDB pretty printers for OSX. This hasn't been done yet. * @param script_name The python script that contains the gdb hooks. */ #define DEFINE_GDB_PY_SCRIPT( script_name ) #endif /// Point GDB at the scripts/gdb-printers.py DEFINE_GDB_PY_SCRIPT( "scripts/gdb-printers.py" ) // Source includes #include "LvArrayConfig.hpp" #include "indexing.hpp" #include "Macros.hpp" // System includes #ifndef NDEBUG #include "totalview/tv_data_display.h" #include "totalview/tv_helpers.hpp" #endif #ifdef LVARRAY_BOUNDS_CHECK /** * @brief Check that @p index is a valid index into the first dimension. * @param index The index to check. * @note This is only active when LVARRAY_BOUNDS_CHECK is defined. */ #define ARRAY_SLICE_CHECK_BOUNDS( index ) \ LVARRAY_ERROR_IF( index < 0 || index >= m_dims[ 0 ], \ "Array Bounds Check Failed: index=" << index << " m_dims[0]=" << m_dims[0] ) #else // LVARRAY_BOUNDS_CHECK /** * @brief Check that @p index is a valid index into the first dimension. * @param index The index to check. * @note This is only active when LVARRAY_BOUNDS_CHECK is defined. */ #define ARRAY_SLICE_CHECK_BOUNDS( index ) #endif // LVARRAY_BOUNDS_CHECK namespace LvArray { /** * @class ArraySlice * @brief This class serves to provide a sliced multidimensional interface to the family of LvArray classes. * @tparam T type of data that is contained by the array * @tparam NDIM_TPARAM The number of dimensions in array (e.g. NDIM=1->vector, NDIM=2->Matrix, etc. ). * @tparam USD The dimension with a unit stride, in an Array with a standard layout * this is the last dimension. * @tparam INDEX_TYPE The integer to use for indexing the components of the array. * @brief This class serves as a sliced interface to an array. This is a lightweight class that contains * only pointers, and provides an operator[] to create a lower dimensionsal slice and an operator() * to access values given a multidimensional index. * In general, instantiations of ArraySlice should only result either taking a slice of an an Array or * an ArrayView via operator[] or from a direct creation via the toSlice/toSliceConst method. */ template< typename T, int NDIM_TPARAM, int USD_TPARAM, typename INDEX_TYPE > class ArraySlice { public: static_assert( USD_TPARAM < NDIM_TPARAM, "USD must be less than NDIM." ); /// The type of the value in the ArraySlice. using ValueType = T; /// The number of dimensions. static constexpr int NDIM = NDIM_TPARAM; /// The unit stride dimension. static constexpr int USD = USD_TPARAM; /// The integer type used for indexing. using IndexType = INDEX_TYPE; /** * @name Constructors, destructor and assignment operators. */ ///@{ /// deleted default constructor ArraySlice() = delete; /** * @brief Construct a new ArraySlice. * @param inputData pointer to the beginning of the data for this slice of the array * @param inputDimensions pointer to the beginning of the dimensions for this slice. * @param inputStrides pointer to the beginning of the strides for this slice */ LVARRAY_HOST_DEVICE inline explicit CONSTEXPR_WITHOUT_BOUNDS_CHECK ArraySlice( T * const LVARRAY_RESTRICT inputData, INDEX_TYPE const * const LVARRAY_RESTRICT inputDimensions, INDEX_TYPE const * const LVARRAY_RESTRICT inputStrides ) noexcept: m_data( inputData ), m_dims( inputDimensions ), m_strides( inputStrides ) { #if defined(LVARRAY_USE_TOTALVIEW_OUTPUT) && !defined(__CUDA_ARCH__) && defined(LVARRAY_BOUNDS_CHECK) ArraySlice::TV_ttf_display_type( nullptr ); #endif } ///@} /** * @name ArraySlice creation methods and user defined conversions */ ///@{ /** * @return Return a new immutable slice. */ LVARRAY_HOST_DEVICE inline constexpr ArraySlice< T const, NDIM, USD, INDEX_TYPE > toSliceConst() const noexcept { return ArraySlice< T const, NDIM, USD, INDEX_TYPE >( m_data, m_dims, m_strides ); } /** * @return Return a new immutable slice. */ template< typename U=T > LVARRAY_HOST_DEVICE inline constexpr operator std::enable_if_t< !std::is_const< U >::value, ArraySlice< T const, NDIM, USD, INDEX_TYPE > > () const noexcept { return toSliceConst(); } ///@} /** * @name Attribute querying methods */ ///@{ /** * @return Return the total size of the slice. */ LVARRAY_HOST_DEVICE inline constexpr INDEX_TYPE size() const noexcept { #if defined( __ibmxl__ ) // Note: This used to be done with a recursive template but XL-release would produce incorrect results. // Specifically in exampleArray it would return an "old" size even after being updated, strange. INDEX_TYPE val = m_dims[ 0 ]; for( int i = 1; i < NDIM; ++i ) { val *= m_dims[ i ]; } return val; #else return indexing::multiplyAll< NDIM >( m_dims ); #endif } /** * @return Return the length of the given dimension. * @param dim the dimension to get the length of. */ LVARRAY_HOST_DEVICE inline CONSTEXPR_WITHOUT_BOUNDS_CHECK INDEX_TYPE size( int const dim ) const noexcept { #ifdef LVARRAY_BOUNDS_CHECK LVARRAY_ERROR_IF_GE( dim, NDIM ); #endif return m_dims[ dim ]; } /** * @return Return the stride of the given dimension. * @param dim the dimension to get the stride of. */ LVARRAY_HOST_DEVICE inline CONSTEXPR_WITHOUT_BOUNDS_CHECK INDEX_TYPE stride( int const dim ) const noexcept { #ifdef LVARRAY_BOUNDS_CHECK LVARRAY_ERROR_IF_GE( dim, NDIM ); #endif return m_strides[ dim ]; } /** * @brief Check if the slice is contiguous in memory * @return @p true if represented slice is contiguous in memory */ LVARRAY_HOST_DEVICE inline constexpr bool isContiguous() const { if( USD < 0 ) return false; if( NDIM == 1 && USD == 0 ) return true; bool rval = true; for( int i = 0; i < NDIM; ++i ) { if( i == USD ) continue; INDEX_TYPE prod = 1; for( int j = 0; j < NDIM; ++j ) { if( j != i ) prod *= m_dims[j]; } rval &= (m_strides[i] <= prod); } return rval; } /** * @tparam INDICES A variadic pack of integral types. * @return Return the linear index from a multidimensional index. * @param indices The indices of the value to get the linear index of. */ template< typename ... INDICES > LVARRAY_HOST_DEVICE inline CONSTEXPR_WITHOUT_BOUNDS_CHECK INDEX_TYPE linearIndex( INDICES... indices ) const { static_assert( sizeof ... (INDICES) == NDIM, "number of indices does not match NDIM" ); #ifdef LVARRAY_BOUNDS_CHECK indexing::checkIndices( m_dims, indices ... ); #endif return indexing::getLinearIndex< USD >( m_strides, indices ... ); } ///@} /** * @name Methods that provide access to the data. */ ///@{ /** * @return A raw pointer. * @note This method is only active when NDIM == 1 and USD == 0. */ template< int NDIM_=NDIM, int USD_=USD > LVARRAY_HOST_DEVICE constexpr inline operator std::enable_if_t< NDIM_ == 1 && USD_ == 0, T * const LVARRAY_RESTRICT > () const noexcept { return m_data; } /** * @return Return a lower dimensionsal slice of this ArrayView. * @param index The index of the slice to create. * @note This method is only active when NDIM > 1. */ template< int U=NDIM > LVARRAY_HOST_DEVICE inline CONSTEXPR_WITHOUT_BOUNDS_CHECK std::enable_if_t< (U > 1), ArraySlice< T, NDIM - 1, USD - 1, INDEX_TYPE > > operator[]( INDEX_TYPE const index ) const noexcept { ARRAY_SLICE_CHECK_BOUNDS( index ); return ArraySlice< T, NDIM-1, USD-1, INDEX_TYPE >( m_data + indexing::ConditionalMultiply< USD == 0 >::multiply( index, m_strides[ 0 ] ), m_dims + 1, m_strides + 1 ); } /** * @return Return a reference to the value at the given index. * @param index The index of the value to access. * @note This method is only active when NDIM == 1. */ template< int U=NDIM > LVARRAY_HOST_DEVICE inline CONSTEXPR_WITHOUT_BOUNDS_CHECK std::enable_if_t< U == 1, T & > operator[]( INDEX_TYPE const index ) const noexcept { ARRAY_SLICE_CHECK_BOUNDS( index ); return m_data[ indexing::ConditionalMultiply< USD == 0 >::multiply( index, m_strides[ 0 ] ) ]; } /** * @tparam INDICES A variadic pack of integral types. * @return Return a reference to the value at the given multidimensional index. * @param indices The indices of the value to access. */ template< typename ... INDICES > LVARRAY_HOST_DEVICE inline constexpr T & operator()( INDICES... indices ) const { static_assert( sizeof ... (INDICES) == NDIM, "number of indices does not match NDIM" ); return m_data[ linearIndex( indices ... ) ]; } /** * @return Return a pointer to the values. * @tparam USD_ Dummy template parameter, do not specify. * @pre The slice must be contiguous. */ template< int USD_ = USD > LVARRAY_HOST_DEVICE inline T * dataIfContiguous() const { // Note: need both compile-time and runtime checks as USD >= 0 does not guarantee contiguous data. static_assert( USD_ >= 0, "Direct data access not supported for non-contiguous slices" ); LVARRAY_ERROR_IF( !isContiguous(), "Direct data access not supported for non-contiguous slices" ); return m_data; } /** * @return Return a pointer to the values. * @pre The slice must be contiguous. */ LVARRAY_HOST_DEVICE inline constexpr T * begin() const { return dataIfContiguous(); } /** * @return Return a pointer to the end values. * @pre The slice must be contiguous. */ LVARRAY_HOST_DEVICE inline constexpr T * end() const { return dataIfContiguous() + size(); } ///@} #if defined(LVARRAY_USE_TOTALVIEW_OUTPUT) && !defined(__CUDA_ARCH__) && defined(LVARRAY_BOUNDS_CHECK) /** * @brief Static function that will be used by Totalview to display the array contents. * @param av A pointer to the array that is being displayed. * @return 0 if everything went OK */ static int TV_ttf_display_type( ArraySlice const * av ) { if( av!=nullptr ) { int constexpr ndim = NDIM; //std::cout<<"Totalview using ("<<totalview::format<T,INDEX_TYPE>(NDIM, av->m_dims )<<") for display of // m_data;"<<std::endl; TV_ttf_add_row( "tv(m_data)", totalview::format< T, INDEX_TYPE >( NDIM, av->m_dims ).c_str(), (av->m_data) ); TV_ttf_add_row( "m_data", totalview::format< T, INDEX_TYPE >( 1, av->m_dims ).c_str(), (av->m_data) ); TV_ttf_add_row( "m_dims", totalview::format< INDEX_TYPE, int >( 1, &ndim ).c_str(), (av->m_dims) ); TV_ttf_add_row( "m_strides", totalview::format< INDEX_TYPE, int >( 1, &ndim ).c_str(), (av->m_strides) ); } return 0; } #endif protected: /// pointer to beginning of data for this array, or sub-array. T * const LVARRAY_RESTRICT m_data; /// pointer to array of length NDIM that contains the lengths of each array dimension INDEX_TYPE const * const LVARRAY_RESTRICT m_dims; /// pointer to array of length NDIM that contains the strides of each array dimension INDEX_TYPE const * const LVARRAY_RESTRICT m_strides; }; } // namespace LvArray
32.221636
141
0.674746
GEOSX
b4e2b4390f6b6396c9073c43a39b3ced7f504869
774
cc
C++
test/main.cc
asia-lab-sustech/ScaleSim
614869fe9ff2092e6c1f219cbcf44391118517d5
[ "MIT" ]
3
2019-06-26T15:11:26.000Z
2022-03-29T14:38:47.000Z
test/main.cc
asia-lab-sustech/ScaleSim
614869fe9ff2092e6c1f219cbcf44391118517d5
[ "MIT" ]
null
null
null
test/main.cc
asia-lab-sustech/ScaleSim
614869fe9ff2092e6c1f219cbcf44391118517d5
[ "MIT" ]
3
2019-05-02T12:21:25.000Z
2022-02-16T07:45:07.000Z
/* * main.cc * * Copyright (c) 2015 Masatoshi Hanai * * This software is released under MIT License. * See LICENSE. * */ #include "glog/logging.h" #include "gflags/gflags.h" #include "gtest/gtest.h" #include "leveldb/db.h" #include "leveldb/options.h" /* test files */ #include "medium/com_test.cc" #include "medium/db_via_lp_test.cc" #include "medium/gvt_test.cc" #include "medium/logical_process_test.cc" #include "small/db_test.cc" #include "small/io_test.cc" #include "small/thread_test.cc" #include "small/util_test.cc" int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); gflags::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(*argv); google::InstallFailureSignalHandler(); return RUN_ALL_TESTS(); }
22.114286
52
0.717054
asia-lab-sustech
b4e46e911df7ab00f710bf1f391e4aecbd1445c7
15,361
cpp
C++
src/vidhrdw/atarisy2.cpp
gameblabla/mame_nspire
83dfe1606aba906bd28608f2cb8f0754492ac3da
[ "Unlicense" ]
33
2015-08-10T11:13:47.000Z
2021-08-30T10:00:46.000Z
src/vidhrdw/atarisy2.cpp
gameblabla/mame_nspire
83dfe1606aba906bd28608f2cb8f0754492ac3da
[ "Unlicense" ]
13
2015-08-25T03:53:08.000Z
2022-03-30T18:02:35.000Z
src/vidhrdw/atarisy2.cpp
gameblabla/mame_nspire
83dfe1606aba906bd28608f2cb8f0754492ac3da
[ "Unlicense" ]
40
2015-08-25T05:09:21.000Z
2022-02-08T05:02:30.000Z
/*************************************************************************** Atari System 2 hardware ****************************************************************************/ #include "driver.h" #include "machine/atarigen.h" #include "vidhrdw/generic.h" #define XCHARS 64 #define YCHARS 48 #define XDIM (XCHARS*8) #define YDIM (YCHARS*8) /************************************* * * Constants * *************************************/ #define PFRAM_SIZE 0x4000 #define ANRAM_SIZE 0x1800 #define MORAM_SIZE 0x0800 /************************************* * * Structures * *************************************/ struct mo_data { struct osd_bitmap *bitmap; int xhold; }; struct pf_overrender_data { struct osd_bitmap *bitmap; int mo_priority; }; /************************************* * * Globals we own * *************************************/ UINT8 *atarisys2_slapstic; /************************************* * * Statics * *************************************/ static UINT8 *playfieldram; static UINT8 *alpharam; static UINT8 videobank; static struct atarigen_pf_state pf_state; static UINT16 latched_vscroll; /************************************* * * Prototypes * *************************************/ static void pf_render_callback(const struct rectangle *clip, const struct rectangle *tiles, const struct atarigen_pf_state *state, void *data); static void pf_check_overrender_callback(const struct rectangle *clip, const struct rectangle *tiles, const struct atarigen_pf_state *state, void *data); static void pf_overrender_callback(const struct rectangle *clip, const struct rectangle *tiles, const struct atarigen_pf_state *state, void *data); static void mo_render_callback(const UINT16 *data, const struct rectangle *clip, void *param); /************************************* * * Video system start * *************************************/ int atarisys2_vh_start(void) { static struct atarigen_mo_desc mo_desc = { 256, /* maximum number of MO's */ 8, /* number of bytes per MO entry */ 2, /* number of bytes between MO words */ 3, /* ignore an entry if this word == 0xffff */ 3, 3, 0xff, /* link = (data[linkword] >> linkshift) & linkmask */ 0 /* render in reverse link order */ }; static struct atarigen_pf_desc pf_desc = { 8, 8, /* width/height of each tile */ 128, 64 /* number of tiles in each direction */ }; /* allocate banked memory */ alpharam = (UINT8*)calloc(0x8000, 1); if (!alpharam) return 1; spriteram = alpharam + ANRAM_SIZE; playfieldram = alpharam + 0x4000; /* reset the videoram banking */ videoram = alpharam; videobank = 0; /* * if we are palette reducing, do the simple thing by marking everything used except for * the transparent sprite and alpha colors; this should give some leeway for machines * that can't give up all 256 colors */ if (palette_used_colors) { int i; memset(palette_used_colors, PALETTE_COLOR_USED, Machine->drv->total_colors * sizeof(UINT8)); for (i = 0; i < 4; i++) palette_used_colors[15 + i * 16] = PALETTE_COLOR_TRANSPARENT; for (i = 0; i < 8; i++) palette_used_colors[64 + i * 4] = PALETTE_COLOR_TRANSPARENT; } /* initialize the playfield */ if (atarigen_pf_init(&pf_desc)) { free(alpharam); return 1; } /* initialize the motion objects */ if (atarigen_mo_init(&mo_desc)) { atarigen_pf_free(); free(alpharam); return 1; } return 0; } /************************************* * * Video system shutdown * *************************************/ void atarisys2_vh_stop(void) { /* free memory */ if (alpharam) free(alpharam); alpharam = playfieldram = spriteram = 0; atarigen_pf_free(); atarigen_mo_free(); } /************************************* * * Scroll/playfield bank write * *************************************/ WRITE_HANDLER( atarisys2_hscroll_w ) { int oldword = READ_WORD(&atarigen_hscroll[offset]); int newword = COMBINE_WORD(oldword, data); WRITE_WORD(&atarigen_hscroll[offset], newword); /* update the playfield parameters - hscroll is clocked on the following scanline */ pf_state.hscroll = (newword >> 6) & 0x03ff; pf_state.param[0] = newword & 0x000f; atarigen_pf_update(&pf_state, cpu_getscanline() + 1); /* mark the playfield dirty for those games that handle it */ if (oldword != newword && (Machine->drv->video_attributes & VIDEO_SUPPORTS_DIRTY)) osd_mark_dirty(Machine->visible_area.min_x, Machine->visible_area.min_y, Machine->visible_area.max_x, Machine->visible_area.max_y, 0); } WRITE_HANDLER( atarisys2_vscroll_w ) { int oldword = READ_WORD(&atarigen_vscroll[offset]); int newword = COMBINE_WORD(oldword, data); WRITE_WORD(&atarigen_vscroll[offset], newword); /* if bit 4 is zero, the scroll value is clocked in right away */ latched_vscroll = (newword >> 6) & 0x01ff; if (!(newword & 0x10)) pf_state.vscroll = latched_vscroll; /* update the playfield parameters */ pf_state.param[1] = newword & 0x000f; atarigen_pf_update(&pf_state, cpu_getscanline() + 1); /* mark the playfield dirty for those games that handle it */ if (oldword != newword && (Machine->drv->video_attributes & VIDEO_SUPPORTS_DIRTY)) osd_mark_dirty(Machine->visible_area.min_x, Machine->visible_area.min_y, Machine->visible_area.max_x, Machine->visible_area.max_y, 0); } /************************************* * * Palette RAM write handler * *************************************/ WRITE_HANDLER( atarisys2_paletteram_w ) { static const int intensity_table[16] = { #define ZB 115 #define Z3 78 #define Z2 37 #define Z1 17 #define Z0 9 0, ZB+Z0, ZB+Z1, ZB+Z1+Z0, ZB+Z2, ZB+Z2+Z0, ZB+Z2+Z1, ZB+Z2+Z1+Z0, ZB+Z3, ZB+Z3+Z0, ZB+Z3+Z1, ZB+Z3+Z1+Z0,ZB+ Z3+Z2, ZB+Z3+Z2+Z0, ZB+Z3+Z2+Z1, ZB+Z3+Z2+Z1+Z0 }; static const int color_table[16] = { 0x0, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xe, 0xf, 0xf }; int inten, red, green, blue; int oldword = READ_WORD(&paletteram[offset]); int newword = COMBINE_WORD(oldword, data); int indx = offset / 2; WRITE_WORD(&paletteram[offset], newword); inten = intensity_table[newword & 15]; red = (color_table[(newword >> 12) & 15] * inten) >> 4; green = (color_table[(newword >> 8) & 15] * inten) >> 4; blue = (color_table[(newword >> 4) & 15] * inten) >> 4; palette_change_color(indx, red, green, blue); } /************************************* * * Video RAM bank read/write handlers * *************************************/ READ_HANDLER( atarisys2_slapstic_r ) { slapstic_tweak(offset / 2); /* an extra tweak for the next opcode fetch */ videobank = slapstic_tweak(0x1234); videoram = alpharam + videobank * 0x2000; return READ_WORD(&atarisys2_slapstic[offset]); } WRITE_HANDLER( atarisys2_slapstic_w ) { slapstic_tweak(offset / 2); /* an extra tweak for the next opcode fetch */ videobank = slapstic_tweak(0x1234); videoram = alpharam + videobank * 0x2000; } /************************************* * * Video RAM read/write handlers * *************************************/ READ_HANDLER( atarisys2_videoram_r ) { return READ_WORD(&videoram[offset]); } WRITE_HANDLER( atarisys2_videoram_w ) { int oldword = READ_WORD(&videoram[offset]); int newword = COMBINE_WORD(oldword, data); WRITE_WORD(&videoram[offset], newword); /* mark the playfield dirty if we write to it */ if (videobank >= 2) if ((oldword & 0x3fff) != (newword & 0x3fff)) { int offs = (&videoram[offset] - playfieldram) / 2; atarigen_pf_dirty[offs] = 0xff; } /* force an update if the link of object 0 changes */ if (videobank == 0 && offset == 0x1806) atarigen_mo_update(spriteram, 0, cpu_getscanline() + 1); } /************************************* * * Periodic scanline updater * *************************************/ void atarisys2_scanline_update(int scanline) { /* update the playfield */ if (scanline == 0) { pf_state.vscroll = latched_vscroll; atarigen_pf_update(&pf_state, scanline); } /* update the motion objects */ if (scanline < YDIM) atarigen_mo_update(spriteram, 0, scanline); } /************************************* * * Main refresh * *************************************/ void atarisys2_vh_screenrefresh(struct osd_bitmap *bitmap, int full_refresh) { struct mo_data modata; int i; /* recalc the palette if necessary */ if (palette_recalc()) memset(atarigen_pf_dirty, 0xff, PFRAM_SIZE / 2); /* set up the all-transparent overrender palette */ for (i = 0; i < 16; i++) atarigen_overrender_colortable[i] = palette_transparent_pen; /* render the playfield */ atarigen_pf_process(pf_render_callback, bitmap, &Machine->visible_area); /* render the motion objects */ modata.xhold = 0; modata.bitmap = bitmap; atarigen_mo_process(mo_render_callback, &modata); /* render the alpha layer */ { const struct GfxElement *gfx = Machine->gfx[2]; int sx, sy, offs; for (sy = 0; sy < YCHARS; sy++) for (sx = 0, offs = sy * 64; sx < XCHARS; sx++, offs++) { int data = READ_WORD(&alpharam[offs * 2]); int code = data & 0x3ff; /* if there's a non-zero code, draw the tile */ if (code) { int color = (data >> 13) & 7; /* draw the character */ drawgfx(bitmap, gfx, code, color, 0, 0, 8 * sx, 8 * sy, 0, TRANSPARENCY_PEN, 0); } } } /* update onscreen messages */ atarigen_update_messages(); } /************************************* * * Playfield rendering * *************************************/ static void pf_render_callback(const struct rectangle *clip, const struct rectangle *tiles, const struct atarigen_pf_state *state, void *param) { const struct GfxElement *gfx = Machine->gfx[0]; struct osd_bitmap *bitmap = (struct osd_bitmap *)param; int x, y; /* standard loop over tiles */ for (y = tiles->min_y; y != tiles->max_y; y = (y + 1) & 63) for (x = tiles->min_x; x != tiles->max_x; x = (x + 1) & 127) { int offs = y * 128 + x; int data = READ_WORD(&playfieldram[offs * 2]); int pfbank = state->param[(data >> 10) & 1]; /* update only if dirty */ if (atarigen_pf_dirty[offs] != pfbank) { int code = (pfbank << 10) + (data & 0x3ff); int color = (data >> 11) & 7; drawgfx(atarigen_pf_bitmap, gfx, code, color, 0, 0, 8 * x, 8 * y, 0, TRANSPARENCY_NONE, 0); atarigen_pf_dirty[offs] = pfbank; } } /* then blast the result */ x = -state->hscroll; y = -state->vscroll; copyscrollbitmap(bitmap, atarigen_pf_bitmap, 1, &x, 1, &y, clip, TRANSPARENCY_NONE, 0); } /************************************* * * Playfield overrender check * *************************************/ static void pf_check_overrender_callback(const struct rectangle *clip, const struct rectangle *tiles, const struct atarigen_pf_state *state, void *param) { struct pf_overrender_data *overrender_data = (struct pf_overrender_data *)param; const struct GfxElement *gfx = Machine->gfx[0]; int mo_priority = overrender_data->mo_priority; int x, y; /* if we've already decided, bail */ if (mo_priority == -1) return; /* standard loop over tiles */ for (y = tiles->min_y; y != tiles->max_y; y = (y + 1) & 63) for (x = tiles->min_x; x != tiles->max_x; x = (x + 1) & 127) { int offs = y * 128 + x; int data = READ_WORD(&playfieldram[offs * 2]); int pf_priority = ((~data >> 13) & 6) | 1; if ((mo_priority + pf_priority) & 4) { int pfbank = state->param[(data >> 10) & 1]; int code = (pfbank << 10) + (data & 0x3ff); if (gfx->pen_usage[code] & 0xff00) { overrender_data->mo_priority = -1; return; } } } } /************************************* * * Playfield overrendering * *************************************/ static void pf_overrender_callback(const struct rectangle *clip, const struct rectangle *tiles, const struct atarigen_pf_state *state, void *param) { const struct pf_overrender_data *overrender_data = (const struct pf_overrender_data *)param; const struct GfxElement *gfx = Machine->gfx[0]; struct osd_bitmap *bitmap = overrender_data->bitmap; int mo_priority = overrender_data->mo_priority; int x, y; /* standard loop over tiles */ for (y = tiles->min_y; y != tiles->max_y; y = (y + 1) & 63) { int sy = (8 * y - state->vscroll) & 0x1ff; if (sy >= YDIM) sy -= 0x200; for (x = tiles->min_x; x != tiles->max_x; x = (x + 1) & 127) { int offs = y * 128 + x; int data = READ_WORD(&playfieldram[offs * 2]); int pf_priority = ((~data >> 13) & 6) | 1; if ((mo_priority + pf_priority) & 4) { int pfbank = state->param[(data >> 10) & 1]; int code = (pfbank << 10) + (data & 0x3ff); int color = (data >> 11) & 7; int sx = (8 * x - state->hscroll) & 0x1ff; if (sx >= XDIM) sx -= 0x400; drawgfx(bitmap, gfx, code, color, 0, 0, sx, sy, clip, TRANSPARENCY_PENS, 0x00ff); } } } } /************************************* * * Motion object rendering * *************************************/ static void mo_render_callback(const UINT16 *data, const struct rectangle *clip, void *param) { struct GfxElement *gfx = Machine->gfx[1]; struct mo_data *modata = (struct mo_data *)param; struct osd_bitmap *bitmap = modata->bitmap; struct pf_overrender_data overrender_data; struct rectangle pf_clip; /* extract data from the various words */ int ypos = -(data[0] >> 6); int hold = data[1] & 0x8000; int hflip = data[1] & 0x4000; int vsize = ((data[1] >> 11) & 7) + 1; int code = (data[1] & 0x7ff) + ((data[0] & 7) << 11); int xpos = (data[2] >> 6); int color = (data[3] >> 12) & 3; int priority = (data[3] >> 13) & 6; /* adjust for height */ ypos -= vsize * 16; /* adjust x position for holding */ if (hold) xpos = modata->xhold; modata->xhold = xpos + 16; /* adjust the final coordinates */ xpos &= 0x3ff; ypos &= 0x1ff; if (xpos >= XDIM) xpos -= 0x400; if (ypos >= YDIM) ypos -= 0x200; /* clip the X coordinate */ if (xpos <= -16 || xpos >= XDIM) return; /* determine the bounding box */ atarigen_mo_compute_clip_16x16(pf_clip, xpos, ypos, 1, vsize, clip); /* determine if we need to overrender */ overrender_data.mo_priority = priority; atarigen_pf_process(pf_check_overrender_callback, &overrender_data, &pf_clip); /* if not, do it simply */ if (overrender_data.mo_priority == priority) { atarigen_mo_draw_16x16_strip(bitmap, gfx, code, color, hflip, 0, xpos, ypos, vsize, clip, TRANSPARENCY_PEN, 15); } /* otherwise, make it tricky */ else { /* draw an instance of the object in all transparent pens */ atarigen_mo_draw_transparent_16x16_strip(bitmap, gfx, code, hflip, 0, xpos, ypos, vsize, clip, TRANSPARENCY_PEN, 15); /* and then draw it normally on the temp bitmap */ atarigen_mo_draw_16x16_strip(atarigen_pf_overrender_bitmap, gfx, code, color, hflip, 0, xpos, ypos, vsize, clip, TRANSPARENCY_NONE, 0); /* overrender the playfield on top of that that */ overrender_data.mo_priority = priority; overrender_data.bitmap = atarigen_pf_overrender_bitmap; atarigen_pf_process(pf_overrender_callback, &overrender_data, &pf_clip); /* finally, copy this chunk to the real bitmap */ copybitmap(bitmap, atarigen_pf_overrender_bitmap, 0, 0, 0, 0, &pf_clip, TRANSPARENCY_THROUGH, palette_transparent_pen); } }
25.601667
153
0.605429
gameblabla
b4e6a57cffeb9caa6d6bb1b159a47c73eb4e7afe
535
hpp
C++
interp/InterpMakedata.hpp
cjang/chai
7faba752cc4491d1b30590abef21edc4efffa0f6
[ "Unlicense" ]
11
2015-06-12T19:54:14.000Z
2021-11-26T10:45:18.000Z
interp/InterpMakedata.hpp
cjang/chai
7faba752cc4491d1b30590abef21edc4efffa0f6
[ "Unlicense" ]
null
null
null
interp/InterpMakedata.hpp
cjang/chai
7faba752cc4491d1b30590abef21edc4efffa0f6
[ "Unlicense" ]
null
null
null
// Copyright 2011 Chris Jang (fastkor@gmail.com) under The Artistic License 2.0 #ifndef _CHAI_INTERP_MAKEDATA_HPP_ #define _CHAI_INTERP_MAKEDATA_HPP_ #include "BaseInterp.hpp" namespace chai_internal { //////////////////////////////////////// // make1_u32, make1_i64 // make1_f32, make1_f64 // make2_u32, make2_i64 // make2_f32, make2_f64 class InterpMakedata : public BaseInterp { protected: void sub_eval(std::stack< std::vector< FrontMem* > >&); public: InterpMakedata(void); }; }; // namespace chai_internal #endif
19.107143
79
0.695327
cjang
b4ed3adfd1126b7428ed5e56ddcae59232575366
22,991
cpp
C++
src/transaction.cpp
AlphaX-Projects/swippcore-2.1.7
4e1aee2154999ec896a3d3db9f117cd33b29a748
[ "MIT" ]
8
2017-12-31T13:41:49.000Z
2022-01-23T07:31:25.000Z
src/transaction.cpp
AlphaX-Projects/swippcore-2.1.7
4e1aee2154999ec896a3d3db9f117cd33b29a748
[ "MIT" ]
16
2017-11-19T22:57:50.000Z
2019-01-21T01:20:07.000Z
src/transaction.cpp
AlphaX-Projects/swippcore-2.1.7
4e1aee2154999ec896a3d3db9f117cd33b29a748
[ "MIT" ]
11
2018-01-07T13:55:23.000Z
2020-06-17T18:44:31.000Z
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2017-2018 The Swipp developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "constraints.h" #include "main.h" #include "sync.h" #include "transaction.h" #include "txdb-leveldb.h" #include "txdb.h" int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; int64_t nResult = 0; for (unsigned int i = 0; i < vin.size(); i++) { nResult += GetOutputFor(vin[i], inputs).nValue; } return nResult; } int64_t CTransaction::GetValueOut() const { int64_t nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { nValueOut += txout.nValue; if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut)) throw std::runtime_error("CTransaction::GetValueOut() : value out of range"); } return nValueOut; } bool CTransaction::ReadFromDisk(CDiskTxPos pos, FILE** pfileRet) { CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION); if (!filein) return error("CTransaction::ReadFromDisk() : OpenBlockFile failed"); // Read transaction if (fseek(filein, pos.nTxPos, SEEK_SET) != 0) return error("CTransaction::ReadFromDisk() : fseek failed"); try { filein >> *this; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Return file pointer if (pfileRet) { if (fseek(filein, pos.nTxPos, SEEK_SET) != 0) return error("CTransaction::ReadFromDisk() : second fseek failed"); *pfileRet = filein.release(); } return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet) { SetNull(); if (!txdb.ReadTxIndex(prevout.hash, txindexRet)) return false; if (!ReadFromDisk(txindexRet.pos)) return false; if (prevout.n >= vout.size()) { SetNull(); return false; } return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout) { CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::ReadFromDisk(COutPoint prevout) { CTxDB txdb("r"); CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::DisconnectInputs(CTxDB& txdb) { // Relinquish previous transactions' spent pointers if (!IsCoinBase()) { BOOST_FOREACH(const CTxIn& txin, vin) { COutPoint prevout = txin.prevout; // Get prev txindex from disk CTxIndex txindex; if (!txdb.ReadTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : ReadTxIndex failed"); if (prevout.n >= txindex.vSpent.size()) return error("DisconnectInputs() : prevout.n out of range"); // Mark outpoint as not spent txindex.vSpent[prevout.n].SetNull(); // Write back if (!txdb.UpdateTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : UpdateTxIndex failed"); } } // Remove transaction from index // This can fail if a duplicate of this transaction was in a chain that got // reorganized away. This is only possible if this transaction was completely // spent, so erasing it would be a no-op anyway. txdb.EraseTxIndex(*this); return true; } bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid) { // FetchInputs can return false either because we just haven't seen some inputs // (in which case the transaction should be stored as an orphan) // or because the transaction is malformed (in which case the transaction should // be dropped). If tx is definitely invalid, fInvalid will be set to true. fInvalid = false; if (IsCoinBase()) return true; // Coinbase transactions have no inputs to fetch. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; if (inputsRet.count(prevout.hash)) continue; // Got it already // Read txindex CTxIndex& txindex = inputsRet[prevout.hash].first; bool fFound = true; if ((fBlock || fMiner) && mapTestPool.count(prevout.hash)) txindex = mapTestPool.find(prevout.hash)->second; else fFound = txdb.ReadTxIndex(prevout.hash, txindex); if (!fFound && (fBlock || fMiner)) return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString(), prevout.hash.ToString()); CTransaction& txPrev = inputsRet[prevout.hash].second; // Read txPrev if (!fFound || txindex.pos == CDiskTxPos(1,1,1)) { // Get prev tx from single transactions in memory if (!mempool.lookup(prevout.hash, txPrev)) return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString(), prevout.hash.ToString()); if (!fFound) txindex.vSpent.resize(txPrev.vout.size()); } else if (!txPrev.ReadFromDisk(txindex.pos)) return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString(), prevout.hash.ToString()); } // Make sure all prevout.n indexes are valid: for (unsigned int i = 0; i < vin.size(); i++) { const COutPoint prevout = vin[i].prevout; assert(inputsRet.count(prevout.hash) != 0); const CTxIndex& txindex = inputsRet[prevout.hash].first; const CTransaction& txPrev = inputsRet[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) { // Revisit this if/when transaction replacement is implemented and allows // adding inputs: fInvalid = true; return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %u %u prev tx %s\n%s", GetHash().ToString(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString(), txPrev.ToString())); } } return true; } bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, unsigned int flags, bool fValidateSig) { // Take over previous transactions' spent pointers // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain // fMiner is true when called from the internal bitcoin miner // ... both are false when called from CTransaction::AcceptToMemoryPool if (!IsCoinBase()) { int64_t nValueIn = 0; int64_t nFees = 0; for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) { return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %u %u prev tx %s\n%s", GetHash().ToString(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString(), txPrev.ToString())); } // If prev is coinbase or coinstake, check that it's matured if (txPrev.IsCoinBase() || txPrev.IsCoinStake()) { for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev) { if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile) { return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight); } } } // ppcoin: check transaction timestamp if (txPrev.nTime > nTime) return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction")); // Check for negative or overflow input values nValueIn += txPrev.vout[prevout.n].nValue; if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return DoS(100, error("ConnectInputs() : txin values out of range")); } // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; // Check for conflicts (double-spend) // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!txindex.vSpent[prevout.n].IsNull()) { return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString(), txindex.vSpent[prevout.n].ToString()); } if (fValidateSig) { // Skip ECDSA signature verification when connecting blocks (fBlock=true) // before the last blockchain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate()))) { // Verify signature if (!VerifySignature(txPrev, *this, i, flags, 0)) { if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) { // Check whether the failure was caused by a // non-mandatory script verification check, such as // non-null dummy arguments; // if so, don't trigger DoS protection to // avoid splitting the network between upgraded and // non-upgraded nodes. if (VerifySignature(txPrev, *this, i, flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, 0)) return error("ConnectInputs() : %s non-mandatory VerifySignature failed", GetHash().ToString()); } // Failures of other flags indicate a transaction that is // invalid in new blocks, e.g. a invalid P2SH. We DoS ban // such nodes as they are not following the protocol. That // said during an upgrade careful thought should be taken // as to the correct behavior - we may want to continue // peering with non-upgraded nodes even after a soft-fork // super-majority vote has passed. return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString())); } } } // Mark outpoints as spent txindex.vSpent[prevout.n] = posThisTx; // Write back if (fBlock || fMiner) mapTestPool[prevout.hash] = txindex; } if (!IsCoinStake()) { if (nValueIn < GetValueOut()) return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString())); // Tally transaction fees int64_t nTxFee = nValueIn - GetValueOut(); if (nTxFee < 0) return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString())); // enforce transaction fees for every block int64_t nRequiredFee = GetMinFee(*this); if (nTxFee < nRequiredFee) { return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString(), FormatMoney(nRequiredFee), FormatMoney(nTxFee))) : false; } nFees += nTxFee; if (!MoneyRange(nFees)) return DoS(100, error("ConnectInputs() : nFees out of range")); } } return true; } bool CTransaction::CheckTransaction() const { // Basic checks that don't depend on any context if (vin.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vin empty")); if (vout.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vout empty")); if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CTransaction::CheckTransaction() : size limits failed")); // Check for negative or overflow output values int64_t nValueOut = 0; for (unsigned int i = 0; i < vout.size(); i++) { const CTxOut& txout = vout[i]; if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake()) return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction")); if (txout.nValue < 0) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative")); if (txout.nValue > 5000000 * COIN) // TODO: Protocol check ?? return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high")); nValueOut += txout.nValue; if (!MoneyRange(nValueOut)) return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range")); } // Check for duplicate inputs set<COutPoint> vInOutPoints; BOOST_FOREACH(const CTxIn& txin, vin) { if (vInOutPoints.count(txin.prevout)) return false; vInOutPoints.insert(txin.prevout); } if (IsCoinBase()) { if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100) return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid")); } else { BOOST_FOREACH(const CTxIn& txin, vin) if (txin.prevout.IsNull()) return DoS(10, error("CTransaction::CheckTransaction() : prevout is null")); } return true; } // ppcoin: total coin age spent in transaction, in the unit of coin-days. // Only those coins meeting minimum age requirement counts. As those // transactions not in main chain are not currently indexed so we // might not find out about their coin age. Older transactions are // guaranteed to be in main chain by sync-checkpoint. This rule is // introduced to help nodes establish a consistent view of the coin // age (trust score) of competing branches. bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const { CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds nCoinAge = 0; if (IsCoinBase()) return true; BOOST_FOREACH(const CTxIn& txin, vin) { // First try finding the previous transaction in database CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) continue; // Previous transaction not in main chain if (nTime < txPrev.nTime) return false; // Transaction timestamp violation // Read block header CBlock block; if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) return false; // Unable to read block of previous transaction if (block.GetBlockTime() + nStakeMinAge > nTime) continue; // Only count coins meeting min age requirement int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue; bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT; LogPrint("coinage", "coin age nValueIn=%d nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString()); } CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60); LogPrint("coinage", "coin age bnCoinDay=%s\n", bnCoinDay.ToString()); nCoinAge = bnCoinDay.getuint64(); return true; } const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const { MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash); if (mi == inputs.end()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found"); const CTransaction& txPrev = (mi->second).second; if (input.prevout.n >= txPrev.vout.size()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range"); return txPrev.vout[input.prevout.n]; } // Return transaction in tx. If it was found inside a block, its hash is placed in hashBlock bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock) { { LOCK(cs_main); { if (mempool.lookup(hash, tx)) return true; } CTxDB txdb("r"); CTxIndex txindex; if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex)) { CBlock block; if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) hashBlock = block.GetHash(); return true; } } return false; } bool IsStandardTx(const CTransaction& tx, string& reason) { if (tx.nVersion > CTransaction::CURRENT_VERSION) { reason = "version"; return false; } // Treat non-final transactions as non-standard to prevent a specific type // of double-spend attack, as well as DoS attacks. (if the transaction // can't be mined, the attacker isn't expending resources broadcasting it) // Basically we don't want to propagate transactions that can't be included in // the next block. // // However, IsFinalTx() is confusing... Without arguments, it uses // chainActive.Height() to evaluate nLockTime; when a block is accepted, chainActive.Height() // is set to the value of nHeight in the block. However, when IsFinalTx() // is called within CBlock::AcceptBlock(), the height of the block *being* // evaluated is what is used. Thus if we want to know if a transaction can // be part of the *next* block, we need to call IsFinalTx() with one more // than chainActive.Height(). // // Timestamps on the other hand don't get any special treatment, because we // can't know what timestamp the next block will have, and there aren't // timestamp applications where it matters. if (!IsFinalTx(tx, nBestHeight + 1)) { reason = "non-final"; return false; } // nTime has different purpose from nLockTime but can be used in similar attacks if (tx.nTime > FutureDrift(GetAdjustedTime(), nBestHeight + 1)) { reason = "time-too-new"; return false; } // Extremely large transactions with lots of inputs can cost the network // almost as much to process as they cost the sender in fees, because // computing signature hashes is O(ninputs*txsize). Limiting transactions // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks. unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION); if (sz >= MAX_STANDARD_TX_SIZE) { reason = "tx-size"; return false; } BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed // keys. (remember the 520 byte limit on redeemScript size) That works // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627 // bytes of scriptSig, which we round off to 1650 bytes for some minor // future-proofing. That's also enough to spend a 20-of-20 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not // considered standard) if (txin.scriptSig.size() > 1650) { reason = "scriptsig-size"; return false; } if (!txin.scriptSig.IsPushOnly()) { reason = "scriptsig-not-pushonly"; return false; } if (!txin.scriptSig.HasCanonicalPushes()) { reason = "scriptsig-non-canonical-push"; return false; } } unsigned int nDataOut = 0; txnouttype whichType; BOOST_FOREACH(const CTxOut& txout, tx.vout) { if (!::IsStandard(txout.scriptPubKey, whichType)) { reason = "scriptpubkey"; return false; } if (whichType == TX_NULL_DATA) nDataOut++; if (txout.nValue == 0) { reason = "dust"; return false; } if (!txout.scriptPubKey.HasCanonicalPushes()) { reason = "scriptpubkey-non-canonical-push"; return false; } } // Not more than one data txout per non-data txout is permitted // Only one data txout is permitted too if (nDataOut > 1 && nDataOut > tx.vout.size() / 2) { reason = "multi-op-return"; return false; } return true; } bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime) { AssertLockHeld(cs_main); // Time based nLockTime implemented in 0.1.6 if (tx.nLockTime == 0) return true; if (nBlockHeight == 0) nBlockHeight = nBestHeight; if (nBlockTime == 0) nBlockTime = GetAdjustedTime(); if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime)) return true; BOOST_FOREACH(const CTxIn& txin, tx.vin) if (!txin.IsFinal()) return false; return true; }
36.149371
129
0.594667
AlphaX-Projects
b4ed3fe52706d6534d0c446b78ba020dbf81fd34
260
cpp
C++
Labs/4/test 1/hello.cpp
HudaFiqri/belajarCPP
cf4d50115d18ecc16244ca7da98febbd8591a0e2
[ "Apache-2.0" ]
null
null
null
Labs/4/test 1/hello.cpp
HudaFiqri/belajarCPP
cf4d50115d18ecc16244ca7da98febbd8591a0e2
[ "Apache-2.0" ]
null
null
null
Labs/4/test 1/hello.cpp
HudaFiqri/belajarCPP
cf4d50115d18ecc16244ca7da98febbd8591a0e2
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; class Main_Class_1{ void func1( string str1, string str2){ string str3 = str1 + str2; cout << str3; } }; int main(){ Main_Class_1 class_Obj; class_Obj.func1("hello ", "world"); }
12.380952
42
0.6
HudaFiqri
b4eec4bc1007d6a7da65ef112a73aa9bf5c0b22e
91,930
cpp
C++
examples/example2/templated/gen-cpp2/file29_types.cpp
eduardo-elizondo/cppcon2017
8c8f09799af398ecdeca5a38ce6430d9f9db2b0e
[ "MIT" ]
29
2017-09-29T17:38:09.000Z
2021-05-03T03:34:28.000Z
examples/example2/templated/gen-cpp2/file29_types.cpp
eduardo-elizondo/cppcon2017
8c8f09799af398ecdeca5a38ce6430d9f9db2b0e
[ "MIT" ]
2
2017-11-05T11:36:59.000Z
2018-01-03T00:38:34.000Z
examples/example2/templated/gen-cpp2/file29_types.cpp
eduardo-elizondo/cppcon2017
8c8f09799af398ecdeca5a38ce6430d9f9db2b0e
[ "MIT" ]
4
2017-09-30T14:52:45.000Z
2017-11-05T10:44:42.000Z
/** * Autogenerated by Thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "file29_types.h" #include "file29_types.tcc" #include <algorithm> #include <folly/Indestructible.h> #include "file29_data.h" namespace example { namespace thrift29 { void Struct0::__clear() { // clear all fields field1.clear(); field2 = 0; field3 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field4.clear(); field5.clear(); field6.clear(); field7.clear(); __isset.__clear(); } bool Struct0::operator==(const Struct0& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!((field2 == rhs.field2))) { return false; } if (!(apache::thrift::StringTraits<std::string>::isEqual(field3, rhs.field3))) { return false; } if (!((field4 == rhs.field4))) { return false; } if (!((field5 == rhs.field5))) { return false; } if (!((field6 == rhs.field6))) { return false; } if (!((field7 == rhs.field7))) { return false; } return true; } const std::set<bool>& Struct0::get_field1() const& { return field1; } std::set<bool> Struct0::get_field1() && { return std::move(field1); } const std::set<std::string>& Struct0::get_field4() const& { return field4; } std::set<std::string> Struct0::get_field4() && { return std::move(field4); } const std::map<std::map<float, int16_t>, int64_t>& Struct0::get_field5() const& { return field5; } std::map<std::map<float, int16_t>, int64_t> Struct0::get_field5() && { return std::move(field5); } const std::map<std::string, bool>& Struct0::get_field6() const& { return field6; } std::map<std::string, bool> Struct0::get_field6() && { return std::move(field6); } const std::set<int64_t>& Struct0::get_field7() const& { return field7; } std::set<int64_t> Struct0::get_field7() && { return std::move(field7); } void Struct0::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field5") { fid = 5; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field6") { fid = 6; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field7") { fid = 7; _ftype = apache::thrift::protocol::T_SET; } } void swap(Struct0& a, Struct0& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.field5, b.field5); swap(a.field6, b.field6); swap(a.field7, b.field7); swap(a.__isset, b.__isset); } template uint32_t Struct0::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct0::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct0::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct0::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct0::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct0::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct0::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct0::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct1::__clear() { // clear all fields ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct0>::clear(&field1); field2 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field3 = 0; field4 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field5.clear(); field6.clear(); ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct0>::clear(&field7); field8 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field9 = 0; field10 = 0; field11.clear(); field12 = 0; field13 = 0; field14 = 0; field15.clear(); field16.clear(); ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct0>::clear(&field17); field18 = 0; field19.clear(); __isset.__clear(); } bool Struct1::operator==(const Struct1& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!(apache::thrift::StringTraits<std::string>::isEqual(field2, rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!((field4 == rhs.field4))) { return false; } if (!((field5 == rhs.field5))) { return false; } if (!((field6 == rhs.field6))) { return false; } if (!((field7 == rhs.field7))) { return false; } if (!((field8 == rhs.field8))) { return false; } if (!((field9 == rhs.field9))) { return false; } if (!((field10 == rhs.field10))) { return false; } if (!((field11 == rhs.field11))) { return false; } if (!((field12 == rhs.field12))) { return false; } if (!((field13 == rhs.field13))) { return false; } if (!((field14 == rhs.field14))) { return false; } if (!((field15 == rhs.field15))) { return false; } if (!((field16 == rhs.field16))) { return false; } if (!((field17 == rhs.field17))) { return false; } if (!((field18 == rhs.field18))) { return false; } if (!((field19 == rhs.field19))) { return false; } return true; } const ::example::thrift29::Struct0& Struct1::get_field1() const& { return field1; } ::example::thrift29::Struct0 Struct1::get_field1() && { return std::move(field1); } const std::vector<std::set<bool>>& Struct1::get_field5() const& { return field5; } std::vector<std::set<bool>> Struct1::get_field5() && { return std::move(field5); } const std::map< ::example::thrift29::Struct0, std::set<int32_t>>& Struct1::get_field6() const& { return field6; } std::map< ::example::thrift29::Struct0, std::set<int32_t>> Struct1::get_field6() && { return std::move(field6); } const ::example::thrift29::Struct0& Struct1::get_field7() const& { return field7; } ::example::thrift29::Struct0 Struct1::get_field7() && { return std::move(field7); } const std::set<std::set<std::vector<double>>>& Struct1::get_field11() const& { return field11; } std::set<std::set<std::vector<double>>> Struct1::get_field11() && { return std::move(field11); } const std::vector<int32_t>& Struct1::get_field15() const& { return field15; } std::vector<int32_t> Struct1::get_field15() && { return std::move(field15); } const std::map<int32_t, bool>& Struct1::get_field16() const& { return field16; } std::map<int32_t, bool> Struct1::get_field16() && { return std::move(field16); } const ::example::thrift29::Struct0& Struct1::get_field17() const& { return field17; } ::example::thrift29::Struct0 Struct1::get_field17() && { return std::move(field17); } const std::vector<std::set<std::string>>& Struct1::get_field19() const& { return field19; } std::vector<std::set<std::string>> Struct1::get_field19() && { return std::move(field19); } void Struct1::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_I16; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field5") { fid = 5; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field6") { fid = 6; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field7") { fid = 7; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field8") { fid = 8; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field9") { fid = 9; _ftype = apache::thrift::protocol::T_I16; } else if (_fname == "field10") { fid = 10; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field11") { fid = 11; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field12") { fid = 12; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field13") { fid = 13; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field14") { fid = 14; _ftype = apache::thrift::protocol::T_I16; } else if (_fname == "field15") { fid = 15; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field16") { fid = 16; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field17") { fid = 17; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field18") { fid = 18; _ftype = apache::thrift::protocol::T_BYTE; } else if (_fname == "field19") { fid = 19; _ftype = apache::thrift::protocol::T_LIST; } } void swap(Struct1& a, Struct1& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.field5, b.field5); swap(a.field6, b.field6); swap(a.field7, b.field7); swap(a.field8, b.field8); swap(a.field9, b.field9); swap(a.field10, b.field10); swap(a.field11, b.field11); swap(a.field12, b.field12); swap(a.field13, b.field13); swap(a.field14, b.field14); swap(a.field15, b.field15); swap(a.field16, b.field16); swap(a.field17, b.field17); swap(a.field18, b.field18); swap(a.field19, b.field19); swap(a.__isset, b.__isset); } template uint32_t Struct1::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct1::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct1::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct1::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct1::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct1::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct1::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct1::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct2::__clear() { // clear all fields field1 = 0; field2 = 0; field3.clear(); field4 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field5 = 0; field6.clear(); field7.clear(); field8 = 0; field9 = 0; field10 = 0; field11.clear(); field12.clear(); __isset.__clear(); } bool Struct2::operator==(const Struct2& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!((field2 == rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!(apache::thrift::StringTraits<std::string>::isEqual(field4, rhs.field4))) { return false; } if (!((field5 == rhs.field5))) { return false; } if (!((field6 == rhs.field6))) { return false; } if (!((field7 == rhs.field7))) { return false; } if (!((field8 == rhs.field8))) { return false; } if (!((field9 == rhs.field9))) { return false; } if (!((field10 == rhs.field10))) { return false; } if (!((field11 == rhs.field11))) { return false; } if (!((field12 == rhs.field12))) { return false; } return true; } const std::vector< ::example::thrift29::Struct0>& Struct2::get_field3() const& { return field3; } std::vector< ::example::thrift29::Struct0> Struct2::get_field3() && { return std::move(field3); } const std::vector< ::example::thrift29::Struct0>& Struct2::get_field6() const& { return field6; } std::vector< ::example::thrift29::Struct0> Struct2::get_field6() && { return std::move(field6); } const std::set<int16_t>& Struct2::get_field7() const& { return field7; } std::set<int16_t> Struct2::get_field7() && { return std::move(field7); } const std::set<int32_t>& Struct2::get_field11() const& { return field11; } std::set<int32_t> Struct2::get_field11() && { return std::move(field11); } const std::vector<double>& Struct2::get_field12() const& { return field12; } std::vector<double> Struct2::get_field12() && { return std::move(field12); } void Struct2::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_FLOAT; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field5") { fid = 5; _ftype = apache::thrift::protocol::T_DOUBLE; } else if (_fname == "field6") { fid = 6; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field7") { fid = 7; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field8") { fid = 8; _ftype = apache::thrift::protocol::T_FLOAT; } else if (_fname == "field9") { fid = 9; _ftype = apache::thrift::protocol::T_BYTE; } else if (_fname == "field10") { fid = 10; _ftype = apache::thrift::protocol::T_I32; } else if (_fname == "field11") { fid = 11; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field12") { fid = 12; _ftype = apache::thrift::protocol::T_LIST; } } void swap(Struct2& a, Struct2& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.field5, b.field5); swap(a.field6, b.field6); swap(a.field7, b.field7); swap(a.field8, b.field8); swap(a.field9, b.field9); swap(a.field10, b.field10); swap(a.field11, b.field11); swap(a.field12, b.field12); swap(a.__isset, b.__isset); } template uint32_t Struct2::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct2::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct2::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct2::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct2::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct2::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct2::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct2::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct3::__clear() { // clear all fields field1.clear(); field2 = 0; field3 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); __isset.__clear(); } bool Struct3::operator==(const Struct3& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!((field2 == rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } return true; } const std::set<std::map<int8_t, int32_t>>& Struct3::get_field1() const& { return field1; } std::set<std::map<int8_t, int32_t>> Struct3::get_field1() && { return std::move(field1); } void Struct3::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_STRING; } } void swap(Struct3& a, Struct3& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.__isset, b.__isset); } template uint32_t Struct3::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct3::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct3::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct3::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct3::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct3::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct3::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct3::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct4::__clear() { // clear all fields field1.clear(); field2.clear(); field3.clear(); field4 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); __isset.__clear(); } bool Struct4::operator==(const Struct4& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!((field2 == rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!(apache::thrift::StringTraits<std::string>::isEqual(field4, rhs.field4))) { return false; } return true; } const std::set<int8_t>& Struct4::get_field1() const& { return field1; } std::set<int8_t> Struct4::get_field1() && { return std::move(field1); } const std::map<bool, std::string>& Struct4::get_field2() const& { return field2; } std::map<bool, std::string> Struct4::get_field2() && { return std::move(field2); } const std::vector<std::map<std::set<int32_t>, bool>>& Struct4::get_field3() const& { return field3; } std::vector<std::map<std::set<int32_t>, bool>> Struct4::get_field3() && { return std::move(field3); } void Struct4::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_STRING; } } void swap(Struct4& a, Struct4& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.__isset, b.__isset); } template uint32_t Struct4::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct4::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct4::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct4::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct4::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct4::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct4::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct4::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct5::__clear() { // clear all fields field1.clear(); field2 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field3.clear(); field4.clear(); field5 = 0; field6 = 0; field7.clear(); field8 = 0; field9 = 0; field10.clear(); __isset.__clear(); } bool Struct5::operator==(const Struct5& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!(apache::thrift::StringTraits<std::string>::isEqual(field2, rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!((field4 == rhs.field4))) { return false; } if (!((field5 == rhs.field5))) { return false; } if (!((field6 == rhs.field6))) { return false; } if (!((field7 == rhs.field7))) { return false; } if (!((field8 == rhs.field8))) { return false; } if (!((field9 == rhs.field9))) { return false; } if (!((field10 == rhs.field10))) { return false; } return true; } const std::vector<float>& Struct5::get_field1() const& { return field1; } std::vector<float> Struct5::get_field1() && { return std::move(field1); } const std::map<bool, std::map<std::string, float>>& Struct5::get_field3() const& { return field3; } std::map<bool, std::map<std::string, float>> Struct5::get_field3() && { return std::move(field3); } const std::map<double, int32_t>& Struct5::get_field4() const& { return field4; } std::map<double, int32_t> Struct5::get_field4() && { return std::move(field4); } const std::vector<float>& Struct5::get_field7() const& { return field7; } std::vector<float> Struct5::get_field7() && { return std::move(field7); } const std::set<int8_t>& Struct5::get_field10() const& { return field10; } std::set<int8_t> Struct5::get_field10() && { return std::move(field10); } void Struct5::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field5") { fid = 5; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field6") { fid = 6; _ftype = apache::thrift::protocol::T_I16; } else if (_fname == "field7") { fid = 7; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field8") { fid = 8; _ftype = apache::thrift::protocol::T_DOUBLE; } else if (_fname == "field9") { fid = 9; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field10") { fid = 10; _ftype = apache::thrift::protocol::T_SET; } } void swap(Struct5& a, Struct5& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.field5, b.field5); swap(a.field6, b.field6); swap(a.field7, b.field7); swap(a.field8, b.field8); swap(a.field9, b.field9); swap(a.field10, b.field10); swap(a.__isset, b.__isset); } template uint32_t Struct5::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct5::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct5::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct5::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct5::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct5::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct5::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct5::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct6::__clear() { // clear all fields field1 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field2 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field3.clear(); field4.clear(); field5.clear(); field6.clear(); field7.clear(); field8.clear(); field9 = 0; field10.clear(); field11 = 0; field12 = 0; field13.clear(); field14.clear(); field15 = 0; field16.clear(); field17 = 0; field18 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field19.clear(); ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct0>::clear(&field20); __isset.__clear(); } bool Struct6::operator==(const Struct6& rhs) const { if (!(apache::thrift::StringTraits<std::string>::isEqual(field1, rhs.field1))) { return false; } if (!(apache::thrift::StringTraits<std::string>::isEqual(field2, rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!((field4 == rhs.field4))) { return false; } if (!((field5 == rhs.field5))) { return false; } if (!((field6 == rhs.field6))) { return false; } if (!((field7 == rhs.field7))) { return false; } if (!((field8 == rhs.field8))) { return false; } if (!((field9 == rhs.field9))) { return false; } if (!((field10 == rhs.field10))) { return false; } if (!((field11 == rhs.field11))) { return false; } if (!((field12 == rhs.field12))) { return false; } if (!((field13 == rhs.field13))) { return false; } if (!((field14 == rhs.field14))) { return false; } if (!((field15 == rhs.field15))) { return false; } if (!((field16 == rhs.field16))) { return false; } if (!((field17 == rhs.field17))) { return false; } if (!(apache::thrift::StringTraits<std::string>::isEqual(field18, rhs.field18))) { return false; } if (!((field19 == rhs.field19))) { return false; } if (!((field20 == rhs.field20))) { return false; } return true; } const std::set<double>& Struct6::get_field3() const& { return field3; } std::set<double> Struct6::get_field3() && { return std::move(field3); } const std::vector<std::string>& Struct6::get_field4() const& { return field4; } std::vector<std::string> Struct6::get_field4() && { return std::move(field4); } const std::vector<int8_t>& Struct6::get_field5() const& { return field5; } std::vector<int8_t> Struct6::get_field5() && { return std::move(field5); } const std::vector<int64_t>& Struct6::get_field6() const& { return field6; } std::vector<int64_t> Struct6::get_field6() && { return std::move(field6); } const std::map<bool, std::vector<int64_t>>& Struct6::get_field7() const& { return field7; } std::map<bool, std::vector<int64_t>> Struct6::get_field7() && { return std::move(field7); } const std::set<std::vector<float>>& Struct6::get_field8() const& { return field8; } std::set<std::vector<float>> Struct6::get_field8() && { return std::move(field8); } const std::set<double>& Struct6::get_field10() const& { return field10; } std::set<double> Struct6::get_field10() && { return std::move(field10); } const std::map<int8_t, int8_t>& Struct6::get_field13() const& { return field13; } std::map<int8_t, int8_t> Struct6::get_field13() && { return std::move(field13); } const std::set<std::string>& Struct6::get_field14() const& { return field14; } std::set<std::string> Struct6::get_field14() && { return std::move(field14); } const std::set<std::map<int64_t, std::set<float>>>& Struct6::get_field16() const& { return field16; } std::set<std::map<int64_t, std::set<float>>> Struct6::get_field16() && { return std::move(field16); } const std::map<int32_t, float>& Struct6::get_field19() const& { return field19; } std::map<int32_t, float> Struct6::get_field19() && { return std::move(field19); } const ::example::thrift29::Struct0& Struct6::get_field20() const& { return field20; } ::example::thrift29::Struct0 Struct6::get_field20() && { return std::move(field20); } void Struct6::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field5") { fid = 5; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field6") { fid = 6; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field7") { fid = 7; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field8") { fid = 8; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field9") { fid = 9; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field10") { fid = 10; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field11") { fid = 11; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field12") { fid = 12; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field13") { fid = 13; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field14") { fid = 14; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field15") { fid = 15; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field16") { fid = 16; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field17") { fid = 17; _ftype = apache::thrift::protocol::T_DOUBLE; } else if (_fname == "field18") { fid = 18; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field19") { fid = 19; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field20") { fid = 20; _ftype = apache::thrift::protocol::T_STRUCT; } } void swap(Struct6& a, Struct6& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.field5, b.field5); swap(a.field6, b.field6); swap(a.field7, b.field7); swap(a.field8, b.field8); swap(a.field9, b.field9); swap(a.field10, b.field10); swap(a.field11, b.field11); swap(a.field12, b.field12); swap(a.field13, b.field13); swap(a.field14, b.field14); swap(a.field15, b.field15); swap(a.field16, b.field16); swap(a.field17, b.field17); swap(a.field18, b.field18); swap(a.field19, b.field19); swap(a.field20, b.field20); swap(a.__isset, b.__isset); } template uint32_t Struct6::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct6::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct6::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct6::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct6::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct6::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct6::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct6::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct7::__clear() { // clear all fields field1 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field2 = 0; field3.clear(); field4.clear(); field5.clear(); field6.clear(); field7 = 0; field8 = 0; field9.clear(); field10 = 0; field11.clear(); field12 = 0; ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct1>::clear(&field13); ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct1>::clear(&field14); field15 = 0; field16.clear(); field17.clear(); __isset.__clear(); } bool Struct7::operator==(const Struct7& rhs) const { if (!(apache::thrift::StringTraits<std::string>::isEqual(field1, rhs.field1))) { return false; } if (!((field2 == rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!((field4 == rhs.field4))) { return false; } if (!((field5 == rhs.field5))) { return false; } if (!((field6 == rhs.field6))) { return false; } if (!((field7 == rhs.field7))) { return false; } if (!((field8 == rhs.field8))) { return false; } if (!((field9 == rhs.field9))) { return false; } if (!((field10 == rhs.field10))) { return false; } if (!((field11 == rhs.field11))) { return false; } if (!((field12 == rhs.field12))) { return false; } if (!((field13 == rhs.field13))) { return false; } if (!((field14 == rhs.field14))) { return false; } if (!((field15 == rhs.field15))) { return false; } if (!((field16 == rhs.field16))) { return false; } if (!((field17 == rhs.field17))) { return false; } return true; } const std::vector<float>& Struct7::get_field3() const& { return field3; } std::vector<float> Struct7::get_field3() && { return std::move(field3); } const std::set<int16_t>& Struct7::get_field4() const& { return field4; } std::set<int16_t> Struct7::get_field4() && { return std::move(field4); } const std::set<int64_t>& Struct7::get_field5() const& { return field5; } std::set<int64_t> Struct7::get_field5() && { return std::move(field5); } const std::vector<std::string>& Struct7::get_field6() const& { return field6; } std::vector<std::string> Struct7::get_field6() && { return std::move(field6); } const std::set<int16_t>& Struct7::get_field9() const& { return field9; } std::set<int16_t> Struct7::get_field9() && { return std::move(field9); } const std::set<std::string>& Struct7::get_field11() const& { return field11; } std::set<std::string> Struct7::get_field11() && { return std::move(field11); } const ::example::thrift29::Struct1& Struct7::get_field13() const& { return field13; } ::example::thrift29::Struct1 Struct7::get_field13() && { return std::move(field13); } const ::example::thrift29::Struct1& Struct7::get_field14() const& { return field14; } ::example::thrift29::Struct1 Struct7::get_field14() && { return std::move(field14); } const std::vector<double>& Struct7::get_field16() const& { return field16; } std::vector<double> Struct7::get_field16() && { return std::move(field16); } const std::map<std::string, int8_t>& Struct7::get_field17() const& { return field17; } std::map<std::string, int8_t> Struct7::get_field17() && { return std::move(field17); } void Struct7::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field5") { fid = 5; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field6") { fid = 6; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field7") { fid = 7; _ftype = apache::thrift::protocol::T_FLOAT; } else if (_fname == "field8") { fid = 8; _ftype = apache::thrift::protocol::T_DOUBLE; } else if (_fname == "field9") { fid = 9; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field10") { fid = 10; _ftype = apache::thrift::protocol::T_FLOAT; } else if (_fname == "field11") { fid = 11; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field12") { fid = 12; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field13") { fid = 13; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field14") { fid = 14; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field15") { fid = 15; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field16") { fid = 16; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field17") { fid = 17; _ftype = apache::thrift::protocol::T_MAP; } } void swap(Struct7& a, Struct7& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.field5, b.field5); swap(a.field6, b.field6); swap(a.field7, b.field7); swap(a.field8, b.field8); swap(a.field9, b.field9); swap(a.field10, b.field10); swap(a.field11, b.field11); swap(a.field12, b.field12); swap(a.field13, b.field13); swap(a.field14, b.field14); swap(a.field15, b.field15); swap(a.field16, b.field16); swap(a.field17, b.field17); swap(a.__isset, b.__isset); } template uint32_t Struct7::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct7::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct7::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct7::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct7::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct7::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct7::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct7::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct8::__clear() { // clear all fields field1 = 0; field2 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field3.clear(); field4 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field5 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field6 = 0; field7 = 0; field8 = 0; field9 = 0; field10 = 0; field11 = 0; field12 = 0; field13 = 0; field14.clear(); field15 = 0; field16.clear(); field17.clear(); field18 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field19 = 0; field20.clear(); field21 = 0; field22 = 0; field23 = 0; field24.clear(); field25 = 0; field26.clear(); field27 = 0; field28.clear(); field29.clear(); field30 = 0; field31.clear(); field32 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field33.clear(); field34 = 0; field35.clear(); field36 = 0; field37 = 0; ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct6>::clear(&field38); field39 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field40 = 0; field41 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field42.clear(); field43.clear(); field44.clear(); field45 = 0; field46.clear(); ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct1>::clear(&field47); ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct1>::clear(&field48); __isset.__clear(); } bool Struct8::operator==(const Struct8& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!(apache::thrift::StringTraits<std::string>::isEqual(field2, rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!((field4 == rhs.field4))) { return false; } if (!((field5 == rhs.field5))) { return false; } if (!((field6 == rhs.field6))) { return false; } if (!((field7 == rhs.field7))) { return false; } if (!((field8 == rhs.field8))) { return false; } if (!((field9 == rhs.field9))) { return false; } if (!((field10 == rhs.field10))) { return false; } if (!((field11 == rhs.field11))) { return false; } if (!((field12 == rhs.field12))) { return false; } if (!((field13 == rhs.field13))) { return false; } if (!((field14 == rhs.field14))) { return false; } if (!((field15 == rhs.field15))) { return false; } if (!((field16 == rhs.field16))) { return false; } if (!((field17 == rhs.field17))) { return false; } if (!((field18 == rhs.field18))) { return false; } if (!((field19 == rhs.field19))) { return false; } if (!((field20 == rhs.field20))) { return false; } if (!((field21 == rhs.field21))) { return false; } if (!((field22 == rhs.field22))) { return false; } if (!((field23 == rhs.field23))) { return false; } if (!((field24 == rhs.field24))) { return false; } if (!((field25 == rhs.field25))) { return false; } if (!((field26 == rhs.field26))) { return false; } if (!((field27 == rhs.field27))) { return false; } if (!((field28 == rhs.field28))) { return false; } if (!((field29 == rhs.field29))) { return false; } if (!((field30 == rhs.field30))) { return false; } if (!((field31 == rhs.field31))) { return false; } if (!((field32 == rhs.field32))) { return false; } if (!((field33 == rhs.field33))) { return false; } if (!((field34 == rhs.field34))) { return false; } if (!((field35 == rhs.field35))) { return false; } if (!((field36 == rhs.field36))) { return false; } if (!((field37 == rhs.field37))) { return false; } if (!((field38 == rhs.field38))) { return false; } if (!((field39 == rhs.field39))) { return false; } if (!((field40 == rhs.field40))) { return false; } if (!(apache::thrift::StringTraits<std::string>::isEqual(field41, rhs.field41))) { return false; } if (!((field42 == rhs.field42))) { return false; } if (!((field43 == rhs.field43))) { return false; } if (!((field44 == rhs.field44))) { return false; } if (!((field45 == rhs.field45))) { return false; } if (!((field46 == rhs.field46))) { return false; } if (!((field47 == rhs.field47))) { return false; } if (!((field48 == rhs.field48))) { return false; } return true; } const std::vector<bool>& Struct8::get_field3() const& { return field3; } std::vector<bool> Struct8::get_field3() && { return std::move(field3); } const std::map< ::example::thrift29::Struct5, float>& Struct8::get_field14() const& { return field14; } std::map< ::example::thrift29::Struct5, float> Struct8::get_field14() && { return std::move(field14); } const std::vector<int32_t>& Struct8::get_field16() const& { return field16; } std::vector<int32_t> Struct8::get_field16() && { return std::move(field16); } const std::set<std::vector< ::example::thrift29::Struct0>>& Struct8::get_field17() const& { return field17; } std::set<std::vector< ::example::thrift29::Struct0>> Struct8::get_field17() && { return std::move(field17); } const std::set<int64_t>& Struct8::get_field20() const& { return field20; } std::set<int64_t> Struct8::get_field20() && { return std::move(field20); } const std::vector<double>& Struct8::get_field24() const& { return field24; } std::vector<double> Struct8::get_field24() && { return std::move(field24); } const std::map< ::example::thrift29::Struct0, double>& Struct8::get_field26() const& { return field26; } std::map< ::example::thrift29::Struct0, double> Struct8::get_field26() && { return std::move(field26); } const std::set<double>& Struct8::get_field28() const& { return field28; } std::set<double> Struct8::get_field28() && { return std::move(field28); } const std::set<std::string>& Struct8::get_field29() const& { return field29; } std::set<std::string> Struct8::get_field29() && { return std::move(field29); } const std::set<std::vector<int16_t>>& Struct8::get_field31() const& { return field31; } std::set<std::vector<int16_t>> Struct8::get_field31() && { return std::move(field31); } const std::vector< ::example::thrift29::Struct3>& Struct8::get_field33() const& { return field33; } std::vector< ::example::thrift29::Struct3> Struct8::get_field33() && { return std::move(field33); } const std::vector<double>& Struct8::get_field35() const& { return field35; } std::vector<double> Struct8::get_field35() && { return std::move(field35); } const ::example::thrift29::Struct6& Struct8::get_field38() const& { return field38; } ::example::thrift29::Struct6 Struct8::get_field38() && { return std::move(field38); } const std::set<float>& Struct8::get_field42() const& { return field42; } std::set<float> Struct8::get_field42() && { return std::move(field42); } const std::set<int64_t>& Struct8::get_field43() const& { return field43; } std::set<int64_t> Struct8::get_field43() && { return std::move(field43); } const std::vector<float>& Struct8::get_field44() const& { return field44; } std::vector<float> Struct8::get_field44() && { return std::move(field44); } const std::set<std::string>& Struct8::get_field46() const& { return field46; } std::set<std::string> Struct8::get_field46() && { return std::move(field46); } const ::example::thrift29::Struct1& Struct8::get_field47() const& { return field47; } ::example::thrift29::Struct1 Struct8::get_field47() && { return std::move(field47); } const ::example::thrift29::Struct1& Struct8::get_field48() const& { return field48; } ::example::thrift29::Struct1 Struct8::get_field48() && { return std::move(field48); } void Struct8::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field5") { fid = 5; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field6") { fid = 6; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field7") { fid = 7; _ftype = apache::thrift::protocol::T_BYTE; } else if (_fname == "field8") { fid = 8; _ftype = apache::thrift::protocol::T_FLOAT; } else if (_fname == "field9") { fid = 9; _ftype = apache::thrift::protocol::T_DOUBLE; } else if (_fname == "field10") { fid = 10; _ftype = apache::thrift::protocol::T_I16; } else if (_fname == "field11") { fid = 11; _ftype = apache::thrift::protocol::T_I16; } else if (_fname == "field12") { fid = 12; _ftype = apache::thrift::protocol::T_I32; } else if (_fname == "field13") { fid = 13; _ftype = apache::thrift::protocol::T_I16; } else if (_fname == "field14") { fid = 14; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field15") { fid = 15; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field16") { fid = 16; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field17") { fid = 17; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field18") { fid = 18; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field19") { fid = 19; _ftype = apache::thrift::protocol::T_DOUBLE; } else if (_fname == "field20") { fid = 20; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field21") { fid = 21; _ftype = apache::thrift::protocol::T_BYTE; } else if (_fname == "field22") { fid = 22; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field23") { fid = 23; _ftype = apache::thrift::protocol::T_DOUBLE; } else if (_fname == "field24") { fid = 24; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field25") { fid = 25; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field26") { fid = 26; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field27") { fid = 27; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field28") { fid = 28; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field29") { fid = 29; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field30") { fid = 30; _ftype = apache::thrift::protocol::T_BYTE; } else if (_fname == "field31") { fid = 31; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field32") { fid = 32; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field33") { fid = 33; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field34") { fid = 34; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field35") { fid = 35; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field36") { fid = 36; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field37") { fid = 37; _ftype = apache::thrift::protocol::T_DOUBLE; } else if (_fname == "field38") { fid = 38; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field39") { fid = 39; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field40") { fid = 40; _ftype = apache::thrift::protocol::T_BYTE; } else if (_fname == "field41") { fid = 41; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field42") { fid = 42; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field43") { fid = 43; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field44") { fid = 44; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field45") { fid = 45; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field46") { fid = 46; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field47") { fid = 47; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field48") { fid = 48; _ftype = apache::thrift::protocol::T_STRUCT; } } void swap(Struct8& a, Struct8& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.field5, b.field5); swap(a.field6, b.field6); swap(a.field7, b.field7); swap(a.field8, b.field8); swap(a.field9, b.field9); swap(a.field10, b.field10); swap(a.field11, b.field11); swap(a.field12, b.field12); swap(a.field13, b.field13); swap(a.field14, b.field14); swap(a.field15, b.field15); swap(a.field16, b.field16); swap(a.field17, b.field17); swap(a.field18, b.field18); swap(a.field19, b.field19); swap(a.field20, b.field20); swap(a.field21, b.field21); swap(a.field22, b.field22); swap(a.field23, b.field23); swap(a.field24, b.field24); swap(a.field25, b.field25); swap(a.field26, b.field26); swap(a.field27, b.field27); swap(a.field28, b.field28); swap(a.field29, b.field29); swap(a.field30, b.field30); swap(a.field31, b.field31); swap(a.field32, b.field32); swap(a.field33, b.field33); swap(a.field34, b.field34); swap(a.field35, b.field35); swap(a.field36, b.field36); swap(a.field37, b.field37); swap(a.field38, b.field38); swap(a.field39, b.field39); swap(a.field40, b.field40); swap(a.field41, b.field41); swap(a.field42, b.field42); swap(a.field43, b.field43); swap(a.field44, b.field44); swap(a.field45, b.field45); swap(a.field46, b.field46); swap(a.field47, b.field47); swap(a.field48, b.field48); swap(a.__isset, b.__isset); } template uint32_t Struct8::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct8::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct8::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct8::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct8::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct8::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct8::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct8::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct9::__clear() { // clear all fields field1 = 0; field2 = 0; field3.clear(); field4 = 0; __isset.__clear(); } bool Struct9::operator==(const Struct9& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!((field2 == rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!((field4 == rhs.field4))) { return false; } return true; } const std::set<std::vector<std::string>>& Struct9::get_field3() const& { return field3; } std::set<std::vector<std::string>> Struct9::get_field3() && { return std::move(field3); } void Struct9::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_FLOAT; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_DOUBLE; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_I32; } } void swap(Struct9& a, Struct9& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.__isset, b.__isset); } template uint32_t Struct9::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct9::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct9::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct9::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct9::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct9::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct9::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct9::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct10::__clear() { // clear all fields field1.clear(); field2 = 0; field3 = 0; field4 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct0>::clear(&field5); __isset.__clear(); } bool Struct10::operator==(const Struct10& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!((field2 == rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!(apache::thrift::StringTraits<std::string>::isEqual(field4, rhs.field4))) { return false; } if (!((field5 == rhs.field5))) { return false; } return true; } const std::vector<int16_t>& Struct10::get_field1() const& { return field1; } std::vector<int16_t> Struct10::get_field1() && { return std::move(field1); } const ::example::thrift29::Struct0& Struct10::get_field5() const& { return field5; } ::example::thrift29::Struct0 Struct10::get_field5() && { return std::move(field5); } void Struct10::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_BYTE; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field5") { fid = 5; _ftype = apache::thrift::protocol::T_STRUCT; } } void swap(Struct10& a, Struct10& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.field5, b.field5); swap(a.__isset, b.__isset); } template uint32_t Struct10::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct10::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct10::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct10::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct10::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct10::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct10::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct10::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct11::__clear() { // clear all fields ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct2>::clear(&field1); field2.clear(); field3 = 0; field4.clear(); field5 = 0; field6 = 0; field7.clear(); field8 = 0; field9 = 0; field10.clear(); field11.clear(); field12 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field13.clear(); field14 = 0; field15.clear(); field16 = 0; field17 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field18.clear(); field19 = 0; __isset.__clear(); } bool Struct11::operator==(const Struct11& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!((field2 == rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!((field4 == rhs.field4))) { return false; } if (!((field5 == rhs.field5))) { return false; } if (!((field6 == rhs.field6))) { return false; } if (!((field7 == rhs.field7))) { return false; } if (!((field8 == rhs.field8))) { return false; } if (!((field9 == rhs.field9))) { return false; } if (!((field10 == rhs.field10))) { return false; } if (!((field11 == rhs.field11))) { return false; } if (!(apache::thrift::StringTraits<std::string>::isEqual(field12, rhs.field12))) { return false; } if (!((field13 == rhs.field13))) { return false; } if (!((field14 == rhs.field14))) { return false; } if (!((field15 == rhs.field15))) { return false; } if (!((field16 == rhs.field16))) { return false; } if (!(apache::thrift::StringTraits<std::string>::isEqual(field17, rhs.field17))) { return false; } if (!((field18 == rhs.field18))) { return false; } if (!((field19 == rhs.field19))) { return false; } return true; } const ::example::thrift29::Struct2& Struct11::get_field1() const& { return field1; } ::example::thrift29::Struct2 Struct11::get_field1() && { return std::move(field1); } const std::vector<std::vector<int64_t>>& Struct11::get_field2() const& { return field2; } std::vector<std::vector<int64_t>> Struct11::get_field2() && { return std::move(field2); } const std::vector<std::string>& Struct11::get_field4() const& { return field4; } std::vector<std::string> Struct11::get_field4() && { return std::move(field4); } const std::vector<double>& Struct11::get_field7() const& { return field7; } std::vector<double> Struct11::get_field7() && { return std::move(field7); } const std::vector<std::set<bool>>& Struct11::get_field10() const& { return field10; } std::vector<std::set<bool>> Struct11::get_field10() && { return std::move(field10); } const std::vector<int64_t>& Struct11::get_field11() const& { return field11; } std::vector<int64_t> Struct11::get_field11() && { return std::move(field11); } const std::vector<std::vector<std::string>>& Struct11::get_field13() const& { return field13; } std::vector<std::vector<std::string>> Struct11::get_field13() && { return std::move(field13); } const std::vector<std::string>& Struct11::get_field15() const& { return field15; } std::vector<std::string> Struct11::get_field15() && { return std::move(field15); } const std::map<std::string, bool>& Struct11::get_field18() const& { return field18; } std::map<std::string, bool> Struct11::get_field18() && { return std::move(field18); } void Struct11::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field5") { fid = 5; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field6") { fid = 6; _ftype = apache::thrift::protocol::T_I32; } else if (_fname == "field7") { fid = 7; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field8") { fid = 8; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field9") { fid = 9; _ftype = apache::thrift::protocol::T_BYTE; } else if (_fname == "field10") { fid = 10; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field11") { fid = 11; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field12") { fid = 12; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field13") { fid = 13; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field14") { fid = 14; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field15") { fid = 15; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field16") { fid = 16; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field17") { fid = 17; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field18") { fid = 18; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field19") { fid = 19; _ftype = apache::thrift::protocol::T_DOUBLE; } } void swap(Struct11& a, Struct11& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.field5, b.field5); swap(a.field6, b.field6); swap(a.field7, b.field7); swap(a.field8, b.field8); swap(a.field9, b.field9); swap(a.field10, b.field10); swap(a.field11, b.field11); swap(a.field12, b.field12); swap(a.field13, b.field13); swap(a.field14, b.field14); swap(a.field15, b.field15); swap(a.field16, b.field16); swap(a.field17, b.field17); swap(a.field18, b.field18); swap(a.field19, b.field19); swap(a.__isset, b.__isset); } template uint32_t Struct11::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct11::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct11::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct11::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct11::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct11::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct11::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct11::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct12::__clear() { // clear all fields ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct3>::clear(&field1); field2 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field3 = 0; field4 = 0; field5.clear(); __isset.__clear(); } bool Struct12::operator==(const Struct12& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!((field2 == rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!((field4 == rhs.field4))) { return false; } if (!((field5 == rhs.field5))) { return false; } return true; } const ::example::thrift29::Struct3& Struct12::get_field1() const& { return field1; } ::example::thrift29::Struct3 Struct12::get_field1() && { return std::move(field1); } const std::map< ::example::thrift29::Struct3, double>& Struct12::get_field5() const& { return field5; } std::map< ::example::thrift29::Struct3, double> Struct12::get_field5() && { return std::move(field5); } void Struct12::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_I16; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field5") { fid = 5; _ftype = apache::thrift::protocol::T_MAP; } } void swap(Struct12& a, Struct12& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.field5, b.field5); swap(a.__isset, b.__isset); } template uint32_t Struct12::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct12::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct12::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct12::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct12::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct12::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct12::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct12::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct13::__clear() { // clear all fields field1.clear(); field2.clear(); field3.clear(); field4 = 0; field5.clear(); field6.clear(); ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct7>::clear(&field7); field8 = 0; ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct0>::clear(&field9); __isset.__clear(); } bool Struct13::operator==(const Struct13& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!((field2 == rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!((field4 == rhs.field4))) { return false; } if (!((field5 == rhs.field5))) { return false; } if (!((field6 == rhs.field6))) { return false; } if (!((field7 == rhs.field7))) { return false; } if (!((field8 == rhs.field8))) { return false; } if (!((field9 == rhs.field9))) { return false; } return true; } const std::map<int64_t, int32_t>& Struct13::get_field1() const& { return field1; } std::map<int64_t, int32_t> Struct13::get_field1() && { return std::move(field1); } const std::vector<int8_t>& Struct13::get_field2() const& { return field2; } std::vector<int8_t> Struct13::get_field2() && { return std::move(field2); } const std::vector<bool>& Struct13::get_field3() const& { return field3; } std::vector<bool> Struct13::get_field3() && { return std::move(field3); } const std::vector<bool>& Struct13::get_field5() const& { return field5; } std::vector<bool> Struct13::get_field5() && { return std::move(field5); } const std::set<bool>& Struct13::get_field6() const& { return field6; } std::set<bool> Struct13::get_field6() && { return std::move(field6); } const ::example::thrift29::Struct7& Struct13::get_field7() const& { return field7; } ::example::thrift29::Struct7 Struct13::get_field7() && { return std::move(field7); } const ::example::thrift29::Struct0& Struct13::get_field9() const& { return field9; } ::example::thrift29::Struct0 Struct13::get_field9() && { return std::move(field9); } void Struct13::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field5") { fid = 5; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field6") { fid = 6; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field7") { fid = 7; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field8") { fid = 8; _ftype = apache::thrift::protocol::T_I16; } else if (_fname == "field9") { fid = 9; _ftype = apache::thrift::protocol::T_STRUCT; } } void swap(Struct13& a, Struct13& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.field5, b.field5); swap(a.field6, b.field6); swap(a.field7, b.field7); swap(a.field8, b.field8); swap(a.field9, b.field9); swap(a.__isset, b.__isset); } template uint32_t Struct13::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct13::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct13::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct13::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct13::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct13::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct13::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct13::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct14::__clear() { // clear all fields ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct6>::clear(&field1); field2 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field3.clear(); ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct6>::clear(&field4); field5.clear(); field6.clear(); field7 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct9>::clear(&field8); field9 = 0; field10.clear(); field11.clear(); field12.clear(); ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct2>::clear(&field13); ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct6>::clear(&field14); field15.clear(); field16.clear(); field17.clear(); field18 = 0; __isset.__clear(); } bool Struct14::operator==(const Struct14& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!(apache::thrift::StringTraits<std::string>::isEqual(field2, rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!((field4 == rhs.field4))) { return false; } if (!((field5 == rhs.field5))) { return false; } if (!((field6 == rhs.field6))) { return false; } if (!((field7 == rhs.field7))) { return false; } if (!((field8 == rhs.field8))) { return false; } if (!((field9 == rhs.field9))) { return false; } if (!((field10 == rhs.field10))) { return false; } if (!((field11 == rhs.field11))) { return false; } if (!((field12 == rhs.field12))) { return false; } if (!((field13 == rhs.field13))) { return false; } if (!((field14 == rhs.field14))) { return false; } if (!((field15 == rhs.field15))) { return false; } if (!((field16 == rhs.field16))) { return false; } if (!((field17 == rhs.field17))) { return false; } if (!((field18 == rhs.field18))) { return false; } return true; } const ::example::thrift29::Struct6& Struct14::get_field1() const& { return field1; } ::example::thrift29::Struct6 Struct14::get_field1() && { return std::move(field1); } const std::vector<std::set<int8_t>>& Struct14::get_field3() const& { return field3; } std::vector<std::set<int8_t>> Struct14::get_field3() && { return std::move(field3); } const ::example::thrift29::Struct6& Struct14::get_field4() const& { return field4; } ::example::thrift29::Struct6 Struct14::get_field4() && { return std::move(field4); } const std::vector<std::map<double, int8_t>>& Struct14::get_field5() const& { return field5; } std::vector<std::map<double, int8_t>> Struct14::get_field5() && { return std::move(field5); } const std::vector<double>& Struct14::get_field6() const& { return field6; } std::vector<double> Struct14::get_field6() && { return std::move(field6); } const ::example::thrift29::Struct9& Struct14::get_field8() const& { return field8; } ::example::thrift29::Struct9 Struct14::get_field8() && { return std::move(field8); } const std::vector<int64_t>& Struct14::get_field10() const& { return field10; } std::vector<int64_t> Struct14::get_field10() && { return std::move(field10); } const std::vector<int64_t>& Struct14::get_field11() const& { return field11; } std::vector<int64_t> Struct14::get_field11() && { return std::move(field11); } const std::set<std::string>& Struct14::get_field12() const& { return field12; } std::set<std::string> Struct14::get_field12() && { return std::move(field12); } const ::example::thrift29::Struct2& Struct14::get_field13() const& { return field13; } ::example::thrift29::Struct2 Struct14::get_field13() && { return std::move(field13); } const ::example::thrift29::Struct6& Struct14::get_field14() const& { return field14; } ::example::thrift29::Struct6 Struct14::get_field14() && { return std::move(field14); } const std::vector< ::example::thrift29::Struct9>& Struct14::get_field15() const& { return field15; } std::vector< ::example::thrift29::Struct9> Struct14::get_field15() && { return std::move(field15); } const std::set<std::map<std::string, bool>>& Struct14::get_field16() const& { return field16; } std::set<std::map<std::string, bool>> Struct14::get_field16() && { return std::move(field16); } const std::set<double>& Struct14::get_field17() const& { return field17; } std::set<double> Struct14::get_field17() && { return std::move(field17); } void Struct14::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field5") { fid = 5; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field6") { fid = 6; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field7") { fid = 7; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field8") { fid = 8; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field9") { fid = 9; _ftype = apache::thrift::protocol::T_I16; } else if (_fname == "field10") { fid = 10; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field11") { fid = 11; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field12") { fid = 12; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field13") { fid = 13; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field14") { fid = 14; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field15") { fid = 15; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field16") { fid = 16; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field17") { fid = 17; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field18") { fid = 18; _ftype = apache::thrift::protocol::T_FLOAT; } } void swap(Struct14& a, Struct14& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.field5, b.field5); swap(a.field6, b.field6); swap(a.field7, b.field7); swap(a.field8, b.field8); swap(a.field9, b.field9); swap(a.field10, b.field10); swap(a.field11, b.field11); swap(a.field12, b.field12); swap(a.field13, b.field13); swap(a.field14, b.field14); swap(a.field15, b.field15); swap(a.field16, b.field16); swap(a.field17, b.field17); swap(a.field18, b.field18); swap(a.__isset, b.__isset); } template uint32_t Struct14::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct14::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct14::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct14::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct14::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct14::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct14::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct14::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct15::__clear() { // clear all fields ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct6>::clear(&field1); field2.clear(); field3 = 0; field4.clear(); field5 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field6.clear(); ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct4>::clear(&field7); field8.clear(); field9 = apache::thrift::StringTraits< std::string>::fromStringLiteral(""); field10 = 0; field11.clear(); __isset.__clear(); } bool Struct15::operator==(const Struct15& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!((field2 == rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!((field4 == rhs.field4))) { return false; } if (!((field5 == rhs.field5))) { return false; } if (!((field6 == rhs.field6))) { return false; } if (!((field7 == rhs.field7))) { return false; } if (!((field8 == rhs.field8))) { return false; } if (!(apache::thrift::StringTraits<std::string>::isEqual(field9, rhs.field9))) { return false; } if (!((field10 == rhs.field10))) { return false; } if (!((field11 == rhs.field11))) { return false; } return true; } const ::example::thrift29::Struct6& Struct15::get_field1() const& { return field1; } ::example::thrift29::Struct6 Struct15::get_field1() && { return std::move(field1); } const std::vector<std::string>& Struct15::get_field2() const& { return field2; } std::vector<std::string> Struct15::get_field2() && { return std::move(field2); } const std::set<float>& Struct15::get_field4() const& { return field4; } std::set<float> Struct15::get_field4() && { return std::move(field4); } const std::map<std::set<float>, int32_t>& Struct15::get_field6() const& { return field6; } std::map<std::set<float>, int32_t> Struct15::get_field6() && { return std::move(field6); } const ::example::thrift29::Struct4& Struct15::get_field7() const& { return field7; } ::example::thrift29::Struct4 Struct15::get_field7() && { return std::move(field7); } const std::map<std::string, std::map<std::map<std::string, int16_t>, int8_t>>& Struct15::get_field8() const& { return field8; } std::map<std::string, std::map<std::map<std::string, int16_t>, int8_t>> Struct15::get_field8() && { return std::move(field8); } const std::map<int32_t, float>& Struct15::get_field11() const& { return field11; } std::map<int32_t, float> Struct15::get_field11() && { return std::move(field11); } void Struct15::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field5") { fid = 5; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field6") { fid = 6; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field7") { fid = 7; _ftype = apache::thrift::protocol::T_STRUCT; } else if (_fname == "field8") { fid = 8; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field9") { fid = 9; _ftype = apache::thrift::protocol::T_STRING; } else if (_fname == "field10") { fid = 10; _ftype = apache::thrift::protocol::T_BOOL; } else if (_fname == "field11") { fid = 11; _ftype = apache::thrift::protocol::T_MAP; } } void swap(Struct15& a, Struct15& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.field5, b.field5); swap(a.field6, b.field6); swap(a.field7, b.field7); swap(a.field8, b.field8); swap(a.field9, b.field9); swap(a.field10, b.field10); swap(a.field11, b.field11); swap(a.__isset, b.__isset); } template uint32_t Struct15::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct15::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct15::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct15::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct15::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct15::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct15::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct15::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct16::__clear() { // clear all fields field1.clear(); field2.clear(); field3.clear(); field4 = 0; field5.clear(); field6 = 0; field7 = 0; ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct0>::clear(&field8); __isset.__clear(); } bool Struct16::operator==(const Struct16& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!((field2 == rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!((field4 == rhs.field4))) { return false; } if (!((field5 == rhs.field5))) { return false; } if (!((field6 == rhs.field6))) { return false; } if (!((field7 == rhs.field7))) { return false; } if (!((field8 == rhs.field8))) { return false; } return true; } const std::vector<int32_t>& Struct16::get_field1() const& { return field1; } std::vector<int32_t> Struct16::get_field1() && { return std::move(field1); } const std::map<double, std::string>& Struct16::get_field2() const& { return field2; } std::map<double, std::string> Struct16::get_field2() && { return std::move(field2); } const std::vector<std::string>& Struct16::get_field3() const& { return field3; } std::vector<std::string> Struct16::get_field3() && { return std::move(field3); } const std::set<std::map<float, std::set<float>>>& Struct16::get_field5() const& { return field5; } std::set<std::map<float, std::set<float>>> Struct16::get_field5() && { return std::move(field5); } const ::example::thrift29::Struct0& Struct16::get_field8() const& { return field8; } ::example::thrift29::Struct0 Struct16::get_field8() && { return std::move(field8); } void Struct16::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_LIST; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_I16; } else if (_fname == "field5") { fid = 5; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field6") { fid = 6; _ftype = apache::thrift::protocol::T_I64; } else if (_fname == "field7") { fid = 7; _ftype = apache::thrift::protocol::T_BYTE; } else if (_fname == "field8") { fid = 8; _ftype = apache::thrift::protocol::T_STRUCT; } } void swap(Struct16& a, Struct16& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.field5, b.field5); swap(a.field6, b.field6); swap(a.field7, b.field7); swap(a.field8, b.field8); swap(a.__isset, b.__isset); } template uint32_t Struct16::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct16::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct16::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct16::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct16::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct16::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct16::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct16::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29 namespace example { namespace thrift29 { void Struct17::__clear() { // clear all fields field1.clear(); field2 = 0; field3 = 0; field4 = 0; field5.clear(); field6 = 0; ::apache::thrift::Cpp2Ops< ::example::thrift29::Struct1>::clear(&field7); __isset.__clear(); } bool Struct17::operator==(const Struct17& rhs) const { if (!((field1 == rhs.field1))) { return false; } if (!((field2 == rhs.field2))) { return false; } if (!((field3 == rhs.field3))) { return false; } if (!((field4 == rhs.field4))) { return false; } if (!((field5 == rhs.field5))) { return false; } if (!((field6 == rhs.field6))) { return false; } if (!((field7 == rhs.field7))) { return false; } return true; } const std::set<std::string>& Struct17::get_field1() const& { return field1; } std::set<std::string> Struct17::get_field1() && { return std::move(field1); } const std::map<int16_t, bool>& Struct17::get_field5() const& { return field5; } std::map<int16_t, bool> Struct17::get_field5() && { return std::move(field5); } const ::example::thrift29::Struct1& Struct17::get_field7() const& { return field7; } ::example::thrift29::Struct1 Struct17::get_field7() && { return std::move(field7); } void Struct17::translateFieldName(FOLLY_MAYBE_UNUSED folly::StringPiece _fname, FOLLY_MAYBE_UNUSED int16_t& fid, FOLLY_MAYBE_UNUSED apache::thrift::protocol::TType& _ftype) { if (false) {} else if (_fname == "field1") { fid = 1; _ftype = apache::thrift::protocol::T_SET; } else if (_fname == "field2") { fid = 2; _ftype = apache::thrift::protocol::T_BYTE; } else if (_fname == "field3") { fid = 3; _ftype = apache::thrift::protocol::T_DOUBLE; } else if (_fname == "field4") { fid = 4; _ftype = apache::thrift::protocol::T_I16; } else if (_fname == "field5") { fid = 5; _ftype = apache::thrift::protocol::T_MAP; } else if (_fname == "field6") { fid = 6; _ftype = apache::thrift::protocol::T_I32; } else if (_fname == "field7") { fid = 7; _ftype = apache::thrift::protocol::T_STRUCT; } } void swap(Struct17& a, Struct17& b) { using ::std::swap; swap(a.field1, b.field1); swap(a.field2, b.field2); swap(a.field3, b.field3); swap(a.field4, b.field4); swap(a.field5, b.field5); swap(a.field6, b.field6); swap(a.field7, b.field7); swap(a.__isset, b.__isset); } template uint32_t Struct17::read<>(apache::thrift::BinaryProtocolReader*); template uint32_t Struct17::write<>(apache::thrift::BinaryProtocolWriter*) const; template uint32_t Struct17::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct17::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; template uint32_t Struct17::read<>(apache::thrift::CompactProtocolReader*); template uint32_t Struct17::write<>(apache::thrift::CompactProtocolWriter*) const; template uint32_t Struct17::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; template uint32_t Struct17::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; }} // example::thrift29
25.961593
174
0.643283
eduardo-elizondo
b4ef7c031157588e415f48dafcc37be25e029c67
17,337
cpp
C++
ALIZE_3.0/src/ViterbiAccum.cpp
ibillxia/VoicePrintReco
20bf32f183abcd483fe1da451b4c75cf995b5f26
[ "MIT" ]
83
2015-01-18T01:20:37.000Z
2022-03-02T20:15:27.000Z
ALIZE_3.0/src/ViterbiAccum.cpp
Dystopiaz/VoicePrintReco
20bf32f183abcd483fe1da451b4c75cf995b5f26
[ "MIT" ]
4
2016-03-03T08:43:00.000Z
2019-03-08T06:20:56.000Z
ALIZE_3.0/src/ViterbiAccum.cpp
Dystopiaz/VoicePrintReco
20bf32f183abcd483fe1da451b4c75cf995b5f26
[ "MIT" ]
59
2015-02-02T03:07:37.000Z
2021-11-22T12:05:42.000Z
/* This file is part of ALIZE which is an open-source tool for speaker recognition. ALIZE 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 3 of the License, or any later version. ALIZE 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 ALIZE. If not, see <http://www.gnu.org/licenses/>. ALIZE is a development project initiated by the ELISA consortium [alize.univ-avignon.fr/] and funded by the French Research Ministry in the framework of the TECHNOLANGUE program [www.technolangue.net] The ALIZE project team wants to highlight the limits of voice authentication in a forensic context. The "Person Authentification by Voice: A Need of Caution" paper proposes a good overview of this point (cf. "Person Authentification by Voice: A Need of Caution", Bonastre J.F., Bimbot F., Boe L.J., Campbell J.P., Douglas D.A., Magrin- chagnolleau I., Eurospeech 2003, Genova]. The conclusion of the paper of the paper is proposed bellow: [Currently, it is not possible to completely determine whether the similarity between two recordings is due to the speaker or to other factors, especially when: (a) the speaker does not cooperate, (b) there is no control over recording equipment, (c) recording conditions are not known, (d) one does not know whether the voice was disguised and, to a lesser extent, (e) the linguistic content of the message is not controlled. Caution and judgment must be exercised when applying speaker recognition techniques, whether human or automatic, to account for these uncontrolled factors. Under more constrained or calibrated situations, or as an aid for investigative purposes, judicious application of these techniques may be suitable, provided they are not considered as infallible. At the present time, there is no scientific process that enables one to uniquely characterize a person=92s voice or to identify with absolute certainty an individual from his or her voice.] Contact Jean-Francois Bonastre for more information about the licence or the use of ALIZE Copyright (C) 2003-2010 Laboratoire d'informatique d'Avignon [lia.univ-avignon.fr] ALIZE admin [alize@univ-avignon.fr] Jean-Francois Bonastre [jean-francois.bonastre@univ-avignon.fr] */ #if !defined(ALIZE_ViterbiAccum_cpp) #define ALIZE_ViterbiAccum_cpp #include <iostream> #include <new> #include "Object.h" #include "ViterbiAccum.h" #include "Exception.h" #include "Mixture.h" #include "Feature.h" #include "Config.h" #include "MixtureStat.h" #include "StatServer.h" using namespace alize; //------------------------------------------------------------------------- ViterbiAccum::ViterbiAccum(StatServer& ss, const Config& c) :Object(), _pConfig(&c), _pStatServer(&ss) { reset(); } //------------------------------------------------------------------------- ViterbiAccum& ViterbiAccum::create(StatServer& ss, const Config& c, const K&) { ViterbiAccum* p = new (std::nothrow) ViterbiAccum(ss, c); assertMemoryIsAllocated(p, __FILE__, __LINE__); return *p; } //------------------------------------------------------------------------- void ViterbiAccum::addState(Mixture& m) { _stateVect.addObject(const_cast<Mixture&>(m)); unsigned long size = _stateVect.size(); _transMatrix.setSize(size*size); } //------------------------------------------------------------------------- real_t& ViterbiAccum::logTransition(unsigned long i, unsigned long j) { unsigned long size = _stateVect.size(); if (i >= size) throw IndexOutOfBoundsException("", __FILE__, __LINE__, i, size); if (j >= size) throw IndexOutOfBoundsException("", __FILE__, __LINE__, i, size); return _transMatrix[j*size + i]; } //------------------------------------------------------------------------- real_t ViterbiAccum::logTransition(unsigned long i, unsigned long j) const { return const_cast<ViterbiAccum*>(this)->logTransition(i, j); } //------------------------------------------------------------------------- Mixture& ViterbiAccum::getState(unsigned long i) const { return _stateVect.getObject(i); } //------------------------------------------------------------------------- unsigned long ViterbiAccum::getStateCount() const { return _stateVect.size(); } //------------------------------------------------------------------------- //------------------------------------------------------------------------- void ViterbiAccum::reset() { _tmpTab.clear(); _llpVect.clear(); _llpDefined = false; _pathDefined = false; _featureCount = 0; } //------------------------------------------------------------------------- void ViterbiAccum::computeAndAccumulate(const Feature& f, double llkW) { unsigned long i, j, nbStates = _stateVect.size(); _llpDefined = _pathDefined = false; // compute llk between the feature and each state _tmpLLKVect.clear(); for (i=0; i<nbStates; i++) //_tmpLLKVect.addValue(_mixtureStatVect.getObject(i).computeLLK(f)-llkW); _tmpLLKVect.addValue(computeStateLLK(i, f)-llkW); // if (_featureCount == 0) // if first feature _llpVect = _tmpLLKVect; else { _tmpllpVect.clear(); unsigned long maxInd = 0; real_t maxllp = 0; for (i=0; i<nbStates; i++) { for (j=0; j<nbStates; j++) { real_t llp = _llpVect[j] + _tmpLLKVect[i] + logTransition(j, i); if (j == 0 || llp > maxllp) { maxllp = llp; maxInd = j; } } _tmpllpVect.addValue(maxllp); _tmpTab.addValue(maxInd); } _llpVect = _tmpllpVect; } _featureCount++; } //------------------------------------------------------------------------- void ViterbiAccum::computeAndAccumulate(FeatureServer& fs, DoubleVector& llkW, unsigned long start, unsigned long count) { unsigned long i, j, nbStates = _stateVect.size(); _llpDefined = _pathDefined = false; double l; Feature f; // compute llk between the feature and each state _tmpLLKVect.clear(); for (i=0; i<nbStates; i++) { l = 0.0; fs.seekFeature(start); for (unsigned long ifeature=start; ifeature < (start+count); ifeature++) { fs.readFeature(f); l += computeStateLLK(i, f) -llkW[ifeature]+logTransition(i,i); } _tmpLLKVect.addValue(l/count); //cout << "start: " << start << " & count: " << count << " Etat " << i << " => " << l/count << endl; } if (_featureCount == 0) // if first feature in the viterbi path { _llpVect = _tmpLLKVect; for(unsigned long c=0; c<count; c++) for (i=0; i<nbStates; i++) _tmpTab.addValue(i); } else { _tmpllpVect.clear(); unsigned long maxInd = 0; real_t maxllp = 0; real_t llp; // For the first frame of the n block (n>0)- find the path for (i=0; i<nbStates; i++) { for (j=0; j<nbStates; j++) { llp = _llpVect[j] + _tmpLLKVect[i] + logTransition(j, i); if (j == 0 || llp > maxllp) { maxllp = llp; maxInd = j; } } _tmpllpVect.addValue(maxllp); _tmpTab.addValue(maxInd); } for(unsigned long c=1; c<count; c++) for (i=0; i<nbStates; i++) _tmpTab.addValue(i); _llpVect = _tmpllpVect; } _featureCount+=count; //cout << " FeatureCount: " << _featureCount << endl; } //------------------------------------------------------------------------- void ViterbiAccum::computeAndAccumulate(FeatureServer& fs, unsigned long start, unsigned long count, double fudge) { unsigned long i, j, nbStates = _stateVect.size(); _llpDefined = _pathDefined = false; double l; Feature f; // compute llk between the feature and each state _tmpLLKVect.clear(); for (i=0; i<nbStates; i++) { l = 0.0; fs.seekFeature(start); for (unsigned long ifeature=start; ifeature < (start+count); ifeature++) { fs.readFeature(f); l += computeStateLLK(i, f); } _tmpLLKVect.addValue(l/count); // cout << "start: " << start << " & count: " << count << " Etat " << i << " => " << l/count << endl; } if (_featureCount == 0) // if first feature in the viterbi path { _llpVect = _tmpLLKVect; for(unsigned long c=0; c<count; c++) for (i=0; i<nbStates; i++) _tmpTab.addValue(i); } else { _tmpllpVect.clear(); unsigned long maxInd = 0; real_t maxllp = 0; real_t llp; // For the first frame of the n block (n>0)- find the path for (i=0; i<nbStates; i++) { for (j=0; j<nbStates; j++) { llp = _llpVect[j] + _tmpLLKVect[i] + logTransition(j, i)*fudge; if (j == 0 || llp > maxllp) { maxllp = llp; maxInd = j; } } _tmpllpVect.addValue(maxllp); _tmpTab.addValue(maxInd); } for(unsigned long c=1; c<count; c++) for (i=0; i<nbStates; i++) _tmpTab.addValue(i); _llpVect = _tmpllpVect; } _featureCount+=count; //cout << " FeatureCount: " << _featureCount << endl; } /*//------------------------------------------------------------------------- void ViterbiAccum::computeAndAccumulate(FeatureServer *fs, DoubleVector& llkW, int start, int count) //------------------------------------------------------------------------- { unsigned long i, j, nbStates = _stateVect.size(); _llpDefined = _pathDefined = false; double l; // compute llk between the feature and each state _tmpLLKVect.clear(); for (i=0; i<nbStates; i++){ l = 0.0; for(int ifeature=start; ifeature < (start+count); ifeature++){ Feature& f=fs->getFeature(ifeature); l += computeStateLLK(i, f)-llkW[ifeature]; } _tmpLLKVect.addValue(l/count); //cout << "start: " << start << " & count: " << count << " Etat " << i << " => " << l/count << endl; } if (_featureCount == 0){ // if first feature _llpVect = _tmpLLKVect; for(int c=0; c<count; c++){ for (i=0; i<nbStates; i++){ _tmpTab.addValue(i); } } } else { _tmpllpVect.clear(); unsigned long maxInd = 0; real_t maxllp = 0; real_t llp; for(int c=0; c<count; c++){ if(c==0){ for (i=0; i<nbStates; i++){ for (j=0; j<nbStates; j++){ llp = _llpVect[j] + _tmpLLKVect[i] + logTransition(j, i); if (j == 0 || llp > maxllp){ maxllp = llp; maxInd = j; } } _tmpllpVect.addValue(maxllp); _tmpTab.addValue(maxInd); } } else{ for (i=0; i<nbStates; i++){ _tmpTab.addValue(i); } } } _llpVect = _tmpllpVect; } _featureCount+=count; //cout << " FeatureCount: " << _featureCount << endl; } */ //------------------------------------------------------------------------- /*void ViterbiAccum::computeAndAccumulate(FeatureServer *fs, DoubleVector& llkW, int start, int count) //------------------------------------------------------------------------- { unsigned long i, j, nbStates = _stateVect.size(); _llpDefined = _pathDefined = false; double l; // compute llk between the feature and each state _tmpLLKVect.clear(); cout << count << " " << start << endl; for(int c=0, ifeature=start; c<count; c++, ifeature++){ Feature& f=fs->getFeature(ifeature); for (i=0; i<nbStates; i++){ l = computeStateLLK(i, f)-llkW[ifeature]; cout << c << " => " << l << endl; _tmpLLKVect.addValue(l); } if (_featureCount == 0){ // if first feature _llpVect = _tmpLLKVect; for (i=0; i<nbStates; i++){ _tmpTab.addValue(i); } } else{ _tmpllpVect.clear(); unsigned long maxInd = 0; real_t maxllp = 0; real_t llp; if(c==0){ for (i=0; i<nbStates; i++){ for (j=0; j<nbStates; j++){ llp = _llpVect[j] + _tmpLLKVect[i] + logTransition(j, i); if (j == 0 || llp > maxllp){ maxllp = llp; maxInd = j; } } _tmpllpVect.addValue(maxllp); _tmpTab.addValue(maxInd); } } else{ for (i=0; i<nbStates; i++){ llp = _llpVect[i] + _tmpLLKVect[i] + logTransition(i, i); _tmpllpVect.addValue(llp); _tmpTab.addValue(i); } } _llpVect = _tmpllpVect; } }//fin for(int c=0... _featureCount+=count; //cout << " FeatureCount: " << _featureCount << endl; } */ //------------------------------------------------------------------------- void ViterbiAccum::computeAndAccumulate(const Feature& f, double fudge, double penality) //------------------------------------------------------------------------- { unsigned long i, j, nbStates = _stateVect.size(); _llpDefined = _pathDefined = false; // compute llk between the feature and each state _tmpLLKVect.clear(); for (i=0; i<nbStates; i++) _tmpLLKVect.addValue(computeStateLLK(i, f)); // if (_featureCount == 0) // if first feature _llpVect = _tmpLLKVect; else { _tmpllpVect.clear(); unsigned long maxInd = 0; real_t maxllp = 0; for (i=0; i<nbStates; i++) { for (j=0; j<nbStates; j++) { real_t llp = _llpVect[j] + _tmpLLKVect[i] + fudge * logTransition(j, i); if(i != j) llp += penality; if (j == 0 || llp > maxllp) { maxllp = llp; maxInd = j; } } _tmpllpVect.addValue(maxllp); _tmpTab.addValue(maxInd); } _llpVect = _tmpllpVect; } _featureCount++; } //------------------------------------------------------------------------- unsigned long ViterbiAccum::getFeatureCount() const {return _featureCount;} //------------------------------------------------------------------------- const ULongVector& ViterbiAccum::getPath() { if (!_pathDefined) { unsigned long i, max = 0, nbStates = _stateVect.size(); // looks for the largest llp for (i=0; i<nbStates; i++){ if (_llpVect[i] > _llpVect[max]) max = i; } _llp = _llpVect[max]; _llpDefined = true; _path.setSize(_featureCount); if (_featureCount != 0) { for (i=_featureCount-1; i>0; i--) { _path[i] = max; max = _tmpTab[(i-1)*nbStates+max]; } _path[0] = max; } _pathDefined = true; } return _path; } //------------------------------------------------------------------------- real_t ViterbiAccum::getLlp() const { if (!_llpDefined) throw Exception("llp undefined", __FILE__, __LINE__); return _llp; } //------------------------------------------------------------------------- lk_t ViterbiAccum::computeStateLLK(unsigned long i, const Feature& f) const { return _pStatServer->computeLLK(_stateVect.getObject(i), f); } //------------------------------------------------------------------------- //------------------------------------------------------------------------- String ViterbiAccum::getClassName() const { return "ViterbiAccum"; } //------------------------------------------------------------------------- String ViterbiAccum::toString() const { unsigned long i, nbStates = getStateCount(); String s = Object::toString() + " Nb States = " + String::valueOf(nbStates) + " Nb features = " + String::valueOf(_featureCount); for (i=0; i<nbStates; i++) { for (unsigned long j=0; j<nbStates; j++) s += "\n Log transition " + String::valueOf(i) + "->" + String::valueOf(j) + " = " + String::valueOf(logTransition(i, j)); } if (_llpDefined) s += "\n llp = " + String::valueOf(_llp); else s += "\n llp = undefined"; if (_pathDefined) for (i=0; i<_featureCount; i++) s += "\n path[" + String::valueOf(i) + "]" + " = " + String::valueOf(_path[i]); else s += "\n path = undefined"; return s; } //------------------------------------------------------------------------- ViterbiAccum::~ViterbiAccum() {} //------------------------------------------------------------------------- #endif // !defined(ALIZE_ViterbiAccum_cpp)
32.588346
106
0.515314
ibillxia
b4f20f4cad28d63a0bc2a8eb9a9607e32b4e31a4
625
cpp
C++
Project_GPS/parametres.cpp
yoannvigolo/Genetique_GPS
05f70d3a3eadc14eb6e653d29bfbf03767f01eb6
[ "BSD-3-Clause" ]
null
null
null
Project_GPS/parametres.cpp
yoannvigolo/Genetique_GPS
05f70d3a3eadc14eb6e653d29bfbf03767f01eb6
[ "BSD-3-Clause" ]
null
null
null
Project_GPS/parametres.cpp
yoannvigolo/Genetique_GPS
05f70d3a3eadc14eb6e653d29bfbf03767f01eb6
[ "BSD-3-Clause" ]
null
null
null
#include "parametres.h" using namespace std; Parametres::Parametres() { } int Parametres::individualsNb = 200; int Parametres::generationsMaxNb = 3; int Parametres::initialGenesNb = 5; int Parametres::minFitness = 15; double Parametres::mutationRate = 1; double Parametres::mutationAddRate = 0.2; double Parametres::mutationDeleteRate = 0.1; double Parametres::crossoverRate = 0.6; // TODO : modifier la graine MyRandom *Parametres::randomGenerator=new MyRandom(); int Parametres::debug = 1; void Parametres::print(QString txt, int d) { if(d<debug) cout<<txt.toStdString()<<endl; }
23.148148
54
0.7072
yoannvigolo
b4f2dd27f34b09ef67816532815f861b6bcd0b0c
11,255
hpp
C++
src/asm.hpp
Azegor/mjc
8b7eaca7e2079378d99a2a6fc7f6076976922dab
[ "MIT" ]
3
2019-08-09T00:57:22.000Z
2020-06-18T23:03:05.000Z
src/asm.hpp
Azegor/mjc
8b7eaca7e2079378d99a2a6fc7f6076976922dab
[ "MIT" ]
null
null
null
src/asm.hpp
Azegor/mjc
8b7eaca7e2079378d99a2a6fc7f6076976922dab
[ "MIT" ]
null
null
null
#ifndef ASM_H #define ASM_H #include <memory> #include <ostream> #include <iostream> #include <sstream> #include <string> #include <typeinfo> #include <vector> #include <unordered_map> #include <cassert> #include <cstdint> #include <cstring> #include <libfirm/firm.h> namespace Asm { using namespace std::string_literals; // enum class OperandType : uint8_t { // Reg, // value from register // Mem, // value from constant memory adress // Indirect, // value from addres in register // Const, // (immediate) constant value // LocLabel, // label of basic block // GlobLabel, // name of function // }; struct Mnemonic { uint32_t opcode; const char *const name; }; extern const Mnemonic *Foo; //= new Mnemonic{0, "foo"}; extern const Mnemonic *Add; extern const Mnemonic *Sub; extern const Mnemonic *IMul; extern const Mnemonic *Div; extern const Mnemonic *Call; extern const Mnemonic *Cmp; extern const Mnemonic *Neg; extern const Mnemonic *Je; extern const Mnemonic *Jne; extern const Mnemonic *Jmp; extern const Mnemonic *Jg; extern const Mnemonic *Jge; extern const Mnemonic *Jl; extern const Mnemonic *Jle; extern const Mnemonic *Inc; extern const Mnemonic *Dec; extern const Mnemonic *Xor; extern const Mnemonic *Mov; extern const Mnemonic *Movq; extern const Mnemonic *Movl; extern const Mnemonic *Movb; extern const Mnemonic *Movslq; extern const Mnemonic *Cqto; extern const Mnemonic *Label; enum class RegName : uint8_t { ax, bx, cx, dx, bp, sp, si, di, r8, r9, r10, r11, r12, r13, r14, r15, }; enum class RegMode : uint8_t { R, // 64 bit E, // 32 bit L, // 8 bit lower part }; RegMode getRegMode(ir_node *node); const char *getRegAsmName(const RegName name, const RegMode mode); enum OpType { OP_IMM, OP_REG, OP_IND, OP_STR, OP_NONE }; struct Op { private: struct _imm { int value; }; struct _str { std::string *str = nullptr; }; struct _reg { RegName name; RegMode mode; }; struct _ind { RegName base; RegMode mode; int32_t offset; }; public: OpType type = OP_NONE; union { _imm imm; _str str; _reg reg; _ind ind; }; Op() { type = OP_NONE; str.str = nullptr; } Op(int v) { type = OP_IMM; imm.value = v; } Op(RegName regName, RegMode regMode) { type = OP_REG; reg.name = regName; reg.mode = regMode; } Op(RegName base, RegMode mode, int offset) { type = OP_IND; ind.base = base; ind.mode = mode; ind.offset = offset; } Op(const Op &src, int offset) { if (src.type == OP_IND) { type = OP_IND; ind.base = src.ind.base; ind.mode = src.ind.mode; ind.offset = offset; } else if (src.type == OP_REG) { type = OP_IND; ind.base = src.reg.name; ind.mode = src.reg.mode; ind.offset = offset; } else assert(false); } Op(const std::string &s) { type = OP_STR; str.str = new std::string(s); } Op(const Op &op) { type = op.type; switch(op.type) { case OP_IMM: imm.value = op.imm.value; break; case OP_REG: reg = op.reg; break; case OP_IND: ind = op.ind; break; case OP_STR: if (op.str.str != nullptr) { str.str = new std::string(*op.str.str); } break; case OP_NONE: break; default: assert(false); } } ~Op() { if (type == OP_STR && str.str != nullptr) { delete str.str; } } Op &operator=(const Op& other) { if (type == OP_STR && str.str != nullptr) delete str.str; type = other.type; switch(type) { case OP_IMM: imm.value = other.imm.value; break; case OP_REG: reg = other.reg; break; case OP_IND: ind = other.ind; break; case OP_STR: str.str = new std::string(*other.str.str); break; default: assert(false); } return *this; } Op &operator=(Op&& other) { if (type == OP_STR && str.str != nullptr) delete str.str; type = other.type; switch(type) { case OP_IMM: imm.value = other.imm.value; break; case OP_REG: reg = other.reg; break; case OP_IND: ind = other.ind; break; case OP_STR: str.str = new std::string(*other.str.str); break; default: {} } return *this; } }; std::ostream &operator<<(std::ostream &o, const Op &op); struct Instr { Op ops[2]; int nOps = -1; const Mnemonic *mnemonic; std::string comment; Instr(const Mnemonic *mne) { mnemonic = mne; nOps = 0; } Instr(const Mnemonic *mne, Op op1, Op op2, std::string c = ""s) { mnemonic = mne; nOps = 2; ops[0] = std::move(op1); ops[1] = std::move(op2); comment = std::move(c); } Instr(const Mnemonic *mne, Op op1, std::string c = ""s) { mnemonic = mne; nOps = 1; ops[0] = std::move(op1); comment = std::move(c); } bool isJmp() const { return mnemonic == Jmp || mnemonic == Je || mnemonic == Jne || mnemonic == Jg || mnemonic == Jge || mnemonic == Jl || mnemonic == Jle; } bool isMov() const { return mnemonic == Mov || mnemonic == Movq || mnemonic == Movl || mnemonic == Movb; } }; std::ostream &operator<<(std::ostream &o, const Instr &instr); // Convenience factory functions to create instructions/operands Instr makeJump(const std::string target, ir_relation relation); Instr makeMov(const RegMode mode, Op source, Op dest, std::string comment = ""s); Op rax(); Op rbx(); Op rcx(); Op rbp(); Op rsp(); /// Memory is adressed the following way: /// segment-override:signed-offset(base,index,scale) /// variations: (be carefull wich are missing!) /// (base) /// (index, scale) /// (base,index,scale) /// signed-offset(base) /// signed-offset(base,index) /// signed-offset(index, scale) /// offset and scale can always be specified (0 and 1 respectively) -> no extra classes /// have Base, BaseIndex, IndexScale, BaseIndexScale class AsmWriter { std::ostream &out; public: AsmWriter(std::ostream &o) : out(o) {} void write() { writeTextSection(); } void writeTextSection(); void writeText(const std::string &text) { out << text << '\n'; } void writeString(const std::string &str) { out << '\t' << str << '\n'; } void writeLabel(const std::string l) { out << l << ":\n"; } void writeComment(const std::string &comment) { out << "/* -- " << comment << " */\n"; } void writeInstr(const Instr &instr) { if (instr.mnemonic != Label) out << '\t'; out << instr << '\n'; } }; std::string getBlockLabel(ir_node *node); class BasicBlock { std::string comment; ir_node *node; std::vector<Instr> startPhiInstrs; std::vector<Instr> phiInstrs; public: std::vector<Instr> instrs; std::vector<Instr> jumpInstrs; // Keep this separate for debugging std::vector<Instr> flattenedInstrs; BasicBlock(ir_node *node, std::string comment = ""s) : comment(std::move(comment)), node(node) {} BasicBlock(BasicBlock &&bb) = default; void flattenInstrs() { assert(flattenedInstrs.size() == 0); // So far, we have several lists of instructions, now // flatten them all to one list. for (auto &instr : startPhiInstrs) { flattenedInstrs.push_back(instr); } for (auto &instr : instrs) { flattenedInstrs.push_back(instr); } for (auto &instr : phiInstrs) { flattenedInstrs.push_back(instr); } for (auto &instr : jumpInstrs) { flattenedInstrs.push_back(instr); } } void pushInstr(const Instr instr) { instrs.push_back(std::move(instr)); } template<typename... Args> void pushInstr(Args &&... args) { instrs.push_back(Asm::Instr(std::forward<Args>(args)...)); } template<typename... Args> void pushJumpInstr(Args &&... args) { jumpInstrs.push_back(Asm::Instr(std::forward<Args>(args)...)); } template<typename... Args> void pushPhiInstr(Args &&... args) { phiInstrs.push_back(Asm::Instr(std::forward<Args>(args)...)); } template<typename... Args> void pushStartPhiInstr(Args &&... args) { startPhiInstrs.push_back(Asm::Instr(std::forward<Args>(args)...)); } template<typename... Args> void replaceInstr(size_t index, Args &&... args) { assert(this->flattenedInstrs.size() == 0); instrs.at(index) = Instr(args...); } void replaceInstr(size_t index, Instr instr) { assert(this->flattenedInstrs.size() == 0); instrs.at(index) = std::move(instr); } template<typename... Args> void replaceFlattenedInstr(size_t index, Args &&... args) { assert(this->flattenedInstrs.size() > 0); flattenedInstrs.at(index) = Instr(args...); } void replaceFlattenedInstr(size_t index, Instr instr) { assert(this->flattenedInstrs.size() > 0); flattenedInstrs.at(index) = std::move(instr); } void removeInstr(size_t index) { assert(this->flattenedInstrs.size() == 0); this->instrs.erase(this->instrs.begin() + index); } void removeFlattenedInstr(size_t index) { assert(this->flattenedInstrs.size() > 0); this->flattenedInstrs.erase(this->flattenedInstrs.begin() + index); } void write(AsmWriter &writer) const { writer.writeLabel(getBlockLabel(node)); for (auto &instr : flattenedInstrs) { writer.writeInstr(instr); } } const std::string &getComment() const { return comment; } ir_node *getNode() { return node; } std::string getLabelStr() { return getBlockLabel(this->node); } }; class Function { std::string fnName; int ARsize = 0; public: std::vector<BasicBlock *> orderedBasicBlocks; std::unordered_map<ir_node *, BasicBlock *> basicBlocks; Function(std::string name) : fnName(std::move(name)) {} Function(Function &&) = default; ~Function () { for(auto bb : orderedBasicBlocks) delete bb; } void newBB(ir_node *node, std::string comment = ""s) { auto bb = new BasicBlock(node, comment); basicBlocks.insert({node, bb}); orderedBasicBlocks.push_back(bb); } BasicBlock *getBB(ir_node *node) { assert(is_Block(node)); if (basicBlocks.find(node) != basicBlocks.end()) { return basicBlocks.at(node); } return nullptr; } std::string getEpilogLabel() const { return fnName + "_epilog"; } void setARSize(int size) { ARsize = size; } int getARSize() { return ARsize; } void writeProlog(AsmWriter &writer) const; void writeEpilog(AsmWriter &writer) const; void write(AsmWriter &writer) const; }; struct Program { std::vector<Function> functions; public: void flattenFunctions() { for (auto &f : functions) { for (auto &b : f.orderedBasicBlocks) { b->flattenInstrs(); } } } void addFunction(Function f) { functions.emplace_back(std::move(f)); } friend std::ostream &operator<<(std::ostream &o, const Program &p) { AsmWriter writer(o); writer.writeTextSection(); for (auto &fn : p.functions) { fn.write(writer); } return o; } }; } #endif // ASM_H
21.644231
90
0.608885
Azegor
b4f2e18ffdcfe20549f8547ce881728eca9ee584
10,697
cpp
C++
native/PNG.cpp
Regal-Internet-Brothers/imageencoder
4b116d8ccedf9a5e29810eaa21985f6ff3b711b6
[ "MIT" ]
1
2015-02-10T21:08:19.000Z
2015-02-10T21:08:19.000Z
native/PNG.cpp
Regal-Internet-Brothers/imageencoder
4b116d8ccedf9a5e29810eaa21985f6ff3b711b6
[ "MIT" ]
null
null
null
native/PNG.cpp
Regal-Internet-Brothers/imageencoder
4b116d8ccedf9a5e29810eaa21985f6ff3b711b6
[ "MIT" ]
null
null
null
// Preprocessor related: // Libraries (MSVC): /* This is mainly for MSVC, the needed libraries have already been added for GCC/MinGW via 'CC_LIBS' in Monkey. Change the names of these libraries to reflect the versions you decide to use. */ #pragma comment(lib, "libpng16.lib") #pragma comment(lib, "zlib.lib") // Includes: // Standard libpng functionality. #include <png.h> // C standard library functionality: #include <cstdio> //#include <cstdlib> // Namespaces: namespace imageEncoder { namespace PNG { // Constant variable(s): // This acts as the internal bit-depth used for PNG encoding. static const int DEFAULT_IMAGE_DEPTH = 8; // 16; // Functions: /* In the event saving wasn't successful, this command will return 'false'. In the case of streams meant specifically for this, this should be an indicator to close the file-stream. The 'stream' argument should point to a standard C stream. This argument is not checked if it is 'NULL'. The 'imageData' argument should be an array of pixels, formatted according to the arguments you pass in. A standard raw RGBA bitmap is already in the proper format by default, and can be used without issues. The 'width' and 'height' arguments should specify the dimensions of the 'imageData' argument. This command is considered "unsafe" under specific situations; please read the 'save_to_file_safe' command's documentation. */ bool save_to_stream(FILE* stream, png_byte* imageData, size_t width, size_t height, int bit_depth=DEFAULT_IMAGE_DEPTH, int color_type=PNG_COLOR_TYPE_RGB_ALPHA, int interlace_type=PNG_INTERLACE_NONE, int compression_type=PNG_COMPRESSION_TYPE_DEFAULT, int filter_type=PNG_FILTER_TYPE_DEFAULT) { // Local variable(s): // I'm leaving these variables at the top, just for the // sake of better potential C compatibility: // For safety reasons, this has to be manually set to 'NULL'. png_byte** row_pointers = NULL; png_structp png_ptr; png_infop info_ptr; // Allocate the needed PNG data: // Attempt to allocate a "write-structure". png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); // Ensure we were able to allocate a "write-structure": if (png_ptr == NULL) { // Tell the user that we couldn't save to the output-stream. return false; } // Attempt to allocate an "info-structure". info_ptr = png_create_info_struct(png_ptr); // Ensure we were able to allocate an "info-structure": if (info_ptr == NULL) { // Since we were unable to create an "info-structure", we need to // destroy our already allocated "write-structure", then return 'false'. png_destroy_write_struct(&png_ptr, NULL); // Tell the user that we couldn't save to the output-stream. return false; } // Standard error handling: if (setjmp(png_jmpbuf(png_ptr))) { // Check if we should free the row-pointers: if (row_pointers != NULL) png_free(png_ptr, row_pointers); png_destroy_write_struct(&png_ptr, &info_ptr); // Tell the user that execution was not successful. return false; } // Assign the data specified to the "info-structure": png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, color_type, interlace_type, compression_type, filter_type); // Allocate an array of pointers for libpng's 'png_set_rows' command. // This is allocated on the heap due to its variable size. row_pointers = (png_byte**)png_malloc(png_ptr, height * sizeof(png_byte*)); // Initialize each row of the image: for (size_t y = 0; y < height; ++y) { //png_byte* row = (png_byte*)png_malloc(png_ptr, sizeof(png_byte) * width * sizeof(pixel)); row_pointers[y] = (png_byte*)(imageData + ((width * y) * sizeof(pixel))); // Deprecated: /* for (size_t x = 0; x < width; ++x) { pixel* pixel = pixel_at(imageData, width, x, y); *row++ = pixel->red; *row++ = pixel->green; *row++ = pixel->blue; *row++ = pixel->alpha; } */ } // Write and encode the image-data using the output-stream: png_init_io(png_ptr, stream); png_set_rows(png_ptr, info_ptr, row_pointers); png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL); // Free any heap-allocated data: // Deprecated: /* for (size_t y = 0; y < height; y++) { png_free(png_ptr, row_pointers[y]); } */ // Free the main PNG-data. // Free the row-pointers. png_free(png_ptr, row_pointers); // Destroy the PNG data we initially retrieved: // This will destroy both the "write-structure", and the "info-structure". png_destroy_write_struct(&png_ptr, &info_ptr); //png_destroy_info_struct(png_ptr, &info_ptr); // Return the default response. return true; } // This acts as a standard file/disk I/O wrapper for the main 'save_to_stream' function. // This command is considered "unsafe" under specific situations; // please read the 'save_to_file_safe' command's documentation. bool save_to_file(const character* path, png_byte* imageData, size_t width, size_t height, int bit_depth=DEFAULT_IMAGE_DEPTH, int color_type=PNG_COLOR_TYPE_RGB_ALPHA, int interlace_type=PNG_INTERLACE_NONE, int compression_type=PNG_COMPRESSION_TYPE_DEFAULT, int filter_type=PNG_FILTER_TYPE_DEFAULT) { // Local variable(s): // This will act as our file-descriptor. FILE* fp; // Attempt to open a file-stream. fp = fopen(path, "wb"); // Check if we could open a file-stream: if (!fp) // fp == NULL return false; // Execute the main routine. bool response = save_to_stream(fp, imageData, width, height, bit_depth, color_type, interlace_type, compression_type, filter_type); // Close the file descriptor. fclose(fp); // Return the calculated response. return response; } /* The following implementation is meant to be a "border-corssing-safe" version of 'save_to_file'. The problem with 'save_to_file' is that it uses standard C I/O, which is problematic when dealing with a DLL (With Visual Studio). This implementation is provided in order to delegate a "macro" of sorts provided by libpng, which provides limited encoding functionality. Visual C++ tends to hate dealing with the C standard library as far as DLLs go, so this is provided. Assuming you're on Windows, you're not using any custom encoding settings via Monkey, and 'IMAGEENCODER_PNG_PREFER_SAFETY' is defined as 'True' by Monkey's preprocessor, this will act as the default implementation. Support for 'color_type' is more or less available. */ bool save_to_file_safe(const character* path, png_byte* imageData, png_uint_32 width, png_uint_32 height, int depth=DEFAULT_IMAGE_DEPTH, int color_type=PNG_COLOR_TYPE_RGB_ALPHA, png_int_32 internal__row_stride=0) { // Local variable(s): int format; // Attempt to re-encode the color-type specified into proper flags: switch (color_type) { case PNG_COLOR_TYPE_GRAY: format = PNG_FORMAT_GRAY; break; case PNG_COLOR_TYPE_GA: format = PNG_FORMAT_GA; break; case PNG_COLOR_TYPE_RGB: format = PNG_FORMAT_RGB; break; case PNG_COLOR_TYPE_RGBA: format = PNG_FORMAT_RGBA; break; default: return false; //break; } // This acts as the standard container used for image I/O. png_image img; // "Zero-out" the structure before doing anything else. memset(&img, 0, sizeof(img)); img.width = width; img.height = height; img.format = format; img.version = PNG_IMAGE_VERSION; // Write and encode the image-data to the file-path specified, then return an appropriate response. return (png_image_write_to_file(&img, path, (int)(depth == 16), (const void*)imageData, internal__row_stride, NULL) != 0); } /* These act as the Monkey-wrappers for the main implementation of 'save_to_file_safe', which are needed in specific situations. These wrappers are only delegated when the 'IMAGEENCODER_PNG_PREFER_SAFETY' variable is defined as 'True' with Monkey's preprocessor. */ #if defined(CFG_IMAGEENCODER_PNG_PREFER_SAFETY) bool save_to_file_safe(String path, BBDataBuffer* imageData, int width, int height, int imageData_Offset_InBytes=0, int depth=DEFAULT_IMAGE_DEPTH, int color_type=PNG_COLOR_TYPE_RGB_ALPHA) { return save_to_file_safe(toCString(path), readPointer<png_byte>(imageData, (size_t)imageData_Offset_InBytes), (png_uint_32)width, (png_uint_32)height, depth, color_type); } #if defined(CFG_IMAGEENCODER_PNG_EXPERIMENTAL) bool save_to_file_safe(String path, Array<int> imageData, int width, int height, int imageData_Offset=0, int depth=DEFAULT_IMAGE_DEPTH, int color_type=PNG_COLOR_TYPE_RGB_ALPHA) { return save_to_file_safe(toCString(path), readPointer<png_byte, int>(imageData, (size_t)imageData_Offset), (png_uint_32)width, (png_uint_32)height, depth, color_type); } #endif #endif // This acts as the Monkey-wrapper for the main implementation of 'save_to_file': // The 'imageData_Offset_InBytes' argument is technically dependent on the size of 'png_byte'. bool save_to_file(String path, BBDataBuffer* imageData, int width, int height, int imageData_Offset_InBytes=0, int bit_depth=DEFAULT_IMAGE_DEPTH, int color_type=PNG_COLOR_TYPE_RGB_ALPHA, int interlace_type=PNG_INTERLACE_NONE, int compression_type=PNG_COMPRESSION_TYPE_DEFAULT, int filter_type=PNG_FILTER_TYPE_DEFAULT) { return save_to_file(toCString(path), readPointer<png_byte>(imageData, (size_t)imageData_Offset_InBytes), (size_t)width, (size_t)height, bit_depth, color_type, interlace_type, compression_type, filter_type); } #if defined(CFG_IMAGEENCODER_PNG_EXPERIMENTAL) // This acts as an experimental Monkey-wrapper for the main implementation of 'save_to_file': // This currently uses non-standard means of retrieving data. bool save_to_file(String path, Array<int> imageData, int width, int height, int imageData_Offset=0, int bit_depth=DEFAULT_IMAGE_DEPTH, int color_type=PNG_COLOR_TYPE_RGB_ALPHA, int interlace_type=PNG_INTERLACE_NONE, int compression_type=PNG_COMPRESSION_TYPE_DEFAULT, int filter_type=PNG_FILTER_TYPE_DEFAULT) { return save_to_file(toCString(path), readPointer<png_byte, int>(imageData, (size_t)imageData_Offset), (size_t)width, (size_t)height, bit_depth, color_type, interlace_type, compression_type, filter_type); } #endif } }
35.42053
319
0.713191
Regal-Internet-Brothers
b4f6033c1c70c9a4ac302fe3121b058954e22f83
1,759
cpp
C++
图论/负环/acwing_904.cpp
tempure/algorithm-advance
38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b
[ "MIT" ]
3
2020-11-16T08:58:30.000Z
2020-11-16T08:58:33.000Z
图论/负环/acwing_904.cpp
tempure/algorithm-advance
38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b
[ "MIT" ]
null
null
null
图论/负环/acwing_904.cpp
tempure/algorithm-advance
38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <cstring> #include <cstdio> using namespace std; //常用2种spfa求负环的方法,常用的是第二种 //统计每个点入队的次数 如果某个点入队n次 那么存在负环 //统计当前每个点的最短路中所包含的边数 如果某个点的 最短路包含的边数>=n 那么有能说明存在负环 //注意虫洞是单向边 const int N = 510, M = 5500; int n, m1, m2; //m1 双向边和单向边的数量 int h[N], ne[M], w[M], e[M], idx; int dist[N]; int q[N], cnt[N]; bool st[N]; void add(int a, int b, int c){ e[idx] = b; ne[idx] = h[a]; w[idx] = c; h[a] = idx ++; } bool spfa(){ int hh = 0, tt = 0; memset(dist, 0, sizeof dist); //注意在求负环中 由于虚拟原点的思路 每个点和原点的距离 都初始化为0 memset(st, 0, sizeof st); memset(cnt, 0, sizeof cnt); for(int i = 1; i <= n; i++){ q[tt++] = i; st[i] = true; //所有点都全部入队 } while(hh != tt){ int t = q[hh++]; if(hh==N) hh = 0; st[t] = false; //不在队列里面就是false for(int i = h[t]; i!= -1; i = ne[i]){ int j =e[i]; if(dist[j] > dist[t] + w[i]){ dist[j] = dist[t] + w[i]; cnt[j] = cnt[t] + 1; if(cnt[j] >= n) return true; if(!st[j]){ q[tt++] = j; if(tt == N) tt= 0; st[j] = true; } } } } return false; //不存在负环 } int main(){ int t; cin >> t; while(t --){ cin >> n >> m1 >> m2; memset(h, -1, sizeof h); idx = 0; while(m1 --){ int a, b, c; cin >> a >> b >> c; add(a, b ,c), add(b, a, c); } while(m2 --){ int a, b, c; cin >> a >> b >> c; add(a, b, -c); //注意是负边 } if(spfa()) puts("YES"); else puts("NO"); } return 0; }
21.192771
71
0.409892
tempure
b4f9c57442c3251c15ea0df5ebccfe73e446086b
2,734
cpp
C++
src/algo/shortest_path.cpp
setyolegowo/ITB-IF5111-2019
4b53c9a69e49bb801fa65b633689670bf2edf4ff
[ "MIT" ]
null
null
null
src/algo/shortest_path.cpp
setyolegowo/ITB-IF5111-2019
4b53c9a69e49bb801fa65b633689670bf2edf4ff
[ "MIT" ]
null
null
null
src/algo/shortest_path.cpp
setyolegowo/ITB-IF5111-2019
4b53c9a69e49bb801fa65b633689670bf2edf4ff
[ "MIT" ]
null
null
null
/** * shortest_path.cpp file. * Implementation. * * @author Setyo Legowo <gw.tio145@gmail.com> * @since 2019.02.18 */ #include <iostream> #include <string> #include <stdexcept> #include "shortest_path.hpp" ShortestPath::ShortestPath(uint32_t _index) { this->start_index = _index; } ShortestPath* ShortestPath::createFromConsoleArgument(int argc, char** argv) { if (argc < 5) { throw "Lack of argument for log linear search: <start_index>"; } uint32_t index; try { index = std::stoi(argv[4]); } catch (const std::invalid_argument& ia) { throw "Invalid argument for <start_index>"; } return new ShortestPath(index); } bool ShortestPath::find(std::vector<House> * houseList) { std::vector<bool> isVisited; for(uint32_t i=0; i<houseList->size(); i++) { isVisited.push_back(false); } this->shortest_path = 0; this->visit(this->start_index, 0, houseList, &isVisited); return true; } void ShortestPath::visit(uint32_t current_index, uint32_t current_path, std::vector<House> * houseList, std::vector<bool> * isVisited) { isVisited->at(current_index) = true; // Visit every house recursively // Go to right uint32_t next_index = this->findUnvisitedRight(current_index, isVisited); if(next_index != UINT32_MAX) { uint32_t new_path = current_path + houseList->at(next_index).posisi_rumah - houseList->at(current_index).posisi_rumah; if(new_path < this->shortest_path) this->shortest_path = new_path; this->visit(next_index, new_path, houseList, isVisited); } // Go to left next_index = this->findUnvisitedLeft(current_index, isVisited); if(next_index != UINT32_MAX) { uint32_t new_path = current_path + houseList->at(current_index).posisi_rumah - houseList->at(next_index).posisi_rumah; if(new_path > this->shortest_path) this->shortest_path = new_path; this->visit(next_index, new_path, houseList, isVisited); } isVisited->at(current_index) = false; return; } uint32_t ShortestPath::findUnvisitedLeft(uint32_t current_index, std::vector<bool> * isVisited) { current_index--; while(current_index + 1 > 0) { if(!isVisited->at(current_index)) return current_index; current_index--; } return UINT32_MAX; } uint32_t ShortestPath::findUnvisitedRight(uint32_t current_index, std::vector<bool> * isVisited) { current_index++; uint32_t array_size = isVisited->size(); while(current_index < array_size) { if(!isVisited->at(current_index)) return current_index; current_index++; } return UINT32_MAX; }
26.803922
136
0.662034
setyolegowo
b4faa19e20f2cb1be5d0641b21663c7f847d1964
3,442
cpp
C++
speexbuild/AGC.cpp
main--/mumble
e1bdd6564bb0445c535d3c711e5142d9bafa13d8
[ "BSD-3-Clause" ]
2
2019-09-10T18:12:41.000Z
2020-07-04T23:57:45.000Z
speexbuild/AGC.cpp
main--/mumble
e1bdd6564bb0445c535d3c711e5142d9bafa13d8
[ "BSD-3-Clause" ]
null
null
null
speexbuild/AGC.cpp
main--/mumble
e1bdd6564bb0445c535d3c711e5142d9bafa13d8
[ "BSD-3-Clause" ]
null
null
null
#include <QtCore> #ifdef Q_OS_WIN #define _WIN32_IE 0x0600 #include <windows.h> #include <shellapi.h> #define CALLGRIND_START_INSTRUMENTATION #define CALLGRIND_STOP_INSTRUMENTATION #define CALLGRIND_ZERO_STATS #else #include <valgrind/callgrind.h> #endif #include <math.h> #include <speex/speex.h> #include <speex/speex_preprocess.h> #include "Timer.h" template<class T> static inline double veccomp(const QVector<T> &a, const QVector<T> &b, const char *n) { long double gdiff = 0.0; if (a.size() != b.size()) { qFatal("%s: %d <=> %d", n, a.size(), b.size()); } for (int i=0;i<a.size();++i) { double diff = fabs(a[i] - b[i]); if (diff > gdiff) gdiff = diff; #ifdef EXACT if (a[i] != b[i]) { #else union { T tv; uint32_t uv; } v1, v2; v1.uv = v2.uv = 0; v1.tv = a[i]; v2.tv = b[i]; if (fabsf(a[i] - b[i]) > 1000) { qWarning("%08x %08x %08x", v1.uv, v2.uv, v1.uv ^ v2.uv); #endif qFatal("%s: Offset %d: %.10g <=> %.10g", n, i, static_cast<double>(a[i]), static_cast<double>(b[i])); } } return gdiff; } int main(int argc, char **argv) { CALLGRIND_STOP_INSTRUMENTATION; CALLGRIND_ZERO_STATS; QCoreApplication a(argc, argv); QFile f((argc >= 2) ? argv[1] : "wb_male.wav"); if (! f.open(QIODevice::ReadOnly)) { qFatal("Failed to open file!"); } f.seek(36 + 8); QFile o("output.agc"); if (! o.open(QIODevice::WriteOnly)) qFatal("Failed to open out file!"); QFile vf("verify.agc"); if (! vf.open(QIODevice::ReadOnly)) qWarning("No verify!"); QDataStream out(&o); QDataStream verify(&vf); static const int iFrameSize = 320; int iarg; SpeexPreprocessState *spp = speex_preprocess_state_init(iFrameSize, 16000); iarg = 0; speex_preprocess_ctl(spp, SPEEX_PREPROCESS_SET_VAD, &iarg); speex_preprocess_ctl(spp, SPEEX_PREPROCESS_SET_DENOISE, &iarg); speex_preprocess_ctl(spp, SPEEX_PREPROCESS_SET_DEREVERB, &iarg); iarg = 1; speex_preprocess_ctl(spp, SPEEX_PREPROCESS_SET_AGC, &iarg); iarg = 21747; speex_preprocess_ctl(spp, SPEEX_PREPROCESS_SET_AGC_TARGET, &iarg); QVector<QByteArray> v; while (1) { QByteArray qba = f.read(iFrameSize * sizeof(short)); if (qba.size() != iFrameSize * sizeof(short)) break; v.append(qba); } int nframes = v.size(); qWarning("Ready to process %d frames of %d samples", nframes, iFrameSize); QVector<short *> qvIn; QVector<short> sIn(nframes * iFrameSize); for (int i=0;i<nframes;i++) { const short *ptr = reinterpret_cast<const short *>(v[i].constData()); short *s = sIn.data() + i * iFrameSize; for (int j=0;j<iFrameSize;++j) s[j] = ptr[j]; qvIn.append(s); } #ifdef Q_OS_WIN if (!SetPriorityClass(GetCurrentProcess(),REALTIME_PRIORITY_CLASS)) qWarning("Application: Failed to set priority!"); #endif Timer t; t.restart(); CALLGRIND_START_INSTRUMENTATION; for (int i=0;i<nframes;i++) { speex_preprocess_run(spp, qvIn[i]); int v; speex_preprocess_ctl(spp, SPEEX_PREPROCESS_GET_AGC_GAIN, &v); qWarning("%d %d", i, v); } CALLGRIND_STOP_INSTRUMENTATION; quint64 e = t.elapsed(); #ifdef Q_OS_WIN if (!SetPriorityClass(GetCurrentProcess(),NORMAL_PRIORITY_CLASS)) qWarning("Application: Failed to reset priority!"); #endif qWarning("Used %llu usec", e); qWarning("%.2f times realtime", (20000ULL * nframes) / (e * 1.0)); if (! RUNNING_ON_VALGRIND) { out << sIn; if (vf.isOpen()) { QVector<short> vIn; verify >> vIn; veccomp(vIn, sIn, "AGC"); } } return 0; }
22.350649
104
0.669378
main--
b4fbb8e0a7741b3d4a46fd64a84a40bf0344578d
672
cpp
C++
hackerrank/data_structures/linked_list/print_list_in_reverse.cpp
sohilladhani/programming
f9a63532013c0ef81679eb922e8ec66d3daf2518
[ "MIT" ]
null
null
null
hackerrank/data_structures/linked_list/print_list_in_reverse.cpp
sohilladhani/programming
f9a63532013c0ef81679eb922e8ec66d3daf2518
[ "MIT" ]
null
null
null
hackerrank/data_structures/linked_list/print_list_in_reverse.cpp
sohilladhani/programming
f9a63532013c0ef81679eb922e8ec66d3daf2518
[ "MIT" ]
null
null
null
/* Question at https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list-in-reverse */ Node* reverse_list(Node *head) { Node* prev = NULL; Node* next = NULL; while(head) { next = head->next; head->next = prev; prev = head; head = next; } head = prev; return head; } void ReversePrint(Node *head) { //if head is null if(!head) return; //only 1 element if(!head->next) { cout<<head->data<<endl; } else { //reverse the list head = reverse_list(head); while(head) { cout<<head->data<<endl; head = head->next; } } }
21.677419
102
0.528274
sohilladhani
b4fbf10dd813e1c528252b267906a3ecc428402d
62,052
cpp
C++
lib/Runtime/Language/JavascriptStackWalker.cpp
paolosevMSFT/ChakraCore
e381509ce04eaee0517a668d5002d3eedf582b8b
[ "MIT" ]
3
2018-08-08T03:36:56.000Z
2019-05-24T08:45:30.000Z
lib/Runtime/Language/JavascriptStackWalker.cpp
paolosevMSFT/ChakraCore
e381509ce04eaee0517a668d5002d3eedf582b8b
[ "MIT" ]
null
null
null
lib/Runtime/Language/JavascriptStackWalker.cpp
paolosevMSFT/ChakraCore
e381509ce04eaee0517a668d5002d3eedf582b8b
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "RuntimeLanguagePch.h" #include "Language/JavascriptFunctionArgIndex.h" #include "Language/InterpreterStackFrame.h" #define FAligned(VALUE, TYPE) ((((LONG_PTR)VALUE) & (sizeof(TYPE)-1)) == 0) #define AlignIt(VALUE, TYPE) (~(~((LONG_PTR)(VALUE) + (sizeof(TYPE)-1)) | (sizeof(TYPE)-1))) namespace Js { Js::ArgumentsObject * JavascriptCallStackLayout::GetArgumentsObject() const { return (Js::ArgumentsObject *)((void **)this)[JavascriptFunctionArgIndex_ArgumentsObject]; } Js::Var* JavascriptCallStackLayout::GetArgumentsObjectLocation() const { return (Js::Var *)&((void **)this)[JavascriptFunctionArgIndex_ArgumentsObject]; } void JavascriptCallStackLayout::SetArgumentsObject(Js::ArgumentsObject * obj) { ((void **)this)[JavascriptFunctionArgIndex_ArgumentsObject] = obj; } Js::Var JavascriptCallStackLayout::GetOffset(int offset) const { Js::Var *varPtr = (Js::Var *)(((char *)this) + offset); Assert(FAligned(varPtr, Js::Var)); return *varPtr; } double JavascriptCallStackLayout::GetDoubleAtOffset(int offset) const { double *dblPtr = (double *)(((char *)this) + offset); #ifdef ENABLE_DEBUG_CONFIG_OPTIONS if (Js::Configuration::Global.flags.IsEnabled(Js::CheckAlignmentFlag)) { Assert(FAligned(dblPtr, double)); } #endif return *dblPtr; } int32 JavascriptCallStackLayout::GetInt32AtOffset(int offset) const { int32 *intPtr = (int32 *)(((char *)this) + offset); #ifdef ENABLE_DEBUG_CONFIG_OPTIONS if (Js::Configuration::Global.flags.IsEnabled(Js::CheckAlignmentFlag)) { Assert(FAligned(intPtr, int32)); } #endif return *intPtr; } SIMDValue JavascriptCallStackLayout::GetSimdValueAtOffset(int offset) const { return *((SIMDValue *)(((char *)this) + offset)); } char * JavascriptCallStackLayout::GetValueChangeOffset(int offset) const { Js::Var *varPtr = (Js::Var *)(((char *)this) + offset); Assert(FAligned(varPtr, Js::Var)); return (char *)varPtr; } ForInObjectEnumerator * JavascriptCallStackLayout::GetForInObjectEnumeratorArrayAtOffset(int offset) const { return (ForInObjectEnumerator *)(((char *)this) + offset); } JavascriptCallStackLayout *JavascriptCallStackLayout::FromFramePointer(void *const framePointer) { return reinterpret_cast<JavascriptCallStackLayout *>( static_cast<void **>(framePointer) + (JavascriptFunctionArgIndex_Function - JavascriptFunctionArgIndex_Frame)); } void* const JavascriptCallStackLayout::ToFramePointer(JavascriptCallStackLayout* callstackLayout) { return reinterpret_cast<void * const>( reinterpret_cast<void **>(callstackLayout) - (JavascriptFunctionArgIndex_Function - JavascriptFunctionArgIndex_Frame)); } Js::Var* JavascriptCallStackLayout::GetArgv() const { return const_cast<Js::Var*>(&this->args[0]); } ScriptContext* JavascriptStackWalker::GetCurrentScriptContext() const { return this->GetCurrentInterpreterFrame() ? this->GetCurrentInterpreterFrame()->GetScriptContext() : this->scriptContext; } Var JavascriptStackWalker::GetCurrentArgumentsObject() const { #if ENABLE_PROFILE_INFO if (interpreterFrame) #else Assert(interpreterFrame); #endif { return interpreterFrame->GetArgumentsObject(); } #if ENABLE_NATIVE_CODEGEN else { if (inlinedFramesBeingWalked) { return inlinedFrameWalker.GetArgumentsObject(); } else { return this->GetCurrentNativeArgumentsObject(); } } #endif } void JavascriptStackWalker::SetCurrentArgumentsObject(Var args) { #if ENABLE_NATIVE_CODEGEN if (interpreterFrame) #else Assert(interpreterFrame); #endif { interpreterFrame->SetArgumentsObject(args); } #if ENABLE_NATIVE_CODEGEN else { if (inlinedFramesBeingWalked) { inlinedFrameWalker.SetArgumentsObject(args); } else { this->SetCurrentNativeArgumentsObject(args); } } #endif } Var JavascriptStackWalker::GetPermanentArguments() const { Assert(IsJavascriptFrame()); AssertMsg(this->GetCurrentFunction()->IsScriptFunction(), "GetPermanentArguments should not be called for non-script function as there is no slot allocated for it."); const uint32 paramCount = GetCallInfo().Count; if (paramCount == 0) { // glob function doesn't allocate ArgumentsObject slot on stack return nullptr; } // Get the heap-allocated args for this frame. Var args = this->GetCurrentArgumentsObject(); if (args && ArgumentsObject::Is(args)) { args = ((ArgumentsObject*)args)->GetHeapArguments(); } return args; } BOOL JavascriptStackWalker::WalkToArgumentsFrame(ArgumentsObject *args) { // Move the walker up the stack until we find the given arguments object on the frame. while (this->Walk(/*includeInlineFrame*/ true)) { if (this->IsJavascriptFrame()) { Var currArgs = this->GetCurrentArgumentsObject(); if (currArgs == args) { return TRUE; } } } return FALSE; } bool JavascriptStackWalker::GetThis(Var* pVarThis, int moduleId) const { #if ENABLE_NATIVE_CODEGEN if (inlinedFramesBeingWalked) { if (inlinedFrameWalker.GetArgc() == 0) { *pVarThis = JavascriptOperators::OP_GetThis(this->scriptContext->GetLibrary()->GetUndefined(), moduleId, scriptContext); return false; } *pVarThis = inlinedFrameWalker.GetThisObject(); Assert(*pVarThis); return true; } else #endif { const CallInfo callInfo = this->GetCallInfo(); if (callInfo.Count == 0) { *pVarThis = JavascriptOperators::OP_GetThis(scriptContext->GetLibrary()->GetUndefined(), moduleId, scriptContext); return false; } *pVarThis = this->GetThisFromFrame(); return (*pVarThis) != nullptr; } } BOOL IsEval(CallInfo callInfo) { return (callInfo.Flags & CallFlags_Eval) != 0; } BOOL JavascriptStackWalker::IsCallerGlobalFunction() const { const CallInfo callInfo = this->GetCallInfo(); JavascriptFunction* function = this->GetCurrentFunction(); if (IsLibraryStackFrameEnabled(this->scriptContext) && !function->IsScriptFunction()) { return false; // native library code can't be global function } FunctionInfo* funcInfo = function->GetFunctionInfo(); if (funcInfo->HasParseableInfo()) { return funcInfo->GetParseableFunctionInfo()->GetIsGlobalFunc() || IsEval(callInfo); } else { AssertMsg(FALSE, "Here we should only have script functions which were already parsed/deserialized."); return callInfo.Count == 0 || IsEval(callInfo); } } BOOL JavascriptStackWalker::IsEvalCaller() const { const CallInfo callInfo = this->GetCallInfo(); return (callInfo.Flags & CallFlags_Eval) != 0; } Var JavascriptStackWalker::GetCurrentNativeArgumentsObject() const { Assert(this->IsJavascriptFrame() && this->interpreterFrame == nullptr); return this->GetCurrentArgv()[JavascriptFunctionArgIndex_ArgumentsObject]; } void JavascriptStackWalker::SetCurrentNativeArgumentsObject(Var args) { Assert(this->IsJavascriptFrame() && this->interpreterFrame == nullptr); this->GetCurrentArgv()[JavascriptFunctionArgIndex_ArgumentsObject] = args; } Js::Var * JavascriptStackWalker::GetJavascriptArgs(bool boxArgsAndDeepCopy) const { Assert(this->IsJavascriptFrame()); #if ENABLE_NATIVE_CODEGEN if (inlinedFramesBeingWalked) { return inlinedFrameWalker.GetArgv(/* includeThis */ false, boxArgsAndDeepCopy); } else #endif if (this->GetCurrentFunction()->GetFunctionInfo()->IsCoroutine()) { JavascriptGenerator* gen = JavascriptGenerator::FromVar(this->GetCurrentArgv()[JavascriptFunctionArgIndex_This]); return gen->GetArguments().Values; } else { return &this->GetCurrentArgv()[JavascriptFunctionArgIndex_SecondScriptArg]; } } uint32 JavascriptStackWalker::GetByteCodeOffset() const { uint32 offset = 0; if (this->IsJavascriptFrame()) { if (this->interpreterFrame) { if (this->TryGetByteCodeOffsetFromInterpreterFrame(offset)) { return offset; } } #if ENABLE_NATIVE_CODEGEN if (TryGetByteCodeOffsetFromNativeFrame(offset)) { return offset; } #endif } return offset; } bool JavascriptStackWalker::TryGetByteCodeOffsetFromInterpreterFrame(uint32& offset) const { #if ENABLE_NATIVE_CODEGEN if (this->lastInternalFrameInfo.codeAddress != nullptr) { return false; } #endif offset = this->interpreterFrame->GetReader()->GetCurrentOffset(); if (offset == 0) { // This will be the case when we are broken on the debugger on very first statement (due to async break). // Or the interpreter loop can throw OOS on entrance before executing bytecode. } else { // Note : For many cases, we move the m_currentLocation of ByteCodeReader already to next available opcode. // This could create problem in binding the exception to proper line offset. // Reducing by 1 will make sure the current offset falls under, current executing opcode. offset--; } return true; } #if ENABLE_NATIVE_CODEGEN bool JavascriptStackWalker::TryGetByteCodeOffsetFromNativeFrame(uint32& offset) const { DWORD_PTR pCodeAddr; if (this->lastInternalFrameInfo.codeAddress != nullptr) { pCodeAddr = (DWORD_PTR)this->lastInternalFrameInfo.codeAddress; } else { pCodeAddr = (DWORD_PTR)this->GetCurrentCodeAddr(); } // If the current instruction's return address is the beginning of the next statement then we will show error for the next line, which would be completely wrong. // The quick fix would be to look the address which is at least lesser than current return address. // Assert to verify at what places this can happen. Assert(pCodeAddr); if (pCodeAddr) { #if defined(_M_ARM) // Note that DWORD_PTR is not actually a pointer type (!) but is simple unsigned long/__int64 (see BaseTsd.h). // Thus, decrement would be by 1 byte and not 4 bytes as in pointer arithmetic. That's exactly what we need. // For ARM the 'return address' is always odd and is 'next instr addr' + 1 byte, so to get to the BLX instr, we need to subtract 2 bytes from it. AssertMsg(pCodeAddr % 2 == 1, "Got even number for pCodeAddr! It's expected to be return address, which should be odd."); pCodeAddr--; #endif pCodeAddr--; } bool usedInternalFrameInfo = false; uint loopNum = GetLoopNumber(usedInternalFrameInfo); JavascriptFunction *function = nullptr; FunctionBody *inlinee = nullptr; function = usedInternalFrameInfo ? this->GetCachedInternalFrameInfo().function : this->GetCurrentFunctionFromPhysicalFrame(); // If there are inlined frames on the stack, we have to be able to return the byte code offsets of those inlined calls // from their respective callers. But, we can use the current native address as IP for only the topmost inlined frame. // TryGetByteCodeOffsetOfInlinee takes care of these conditions and sets up the offset of an inlinee in 'offset', if the // current inlinee frame is not the topmost of the inlinee frames. if (HasInlinedFramesOnStack() && TryGetByteCodeOffsetOfInlinee(function, loopNum, pCodeAddr, &inlinee, offset, usedInternalFrameInfo)) { return true; } StatementData data; if (function->GetFunctionBody() && function->GetFunctionBody()->GetMatchingStatementMapFromNativeAddress(pCodeAddr, data, loopNum, inlinee)) { offset = data.bytecodeBegin; return true; } return false; } uint JavascriptStackWalker::GetLoopNumber(bool& usedInternalFrameInfo) const { uint loopNum = LoopHeader::NoLoop; if (this->lastInternalFrameInfo.codeAddress != nullptr) { if (this->lastInternalFrameInfo.frameType == InternalFrameType_LoopBody) { AnalysisAssert(this->interpreterFrame); loopNum = this->interpreterFrame->GetCurrentLoopNum(); Assert(loopNum != LoopHeader::NoLoop); usedInternalFrameInfo = true; } } else { if (this->IsCurrentPhysicalFrameForLoopBody()) { // Internal frame but codeAddress on lastInternalFrameInfo not set. We must be in an inlined frame in the loop body. Assert(this->tempInterpreterFrame); loopNum = this->tempInterpreterFrame->GetCurrentLoopNum(); Assert(loopNum != LoopHeader::NoLoop); usedInternalFrameInfo = false; } } return loopNum; } bool JavascriptStackWalker::TryGetByteCodeOffsetOfInlinee(Js::JavascriptFunction* parentFunction, uint loopNum, DWORD_PTR pCodeAddr, Js::FunctionBody** inlinee, uint32& offset, bool useInternalFrameInfo) const { // For inlined frames, translation from native offset -> source code happens in two steps. // The native offset is first translated into a statement index using the physical frame's // source context info. This statement index is then looked up in the *inlinee*'s source // context info to get the bytecode offset. // // For all inlined frames contained within a physical frame we have only one offset == (IP - entry). // Since we can't use that to get the other inlined callers' IPs, we save the IP of all inlined // callers in their "callinfo" (See InlineeCallInfo). The top most inlined frame uses the IP // of the physical frame. All other inlined frames use the InlineeStartOffset stored in their call info // to calculate the byte code offset of the callsite of the inlinee they called. StatementData data; uint32 inlineeOffset = 0; *inlinee = InlinedFramesBeingWalked() ? inlinedFrameWalker.GetFunctionObject()->GetFunctionBody() : nullptr; InlinedFrameWalker tmpFrameWalker; if (InlinedFramesBeingWalked()) { // Inlined frames are being walked right now. The top most frame is where the IP is. if (!inlinedFrameWalker.IsTopMostFrame()) { inlineeOffset = inlinedFrameWalker.GetCurrentInlineeOffset(); } } else if (ScriptFunction::Test(parentFunction) && HasInlinedFramesOnStack()) { // Inlined frames are not being walked right now. However, if there // are inlined frames on the stack the InlineeCallInfo of the first inlined frame // has the native offset of the current physical frame. Assert(!*inlinee); InlinedFrameWalker::FromPhysicalFrame(tmpFrameWalker, currentFrame, ScriptFunction::FromVar(parentFunction), PreviousInterpreterFrameIsFromBailout(), loopNum, this, useInternalFrameInfo, false /*noAlloc*/); inlineeOffset = tmpFrameWalker.GetBottomMostInlineeOffset(); tmpFrameWalker.Close(); } if (inlineeOffset != 0 && parentFunction->GetFunctionBody()->GetMatchingStatementMapFromNativeOffset(pCodeAddr, inlineeOffset, data, loopNum, *inlinee)) { offset = data.bytecodeBegin; return true; } return false; } bool JavascriptStackWalker::PreviousInterpreterFrameIsFromBailout() const { if (lastInternalFrameInfo.codeAddress) { return lastInternalFrameInfo.previousInterpreterFrameIsFromBailout; } return this->previousInterpreterFrameIsFromBailout; } bool JavascriptStackWalker::InlinedFramesBeingWalked() const { if (lastInternalFrameInfo.codeAddress) { return false; } return this->inlinedFramesBeingWalked; } bool JavascriptStackWalker::HasInlinedFramesOnStack() const { if (lastInternalFrameInfo.codeAddress) { return lastInternalFrameInfo.hasInlinedFramesOnStack; } return this->hasInlinedFramesOnStack; } #endif bool JavascriptStackWalker::GetSourcePosition(const WCHAR** sourceFileName, ULONG* line, LONG* column) { uint byteCodeoffset = this->GetByteCodeOffset(); if(byteCodeoffset) { Js::FunctionBody* functionBody = this->GetCurrentFunction()->GetFunctionBody(); if (functionBody->GetLineCharOffset(byteCodeoffset, line, column)) { if(functionBody->GetUtf8SourceInfo()->IsDynamic()) { *sourceFileName = _u("Dynamic Code"); } else { *sourceFileName = functionBody->GetUtf8SourceInfo()->GetSrcInfo()->sourceContextInfo->url; } return true; } } return false; } Js::JavascriptFunction * JavascriptStackWalker::UpdateFrame(bool includeInlineFrames) { this->isJavascriptFrame = this->CheckJavascriptFrame(includeInlineFrames); if (this->IsJavascriptFrame()) { // In case we have a cross site thunk, update the script context Js::JavascriptFunction *function = this->GetCurrentFunction(); #if ENABLE_NATIVE_CODEGEN bool isCurrentPhysicalFrameForLoopBody = this->IsCurrentPhysicalFrameForLoopBody(); #endif if (this->interpreterFrame) { #if ENABLE_NATIVE_CODEGEN if (lastInternalFrameInfo.codeAddress != nullptr) { this->previousInterpreterFrameIsForLoopBody = true; } #endif // We might've bailed out of an inlinee, so check if there were any inlinees. if (this->interpreterFrame->TestFlags(InterpreterStackFrameFlags_FromBailOut)) { previousInterpreterFrameIsFromBailout = true; #if ENABLE_NATIVE_CODEGEN Assert(!inlinedFramesBeingWalked); if (includeInlineFrames) { int loopNum = -1; if (isCurrentPhysicalFrameForLoopBody) { loopNum = this->tempInterpreterFrame->GetCurrentLoopNum(); } bool hasInlinedFramesOnStack = InlinedFrameWalker::FromPhysicalFrame(inlinedFrameWalker, currentFrame, ScriptFunction::FromVar(function), true /*fromBailout*/, loopNum, this, false /*useInternalFrameInfo*/, false /*noAlloc*/); if (hasInlinedFramesOnStack) { // We're now back in the state where currentFrame == physical frame of the inliner, but // since interpreterFrame != null, we'll pick values from the interpreterFrame (the bailout // frame of the inliner). Set a flag to tell the stack walker that it needs to start from the // inlinee frames on the stack when Walk() is called. this->inlinedFramesBeingWalked = inlinedFrameWalker.Next(inlinedFrameCallInfo); this->hasInlinedFramesOnStack = hasInlinedFramesOnStack; Assert(inlinedFramesBeingWalked); Assert(StackScriptFunction::GetCurrentFunctionObject(this->interpreterFrame->GetJavascriptFunction()) == inlinedFrameWalker.GetFunctionObject()); } else { Assert(!isCurrentPhysicalFrameForLoopBody); } } else if (isCurrentPhysicalFrameForLoopBody) { // Getting here is only possible when the current interpreterFrame is for a function which // encountered a bailout after getting inlined in a jitted loop body. If we are not including // inlined frames in the stack walk, we need to set the codeAddress on lastInternalFrameInfo, // which would have otherwise been set upon closing the inlinedFrameWalker, now. // Note that we already have an assert in CheckJavascriptFrame to ensure this. SetCachedInternalFrameInfo(InternalFrameType_LoopBody, function, false /*hasInlinedFramesOnStack*/, true /*previousInterpreterFrameIsFromBailout*/); } #else // How did we bail out when JIT was disabled? Assert(false); #endif } else { Assert(StackScriptFunction::GetCurrentFunctionObject(this->interpreterFrame->GetJavascriptFunction()) == function); previousInterpreterFrameIsFromBailout = false; } } else if (!this->isNativeLibraryFrame) { #if ENABLE_NATIVE_CODEGEN Assert(!HasInlinedFramesOnStack() || (includeInlineFrames && isCurrentPhysicalFrameForLoopBody)); if (!HasInlinedFramesOnStack() && includeInlineFrames) { // Check whether there are inlined frames nested in this native frame. The corresponding check for // a jitted loop body frame should have been done in CheckJavascriptFrame Assert(lastInternalFrameInfo.codeAddress == nullptr); bool inlinedFramesFound = InlinedFrameWalker::FromPhysicalFrame( inlinedFrameWalker, currentFrame, ScriptFunction::FromVar(function), false, // fromBailout -1, // loopNum nullptr,// walker false, // useInternalFrameInfo false // noAlloc ); if (inlinedFramesFound) { this->inlinedFramesBeingWalked = inlinedFrameWalker.Next(inlinedFrameCallInfo); this->hasInlinedFramesOnStack = true; Assert(inlinedFramesBeingWalked); } } #endif } this->scriptContext = function->GetScriptContext(); return function; } return nullptr; } #if ENABLE_NATIVE_CODEGEN void JavascriptStackWalker::WalkAndClearInlineeFrameCallInfoOnException(void *tryCatchFrameAddr) { // Walk the stack and when we find the first native frame, we clear the inlinee's callinfo for this frame // It is sufficient we stop at the first native frame which had the enclosing try-catch // TODO : Revisit when we start inlining functions with try-catch/try-finally while (this->Walk(true)) { if (JavascriptFunction::IsNativeAddress(this->scriptContext, this->currentFrame.GetInstructionPointer())) { if (HasInlinedFramesOnStack()) { for (int index = inlinedFrameWalker.GetFrameCount() - 1; index >= 0; index--) { auto inlinedFrame = inlinedFrameWalker.GetFrameAtIndex(index); inlinedFrame->callInfo.Clear(); } } if (this->currentFrame.GetFrame() == tryCatchFrameAddr) { break; } } } } #endif // Note: noinline is to make sure that when we unwind to the unwindToAddress, there is at least one frame to unwind. _NOINLINE JavascriptStackWalker::JavascriptStackWalker(ScriptContext * scriptContext, bool useEERContext, PVOID returnAddress, bool _forceFullWalk /*=false*/) : inlinedFrameCallInfo(CallFlags_None, 0), shouldDetectPartiallyInitializedInterpreterFrame(true), forceFullWalk(_forceFullWalk), previousInterpreterFrameIsFromBailout(false), previousInterpreterFrameIsForLoopBody(false), hasInlinedFramesOnStack(false) { if (scriptContext == NULL) { Throw::InternalError(); } this->scriptContext = scriptContext; // Pull the current script state from the thread context. ThreadContext * threadContext = scriptContext->GetThreadContext(); this->entryExitRecord = threadContext->GetScriptEntryExit(); this->nativeLibraryEntry = threadContext->PeekNativeLibraryEntry(); this->prevNativeLibraryEntry = nullptr; this->interpreterFrame = NULL; this->isJavascriptFrame = false; this->isNativeLibraryFrame = false; if (entryExitRecord->frameIdOfScriptExitFunction != NULL) { // We're currently outside the script, so grab the frame from which we left. this->scriptContext = entryExitRecord->scriptContext; this->isInitialFrame = this->currentFrame.InitializeByFrameId(entryExitRecord->frameIdOfScriptExitFunction, this->scriptContext); } else { // Just start with the caller this->isInitialFrame = this->currentFrame.InitializeByReturnAddress(_ReturnAddress(), this->scriptContext); } if (useEERContext) { this->tempInterpreterFrame = this->scriptContext->GetThreadContext()->GetLeafInterpreterFrame(); } else { // We need to generate stack for the passed script context, so use the leaf interpreter frame for passed script context this->tempInterpreterFrame = scriptContext->GetThreadContext()->GetLeafInterpreterFrame(); } inlinedFramesBeingWalked = false; } BOOL JavascriptStackWalker::Walk(bool includeInlineFrames) { // Walk one frame up the call stack. this->interpreterFrame = NULL; #if ENABLE_NATIVE_CODEGEN if (lastInternalFrameInfo.codeAddress != nullptr && this->previousInterpreterFrameIsForLoopBody) { this->previousInterpreterFrameIsForLoopBody = false; ClearCachedInternalFrameInfo(); } if (inlinedFramesBeingWalked) { Assert(includeInlineFrames); inlinedFramesBeingWalked = inlinedFrameWalker.Next(inlinedFrameCallInfo); if (!inlinedFramesBeingWalked) { inlinedFrameWalker.Close(); if ((this->IsCurrentPhysicalFrameForLoopBody())) { // Done walking inlined frames in a loop body, cache the native code address now // in order to skip the loop body frame. this->SetCachedInternalFrameInfo(InternalFrameType_LoopBody, this->GetCurrentFunctionFromPhysicalFrame(), true /*hasInlinedFramesOnStack*/, previousInterpreterFrameIsFromBailout); isJavascriptFrame = false; } } return true; } #endif this->hasInlinedFramesOnStack = false; if (this->isInitialFrame) { this->isInitialFrame = false; // Only walk initial frame once } else if (!this->currentFrame.Next()) { this->isJavascriptFrame = false; return false; } // If we're at the entry from a host frame, hop to the frame from which we left the script. if (AlignAndCheckAddressOfReturnAddressMatch(this->currentFrame.GetAddressOfInstructionPointer(), this->entryExitRecord->addrOfReturnAddrOfScriptEntryFunction)) { BOOL hasCaller = this->entryExitRecord->hasCaller || this->forceFullWalk; #ifdef CHECK_STACKWALK_EXCEPTION BOOL ignoreStackWalkException = this->entryExitRecord->ignoreStackWalkException; #endif this->entryExitRecord = this->entryExitRecord->next; if (this->entryExitRecord == NULL) { this->isJavascriptFrame = false; return false; } if (!hasCaller && !this->scriptContext->IsDiagnosticsScriptContext()) { #ifdef CHECK_STACKWALK_EXCEPTION if (!ignoreStackWalkException) { AssertMsg(false, "walk pass no caller frame"); } #endif this->isJavascriptFrame = false; return false; } this->scriptContext = this->entryExitRecord->scriptContext; this->currentFrame.SkipToFrame(this->entryExitRecord->frameIdOfScriptExitFunction); } this->UpdateFrame(includeInlineFrames); return true; } BOOL JavascriptStackWalker::GetCallerWithoutInlinedFrames(_Out_opt_ JavascriptFunction ** ppFunc) { return GetCaller(ppFunc, /*includeInlineFrames*/ false); } BOOL JavascriptStackWalker::GetCaller(_Out_opt_ JavascriptFunction ** ppFunc, bool includeInlineFrames) { while (this->Walk(includeInlineFrames)) { if (this->IsJavascriptFrame()) { Assert(entryExitRecord != NULL); if (ppFunc) { *ppFunc = this->GetCurrentFunction(); } AssertMsg(!this->shouldDetectPartiallyInitializedInterpreterFrame, "must have skipped first frame if needed"); return true; } } if (ppFunc) { *ppFunc = nullptr; } return false; } BOOL JavascriptStackWalker::GetNonLibraryCodeCaller(_Out_opt_ JavascriptFunction ** ppFunc) { while (this->GetCaller(ppFunc)) { Assert(ppFunc != nullptr); __analysis_assume(ppFunc != nullptr); if (!(*ppFunc)->IsLibraryCode()) { return true; } } return false; } /*static*/ bool JavascriptStackWalker::IsLibraryStackFrameEnabled(Js::ScriptContext * scriptContext) { Assert(scriptContext != nullptr); return CONFIG_FLAG(LibraryStackFrame); } // Check if a function is a display caller: user code, or native library / boundary script library code bool JavascriptStackWalker::IsDisplayCaller(JavascriptFunction* func) { FunctionBody* body = func->GetFunctionBody(); if (IsLibraryStackFrameEnabled(func->GetScriptContext())) { return !func->IsScriptFunction() || !body->GetUtf8SourceInfo()->GetIsLibraryCode() || body->IsPublicLibraryCode(); } else { return !body->GetUtf8SourceInfo()->GetIsLibraryCode(); } } bool JavascriptStackWalker::GetDisplayCaller(_Out_opt_ JavascriptFunction ** ppFunc) { while (this->GetCaller(ppFunc)) { Assert(ppFunc != nullptr); __analysis_assume(ppFunc != nullptr); if (IsDisplayCaller(*ppFunc)) { return true; } } return false; } PCWSTR JavascriptStackWalker::GetCurrentNativeLibraryEntryName() const { Assert(IsLibraryStackFrameEnabled(this->scriptContext) && this->prevNativeLibraryEntry && this->prevNativeLibraryEntry->next == this->nativeLibraryEntry); return this->prevNativeLibraryEntry->name; } // WalkToTarget skips internal frames BOOL JavascriptStackWalker::WalkToTarget(JavascriptFunction * funcTarget) { // Walk up the call stack until we find the frame that belongs to the given function. while (this->Walk(/*includeInlineFrames*/ true)) { if (this->IsJavascriptFrame() && this->GetCurrentFunction() == funcTarget) { // Skip internal names Assert( !(this->GetCallInfo().Flags & CallFlags_InternalFrame) ); return true; } } return false; } bool JavascriptStackWalker::AlignAndCheckAddressOfReturnAddressMatch(void* addressOfReturnAddress, void* nativeLibraryEntryAddress) { return addressOfReturnAddress == nativeLibraryEntryAddress #if defined(_M_IX86) // Under some odd cases on x86, addressOfReturnAddress and stashed entry address need to be aligned. // This happens when code is generated using two stack pointers. One or both have the address of // return address offset by 4, 8, or 12. || (((uint)nativeLibraryEntryAddress - (uint)addressOfReturnAddress < 0x10) && *(void**)addressOfReturnAddress == *(void**)nativeLibraryEntryAddress ) #endif ; } void ** JavascriptStackWalker::GetCurrentArgv() const { Assert(this->IsJavascriptFrame()); Assert(this->interpreterFrame != nullptr || (this->prevNativeLibraryEntry && AlignAndCheckAddressOfReturnAddressMatch(this->currentFrame.GetAddressOfReturnAddress(), this->prevNativeLibraryEntry->addr)) || JavascriptFunction::IsNativeAddress(this->scriptContext, (void*)this->currentFrame.GetInstructionPointer())); bool isNativeAddr = (this->interpreterFrame == nullptr) && (!this->prevNativeLibraryEntry || !AlignAndCheckAddressOfReturnAddressMatch(this->currentFrame.GetAddressOfReturnAddress(), this->prevNativeLibraryEntry->addr)); void ** argv = currentFrame.GetArgv(isNativeAddr, false /*shouldCheckForNativeAddr*/); Assert(argv); return argv; } bool JavascriptStackWalker::CheckJavascriptFrame(bool includeInlineFrames) { this->isNativeLibraryFrame = false; // Clear previous result void * codeAddr = this->currentFrame.GetInstructionPointer(); if (this->tempInterpreterFrame && codeAddr == this->tempInterpreterFrame->GetReturnAddress()) { bool isBailoutInterpreter = this->tempInterpreterFrame->TestFlags(Js::InterpreterStackFrameFlags_FromBailOut); // We need to skip over the first interpreter frame on the stack if it is the partially initialized frame // otherwise it is a real frame and we should continue. // For fully initialized frames (PushPopHelper was called) the thunk stack addr is equal or below addressOfReturnAddress // as the latter one is obtained in InterpreterStackFrame::InterpreterThunk called by the thunk. bool isPartiallyInitializedFrame = this->shouldDetectPartiallyInitializedInterpreterFrame && this->currentFrame.GetAddressOfReturnAddress(isBailoutInterpreter /*isCurrentContextNative*/, false /*shouldCheckForNativeAddr*/) < this->tempInterpreterFrame->GetAddressOfReturnAddress(); this->shouldDetectPartiallyInitializedInterpreterFrame = false; if (isPartiallyInitializedFrame) { return false; // Skip it. } void ** argv = this->currentFrame.GetArgv(isBailoutInterpreter /*isCurrentContextNative*/, false /*shouldCheckForNativeAddr*/); if (argv == nullptr) { // NOTE: When we switch to walking the stack ourselves and skip non engine frames, this should never happen. return false; } this->interpreterFrame = this->tempInterpreterFrame; this->tempInterpreterFrame = this->interpreterFrame->GetPreviousFrame(); #if ENABLE_NATIVE_CODEGEN #if DBG if (((CallInfo const *)&argv[JavascriptFunctionArgIndex_CallInfo])->Flags & CallFlags_InternalFrame) { // The return address of the interpreterFrame is the same as the entryPoint for a jitted loop body. // This can only ever happen when we have bailed out from a function inlined in the loop body. We // wouldn't have created a new interpreterFrame if the bailout were from the loop body itself. Assert(this->interpreterFrame->TestFlags(Js::InterpreterStackFrameFlags_FromBailOut)); InlinedFrameWalker tmpFrameWalker; Assert(InlinedFrameWalker::FromPhysicalFrame(tmpFrameWalker, currentFrame, Js::ScriptFunction::FromVar(argv[JavascriptFunctionArgIndex_Function]), true /*fromBailout*/, this->tempInterpreterFrame->GetCurrentLoopNum(), this, false /*useInternalFrameInfo*/, true /*noAlloc*/)); tmpFrameWalker.Close(); } #endif //DBG #endif //ENABLE_NATIVE_CODEGEN return true; } if (IsLibraryStackFrameEnabled(this->scriptContext) && this->nativeLibraryEntry) { void* addressOfReturnAddress = this->currentFrame.GetAddressOfReturnAddress(); void* nativeLibraryEntryAddress = this->nativeLibraryEntry->addr; AssertMsg(addressOfReturnAddress <= nativeLibraryEntryAddress, "Missed matching native library entry?"); if (AlignAndCheckAddressOfReturnAddressMatch(addressOfReturnAddress, nativeLibraryEntryAddress)) { this->isNativeLibraryFrame = true; this->shouldDetectPartiallyInitializedInterpreterFrame = false; this->prevNativeLibraryEntry = this->nativeLibraryEntry; // Saves match in prevNativeLibraryEntry this->nativeLibraryEntry = this->nativeLibraryEntry->next; return true; } } #if ENABLE_NATIVE_CODEGEN BOOL isNativeAddr = JavascriptFunction::IsNativeAddress(this->scriptContext, codeAddr); if (isNativeAddr) { this->shouldDetectPartiallyInitializedInterpreterFrame = false; void ** argv = this->currentFrame.GetArgv(true /*isCurrentContextNative*/, false /*shouldCheckForNativeAddr*/); if (argv == nullptr) { // NOTE: When we switch to walking the stack ourselves and skip non engine frames, this should never happen. return false; } ScriptFunction* funcObj = Js::ScriptFunction::FromVar(argv[JavascriptFunctionArgIndex_Function]); if (funcObj->GetFunctionBody()->GetIsAsmjsMode()) { return false; } // Note: this check has to happen after asm.js check, because call info is not valid for asm.js if (((CallInfo const *)&argv[JavascriptFunctionArgIndex_CallInfo])->Flags & CallFlags_InternalFrame) { if (includeInlineFrames && InlinedFrameWalker::FromPhysicalFrame(inlinedFrameWalker, currentFrame, Js::ScriptFunction::FromVar(argv[JavascriptFunctionArgIndex_Function]), false /*fromBailout*/, this->tempInterpreterFrame->GetCurrentLoopNum(), this, false /*useInternalFrameInfo*/, false /*noAlloc*/)) { // Found inlined frames in a jitted loop body. We dont want to skip the inlined frames; walk all of them before setting codeAddress on lastInternalFrameInfo. // DeepCopy here because, if there is an inlinee in a loop body, FromPhysicalFrame won't be called from UpdateFrame this->inlinedFramesBeingWalked = inlinedFrameWalker.Next(inlinedFrameCallInfo); this->hasInlinedFramesOnStack = true; Assert(inlinedFramesBeingWalked); return true; } SetCachedInternalFrameInfo(InternalFrameType_LoopBody, funcObj, false /*hasInlinedFramesOnStack*/, previousInterpreterFrameIsFromBailout); return false; } return true; } #endif return false; } void * JavascriptStackWalker::GetCurrentCodeAddr() const { return this->currentFrame.GetInstructionPointer(); } JavascriptFunction * JavascriptStackWalker::GetCurrentFunction(bool includeInlinedFrames /* = true */) const { Assert(this->IsJavascriptFrame()); #if ENABLE_NATIVE_CODEGEN if (includeInlinedFrames && inlinedFramesBeingWalked) { return inlinedFrameWalker.GetFunctionObject(); } else #endif if (this->isNativeLibraryFrame) { // Return saved function. Do not read from stack as compiler may stackpack/optimize args. return JavascriptFunction::FromVar(this->prevNativeLibraryEntry->function); } else { return StackScriptFunction::GetCurrentFunctionObject((JavascriptFunction *)this->GetCurrentArgv()[JavascriptFunctionArgIndex_Function]); } } void JavascriptStackWalker::SetCurrentFunction(JavascriptFunction * function) { Assert(this->IsJavascriptFrame()); #if ENABLE_NATIVE_CODEGEN if (inlinedFramesBeingWalked) { inlinedFrameWalker.SetFunctionObject(function); } else #endif { this->GetCurrentArgv()[JavascriptFunctionArgIndex_Function] = function; } } JavascriptFunction *JavascriptStackWalker::GetCurrentFunctionFromPhysicalFrame() const { return GetCurrentFunction(false); } CallInfo JavascriptStackWalker::GetCallInfo(bool includeInlinedFrames /* = true */) const { Assert(this->IsJavascriptFrame()); CallInfo callInfo; if (includeInlinedFrames && inlinedFramesBeingWalked) { // Since we don't support inlining constructors yet, its questionable if we should handle the // hidden frame display here? callInfo = inlinedFrameCallInfo; } else if (this->GetCurrentFunction()->GetFunctionInfo()->IsCoroutine()) { JavascriptGenerator* gen = JavascriptGenerator::FromVar(this->GetCurrentArgv()[JavascriptFunctionArgIndex_This]); callInfo = gen->GetArguments().Info; } else if (this->isNativeLibraryFrame) { // Return saved callInfo. Do not read from stack as compiler may stackpack/optimize args. callInfo = this->prevNativeLibraryEntry->callInfo; } else { callInfo = *(CallInfo const *)&this->GetCurrentArgv()[JavascriptFunctionArgIndex_CallInfo]; } if (callInfo.Flags & Js::CallFlags_ExtraArg) { callInfo.Flags = (CallFlags)(callInfo.Flags & ~Js::CallFlags_ExtraArg); } return callInfo; } CallInfo JavascriptStackWalker::GetCallInfoFromPhysicalFrame() const { return GetCallInfo(false); } Var JavascriptStackWalker::GetThisFromFrame() const { Assert(!inlinedFramesBeingWalked); Assert(this->IsJavascriptFrame()); if (this->GetCurrentFunction()->GetFunctionInfo()->IsCoroutine()) { JavascriptGenerator* gen = JavascriptGenerator::FromVar(this->GetCurrentArgv()[JavascriptFunctionArgIndex_This]); return gen->GetArguments()[0]; } return this->GetCurrentArgv()[JavascriptFunctionArgIndex_This]; } #if ENABLE_NATIVE_CODEGEN void JavascriptStackWalker::ClearCachedInternalFrameInfo() { this->lastInternalFrameInfo.Clear(); } void JavascriptStackWalker::SetCachedInternalFrameInfo(InternalFrameType frameType, JavascriptFunction* function, bool hasInlinedFramesOnStack, bool previousInterpreterFrameIsFromBailout) { if (!this->lastInternalFrameInfo.codeAddress) { this->lastInternalFrameInfo.Set( this->GetCurrentCodeAddr(), this->currentFrame.GetFrame(), this->currentFrame.GetStackCheckCodeHeight(), frameType, function, hasInlinedFramesOnStack, previousInterpreterFrameIsFromBailout); } } #endif bool JavascriptStackWalker::IsCurrentPhysicalFrameForLoopBody() const { return !!(this->GetCallInfoFromPhysicalFrame().Flags & CallFlags_InternalFrame); } bool JavascriptStackWalker::IsWalkable(ScriptContext *scriptContext) { if (scriptContext == NULL) { return false; } ThreadContext *threadContext = scriptContext->GetThreadContext(); if (threadContext == NULL) { return false; } return (threadContext->GetScriptEntryExit() != NULL); } BOOL JavascriptStackWalker::GetCaller(_Out_opt_ JavascriptFunction** ppFunc, ScriptContext* scriptContext) { if (!IsWalkable(scriptContext)) { if (ppFunc) { *ppFunc = nullptr; } return FALSE; } JavascriptStackWalker walker(scriptContext); return walker.GetCaller(ppFunc); } BOOL JavascriptStackWalker::GetCaller(_Out_opt_ JavascriptFunction** ppFunc, uint32* byteCodeOffset, ScriptContext* scriptContext) { JavascriptStackWalker walker(scriptContext); if (walker.GetCaller(ppFunc)) { *byteCodeOffset = walker.GetByteCodeOffset(); return TRUE; } return FALSE; } bool JavascriptStackWalker::GetThis(Var* pThis, int moduleId, ScriptContext* scriptContext) { JavascriptStackWalker walker(scriptContext); JavascriptFunction* caller; return walker.GetCaller(&caller) && walker.GetThis(pThis, moduleId); } bool JavascriptStackWalker::GetThis(Var* pThis, int moduleId, JavascriptFunction* func, ScriptContext* scriptContext) { JavascriptStackWalker walker(scriptContext); JavascriptFunction* caller; while (walker.GetCaller(&caller)) { if (caller == func) { walker.GetThis(pThis, moduleId); return true; } } return false; } // Try to see whether there is a top-most javascript frame, and if there is return true if it's native. // Returns true if top most frame is javascript frame, in this case the isNative parameter receives true // when top-most frame is native, false otherwise. // Returns false if top most frame is not a JavaScript frame. /* static */ bool JavascriptStackWalker::TryIsTopJavaScriptFrameNative(ScriptContext* scriptContext, bool* isNative, bool ignoreLibraryCode /* = false */) { Assert(scriptContext); Assert(isNative); Js::JavascriptFunction* caller; Js::JavascriptStackWalker walker(scriptContext); BOOL isSuccess; if (ignoreLibraryCode) { isSuccess = walker.GetNonLibraryCodeCaller(&caller); } else { isSuccess = walker.GetCaller(&caller); } if (isSuccess) { *isNative = (walker.GetCurrentInterpreterFrame() == NULL); return true; } return false; } #if ENABLE_NATIVE_CODEGEN bool InlinedFrameWalker::FromPhysicalFrame(InlinedFrameWalker& self, StackFrame& physicalFrame, Js::ScriptFunction *parent, bool fromBailout, int loopNum, const JavascriptStackWalker * const stackWalker, bool useInternalFrameInfo, bool noAlloc) { bool inlinedFramesFound = false; FunctionBody* parentFunctionBody = parent->GetFunctionBody(); EntryPointInfo *entryPointInfo; if (loopNum != -1) { Assert(stackWalker); } void *nativeCodeAddress = nullptr; void *framePointer = nullptr; if (loopNum != -1 && useInternalFrameInfo) { Assert(stackWalker->GetCachedInternalFrameInfo().codeAddress != nullptr); InternalFrameInfo lastInternalFrameInfo = stackWalker->GetCachedInternalFrameInfo(); nativeCodeAddress = lastInternalFrameInfo.codeAddress; framePointer = lastInternalFrameInfo.framePointer; } else { nativeCodeAddress = physicalFrame.GetInstructionPointer(); framePointer = physicalFrame.GetFrame(); } if (loopNum != -1) { entryPointInfo = (Js::EntryPointInfo*)parentFunctionBody->GetLoopEntryPointInfoFromNativeAddress((DWORD_PTR)nativeCodeAddress, loopNum); } else { entryPointInfo = (Js::EntryPointInfo*)parentFunctionBody->GetEntryPointFromNativeAddress((DWORD_PTR)nativeCodeAddress); } AssertMsg(entryPointInfo != nullptr, "Inlined frame should resolve to the right parent address"); if (entryPointInfo->HasInlinees()) { void *entry = reinterpret_cast<void*>(entryPointInfo->GetNativeAddress()); InlinedFrameWalker::InlinedFrame *outerMostFrame = InlinedFrame::FromPhysicalFrame(physicalFrame, stackWalker, entry, entryPointInfo, useInternalFrameInfo); if (!outerMostFrame) { return inlinedFramesFound; } if (!fromBailout) { InlineeFrameRecord* record = entryPointInfo->FindInlineeFrame((void*)nativeCodeAddress); if (record) { record->RestoreFrames(parent->GetFunctionBody(), outerMostFrame, JavascriptCallStackLayout::FromFramePointer(framePointer), false /* boxValues */); } } if (outerMostFrame->callInfo.Count) { inlinedFramesFound = true; if (noAlloc) { return inlinedFramesFound; } int32 frameCount = 0; InlinedFrameWalker::InlinedFrame *frameIterator = outerMostFrame; while (frameIterator->callInfo.Count) { frameCount++; frameIterator = frameIterator->Next(); } InlinedFrameWalker::InlinedFrame **frames = HeapNewArray(InlinedFrameWalker::InlinedFrame*, frameCount); frameIterator = outerMostFrame; for (int index = frameCount - 1; index >= 0; index--) { Assert(frameIterator); frames[index] = frameIterator; frameIterator = frameIterator->Next(); } self.Initialize(frameCount, frames, parent); } } return inlinedFramesFound; } void InlinedFrameWalker::Close() { parentFunction = nullptr; HeapDeleteArray(frameCount, frames); frames = nullptr; currentIndex = -1; frameCount = 0; } bool InlinedFrameWalker::Next(CallInfo& callInfo) { MoveNext(); InlinedFrameWalker::InlinedFrame *const currentFrame = GetCurrentFrame(); if (currentFrame) { callInfo.Flags = CallFlags_None; callInfo.Count = (currentFrame->callInfo.Count & 0xFFFF); } return currentFrame != nullptr; } size_t InlinedFrameWalker::GetArgc() const { InlinedFrameWalker::InlinedFrame *const currentFrame = GetCurrentFrame(); Assert(currentFrame); return currentFrame->callInfo.Count; } // Note: the boxArgsAndDeepCopy parameter should be true when a copy of the JS args must be ensured to // be on the heap. This results in a new array of Vars with deep copied boxed values (where // appropriate). // Otherwise, this parameter should be false. For instance, if the args will only be used // internally to gather type info, the values are not boxed (so, some Vars may still be on // the stack) and the array of the current frame is returned. Js::Var *InlinedFrameWalker::GetArgv(bool includeThis, bool boxArgsAndDeepCopy) const { InlinedFrameWalker::InlinedFrame *const currentFrame = GetCurrentFrame(); Assert(currentFrame); uint firstArg = includeThis ? InlinedFrameArgIndex_This : InlinedFrameArgIndex_SecondScriptArg; size_t argCount = this->GetArgc() - firstArg; Js::Var *args; if (!boxArgsAndDeepCopy) { args = &currentFrame->argv[firstArg]; } else { args = RecyclerNewArray(parentFunction->GetScriptContext()->GetRecycler(), Js::Var, argCount); for (size_t i = 0; i < argCount; i++) { args[i] = currentFrame->argv[firstArg + i]; } this->FinalizeStackValues(args, argCount, true /*deepCopy*/); } return args; } void InlinedFrameWalker::FinalizeStackValues(__in_ecount(argCount) Js::Var args[], size_t argCount, bool deepCopy) const { ScriptContext *scriptContext = this->GetFunctionObject()->GetScriptContext(); for (size_t i = 0; i < argCount; i++) { args[i] = Js::JavascriptOperators::BoxStackInstance(args[i], scriptContext, false /*allowStackFunction*/, deepCopy); } } Js::JavascriptFunction *InlinedFrameWalker::GetFunctionObject() const { InlinedFrameWalker::InlinedFrame *const currentFrame = GetCurrentFrame(); Assert(currentFrame); return StackScriptFunction::GetCurrentFunctionObject(currentFrame->function); } void InlinedFrameWalker::SetFunctionObject(Js::JavascriptFunction * function) { InlinedFrameWalker::InlinedFrame *const currentFrame = GetCurrentFrame(); Assert(currentFrame); currentFrame->function = function; } Js::Var InlinedFrameWalker::GetArgumentsObject() const { InlinedFrameWalker::InlinedFrame *const currentFrame = GetCurrentFrame(); Assert(currentFrame); return currentFrame->arguments; } void InlinedFrameWalker::SetArgumentsObject(Js::Var arguments) { InlinedFrameWalker::InlinedFrame *currentFrame = (InlinedFrameWalker::InlinedFrame *)GetCurrentFrame(); Assert(currentFrame); currentFrame->arguments = arguments; } Js::Var InlinedFrameWalker::GetThisObject() const { InlinedFrameWalker::InlinedFrame *const currentFrame = GetCurrentFrame(); Assert(currentFrame); return currentFrame->argv[InlinedFrameArgIndex_This]; } bool InlinedFrameWalker::IsCallerPhysicalFrame() const { return currentIndex == (frameCount - 1); } bool InlinedFrameWalker::IsTopMostFrame() const { return currentIndex == 0; } uint32 InlinedFrameWalker::GetCurrentInlineeOffset() const { Assert(!IsTopMostFrame()); Assert(currentIndex); #pragma warning(push) #pragma warning(disable: 4254) return GetFrameAtIndex(currentIndex - 1)->callInfo.InlineeStartOffset; #pragma warning(pop) } uint32 InlinedFrameWalker::GetBottomMostInlineeOffset() const { Assert(frameCount); #pragma warning(push) #pragma warning(disable: 4254) return GetFrameAtIndex(frameCount - 1)->callInfo.InlineeStartOffset; #pragma warning(pop) } Js::JavascriptFunction *InlinedFrameWalker::GetBottomMostFunctionObject() const { Assert(frameCount); return GetFrameAtIndex(frameCount - 1)->function; } InlinedFrameWalker::InlinedFrame *const InlinedFrameWalker::GetCurrentFrame() const { return GetFrameAtIndex(currentIndex); } InlinedFrameWalker::InlinedFrame *const InlinedFrameWalker::GetFrameAtIndex(signed index) const { Assert(frames); Assert(frameCount); InlinedFrameWalker::InlinedFrame *frame = nullptr; if (index < frameCount) { frame = frames[index]; } return frame; } void InlinedFrameWalker::MoveNext() { currentIndex++; } void InlinedFrameWalker::Initialize(int32 frameCount, __in_ecount(frameCount) InlinedFrame **frames, Js::ScriptFunction *parent) { Assert(!parentFunction); Assert(!this->frames); Assert(!this->frameCount); Assert(currentIndex == -1); this->parentFunction = parent; this->frames = frames; this->frameCount = frameCount; this->currentIndex = -1; } InlinedFrameWalker::InlinedFrame* InlinedFrameWalker::InlinedFrame::FromPhysicalFrame(StackFrame& currentFrame, const JavascriptStackWalker * const stackWalker, void *entry, EntryPointInfo* entryPointInfo, bool useInternalFrameInfo) { // If the current javascript frame is a native frame, get the inlined frame from it, otherwise // it may be possible that current frame is the interpreter frame for a jitted loop body // If the loop body had some inlinees in it, retrieve the inlined frame using the cached info, // viz. instruction pointer, frame pointer, and stackCheckCodeHeight, about the loop body frame. struct InlinedFrame *inlinedFrame = nullptr; void *codeAddr, *framePointer; size_t stackCheckCodeHeight; if (useInternalFrameInfo) { codeAddr = stackWalker->GetCachedInternalFrameInfo().codeAddress; framePointer = stackWalker->GetCachedInternalFrameInfo().framePointer; stackCheckCodeHeight = stackWalker->GetCachedInternalFrameInfo().stackCheckCodeHeight; } else { codeAddr = currentFrame.GetInstructionPointer(); framePointer = currentFrame.GetFrame(); stackCheckCodeHeight = currentFrame.GetStackCheckCodeHeight(); } if (!StackFrame::IsInStackCheckCode(entry, codeAddr, stackCheckCodeHeight)) { inlinedFrame = (struct InlinedFrame *)(((uint8 *)framePointer) - entryPointInfo->GetFrameHeight()); } return inlinedFrame; } void InternalFrameInfo::Set( void *codeAddress, void *framePointer, size_t stackCheckCodeHeight, InternalFrameType frameType, JavascriptFunction* function, bool hasInlinedFramesOnStack, bool previousInterpreterFrameIsFromBailout) { // We skip a jitted loop body's native frame when walking the stack and refer to the loop body's interpreter frame to get the function. // However, if the loop body has inlinees, to retrieve inlinee frames we need to cache some info about the loop body's native frame. this->codeAddress = codeAddress; this->framePointer = framePointer; this->stackCheckCodeHeight = stackCheckCodeHeight; this->frameType = frameType; this->function = function; this->hasInlinedFramesOnStack = hasInlinedFramesOnStack; this->previousInterpreterFrameIsFromBailout = previousInterpreterFrameIsFromBailout; } void InternalFrameInfo::Clear() { this->codeAddress = nullptr; this->framePointer = nullptr; this->stackCheckCodeHeight = (uint)-1; this->frameType = InternalFrameType_None; this->function = nullptr; this->hasInlinedFramesOnStack = false; this->previousInterpreterFrameIsFromBailout = false; } #endif #if DBG // Force a stack walk which till we find an interpreter frame // This will ensure inlined frames are decoded. bool JavascriptStackWalker::ValidateTopJitFrame(Js::ScriptContext* scriptContext) { if (!Configuration::Global.flags.ValidateInlineStack) { return true; } Js::JavascriptStackWalker walker(scriptContext); Js::JavascriptFunction* function; while (walker.GetCaller(&function)) { Assert(function); if (walker.GetCurrentInterpreterFrame() != nullptr) { break; } } // If no asserts have fired yet - we should have succeeded. return true; } #endif }
38.517691
236
0.623364
paolosevMSFT
b4fceca31c3cab9e14129ce8c2214ec2e3de9182
3,652
cpp
C++
core/tcp_mailbox.cpp
BowenforGit/Grasper
268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7
[ "Apache-2.0" ]
null
null
null
core/tcp_mailbox.cpp
BowenforGit/Grasper
268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7
[ "Apache-2.0" ]
null
null
null
core/tcp_mailbox.cpp
BowenforGit/Grasper
268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7
[ "Apache-2.0" ]
null
null
null
/* Copyright 2019 Husky Data Lab, CUHK Authors: Changji Li (cjli@cse.cuhk.edu.hk) */ #include "core/tcp_mailbox.hpp" using namespace std; TCPMailbox::~TCPMailbox() { for (auto &r : receivers_) if (r != NULL) delete r; for (auto &s : senders_) { if (s.second != NULL) { delete s.second; s.second = NULL; } } } void TCPMailbox::Init(vector<Node> & nodes) { receivers_.resize(config_->global_num_threads); for (int tid = 0; tid < config_->global_num_threads; tid++) { receivers_[tid] = new zmq::socket_t(context, ZMQ_PULL); char addr[64] = ""; sprintf(addr, "tcp://*:%d", my_node_.tcp_port + 1 + tid); receivers_[tid]->bind(addr); } for (int nid = 0; nid < config_->global_num_workers; nid++) { Node & r_node = GetNodeById(nodes, nid + 1); string ibname = r_node.ibname; for (int tid = 0; tid < config_->global_num_threads; tid++) { int pcode = port_code(nid, tid); senders_[pcode] = new zmq::socket_t(context, ZMQ_PUSH); char addr[64] = ""; sprintf(addr, "tcp://%s:%d", ibname.c_str(), r_node.tcp_port + 1 + tid); // FIXME: check return value senders_[pcode]->connect(addr); } } locks = (pthread_spinlock_t *)malloc(sizeof(pthread_spinlock_t) * (config_->global_num_threads * config_->global_num_workers)); for (int n = 0; n < config_->global_num_workers; n++) { for (int t = 0; t < config_->global_num_threads; t++) pthread_spin_init(&locks[n * config_->global_num_threads + t], 0); } schedulers = (scheduler_t *)malloc(sizeof(scheduler_t) * config_->global_num_threads); memset(schedulers, 0, sizeof(scheduler_t) * config_->global_num_threads); local_msgs = (ThreadSafeQueue<Message> **)malloc(sizeof(ThreadSafeQueue<Message>*) * config_->global_num_threads); for (int i = 0; i < config_->global_num_threads; i++) { local_msgs[i] = new ThreadSafeQueue<Message>(); } local_remote_ratio = 3; } int TCPMailbox::Send(int tid, const Message & msg) { if (msg.meta.recver_nid == my_node_.get_local_rank()) { local_msgs[msg.meta.recver_tid]->Push(msg); } else { int pcode = port_code(msg.meta.recver_nid, msg.meta.recver_tid); ibinstream m; m << msg; zmq::message_t zmq_msg(m.size()); memcpy((void *)zmq_msg.data(), m.get_buf(), m.size()); pthread_spin_lock(&locks[pcode]); if (senders_.find(pcode) == senders_.end()) { cout << "Cannot find dst_node port num" << endl; return 0; } senders_[pcode]->send(zmq_msg, ZMQ_DONTWAIT); pthread_spin_unlock(&locks[pcode]); } } bool TCPMailbox::TryRecv(int tid, Message & msg) { int type = (schedulers[tid].rr_cnt++) % local_remote_ratio; if (type != 0) { // Try local msg queue with higher priority if (local_msgs[tid]->Size() != 0) { local_msgs[tid]->WaitAndPop(msg); return true; } } zmq::message_t zmq_msg; obinstream um; // Try tcp recv if (receivers_[tid]->recv(&zmq_msg) < 0) { cout << "Node " << my_node_.get_local_rank() << " recvs with error " << strerror(errno) << std::endl; } else { char* buf = new char[zmq_msg.size()]; memcpy(buf, zmq_msg.data(), zmq_msg.size()); um.assign(buf, zmq_msg.size(), 0); um >> msg; return true; } return false; } void TCPMailbox::Recv(int tid, Message & msg) { return; } void TCPMailbox::Sweep(int tid) { return; }
31.756522
131
0.590635
BowenforGit
3705f38a7e270ef44de9ebb1fc16ffb0d6256bb6
8,109
cpp
C++
tests/test_liststorage.cpp
dkw-aau/trident-clone
18f896db2be05870069ae7b3aa6b4837c74fff0f
[ "Apache-2.0" ]
20
2018-10-17T21:39:40.000Z
2021-11-10T11:07:23.000Z
tests/test_liststorage.cpp
dkw-aau/trident-clone
18f896db2be05870069ae7b3aa6b4837c74fff0f
[ "Apache-2.0" ]
5
2020-07-06T22:50:04.000Z
2022-03-17T10:34:15.000Z
tests/test_liststorage.cpp
dkw-aau/trident-clone
18f896db2be05870069ae7b3aa6b4837c74fff0f
[ "Apache-2.0" ]
9
2018-09-18T11:37:35.000Z
2022-03-29T07:46:41.000Z
#include <iostream> #include <chrono> #include <cstdlib> #include "../src/kb/kb.h" #include "../src/kb/inserter.h" #include "../src/kb/querier.h" #include "../src/utils/propertymap.h" #include <sstream> #include <fstream> using namespace std; namespace timens = std::chrono; class MyTreeInserter: public TreeInserter { private: Inserter *ins; TermCoordinates c; public: MyTreeInserter(Inserter *ins) { this->ins = ins; } void addEntry(nTerm key, int64_t nElements, short file, int pos, char strategy) { c.set(0, file, pos, nElements, strategy); ins->insert(key, &c); } }; int main(int argc, const char** argv) { int n1 = 10000000 * 3; int64_t *array1 = new int64_t[n1]; for (int64_t i = 0; i < n1; ++i) { array1[i] = i; } int64_t firstKey = n1; int64_t *array2 = new int64_t[n1]; for (int64_t i = 0; i < n1; ++i) { if (i % 300 == 0) firstKey = i + n1; if (i % 3 == 0) array2[i] = firstKey; else array2[i] = i + n1; } int64_t startN3 = 2 * n1; firstKey = startN3; int64_t *array3 = new int64_t[n1]; for (int64_t i = 0; i < n1; ++i) { if (i % 30000 == 0) firstKey = i + startN3; if (i % 3 == 0) array3[i] = firstKey; else array3[i] = i + startN3; } cout << "Finished filling the array" << endl; KBConfig c; c.setParamInt(STORAGE_MAX_FILE_SIZE, 16 * 1024 * 1024); std::string inPath("/Users/jacopo/Desktop/kb"); KB *kb = new KB(inPath, false, c); Inserter *ins = kb->insert(); //Populate the tree std::chrono::system_clock::time_point start = std::chrono::system_clock::now(); cout << "Start inserting" << endl; MyTreeInserter tins(ins); for (int i = 0; i < n1; i += 3) { if (i % 1000000 == 0) { cout << "Inserting n1 " << i << endl; } ins->insert(0, array1[i], array1[i + 1], array1[i + 2], NULL, tins); } for (int i = 0; i < n1; i += 3) { if (i % 1000000 == 0) { cout << "Inserting n2 " << i << endl; } ins->insert(0, array2[i], array2[i + 1], array2[i + 2], NULL, tins); } for (int i = 0; i < n1; i += 3) { if (i % 1000000 == 0) { cout << "Inserting n3 " << i << endl; } ins->insert(0, array3[i], array3[i + 1], array3[i + 2], NULL, tins); } ins->flush(0, NULL, tins); std::chrono::duration<double> sec = std::chrono::system_clock::now() - start; cout << "Duration insertion " << sec.count() / 1000 << endl; delete[] array1; delete[] array2; delete[] array3; delete ins; delete kb; kb = new KB(inPath, true, c); Querier *q = kb->query(); //* TEST QUERIES *// for (int i = 0; i < n1; i += 3) { PairItr *itr = q->get(0, i, -1, -1); if (itr != NULL) { if (itr->has_next()) { itr->next_pair(); if (itr->getValue1() != i + 1 || itr->getValue2() != i + 2) { cerr << "Problem1" << endl; ; break; } } else { cerr << "Problem2" << endl; break; } q->releaseItr(itr); } else { cerr << "Not found " << i << endl; break; } } cout << "Finished N1 with x -1 -1" << endl; for (int i = 0; i < n1; i += 3) { PairItr *itr = q->get(0, i, i + 1, -1); if (itr != NULL) { if (itr->has_next()) { itr->next_pair(); if (itr->getValue1() != i + 1 || itr->getValue2() != i + 2) { cerr << "Problem1" << endl; ; break; } } else { cerr << "Problem2" << endl; break; } q->releaseItr(itr); } else { cerr << "Not found " << i << endl; break; } } cout << "Finished N1 with x y -1" << endl; for (int i = 0; i < n1; i += 3) { PairItr *itr = q->get(0, i, i + 1, i + 2); if (itr != NULL) { if (itr->has_next()) { itr->next_pair(); if (itr->getValue1() != i + 1 || itr->getValue2() != i + 2) { cerr << "Problem1" << endl; ; break; } } else { cerr << "Problem2" << endl; break; } q->releaseItr(itr); } else { cerr << "Not found " << i << endl; break; } } cout << "Finished N1 with x y z" << endl; for (int i = 0; i < n1; i += 300) { PairItr *itr = q->get(0, n1 + i, -1, -1); if (itr != NULL) { int count = 0; int countTriples = 0; while (itr->has_next()) { itr->next_pair(); if (itr->getValue1() != i + n1 + count + 1 || itr->getValue2() != i + n1 + count + 2) { cerr << "Problem " << itr->getValue1() << " " << itr->getValue2() << endl; break; } count += 3; countTriples++; } if (countTriples != 100) { cerr << "Problem2" << endl; break; } q->releaseItr(itr); } else { cout << "Not found " << i << endl; break; } } cout << "Finished N2 with x -1 -1" << endl; int offset = 0; for (int i = 0; i < n1; i += 300) { PairItr *itr = q->get(0, n1 + i, n1 + offset + i + 1, -1); if (itr != NULL) { int count = 0; while (itr->has_next()) { itr->next_pair(); if (itr->getValue1() != i + n1 + count + offset + 1 || itr->getValue2() != i + n1 + count + offset + 2) { cerr << "Problem " << itr->getValue1() << " " << itr->getValue2() << endl; break; } count += 3; } if (count != 3) { cerr << "Problem2" << endl; break; } q->releaseItr(itr); } else { cout << "Not found " << i << endl; break; } offset = (offset + 3) % 300; } cout << "Finished N2 with x y -1" << endl; offset = 0; for (int i = 0; i < n1; i += 300) { PairItr *itr = q->get(0, n1 + i, n1 + offset + i + 1, n1 + offset + i + 2); if (itr != NULL) { int count = 0; while (itr->has_next()) { itr->next_pair(); if (itr->getValue1() != i + n1 + count + offset + 1 || itr->getValue2() != i + n1 + count + offset + 2) { cerr << "Problem " << itr->getValue1() << " " << itr->getValue2() << endl; break; } count += 3; } if (count != 3) { cerr << "Problem2" << endl; break; } q->releaseItr(itr); } else { cout << "Not found " << i << endl; break; } offset = (offset + 3) % 300; } cout << "Finished N2 with x y z" << endl; for (int i = 0; i < n1; i += 30000) { PairItr *itr = q->get(0, startN3 + i, -1, -1); if (itr != NULL) { int count = 0; while (itr->has_next()) { itr->next_pair(); if (itr->getValue1() != i + startN3 + count + 1 || itr->getValue2() != i + startN3 + count + 2) { cerr << "Problem " << itr->getValue1() << " " << itr->getValue2() << endl; break; } count += 3; } if (count != 30000) { cerr << "Problem2" << endl; break; } q->releaseItr(itr); } else { cout << "Not found " << i << endl; break; } } cout << "Finished N3 with x -1 -1" << endl; offset = 0; for (int i = 0; i < n1; i += 30000) { PairItr *itr = q->get(0, startN3 + i, startN3 + offset + i + 1, -1); if (itr != NULL) { int count = 0; while (itr->has_next()) { itr->next_pair(); if (itr->getValue1() != i + startN3 + count + offset + 1 || itr->getValue2() != i + startN3 + count + offset + 2) { cerr << "Problem " << itr->getValue1() << " " << itr->getValue2() << endl; break; } count += 3; } if (count != 3) { cerr << "Problem2" << endl; break; } q->releaseItr(itr); } else { cout << "Not found " << i << endl; break; } offset = (offset + 3) % 30000; } cout << "Finished N3 with x y -1" << endl; offset = 0; for (int i = 0; i < n1; i += 30000) { PairItr *itr = q->get(0, startN3 + i, startN3 + offset + i + 1, startN3 + offset + i + 2); if (itr != NULL) { int count = 0; while (itr->has_next()) { itr->next_pair(); if (itr->getValue1() != i + startN3 + count + offset + 1 || itr->getValue2() != i + startN3 + count + offset + 2) { cerr << "Problem " << itr->getValue1() << " " << itr->getValue2() << endl; break; } count += 3; } if (count != 3) { cerr << "Problem2" << endl; break; } q->releaseItr(itr); } else { cout << "Not found " << i << endl; break; } offset = (offset + 3) % 30000; } cout << "Finished N3 with x y z" << endl; //Delete everything cout << "Delete everything" << endl; delete q; delete kb; return 0; }
21.97561
70
0.504378
dkw-aau
3705f507602c85b6e3150414f860120d5dd8ec8b
606
cpp
C++
src/api/cpp/util.cpp
JuliaComputing/arrayfire
93427f09ff928f97df29c0e358c3fcf6b478bec6
[ "BSD-3-Clause" ]
1
2018-06-14T23:49:18.000Z
2018-06-14T23:49:18.000Z
src/api/cpp/util.cpp
JuliaComputing/arrayfire
93427f09ff928f97df29c0e358c3fcf6b478bec6
[ "BSD-3-Clause" ]
1
2015-07-02T15:53:02.000Z
2015-07-02T15:53:02.000Z
src/api/cpp/util.cpp
JuliaComputing/arrayfire
93427f09ff928f97df29c0e358c3fcf6b478bec6
[ "BSD-3-Clause" ]
1
2018-02-26T17:11:03.000Z
2018-02-26T17:11:03.000Z
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <af/array.h> #include <af/util.h> #include "error.hpp" #include <cstdio> using namespace std; namespace af { void print(const char *exp, const array &arr) { printf("%s ", exp); AF_THROW(af_print_array(arr.get())); return; } }
23.307692
58
0.531353
JuliaComputing
370735f38fcb85decac68789dc4a5ae4b5220564
1,373
cpp
C++
demo/enable/qt/main.cpp
ricardocosme/saci
2a6a134f63b6e69fde452e0fe9bb5acfd149a6e4
[ "BSL-1.0" ]
1
2020-07-29T20:42:58.000Z
2020-07-29T20:42:58.000Z
demo/enable/qt/main.cpp
ricardocosme/saci
2a6a134f63b6e69fde452e0fe9bb5acfd149a6e4
[ "BSL-1.0" ]
null
null
null
demo/enable/qt/main.cpp
ricardocosme/saci
2a6a134f63b6e69fde452e0fe9bb5acfd149a6e4
[ "BSL-1.0" ]
null
null
null
// Copyright Ricardo Calheiros de Miranda Cosme 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <QtGui/QApplication> #include <QtGui/QDialog> #include <QtGui/QVBoxLayout> #include <coruja/object/object.hpp> #include <coruja/object/view/transform.hpp> #include <saci/qt/checkbox/checkbox.hpp> #include <saci/qt/textedit/textedit.hpp> #include <iostream> #include <string> using namespace coruja; int main(int argc, char** argv) { QApplication app(argc, argv); QDialog window; QVBoxLayout layout(&window); QCheckBox qcheckbox(&window); QTextEdit qtextedit(&window); layout.addWidget(&qcheckbox); layout.addWidget(&qtextedit); object<bool> model{false}; model.for_each([](bool v) { std::cout << "checkbox is " << (v ? "true" : "false") << std::endl; }); saci::qt::checkbox checkbox(model, qcheckbox); object<std::string> name{"Clear this text to disable the checkbox"}; name.for_each([](std::string s) { std::cout << "name is '" << s << "'" << std::endl; }); saci::qt::textedit textedit(name, qtextedit); window.show(); checkbox.enable(view::transform(name, [](std::string s){ return !s.empty(); })); model = true; return app.exec(); }
26.403846
84
0.651857
ricardocosme
370caf375423fb0162eb213407ee40f6b2f944d8
2,609
cpp
C++
Codility/generate_string2.cpp
SadiHassan/leet
0adc41d89c3e63a7a78d47dcd7eabeefe14972d6
[ "MIT" ]
1
2019-12-24T19:41:34.000Z
2019-12-24T19:41:34.000Z
Codility/generate_string2.cpp
SadiHassan/leet
0adc41d89c3e63a7a78d47dcd7eabeefe14972d6
[ "MIT" ]
null
null
null
Codility/generate_string2.cpp
SadiHassan/leet
0adc41d89c3e63a7a78d47dcd7eabeefe14972d6
[ "MIT" ]
1
2019-12-23T10:20:00.000Z
2019-12-23T10:20:00.000Z
#include <bits/stdc++.h> using namespace std; string generate_string(int A, int B, int C){ if(A + B + C == 0) return ""; string s = ""; if( A + B == 0){ for(int i = 1; i <= min(2,C); i++) s += 'c'; return s; } if( A + C == 0){ for(int i = 1; i <= min(2,B); i++) s += 'b'; return s; } if( B + C == 0){ for(int i = 1; i <= min(2,A); i++) s += 'a'; return s; } if( (A == B) && (B == C)){ for(int i = 1; i <= A; i++) s += "abc"; return s; } priority_queue< pair<int,char> > pq; pair<int,char> first, second; pq.push({A,'a'}); pq.push({B,'b'}); pq.push({C,'c'}); while(!pq.empty()) { first = pq.top(); pq.pop(); int len = s.size(); if(len > 0 && s[len - 1] == first.second){ if(pq.empty()) break; // s is the answer else{ second = pq.top();pq.pop(); s += second.second; second.first -= 1; if(second.first != 0) pq.push(second); pq.push(first); } } else{ int limit = min(2, first.first); for(int i = 0; i < limit; i++){ s += first.second; first.first -= 1; } if(first.first != 0) pq.push(first); } } return s; } bool is_valid(string str){ int len = str.size(); if(len < 3) return true; for(int i = 0; i < len - 3; i++){ if(str[i] == str[i + 1] && str[i + 1] == str[i + 2]) return false; } return true; } int main() { int A, B , C; A = 0; B = 0; C = 5; int MIN = 900; int MAX = 1000; string ans = generate_string(A, B, C); cout << ans << " " << ans.size() << " Valid = " << is_valid(ans)<< endl; bool output = true; if(output){ freopen("C:\\Users\\sadi\\GitHub\\leet\\Codility\\output.csv", "w", stdout); for(int A = MIN; A <= MAX; A++){ for(int B = MIN; B <= MAX; B++){ for(int C = MIN; C <= MAX; C++){ string ans = generate_string(A, B, C); int len = ans.size(); string validity = ""; if(!is_valid(ans)) validity = "INVALID"; cout << A << "," << B << "," << C << "," << len << "," << validity << ","<< ans << endl; } } } fclose(stdout); } return 0; }
26.09
116
0.377539
SadiHassan
37135548258fe56d855aeb2cd8734811708f4539
5,265
cpp
C++
timer.cpp
AngularsCoding/Timer
949e9b65a665fe69cec2822e508727828633fdbe
[ "CC0-1.0" ]
1
2021-05-21T05:51:38.000Z
2021-05-21T05:51:38.000Z
timer.cpp
AngularsCoding/Timer
949e9b65a665fe69cec2822e508727828633fdbe
[ "CC0-1.0" ]
null
null
null
timer.cpp
AngularsCoding/Timer
949e9b65a665fe69cec2822e508727828633fdbe
[ "CC0-1.0" ]
2
2021-04-18T07:36:15.000Z
2022-01-04T14:44:49.000Z
#include<iostream> #include<conio.h> #include<dos.h> #include <windows.h> #include <time.h> using namespace std; char d0[5][3] = { 178,178,178, 178,' ',178, 178,' ',178, 178,' ',178, 178,178,178 }; char d1[5][3] = { ' ',' ',178, ' ',' ',178, ' ',' ',178, ' ',' ',178, ' ',' ',178 }; char d2[5][3] = { 178,178,178, ' ',' ',178, 178,178,178, 178,' ',' ', 178,178,178 }; char d3[5][3] = { 178,178,178, ' ',' ',178, 178,178,178, ' ',' ',178, 178,178,178 }; char d4[5][3] = { 178,' ',178, 178,' ',178, 178,178,178, ' ',' ',178, ' ',' ',178 }; char d5[5][3] = { 178,178,178, 178,' ',' ', 178,178,178, ' ',' ',178, 178,178,178 }; char d6[5][3] = { 178,178,178, 178,' ',' ', 178,178,178, 178,' ',178, 178,178,178 }; char d7[5][3] = { 178,178,178, ' ',' ',178, ' ',' ',178, ' ',' ',178, ' ',' ',178 }; char d8[5][3] = { 178,178,178, 178,' ',178, 178,178,178, 178,' ',178, 178,178,178 }; char d9[5][3] = { 178,178,178, 178,' ',178, 178,178,178, ' ',' ',178, ' ',' ',178 }; char sep[5][3] = { ' ',' ',' ', ' ',178,' ', ' ',' ',' ', ' ',178,' ', ' ',' ',' ' }; HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); COORD CursorPosition; void gotoxy(int x, int y){ CursorPosition.X = x; CursorPosition.Y = y; SetConsoleCursorPosition(console, CursorPosition); } void setcursor(bool visible, DWORD size) { if(size == 0) size = 20; CONSOLE_CURSOR_INFO lpCursor; lpCursor.bVisible = visible; lpCursor.dwSize = size; SetConsoleCursorInfo(console,&lpCursor); } void printDigit(int no, int x, int y ){ for(int i=0; i<5; i++){ for(int j=0; j<3; j++){ switch(no){ case 0: gotoxy(x+j, y+i); cout<<d0[i][j]; break; case 1: gotoxy(x+j, y+i); cout<<d1[i][j]; break; case 2: gotoxy(x+j, y+i); cout<<d2[i][j]; break; case 3: gotoxy(x+j, y+i); cout<<d3[i][j]; break; case 4: gotoxy(x+j, y+i); cout<<d4[i][j]; break; case 5: gotoxy(x+j, y+i); cout<<d5[i][j]; break; case 6: gotoxy(x+j, y+i); cout<<d6[i][j]; break; case 7: gotoxy(x+j, y+i); cout<<d7[i][j]; break; case 8: gotoxy(x+j, y+i); cout<<d8[i][j]; break; case 9: gotoxy(x+j, y+i); cout<<d9[i][j]; break; case 10: gotoxy(x+j, y+i); cout<<sep[i][j]; break; } } } } void drawBorder(int x=0, int y=0){ char v = 186; // vertical char h = 205; // horizontal char tr = 187; char br = 188; char tl = 201; char bl = 200; int width = 50; int height = 11; gotoxy((width/2)+x-11, y); cout<<"T I M E R P R O G R E S S"; for( int i=1; i<=height; i++ ){ for( int j=1; j<=width; j++ ){ gotoxy(j+x,i+y); if( i==1 && j==1 ) cout<< tl; else if( i==height && j==1 ) cout<< bl; else if( i==1 && j==width ) cout<< tr; else if( i==height && j==width ) cout<< br; else if( i==1 || i==height ) cout<< h; else if( j==1 || j==width ) cout<< v; } } } int main() { system("cls"); setcursor(0,0); int hour = 0; int min = 0; int sec = 0; int timerStart = 1; int gap = 5; int posX; int posY = 8; char op; do{ system("cls"); cout<<endl<<endl; cout<<"======================================="<<endl; cout<<" T I M E R "<<endl; cout<<"======================================="<<endl<<endl; cout<<"Set Time for Timer "<<endl<<endl; cout<<"Enter Hour: "; cin>> hour; cout<<"Enter Minute: "; cin>> min; cout<<"Enter Seconds: "; cin>> sec; while(1){ system("cls"); drawBorder(9,4); posX = 15; if(kbhit()){ char ch = getch(); if(ch==27){ break; } } if( hour < 10 ){ printDigit(0, posX, posY); printDigit(hour, posX+=gap, posY); } else{ printDigit(hour/10, posX, posY); printDigit(hour%10, posX+=gap, posY); } printDigit(10, posX+=gap, posY); if( min < 10 ){ printDigit(0, posX+=gap, posY); printDigit(min, posX+=gap, posY); } else{ printDigit(min/10, posX+=gap, posY); printDigit(min%10, posX+=gap, posY); } printDigit(10, posX+=gap, posY); if( sec < 10 ){ printDigit(0, posX+=gap, posY); printDigit(sec, posX+=gap, posY); } else{ printDigit(sec/10, posX+=gap, posY); printDigit(sec%10, posX+=gap, posY); } //50 millisecond processing time is deducted, you can change it... Sleep(950); if( hour == 0 && min == 0 && sec == 0 ){ gotoxy(10,18); cout<<"Timer Stopped"; // getch(); break; } sec--; if( sec<0 ){ sec = 59; min--; } if( min<0 ){ min = 59; hour--; } if( hour<0 ){ sec = 0; min = 0; hour = 0; } } gotoxy(10,20); cout<<"Do you want to use timer again (y/n): "; op = getch(); }while(op=='y' || op=='Y'); return 0; }
20.566406
70
0.447483
AngularsCoding
37153e87eecf7221a4529aaef208c21b6ecde840
1,769
cpp
C++
codelib/huffman_coding.cpp
TissueRoll/admu-progvar-notebook
efd1c48872d40aeabe2b03af7b986bb831c062b1
[ "MIT" ]
null
null
null
codelib/huffman_coding.cpp
TissueRoll/admu-progvar-notebook
efd1c48872d40aeabe2b03af7b986bb831c062b1
[ "MIT" ]
null
null
null
codelib/huffman_coding.cpp
TissueRoll/admu-progvar-notebook
efd1c48872d40aeabe2b03af7b986bb831c062b1
[ "MIT" ]
null
null
null
#include <cstdlib> #include <iostream> #include <queue> #include <string> #include <vector> #include <cstring> #include <utility> #include <map> typedef std::pair<int, int> ii; const int MAXN = 1000; std::string huffman_codes[MAXN]; std::vector<int> adj[MAXN]; std::string seq; void dfs(int u) { if (adj[u].size() == 0) { huffman_codes[u] = seq; } else { seq.push_back('0'); dfs(adj[u][0]); seq.pop_back(); seq.push_back('1'); dfs(adj[u][1]); seq.pop_back(); } } int main() { std::string s; std::getline(std::cin, s); int freq[256]; memset(freq, 0, sizeof freq); for (int i = 0; i < s.length(); ++i) freq[s[i]]++; std::priority_queue<ii, std::vector<ii>, std::greater<ii> > pq; std::string chars = ""; std::map<char, int> char_to_idx; for (int i = 0; i < 256; ++i) { if (freq[i]) { pq.push({freq[i], chars.size()}); char_to_idx[char(i)] = chars.size(); chars.push_back(char(i)); } } int N = chars.length(); int orig_n = N; while (pq.size() > 1) { ii u = pq.top(); pq.pop(); ii v = pq.top(); pq.pop(); adj[N].push_back(u.second); adj[N].push_back(v.second); pq.push({u.first + v.first, N}); N++; } seq = ""; dfs(N - 1); std::cout<<"\nhuffman codes:\n"; std::printf("char | freq | code\n"); for (int i = 0; i < orig_n; ++i) std::printf("%4c%7d%7s\n", chars[i], freq[chars[i]], huffman_codes[i].c_str()); std::cout<<"\nencryption of the original text:\n"; int huffman_length = 0; for (char c : s) { std::cout<<huffman_codes[char_to_idx[c]]; huffman_length += huffman_codes[char_to_idx[c]].size(); } std::cout<<"\n"; std::cout<<"\nlength of encrypted text:\n"; std::cout<<huffman_length; return 0; }
21.313253
83
0.568683
TissueRoll
371556693e55cba56c46e6aef434fe69c28613b3
6,890
hpp
C++
mjolnir/forcefield/local/BondLengthGoContactInteraction.hpp
ToruNiina/Mjolnir
44435dd3afc12f5c8ea27a66d7ab282df3e588ff
[ "MIT" ]
12
2017-02-01T08:28:38.000Z
2018-08-25T15:47:51.000Z
mjolnir/forcefield/local/BondLengthGoContactInteraction.hpp
Mjolnir-MD/Mjolnir
043df4080720837042c6b67a5495ecae198bc2b3
[ "MIT" ]
60
2019-01-14T08:11:33.000Z
2021-07-29T08:26:36.000Z
mjolnir/forcefield/local/BondLengthGoContactInteraction.hpp
Mjolnir-MD/Mjolnir
043df4080720837042c6b67a5495ecae198bc2b3
[ "MIT" ]
8
2019-01-13T11:03:31.000Z
2021-08-01T11:38:00.000Z
#ifndef MJOLNIR_INTERACTION_BOND_LENGTH_GO_CONTACT_INTERACTION_HPP #define MJOLNIR_INTERACTION_BOND_LENGTH_GO_CONTACT_INTERACTION_HPP #include <mjolnir/forcefield/local/BondLengthInteraction.hpp> #include <mjolnir/forcefield/local/GoContactPotential.hpp> namespace mjolnir { // It is a specialization of BondLengthInteraction for GoContactPotential. // In the case of GoContactPotential, we can omit `sqrt` call that is // normally used to calculate distance because we only needs the squared distance. template<typename realT, template<typename, typename> class boundaryT> class BondLengthInteraction< SimulatorTraits<realT, boundaryT>, GoContactPotential<realT> > final : public LocalInteractionBase<SimulatorTraits<realT, boundaryT>> { public: using traits_type = SimulatorTraits<realT, boundaryT>; using potential_type = GoContactPotential<realT>; using base_type = LocalInteractionBase<traits_type>; using real_type = typename base_type::real_type; using coordinate_type = typename base_type::coordinate_type; using system_type = typename base_type::system_type; using topology_type = typename base_type::topology_type; using connection_kind_type = typename base_type::connection_kind_type; using indices_type = std::array<std::size_t, 2>; using potential_index_pair = std::pair<indices_type, potential_type>; using container_type = std::vector<potential_index_pair>; using iterator = typename container_type::iterator; using const_iterator = typename container_type::const_iterator; public: BondLengthInteraction(const connection_kind_type kind, const container_type& pot) : kind_(kind), potentials_(pot) {} BondLengthInteraction(const connection_kind_type kind, container_type&& pot) : kind_(kind), potentials_(std::move(pot)) {} ~BondLengthInteraction() override {} real_type calc_energy(const system_type& sys) const noexcept override { real_type E = 0.; for(const auto& idxp : this->potentials_) { E += idxp.second.potential(math::length(sys.adjust_direction( sys.position(idxp.first[0]), sys.position(idxp.first[1])))); } return E; } void calc_force(system_type& sys) const noexcept override { this->template calc_force_energy_virial_impl<false, false>(sys); return; } void calc_force_and_virial(system_type& sys) const noexcept override { this->template calc_force_energy_virial_impl<false, true>(sys); return; } real_type calc_force_and_energy(system_type& sys) const noexcept override { return this->template calc_force_energy_virial_impl<true, false>(sys); } real_type calc_force_virial_energy(system_type& sys) const noexcept override { return this->template calc_force_energy_virial_impl<true, true>(sys); } void initialize(const system_type& sys) override { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); MJOLNIR_LOG_INFO("potential = ", potential_type::name(), ", number of bonds = ", potentials_.size()); for(auto& potential : potentials_) { potential.second.initialize(sys); } return; } void update(const system_type& sys) override { for(auto& item : potentials_) { item.second.update(sys); } } // do nothing. this is used to reduce margin of neighbor list, and added // to this class for the consistency. void reduce_margin(const real_type, const system_type&) override {return;} void scale_margin(const real_type, const system_type&) override {return;} std::string name() const override {return "BondLengthGoContact"_s;} void write_topology(topology_type& topol) const override { if(this->kind_.empty() || this->kind_ == "none") {return;} for(const auto& idxp : this->potentials_) { const auto i = idxp.first[0]; const auto j = idxp.first[1]; topol.add_connection(i, j, this->kind_); } return; } container_type const& potentials() const noexcept {return potentials_;} container_type& potentials() noexcept {return potentials_;} base_type* clone() const override { return new BondLengthInteraction(kind_, container_type(potentials_)); } private: template<bool NeedEnergy, bool NeedVirial> real_type calc_force_energy_virial_impl(system_type& sys) const noexcept { real_type energy = 0; for(const auto& idxp : this->potentials_) { const std::size_t idx0 = idxp.first[0]; const std::size_t idx1 = idxp.first[1]; const auto& pot = idxp.second; const auto dpos = sys.adjust_direction(sys.position(idx0), sys.position(idx1)); const real_type len2 = math::length_sq(dpos); if(pot.cutoff() * pot.cutoff() <= len2) { continue; } const real_type r2 = real_type(1) / len2; const real_type v0r_2 = pot.v0() * pot.v0() * r2; const real_type v0r_6 = v0r_2 * v0r_2 * v0r_2; const real_type v0r_10 = v0r_6 * v0r_2 * v0r_2; const real_type v0r_12 = v0r_10 * v0r_2; if(NeedEnergy) { energy += pot.k() * (5 * v0r_12 - 6 * v0r_10); } const auto coef = -60 * pot.k() * r2 * (v0r_10 - v0r_12); const auto f = coef * dpos; sys.force(idx0) -= f; sys.force(idx1) += f; if(NeedVirial) { sys.virial() += math::tensor_product(dpos, f); } } return energy; } private: connection_kind_type kind_; container_type potentials_; }; } // mjolnir #ifdef MJOLNIR_SEPARATE_BUILD #include <mjolnir/core/BoundaryCondition.hpp> #include <mjolnir/core/SimulatorTraits.hpp> namespace mjolnir { // go-contact extern template class BondLengthInteraction<SimulatorTraits<double, UnlimitedBoundary >, GoContactPotential<double>>; extern template class BondLengthInteraction<SimulatorTraits<float, UnlimitedBoundary >, GoContactPotential<float> >; extern template class BondLengthInteraction<SimulatorTraits<double, CuboidalPeriodicBoundary>, GoContactPotential<double>>; extern template class BondLengthInteraction<SimulatorTraits<float, CuboidalPeriodicBoundary>, GoContactPotential<float> >; } // mjolnir #endif // MJOLNIR_SEPARATE_BUILD #endif /* MJOLNIR_INTERACTION_BOND_LENGTH_GO_CONTACT_INTERACTION_HPP */
35.515464
123
0.651814
ToruNiina
7dec0f68c58b5959660a5c56b6c704de6e673133
768
cpp
C++
Card/Capacity.cpp
GP-S/HOTS
85903015033184694e3b2b70af401a0ea5de11b7
[ "Unlicense", "MIT" ]
1
2021-05-30T02:13:37.000Z
2021-05-30T02:13:37.000Z
Card/Capacity.cpp
GP-S/HOTS
85903015033184694e3b2b70af401a0ea5de11b7
[ "Unlicense", "MIT" ]
null
null
null
Card/Capacity.cpp
GP-S/HOTS
85903015033184694e3b2b70af401a0ea5de11b7
[ "Unlicense", "MIT" ]
null
null
null
#include "Capacity.h" Capacity::Capacity() { } Capacity::Capacity(std::string type,int durabilty) { this->type=type; this->durabilty=durabilty; } Capacity::~Capacity() { } std::string Capacity::getType() { return type; } int Capacity::getDurabilty() { return durabilty; } void Capacity::setType(std::string type) { this->type=type; } void Capacity::setDurabilty(int durabilty) { this->durabilty = durabilty; } void Capacity::setActive(bool active) { this->active=active; } bool Capacity::getActive() { return active; } void Capacity::decreaseDurability(){ if(durabilty != -1) durabilty--; } Effect* Capacity::getEffect(){ return effect; } void Capacity::setEffect(Effect* effect){ this->effect=effect; }
11.294118
50
0.666667
GP-S
7ded9d03e247477b501dffca22b3b13b0bae1e58
2,440
hpp
C++
include/asioext/impl/file_handle_win.hpp
zweistein-frm2/asio-extensions
bafea77c48d674930405cb7f93bdfe65539abc39
[ "BSL-1.0" ]
17
2018-04-13T00:38:55.000Z
2022-01-21T08:38:36.000Z
include/asioext/impl/file_handle_win.hpp
zweistein-frm2/asio-extensions
bafea77c48d674930405cb7f93bdfe65539abc39
[ "BSL-1.0" ]
4
2017-03-16T03:34:38.000Z
2020-05-08T00:05:51.000Z
include/asioext/impl/file_handle_win.hpp
zweistein-frm2/asio-extensions
bafea77c48d674930405cb7f93bdfe65539abc39
[ "BSL-1.0" ]
5
2017-09-06T15:56:04.000Z
2021-09-14T07:38:02.000Z
/// @copyright Copyright (c) 2015 Tim Niederhausen (tim@rnc-ag.de) /// Distributed under the Boost Software License, Version 1.0. /// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef ASIOEXT_IMPL_FILEHANDLE_WIN_HPP #define ASIOEXT_IMPL_FILEHANDLE_WIN_HPP #include "asioext/file_handle.hpp" #include "asioext/detail/win_file_ops.hpp" #include "asioext/detail/buffer.hpp" ASIOEXT_NS_BEGIN // Note: Currently always only the first buffer is used. // This is possible since we can get away with returning less than requested // and is unfortunately the only way this can be implemented reasonably. // // Windows has vectored I/O functions (ReadFileScatter, WriteFileGather), // but they impose very strict alignment and size requirements and are thus // unusable here. template <typename MutableBufferSequence> std::size_t file_handle::read_some(const MutableBufferSequence& buffers, error_code& ec) ASIOEXT_NOEXCEPT { const asio::mutable_buffer buf = asioext::first_mutable_buffer(buffers); return detail::win_file_ops::read( handle_, buf.data(), static_cast<uint32_t>(buf.size()), ec); } template <typename ConstBufferSequence> std::size_t file_handle::write_some(const ConstBufferSequence& buffers, error_code& ec) ASIOEXT_NOEXCEPT { const asio::const_buffer buf = asioext::first_const_buffer(buffers); return detail::win_file_ops::write( handle_, buf.data(), static_cast<uint32_t>(buf.size()), ec); } template <typename MutableBufferSequence> std::size_t file_handle::read_some_at(uint64_t offset, const MutableBufferSequence& buffers, error_code& ec) ASIOEXT_NOEXCEPT { const asio::mutable_buffer buf = asioext::first_mutable_buffer(buffers); return detail::win_file_ops::pread( handle_, buf.data(), static_cast<uint32_t>(buf.size()), offset, ec); } template <typename ConstBufferSequence> std::size_t file_handle::write_some_at(uint64_t offset, const ConstBufferSequence& buffers, error_code& ec) ASIOEXT_NOEXCEPT { const asio::const_buffer buf = asioext::first_const_buffer(buffers); return detail::win_file_ops::pwrite( handle_, buf.data(), static_cast<uint32_t>(buf.size()), offset, ec); } ASIOEXT_NS_END #endif
38.125
91
0.706967
zweistein-frm2
7def13f11c951427394d6b51cffee9e0b0b764bd
595
hpp
C++
Blast2D/core/ecs/type_info.hpp
daethalus/Blast2D
f8063a298d0f4059435d13e9390def3ebf62be5f
[ "MIT" ]
null
null
null
Blast2D/core/ecs/type_info.hpp
daethalus/Blast2D
f8063a298d0f4059435d13e9390def3ebf62be5f
[ "MIT" ]
null
null
null
Blast2D/core/ecs/type_info.hpp
daethalus/Blast2D
f8063a298d0f4059435d13e9390def3ebf62be5f
[ "MIT" ]
null
null
null
#ifndef BLAST2D_TYPE_INFO_HPP #define BLAST2D_TYPE_INFO_HPP #include <string> #include <iostream> #include <vector> namespace Blast2D{ using Index = std::size_t; template<typename Type> struct TypeInfo { static Index index(Index index) { static const Index constIndex = index; return constIndex; } static Index resource(Index resource) { static const Index constResource = resource; return constResource; } static Index index() { return index(0); } }; } #endif
17.5
56
0.601681
daethalus
7df5a1f6d3c8bbe89c9c71591f5fe533d9086486
2,628
ipp
C++
include/stats_incl/dens/dinvwish.ipp
davidnsw/sss
8ca2e4c28027e62ca1238724dc2912d2205e16b6
[ "Apache-2.0" ]
null
null
null
include/stats_incl/dens/dinvwish.ipp
davidnsw/sss
8ca2e4c28027e62ca1238724dc2912d2205e16b6
[ "Apache-2.0" ]
null
null
null
include/stats_incl/dens/dinvwish.ipp
davidnsw/sss
8ca2e4c28027e62ca1238724dc2912d2205e16b6
[ "Apache-2.0" ]
null
null
null
/*################################################################################ ## ## Copyright (C) 2011-2020 Keith O'Hara ## ## This file is part of the StatsLib C++ library. ## ## 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. ## ################################################################################*/ /* * pdf of the inverse-Wishart distribution */ /** * @brief Density function of the Inverse-Wishart distribution * * @param X a positive semi-definite matrix. * @param Psi_par a positive semi-definite scale matrix. * @param nu_par the degrees of parameter, a real-valued input. * @param log_form return the log-density or the true form. * * @return the density function evaluated at \c X. */ template<typename mT, typename pT, typename not_arma_mat<mT>::type*> statslib_inline return_t<pT> dinvwish(const mT& X, const mT& Psi_par, const pT nu_par, bool const log_form) { typedef return_t<pT> eT; const ullint_t K = mat_ops::n_rows(X); const eT nu_par_d2 = static_cast<eT>(nu_par) / eT(2); // const eT lmg_term = gcem::lmgamma(nu_par_d2, K); const eT norm_term = nu_par_d2*mat_ops::log_det(Psi_par) - nu_par_d2*K*eT(GCEM_LOG_2) - lmg_term; eT ret = norm_term - eT(0.5) * ( (nu_par+K+1) * mat_ops::log_det(X) + mat_ops::trace(mat_ops::solve(X,Psi_par)) ); if (!log_form) { ret = std::exp(ret); } // return ret; } #ifdef STATS_ENABLE_ARMA_WRAPPERS template<typename eT, typename pT> statslib_inline eT dinvwish(const ArmaMat<eT>& X, const ArmaMat<eT>& Psi_par, const pT nu_par, const bool log_form) { const ullint_t K = X.n_rows; const eT nu_par_d2 = static_cast<eT>(nu_par) / eT(2); // const eT lmg_term = gcem::lmgamma(nu_par_d2, K); const eT norm_term = nu_par_d2*mat_ops::log_det(Psi_par) - nu_par_d2*K*eT(GCEM_LOG_2) - lmg_term; eT ret = norm_term - eT(0.5) * ( (nu_par+K+1) * mat_ops::log_det(X) + mat_ops::trace(mat_ops::solve(X,Psi_par)) ); if (!log_form) { ret = std::exp(ret); } // return ret; } #endif
30.206897
118
0.624429
davidnsw
7df6ebead745d69a55fa21c29fdaf2a2abdcada9
1,163
hpp
C++
MEX/src/cpp/body_pose/body_pose_types.hpp
umariqb/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
47
2016-07-25T00:48:59.000Z
2021-02-17T09:19:03.000Z
MEX/src/cpp/body_pose/body_pose_types.hpp
umariqb/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
5
2016-09-17T19:40:46.000Z
2018-11-07T06:49:02.000Z
MEX/src/cpp/body_pose/body_pose_types.hpp
iqbalu/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
35
2016-07-21T09:13:15.000Z
2019-05-13T14:11:37.000Z
#ifndef BODY_POSE_TYPES_HH #define BODY_POSE_TYPES_HH /* * body_pose_types.hpp * * Created on: Oct 15, 2014 * Author: Umar Iqbal */ namespace body_pose{ // TYPE_BODY_J[Number of Joints] // pose style enum BodyPoseTypes { FULL_BODY_J13 = 13, /* /\ /| |\ [head, l_sho, r_sho, l_hips, r_hips, l_elb, l_wri, r_elb, r_wri, l_knee, l_ankl, r_knee, r_ankl] | | \ / */ FULL_BODY_J14 = 14, //[head_top, neck, l_sho, r_sho, l_hips, r_hips, l_elb, l_wri, r_elb, r_wri, l_knee, l_ankl, r_knee, r_ankl] FULL_BODY_J17 = 17, // [head_top, chin, neck, l_sho', r_sho', abdomen', root', l_hip', r_hip', l_elb', l_wri', r_elb', r_wri' l_knee', l_ankl', r_knee', r_ankle] FULL_BODY_J13_TEMPORAL = 39, // with two neighbouring frames UPPER_BODY_J7 = 7, // upper body parts without hips UPPER_BODY_J9 = 9, // upper body parts with hip joints }; } #endif
40.103448
185
0.504729
umariqb
7df7454f92487cda17f4e025b9d377b7ff960792
2,363
cpp
C++
general/sets.cpp
benzwick/mfem
4d5fdfd553b24ff37716f736f83df2d238d9a696
[ "BSD-3-Clause" ]
1
2020-08-15T07:00:22.000Z
2020-08-15T07:00:22.000Z
general/sets.cpp
benzwick/mfem
4d5fdfd553b24ff37716f736f83df2d238d9a696
[ "BSD-3-Clause" ]
1
2019-04-24T21:18:24.000Z
2019-04-25T18:00:45.000Z
general/sets.cpp
benzwick/mfem
4d5fdfd553b24ff37716f736f83df2d238d9a696
[ "BSD-3-Clause" ]
1
2021-09-15T14:14:29.000Z
2021-09-15T14:14:29.000Z
// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "sets.hpp" namespace mfem { IntegerSet::IntegerSet(IntegerSet &s) : me(s.me.Size()) { for (int i = 0; i < me.Size(); i++) { me[i] = s.me[i]; } } int IntegerSet::operator== (IntegerSet &s) { if (me.Size() != s.me.Size()) { return 0; } for (int i = 0; i < me.Size(); i++) if (me[i] != s.me[i]) { return 0; } return 1; } int IntegerSet::PickRandomElement() { int i, size = me.Size(); unsigned int seed = 0; for (i = 0; i < size; i++) { seed += me[i]; } srand(seed); return me[rand()/(RAND_MAX/size)]; } void IntegerSet::Recreate(const int n, const int *p) { int i, j; me.SetSize(n); for (i = 0; i < n; i++) { me[i] = p[i]; } me.Sort(); for (j = 0, i = 1; i < n; i++) if (me[i] != me[j]) { me[++j] = me[i]; } me.SetSize(j+1); } int ListOfIntegerSets::Insert(IntegerSet &s) { for (int i = 0; i < TheList.Size(); i++) if (*TheList[i] == s) { return i; } TheList.Append(new IntegerSet(s)); return TheList.Size()-1; } int ListOfIntegerSets::Lookup(IntegerSet &s) { for (int i = 0; i < TheList.Size(); i++) if (*TheList[i] == s) { return i; } mfem_error("ListOfIntegerSets::Lookup (), integer set not found."); return -1; } void ListOfIntegerSets::AsTable(Table & t) { int i; t.MakeI(Size()); for (i = 0; i < Size(); i++) { t.AddColumnsInRow(i, TheList[i] -> Size()); } t.MakeJ(); for (i = 0; i < Size(); i++) { Array<int> &row = *TheList[i]; t.AddConnections(i, row.GetData(), row.Size()); } t.ShiftUpI(); } ListOfIntegerSets::~ListOfIntegerSets() { for (int i = 0; i < TheList.Size(); i++) { delete TheList[i]; } } }
17.123188
80
0.547609
benzwick
7dfc182c5e772de58ddce7507e1a8f9a84f7d863
1,088
hpp
C++
src/engine/texturesystem.hpp
Spirrwell/Mod-Engine
9b9c7e3d6e14450d8a3f807bca8a9244f6e8b23d
[ "MIT" ]
2
2020-03-19T14:13:07.000Z
2020-09-07T07:26:23.000Z
src/engine/texturesystem.hpp
Spirrwell/Mod-Engine
9b9c7e3d6e14450d8a3f807bca8a9244f6e8b23d
[ "MIT" ]
3
2020-03-28T04:05:04.000Z
2020-05-08T06:38:18.000Z
src/engine/texturesystem.hpp
Spirrwell/Mod-Engine
9b9c7e3d6e14450d8a3f807bca8a9244f6e8b23d
[ "MIT" ]
null
null
null
#ifndef TEXTURESYSTEM_HPP #define TEXTURESYSTEM_HPP #include <unordered_map> #include <string> #include <mutex> #include "engine/itexturesystem.hpp" #include "enginesystem.hpp" #include "filesystem.hpp" #include "memory.hpp" #include "vulkansystem.hpp" class Texture; class TextureSystem : public ITextureSystem, public EngineSystem { public: void configure( Engine *engine ) override; void unconfigure( Engine *engine ) override; void LoadDefaultTextures(); ITexture *LoadTexture( const std::filesystem::path &relpath, const std::string &pathid, IResourcePool *resourcePoolPtr ) override; ITexture *FindTexture( const std::filesystem::path &relpath, IResourcePool *resourcePoolPtr ) const override; private: ITexture *FindTexture_Internal( const std::filesystem::path &relpath, IResourcePool *resourcePoolPtr ) const; public: Texture *GetErrorTexture() const { return errorTexture; } private: FileSystem *fileSystem = nullptr; VulkanSystem *vulkanSystem = nullptr; Texture *errorTexture = nullptr; mutable std::mutex texturesMutex; }; #endif // TEXTURESYSTEM_HPP
24.727273
131
0.779412
Spirrwell
b40123b2a4275eebc30ce29d3b8c8f7208bc4534
4,197
cpp
C++
graph-source-code/362-E/5897240.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/362-E/5897240.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/362-E/5897240.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++ #include <cstdio> #include <iostream> #include <vector> #include <list> #include <queue> #include <map> #include <set> #include <utility> #include <functional> #include <string> #include <algorithm> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; typedef long long ll; typedef pair<int,int> pii; typedef map<int,int> mii; typedef vector<int> vi; typedef vector< vector<int> > vvi; typedef vector<char> vc; typedef vector<bool> vb; typedef vector<string> vs; #define rep(i,n) for(int i=0;i<(n);i++) #define forup(i,a,b) for(int i=(a);i<=(b);i++) #define fordn(i,a,b) for(int i=(a);i>=(b);i--) #define drep(i,n) for(i=0;i<(n);i++) #define dforup(i,a,b) for(i=(a);i<=(b);i++) #define dfordn(i,a,b) for(i=(a);i>=(b);i--) #define all(x) x.begin(),x.end() #define permute(x) next_permutation(all(x)) #define pb push_back #define mp make_pair #define fi first #define sc second #define gi(x) scanf("%d",&x) // MinCostMaxFlow Codechunk const int inv=int(1e9); const int max_v=55; // u:neighbour, p:price per unit flow, c:capacity, f:flow // oix: if adjlel a belongs to adjl[v] then oix is s.t. adjl[a.u][a.oix].u=v; // oix: abbreviation for 'opposite index' struct adjlel { int u,p,c,f,oix; adjlel(){} adjlel(int u_, int p_, int c_, int f_, int oix_){u=u_; p=p_; c=c_; f=f_; oix=oix_;} }; struct less_adjlel : public binary_function < adjlel, adjlel, bool > { bool operator()(const adjlel &a, const adjlel &b){ return pii(a.u,a.p)<pii(b.u,b.p); } }; int s,t; int v,e; vector< adjlel > fadjl[max_v], adjl[max_v]; // fadjl is useful only as a temporary storage to facilitate construction of adjl // fadjl should be used only if the original graph has multiple edges which are replaceable by a single edge // If not, both fadjl and less_adjlel are useless. This will be the case for most problems. // fadjl and less_adjlel are highly problem specific and should be used only after analysis int dst[max_v]; int par[max_v]; int pvix[max_v]; int vpix[max_v]; int aug[max_v]; queue<int> Q; int augval; bool inQ[max_v]; bool augmentingpath() { while(!Q.empty()) Q.pop(); fill(dst,dst+v,inv); fill(inQ,inQ+v,false); fill(pvix,pvix+v,-1); fill(vpix,vpix+v,-1); dst[s]=0; par[s]=s; aug[s]=inv; Q.push(s); inQ[s]=true; while(!Q.empty()) { int vt=Q.front(); Q.pop(); inQ[vt]=false; rep(i,adjl[vt].size()) { int nb=adjl[vt][i].u; if(adjl[vt][i].c-adjl[vt][i].f>0 and dst[vt]!=inv and dst[vt]+adjl[vt][i].p<dst[nb]) { if(not inQ[nb]) { Q.push(nb); inQ[nb]=true; } dst[nb]=dst[vt]+adjl[vt][i].p; pvix[nb]=i; vpix[nb]=adjl[vt][i].oix; par[nb]=vt; aug[nb]=min(aug[vt],adjl[vt][i].c-adjl[vt][i].f); } } } augval=aug[t]; return (dst[t]!=inv); } void augmentflow(int vt) { if(par[vt]!=vt) { adjl[par[vt]][pvix[vt]].f+=augval; adjl[vt][vpix[vt]].f-=augval; augmentflow(par[vt]); } } int findmincostmaxflow() { while(augmentingpath()) augmentflow(t); int mincostmaxflow=0; /*rep(vt,v) rep(nb,v) if(f[vt][nb]>0) mincostmaxflow+=f[vt][nb]*p[vt][nb];*/ rep(vt,v) rep(i,adjl[vt].size()) { if(adjl[vt][i].f>0) mincostmaxflow+=(adjl[vt][i].f*adjl[vt][i].p); } return mincostmaxflow; } // End of Codechunk int n,k,c[max_v][max_v]; void add_edge(int u,int v,int cap,int price) { int szu=adjl[u].size(),szv=adjl[v].size(); //printf("%d %d %d %d\n",u,v,cap,price); adjl[u].pb(adjlel(v,price,cap,0,szv)); adjl[v].pb(adjlel(u,-price,0,0,szu)); } bool possible(int flow) { rep(i,v) adjl[i].clear(); rep(i,n) rep(j,n) if(c[i][j]>0) { add_edge(i,j,c[i][j],0); add_edge(i,j,inv,1); } add_edge(s,0,flow,0); add_edge(n-1,t,flow,0); int mcf=findmincostmaxflow(); if(adjl[s][0].f<flow or mcf>k) return false; return true; } int main() { gi(n); gi(k); rep(i,n) rep(j,n) gi(c[i][j]); v=n+2; s=n; t=n+1; int l=0,r=int(1e8); while((l+1)<r) { int flow=(l+r)/2; if(possible(flow)) l=flow; else r=flow; } printf("%d\n",l); return 0; }
22.686486
109
0.599952
AmrARaouf
b402e9753323e8d5da494e526f7e22814080c8af
156,561
cpp
C++
cstrike15_src/particles/particles.cpp
5R33CH4/-5R33CH4-CSGO-Source-Code
dafb3cafa88f37cd405df3a9ffbbcdcb1dba8f63
[ "MIT" ]
4
2020-11-25T11:45:10.000Z
2021-03-17T15:22:01.000Z
cstrike15_src/particles/particles.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
null
null
null
cstrike15_src/particles/particles.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
7
2021-08-22T11:29:02.000Z
2022-03-29T11:59:15.000Z
//===== Copyright � 1996-2007, Valve Corporation, All rights reserved. ======// // // Purpose: particle system code // //===========================================================================// #include "tier0/platform.h" #include "particles/particles.h" #include "bitmap/psheet.h" #include "filesystem.h" #include "tier2/tier2.h" #include "tier2/fileutils.h" #include "tier1/utlbuffer.h" #include "tier1/UtlStringMap.h" #include "tier1/strtools.h" #include "dmxloader/dmxloader.h" #include "materialsystem/imaterial.h" #include "materialsystem/imaterialvar.h" #include "materialsystem/itexture.h" #include "materialsystem/imesh.h" #include "tier0/vprof.h" #include "tier1/keyvalues.h" #include "tier1/lzmaDecoder.h" #include "random_floats.h" #include "vtf/vtf.h" #include "studio.h" #include "particles_internal.h" #include "ivrenderview.h" #include "materialsystem/imaterialsystem.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // rename table from the great rename static char *s_RemapOperatorNameTable[]={ "alpha_fade", "Alpha Fade and Decay", "alpha_fade_in_random", "Alpha Fade In Random", "alpha_fade_out_random", "Alpha Fade Out Random", "basic_movement", "Movement Basic", "color_fade", "Color Fade", "controlpoint_light", "Color Light From Control Point", "Dampen Movement Relative to Control Point", "Movement Dampen Relative to Control Point", "Distance Between Control Points Scale", "Remap Distance Between Two Control Points to Scalar", "Distance to Control Points Scale", "Remap Distance to Control Point to Scalar", "lifespan_decay", "Lifespan Decay", "lock to bone", "Movement Lock to Bone", "postion_lock_to_controlpoint", "Movement Lock to Control Point", "maintain position along path", "Movement Maintain Position Along Path", "Match Particle Velocities", "Movement Match Particle Velocities", "Max Velocity", "Movement Max Velocity", "noise", "Noise Scalar", "vector noise", "Noise Vector", "oscillate_scalar", "Oscillate Scalar", "oscillate_vector", "Oscillate Vector", "Orient Rotation to 2D Direction", "Rotation Orient to 2D Direction", "radius_scale", "Radius Scale", "Random Cull", "Cull Random", "remap_scalar", "Remap Scalar", "rotation_movement", "Rotation Basic", "rotation_spin", "Rotation Spin Roll", "rotation_spin yaw", "Rotation Spin Yaw", "alpha_random", "Alpha Random", "color_random", "Color Random", "create from parent particles", "Position From Parent Particles", "Create In Hierarchy", "Position In CP Hierarchy", "random position along path", "Position Along Path Random", "random position on model", "Position on Model Random", "sequential position along path", "Position Along Path Sequential", "position_offset_random", "Position Modify Offset Random", "position_warp_random", "Position Modify Warp Random", "position_within_box", "Position Within Box Random", "position_within_sphere", "Position Within Sphere Random", "Inherit Velocity", "Velocity Inherit from Control Point", "Initial Repulsion Velocity", "Velocity Repulse from World", "Initial Velocity Noise", "Velocity Noise", "Initial Scalar Noise", "Remap Noise to Scalar", "Lifespan from distance to world", "Lifetime from Time to Impact", "Pre-Age Noise", "Lifetime Pre-Age Noise", "lifetime_random", "Lifetime Random", "radius_random", "Radius Random", "random yaw", "Rotation Yaw Random", "Randomly Flip Yaw", "Rotation Yaw Flip Random", "rotation_random", "Rotation Random", "rotation_speed_random", "Rotation Speed Random", "sequence_random", "Sequence Random", "second_sequence_random", "Sequence Two Random", "trail_length_random", "Trail Length Random", "velocity_random", "Velocity Random", }; static char const *RemapOperatorName( char const *pOpName ) { for( int i = 0 ; i < ARRAYSIZE( s_RemapOperatorNameTable ) ; i += 2 ) { if ( Q_stricmp( pOpName, s_RemapOperatorNameTable[i] ) == 0 ) { return s_RemapOperatorNameTable[i + 1 ]; } } return pOpName; } //----------------------------------------------------------------------------- // Default implementation of particle system mgr //----------------------------------------------------------------------------- static CParticleSystemMgr s_ParticleSystemMgr; CParticleSystemMgr *g_pParticleSystemMgr = &s_ParticleSystemMgr; CParticleSystemMgr::ParticleAttribute_t CParticleSystemMgr::s_AttributeTable[ MAX_PARTICLE_ATTRIBUTES ]; int g_nParticle_Multiplier = 1; //----------------------------------------------------------------------------- // Particle dictionary //----------------------------------------------------------------------------- class CParticleSystemDictionary { public: ~CParticleSystemDictionary(); CParticleSystemDefinition* AddParticleSystem( CDmxElement *pParticleSystem ); int Count() const; int NameCount() const; CParticleSystemDefinition* GetParticleSystem( int i ); ParticleSystemHandle_t FindParticleSystemHandle( const char *pName ); ParticleSystemHandle_t FindOrAddParticleSystemHandle( const char *pName ); CParticleSystemDefinition* FindParticleSystem( ParticleSystemHandle_t h ); CParticleSystemDefinition* FindParticleSystem( const char *pName ); CParticleSystemDefinition* FindParticleSystem( const DmObjectId_t &id ); CParticleSystemDefinition* operator[]( int idx ) { return m_ParticleNameMap[ idx ]; } private: typedef CUtlStringMap< CParticleSystemDefinition * > ParticleNameMap_t; typedef CUtlVector< CParticleSystemDefinition* > ParticleIdMap_t; void DestroyExistingElement( CDmxElement *pElement ); ParticleNameMap_t m_ParticleNameMap; ParticleIdMap_t m_ParticleIdMap; }; //----------------------------------------------------------------------------- // Destructor //----------------------------------------------------------------------------- CParticleSystemDictionary::~CParticleSystemDictionary() { int nCount = m_ParticleIdMap.Count(); for ( int i = 0; i < nCount; ++i ) { delete m_ParticleIdMap[i]; } } //----------------------------------------------------------------------------- // Destroys an existing element, returns if this element should be added to the name list //----------------------------------------------------------------------------- void CParticleSystemDictionary::DestroyExistingElement( CDmxElement *pElement ) { const char *pParticleSystemName = pElement->GetName(); bool bPreventNameBasedLookup = pElement->GetValue<bool>( "preventNameBasedLookup" ); if ( !bPreventNameBasedLookup ) { if ( m_ParticleNameMap.Defined( pParticleSystemName ) ) { CParticleSystemDefinition *pDef = m_ParticleNameMap[ pParticleSystemName ]; delete pDef; m_ParticleNameMap[ pParticleSystemName ] = NULL; } return; } // Use id based lookup instead int nCount = m_ParticleIdMap.Count(); const DmObjectId_t& id = pElement->GetId(); for ( int i = 0; i < nCount; ++i ) { // Was already removed by the name lookup if ( !IsUniqueIdEqual( m_ParticleIdMap[i]->GetId(), id ) ) continue; CParticleSystemDefinition *pDef = m_ParticleIdMap[ i ]; m_ParticleIdMap.FastRemove( i ); delete pDef; break; } } //----------------------------------------------------------------------------- // Adds a destructor //----------------------------------------------------------------------------- CParticleSystemDefinition* CParticleSystemDictionary::AddParticleSystem( CDmxElement *pParticleSystem ) { if ( Q_stricmp( pParticleSystem->GetTypeString(), "DmeParticleSystemDefinition" ) ) return NULL; DestroyExistingElement( pParticleSystem ); CParticleSystemDefinition *pDef = new CParticleSystemDefinition; // Must add the def to the maps before Read() because Read() may create new child particle systems bool bPreventNameBasedLookup = pParticleSystem->GetValue<bool>( "preventNameBasedLookup" ); if ( !bPreventNameBasedLookup ) { m_ParticleNameMap[ pParticleSystem->GetName() ] = pDef; } else { m_ParticleIdMap.AddToTail( pDef ); } pDef->Read( pParticleSystem ); return pDef; } int CParticleSystemDictionary::NameCount() const { return m_ParticleNameMap.GetNumStrings(); } int CParticleSystemDictionary::Count() const { return m_ParticleIdMap.Count(); } CParticleSystemDefinition* CParticleSystemDictionary::GetParticleSystem( int i ) { return m_ParticleIdMap[i]; } ParticleSystemHandle_t CParticleSystemDictionary::FindParticleSystemHandle( const char *pName ) { return m_ParticleNameMap.Find( pName ); } ParticleSystemHandle_t CParticleSystemDictionary::FindOrAddParticleSystemHandle( const char *pName ) { int nCount = m_ParticleNameMap.GetNumStrings(); ParticleSystemHandle_t hSystem = m_ParticleNameMap.AddString( pName ); if ( hSystem >= nCount ) { m_ParticleNameMap[ hSystem ] = NULL; } return hSystem; } CParticleSystemDefinition* CParticleSystemDictionary::FindParticleSystem( ParticleSystemHandle_t h ) { if ( h == UTL_INVAL_SYMBOL || h >= m_ParticleNameMap.GetNumStrings() ) return NULL; return m_ParticleNameMap[ h ]; } CParticleSystemDefinition* CParticleSystemDictionary::FindParticleSystem( const char *pName ) { if ( m_ParticleNameMap.Defined( pName ) ) return m_ParticleNameMap[ pName ]; return NULL; } CParticleSystemDefinition* CParticleSystemDictionary::FindParticleSystem( const DmObjectId_t &id ) { int nCount = m_ParticleIdMap.Count(); for ( int i = 0; i < nCount; ++i ) { if ( IsUniqueIdEqual( m_ParticleIdMap[i]->GetId(), id ) ) return m_ParticleIdMap[i]; } return NULL; } //----------------------------------------------------------------------------- // For editing, create a faked particle operator definition for children // The only thing used in here is GetUnpackStructure. //----------------------------------------------------------------------------- BEGIN_DMXELEMENT_UNPACK( ParticleChildrenInfo_t ) DMXELEMENT_UNPACK_FIELD( "delay", "0.0", float, m_flDelay ) DMXELEMENT_UNPACK_FIELD( "end cap effect", "0", bool, m_bEndCap ) END_DMXELEMENT_UNPACK( ParticleChildrenInfo_t, s_ChildrenInfoUnpack ) class CChildOperatorDefinition : public IParticleOperatorDefinition { public: virtual const char *GetName() const { Assert(0); return NULL; } virtual CParticleOperatorInstance *CreateInstance( const DmObjectId_t &id ) const { Assert(0); return NULL; } // virtual void DestroyInstance( CParticleOperatorInstance *pInstance ) const { Assert(0); } virtual const DmxElementUnpackStructure_t* GetUnpackStructure() const { return s_ChildrenInfoUnpack; } virtual ParticleOperatorId_t GetId() const { return OPERATOR_GENERIC; } virtual uint32 GetFilter() const { return 0; } virtual bool IsObsolete() const { return false; } }; static CChildOperatorDefinition s_ChildOperatorDefinition; //----------------------------------------------------------------------------- // // CParticleSystemDefinition // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Unpack structure for CParticleSystemDefinition //----------------------------------------------------------------------------- BEGIN_DMXELEMENT_UNPACK( CParticleSystemDefinition ) DMXELEMENT_UNPACK_FIELD( "max_particles", "1000", int, m_nMaxParticles ) DMXELEMENT_UNPACK_FIELD( "initial_particles", "0", int, m_nInitialParticles ) DMXELEMENT_UNPACK_FIELD_UTLSTRING_USERDATA( "material", "vgui/white", m_MaterialName, "vmtPicker" ) DMXELEMENT_UNPACK_FIELD( "bounding_box_min", "-10 -10 -10", Vector, m_BoundingBoxMin ) DMXELEMENT_UNPACK_FIELD( "bounding_box_max", "10 10 10", Vector, m_BoundingBoxMax ) DMXELEMENT_UNPACK_FIELD( "cull_radius", "0", float, m_flCullRadius ) DMXELEMENT_UNPACK_FIELD( "cull_cost", "1", float, m_flCullFillCost ) DMXELEMENT_UNPACK_FIELD( "cull_control_point", "0", int, m_nCullControlPoint ) DMXELEMENT_UNPACK_FIELD_UTLSTRING( "cull_replacement_definition", "", m_CullReplacementName ) DMXELEMENT_UNPACK_FIELD_UTLSTRING( "fallback replacement definition", "", m_FallbackReplacementName ) DMXELEMENT_UNPACK_FIELD( "fallback max count", "-1", int, m_nFallbackMaxCount ) DMXELEMENT_UNPACK_FIELD( "radius", "5", float, m_flConstantRadius ) DMXELEMENT_UNPACK_FIELD( "color", "255 255 255 255", Color, m_ConstantColor ) DMXELEMENT_UNPACK_FIELD( "rotation", "0", float, m_flConstantRotation ) DMXELEMENT_UNPACK_FIELD( "rotation_speed", "0", float, m_flConstantRotationSpeed ) DMXELEMENT_UNPACK_FIELD( "normal", "0 0 1", Vector, m_ConstantNormal ) DMXELEMENT_UNPACK_FIELD_USERDATA( "sequence_number", "0", int, m_nConstantSequenceNumber, "sheetsequencepicker" ) DMXELEMENT_UNPACK_FIELD_USERDATA( "sequence_number 1", "0", int, m_nConstantSequenceNumber1, "sheetsequencepicker_second" ) DMXELEMENT_UNPACK_FIELD( "group id", "0", int, m_nGroupID ) DMXELEMENT_UNPACK_FIELD( "maximum time step", "0.1", float, m_flMaximumTimeStep ) DMXELEMENT_UNPACK_FIELD( "maximum sim tick rate", "0.0", float, m_flMaximumSimTime ) DMXELEMENT_UNPACK_FIELD( "minimum sim tick rate", "0.0", float, m_flMinimumSimTime ) DMXELEMENT_UNPACK_FIELD( "minimum rendered frames", "0", int, m_nMinimumFrames ) DMXELEMENT_UNPACK_FIELD( "control point to disable rendering if it is the camera", "-1", int, m_nSkipRenderControlPoint ) DMXELEMENT_UNPACK_FIELD( "control point to only enable rendering if it is the camera", "-1", int, m_nAllowRenderControlPoint ) DMXELEMENT_UNPACK_FIELD( "maximum draw distance", "100000.0", float, m_flMaxDrawDistance ) DMXELEMENT_UNPACK_FIELD( "time to sleep when not drawn", "8", float, m_flNoDrawTimeToGoToSleep ) DMXELEMENT_UNPACK_FIELD( "Sort particles", "1", bool, m_bShouldSort ) DMXELEMENT_UNPACK_FIELD( "batch particle systems", "0", bool, m_bShouldBatch ) DMXELEMENT_UNPACK_FIELD( "view model effect", "0", bool, m_bViewModelEffect ) DMXELEMENT_UNPACK_FIELD( "screen space effect", "0", bool, m_bScreenSpaceEffect ) DMXELEMENT_UNPACK_FIELD( "draw through leafsystem", "1", bool, m_bDrawThroughLeafSystem ) DMXELEMENT_UNPACK_FIELD( "maximum portal recursion depth", "8", int, m_nMaxRecursionDepth ) DMXELEMENT_UNPACK_FIELD( "aggregation radius", "0", float, m_flAggregateRadius ) DMXELEMENT_UNPACK_FIELD( "minimum free particles to aggregate", "0", int, m_nAggregationMinAvailableParticles ) DMXELEMENT_UNPACK_FIELD( "minimum simulation time step", "0", float, m_flMinimumTimeStep ) DMXELEMENT_UNPACK_FIELD( "minimum CPU level", "0", int, m_nMinCPULevel ) DMXELEMENT_UNPACK_FIELD( "minimum GPU level", "0", int, m_nMinGPULevel ) DMXELEMENT_UNPACK_FIELD( "freeze simulation after time", "1000000000", float, m_flStopSimulationAfterTime ) END_DMXELEMENT_UNPACK( CParticleSystemDefinition, s_pParticleSystemDefinitionUnpack ) //----------------------------------------------------------------------------- // // CParticleOperatorDefinition begins here // A template describing how a particle system will function // //----------------------------------------------------------------------------- void CParticleSystemDefinition::UnlinkAllCollections() { while ( m_pFirstCollection ) { m_pFirstCollection->UnlinkFromDefList(); } Assert( m_nFallbackCurrentCount == 0 ); } const char *CParticleSystemDefinition::GetName() const { return m_Name; } //----------------------------------------------------------------------------- // Should we always precache this? //----------------------------------------------------------------------------- bool CParticleSystemDefinition::ShouldAlwaysPrecache() const { return m_bAlwaysPrecache; } //----------------------------------------------------------------------------- // Precache/uncache //----------------------------------------------------------------------------- void CParticleSystemDefinition::Precache() { if ( m_bIsPrecached ) return; m_bIsPrecached = true; #ifndef DEDICATED if ( !UTIL_IsDedicatedServer() && g_pMaterialSystem ) { m_Material.Init( MaterialName(), TEXTURE_GROUP_OTHER, true ); if ( m_Material->HasProxy() ) { Warning( "Material %s used by particle systems cannot use proxies!\n", m_Material->GetName() ); m_Material.Init( "debug/particleerror", TEXTURE_GROUP_OTHER, true ); } g_pParticleSystemMgr->FindOrLoadSheet( this ); // NOTE: Subtle. This has to be called after HasProxy, which will // have loaded all material vars. The "queue friendly" version of a material // doesn't precache material vars m_Material->GetColorModulation( &m_vecMaterialModulation[0], &m_vecMaterialModulation[1], &m_vecMaterialModulation[2] ); m_vecMaterialModulation[3] = m_Material->GetAlphaModulation(); } #endif if ( HasFallback() ) { CParticleSystemDefinition *pFallback = GetFallbackReplacementDefinition(); if ( pFallback ) { pFallback->Precache(); } } // call the precache method of the renderers in case they need assets for( int i = 0; i < m_Renderers.Count(); i++ ) { CParticleOperatorInstance *pOp = m_Renderers[i]; pOp->Precache(); } int nChildCount = m_Children.Count(); for ( int i = 0; i < nChildCount; ++i ) { CParticleSystemDefinition *pChild; if ( m_Children[i].m_bUseNameBasedLookup ) { pChild = g_pParticleSystemMgr->FindParticleSystem( m_Children[i].m_Name ); } else { pChild = g_pParticleSystemMgr->FindParticleSystem( m_Children[i].m_Id ); } if ( pChild ) { pChild->Precache(); } } } void CParticleSystemDefinition::Uncache() { if ( !m_bIsPrecached ) return; m_bIsPrecached = false; m_Material.Shutdown(); // m_Material.Init( "debug/particleerror", TEXTURE_GROUP_OTHER, true ); // m_vecMaterialModulation.Init( 1.0f, 1.0f, 1.0f, 1.0f ); if ( HasFallback() ) { CParticleSystemDefinition *pFallback = GetFallbackReplacementDefinition(); if ( pFallback ) { pFallback->Uncache(); } } for( int i = 0; i < m_Renderers.Count(); i++ ) { CParticleOperatorInstance *pOp = m_Renderers[i]; pOp->Uncache(); } int nChildCount = m_Children.Count(); for ( int i = 0; i < nChildCount; ++i ) { CParticleSystemDefinition *pChild; if ( m_Children[i].m_bUseNameBasedLookup ) { pChild = g_pParticleSystemMgr->FindParticleSystem( m_Children[i].m_Name ); } else { pChild = g_pParticleSystemMgr->FindParticleSystem( m_Children[i].m_Id ); } if ( pChild ) { pChild->Uncache(); } } } //----------------------------------------------------------------------------- // Has this been precached? //----------------------------------------------------------------------------- bool CParticleSystemDefinition::IsPrecached() const { return m_bIsPrecached; } //----------------------------------------------------------------------------- // Helper methods to help with unserialization //----------------------------------------------------------------------------- void CParticleSystemDefinition::ParseOperators( const char *pszOpKey, ParticleFunctionType_t nFunctionType, CDmxElement *pElement, CUtlVector<CParticleOperatorInstance *> &outList) { const CDmxAttribute* pAttribute = pElement->GetAttribute( pszOpKey ); if ( !pAttribute || pAttribute->GetType() != AT_ELEMENT_ARRAY ) return; const CUtlVector<IParticleOperatorDefinition *> &flist = g_pParticleSystemMgr->GetAvailableParticleOperatorList( nFunctionType ); const CUtlVector< CDmxElement* >& ops = pAttribute->GetArray<CDmxElement*>( ); int nCount = ops.Count(); for ( int i = 0; i < nCount; ++i ) { const char *pOrigName = ops[i]->GetValueString( "functionName" ); char const *pOpName = RemapOperatorName( pOrigName ); if ( pOpName != pOrigName ) { pElement->SetValue( "functionName", pOpName ); } bool bFound = false; int nFunctionCount = flist.Count(); for( int j = 0; j < nFunctionCount; ++j ) { if ( Q_stricmp( pOpName, flist[j]->GetName() ) ) continue; // found it! bFound = true; CParticleOperatorInstance *pNewRef = flist[j]->CreateInstance( ops[i]->GetId() ); const DmxElementUnpackStructure_t *pUnpack = flist[j]->GetUnpackStructure(); if ( pUnpack ) { ops[i]->UnpackIntoStructure( pNewRef, pUnpack ); } pNewRef->InitParams( this ); pNewRef->CheckForFastPath(); m_nAttributeReadMask |= pNewRef->GetReadAttributes(); m_nControlPointReadMask |= pNewRef->GetReadControlPointMask(); m_nControlPointNonPositionalMask |= pNewRef->GetNonPositionalControlPointMask(); switch( nFunctionType ) { case FUNCTION_INITIALIZER: case FUNCTION_EMITTER: m_nPerParticleInitializedAttributeMask |= pNewRef->GetWrittenAttributes(); Assert( pNewRef->GetReadInitialAttributes() == 0 ); break; case FUNCTION_OPERATOR: case FUNCTION_FORCEGENERATOR: case FUNCTION_CONSTRAINT: m_nPerParticleUpdatedAttributeMask |= pNewRef->GetWrittenAttributes(); m_nInitialAttributeReadMask |= pNewRef->GetReadInitialAttributes(); break; case FUNCTION_RENDERER: m_nPerParticleUpdatedAttributeMask |= pNewRef->GetWrittenAttributes(); m_nInitialAttributeReadMask |= pNewRef->GetReadInitialAttributes(); break; } // Special case: Reading particle ID means we're reading the initial particle id if ( ( pNewRef->GetReadAttributes() | pNewRef->GetReadInitialAttributes() ) & PARTICLE_ATTRIBUTE_PARTICLE_ID_MASK ) { m_nInitialAttributeReadMask |= PARTICLE_ATTRIBUTE_PARTICLE_ID_MASK; m_nPerParticleInitializedAttributeMask |= PARTICLE_ATTRIBUTE_PARTICLE_ID_MASK; } outList.AddToTail( pNewRef ); break; } if ( !bFound ) { if ( flist.Count() ) // don't warn if no ops of that type defined (server) Warning( "Didn't find particle function %s\n", pOpName ); } } } void CParticleSystemDefinition::ParseChildren( CDmxElement *pElement ) { const CUtlVector<CDmxElement*>& children = pElement->GetArray<CDmxElement*>( "children" ); int nCount = children.Count(); for ( int i = 0; i < nCount; ++i ) { CDmxElement *pChild = children[i]->GetValue<CDmxElement*>( "child" ); if ( !pChild || Q_stricmp( pChild->GetTypeString(), "DmeParticleSystemDefinition" ) ) continue; int j = m_Children.AddToTail(); children[i]->UnpackIntoStructure( &m_Children[j], s_ChildrenInfoUnpack ); m_Children[j].m_bUseNameBasedLookup = !pChild->GetValue<bool>( "preventNameBasedLookup" ); if ( m_Children[j].m_bUseNameBasedLookup ) { m_Children[j].m_Name = g_pParticleSystemMgr->FindOrAddParticleSystemIndex( pChild->GetName() ); } else { CopyUniqueId( pChild->GetId(), &m_Children[j].m_Id ); } // Check to see if this child has been encountered already, and if not, then // create a new particle definition for this child g_pParticleSystemMgr->AddParticleSystem( pChild ); } } void CParticleSystemDefinition::Read( CDmxElement *pElement ) { m_Name = pElement->GetName(); CopyUniqueId( pElement->GetId(), &m_Id ); pElement->UnpackIntoStructure( this, s_pParticleSystemDefinitionUnpack ); if ( m_nInitialParticles < 0 ) { m_nInitialParticles = 0; } if ( m_nMaxParticles < 1 ) { m_nMaxParticles = 1; } m_nMaxParticles *= g_nParticle_Multiplier; m_nMaxParticles = MIN( m_nMaxParticles, MAX_PARTICLES_IN_A_SYSTEM ); if ( m_flCullRadius > 0 ) { m_nControlPointReadMask |= 1ULL << m_nCullControlPoint; } ParseOperators( "renderers", FUNCTION_RENDERER, pElement, m_Renderers ); ParseOperators( "operators", FUNCTION_OPERATOR, pElement, m_Operators ); ParseOperators( "initializers", FUNCTION_INITIALIZER, pElement, m_Initializers ); ParseOperators( "emitters", FUNCTION_EMITTER, pElement, m_Emitters ); ParseChildren( pElement ); ParseOperators( "forces", FUNCTION_FORCEGENERATOR, pElement, m_ForceGenerators ); ParseOperators( "constraints", FUNCTION_CONSTRAINT, pElement, m_Constraints ); SetupContextData(); } IMaterial *CParticleSystemDefinition::GetMaterial() const { // NOTE: This has to be this way to ensure we don't load every freaking material @ startup Assert( IsPrecached() ); if ( !IsPrecached() ) return NULL; return (IMaterial *) ( (const IMaterial *) m_Material ); } CUtlSymbol CParticleSystemDefinition::GetSheetSymbol() const { Assert( IsSheetSymbolCached() ); return m_SheetSymbol; } void CParticleSystemDefinition::CacheSheetSymbol( CUtlSymbol sheetSymbol ) { m_SheetSymbol = sheetSymbol; m_bSheetSymbolCached = true; } bool CParticleSystemDefinition::IsSheetSymbolCached() const { return m_bSheetSymbolCached; } void CParticleSystemDefinition::InvalidateSheetSymbol() { m_bSheetSymbolCached = false; } //---------------------------------------------------------------------------------- // Returns the particle system fallback //---------------------------------------------------------------------------------- CParticleSystemDefinition *CParticleSystemDefinition::GetFallbackReplacementDefinition() const { if ( HasFallback() ) { if ( !m_pFallback() ) { const_cast< CParticleSystemDefinition* >( this )->m_pFallback.Set( g_pParticleSystemMgr->FindParticleSystem( m_FallbackReplacementName ) ); } return m_pFallback(); } return NULL; } //---------------------------------------------------------------------------------- // Does the particle system use the power of two frame buffer texture (refraction?) //---------------------------------------------------------------------------------- bool CParticleSystemDefinition::UsesPowerOfTwoFrameBufferTexture() { // NOTE: This has to be this way to ensure we don't load every freaking material @ startup Assert( IsPrecached() ); return g_pMaterialSystem && m_Material && m_Material->NeedsPowerOfTwoFrameBufferTexture( false ); // The false checks if it will ever need the frame buffer, not just this frame } //---------------------------------------------------------------------------------- // Does the particle system use the power of two frame buffer texture (refraction?) //---------------------------------------------------------------------------------- bool CParticleSystemDefinition::UsesFullFrameBufferTexture() { // NOTE: This has to be this way to ensure we don't load every freaking material @ startup Assert( IsPrecached() ); return g_pMaterialSystem && m_Material && m_Material->NeedsFullFrameBufferTexture( false ); // The false checks if it will ever need the frame buffer, not just this frame } //----------------------------------------------------------------------------- // Helper methods to write particle systems //----------------------------------------------------------------------------- void CParticleSystemDefinition::WriteOperators( CDmxElement *pElement, const char *pOpKeyName, const CUtlVector<CParticleOperatorInstance *> &inList ) { CDmxElementModifyScope modify( pElement ); CDmxAttribute* pAttribute = pElement->AddAttribute( pOpKeyName ); CUtlVector< CDmxElement* >& ops = pAttribute->GetArrayForEdit<CDmxElement*>( ); int nCount = inList.Count(); for ( int i = 0; i < nCount; ++i ) { CDmxElement *pOperator = CreateDmxElement( "DmeParticleOperator" ); ops.AddToTail( pOperator ); const IParticleOperatorDefinition *pDef = inList[i]->GetDefinition(); pOperator->SetValue( "name", pDef->GetName() ); pOperator->SetValue( "functionName", pDef->GetName() ); const DmxElementUnpackStructure_t *pUnpack = pDef->GetUnpackStructure(); if ( pUnpack ) { pOperator->AddAttributesFromStructure( inList[i], pUnpack ); } } } void CParticleSystemDefinition::WriteChildren( CDmxElement *pElement ) { CDmxElementModifyScope modify( pElement ); CDmxAttribute* pAttribute = pElement->AddAttribute( "children" ); CUtlVector< CDmxElement* >& children = pAttribute->GetArrayForEdit<CDmxElement*>( ); int nCount = m_Children.Count(); for ( int i = 0; i < nCount; ++i ) { CDmxElement *pChildRef = CreateDmxElement( "DmeParticleChild" ); children.AddToTail( pChildRef ); children[i]->AddAttributesFromStructure( &m_Children[i], s_ChildrenInfoUnpack ); CDmxElement *pChildParticleSystem; if ( m_Children[i].m_bUseNameBasedLookup ) { pChildParticleSystem = g_pParticleSystemMgr->CreateParticleDmxElement( g_pParticleSystemMgr->GetParticleSystemNameFromIndex( m_Children[i].m_Name ) ); } else { pChildParticleSystem = g_pParticleSystemMgr->CreateParticleDmxElement( m_Children[i].m_Id ); } pChildRef->SetValue( "name", pChildParticleSystem->GetName() ); pChildRef->SetValue( "child", pChildParticleSystem ); } } CDmxElement *CParticleSystemDefinition::Write() { const char *pName = GetName(); CDmxElement *pElement = CreateDmxElement( "DmeParticleSystemDefinition" ); pElement->SetValue( "name", pName ); pElement->AddAttributesFromStructure( this, s_pParticleSystemDefinitionUnpack ); WriteOperators( pElement, "renderers",m_Renderers ); WriteOperators( pElement, "operators", m_Operators ); WriteOperators( pElement, "initializers", m_Initializers ); WriteOperators( pElement, "emitters", m_Emitters ); WriteChildren( pElement ); WriteOperators( pElement, "forces", m_ForceGenerators ); WriteOperators( pElement, "constraints", m_Constraints ); return pElement; } void CParticleSystemDefinition::SetupContextData( void ) { // calculate sizes and offsets for context data CUtlVector<CParticleOperatorInstance *> *olists[] = { &m_Operators, &m_Renderers, &m_Initializers, &m_Emitters, &m_ForceGenerators, &m_Constraints }; CUtlVector<size_t> *offsetLists[] = { &m_nOperatorsCtxOffsets, &m_nRenderersCtxOffsets, &m_nInitializersCtxOffsets, &m_nEmittersCtxOffsets, &m_nForceGeneratorsCtxOffsets, &m_nConstraintsCtxOffsets, }; // loop through all operators, fill in offset entries, and calulate total data needed m_nContextDataSize = 0; for( int i = 0; i < NELEMS( olists ); i++ ) { int nCount = olists[i]->Count(); for( int j = 0; j < nCount; j++ ) { offsetLists[i]->AddToTail( m_nContextDataSize ); m_nContextDataSize += (*olists[i])[j]->GetRequiredContextBytes(); // align context data m_nContextDataSize = (m_nContextDataSize + 15) & (~0xf ); } } } //----------------------------------------------------------------------------- // Finds an operator by id //----------------------------------------------------------------------------- CUtlVector<CParticleOperatorInstance *> *CParticleSystemDefinition::GetOperatorList( ParticleFunctionType_t type ) { switch( type ) { case FUNCTION_EMITTER: return &m_Emitters; case FUNCTION_RENDERER: return &m_Renderers; case FUNCTION_INITIALIZER: return &m_Initializers; case FUNCTION_OPERATOR: return &m_Operators; case FUNCTION_FORCEGENERATOR: return &m_ForceGenerators; case FUNCTION_CONSTRAINT: return &m_Constraints; default: Assert(0); return NULL; } } //----------------------------------------------------------------------------- // Finds an operator by id //----------------------------------------------------------------------------- CParticleOperatorInstance *CParticleSystemDefinition::FindOperatorById( ParticleFunctionType_t type, const DmObjectId_t &id ) { CUtlVector<CParticleOperatorInstance *> *pVec = GetOperatorList( type ); if ( !pVec ) return NULL; int nCount = pVec->Count(); for ( int i = 0; i < nCount; ++i ) { if ( IsUniqueIdEqual( id, pVec->Element(i)->GetId() ) ) return pVec->Element(i); } return NULL; } //----------------------------------------------------------------------------- // Finds an operator by name (slow!) //----------------------------------------------------------------------------- CParticleOperatorInstance *CParticleSystemDefinition::FindOperatorByName( const char *pOperatorName ) { for ( int i = 0; i < PARTICLE_FUNCTION_COUNT; i++ ) { CUtlVector<CParticleOperatorInstance *> *pVec = ( i == FUNCTION_CHILDREN ) ? NULL : GetOperatorList( (ParticleFunctionType_t)i ); if ( !pVec ) continue; int nCount = pVec->Count(); for ( int j = 0; j < nCount; ++j ) { if ( !Q_stricmp( pOperatorName, pVec->Element(j)->GetDefinition()->GetName() ) ) return pVec->Element(j); } } return NULL; } //----------------------------------------------------------------------------- // // CParticleOperatorInstance // //----------------------------------------------------------------------------- void CParticleOperatorInstance::InitNewParticles( CParticleCollection *pParticles, int nFirstParticle, int nParticleCount, int nAttributeWriteMask, void *pContext ) const { if ( !nParticleCount ) return; if ( nParticleCount < 16 ) // don't bother with vectorizing // unless enough particles to bother { InitNewParticlesScalar( pParticles, nFirstParticle, nParticleCount, nAttributeWriteMask, pContext ); return; } int nHead = nFirstParticle & 3; if ( nHead ) { // need to init up to 3 particles before we are block aligned int nHeadCount = MIN( nParticleCount, 4 - nHead ); InitNewParticlesScalar( pParticles, nFirstParticle, nHeadCount, nAttributeWriteMask, pContext ); nParticleCount -= nHeadCount; nFirstParticle += nHeadCount; } // now, we are aligned int nBlockCount = nParticleCount / 4; if ( nBlockCount ) { InitNewParticlesBlock( pParticles, nFirstParticle / 4, nBlockCount, nAttributeWriteMask, pContext ); nParticleCount -= 4 * nBlockCount; nFirstParticle += 4 * nBlockCount; } // do tail if ( nParticleCount ) { InitNewParticlesScalar( pParticles, nFirstParticle, nParticleCount, nAttributeWriteMask, pContext ); } } //----------------------------------------------------------------------------- // // CParticleCollection // //----------------------------------------------------------------------------- //------------------------------------------------------------------------------ // need custom new/delete for alignment for simd //------------------------------------------------------------------------------ #include "tier0/memdbgoff.h" void *CParticleCollection::operator new( size_t nSize ) { return MemAlloc_AllocAligned( nSize, 16 ); } void* CParticleCollection::operator new( size_t nSize, int nBlockUse, const char *pFileName, int nLine ) { return MemAlloc_AllocAlignedFileLine( nSize, 16, pFileName, nLine ); } void CParticleCollection::operator delete(void *pData) { if ( pData ) { MemAlloc_FreeAligned( pData ); } } void CParticleCollection::operator delete( void* pData, int nBlockUse, const char *pFileName, int nLine ) { if ( pData ) { MemAlloc_FreeAligned( pData ); } } void *CWorldCollideContextData::operator new( size_t nSize ) { return MemAlloc_AllocAligned( nSize, 16 ); } void* CWorldCollideContextData::operator new( size_t nSize, int nBlockUse, const char *pFileName, int nLine ) { return MemAlloc_AllocAlignedFileLine( nSize, 16, pFileName, nLine ); } void CWorldCollideContextData::operator delete(void *pData) { if ( pData ) { MemAlloc_FreeAligned( pData ); } } void CWorldCollideContextData::operator delete( void* pData, int nBlockUse, const char *pFileName, int nLine ) { if ( pData ) { MemAlloc_FreeAligned( pData ); } } #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // Constructor, destructor //----------------------------------------------------------------------------- CParticleCollection::CParticleCollection( ) { COMPILE_TIME_ASSERT( ( MAX_RANDOM_FLOATS & ( MAX_RANDOM_FLOATS - 1 ) ) == 0 ); COMPILE_TIME_ASSERT( sizeof( s_pRandomFloats ) / sizeof( float ) >= MAX_RANDOM_FLOATS ); Plat_FastMemset( this, 0, sizeof(CParticleCollection) ); m_flOOMaxDistSqr = 1.0f; m_flPreviousDt = 0.05f; m_nParticleFlags = PCFLAGS_FIRST_FRAME; m_LocalLighting = Color(255, 255, 255, 255); m_LocalLightingCP = -1; m_bPendingRestart = false; m_flTargetDrawTime = 0; m_bQueuedStartEmission = false; m_bFrozen = false; m_pCPInfo = NULL; m_pCachedParticleBatches = NULL; m_bTriedLoadingSheet = false; } CParticleCollection::~CParticleCollection( void ) { UnlinkFromDefList(); m_Children.Purge(); if ( m_pParticleMemory ) { MemAlloc_FreeAligned( m_pParticleMemory ); m_pParticleMemory = NULL; } if ( m_pPreviousAttributeMemory ) { MemAlloc_FreeAligned( m_pPreviousAttributeMemory ); m_pPreviousAttributeMemory = NULL; } if ( m_pParticleInitialMemory ) { MemAlloc_FreeAligned( m_pParticleInitialMemory ); m_pParticleInitialMemory = NULL; } if ( m_pConstantMemory ) { MemAlloc_FreeAligned( m_pConstantMemory ); m_pConstantMemory = NULL; } if ( m_pOperatorContextData ) { MemAlloc_FreeAligned( m_pOperatorContextData ); m_pOperatorContextData = NULL; } for( int i = 0 ; i < ARRAYSIZE( m_pCollisionCacheData ) ; i++ ) { if ( m_pCollisionCacheData[i] ) { delete m_pCollisionCacheData[i]; m_pCollisionCacheData[i] = NULL; } } if ( m_pCPInfo ) { delete[] m_pCPInfo; m_pCPInfo = NULL; } if ( m_pCachedParticleBatches ) { delete m_pCachedParticleBatches; m_pCachedParticleBatches = NULL; } } //----------------------------------------------------------------------------- // Initialization //----------------------------------------------------------------------------- void CParticleCollection::Init( CParticleSystemDefinition *pDef, float flDelay, int nRandomSeed ) { m_pDef = pDef; // Link into def list LinkIntoDefList(); m_pRenderable = NULL; InitStorage( pDef ); // Initialize sheet data m_Sheet.Set( g_pParticleSystemMgr->FindOrLoadSheet( pDef ) ); m_bTriedLoadingSheet = false; // FIXME: This seed needs to be recorded per instance! m_bIsScrubbable = ( nRandomSeed != 0 ); if ( m_bIsScrubbable ) { m_nRandomSeed = nRandomSeed; } else { m_nRandomSeed = (int)(intp)this; #ifndef _DEBUG m_nRandomSeed += Plat_MSTime(); #endif } SetAttributeToConstant( PARTICLE_ATTRIBUTE_XYZ, 0.0f, 0.0f, 0.0f ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_PREV_XYZ, 0.0f, 0.0f, 0.0f ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_LIFE_DURATION, 1.0f ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_RADIUS, pDef->m_flConstantRadius ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_ROTATION, pDef->m_flConstantRotation ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_ROTATION_SPEED, pDef->m_flConstantRotationSpeed ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_TINT_RGB, pDef->m_ConstantColor.r() / 255.0f, pDef->m_ConstantColor.g() / 255.0f, pDef->m_ConstantColor.b() / 255.0f ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_ALPHA, pDef->m_ConstantColor.a() / 255.0f ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_CREATION_TIME, 0.0f ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_SEQUENCE_NUMBER, pDef->m_nConstantSequenceNumber ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_SEQUENCE_NUMBER1, pDef->m_nConstantSequenceNumber1 ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_TRAIL_LENGTH, 0.1f ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_PARTICLE_ID, 0 ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_YAW, 0.0f ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_ALPHA2, 1.0f ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_PITCH, 0.0f ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_NORMAL, pDef->m_ConstantNormal.x, pDef->m_ConstantNormal.y, pDef->m_ConstantNormal.z ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_GLOW_RGB, 1.0f, 1.0f, 1.0f ); SetAttributeToConstant( PARTICLE_ATTRIBUTE_GLOW_ALPHA, 1.0f ); // Offset the child in time m_flCurTime = -flDelay; m_fl4CurTime = ReplicateX4( m_flCurTime ); if ( m_pDef->m_nContextDataSize ) { m_pOperatorContextData = reinterpret_cast<uint8 *> ( MemAlloc_AllocAligned( m_pDef->m_nContextDataSize, 16 ) ); } m_flNextSleepTime = g_pParticleSystemMgr->GetLastSimulationTime() + pDef->m_flNoDrawTimeToGoToSleep; m_nControlPointReadMask = pDef->m_nControlPointReadMask; m_nControlPointNonPositionalMask = pDef->m_nControlPointNonPositionalMask; // Instance child particle systems int nChildCount = pDef->m_Children.Count(); for ( int i = 0; i < nChildCount; ++i ) { if ( nRandomSeed != 0 ) { nRandomSeed += 129; } CParticleCollection *pChild; if ( pDef->m_Children[i].m_bUseNameBasedLookup ) { pChild = g_pParticleSystemMgr->CreateParticleCollection( pDef->m_Children[i].m_Name, -m_flCurTime + pDef->m_Children[i].m_flDelay, nRandomSeed ); } else { pChild = g_pParticleSystemMgr->CreateParticleCollection( pDef->m_Children[i].m_Id, -m_flCurTime + pDef->m_Children[i].m_flDelay, nRandomSeed ); } if ( pChild ) { pChild->m_pParent = this; m_Children.AddToTail( pChild ); m_nControlPointReadMask |= pChild->m_nControlPointReadMask; m_nControlPointNonPositionalMask |= pChild->m_nControlPointNonPositionalMask; if ( pDef->m_Children[i].m_bEndCap ) { pChild->m_flCurTime = -FLT_MAX; } } } if ( !IsValid() ) return; m_bIsTranslucent = ComputeIsTranslucent(); m_bIsTwoPass = ComputeIsTwoPass(); m_bIsBatchable = ComputeIsBatchable(); m_bIsOrderImportant = ComputeIsOrderImportant(); m_bRunForParentApplyKillList = ComputeRunForParentApplyKillList(); LabelTextureUsage(); m_bAnyUsesPowerOfTwoFrameBufferTexture = ComputeUsesPowerOfTwoFrameBufferTexture(); m_bAnyUsesFullFrameBufferTexture = ComputeUsesFullFrameBufferTexture(); m_bInEndCap = false; // now, allocate the control point data. // we will always allocate on extra, so that if someone sets a control point that the particle system doesn't // use, then there will be a dummy one to write to. int nHighest; for( nHighest = 63; nHighest > 0 ; nHighest-- ) { if ( m_nControlPointReadMask & ( 1ll << nHighest ) ) { break; } } m_nNumControlPointsAllocated = MIN( MAX_PARTICLE_CONTROL_POINTS, 2 + nHighest ); //Warning( " save %d bytes by only allocating %d cp's\n", ( 64 - m_nNumControlPointsAllocated ) * sizeof( CParticleCPInfo ), m_nNumControlPointsAllocated ); m_pCPInfo = new CParticleCPInfo[ m_nNumControlPointsAllocated]; // align all control point orientations with the global world Plat_FastMemset( m_pCPInfo, 0, sizeof( CParticleCPInfo ) * m_nNumControlPointsAllocated ); for( int i=0; i < m_nNumControlPointsAllocated; i++ ) { ControlPoint(i).m_ForwardVector.y = 1.0f; ControlPoint(i).m_UpVector.z = 1.0f; ControlPoint(i).m_RightVector.x = 1.0f; } // now, init context data CUtlVector<CParticleOperatorInstance *> *olists[] = { &(m_pDef->m_Operators), &(m_pDef->m_Renderers), &(m_pDef->m_Initializers), &(m_pDef->m_Emitters), &(m_pDef->m_ForceGenerators), &(m_pDef->m_Constraints), }; CUtlVector<size_t> *offsetlists[]= { &(m_pDef->m_nOperatorsCtxOffsets), &(m_pDef->m_nRenderersCtxOffsets), &(m_pDef->m_nInitializersCtxOffsets), &(m_pDef->m_nEmittersCtxOffsets), &(m_pDef->m_nForceGeneratorsCtxOffsets), &(m_pDef->m_nConstraintsCtxOffsets), }; for( int i=0; i<NELEMS( olists ); i++ ) { int nOperatorCount = olists[i]->Count(); for( int j=0; j < nOperatorCount; j++ ) { (*olists[i])[j]->InitializeContextData( this, m_pOperatorContextData+ (*offsetlists)[i][j] ); } } } int CParticleCollection::GetCurrentParticleDefCount( CParticleSystemDefinition* pDef ) { int nDefCount = pDef->m_nFallbackCurrentCount; CParticleSystemDefinition *pFallback = pDef; while ( pFallback && pFallback->HasFallback() ) { pFallback = pFallback->GetFallbackReplacementDefinition(); if ( !pFallback ) { break; } nDefCount += pFallback->m_nFallbackCurrentCount; } return nDefCount; } bool CParticleCollection::Init( CParticleSystemDefinition *pDef ) { if ( pDef->GetMinCPULevel() > g_pParticleSystemMgr->GetParticleCPULevel() || pDef->GetMinGPULevel() > g_pParticleSystemMgr->GetParticleGPULevel() ) { pDef = NULL; return false; } float flFallbackMultiplier = g_pParticleSystemMgr->GetFallbackMultiplier(); float flFallbackBase = g_pParticleSystemMgr->GetFallbackBase(); float flThresholdSimMS = g_pParticleSystemMgr->GetSimFallbackThresholdMs(); int nFallbackCount = GetCurrentParticleDefCount( pDef ); // Determine if we've gone past our maximum allowable time for simulating particles. // NOTE: If particle simulation starts overlapping client operations, then we'll need to // make setting and querying of sim duration threadsafe. float flPreviousSimMS = g_pParticleSystemMgr->GetLastSimulationDuration() * 1000.0f; if ( flPreviousSimMS > flThresholdSimMS ) { float flMSOver = flPreviousSimMS - flThresholdSimMS; float flSimFallbackBaseMultiplier = g_pParticleSystemMgr->GetSimFallbackBaseMultiplier(); // Increase the fallback base by a factor of r_particle_sim_fallback_base_multiplier // for each millisecond we're over the threshold flFallbackBase += flMSOver * flSimFallbackBaseMultiplier; // Uncomment to spew when we're trying to fall back because sim time took too long //Warning( "Particle sim took too long: %f, threshold %f\n", flPreviousSimMS, flThresholdSimMS ); } // If our maximum number of simultaneous definitions has been exceeded fallback to the appropriate def while ( pDef && pDef->HasFallback() && ( ( nFallbackCount * flFallbackMultiplier ) + flFallbackBase ) >= pDef->m_nFallbackMaxCount ) { nFallbackCount -= pDef->m_nFallbackCurrentCount; pDef = pDef->GetFallbackReplacementDefinition(); } if ( !pDef ) // || !pDef->IsPrecached() ) { Warning( "Particlelib: Missing precache for particle system type \"%s\"!\n", pDef ? pDef->GetName() : "unknown" ); CParticleSystemDefinition *pErrorDef = g_pParticleSystemMgr->FindParticleSystem( "error" ); if ( pErrorDef ) { pDef = pErrorDef; } } Init( pDef, 0.0f, 0 ); return IsValid(); } bool CParticleCollection::Init( const char *pParticleSystemName ) { if ( !pParticleSystemName ) return false; CParticleSystemDefinition *pDef = g_pParticleSystemMgr->FindParticleSystem( pParticleSystemName ); if ( !pDef ) { Warning( "Attempted to create unknown particle system type \"%s\"!\n", pParticleSystemName ); return false; } return Init( pDef ); } bool CParticleCollection::IsFullyValid( void ) const { if ( m_pDef.GetObject() == NULL ) return false; for( CParticleCollection *p = m_Children.m_pHead; p; p = p->m_pNext ) { if ( !p->IsFullyValid() ) return false; } return true; } bool CParticleCollection::DependsOnSystem( const char *pName ) const { if ( m_pDef.GetObject() == NULL ) return false; if ( m_pDef->m_Name == pName ) return true; for( CParticleCollection *p = m_Children.m_pHead; p; p = p->m_pNext ) { if ( p->DependsOnSystem(pName) ) return true; } return false; } //----------------------------------------------------------------------------- // List management for collections sharing the same particle definition //----------------------------------------------------------------------------- void CParticleCollection::LinkIntoDefList( ) { Assert( !m_pPrevDef && !m_pNextDef ); ++( m_pDef->m_nFallbackCurrentCount ); m_pPrevDef = NULL; m_pNextDef = m_pDef->m_pFirstCollection; m_pDef->m_pFirstCollection = this; if ( m_pNextDef ) { m_pNextDef->m_pPrevDef = this; } #ifdef _DEBUG CParticleCollection *pCollection = m_pDef->FirstCollection(); while ( pCollection ) { Assert( pCollection->m_pDef == m_pDef ); pCollection = pCollection->GetNextCollectionUsingSameDef(); } #endif } void CParticleCollection::UnlinkFromDefList( ) { if ( !m_pDef ) return; --( m_pDef->m_nFallbackCurrentCount ); if ( m_pDef->m_pFirstCollection == this ) { m_pDef->m_pFirstCollection = m_pNextDef; Assert( !m_pPrevDef ); } else { Assert( m_pPrevDef ); m_pPrevDef->m_pNextDef = m_pNextDef; } if ( m_pNextDef ) { m_pNextDef->m_pPrevDef = m_pPrevDef; } m_pNextDef = m_pPrevDef = NULL; #ifdef _DEBUG CParticleCollection *pCollection = m_pDef->FirstCollection(); while ( pCollection ) { Assert( pCollection->m_pDef == m_pDef ); pCollection = pCollection->GetNextCollectionUsingSameDef(); } #endif m_pDef = NULL; } //----------------------------------------------------------------------------- // Reset the particle cache if the frame has changed //----------------------------------------------------------------------------- void CParticleCollection::ResetParticleCache() { if ( m_pCachedParticleBatches ) { uint32 nCurrentFrame = g_pMaterialSystem->GetCurrentFrameCount(); if ( m_pCachedParticleBatches->m_nLastValidParticleCacheFrame != nCurrentFrame ) { m_pCachedParticleBatches->ClearBatches(); m_pCachedParticleBatches->m_nLastValidParticleCacheFrame = nCurrentFrame; } } } //----------------------------------------------------------------------------- // Get the cached particle batches for this particular particle collection //----------------------------------------------------------------------------- CCachedParticleBatches *CParticleCollection::GetCachedParticleBatches() { if ( !m_pCachedParticleBatches ) { m_pCachedParticleBatches = new CCachedParticleBatches(); } return m_pCachedParticleBatches; } //----------------------------------------------------------------------------- // Particle memory initialization //----------------------------------------------------------------------------- void CParticleCollection::InitStorage( CParticleSystemDefinition *pDef ) { Assert( pDef->m_nMaxParticles < 65536 ); m_nMaxAllowedParticles = MIN( MAX_PARTICLES_IN_A_SYSTEM, pDef->m_nMaxParticles ); m_nAllocatedParticles = 4 + 4 * ( ( m_nMaxAllowedParticles + 3 ) / 4 ); int nConstantMemorySize = 3 * 4 * MAX_PARTICLE_ATTRIBUTES * sizeof(float) + 16; // Align allocation for constant attributes to 16 byte boundaries m_pConstantMemory = (uint8 * ) MemAlloc_AllocAligned( nConstantMemorySize, 16 ); m_pConstantAttributes = ( float * ) m_pConstantMemory; m_nPerParticleInitializedAttributeMask = pDef->m_nPerParticleInitializedAttributeMask; m_nPerParticleUpdatedAttributeMask = pDef->m_nPerParticleUpdatedAttributeMask; // Only worry about initial attributes that are per-particle *and* are updated at a later time // If they aren't updated at a later time, then we can just point the initial + current pointers at the same memory m_nPerParticleReadInitialAttributeMask = pDef->m_nInitialAttributeReadMask & ( pDef->m_nPerParticleInitializedAttributeMask & pDef->m_nPerParticleUpdatedAttributeMask ); // This is the mask of attributes which are initialized per-particle, but never updated // *and* where operators want to read initial particle state int nPerParticleReadConstantAttributeMask = pDef->m_nInitialAttributeReadMask & ( pDef->m_nPerParticleInitializedAttributeMask & ( ~pDef->m_nPerParticleUpdatedAttributeMask ) ); int sz = 0; int nInitialAttributeSize = 0; int nPerParticleAttributeMask = m_nPerParticleInitializedAttributeMask | m_nPerParticleUpdatedAttributeMask; for( int bit = 0; bit < MAX_PARTICLE_ATTRIBUTES; bit++ ) { int nAttrSize = ( ( 1 << bit ) & ATTRIBUTES_WHICH_ARE_VEC3S_MASK ) ? 3 : 1; if ( nPerParticleAttributeMask & ( 1 << bit ) ) { sz += nAttrSize; } if ( m_nPerParticleReadInitialAttributeMask & ( 1 << bit ) ) { nInitialAttributeSize += nAttrSize; } } // Gotta allocate a couple extra floats to account for padding int nAllocationSize = m_nAllocatedParticles * sz * sizeof(float) + sizeof( FourVectors ); m_pParticleMemory = ( uint8 * ) MemAlloc_AllocAligned( nAllocationSize, 16 ); m_nAttributeMemorySize = nAllocationSize; Plat_FastMemset( m_pParticleMemory, 0, nAllocationSize ); // Allocate space for the initial attributes if ( nInitialAttributeSize != 0 ) { int nInitialAllocationSize = m_nAllocatedParticles * nInitialAttributeSize * sizeof(float) + sizeof( FourVectors ); m_pParticleInitialMemory = ( uint8 * ) MemAlloc_AllocAligned( nInitialAllocationSize, 16 ); Plat_FastMemset( m_pParticleInitialMemory, 0, nInitialAllocationSize ); } // Align allocation to 16-byte boundaries float *pMem = ( float* ) m_pParticleMemory; float *pInitialMem = ( float* )( m_pParticleInitialMemory ); // Point each attribute to memory associated with that attribute for( int bit = 0; bit < MAX_PARTICLE_ATTRIBUTES; bit++ ) { int nAttrSize = ( ( 1 << bit ) & ATTRIBUTES_WHICH_ARE_VEC3S_MASK ) ? 3 : 1; if ( nPerParticleAttributeMask & ( 1 << bit ) ) { m_ParticleAttributes.m_pAttributes[ bit ] = pMem; m_ParticleAttributes.m_nFloatStrides[ bit ] = nAttrSize * 4; pMem += nAttrSize * m_nAllocatedParticles; } else { m_ParticleAttributes.m_pAttributes[ bit ] = GetConstantAttributeMemory( bit ); m_ParticleAttributes.m_nFloatStrides[ bit ] = 0; } // Are we reading if ( pDef->m_nInitialAttributeReadMask & ( 1 << bit ) ) { if ( m_nPerParticleReadInitialAttributeMask & ( 1 << bit ) ) { Assert( pInitialMem ); m_ParticleInitialAttributes.m_pAttributes[ bit ] = pInitialMem; m_ParticleInitialAttributes.m_nFloatStrides[ bit ] = nAttrSize * 4; pInitialMem += nAttrSize * m_nAllocatedParticles; } else if ( nPerParticleReadConstantAttributeMask & ( 1 << bit ) ) { m_ParticleInitialAttributes.m_pAttributes[ bit ] = m_ParticleAttributes.m_pAttributes[ bit ]; m_ParticleInitialAttributes.m_nFloatStrides[ bit ] = m_ParticleAttributes.m_nFloatStrides[ bit ]; } else { m_ParticleInitialAttributes.m_pAttributes[ bit ] = GetConstantAttributeMemory( bit ); m_ParticleInitialAttributes.m_nFloatStrides[ bit ] = 0; } } else { // Catch errors where code is reading data it didn't request m_ParticleInitialAttributes.m_pAttributes[ bit ] = NULL; m_ParticleInitialAttributes.m_nFloatStrides[ bit ] = 0; } } } //----------------------------------------------------------------------------- // Returns the particle collection name //----------------------------------------------------------------------------- const char *CParticleCollection::GetName() const { return m_pDef ? m_pDef->GetName() : ""; } //----------------------------------------------------------------------------- // Does the particle system use the frame buffer texture (refraction?) //----------------------------------------------------------------------------- bool CParticleCollection::UsesPowerOfTwoFrameBufferTexture( bool bThisFrame ) const { if ( ! m_bAnyUsesPowerOfTwoFrameBufferTexture ) // quick out if neither us or our children ever use { return false; } if ( bThisFrame ) { return SystemContainsParticlesWithBoolSet( &CParticleCollection::m_bUsesPowerOfTwoFrameBufferTexture ); } return true; } //----------------------------------------------------------------------------- // Does the particle system use the full frame buffer texture (soft particles) //----------------------------------------------------------------------------- bool CParticleCollection::UsesFullFrameBufferTexture( bool bThisFrame ) const { if ( ! m_bAnyUsesFullFrameBufferTexture ) // quick out if neither us or our children ever use { return false; } if ( bThisFrame ) { return SystemContainsParticlesWithBoolSet( &CParticleCollection::m_bUsesFullFrameBufferTexture ); } return true; } bool CParticleCollection::SystemContainsParticlesWithBoolSet( bool CParticleCollection::*pField ) const { if ( m_nActiveParticles && ( this->*pField ) ) return true; for( CParticleCollection *p = m_Children.m_pHead; p; p = p->m_pNext ) { if ( p->SystemContainsParticlesWithBoolSet( pField ) ) return true; } return false; } void CParticleCollection::LabelTextureUsage( void ) { if ( m_pDef ) { m_bUsesPowerOfTwoFrameBufferTexture = m_pDef->UsesPowerOfTwoFrameBufferTexture(); m_bUsesFullFrameBufferTexture = m_pDef->UsesFullFrameBufferTexture(); } for( CParticleCollection *p = m_Children.m_pHead; p; p = p->m_pNext ) { p->LabelTextureUsage(); } } bool CParticleCollection::ComputeUsesPowerOfTwoFrameBufferTexture() { if ( !m_pDef ) return false; if ( m_pDef->UsesPowerOfTwoFrameBufferTexture() ) return true; for( CParticleCollection *p = m_Children.m_pHead; p; p = p->m_pNext ) { if ( p->UsesPowerOfTwoFrameBufferTexture( false ) ) return true; } return false; } bool CParticleCollection::ComputeUsesFullFrameBufferTexture() { if ( !m_pDef ) return false; if ( m_pDef->UsesFullFrameBufferTexture() ) return true; for( CParticleCollection *p = m_Children.m_pHead; p; p = p->m_pNext ) { if ( p->UsesFullFrameBufferTexture( false ) ) return true; } return false; } //----------------------------------------------------------------------------- // Is the particle system two-pass? //----------------------------------------------------------------------------- bool CParticleCollection::ContainsOpaqueCollections() { if ( !m_pDef ) return false; IMaterial *pMaterial = m_pDef->GetMaterial(); if ( pMaterial && ( !m_pDef->GetMaterial()->IsTranslucent() ) ) return true; for( CParticleCollection *p = m_Children.m_pHead; p; p = p->m_pNext ) { if ( p->ContainsOpaqueCollections( ) ) return true; } return false; } //----------------------------------------------------------------------------- // Is the particle system two-pass? //----------------------------------------------------------------------------- bool CParticleCollection::IsTwoPass() const { return m_bIsTwoPass; } bool CParticleCollection::ComputeIsTwoPass() { if ( !ComputeIsTranslucent() ) return false; return ContainsOpaqueCollections(); } //----------------------------------------------------------------------------- // Is the particle system translucent //----------------------------------------------------------------------------- bool CParticleCollection::IsTranslucent() const { return m_bIsTranslucent; } bool CParticleCollection::ComputeIsTranslucent() { if ( !m_pDef ) return false; IMaterial *pMaterial = m_pDef->GetMaterial(); if ( pMaterial && ( m_pDef->GetMaterial()->IsTranslucent() ) ) return true; for( CParticleCollection *p = m_Children.m_pHead; p; p = p->m_pNext ) { if ( p->IsTranslucent( ) ) return true; } return false; } //----------------------------------------------------------------------------- // Is the particle system batchable //----------------------------------------------------------------------------- bool CParticleCollection::IsBatchable() const { return m_bIsBatchable; } bool CParticleCollection::ComputeIsBatchable() { int nRendererCount = GetRendererCount(); for( int i = 0; i < nRendererCount; i++ ) { if ( !GetRenderer( i )->IsBatchable() ) return false; } for( CParticleCollection *p = m_Children.m_pHead; p; p = p->m_pNext ) { if ( !p->IsBatchable() ) return false; } return true; } //----------------------------------------------------------------------------- // Is the order of the particles important //----------------------------------------------------------------------------- bool CParticleCollection::IsOrderImportant() const { return m_bIsOrderImportant; } bool CParticleCollection::ComputeIsOrderImportant() { int nRendererCount = GetRendererCount(); for( int i = 0; i < nRendererCount; i++ ) { if ( GetRenderer( i )->IsOrderImportant() ) return true; } for( CParticleCollection *p = m_Children.m_pHead; p; p = p->m_pNext ) { if ( p->IsOrderImportant() ) return true; } return false; } //----------------------------------------------------------------------------- // Does this system want to run inside its parent's ApplyKillList? //----------------------------------------------------------------------------- bool CParticleCollection::ShouldRunForParentApplyKillList() const { return m_bRunForParentApplyKillList; } bool CParticleCollection::ComputeRunForParentApplyKillList() { // Only run the system during ApplyKillList if an emitter operator wants to run then // (initializers may then run subsequently, but they won't without an emitter!) bool bApplyingKillList = true; int nEmitterCount = m_pDef->m_Emitters.Count(); for( int i = 0; i < nEmitterCount; i++ ) { if ( m_pDef->m_Emitters[i]->ShouldRun( bApplyingKillList ) ) return true; } return false; } //----------------------------------------------------------------------------- // Renderer iteration //----------------------------------------------------------------------------- int CParticleCollection::GetRendererCount() const { return IsValid() ? m_pDef->m_Renderers.Count() : 0; } CParticleOperatorInstance *CParticleCollection::GetRenderer( int i ) { return IsValid() ? m_pDef->m_Renderers[i] : NULL; } void *CParticleCollection::GetRendererContext( int i ) { return IsValid() ? m_pOperatorContextData + m_pDef->m_nRenderersCtxOffsets[i] : NULL; } //----------------------------------------------------------------------------- // Visualize operators (for editing/debugging) //----------------------------------------------------------------------------- void CParticleCollection::VisualizeOperator( const DmObjectId_t *pOpId ) { m_pRenderOp = NULL; if ( !pOpId || !m_pDef ) return; m_pRenderOp = m_pDef->FindOperatorById( FUNCTION_EMITTER, *pOpId ); if ( !m_pRenderOp ) { m_pRenderOp = m_pDef->FindOperatorById( FUNCTION_INITIALIZER, *pOpId ); if ( !m_pRenderOp ) { m_pRenderOp = m_pDef->FindOperatorById( FUNCTION_OPERATOR, *pOpId ); } } } float FadeInOut( float flFadeInStart, float flFadeInEnd, float flFadeOutStart, float flFadeOutEnd, float flCurTime ) { if ( flFadeInStart > flCurTime ) // started yet? return 0.0; if ( ( flFadeOutEnd > 0. ) && ( flFadeOutEnd < flCurTime ) ) // timed out? return 0.; // handle out of order cases flFadeInEnd = MAX( flFadeInEnd, flFadeInStart ); flFadeOutStart = MAX( flFadeOutStart, flFadeInEnd ); flFadeOutEnd = MAX( flFadeOutEnd, flFadeOutStart ); float flStrength = 1.0; if ( ( flFadeInEnd > flCurTime ) && ( flFadeInEnd > flFadeInStart ) ) flStrength = MIN( flStrength, FLerp( 0, 1, flFadeInStart, flFadeInEnd, flCurTime ) ); if ( ( flCurTime > flFadeOutStart) && ( flFadeOutEnd > flFadeOutStart) ) flStrength = MIN( flStrength, FLerp( 0, 1, flFadeOutEnd, flFadeOutStart, flCurTime ) ); return flStrength; } bool CParticleCollection::CheckIfOperatorShouldRun( CParticleOperatorInstance const * pOp , float *pflCurStrength, bool bApplyingParentKillList ) { if ( !pOp->ShouldRun( bApplyingParentKillList ) ) return false; if ( pOp->m_bStrengthFastPath ) { *pflCurStrength = 1.0; return true; } if ( pOp->m_nOpEndCapState != -1 ) { if ( m_bInEndCap != ( pOp->m_nOpEndCapState == 1 ) ) return false; } float flTime=m_flCurTime; if ( pOp->m_nOpTimeOffsetSeed ) // allow per-instance-of-particle-system random phase control for operator strength. { float flOffset = RandomFloat( pOp->m_nOpTimeOffsetSeed, pOp->m_flOpTimeOffsetMin, pOp->m_flOpTimeOffsetMax ); flTime += flOffset; flTime = MAX( 0.0, flTime ); } if ( pOp->m_nOpTimeScaleSeed && ( flTime > pOp->m_flOpStartFadeInTime ) ) { float flTimeScalar = 1.0 / MAX( .0001, RandomFloat( pOp->m_nOpTimeScaleSeed, pOp->m_flOpTimeScaleMin, pOp->m_flOpTimeScaleMax ) ); flTime = pOp->m_flOpStartFadeInTime + flTimeScalar * ( flTime - pOp->m_flOpStartFadeInTime ); } if ( pOp->m_flOpFadeOscillatePeriod > 0.0 ) { flTime = fmod( m_flCurTime*( 1.0/pOp->m_flOpFadeOscillatePeriod ), 1.0 ); } float flStrength = FadeInOut( pOp->m_flOpStartFadeInTime, pOp->m_flOpEndFadeInTime, pOp->m_flOpStartFadeOutTime, pOp->m_flOpEndFadeOutTime, flTime ); if ( pOp->m_nOpStrengthScaleSeed ) { float flStrengthMultiplier = RandomFloat( pOp->m_nOpStrengthScaleSeed, pOp->m_flOpStrengthMinScale, pOp->m_flOpStrengthMaxScale ); flStrength *= MAX( 0., flStrength * flStrengthMultiplier ); } *pflCurStrength = flStrength; return ( flStrength > 0.0 ); } void CParticleOperatorInstance::CheckForFastPath( void ) { // store away whether this operator has any of the operator modulation params set (most ops dont) if ( ( m_flOpStartFadeInTime == 0. ) && ( m_flOpEndFadeOutTime == 0. ) && ( m_flOpStartFadeOutTime == 0. ) && ( m_flOpEndFadeOutTime == 0. ) && ( m_flOpTimeOffsetMin == 0 ) && ( m_flOpTimeOffsetMax == 0 ) && ( m_flOpTimeScaleMin == 1 ) && ( m_flOpTimeScaleMax == 1 ) && ( m_flOpStrengthMaxScale == 1 ) && ( m_flOpStrengthMinScale == 1 ) && ( m_nOpEndCapState == -1 ) ) { m_bStrengthFastPath = true; } else { m_bStrengthFastPath = false; } } bool CParticleOperatorInstance::HasAttribute( CParticleCollection *pParticles, int nAttribute ) const { return ( pParticles->m_ParticleAttributes.Stride( nAttribute ) > 0 ); } KillListItem_t *CParticleOperatorInstance::GetParentKillList( CParticleCollection *pParticles, int &nNumParticlesToKill ) const { if ( pParticles->m_pParent ) { nNumParticlesToKill = pParticles->m_pParent->m_nNumParticlesToKill; return pParticles->m_pParent->m_pParticleKillList; } nNumParticlesToKill = 0; return NULL; } #ifdef NDEBUG #define CHECKSYSTEM( p ) 0 #else static void CHECKSYSTEM( CParticleCollection *pParticles ) { // Assert( pParticles->m_nActiveParticles <= pParticles->m_pDef->m_nMaxParticles ); for ( int i = 0; i < pParticles->m_nActiveParticles; ++i ) { const float *xyz = pParticles->GetFloatAttributePtr( PARTICLE_ATTRIBUTE_XYZ, i ); const float *rad = pParticles->GetFloatAttributePtr( PARTICLE_ATTRIBUTE_RADIUS, i ); const float *xyz_prev = pParticles->GetFloatAttributePtr( PARTICLE_ATTRIBUTE_PREV_XYZ, i ); Assert( IsFinite( rad[0] ) ); Assert( IsFinite( xyz[0] ) ); Assert( IsFinite( xyz[4] ) ); Assert( IsFinite( xyz[8] ) ); Assert( IsFinite( xyz_prev[0] ) ); Assert( IsFinite( xyz_prev[4] ) ); Assert( IsFinite( xyz_prev[8] ) ); } } #endif void CParticleCollection::RunRestartedEmitters( void ) { // run all emitters once that want to respond to a restart if ( m_nParticleFlags & PCFLAGS_FIRST_FRAME ) // in case we aggregated twice before _any_ sim { SimulateFirstFrame(); m_nParticleFlags &= ~PCFLAGS_FIRST_FRAME; } else { UpdatePrevControlPoints( m_flPreviousDt ); // make sure control points are virgin } int nEmitterCount = m_pDef->m_Emitters.Count(); for( int i=0; i < nEmitterCount; i++ ) { int nOldParticleCount = m_nActiveParticles; float flEmitStrength = 0; if ( CheckIfOperatorShouldRun( m_pDef->m_Emitters[i], &flEmitStrength ) ) { uint32 nInittedMask = m_pDef->m_Emitters[i]->Emit( this, flEmitStrength, m_pOperatorContextData + m_pDef->m_nEmittersCtxOffsets[i] ); if ( nOldParticleCount != m_nActiveParticles ) { // init newly emitted particles InitializeNewParticles( nOldParticleCount, m_nActiveParticles - nOldParticleCount, nInittedMask ); CHECKSYSTEM( this ); } } } for( CParticleCollection *pChild = m_Children.m_pHead; pChild != NULL; pChild = pChild->m_pNext ) pChild->RunRestartedEmitters(); } // rj: this may not be the correct thing to do, to set all of the children to the same renderable. particles_new may need to set the renderable to themselves instead. void CParticleCollection::SetRenderable( void *pRenderable ) { m_pRenderable = pRenderable; for( CParticleCollection *p = m_Children.m_pHead; p; p = p->m_pNext ) { p->SetRenderable( pRenderable ); } } //----------------------------------------------------------------------------- // Restarts a particle system //----------------------------------------------------------------------------- void CParticleCollection::Restart( EParticleRestartMode_t eMode ) { // Always reset the framecount for tick rates - this needs to be reset so that systems which are framerate dependent get updated frame counts m_nDrawnFrames = 0; // if we already have a pending restart, process it now if ( m_bPendingRestart ) { RunRestartedEmitters(); m_bPendingRestart = false; } if ( eMode == RESTART_RESET_AND_MAKE_SURE_EMITS_HAPPEN ) { m_bPendingRestart = true; m_nParticleFlags &= ~PCFLAGS_PREV_CONTROL_POINTS_INITIALIZED; } int nEmitterCount = m_pDef->m_Emitters.Count(); for( int i = 0; i < nEmitterCount; i++ ) { m_pDef->m_Emitters[i]->Restart( this, m_pOperatorContextData + m_pDef->m_nEmittersCtxOffsets[i] ); } int nInitializerCount = m_pDef->m_Initializers.Count(); for( int i = 0; i < nInitializerCount; i++ ) { m_pDef->m_Initializers[i]->Restart( this, m_pOperatorContextData + m_pDef->m_nInitializersCtxOffsets[i] ); } // Update all children for( CParticleCollection *pChild = m_Children.m_pHead; pChild != NULL; pChild = pChild->m_pNext ) { // Remove any delays from the time (otherwise we're offset by it oddly) pChild->Restart( eMode ); } } //----------------------------------------------------------------------------- // Main entry point for rendering //----------------------------------------------------------------------------- void CParticleCollection::Render( int nViewRecursionLevel, IMatRenderContext *pRenderContext, const Vector4D &vecDiffuseModulation, bool bTranslucentOnly, void *pCameraObject ) { if ( !IsValid() ) return; if ( !m_Sheet() && !m_bTriedLoadingSheet ) { m_bTriedLoadingSheet = true; m_Sheet.Set( g_pParticleSystemMgr->FindOrLoadSheet( m_pDef, true ) ); } m_flNextSleepTime = MAX( m_flNextSleepTime, ( g_pParticleSystemMgr->GetLastSimulationTime() + m_pDef->m_flNoDrawTimeToGoToSleep )); if ( m_nActiveParticles != 0 ) { Vector4D vecActualModulation; Vector4DMultiply( vecDiffuseModulation, m_pDef->m_vecMaterialModulation, vecActualModulation ); IMaterial *pMaterial = m_pDef->GetMaterial(); if ( pMaterial && ( !bTranslucentOnly || m_pDef->GetMaterial()->IsTranslucent() || ( vecActualModulation[3] != 1.0f ) ) ) { #if MEASURE_PARTICLE_PERF double flSTime = Plat_FloatTime(); #endif int nCount = m_pDef->m_Renderers.Count(); for( int i = 0; i < nCount; i++ ) { float flStrength; if ( !CheckIfOperatorShouldRun( m_pDef->m_Renderers[i], &flStrength ) ) continue; if ( m_pDef->IsScreenSpaceEffect() ) { pRenderContext->MatrixMode( MATERIAL_VIEW ); pRenderContext->PushMatrix(); pRenderContext->LoadIdentity(); pRenderContext->MatrixMode( MATERIAL_PROJECTION ); pRenderContext->PushMatrix(); pRenderContext->LoadIdentity(); pRenderContext->Ortho( -100, -100, 100, 100, -100, 100 ); m_pDef->m_Renderers[i]->Render( pRenderContext, this, vecActualModulation, m_pOperatorContextData + m_pDef->m_nRenderersCtxOffsets[i], nViewRecursionLevel ); pRenderContext->MatrixMode( MATERIAL_VIEW ); pRenderContext->PopMatrix(); pRenderContext->MatrixMode( MATERIAL_PROJECTION ); pRenderContext->PopMatrix(); } else { m_pDef->m_Renderers[i]->Render( pRenderContext, this, vecActualModulation, m_pOperatorContextData + m_pDef->m_nRenderersCtxOffsets[i], nViewRecursionLevel ); } } #if MEASURE_PARTICLE_PERF float flETime = Plat_FloatTime() - flSTime; m_pDef->m_flUncomittedTotalRenderTime += flETime; m_pDef->m_flMaxMeasuredRenderTime = MAX( m_pDef->m_flMaxMeasuredRenderTime, flETime ); #endif } } // let children render for( CParticleCollection *p = m_Children.m_pHead; p; p = p->m_pNext ) { p->Render( nViewRecursionLevel, pRenderContext, vecDiffuseModulation, bTranslucentOnly, pCameraObject ); } // Visualize specific ops for debugging/editing if ( m_pRenderOp ) { m_pRenderOp->Render( this ); } } void CParticleCollection::UpdatePrevControlPoints( float dt ) { m_flPreviousDt = dt; for(int i=0; i <= m_nHighestCP; i++ ) ControlPoint( i ).m_PrevPosition = ControlPoint( i ).m_Position; m_nParticleFlags |= PCFLAGS_PREV_CONTROL_POINTS_INITIALIZED; } #if MEASURE_PARTICLE_PERF #if VPROF_LEVEL > 0 #define START_OP float flOpStartTime = Plat_FloatTime(); VPROF_ENTER_SCOPE(pOp->GetDefinition()->GetName()) #else #define START_OP float flOpStartTime = Plat_FloatTime(); #endif #if VPROF_LEVEL > 0 #define END_OP if ( 1 ) { \ float flETime = Plat_FloatTime() - flOpStartTime; \ IParticleOperatorDefinition *pDef = (IParticleOperatorDefinition *) pOp->m_pDef; \ pDef->RecordExecutionTime( flETime ); \ } \ VPROF_EXIT_SCOPE() #else #define END_OP if ( 1 ) { \ float flETime = Plat_FloatTime() - flOpStartTime; \ IParticleOperatorDefinition *pDef = (IParticleOperatorDefinition *) pOp->m_pDef; \ pDef->RecordExecutionTime( flETime ); \ } #endif #else #define START_OP #define END_OP #endif void CParticleCollection::InitializeNewParticles( int nFirstParticle, int nParticleCount, uint32 nInittedMask, bool bApplyingParentKillList ) { VPROF_BUDGET( "CParticleCollection::InitializeNewParticles", VPROF_BUDGETGROUP_PARTICLE_SIMULATION ); #ifdef _DEBUG m_bIsRunningInitializers = true; #endif // now, initialize the attributes of all the new particles int nPerParticleAttributeMask = m_nPerParticleInitializedAttributeMask | m_nPerParticleUpdatedAttributeMask; int nAttrsLeftToInit = nPerParticleAttributeMask & ~nInittedMask; int nInitializerCount = m_pDef->m_Initializers.Count(); for ( int i = 0; i < nInitializerCount; i++ ) { CParticleOperatorInstance *pOp = m_pDef->m_Initializers[i]; int nInitializerAttrMask = pOp->GetWrittenAttributes(); if ( ( ( nInitializerAttrMask & nAttrsLeftToInit ) == 0 ) || pOp->InitMultipleOverride() ) continue; if ( !pOp->ShouldRun( bApplyingParentKillList ) ) continue; void *pContext = m_pOperatorContextData + m_pDef->m_nInitializersCtxOffsets[i]; START_OP; if ( m_bIsScrubbable && !pOp->IsScrubSafe() ) { for ( int j = 0; j < nParticleCount; ++j ) { pOp->InitNewParticles( this, nFirstParticle + j, 1, nAttrsLeftToInit, pContext ); } } else { pOp->InitNewParticles( this, nFirstParticle, nParticleCount, nAttrsLeftToInit, pContext ); } END_OP; nAttrsLeftToInit &= ~nInitializerAttrMask; } // always run second tier initializers (modifiers) after first tier - this ensures they don't get stomped. for ( int i = 0; i < nInitializerCount; i++ ) { int nInitializerAttrMask = m_pDef->m_Initializers[i]->GetWrittenAttributes(); CParticleOperatorInstance *pOp = m_pDef->m_Initializers[i]; if ( !pOp->InitMultipleOverride() ) continue; if ( !pOp->ShouldRun( bApplyingParentKillList ) ) continue; void *pContext = m_pOperatorContextData + m_pDef->m_nInitializersCtxOffsets[i]; START_OP; if ( m_bIsScrubbable && !pOp->IsScrubSafe() ) { for ( int j = 0; j < nParticleCount; ++j ) { pOp->InitNewParticles( this, nFirstParticle + j, 1, nAttrsLeftToInit, pContext ); } } else { pOp->InitNewParticles( this, nFirstParticle, nParticleCount, nAttrsLeftToInit, pContext ); } END_OP; nAttrsLeftToInit &= ~nInitializerAttrMask; } #ifdef _DEBUG m_bIsRunningInitializers = false; #endif InitParticleAttributes( nFirstParticle, nParticleCount, nAttrsLeftToInit ); CopyInitialAttributeValues( nFirstParticle, nParticleCount ); } void CParticleCollection::SkipToTime( float t ) { if ( t > m_flCurTime ) { UpdatePrevControlPoints( t - m_flCurTime ); m_flCurTime = t; m_fl4CurTime = ReplicateX4( t ); m_nParticleFlags &= ~PCFLAGS_FIRST_FRAME; // FIXME: In future, we may have to tell operators, initializers about this too int nEmitterCount = m_pDef->m_Emitters.Count(); int i; for( i = 0; i < nEmitterCount; i++ ) { m_pDef->m_Emitters[i]->SkipToTime( t, this, m_pOperatorContextData + m_pDef->m_nEmittersCtxOffsets[i] ); } CParticleCollection *pChild; // Update all children for( i = 0, pChild = m_Children.m_pHead; pChild != NULL; pChild = pChild->m_pNext, i++ ) { // Remove any delays from the time (otherwise we're offset by it oddly) pChild->SkipToTime( t - m_pDef->m_Children[i].m_flDelay ); } } } void CParticleCollection::SimulateFirstFrame( ) { m_flPrevSimTime = 1.0e23; m_flDt = 0.0f; m_nDrawnFrames = 0; // For the first frame, copy over the initial control points if ( ( m_nParticleFlags & PCFLAGS_PREV_CONTROL_POINTS_INITIALIZED ) == 0 ) { UpdatePrevControlPoints( 0.05f ); } m_nOperatorRandomSampleOffset = 0; int nCount = m_pDef->m_Operators.Count(); for( int i = 0; i < nCount; i++ ) { float flStrength = 0; CParticleOperatorInstance *pOp = m_pDef->m_Operators[i]; if ( pOp->ShouldRunBeforeEmitters() && CheckIfOperatorShouldRun( pOp, &flStrength ) ) { pOp->Operate( this, flStrength, m_pOperatorContextData + m_pDef->m_nOperatorsCtxOffsets[i] ); CHECKSYSTEM( this ); UpdatePrevControlPoints( 0.05f ); } m_nOperatorRandomSampleOffset += 17; } // first, create initial particles int nNumToCreate = MIN( m_pDef->m_nInitialParticles, m_nMaxAllowedParticles ); if ( nNumToCreate > 0 ) { SetNActiveParticles( nNumToCreate ); InitializeNewParticles( 0, nNumToCreate, 0 ); CHECKSYSTEM( this ); } } void CParticleCollection::EmitAndInit( CParticleCollection *pCollection, bool bApplyingParentKillList ) // static { if ( bApplyingParentKillList && !pCollection->ShouldRunForParentApplyKillList() ) return; int nEmitterCount = pCollection->m_pDef->m_Emitters.Count(); for( int i = 0; i < nEmitterCount; i++ ) { int nOldParticleCount = pCollection->m_nActiveParticles; float flEmitStrength = 0; if ( pCollection->CheckIfOperatorShouldRun( pCollection->m_pDef->m_Emitters[i], &flEmitStrength, bApplyingParentKillList ) ) { uint32 nInittedMask = pCollection->m_pDef->m_Emitters[i]->Emit( pCollection, flEmitStrength, pCollection->m_pOperatorContextData + pCollection->m_pDef->m_nEmittersCtxOffsets[i] ); if ( nOldParticleCount != pCollection->m_nActiveParticles ) { // init newly emitted particles pCollection->InitializeNewParticles( nOldParticleCount, pCollection->m_nActiveParticles - nOldParticleCount, nInittedMask, bApplyingParentKillList ); CHECKSYSTEM( pCollection ); } } } } void CParticleCollection::Simulate( float dt ) { VPROF_BUDGET( "CParticleCollection::Simulate", VPROF_BUDGETGROUP_PARTICLE_SIMULATION ); if ( ( dt < 0.0f ) || ( m_bFrozen ) ) return; if ( !m_pDef ) return; // Don't do anything until we've hit t == 0 // This is used for delayed children if ( m_flCurTime < 0.0f ) { if ( dt >= 1.0e-22 ) { m_flCurTime += dt; m_fl4CurTime = ReplicateX4( m_flCurTime ); UpdatePrevControlPoints( dt ); } return; } // run initializers if necessary (once we hit t == 0) if ( m_nParticleFlags & PCFLAGS_FIRST_FRAME ) { SimulateFirstFrame(); m_nParticleFlags &= ~PCFLAGS_FIRST_FRAME; } else { // if the system has been Reset, we need to copy the control points to prev control points if ( ! ( m_nParticleFlags & PCFLAGS_PREV_CONTROL_POINTS_INITIALIZED ) ) UpdatePrevControlPoints( m_flPreviousDt ); } if ( dt < 1.0e-22 ) return; m_bPendingRestart = false; #if MEASURE_PARTICLE_PERF float flStartSimTime = Plat_FloatTime(); #endif bool bAttachedKillList = false; if ( ! HasAttachedKillList() ) { g_pParticleSystemMgr->AttachKillList( this ); bAttachedKillList = true; } float flRemainingDt = dt; float flMaxDT = 0.1; // default if ( m_pDef->m_flMaximumTimeStep > 0.0 ) flMaxDT = m_pDef->m_flMaximumTimeStep; // Limit timestep if needed (prevents short lived particles from being created and destroyed before being rendered. //if ( m_pDef->m_flMaximumSimTime != 0.0 && !m_bHasDrawnOnce ) if ( m_pDef->m_flMaximumSimTime != 0.0 && ( m_nDrawnFrames <= m_pDef->m_nMinimumFrames ) ) { if ( ( flRemainingDt + m_flCurTime ) > m_pDef->m_flMaximumSimTime ) { //if delta+current > checkpoint then delta = checkpoint - current flRemainingDt = m_pDef->m_flMaximumSimTime - m_flCurTime; flRemainingDt = MAX( m_pDef->m_flMinimumSimTime, flRemainingDt ); } m_nDrawnFrames += 1; } flRemainingDt = MIN( flRemainingDt, 10 * flMaxDT ); // no more than 10 passes ever m_flTargetDrawTime += flRemainingDt; if ( ( m_flTargetDrawTime >= m_flPrevSimTime ) && ( m_flTargetDrawTime < m_flCurTime ) ) { // we can skip simulation flRemainingDt = 0; } float flMinTime = m_pDef->m_flMinimumTimeStep; bool bSaveOldValuesForInterpolation = false; while( flRemainingDt > 0.0 ) { float flDT_ThisStep = flRemainingDt; if ( flDT_ThisStep > flMaxDT ) { flDT_ThisStep = flMaxDT; } else { if ( flMinTime > flDT_ThisStep ) // can't do lerping if its going to take multiple steps? { flDT_ThisStep = flMinTime; bSaveOldValuesForInterpolation = true; } } flRemainingDt -= flDT_ThisStep; if ( m_flDt ) m_flPreviousDt = m_flDt; m_flDt = flDT_ThisStep; m_flPrevSimTime = m_flCurTime; m_flCurTime += flDT_ThisStep; m_fl4CurTime = ReplicateX4( m_flCurTime ); // now, if we are oging to interpolate, copy the current values of all attributes away if ( bSaveOldValuesForInterpolation ) { // !! speed - we could copy just the active region. if ( ! m_pPreviousAttributeMemory ) { m_pPreviousAttributeMemory = ( uint8 * ) MemAlloc_AllocAligned( m_nAttributeMemorySize, 16 ); memset( m_pPreviousAttributeMemory, 0, m_nAttributeMemorySize ); // set up the pointers m_PreviousFrameAttributes = m_ParticleAttributes; for( int i = 0; i < MAX_PARTICLE_ATTRIBUTES; i++ ) { if ( m_ParticleAttributes.Stride( i ) ) { m_PreviousFrameAttributes.m_pAttributes[i] = ( float * ) ( GetPrevAttributeMemory() + ( m_ParticleAttributes.ByteAddress( i ) - GetAttributeMemory() ) ); } } } CopyParticleAttributesToPreviousAttributes(); } #ifdef _DEBUG m_bIsRunningOperators = true; #endif m_nOperatorRandomSampleOffset = 0; int nCount = m_pDef->m_Operators.Count(); for( int i = 0; i < nCount; i++ ) { float flStrength; CParticleOperatorInstance *pOp = m_pDef->m_Operators[i]; if ( pOp->ShouldRunBeforeEmitters() && CheckIfOperatorShouldRun( pOp, &flStrength ) ) { START_OP; pOp->Operate( this, flStrength, m_pOperatorContextData + m_pDef->m_nOperatorsCtxOffsets[i] ); END_OP; CHECKSYSTEM( this ); if ( m_nNumParticlesToKill ) { ApplyKillList(); } m_nOperatorRandomSampleOffset += 17; } } #ifdef _DEBUG m_bIsRunningOperators = false; #endif // Run emitters and initializers: EmitAndInit( this ); #ifdef _DEBUG m_bIsRunningOperators = true; #endif m_nOperatorRandomSampleOffset = 0; nCount = m_pDef->m_Operators.Count(); if ( m_nActiveParticles ) for( int i = 0; i < nCount; i++ ) { float flStrength; CParticleOperatorInstance *pOp = m_pDef->m_Operators[i]; if ( (! pOp->ShouldRunBeforeEmitters() ) && CheckIfOperatorShouldRun( pOp, &flStrength ) ) { START_OP; pOp->Operate( this, flStrength, m_pOperatorContextData + m_pDef->m_nOperatorsCtxOffsets[i] ); END_OP; CHECKSYSTEM( this ); if ( m_nNumParticlesToKill ) { ApplyKillList(); if ( ! m_nActiveParticles ) break; // don't run any more operators } m_nOperatorRandomSampleOffset += 17; } } #ifdef _DEBUG m_bIsRunningOperators = false; #endif nCount = m_pDef->m_Renderers.Count(); for( int i = 0; i < nCount; i++ ) { CParticleOperatorInstance *pOp = m_pDef->m_Renderers[i]; START_OP; pOp->PostSimulate( this, m_pOperatorContextData + m_pDef->m_nRenderersCtxOffsets[i] ); END_OP; } } #if MEASURE_PARTICLE_PERF m_pDef->m_nMaximumActiveParticles = MAX( m_pDef->m_nMaximumActiveParticles, m_nActiveParticles ); float flETime = Plat_FloatTime() - flStartSimTime; m_pDef->m_flUncomittedTotalSimTime += flETime; m_pDef->m_flMaxMeasuredSimTime = MAX( m_pDef->m_flMaxMeasuredSimTime, flETime ); #endif // let children simulate for( CParticleCollection *i = m_Children.m_pHead; i; i = i->m_pNext ) { LoanKillListTo( i ); // re-use the allocated kill list for the children i->Simulate( dt ); i->m_pParticleKillList = NULL; } if ( bAttachedKillList ) g_pParticleSystemMgr->DetachKillList( this ); UpdatePrevControlPoints( dt ); // Bloat the bounding box by bounds around the control point BloatBoundsUsingControlPoint(); // check for freezing if ( m_pDef->m_flStopSimulationAfterTime < m_flCurTime ) { m_bFrozen = true; } // FIXME: Is there a way of doing this iteratively? // RecomputeBounds(); } //----------------------------------------------------------------------------- // Copies the constant attributes into the per-particle attributes //----------------------------------------------------------------------------- void CParticleCollection::InitParticleAttributes( int nStartParticle, int nNumParticles, int nAttrsLeftToInit ) { if ( nAttrsLeftToInit == 0 ) return; // !! speed!! do sse init here for( int i = nStartParticle; i < nStartParticle + nNumParticles; i++ ) { for ( int nAttr = 0; nAttr < MAX_PARTICLE_ATTRIBUTES; ++nAttr ) { if ( ( nAttrsLeftToInit & ( 1 << nAttr ) ) == 0 ) continue; float *pAttrData = GetFloatAttributePtrForWrite( nAttr, i ); // Special case for particle id if ( nAttr == PARTICLE_ATTRIBUTE_PARTICLE_ID ) { *( (int*)pAttrData ) = ( m_nRandomSeed + m_nUniqueParticleId ) & RANDOM_FLOAT_MASK; m_nUniqueParticleId++; continue; } // Special case for the creation time mask if ( nAttr == PARTICLE_ATTRIBUTE_CREATION_TIME ) { *pAttrData = m_flCurTime; continue; } // If this assertion fails, it means we're writing into constant memory, which is a nono Assert( m_ParticleAttributes.Stride( nAttr ) != 0 ); float *pConstantAttr = GetConstantAttributeMemory( nAttr ); *pAttrData = *pConstantAttr; if ( m_ParticleAttributes.Stride( nAttr ) == 12 ) { pAttrData[4] = pConstantAttr[4]; pAttrData[8] = pConstantAttr[8]; } } } } void CParticleCollection::CopyInitialAttributeValues( int nStartParticle, int nNumParticles ) { // if doinginterpolated sim, update the previous values to be the current ones, otherwise we may interpolate between // old values based upon a previous particle that was in this slot. if ( m_nPerParticleReadInitialAttributeMask == 0 ) return; // FIXME: Do SSE copy here for( int i = nStartParticle; i < nStartParticle + nNumParticles; i++ ) { for ( int nAttr = 0; nAttr < MAX_PARTICLE_ATTRIBUTES; ++nAttr ) { if ( m_nPerParticleReadInitialAttributeMask & (1 << nAttr) ) { const float *pSrcAttribute = GetFloatAttributePtr( nAttr, i ); float *pDestAttribute = GetInitialFloatAttributePtrForWrite( nAttr, i ); Assert( m_ParticleInitialAttributes.Stride( nAttr ) != 0 ); Assert( m_ParticleAttributes.Stride( nAttr ) == m_ParticleInitialAttributes.Stride( nAttr ) ); *pDestAttribute = *pSrcAttribute; if ( m_ParticleAttributes.Stride( nAttr ) == 12 ) { pDestAttribute[4] = pSrcAttribute[4]; pDestAttribute[8] = pSrcAttribute[8]; } } } } } void CParticleCollection::CopyParticleAttributesToPreviousAttributes( void ) const { for( int i = 0; i < MAX_PARTICLE_ATTRIBUTES; i++ ) { if ( m_PreviousFrameAttributes.Stride( i ) ) { int nSz = m_nPaddedActiveParticles * 4 * m_PreviousFrameAttributes.Stride( i ); memcpy( m_PreviousFrameAttributes.Address( i ), m_ParticleAttributes.Address( i ), nSz ); } } } //-----------------------------------------------------------------------------e // Computes a random vector inside a sphere //----------------------------------------------------------------------------- float CParticleCollection::RandomVectorInUnitSphere( int nRandomSampleId, Vector *pVector ) { // Guarantee uniform random distribution within a sphere // Graphics gems III contains this algorithm ("Nonuniform random point sets via warping") float u = RandomFloat( nRandomSampleId, 0.0001f, 1.0f ); float v = RandomFloat( nRandomSampleId+1, 0.0001f, 1.0f ); float w = RandomFloat( nRandomSampleId+2, 0.0001f, 1.0f ); float flPhi = acos( 1 - 2 * u ); float flTheta = 2 * M_PI * v; float flRadius = powf( w, 1.0f / 3.0f ); float flSinPhi, flCosPhi; float flSinTheta, flCosTheta; SinCos( flPhi, &flSinPhi, &flCosPhi ); SinCos( flTheta, &flSinTheta, &flCosTheta ); pVector->x = flRadius * flSinPhi * flCosTheta; pVector->y = flRadius * flSinPhi * flSinTheta; pVector->z = flRadius * flCosPhi; return flRadius; } //----------------------------------------------------------------------------- // Used to retrieve the position of a control point // somewhere between m_flCurTime and m_flCurTime - m_fPreviousDT //----------------------------------------------------------------------------- void CParticleCollection::GetControlPointAtTime( int nControlPoint, float flTime, Vector *pControlPoint ) { Assert( m_pDef->ReadsControlPoint( nControlPoint ) ); // if ( nControlPoint > GetHighestControlPoint() ) // { // DevWarning(2, "Warning : Particle system (%s) using unassigned ControlPoint %d!\n", GetName(), nControlPoint ); // } float flPrevTime = m_flCurTime - m_flDt; // While this assert is valid, the below if statement is a good enough band-aid to make it so that // particles aren't appearing a weird locations. // Assert( flTime + 0.5f >= flPrevTime && flTime <= m_flCurTime ); if ( flTime < flPrevTime ) { flTime = flPrevTime; } float deltaTime = ( flTime - flPrevTime ); if ( m_flDt == 0.0f || ( deltaTime == 0.0f ) ) { VectorCopy( ControlPoint( nControlPoint ).m_Position, *pControlPoint ); return; } float t = deltaTime / m_flDt; VectorLerp( ControlPoint( nControlPoint ).m_PrevPosition, ControlPoint( nControlPoint ).m_Position, t, *pControlPoint ); Assert( IsFinite(pControlPoint->x) && IsFinite(pControlPoint->y) && IsFinite(pControlPoint->z) ); } //----------------------------------------------------------------------------- // Used to retrieve the previous position of a control point // //----------------------------------------------------------------------------- void CParticleCollection::GetControlPointAtPrevTime( int nControlPoint, Vector *pControlPoint ) { Assert( m_pDef->ReadsControlPoint( nControlPoint ) ); *pControlPoint = ControlPoint( nControlPoint ).m_PrevPosition; } void CParticleCollection::GetControlPointTransformAtCurrentTime( int nControlPoint, matrix3x4_t *pMat ) { Assert( m_pDef->ReadsControlPoint( nControlPoint ) ); const Vector &vecControlPoint = GetControlPointAtCurrentTime( nControlPoint ); // FIXME: Use quaternion lerp to get control point transform at time Vector left; VectorMultiply( ControlPoint( nControlPoint ).m_RightVector, -1.0f, left ); pMat->Init( ControlPoint( nControlPoint ).m_ForwardVector, left, ControlPoint( nControlPoint ).m_UpVector, vecControlPoint ); } void CParticleCollection::GetControlPointTransformAtCurrentTime( int nControlPoint, VMatrix *pMat ) { GetControlPointTransformAtCurrentTime( nControlPoint, &pMat->As3x4() ); pMat->m[3][0] = pMat->m[3][1] = pMat->m[3][2] = 0.0f; pMat->m[3][3] = 1.0f; } void CParticleCollection::GetControlPointOrientationAtTime( int nControlPoint, float flTime, Vector *pForward, Vector *pRight, Vector *pUp ) { Assert( m_pDef->ReadsControlPoint( nControlPoint ) ); // FIXME: Use quaternion lerp to get control point transform at time *pForward = ControlPoint( nControlPoint ).m_ForwardVector; *pRight = ControlPoint( nControlPoint ).m_RightVector; *pUp = ControlPoint( nControlPoint ).m_UpVector; } void CParticleCollection::GetControlPointTransformAtTime( int nControlPoint, float flTime, matrix3x4_t *pMat ) { Assert( m_pDef->ReadsControlPoint( nControlPoint ) ); Vector vecControlPoint; GetControlPointAtTime( nControlPoint, flTime, &vecControlPoint ); // FIXME: Use quaternion lerp to get control point transform at time Vector left; VectorMultiply( ControlPoint(nControlPoint).m_RightVector, -1.0f, left ); pMat->Init( ControlPoint( nControlPoint ).m_ForwardVector, left, ControlPoint( nControlPoint ).m_UpVector, vecControlPoint ); } void CParticleCollection::GetControlPointTransformAtTime( int nControlPoint, float flTime, VMatrix *pMat ) { GetControlPointTransformAtTime( nControlPoint, flTime, &pMat->As3x4() ); pMat->m[3][0] = pMat->m[3][1] = pMat->m[3][2] = 0.0f; pMat->m[3][3] = 1.0f; } void CParticleCollection::GetControlPointTransformAtTime( int nControlPoint, float flTime, CParticleSIMDTransformation *pXForm ) { Assert( m_pDef->ReadsControlPoint( nControlPoint ) ); Vector vecControlPoint; GetControlPointAtTime( nControlPoint, flTime, &vecControlPoint ); pXForm->m_v4Origin.DuplicateVector( vecControlPoint ); pXForm->m_v4Fwd.DuplicateVector( ControlPoint( nControlPoint ).m_ForwardVector ); pXForm->m_v4Up.DuplicateVector( ControlPoint( nControlPoint ).m_UpVector ); //Vector left; //VectorMultiply( ControlPoint(nControlPoint).m_RightVector, -1.0f, left ); pXForm->m_v4Right.DuplicateVector( ControlPoint( nControlPoint ).m_RightVector ); } int CParticleCollection::GetHighestControlPoint( void ) const { return m_nHighestCP; } //----------------------------------------------------------------------------- // Returns the render bounds //----------------------------------------------------------------------------- void CParticleCollection::GetBounds( Vector *pMin, Vector *pMax ) { *pMin = m_MinBounds; *pMax = m_MaxBounds; } //----------------------------------------------------------------------------- // Bloat the bounding box by bounds around the control point //----------------------------------------------------------------------------- void CParticleCollection::BloatBoundsUsingControlPoint() { // more specifically, some particle systems were using "start" as an input, so it got set as control point 1, // so other particle systems had an extra point in their bounding box, that generally remained at the world origin RecomputeBounds(); // Deal with children // NOTE: Bounds have been recomputed for children prior to this call in Simulate bool bIsValid = m_bBoundsValid; Vector vecMins, vecMaxs; for( CParticleCollection *i = m_Children.m_pHead; i; i = i->m_pNext ) { // mdonofrio - skip screen space effects, they have CPs at the origin if( (i->m_nActiveParticles > 0 ) && (!i->m_pDef->IsScreenSpaceEffect()) ) { i->GetBounds( &vecMins, &vecMaxs ); VectorMin( m_MinBounds, vecMins, m_MinBounds ); VectorMax( m_MaxBounds, vecMaxs, m_MaxBounds ); bIsValid = ( bIsValid || i->m_bBoundsValid ); } } m_bBoundsValid = bIsValid; } //----------------------------------------------------------------------------- // Recomputes the bounds //----------------------------------------------------------------------------- inline void UpdateBounds( fltx4 &min_, fltx4 &max_, fltx4 &sum_, fltx4 val ) { min_ = MinSIMD( min_, val ); max_ = MaxSIMD( max_, val ); sum_ = AddSIMD( sum_, val ); } inline void UpdateBounds( float &min_, float &max_, float &sum_, float val ) { min_ = MIN( min_, val ); max_ = MAX( max_, val ); sum_ = sum_ + val; } void CParticleCollection::RecomputeBounds( void ) { // mdonofrio - skip screen space effects (as they have CPs at the origin) as well as those with 0 active particles if( ( m_nActiveParticles == 0 ) || m_pDef->IsScreenSpaceEffect() ) { m_bBoundsValid = false; m_MinBounds.Init( FLT_MAX, FLT_MAX, FLT_MAX ); m_MaxBounds.Init( -FLT_MAX, -FLT_MAX, -FLT_MAX ); m_Center.Init(); return; } fltx4 min_x = ReplicateX4(1.0e23); fltx4 min_y = min_x; fltx4 min_z = min_x; fltx4 max_x = ReplicateX4(-1.0e23); fltx4 max_y = max_x; fltx4 max_z = max_x; fltx4 sum_x = Four_Zeros; fltx4 sum_y = Four_Zeros; fltx4 sum_z = Four_Zeros; float flMaxTail = m_pDef->GetMaxTailLength(); float flOODt = ( m_flDt != 0.0f ) ? ( 1.0f / m_flDt ) : 1.0f; fltx4 maxtail = ReplicateX4( flMaxTail ); fltx4 oodt = ReplicateX4( flOODt ); size_t xyz_stride, prev_stride, trail_stride; const fltx4 *xyz = GetM128AttributePtr( PARTICLE_ATTRIBUTE_XYZ, &xyz_stride ); const fltx4 *prev = GetM128AttributePtr( PARTICLE_ATTRIBUTE_PREV_XYZ, &prev_stride ); const fltx4 *trail = GetM128AttributePtr( PARTICLE_ATTRIBUTE_TRAIL_LENGTH, &trail_stride ); int ctr = m_nActiveParticles/4; bool bHasTail = ( flMaxTail > 0.0f ); if ( bHasTail ) { while ( ctr-- ) { UpdateBounds( min_x, max_x, sum_x, xyz[0] ); UpdateBounds( min_y, max_y, sum_y, xyz[1] ); UpdateBounds( min_z, max_z, sum_z, xyz[2] ); fltx4 delta_x = SubSIMD( prev[0], xyz[0] ); fltx4 delta_y = SubSIMD( prev[1], xyz[1] ); fltx4 delta_z = SubSIMD( prev[2], xyz[2] ); fltx4 d2_x = MulSIMD( delta_x, delta_x ); fltx4 d2_y = MulSIMD( delta_y, delta_y ); fltx4 d2_z = MulSIMD( delta_z, delta_z ); fltx4 lensq = AddSIMD( d2_z, AddSIMD( d2_y, d2_x ) ); fltx4 len = MaxSIMD( ReplicateX4( 0.001f ), SqrtSIMD( lensq ) ); fltx4 invlen = ReciprocalSIMD( len ); delta_x = MulSIMD( delta_x, invlen ); delta_y = MulSIMD( delta_y, invlen ); delta_z = MulSIMD( delta_z, invlen ); len = MulSIMD( len, trail[0] ); len = MulSIMD( len, oodt ); len = MinSIMD( len, maxtail ); delta_x = MulSIMD( delta_x, len ); delta_y = MulSIMD( delta_y, len ); delta_z = MulSIMD( delta_z, len ); fltx4 tail_x = AddSIMD( xyz[0], delta_x ); fltx4 tail_y = AddSIMD( xyz[1], delta_y ); fltx4 tail_z = AddSIMD( xyz[2], delta_z ); UpdateBounds( min_x, max_x, sum_x, tail_x ); UpdateBounds( min_y, max_y, sum_y, tail_y ); UpdateBounds( min_z, max_z, sum_z, tail_z ); xyz += xyz_stride; prev += prev_stride; trail += trail_stride; } } else { while ( ctr-- ) { UpdateBounds( min_x, max_x, sum_x, xyz[0] ); UpdateBounds( min_y, max_y, sum_y, xyz[1] ); UpdateBounds( min_z, max_z, sum_z, xyz[2] ); xyz += xyz_stride; } } m_bBoundsValid = true; m_MinBounds.x = MIN( MIN( SubFloat( min_x, 0 ), SubFloat( min_x, 1 ) ), MIN( SubFloat( min_x, 2 ), SubFloat( min_x, 3 ) ) ); m_MinBounds.y = MIN( MIN( SubFloat( min_y, 0 ), SubFloat( min_y, 1 ) ), MIN( SubFloat( min_y, 2 ), SubFloat( min_y, 3 ) ) ); m_MinBounds.z = MIN( MIN( SubFloat( min_z, 0 ), SubFloat( min_z, 1 ) ), MIN( SubFloat( min_z, 2 ), SubFloat( min_z, 3 ) ) ); m_MaxBounds.x = MAX( MAX( SubFloat( max_x, 0 ), SubFloat( max_x, 1 ) ), MAX( SubFloat( max_x, 2 ), SubFloat( max_x, 3 ) ) ); m_MaxBounds.y = MAX( MAX( SubFloat( max_y, 0 ), SubFloat( max_y, 1 ) ), MAX( SubFloat( max_y, 2 ), SubFloat( max_y, 3 ) ) ); m_MaxBounds.z = MAX( MAX( SubFloat( max_z, 0 ), SubFloat( max_z, 1 ) ), MAX( SubFloat( max_z, 2 ), SubFloat( max_z, 3 ) ) ); float fsum_x = SubFloat( sum_x, 0 ) + SubFloat( sum_x, 1 ) + SubFloat( sum_x, 2 ) + SubFloat( sum_x, 3 ); float fsum_y = SubFloat( sum_y, 0 ) + SubFloat( sum_y, 1 ) + SubFloat( sum_y, 2 ) + SubFloat( sum_y, 3 ); float fsum_z = SubFloat( sum_z, 0 ) + SubFloat( sum_z, 1 ) + SubFloat( sum_z, 2 ) + SubFloat( sum_z, 3 ); // now, handle "tail" in a non-sse manner for( int i=0; i < ( m_nActiveParticles & 3 ); i++) { Vector pos( SubFloat( xyz[0], i ), SubFloat( xyz[1], i ), SubFloat( xyz[2], i ) ); UpdateBounds( m_MinBounds.x, m_MaxBounds.x, fsum_x, pos.x ); UpdateBounds( m_MinBounds.y, m_MaxBounds.y, fsum_y, pos.y ); UpdateBounds( m_MinBounds.z, m_MaxBounds.z, fsum_z, pos.z ); if ( bHasTail ) if ( flMaxTail > 0.0f ) { Vector pos_prev( SubFloat( prev[0], i ), SubFloat( prev[1], i ), SubFloat( prev[2], i ) ); Vector dir = pos_prev - pos; float len = VectorNormalize( dir ); len = MIN( MAX( len, 0.001f ) * SubFloat( trail[0], i ) * flOODt, flMaxTail ); Vector tail = pos + dir * len; UpdateBounds( m_MinBounds.x, m_MaxBounds.x, fsum_x, tail.x ); UpdateBounds( m_MinBounds.y, m_MaxBounds.y, fsum_y, tail.y ); UpdateBounds( m_MinBounds.z, m_MaxBounds.z, fsum_z, tail.z ); } } VectorAdd( m_MinBounds, m_pDef->m_BoundingBoxMin, m_MinBounds ); VectorAdd( m_MaxBounds, m_pDef->m_BoundingBoxMax, m_MaxBounds ); // calculate center float flOONumParticles = 1.0 / ( ( flMaxTail > 0.0f ) ? 2 * m_nActiveParticles : m_nActiveParticles ); m_Center.x = flOONumParticles * fsum_x; m_Center.y = flOONumParticles * fsum_y; m_Center.z = flOONumParticles * fsum_z; } //----------------------------------------------------------------------------- // Is the particle system finished emitting + all its particles are dead? //----------------------------------------------------------------------------- bool CParticleCollection::IsFinished( void ) const { if ( !m_pDef ) return true; if ( m_nParticleFlags & PCFLAGS_FIRST_FRAME ) return false; if ( m_nActiveParticles ) return false; if ( m_bDormant ) return false; // no particles. See if any emmitters intead to create more particles int nEmitterCount = m_pDef->m_Emitters.Count(); for( int i=0; i < nEmitterCount; i++ ) { if ( m_pDef->m_Emitters[i]->MayCreateMoreParticles( this, m_pOperatorContextData+m_pDef->m_nEmittersCtxOffsets[i] ) ) return false; } // make sure all children are finished CParticleCollection *pChild = m_Children.Head(); for( int i = 0; pChild != NULL; pChild = pChild->m_pNext, i++ ) { if ( !pChild->IsFinished() && !m_pDef->m_Children[i].m_bEndCap ) return false; // return false if we're currently playing our endcap effect and not finished with it if ( m_pDef->m_Children[i].m_bEndCap && !pChild->IsFinished() && m_bInEndCap ) return false; } return true; } //----------------------------------------------------------------------------- // Purpose: Stop emitting particles //----------------------------------------------------------------------------- void CParticleCollection::StopEmission( bool bInfiniteOnly, bool bRemoveAllParticles, bool bWakeOnStop, bool bPlayEndCap ) { if ( !m_pDef ) return; // Whenever we call stop emission, we clear out our dormancy. This ensures we // get deleted if we're told to stop emission while dormant. SetDormant() ensures // dormancy is set to true after stopping out emission. m_bDormant = false; if ( bWakeOnStop ) { // Set next sleep time - an additional fudge factor is added over the normal time // so that existing particles have a chance to go away. m_flNextSleepTime = MAX( m_flNextSleepTime, ( g_pParticleSystemMgr->GetLastSimulationTime() + 10 )); } m_bEmissionStopped = true; for( int i=0; i < m_pDef->m_Emitters.Count(); i++ ) { m_pDef->m_Emitters[i]->StopEmission( this, m_pOperatorContextData + m_pDef->m_nEmittersCtxOffsets[i], bInfiniteOnly ); } if ( bRemoveAllParticles ) { SetNActiveParticles( 0 ); } // Stop our children as well if ( bPlayEndCap ) { CParticleCollection *pChild; int i; m_bInEndCap = true; for( i = 0, pChild = m_Children.m_pHead; pChild != NULL; pChild = pChild->m_pNext, i++ ) { pChild->m_bInEndCap = true; if ( m_pDef->m_Children[i].m_bEndCap ) { pChild->m_flCurTime = 0.0f; pChild->StartEmission( bInfiniteOnly ); } else pChild->StopEmission( bInfiniteOnly, bRemoveAllParticles, bWakeOnStop, bPlayEndCap ); } } else { for( CParticleCollection *p = m_Children.m_pHead; p; p = p->m_pNext ) { p->StopEmission( bInfiniteOnly, bRemoveAllParticles ); } } } //----------------------------------------------------------------------------- // Purpose: Stop emitting particles //----------------------------------------------------------------------------- void CParticleCollection::StartEmission( bool bInfiniteOnly ) { if ( !m_pDef ) return; m_bEmissionStopped = false; for( int i=0; i < m_pDef->m_Emitters.Count(); i++ ) { m_pDef->m_Emitters[i]->StartEmission( this, m_pOperatorContextData + m_pDef->m_nEmittersCtxOffsets[i], bInfiniteOnly ); } // Start our children as well CParticleCollection *pChild = m_Children.Head(); for( int i = 0; pChild != NULL; pChild = pChild->m_pNext, i++ ) { // Don't start End Cap Effects - these only play when stopping emission. if ( !m_pDef->m_Children[i].m_bEndCap ) { pChild->StartEmission( bInfiniteOnly ); } } // Set our sleep time to some time in the future so we update again m_flNextSleepTime = g_pParticleSystemMgr->GetLastSimulationTime() + m_pDef->m_flNoDrawTimeToGoToSleep; } //----------------------------------------------------------------------------- // Purpose: Dormant particle systems simulate their particles, but don't emit // new ones. Unlike particle systems that have StopEmission() called // dormant particle systems don't remove themselves when they're // out of particles, assuming they'll return at some point. //----------------------------------------------------------------------------- void CParticleCollection::SetDormant( bool bDormant ) { // Don't stop or start emission if we are not changing dormancy state if ( bDormant == m_bDormant ) return; // If emissions have already been stopped, don't go dormant, we're supposed to be dying. if ( m_bEmissionStopped && bDormant ) return; if ( bDormant ) { StopEmission(); m_bQueuedStartEmission = false; } else { //StartEmission(); m_bQueuedStartEmission = true; // start emission during next sim step // Set our sleep time to some time in the future so we update again m_flNextSleepTime = g_pParticleSystemMgr->GetLastSimulationTime() + m_pDef->m_flNoDrawTimeToGoToSleep; } m_bDormant = bDormant; } bool CParticleCollection::IsEmitting() const { return !m_bEmissionStopped; } void CParticleAttributeAddressTable::CopyParticleAttributes( int nSrcIndex, int nDestIndex ) const { for( int p = 0; p < ARRAYSIZE( m_pAttributes ); p++ ) { switch( m_nFloatStrides[p] ) { case 4: // move a float m_pAttributes[p][nDestIndex] = m_pAttributes[p][nSrcIndex]; break; case 12: // move a vec3 { // sse weirdness int oldidxsse = 12 * ( nDestIndex >> 2 ); int oldofs = oldidxsse + ( nDestIndex & 3 ); int lastidxsse = 12 * ( nSrcIndex >> 2 ); int lastofs = lastidxsse + ( nSrcIndex & 3 ); m_pAttributes[p][oldofs] = m_pAttributes[p][lastofs]; m_pAttributes[p][4 + oldofs] = m_pAttributes[p][4 + lastofs]; m_pAttributes[p][8 + oldofs] = m_pAttributes[p][8 + lastofs]; break; } } } } void CParticleCollection::MoveParticle( int nInitialIndex, int nNewIndex ) { // Copy the per-particle attributes m_ParticleAttributes.CopyParticleAttributes( nInitialIndex, nNewIndex ); m_ParticleInitialAttributes.CopyParticleAttributes( nInitialIndex, nNewIndex ); if ( m_pPreviousAttributeMemory ) { m_PreviousFrameAttributes.CopyParticleAttributes( nInitialIndex, nNewIndex ); } } //----------------------------------------------------------------------------- // Kill List processing. //----------------------------------------------------------------------------- #define THREADED_PARTICLES 1 #if THREADED_PARTICLES #define MAX_SIMULTANEOUS_KILL_LISTS 16 static volatile int g_nKillBufferInUse[MAX_SIMULTANEOUS_KILL_LISTS]; static KillListItem_t *g_pKillBuffers[MAX_SIMULTANEOUS_KILL_LISTS]; void CParticleSystemMgr::DetachKillList( CParticleCollection *pParticles ) { if ( pParticles->m_pParticleKillList ) { // find which it is for(int i=0; i < NELEMS( g_pKillBuffers ); i++) { if ( g_pKillBuffers[i] == pParticles->m_pParticleKillList ) { pParticles->m_pParticleKillList = NULL; g_nKillBufferInUse[i] = 0; // no need to interlock return; } } Assert( 0 ); // how did we get here? } } void CParticleSystemMgr::AttachKillList( CParticleCollection *pParticles ) { // look for a free slot for(;;) { for(int i=0; i < NELEMS( g_nKillBufferInUse ); i++) { if ( ! g_nKillBufferInUse[i] ) // available? { // try to take it! if ( ThreadInterlockedAssignIf( &( g_nKillBufferInUse[i]), 1, 0 ) ) { if ( ! g_pKillBuffers[i] ) { g_pKillBuffers[i] = new KillListItem_t[MAX_PARTICLES_IN_A_SYSTEM]; } pParticles->m_pParticleKillList = g_pKillBuffers[i]; return; // done! } } } Assert(0); // why don't we have enough buffers? ThreadSleep(); } } #else // use one static kill list. no worries because of not threading static KillListItem_t g_nParticleKillList[MAX_PARTICLES_IN_A_SYSTEM]; void CParticleSystemMgr::AttachKillList( CParticleCollection *pParticles ) { pParticles->m_pParticleKillList = g_nParticleKillList; } void CParticleCollection::DetachKillList( CParticleCollection *pParticles ) { Assert( pParticles->m_nNumParticlesToKill == 0 ); pParticles->m_pParticleKillList = NULL; } #endif void CParticleCollection::ApplyKillList( void ) { // first, kill particles past bounds const KillListItem_t *pCurKillListSlot = m_pParticleKillList; while( m_nNumParticlesToKill && pCurKillListSlot[ m_nNumParticlesToKill-1 ].nIndex >= (uint)m_nActiveParticles ) { m_nNumParticlesToKill--; } Assert( m_nNumParticlesToKill <= m_nActiveParticles ); if ( m_nNumParticlesToKill == 0 ) return; // next, run any child system emitter/initializer operators which request the parent's kill list: bool bApplyingParentKillList = true; for( CParticleCollection *pChild = m_Children.m_pHead; pChild != NULL; pChild = pChild->m_pNext ) { // TODO: make this more general (there's a bunch of "first frame" and "frame-to-frame" setup that happens in Simulate() which is skipped here) EmitAndInit( pChild, bApplyingParentKillList ); } // now, execute kill list (NOTE: this algorithm assumes the particles listed // in the kill list are in ascending order - this is checked in KillParticle) unsigned int nParticlesActiveNow = m_nActiveParticles; int nLeftInKillList = m_nNumParticlesToKill; if ( nLeftInKillList == m_nActiveParticles ) { nParticlesActiveNow = 0; // Simply discard all particles } // TODO: check KILL_LIST_FLAG_DONT_KILL here (take no action for those kill list entries) else if ( IsOrderImportant() ) { // shift m_pParticleKillList[ nLeftInKillList ].nIndex = m_nActiveParticles; for ( int nKilled = 0; nKilled < nLeftInKillList; ) { int nWriteIndex = m_pParticleKillList[ nKilled ].nIndex - nKilled; nKilled++; int nNextIndexToKill = m_pParticleKillList[ nKilled ].nIndex - nKilled; for ( nWriteIndex; nWriteIndex < nNextIndexToKill; nWriteIndex++ ) { MoveParticle( ( nWriteIndex + nKilled ), nWriteIndex ); } } nParticlesActiveNow -= nLeftInKillList; } else { while( nLeftInKillList ) { unsigned int nKillIndex = (pCurKillListSlot++)->nIndex; nLeftInKillList--; // now, we will move a particle from the end to where we are // first, we have to find the last particle (which is not in the kill list) while ( nLeftInKillList && ( pCurKillListSlot[ nLeftInKillList-1 ].nIndex == nParticlesActiveNow-1 )) { nLeftInKillList--; nParticlesActiveNow--; } // we might be killing the last particle if ( nKillIndex == nParticlesActiveNow-1 ) { // killing last one nParticlesActiveNow--; break; // we are done } // move the last particle to this one and chop off the end of the list MoveParticle( nParticlesActiveNow-1, nKillIndex ); nParticlesActiveNow--; } } // set count in system and wipe kill list SetNActiveParticles( nParticlesActiveNow ); m_nNumParticlesToKill = 0; } void CParticleCollection::CalculatePathValues( CPathParameters const &PathIn, float flTimeStamp, Vector *pStartPnt, Vector *pMidPnt, Vector *pEndPnt ) { Vector StartPnt; GetControlPointAtTime( PathIn.m_nStartControlPointNumber, flTimeStamp, &StartPnt ); Vector EndPnt; GetControlPointAtTime( PathIn.m_nEndControlPointNumber, flTimeStamp, &EndPnt ); Vector MidP; VectorLerp(StartPnt, EndPnt, PathIn.m_flMidPoint, MidP); if ( PathIn.m_nBulgeControl ) { Vector vTarget=(EndPnt-StartPnt); float flBulgeScale = 0.0; int nCP=PathIn.m_nStartControlPointNumber; if ( PathIn.m_nBulgeControl == 2) nCP = PathIn.m_nEndControlPointNumber; Vector Fwd = ControlPoint( nCP ).m_ForwardVector; float len=VectorLength( vTarget); if ( len > 1.0e-6 ) { vTarget *= (1.0/len); // normalize flBulgeScale = 1.0-fabs( DotProduct( vTarget, Fwd )); // bulge inversely scaled } Vector Potential_MidP=Fwd; float flOffsetDist = VectorLength( Potential_MidP ); if ( flOffsetDist > 1.0e-6 ) { Potential_MidP *= (PathIn.m_flBulge*len*flBulgeScale)/flOffsetDist; MidP += Potential_MidP; } } else { Vector RndVector; RandomVector( 0, -PathIn.m_flBulge, PathIn.m_flBulge, &RndVector); MidP+=RndVector; } *pStartPnt = StartPnt; *pMidPnt = MidP; *pEndPnt = EndPnt; } //----------------------------------------------------------------------------- // // Default impelemtation of the query // //----------------------------------------------------------------------------- class CDefaultParticleSystemQuery : public CBaseAppSystem< IParticleSystemQuery > { public: virtual bool IsEditor( ) { return false; } virtual void GetLightingAtPoint( const Vector& vecOrigin, Color &tint ) { tint.SetColor( 255, 255, 255, 255 ); } virtual void TraceLine( const Vector& vecAbsStart, const Vector& vecAbsEnd, unsigned int mask, const class IHandleEntity *ignore, int collisionGroup, CBaseTrace *ptr ) { ptr->fraction = 1.0; // no hit } virtual bool IsPointInSolid( const Vector& vecPos, const int nContentsMask ) { return false; } virtual void GetRandomPointsOnControllingObjectHitBox( CParticleCollection *pParticles, int nControlPointNumber, int nNumPtsOut, float flBBoxScale, int nNumTrysToGetAPointInsideTheModel, Vector *pPntsOut, Vector vecDirectionBias, Vector *pHitBoxRelativeCoordOut, int *pHitBoxIndexOut, int nDesiredHitbox, const char *pszHitboxSetName ) { for ( int i = 0; i < nNumPtsOut; ++i ) { pPntsOut[i].Init(); } } virtual void GetClosestControllingObjectHitBox( CParticleCollection *pParticles, int nControlPointNumber, int nNumPtsIn, float flBBoxScale, Vector *pPntsIn, Vector *pHitBoxRelativeCoordOut, int *pHitBoxIndexOut, int nDesiredHitbox, const char *pszHitboxSetName ) { for ( int i=0; i < nNumPtsIn; i++ ) { if ( pHitBoxIndexOut ) pHitBoxIndexOut[i] = 0; if ( pHitBoxRelativeCoordOut ) pHitBoxRelativeCoordOut[i].Init(); } } virtual void TraceAgainstRayTraceEnv( int envnumber, const FourRays &rays, fltx4 TMin, fltx4 TMax, RayTracingResult *rslt_out, int32 skip_id ) const { rslt_out->HitDistance = Four_Ones; rslt_out->surface_normal.DuplicateVector( vec3_origin ); } virtual Vector GetCurrentViewOrigin() { return vec3_origin; } virtual int GetActivityCount() { return 0; } virtual const char *GetActivityNameFromIndex( int nActivityIndex ) { return 0; } virtual int GetActivityNumber( void *pModel, const char *m_pszActivityName ) { return -1; } virtual float GetPixelVisibility( int *pQueryHandle, const Vector &vecOrigin, float flScale ) { return 0.0f; } virtual void PreSimulate( ) { } virtual void PostSimulate( ) { } virtual void DebugDrawLine( const Vector &origin, const Vector &target, int r, int g, int b, bool noDepthTest, float duration ) { } virtual void DrawModel( void *pModel, const matrix3x4_t &DrawMatrix, CParticleCollection *pParticles, int nParticleNumber, int nBodyPart, int nSubModel, int nSkin, int nAnimationSequence = 0, float flAnimationRate = 30.0f, float r = 1.0f, float g = 1.0f, float b = 1.0f, float a = 1.0f ) { } virtual void UpdateProjectedTexture( const int nParticleID, IMaterial *pMaterial, Vector &vOrigin, float flRadius, float flRotation, float r, float g, float b, float a, void *&pUserVar ) { } }; static CDefaultParticleSystemQuery s_DefaultParticleSystemQuery; //----------------------------------------------------------------------------- // // Particle system manager // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- CParticleSystemMgr::CParticleSystemMgr() // m_SheetList( DefLessFunc( ITexture * ) ) { m_pQuery = &s_DefaultParticleSystemQuery; m_bDidInit = false; m_bUsingDefaultQuery = true; m_bShouldLoadSheets = true; m_bAllowPrecache = true; m_pParticleSystemDictionary = NULL; m_nNumFramesMeasured = 0; m_flLastSimulationTime = 0.0f; m_flLastSimulationDuration = 0.0f; m_pShadowDepthMaterial = NULL; // Init the attribute table InitAttributeTable(); } CParticleSystemMgr::~CParticleSystemMgr() { FlushAllSheets(); if ( m_pParticleSystemDictionary ) { delete m_pParticleSystemDictionary; m_pParticleSystemDictionary = NULL; } } //----------------------------------------------------------------------------- // Initialize the particle system //----------------------------------------------------------------------------- bool CParticleSystemMgr::Init( IParticleSystemQuery *pQuery, bool bAllowPrecache ) { if ( g_pMaterialSystem && ( !g_pMaterialSystem->QueryInterface( MATERIAL_SYSTEM_INTERFACE_VERSION ) ) ) { Msg( "CParticleSystemMgr compiled using an old IMaterialSystem\n" ); return false; } if ( m_bUsingDefaultQuery && pQuery ) { m_pQuery = pQuery; m_bUsingDefaultQuery = false; } if ( !m_bDidInit ) { m_pParticleSystemDictionary = new CParticleSystemDictionary; // NOTE: This is for the editor only AddParticleOperator( FUNCTION_CHILDREN, &s_ChildOperatorDefinition ); if ( g_pMaterialSystem ) { MEM_ALLOC_CREDIT(); KeyValues *pVMTKeyValues = new KeyValues( "DepthWrite" ); pVMTKeyValues->SetInt( "$no_fullbright", 1 ); pVMTKeyValues->SetInt( "$model", 0 ); pVMTKeyValues->SetInt( "$alphatest", 0 ); m_pShadowDepthMaterial = g_pMaterialSystem->CreateMaterial( "__particlesDepthWrite", pVMTKeyValues ); } SeedRandSIMD( 12345678 ); m_bDidInit = true; } m_bAllowPrecache = bAllowPrecache; return true; } //----------------------------------------------------------------------------- void CParticleSystemMgr::Shutdown() { if ( m_pShadowDepthMaterial ) { m_pShadowDepthMaterial->Release(); m_pShadowDepthMaterial = NULL; } } //----------------------------------------------------------------------------- // Init the attribute table //----------------------------------------------------------------------------- void CParticleSystemMgr::InitAttributeTable( void ) { // Init the attribute table #define INITPARTICLE_ATTRIBUTE( name ) \ { \ int bit = PARTICLE_ATTRIBUTE_##name; \ s_AttributeTable[ bit ].nDataType = PARTICLE_ATTRIBUTE_##name##_DATATYPE; \ s_AttributeTable[ bit ].pName = #name; \ } memset( s_AttributeTable, 0, sizeof( s_AttributeTable ) ); INITPARTICLE_ATTRIBUTE( XYZ ); INITPARTICLE_ATTRIBUTE( LIFE_DURATION ); INITPARTICLE_ATTRIBUTE( PREV_XYZ ); INITPARTICLE_ATTRIBUTE( RADIUS ); INITPARTICLE_ATTRIBUTE( ROTATION ); INITPARTICLE_ATTRIBUTE( ROTATION_SPEED ); INITPARTICLE_ATTRIBUTE( TINT_RGB ); INITPARTICLE_ATTRIBUTE( ALPHA ); INITPARTICLE_ATTRIBUTE( CREATION_TIME ); INITPARTICLE_ATTRIBUTE( SEQUENCE_NUMBER ); INITPARTICLE_ATTRIBUTE( TRAIL_LENGTH ); INITPARTICLE_ATTRIBUTE( PARTICLE_ID ); INITPARTICLE_ATTRIBUTE( YAW ); INITPARTICLE_ATTRIBUTE( SEQUENCE_NUMBER1 ); INITPARTICLE_ATTRIBUTE( HITBOX_INDEX ); INITPARTICLE_ATTRIBUTE( HITBOX_RELATIVE_XYZ ); INITPARTICLE_ATTRIBUTE( ALPHA2 ); INITPARTICLE_ATTRIBUTE( SCRATCH_VEC ); INITPARTICLE_ATTRIBUTE( SCRATCH_FLOAT ); INITPARTICLE_ATTRIBUTE( UNUSED ); INITPARTICLE_ATTRIBUTE( PITCH ); INITPARTICLE_ATTRIBUTE( NORMAL ); INITPARTICLE_ATTRIBUTE( GLOW_RGB ); INITPARTICLE_ATTRIBUTE( GLOW_ALPHA ); for ( int i = 0; i < MAX_PARTICLE_ATTRIBUTES; i++ ) { if ( !s_AttributeTable[ i ].pName ) { // The above list of initializers needs updating! Warning( "CParticleSystemMgr::InitAttributeTable has an out-of-date attribute list! (element %d not set up)\n", i ); Assert( 0 ); } } } //---------------------------------------------------------------------------------- // String -> Attribute mapping //---------------------------------------------------------------------------------- int CParticleSystemMgr::GetParticleAttributeByName( const char *pName ) const { // TODO: OPTIMIZATION: use Chris's CUtlStringToken class here to speed this up for ( int i = 0; i < MAX_PARTICLE_ATTRIBUTES; i++ ) { if ( !Q_stricmp( pName, s_AttributeTable[ i ].pName ) ) return i; } return -1; } //---------------------------------------------------------------------------------- // Attribute -> String mapping //---------------------------------------------------------------------------------- const char *CParticleSystemMgr::GetParticleAttributeName( int nAttribute ) const { if ( ( nAttribute < 0 ) || ( nAttribute >= MAX_PARTICLE_ATTRIBUTES ) ) { Assert( 0 ); return "unknown"; } return s_AttributeTable[ nAttribute ].pName; } //---------------------------------------------------------------------------------- // Get the data type of a given attribute //---------------------------------------------------------------------------------- EAttributeDataType CParticleSystemMgr::GetParticleAttributeDataType( int nAttribute ) const { Assert( nAttribute >= 0 ); Assert( nAttribute < MAX_PARTICLE_ATTRIBUTES ); return s_AttributeTable[ nAttribute ].nDataType; } //---------------------------------------------------------------------------------- // Cache/uncache materials used by particle systems //---------------------------------------------------------------------------------- void CParticleSystemMgr::PrecacheParticleSystem( int nStringNumber, const char *pName ) { if ( !pName || !pName[0] ) { return; } ParticleSystemHandle_t hParticleSystem = GetParticleSystemIndex( pName ); // Used to display an error system if the requested one isn't known from the manifest if ( hParticleSystem == UTL_INVAL_SYMBOL ) { Warning( "Attempted to precache unknown particle system \"%s\"!\n", pName ); hParticleSystem = GetParticleSystemIndex( "error" ); } CParticleSystemDefinition* pDef = FindParticleSystem( hParticleSystem ); CUtlVector< ParticleSystemHandle_t > &lookup = ( nStringNumber >= 0 ) ? m_PrecacheLookup : m_ClientPrecacheLookup; if ( nStringNumber < 0 ) { nStringNumber = - nStringNumber - 1; } int nCountToAdd = nStringNumber + 1 - lookup.Count(); for ( int i = 0; i < nCountToAdd; ++i ) { lookup.AddToTail( UTL_INVAL_SYMBOL ); } lookup[ nStringNumber ] = hParticleSystem; if ( !pDef ) { Warning( "Attempted to precache unknown particle system \"%s\"!\n", pName ); return; } pDef->Precache(); } void CParticleSystemMgr::LevelShutdown( void ) { #ifndef SERVER_PARTICLE_LIB // InvalidateGlobalCollisionCache(); // keep the collision cahce out of the server binary for now #endif } void CParticleSystemMgr::UncacheAllParticleSystems() { m_PrecacheLookup.RemoveAll(); m_ClientPrecacheLookup.RemoveAll(); if ( m_pParticleSystemDictionary ) { int nCount = m_pParticleSystemDictionary->Count(); for ( int i = 0; i < nCount; ++i ) { m_pParticleSystemDictionary->GetParticleSystem( i )->Uncache(); } nCount = m_pParticleSystemDictionary->NameCount(); for ( ParticleSystemHandle_t h = 0; h < nCount; ++h ) { m_pParticleSystemDictionary->FindParticleSystem( h )->Uncache(); } } // Flush sheets, as they can accumulate several MB of memory per map FlushAllSheets(); } //----------------------------------------------------------------------------- // return the particle field name //----------------------------------------------------------------------------- static const char *s_pParticleFieldNames[MAX_PARTICLE_ATTRIBUTES] = { "Position", // XYZ, 0 "Life Duration", // LIFE_DURATION, 1 ); "Position Previous",// PREV_XYZ "Radius", // RADIUS, 3 ); "Roll", // ROTATION, 4 ); "Roll Speed", // ROTATION_SPEED, 5 ); "Color", // TINT_RGB, 6 ); "Alpha", // ALPHA, 7 ); "Creation Time", // CREATION_TIME, 8 ); "Sequence Number", // SEQUENCE_NUMBER, 9 ); "Trail Length", // TRAIL_LENGTH, 10 ); "Particle ID", // PARTICLE_ID, 11 ); "Yaw", // YAW, 12 ); "Sequence Number 1",// SEQUENCE_NUMBER1, 13 ); "Hitbox Index", // HITBOX_INDEX, 14 "Hitbox Offset Position", // HITBOX_XYZ_RELATIVE 15 "Alpha Alternate", // ALPHA2, 16 "Scratch Vector", // SCRATCH_VEC 17 "Scratch Float", // SCRATCH_FLOAT 18 NULL, "Pitch", // PITCH, 20 "Normal", // NORMAL, 21 "Glow RGB", //GLOW_RGB,22 "Glow Alpha", //GLOW_ALPHA,23 }; const char* CParticleSystemMgr::GetParticleFieldName( int nParticleField ) const { return s_pParticleFieldNames[nParticleField]; } //----------------------------------------------------------------------------- // Returns the available particle operators //----------------------------------------------------------------------------- void CParticleSystemMgr::AddParticleOperator( ParticleFunctionType_t nOpType, IParticleOperatorDefinition *pOpFactory ) { m_ParticleOperators[nOpType].AddToTail( pOpFactory ); } static const char *s_pFilterNames[ ] = { "All", "Position and Velocity", "Life Duration", "Parameter Remapping", "Rotation", "Size", "Color and Opacity", "Animation Sequence", "Hitbox", "Normal", "Control Points" }; const char *CParticleSystemMgr::GetFilterName( ParticleFilterType_t nFilterType ) const { COMPILE_TIME_ASSERT( ARRAYSIZE( s_pFilterNames ) == FILTER_COUNT ); return s_pFilterNames[nFilterType]; } CUtlVector< IParticleOperatorDefinition *> &CParticleSystemMgr::GetAvailableParticleOperatorList( ParticleFunctionType_t nWhichList ) { return m_ParticleOperators[nWhichList]; } const DmxElementUnpackStructure_t *CParticleSystemMgr::GetParticleSystemDefinitionUnpackStructure() { return s_pParticleSystemDefinitionUnpack; } //------------------------------------------------------------------------------ // custom allocators for operators so simd aligned //------------------------------------------------------------------------------ #include "tier0/memdbgoff.h" void *CParticleOperatorInstance::operator new( size_t nSize ) { return MemAlloc_AllocAligned( nSize, 16 ); } void* CParticleOperatorInstance::operator new( size_t nSize, int nBlockUse, const char *pFileName, int nLine ) { return MemAlloc_AllocAlignedFileLine( nSize, 16, pFileName, nLine ); } void CParticleOperatorInstance::operator delete(void *pData) { if ( pData ) { MemAlloc_FreeAligned( pData ); } } void CParticleOperatorInstance::operator delete( void* pData, int nBlockUse, const char *pFileName, int nLine ) { if ( pData ) { MemAlloc_FreeAligned( pData ); } } #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // Load a PCF file and list the particle systems in it //----------------------------------------------------------------------------- void CParticleSystemMgr::GetParticleSystemsInFile( const char *pFileName, CUtlVector< CUtlString > *pOutSystemNameList ) { if( pOutSystemNameList == NULL ) return; pOutSystemNameList->RemoveAll(); CUtlBuffer buf; if ( !g_pFullFileSystem->ReadFile( pFileName, "GAME", buf ) ) { return; } GetParticleSystemsInBuffer( buf, pOutSystemNameList ); } void CParticleSystemMgr::GetParticleSystemsInBuffer( CUtlBuffer &buf, CUtlVector<CUtlString> *pOutSystemNameList ) { if( pOutSystemNameList == NULL ) return; pOutSystemNameList->RemoveAll(); DECLARE_DMX_CONTEXT( ); CDmxElement *pRoot; if ( !UnserializeDMX( buf, &pRoot ) ) { return; } if ( !Q_stricmp( pRoot->GetTypeString(), "DmeParticleSystemDefinition" ) ) { pOutSystemNameList->AddToTail( pRoot->GetName() ); CleanupDMX( pRoot ); return; } const CDmxAttribute *pDefinitions = pRoot->GetAttribute( "particleSystemDefinitions" ); if ( !pDefinitions || pDefinitions->GetType() != AT_ELEMENT_ARRAY ) { CleanupDMX( pRoot ); return; } const CUtlVector< CDmxElement* >& definitions = pDefinitions->GetArray<CDmxElement*>( ); int nCount = definitions.Count(); for ( int i = 0; i < nCount; ++i ) { pOutSystemNameList->AddToTail( definitions[i]->GetName() ); } CleanupDMX( pRoot ); } //----------------------------------------------------------------------------- // Read the particle config file from a utlbuffer //----------------------------------------------------------------------------- bool CParticleSystemMgr::ReadParticleDefinitions( CUtlBuffer &buf, const char *pFileName, bool bPrecache, bool bDecommitTempMemory ) { DECLARE_DMX_CONTEXT_DECOMMIT( bDecommitTempMemory ); CDmxElement *pRoot; if ( !UnserializeDMX( buf, &pRoot, pFileName ) ) { Warning( "Unable to read particle definition %s! UtlBuffer is probably the wrong type!\n", pFileName ); return false; } if ( !Q_stricmp( pRoot->GetTypeString(), "DmeParticleSystemDefinition" ) ) { CParticleSystemDefinition *pDef = m_pParticleSystemDictionary->AddParticleSystem( pRoot ); if ( pDef && bPrecache ) { pDef->m_bAlwaysPrecache = true; if ( m_bAllowPrecache ) { pDef->Precache(); } } CleanupDMX( pRoot ); return true; } const CDmxAttribute *pDefinitions = pRoot->GetAttribute( "particleSystemDefinitions" ); if ( !pDefinitions || pDefinitions->GetType() != AT_ELEMENT_ARRAY ) { CleanupDMX( pRoot ); return false; } const CUtlVector< CDmxElement* >& definitions = pDefinitions->GetArray<CDmxElement*>( ); int nCount = definitions.Count(); for ( int i = 0; i < nCount; ++i ) { CParticleSystemDefinition *pDef = m_pParticleSystemDictionary->AddParticleSystem( definitions[i] ); if ( pDef && bPrecache ) { pDef->m_bAlwaysPrecache = true; if ( m_bAllowPrecache ) { pDef->Precache(); } } } CleanupDMX( pRoot ); return true; } //----------------------------------------------------------------------------- // Decommits temporary memory //----------------------------------------------------------------------------- void CParticleSystemMgr::DecommitTempMemory() { DecommitDMXMemory(); } //----------------------------------------------------------------------------- // Sets the last simulation time, used for particle system sleeping logic //----------------------------------------------------------------------------- void CParticleSystemMgr::SetLastSimulationTime( float flTime ) { m_flLastSimulationTime = flTime; } float CParticleSystemMgr::GetLastSimulationTime() const { return m_flLastSimulationTime; } //----------------------------------------------------------------------------- // Sets the last simulation duration ( the amount of time we spent simulating particle ) last frame // Used to fallback to cheaper particle systems under load //----------------------------------------------------------------------------- void CParticleSystemMgr::SetLastSimulationDuration( float flDuration ) { m_flLastSimulationDuration = flDuration; } float CParticleSystemMgr::GetLastSimulationDuration() const { return m_flLastSimulationDuration; } //----------------------------------------------------------------------------- // GPU/CPU Level //----------------------------------------------------------------------------- void CParticleSystemMgr::SetSystemLevel( int nCPULevel, int nGPULevel ) { m_nCPULevel = nCPULevel; m_nGPULevel = nGPULevel; } int CParticleSystemMgr::GetParticleCPULevel() const { return m_nCPULevel; } int CParticleSystemMgr::GetParticleGPULevel() const { return m_nGPULevel; } //----------------------------------------------------------------------------- // Fallback paramters //----------------------------------------------------------------------------- void CParticleSystemMgr::SetFallbackParameters( float flBase, float flMultiplier, float flSimFallbackBaseMultiplier, float flSimThresholdMs ) { m_flFallbackBase = flBase; m_flFallbackMultiplier = flMultiplier; m_flSimFallbackBaseMultiplier = flSimFallbackBaseMultiplier; m_flSimThresholdMs = flSimThresholdMs; } float CParticleSystemMgr::GetFallbackBase() const { return m_flFallbackBase; } float CParticleSystemMgr::GetFallbackMultiplier() const { return m_flFallbackMultiplier; } float CParticleSystemMgr::GetSimFallbackThresholdMs() const { return m_flSimThresholdMs; } float CParticleSystemMgr::GetSimFallbackBaseMultiplier() const { return m_flSimFallbackBaseMultiplier; } //----------------------------------------------------------------------------- // Unserialization-related methods //----------------------------------------------------------------------------- void CParticleSystemMgr::AddParticleSystem( CDmxElement *pParticleSystem ) { m_pParticleSystemDictionary->AddParticleSystem( pParticleSystem ); } CParticleSystemDefinition* CParticleSystemMgr::FindParticleSystem( const char *pName ) { return m_pParticleSystemDictionary->FindParticleSystem( pName ); } CParticleSystemDefinition* CParticleSystemMgr::FindParticleSystem( const DmObjectId_t& id ) { return m_pParticleSystemDictionary->FindParticleSystem( id ); } CParticleSystemDefinition* CParticleSystemMgr::FindParticleSystem( ParticleSystemHandle_t hParticleSystem ) { return m_pParticleSystemDictionary->FindParticleSystem( hParticleSystem ); } CParticleSystemDefinition* CParticleSystemMgr::FindPrecachedParticleSystem( int nPrecacheIndex ) { CUtlVector< ParticleSystemHandle_t > &lookup = ( nPrecacheIndex >= 0 ) ? m_PrecacheLookup : m_ClientPrecacheLookup; if ( nPrecacheIndex < 0 ) { nPrecacheIndex = - nPrecacheIndex - 1; } if ( nPrecacheIndex >= lookup.Count() ) return NULL; return FindParticleSystem( lookup[nPrecacheIndex] ); } //----------------------------------------------------------------------------- // Read the particle config file from a utlbuffer //----------------------------------------------------------------------------- bool CParticleSystemMgr::ReadParticleConfigFile( CUtlBuffer &buf, bool bPrecache, bool bDecommitTempMemory, const char *pFileName ) { return ReadParticleDefinitions( buf, pFileName, bPrecache, bDecommitTempMemory ); } //----------------------------------------------------------------------------- // Read the particle config file from a utlbuffer //----------------------------------------------------------------------------- bool CParticleSystemMgr::ReadParticleConfigFile( const char *pFileName, bool bPrecache, bool bDecommitTempMemory ) { // Names starting with a '!' are always precached. if ( pFileName[0] == '!' ) { bPrecache = true; ++pFileName; } if ( PLATFORM_EXT[0] ) { char szTargetName[MAX_PATH]; CreatePlatformFilename( pFileName, szTargetName, sizeof( szTargetName ) ); CUtlBuffer fileBuffer; bool bHaveParticles = g_pFullFileSystem->ReadFile( szTargetName, "GAME", fileBuffer ); if ( bHaveParticles ) { fileBuffer.SetBigEndian( false ); return ReadParticleConfigFile( fileBuffer, bPrecache, bDecommitTempMemory, szTargetName ); } else { // 360/PS3 version should have been there, 360/PS3 zips can only have binary particles Warning( "Particles: Missing '%s'\n", szTargetName ); return false; } } // char pFallbackBuf[MAX_PATH]; if ( IsPC() ) { // Look for fallback particle systems char pTemp[MAX_PATH]; Q_StripExtension( pFileName, pTemp, sizeof(pTemp) ); const char *pExt = Q_GetFileExtension( pFileName ); if ( !pExt ) { pExt = "pcf"; } /* // FIXME: Hook GPU level and/or CPU level into fallbacks instead of dxsupport level if ( g_pMaterialSystemHardwareConfig->GetDXSupportLevel() < 90 ) { Q_snprintf( pFallbackBuf, sizeof(pFallbackBuf), "%s_dx80.%s", pTemp, pExt ); if ( g_pFullFileSystem->FileExists( pFallbackBuf ) ) { pFileName = pFallbackBuf; } } else if ( g_pMaterialSystemHardwareConfig->GetDXSupportLevel() == 90 && g_pMaterialSystemHardwareConfig->PreferReducedFillrate() ) { Q_snprintf( pFallbackBuf, sizeof(pFallbackBuf), "%s_dx90_slow.%s", pTemp, pExt ); if ( g_pFullFileSystem->FileExists( pFallbackBuf ) ) { pFileName = pFallbackBuf; } } */ } CUtlBuffer buf( 0, 0, 0 ); if ( IsX360() || IsPS3() ) { // fell through, load as pc particle resource file buf.ActivateByteSwapping( true ); } if ( g_pFullFileSystem->ReadFile( pFileName, "GAME", buf ) ) { return ReadParticleConfigFile( buf, bPrecache, bDecommitTempMemory, pFileName ); } Warning( "Particles: Missing '%s'\n", pFileName ); return false; } //----------------------------------------------------------------------------- // Write a specific particle config to a utlbuffer //----------------------------------------------------------------------------- bool CParticleSystemMgr::WriteParticleConfigFile( const char *pParticleSystemName, CUtlBuffer &buf, bool bPreventNameBasedLookup ) { DECLARE_DMX_CONTEXT(); // Create DMX elements representing the particle system definition CDmxElement *pParticleSystem = CreateParticleDmxElement( pParticleSystemName ); return WriteParticleConfigFile( pParticleSystem, buf, bPreventNameBasedLookup ); } bool CParticleSystemMgr::WriteParticleConfigFile( const DmObjectId_t& id, CUtlBuffer &buf, bool bPreventNameBasedLookup ) { DECLARE_DMX_CONTEXT(); // Create DMX elements representing the particle system definition CDmxElement *pParticleSystem = CreateParticleDmxElement( id ); return WriteParticleConfigFile( pParticleSystem, buf, bPreventNameBasedLookup ); } bool CParticleSystemMgr::WriteParticleConfigFile( CDmxElement *pParticleSystem, CUtlBuffer &buf, bool bPreventNameBasedLookup ) { pParticleSystem->SetValue( "preventNameBasedLookup", bPreventNameBasedLookup ); CDmxAttribute* pAttribute = pParticleSystem->GetAttribute( "children" ); const CUtlVector< CDmxElement* >& children = pAttribute->GetArray<CDmxElement*>( ); int nCount = children.Count(); for ( int i = 0; i < nCount; ++i ) { CDmxElement *pChildRef = children[ i ]; CDmxElement *pChild = pChildRef->GetValue<CDmxElement*>( "child" ); pChild->SetValue( "preventNameBasedLookup", bPreventNameBasedLookup ); } // Now write the DMX elements out bool bOk = SerializeDMX( buf, pParticleSystem ); CleanupDMX( pParticleSystem ); return bOk; } ParticleSystemHandle_t CParticleSystemMgr::GetParticleSystemIndex( const char *pParticleSystemName ) { if ( !pParticleSystemName ) return UTL_INVAL_SYMBOL; return m_pParticleSystemDictionary->FindParticleSystemHandle( pParticleSystemName ); } ParticleSystemHandle_t CParticleSystemMgr::FindOrAddParticleSystemIndex( const char *pParticleSystemName ) { if ( !pParticleSystemName ) return UTL_INVAL_SYMBOL; return m_pParticleSystemDictionary->FindOrAddParticleSystemHandle( pParticleSystemName ); } const char *CParticleSystemMgr::GetParticleSystemNameFromIndex( ParticleSystemHandle_t iIndex ) { CParticleSystemDefinition *pDef = m_pParticleSystemDictionary->FindParticleSystem( iIndex ); return pDef ? pDef->GetName() : "Unknown"; } int CParticleSystemMgr::GetParticleSystemCount( void ) { return m_pParticleSystemDictionary->NameCount(); } //----------------------------------------------------------------------------- // Factory method for creating particle collections //----------------------------------------------------------------------------- CParticleCollection *CParticleSystemMgr::CreateParticleCollection( const char *pParticleSystemName, float flDelay, int nRandomSeed ) { if ( !pParticleSystemName ) return NULL; CParticleSystemDefinition *pDef = m_pParticleSystemDictionary->FindParticleSystem( pParticleSystemName ); if ( !pDef ) { Warning( "Attempted to create unknown particle system type %s\n", pParticleSystemName ); return NULL; } CParticleCollection *pParticleCollection = new CParticleCollection; pParticleCollection->Init( pDef, flDelay, nRandomSeed ); return pParticleCollection; } CParticleCollection *CParticleSystemMgr::CreateParticleCollection( ParticleSystemHandle_t particleSystemName, float flDelay, int nRandomSeed ) { if ( particleSystemName == UTL_INVAL_SYMBOL ) return NULL; CParticleSystemDefinition *pDef = m_pParticleSystemDictionary->FindParticleSystem( particleSystemName ); if ( !pDef ) { Warning( "Attempted to create unknown particle system with unknown symbol\n" ); return NULL; } CParticleCollection *pParticleCollection = new CParticleCollection; pParticleCollection->Init( pDef, flDelay, nRandomSeed ); return pParticleCollection; } CParticleCollection *CParticleSystemMgr::CreateParticleCollection( const DmObjectId_t &id, float flDelay, int nRandomSeed ) { if ( !IsUniqueIdValid( id ) ) return NULL; CParticleSystemDefinition *pDef = m_pParticleSystemDictionary->FindParticleSystem( id ); if ( !pDef ) { char pBuf[256]; UniqueIdToString( id, pBuf, sizeof(pBuf) ); Warning( "Attempted to create unknown particle system id %s\n", pBuf ); return NULL; } CParticleCollection *pParticleCollection = new CParticleCollection; pParticleCollection->Init( pDef, flDelay, nRandomSeed ); return pParticleCollection; } //-------------------------------------------------------------------------------- // Is a particular particle system defined? //-------------------------------------------------------------------------------- bool CParticleSystemMgr::IsParticleSystemDefined( const DmObjectId_t &id ) { if ( !IsUniqueIdValid( id ) ) return false; CParticleSystemDefinition *pDef = m_pParticleSystemDictionary->FindParticleSystem( id ); return ( pDef != NULL ); } //-------------------------------------------------------------------------------- // Is a particular particle system defined? //-------------------------------------------------------------------------------- bool CParticleSystemMgr::IsParticleSystemDefined( const char *pName ) { if ( !pName || !pName[0] ) return false; CParticleSystemDefinition *pDef = m_pParticleSystemDictionary->FindParticleSystem( pName ); return ( pDef != NULL ); } //-------------------------------------------------------------------------------- // Particle kill list //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // Serialization-related methods //-------------------------------------------------------------------------------- CDmxElement *CParticleSystemMgr::CreateParticleDmxElement( const DmObjectId_t &id ) { CParticleSystemDefinition *pDef = m_pParticleSystemDictionary->FindParticleSystem( id ); // Create DMX elements representing the particle system definition return pDef->Write( ); } CDmxElement *CParticleSystemMgr::CreateParticleDmxElement( const char *pParticleSystemName ) { CParticleSystemDefinition *pDef = m_pParticleSystemDictionary->FindParticleSystem( pParticleSystemName ); // Create DMX elements representing the particle system definition return pDef->Write( ); } //-------------------------------------------------------------------------------- // Particle sheets //-------------------------------------------------------------------------------- static unsigned int s_nBaseTextureVarCache = 0; CSheet *CParticleSystemMgr::FindOrLoadSheet( CParticleSystemDefinition *pDef, bool bTryReloading ) { if ( !m_bShouldLoadSheets ) return NULL; if ( !bTryReloading ) { if ( pDef->IsSheetSymbolCached() ) { if ( !pDef->GetSheetSymbol().IsValid() ) return NULL; return m_SheetList[ pDef->GetSheetSymbol() ]; } pDef->CacheSheetSymbol( UTL_INVAL_SYMBOL ); } IMaterial *pMaterial = pDef->GetMaterial(); if ( !pMaterial ) return NULL; IMaterialVar *pVar = pMaterial->FindVarFast( "$basetexture", &s_nBaseTextureVarCache ); if ( !pVar || !pVar->IsDefined() ) return NULL; ITexture *pTex = pVar->GetTextureValue(); if ( !pTex || pTex->IsError() ) return NULL; CSheet *pNewSheet = NULL; int nCurCount = m_SheetList.GetNumStrings(); CUtlSymbol sheetName = m_SheetList.AddString( pTex->GetName() ); if ( ( sheetName < nCurCount ) && ( !bTryReloading ) ) { // Means the string was already known pNewSheet = m_SheetList[ sheetName ]; } else { // get compact sheet representation held by texture size_t numBytes; void const *pSheetData = pTex->GetResourceData( VTF_RSRC_SHEET, &numBytes ); if ( pSheetData ) { // expand compact sheet into fatter runtime form CUtlBuffer bufLoad( pSheetData, numBytes, CUtlBuffer::READ_ONLY ); pNewSheet = new CSheet( bufLoad ); } m_SheetList[ sheetName ] = pNewSheet; } pDef->CacheSheetSymbol( sheetName ); return pNewSheet; } void CParticleSystemMgr::FlushAllSheets( void ) { m_SheetList.PurgeAndDeleteElements(); if ( !m_pParticleSystemDictionary ) return; int nCount = m_pParticleSystemDictionary->Count(); for ( int i = 0; i < nCount; ++i ) { CParticleSystemDefinition* pDef = m_pParticleSystemDictionary->GetParticleSystem( i ); pDef->InvalidateSheetSymbol(); } nCount = m_pParticleSystemDictionary->NameCount(); for ( ParticleSystemHandle_t h = 0; h < nCount; ++h ) { CParticleSystemDefinition* pDef = m_pParticleSystemDictionary->FindParticleSystem( h ); pDef->InvalidateSheetSymbol(); } } void CParticleSystemMgr::ShouldLoadSheets( bool bLoadSheets ) { // Client loads sheets for rendering, server doesn't need to. m_bShouldLoadSheets = bLoadSheets; } //----------------------------------------------------------------------------- // Render cache //----------------------------------------------------------------------------- void CParticleSystemMgr::ResetRenderCache( void ) { int nCount = m_RenderCache.Count(); for ( int i = 0; i < nCount; ++i ) { m_RenderCache[i].m_ParticleCollections.RemoveAll(); } } void CParticleSystemMgr::AddToRenderCache( CParticleCollection *pParticles ) { if ( !pParticles->IsValid() ) return; IMaterial *pMaterial = pParticles->m_pDef->GetMaterial(); if ( ( !pMaterial) || pMaterial->IsTranslucent() ) return; pParticles->m_flNextSleepTime = MAX( pParticles->m_flNextSleepTime, ( g_pParticleSystemMgr->GetLastSimulationTime() + pParticles->m_pDef->m_flNoDrawTimeToGoToSleep )); // Find the current rope list. int iRenderCache = 0; int nRenderCacheCount = m_RenderCache.Count(); for ( ; iRenderCache < nRenderCacheCount; ++iRenderCache ) { if ( ( pParticles->m_pDef->GetMaterial() == m_RenderCache[iRenderCache].m_pMaterial ) ) break; } // A full rope list should have been generate in CreateRenderCache // If we didn't find one, then allocate the mofo. if ( iRenderCache == nRenderCacheCount ) { iRenderCache = m_RenderCache.AddToTail(); m_RenderCache[iRenderCache].m_pMaterial = pParticles->m_pDef->GetMaterial(); } m_RenderCache[iRenderCache].m_ParticleCollections.AddToTail( pParticles ); for( CParticleCollection *p = pParticles->m_Children.m_pHead; p; p = p->m_pNext ) { AddToRenderCache( p ); } } void CParticleSystemMgr::BuildBatchList( int iRenderCache, IMatRenderContext *pRenderContext, CUtlVector< Batch_t >& batches ) { batches.RemoveAll(); IMaterial *pMaterial = m_RenderCache[iRenderCache].m_pMaterial; int nMaxVertices = pRenderContext->GetMaxVerticesToRender( pMaterial ); int nMaxIndices = pRenderContext->GetMaxIndicesToRender(); int nRemainingVertices = nMaxVertices; int nRemainingIndices = nMaxIndices; int i = batches.AddToTail(); Batch_t* pBatch = &batches[i]; pBatch->m_nVertCount = 0; pBatch->m_nIndexCount = 0; // Ask each renderer about the # of verts + ints it will draw int nCacheCount = m_RenderCache[iRenderCache].m_ParticleCollections.Count(); for ( int iCache = 0; iCache < nCacheCount; ++iCache ) { CParticleCollection *pParticles = m_RenderCache[iRenderCache].m_ParticleCollections[iCache]; if ( !pParticles->IsValid() ) continue; int nRenderCount = pParticles->GetRendererCount(); for ( int j = 0; j < nRenderCount; ++j ) { int nFirstParticle = 0; while ( nFirstParticle < pParticles->m_nActiveParticles ) { int i; BatchStep_t step; step.m_pParticles = pParticles; step.m_pRenderer = pParticles->GetRenderer( j ); step.m_pContext = pParticles->GetRendererContext( j ); step.m_nFirstParticle = nFirstParticle; step.m_nParticleCount = step.m_pRenderer->GetParticlesToRender( pParticles, step.m_pContext, nFirstParticle, nRemainingVertices, nRemainingIndices, &step.m_nVertCount, &i ); nFirstParticle += step.m_nParticleCount; if ( step.m_nParticleCount > 0 ) { pBatch->m_nVertCount += step.m_nVertCount; pBatch->m_nIndexCount += i; pBatch->m_BatchStep.AddToTail( step ); Assert( pBatch->m_nVertCount <= nMaxVertices && pBatch->m_nIndexCount <= nMaxIndices ); } else { if ( pBatch->m_nVertCount == 0 ) break; // Not enough room Assert( pBatch->m_nVertCount > 0 && pBatch->m_nIndexCount > 0 ); int j = batches.AddToTail(); pBatch = &batches[j]; pBatch->m_nVertCount = 0; pBatch->m_nIndexCount = 0; nRemainingVertices = nMaxVertices; nRemainingIndices = nMaxIndices; } } } } if ( pBatch->m_nVertCount <= 0 || pBatch->m_nIndexCount <= 0 ) { batches.FastRemove( batches.Count() - 1 ); } } void CParticleSystemMgr::DumpParticleList( const char *pNameSubstring /* = NULL */ ) { if ( pNameSubstring ) { DevMsg( "New Particle Systems Matching '%s':\n", pNameSubstring ); } else { DevMsg( "All Particle Systems:\n" ); } for ( int i = 0; i < m_pParticleSystemDictionary->NameCount(); i++ ) { CParticleSystemDefinition *p = ( *m_pParticleSystemDictionary )[ i ]; if ( !pNameSubstring || V_stristr(p->GetName(),pNameSubstring) ) { for ( CParticleCollection *c = p->FirstCollection(); c; c = c->GetNextCollectionUsingSameDef() ) { Vector min,max,center; c->GetBounds( &min, &max ); center = (min+max)*0.5f; DevMsg( "%40s: Age: %6.2f, NumActive: %3d, Bounds Center: (%.2f,%.2f,%.2f) (0x%p)\n", p->GetName(), c->m_flCurTime, c->m_nActiveParticles, center.x, center.y, center.z, c ); } } } } void CParticleSystemMgr::DumpProfileInformation( void ) { #if MEASURE_PARTICLE_PERF int nTotalTests = 0; int nActualTests = 0; FileHandle_t fh = g_pFullFileSystem->Open( "particle_profile.csv", "w", "DEFAULT_WRITE_PATH" ); if ( fh == FILESYSTEM_INVALID_HANDLE ) { Warning( "*** Unable to open profile file!\n" ); return; } g_pFullFileSystem->FPrintf( fh, "numframes,%d\n", m_nNumFramesMeasured ); g_pFullFileSystem->FPrintf( fh, "name, total time, max time, max particles, allocated particles, total render time, max render time, number of intersection tests, number of actual traces\n"); for( int i=0; i < m_pParticleSystemDictionary->NameCount(); i++ ) { CParticleSystemDefinition *p = ( *m_pParticleSystemDictionary )[ i ]; if ( p->m_nMaximumActiveParticles ) { nTotalTests += p->m_nNumIntersectionTests; nActualTests +=p->m_nNumActualRayTraces; g_pFullFileSystem->FPrintf( fh, "%s,%f,%f,%d,%d,%f,%f,%d,%d\n", p->m_Name.Get(), p->m_flTotalSimTime, p->m_flMaxMeasuredSimTime, p->m_nMaximumActiveParticles, p->m_nMaxParticles, p->m_flTotalRenderTime, p->m_flMaxMeasuredRenderTime, p->m_nNumIntersectionTests(), p->m_nNumActualRayTraces() ); } } if ( nTotalTests ) { g_pFullFileSystem->FPrintf( fh, "\n\nTrace cache efficiency = %f%%\n\n", 100.0 * ( 1.0 - ( nActualTests * ( 1.0 / nTotalTests ) ) ) ); } g_pFullFileSystem->FPrintf( fh, "\n\nopname, total time, max time, total render time, max render time\n"); for(int i=0; i < ARRAYSIZE( m_ParticleOperators ); i++) { for(int j=0; j < m_ParticleOperators[i].Count() ; j++ ) { float flmax = m_ParticleOperators[i][j]->MaximumRecordedExecutionTime(); float fltotal = m_ParticleOperators[i][j]->TotalRecordedExecutionTime(); if ( fltotal > 0.0 ) { g_pFullFileSystem->FPrintf( fh, "%s,%f,%f\n", m_ParticleOperators[i][j]->GetName(), fltotal, flmax ); } } } g_pFullFileSystem->Close( fh ); #endif } void CParticleSystemMgr::CommitProfileInformation( bool bCommit ) { #if MEASURE_PARTICLE_PERF if ( 1 ) { if ( bCommit ) { m_nNumFramesMeasured++; } for( int i=0; i < m_pParticleSystemDictionary->NameCount(); i++ ) { CParticleSystemDefinition *p = ( *m_pParticleSystemDictionary )[ i ]; if ( bCommit ) { p->m_flTotalSimTime += p->m_flUncomittedTotalSimTime; p->m_flTotalRenderTime += p->m_flUncomittedTotalRenderTime; } p->m_flUncomittedTotalSimTime = 0.; p->m_flUncomittedTotalRenderTime = 0.; } for(int i=0; i < ARRAYSIZE( m_ParticleOperators ); i++) { for(int j=0; j < m_ParticleOperators[i].Count() ; j++ ) { if ( bCommit ) { m_ParticleOperators[i][j]->m_flTotalExecutionTime += m_ParticleOperators[i][j]->m_flUncomittedTime; } m_ParticleOperators[i][j]->m_flUncomittedTime = 0; } } } #endif } void CParticleSystemMgr::DrawRenderCache( IMatRenderContext *pRenderContext, bool bShadowDepth ) { int nRenderCacheCount = m_RenderCache.Count(); if ( nRenderCacheCount == 0 ) return; VPROF_BUDGET( "CParticleSystemMgr::DrawRenderCache", VPROF_BUDGETGROUP_PARTICLE_RENDERING ); pRenderContext->MatrixMode( MATERIAL_MODEL ); pRenderContext->PushMatrix(); pRenderContext->LoadIdentity(); CUtlVector< Batch_t > batches( 0, 8 ); for ( int iRenderCache = 0; iRenderCache < nRenderCacheCount; ++iRenderCache ) { int nCacheCount = m_RenderCache[iRenderCache].m_ParticleCollections.Count(); if ( nCacheCount == 0 ) continue; // FIXME: When rendering shadow depth, do it all in 1 batch IMaterial *pMaterial = bShadowDepth ? m_pShadowDepthMaterial : m_RenderCache[iRenderCache].m_pMaterial; BuildBatchList( iRenderCache, pRenderContext, batches ); int nBatchCount = batches.Count(); if ( nBatchCount == 0 ) continue; pRenderContext->Bind( pMaterial ); CMeshBuilder meshBuilder; IMesh* pMesh = pRenderContext->GetDynamicMesh( ); for ( int i = 0; i < nBatchCount; ++i ) { const Batch_t& batch = batches[i]; Assert( batch.m_nVertCount > 0 && batch.m_nIndexCount > 0 ); meshBuilder.Begin( pMesh, MATERIAL_TRIANGLES, batch.m_nVertCount, batch.m_nIndexCount ); int nVertexOffset = 0; int nBatchStepCount = batch.m_BatchStep.Count(); for ( int j = 0; j < nBatchStepCount; ++j ) { const BatchStep_t &step = batch.m_BatchStep[j]; // FIXME: this will break if it ever calls into C_OP_RenderSprites::Render[TwoSequence]SpriteCard() // (need to protect against that and/or split the meshBuilder batch to support that path here) step.m_pRenderer->RenderUnsorted( step.m_pParticles, step.m_pContext, pRenderContext, meshBuilder, nVertexOffset, step.m_nFirstParticle, step.m_nParticleCount ); nVertexOffset += step.m_nVertCount; } meshBuilder.End(); pMesh->Draw(); } } ResetRenderCache( ); pRenderContext->MatrixMode( MATERIAL_MODEL ); pRenderContext->PopMatrix(); } void IParticleSystemQuery::GetRandomPointsOnControllingObjectHitBox( CParticleCollection *pParticles, int nControlPointNumber, int nNumPtsOut, float flBBoxScale, int nNumTrysToGetAPointInsideTheModel, Vector *pPntsOut, Vector vecDirectionalBias, Vector *pHitBoxRelativeCoordOut, int *pHitBoxIndexOut, int nDesiredHitbox, const char *pszHitboxSetName ) { for(int i=0; i < nNumPtsOut; i++) { pPntsOut[i]=pParticles->ControlPoint( nControlPointNumber ).m_Position; if ( pHitBoxRelativeCoordOut ) pHitBoxRelativeCoordOut[i].Init(); if ( pHitBoxIndexOut ) pHitBoxIndexOut[i] = -1; } } void CParticleCollection::UpdateHitBoxInfo( int nControlPointNumber, const char *pszHitboxSetName ) { CModelHitBoxesInfo &hb = ControlPointHitBox( nControlPointNumber ); if ( hb.m_flLastUpdateTime == m_flCurTime ) return; // up to date hb.m_flLastUpdateTime = m_flCurTime; // make sure space allocated if ( ! hb.m_pHitBoxes ) hb.m_pHitBoxes = new ModelHitBoxInfo_t[ MAXSTUDIOBONES ]; if ( ! hb.m_pPrevBoxes ) hb.m_pPrevBoxes = new ModelHitBoxInfo_t[ MAXSTUDIOBONES ]; // save current into prev hb.m_nNumPrevHitBoxes = hb.m_nNumHitBoxes; hb.m_flPrevLastUpdateTime = hb.m_flLastUpdateTime; V_swap( hb.m_pHitBoxes, hb.m_pPrevBoxes ); // issue hitbox query hb.m_nNumHitBoxes = g_pParticleSystemMgr->Query()->GetControllingObjectHitBoxInfo( this, nControlPointNumber, MAXSTUDIOBONES, hb.m_pHitBoxes, pszHitboxSetName ); } void GetParticleManifest( CUtlVector<CUtlString>& list ) { GetParticleManifest( list, "particles/particles_manifest.txt" ); } void GetParticleManifest( CUtlVector<CUtlString>& list, const char *pFile ) { // Open the manifest file, and read the particles specified inside it KeyValues *manifest = new KeyValues( pFile ); if ( manifest->LoadFromFile( g_pFullFileSystem, pFile, "GAME" ) ) { for ( KeyValues *sub = manifest->GetFirstSubKey(); sub != NULL; sub = sub->GetNextKey() ) { if ( !Q_stricmp( sub->GetName(), "file" ) ) { list.AddToTail( sub->GetString() ); continue; } Warning( "CParticleMgr::Init: Manifest '%s' with bogus file type '%s', expecting 'file'\n", pFile, sub->GetName() ); } } else { Warning( "PARTICLE SYSTEM: Unable to load manifest file '%s'\n", pFile ); } manifest->deleteThis(); }
32.200946
192
0.665881
5R33CH4
b4035ea351e968f72b6ced4e27302e44d72e9521
18,436
cpp
C++
qmlui/fixtureutils.cpp
prozessorkern/qlcplus
e8be5b1a99eaad4c409aca14ae0f93f7fed84480
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
qmlui/fixtureutils.cpp
prozessorkern/qlcplus
e8be5b1a99eaad4c409aca14ae0f93f7fed84480
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
qmlui/fixtureutils.cpp
prozessorkern/qlcplus
e8be5b1a99eaad4c409aca14ae0f93f7fed84480
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* Q Light Controller Plus fixtureutils.cpp Copyright (c) Massimo Callegari 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 <QDebug> #include "monitorproperties.h" #include "qlcfixturemode.h" #include "qlccapability.h" #include "fixtureutils.h" #include "qlcmacros.h" #include "fixture.h" #include "doc.h" #define FIXTURE_ID_BITS 16 #define FIXTURE_HEAD_BITS 8 #define FIXTURE_LINKED_BITS 8 #define MAX_FIXTURE_NUMBER (1 << FIXTURE_ID_BITS) #define MAX_HEADS_NUMBER (1 << FIXTURE_HEAD_BITS) #define MAX_LINKED_NUMBER (1 << FIXTURE_LINKED_BITS) #define MIN_STROBE_FREQ_HZ 0.5 #define MAX_STROBE_FREQ_HZ 10.0 #define MIN_PULSE_FREQ_HZ 0.25 #define MAX_PULSE_FREQ_HZ 5 #define MIN_POSITION_SPEED 4000 // ms #define MAX_POSITION_SPEED 20000 // ms #define MIN_GOBO_SPEED 500 // ms #define MAX_GOBO_SPEED 5000 // ms FixtureUtils::FixtureUtils() { } quint32 FixtureUtils::fixtureItemID(quint32 fid, quint16 headIndex, quint16 linkedIndex) { Q_ASSERT(fid < MAX_FIXTURE_NUMBER); Q_ASSERT(headIndex < MAX_HEADS_NUMBER); Q_ASSERT(linkedIndex < MAX_LINKED_NUMBER); return (fid << (FIXTURE_HEAD_BITS + FIXTURE_LINKED_BITS)) | ((quint32)headIndex << FIXTURE_LINKED_BITS) | (quint32)linkedIndex; } quint32 FixtureUtils::itemFixtureID(quint32 itemID) { return (itemID >> (FIXTURE_HEAD_BITS + FIXTURE_LINKED_BITS)); } quint16 FixtureUtils::itemHeadIndex(quint32 itemID) { return ((itemID >> FIXTURE_LINKED_BITS) & ((1 << FIXTURE_HEAD_BITS) - 1)); } quint16 FixtureUtils::itemLinkedIndex(quint32 itemID) { return (itemID & ((1 << FIXTURE_LINKED_BITS) - 1)); } QPointF FixtureUtils::item2DPosition(MonitorProperties *monProps, int pointOfView, QVector3D pos) { QPointF point(0, 0); float gridUnits = monProps->gridUnits() == MonitorProperties::Meters ? 1000.0 : 304.8; switch(pointOfView) { case MonitorProperties::TopView: point.setX(pos.x()); point.setY(pos.z()); break; case MonitorProperties::Undefined: case MonitorProperties::FrontView: point.setX(pos.x()); point.setY((monProps->gridSize().y() * gridUnits) - pos.y()); break; case MonitorProperties::RightSideView: point.setX((monProps->gridSize().x() * gridUnits) - pos.z()); point.setY((monProps->gridSize().y() * gridUnits) - pos.y()); break; case MonitorProperties::LeftSideView: point.setX(pos.z()); point.setY((monProps->gridSize().y() * gridUnits) - pos.y()); break; } return point; } float FixtureUtils::item2DRotation(int pointOfView, QVector3D rot) { switch(pointOfView) { case MonitorProperties::TopView: return rot.y(); break; case MonitorProperties::RightSideView: case MonitorProperties::LeftSideView: return rot.x(); break; default: return rot.z(); break; } return 0; } QSizeF FixtureUtils::item2DDimension(QLCFixtureMode *fxMode, int pointOfView) { QSizeF size(300, 300); if (fxMode == nullptr) return size; QLCPhysical phy = fxMode->physical(); if (phy.width() == 0) phy.setWidth(300); if (phy.height() == 0) phy.setHeight(300); if (phy.depth() == 0) phy.setDepth(300); switch(pointOfView) { case MonitorProperties::TopView: size.setWidth(phy.width()); size.setHeight(phy.depth()); break; case MonitorProperties::Undefined: case MonitorProperties::FrontView: size.setWidth(phy.width()); size.setHeight(phy.height()); break; case MonitorProperties::RightSideView: case MonitorProperties::LeftSideView: size.setWidth(phy.depth()); size.setHeight(phy.height()); break; } return size; } void FixtureUtils::alignItem(QVector3D refPos, QVector3D &origPos, int pointOfView, int alignment) { switch(pointOfView) { case MonitorProperties::TopView: { switch(alignment) { case Qt::AlignTop: origPos.setZ(refPos.z()); break; case Qt::AlignLeft: origPos.setX(refPos.x()); break; } } break; case MonitorProperties::Undefined: case MonitorProperties::FrontView: { switch(alignment) { case Qt::AlignTop: origPos.setY(refPos.y()); break; case Qt::AlignLeft: origPos.setX(refPos.x()); break; } } break; case MonitorProperties::RightSideView: case MonitorProperties::LeftSideView: { switch(alignment) { case Qt::AlignTop: origPos.setY(refPos.y()); break; case Qt::AlignLeft: origPos.setZ(refPos.z()); break; } } break; } } QVector3D FixtureUtils::item3DPosition(MonitorProperties *monProps, QPointF point, float thirdVal) { QVector3D pos(point.x(), point.y(), thirdVal); switch(monProps->pointOfView()) { case MonitorProperties::TopView: pos = QVector3D(point.x(), thirdVal, point.y()); break; case MonitorProperties::RightSideView: pos = QVector3D(thirdVal, point.y(), monProps->gridSize().z() - point.x()); break; case MonitorProperties::LeftSideView: pos = QVector3D(thirdVal, point.y(), point.x()); break; default: break; } return pos; } QPointF FixtureUtils::available2DPosition(Doc *doc, int pointOfView, QRectF fxRect) { MonitorProperties *monProps = doc->monitorProperties(); if (monProps == nullptr) return QPointF(0, 0); qreal xPos = fxRect.x(), yPos = fxRect.y(); qreal maxYOffset = 0; float gridUnits = monProps->gridUnits() == MonitorProperties::Meters ? 1000.0 : 304.8; QSize gridSize; switch (pointOfView) { case MonitorProperties::TopView: gridSize = QSize(monProps->gridSize().x(), monProps->gridSize().z()); break; case MonitorProperties::RightSideView: case MonitorProperties::LeftSideView: gridSize = QSize(monProps->gridSize().z(), monProps->gridSize().y()); break; default: gridSize = QSize(monProps->gridSize().x(), monProps->gridSize().y()); break; } QRectF gridArea(0, 0, (float)gridSize.width() * gridUnits, (float)gridSize.height() * gridUnits); qreal origWidth = fxRect.width(); qreal origHeight = fxRect.height(); for (Fixture *fixture : doc->fixtures()) { if (monProps->containsFixture(fixture->id()) == false) continue; QLCFixtureMode *fxMode = fixture->fixtureMode(); for (quint32 subID : monProps->fixtureIDList(fixture->id())) { quint16 headIndex = monProps->fixtureHeadIndex(subID); quint16 linkedIndex = monProps->fixtureLinkedIndex(subID); QPointF fxPoint = item2DPosition(monProps, pointOfView, monProps->fixturePosition(fixture->id(), headIndex, linkedIndex)); QSizeF fxSize = item2DDimension(fixture->type() == QLCFixtureDef::Dimmer ? nullptr : fxMode, pointOfView); qreal itemXPos = fxPoint.x(); qreal itemYPos = fxPoint.y(); qreal itemWidth = fxSize.width(); qreal itemHeight = fxSize.height(); // store the next Y row in case we need to lower down if (itemYPos + itemHeight > maxYOffset ) maxYOffset = itemYPos + itemHeight; QRectF itemRect(itemXPos, itemYPos, itemWidth, itemHeight); //qDebug() << "item rect:" << itemRect << "fxRect:" << fxRect; if (fxRect.intersects(itemRect) == true) { xPos = itemXPos + itemWidth + 50; //add an extra 50mm spacing if (xPos + fxRect.width() > gridArea.width()) { xPos = 0; yPos = maxYOffset + 50; maxYOffset = 0; } fxRect.setX(xPos); fxRect.setY(yPos); // restore width and height as setX and setY mess them fxRect.setWidth(origWidth); fxRect.setHeight(origHeight); } } } return QPointF(xPos, yPos); } QColor FixtureUtils::blendColors(QColor a, QColor b, float mix) { // linear blending - https://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending qreal mr = b.redF() * mix + a.redF() * (1 - mix); qreal mg = b.greenF() * mix + a.greenF() * (1 - mix); qreal mb = b.blueF() * mix + a.blueF() * (1 - mix); /* // non linear blending qreal mr = qSqrt((1 - mix) * qPow(a.redF(), 2) + mix * qPow(b.redF(), 2)); qreal mg = qSqrt((1 - mix) * qPow(a.greenF(), 2) + mix * qPow(b.greenF(), 2)); qreal mb = qSqrt((1 - mix) * qPow(a.blueF(), 2) + mix * qPow(b.blueF(), 2)); */ return QColor(mr * 255.0, mg * 255.0, mb * 255.0); } QColor FixtureUtils::headColor(Fixture *fixture, int headIndex) { QColor finalColor = Qt::white; QVector <quint32> rgbCh = fixture->rgbChannels(headIndex); if (rgbCh.size() == 3) { finalColor.setRgb(fixture->channelValueAt(rgbCh.at(0)), fixture->channelValueAt(rgbCh.at(1)), fixture->channelValueAt(rgbCh.at(2))); } QVector <quint32> cmyCh = fixture->cmyChannels(headIndex); if (cmyCh.size() == 3) { finalColor.setCmyk(fixture->channelValueAt(cmyCh.at(0)), fixture->channelValueAt(cmyCh.at(1)), fixture->channelValueAt(cmyCh.at(2)), 0); } quint32 white = fixture->channelNumber(QLCChannel::White, QLCChannel::MSB, headIndex); quint32 amber = fixture->channelNumber(QLCChannel::Amber, QLCChannel::MSB, headIndex); quint32 UV = fixture->channelNumber(QLCChannel::UV, QLCChannel::MSB, headIndex); quint32 lime = fixture->channelNumber(QLCChannel::Lime, QLCChannel::MSB, headIndex); quint32 indigo = fixture->channelNumber(QLCChannel::Indigo, QLCChannel::MSB, headIndex); if (white != QLCChannel::invalid() && fixture->channelValueAt(white)) finalColor = blendColors(finalColor, Qt::white, (float)fixture->channelValueAt(white) / 255.0); if (amber != QLCChannel::invalid() && fixture->channelValueAt(amber)) finalColor = blendColors(finalColor, QColor(0xFFFF7E00), (float)fixture->channelValueAt(amber) / 255.0); if (UV != QLCChannel::invalid() && fixture->channelValueAt(UV)) finalColor = blendColors(finalColor, QColor(0xFF9400D3), (float)fixture->channelValueAt(UV) / 255.0); if (lime != QLCChannel::invalid() && fixture->channelValueAt(lime)) finalColor = blendColors(finalColor, QColor(0xFFADFF2F), (float)fixture->channelValueAt(lime) / 255.0); if (indigo != QLCChannel::invalid() && fixture->channelValueAt(indigo)) finalColor = blendColors(finalColor, QColor(0xFF4B0082), (float)fixture->channelValueAt(indigo) / 255.0); return finalColor; } QColor FixtureUtils::applyColorFilter(QColor source, QColor filter) { //qDebug() << "SOURCE" << source << "FILTER" << filter; return QColor(source.redF() * filter.redF() * 255.0, source.greenF() * filter.greenF() * 255.0, source.blueF() * filter.blueF() * 255.0); } void FixtureUtils::positionTimings(const QLCChannel *ch, uchar value, int &panDuration, int &tiltDuration) { panDuration = -1; tiltDuration = -1; switch (ch->preset()) { case QLCChannel::SpeedPanTiltFastSlow: panDuration = tiltDuration = SCALE(value, 0, 255, MIN_POSITION_SPEED, MAX_POSITION_SPEED); break; case QLCChannel::SpeedPanTiltSlowFast: panDuration = tiltDuration = SCALE(255 - value, 0, 255, MIN_POSITION_SPEED, MAX_POSITION_SPEED); break; case QLCChannel::SpeedPanFastSlow: panDuration = SCALE(value, 0, 255, MIN_POSITION_SPEED, MAX_POSITION_SPEED); break; case QLCChannel::SpeedPanSlowFast: panDuration = SCALE(255 - value, 0, 255, MIN_POSITION_SPEED, MAX_POSITION_SPEED); break; case QLCChannel::SpeedTiltFastSlow: tiltDuration = SCALE(value, 0, 255, MIN_POSITION_SPEED, MAX_POSITION_SPEED); break; case QLCChannel::SpeedTiltSlowFast: tiltDuration = SCALE(255 - value, 0, 255, MIN_POSITION_SPEED, MAX_POSITION_SPEED); break; default: break; } } bool FixtureUtils::goboTiming(const QLCCapability *cap, uchar value, int &speed) { speed = MIN_GOBO_SPEED; bool clockwise = true; if (cap->preset() == QLCCapability::Custom) { speed = -1; return true; } value = SCALE(value, cap->min(), cap->max(), 1, 255); switch (cap->preset()) { case QLCCapability::RotationClockwise: speed = MIN_GOBO_SPEED + ((MAX_GOBO_SPEED - MIN_GOBO_SPEED) / 2); break; case QLCCapability::RotationClockwiseFastToSlow: speed = SCALE(value, 0, 255, MIN_GOBO_SPEED, MAX_GOBO_SPEED); break; case QLCCapability::RotationClockwiseSlowToFast: speed = SCALE(255 - value, 0, 255, MIN_GOBO_SPEED, MAX_GOBO_SPEED); break; case QLCCapability::RotationStop: speed = 0; break; case QLCCapability::RotationCounterClockwise: speed = MIN_GOBO_SPEED + ((MAX_GOBO_SPEED - MIN_GOBO_SPEED) / 2); clockwise = false; break; case QLCCapability::RotationCounterClockwiseFastToSlow: speed = SCALE(value, 0, 255, MIN_GOBO_SPEED, MAX_GOBO_SPEED); clockwise = false; break; case QLCCapability::RotationCounterClockwiseSlowToFast: speed = SCALE(255 - value, 0, 255, MIN_GOBO_SPEED, MAX_GOBO_SPEED); clockwise = false; break; default: // not a handled/valid capability. Invalidate speed speed = -1; break; } return clockwise; } int FixtureUtils::shutterTimings(const QLCChannel *ch, uchar value, int &highTime, int &lowTime) { int capPreset = QLCCapability::ShutterOpen; float freq = 1.0; switch (ch->preset()) { case QLCChannel::ShutterStrobeSlowFast: if (value) capPreset = QLCCapability::StrobeSlowToFast; break; case QLCChannel::ShutterStrobeFastSlow: if (value) { capPreset = QLCCapability::StrobeFastToSlow; value = 255 - value; } break; default: { QLCCapability *cap = ch->searchCapability(value); if (cap == nullptr) break; capPreset = cap->preset(); switch (capPreset) { case QLCCapability::ShutterOpen: case QLCCapability::ShutterClose: break; case QLCCapability::StrobeSlowToFast: case QLCCapability::PulseSlowToFast: case QLCCapability::RampUpSlowToFast: case QLCCapability::RampDownSlowToFast: value = SCALE(value, cap->min(), cap->max(), 1, 255); break; case QLCCapability::StrobeFastToSlow: case QLCCapability::PulseFastToSlow: case QLCCapability::RampUpFastToSlow: case QLCCapability::RampDownFastToSlow: value = 255 - SCALE(value, cap->min(), cap->max(), 1, 255); break; case QLCCapability::StrobeFrequency: case QLCCapability::PulseFrequency: case QLCCapability::RampUpFrequency: case QLCCapability::RampDownFrequency: freq = cap->resource(0).toFloat(); break; case QLCCapability::StrobeFreqRange: case QLCCapability::PulseFreqRange: case QLCCapability::RampUpFreqRange: case QLCCapability::RampDownFreqRange: freq = SCALE(value, cap->min(), cap->max(), cap->resource(0).toFloat(), cap->resource(1).toFloat()); break; default: // invalidate any other preset, to avoid messing up the preview capPreset = QLCCapability::Custom; break; } } break; } switch (capPreset) { case QLCCapability::StrobeSlowToFast: case QLCCapability::StrobeFastToSlow: freq = qMax(((float)value * MAX_STROBE_FREQ_HZ) / 255.0, MIN_STROBE_FREQ_HZ); highTime = qBound(50.0, 500.0 / freq, 200.0); lowTime = qMax((1000.0 / freq) - highTime, 0.0); break; case QLCCapability::RampUpSlowToFast: case QLCCapability::RampUpFastToSlow: case QLCCapability::RampDownSlowToFast: case QLCCapability::RampDownFastToSlow: case QLCCapability::PulseSlowToFast: case QLCCapability::PulseFastToSlow: freq = qMax(((float)value * MAX_PULSE_FREQ_HZ) / 255.0, MIN_PULSE_FREQ_HZ); highTime = qMax(50.0, 1000.0 / freq); lowTime = 0; break; default: highTime = qBound(50.0, 500.0 / freq, 200.0); lowTime = qMax((1000.0 / freq) - highTime, 0.0); break; } //qDebug() << "Frequency:" << freq << "Hz, high:" << highTime << ", low:" << lowTime; return capPreset; }
34.077634
118
0.598503
prozessorkern
b405922ec15ab35a4c770376ec46e00d3ba6369f
1,199
hpp
C++
subprojects/libusbcpp/include/libusbcpp/error.hpp
mmmspatz/wumbo_mr
7dfecd4cb824ad2268f6f9208e3fe6c9510fb097
[ "BSL-1.0" ]
1
2021-02-12T06:54:53.000Z
2021-02-12T06:54:53.000Z
subprojects/libusbcpp/include/libusbcpp/error.hpp
mmmspatz/wumbo_mr
7dfecd4cb824ad2268f6f9208e3fe6c9510fb097
[ "BSL-1.0" ]
null
null
null
subprojects/libusbcpp/include/libusbcpp/error.hpp
mmmspatz/wumbo_mr
7dfecd4cb824ad2268f6f9208e3fe6c9510fb097
[ "BSL-1.0" ]
null
null
null
// Copyright Mark H. Spatz 2021-present // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // https://www.boost.org/LICENSE_1_0.txt) #pragma once #include <stdexcept> #include "core.hpp" namespace libusbcpp { template <c::libusb_error error_code> struct Error : std::exception { const char *what() const noexcept final { return c::libusb_error_name(error_code); } }; inline unsigned int ChkRet(int ret) { if (ret >= 0) { return static_cast<unsigned int>(ret); } switch (ret) { #define HANDLE(ERROR_CODE) \ case c::ERROR_CODE: \ throw Error<c::ERROR_CODE>(); HANDLE(LIBUSB_ERROR_IO) HANDLE(LIBUSB_ERROR_INVALID_PARAM) HANDLE(LIBUSB_ERROR_ACCESS) HANDLE(LIBUSB_ERROR_NO_DEVICE) HANDLE(LIBUSB_ERROR_NOT_FOUND) HANDLE(LIBUSB_ERROR_BUSY) HANDLE(LIBUSB_ERROR_TIMEOUT) HANDLE(LIBUSB_ERROR_OVERFLOW) HANDLE(LIBUSB_ERROR_PIPE) HANDLE(LIBUSB_ERROR_INTERRUPTED) HANDLE(LIBUSB_ERROR_NO_MEM) HANDLE(LIBUSB_ERROR_NOT_SUPPORTED) HANDLE(LIBUSB_ERROR_OTHER) #undef HANDLE default: throw std::runtime_error("Unknown libusb error code"); } } } // namespace libusbcpp
25.510638
86
0.729775
mmmspatz
b405d83ba3e02315ea4a54738bbca4f5dd4d29d8
5,037
cpp
C++
tests/test_record_format.cpp
pthis/CppLogging
5c76bceef12eec705bf07b28c09d74023c1c3bb0
[ "MIT" ]
97
2016-10-09T04:10:25.000Z
2022-03-30T21:23:25.000Z
tests/test_record_format.cpp
pthis/CppLogging
5c76bceef12eec705bf07b28c09d74023c1c3bb0
[ "MIT" ]
4
2019-10-25T01:45:13.000Z
2021-12-15T04:09:58.000Z
tests/test_record_format.cpp
pthis/CppLogging
5c76bceef12eec705bf07b28c09d74023c1c3bb0
[ "MIT" ]
34
2018-12-28T14:01:46.000Z
2021-11-24T17:22:09.000Z
// // Created by Ivan Shynkarenka on 18.09.2016 // #include "test.h" #include "logging/record.h" using namespace CppLogging; namespace { class Date { public: Date(int year, int month, int day) : _year(year), _month(month), _day(day) {} friend std::ostream& operator<<(std::ostream& os, const Date& date) { return os << date._year << '-' << date._month << '-' << date._day; } friend CppLogging::Record& operator<<(CppLogging::Record& record, const Date& date) { return record.StoreCustomFormat("{}-{}-{}", date._year, date._month, date._day); } private: int _year, _month, _day; }; class DateTime { public: DateTime(Date date, int hours, int minutes, int seconds) : _date(date), _hours(hours), _minutes(minutes), _seconds(seconds) {} friend std::ostream& operator<<(std::ostream& os, const DateTime& datetime) { return os << datetime._date << " " << datetime._hours << ':' << datetime._minutes << ':' << datetime._seconds; } friend CppLogging::Record& operator<<(CppLogging::Record& record, const DateTime& datetime) { const size_t begin = record.StoreListBegin(); record.StoreList(datetime._date); record.StoreList(' '); record.StoreList(datetime._hours); record.StoreList(':'); record.StoreList(datetime._minutes); record.StoreList(':'); record.StoreList(datetime._seconds); return record.StoreListEnd(begin); } private: Date _date; int _hours, _minutes, _seconds; }; template <typename... T> std::string format(fmt::format_string<T...> pattern, T&&... args) { Record record; record.Format(pattern, std::forward<T>(args)...); return record.message; } template <typename... T> std::string store(fmt::format_string<T...> pattern, T&&... args) { Record record; record.StoreFormat(pattern, std::forward<T>(args)...); record.message = record.RestoreFormat(); return record.message; } } // namespace TEST_CASE("Format message", "[CppLogging]") { REQUIRE(format("no arguments") == "no arguments"); REQUIRE(format("{0}, {1}, {2}", -1, 0, 1) == "-1, 0, 1"); REQUIRE(format("{0}, {1}, {2}", 'a', 'b', 'c') == "a, b, c"); REQUIRE(format("{}, {}, {}", 'a', 'b', 'c') == "a, b, c"); REQUIRE(format("{2}, {1}, {0}", 'a', 'b', 'c') == "c, b, a"); REQUIRE(format("{0}{1}{0}", "abra", "cad") == "abracadabra"); REQUIRE(format("{:<30}", "left aligned") == "left aligned "); REQUIRE(format("{:>30}", "right aligned") == " right aligned"); REQUIRE(format("{:^30}", "centered") == " centered "); REQUIRE(format("{:*^30}", "centered") == "***********centered***********"); REQUIRE(format("{:+f}; {:+f}", 3.14, -3.14) == "+3.140000; -3.140000"); REQUIRE(format("{: f}; {: f}", 3.14, -3.14) == " 3.140000; -3.140000"); REQUIRE(format("{:-f}; {:-f}", 3.14, -3.14) == "3.140000; -3.140000"); REQUIRE(format("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42) == "int: 42; hex: 2a; oct: 52; bin: 101010"); REQUIRE(format("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}", 42) == "int: 42; hex: 0x2a; oct: 052; bin: 0b101010"); REQUIRE(format("The date is {}", Date(2012, 12, 9)) == "The date is 2012-12-9"); REQUIRE(format("The datetime is {}", DateTime(Date(2012, 12, 9), 13, 15, 57)) == "The datetime is 2012-12-9 13:15:57"); REQUIRE(format("Elapsed time: {s:.2f} seconds", "s"_a = 1.23) == "Elapsed time: 1.23 seconds"); } TEST_CASE("Store message", "[CppLogging]") { REQUIRE(store("no arguments") == "no arguments"); REQUIRE(store("{0}, {1}, {2}", -1, 0, 1) == "-1, 0, 1"); REQUIRE(store("{0}, {1}, {2}", 'a', 'b', 'c') == "a, b, c"); REQUIRE(store("{}, {}, {}", 'a', 'b', 'c') == "a, b, c"); REQUIRE(store("{2}, {1}, {0}", 'a', 'b', 'c') == "c, b, a"); REQUIRE(store("{0}{1}{0}", "abra", "cad") == "abracadabra"); REQUIRE(store("{:<30}", "left aligned") == "left aligned "); REQUIRE(store("{:>30}", "right aligned") == " right aligned"); REQUIRE(store("{:^30}", "centered") == " centered "); REQUIRE(store("{:*^30}", "centered") == "***********centered***********"); REQUIRE(store("{:+f}; {:+f}", 3.14, -3.14) == "+3.140000; -3.140000"); REQUIRE(store("{: f}; {: f}", 3.14, -3.14) == " 3.140000; -3.140000"); REQUIRE(store("{:-f}; {:-f}", 3.14, -3.14) == "3.140000; -3.140000"); REQUIRE(store("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42) == "int: 42; hex: 2a; oct: 52; bin: 101010"); REQUIRE(store("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}", 42) == "int: 42; hex: 0x2a; oct: 052; bin: 0b101010"); REQUIRE(store("The date is {}", Date(2012, 12, 9)) == "The date is 2012-12-9"); REQUIRE(store("The datetime is {}", DateTime(Date(2012, 12, 9), 13, 15, 57)) == "The datetime is 2012-12-9 13:15:57"); REQUIRE(store("Elapsed time: {s:.2f} seconds", "s"_a = 1.23) == "Elapsed time: 1.23 seconds"); }
43.422414
132
0.542585
pthis
b408af44dddc358ee3b0ba4091d9e7a884b3143e
785
cpp
C++
chapter-15/Program pg 464.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
chapter-15/Program pg 464.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
chapter-15/Program pg 464.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
/* cunstructor with parameters */ #include<iostream> using namespace std; class A { private: int a; public: A() { a=0; } A(int n) { a=n; } void showA() { cout<<"A = "<<a<<endl; } }; class B { private: int b; public: B() { b=0; } B(int n) { b=n; } void showB() { cout<<"B = "<<b<<endl; } }; class C: public A, public B { private: int c; public: C(): B(),A() { c=0; } C(int x, int y, int z): A(x), B(y) { c=z; } void showC() { A::showA(); B::showB(); cout<<"c = "<<c<<endl; } }; main() { C obj(1,2,3); obj.showC(); }
10.608108
39
0.346497
JahanzebNawaz
b40ebb6b1148e194d1577fd72c361b7f57503c32
706
cpp
C++
solutions/URI_1061 - (2303944) - Accepted.cpp
KelwinKomka/URI-Online-Judge-1
3d6e37ebe3aa145f47dfcad8b219e53c3cae50f6
[ "MIT" ]
null
null
null
solutions/URI_1061 - (2303944) - Accepted.cpp
KelwinKomka/URI-Online-Judge-1
3d6e37ebe3aa145f47dfcad8b219e53c3cae50f6
[ "MIT" ]
null
null
null
solutions/URI_1061 - (2303944) - Accepted.cpp
KelwinKomka/URI-Online-Judge-1
3d6e37ebe3aa145f47dfcad8b219e53c3cae50f6
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, const char * argv[]) { int i, dia1, h1, m1, s1, dia2, h2, m2, s2, seg1, seg; string c; cin >> c >> dia1 >> h1 >> c >> m1 >> c >> s1 >> c >> dia2 >> h2 >> c >> m2 >> c >> s2; seg1 = 3600*h1 + 60*m1 + s1; if(dia2-dia1 == 0) seg = 3600*h2 + 60*m2 + s2 - seg1; else seg = ((dia2-dia1-1) * 86400) + (86400-seg1) + 3600*h2 + 60*m2 + s2; cout << (seg/86400) << " dia(s)" << endl; cout << (seg%86400)/3600 << " hora(s)" << endl; cout << ((seg%86400)%3600)/60 << " minuto(s)" << endl; cout << ((seg%86400)%3600)%60 << " segundo(s)" << endl; return 0; }
28.24
91
0.46034
KelwinKomka
b40ef601ea2f2ca96d4a3f84e1b3f7b9b3e811ba
105,976
cpp
C++
interface/src/avatar/MyAvatar.cpp
trentpolack/hifi
3b8636b75c3df242c0aeecbca6e01f386e238f45
[ "Apache-2.0" ]
null
null
null
interface/src/avatar/MyAvatar.cpp
trentpolack/hifi
3b8636b75c3df242c0aeecbca6e01f386e238f45
[ "Apache-2.0" ]
null
null
null
interface/src/avatar/MyAvatar.cpp
trentpolack/hifi
3b8636b75c3df242c0aeecbca6e01f386e238f45
[ "Apache-2.0" ]
null
null
null
// // MyAvatar.cpp // interface/src/avatar // // Created by Mark Peng on 8/16/13. // Copyright 2012 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include <algorithm> #include <vector> #include <QBuffer> #include <glm/gtx/norm.hpp> #include <glm/gtx/vector_angle.hpp> #include <QtCore/QTimer> #include <scripting/HMDScriptingInterface.h> #include <AccountManager.h> #include <AddressManager.h> #include <AudioClient.h> #include <display-plugins/DisplayPlugin.h> #include <FSTReader.h> #include <GeometryUtil.h> #include <NodeList.h> #include <udt/PacketHeaders.h> #include <PathUtils.h> #include <PerfStat.h> #include <SharedUtil.h> #include <SoundCache.h> #include <TextRenderer3D.h> #include <UserActivityLogger.h> #include <AnimDebugDraw.h> #include <AnimClip.h> #include <recording/Deck.h> #include <recording/Recorder.h> #include <recording/Clip.h> #include <recording/Frame.h> #include <RecordingScriptingInterface.h> #include "Application.h" #include "devices/Faceshift.h" #include "AvatarManager.h" #include "AvatarActionHold.h" #include "Menu.h" #include "MyAvatar.h" #include "Physics.h" #include "Util.h" #include "InterfaceLogging.h" #include "DebugDraw.h" #include "EntityEditPacketSender.h" #include "MovingEntitiesOperator.h" using namespace std; const float DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES = 30.0f; const float MAX_WALKING_SPEED = 2.6f; // human walking speed const float MAX_BOOST_SPEED = 0.5f * MAX_WALKING_SPEED; // action motor gets additive boost below this speed const float MIN_AVATAR_SPEED = 0.05f; const float MIN_AVATAR_SPEED_SQUARED = MIN_AVATAR_SPEED * MIN_AVATAR_SPEED; // speed is set to zero below this const float YAW_SPEED_DEFAULT = 120.0f; // degrees/sec const float PITCH_SPEED_DEFAULT = 90.0f; // degrees/sec // TODO: normalize avatar speed for standard avatar size, then scale all motion logic // to properly follow avatar size. float MAX_AVATAR_SPEED = 30.0f; float MAX_ACTION_MOTOR_SPEED = MAX_AVATAR_SPEED; float MIN_SCRIPTED_MOTOR_TIMESCALE = 0.005f; float DEFAULT_SCRIPTED_MOTOR_TIMESCALE = 1.0e6f; const int SCRIPTED_MOTOR_CAMERA_FRAME = 0; const int SCRIPTED_MOTOR_AVATAR_FRAME = 1; const int SCRIPTED_MOTOR_WORLD_FRAME = 2; const QString& DEFAULT_AVATAR_COLLISION_SOUND_URL = "https://hifi-public.s3.amazonaws.com/sounds/Collisions-otherorganic/Body_Hits_Impact.wav"; const float MyAvatar::ZOOM_MIN = 0.5f; const float MyAvatar::ZOOM_MAX = 25.0f; const float MyAvatar::ZOOM_DEFAULT = 1.5f; MyAvatar::MyAvatar(RigPointer rig) : Avatar(rig), _wasPushing(false), _isPushing(false), _isBeingPushed(false), _isBraking(false), _isAway(false), _boomLength(ZOOM_DEFAULT), _yawSpeed(YAW_SPEED_DEFAULT), _pitchSpeed(PITCH_SPEED_DEFAULT), _thrust(0.0f), _actionMotorVelocity(0.0f), _scriptedMotorVelocity(0.0f), _scriptedMotorTimescale(DEFAULT_SCRIPTED_MOTOR_TIMESCALE), _scriptedMotorFrame(SCRIPTED_MOTOR_CAMERA_FRAME), _motionBehaviors(AVATAR_MOTION_DEFAULTS), _characterController(this), _lookAtTargetAvatar(), _shouldRender(true), _eyeContactTarget(LEFT_EYE), _realWorldFieldOfView("realWorldFieldOfView", DEFAULT_REAL_WORLD_FIELD_OF_VIEW_DEGREES), _useAdvancedMovementControls("advancedMovementForHandControllersIsChecked", false), _hmdSensorMatrix(), _hmdSensorOrientation(), _hmdSensorPosition(), _bodySensorMatrix(), _goToPending(false), _goToPosition(), _goToOrientation(), _rig(rig), _prevShouldDrawHead(true), _audioListenerMode(FROM_HEAD), _hmdAtRestDetector(glm::vec3(0), glm::quat()) { using namespace recording; _skeletonModel->flagAsCauterized(); clearDriveKeys(); // Necessary to select the correct slot using SlotType = void(MyAvatar::*)(const glm::vec3&, bool, const glm::quat&, bool); // connect to AddressManager signal for location jumps connect(DependencyManager::get<AddressManager>().data(), &AddressManager::locationChangeRequired, this, static_cast<SlotType>(&MyAvatar::goToLocation)); // handle scale constraints imposed on us by the domain-server auto& domainHandler = DependencyManager::get<NodeList>()->getDomainHandler(); // when we connect to a domain and retrieve its settings, we restrict our max/min scale based on those settings connect(&domainHandler, &DomainHandler::settingsReceived, this, &MyAvatar::restrictScaleFromDomainSettings); // when we leave a domain we lift whatever restrictions that domain may have placed on our scale connect(&domainHandler, &DomainHandler::disconnectedFromDomain, this, &MyAvatar::clearScaleRestriction); _characterController.setEnabled(true); _bodySensorMatrix = deriveBodyFromHMDSensor(); using namespace recording; auto player = DependencyManager::get<Deck>(); auto recorder = DependencyManager::get<Recorder>(); connect(player.data(), &Deck::playbackStateChanged, [=] { bool isPlaying = player->isPlaying(); if (isPlaying) { auto recordingInterface = DependencyManager::get<RecordingScriptingInterface>(); if (recordingInterface->getPlayFromCurrentLocation()) { setRecordingBasis(); } _wasCharacterControllerEnabled = _characterController.isEnabled(); _characterController.setEnabled(false); } else { clearRecordingBasis(); useFullAvatarURL(_fullAvatarURLFromPreferences, _fullAvatarModelName); _characterController.setEnabled(_wasCharacterControllerEnabled); } auto audioIO = DependencyManager::get<AudioClient>(); audioIO->setIsPlayingBackRecording(isPlaying); if (_rig) { _rig->setEnableAnimations(!isPlaying); } }); connect(recorder.data(), &Recorder::recordingStateChanged, [=] { if (recorder->isRecording()) { setRecordingBasis(); } else { clearRecordingBasis(); } }); static const recording::FrameType AVATAR_FRAME_TYPE = recording::Frame::registerFrameType(AvatarData::FRAME_NAME); Frame::registerFrameHandler(AVATAR_FRAME_TYPE, [=](Frame::ConstPointer frame) { static AvatarData dummyAvatar; AvatarData::fromFrame(frame->data, dummyAvatar); if (getRecordingBasis()) { dummyAvatar.setRecordingBasis(getRecordingBasis()); } else { dummyAvatar.clearRecordingBasis(); } auto recordingInterface = DependencyManager::get<RecordingScriptingInterface>(); if (recordingInterface->getPlayerUseSkeletonModel() && dummyAvatar.getSkeletonModelURL().isValid() && (dummyAvatar.getSkeletonModelURL() != getSkeletonModelURL())) { setSkeletonModelURL(dummyAvatar.getSkeletonModelURL()); } if (recordingInterface->getPlayerUseDisplayName() && dummyAvatar.getDisplayName() != getDisplayName()) { setDisplayName(dummyAvatar.getDisplayName()); } setPosition(dummyAvatar.getPosition()); setOrientation(dummyAvatar.getOrientation()); if (!dummyAvatar.getAttachmentData().isEmpty()) { setAttachmentData(dummyAvatar.getAttachmentData()); } auto headData = dummyAvatar.getHeadData(); if (headData && _headData) { // blendshapes if (!headData->getBlendshapeCoefficients().isEmpty()) { _headData->setBlendshapeCoefficients(headData->getBlendshapeCoefficients()); } // head orientation _headData->setLookAtPosition(headData->getLookAtPosition()); } auto jointData = dummyAvatar.getRawJointData(); if (jointData.length() > 0 && _rig) { _rig->copyJointsFromJointData(jointData); } }); connect(rig.get(), SIGNAL(onLoadComplete()), this, SIGNAL(onLoadComplete())); } MyAvatar::~MyAvatar() { _lookAtTargetAvatar.reset(); } void MyAvatar::registerMetaTypes(QScriptEngine* engine) { QScriptValue value = engine->newQObject(this, QScriptEngine::QtOwnership, QScriptEngine::ExcludeDeleteLater | QScriptEngine::ExcludeChildObjects); engine->globalObject().setProperty("MyAvatar", value); QScriptValue driveKeys = engine->newObject(); auto metaEnum = QMetaEnum::fromType<DriveKeys>(); for (int i = 0; i < MAX_DRIVE_KEYS; ++i) { driveKeys.setProperty(metaEnum.key(i), metaEnum.value(i)); } engine->globalObject().setProperty("DriveKeys", driveKeys); qScriptRegisterMetaType(engine, audioListenModeToScriptValue, audioListenModeFromScriptValue); qScriptRegisterMetaType(engine, driveKeysToScriptValue, driveKeysFromScriptValue); } void MyAvatar::setOrientationVar(const QVariant& newOrientationVar) { Avatar::setOrientation(quatFromVariant(newOrientationVar)); } QVariant MyAvatar::getOrientationVar() const { return quatToVariant(Avatar::getOrientation()); } // virtual void MyAvatar::simulateAttachments(float deltaTime) { // don't update attachments here, do it in harvestResultsFromPhysicsSimulation() } QByteArray MyAvatar::toByteArrayStateful(AvatarDataDetail dataDetail) { CameraMode mode = qApp->getCamera()->getMode(); _globalPosition = getPosition(); _globalBoundingBoxDimensions.x = _characterController.getCapsuleRadius(); _globalBoundingBoxDimensions.y = _characterController.getCapsuleHalfHeight(); _globalBoundingBoxDimensions.z = _characterController.getCapsuleRadius(); _globalBoundingBoxOffset = _characterController.getCapsuleLocalOffset(); if (mode == CAMERA_MODE_THIRD_PERSON || mode == CAMERA_MODE_INDEPENDENT) { // fake the avatar position that is sent up to the AvatarMixer glm::vec3 oldPosition = getPosition(); setPosition(getSkeletonPosition()); QByteArray array = AvatarData::toByteArrayStateful(dataDetail); // copy the correct position back setPosition(oldPosition); return array; } return AvatarData::toByteArrayStateful(dataDetail); } void MyAvatar::resetSensorsAndBody() { qApp->getActiveDisplayPlugin()->resetSensors(); reset(true, false, true); } void MyAvatar::centerBody() { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "centerBody"); return; } // derive the desired body orientation from the current hmd orientation, before the sensor reset. auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. // transform this body into world space auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix; auto worldBodyPos = extractTranslation(worldBodyMatrix); auto worldBodyRot = glm::normalize(glm::quat_cast(worldBodyMatrix)); if (_characterController.getState() == CharacterController::State::Ground) { // the avatar's physical aspect thinks it is standing on something // therefore need to be careful to not "center" the body below the floor float downStep = glm::dot(worldBodyPos - getPosition(), _worldUpDirection); if (downStep < -0.5f * _characterController.getCapsuleHalfHeight() + _characterController.getCapsuleRadius()) { worldBodyPos -= downStep * _worldUpDirection; } } // this will become our new position. setPosition(worldBodyPos); setOrientation(worldBodyRot); // reset the body in sensor space _bodySensorMatrix = newBodySensorMatrix; // rebuild the sensor to world matrix updateSensorToWorldMatrix(); } void MyAvatar::clearIKJointLimitHistory() { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "clearIKJointLimitHistory"); return; } if (_rig) { _rig->clearIKJointLimitHistory(); } } void MyAvatar::reset(bool andRecenter, bool andReload, bool andHead) { assert(QThread::currentThread() == thread()); // Reset dynamic state. _wasPushing = _isPushing = _isBraking = false; _follow.deactivate(); if (andReload) { _skeletonModel->reset(); } if (andHead) { // which drives camera in desktop getHead()->reset(); } setThrust(glm::vec3(0.0f)); if (andRecenter) { // derive the desired body orientation from the *old* hmd orientation, before the sensor reset. auto newBodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. // transform this body into world space auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix; auto worldBodyPos = extractTranslation(worldBodyMatrix); auto worldBodyRot = glm::normalize(glm::quat_cast(worldBodyMatrix)); // this will become our new position. setPosition(worldBodyPos); setOrientation(worldBodyRot); // now sample the new hmd orientation AFTER sensor reset, which should be identity. glm::mat4 identity; updateFromHMDSensorMatrix(identity); // update the body in sensor space using the new hmd sensor sample _bodySensorMatrix = deriveBodyFromHMDSensor(); // rebuild the sensor to world matrix such that, the HMD will point in the desired orientation. // i.e. the along avatar's current position and orientation. updateSensorToWorldMatrix(); } } void MyAvatar::update(float deltaTime) { // update moving average of HMD facing in xz plane. const float HMD_FACING_TIMESCALE = 4.0f; // very slow average float tau = deltaTime / HMD_FACING_TIMESCALE; _hmdSensorFacingMovingAverage = lerp(_hmdSensorFacingMovingAverage, _hmdSensorFacing, tau); #ifdef DEBUG_DRAW_HMD_MOVING_AVERAGE glm::vec3 p = transformPoint(getSensorToWorldMatrix(), _hmdSensorPosition + glm::vec3(_hmdSensorFacingMovingAverage.x, 0.0f, _hmdSensorFacingMovingAverage.y)); DebugDraw::getInstance().addMarker("facing-avg", getOrientation(), p, glm::vec4(1.0f)); p = transformPoint(getSensorToWorldMatrix(), _hmdSensorPosition + glm::vec3(_hmdSensorFacing.x, 0.0f, _hmdSensorFacing.y)); DebugDraw::getInstance().addMarker("facing", getOrientation(), p, glm::vec4(1.0f)); #endif if (_goToPending) { setPosition(_goToPosition); setOrientation(_goToOrientation); _hmdSensorFacingMovingAverage = _hmdSensorFacing; // reset moving average _goToPending = false; // updateFromHMDSensorMatrix (called from paintGL) expects that the sensorToWorldMatrix is updated for any position changes // that happen between render and Application::update (which calls updateSensorToWorldMatrix to do so). // However, render/MyAvatar::update/Application::update don't always match (e.g., when using the separate avatar update thread), // so we update now. It's ok if it updates again in the normal way. updateSensorToWorldMatrix(); emit positionGoneTo(); } Head* head = getHead(); head->relax(deltaTime); updateFromTrackers(deltaTime); // Get audio loudness data from audio input device // Also get the AudioClient so we can update the avatar bounding box data // on the AudioClient side. auto audio = DependencyManager::get<AudioClient>(); head->setAudioLoudness(audio->getLastInputLoudness()); head->setAudioAverageLoudness(audio->getAudioAverageInputLoudness()); glm::vec3 halfBoundingBoxDimensions(_characterController.getCapsuleRadius(), _characterController.getCapsuleHalfHeight(), _characterController.getCapsuleRadius()); halfBoundingBoxDimensions += _characterController.getCapsuleLocalOffset(); QMetaObject::invokeMethod(audio.data(), "setAvatarBoundingBoxParameters", Q_ARG(glm::vec3, (getPosition() - halfBoundingBoxDimensions)), Q_ARG(glm::vec3, (halfBoundingBoxDimensions*2.0f))); uint64_t now = usecTimestampNow(); if (now > _identityPacketExpiry || _avatarEntityDataLocallyEdited) { _identityPacketExpiry = now + AVATAR_IDENTITY_PACKET_SEND_INTERVAL_MSECS; sendIdentityPacket(); } simulate(deltaTime); currentEnergy += energyChargeRate; currentEnergy -= getAccelerationEnergy(); currentEnergy -= getAudioEnergy(); if(didTeleport()) { currentEnergy = 0.0f; } currentEnergy = max(0.0f, min(currentEnergy,1.0f)); emit energyChanged(currentEnergy); updateEyeContactTarget(deltaTime); } void MyAvatar::updateEyeContactTarget(float deltaTime) { _eyeContactTargetTimer -= deltaTime; if (_eyeContactTargetTimer < 0.0f) { const float CHANCE_OF_CHANGING_TARGET = 0.01f; if (randFloat() < CHANCE_OF_CHANGING_TARGET) { float const FIFTY_FIFTY_CHANCE = 0.5f; float const EYE_TO_MOUTH_CHANCE = 0.25f; switch (_eyeContactTarget) { case LEFT_EYE: _eyeContactTarget = (randFloat() < EYE_TO_MOUTH_CHANCE) ? MOUTH : RIGHT_EYE; break; case RIGHT_EYE: _eyeContactTarget = (randFloat() < EYE_TO_MOUTH_CHANCE) ? MOUTH : LEFT_EYE; break; case MOUTH: default: _eyeContactTarget = (randFloat() < FIFTY_FIFTY_CHANCE) ? RIGHT_EYE : LEFT_EYE; break; } const float EYE_TARGET_DELAY_TIME = 0.33f; _eyeContactTargetTimer = EYE_TARGET_DELAY_TIME; } } } extern QByteArray avatarStateToFrame(const AvatarData* _avatar); extern void avatarStateFromFrame(const QByteArray& frameData, AvatarData* _avatar); void MyAvatar::simulate(float deltaTime) { PerformanceTimer perfTimer("simulate"); animateScaleChanges(deltaTime); { PerformanceTimer perfTimer("transform"); bool stepAction = false; // When there are no step values, we zero out the last step pulse. // This allows a user to do faster snapping by tapping a control for (int i = STEP_TRANSLATE_X; !stepAction && i <= STEP_YAW; ++i) { if (getDriveKey((DriveKeys)i) != 0.0f) { stepAction = true; } } updateOrientation(deltaTime); updatePosition(deltaTime); } // update sensorToWorldMatrix for camera and hand controllers // before we perform rig animations and IK. updateSensorToWorldMatrix(); { PerformanceTimer perfTimer("skeleton"); _skeletonModel->simulate(deltaTime); } // we've achived our final adjusted position and rotation for the avatar // and all of its joints, now update our attachements. Avatar::simulateAttachments(deltaTime); if (!_skeletonModel->hasSkeleton()) { // All the simulation that can be done has been done getHead()->setPosition(getPosition()); // so audio-position isn't 0,0,0 return; } { PerformanceTimer perfTimer("joints"); // copy out the skeleton joints from the model if (_rigEnabled) { _rig->copyJointsIntoJointData(_jointData); } } { PerformanceTimer perfTimer("head"); Head* head = getHead(); glm::vec3 headPosition; if (!_skeletonModel->getHeadPosition(headPosition)) { headPosition = getPosition(); } head->setPosition(headPosition); head->setScale(getUniformScale()); head->simulate(deltaTime, true); } // Record avatars movements. auto recorder = DependencyManager::get<recording::Recorder>(); if (recorder->isRecording()) { static const recording::FrameType FRAME_TYPE = recording::Frame::registerFrameType(AvatarData::FRAME_NAME); recorder->recordFrame(FRAME_TYPE, toFrame(*this)); } locationChanged(); // if a entity-child of this avatar has moved outside of its queryAACube, update the cube and tell the entity server. auto entityTreeRenderer = qApp->getEntities(); EntityTreePointer entityTree = entityTreeRenderer ? entityTreeRenderer->getTree() : nullptr; if (entityTree) { bool flyingAllowed = true; bool ghostingAllowed = true; entityTree->withWriteLock([&] { std::shared_ptr<ZoneEntityItem> zone = entityTreeRenderer->myAvatarZone(); if (zone) { flyingAllowed = zone->getFlyingAllowed(); ghostingAllowed = zone->getGhostingAllowed(); } auto now = usecTimestampNow(); EntityEditPacketSender* packetSender = qApp->getEntityEditPacketSender(); MovingEntitiesOperator moveOperator(entityTree); forEachDescendant([&](SpatiallyNestablePointer object) { // if the queryBox has changed, tell the entity-server if (object->computePuffedQueryAACube() && object->getNestableType() == NestableType::Entity) { EntityItemPointer entity = std::static_pointer_cast<EntityItem>(object); bool success; AACube newCube = entity->getQueryAACube(success); if (success) { moveOperator.addEntityToMoveList(entity, newCube); } if (packetSender) { EntityItemProperties properties = entity->getProperties(); properties.setQueryAACubeDirty(); properties.setLastEdited(now); packetSender->queueEditEntityMessage(PacketType::EntityEdit, entityTree, entity->getID(), properties); entity->setLastBroadcast(usecTimestampNow()); } } }); // also update the position of children in our local octree if (moveOperator.hasMovingEntities()) { PerformanceTimer perfTimer("recurseTreeWithOperator"); entityTree->recurseTreeWithOperator(&moveOperator); } }); _characterController.setFlyingAllowed(flyingAllowed); if (!_characterController.isEnabled() && !ghostingAllowed) { _characterController.setEnabled(true); } } updateAvatarEntities(); } // As far as I know no HMD system supports a play area of a kilometer in radius. static const float MAX_HMD_ORIGIN_DISTANCE = 1000.0f; // Pass a recent sample of the HMD to the avatar. // This can also update the avatar's position to follow the HMD // as it moves through the world. void MyAvatar::updateFromHMDSensorMatrix(const glm::mat4& hmdSensorMatrix) { // update the sensorMatrices based on the new hmd pose _hmdSensorMatrix = hmdSensorMatrix; auto newHmdSensorPosition = extractTranslation(hmdSensorMatrix); if (newHmdSensorPosition != _hmdSensorPosition && glm::length(newHmdSensorPosition) > MAX_HMD_ORIGIN_DISTANCE) { qWarning() << "Invalid HMD sensor position " << newHmdSensorPosition; // Ignore unreasonable HMD sensor data return; } _hmdSensorPosition = newHmdSensorPosition; _hmdSensorOrientation = glm::quat_cast(hmdSensorMatrix); _hmdSensorFacing = getFacingDir2D(_hmdSensorOrientation); } void MyAvatar::updateJointFromController(controller::Action poseKey, ThreadSafeValueCache<glm::mat4>& matrixCache) { assert(QThread::currentThread() == thread()); auto userInputMapper = DependencyManager::get<UserInputMapper>(); controller::Pose controllerPose = userInputMapper->getPoseState(poseKey); Transform transform; transform.setTranslation(controllerPose.getTranslation()); transform.setRotation(controllerPose.getRotation()); glm::mat4 controllerMatrix = transform.getMatrix(); matrixCache.set(controllerMatrix); } // best called at end of main loop, after physics. // update sensor to world matrix from current body position and hmd sensor. // This is so the correct camera can be used for rendering. void MyAvatar::updateSensorToWorldMatrix() { // update the sensor mat so that the body position will end up in the desired // position when driven from the head. glm::mat4 desiredMat = createMatFromQuatAndPos(getOrientation(), getPosition()); _sensorToWorldMatrix = desiredMat * glm::inverse(_bodySensorMatrix); lateUpdatePalms(); if (_enableDebugDrawSensorToWorldMatrix) { DebugDraw::getInstance().addMarker("sensorToWorldMatrix", glmExtractRotation(_sensorToWorldMatrix), extractTranslation(_sensorToWorldMatrix), glm::vec4(1)); } _sensorToWorldMatrixCache.set(_sensorToWorldMatrix); updateJointFromController(controller::Action::LEFT_HAND, _controllerLeftHandMatrixCache); updateJointFromController(controller::Action::RIGHT_HAND, _controllerRightHandMatrixCache); } // Update avatar head rotation with sensor data void MyAvatar::updateFromTrackers(float deltaTime) { glm::vec3 estimatedPosition, estimatedRotation; bool inHmd = qApp->isHMDMode(); bool playing = DependencyManager::get<recording::Deck>()->isPlaying(); if (inHmd && playing) { return; } FaceTracker* tracker = qApp->getActiveFaceTracker(); bool inFacetracker = tracker && !tracker->isMuted(); if (inHmd) { estimatedPosition = extractTranslation(getHMDSensorMatrix()); estimatedPosition.x *= -1.0f; _trackedHeadPosition = estimatedPosition; const float OCULUS_LEAN_SCALE = 0.05f; estimatedPosition /= OCULUS_LEAN_SCALE; } else if (inFacetracker) { estimatedPosition = tracker->getHeadTranslation(); _trackedHeadPosition = estimatedPosition; estimatedRotation = glm::degrees(safeEulerAngles(tracker->getHeadRotation())); } // Rotate the body if the head is turned beyond the screen if (Menu::getInstance()->isOptionChecked(MenuOption::TurnWithHead)) { const float TRACKER_YAW_TURN_SENSITIVITY = 0.5f; const float TRACKER_MIN_YAW_TURN = 15.0f; const float TRACKER_MAX_YAW_TURN = 50.0f; if ( (fabs(estimatedRotation.y) > TRACKER_MIN_YAW_TURN) && (fabs(estimatedRotation.y) < TRACKER_MAX_YAW_TURN) ) { if (estimatedRotation.y > 0.0f) { _bodyYawDelta += (estimatedRotation.y - TRACKER_MIN_YAW_TURN) * TRACKER_YAW_TURN_SENSITIVITY; } else { _bodyYawDelta += (estimatedRotation.y + TRACKER_MIN_YAW_TURN) * TRACKER_YAW_TURN_SENSITIVITY; } } } // Set the rotation of the avatar's head (as seen by others, not affecting view frustum) // to be scaled such that when the user's physical head is pointing at edge of screen, the // avatar head is at the edge of the in-world view frustum. So while a real person may move // their head only 30 degrees or so, this may correspond to a 90 degree field of view. // Note that roll is magnified by a constant because it is not related to field of view. Head* head = getHead(); if (inHmd || playing) { head->setDeltaPitch(estimatedRotation.x); head->setDeltaYaw(estimatedRotation.y); head->setDeltaRoll(estimatedRotation.z); } else { ViewFrustum viewFrustum; qApp->copyViewFrustum(viewFrustum); float magnifyFieldOfView = viewFrustum.getFieldOfView() / _realWorldFieldOfView.get(); head->setDeltaPitch(estimatedRotation.x * magnifyFieldOfView); head->setDeltaYaw(estimatedRotation.y * magnifyFieldOfView); head->setDeltaRoll(estimatedRotation.z); } } glm::vec3 MyAvatar::getLeftHandPosition() const { auto pose = getLeftHandControllerPoseInAvatarFrame(); return pose.isValid() ? pose.getTranslation() : glm::vec3(0.0f); } glm::vec3 MyAvatar::getRightHandPosition() const { auto pose = getRightHandControllerPoseInAvatarFrame(); return pose.isValid() ? pose.getTranslation() : glm::vec3(0.0f); } glm::vec3 MyAvatar::getLeftHandTipPosition() const { const float TIP_LENGTH = 0.3f; auto pose = getLeftHandControllerPoseInAvatarFrame(); return pose.isValid() ? pose.getTranslation() * pose.getRotation() + glm::vec3(0.0f, TIP_LENGTH, 0.0f) : glm::vec3(0.0f); } glm::vec3 MyAvatar::getRightHandTipPosition() const { const float TIP_LENGTH = 0.3f; auto pose = getRightHandControllerPoseInAvatarFrame(); return pose.isValid() ? pose.getTranslation() * pose.getRotation() + glm::vec3(0.0f, TIP_LENGTH, 0.0f) : glm::vec3(0.0f); } controller::Pose MyAvatar::getLeftHandPose() const { return getLeftHandControllerPoseInAvatarFrame(); } controller::Pose MyAvatar::getRightHandPose() const { return getRightHandControllerPoseInAvatarFrame(); } controller::Pose MyAvatar::getLeftHandTipPose() const { auto pose = getLeftHandControllerPoseInAvatarFrame(); glm::vec3 tipTrans = getLeftHandTipPosition(); pose.velocity += glm::cross(pose.getAngularVelocity(), pose.getTranslation() - tipTrans); pose.translation = tipTrans; return pose; } controller::Pose MyAvatar::getRightHandTipPose() const { auto pose = getRightHandControllerPoseInAvatarFrame(); glm::vec3 tipTrans = getRightHandTipPosition(); pose.velocity += glm::cross(pose.getAngularVelocity(), pose.getTranslation() - tipTrans); pose.translation = tipTrans; return pose; } // virtual void MyAvatar::render(RenderArgs* renderArgs, const glm::vec3& cameraPosition) { // don't render if we've been asked to disable local rendering if (!_shouldRender) { return; // exit early } Avatar::render(renderArgs, cameraPosition); } void MyAvatar::overrideAnimation(const QString& url, float fps, bool loop, float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "overrideAnimation", Q_ARG(const QString&, url), Q_ARG(float, fps), Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); return; } _rig->overrideAnimation(url, fps, loop, firstFrame, lastFrame); } void MyAvatar::restoreAnimation() { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "restoreAnimation"); return; } _rig->restoreAnimation(); } QStringList MyAvatar::getAnimationRoles() { if (QThread::currentThread() != thread()) { QStringList result; QMetaObject::invokeMethod(this, "getAnimationRoles", Qt::BlockingQueuedConnection, Q_RETURN_ARG(QStringList, result)); return result; } return _rig->getAnimationRoles(); } void MyAvatar::overrideRoleAnimation(const QString& role, const QString& url, float fps, bool loop, float firstFrame, float lastFrame) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "overrideRoleAnimation", Q_ARG(const QString&, role), Q_ARG(const QString&, url), Q_ARG(float, fps), Q_ARG(bool, loop), Q_ARG(float, firstFrame), Q_ARG(float, lastFrame)); return; } _rig->overrideRoleAnimation(role, url, fps, loop, firstFrame, lastFrame); } void MyAvatar::restoreRoleAnimation(const QString& role) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "restoreRoleAnimation", Q_ARG(const QString&, role)); return; } _rig->restoreRoleAnimation(role); } void MyAvatar::saveData() { Settings settings; settings.beginGroup("Avatar"); settings.setValue("headPitch", getHead()->getBasePitch()); settings.setValue("scale", _targetScale); settings.setValue("fullAvatarURL", _fullAvatarURLFromPreferences == AvatarData::defaultFullAvatarModelUrl() ? "" : _fullAvatarURLFromPreferences.toString()); settings.setValue("fullAvatarModelName", _fullAvatarModelName); QUrl animGraphUrl = _prefOverrideAnimGraphUrl.get(); settings.setValue("animGraphURL", animGraphUrl); settings.beginWriteArray("attachmentData"); for (int i = 0; i < _attachmentData.size(); i++) { settings.setArrayIndex(i); const AttachmentData& attachment = _attachmentData.at(i); settings.setValue("modelURL", attachment.modelURL); settings.setValue("jointName", attachment.jointName); settings.setValue("translation_x", attachment.translation.x); settings.setValue("translation_y", attachment.translation.y); settings.setValue("translation_z", attachment.translation.z); glm::vec3 eulers = safeEulerAngles(attachment.rotation); settings.setValue("rotation_x", eulers.x); settings.setValue("rotation_y", eulers.y); settings.setValue("rotation_z", eulers.z); settings.setValue("scale", attachment.scale); settings.setValue("isSoft", attachment.isSoft); } settings.endArray(); if (_avatarEntityData.size() == 0) { // HACK: manually remove empty 'avatarEntityData' else deleted avatarEntityData may show up in settings file settings.remove("avatarEntityData"); } settings.beginWriteArray("avatarEntityData"); int avatarEntityIndex = 0; auto hmdInterface = DependencyManager::get<HMDScriptingInterface>(); _avatarEntitiesLock.withReadLock([&] { for (auto entityID : _avatarEntityData.keys()) { if (hmdInterface->getCurrentTabletFrameID() == entityID) { // don't persist the tablet between domains / sessions continue; } settings.setArrayIndex(avatarEntityIndex); settings.setValue("id", entityID); settings.setValue("properties", _avatarEntityData.value(entityID)); avatarEntityIndex++; } }); settings.endArray(); settings.setValue("displayName", _displayName); settings.setValue("collisionSoundURL", _collisionSoundURL); settings.setValue("useSnapTurn", _useSnapTurn); settings.setValue("clearOverlayWhenMoving", _clearOverlayWhenMoving); settings.endGroup(); } float loadSetting(Settings& settings, const QString& name, float defaultValue) { float value = settings.value(name, defaultValue).toFloat(); if (glm::isnan(value)) { value = defaultValue; } return value; } void MyAvatar::setEnableDebugDrawDefaultPose(bool isEnabled) { _enableDebugDrawDefaultPose = isEnabled; if (!isEnabled) { AnimDebugDraw::getInstance().removeAbsolutePoses("myAvatarDefaultPoses"); } } void MyAvatar::setEnableDebugDrawAnimPose(bool isEnabled) { _enableDebugDrawAnimPose = isEnabled; if (!isEnabled) { AnimDebugDraw::getInstance().removeAbsolutePoses("myAvatarAnimPoses"); } } void MyAvatar::setEnableDebugDrawPosition(bool isEnabled) { if (isEnabled) { const glm::vec4 red(1.0f, 0.0f, 0.0f, 1.0f); DebugDraw::getInstance().addMyAvatarMarker("avatarPosition", glm::quat(), glm::vec3(), red); } else { DebugDraw::getInstance().removeMyAvatarMarker("avatarPosition"); } } void MyAvatar::setEnableDebugDrawHandControllers(bool isEnabled) { _enableDebugDrawHandControllers = isEnabled; if (!isEnabled) { DebugDraw::getInstance().removeMarker("leftHandController"); DebugDraw::getInstance().removeMarker("rightHandController"); } } void MyAvatar::setEnableDebugDrawSensorToWorldMatrix(bool isEnabled) { _enableDebugDrawSensorToWorldMatrix = isEnabled; if (!isEnabled) { DebugDraw::getInstance().removeMarker("sensorToWorldMatrix"); } } void MyAvatar::setEnableMeshVisible(bool isEnabled) { render::ScenePointer scene = qApp->getMain3DScene(); _skeletonModel->setVisibleInScene(isEnabled, scene); } void MyAvatar::setUseAnimPreAndPostRotations(bool isEnabled) { AnimClip::usePreAndPostPoseFromAnim = isEnabled; reset(true); } void MyAvatar::setEnableInverseKinematics(bool isEnabled) { _rig->setEnableInverseKinematics(isEnabled); } void MyAvatar::loadData() { Settings settings; settings.beginGroup("Avatar"); getHead()->setBasePitch(loadSetting(settings, "headPitch", 0.0f)); _targetScale = loadSetting(settings, "scale", 1.0f); setScale(glm::vec3(_targetScale)); _prefOverrideAnimGraphUrl.set(QUrl(settings.value("animGraphURL", "").toString())); _fullAvatarURLFromPreferences = settings.value("fullAvatarURL", AvatarData::defaultFullAvatarModelUrl()).toUrl(); _fullAvatarModelName = settings.value("fullAvatarModelName", DEFAULT_FULL_AVATAR_MODEL_NAME).toString(); useFullAvatarURL(_fullAvatarURLFromPreferences, _fullAvatarModelName); QVector<AttachmentData> attachmentData; int attachmentCount = settings.beginReadArray("attachmentData"); for (int i = 0; i < attachmentCount; i++) { settings.setArrayIndex(i); AttachmentData attachment; attachment.modelURL = settings.value("modelURL").toUrl(); attachment.jointName = settings.value("jointName").toString(); attachment.translation.x = loadSetting(settings, "translation_x", 0.0f); attachment.translation.y = loadSetting(settings, "translation_y", 0.0f); attachment.translation.z = loadSetting(settings, "translation_z", 0.0f); glm::vec3 eulers; eulers.x = loadSetting(settings, "rotation_x", 0.0f); eulers.y = loadSetting(settings, "rotation_y", 0.0f); eulers.z = loadSetting(settings, "rotation_z", 0.0f); attachment.rotation = glm::quat(eulers); attachment.scale = loadSetting(settings, "scale", 1.0f); attachment.isSoft = settings.value("isSoft").toBool(); attachmentData.append(attachment); } settings.endArray(); setAttachmentData(attachmentData); int avatarEntityCount = settings.beginReadArray("avatarEntityData"); for (int i = 0; i < avatarEntityCount; i++) { settings.setArrayIndex(i); QUuid entityID = settings.value("id").toUuid(); // QUuid entityID = QUuid::createUuid(); // generate a new ID QByteArray properties = settings.value("properties").toByteArray(); updateAvatarEntity(entityID, properties); } settings.endArray(); if (avatarEntityCount == 0) { // HACK: manually remove empty 'avatarEntityData' else legacy data may persist in settings file settings.remove("avatarEntityData"); } setAvatarEntityDataChanged(true); setDisplayName(settings.value("displayName").toString()); setCollisionSoundURL(settings.value("collisionSoundURL", DEFAULT_AVATAR_COLLISION_SOUND_URL).toString()); setSnapTurn(settings.value("useSnapTurn", _useSnapTurn).toBool()); setClearOverlayWhenMoving(settings.value("clearOverlayWhenMoving", _clearOverlayWhenMoving).toBool()); settings.endGroup(); setEnableMeshVisible(Menu::getInstance()->isOptionChecked(MenuOption::MeshVisible)); setEnableDebugDrawDefaultPose(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawDefaultPose)); setEnableDebugDrawAnimPose(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawAnimPose)); setEnableDebugDrawPosition(Menu::getInstance()->isOptionChecked(MenuOption::AnimDebugDrawPosition)); } void MyAvatar::saveAttachmentData(const AttachmentData& attachment) const { Settings settings; settings.beginGroup("savedAttachmentData"); settings.beginGroup(_skeletonModel->getURL().toString()); settings.beginGroup(attachment.modelURL.toString()); settings.setValue("jointName", attachment.jointName); settings.beginGroup(attachment.jointName); settings.setValue("translation_x", attachment.translation.x); settings.setValue("translation_y", attachment.translation.y); settings.setValue("translation_z", attachment.translation.z); glm::vec3 eulers = safeEulerAngles(attachment.rotation); settings.setValue("rotation_x", eulers.x); settings.setValue("rotation_y", eulers.y); settings.setValue("rotation_z", eulers.z); settings.setValue("scale", attachment.scale); settings.endGroup(); settings.endGroup(); settings.endGroup(); settings.endGroup(); } AttachmentData MyAvatar::loadAttachmentData(const QUrl& modelURL, const QString& jointName) const { Settings settings; settings.beginGroup("savedAttachmentData"); settings.beginGroup(_skeletonModel->getURL().toString()); settings.beginGroup(modelURL.toString()); AttachmentData attachment; attachment.modelURL = modelURL; if (jointName.isEmpty()) { attachment.jointName = settings.value("jointName").toString(); } else { attachment.jointName = jointName; } settings.beginGroup(attachment.jointName); if (settings.contains("translation_x")) { attachment.translation.x = loadSetting(settings, "translation_x", 0.0f); attachment.translation.y = loadSetting(settings, "translation_y", 0.0f); attachment.translation.z = loadSetting(settings, "translation_z", 0.0f); glm::vec3 eulers; eulers.x = loadSetting(settings, "rotation_x", 0.0f); eulers.y = loadSetting(settings, "rotation_y", 0.0f); eulers.z = loadSetting(settings, "rotation_z", 0.0f); attachment.rotation = glm::quat(eulers); attachment.scale = loadSetting(settings, "scale", 1.0f); } else { attachment = AttachmentData(); } settings.endGroup(); settings.endGroup(); settings.endGroup(); settings.endGroup(); return attachment; } int MyAvatar::parseDataFromBuffer(const QByteArray& buffer) { qCDebug(interfaceapp) << "Error: ignoring update packet for MyAvatar" << " packetLength = " << buffer.size(); // this packet is just bad, so we pretend that we unpacked it ALL return buffer.size(); } void MyAvatar::updateLookAtTargetAvatar() { // // Look at the avatar whose eyes are closest to the ray in direction of my avatar's head // And set the correctedLookAt for all (nearby) avatars that are looking at me. _lookAtTargetAvatar.reset(); _targetAvatarPosition = glm::vec3(0.0f); glm::vec3 lookForward = getHead()->getFinalOrientationInWorldFrame() * IDENTITY_FRONT; glm::vec3 cameraPosition = qApp->getCamera()->getPosition(); float smallestAngleTo = glm::radians(DEFAULT_FIELD_OF_VIEW_DEGREES) / 2.0f; const float KEEP_LOOKING_AT_CURRENT_ANGLE_FACTOR = 1.3f; const float GREATEST_LOOKING_AT_DISTANCE = 10.0f; AvatarHash hash = DependencyManager::get<AvatarManager>()->getHashCopy(); foreach (const AvatarSharedPointer& avatarPointer, hash) { auto avatar = static_pointer_cast<Avatar>(avatarPointer); bool isCurrentTarget = avatar->getIsLookAtTarget(); float distanceTo = glm::length(avatar->getHead()->getEyePosition() - cameraPosition); avatar->setIsLookAtTarget(false); if (!avatar->isMyAvatar() && avatar->isInitialized() && (distanceTo < GREATEST_LOOKING_AT_DISTANCE * getUniformScale())) { float radius = glm::length(avatar->getHead()->getEyePosition() - avatar->getHead()->getRightEyePosition()); float angleTo = coneSphereAngle(getHead()->getEyePosition(), lookForward, avatar->getHead()->getEyePosition(), radius); if (angleTo < (smallestAngleTo * (isCurrentTarget ? KEEP_LOOKING_AT_CURRENT_ANGLE_FACTOR : 1.0f))) { _lookAtTargetAvatar = avatarPointer; _targetAvatarPosition = avatarPointer->getPosition(); smallestAngleTo = angleTo; } if (isLookingAtMe(avatar)) { // Alter their gaze to look directly at my camera; this looks more natural than looking at my avatar's face. glm::vec3 lookAtPosition = avatar->getHead()->getLookAtPosition(); // A position, in world space, on my avatar. // The camera isn't at the point midway between the avatar eyes. (Even without an HMD, the head can be offset a bit.) // Let's get everything to world space: glm::vec3 avatarLeftEye = getHead()->getLeftEyePosition(); glm::vec3 avatarRightEye = getHead()->getRightEyePosition(); // First find out where (in world space) the person is looking relative to that bridge-of-the-avatar point. // (We will be adding that offset to the camera position, after making some other adjustments.) glm::vec3 gazeOffset = lookAtPosition - getHead()->getEyePosition(); ViewFrustum viewFrustum; qApp->copyViewFrustum(viewFrustum); // scale gazeOffset by IPD, if wearing an HMD. if (qApp->isHMDMode()) { glm::mat4 leftEye = qApp->getEyeOffset(Eye::Left); glm::mat4 rightEye = qApp->getEyeOffset(Eye::Right); glm::vec3 leftEyeHeadLocal = glm::vec3(leftEye[3]); glm::vec3 rightEyeHeadLocal = glm::vec3(rightEye[3]); glm::vec3 humanLeftEye = viewFrustum.getPosition() + (viewFrustum.getOrientation() * leftEyeHeadLocal); glm::vec3 humanRightEye = viewFrustum.getPosition() + (viewFrustum.getOrientation() * rightEyeHeadLocal); auto hmdInterface = DependencyManager::get<HMDScriptingInterface>(); float ipdScale = hmdInterface->getIPDScale(); // Scale by proportional differences between avatar and human. float humanEyeSeparationInModelSpace = glm::length(humanLeftEye - humanRightEye) * ipdScale; float avatarEyeSeparation = glm::length(avatarLeftEye - avatarRightEye); if (avatarEyeSeparation > 0.0f) { gazeOffset = gazeOffset * humanEyeSeparationInModelSpace / avatarEyeSeparation; } } // And now we can finally add that offset to the camera. glm::vec3 corrected = viewFrustum.getPosition() + gazeOffset; avatar->getHead()->setCorrectedLookAtPosition(corrected); } else { avatar->getHead()->clearCorrectedLookAtPosition(); } } else { avatar->getHead()->clearCorrectedLookAtPosition(); } } auto avatarPointer = _lookAtTargetAvatar.lock(); if (avatarPointer) { static_pointer_cast<Avatar>(avatarPointer)->setIsLookAtTarget(true); } } void MyAvatar::clearLookAtTargetAvatar() { _lookAtTargetAvatar.reset(); } eyeContactTarget MyAvatar::getEyeContactTarget() { return _eyeContactTarget; } glm::vec3 MyAvatar::getDefaultEyePosition() const { return getPosition() + getWorldAlignedOrientation() * Quaternions::Y_180 * _skeletonModel->getDefaultEyeModelPosition(); } const float SCRIPT_PRIORITY = 1.0f + 1.0f; const float RECORDER_PRIORITY = 1.0f + 1.0f; void MyAvatar::setJointRotations(QVector<glm::quat> jointRotations) { int numStates = glm::min(_skeletonModel->getJointStateCount(), jointRotations.size()); for (int i = 0; i < numStates; ++i) { // HACK: ATM only Recorder calls setJointRotations() so we hardcode its priority here _skeletonModel->setJointRotation(i, true, jointRotations[i], RECORDER_PRIORITY); } } void MyAvatar::setJointData(int index, const glm::quat& rotation, const glm::vec3& translation) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setJointData", Q_ARG(int, index), Q_ARG(const glm::quat&, rotation), Q_ARG(const glm::vec3&, translation)); return; } // HACK: ATM only JS scripts call setJointData() on MyAvatar so we hardcode the priority _rig->setJointState(index, true, rotation, translation, SCRIPT_PRIORITY); } void MyAvatar::setJointRotation(int index, const glm::quat& rotation) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setJointRotation", Q_ARG(int, index), Q_ARG(const glm::quat&, rotation)); return; } // HACK: ATM only JS scripts call setJointData() on MyAvatar so we hardcode the priority _rig->setJointRotation(index, true, rotation, SCRIPT_PRIORITY); } void MyAvatar::setJointTranslation(int index, const glm::vec3& translation) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setJointTranslation", Q_ARG(int, index), Q_ARG(const glm::vec3&, translation)); return; } // HACK: ATM only JS scripts call setJointData() on MyAvatar so we hardcode the priority _rig->setJointTranslation(index, true, translation, SCRIPT_PRIORITY); } void MyAvatar::clearJointData(int index) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "clearJointData", Q_ARG(int, index)); return; } _rig->clearJointAnimationPriority(index); } void MyAvatar::clearJointsData() { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "clearJointsData"); return; } _rig->clearJointStates(); } void MyAvatar::setSkeletonModelURL(const QUrl& skeletonModelURL) { Avatar::setSkeletonModelURL(skeletonModelURL); render::ScenePointer scene = qApp->getMain3DScene(); _skeletonModel->setVisibleInScene(true, scene); _headBoneSet.clear(); } void MyAvatar::resetFullAvatarURL() { auto lastAvatarURL = getFullAvatarURLFromPreferences(); auto lastAvatarName = getFullAvatarModelName(); useFullAvatarURL(QUrl()); useFullAvatarURL(lastAvatarURL, lastAvatarName); } void MyAvatar::useFullAvatarURL(const QUrl& fullAvatarURL, const QString& modelName) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "useFullAvatarURL", Qt::BlockingQueuedConnection, Q_ARG(const QUrl&, fullAvatarURL), Q_ARG(const QString&, modelName)); return; } if (_fullAvatarURLFromPreferences != fullAvatarURL) { _fullAvatarURLFromPreferences = fullAvatarURL; if (modelName.isEmpty()) { QVariantHash fullAvatarFST = FSTReader::downloadMapping(_fullAvatarURLFromPreferences.toString()); _fullAvatarModelName = fullAvatarFST["name"].toString(); } else { _fullAvatarModelName = modelName; } } const QString& urlString = fullAvatarURL.toString(); if (urlString.isEmpty() || (fullAvatarURL != getSkeletonModelURL())) { setSkeletonModelURL(fullAvatarURL); UserActivityLogger::getInstance().changedModel("skeleton", urlString); } _identityPacketExpiry = 0; // triggers an identity packet next update() } void MyAvatar::setAttachmentData(const QVector<AttachmentData>& attachmentData) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setAttachmentData", Qt::BlockingQueuedConnection, Q_ARG(const QVector<AttachmentData>, attachmentData)); return; } Avatar::setAttachmentData(attachmentData); } glm::vec3 MyAvatar::getSkeletonPosition() const { CameraMode mode = qApp->getCamera()->getMode(); if (mode == CAMERA_MODE_THIRD_PERSON || mode == CAMERA_MODE_INDEPENDENT) { // The avatar is rotated PI about the yAxis, so we have to correct for it // to get the skeleton offset contribution in the world-frame. const glm::quat FLIP = glm::angleAxis(PI, glm::vec3(0.0f, 1.0f, 0.0f)); return getPosition() + getOrientation() * FLIP * _skeletonOffset; } return Avatar::getPosition(); } void MyAvatar::rebuildCollisionShape() { // compute localAABox float scale = getUniformScale(); float radius = scale * _skeletonModel->getBoundingCapsuleRadius(); float height = scale * _skeletonModel->getBoundingCapsuleHeight() + 2.0f * radius; glm::vec3 corner(-radius, -0.5f * height, -radius); corner += scale * _skeletonModel->getBoundingCapsuleOffset(); glm::vec3 diagonal(2.0f * radius, height, 2.0f * radius); _characterController.setLocalBoundingBox(corner, diagonal); } static controller::Pose applyLowVelocityFilter(const controller::Pose& oldPose, const controller::Pose& newPose) { controller::Pose finalPose = newPose; if (newPose.isValid()) { // Use a velocity sensitive filter to damp small motions and preserve large ones with // no latency. float velocityFilter = glm::clamp(1.0f - glm::length(oldPose.getVelocity()), 0.0f, 1.0f); finalPose.translation = oldPose.getTranslation() * velocityFilter + newPose.getTranslation() * (1.0f - velocityFilter); finalPose.rotation = safeMix(oldPose.getRotation(), newPose.getRotation(), 1.0f - velocityFilter); } return finalPose; } void MyAvatar::setHandControllerPosesInSensorFrame(const controller::Pose& left, const controller::Pose& right) { if (controller::InputDevice::getLowVelocityFilter()) { auto oldLeftPose = getLeftHandControllerPoseInSensorFrame(); auto oldRightPose = getRightHandControllerPoseInSensorFrame(); _leftHandControllerPoseInSensorFrameCache.set(applyLowVelocityFilter(oldLeftPose, left)); _rightHandControllerPoseInSensorFrameCache.set(applyLowVelocityFilter(oldRightPose, right)); } else { _leftHandControllerPoseInSensorFrameCache.set(left); _rightHandControllerPoseInSensorFrameCache.set(right); } } controller::Pose MyAvatar::getLeftHandControllerPoseInSensorFrame() const { return _leftHandControllerPoseInSensorFrameCache.get(); } controller::Pose MyAvatar::getRightHandControllerPoseInSensorFrame() const { return _rightHandControllerPoseInSensorFrameCache.get(); } controller::Pose MyAvatar::getLeftHandControllerPoseInWorldFrame() const { return _leftHandControllerPoseInSensorFrameCache.get().transform(getSensorToWorldMatrix()); } controller::Pose MyAvatar::getRightHandControllerPoseInWorldFrame() const { return _rightHandControllerPoseInSensorFrameCache.get().transform(getSensorToWorldMatrix()); } controller::Pose MyAvatar::getLeftHandControllerPoseInAvatarFrame() const { glm::mat4 invAvatarMatrix = glm::inverse(createMatFromQuatAndPos(getOrientation(), getPosition())); return getLeftHandControllerPoseInWorldFrame().transform(invAvatarMatrix); } controller::Pose MyAvatar::getRightHandControllerPoseInAvatarFrame() const { glm::mat4 invAvatarMatrix = glm::inverse(createMatFromQuatAndPos(getOrientation(), getPosition())); return getRightHandControllerPoseInWorldFrame().transform(invAvatarMatrix); } void MyAvatar::updateMotors() { _characterController.clearMotors(); glm::quat motorRotation; if (_motionBehaviors & AVATAR_MOTION_ACTION_MOTOR_ENABLED) { if (_characterController.getState() == CharacterController::State::Hover) { motorRotation = getHead()->getCameraOrientation(); } else { // non-hovering = walking: follow camera twist about vertical but not lift // so we decompose camera's rotation and store the twist part in motorRotation glm::quat liftRotation; swingTwistDecomposition(getHead()->getCameraOrientation(), _worldUpDirection, liftRotation, motorRotation); } const float DEFAULT_MOTOR_TIMESCALE = 0.2f; const float INVALID_MOTOR_TIMESCALE = 1.0e6f; if (_isPushing || _isBraking || !_isBeingPushed) { _characterController.addMotor(_actionMotorVelocity, motorRotation, DEFAULT_MOTOR_TIMESCALE, INVALID_MOTOR_TIMESCALE); } else { // _isBeingPushed must be true --> disable action motor by giving it a long timescale, // otherwise it's attempt to "stand in in place" could defeat scripted motor/thrusts _characterController.addMotor(_actionMotorVelocity, motorRotation, INVALID_MOTOR_TIMESCALE); } } if (_motionBehaviors & AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED) { if (_scriptedMotorFrame == SCRIPTED_MOTOR_CAMERA_FRAME) { motorRotation = getHead()->getCameraOrientation() * glm::angleAxis(PI, Vectors::UNIT_Y); } else if (_scriptedMotorFrame == SCRIPTED_MOTOR_AVATAR_FRAME) { motorRotation = getOrientation() * glm::angleAxis(PI, Vectors::UNIT_Y); } else { // world-frame motorRotation = glm::quat(); } _characterController.addMotor(_scriptedMotorVelocity, motorRotation, _scriptedMotorTimescale); } // legacy support for 'MyAvatar::applyThrust()', which has always been implemented as a // short-lived linearAcceleration _characterController.setLinearAcceleration(_thrust); _thrust = Vectors::ZERO; } void MyAvatar::prepareForPhysicsSimulation() { relayDriveKeysToCharacterController(); updateMotors(); bool success; glm::vec3 parentVelocity = getParentVelocity(success); if (!success) { qDebug() << "Warning: getParentVelocity failed" << getID(); parentVelocity = glm::vec3(); } _characterController.setParentVelocity(parentVelocity); _characterController.setPositionAndOrientation(getPosition(), getOrientation()); if (qApp->isHMDMode()) { _follow.prePhysicsUpdate(*this, deriveBodyFromHMDSensor(), _bodySensorMatrix, hasDriveInput()); } else { _follow.deactivate(); } _prePhysicsRoomPose = AnimPose(_sensorToWorldMatrix); } void MyAvatar::harvestResultsFromPhysicsSimulation(float deltaTime) { glm::vec3 position = getPosition(); glm::quat orientation = getOrientation(); if (_characterController.isEnabledAndReady()) { _characterController.getPositionAndOrientation(position, orientation); } nextAttitude(position, orientation); _bodySensorMatrix = _follow.postPhysicsUpdate(*this, _bodySensorMatrix); if (_characterController.isEnabledAndReady()) { setVelocity(_characterController.getLinearVelocity() + _characterController.getFollowVelocity()); } else { setVelocity(getVelocity() + _characterController.getFollowVelocity()); } } QString MyAvatar::getScriptedMotorFrame() const { QString frame = "avatar"; if (_scriptedMotorFrame == SCRIPTED_MOTOR_CAMERA_FRAME) { frame = "camera"; } else if (_scriptedMotorFrame == SCRIPTED_MOTOR_WORLD_FRAME) { frame = "world"; } return frame; } void MyAvatar::setScriptedMotorVelocity(const glm::vec3& velocity) { float MAX_SCRIPTED_MOTOR_SPEED = 500.0f; _scriptedMotorVelocity = velocity; float speed = glm::length(_scriptedMotorVelocity); if (speed > MAX_SCRIPTED_MOTOR_SPEED) { _scriptedMotorVelocity *= MAX_SCRIPTED_MOTOR_SPEED / speed; } } void MyAvatar::setScriptedMotorTimescale(float timescale) { // we clamp the timescale on the large side (instead of just the low side) to prevent // obnoxiously large values from introducing NaN into avatar's velocity _scriptedMotorTimescale = glm::clamp(timescale, MIN_SCRIPTED_MOTOR_TIMESCALE, DEFAULT_SCRIPTED_MOTOR_TIMESCALE); } void MyAvatar::setScriptedMotorFrame(QString frame) { if (frame.toLower() == "camera") { _scriptedMotorFrame = SCRIPTED_MOTOR_CAMERA_FRAME; } else if (frame.toLower() == "avatar") { _scriptedMotorFrame = SCRIPTED_MOTOR_AVATAR_FRAME; } else if (frame.toLower() == "world") { _scriptedMotorFrame = SCRIPTED_MOTOR_WORLD_FRAME; } } void MyAvatar::clearScriptableSettings() { _scriptedMotorVelocity = Vectors::ZERO; _scriptedMotorTimescale = DEFAULT_SCRIPTED_MOTOR_TIMESCALE; } void MyAvatar::setCollisionSoundURL(const QString& url) { if (url != _collisionSoundURL) { _collisionSoundURL = url; emit newCollisionSoundURL(QUrl(_collisionSoundURL)); } } SharedSoundPointer MyAvatar::getCollisionSound() { if (!_collisionSound) { _collisionSound = DependencyManager::get<SoundCache>()->getSound(_collisionSoundURL); } return _collisionSound; } void MyAvatar::attach(const QString& modelURL, const QString& jointName, const glm::vec3& translation, const glm::quat& rotation, float scale, bool isSoft, bool allowDuplicates, bool useSaved) { if (QThread::currentThread() != thread()) { Avatar::attach(modelURL, jointName, translation, rotation, scale, isSoft, allowDuplicates, useSaved); return; } if (useSaved) { AttachmentData attachment = loadAttachmentData(modelURL, jointName); if (attachment.isValid()) { Avatar::attach(modelURL, attachment.jointName, attachment.translation, attachment.rotation, attachment.scale, attachment.isSoft, allowDuplicates, useSaved); return; } } Avatar::attach(modelURL, jointName, translation, rotation, scale, isSoft, allowDuplicates, useSaved); } void MyAvatar::setVisibleInSceneIfReady(Model* model, render::ScenePointer scene, bool visible) { if (model->isActive() && model->isRenderable()) { model->setVisibleInScene(visible, scene); } } void MyAvatar::initHeadBones() { int neckJointIndex = -1; if (_skeletonModel->isLoaded()) { neckJointIndex = _skeletonModel->getFBXGeometry().neckJointIndex; } if (neckJointIndex == -1) { return; } _headBoneSet.clear(); std::queue<int> q; q.push(neckJointIndex); _headBoneSet.insert(neckJointIndex); // fbxJoints only hold links to parents not children, so we have to do a bit of extra work here. while (q.size() > 0) { int jointIndex = q.front(); for (int i = 0; i < _skeletonModel->getJointStateCount(); i++) { if (jointIndex == _skeletonModel->getParentJointIndex(i)) { _headBoneSet.insert(i); q.push(i); } } q.pop(); } } QUrl MyAvatar::getAnimGraphOverrideUrl() const { return _prefOverrideAnimGraphUrl.get(); } void MyAvatar::setAnimGraphOverrideUrl(QUrl value) { _prefOverrideAnimGraphUrl.set(value); if (!value.isEmpty()) { setAnimGraphUrl(value); } else { initAnimGraph(); } } QUrl MyAvatar::getAnimGraphUrl() const { return _currentAnimGraphUrl.get(); } void MyAvatar::setAnimGraphUrl(const QUrl& url) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setAnimGraphUrl", Q_ARG(QUrl, url)); return; } if (_currentAnimGraphUrl.get() == url) { return; } destroyAnimGraph(); _skeletonModel->reset(); // Why is this necessary? Without this, we crash in the next render. _currentAnimGraphUrl.set(url); _rig->initAnimGraph(url); _bodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. updateSensorToWorldMatrix(); // Uses updated position/orientation and _bodySensorMatrix changes } void MyAvatar::initAnimGraph() { QUrl graphUrl; if (!_prefOverrideAnimGraphUrl.get().isEmpty()) { graphUrl = _prefOverrideAnimGraphUrl.get(); } else if (!_fstAnimGraphOverrideUrl.isEmpty()) { graphUrl = _fstAnimGraphOverrideUrl; } else { graphUrl = QUrl::fromLocalFile(PathUtils::resourcesPath() + "avatar/avatar-animation.json"); } _rig->initAnimGraph(graphUrl); _currentAnimGraphUrl.set(graphUrl); _bodySensorMatrix = deriveBodyFromHMDSensor(); // Based on current cached HMD position/rotation.. updateSensorToWorldMatrix(); // Uses updated position/orientation and _bodySensorMatrix changes } void MyAvatar::destroyAnimGraph() { _rig->destroyAnimGraph(); } void MyAvatar::postUpdate(float deltaTime) { Avatar::postUpdate(deltaTime); render::ScenePointer scene = qApp->getMain3DScene(); if (_skeletonModel->initWhenReady(scene)) { initHeadBones(); _skeletonModel->setCauterizeBoneSet(_headBoneSet); _fstAnimGraphOverrideUrl = _skeletonModel->getGeometry()->getAnimGraphOverrideUrl(); initAnimGraph(); } if (_enableDebugDrawDefaultPose || _enableDebugDrawAnimPose) { auto animSkeleton = _rig->getAnimSkeleton(); // the rig is in the skeletonModel frame AnimPose xform(glm::vec3(1), _skeletonModel->getRotation(), _skeletonModel->getTranslation()); if (_enableDebugDrawDefaultPose && animSkeleton) { glm::vec4 gray(0.2f, 0.2f, 0.2f, 0.2f); AnimDebugDraw::getInstance().addAbsolutePoses("myAvatarDefaultPoses", animSkeleton, _rig->getAbsoluteDefaultPoses(), xform, gray); } if (_enableDebugDrawAnimPose && animSkeleton) { // build absolute AnimPoseVec from rig AnimPoseVec absPoses; absPoses.reserve(_rig->getJointStateCount()); for (int i = 0; i < _rig->getJointStateCount(); i++) { absPoses.push_back(AnimPose(_rig->getJointTransform(i))); } glm::vec4 cyan(0.1f, 0.6f, 0.6f, 1.0f); AnimDebugDraw::getInstance().addAbsolutePoses("myAvatarAnimPoses", animSkeleton, absPoses, xform, cyan); } } if (_enableDebugDrawHandControllers) { auto leftHandPose = getLeftHandControllerPoseInWorldFrame(); auto rightHandPose = getRightHandControllerPoseInWorldFrame(); if (leftHandPose.isValid()) { DebugDraw::getInstance().addMarker("leftHandController", leftHandPose.getRotation(), leftHandPose.getTranslation(), glm::vec4(1)); } else { DebugDraw::getInstance().removeMarker("leftHandController"); } if (rightHandPose.isValid()) { DebugDraw::getInstance().addMarker("rightHandController", rightHandPose.getRotation(), rightHandPose.getTranslation(), glm::vec4(1)); } else { DebugDraw::getInstance().removeMarker("rightHandController"); } } DebugDraw::getInstance().updateMyAvatarPos(getPosition()); DebugDraw::getInstance().updateMyAvatarRot(getOrientation()); AnimPose postUpdateRoomPose(_sensorToWorldMatrix); updateHoldActions(_prePhysicsRoomPose, postUpdateRoomPose); } void MyAvatar::preDisplaySide(RenderArgs* renderArgs) { // toggle using the cauterizedBones depending on where the camera is and the rendering pass type. const bool shouldDrawHead = shouldRenderHead(renderArgs); if (shouldDrawHead != _prevShouldDrawHead) { _skeletonModel->setEnableCauterization(!shouldDrawHead); } _prevShouldDrawHead = shouldDrawHead; } const float RENDER_HEAD_CUTOFF_DISTANCE = 0.3f; bool MyAvatar::cameraInsideHead() const { const glm::vec3 cameraPosition = qApp->getCamera()->getPosition(); return glm::length(cameraPosition - getHeadPosition()) < (RENDER_HEAD_CUTOFF_DISTANCE * getUniformScale()); } bool MyAvatar::shouldRenderHead(const RenderArgs* renderArgs) const { bool defaultMode = renderArgs->_renderMode == RenderArgs::DEFAULT_RENDER_MODE; bool firstPerson = qApp->getCamera()->getMode() == CAMERA_MODE_FIRST_PERSON; bool insideHead = cameraInsideHead(); return !defaultMode || !firstPerson || !insideHead; } void MyAvatar::updateOrientation(float deltaTime) { // Smoothly rotate body with arrow keys float targetSpeed = getDriveKey(YAW) * _yawSpeed; if (targetSpeed != 0.0f) { const float ROTATION_RAMP_TIMESCALE = 0.1f; float blend = deltaTime / ROTATION_RAMP_TIMESCALE; if (blend > 1.0f) { blend = 1.0f; } _bodyYawDelta = (1.0f - blend) * _bodyYawDelta + blend * targetSpeed; } else if (_bodyYawDelta != 0.0f) { // attenuate body rotation speed const float ROTATION_DECAY_TIMESCALE = 0.05f; float attenuation = 1.0f - deltaTime / ROTATION_DECAY_TIMESCALE; if (attenuation < 0.0f) { attenuation = 0.0f; } _bodyYawDelta *= attenuation; float MINIMUM_ROTATION_RATE = 2.0f; if (fabsf(_bodyYawDelta) < MINIMUM_ROTATION_RATE) { _bodyYawDelta = 0.0f; } } float totalBodyYaw = _bodyYawDelta * deltaTime; // Comfort Mode: If you press any of the left/right rotation drive keys or input, you'll // get an instantaneous 15 degree turn. If you keep holding the key down you'll get another // snap turn every half second. if (getDriveKey(STEP_YAW) != 0.0f) { totalBodyYaw += getDriveKey(STEP_YAW); } // use head/HMD orientation to turn while flying if (getCharacterController()->getState() == CharacterController::State::Hover) { // This is the direction the user desires to fly in. glm::vec3 desiredFacing = getHead()->getCameraOrientation() * Vectors::UNIT_Z; desiredFacing.y = 0.0f; // This is our reference frame, it is captured when the user begins to move. glm::vec3 referenceFacing = transformVectorFast(_sensorToWorldMatrix, _hoverReferenceCameraFacing); referenceFacing.y = 0.0f; referenceFacing = glm::normalize(referenceFacing); glm::vec3 referenceRight(referenceFacing.z, 0.0f, -referenceFacing.x); const float HOVER_FLY_ROTATION_PERIOD = 0.5f; float tau = glm::clamp(deltaTime / HOVER_FLY_ROTATION_PERIOD, 0.0f, 1.0f); // new facing is a linear interpolation between the desired and reference vectors. glm::vec3 newFacing = glm::normalize((1.0f - tau) * referenceFacing + tau * desiredFacing); // calcualte the signed delta yaw angle to apply so that we match our newFacing. float sign = copysignf(1.0f, glm::dot(desiredFacing, referenceRight)); float deltaAngle = sign * acosf(glm::clamp(glm::dot(referenceFacing, newFacing), -1.0f, 1.0f)); // speedFactor is 0 when we are at rest adn 1.0 when we are at max flying speed. const float MAX_FLYING_SPEED = 30.0f; float speedFactor = glm::min(glm::length(getVelocity()) / MAX_FLYING_SPEED, 1.0f); // apply our delta, but scale it by the speed factor, so we turn faster when we are flying faster. totalBodyYaw += (speedFactor * deltaAngle * (180.0f / PI)); } // update body orientation by movement inputs setOrientation(getOrientation() * glm::quat(glm::radians(glm::vec3(0.0f, totalBodyYaw, 0.0f)))); getHead()->setBasePitch(getHead()->getBasePitch() + getDriveKey(PITCH) * _pitchSpeed * deltaTime); if (qApp->isHMDMode()) { glm::quat orientation = glm::quat_cast(getSensorToWorldMatrix()) * getHMDSensorOrientation(); glm::quat bodyOrientation = getWorldBodyOrientation(); glm::quat localOrientation = glm::inverse(bodyOrientation) * orientation; // these angles will be in radians // ... so they need to be converted to degrees before we do math... glm::vec3 euler = glm::eulerAngles(localOrientation) * DEGREES_PER_RADIAN; Head* head = getHead(); head->setBaseYaw(YAW(euler)); head->setBasePitch(PITCH(euler)); head->setBaseRoll(ROLL(euler)); } } void MyAvatar::updateActionMotor(float deltaTime) { bool thrustIsPushing = (glm::length2(_thrust) > EPSILON); bool scriptedMotorIsPushing = (_motionBehaviors & AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED) && _scriptedMotorTimescale < MAX_CHARACTER_MOTOR_TIMESCALE; _isBeingPushed = thrustIsPushing || scriptedMotorIsPushing; if (_isPushing || _isBeingPushed) { // we don't want the motor to brake if a script is pushing the avatar around // (we assume the avatar is driving itself via script) _isBraking = false; } else { float speed = glm::length(_actionMotorVelocity); const float MIN_ACTION_BRAKE_SPEED = 0.1f; _isBraking = _wasPushing || (_isBraking && speed > MIN_ACTION_BRAKE_SPEED); } // compute action input glm::vec3 front = (getDriveKey(TRANSLATE_Z)) * IDENTITY_FRONT; glm::vec3 right = (getDriveKey(TRANSLATE_X)) * IDENTITY_RIGHT; glm::vec3 direction = front + right; CharacterController::State state = _characterController.getState(); if (state == CharacterController::State::Hover) { // we're flying --> support vertical motion glm::vec3 up = (getDriveKey(TRANSLATE_Y)) * IDENTITY_UP; direction += up; } _wasPushing = _isPushing; float directionLength = glm::length(direction); _isPushing = directionLength > EPSILON; // normalize direction if (_isPushing) { direction /= directionLength; } else { direction = Vectors::ZERO; } if (state == CharacterController::State::Hover) { // we're flying --> complex acceleration curve that builds on top of current motor speed and caps at some max speed float motorSpeed = glm::length(_actionMotorVelocity); float finalMaxMotorSpeed = getUniformScale() * MAX_ACTION_MOTOR_SPEED; float speedGrowthTimescale = 2.0f; float speedIncreaseFactor = 1.8f; motorSpeed *= 1.0f + glm::clamp(deltaTime / speedGrowthTimescale , 0.0f, 1.0f) * speedIncreaseFactor; const float maxBoostSpeed = getUniformScale() * MAX_BOOST_SPEED; if (_isPushing) { if (motorSpeed < maxBoostSpeed) { // an active action motor should never be slower than this float boostCoefficient = (maxBoostSpeed - motorSpeed) / maxBoostSpeed; motorSpeed += MIN_AVATAR_SPEED * boostCoefficient; } else if (motorSpeed > finalMaxMotorSpeed) { motorSpeed = finalMaxMotorSpeed; } } _actionMotorVelocity = motorSpeed * direction; } else { // we're interacting with a floor --> simple horizontal speed and exponential decay _actionMotorVelocity = MAX_WALKING_SPEED * direction; } float boomChange = getDriveKey(ZOOM); _boomLength += 2.0f * _boomLength * boomChange + boomChange * boomChange; _boomLength = glm::clamp<float>(_boomLength, ZOOM_MIN, ZOOM_MAX); } void MyAvatar::updatePosition(float deltaTime) { if (_motionBehaviors & AVATAR_MOTION_ACTION_MOTOR_ENABLED) { updateActionMotor(deltaTime); } vec3 velocity = getVelocity(); const float MOVING_SPEED_THRESHOLD_SQUARED = 0.0001f; // 0.01 m/s if (!_characterController.isEnabledAndReady()) { // _characterController is not in physics simulation but it can still compute its target velocity updateMotors(); _characterController.computeNewVelocity(deltaTime, velocity); float speed2 = glm::length2(velocity); if (speed2 > MIN_AVATAR_SPEED_SQUARED) { // update position ourselves applyPositionDelta(deltaTime * velocity); } measureMotionDerivatives(deltaTime); _moving = speed2 > MOVING_SPEED_THRESHOLD_SQUARED; } else { // physics physics simulation updated elsewhere float speed2 = glm::length2(velocity); _moving = speed2 > MOVING_SPEED_THRESHOLD_SQUARED; } // capture the head rotation, in sensor space, when the user first indicates they would like to move/fly. if (!_hoverReferenceCameraFacingIsCaptured && (fabs(getDriveKey(TRANSLATE_Z)) > 0.1f || fabs(getDriveKey(TRANSLATE_X)) > 0.1f)) { _hoverReferenceCameraFacingIsCaptured = true; // transform the camera facing vector into sensor space. _hoverReferenceCameraFacing = transformVectorFast(glm::inverse(_sensorToWorldMatrix), getHead()->getCameraOrientation() * Vectors::UNIT_Z); } else if (_hoverReferenceCameraFacingIsCaptured && (fabs(getDriveKey(TRANSLATE_Z)) <= 0.1f && fabs(getDriveKey(TRANSLATE_X)) <= 0.1f)) { _hoverReferenceCameraFacingIsCaptured = false; } } void MyAvatar::updateCollisionSound(const glm::vec3 &penetration, float deltaTime, float frequency) { // COLLISION SOUND API in Audio has been removed } bool findAvatarAvatarPenetration(const glm::vec3 positionA, float radiusA, float heightA, const glm::vec3 positionB, float radiusB, float heightB, glm::vec3& penetration) { glm::vec3 positionBA = positionB - positionA; float xzDistance = sqrt(positionBA.x * positionBA.x + positionBA.z * positionBA.z); if (xzDistance < (radiusA + radiusB)) { float yDistance = fabs(positionBA.y); float halfHeights = 0.5f * (heightA + heightB); if (yDistance < halfHeights) { // cylinders collide if (xzDistance > 0.0f) { positionBA.y = 0.0f; // note, penetration should point from A into B penetration = positionBA * ((radiusA + radiusB - xzDistance) / xzDistance); return true; } else { // exactly coaxial -- we'll return false for this case return false; } } else if (yDistance < halfHeights + radiusA + radiusB) { // caps collide if (positionBA.y < 0.0f) { // A is above B positionBA.y += halfHeights; float BA = glm::length(positionBA); penetration = positionBA * (radiusA + radiusB - BA) / BA; return true; } else { // A is below B positionBA.y -= halfHeights; float BA = glm::length(positionBA); penetration = positionBA * (radiusA + radiusB - BA) / BA; return true; } } } return false; } // There can be a separation between the _targetScale and the actual scale of the rendered avatar in a domain. // When the avatar enters a domain where their target scale is not allowed according to the min/max // we do not change their saved target scale. Instead, we use getDomainLimitedScale() to render the avatar // at a domain appropriate size. When the avatar leaves the limiting domain, we'll return them to their previous target scale. // While connected to a domain that limits avatar scale if the user manually changes their avatar scale, we change // target scale to match the new scale they have chosen. When they leave the domain they will not return to the scale they were // before they entered the limiting domain. void MyAvatar::clampTargetScaleToDomainLimits() { // when we're about to change the target scale because the user has asked to increase or decrease their scale, // we first make sure that we're starting from a target scale that is allowed by the current domain auto clampedTargetScale = glm::clamp(_targetScale, _domainMinimumScale, _domainMaximumScale); if (clampedTargetScale != _targetScale) { qCDebug(interfaceapp, "Clamped scale to %f since original target scale %f was not allowed by domain", (double)clampedTargetScale, (double)_targetScale); setTargetScale(clampedTargetScale); } } void MyAvatar::clampScaleChangeToDomainLimits(float desiredScale) { auto clampedTargetScale = glm::clamp(desiredScale, _domainMinimumScale, _domainMaximumScale); if (clampedTargetScale != desiredScale) { qCDebug(interfaceapp, "Forcing scale to %f since %f is not allowed by domain", clampedTargetScale, desiredScale); } setTargetScale(clampedTargetScale); qCDebug(interfaceapp, "Changed scale to %f", (double)_targetScale); } void MyAvatar::increaseSize() { // make sure we're starting from an allowable scale clampTargetScaleToDomainLimits(); // calculate what our new scale should be float updatedTargetScale = _targetScale * (1.0f + SCALING_RATIO); // attempt to change to desired scale (clamped to the domain limits) clampScaleChangeToDomainLimits(updatedTargetScale); } void MyAvatar::decreaseSize() { // make sure we're starting from an allowable scale clampTargetScaleToDomainLimits(); // calculate what our new scale should be float updatedTargetScale = _targetScale * (1.0f - SCALING_RATIO); // attempt to change to desired scale (clamped to the domain limits) clampScaleChangeToDomainLimits(updatedTargetScale); } void MyAvatar::resetSize() { // attempt to reset avatar size to the default (clamped to domain limits) const float DEFAULT_AVATAR_SCALE = 1.0f; clampScaleChangeToDomainLimits(DEFAULT_AVATAR_SCALE); } void MyAvatar::restrictScaleFromDomainSettings(const QJsonObject& domainSettingsObject) { // pull out the minimum and maximum scale and set them to restrict our scale static const QString AVATAR_SETTINGS_KEY = "avatars"; auto avatarsObject = domainSettingsObject[AVATAR_SETTINGS_KEY].toObject(); static const QString MIN_SCALE_OPTION = "min_avatar_scale"; float settingMinScale = avatarsObject[MIN_SCALE_OPTION].toDouble(MIN_AVATAR_SCALE); setDomainMinimumScale(settingMinScale); static const QString MAX_SCALE_OPTION = "max_avatar_scale"; float settingMaxScale = avatarsObject[MAX_SCALE_OPTION].toDouble(MAX_AVATAR_SCALE); setDomainMaximumScale(settingMaxScale); // make sure that the domain owner didn't flip min and max if (_domainMinimumScale > _domainMaximumScale) { std::swap(_domainMinimumScale, _domainMaximumScale); } qCDebug(interfaceapp, "This domain requires a minimum avatar scale of %f and a maximum avatar scale of %f", (double)_domainMinimumScale, (double)_domainMaximumScale); // debug to log if this avatar's scale in this domain will be clamped auto clampedScale = glm::clamp(_targetScale, _domainMinimumScale, _domainMaximumScale); if (_targetScale != clampedScale) { qCDebug(interfaceapp, "Avatar scale will be clamped to %f because %f is not allowed by current domain", (double)clampedScale, (double)_targetScale); } } void MyAvatar::clearScaleRestriction() { _domainMinimumScale = MIN_AVATAR_SCALE; _domainMaximumScale = MAX_AVATAR_SCALE; } void MyAvatar::goToLocation(const QVariant& propertiesVar) { qCDebug(interfaceapp, "MyAvatar QML goToLocation"); auto properties = propertiesVar.toMap(); if (!properties.contains("position")) { qCWarning(interfaceapp, "goToLocation called without a position variable"); return; } bool validPosition; glm::vec3 v = vec3FromVariant(properties["position"], validPosition); if (!validPosition) { qCWarning(interfaceapp, "goToLocation called with invalid position variable"); return; } bool validOrientation = false; glm::quat q; if (properties.contains("orientation")) { q = quatFromVariant(properties["orientation"], validOrientation); if (!validOrientation) { glm::vec3 eulerOrientation = vec3FromVariant(properties["orientation"], validOrientation); q = glm::quat(eulerOrientation); if (!validOrientation) { qCWarning(interfaceapp, "goToLocation called with invalid orientation variable"); } } } if (validOrientation) { goToLocation(v, true, q); } else { goToLocation(v); } } void MyAvatar::goToLocation(const glm::vec3& newPosition, bool hasOrientation, const glm::quat& newOrientation, bool shouldFaceLocation) { qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - moving to " << newPosition.x << ", " << newPosition.y << ", " << newPosition.z; _goToPending = true; _goToPosition = newPosition; _goToOrientation = getOrientation(); if (hasOrientation) { qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - new orientation is " << newOrientation.x << ", " << newOrientation.y << ", " << newOrientation.z << ", " << newOrientation.w; // orient the user to face the target glm::quat quatOrientation = cancelOutRollAndPitch(newOrientation); if (shouldFaceLocation) { quatOrientation = newOrientation * glm::angleAxis(PI, Vectors::UP); // move the user a couple units away const float DISTANCE_TO_USER = 2.0f; _goToPosition = newPosition - quatOrientation * IDENTITY_FRONT * DISTANCE_TO_USER; } _goToOrientation = quatOrientation; } emit transformChanged(); } void MyAvatar::updateMotionBehaviorFromMenu() { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "updateMotionBehaviorFromMenu"); return; } Menu* menu = Menu::getInstance(); if (menu->isOptionChecked(MenuOption::ActionMotorControl)) { _motionBehaviors |= AVATAR_MOTION_ACTION_MOTOR_ENABLED; } else { _motionBehaviors &= ~AVATAR_MOTION_ACTION_MOTOR_ENABLED; } if (menu->isOptionChecked(MenuOption::ScriptedMotorControl)) { _motionBehaviors |= AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED; } else { _motionBehaviors &= ~AVATAR_MOTION_SCRIPTED_MOTOR_ENABLED; } setCharacterControllerEnabled(menu->isOptionChecked(MenuOption::EnableCharacterController)); } void MyAvatar::setCharacterControllerEnabled(bool enabled) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "setCharacterControllerEnabled", Q_ARG(bool, enabled)); return; } bool ghostingAllowed = true; auto entityTreeRenderer = qApp->getEntities(); if (entityTreeRenderer) { std::shared_ptr<ZoneEntityItem> zone = entityTreeRenderer->myAvatarZone(); if (zone) { ghostingAllowed = zone->getGhostingAllowed(); } } _characterController.setEnabled(ghostingAllowed ? enabled : true); } bool MyAvatar::getCharacterControllerEnabled() { return _characterController.isEnabled(); } void MyAvatar::clearDriveKeys() { _driveKeys.fill(0.0f); } void MyAvatar::setDriveKey(DriveKeys key, float val) { try { _driveKeys.at(key) = val; } catch (const std::exception&) { qCCritical(interfaceapp) << Q_FUNC_INFO << ": Index out of bounds"; } } float MyAvatar::getDriveKey(DriveKeys key) const { return isDriveKeyDisabled(key) ? 0.0f : getRawDriveKey(key); } float MyAvatar::getRawDriveKey(DriveKeys key) const { try { return _driveKeys.at(key); } catch (const std::exception&) { qCCritical(interfaceapp) << Q_FUNC_INFO << ": Index out of bounds"; return 0.0f; } } void MyAvatar::relayDriveKeysToCharacterController() { if (getDriveKey(TRANSLATE_Y) > 0.0f) { _characterController.jump(); } } void MyAvatar::disableDriveKey(DriveKeys key) { try { _disabledDriveKeys.set(key); } catch (const std::exception&) { qCCritical(interfaceapp) << Q_FUNC_INFO << ": Index out of bounds"; } } void MyAvatar::enableDriveKey(DriveKeys key) { try { _disabledDriveKeys.reset(key); } catch (const std::exception&) { qCCritical(interfaceapp) << Q_FUNC_INFO << ": Index out of bounds"; } } bool MyAvatar::isDriveKeyDisabled(DriveKeys key) const { try { return _disabledDriveKeys.test(key); } catch (const std::exception&) { qCCritical(interfaceapp) << Q_FUNC_INFO << ": Index out of bounds"; return true; } } glm::vec3 MyAvatar::getWorldBodyPosition() const { return transformPoint(_sensorToWorldMatrix, extractTranslation(_bodySensorMatrix)); } glm::quat MyAvatar::getWorldBodyOrientation() const { return glm::quat_cast(_sensorToWorldMatrix * _bodySensorMatrix); } // old school meat hook style glm::mat4 MyAvatar::deriveBodyFromHMDSensor() const { // HMD is in sensor space. const glm::vec3 hmdPosition = getHMDSensorPosition(); const glm::quat hmdOrientation = getHMDSensorOrientation(); const glm::quat hmdOrientationYawOnly = cancelOutRollAndPitch(hmdOrientation); // 2 meter tall dude (in rig coordinates) const glm::vec3 DEFAULT_RIG_MIDDLE_EYE_POS(0.0f, 0.9f, 0.0f); const glm::vec3 DEFAULT_RIG_NECK_POS(0.0f, 0.70f, 0.0f); const glm::vec3 DEFAULT_RIG_HIPS_POS(0.0f, 0.05f, 0.0f); int rightEyeIndex = _rig->indexOfJoint("RightEye"); int leftEyeIndex = _rig->indexOfJoint("LeftEye"); int neckIndex = _rig->indexOfJoint("Neck"); int hipsIndex = _rig->indexOfJoint("Hips"); glm::vec3 rigMiddleEyePos = DEFAULT_RIG_MIDDLE_EYE_POS; if (leftEyeIndex >= 0 && rightEyeIndex >= 0) { rigMiddleEyePos = (_rig->getAbsoluteDefaultPose(leftEyeIndex).trans() + _rig->getAbsoluteDefaultPose(rightEyeIndex).trans()) / 2.0f; } glm::vec3 rigNeckPos = neckIndex != -1 ? _rig->getAbsoluteDefaultPose(neckIndex).trans() : DEFAULT_RIG_NECK_POS; glm::vec3 rigHipsPos = hipsIndex != -1 ? _rig->getAbsoluteDefaultPose(hipsIndex).trans() : DEFAULT_RIG_HIPS_POS; glm::vec3 localEyes = (rigMiddleEyePos - rigHipsPos); glm::vec3 localNeck = (rigNeckPos - rigHipsPos); // apply simplistic head/neck model // figure out where the avatar body should be by applying offsets from the avatar's neck & head joints. // eyeToNeck offset is relative full HMD orientation. // while neckToRoot offset is only relative to HMDs yaw. // Y_180 is necessary because rig is z forward and hmdOrientation is -z forward glm::vec3 eyeToNeck = hmdOrientation * Quaternions::Y_180 * (localNeck - localEyes); glm::vec3 neckToRoot = hmdOrientationYawOnly * Quaternions::Y_180 * -localNeck; glm::vec3 bodyPos = hmdPosition + eyeToNeck + neckToRoot; return createMatFromQuatAndPos(hmdOrientationYawOnly, bodyPos); } glm::vec3 MyAvatar::getPositionForAudio() { switch (_audioListenerMode) { case AudioListenerMode::FROM_HEAD: return getHead()->getPosition(); case AudioListenerMode::FROM_CAMERA: return qApp->getCamera()->getPosition(); case AudioListenerMode::CUSTOM: return _customListenPosition; } return vec3(); } glm::quat MyAvatar::getOrientationForAudio() { switch (_audioListenerMode) { case AudioListenerMode::FROM_HEAD: return getHead()->getFinalOrientationInWorldFrame(); case AudioListenerMode::FROM_CAMERA: return qApp->getCamera()->getOrientation(); case AudioListenerMode::CUSTOM: return _customListenOrientation; } return quat(); } void MyAvatar::setAudioListenerMode(AudioListenerMode audioListenerMode) { if (_audioListenerMode != audioListenerMode) { _audioListenerMode = audioListenerMode; emit audioListenerModeChanged(); } } QScriptValue audioListenModeToScriptValue(QScriptEngine* engine, const AudioListenerMode& audioListenerMode) { return audioListenerMode; } void audioListenModeFromScriptValue(const QScriptValue& object, AudioListenerMode& audioListenerMode) { audioListenerMode = static_cast<AudioListenerMode>(object.toUInt16()); } QScriptValue driveKeysToScriptValue(QScriptEngine* engine, const MyAvatar::DriveKeys& driveKeys) { return driveKeys; } void driveKeysFromScriptValue(const QScriptValue& object, MyAvatar::DriveKeys& driveKeys) { driveKeys = static_cast<MyAvatar::DriveKeys>(object.toUInt16()); } void MyAvatar::lateUpdatePalms() { Avatar::updatePalms(); } static const float FOLLOW_TIME = 0.5f; MyAvatar::FollowHelper::FollowHelper() { deactivate(); } void MyAvatar::FollowHelper::deactivate() { for (int i = 0; i < NumFollowTypes; i++) { deactivate((FollowType)i); } } void MyAvatar::FollowHelper::deactivate(FollowType type) { assert(type >= 0 && type < NumFollowTypes); _timeRemaining[(int)type] = 0.0f; } void MyAvatar::FollowHelper::activate(FollowType type) { assert(type >= 0 && type < NumFollowTypes); // TODO: Perhaps, the follow time should be proportional to the displacement. _timeRemaining[(int)type] = FOLLOW_TIME; } bool MyAvatar::FollowHelper::isActive(FollowType type) const { assert(type >= 0 && type < NumFollowTypes); return _timeRemaining[(int)type] > 0.0f; } bool MyAvatar::FollowHelper::isActive() const { for (int i = 0; i < NumFollowTypes; i++) { if (isActive((FollowType)i)) { return true; } } return false; } float MyAvatar::FollowHelper::getMaxTimeRemaining() const { float max = 0.0f; for (int i = 0; i < NumFollowTypes; i++) { if (_timeRemaining[i] > max) { max = _timeRemaining[i]; } } return max; } void MyAvatar::FollowHelper::decrementTimeRemaining(float dt) { for (int i = 0; i < NumFollowTypes; i++) { _timeRemaining[i] -= dt; } } bool MyAvatar::FollowHelper::shouldActivateRotation(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { auto cameraMode = qApp->getCamera()->getMode(); if (cameraMode == CAMERA_MODE_THIRD_PERSON) { return false; } else { const float FOLLOW_ROTATION_THRESHOLD = cosf(PI / 6.0f); // 30 degrees glm::vec2 bodyFacing = getFacingDir2D(currentBodyMatrix); return glm::dot(myAvatar.getHMDSensorFacingMovingAverage(), bodyFacing) < FOLLOW_ROTATION_THRESHOLD; } } bool MyAvatar::FollowHelper::shouldActivateHorizontal(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { // -z axis of currentBodyMatrix in world space. glm::vec3 forward = glm::normalize(glm::vec3(-currentBodyMatrix[0][2], -currentBodyMatrix[1][2], -currentBodyMatrix[2][2])); // x axis of currentBodyMatrix in world space. glm::vec3 right = glm::normalize(glm::vec3(currentBodyMatrix[0][0], currentBodyMatrix[1][0], currentBodyMatrix[2][0])); glm::vec3 offset = extractTranslation(desiredBodyMatrix) - extractTranslation(currentBodyMatrix); float forwardLeanAmount = glm::dot(forward, offset); float lateralLeanAmount = glm::dot(right, offset); const float MAX_LATERAL_LEAN = 0.3f; const float MAX_FORWARD_LEAN = 0.15f; const float MAX_BACKWARD_LEAN = 0.1f; if (forwardLeanAmount > 0 && forwardLeanAmount > MAX_FORWARD_LEAN) { return true; } else if (forwardLeanAmount < 0 && forwardLeanAmount < -MAX_BACKWARD_LEAN) { return true; } return fabs(lateralLeanAmount) > MAX_LATERAL_LEAN; } bool MyAvatar::FollowHelper::shouldActivateVertical(const MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix) const { const float CYLINDER_TOP = 0.1f; const float CYLINDER_BOTTOM = -1.5f; glm::vec3 offset = extractTranslation(desiredBodyMatrix) - extractTranslation(currentBodyMatrix); return (offset.y > CYLINDER_TOP) || (offset.y < CYLINDER_BOTTOM); } void MyAvatar::FollowHelper::prePhysicsUpdate(MyAvatar& myAvatar, const glm::mat4& desiredBodyMatrix, const glm::mat4& currentBodyMatrix, bool hasDriveInput) { _desiredBodyMatrix = desiredBodyMatrix; if (myAvatar.getHMDLeanRecenterEnabled()) { if (!isActive(Rotation) && shouldActivateRotation(myAvatar, desiredBodyMatrix, currentBodyMatrix)) { activate(Rotation); } if (!isActive(Horizontal) && shouldActivateHorizontal(myAvatar, desiredBodyMatrix, currentBodyMatrix)) { activate(Horizontal); } if (!isActive(Vertical) && (shouldActivateVertical(myAvatar, desiredBodyMatrix, currentBodyMatrix) || hasDriveInput)) { activate(Vertical); } } glm::mat4 desiredWorldMatrix = myAvatar.getSensorToWorldMatrix() * _desiredBodyMatrix; glm::mat4 currentWorldMatrix = myAvatar.getSensorToWorldMatrix() * currentBodyMatrix; AnimPose followWorldPose(currentWorldMatrix); if (isActive(Rotation)) { followWorldPose.rot() = glmExtractRotation(desiredWorldMatrix); } if (isActive(Horizontal)) { glm::vec3 desiredTranslation = extractTranslation(desiredWorldMatrix); followWorldPose.trans().x = desiredTranslation.x; followWorldPose.trans().z = desiredTranslation.z; } if (isActive(Vertical)) { glm::vec3 desiredTranslation = extractTranslation(desiredWorldMatrix); followWorldPose.trans().y = desiredTranslation.y; } myAvatar.getCharacterController()->setFollowParameters(followWorldPose, getMaxTimeRemaining()); } glm::mat4 MyAvatar::FollowHelper::postPhysicsUpdate(const MyAvatar& myAvatar, const glm::mat4& currentBodyMatrix) { if (isActive()) { float dt = myAvatar.getCharacterController()->getFollowTime(); decrementTimeRemaining(dt); // apply follow displacement to the body matrix. glm::vec3 worldLinearDisplacement = myAvatar.getCharacterController()->getFollowLinearDisplacement(); glm::quat worldAngularDisplacement = myAvatar.getCharacterController()->getFollowAngularDisplacement(); glm::quat sensorToWorld = glmExtractRotation(myAvatar.getSensorToWorldMatrix()); glm::quat worldToSensor = glm::inverse(sensorToWorld); glm::vec3 sensorLinearDisplacement = worldToSensor * worldLinearDisplacement; glm::quat sensorAngularDisplacement = worldToSensor * worldAngularDisplacement * sensorToWorld; glm::mat4 newBodyMat = createMatFromQuatAndPos(sensorAngularDisplacement * glmExtractRotation(currentBodyMatrix), sensorLinearDisplacement + extractTranslation(currentBodyMatrix)); return newBodyMat; } else { return currentBodyMatrix; } } float MyAvatar::getAccelerationEnergy() { glm::vec3 velocity = getVelocity(); int changeInVelocity = abs(velocity.length() - priorVelocity.length()); float changeInEnergy = priorVelocity.length() * changeInVelocity * AVATAR_MOVEMENT_ENERGY_CONSTANT; priorVelocity = velocity; return changeInEnergy; } float MyAvatar::getEnergy() { return currentEnergy; } void MyAvatar::setEnergy(float value) { currentEnergy = value; } float MyAvatar::getAudioEnergy() { return getAudioLoudness() * AUDIO_ENERGY_CONSTANT; } bool MyAvatar::didTeleport() { glm::vec3 pos = getPosition(); glm::vec3 changeInPosition = pos - lastPosition; lastPosition = pos; return (changeInPosition.length() > MAX_AVATAR_MOVEMENT_PER_FRAME); } bool MyAvatar::hasDriveInput() const { return fabsf(getDriveKey(TRANSLATE_X)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Y)) > 0.0f || fabsf(getDriveKey(TRANSLATE_Z)) > 0.0f; } void MyAvatar::setAway(bool value) { _isAway = value; if (_isAway) { emit wentAway(); } else { emit wentActive(); } } // The resulting matrix is used to render the hand controllers, even if the camera is decoupled from the avatar. // Specificly, if we are rendering using a third person camera. We would like to render the hand controllers in front of the camera, // not in front of the avatar. glm::mat4 MyAvatar::computeCameraRelativeHandControllerMatrix(const glm::mat4& controllerSensorMatrix) const { // Fetch the current camera transform. glm::mat4 cameraWorldMatrix = qApp->getCamera()->getTransform(); if (qApp->getCamera()->getMode() == CAMERA_MODE_MIRROR) { cameraWorldMatrix *= createMatFromScaleQuatAndPos(vec3(-1.0f, 1.0f, 1.0f), glm::quat(), glm::vec3()); } // compute a NEW sensorToWorldMatrix for the camera. The equation is cameraWorldMatrix = cameraSensorToWorldMatrix * _hmdSensorMatrix. // here we solve for the unknown cameraSensorToWorldMatrix. glm::mat4 cameraSensorToWorldMatrix = cameraWorldMatrix * glm::inverse(_hmdSensorMatrix); // Using the new cameraSensorToWorldMatrix, compute where the controller is in world space. glm::mat4 controllerWorldMatrix = cameraSensorToWorldMatrix * controllerSensorMatrix; // move it into avatar space glm::mat4 avatarMatrix = createMatFromQuatAndPos(getOrientation(), getPosition()); return glm::inverse(avatarMatrix) * controllerWorldMatrix; } glm::quat MyAvatar::getAbsoluteJointRotationInObjectFrame(int index) const { if (index < 0) { index += numeric_limits<unsigned short>::max() + 1; // 65536 } switch (index) { case CONTROLLER_LEFTHAND_INDEX: { return getLeftHandControllerPoseInAvatarFrame().getRotation(); } case CONTROLLER_RIGHTHAND_INDEX: { return getRightHandControllerPoseInAvatarFrame().getRotation(); } case CAMERA_RELATIVE_CONTROLLER_LEFTHAND_INDEX: { auto pose = _leftHandControllerPoseInSensorFrameCache.get(); glm::mat4 controllerSensorMatrix = createMatFromQuatAndPos(pose.rotation, pose.translation); glm::mat4 result = computeCameraRelativeHandControllerMatrix(controllerSensorMatrix); return glmExtractRotation(result); } case CAMERA_RELATIVE_CONTROLLER_RIGHTHAND_INDEX: { auto pose = _rightHandControllerPoseInSensorFrameCache.get(); glm::mat4 controllerSensorMatrix = createMatFromQuatAndPos(pose.rotation, pose.translation); glm::mat4 result = computeCameraRelativeHandControllerMatrix(controllerSensorMatrix); return glmExtractRotation(result); } case CAMERA_MATRIX_INDEX: { bool success; Transform avatarTransform; Transform::mult(avatarTransform, getParentTransform(success), getLocalTransform()); glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix(); return glmExtractRotation(invAvatarMat * qApp->getCamera()->getTransform()); } default: { return Avatar::getAbsoluteJointRotationInObjectFrame(index); } } } glm::vec3 MyAvatar::getAbsoluteJointTranslationInObjectFrame(int index) const { if (index < 0) { index += numeric_limits<unsigned short>::max() + 1; // 65536 } switch (index) { case CONTROLLER_LEFTHAND_INDEX: { return getLeftHandControllerPoseInAvatarFrame().getTranslation(); } case CONTROLLER_RIGHTHAND_INDEX: { return getRightHandControllerPoseInAvatarFrame().getTranslation(); } case CAMERA_RELATIVE_CONTROLLER_LEFTHAND_INDEX: { auto pose = _leftHandControllerPoseInSensorFrameCache.get(); glm::mat4 controllerSensorMatrix = createMatFromQuatAndPos(pose.rotation, pose.translation); glm::mat4 result = computeCameraRelativeHandControllerMatrix(controllerSensorMatrix); return extractTranslation(result); } case CAMERA_RELATIVE_CONTROLLER_RIGHTHAND_INDEX: { auto pose = _rightHandControllerPoseInSensorFrameCache.get(); glm::mat4 controllerSensorMatrix = createMatFromQuatAndPos(pose.rotation, pose.translation); glm::mat4 result = computeCameraRelativeHandControllerMatrix(controllerSensorMatrix); return extractTranslation(result); } case CAMERA_MATRIX_INDEX: { bool success; Transform avatarTransform; Transform::mult(avatarTransform, getParentTransform(success), getLocalTransform()); glm::mat4 invAvatarMat = avatarTransform.getInverseMatrix(); return extractTranslation(invAvatarMat * qApp->getCamera()->getTransform()); } default: { return Avatar::getAbsoluteJointTranslationInObjectFrame(index); } } } bool MyAvatar::pinJoint(int index, const glm::vec3& position, const glm::quat& orientation) { auto hipsIndex = getJointIndex("Hips"); if (index != hipsIndex) { qWarning() << "Pinning is only supported for the hips joint at the moment."; return false; } slamPosition(position); setOrientation(orientation); _rig->setMaxHipsOffsetLength(0.05f); auto it = std::find(_pinnedJoints.begin(), _pinnedJoints.end(), index); if (it == _pinnedJoints.end()) { _pinnedJoints.push_back(index); } return true; } bool MyAvatar::clearPinOnJoint(int index) { auto it = std::find(_pinnedJoints.begin(), _pinnedJoints.end(), index); if (it != _pinnedJoints.end()) { _pinnedJoints.erase(it); auto hipsIndex = getJointIndex("Hips"); if (index == hipsIndex) { _rig->setMaxHipsOffsetLength(FLT_MAX); } return true; } return false; } float MyAvatar::getIKErrorOnLastSolve() const { return _rig->getIKErrorOnLastSolve(); } // thread-safe void MyAvatar::addHoldAction(AvatarActionHold* holdAction) { std::lock_guard<std::mutex> guard(_holdActionsMutex); _holdActions.push_back(holdAction); } // thread-safe void MyAvatar::removeHoldAction(AvatarActionHold* holdAction) { std::lock_guard<std::mutex> guard(_holdActionsMutex); auto iter = std::find(std::begin(_holdActions), std::end(_holdActions), holdAction); if (iter != std::end(_holdActions)) { _holdActions.erase(iter); } } void MyAvatar::updateHoldActions(const AnimPose& prePhysicsPose, const AnimPose& postUpdatePose) { auto entityTreeRenderer = qApp->getEntities(); EntityTreePointer entityTree = entityTreeRenderer ? entityTreeRenderer->getTree() : nullptr; if (entityTree) { // lateAvatarUpdate will modify entity position & orientation, so we need an entity write lock entityTree->withWriteLock([&] { // to prevent actions from adding or removing themselves from the _holdActions vector // while we are iterating, we need to enter a critical section. std::lock_guard<std::mutex> guard(_holdActionsMutex); for (auto& holdAction : _holdActions) { holdAction->lateAvatarUpdate(prePhysicsPose, postUpdatePose); } }); } }
40.279742
167
0.689014
trentpolack
b4110b5b9acf31ce7ea2d61b82540806dc7e077e
30,969
cc
C++
test/extensions/filters/http/grpc_json_transcoder/grpc_json_transcoder_integration_test.cc
guowendev/envoy
59c15a07ffe742c2101c3803b0f5909cb35a2afc
[ "Apache-2.0" ]
null
null
null
test/extensions/filters/http/grpc_json_transcoder/grpc_json_transcoder_integration_test.cc
guowendev/envoy
59c15a07ffe742c2101c3803b0f5909cb35a2afc
[ "Apache-2.0" ]
30
2022-02-17T02:28:37.000Z
2022-03-31T02:31:02.000Z
test/extensions/filters/http/grpc_json_transcoder/grpc_json_transcoder_integration_test.cc
cpakulski/envoy
8bbec6dc213fc99f181589cf6099aadacb2a8923
[ "Apache-2.0" ]
null
null
null
#include "common/grpc/codec.h" #include "common/grpc/common.h" #include "common/http/message_impl.h" #include "common/protobuf/protobuf.h" #include "test/integration/http_integration.h" #include "test/mocks/http/mocks.h" #include "test/proto/bookstore.pb.h" #include "test/test_common/utility.h" #include "absl/strings/match.h" #include "gtest/gtest.h" using Envoy::Protobuf::TextFormat; using Envoy::Protobuf::util::MessageDifferencer; using Envoy::ProtobufUtil::Status; using Envoy::ProtobufUtil::error::Code; using Envoy::ProtobufWkt::Empty; namespace Envoy { namespace { // A magic header value which marks header as not expected. constexpr char UnexpectedHeaderValue[] = "Unexpected header value"; class GrpcJsonTranscoderIntegrationTest : public testing::TestWithParam<Network::Address::IpVersion>, public HttpIntegrationTest { public: GrpcJsonTranscoderIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam()) {} /** * Global initializer for all integration tests. */ void SetUp() override { setUpstreamProtocol(FakeHttpConnection::Type::HTTP2); const std::string filter = R"EOF( name: envoy.grpc_json_transcoder config: proto_descriptor : "{}" services : "bookstore.Bookstore" )EOF"; config_helper_.addFilter( fmt::format(filter, TestEnvironment::runfilesPath("/test/proto/bookstore.descriptor"))); } /** * Global destructor for all integration tests. */ void TearDown() override { test_server_.reset(); fake_upstream_connection_.reset(); fake_upstreams_.clear(); } protected: template <class RequestType, class ResponseType> void testTranscoding(Http::HeaderMap&& request_headers, const std::string& request_body, const std::vector<std::string>& grpc_request_messages, const std::vector<std::string>& grpc_response_messages, const Status& grpc_status, Http::HeaderMap&& response_headers, const std::string& response_body, bool full_response = true) { codec_client_ = makeHttpConnection(lookupPort("http")); IntegrationStreamDecoderPtr response; if (!request_body.empty()) { auto encoder_decoder = codec_client_->startRequest(request_headers); request_encoder_ = &encoder_decoder.first; response = std::move(encoder_decoder.second); Buffer::OwnedImpl body(request_body); codec_client_->sendData(*request_encoder_, body, true); } else { response = codec_client_->makeHeaderOnlyRequest(request_headers); } ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_)); if (!grpc_request_messages.empty()) { ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_)); ASSERT_TRUE(upstream_request_->waitForEndStream(*dispatcher_)); Grpc::Decoder grpc_decoder; std::vector<Grpc::Frame> frames; EXPECT_TRUE(grpc_decoder.decode(upstream_request_->body(), frames)); EXPECT_EQ(grpc_request_messages.size(), frames.size()); for (size_t i = 0; i < grpc_request_messages.size(); ++i) { RequestType actual_message; if (frames[i].length_ > 0) { EXPECT_TRUE(actual_message.ParseFromString(frames[i].data_->toString())); } RequestType expected_message; EXPECT_TRUE(TextFormat::ParseFromString(grpc_request_messages[i], &expected_message)); EXPECT_TRUE(MessageDifferencer::Equivalent(expected_message, actual_message)); } Http::TestHeaderMapImpl response_headers; response_headers.insertStatus().value(200); response_headers.insertContentType().value(std::string("application/grpc")); if (grpc_response_messages.empty()) { response_headers.insertGrpcStatus().value(static_cast<uint64_t>(grpc_status.error_code())); response_headers.insertGrpcMessage().value(absl::string_view( grpc_status.error_message().data(), grpc_status.error_message().size())); upstream_request_->encodeHeaders(response_headers, true); } else { response_headers.addCopy(Http::LowerCaseString("trailer"), "Grpc-Status"); response_headers.addCopy(Http::LowerCaseString("trailer"), "Grpc-Message"); upstream_request_->encodeHeaders(response_headers, false); for (const auto& response_message_str : grpc_response_messages) { ResponseType response_message; EXPECT_TRUE(TextFormat::ParseFromString(response_message_str, &response_message)); auto buffer = Grpc::Common::serializeToGrpcFrame(response_message); upstream_request_->encodeData(*buffer, false); } Http::TestHeaderMapImpl response_trailers; response_trailers.insertGrpcStatus().value(static_cast<uint64_t>(grpc_status.error_code())); response_trailers.insertGrpcMessage().value(absl::string_view( grpc_status.error_message().data(), grpc_status.error_message().size())); upstream_request_->encodeTrailers(response_trailers); } EXPECT_TRUE(upstream_request_->complete()); } response->waitForEndStream(); EXPECT_TRUE(response->complete()); if (response->headers().get(Http::LowerCaseString("transfer-encoding")) == nullptr || !absl::StartsWith(response->headers() .get(Http::LowerCaseString("transfer-encoding")) ->value() .getStringView(), "chunked")) { EXPECT_EQ(response->headers().get(Http::LowerCaseString("trailer")), nullptr); } response_headers.iterate( [](const Http::HeaderEntry& entry, void* context) -> Http::HeaderMap::Iterate { auto* response = static_cast<IntegrationStreamDecoder*>(context); Http::LowerCaseString lower_key{std::string(entry.key().getStringView())}; if (entry.value() == UnexpectedHeaderValue) { EXPECT_FALSE(response->headers().get(lower_key)); } else { EXPECT_EQ(entry.value().getStringView(), response->headers().get(lower_key)->value().getStringView()); } return Http::HeaderMap::Iterate::Continue; }, response.get()); if (!response_body.empty()) { if (full_response) { EXPECT_EQ(response_body, response->body()); } else { EXPECT_TRUE(absl::StartsWith(response->body(), response_body)); } } codec_client_->close(); ASSERT_TRUE(fake_upstream_connection_->close()); ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect()); } }; INSTANTIATE_TEST_SUITE_P(IpVersions, GrpcJsonTranscoderIntegrationTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryPost) { HttpIntegrationTest::initialize(); testTranscoding<bookstore::CreateShelfRequest, bookstore::Shelf>( Http::TestHeaderMapImpl{{":method", "POST"}, {":path", "/shelf"}, {":authority", "host"}, {"content-type", "application/json"}}, R"({"theme": "Children"})", {R"(shelf { theme: "Children" })"}, {R"(id: 20 theme: "Children" )"}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}, {"content-length", "30"}, {"grpc-status", "0"}}, R"({"id":"20","theme":"Children"})"); } TEST_P(GrpcJsonTranscoderIntegrationTest, QueryParams) { HttpIntegrationTest::initialize(); // 1. Binding theme='Children' in CreateShelfRequest // Using the following HTTP template: // POST /shelves // body: shelf testTranscoding<bookstore::CreateShelfRequest, bookstore::Shelf>( Http::TestHeaderMapImpl{{":method", "POST"}, {":path", "/shelf?shelf.theme=Children"}, {":authority", "host"}, {"content-type", "application/json"}}, "", {R"(shelf { theme: "Children" })"}, {R"(id: 20 theme: "Children" )"}, Status(), Http::TestHeaderMapImpl{ {":status", "200"}, {"content-type", "application/json"}, }, R"({"id":"20","theme":"Children"})"); // 2. Binding theme='Children' and id='999' in CreateShelfRequest testTranscoding<bookstore::CreateShelfRequest, bookstore::Shelf>( Http::TestHeaderMapImpl{{":method", "POST"}, {":path", "/shelf?shelf.id=999&shelf.theme=Children"}, {":authority", "host"}, {"content-type", "application/json"}}, "", {R"(shelf { id: 999 theme: "Children" })"}, {R"(id: 999 theme: "Children" )"}, Status(), Http::TestHeaderMapImpl{ {":status", "200"}, {"content-type", "application/json"}, }, R"({"id":"999","theme":"Children"})"); // 3. Binding shelf=1, book=<post body> and book.title='War and Peace' in CreateBookRequest // Using the following HTTP template: // POST /shelves/{shelf}/books // body: book testTranscoding<bookstore::CreateBookRequest, bookstore::Book>( Http::TestHeaderMapImpl{{":method", "PUT"}, {":path", "/shelves/1/books?book.title=War%20and%20Peace"}, {":authority", "host"}}, R"({"author" : "Leo Tolstoy"})", {R"(shelf: 1 book { author: "Leo Tolstoy" title: "War and Peace" })"}, {R"(id: 3 author: "Leo Tolstoy" title: "War and Peace")"}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}}, R"({"id":"3","author":"Leo Tolstoy","title":"War and Peace"})"); // 4. Binding shelf=1, book.author='Leo Tolstoy' and book.title='War and Peace' in // CreateBookRequest // Using the following HTTP template: // POST /shelves/{shelf}/books // body: book testTranscoding<bookstore::CreateBookRequest, bookstore::Book>( Http::TestHeaderMapImpl{ {":method", "PUT"}, {":path", "/shelves/1/books?book.author=Leo%20Tolstoy&book.title=War%20and%20Peace"}, {":authority", "host"}}, "", {R"(shelf: 1 book { author: "Leo Tolstoy" title: "War and Peace" })"}, {R"(id: 3 author: "Leo Tolstoy" title: "War and Peace")"}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}}, R"({"id":"3","author":"Leo Tolstoy","title":"War and Peace"})"); // 5. Test URL decoding. testTranscoding<bookstore::CreateBookRequest, bookstore::Book>( Http::TestHeaderMapImpl{{":method", "PUT"}, {":path", "/shelves/1/books?book.title=War%20%26%20Peace"}, {":authority", "host"}}, R"({"author" : "Leo Tolstoy"})", {R"(shelf: 1 book { author: "Leo Tolstoy" title: "War & Peace" })"}, {R"(id: 3 author: "Leo Tolstoy" title: "War & Peace")"}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}}, R"({"id":"3","author":"Leo Tolstoy","title":"War & Peace"})"); // 6. Binding all book fields through query params. testTranscoding<bookstore::CreateBookRequest, bookstore::Book>( Http::TestHeaderMapImpl{ {":method", "PUT"}, {":path", "/shelves/1/books?book.id=999&book.author=Leo%20Tolstoy&book.title=War%20and%20Peace"}, {":authority", "host"}}, "", {R"(shelf: 1 book { id : 999 author: "Leo Tolstoy" title: "War and Peace" })"}, {R"(id: 999 author: "Leo Tolstoy" title: "War and Peace")"}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}}, R"({"id":"999","author":"Leo Tolstoy","title":"War and Peace"})"); // 7. Binding shelf=3, book=<post body> and the repeated field book.quote with // two values ("Winter is coming" and "Hold the door") in CreateBookRequest. // These values should be added to the repeated field in addition to what is // translated in the body. // Using the following HTTP template: // POST /shelves/{shelf}/books // body: book std::string reqBody = R"({"id":"999","author":"George R.R. Martin","title":"A Game of Thrones",)" R"("quotes":["A girl has no name","A very small man can cast a very large shadow"]})"; std::string grpcResp = R"(id : 999 author: "George R.R. Martin" title: "A Game of Thrones" quotes: "A girl has no name" quotes : "A very small man can cast a very large shadow" quotes: "Winter is coming" quotes : "Hold the door")"; std::string expectGrpcRequest = absl::StrCat("shelf: 1 book {", grpcResp, "}"); std::string respBody = R"({"id":"999","author":"George R.R. Martin","title":"A Game of Thrones","quotes":["A girl has no name")" R"(,"A very small man can cast a very large shadow","Winter is coming","Hold the door"]})"; testTranscoding<bookstore::CreateBookRequest, bookstore::Book>( Http::TestHeaderMapImpl{ {":method", "PUT"}, {":path", "/shelves/1/books?book.quotes=Winter%20is%20coming&book.quotes=Hold%20the%20door"}, {":authority", "host"}}, reqBody, {expectGrpcRequest}, {grpcResp}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}}, respBody); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryGet) { HttpIntegrationTest::initialize(); testTranscoding<Empty, bookstore::ListShelvesResponse>( Http::TestHeaderMapImpl{{":method", "GET"}, {":path", "/shelves"}, {":authority", "host"}}, "", {""}, {R"(shelves { id: 20 theme: "Children" } shelves { id: 1 theme: "Foo" } )"}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}, {"content-length", "69"}, {"grpc-status", "0"}}, R"({"shelves":[{"id":"20","theme":"Children"},{"id":"1","theme":"Foo"}]})"); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryGetHttpBody) { HttpIntegrationTest::initialize(); testTranscoding<Empty, google::api::HttpBody>( Http::TestHeaderMapImpl{{":method", "GET"}, {":path", "/index"}, {":authority", "host"}}, "", {""}, {R"(content_type: "text/html" data: "<h1>Hello!</h1>" )"}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "text/html"}, {"content-length", "15"}, {"grpc-status", "0"}}, R"(<h1>Hello!</h1>)"); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryGetError) { HttpIntegrationTest::initialize(); testTranscoding<bookstore::GetShelfRequest, bookstore::Shelf>( Http::TestHeaderMapImpl{ {":method", "GET"}, {":path", "/shelves/100?"}, {":authority", "host"}}, "", {"shelf: 100"}, {}, Status(Code::NOT_FOUND, "Shelf 100 Not Found"), Http::TestHeaderMapImpl{ {":status", "404"}, {"grpc-status", "5"}, {"grpc-message", "Shelf 100 Not Found"}}, ""); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryGetError1) { const std::string filter = R"EOF( name: envoy.grpc_json_transcoder config: proto_descriptor : "{}" services : "bookstore.Bookstore" ignore_unknown_query_parameters : true )EOF"; config_helper_.addFilter( fmt::format(filter, TestEnvironment::runfilesPath("/test/proto/bookstore.descriptor"))); HttpIntegrationTest::initialize(); testTranscoding<bookstore::GetShelfRequest, bookstore::Shelf>( Http::TestHeaderMapImpl{{":method", "GET"}, {":path", "/shelves/100?unknown=1&shelf=9999"}, {":authority", "host"}}, "", {"shelf: 9999"}, {}, Status(Code::NOT_FOUND, "Shelf 9999 Not Found"), Http::TestHeaderMapImpl{ {":status", "404"}, {"grpc-status", "5"}, {"grpc-message", "Shelf 9999 Not Found"}}, ""); } // Test an upstream that returns an error in a trailer-only response. TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryErrorConvertedToJson) { const std::string filter = R"EOF( name: envoy.grpc_json_transcoder config: proto_descriptor: "{}" services: "bookstore.Bookstore" convert_grpc_status: true )EOF"; config_helper_.addFilter( fmt::format(filter, TestEnvironment::runfilesPath("/test/proto/bookstore.descriptor"))); HttpIntegrationTest::initialize(); testTranscoding<bookstore::GetShelfRequest, bookstore::Shelf>( Http::TestHeaderMapImpl{ {":method", "GET"}, {":path", "/shelves/100"}, {":authority", "host"}}, "", {"shelf: 100"}, {}, Status(Code::NOT_FOUND, "Shelf 100 Not Found"), Http::TestHeaderMapImpl{{":status", "404"}, {"content-type", "application/json"}, {"grpc-status", UnexpectedHeaderValue}, {"grpc-message", UnexpectedHeaderValue}}, R"({"code":5,"message":"Shelf 100 Not Found"})"); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryDelete) { HttpIntegrationTest::initialize(); testTranscoding<bookstore::DeleteBookRequest, Empty>( Http::TestHeaderMapImpl{ {":method", "DELETE"}, {":path", "/shelves/456/books/123"}, {":authority", "host"}}, "", {"shelf: 456 book: 123"}, {""}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}, {"content-length", "2"}, {"grpc-status", "0"}}, "{}"); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryPatch) { HttpIntegrationTest::initialize(); testTranscoding<bookstore::UpdateBookRequest, bookstore::Book>( Http::TestHeaderMapImpl{ {":method", "PATCH"}, {":path", "/shelves/456/books/123"}, {":authority", "host"}}, R"({"author" : "Leo Tolstoy", "title" : "War and Peace"})", {R"(shelf: 456 book { id: 123 author: "Leo Tolstoy" title: "War and Peace" })"}, {R"(id: 123 author: "Leo Tolstoy" title: "War and Peace")"}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}, {"content-length", "59"}, {"grpc-status", "0"}}, R"({"id":"123","author":"Leo Tolstoy","title":"War and Peace"})"); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryCustom) { HttpIntegrationTest::initialize(); testTranscoding<bookstore::GetShelfRequest, Empty>( Http::TestHeaderMapImpl{ {":method", "OPTIONS"}, {":path", "/shelves/456"}, {":authority", "host"}}, "", {"shelf: 456"}, {""}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}, {"content-length", "2"}, {"grpc-status", "0"}}, "{}"); } TEST_P(GrpcJsonTranscoderIntegrationTest, BindingAndBody) { HttpIntegrationTest::initialize(); testTranscoding<bookstore::CreateBookRequest, bookstore::Book>( Http::TestHeaderMapImpl{ {":method", "PUT"}, {":path", "/shelves/1/books"}, {":authority", "host"}}, R"({"author" : "Leo Tolstoy", "title" : "War and Peace"})", {R"(shelf: 1 book { author: "Leo Tolstoy" title: "War and Peace" })"}, {R"(id: 3 author: "Leo Tolstoy" title: "War and Peace")"}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}}, R"({"id":"3","author":"Leo Tolstoy","title":"War and Peace"})"); } TEST_P(GrpcJsonTranscoderIntegrationTest, ServerStreamingGet) { HttpIntegrationTest::initialize(); // 1: Normal streaming get testTranscoding<bookstore::ListBooksRequest, bookstore::Book>( Http::TestHeaderMapImpl{ {":method", "GET"}, {":path", "/shelves/1/books"}, {":authority", "host"}}, "", {"shelf: 1"}, {R"(id: 1 author: "Neal Stephenson" title: "Readme")", R"(id: 2 author: "George R.R. Martin" title: "A Game of Thrones")"}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}}, R"([{"id":"1","author":"Neal Stephenson","title":"Readme"})" R"(,{"id":"2","author":"George R.R. Martin","title":"A Game of Thrones"}])"); // 2: Empty response (trailers only) from streaming backend. // Response type is a valid JSON, so content type should be application/json. // Regression test for github.com/envoyproxy/envoy#5011 testTranscoding<bookstore::ListBooksRequest, bookstore::Book>( Http::TestHeaderMapImpl{ {":method", "GET"}, {":path", "/shelves/2/books"}, {":authority", "host"}}, "", {"shelf: 2"}, {}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}}, "[]"); // 3: Empty response (trailers only) from streaming backend, with a gRPC error. testTranscoding<bookstore::ListBooksRequest, bookstore::Book>( Http::TestHeaderMapImpl{ {":method", "GET"}, {":path", "/shelves/37/books"}, {":authority", "host"}}, "", {"shelf: 37"}, {}, Status(Code::NOT_FOUND, "Shelf 37 not found"), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}}, "[]"); } TEST_P(GrpcJsonTranscoderIntegrationTest, StreamingPost) { HttpIntegrationTest::initialize(); testTranscoding<bookstore::CreateShelfRequest, bookstore::Shelf>( Http::TestHeaderMapImpl{ {":method", "POST"}, {":path", "/bulk/shelves"}, {":authority", "host"}}, R"([ { "theme" : "Classics" }, { "theme" : "Satire" }, { "theme" : "Russian" }, { "theme" : "Children" }, { "theme" : "Documentary" }, { "theme" : "Mystery" }, ])", {R"(shelf { theme: "Classics" })", R"(shelf { theme: "Satire" })", R"(shelf { theme: "Russian" })", R"(shelf { theme: "Children" })", R"(shelf { theme: "Documentary" })", R"(shelf { theme: "Mystery" })"}, {R"(id: 3 theme: "Classics")", R"(id: 4 theme: "Satire")", R"(id: 5 theme: "Russian")", R"(id: 6 theme: "Children")", R"(id: 7 theme: "Documentary")", R"(id: 8 theme: "Mystery")"}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}, {"transfer-encoding", "chunked"}}, R"([{"id":"3","theme":"Classics"})" R"(,{"id":"4","theme":"Satire"})" R"(,{"id":"5","theme":"Russian"})" R"(,{"id":"6","theme":"Children"})" R"(,{"id":"7","theme":"Documentary"})" R"(,{"id":"8","theme":"Mystery"}])"); } TEST_P(GrpcJsonTranscoderIntegrationTest, InvalidJson) { HttpIntegrationTest::initialize(); // Usually the response would be // "Unexpected token.\n" // "INVALID_JSON\n" // "^" // If Envoy does a short read of the upstream connection, it may only read part of the // string "INVALID_JSON". Envoy will note "Unexpected token [whatever substring is read] testTranscoding<bookstore::CreateShelfRequest, bookstore::Shelf>( Http::TestHeaderMapImpl{{":method", "POST"}, {":path", "/shelf"}, {":authority", "host"}}, R"(INVALID_JSON)", {}, {}, Status(), Http::TestHeaderMapImpl{{":status", "400"}, {"content-type", "text/plain"}}, "Unexpected token.\nI", false); testTranscoding<bookstore::CreateShelfRequest, bookstore::Shelf>( Http::TestHeaderMapImpl{{":method", "POST"}, {":path", "/shelf"}, {":authority", "host"}}, R"({ "theme" : "Children")", {}, {}, Status(), Http::TestHeaderMapImpl{{":status", "400"}, {"content-type", "text/plain"}}, "Unexpected end of string. Expected , or } after key:value pair.\n" "\n" "^"); // Usually the response would be // "Expected : between key:value pair.\n" // "{ \"theme\" \"Children\" }\n" // " ^"); // But as with INVALID_JSON Envoy may not read the full string from the upstream connection so may // generate its error based on a partial upstream response. testTranscoding<bookstore::CreateShelfRequest, bookstore::Shelf>( Http::TestHeaderMapImpl{{":method", "POST"}, {":path", "/shelf"}, {":authority", "host"}}, R"({ "theme" "Children" })", {}, {}, Status(), Http::TestHeaderMapImpl{{":status", "400"}, {"content-type", "text/plain"}}, "Expected : between key:value pair.\n", false); testTranscoding<bookstore::CreateShelfRequest, bookstore::Shelf>( Http::TestHeaderMapImpl{{":method", "POST"}, {":path", "/shelf"}, {":authority", "host"}}, R"({ "theme" : "Children" }EXTRA)", {}, {}, Status(), Http::TestHeaderMapImpl{{":status", "400"}, {"content-type", "text/plain"}}, "Parsing terminated before end of input.\n", false); } std::string createDeepJson(int level, bool valid) { std::string begin = R"({"k":)"; std::string deep_val = R"("v")"; std::string end = R"(})"; std::string json; for (int i = 0; i < level; ++i) { absl::StrAppend(&json, begin); } if (valid) { absl::StrAppend(&json, deep_val); } for (int i = 0; i < level; ++i) { absl::StrAppend(&json, end); } return json; } std::string jsonStrToPbStrucStr(std::string json) { Envoy::ProtobufWkt::Struct message; std::string structStr; TestUtility::loadFromJson(json, message); TextFormat::PrintToString(message, &structStr); return structStr; } TEST_P(GrpcJsonTranscoderIntegrationTest, DeepStruct) { HttpIntegrationTest::initialize(); // Due to the limit of protobuf util, we can only compare to level 32. std::string deepJson = createDeepJson(32, true); std::string deepProto = "content {" + jsonStrToPbStrucStr(deepJson) + "}"; testTranscoding<bookstore::EchoStructReqResp, bookstore::EchoStructReqResp>( Http::TestHeaderMapImpl{ {":method", "POST"}, {":path", "/echoStruct"}, {":authority", "host"}}, deepJson, {deepProto}, {deepProto}, Status(), Http::TestHeaderMapImpl{ {":status", "200"}, {"content-type", "application/json"}, {"grpc-status", "0"}}, R"({"content":)" + deepJson + R"(})"); // The valid deep struct is parsed successfully. // Since we didn't set the response, it return 503. // Response body is empty (not a valid JSON), so content type should be application/grpc. testTranscoding<bookstore::EchoStructReqResp, bookstore::EchoStructReqResp>( Http::TestHeaderMapImpl{ {":method", "POST"}, {":path", "/echoStruct"}, {":authority", "host"}}, createDeepJson(100, true), {}, {}, Status(), Http::TestHeaderMapImpl{{":status", "503"}, {"content-type", "application/grpc"}}, ""); // The invalid deep struct is detected. testTranscoding<bookstore::EchoStructReqResp, bookstore::EchoStructReqResp>( Http::TestHeaderMapImpl{ {":method", "POST"}, {":path", "/echoStruct"}, {":authority", "host"}}, createDeepJson(100, false), {}, {}, Status(), Http::TestHeaderMapImpl{{":status", "400"}, {"content-type", "text/plain"}}, "Unexpected token.\n", false); } std::string createLargeJson(int level) { std::shared_ptr<ProtobufWkt::Value> cur = std::make_shared<ProtobufWkt::Value>(); for (int i = 0; i < level - 1; ++i) { std::shared_ptr<ProtobufWkt::Value> next = std::make_shared<ProtobufWkt::Value>(); ProtobufWkt::Value val = ProtobufWkt::Value(); ProtobufWkt::Value left = ProtobufWkt::Value(*cur); ProtobufWkt::Value right = ProtobufWkt::Value(*cur); val.mutable_list_value()->add_values()->Swap(&left); val.mutable_list_value()->add_values()->Swap(&right); (*next->mutable_struct_value()->mutable_fields())["k"] = val; cur = next; } return MessageUtil::getJsonStringFromMessage(*cur, false, false); } TEST_P(GrpcJsonTranscoderIntegrationTest, LargeStruct) { HttpIntegrationTest::initialize(); // Create a 40kB json payload. std::string largeJson = createLargeJson(12); std::string largeProto = "content {" + jsonStrToPbStrucStr(largeJson) + "}"; testTranscoding<bookstore::EchoStructReqResp, bookstore::EchoStructReqResp>( Http::TestHeaderMapImpl{ {":method", "POST"}, {":path", "/echoStruct"}, {":authority", "host"}}, largeJson, {largeProto}, {largeProto}, Status(), Http::TestHeaderMapImpl{ {":status", "200"}, {"content-type", "application/json"}, {"grpc-status", "0"}}, R"({"content":)" + largeJson + R"(})"); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnknownField) { HttpIntegrationTest::initialize(); testTranscoding<bookstore::CreateShelfRequest, bookstore::Shelf>( Http::TestHeaderMapImpl{{":method", "POST"}, {":path", "/shelf"}, {":authority", "host"}, {"content-type", "application/json"}}, R"({"theme": "Children", "unknown1": "a", "unknown2" : {"a" : "b"}, "unknown3" : ["a", "b", "c"]})", {R"(shelf { theme: "Children" })"}, {R"(id: 20 theme: "Children" )"}, Status(), Http::TestHeaderMapImpl{{":status", "200"}, {"content-type", "application/json"}, {"content-length", "30"}, {"grpc-status", "0"}}, R"({"id":"20","theme":"Children"})"); } TEST_P(GrpcJsonTranscoderIntegrationTest, UTF8) { HttpIntegrationTest::initialize(); testTranscoding<bookstore::CreateShelfRequest, bookstore::Shelf>( Http::TestHeaderMapImpl{{":method", "POST"}, {":path", "/shelf"}, {":authority", "host"}, {"content-type", "application/json"}}, "{\"id\":\"20\",\"theme\":\"\xC2\xAE\"}", {"shelf {id : 20 theme: \"®\" }"}, {"id: 20 theme: \"\xC2\xAE\""}, Status(), Http::TestHeaderMapImpl{ {":status", "200"}, {"content-type", "application/json"}, {"grpc-status", "0"}}, R"({"id":"20","theme":"®"})"); testTranscoding<bookstore::CreateShelfRequest, bookstore::Shelf>( Http::TestHeaderMapImpl{{":method", "POST"}, {":path", "/shelf"}, {":authority", "host"}, {"content-type", "application/json"}}, "{\"id\":\"20\",\"theme\":\"\xC3\x28\"}", {}, {""}, Status(), Http::TestHeaderMapImpl{{":status", "400"}}, R"(Encountered non UTF-8 code points)", false); } } // namespace } // namespace Envoy
46.922727
111
0.597533
guowendev
b41171d4071a6577b8f894f025d471eda1cc5533
8,775
cpp
C++
DLLInterface/PluginDLL.cpp
basic4gl-guy/basic4gl
5d4da444d36cdd5e020062adb02373e3efb21303
[ "BSD-3-Clause" ]
1
2020-01-14T11:25:00.000Z
2020-01-14T11:25:00.000Z
DLLInterface/PluginDLL.cpp
basic4gl-guy/basic4gl
5d4da444d36cdd5e020062adb02373e3efb21303
[ "BSD-3-Clause" ]
null
null
null
DLLInterface/PluginDLL.cpp
basic4gl-guy/basic4gl
5d4da444d36cdd5e020062adb02373e3efb21303
[ "BSD-3-Clause" ]
null
null
null
//--------------------------------------------------------------------------- #pragma hdrstop #include "PluginDLL.h" #ifdef VM_STATE_STREAMING #include "streaming.h" #endif #include <windows.h> #define BASIC4GL_DLL_MIN_VERSION 3 // Minimum plugin version Basic4GL is compatible with. // (DJLinux's extensive plugin library is built with version 3, so maintaining backwards compatibility is important.) using namespace std; //--------------------------------------------------------------------------- #pragma package(smart_init) //////////////////////////////////////////////////////////////////////////////// // Helper functions bool LoadFileDetails(HINSTANCE dll, PluginDLLFile &details) { assert(dll != NULL); // Find query function DLL_Basic4GL_QueryFunction query = (DLL_Basic4GL_QueryFunction) GetProcAddress(dll, "Basic4GL_Query"); if (query == NULL) return false; // Query the DLL for details char detailStr[256]; memset(detailStr, 0, 256); details.version.major = 0; details.version.minor = 0; int version = query(detailStr, &details.version.major, &details.version.minor); details.description = detailStr; // Note: Calling code must calculate details.filename and details.loaded itself return version >= BASIC4GL_DLL_MIN_VERSION && version <= BASIC4GL_DLL_VERSION; } //////////////////////////////////////////////////////////////////////////////// // PluginDLL PluginDLL::PluginDLL(PluginDLLManager &_manager, std::string path, std::string _filename, bool isStandaloneExe) : PluginLibrary(_manager) { // Save filename filename = LowerCase(_filename); // Load DLL handle = (int) LoadLibrary((path + filename).c_str()); if (handle == NULL) return; // Query file details fileDetails.filename = filename; fileDetails.loaded = true; if (!LoadFileDetails((HINSTANCE) handle, fileDetails)) return; // Find Init function DLL_Basic4GL_InitFunction init = (DLL_Basic4GL_InitFunction) GetProcAddress((HINSTANCE) handle, "Basic4GL_Init"); if (init == NULL) return; // Call init function to get plugin interface plugin = init(); if (plugin == NULL) return; // Inform plugin it has been loaded. Let it register its functions. if (!plugin->Load(*static_cast<IDLL_Basic4GL_FunctionRegistry*>(this), isStandaloneExe)) return; CompleteFunction(); // DLL successfully initialised failed = false; } PluginDLL::~PluginDLL() { // Unload plugin first Unload(); // Unload DLL if (handle != NULL) FreeLibrary((HINSTANCE) handle); } std::string PluginDLL::Error() { if (handle == NULL) return "Could not load plugin DLL: " + filename; else if (plugin == NULL) return "Could not initialise plugin: " + filename; else return PluginLibrary::Error(); } bool PluginDLL::IsDLL() { return true; } std::string PluginDLL::Description() { return fileDetails.filename; } //////////////////////////////////////////////////////////////////////////////// // PluginDLLManager PluginDLLManager::PluginDLLManager(std::string _directory, bool _isStandaloneExe) : PluginManager(_isStandaloneExe), directory(_directory) { // Postfix a closing slash if necessary if (directory != "" && directory[directory.length() - 1] != '\\') directory += '\\'; } DLLFileVector PluginDLLManager::DLLFiles() { DLLFileVector result; // Scan directory for files std::string searchPath = directory + "*.dll"; WIN32_FIND_DATA seekData; HANDLE seekHandle = FindFirstFile(searchPath.c_str(), &seekData); if (seekHandle == INVALID_HANDLE_VALUE) return result; // Scan DLL files in directory and add to list bool foundFile = true; while (foundFile) { // Open the DLL and query it for details HINSTANCE dll = LoadLibrary((directory + seekData.cFileName).c_str()); if (dll != NULL) { // Query details from DLL PluginDLLFile details; details.filename = seekData.cFileName; details.loaded = IsLoaded(details.filename); if (LoadFileDetails(dll, details)) { // Add DLL file entries result.push_back(details); } // Unload the DLL FreeLibrary(dll); } // Find next DLL in directory foundFile = FindNextFile(seekHandle, &seekData); } // File search finished FindClose(seekHandle); return result; } PluginLibraryVector::iterator PluginDLLManager::FindItor(std::string filename) { // Search loaded DLLs for given filename std::string lcase = LowerCase(filename); for (PluginLibraryVector::iterator i = dlls.begin(); i != dlls.end(); i++) { // Filter to DLLs if ((*i)->IsDLL()) { PluginDLL *dll = static_cast<PluginDLL*>(*i); if (dll->Filename() == lcase) return i; } } return dlls.end(); } PluginDLL *PluginDLLManager::Find(std::string filename) { // Find itor PluginLibraryVector::iterator i = FindItor(filename); // Return DLL return i == dlls.end() ? NULL : static_cast<PluginDLL*>(*i); } bool PluginDLLManager::LoadDLL(std::string filename) { // Attempt to load DLL // First check that it's not already loaded if (IsLoaded(filename)) { error = "A plugin DLL by this name is already loaded"; return false; } // Load DLL PluginDLL *dll = new PluginDLL(*this, directory, filename, isStandaloneExe); if (dll->Failed()) { error = dll->Error(); delete dll; return false; } // Add to list dlls.push_back(dll); return true; } bool PluginDLLManager::UnloadDLL(std::string filename) { // Find DLL PluginLibraryVector::iterator i = FindItor(filename); if (i == dlls.end()) { error = "This plugin DLL is not loaded"; return false; } // Check that DLL can be unloaded. // If the DLL owns objects that are currently used by other DLLs, then it // cannot be unloaded before the other DLLs have been. PluginDLL* dll = static_cast<PluginDLL*>(*i); if (dll->IsReferenced()) { error = (std::string) "The following plugin DLL(s) must be unloaded first:\r\n" + dll->DescribeReferencingDLLs(); return false; } // Inform other DLLs that this one is being unloaded for (PluginLibraryVector::iterator j = dlls.begin(); j != dlls.end(); j++) if ((*i) != (*j) && (*j)->IsDLL()) static_cast<PluginDLL*>(*j)->RemoveReferencingDLL(dll); // Unregister all interfaces owned by this DLL std::map<std::string,PluginDLLSharedInterface>::iterator k = sharedInterfaces.begin(); while (k != sharedInterfaces.end()) { std::map<std::string,PluginDLLSharedInterface>::iterator current = k; k++; if (current->second.owner == *i) sharedInterfaces.erase(current); } // Unload it delete *i; // Remove it from our list dlls.erase(i); return true; } #ifdef VM_STATE_STREAMING void PluginDLLManager::StreamOut(std::ostream& stream) const { // Write DLL filenames, and versions WriteLong(stream, dlls.size()); for (int i = 0; i < dlls.size(); i++) { if (dlls[i]->IsDLL()) { PluginDLL* dll = static_cast<PluginDLL*>(dlls[i]); string filename = dll->FileDetails().filename; WriteString(stream, filename); WriteLong(stream, dll->FileDetails().version.major); WriteLong(stream, dll->FileDetails().version.minor); } } } bool PluginDLLManager::StreamIn(std::istream& stream) { // Clear out any existing plugins Clear(); int count = ReadLong(stream); for (int i = 0; i < count; i++) { // Read file details string filename = ReadString(stream); PluginVersion version; version.major = ReadLong(stream); version.minor = ReadLong(stream); // Attempt to load DLL if (!LoadDLL(filename)) return false; // Check version number PluginDLL *dll = Find(filename); if (!dll->FileDetails().version.Matches(version)) { error = "Plugin DLL " + filename + " is the wrong version.\r\n" + "Version is " + dll->FileDetails().version.VersionString() + ", expected " + version.VersionString(); return false; } } return true; } #endif const vector<PluginDLL*> PluginDLLManager::LoadedDLLs() { vector<PluginDLL*> result; for ( PluginLibraryVector::iterator i = dlls.begin(); i != dlls.end(); i++) { if ((*i)->IsDLL()) result.push_back(static_cast<PluginDLL*>(*i)); } return result; }
27.857143
128
0.607066
basic4gl-guy
b415e9a7298b93e130d7bfd7225442e1ef69108a
3,341
cpp
C++
src/cbag/layout/path_util.cpp
ayan-biswas/cbag
0d08394cf39e90bc3acb4a94fd7b5a6560cf103c
[ "BSD-3-Clause" ]
1
2020-01-07T04:44:17.000Z
2020-01-07T04:44:17.000Z
src/cbag/layout/path_util.cpp
skyworksinc/cbag
0d08394cf39e90bc3acb4a94fd7b5a6560cf103c
[ "BSD-3-Clause" ]
null
null
null
src/cbag/layout/path_util.cpp
skyworksinc/cbag
0d08394cf39e90bc3acb4a94fd7b5a6560cf103c
[ "BSD-3-Clause" ]
1
2020-01-07T04:45:13.000Z
2020-01-07T04:45:13.000Z
#include <fmt/core.h> #include <fmt/ostream.h> #include <cbag/layout/path_util.h> namespace cbag { namespace layout { void add_path_points(pt_vector &vec, coord_t x, coord_t y, const vector45 &p, const vector45 &n, bool is_45, end_style style, offset_t w_main, offset_t w_norm) { switch (style) { case end_style::truncate: { auto xw = n.dx * w_main; auto yw = n.dy * w_main; vec.emplace_back(cbag::point{x + xw, y + yw}); vec.emplace_back(cbag::point{x - xw, y - yw}); break; } case end_style::extend: vec.emplace_back(cbag::point{x - (p.dx - n.dx) * w_main, y - (p.dy - n.dy) * w_main}); vec.emplace_back(cbag::point{x - (p.dx + n.dx) * w_main, y - (p.dy + n.dy) * w_main}); break; case end_style::triangle: { auto xw = n.dx * w_main; auto yw = n.dy * w_main; vec.emplace_back(cbag::point{x + xw, y + yw}); vec.emplace_back(cbag::point{x - w_main * p.dx, y - w_main * p.dy}); vec.emplace_back(cbag::point{x - xw, y - yw}); break; } default: { auto xnm = n.dx * w_main; auto ynm = n.dy * w_main; auto xpm = p.dx * w_main; auto ypm = p.dy * w_main; auto xnn = n.dx * w_norm; auto ynn = n.dy * w_norm; auto xpn = p.dx * w_norm; auto ypn = p.dy * w_norm; vec.emplace_back(cbag::point{x - xpn + xnm, y - ypn + ynm}); vec.emplace_back(cbag::point{x - xpm + xnn, y - ypm + ynn}); vec.emplace_back(cbag::point{x - xpm - xnn, y - ypm - ynn}); vec.emplace_back(cbag::point{x - xpn - xnm, y - ypn - ynm}); } } } // namespace layout end_style get_style(end_style ans, offset_t half_width, bool is_45) { if (ans == end_style::round) { // handle degenerate cases switch (half_width) { case 1: return (is_45) ? end_style::triangle : end_style::extend; case 2: return (is_45) ? end_style::extend : end_style::triangle; default: return end_style::round; } } return ans; } pt_vector path_to_poly45(coord_t x0, coord_t y0, coord_t x1, coord_t y1, offset_t half_width, end_style sty0, end_style sty1) { vector45 p_norm{x1 - x0, y1 - y0}; p_norm.normalize(); // handle empty path if (half_width == 0 || (p_norm.dx == 0 && p_norm.dy == 0)) { return {}; } // handle invalid path if (!p_norm.valid()) { throw std::invalid_argument(fmt::format("path segment vector {} not valid", p_norm)); } bool is_45 = p_norm.is_45_or_invalid(); // initialize point array, reserve space for worst case pt_vector ans; ans.reserve(8); vector45 n_norm = p_norm.get_rotate90(); auto half_diag = static_cast<offset_t>(round(half_width / root2)); offset_t w_main, w_norm; if (is_45) { w_main = half_diag; w_norm = half_width - half_diag; } else { w_main = half_width; w_norm = 2 * half_diag - half_width; } add_path_points(ans, x0, y0, p_norm, n_norm, is_45, sty0, w_main, w_norm); p_norm.invert(); n_norm.invert(); add_path_points(ans, x1, y1, p_norm, n_norm, is_45, sty1, w_main, w_norm); return ans; } } // namespace layout } // namespace cbag
32.125
96
0.575875
ayan-biswas
b419bcb4f302ee1d0d3fdf1514b5ac1068e2b061
9,430
cpp
C++
main_d1/config.cpp
ziplantil/CacaoticusDescent
b4299442bc43310690a666e181dd983c1491dce1
[ "MIT" ]
null
null
null
main_d1/config.cpp
ziplantil/CacaoticusDescent
b4299442bc43310690a666e181dd983c1491dce1
[ "MIT" ]
null
null
null
main_d1/config.cpp
ziplantil/CacaoticusDescent
b4299442bc43310690a666e181dd983c1491dce1
[ "MIT" ]
null
null
null
/* THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE. COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "misc/types.h" #include "game.h" #include "digi.h" #include "kconfig.h" #include "2d/palette.h" #include "platform/joy.h" #include "args.h" #include "player.h" #include "mission.h" #include "misc/error.h" //#include "sos.h"//These sos headers are part of a commercial library, and aren't included-KRB //#include "sosm.h" static const char* digi_dev_str = "DigiDeviceID"; static const char* digi_port_str = "DigiPort"; static const char* digi_irq_str = "DigiIrq"; static const char* digi_dma_str = "DigiDma"; static const char* digi_volume_str = "DigiVolume"; static const char* midi_volume_str = "MidiVolume"; static const char* midi_dev_str = "MidiDeviceID"; static const char* midi_port_str = "MidiPort"; static const char* detail_level_str = "DetailLevel"; static const char* gamma_level_str = "GammaLevel"; static const char* stereo_rev_str = "StereoReverse"; static const char* joystick_min_str = "JoystickMin"; static const char* joystick_max_str = "JoystickMax"; static const char* joystick_cen_str = "JoystickCen"; static const char* last_player_str = "LastPlayer"; static const char* last_mission_str = "LastMission"; static const char* config_vr_type_str = "VR_type"; static const char* config_vr_tracking_str = "VR_tracking"; char config_last_player[CALLSIGN_LEN + 1] = ""; char config_last_mission[MISSION_NAME_LEN + 1] = ""; int Config_digi_type = 0; int Config_midi_type = 0; int Config_vr_type = 0; int Config_vr_tracking = 0; extern int8_t Object_complexity, Object_detail, Wall_detail, Wall_render_depth, Debris_amount, SoundChannels; void set_custom_detail_vars(void); int ReadConfigFile() { FILE* infile; char line[80], * token, * value, * ptr; uint8_t gamma; int joy_axis_min[4]; int joy_axis_center[4]; int joy_axis_max[4]; int i; strcpy(config_last_player, ""); joy_axis_min[0] = joy_axis_min[1] = joy_axis_min[2] = joy_axis_min[3] = 0; joy_axis_max[0] = joy_axis_max[1] = joy_axis_max[2] = joy_axis_max[3] = 0; joy_axis_center[0] = joy_axis_center[1] = joy_axis_center[2] = joy_axis_center[3] = 0; joy_set_cal_vals(joy_axis_min, joy_axis_center, joy_axis_max); digi_driver_board = 0; digi_driver_port = 0; digi_driver_irq = 0; digi_driver_dma = 0; digi_midi_type = 0; digi_midi_port = 0; Config_digi_volume = 4; Config_midi_volume = 4; Config_control_type = 0; Config_channels_reversed = 0; infile = fopen("descent.cfg", "rt"); if (infile == NULL) { return 1; } while (!feof(infile)) { memset(line, 0, 80); fgets(line, 80, infile); ptr = &(line[0]); while (isspace(*ptr)) ptr++; if (*ptr != '\0') { token = strtok(ptr, "="); value = strtok(NULL, "="); if (!strcmp(token, digi_dev_str)) digi_driver_board = strtol(value, NULL, 16); else if (!strcmp(token, digi_port_str)) digi_driver_port = strtol(value, NULL, 16); else if (!strcmp(token, digi_irq_str)) digi_driver_irq = strtol(value, NULL, 10); else if (!strcmp(token, digi_dma_str)) digi_driver_dma = strtol(value, NULL, 10); else if (!strcmp(token, digi_volume_str)) Config_digi_volume = (uint8_t)strtol(value, NULL, 10); else if (!strcmp(token, midi_dev_str)) digi_midi_type = strtol(value, NULL, 16); else if (!strcmp(token, midi_port_str)) digi_midi_port = strtol(value, NULL, 16); else if (!strcmp(token, midi_volume_str)) Config_midi_volume = (uint8_t)strtol(value, NULL, 10); else if (!strcmp(token, stereo_rev_str)) Config_channels_reversed = (uint8_t)strtol(value, NULL, 10); else if (!strcmp(token, gamma_level_str)) { gamma = (uint8_t)strtol(value, NULL, 10); gr_palette_set_gamma(gamma); } else if (!strcmp(token, detail_level_str)) { Detail_level = strtol(value, NULL, 10); if (Detail_level == NUM_DETAIL_LEVELS - 1) { int count, dummy, oc, od, wd, wrd, da, sc; count = sscanf(value, "%d,%d,%d,%d,%d,%d,%d\n", &dummy, &oc, &od, &wd, &wrd, &da, &sc); if (count == 7) { Object_complexity = oc; Object_detail = od; Wall_detail = wd; Wall_render_depth = wrd; Debris_amount = da; SoundChannels = sc; set_custom_detail_vars(); } } } /*else if (!strcmp(token, joystick_min_str)) { //[ISB] cut calibration stuff since it's not usable for chocolate. sscanf(value, "%d,%d,%d,%d", &joy_axis_min[0], &joy_axis_min[1], &joy_axis_min[2], &joy_axis_min[3]); } else if (!strcmp(token, joystick_max_str)) { sscanf(value, "%d,%d,%d,%d", &joy_axis_max[0], &joy_axis_max[1], &joy_axis_max[2], &joy_axis_max[3]); } else if (!strcmp(token, joystick_cen_str)) { sscanf(value, "%d,%d,%d,%d", &joy_axis_center[0], &joy_axis_center[1], &joy_axis_center[2], &joy_axis_center[3]); }*/ else if (!strcmp(token, last_player_str)) { char* p; memset(config_last_player, '\0', CALLSIGN_LEN + 1 * sizeof(char)); strncpy(config_last_player, value, CALLSIGN_LEN); p = strchr(config_last_player, '\n'); if (p)* p = 0; } else if (!strcmp(token, last_mission_str)) { char* p; memset(config_last_mission, '\0', MISSION_NAME_LEN + 1 * sizeof(char)); strncpy(config_last_mission, value, MISSION_NAME_LEN); p = strchr(config_last_mission, '\n'); if (p)* p = 0; } else if (!strcmp(token, config_vr_type_str)) { Config_vr_type = strtol(value, NULL, 10); } else if (!strcmp(token, config_vr_tracking_str)) { Config_vr_tracking = strtol(value, NULL, 10); } } } fclose(infile); i = FindArg("-volume"); if (i > 0) { i = atoi(Args[i + 1]); if (i < 0) i = 0; if (i > 100) i = 100; Config_digi_volume = (i * 8) / 100; Config_midi_volume = (i * 8) / 100; } if (Config_digi_volume > 8) Config_digi_volume = 8; if (Config_midi_volume > 8) Config_midi_volume = 8; joy_set_cal_vals(joy_axis_min, joy_axis_center, joy_axis_max); digi_set_volume((Config_digi_volume * 32768) / 8, (Config_midi_volume * 128) / 8); /* printf( "DigiDeviceID: 0x%x\n", digi_driver_board ); printf( "DigiPort: 0x%x\n", digi_driver_port ); printf( "DigiIrq: 0x%x\n", digi_driver_irq ); printf( "DigiDma: 0x%x\n", digi_driver_dma ); printf( "MidiDeviceID: 0x%x\n", digi_midi_type ); printf( "MidiPort: 0x%x\n", digi_midi_port ); key_getch(); */ Config_midi_type = digi_midi_type; Config_digi_type = digi_driver_board; return 0; } int WriteConfigFile() { FILE* infile; char str[256]; int joy_axis_min[4]; int joy_axis_center[4]; int joy_axis_max[4]; uint8_t gamma = gr_palette_get_gamma(); joy_get_cal_vals(joy_axis_min, joy_axis_center, joy_axis_max); infile = fopen("descent.cfg", "wt"); if (infile == NULL) { return 1; } sprintf(str, "%s=0x%x\n", digi_dev_str, Config_digi_type); fputs(str, infile); sprintf(str, "%s=0x%x\n", digi_port_str, digi_driver_port); fputs(str, infile); sprintf(str, "%s=%d\n", digi_irq_str, digi_driver_irq); fputs(str, infile); sprintf(str, "%s=%d\n", digi_dma_str, digi_driver_dma); fputs(str, infile); sprintf(str, "%s=%d\n", digi_volume_str, Config_digi_volume); fputs(str, infile); sprintf(str, "%s=0x%x\n", midi_dev_str, Config_midi_type); fputs(str, infile); sprintf(str, "%s=0x%x\n", midi_port_str, digi_midi_port); fputs(str, infile); sprintf(str, "%s=%d\n", midi_volume_str, Config_midi_volume); fputs(str, infile); sprintf(str, "%s=%d\n", stereo_rev_str, Config_channels_reversed); fputs(str, infile); sprintf(str, "%s=%d\n", gamma_level_str, gamma); fputs(str, infile); if (Detail_level == NUM_DETAIL_LEVELS - 1) sprintf(str, "%s=%d,%d,%d,%d,%d,%d,%d\n", detail_level_str, Detail_level, Object_complexity, Object_detail, Wall_detail, Wall_render_depth, Debris_amount, SoundChannels); else sprintf(str, "%s=%d\n", detail_level_str, Detail_level); fputs(str, infile); sprintf(str, "%s=%d,%d,%d,%d\n", joystick_min_str, joy_axis_min[0], joy_axis_min[1], joy_axis_min[2], joy_axis_min[3]); fputs(str, infile); sprintf(str, "%s=%d,%d,%d,%d\n", joystick_cen_str, joy_axis_center[0], joy_axis_center[1], joy_axis_center[2], joy_axis_center[3]); fputs(str, infile); sprintf(str, "%s=%d,%d,%d,%d\n", joystick_max_str, joy_axis_max[0], joy_axis_max[1], joy_axis_max[2], joy_axis_max[3]); fputs(str, infile); sprintf(str, "%s=%s\n", last_player_str, Players[Player_num].callsign); fputs(str, infile); sprintf(str, "%s=%s\n", last_mission_str, config_last_mission); fputs(str, infile); sprintf(str, "%s=%d\n", config_vr_type_str, Config_vr_type); fputs(str, infile); sprintf(str, "%s=%d\n", config_vr_tracking_str, Config_vr_tracking); fputs(str, infile); fclose(infile); return 0; }
32.743056
132
0.693001
ziplantil
b41a44a15d91852df05b71d086861bd560862cc5
2,770
cpp
C++
ekbase/plaza/connection.cpp
artintexo/exkit
18d71e84d688060f0c30af456dcbec5252ebbdac
[ "MIT" ]
2
2019-05-20T10:02:16.000Z
2021-01-04T06:18:55.000Z
ekbase/plaza/connection.cpp
artintexo/exkit
18d71e84d688060f0c30af456dcbec5252ebbdac
[ "MIT" ]
null
null
null
ekbase/plaza/connection.cpp
artintexo/exkit
18d71e84d688060f0c30af456dcbec5252ebbdac
[ "MIT" ]
3
2020-09-07T06:44:54.000Z
2022-01-01T11:52:33.000Z
#include "connection.h" #include "utils.h" #include "base/context.h" #include "base/holder.h" #include <thread> Connection::Connection(Plaza *plz, std::string name, std::string settings) : plz(plz), hld(plz->GetHolder()), name(name), settings(settings), state(0) { P2ERR(cg_conn_new(settings.c_str(), &conn)); } Connection::~Connection() { P2DBG(cg_conn_destroy(conn)); } void Connection::Open() { while (state != CG_STATE_ACTIVE && Application::GetMainFlag()) TryOpen(); } void Connection::Close() { while (state != CG_STATE_CLOSED) TryClose(); } void Connection::Process() { P2ERR(cg_conn_getstate(conn, &state)); switch (state) { case CG_STATE_ACTIVE: switch (cg_conn_process(conn, 0, 0)) { case CG_ERR_OK: break; case CG_ERR_TIMEOUT: std::this_thread::sleep_for(std::chrono::nanoseconds(1)); break; case CG_ERR_INVALIDARGUMENT: P2ERR(CG_ERR_INVALIDARGUMENT); break; case CG_ERR_INTERNAL: P2ERR(CG_ERR_INTERNAL); break; } break; case CG_STATE_ERROR: P2DBG(cg_conn_close(conn)); break; case CG_STATE_CLOSED: P2DBG(cg_conn_open(conn, 0)); break; case CG_STATE_OPENING: break; default: LOGW("%s UNKNOWN 0x%X", name.c_str(), state); break; } } void Connection::TryOpen() { P2ERR(cg_conn_getstate(conn, &state)); switch (state) { case CG_STATE_ACTIVE: LogState(); break; case CG_STATE_ERROR: P2DBG(cg_conn_close(conn)); break; case CG_STATE_CLOSED: P2DBG(cg_conn_open(conn, 0)); break; case CG_STATE_OPENING: break; default: LOGW("%s UNKNOWN 0x%X", name.c_str(), state); break; } } void Connection::TryClose() { P2ERR(cg_conn_getstate(conn, &state)); switch (state) { case CG_STATE_ACTIVE: P2DBG(cg_conn_close(conn)); break; case CG_STATE_ERROR: P2DBG(cg_conn_close(conn)); break; case CG_STATE_CLOSED: LogState(); break; case CG_STATE_OPENING: break; default: LOGW("%s UNKNOWN 0x%X", name.c_str(), state); break; } } void Connection::LogState() { switch (state) { case CG_STATE_ACTIVE: LOGD("%s ACTIVE", name.c_str()); break; case CG_STATE_ERROR: LOGD("%s ERROR", name.c_str()); break; case CG_STATE_CLOSED: LOGD("%s CLOSED", name.c_str()); break; case CG_STATE_OPENING: LOGD("%s OPENING", name.c_str()); break; default: LOGW("%s UNKNOWN 0x%X", name.c_str(), state); break; } }
21.307692
79
0.577978
artintexo
b41b08ea7e9549c680ea9cfd58afa9a3ec58de9b
4,031
cc
C++
mascot_examples/safety/dcdc/LazySafe/dcdc.cc
hsukyle/mascot
510193eaf9bb4d478677ad1b24d2ef9344ee40b0
[ "Apache-2.0" ]
1
2017-08-19T03:24:09.000Z
2017-08-19T03:24:09.000Z
mascot_examples/safety/dcdc/LazySafe/dcdc.cc
hsukyle/mascot
510193eaf9bb4d478677ad1b24d2ef9344ee40b0
[ "Apache-2.0" ]
null
null
null
mascot_examples/safety/dcdc/LazySafe/dcdc.cc
hsukyle/mascot
510193eaf9bb4d478677ad1b24d2ef9344ee40b0
[ "Apache-2.0" ]
null
null
null
#include <array> #include <iostream> #include <cmath> #define _USE_MATH_DEFINES #include <string> #include "AdaptAbsSafe.hh" using namespace scots; /* dimensions */ #define dimX 2 #define dimU 1 /* data types for the ode solver */ typedef std::array<double, dimX> X_type; typedef std::array<double, dimU> U_type; const double w[dimX] = {0.001, 0.001}; /* we integrate the simple ode by 0.3 sec (the result is stored in x) */ auto sysNext = [](X_type &x, U_type &u, OdeSolver solver) -> void { auto sysODE = [](X_type &dxdt, const X_type &x, const U_type &u) -> void { const double r0 = 1.0 ; const double vs = 1.0 ; const double rl = 0.05 ; const double rc = rl / 10 ; const double xl = 3.0 ; const double xc = 70.0 ; const double b[2]={vs/xl, 0}; double a[2][2]; if(u[0]==0.5) { a[0][0] = -rl / xl; a[0][1] = 0; a[1][0] = 0; a[1][1] = (-1 / xc) * (1 / (r0 + rc)); } else { a[0][0] = (-1 / xl) * (rl + ((r0 * rc) / (r0 + rc))) ; a[0][1] = ((-1 / xl) * (r0 / (r0 + rc))) / 5 ; a[1][0] = 5 * (r0 / (r0 + rc)) * (1 / xc); a[1][1] =(-1 / xc) * (1 / (r0 + rc)) ; } dxdt[0] = a[0][0]*x[0]+a[0][1]*x[1] + b[0]; dxdt[1] = a[1][0]*x[0]+a[1][1]*x[1] + b[1]; }; solver(sysODE, x, u); }; /* computation of the growth bound (the result is stored in r) */ auto radNext = [](X_type &r, U_type &u, OdeSolver solver) -> void { auto radODE = [](X_type &drdt, const X_type &r, const U_type &u) -> void { const double r0 = 1.0 ; const double rl = 0.05 ; const double rc = rl / 10 ; const double xl = 3.0 ; const double xc = 70.0 ; double a[2][2]; if(u[0]==0.5) { a[0][0] = -rl / xl; a[0][1] = 0; a[1][0] = 0; a[1][1] = (-1 / xc) * (1 / (r0 + rc)); } else { a[0][0] = (-1 / xl) * (rl + ((r0 * rc) / (r0 + rc))) ; a[0][1] = ((1 / xl) * (r0 / (r0 + rc))) / 5 ; a[1][0] = 5 * (r0 / (r0 + rc)) * (1 / xc); a[1][1] =(-1 / xc) * (1 / (r0 + rc)) ; } drdt[0] = a[0][0]*r[0]+a[0][1]*r[1] + w[0]; drdt[1] = a[1][0]*r[0]+a[1][1]*r[1] + w[1]; }; solver(radODE, r, u); }; auto dcdcAddS = [](SymbolicSet* S) -> void { double H[4*2] = {-1, 0, 1, 0, 0, -1, 0, 1}; double h[4] = {-1.15, 1.55, -5.45, 5.85}; S->addPolytope(4, H, h, INNER); }; int main(int argc, char **argv) { /* sanity check */ if (argc == 1) { std::ostringstream os; os << "Error: you need to specify the number of abstraction layers."; throw std::invalid_argument(os.str().c_str()); return 0; } /* number of abstraction layers */ int numAbs = std::stoi(argv[1]); double lbX[dimX] = {1.15, 5.45}; double ubX[dimX] = {1.55, 5.85}; /* the system dynamics has two modes which correspond to two distinct abstract control inputs (in our case, they are 0.5, 1.5) */ double lbU[dimU] = {0}; double ubU[dimU] = {2}; double etaU[dimU] = {1}; int nint = 5; double etaX[dimX]= {(pow(2,numAbs-1)*2/4e3), (pow(2,numAbs-1)*2/4e3)}; double tau = pow(2, numAbs-1)*0.0625; double etaRatio[dimX] = {2, 2}; double tauRatio = 2; int verbose = 1; X_type x; U_type u; std::string logfile = "dcdc"; logfile += std::to_string(numAbs); logfile += "A.log"; System dcdc(dimX, lbX, ubX, etaX, tau, dimU, lbU, ubU, etaU, etaRatio, tauRatio, nint, numAbs); AdaptAbsSafe abs(logfile.c_str(), verbose); abs.initialize(&dcdc, dcdcAddS); TicToc timer; timer.tic(); abs.onTheFlySafeNoAux(sysNext, radNext, x, u); clog << "-----------------------------------------------Total time: " << timer.toc() << " seconds.\n"; }
29.639706
133
0.46713
hsukyle
b41cc24918e165800a367cf5e773e8ad4baee4c7
1,262
hh
C++
src/utils/CppPyWrapper.hh
LeoRya/py-orbit
340b14b6fd041ed8ec2cc25b0821b85742aabe0c
[ "MIT" ]
17
2018-02-09T23:39:06.000Z
2022-03-04T16:27:04.000Z
src/utils/CppPyWrapper.hh
LeoRya/py-orbit
340b14b6fd041ed8ec2cc25b0821b85742aabe0c
[ "MIT" ]
22
2017-05-31T19:40:14.000Z
2021-09-24T22:07:47.000Z
src/utils/CppPyWrapper.hh
LeoRya/py-orbit
340b14b6fd041ed8ec2cc25b0821b85742aabe0c
[ "MIT" ]
37
2016-12-08T19:39:35.000Z
2022-02-11T19:59:34.000Z
//////////////////////////////// -*- C++ -*- ////////////////////////////// // // FILE NAME // CppPyWrapper.hh // // CREATED // 04/22/2003 // // DESCRIPTION // The base class that provides capability to keep the reference to // the Python class instance that is wrapping the c++ subclassing // this class. // /////////////////////////////////////////////////////////////////////////// #ifndef CPP_PY_WRAPPER_H #define CPP_PY_WRAPPER_H #include "Python.h" namespace OrbitUtils{ /** The base class that provides capability to keep the reference to the Python class instance that is wrapping the c++ subclassing this class. */ class CppPyWrapper { public: /** Constructor of the CppPyWrapper class with reference to Python class instance. */ CppPyWrapper(PyObject* py_wrapperIn); /** Constructor of the CppPyWrapper class with NULL reference to Python class. */ CppPyWrapper(); /** Destrictor. It is empty. */ ~CppPyWrapper(); /** Sets the reference to Python class instance. */ void setPyWrapper(PyObject* py_wrapperIn); /** Returns the reference to Python class instance. */ PyObject* getPyWrapper(); private: PyObject* cpp_py_wrapper; }; }; #endif
22.945455
88
0.593502
LeoRya
b41d52f3cd2dc5693ba3f850ae5794895b7b18e5
3,581
cpp
C++
dynamic_vino_lib/src/models/head_pose_detection_model.cpp
ahuizxc/ros2_openvino_toolkit
ce28271e62fc6e1ad028137d0b6882eb9f7bdf6d
[ "Apache-2.0" ]
4
2018-11-21T14:17:28.000Z
2021-03-14T23:02:13.000Z
dynamic_vino_lib/src/models/head_pose_detection_model.cpp
ahuizxc/ros2_openvino_toolkit
ce28271e62fc6e1ad028137d0b6882eb9f7bdf6d
[ "Apache-2.0" ]
2
2020-11-25T08:47:42.000Z
2020-12-29T02:10:08.000Z
dynamic_vino_lib/src/models/head_pose_detection_model.cpp
ahuizxc/ros2_openvino_toolkit
ce28271e62fc6e1ad028137d0b6882eb9f7bdf6d
[ "Apache-2.0" ]
2
2020-09-09T06:34:49.000Z
2020-11-02T05:58:21.000Z
/* * Copyright (c) 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @brief a header file with declaration of HeadPoseDetectionModel class * @file head_pose_detection_model.cpp */ #include <map> #include <string> #include "dynamic_vino_lib/models/head_pose_detection_model.hpp" #include "dynamic_vino_lib/slog.hpp" // Validated Head Pose Network Models::HeadPoseDetectionModel::HeadPoseDetectionModel( const std::string& model_loc, int input_num, int output_num, int max_batch_size) : BaseModel(model_loc, input_num, output_num, max_batch_size){} void Models::HeadPoseDetectionModel::checkLayerProperty( const InferenceEngine::CNNNetReader::Ptr& net_reader) { slog::info << "Checking Head Pose network outputs" << slog::endl; InferenceEngine::OutputsDataMap outputInfo( net_reader->getNetwork().getOutputsInfo()); std::map<std::string, bool> layerNames = {{output_angle_r_, false}, {output_angle_p_, false}, {output_angle_y_, false}}; for (auto&& output : outputInfo) { InferenceEngine::CNNLayerPtr layer = output.second->getCreatorLayer().lock(); if (layerNames.find(layer->name) == layerNames.end()) { throw std::logic_error("Head Pose network output layer unknown: " + layer->name + ", should be " + output_angle_r_ + " or " + output_angle_p_ + " or " + output_angle_y_); } if (layer->type != "FullyConnected") { throw std::logic_error("Head Pose network output layer (" + layer->name + ") has invalid type: " + layer->type + ", should be FullyConnected"); } auto fc = dynamic_cast<InferenceEngine::FullyConnectedLayer*>(layer.get()); if (fc->_out_num != 1) { throw std::logic_error("Head Pose network output layer (" + layer->name + ") has invalid out-size=" + std::to_string(fc->_out_num) + ", should be 1"); } layerNames[layer->name] = true; } } void Models::HeadPoseDetectionModel::setLayerProperty( InferenceEngine::CNNNetReader::Ptr net_reader) { // set input property InferenceEngine::InputsDataMap input_info_map( net_reader->getNetwork().getInputsInfo()); InferenceEngine::InputInfo::Ptr input_info = input_info_map.begin()->second; input_info->setPrecision(InferenceEngine::Precision::U8); input_info->getInputData()->setLayout(InferenceEngine::Layout::NCHW); input_ = input_info_map.begin()->first; // set output property InferenceEngine::OutputsDataMap output_info_map( net_reader->getNetwork().getOutputsInfo()); for (auto& output : output_info_map){ output.second->setPrecision(InferenceEngine::Precision::FP32); output.second->setLayout(InferenceEngine::Layout::NC); } } const std::string Models::HeadPoseDetectionModel::getModelName() const { return "Head Pose Network"; }
38.923913
79
0.66406
ahuizxc
b41da17f244423956469703d0640b94cb00de083
13,311
cpp
C++
src/Magnum/Trade/AnimationData.cpp
hsdk123/magnum
806e0800083020eaeee2a4d7d96f2991f4b51f15
[ "MIT" ]
null
null
null
src/Magnum/Trade/AnimationData.cpp
hsdk123/magnum
806e0800083020eaeee2a4d7d96f2991f4b51f15
[ "MIT" ]
null
null
null
src/Magnum/Trade/AnimationData.cpp
hsdk123/magnum
806e0800083020eaeee2a4d7d96f2991f4b51f15
[ "MIT" ]
null
null
null
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 Vladimír Vondruš <mosra@centrum.cz> 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 "AnimationData.h" #include <Corrade/Utility/Debug.h> #include "Magnum/Math/Vector4.h" #include "Magnum/Math/Quaternion.h" #include "Magnum/Trade/Implementation/arrayUtilities.h" namespace Magnum { namespace Trade { AnimationData::AnimationData(Containers::Array<char>&& data, Containers::Array<AnimationTrackData>&& tracks, const Range1D& duration, const void* importerState) noexcept: _dataFlags{DataFlag::Owned|DataFlag::Mutable}, _duration{duration}, _data{std::move(data)}, _tracks{std::move(tracks)}, _importerState{importerState} {} AnimationData::AnimationData(Containers::Array<char>&& data, std::initializer_list<AnimationTrackData> tracks, const Range1D& duration, const void* importerState): AnimationData{std::move(data), Implementation::initializerListToArrayWithDefaultDeleter(tracks), duration, importerState} {} AnimationData::AnimationData(const DataFlags dataFlags, const Containers::ArrayView<const void> data, Containers::Array<AnimationTrackData>&& tracks, const Range1D& duration, const void* importerState) noexcept: AnimationData{Containers::Array<char>{const_cast<char*>(static_cast<const char*>(data.data())), data.size(), Implementation::nonOwnedArrayDeleter}, std::move(tracks), duration, importerState} { CORRADE_ASSERT(!(dataFlags & DataFlag::Owned), "Trade::AnimationData: can't construct a non-owned instance with" << dataFlags, ); _dataFlags = dataFlags; } AnimationData::AnimationData(const DataFlags dataFlags, const Containers::ArrayView<const void> data, std::initializer_list<AnimationTrackData> tracks, const Range1D& duration, const void* importerState): AnimationData{dataFlags, data, Implementation::initializerListToArrayWithDefaultDeleter(tracks), duration, importerState} {} AnimationData::AnimationData(Containers::Array<char>&& data, Containers::Array<AnimationTrackData>&& tracks, const void* importerState) noexcept: _dataFlags{DataFlag::Owned|DataFlag::Mutable}, _data{std::move(data)}, _tracks{std::move(tracks)}, _importerState{importerState} { if(!_tracks.empty()) { /* Reset duration to duration of the first track so it properly support cases where tracks don't start at 0 */ _duration = _tracks.front()._view.duration(); for(std::size_t i = 1; i != _tracks.size(); ++i) _duration = Math::join(_duration, _tracks[i]._view.duration()); } } AnimationData::AnimationData(Containers::Array<char>&& data, std::initializer_list<AnimationTrackData> tracks, const void* importerState): AnimationData{std::move(data), Implementation::initializerListToArrayWithDefaultDeleter(tracks), importerState} {} AnimationData::AnimationData(const DataFlags dataFlags, const Containers::ArrayView<const void> data, Containers::Array<AnimationTrackData>&& tracks, const void* importerState) noexcept: AnimationData{Containers::Array<char>{const_cast<char*>(static_cast<const char*>(data.data())), data.size(), Implementation::nonOwnedArrayDeleter}, std::move(tracks), importerState} { CORRADE_ASSERT(!(dataFlags & DataFlag::Owned), "Trade::AnimationData: can't construct a non-owned instance with" << dataFlags, ); _dataFlags = dataFlags; } AnimationData::AnimationData(const DataFlags dataFlags, const Containers::ArrayView<const void> data, std::initializer_list<AnimationTrackData> tracks, const void* importerState): AnimationData{dataFlags, data, Implementation::initializerListToArrayWithDefaultDeleter(tracks), importerState} {} AnimationData::~AnimationData() = default; AnimationData::AnimationData(AnimationData&&) noexcept = default; AnimationData& AnimationData::operator=(AnimationData&&) noexcept = default; Containers::ArrayView<char> AnimationData::mutableData() & { CORRADE_ASSERT(_dataFlags & DataFlag::Mutable, "Trade::AnimationData::mutableData(): the animation is not mutable", {}); return _data; } AnimationTrackType AnimationData::trackType(UnsignedInt id) const { CORRADE_ASSERT(id < _tracks.size(), "Trade::AnimationData::trackType(): index out of range", {}); return _tracks[id]._type; } AnimationTrackType AnimationData::trackResultType(UnsignedInt id) const { CORRADE_ASSERT(id < _tracks.size(), "Trade::AnimationData::trackResultType(): index out of range", {}); return _tracks[id]._resultType; } AnimationTrackTargetType AnimationData::trackTargetType(UnsignedInt id) const { CORRADE_ASSERT(id < _tracks.size(), "Trade::AnimationData::trackTargetType(): index out of range", {}); return _tracks[id]._targetType; } UnsignedInt AnimationData::trackTarget(UnsignedInt id) const { CORRADE_ASSERT(id < _tracks.size(), "Trade::AnimationData::trackTarget(): index out of range", {}); return _tracks[id]._target; } const Animation::TrackViewStorage<const Float>& AnimationData::track(UnsignedInt id) const { CORRADE_ASSERT(id < _tracks.size(), "Trade::AnimationData::track(): index out of range", _tracks[id]._view); return _tracks[id]._view; } const Animation::TrackViewStorage<Float>& AnimationData::mutableTrack(UnsignedInt id) { CORRADE_ASSERT(_dataFlags & DataFlag::Mutable, "Trade::AnimationData::mutableTrack(): the animation is not mutable", reinterpret_cast<const Animation::TrackViewStorage<Float>&>(_tracks[id]._view)); CORRADE_ASSERT(id < _tracks.size(), "Trade::AnimationData::track(): index out of range", reinterpret_cast<const Animation::TrackViewStorage<Float>&>(_tracks[id]._view)); return reinterpret_cast<const Animation::TrackViewStorage<Float>&>(_tracks[id]._view); } Containers::Array<char> AnimationData::release() { _tracks = nullptr; return std::move(_data); } template<class V, class R> auto animationInterpolatorFor(Animation::Interpolation interpolation) -> R(*)(const V&, const V&, Float) { return Animation::interpolatorFor<V, R>(interpolation); } #ifndef DOXYGEN_GENERATING_OUTPUT template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<bool, bool>(Animation::Interpolation) -> bool(*)(const bool&, const bool&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Float, Float>(Animation::Interpolation) -> Float(*)(const Float&, const Float&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<UnsignedInt, UnsignedInt>(Animation::Interpolation) -> UnsignedInt(*)(const UnsignedInt&, const UnsignedInt&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Int, Int>(Animation::Interpolation) -> Int(*)(const Int&, const Int&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Math::BoolVector<2>, Math::BoolVector<2>>(Animation::Interpolation) -> Math::BoolVector<2>(*)(const Math::BoolVector<2>&, const Math::BoolVector<2>&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Math::BoolVector<3>, Math::BoolVector<3>>(Animation::Interpolation) -> Math::BoolVector<3>(*)(const Math::BoolVector<3>&, const Math::BoolVector<3>&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Math::BoolVector<4>, Math::BoolVector<4>>(Animation::Interpolation) -> Math::BoolVector<4>(*)(const Math::BoolVector<4>&, const Math::BoolVector<4>&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Vector2, Vector2>(Animation::Interpolation) -> Vector2(*)(const Vector2&, const Vector2&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Vector2i, Vector2i>(Animation::Interpolation) -> Vector2i(*)(const Vector2i&, const Vector2i&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Vector2ui, Vector2ui>(Animation::Interpolation) -> Vector2ui(*)(const Vector2ui&, const Vector2ui&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Vector3, Vector3>(Animation::Interpolation) -> Vector3(*)(const Vector3&, const Vector3&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Vector3i, Vector3i>(Animation::Interpolation) -> Vector3i(*)(const Vector3i&, const Vector3i&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Vector3ui, Vector3ui>(Animation::Interpolation) -> Vector3ui(*)(const Vector3ui&, const Vector3ui&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Vector4, Vector4>(Animation::Interpolation) -> Vector4(*)(const Vector4&, const Vector4&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Vector4d, Vector4d>(Animation::Interpolation) -> Vector4d(*)(const Vector4d&, const Vector4d&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Vector4i, Vector4i>(Animation::Interpolation) -> Vector4i(*)(const Vector4i&, const Vector4i&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Vector4ui, Vector4ui>(Animation::Interpolation) -> Vector4ui(*)(const Vector4ui&, const Vector4ui&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Complex, Complex>(Animation::Interpolation) -> Complex(*)(const Complex&, const Complex&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<Quaternion, Quaternion>(Animation::Interpolation) -> Quaternion(*)(const Quaternion&, const Quaternion&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<DualQuaternion, DualQuaternion>(Animation::Interpolation) -> DualQuaternion(*)(const DualQuaternion&, const DualQuaternion&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<CubicHermite2D, Math::Vector2<Float>>(Animation::Interpolation) -> Math::Vector2<Float>(*)(const CubicHermite2D&, const CubicHermite2D&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<CubicHermite3D, Math::Vector3<Float>>(Animation::Interpolation) -> Math::Vector3<Float>(*)(const CubicHermite3D&, const CubicHermite3D&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<CubicHermiteComplex, Complex>(Animation::Interpolation) -> Complex(*)(const CubicHermiteComplex&, const CubicHermiteComplex&, Float); template MAGNUM_TRADE_EXPORT auto animationInterpolatorFor<CubicHermiteQuaternion, Quaternion>(Animation::Interpolation) -> Quaternion(*)(const CubicHermiteQuaternion&, const CubicHermiteQuaternion&, Float); Debug& operator<<(Debug& debug, const AnimationTrackType value) { debug << "Trade::AnimationTrackType" << Debug::nospace; switch(value) { /* LCOV_EXCL_START */ #define _c(value) case AnimationTrackType::value: return debug << "::" #value; _c(Bool) _c(Float) _c(UnsignedInt) _c(Int) _c(BoolVector2) _c(BoolVector3) _c(BoolVector4) _c(Vector2) _c(Vector2ui) _c(Vector2i) _c(Vector3) _c(Vector3ui) _c(Vector3i) _c(Vector4) _c(Vector4ui) _c(Vector4i) _c(Complex) _c(Quaternion) _c(DualQuaternion) _c(CubicHermite1D) _c(CubicHermite2D) _c(CubicHermite3D) _c(CubicHermiteComplex) _c(CubicHermiteQuaternion) #undef _c /* LCOV_EXCL_STOP */ } return debug << "(" << Debug::nospace << reinterpret_cast<void*>(UnsignedByte(value)) << Debug::nospace << ")"; } Debug& operator<<(Debug& debug, const AnimationTrackTargetType value) { if(UnsignedByte(value) >= UnsignedByte(AnimationTrackTargetType::Custom)) return debug << "Trade::AnimationTrackTargetType::Custom(" << Debug::nospace << UnsignedByte(value) << Debug::nospace << ")"; switch(value) { /* LCOV_EXCL_START */ #define _c(value) case AnimationTrackTargetType::value: return debug << "Trade::AnimationTrackTargetType::" #value; _c(Translation2D) _c(Translation3D) _c(Rotation2D) _c(Rotation3D) _c(Scaling2D) _c(Scaling3D) #undef _c /* LCOV_EXCL_STOP */ /* To silence compiler warning about unhandled values */ case AnimationTrackTargetType::Custom: CORRADE_INTERNAL_ASSERT_UNREACHABLE(); /* LCOV_EXCL_LINE */ } return debug << "Trade::AnimationTrackTargetType(" << Debug::nospace << reinterpret_cast<void*>(UnsignedByte(value)) << Debug::nospace << ")"; } #endif }}
63.688995
405
0.75246
hsdk123
b41f5ac04fa4a55b5b7ab06bba5daff418dab115
4,398
hh
C++
twilio.hh
esemeniuc/twilioTest
7c3b88ff1b0fb36b000a9e1806d0c35d20492a89
[ "MIT" ]
null
null
null
twilio.hh
esemeniuc/twilioTest
7c3b88ff1b0fb36b000a9e1806d0c35d20492a89
[ "MIT" ]
null
null
null
twilio.hh
esemeniuc/twilioTest
7c3b88ff1b0fb36b000a9e1806d0c35d20492a89
[ "MIT" ]
null
null
null
#include <sstream> #include <curl/curl.h> #include "twilio.hh" namespace twilio { Twilio::Twilio( const std::string& accound_sid_in, const std::string& auth_token_in ) { account_sid = accound_sid_in; auth_token = auth_token_in; } void Twilio::set_account_sid(const std::string& accound_sid_in) { account_sid = accound_sid_in; } void Twilio::set_auth_token(const std::string& auth_token_in) { auth_token = auth_token_in; } // Portably ignore curl response size_t Twilio::_null_write( char *ptr, size_t size, size_t nmemb, void *userdata) { return size*nmemb; } // Write curl response to a stringstream size_t Twilio::_stream_write( char *ptr, size_t size, size_t nmemb, void *userdata) { size_t response_size = size * nmemb; std::stringstream *ss = (std::stringstream*)userdata; ss->write(ptr, response_size); return response_size; } // Method send_message: // Returns 'true' if the result of the eventual HTTP post to Twilio is status // code 200 or 201. Either other status codes or errors in curl will cause // a false result. // Inputs: // - to_number: Where to send the MMS or SMS // - from_number: Number in your Twilio account to use as a sender. // - message_body: (Max: 1600 characters) The body of the MMS or SMS // message which will be sent to the to_number. // // Outputs: // - response: Either the curl error message or the Twilio response // if verbose. // Optional: // - picture_url: If picture URL is included, a MMS will be sent // - verbose: Whether to print all the responses bool Twilio::send_message( const std::string& to_number, const std::string& from_number, const std::string& message_body, std::string& response, const std::string& picture_url, bool verbose) { std::stringstream response_stream; // See: https://www.twilio.com/docs/api/rest/sending-messages for // information on Twilio body size limits. if (message_body.length() > 1600) { response_stream << "Message body must have 1600 or fewer" << " characters. Cannot send message with " << message_body.length() << " characters."; response = response_stream.str(); return false; } CURL *curl; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); std::stringstream url; std::string url_string; url << "https://api.twilio.com/2010-04-01/Accounts/" << account_sid << "/Messages"; url_string = url.str(); std::stringstream parameters; std::string parameter_string; parameters << "To=" << to_number << "&From=" << from_number << "&Body=" << message_body; if (!picture_url.empty()) { parameters << "&MediaUrl=" << picture_url; } parameter_string = parameters.str(); curl_easy_setopt(curl, CURLOPT_POST, 1); curl_easy_setopt(curl, CURLOPT_URL, url_string.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, parameter_string.c_str()); curl_easy_setopt(curl, CURLOPT_USERNAME, account_sid.c_str()); curl_easy_setopt(curl, CURLOPT_PASSWORD, auth_token.c_str()); if (!verbose) { curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _null_write); } else { curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _stream_write); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_stream); } CURLcode res = curl_easy_perform(curl); curl_easy_cleanup(curl); long http_code = 0; curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &http_code); // Check for curl errors and Twilio failure status codes. if (res != CURLE_OK) { response = curl_easy_strerror(res); return false; } else if (http_code != 200 && http_code != 201) { response = response_stream.str(); return false; } else { response = response_stream.str(); return true; } } } // end namespace twilio
30.971831
79
0.599818
esemeniuc
b41f5ae6d34f190145a97e41938a8701e5bbaa87
5,966
cpp
C++
tests/unit/helpers/src/Comparators.cpp
SusanTan/noelle
33c9e10a20bc59590c13bf29fb661fc406a9e687
[ "MIT" ]
43
2020-09-04T15:21:40.000Z
2022-03-23T03:53:02.000Z
tests/unit/helpers/src/Comparators.cpp
SusanTan/noelle
33c9e10a20bc59590c13bf29fb661fc406a9e687
[ "MIT" ]
15
2020-09-17T18:06:15.000Z
2022-01-24T17:14:36.000Z
tests/unit/helpers/src/Comparators.cpp
SusanTan/noelle
33c9e10a20bc59590c13bf29fb661fc406a9e687
[ "MIT" ]
23
2020-09-04T15:50:09.000Z
2022-03-25T13:38:25.000Z
/* * Copyright 2016 - 2019 Angelo Matni, Simone Campanoni * * 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 "Comparators.hpp" namespace parallelizertests { std::pair<Values, Values> Comparator::nonIntersecting (Values &v, Values &w) { Values notV, notW; for (auto x : v) { if (w.find(x) == w.end()) { notW.insert(x); } } for (auto y : w) { if (v.find(y) == v.end()) { notV.insert(y); } } return make_pair(notV, notW); } FileComparator::FileComparator (std::string filename, std::string unordered, std::string ordered) : unorderedDelimiter{unordered}, orderedDelimiter{ordered} { ifstream file; file.open(filename); if (!file.is_open()) { errs() << "Could not open file: " << filename << "\n"; throw; } const std::set<std::string> lineContinuations { orderedDelimiter, unorderedDelimiter }; std::string line; std::string group = ""; std::vector<std::string> lineSplits{}; while (getline(file, line)) { Parser::trim(line); if (line == "") { group = ""; continue; } if (line[0] == '#') { continue; } if (group == "") { group = line; groupValues[group].clear(); } else { lineSplits.push_back(line); std::string lastCharacter(1, line[line.length() - 1]); if (lineContinuations.find(lastCharacter) == lineContinuations.end()) { std::string fullLine; for (auto l : lineSplits) fullLine += l; lineSplits.clear(); groupValues[group].insert(processDelimitedRow(fullLine)); } } } file.close(); } std::string FileComparator::processDelimitedRow (std::string value) { Parser::trim(value); /* * Determine if the whole value represents an ordered/unordered set of tokens */ std::vector<std::string> unorderedTokens{}, orderedTokens{}; trySplitOrderedAndUnordered(value, orderedTokens, unorderedTokens); bool isUnordered = unorderedTokens.size() > 1; bool isOrdered = orderedTokens.size() > 1; /* * Trim each token, and if unordered, sort lexicographically */ if (!isUnordered && !isOrdered) return value; auto &tokens = isUnordered ? unorderedTokens : orderedTokens; for (auto &token : tokens) Parser::trim(token); if (isUnordered) std::sort(tokens.begin(), tokens.end()); /* * Recombine the tokens */ std::string result = tokens[0]; for (int i = 1; i < tokens.size(); ++i) result += orderedDelimiter + tokens[i]; return result; } std::pair<Values, Values> FileComparator::nonIntersectingGroups (std::set<std::string> &groupNames) { Values selfGroups{}; for (auto pair : groupValues) selfGroups.insert(pair.first); return nonIntersecting(selfGroups, groupNames); } std::pair<Values, Values> FileComparator::nonIntersectingOfGroup (std::string group, Values &values) { Values processedValues{}; for (auto value : values) processedValues.insert(processDelimitedRow(value)); return nonIntersecting(this->groupValues[group], processedValues); } const std::unordered_map<std::string, std::set<std::string>> &FileComparator::getGroupValues () { return this->groupValues; } std::vector<std::string> FileComparator::split (std::string value) { std::vector<std::string> unorderedTokens; std::vector<std::string> orderedTokens; trySplitOrderedAndUnordered(value, orderedTokens, unorderedTokens); return orderedTokens.size() > 1 ? orderedTokens : unorderedTokens; } void FileComparator::trySplitOrderedAndUnordered ( std::string value, std::vector<std::string> &ordered, std::vector<std::string> &unordered ) { std::vector<std::string> unorderedTokens = Parser::split(value, unorderedDelimiter); std::vector<std::string> orderedTokens = Parser::split(value, orderedDelimiter); bool isUnordered = unorderedTokens.size() > 1; bool isOrdered = orderedTokens.size() > 1; assert(!(isUnordered && isOrdered) && "Error: tests cannot mix unordered and ordered expected values"); ordered.clear(); ordered.insert(ordered.begin(), orderedTokens.begin(), orderedTokens.end()); unordered.clear(); unordered.insert(unordered.begin(), unorderedTokens.begin(), unorderedTokens.end()); } void Parser::ltrim (std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); })); } void Parser::rtrim (std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(), s.end()); } void Parser::trim (std::string &s) { ltrim(s); rtrim(s); } std::vector<std::string> Parser::split (std::string s, std::string delimiter) { size_t prev_pos = 0, pos = 0; std::vector<std::string> tokens{}; while (prev_pos < s.length() && (pos = s.find(delimiter, prev_pos)) != std::string::npos) { tokens.push_back(s.substr(prev_pos, pos - prev_pos)); prev_pos = pos + 1; } if (prev_pos != s.length()) tokens.push_back(s.substr(prev_pos, s.length() - prev_pos)); return tokens; } }
34.888889
435
0.688066
SusanTan
b41fb469c5f099b67984302efaac01fa39b3663e
1,459
hh
C++
src/phantasm-hardware-interface/limits.hh
project-arcana/phantasm-hardware-interface
d75e23b0ac46efb304246930d680851bbe7f6561
[ "MIT" ]
6
2020-12-09T13:53:26.000Z
2021-12-24T14:13:17.000Z
src/phantasm-hardware-interface/limits.hh
project-arcana/phantasm-hardware-interface
d75e23b0ac46efb304246930d680851bbe7f6561
[ "MIT" ]
5
2020-01-29T09:46:36.000Z
2020-09-04T16:15:53.000Z
src/phantasm-hardware-interface/limits.hh
project-arcana/phantasm-hardware-interface
d75e23b0ac46efb304246930d680851bbe7f6561
[ "MIT" ]
null
null
null
#pragma once namespace phi::limits { enum limits_e : unsigned { /// the maximum amount of render targets per render pass, excluding the depthstencil target /// NOTE: D3D12 only supports up to 8 render targets max_render_targets = 8u, /// the maximum amount of resource transitions per transition command /// configurable max_resource_transitions = 4u, /// the maximum amount of UAV barriers per command /// configurable max_uav_barriers = 8u, /// the maximum amount of shader arguments per draw- or compute dispatch command /// NOTE: The Vulkan backend requires (2 * max_shader_arguments) descriptor sets, /// most non-desktop GPUs only support a maximum of 8. max_shader_arguments = 4u, /// the maximum amount of samplers per shader view /// configurable max_shader_samplers = 16u, /// the maximum size for root constants /// configurable in increments of 4, also concerns CPU memory (cmd::draw, cmd::dispatch) max_root_constant_bytes = 16u, /// the maximum amount of usable vertex buffers (per drawcall and in a graphics PSO) max_vertex_buffers = 4u, /// the maximum amount of argument associations /// configurable max_raytracing_argument_assocs = 8u, /// the maximum amount of hit groups /// configurable max_raytracing_hit_groups = 16u, /// amount of shader stages in the graphics pipeline num_graphics_shader_stages = 5u, }; }
31.042553
95
0.707334
project-arcana
b4215cca9af8f0956e18c4f637e9c18770245e9c
1,050
hpp
C++
emp/base/_is_streamable.hpp
mercere99/Wordle
cbfc104f049f0737422d3f90e3decfb96df8e8e0
[ "MIT" ]
null
null
null
emp/base/_is_streamable.hpp
mercere99/Wordle
cbfc104f049f0737422d3f90e3decfb96df8e8e0
[ "MIT" ]
null
null
null
emp/base/_is_streamable.hpp
mercere99/Wordle
cbfc104f049f0737422d3f90e3decfb96df8e8e0
[ "MIT" ]
null
null
null
/** * @note This file is part of Empirical, https://github.com/devosoft/Empirical * @copyright Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md * @date 2020. * * @file _is_streamable.hpp * @brief Test at compile time whether a type can be streamed. * @note This header is for internal use to preserve levelization. * Include meta/type_traits.hpp to use is_streamable. */ #ifndef EMP_BASE__IS_STREAMABLE_HPP_INCLUDE #define EMP_BASE__IS_STREAMABLE_HPP_INCLUDE namespace emp { // adapted from https://stackoverflow.com/a/22759544 template<typename S, typename T> class is_streamable { template<typename SS, typename TT> static auto test(int) -> decltype( std::declval<SS&>() << std::declval<TT>(), std::true_type() ); template<typename, typename> static auto test(...) -> std::false_type; public: /// Determine if a type can be streamed. static constexpr bool value = decltype(test<S,T>(0))::value; }; } // namespace emp #endif // #ifndef EMP_BASE__IS_STREAMABLE_HPP_INCLUDE
26.923077
96
0.725714
mercere99
b421d792460897c394a715f50735223bf1b207ff
3,608
hpp
C++
src/Switch.Core/include/Switch/System/ConsoleCancelEventArgs.hpp
victor-timoshin/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
4
2020-02-11T13:22:58.000Z
2022-02-24T00:37:43.000Z
src/Switch.Core/include/Switch/System/ConsoleCancelEventArgs.hpp
sgf/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
null
null
null
src/Switch.Core/include/Switch/System/ConsoleCancelEventArgs.hpp
sgf/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
2
2020-02-01T02:19:01.000Z
2021-12-30T06:44:00.000Z
/// @file /// @brief Contains Switch::System::ConsoleCancelEventArgs class. #pragma once #include "ConsoleSpecialKey.hpp" #include "EventArgs.hpp" #include "../Property.hpp" /// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more. namespace Switch { /// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. namespace System { /// @brief Provides data for the Console::CancelKeyPress event. This class cannot be inherited. /// @par Library /// Switch.Core /// @remarks A user can interrupt a console application process by simultaneously pressing the Control modifier key and the C console key (Ctrl+C), or the Control modifier key and the Break console key (Ctrl+Break). The Switch consequently provides a ConsoleCancelEventArgs object to the event handler for the Console.CancelKeyPress event to specify whether the process should be cancelled. /// @remarks If the Cancel property is set to true in the event handler, the process is resumed; otherwise, the process is terminated. By default, the value of the ConsoleCancelEventArgs property is false, and the process terminates. class core_export_ ConsoleCancelEventArgs final : public EventArgs { public: /// @brief Initializes a new instance of the GiveFeedbackEventArgs class. ConsoleCancelEventArgs() {} /// @brief Initializes a new instance of the GiveFeedbackEventArgs class. /// @param effects The type of drag-and-drop operation. Possible values are obtained by applying the bitwise OR (|) operation to the constants defined in the DragDropEffects. /// @param true if default pointers are used; otherwise, false. ConsoleCancelEventArgs(bool cancel, ConsoleSpecialKey specialKey) : cancel(cancel), specialKey(specialKey) {} /// @cond ConsoleCancelEventArgs(const ConsoleCancelEventArgs& consoleCancelSpecialEventArgs) : cancel(consoleCancelSpecialEventArgs.cancel), specialKey(consoleCancelSpecialEventArgs.specialKey) {} ConsoleCancelEventArgs& operator=(const ConsoleCancelEventArgs& consoleCancelSpecialEventArgs) { this->cancel = consoleCancelSpecialEventArgs.cancel; this->specialKey = consoleCancelSpecialEventArgs.specialKey; return *this; } /// @endcond /// @brief Gets or sets a value that indicates whether simultaneously pressing the Control modifier key and the C console key (Ctrl+C) or the Ctrl+Break keys terminates the current process. The default is false, which terminates the current process. /// @return true if the current process should resume when the event handler concludes; false if the current process should terminate. The default value is false; the current process terminates when the event handler returns. If true, the current process continues. property_<bool> Cancel { get_ {return this->cancel;}, set_ {this->cancel = value;} }; /// @brief Gets the combination of modifier and console keys that interrupted the current process. /// @return One of the enumeration values that specifies the key combination that interrupted the current process. There is no default value. property_<ConsoleSpecialKey, readonly_> SpecialKey { get_ {return this->specialKey;} }; private: bool cancel = true; ConsoleSpecialKey specialKey = static_cast<ConsoleSpecialKey>(0); }; } } using namespace Switch;
62.206897
394
0.75
victor-timoshin
b42474870b89178710a8a1df6156ce4f99d654e2
3,335
cpp
C++
Code/EditorPlugins/Assets/EnginePluginAssets/MeshAsset/MeshView.cpp
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
703
2015-03-07T15:30:40.000Z
2022-03-30T00:12:40.000Z
Code/EditorPlugins/Assets/EnginePluginAssets/MeshAsset/MeshView.cpp
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
233
2015-01-11T16:54:32.000Z
2022-03-19T18:00:47.000Z
Code/EditorPlugins/Assets/EnginePluginAssets/MeshAsset/MeshView.cpp
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
101
2016-10-28T14:05:10.000Z
2022-03-30T19:00:59.000Z
#include <EnginePluginAssets/EnginePluginAssetsPCH.h> #include <EnginePluginAssets/MeshAsset/MeshContext.h> #include <EnginePluginAssets/MeshAsset/MeshView.h> #include <RendererCore/Debug/DebugRenderer.h> #include <RendererCore/RenderWorld/RenderWorld.h> #include <RendererFoundation/Resources/Buffer.h> ezMeshViewContext::ezMeshViewContext(ezMeshContext* pMeshContext) : ezEngineProcessViewContext(pMeshContext) { m_pContext = pMeshContext; // Start with something valid. m_Camera.SetCameraMode(ezCameraMode::PerspectiveFixedFovX, 45.0f, 0.05f, 10000.0f); m_Camera.LookAt(ezVec3(1, 1, 1), ezVec3::ZeroVector(), ezVec3(0.0f, 0.0f, 1.0f)); } ezMeshViewContext::~ezMeshViewContext() {} bool ezMeshViewContext::UpdateThumbnailCamera(const ezBoundingBoxSphere& bounds) { return !FocusCameraOnObject(m_Camera, bounds, 45.0f, -ezVec3(5, -2, 3)); } ezViewHandle ezMeshViewContext::CreateView() { ezView* pView = nullptr; ezRenderWorld::CreateView("Mesh Editor - View", pView); pView->SetRenderPipelineResource(CreateDefaultRenderPipeline()); ezEngineProcessDocumentContext* pDocumentContext = GetDocumentContext(); pView->SetWorld(pDocumentContext->GetWorld()); pView->SetCamera(&m_Camera); return pView->GetHandle(); } void ezMeshViewContext::SetCamera(const ezViewRedrawMsgToEngine* pMsg) { if (m_pContext->m_bDisplayGrid) { ezEngineProcessViewContext::DrawSimpleGrid(); } ezEngineProcessViewContext::SetCamera(pMsg); const ezUInt32 viewHeight = pMsg->m_uiWindowHeight; auto hMesh = m_pContext->GetMesh(); if (hMesh.IsValid()) { ezResourceLock<ezMeshResource> pMesh(hMesh, ezResourceAcquireMode::AllowLoadingFallback); ezResourceLock<ezMeshBufferResource> pMeshBuffer(pMesh->GetMeshBuffer(), ezResourceAcquireMode::AllowLoadingFallback); auto& bufferDesc = ezGALDevice::GetDefaultDevice()->GetBuffer(pMeshBuffer->GetVertexBuffer())->GetDescription(); ezUInt32 uiNumVertices = bufferDesc.m_uiTotalSize / bufferDesc.m_uiStructSize; ezUInt32 uiNumTriangles = pMeshBuffer->GetPrimitiveCount(); const ezBoundingBox& bbox = pMeshBuffer->GetBounds().GetBox(); ezUInt32 uiNumUVs = 0; ezUInt32 uiNumColors = 0; for (auto& vertexStream : pMeshBuffer->GetVertexDeclaration().m_VertexStreams) { if (vertexStream.m_Semantic >= ezGALVertexAttributeSemantic::TexCoord0 && vertexStream.m_Semantic <= ezGALVertexAttributeSemantic::TexCoord9) { ++uiNumUVs; } else if (vertexStream.m_Semantic >= ezGALVertexAttributeSemantic::Color0 && vertexStream.m_Semantic <= ezGALVertexAttributeSemantic::Color7) { ++uiNumColors; } } ezStringBuilder sText; sText.AppendFormat("Triangles: \t{}\t\n", uiNumTriangles); sText.AppendFormat("Vertices: \t{}\t\n", uiNumVertices); sText.AppendFormat("UV Channels: \t{}\t\n", uiNumUVs); sText.AppendFormat("Color Channels: \t{}\t\n", uiNumColors); sText.AppendFormat("Bytes Per Vertex: \t{}\t\n", bufferDesc.m_uiStructSize); sText.AppendFormat("Bounding Box: \twidth={0}, depth={1}, height={2}\t", ezArgF(bbox.GetHalfExtents().x * 2, 2), ezArgF(bbox.GetHalfExtents().y * 2, 2), ezArgF(bbox.GetHalfExtents().z * 2, 2)); ezDebugRenderer::DrawInfoText(m_hView, ezDebugRenderer::ScreenPlacement::BottomLeft, "AssetStats", sText); } }
37.47191
147
0.746327
Tekh-ops
b42643e05a858492cc25fc3056cb58f131dbc0d1
7,111
cpp
C++
Sources/Tools/EPI/Document/DocumentModel.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
2
2015-04-16T01:05:53.000Z
2019-08-26T07:38:43.000Z
Sources/Tools/EPI/Document/DocumentModel.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
Sources/Tools/EPI/Document/DocumentModel.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider, * Jérémie Comarmond, Didier Colin. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "DocumentModel.h" #include <QMessageBox> #include <Universe/Node.h> #include <EPI/ImportInfo/ImportModelInfo.h> #include <EPI/Document/Properties/PtyDocModel.moc.h> #include <EPI/Document/Properties/PtyDocInformation.moc.h> #include <EPI/Document/Properties/PtyModel.moc.h> #include <EPI/Document/Properties/PtyTransform.moc.h> #include <EPI/Document/Tools.h> #include <QtToolbox/VFSDialog.moc.h> #include <EPI/Document/GuiDescription.h> #include <EPI/DocumentRenderer.h> namespace EPI { //----------------------------------------------------------------------------- DocumentModel::DocumentModel(GuiDocument& guiGoc, const Ptr<DocumentRenderer>& pDocRdr, const Ptr<ImportModelInfo>& pModelInfo) : DocumentBase(guiGoc, DOC_MODEL, pDocRdr) { Ptr<GuiDescription> pGuiDesc(new GuiDescription()); Core::List<EViewportCameraNavigation> viewCameraNavigation; viewCameraNavigation.push_back(VIEWPORT_CAMERA_ORBITAL); viewCameraNavigation.push_back(VIEWPORT_CAMERA_QUAKE); pGuiDesc->setViewportCameraNavigations(viewCameraNavigation); Core::List<EViewportPickingType> viewPickingTypes; viewPickingTypes.push_back(VIEWPORT_PICKING_PTY); pGuiDesc->setViewportPickingTypes(viewPickingTypes); setGuiDescription(pGuiDesc); LM_DEBUG_PTR_CAST<PyDocumentInformation> (getPyDocumentInformation())->setTitle(pModelInfo->modelName); Ptr<Property> pPtyDocModel (new PtyDocModel(guiGoc, getWorld(), getStateRecorder(), pModelInfo, L"Model-Editing")); getPropertyDocumentContent()->addChild(pPtyDocModel); setGenerationProperty(pPtyDocModel); } //----------------------------------------------------------------------------- DocumentModel::~DocumentModel() { } //----------------------------------------------------------------------------- Ptr<Property> DocumentModel::getDefaultProperty() const { return LM_DEBUG_PTR_CAST<PtyDocModel>(getPropertyDocumentContent()->getChild(0))->getPtyModel(); } //----------------------------------------------------------------------------- Core::Orientationf DocumentModel::getDefaultCameraOrientation() const { return Core::Orientationf (Core::deg2rad(-10), Core::deg2rad(180), Core::deg2rad(0)); } //----------------------------------------------------------------------------- Core::Vector3f DocumentModel::getDefaultCameraTargetPosition() const { Ptr<PtyTransform> pPtyTrans; pPtyTrans = LM_DEBUG_PTR_CAST<PtyTransform>(LM_DEBUG_PTR_CAST<PtyModel>(getDefaultProperty())->getPtyTransform()); return pPtyTrans->getCenterBoundingBoxInWorldAxis(); } //----------------------------------------------------------------------------- void DocumentModel::save() { if (getTitle().startsWith(L"/") == true) { saveFile(getTitle()); } else { saveAs(); } } //----------------------------------------------------------------------------- void DocumentModel::saveAs() { QtToolbox::VFSDialog dlg(*getDocumentRenderer()->getVFS(), QtToolbox::VFSD_SAVE, DOCUMENT_MODEL_EXT, NULL); if(dlg.exec()) { Core::String fileName = dlg.getSelectedFile(); saveFile(fileName); Ptr<PyDocumentInformation> pPinfo = LM_DEBUG_PTR_CAST<PyDocumentInformation>(getPyDocumentInformation()); pPinfo->setTitle(fileName); } } //----------------------------------------------------------------------------- void DocumentModel::saveFile(const Core::String & fileName) { LM_DEBUG_PTR_CAST<PtyDocModel>(getPropertyDocumentContent()->getChild(0))->save(fileName); setModified(false); } //----------------------------------------------------------------------------- Ptr<Universe::World> DocumentModel::getWorldDeco() { Ptr<PtyDocModel> pPtyDocModel = LM_DEBUG_PTR_CAST<PtyDocModel>(getPropertyDocumentContent()->getChild(0)); if (_worldDecoPath != pPtyDocModel->getWorldDecoPath()) { _worldDecoPath = pPtyDocModel->getWorldDecoPath(); _pWorldDeco = null; if (_worldDecoPath != L"") { _pWorldDeco = Ptr<Universe::World>( new Universe::World(getDocumentRenderer()->getRenderer(), getDocumentRenderer()->getVFS(), null, getDocumentRenderer()->getAudioDevice())); _pWorldDeco->getNodeListener()->setGain(0.f); try { Ptr<Core::InputStream> pInput = getDocumentRenderer()->getVFS()->readFile(_worldDecoPath); Core::XMLDocument xmlDocument; xmlDocument.loadDocument(*pInput); _pWorldDeco->importWorldXML(xmlDocument); } catch(Core::Exception & e) { String message; message << L"An exception has been caught while extracting data from the XML file :\n" << e.getMessage(); QMessageBox::critical( NULL, "Nyx", Core::String8(message).c_str()); } copyEnvironnementParam(*getWorld(), *_pWorldDeco); configWorldDeco(getWorld(), _pWorldDeco); } } return _pWorldDeco; } //----------------------------------------------------------------------------- Ptr<Property> DocumentModel::getPtyForEdition() const { return getDefaultProperty(); } //----------------------------------------------------------------------------- } // namespace EPI
42.580838
189
0.61651
benkaraban
b42af4eb28253ed0b82ea16a766861c58fb13614
3,387
cpp
C++
Code/GraphMol/FileParsers/testExtendedStereoParsing.cpp
jungb-basf/rdkit
5d0eb77c655b6ba91f0891e7dc51e658aced3d00
[ "BSD-3-Clause" ]
4
2020-12-29T14:52:15.000Z
2021-08-28T08:12:45.000Z
Code/GraphMol/FileParsers/testExtendedStereoParsing.cpp
jungb-basf/rdkit
5d0eb77c655b6ba91f0891e7dc51e658aced3d00
[ "BSD-3-Clause" ]
9
2016-08-08T13:53:40.000Z
2020-03-08T05:52:07.000Z
Code/GraphMol/FileParsers/testExtendedStereoParsing.cpp
bp-kelley/rdkit
e0de7c9622ce73894b1e7d9568532f6d5638058a
[ "BSD-3-Clause" ]
4
2020-03-30T04:00:53.000Z
2021-02-25T23:11:52.000Z
// // Copyright (C) 2018 T5 Informatics GmbH // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <RDGeneral/RDLog.h> #include <GraphMol/RDKitBase.h> #include <GraphMol/StereoGroup.h> #include "FileParsers.h" #include "MolFileStereochem.h" #include <RDGeneral/FileParseException.h> #include <RDGeneral/BadFileException.h> #include <clocale> #include <cstdlib> #include <string> #include <fstream> #include <memory> using namespace RDKit; std::unique_ptr<RWMol> readTestFile(const std::string &baseName) { std::string rdbase = getenv("RDBASE"); std::string fName = rdbase + "/Code/GraphMol/FileParsers/test_data/" + baseName; auto m = MolFileToMol(fName); return std::unique_ptr<RWMol>(m); } void testOr() { BOOST_LOG(rdInfoLog) << "testing extended stereo parsing with an OR block" << std::endl; auto m = readTestFile("two_centers_or.mol"); TEST_ASSERT(m.get()); TEST_ASSERT(m->getNumAtoms() == 8); auto stereo_groups = m->getStereoGroups(); TEST_ASSERT(stereo_groups.size() == 2); TEST_ASSERT(stereo_groups[0].getGroupType() == RDKit::StereoGroupType::STEREO_ABSOLUTE); TEST_ASSERT(stereo_groups[0].getAtoms().size() == 1u); TEST_ASSERT(stereo_groups[1].getGroupType() == RDKit::StereoGroupType::STEREO_OR); TEST_ASSERT(stereo_groups[1].getAtoms().size() == 2u); BOOST_LOG(rdInfoLog) << "done" << std::endl; } void testAnd() { BOOST_LOG(rdInfoLog) << "testing extended stereo parsing with an AND block" << std::endl; auto m = readTestFile("two_centers_and.mol"); TEST_ASSERT(m.get()); TEST_ASSERT(m->getNumAtoms() == 8); auto stereo_groups = m->getStereoGroups(); TEST_ASSERT(stereo_groups.size() == 2); TEST_ASSERT(stereo_groups[0].getGroupType() == RDKit::StereoGroupType::STEREO_ABSOLUTE); TEST_ASSERT(stereo_groups[1].getGroupType() == RDKit::StereoGroupType::STEREO_AND); BOOST_LOG(rdInfoLog) << "done" << std::endl; } void testWrite() { BOOST_LOG(rdInfoLog) << "testing extended stereo file writing" << std::endl; auto m0 = readTestFile("two_centers_and.mol"); TEST_ASSERT(m0.get()); std::string block = RDKit::MolToMolBlock(*m0); auto m1 = RDKit::MolBlockToMol(block); // Check that the extended stereo information has the same extended stereo // types and same atoms marked for extended stereo. auto stereo_groups0 = m0->getStereoGroups(); auto stereo_groups1 = m1->getStereoGroups(); TEST_ASSERT(stereo_groups0.size() == stereo_groups1.size()); for (unsigned i = 0u; i < 2; ++i) { TEST_ASSERT(stereo_groups0[i].getGroupType() == stereo_groups1[i].getGroupType()); TEST_ASSERT(stereo_groups0[i].getAtoms().size() == stereo_groups1[i].getAtoms().size()); for (auto &&atom0 = stereo_groups0[i].getAtoms().begin(), atom1 = stereo_groups1[i].getAtoms().begin(); atom0 != stereo_groups0[i].getAtoms().end(); ++atom0, ++atom1) { TEST_ASSERT((*atom0)->getIdx() == (*atom1)->getIdx()); } } delete (m1); BOOST_LOG(rdInfoLog) << "done" << std::endl; } int main(int argc, char *argv[]) { (void)argc; (void)argv; testOr(); testAnd(); testWrite(); return 0; }
31.361111
86
0.674343
jungb-basf
b42cde325aa346417b0947f8751ccdc30ea6d230
11,898
cpp
C++
Sources/UI/Controller/window_manager.cpp
ValtoFrameworks/ClanLib
2d6b59386ce275742653b354a1daab42cab7cb3e
[ "Linux-OpenIB" ]
null
null
null
Sources/UI/Controller/window_manager.cpp
ValtoFrameworks/ClanLib
2d6b59386ce275742653b354a1daab42cab7cb3e
[ "Linux-OpenIB" ]
null
null
null
Sources/UI/Controller/window_manager.cpp
ValtoFrameworks/ClanLib
2d6b59386ce275742653b354a1daab42cab7cb3e
[ "Linux-OpenIB" ]
null
null
null
/* ** ClanLib SDK ** Copyright (c) 1997-2016 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Magnus Norddahl */ #include "UI/precomp.h" #include "API/UI/Controller/window_manager.h" #include "API/UI/UIThread/ui_thread.h" #include "API/Display/Window/display_window_description.h" #include "API/Display/Window/display_window.h" #include "API/Display/2D/canvas.h" #include "API/Display/2D/image.h" #include "API/Display/System/run_loop.h" #include "API/Display/Image/pixel_buffer.h" #include "API/Core/IOData/path_help.h" #include <map> namespace clan { class WindowManagerImpl { public: bool exit_on_last_close = true; std::map<WindowController *, std::shared_ptr<WindowController>> windows; }; ///////////////////////////////////////////////////////////////////////// class WindowControllerImpl { public: std::string title; Sizef initial_size; bool frame_geometry = true; bool resizable = true; std::vector<std::string> icon_images; std::shared_ptr<View> root_view = std::make_shared<View>(); WindowManager *manager = nullptr; std::shared_ptr<TopLevelWindow> window; std::weak_ptr<View> modal_owner; }; ///////////////////////////////////////////////////////////////////////// WindowManager::WindowManager() : impl(new WindowManagerImpl) { } WindowManager::~WindowManager() { } void WindowManager::set_exit_on_last_close(bool enable) { impl->exit_on_last_close = enable; } void WindowManager::present_main(const std::shared_ptr<WindowController> &controller, DisplayWindowDescription* desc, WindowShowType show_type) { auto& controller_impl = controller->impl; if (controller_impl->manager) return; DisplayWindowDescription simple_desc; if (!desc) { simple_desc.set_main_window(); simple_desc.set_visible(false); simple_desc.set_title(controller->title()); simple_desc.set_allow_resize(controller_impl->resizable); if (controller_impl->initial_size != Sizef()) simple_desc.set_size(controller_impl->initial_size, !controller_impl->frame_geometry); desc = &simple_desc; } controller_impl->manager = this; controller_impl->window = std::make_shared<TopLevelWindow>(*desc); auto& root_view = controller->root_view(); controller_impl->window->set_root_view(root_view); DisplayWindow display_window = controller_impl->window->display_window(); controller->slots.connect(display_window.sig_window_close(), bind_member(controller.get(), &WindowController::dismiss)); impl->windows[controller.get()] = controller; if (controller_impl->initial_size == Sizef()) { Canvas canvas = root_view->canvas(); float width = root_view->preferred_width(canvas); float height = root_view->preferred_height(canvas, width); Rectf content_box(0.0f, 0.0f, width, height); Rectf margin_box = ViewGeometry::from_content_box(root_view->style_cascade(), content_box).margin_box(); display_window.set_size(margin_box.get_width(), margin_box.get_height(), true); } auto icon_images = controller_impl->icon_images; if (!icon_images.empty()) { display_window.set_large_icon(PixelBuffer(icon_images.front())); display_window.set_large_icon(PixelBuffer(icon_images.back())); } controller_impl->window->show(show_type); } void WindowManager::present_modal(View *owner, const std::shared_ptr<WindowController> &controller, DisplayWindowDescription* desc) { auto& controller_impl = controller->impl; if (controller_impl->manager) return; Pointf screen_pos = owner->to_screen_pos(owner->geometry().content_box().get_center()); DisplayWindowDescription simple_desc; DisplayWindow owner_display_window = owner->view_tree()->display_window(); if (!desc) { simple_desc.set_dialog_window(); simple_desc.set_visible(false); simple_desc.set_title(controller->title()); simple_desc.show_minimize_button(false); simple_desc.show_maximize_button(false); simple_desc.set_allow_resize(controller_impl->resizable); if (owner_display_window) simple_desc.set_owner_window(owner_display_window); if (controller_impl->initial_size != Sizef()) simple_desc.set_size(controller_impl->initial_size, !controller_impl->frame_geometry); desc = &simple_desc; } controller_impl->modal_owner = owner->shared_from_this(); controller_impl->manager = this; controller_impl->window = std::make_shared<TopLevelWindow>(*desc); auto& root_view = controller->root_view(); controller_impl->window->set_root_view(root_view); DisplayWindow controller_display_window = controller_impl->window->display_window(); controller->slots.connect(controller_display_window.sig_window_close(), bind_member(controller.get(), &WindowController::dismiss)); impl->windows[controller.get()] = controller; if (controller_impl->initial_size == Sizef()) { Canvas canvas = root_view->canvas(); float width = root_view->preferred_width(canvas); float height = root_view->preferred_height(canvas, width); Rectf content_box(screen_pos.x - width * 0.5f, screen_pos.y - height * 0.5f, screen_pos.x + width * 0.5f, screen_pos.y + height * 0.5f); Rectf margin_box = ViewGeometry::from_content_box(root_view->style_cascade(), content_box).margin_box(); controller_display_window.set_position(margin_box, true); } auto icon_images = controller_impl->icon_images; if (!icon_images.empty()) { controller_display_window.set_large_icon(PixelBuffer(icon_images.front())); controller_display_window.set_large_icon(PixelBuffer(icon_images.back())); } controller_impl->window->show(WindowShowType::show); if (owner_display_window) owner_display_window.set_enabled(false); } void WindowManager::present_popup(View *owner, const Pointf &pos, const std::shared_ptr<WindowController> &controller, DisplayWindowDescription* desc) { auto& controller_impl = controller->impl; if (controller_impl->manager) return; Pointf screen_pos = owner->to_screen_pos(pos); DisplayWindowDescription simple_desc; DisplayWindow owner_display_window = owner->view_tree()->display_window(); if (!desc) { simple_desc.set_popup_window(); simple_desc.set_visible(false); simple_desc.set_topmost(true); simple_desc.set_no_activate(true); simple_desc.show_caption(false); simple_desc.show_sysmenu(false); simple_desc.show_minimize_button(false); simple_desc.show_maximize_button(false); if (owner_display_window) simple_desc.set_owner_window(owner_display_window); if (controller_impl->initial_size != Sizef()) simple_desc.set_size(controller_impl->initial_size, !controller_impl->frame_geometry); desc = &simple_desc; } controller_impl->manager = this; controller_impl->window = std::make_shared<TopLevelWindow>(*desc); auto& root_view = controller->root_view(); controller_impl->window->set_root_view(root_view); if (owner_display_window) controller->slots.connect(owner_display_window.sig_lost_focus(), bind_member(controller.get(), &WindowController::dismiss)); impl->windows[controller.get()] = controller; if (controller_impl->initial_size == Sizef()) { Canvas canvas = root_view->canvas(); float width = root_view->preferred_width(canvas); float height = root_view->preferred_height(canvas, width); Rectf content_box(screen_pos.x, screen_pos.y, screen_pos.x + width, screen_pos.y + height); Rectf margin_box = ViewGeometry::from_content_box(root_view->style_cascade(), content_box).margin_box(); DisplayWindow controller_display_window = controller_impl->window->display_window(); controller_display_window.set_position(margin_box, false); } controller_impl->window->show(WindowShowType::show_no_activate); } /// Translates a call to all top-level windows. void WindowManager::flip(int interval) { for (auto& map_item : impl->windows) { auto& top_level_window = map_item.first->impl->window; top_level_window->display_window().flip(interval); } } ///////////////////////////////////////////////////////////////////////// WindowController::WindowController() : impl(new WindowControllerImpl) { } WindowController::~WindowController() { } const std::shared_ptr<View> &WindowController::root_view() const { return impl->root_view; } void WindowController::set_root_view(std::shared_ptr<View> root_view) { impl->root_view = root_view; } const std::string &WindowController::title() const { return impl->title; } void WindowController::set_title(const std::string &title) { impl->title = title; if (impl->window) { DisplayWindow display_window = impl->window->display_window(); if (display_window) display_window.set_title(title); } } void WindowController::set_frame_size(const Sizef &size, bool resizable) { impl->initial_size = size; impl->frame_geometry = true; impl->resizable = resizable; if (impl->window) { DisplayWindow display_window = impl->window->display_window(); if (display_window) display_window.set_size(size.width, size.height, false); } } void WindowController::set_content_size(const Sizef &size, bool resizable) { impl->initial_size = size; impl->frame_geometry = false; impl->resizable = resizable; if (impl->window) { DisplayWindow display_window = impl->window->display_window(); if (display_window) display_window.set_size(size.width, size.height, true); } } void WindowController::set_resizable(bool resizable) { impl->resizable = resizable; } bool WindowController::resizable() { return impl->resizable; } void WindowController::set_icon(const std::vector<std::string> &icon_images) { impl->icon_images = icon_images; if (impl->window) { DisplayWindow display_window = impl->window->display_window(); if (display_window && !icon_images.empty()) { display_window.set_large_icon(PixelBuffer(icon_images.front())); display_window.set_large_icon(PixelBuffer(icon_images.back())); } } } void WindowController::dismiss() { if (impl->manager) { auto modal_owner = impl->modal_owner.lock(); if (modal_owner && modal_owner->view_tree()) { DisplayWindow display_window = modal_owner->view_tree()->display_window(); if (display_window) { display_window.set_enabled(true); if (impl->window->display_window().has_focus()) display_window.show(true); // activate parent to workaround bug in Windows in some situations } } auto manager = impl->manager; // Reset fields before erase because 'this' might be destroyed if 'windows' had the last reference impl->window.reset(); impl->modal_owner.reset(); auto &windows = manager->impl->windows; auto it = windows.find(this); if (it != windows.end()) windows.erase(it); if (manager->impl->exit_on_last_close && windows.empty()) RunLoop::exit(); } } void WindowController::immediate_update() { impl->window->immediate_update(); } }
31.39314
151
0.726425
ValtoFrameworks
b4329ed890ebebfbb0ee4738c654c77080fe7027
25,786
cpp
C++
_studio/shared/umc/codec/mpeg2_dec/src/umc_mpeg2_dec.cpp
TianmiChen/MediaSDK-1
cff8ca88a06609685d37d86d47a31777448aaad8
[ "MIT" ]
1
2019-09-26T23:47:58.000Z
2019-09-26T23:47:58.000Z
_studio/shared/umc/codec/mpeg2_dec/src/umc_mpeg2_dec.cpp
TianmiChen/MediaSDK-1
cff8ca88a06609685d37d86d47a31777448aaad8
[ "MIT" ]
null
null
null
_studio/shared/umc/codec/mpeg2_dec/src/umc_mpeg2_dec.cpp
TianmiChen/MediaSDK-1
cff8ca88a06609685d37d86d47a31777448aaad8
[ "MIT" ]
null
null
null
// Copyright (c) 2017-2018 Intel Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "umc_defs.h" #if defined (MFX_ENABLE_MPEG2_VIDEO_DECODE) #include <vector> #include "vm_sys_info.h" #include "vm_time.h" #include "umc_video_data.h" #include "umc_memory_allocator.h" #include "umc_mpeg2_dec_base.h" #include "umc_mpeg2_dec.h" #include "mfx_trace.h" #include "mfx_common_int.h" using namespace UMC; static void ClearUserDataVector(sVideoFrameBuffer::UserDataVector & data) { for (sVideoFrameBuffer::UserDataVector::iterator it = data.begin(), et = data.end(); it != et; ++it) { free(it->first); } data.clear(); } bool MPEG2VideoDecoderBase::InitTables() { return true; } void MPEG2VideoDecoderBase::DeleteHuffmanTables() { } bool MPEG2VideoDecoderBase::DeleteTables() { // release tools if (video_ptr) { free(video_ptr); video_ptr = NULL; } for(int i = 0; i < 2*DPB_SIZE; i++) { delete[] Video[i]; Video[i] = NULL; ClearUserDataVector(frame_user_data_v[i]); } // release tables DeleteHuffmanTables(); return UMC_OK; } Status MPEG2VideoDecoderBase::ThreadingSetup(int32_t maxThreads) { int32_t i,j; int32_t aligned_size; m_nNumberOfThreads = maxThreads; if (0 >= m_nNumberOfThreads) m_nNumberOfThreads = 1; else if (8 < m_nNumberOfThreads) m_nNumberOfThreads = 8; aligned_size = (int32_t)((sizeof(VideoContext) + 15) &~ 15); size_t size = m_nNumberOfThreads*aligned_size*2*DPB_SIZE; video_ptr = (uint8_t*)malloc(size); if (NULL == video_ptr) return UMC_ERR_ALLOC; memset(video_ptr, 0, size); uint8_t * temp = video_ptr; for(j = 0; j < 2*DPB_SIZE; j++) { Video[j] = new VideoContext*[m_nNumberOfThreads]; for(i = 0; i < m_nNumberOfThreads; i++) { Video[j][i] = (VideoContext*)temp; temp += aligned_size; } } m_nNumberOfAllocatedThreads = m_nNumberOfThreads; return UMC_OK; } Status MPEG2VideoDecoderBase::Init(BaseCodecParams *pInit) { int i; VideoDecoderParams *init = DynamicCast<VideoDecoderParams, BaseCodecParams>(pInit); if(!init) return UMC_ERR_INIT; Reset(); m_ClipInfo = init->info; m_lFlags = init->lFlags; //m_bExternalSurface = (init->lFlags & FLAG_VDEC_EXTERNAL_SURFACE_USE) != 0; // creates thread's structures (Video[]) if(UMC_OK != ThreadingSetup(init->numThreads)) return UMC_ERR_ALLOC; if (0 != init->info.framerate) { m_isFrameRateFromInit = true; sequenceHeader.delta_frame_time = init->info.framerate; } if (0 != init->info.aspect_ratio_width && 0 != init->info.aspect_ratio_height) { m_isAspectRatioFromInit = true; } if(UMC_OK != DecodeSequenceHeader( 0 , 0)) return (UMC_ERR_INVALID_PARAMS); // work-arounf for mpeg1 m_ClipInfo.stream_type = UNDEF_VIDEO; if (false == InitTables()) return UMC_ERR_INIT; sequenceHeader.frame_count = 0; sequenceHeader.stream_time = 0; frame_buffer.latest_prev = -1; frame_buffer.common_curr_index = -1; frame_buffer.latest_next = -1; frame_buffer.retrieve = -1; for(i = 0; i < 2*DPB_SIZE; i++) { frame_buffer.ret_array[i] = -1; frame_buffer.curr_index[i] = -1; frame_buffer.field_buffer_index[i] = 0; frame_buffer.frame_p_c_n[i].frame_time = -1; frame_buffer.frame_p_c_n[i].duration = 0; frame_buffer.frame_p_c_n[i].IsUserDataDecoded = false; frame_buffer.frame_p_c_n[i].us_data_size = 0; ClearUserDataVector(frame_user_data_v[i]); frame_buffer.frame_p_c_n[i].va_index = -1; task_locked[i] = -1; m_dTime[i].time = -1.; m_dTime[i].isOriginal = false; m_nNumberOfThreadsTask[i] = m_nNumberOfThreads; } m_dTimeCalc = -1.; frame_buffer.ret_array_curr = 0; frame_buffer.ret_index = -1; frame_buffer.ret_array_free = 0; frame_buffer.ret_array_len = 0; sequenceHeader.stream_time_temporal_reference = -1; sequenceHeader.stream_time = 0; m_SkipLevel = SKIP_NONE; m_IsSHDecoded = false; m_FirstHeaderAfterSequenceHeaderParsed = false; m_IsDataFirst = true; m_picture_coding_type_save = MPEG2_I_PICTURE; m_IsLastFrameProcessed = false; m_InitClipInfo = m_ClipInfo; return UMC_OK; } Status MPEG2VideoDecoderBase::PrepareBuffer(MediaData* data, int task_num) { VideoContext *video = Video[task_num][0]; uint8_t *ptr; size_t size; if (data == 0) { return UMC_OK; } ptr = (uint8_t*)data->GetDataPointer(); size = data->GetDataSize(); INIT_BITSTREAM(video->bs, ptr, ptr + size); return UMC_OK; } bool MPEG2VideoDecoderBase::IsPictureToSkip(int task_num) { if(frame_buffer.field_buffer_index[task_num] == 0) // not for second field { // sequenceHeader.stream_time_temporal_reference++; if(PictureHeader[task_num].picture_coding_type == MPEG2_I_PICTURE) { if(sequenceHeader.first_i_occure) sequenceHeader.first_p_occure = 1; sequenceHeader.first_i_occure = 1; if(m_SkipLevel == SKIP_ALL) { return true; } } else if(!sequenceHeader.first_i_occure) { // To support only P frames streams this check is disabled //return true; } else if(PictureHeader[task_num].picture_coding_type == MPEG2_P_PICTURE) { sequenceHeader.first_p_occure = 1; if(m_SkipLevel >= SKIP_PB) { return true; } } else if(PictureHeader[task_num].picture_coding_type == MPEG2_B_PICTURE) { if(m_SkipLevel >= SKIP_B) { return true; } } } return false; } //$$$$$$$$$$$$$$$$ //additional functions for UMC-MFX interaction Status MPEG2VideoDecoderBase::GetCCData(uint8_t* ptr, uint32_t *user_data_size, double & time_stamp, uint32_t bufsize) { if (m_user_ts_data.empty() || m_user_data.empty()) { *user_data_size = 0; time_stamp = 0.0; return UMC_OK; } time_stamp = m_user_ts_data.front(); uint8_t *p_user_data = m_user_data.front().first; *user_data_size = static_cast<uint32_t>(m_user_data.front().second); if (*user_data_size == 0 || p_user_data == nullptr) { m_user_ts_data.erase(m_user_ts_data.begin()); m_user_data.erase(m_user_data.begin()); *user_data_size = 0; time_stamp = 0.0; return UMC_OK; } if (bufsize < *user_data_size) { *user_data_size *= 8; time_stamp = 0.0; return UMC_ERR_NOT_ENOUGH_BUFFER; } std::copy(p_user_data, p_user_data + *user_data_size, ptr); *user_data_size *= 8; free(p_user_data); m_user_ts_data.erase(m_user_ts_data.begin()); m_user_data.erase(m_user_data.begin()); return UMC_OK; } Status MPEG2VideoDecoderBase::GetPictureHeader(MediaData* input, int task_num, int prev_task_num) { Status umcRes = UMC_OK; m_IsFrameSkipped = false; m_IsSHDecoded = false; if(task_num >= DPB_SIZE) frame_buffer.field_buffer_index[task_num] = 1; else frame_buffer.field_buffer_index[task_num] = 0; if(prev_task_num != -1) { sequenceHeader.mb_width[task_num] = sHSaved.mb_width; sequenceHeader.mb_height[task_num] = sHSaved.mb_height; sequenceHeader.numMB[task_num] = sHSaved.numMB; sequenceHeader.extension_start_code_ID[task_num] = sHSaved.extension_start_code_ID; sequenceHeader.scalable_mode[task_num] = sHSaved.scalable_mode; } frame_buffer.frame_p_c_n[task_num].IsUserDataDecoded = false; frame_buffer.frame_p_c_n[task_num].us_data_size = 0; if(input == NULL) { //if (m_lFlags & FLAG_VDEC_REORDER) { if(!m_IsLastFrameProcessed) { double currentTime = -1; bool isOriginal = false; frame_buffer.ret_index = frame_buffer.latest_next; frame_buffer.curr_index[task_num] = frame_buffer.latest_next; if(frame_buffer.latest_next >= 0) CalculateFrameTime(currentTime, &m_dTime[frame_buffer.ret_index].time, &isOriginal, task_num, true); frame_buffer.ret_index = -1; if(frame_buffer.latest_next >= 0) { frame_buffer.ret_array[frame_buffer.ret_array_free] = frame_buffer.latest_next; frame_buffer.ret_index = frame_buffer.latest_next; frame_buffer.ret_array_free++; if(frame_buffer.ret_array_free >= DPB_SIZE) frame_buffer.ret_array_free = 0; frame_buffer.ret_array_len++; } } m_IsLastFrameProcessed = true; } return UMC_OK; } PrepareBuffer(input, task_num); VideoContext *video = Video[task_num][0]; uint32_t code; if (!sequenceHeader.is_decoded) { if(UMC_OK != FindSequenceHeader(Video[task_num][0])) return (UMC_ERR_NOT_ENOUGH_DATA); umcRes = DecodeSequenceHeader(Video[task_num][0], task_num); if(UMC_OK != umcRes) return umcRes; } SHOW_BITS(video->bs, 32, code); do { GET_START_CODE(video->bs, code); // some headers are possible here if(code == (uint32_t)UMC_ERR_NOT_ENOUGH_DATA) { if(GET_OFFSET(video->bs) > 0) // some data was decoded return UMC_ERR_NOT_ENOUGH_DATA; else // no start codes found return UMC_ERR_SYNC; } if(code == SEQUENCE_END_CODE) continue; if(code != PICTURE_START_CODE) { Status s = DecodeHeader(code, video, task_num); if (s != UMC_OK) return s; } } while (code != PICTURE_START_CODE); umcRes = DecodeHeader(PICTURE_START_CODE, video, task_num); if(umcRes != UMC_OK) return umcRes; if(!m_IsFrameSkipped) { double currentTime = input->GetTime(); bool isOriginal = false; CalculateFrameTime(currentTime, &m_dTimeCalc, &isOriginal, task_num, false); if (0 <= frame_buffer.ret_index) { m_dTime[frame_buffer.ret_index].time = m_dTimeCalc; m_dTime[frame_buffer.ret_index].isOriginal = isOriginal; } frame_buffer.ret_index = -1; } if(m_IsDataFirst && PictureHeader[task_num].picture_coding_type != MPEG2_I_PICTURE) { m_IsDataFirst = false; // To support only P frames streams this check is disabled // return UMC_WRN_INVALID_STREAM; } m_IsDataFirst = false; if (m_IsFrameSkipped) { return UMC_ERR_NOT_ENOUGH_DATA; }//if (m_IsFrameSkipped) return (umcRes); } Status MPEG2VideoDecoderBase::ProcessRestFrame(int task_num) { MFX_AUTO_LTRACE(MFX_TRACE_LEVEL_HOTSPOTS, "MPEG2VideoDecoderBase::ProcessRestFrame"); Status umcRes = UMC_OK; VideoContext* video = Video[task_num][0]; int32_t i; Video[task_num][0]->slice_vertical_position = 1; m_nNumberOfThreadsTask[task_num] = m_nNumberOfThreads; sHSaved.mb_width = sequenceHeader.mb_width[task_num]; sHSaved.mb_height = sequenceHeader.mb_height[task_num]; sHSaved.numMB = sequenceHeader.numMB[task_num]; sHSaved.extension_start_code_ID = sequenceHeader.extension_start_code_ID[task_num]; sHSaved.scalable_mode = sequenceHeader.scalable_mode[task_num]; if (m_nNumberOfThreadsTask[task_num] > 1) { #define MAX_START_CODES 1024 uint8_t *start_ptr = GET_BYTE_PTR(video->bs); uint8_t *end_ptr = GET_END_PTR(video->bs)-3; uint8_t *ptr = start_ptr, *ptrz = start_ptr; uint8_t *prev_ptr; int32_t curr_thread; int32_t len = (int32_t)(end_ptr - start_ptr); int32_t j, start_count = 0; int32_t start_pos[MAX_START_CODES]; memset(start_pos,0,sizeof(int32_t)*MAX_START_CODES); for (start_count = 0; start_count < MAX_START_CODES; start_count++) { int32_t code; do { while (ptr < end_ptr && (ptr[0] || ptr[1] || ptr[2] > 1)) ptr++; ptrz = ptr; while (ptr < end_ptr && !ptr[2]) ptr++; } while (ptr < end_ptr && ptr[2] != 1); if (ptr >= end_ptr) { ptr = GET_END_PTR(video->bs); break; } code = ptr[3]; if (code > 0 && code < 0xb0) { // start of slice start_pos[start_count] = (int32_t)(ptrz - start_ptr); ptr += 4; } else break; } if (start_count == MAX_START_CODES) { while (ptr < end_ptr && (ptr[0] || ptr[1] || ptr[2] != 1 || (ptr[3] > 0 && ptr[3] < 0xb0))) ptr++; ptrz = ptr; } len = (int32_t)(ptrz - start_ptr); prev_ptr = start_ptr; curr_thread = 1; // 0th will be last int32_t taskNumThreads = m_nNumberOfThreadsTask[task_num]; for (i = 0, j = 0; i < taskNumThreads; i++) { int32_t approx = len * (i + 1) / m_nNumberOfThreadsTask[task_num]; if (start_pos[j] > approx) { m_nNumberOfThreadsTask[task_num] -= 1; // no data for thread - covered by previous continue; } while (j < start_count && start_pos[j] < approx) j++; if(j == start_count) { // it will be last thread -> to 0th SET_PTR(Video[task_num][0]->bs, prev_ptr) m_nNumberOfThreadsTask[task_num] = curr_thread; break; } INIT_BITSTREAM(Video[task_num][curr_thread]->bs, prev_ptr, start_ptr + start_pos[j]); curr_thread++; prev_ptr = start_ptr + start_pos[j]; } INIT_BITSTREAM(Video[task_num][0]->bs, prev_ptr, end_ptr + 3); } return umcRes; } Status MPEG2VideoDecoderBase::PostProcessUserData(int display_index) { Status umcRes = UMC_OK; if(frame_buffer.frame_p_c_n[display_index].IsUserDataDecoded) { MediaData ccData; { // TODO: implement payload limitation according to spec when it be ready. Currently ~10 seconds if (m_user_data.size() >= 300) { // assert(m_user_data.size() == m_user_ts_data.size()); int items_to_discard = (int)m_user_data.size() - 300; sVideoFrameBuffer::UserDataVector tmpvec(m_user_data.begin(), m_user_data.begin() + items_to_discard); ClearUserDataVector(tmpvec); m_user_data.erase(m_user_data.begin(), m_user_data.begin() + items_to_discard); m_user_ts_data.erase(m_user_ts_data.begin(), m_user_ts_data.begin() + items_to_discard); } size_t userDataCount = frame_user_data_v[display_index].size(); for (uint32_t i = 0; i < userDataCount; i += 1) { m_user_data.push_back(frame_user_data_v[display_index][i]); m_user_ts_data.push_back(m_dTime[display_index].time); } // memory ownership transfered to m_user_data, so just clear() frame_user_data_v[display_index].clear(); } } // if(frame_buffer.frame_p_c_n[display_index].IsUserDataDecoded) return umcRes; } // Close decoding Status MPEG2VideoDecoderBase::Close() { DeleteTables(); ClearUserDataVector(m_user_data); m_user_ts_data.clear(); if (shMask.memMask) { free(shMask.memMask); } shMask.memMask = NULL; shMask.memSize = 0; return UMC_OK; } MPEG2VideoDecoderBase::MPEG2VideoDecoderBase() : m_dTimeCalc(0) , m_picture_coding_type_save(MPEG2_I_PICTURE) , bNeedNewFrame(false) , m_SkipLevel(SKIP_NONE) , sequenceHeader() , sHSaved() , shMask() , m_signalInfo() , b_curr_number_backup(0) , first_i_occure_backup(0) , frame_count_backup(0) , video_ptr(NULL) , m_lFlags(0) , m_nNumberOfThreads(1) , m_nNumberOfAllocatedThreads(1) , m_IsFrameSkipped(false) , m_IsSHDecoded(false) , m_FirstHeaderAfterSequenceHeaderParsed(false) , m_IsDataFirst(true) , m_IsLastFrameProcessed(false) , m_isFrameRateFromInit(false) , m_isAspectRatioFromInit(false) , m_InitClipInfo() { for (int i = 0; i < 2*DPB_SIZE; i++) { Video[i] = NULL; memset(&PictureHeader[i], 0, sizeof(sPictureHeader)); } memset(task_locked, 0, sizeof(task_locked)); memset(m_nNumberOfThreadsTask, 0, sizeof(m_nNumberOfThreadsTask)); m_ClipInfo.clip_info.width = m_ClipInfo.clip_info.height= 100; m_ClipInfo.stream_type = UNDEF_VIDEO; sequenceHeader.profile = MPEG2_PROFILE_MAIN; sequenceHeader.level = MPEG2_LEVEL_MAIN; frame_buffer.allocated_cformat = NONE; m_user_data.clear(); m_user_ts_data.clear(); } MPEG2VideoDecoderBase::~MPEG2VideoDecoderBase() { m_isFrameRateFromInit = false; m_isAspectRatioFromInit = false; Close(); } Status MPEG2VideoDecoderBase::Reset() { sequenceHeader.is_decoded = false; sequenceHeader.first_i_occure = 0; sequenceHeader.first_p_occure = 0; sequenceHeader.broken_link = 0; sequenceHeader.closed_gop = 0; sequenceHeader.time_code.gop_picture = 0; sequenceHeader.time_code.gop_seconds = 0; sequenceHeader.time_code.gop_minutes = 0; sequenceHeader.time_code.gop_hours = 0; sequenceHeader.time_code.gop_drop_frame_flag = 0; sequenceHeader.stream_time = 0; //-sequenceHeader.delta_frame_time; sequenceHeader.frame_rate_extension_d = 0; sequenceHeader.frame_rate_extension_n = 0; sequenceHeader.frame_rate_code = 0; sequenceHeader.aspect_ratio_code = 0; sequenceHeader.chroma_format = 0; sequenceHeader.width = 0; sequenceHeader.height = 0; frame_buffer.latest_prev = -1; frame_buffer.common_curr_index = -1; frame_buffer.latest_next = -1; m_picture_coding_type_save = MPEG2_I_PICTURE; m_IsLastFrameProcessed = false; m_isFrameRateFromInit = false; m_isAspectRatioFromInit = false; for (int i = 0; i < 2*DPB_SIZE; i++) { PictureHeader[i].intra_vlc_format = 0; PictureHeader[i].curr_intra_dc_multi = intra_dc_multi[0]; frame_buffer.ret_array[i] = -1; frame_buffer.curr_index[i] = -1; frame_buffer.retrieve = -1; frame_buffer.field_buffer_index[i] = 0; frame_buffer.frame_p_c_n[i].frame_time = -1; frame_buffer.frame_p_c_n[i].duration = 0; frame_buffer.frame_p_c_n[i].IsUserDataDecoded = false; frame_buffer.frame_p_c_n[i].us_data_size = 0; ClearUserDataVector(frame_user_data_v[i]); frame_buffer.frame_p_c_n[i].va_index = -1; task_locked[i] = -1; m_dTime[i].time = -1.; m_dTime[i].isOriginal = false; m_nNumberOfThreadsTask[i] = m_nNumberOfThreads; } m_dTimeCalc = -1.; frame_buffer.ret_array_curr = 0; frame_buffer.ret_index = -1; frame_buffer.ret_array_free = 0; frame_buffer.ret_array_len = 0; m_SkipLevel = SKIP_NONE; if (shMask.memMask) { free(shMask.memMask); } shMask.memMask = NULL; shMask.memSize = 0; return UMC_OK; } Status MPEG2VideoDecoderBase::GetInfo(BaseCodecParams* info) { if(!info) return UMC_ERR_NULL_PTR; // BaseCodecParams info->profile = sequenceHeader.profile; info->level = sequenceHeader.level; VideoDecoderParams *pParams = DynamicCast<VideoDecoderParams> (info); if (pParams) { pParams->info = m_ClipInfo; pParams->lFlags = m_lFlags; pParams->lpMemoryAllocator = 0; pParams->numThreads = m_nNumberOfThreads; } return UMC_OK; } Status MPEG2VideoDecoderBase::GetSequenceHeaderMemoryMask(uint8_t *buffer, uint16_t &size) { if (!buffer) return UMC_ERR_NULL_PTR; if (size < shMask.memSize) return UMC_ERR_NOT_ENOUGH_BUFFER; std::copy(shMask.memMask, shMask.memMask + shMask.memSize, buffer); size = shMask.memSize; return UMC_OK; } Status MPEG2VideoDecoderBase::GetSignalInfoInformation(mfxExtVideoSignalInfo *buffer) { if (!buffer) return UMC_ERR_NULL_PTR; buffer->ColourDescriptionPresent = m_signalInfo.ColourDescriptionPresent; buffer->ColourPrimaries = m_signalInfo.ColourPrimaries; buffer->VideoFormat = m_signalInfo.VideoFormat; buffer->TransferCharacteristics = m_signalInfo.TransferCharacteristics; buffer->MatrixCoefficients = m_signalInfo.MatrixCoefficients; return UMC_OK; } Status MPEG2VideoDecoderBase::GetFrame(MediaData* , MediaData* ) { return UMC_OK; } void MPEG2VideoDecoderBase::ReadCCData(int task_num) { uint8_t* readptr; int32_t input_size; int32_t code; int32_t t_num = task_num < DPB_SIZE? task_num : task_num - DPB_SIZE; VideoContext* video = Video[task_num][0]; input_size = (int32_t)(GET_REMAINED_BYTES(video->bs)); readptr = GET_BYTE_PTR(video->bs); FIND_START_CODE(video->bs, code); if (code != UMC_ERR_NOT_ENOUGH_DATA) { input_size = (int32_t)(GET_BYTE_PTR(video->bs) - readptr); } // ------------------- { uint8_t *p = (uint8_t *) malloc(input_size + 4); if (!p) { frame_buffer.frame_p_c_n[t_num].IsUserDataDecoded = false; return; } p[0] = 0; p[1] = 0; p[2] = 1; p[3] = 0xb2; MFX_INTERNAL_CPY(p + 4, readptr, input_size); frame_user_data_v[t_num].push_back(std::make_pair(p, input_size + 4)); frame_buffer.frame_p_c_n[t_num].IsUserDataDecoded = true; } } #define SHIFT_PTR(oldptr, oldbase, newbase) \ ( (newbase) + ( (uint8_t*)(oldptr) - (uint8_t*)(oldbase) ) ) //Common functions int32_t MPEG2VideoDecoderBase::GetCurrDecodingIndex(int task_num) { int index = frame_buffer.curr_index[task_num] < DPB_SIZE? frame_buffer.curr_index[task_num] : frame_buffer.curr_index[task_num]-DPB_SIZE; return index; } int32_t MPEG2VideoDecoderBase::GetPrevDecodingIndex(int index) { return frame_buffer.frame_p_c_n[index].prev_index; } int32_t MPEG2VideoDecoderBase::GetNextDecodingIndex(int index) { return frame_buffer.frame_p_c_n[index].next_index; } int32_t MPEG2VideoDecoderBase::GetFrameType(int index) { return frame_buffer.frame_p_c_n[index].frame_type; } bool MPEG2VideoDecoderBase::IsFrameSkipped() { return m_IsFrameSkipped; } void MPEG2VideoDecoderBase::SetSkipMode(int32_t SkipMode) { m_SkipLevel = SkipMode; } double MPEG2VideoDecoderBase::GetCurrDecodedTime(int index) { return m_dTime[index].time; } bool MPEG2VideoDecoderBase::isOriginalTimeStamp(int index) { return m_dTime[index].isOriginal; } int32_t MPEG2VideoDecoderBase::GetCurrThreadsNum(int task_num) { return m_nNumberOfThreadsTask[task_num]; } bool MPEG2VideoDecoderBase::IsFramePictureStructure(int task_num) { return(PictureHeader[task_num].picture_structure == FRAME_PICTURE); } int32_t MPEG2VideoDecoderBase::GetDisplayIndex() { if(frame_buffer.ret_array[frame_buffer.ret_array_curr] != -1) { frame_buffer.retrieve = frame_buffer.ret_array[frame_buffer.ret_array_curr]; if (frame_buffer.retrieve >= DPB_SIZE) frame_buffer.retrieve -= DPB_SIZE; frame_buffer.ret_array[frame_buffer.ret_array_curr] = -1; frame_buffer.ret_array_curr++; if(frame_buffer.ret_array_curr >= DPB_SIZE) frame_buffer.ret_array_curr = 0; frame_buffer.ret_array_len--; } else { frame_buffer.retrieve = -1; } return frame_buffer.retrieve; } int32_t MPEG2VideoDecoderBase::GetRetBufferLen() { return frame_buffer.ret_array_len; } int MPEG2VideoDecoderBase::FindFreeTask() { int i; for(i = 0; i < DPB_SIZE; i++) if(task_locked[i] == -1) return i; return -1; } void MPEG2VideoDecoderBase::LockTask(int index) { task_locked[index] = 1; } void MPEG2VideoDecoderBase::UnLockTask(int index) { if (index >= DPB_SIZE) index -= DPB_SIZE; if (index < 0 || index >= DPB_SIZE) return; task_locked[index] = -1; task_locked[index + DPB_SIZE] = -1; } void MPEG2VideoDecoderBase::SetCorruptionFlag(int index) { if (index < 0) { return; } frame_buffer.frame_p_c_n[index].isCorrupted = true; } bool MPEG2VideoDecoderBase::GetCorruptionFlag(int index) { return frame_buffer.frame_p_c_n[index].isCorrupted; } #endif // MFX_ENABLE_MPEG2_VIDEO_DECODE
27.608137
118
0.65202
TianmiChen
b43513f0f0e91788d1f66ddd4b5ffaa59094f6a0
1,313
hpp
C++
src/Window.hpp
DomRe/eBookReaderNX
991121aa7c9ee508496f7c75fb7a8a0965b7b28b
[ "Apache-2.0" ]
14
2019-02-10T12:18:44.000Z
2021-03-29T04:24:55.000Z
src/Window.hpp
DomRe/eBookReaderNX
991121aa7c9ee508496f7c75fb7a8a0965b7b28b
[ "Apache-2.0" ]
1
2018-09-18T17:56:16.000Z
2018-09-19T02:47:06.000Z
src/Window.hpp
reworks/eBookReaderNX
991121aa7c9ee508496f7c75fb7a8a0965b7b28b
[ "Apache-2.0" ]
5
2019-05-21T19:15:58.000Z
2021-03-16T15:49:24.000Z
/// /// eBookReaderNX /// reworks /// Apache 2.0 License. /// #ifndef EBRNX_WINDOW_HPP_ #define EBRNX_WINDOW_HPP_ #include <SDL2/SDL_video.h> #include <SDL2/SDL_render.h> /// /// The Window class to hold data about /// an SDL_Window object. /// class Window { public: /// /// \brief Default constructor. /// /// m_open defaults to true, and sdl2 window & renderer default to nullptr. /// Window(); /// /// Defaulted destructor. /// ~Window() = default; /// /// \brief Creates the window. /// /// By default, the window takes up the entire screen. /// /// \param title Title for the window / of the app. /// void create(const char* title); /// /// Clean up memory, sdl2 stuff, etc. /// void destroy(); /// /// Clears the renderer in prep to draw to it. /// void beginRender(); /// /// Displays everything to the renderer. /// void endRender(); /// /// Retrieve the renderer. /// /// \return CONST pointer to SDL_Renderer object. We want it const because we don't want the pointer to change. /// SDL_Renderer* getRenderer() const; public: /// /// Keep track of window being open or not. /// bool m_open; private: /// /// Pointer to sdl2 window data. /// SDL_Window* m_window; /// /// Pointer to sdl2 renderer data. /// SDL_Renderer* m_renderer; }; #endif
16.209877
112
0.635187
DomRe
b438acae0c9ead6ca468b517c90c915689f526a1
2,897
cc
C++
libs/quadwild/libs/CoMISo/Solver/UMFPACKSolverT.cc
Pentacode-IAFA/Quad-Remeshing
f8fd4c10abf1c54656b38a00b8a698b952a85fe2
[ "Apache-2.0" ]
29
2019-11-27T00:43:07.000Z
2020-02-25T14:35:54.000Z
libs/quadwild/libs/CoMISo/Solver/UMFPACKSolverT.cc
Pentacode-IAFA/Quad-Remeshing
f8fd4c10abf1c54656b38a00b8a698b952a85fe2
[ "Apache-2.0" ]
1
2018-11-14T23:14:58.000Z
2018-11-14T23:14:58.000Z
libs/quadwild/libs/CoMISo/Solver/UMFPACKSolverT.cc
Pentacode-IAFA/Quad-Remeshing
f8fd4c10abf1c54656b38a00b8a698b952a85fe2
[ "Apache-2.0" ]
4
2019-11-27T05:19:03.000Z
2020-03-23T22:49:53.000Z
/*===========================================================================*\ * * * CoMISo * * Copyright (C) 2008-2009 by Computer Graphics Group, RWTH Aachen * * www.rwth-graphics.de * * * *---------------------------------------------------------------------------* * This file is part of CoMISo. * * * * CoMISo is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * CoMISo is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with CoMISo. If not, see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ #define COMISO_UMFPACK_SOLVER_TEMPLATES_C #include "UMFPACKSolver.hh" namespace COMISO { template< class GMM_MatrixT> bool UMFPACKSolver::calc_system_gmm( const GMM_MatrixT& _mat) { // std::vector<int> colptr; // std::vector<int> rowind; // std::vector<double> values; if(show_timings_) sw_.start(); COMISO_GMM::get_ccs_symmetric_data( _mat, 'c', values_, rowind_, colptr_ ); if(show_timings_) { std::cerr << "UMFPACK Timing GMM convert: " << sw_.stop()/1000.0 << "s\n"; } return calc_system( colptr_, rowind_, values_); } //----------------------------------------------------------------------------- template< class GMM_MatrixT> bool UMFPACKSolver::update_system_gmm( const GMM_MatrixT& _mat) { // std::vector<int> colptr; // std::vector<int> rowind; // std::vector<double> values; COMISO_GMM::get_ccs_symmetric_data( _mat, 'c', values_, rowind_, colptr_ ); return update_system( colptr_, rowind_, values_); } }
35.765432
81
0.409734
Pentacode-IAFA
b4393706b290aa03365cdc16b6bc7c82636511e6
11,804
cpp
C++
src/graphics/ModelIO.cpp
caseymcc/Vorb
a2782bbff662c226002fa69bae688a44770deaf4
[ "MIT" ]
1
2018-10-17T06:37:17.000Z
2018-10-17T06:37:17.000Z
src/graphics/ModelIO.cpp
caseymcc/Vorb
a2782bbff662c226002fa69bae688a44770deaf4
[ "MIT" ]
null
null
null
src/graphics/ModelIO.cpp
caseymcc/Vorb
a2782bbff662c226002fa69bae688a44770deaf4
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "graphics/ModelIO.h" namespace vorb { namespace graphics { namespace impl { static const cString traverseWhitespace(const cString s) { while (true) { switch (*s) { case 0: return nullptr; case ' ': case '\t': s++; break; default: return s; } } } static const cString traverseNonWhitespace(const cString s) { while (true) { switch (*s) { case 0: return nullptr; case ' ': case '\t': case '\r': case '\n': return s; default: s++; break; } } } static const cString moveToNewLine(const cString s) { bool looking = true; while (looking) { switch (*s) { case 0: return nullptr; case '\n': looking = false; s++; break; default: s++; break; } } while (true) { switch (*s) { case 0: return nullptr; case ' ': case '\t': case '\r': case '\n': s++; break; default: return s; } } } static f32 readF32(const cString& data) { data = traverseWhitespace(data); f32 f = (f32)atof(data); data = traverseNonWhitespace(data); return f; } static f32v2 readVec2(const cString& data) { f32v2 ret; ret.x = readF32(data); ret.y = readF32(data); return ret; } static f32v3 readVec3(const cString& data) { f32v3 ret; ret.x = readF32(data); ret.y = readF32(data); ret.z = readF32(data); return ret; } static ui32 readNumeric(const cString& data) { ui32 v = 0; const cString initial = data; while (*data != 0) { if (*data >= '0' && *data <= '9') { v *= 10; v += *data - '0'; data++; } else { return (data == initial) ? 1 : v; } } return 1; } static ui32v3 readVertexIndices(const cString& data) { ui32v3 inds(1, 1, 1); data = traverseWhitespace(data); inds.x = readNumeric(data); if (*data == '/') { data++; inds.y = readNumeric(data); } if (*data == '/') { data++; inds.z = readNumeric(data); } inds -= 1; data = traverseNonWhitespace(data); return inds; } static ui32 indexOf(const ui32v3& vert, OBJMesh& mesh) { auto kvp = mesh.vertices.find(vert); if (kvp == mesh.vertices.end()) { ui32 index = (ui32)mesh.vertices.size(); mesh.vertices[vert] = index; return index; } else { return kvp->second; } } template<typename T> void readBinary(const ui8*& data, T* dst) { *dst = *((const T*)data); data += sizeof(T); } } } } ui32v2 vg::ModelIO::loadOBJ(CALLER_DELETE const cString data, OUT OBJMesh& mesh) { ui32v3 baseDataOffsets( mesh.positions.size(), mesh.uvs.size(), mesh.normals.size() ); ui32 vertexCountInitial = (ui32)mesh.vertices.size(); ui32 indicesAdded = 0; const cString cs = data; cs += strspn(cs, " \t\r\n"); while (cs) { switch (*cs) { case 0: cs = nullptr; break; case 'v': cs++; switch (*cs) { case 0: cs = nullptr; break; case 't': cs++; mesh.uvs.emplace_back(impl::readVec2(cs)); break; case 'n': cs++; mesh.normals.emplace_back(impl::readVec3(cs)); break; default: mesh.positions.emplace_back(impl::readVec3(cs)); break; } break; case 'f': { cs++; ui32v3 face; ui32v3 v1 = impl::readVertexIndices(cs) + baseDataOffsets; face.x = impl::indexOf(v1, mesh); ui32v3 v2 = impl::readVertexIndices(cs) + baseDataOffsets; face.y = impl::indexOf(v2, mesh); ui32v3 v3 = impl::readVertexIndices(cs) + baseDataOffsets; face.z = impl::indexOf(v3, mesh); mesh.triangles.emplace_back(face); indicesAdded += 3; } break; case '#': // Congrats, you used a comment in a mesh file break; default: break; } if (cs) cs = impl::moveToNewLine(cs); } return ui32v2((ui32)(mesh.vertices.size() - vertexCountInitial), indicesAdded); } CALLER_DELETE vg::MeshDataRaw vg::ModelIO::loadRAW(CALLER_DELETE const void* data, OUT vg::VertexDeclaration& decl, OUT ui32& indexSize) { vg::MeshDataRaw mesh = {}; const ui8* bytes = (const ui8*)data; // Read the header char header[5]; impl::readBinary<ui32>(bytes, (ui32*)header); header[4] = 0; if (strcmp(header, "VRAW") != 0) return mesh; // Read vertex elements ui32 count; impl::readBinary<ui32>(bytes, &count); ui32 vertexSize = 0; decl.setData(count); for (ui32 i = 0; i < count; i++) { impl::readBinary<vg::VertexElement>(bytes, &decl[i]); vertexSize += decl[i].componentSize * decl[i].componentCount; } // Read index size impl::readBinary<ui32>(bytes, &indexSize); // Read vertex data impl::readBinary<ui32>(bytes, &mesh.vertexCount); ui32 s = vertexSize * mesh.vertexCount; mesh.vertices = new ui8[s]; memcpy(mesh.vertices, bytes, s); bytes += s; // Read index data impl::readBinary<ui32>(bytes, &mesh.indexCount); s = indexSize * mesh.indexCount; mesh.indices = new ui8[s]; memcpy(mesh.indices, bytes, s); bytes += s; return mesh; } CALLER_DELETE vg::Skeleton vg::ModelIO::loadAnim(CALLER_DELETE const void* data) { vg::Skeleton skeleton = {}; const ui8* bytes = (const ui8*)data; // Read the header char header[5]; impl::readBinary<ui32>(bytes, (ui32*)header); header[4] = 0; if (strcmp(header, "ANIM") != 0) return skeleton; { // Read number of bones ui32 numBones; impl::readBinary<ui32>(bytes, &numBones); skeleton.numBones = numBones; } { // Parse file data vg::BoneInformation* boneInfo = new vg::BoneInformation[skeleton.numBones](); std::unordered_map<nString, ui32> boneMap; for (size_t bi = 0; bi < skeleton.numBones; bi++) { BoneInformation& bone = boneInfo[bi]; { // Read name ui32 l; impl::readBinary<ui32>(bytes, &l); bone.name.resize(l); memcpy(&bone.name[0], bytes, l); bytes += l; boneMap[bone.name] = (ui32)bi; } { // Read parent's name ui32 l; impl::readBinary<ui32>(bytes, &l); if (l != 0) { bone.parent.resize(l); memcpy(&bone.parent[0], bytes, l); bytes += l; } } // Read the rest pose impl::readBinary<f32v4>(bytes, (f32v4*)&bone.rest.rotation); impl::readBinary<f32v3>(bytes, &bone.rest.translation); { // Read number of frames ui32 frames; impl::readBinary<ui32>(bytes, &frames); bone.keyframes.setData(frames); skeleton.numFrames += frames; } // Read all the keyframes for (size_t i = 0; i < bone.keyframes.size(); i++) { impl::readBinary<i32>(bytes, &bone.keyframes[i].frame); impl::readBinary<f32v4>(bytes, (f32v4*)&bone.keyframes[i].transform.rotation); impl::readBinary<f32v3>(bytes, &bone.keyframes[i].transform.translation); } } // Flatten data skeleton.bones = new Bone[skeleton.numBones](); skeleton.frames = new Keyframe[skeleton.numFrames](); size_t ki = 0; for (size_t bi = 0; bi < skeleton.numBones; bi++) { Bone& bone = skeleton.bones[bi]; // Identifying information bone.name = boneInfo[bi].name; bone.index = (ui32)bi; bone.numChildren = 0; // Find parent bone.parent = nullptr; if (boneInfo[bi].parent.size() > 0) { auto kvp = boneMap.find(boneInfo[bi].parent); if (kvp != boneMap.end()) { bone.parent = skeleton.bones + kvp->second; skeleton.numChildrenReferences++; bone.parent->numChildren++; } } // Rest pose bone.rest = boneInfo[bi].rest; // Copy keyframes bone.numFrames = boneInfo[bi].keyframes.size(); bone.keyframes = skeleton.frames + ki; ki += bone.numFrames; memcpy(bone.keyframes, &boneInfo[bi].keyframes[0], bone.numFrames * sizeof(Keyframe)); } delete[] boneInfo; } { // Make children pointers skeleton.childrenArray = new Bone*[skeleton.numChildrenReferences](); // Place initial pointer locations for (size_t bi = 0, ci = 0; bi < skeleton.numBones; bi++) { if (skeleton.bones[bi].numChildren > 0) { skeleton.bones[bi].children = skeleton.childrenArray + ci; ci += skeleton.bones[bi].numChildren; } } // Write children references for (size_t bi = 0; bi < skeleton.numBones; bi++) { if (skeleton.bones[bi].parent) { *skeleton.bones[bi].parent->children = skeleton.bones + bi; skeleton.bones[bi].parent->children++; } } // Reset pointers for (size_t bi = 0; bi < skeleton.numBones; bi++) { if (skeleton.bones[bi].numChildren > 0) { skeleton.bones[bi].children -= skeleton.bones[bi].numChildren; } } } return skeleton; }
32.698061
138
0.439851
caseymcc
b4397660f7c8d9836e9f032121cc4919240858ac
1,842
cpp
C++
src/engine/components/vgui2/dme_controls/AttributeMDLPickerPanel.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/engine/components/vgui2/dme_controls/AttributeMDLPickerPanel.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/engine/components/vgui2/dme_controls/AttributeMDLPickerPanel.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //===========================================================================// #include "dme_controls/AttributeMDLPickerPanel.h" #include "filesystem.h" #include "vgui_controls/Button.h" #include "vgui_controls/FileOpenDialog.h" #include "dme_controls/AttributeTextEntry.h" #include "matsys_controls/MDLPicker.h" #include "tier1/KeyValues.h" using namespace vgui; //----------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- CAttributeMDLPickerPanel::CAttributeMDLPickerPanel(vgui::Panel *parent, const AttributeWidgetInfo_t &info) : BaseClass(parent, info) { } CAttributeMDLPickerPanel::~CAttributeMDLPickerPanel() { } //----------------------------------------------------------------------------- // Called when it's time to show the MDL picker //----------------------------------------------------------------------------- void CAttributeMDLPickerPanel::ShowPickerDialog() { // Open file CMDLPickerFrame *pMDLPickerDialog = new CMDLPickerFrame(this, "Select .MDL File"); pMDLPickerDialog->AddActionSignalTarget(this); pMDLPickerDialog->DoModal(); } //----------------------------------------------------------------------------- // Called when it's time to show the MDL picker //----------------------------------------------------------------------------- void CAttributeMDLPickerPanel::OnMDLSelected(KeyValues *pKeyValues) { const char *pMDLName = pKeyValues->GetString("mdl", NULL); if (!pMDLName || !pMDLName[0]) return; // Apply to text panel m_pData->SetText(pMDLName); SetDirty(true); if (IsAutoApply()) { Apply(); } }
32.315789
108
0.494571
cstom4994
b43ade6a4c58e29260b9245364e029d2d35704ca
5,574
hpp
C++
include/htcw_data.hpp
codewitch-honey-crisis/htcw_data
2cbbc318441a7380f31e60adbf3e1cf994034e5b
[ "MIT" ]
null
null
null
include/htcw_data.hpp
codewitch-honey-crisis/htcw_data
2cbbc318441a7380f31e60adbf3e1cf994034e5b
[ "MIT" ]
null
null
null
include/htcw_data.hpp
codewitch-honey-crisis/htcw_data
2cbbc318441a7380f31e60adbf3e1cf994034e5b
[ "MIT" ]
null
null
null
#pragma once #include <stdlib.h> namespace data { // dynamic vector of scalar (constructorless) data template <typename T> class simple_vector final { void* (*m_allocator)(size_t); void* (*m_reallocator)(void*, size_t); void (*m_deallocator)(void*); size_t m_size; // size in number of T values T* m_begin; size_t m_capacity; // allocated size in T values bool resize(size_t new_size) { size_t capacity = new_size; if (capacity > this->m_capacity) { size_t newcap = capacity + (this->m_capacity >> 1u); void* data ; if(this->m_begin) { data = m_reallocator(this->m_begin, newcap * sizeof(T)); } else { newcap=8; const size_t newsz = newcap*sizeof(T); data = m_allocator(newsz); } if (data) { this->m_capacity = newcap; this->m_begin = (T*)data; } else return false; //error: not enough memory } this->m_size = new_size; return true; } public: simple_vector(void*(allocator)(size_t) = ::malloc, void*(reallocator)(void*, size_t) = ::realloc, void(deallocator)(void*) = ::free) : m_allocator(allocator), m_reallocator(reallocator), m_deallocator(deallocator) { m_begin = nullptr; m_size = 0; m_capacity = 0; } ~simple_vector() { m_size = 0; if (m_begin != nullptr) { m_deallocator(m_begin); m_begin = nullptr; } } inline size_t size() const { return m_size; } inline size_t capacity() const { return m_capacity; } inline const T* cbegin() const { return m_begin; } inline const T* cend() const { return m_begin + m_size; } inline T* begin() { return m_begin; } inline T* end() { return m_begin + m_size; } void clear() { if(m_begin) { m_size = 0; m_capacity = 0; m_deallocator(m_begin); m_begin = nullptr; } } bool push_back(const T& value) { if (!resize(m_size + 1)) { return false; } m_begin[m_size - 1] = value; return true; } }; template<typename TKey, typename TValue> struct simple_pair { TKey key; TValue value; simple_pair(TKey key,TValue value) : key(key), value(value) { } simple_pair(const simple_pair& rhs) { key = rhs.key; value = rhs.value; } simple_pair& operator=(const simple_pair& rhs) { key = rhs.key; value = rhs.value; return *this; } simple_pair(simple_pair&& rhs) { key = rhs.key; value = rhs.value; } simple_pair& operator=(simple_pair&& rhs) { key = rhs.key; value = rhs.value; return *this; } }; template<typename TKey,typename TValue, size_t Size> class simple_fixed_map final { static_assert(Size>0,"Size must be a positive integer"); using bucket_type = simple_vector<simple_pair<TKey,TValue>>; bucket_type m_buckets[Size]; int(*m_hash_function)(const TKey&); size_t m_size; public: simple_fixed_map(int(hash_function)(const TKey&), void*(allocator)(size_t) = ::malloc, void*(reallocator)(void*, size_t) = ::realloc, void(deallocator)(void*) = ::free) : m_hash_function(hash_function),m_size(0) { for(size_t i = 0;i<(int)Size;++i) { m_buckets[i]=bucket_type(allocator,reallocator,deallocator); } } using key_type = TKey; using mapped_type = TValue; using value_type = simple_pair<const TKey,TValue>; inline size_t size() const { return m_size; } void clear() { m_size = 0; for(size_t i = 0;i<Size;++i) { m_buckets->clear(); } } bool insert(const value_type& value) { int h = m_hash_function(value.key)%Size; bucket_type& bucket = m_buckets[h]; if(bucket.size()) { auto it = bucket.cbegin(); while(it!=bucket.cend()) { if(it->key==value.key) { return false; } ++it; } } if(bucket.push_back({value.key,value.value})) { ++m_size; return true; } return false; } const mapped_type* find(const key_type& key) const { int h = m_hash_function(key)%Size; const bucket_type& bucket = m_buckets[h]; if(bucket.size()) { auto it = bucket.cbegin(); while(it!=bucket.cend()) { if(it->key==key) { return &it->value; } ++it; } } return nullptr; } }; } // namespace data
34.196319
103
0.468425
codewitch-honey-crisis
b44449bef010ac258d84c8d0dca4ff34c38743ee
5,369
cpp
C++
tests/ocltst/module/gl/OCLGLTexture.cpp
RadeonOpenCompute/ROCm-OpenCL-Runtime
12d926d06d36fe74876a82f8f8e1ce8ce7902728
[ "MIT" ]
137
2017-05-12T14:49:38.000Z
2022-02-21T06:46:40.000Z
tests/ocltst/module/gl/OCLGLTexture.cpp
RadeonOpenCompute/ROCm-OpenCL-Runtime
12d926d06d36fe74876a82f8f8e1ce8ce7902728
[ "MIT" ]
103
2017-05-12T23:07:28.000Z
2022-03-31T14:49:32.000Z
tests/ocltst/module/gl/OCLGLTexture.cpp
RadeonOpenCompute/ROCm-OpenCL-Runtime
12d926d06d36fe74876a82f8f8e1ce8ce7902728
[ "MIT" ]
53
2017-05-13T11:36:32.000Z
2022-03-27T09:29:42.000Z
/* Copyright (c) 2010 - 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 "OCLGLTexture.h" #include <assert.h> #include <stdio.h> #include <string.h> #include <time.h> const static char* strKernelui = "__kernel void gltexture_test(read_only image2d_t source, write_only " "image2d_t dest) \n" "{ " " \n" " int tidX = get_global_id(0); " " \n" " int tidY = get_global_id(1); " " \n" " uint4 pixel = read_imageui(source, (int2)(tidX, tidY)); " " \n" " write_imageui(dest, (int2)(tidX, tidY), pixel); " " \n" "}"; const static char* strKernelf = "__kernel void gltexture_test(read_only image2d_t source, write_only " "image2d_t dest) \n" "{ " " \n" " int tidX = get_global_id(0); " " \n" " int tidY = get_global_id(1); " " \n" " float4 pixel = read_imagef(source, (int2)(tidX, tidY)); " " \n" " write_imagef(dest, (int2)(tidX, tidY), pixel); " " \n" "} " " \n"; OCLGLTexture::OCLGLTexture() : inDataGL_(NULL), outDataGL_(NULL), inGLTexture_(0), outGLTexture_(0) { _numSubTests = 4 * 2; } OCLGLTexture::~OCLGLTexture() {} void OCLGLTexture::open(unsigned int test, char* units, double& conversion, unsigned int deviceId) { // Initialize random number seed srand((unsigned int)time(NULL)); OCLGLCommon::open(test, units, conversion, deviceId); if (_errorFlag) return; currentTest_ = test % 4; testRender_ = ((test / 4) >= 1) ? true : false; // Build the kernel if (0 == currentTest_) { program_ = _wrapper->clCreateProgramWithSource(context_, 1, &strKernelui, NULL, &error_); } else { program_ = _wrapper->clCreateProgramWithSource(context_, 1, &strKernelf, NULL, &error_); } CHECK_RESULT((error_ != CL_SUCCESS), "clCreateProgramWithSource() failed (%d)", error_); error_ = _wrapper->clBuildProgram(program_, 1, &devices_[deviceId], NULL, NULL, NULL); if (error_ != CL_SUCCESS) { char programLog[1024]; _wrapper->clGetProgramBuildInfo(program_, devices_[deviceId], CL_PROGRAM_BUILD_LOG, 1024, programLog, 0); printf("\n%s\n", programLog); fflush(stdout); } CHECK_RESULT((error_ != CL_SUCCESS), "clBuildProgram() failed (%d)", error_); kernel_ = _wrapper->clCreateKernel(program_, "gltexture_test", &error_); CHECK_RESULT((error_ != CL_SUCCESS), "clCreateKernel() failed (%d)", error_); } void OCLGLTexture::run(void) { bool retVal = false; switch (currentTest_) { case 0: retVal = runTextureTest<unsigned int>(GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT); break; case 1: retVal = runTextureTest<unsigned char>(GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE); break; case 2: retVal = runTextureTest<short>(GL_RGBA16, GL_RGBA, GL_SHORT); break; case 3: retVal = runTextureTest<float>(GL_RGBA32F, GL_RGBA, GL_FLOAT); break; default: CHECK_RESULT(true, "unsupported test number\n"); } CHECK_RESULT((retVal != true), "cl-gl texture interop test failed "); } unsigned int OCLGLTexture::close(void) { clReleaseMemObject(buffers_[0]); clReleaseMemObject(buffers_[1]); buffers_.clear(); // Delete GL in & out buffers glFinish(); glBindTexture(GL_TEXTURE_2D, 0); glDeleteTextures(1, &inGLTexture_); inGLTexture_ = 0; glDeleteTextures(1, &outGLTexture_); outGLTexture_ = 0; free(inDataGL_); inDataGL_ = NULL; free(outDataGL_); outDataGL_ = NULL; return OCLGLCommon::close(); }
37.027586
80
0.57683
RadeonOpenCompute
b445868c69249d83885c0cb2a3f46d8d4d99c876
83,691
cpp
C++
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_MethodImpl.cpp
eudora-jia/CIDLib
02795d283d95f8a5a4fafa401b6189851901b81b
[ "MIT" ]
1
2019-05-28T06:33:01.000Z
2019-05-28T06:33:01.000Z
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_MethodImpl.cpp
eudora-jia/CIDLib
02795d283d95f8a5a4fafa401b6189851901b81b
[ "MIT" ]
null
null
null
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_MethodImpl.cpp
eudora-jia/CIDLib
02795d283d95f8a5a4fafa401b6189851901b81b
[ "MIT" ]
null
null
null
// // FILE NAME: CIDMacroEng_MethodImpl.cpp // // AUTHOR: Dean Roddey // // CREATED: 01/12/2003 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements TMEngMethodImpl class. This class represents the // actual implementation of a 'method' in the macro engine system. External // methods (those handled by C++ code) can each provide a derivative of // this class and override the Invoke() method. We provide a single, generic // one that is used to do all native (opcode based) methods. It's Invoke() // override is the one that interprets opcodes. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // // --------------------------------------------------------------------------- // Facility specific includes // --------------------------------------------------------------------------- #include "CIDMacroEng_.hpp" // --------------------------------------------------------------------------- // Magic RTTI macros // --------------------------------------------------------------------------- RTTIDecls(TMEngMethodImpl,TMEngNamedItem) RTTIDecls(TMEngOpMethodImpl,TMEngMethodImpl) // --------------------------------------------------------------------------- // CLASS: TMEngJumpTableItem // PREFIX: jtbli // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TMEngJumpTableItem: Constructors and Destructor // --------------------------------------------------------------------------- TMEngJumpTableItem:: TMEngJumpTableItem( const tCIDLib::TCard4 c4IPToSet , TMEngClassVal* const pmecvToAdopt) : m_c4IP(c4IPToSet) , m_pmecvCase(pmecvToAdopt) { } TMEngJumpTableItem::~TMEngJumpTableItem() { delete m_pmecvCase; } // --------------------------------------------------------------------------- // TMEngJumpTableItem: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::ESortComps TMEngJumpTableItem::eComp( const TMEngClassVal& mecvToCheck , tCIDLib::TCard4& c4IP) const { #if CID_DEBUG_ON if (m_pmecvCase->c2ClassId() != mecvToCheck.c2ClassId()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcDbg_DifferentCaseTypes , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TCardinal(m_pmecvCase->c2ClassId()) , TCardinal(mecvToCheck.c2ClassId()) ); } #endif tCIDLib::ESortComps eRet = tCIDLib::ESortComps::Equal; switch(tCIDMacroEng::EIntrinsics(mecvToCheck.c2ClassId())) { case tCIDMacroEng::EIntrinsics::Card1 : { const TMEngCard1Val& mecvThis = *static_cast<const TMEngCard1Val*>(m_pmecvCase); const TMEngCard1Val& mecvThat = static_cast<const TMEngCard1Val&>(mecvToCheck); if (mecvThis.c1Value() < mecvThat.c1Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.c1Value() > mecvThat.c1Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Card2 : { const TMEngCard2Val& mecvThis = *static_cast<const TMEngCard2Val*>(m_pmecvCase); const TMEngCard2Val& mecvThat = static_cast<const TMEngCard2Val&>(mecvToCheck); if (mecvThis.c2Value() < mecvThat.c2Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.c2Value() > mecvThat.c2Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Card4 : { const TMEngCard4Val& mecvThis = *static_cast<const TMEngCard4Val*>(m_pmecvCase); const TMEngCard4Val& mecvThat = static_cast<const TMEngCard4Val&>(mecvToCheck); if (mecvThis.c4Value() < mecvThat.c4Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.c4Value() > mecvThat.c4Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Int1 : { const TMEngInt1Val& mecvThis = *static_cast<const TMEngInt1Val*>(m_pmecvCase); const TMEngInt1Val& mecvThat= static_cast<const TMEngInt1Val&>(mecvToCheck); if (mecvThis.i1Value() < mecvThat.i1Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.i1Value() > mecvThat.i1Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Int2 : { const TMEngInt2Val& mecvThis = *static_cast<const TMEngInt2Val*>(m_pmecvCase); const TMEngInt2Val& mecvThat= static_cast<const TMEngInt2Val&>(mecvToCheck); if (mecvThis.i2Value() < mecvThat.i2Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.i2Value() > mecvThat.i2Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Int4 : { const TMEngInt4Val& mecvThis = *static_cast<const TMEngInt4Val*>(m_pmecvCase); const TMEngInt4Val& mecvThat= static_cast<const TMEngInt4Val&>(mecvToCheck); if (mecvThis.i4Value() < mecvThat.i4Value()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.i4Value() > mecvThat.i4Value()) eRet = tCIDLib::ESortComps::FirstGreater; break; } case tCIDMacroEng::EIntrinsics::Char : { const TMEngCharVal& mecvThis = *static_cast<const TMEngCharVal*>(m_pmecvCase); const TMEngCharVal& mecvThat= static_cast<const TMEngCharVal&>(mecvToCheck); if (mecvThis.chValue() < mecvThat.chValue()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.chValue() > mecvThat.chValue()) eRet = tCIDLib::ESortComps::FirstGreater; break; } default : { // // It should be some enum derivative. If debugging, then use our C++ // level RTTI to insure it is. // #if CID_DEBUG_ON if (!mecvToCheck.bIsDescendantOf(TMEngEnumVal::clsThis())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcDbg_UnknownSwitchType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TCardinal(mecvToCheck.c2ClassId()) ); } #endif const TMEngEnumVal& mecvThis = *static_cast<const TMEngEnumVal*>(m_pmecvCase); const TMEngEnumVal& mecvThat= static_cast<const TMEngEnumVal&>(mecvToCheck); if (mecvThis.c4Ordinal() < mecvThat.c4Ordinal()) eRet = tCIDLib::ESortComps::FirstLess; else if (mecvThis.c4Ordinal() > mecvThat.c4Ordinal()) eRet = tCIDLib::ESortComps::FirstGreater; break; } } if (eRet == tCIDLib::ESortComps::Equal) c4IP = m_c4IP; return eRet; } // --------------------------------------------------------------------------- // CLASS: TMEngJumpTable // PREFIX: jtbl // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TMEngJumpTable: Constructors and Destructor // --------------------------------------------------------------------------- TMEngJumpTable::TMEngJumpTable() : m_c4DefIP(kCIDLib::c4MaxCard) , m_colCases(tCIDLib::EAdoptOpts::Adopt) { } TMEngJumpTable::~TMEngJumpTable() { } // --------------------------------------------------------------------------- // TMEngJumpTable: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TVoid TMEngJumpTable::AddDefaultItem(const tCIDLib::TCard4 c4IPToSet) { m_c4DefIP = c4IPToSet; } tCIDLib::TVoid TMEngJumpTable::AddItem(const tCIDLib::TCard4 c4IPToSet , TMEngClassVal* const pmecvToAdopt) { m_colCases.Add(new TMEngJumpTableItem(c4IPToSet, pmecvToAdopt)); } tCIDLib::TBoolean TMEngJumpTable::bFindMatch( const TMEngClassVal& mecvToCheck , tCIDLib::TCard4& c4IP) const { const tCIDLib::TCard4 c4Count = m_colCases.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { if (m_colCases[c4Index]->eComp(mecvToCheck, c4IP) == tCIDLib::ESortComps::Equal) return kCIDLib::True; } return kCIDLib::False; } tCIDLib::TBoolean TMEngJumpTable::bHasRequiredItems() const { return (!m_colCases.bIsEmpty() && (m_c4DefIP != kCIDLib::c4MaxCard)); } tCIDLib::TCard4 TMEngJumpTable::c4DefCaseIP() const { return m_c4DefIP; } TMEngJumpTableItem& TMEngJumpTable::jtbliAt(const tCIDLib::TCard4 c4At) { #if CID_DEBUG_ON if (c4At >= m_colCases.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcDbg_BadJmpTableIndex , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c4At) ); } #endif return *m_colCases[c4At]; } // --------------------------------------------------------------------------- // CLASS: TMEngMethodImpl // PREFIX: memeth // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TMEngMethodImpl: Public, static methods // --------------------------------------------------------------------------- const TString& TMEngMethodImpl::strKey(const TMEngMethodImpl& memethSrc) { return memethSrc.strName(); } // --------------------------------------------------------------------------- // TMEngMethodImpl: Destructor // --------------------------------------------------------------------------- TMEngMethodImpl::~TMEngMethodImpl() { // Clean up the locals and string pool collections delete m_pcolLocalList; delete m_pcolStringPool; } // --------------------------------------------------------------------------- // TMEngMethodImpl: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TCard2 TMEngMethodImpl::c2AddLocal(const TMEngLocalInfo& meliToAdd) { // If not allocated yet, create the locals collection if (!m_pcolLocalList) m_pcolLocalList = new TLocalList(16); // Make sure we don't have one with this name already const tCIDLib::TCard4 c4Count = m_pcolLocalList->c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { if (m_pcolLocalList->objAt(c4Index).strName() == meliToAdd.strName()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_DupLocalName , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , meliToAdd.strName() ); } } facCIDMacroEng().CheckIdOverflow(c4Count, L"Locals"); // Looks ok, so take it const tCIDLib::TCard2 c2Id = tCIDLib::TCard2(c4Count); TMEngLocalInfo& meliNew = m_pcolLocalList->objAdd(meliToAdd); meliNew.c2Id(c2Id); return c2Id; } tCIDLib::TCard2 TMEngMethodImpl::c2AddString(const TString& strToAdd , const tCIDLib::TBoolean bFindDups) { // Allocate the pool collection if not already if (!m_pcolStringPool) m_pcolStringPool = new TStringPool(tCIDLib::EAdoptOpts::Adopt, 8); // // If we are to find dups, then see if we already have this string in // the pool and don't add a new copy, just give back the existing id. // if (bFindDups && !m_pcolStringPool->bIsEmpty()) { const tCIDLib::TCard4 c4Count = m_pcolStringPool->c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { if (strToAdd == m_pcolStringPool->pobjAt(c4Index)->strValue()) return tCIDLib::TCard2(c4Index); } } // Create a string value object with the passed value const tCIDLib::TCard2 c2NewId(tCIDLib::TCard2(m_pcolStringPool->c4ElemCount())); TString strName(L"PoolItem"); strName.AppendFormatted(c2NewId); TMEngStringVal* pmecvNew = new TMEngStringVal ( strName , tCIDMacroEng::EConstTypes::Const , strToAdd ); // Add it, and set it's id to the next id pmecvNew->c2Id(c2NewId); m_pcolStringPool->Add(pmecvNew); return pmecvNew->c2Id(); } tCIDLib::TCard4 TMEngMethodImpl::c4LocalCount() const { // If not allocated yet, then zero definitely if (!m_pcolLocalList) return 0; return m_pcolLocalList->c4ElemCount(); } tCIDLib::TCard4 TMEngMethodImpl::c4StringCount() const { // If not allocated yet, then zero definitely if (!m_pcolStringPool) return 0; return m_pcolStringPool->c4ElemCount(); } const TMEngClassVal& TMEngMethodImpl::mecvFindPoolItem(const tCIDLib::TCard2 c2Id) const { if (!m_pcolStringPool || (c2Id >= m_pcolStringPool->c4ElemCount())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadStringPoolId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , strName() ); } return *m_pcolStringPool->pobjAt(c2Id); } TMEngClassVal& TMEngMethodImpl::mecvFindPoolItem(const tCIDLib::TCard2 c2Id) { if (!m_pcolStringPool || (c2Id >= m_pcolStringPool->c4ElemCount())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadStringPoolId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , strName() ); } return *m_pcolStringPool->pobjAt(c2Id); } const TMEngLocalInfo& TMEngMethodImpl::meliFind(const tCIDLib::TCard2 c2Id) const { if (!m_pcolLocalList || (c2Id >= m_pcolLocalList->c4ElemCount())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadLocalId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , strName() ); } return m_pcolLocalList->objAt(c2Id); } TMEngLocalInfo& TMEngMethodImpl::meliFind(const tCIDLib::TCard2 c2Id) { if (!m_pcolLocalList || (c2Id >= m_pcolLocalList->c4ElemCount())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadLocalId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , strName() ); } return m_pcolLocalList->objAt(c2Id); } const TMEngLocalInfo* TMEngMethodImpl::pmeliFind(const TString& strName) const { // If we've not allocated the collection, obviously not if (!m_pcolLocalList) return nullptr; // Make sure we don't have one with this name already const tCIDLib::TCard4 c4Count = m_pcolLocalList->c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { const TMEngLocalInfo& meliCur = m_pcolLocalList->objAt(c4Index); if (meliCur.strName() == strName) return &meliCur; } return nullptr; } TMEngLocalInfo* TMEngMethodImpl::pmeliFind(const TString& strName) { // If we've not allocated the collection, obviously not if (!m_pcolLocalList) return nullptr; // Make sure we don't have one with this name already const tCIDLib::TCard4 c4Count = m_pcolLocalList->c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { TMEngLocalInfo& meliCur = m_pcolLocalList->objAt(c4Index); if (meliCur.strName() == strName) return &meliCur; } return nullptr; } tCIDLib::TVoid TMEngMethodImpl::PushLocals(TCIDMacroEngine& meOwner) { // If not allocated yet, create the locals collection if (!m_pcolLocalList) m_pcolLocalList = new TLocalList(16); const tCIDLib::TCard4 c4Count = m_pcolLocalList->c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { TMEngLocalInfo& meliCur = m_pcolLocalList->objAt(c4Index); // // Look up the type of this parm and create a value. // // <TBD> We cannot use pool values for locals, because the negate // opcode will convert a non-const pool value in place instead // of replacing it. We have to have some way to say it's a pool // value, so it get's cleaned up ok, but also say it's a local // so that it get's treated correctly. // // For now, we just create a new object for all locals. // const tCIDLib::TCard2 c2Id = meliCur.c2ClassId(); TMEngClassVal* pmecvLocal = meOwner.meciFind(c2Id).pmecvMakeStorage ( meliCur.strName(), meOwner, meliCur.eConst() ); meOwner.PushValue(pmecvLocal, tCIDMacroEng::EStackItems::Local); } } // --------------------------------------------------------------------------- // TMEngMethodImpl: Hidden Constructors // --------------------------------------------------------------------------- TMEngMethodImpl::TMEngMethodImpl(const TString& strName , const tCIDLib::TCard2 c2MethodId) : TMEngNamedItem(strName, c2MethodId) , m_pcolLocalList(nullptr) , m_pcolStringPool(nullptr) { } // --------------------------------------------------------------------------- // CLASS: TMEngOpMethodImpl // PREFIX: memeth // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // Constructors and Destructor // --------------------------------------------------------------------------- TMEngOpMethodImpl::TMEngOpMethodImpl(const TString& strName , const tCIDLib::TCard2 c2MethodId) : TMEngMethodImpl(strName, c2MethodId) , m_colOpCodes(128) , m_pjtblSwitches(nullptr) { } TMEngOpMethodImpl::~TMEngOpMethodImpl() { // Delete the jump table list if we have one try { delete m_pjtblSwitches; } catch(TError& errToCatch) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } catch(...) { } } // --------------------------------------------------------------------------- // TMEngMethodImpl: Public operators // --------------------------------------------------------------------------- const TMEngOpCode& TMEngOpMethodImpl::operator[](const tCIDLib::TCard4 c4Index) const { if (c4Index >= m_colOpCodes.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TCardinal(c4Index) ); } return m_colOpCodes[c4Index]; } TMEngOpCode& TMEngOpMethodImpl::operator[](const tCIDLib::TCard4 c4Index) { if (c4Index >= m_colOpCodes.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TCardinal(c4Index) ); } return m_colOpCodes[c4Index]; } // --------------------------------------------------------------------------- // TMEngOpMethodImpl: Public, inherited methods // --------------------------------------------------------------------------- tCIDLib::TVoid TMEngOpMethodImpl::Invoke( TMEngClassVal& mecvInstance , const TMEngClassInfo& meciTarget , const TMEngMethodInfo& methiThis , TCIDMacroEngine& meOwner) { // // Remember the stack top upon entry. If we throw out of here, we have // to remember to clean up back to there again. // const tCIDLib::TCard4 c4BasePointer = meOwner.c4StackTop(); // // We have two levels of exception handling, one for exceptions coming out of // a called method and one that occurs within the current method. We need // to know that the inner one was done, so that we don't do some redundant // work on the second one after the inner rethrows. // tCIDLib::TBoolean bThrowReported = kCIDLib::False; // // Get a pointer to the debugger interface. The macro engine owns this, // so we just get a pointer to avoid having to call his getter over and // over. We'll call back on this every time we hit a line opcode. It will // usually be zero, in which case we do nothing with it. // MMEngDebugIntf* pmedbgToCall = meOwner.pmedbgToUse(); #if CID_DEBUG_ON tCIDLib::TBoolean bDoDump = kCIDLib::False; if (bDoDump) { DumpOpCodes(*meOwner.pstrmConsole(), meOwner); meOwner.pstrmConsole()->Flush(); } #endif // // If we have any locals, then push them now. Their ids are relative // to the base pointer we stored above. // if (c4LocalCount()) { PushLocals(meOwner); // If we have a debug callback, tell him new locals were created if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::True); } // // And now let's enter the opcode processing loop. We process opcodes // in the order found, except when we hit jump opcodes. If we hit the // end of the opcodes or we hit a return opcode, we will break out. // try { // We need an index, which is our 'instruction pointer' tCIDLib::TCard4 c4IP = 0; // // Remember the opcode count. If we get to this, then we are at // the end of the method. // const tCIDLib::TCard4 c4EndIndex = m_colOpCodes.c4ElemCount(); tCIDLib::TBoolean bDone = kCIDLib::False; tCIDLib::TBoolean bNoIncIP = kCIDLib::False; while (!bDone) { // Get the current opcode const TMEngOpCode& meopCur = m_colOpCodes[c4IP]; switch(meopCur.eOpCode()) { case tCIDMacroEng::EOpCodes::CallExcept : case tCIDMacroEng::EOpCodes::CallLocal : case tCIDMacroEng::EOpCodes::CallMember : case tCIDMacroEng::EOpCodes::CallParent : case tCIDMacroEng::EOpCodes::CallParm : case tCIDMacroEng::EOpCodes::CallStack : case tCIDMacroEng::EOpCodes::CallThis : { TMEngClassVal* pmecvTarget; const TMEngClassInfo* pmeciTarget; tCIDLib::TCard2 c2MethId; if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallExcept) { pmecvTarget = &meOwner.mecvExceptionThrown(); pmeciTarget = &meOwner.meciFind(pmecvTarget->c2ClassId()); c2MethId = meopCur[0]; } else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallStack) { pmecvTarget = &meOwner.mecvStackAt ( meOwner.c4StackTop() - meopCur[0] ); pmeciTarget = &meOwner.meciFind(pmecvTarget->c2ClassId()); c2MethId = meopCur[1]; } else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallThis) { pmecvTarget = &mecvInstance; pmeciTarget = &meciTarget; c2MethId = meopCur[0]; } else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallParent) { pmecvTarget = &mecvInstance; pmeciTarget = &meOwner.meciFind(meciTarget.c2ParentClassId()); c2MethId = meopCur[0]; } else { // // The first index is the id of the member, local, or // parm that the call is being made against. So, // according to the opcode, look up the target value // object. // if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallLocal) { // // The local ids are relative to the base pointer // for our stack frame. // pmecvTarget = &meOwner.mecvStackAt ( c4BasePointer + meopCur[0] ); } else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallMember) { // Get the indicated member, in the first index pmecvTarget = &mecvInstance.mecvFind(meopCur[0], meOwner); } else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallParm) { // It's a parm already on the stack pmecvTarget = &meOwner.mecvStackAt ( (c4BasePointer - (methiThis.c4ParmCount() + 1)) + meopCur[0] ); } else { // Not a known target type, so throw facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_UnknownCallType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Unknown , TInteger(tCIDLib::i4EnumOrd(meopCur.eOpCode())) ); } // Get the class info for the class of the target pmeciTarget = &meOwner.meciFind(pmecvTarget->c2ClassId()); c2MethId = meopCur[1]; } // // And invoke it. The parameters are on the call stack, // but we have to push the method onto the call stack // before invoking it. // try { // // Push a call item on the stack and if we have a debugger // installed, let it know about the change. // meOwner.meciPushMethodCall ( pmeciTarget->c2Id() , c2MethId , &meciTarget , this , &methiThis , &mecvInstance , meOwner.c4CurLine() , c4IP ); if (pmedbgToCall) pmedbgToCall->CallStackChange(); // // Looks ok, so call the class with the instance and // method info. It will pass it on to the appropriate // method. // // If we are doing a parent call, that's a monomorphic // dispatch, else do polymorphic to go to the most // derived. // tCIDMacroEng::EDispatch eDispatch; if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CallParent) eDispatch = tCIDMacroEng::EDispatch::Mono; else eDispatch = tCIDMacroEng::EDispatch::Poly; pmeciTarget->Invoke ( meOwner , *pmecvTarget , c2MethId , eDispatch ); // // We clean off the call item, since we pushed it, // and let any debugger know about it. // meOwner.PopTop(); if (pmedbgToCall) pmedbgToCall->CallStackChange(); } catch(TError& errToCatch) { // // We clean off the call item, since we pushed it, // and let any debugger know about it. // meOwner.PopTop(); if (pmedbgToCall) pmedbgToCall->CallStackChange(); if (facCIDMacroEng().bLogFailures() && !meOwner.bInIDE()) { facCIDMacroEng().LogMsg ( CID_FILE , CID_LINE , kMEngErrs::errcEng_ExceptionFrom , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::AppStatus , pmeciTarget->strClassPath() , pmeciTarget->methiFind(c2MethId).strName() ); } // If the error itself hasn't been logged, then do it if (facCIDMacroEng().bShouldLog(errToCatch)) TModule::LogEventObj(errToCatch); // Let the error handler know about it, if not already if (!errToCatch.bReported()) meOwner.Exception(errToCatch); bThrowReported = kCIDLib::True; errToCatch.AddStackLevel(CID_FILE, CID_LINE); throw; } catch(const TDbgExitException&) { // // We clean off the call item, since we pushed it, // and let any debugger know about it. // meOwner.PopTop(); if (pmedbgToCall) pmedbgToCall->CallStackChange(); // Just rethrow. We are being forced down throw; } catch(const TExceptException&) { // // The called method threw a macro level exception // and didn't handle it. So we need to see if we // have a handler. If so, jump to the catch block, // else, rethrow. // tCIDLib::TCard4 c4New; const tCIDLib::TCard4 c4Tmp = meOwner.c4FindNextTry(c4New); if ((c4Tmp < c4BasePointer) || (c4Tmp == kCIDLib::c4MaxCard)) throw; // Pop back to the indicated position meOwner.PopBackTo(c4Tmp); if (pmedbgToCall) pmedbgToCall->CallStackChange(); // And set the IP to the catch IP bNoIncIP = kCIDLib::True; c4IP = c4New; } catch(...) { // // We clean off the call item, since we pushed it, // and let any debugger know about it. // meOwner.PopTop(); if (pmedbgToCall) pmedbgToCall->CallStackChange(); if (facCIDMacroEng().bLogFailures()) { facCIDMacroEng().LogMsg ( CID_FILE , CID_LINE , kMEngErrs::errcEng_UnknownExceptFrom , tCIDLib::ESeverities::Status , tCIDLib::EErrClasses::AppStatus , pmeciTarget->strClassPath() , pmeciTarget->methiFind(c2MethId).strName() ); } // Tell the engine about it meOwner.UnknownException(); bThrowReported = kCIDLib::True; throw; } break; } case tCIDMacroEng::EOpCodes::ColIndex : { // // The top of stack is an index value, and the one before // that is a collection object. // const tCIDLib::TCard4 c4Top = meOwner.c4StackTop(); TMEngClassVal& mecvIndex = meOwner.mecvStackAt(c4Top - 1); TMEngClassVal& mecvCollect = meOwner.mecvStackAt(c4Top - 2); #if CID_DEBUG_ON if (!mecvCollect.bIsDescendantOf(TMEngCollectVal::clsThis())) { TMEngClassInfo& meciCol = meOwner.meciFind(mecvCollect.c2ClassId()); facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcDbg_NotCollectionType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::TypeMatch , meciCol.strClassPath() ); } #endif // // Cast the value object to the (C++ level) base collection // value class, and ask it to get us the object at the // indicated index. // // It will throw a macro level index error if the index is // not good. // try { TMEngCollectVal& mecvActual ( static_cast<TMEngCollectVal&>(mecvCollect) ); TMEngClassVal* pmecvElem ( mecvActual.pmecvGetAt(meOwner, mecvIndex) ); // Pop the two values off the stack top meOwner.MultiPop(2); // And push the new value meOwner.PushValue(pmecvElem, tCIDMacroEng::EStackItems::ColElem); } catch(const TExceptException&) { // Do the macro level try/catch handling tCIDLib::TCard4 c4New; const tCIDLib::TCard4 c4Tmp = meOwner.c4FindNextTry(c4New); if ((c4Tmp < c4BasePointer) || (c4Tmp == kCIDLib::c4MaxCard)) throw; // Pop back to the indicated position meOwner.PopBackTo(c4Tmp); // And set the IP to the catch IP bNoIncIP = kCIDLib::True; c4IP = c4New; } break; }; case tCIDMacroEng::EOpCodes::Copy : { const tCIDLib::TCard4 c4Top = meOwner.c4StackTop(); TMEngClassVal& mecvSrc = meOwner.mecvStackAt(c4Top - 1); TMEngClassVal& mecvTar = meOwner.mecvStackAt(c4Top - 2); if (meOwner.bValidation()) { TMEngClassInfo& meciSrc = meOwner.meciFind(mecvSrc.c2ClassId()); TMEngClassInfo& meciTar = meOwner.meciFind(mecvTar.c2ClassId()); if (!meciSrc.bIsCopyable() || !meciTar.bIsCopyable()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcRT_BadCopyOpParms , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::TypeMatch , meciSrc.strClassPath() , meciTar.strClassPath() ); } } // If the source and target are not the same, do the copy if (&mecvSrc != &mecvTar) mecvTar.CopyFrom(mecvSrc, meOwner); // And pop them both off meOwner.MultiPop(2); break; } case tCIDMacroEng::EOpCodes::CondEnumInc : case tCIDMacroEng::EOpCodes::ResetEnum : { // // The top of stack must be an enumerated object. We will // look at it and if it is not at it's max, we will // increment it, else we'll do nothing. We leave a boolean // value on the stack to indicate whether we incremented // it or not. // TMEngClassVal& mecvTop = meOwner.mecvStackAtTop(); // If validating, make sure it's an enum if (meOwner.bValidation()) { if (!meOwner.bIsDerivedFrom(mecvTop.c2ClassId() , tCIDMacroEng::EIntrinsics::Enum)) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_WrongStackTopType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TString(L"enumerated") , meOwner.strClassPathForId(mecvTop.c2ClassId()) ); } if (mecvTop.bIsConst()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_NotNConstStackItem , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TString(L"enumerated") ); } } TMEngEnumVal& mecvEnum = static_cast<TMEngEnumVal&>(mecvTop); if (tCIDMacroEng::EOpCodes::CondEnumInc == meopCur.eOpCode()) { if (mecvEnum.bAtMax()) { meOwner.PushBoolean(kCIDLib::False, tCIDMacroEng::EConstTypes::Const); } else { mecvEnum.Increment(); meOwner.PushBoolean(kCIDLib::True, tCIDMacroEng::EConstTypes::Const); } } else { mecvEnum.c4Ordinal(0); } break; } case tCIDMacroEng::EOpCodes::CondJump : { // // The top of stack is a boolean value. We get it's // value then pop it. Then we either jump or not // depending on it's value and whether we are a jump // not jump. // tCIDLib::TBoolean bJump = meOwner.bStackValAt ( meOwner.c4StackTop() - 1 ); meOwner.PopTop(); // If we need to jump, the new IP is in an immedate if (bJump) { c4IP = meopCur.c4Immediate(); bNoIncIP = kCIDLib::True; } break; } case tCIDMacroEng::EOpCodes::CondJumpNP : { // If we need to jump, the new IP is in an immedate if (meOwner.bStackValAt(meOwner.c4StackTop() - 1)) { c4IP = meopCur.c4Immediate(); bNoIncIP = kCIDLib::True; } break; } case tCIDMacroEng::EOpCodes::CurLine : { // Just store the line number stored meOwner.c4CurLine(meopCur.c4Immediate()); // // If we have a debugger installed, then we need to // call it and take action based on what it returns. // if (pmedbgToCall) { tCIDMacroEng::EDbgActs eAct = pmedbgToCall->eAtLine ( meciTarget , methiThis , *this , mecvInstance , meopCur.c4Immediate() , c4IP ); // // If he tells us to exit, then throw an exception // that will dump us back to the top level, who will // tell the debugger we've exited. // if ((eAct == tCIDMacroEng::EDbgActs::CloseSession) || (eAct == tCIDMacroEng::EDbgActs::Exit)) { throw TDbgExitException(eAct); } } break; } case tCIDMacroEng::EOpCodes::EndTry : { // // The top of stack must be a try item, which we want // to pop. If validating, then check it. // if (meOwner.bValidation()) { if (meOwner.mecsiTop().eType() != tCIDMacroEng::EStackItems::Try) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_ExpectedTry , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TCardinal(meOwner.c4CurLine()) , meciTarget.strClassPath() ); } } meOwner.PopTop(); break; } case tCIDMacroEng::EOpCodes::FlipTop : { // Just ask the engine to flip the top two stack items meOwner.FlipStackTop(); break; } case tCIDMacroEng::EOpCodes::Jump : { // Get the new IP out const tCIDLib::TCard4 c4New = meopCur.c4Immediate(); // // If debugging, make sure that we aren't going to jump // out of the valid range. // if (c4New >= c4EndIndex) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadJump , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , TCardinal(c4IP) , meciTarget.strClassPath() , strName() ); } // Looks ok, so set it c4IP = c4New; bNoIncIP = kCIDLib::True; break; } case tCIDMacroEng::EOpCodes::LogicalAnd : case tCIDMacroEng::EOpCodes::LogicalOr : case tCIDMacroEng::EOpCodes::LogicalXor : { // Get the two top items as booleans tCIDLib::TBoolean bFirst = meOwner.bStackValAt ( meOwner.c4StackTop() - 1 ); tCIDLib::TBoolean bSecond = meOwner.bStackValAt ( meOwner.c4StackTop() - 2 ); // Do the indicated operation if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::LogicalAnd) bFirst &= bSecond; else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::LogicalOr) bFirst |= bSecond; else if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::LogicalXor) bFirst ^= bSecond; // Now pop the top two items off meOwner.MultiPop(2); // And put our new result on the top meOwner.PushBoolean(bFirst, tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::MultiPop : { meOwner.MultiPop(meopCur.c4Immediate()); break; } case tCIDMacroEng::EOpCodes::Negate : { // // The top of stack must be a boolean value. We have // to pop it and push back the negated version We // cannot modify the value on the stack itself, even if // a temp, since it may be referred to again later. // TMEngCallStackItem& mecsiTop = meOwner.mecsiTop(); if (meOwner.bValidation()) { if (mecsiTop.mecvPushed().c2ClassId() != tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Boolean)) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcEng_NotStackItemType , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , meOwner.strClassPathForId(tCIDMacroEng::EIntrinsics::Boolean) ); } } TMEngBooleanVal& mecvTop = static_cast<TMEngBooleanVal&> ( mecsiTop.mecvPushed() ); const tCIDMacroEng::EConstTypes eConst = mecvTop.eConst(); const tCIDLib::TBoolean bSave = !mecvTop.bValue(); meOwner.PopTop(); meOwner.PushBoolean(bSave, eConst); break; } case tCIDMacroEng::EOpCodes::NoOp : // Do nothing break; case tCIDMacroEng::EOpCodes::NotCondJump : { // // The top of stack is a boolean value. We get it's // value then pop it. Then we either jump or not // depending on it's value and whether we are a jump // not jump. // tCIDLib::TBoolean bJump = meOwner.bStackValAt ( meOwner.c4StackTop() - 1 ); meOwner.PopTop(); // If we need to jump, the new IP is in an immedate if (!bJump) { c4IP = meopCur.c4Immediate(); bNoIncIP = kCIDLib::True; } break; } case tCIDMacroEng::EOpCodes::NotCondJumpNP : { if (!meOwner.bStackValAt(meOwner.c4StackTop() - 1)) { c4IP = meopCur.c4Immediate(); bNoIncIP = kCIDLib::True; } break; } case tCIDMacroEng::EOpCodes::PopTop : { // Just pop the stack meOwner.PopTop(); break; } case tCIDMacroEng::EOpCodes::PopToReturn : { // // Get the value on the top of the stack, and copy it to // the return value object. If debugging, make sure that // the types are the same and that the type is copyable. // TMEngClassVal& mecvTop = meOwner.mecvStackAtTop(); TMEngClassVal& mecvRet = meOwner.mecvStackAt ( c4BasePointer - (methiThis.c4ParmCount() + 2) ); mecvRet.CopyFrom(mecvTop, meOwner); meOwner.PopTop(); break; } case tCIDMacroEng::EOpCodes::PushCurLine : { meOwner.PushCard4(meOwner.c4CurLine(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushEnum : { meOwner.PushEnum(meopCur[0], meopCur[1], tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushException : { meOwner.PushException(); break; } case tCIDMacroEng::EOpCodes::PushImBoolean : { meOwner.PushBoolean(meopCur.bImmediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImCard1 : { meOwner.PushCard1(meopCur.c1Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImCard2 : { meOwner.PushCard2(meopCur.c2Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImCard4 : { meOwner.PushCard4(meopCur.c4Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImCard8 : { meOwner.PushCard8(meopCur.c8Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImChar : { meOwner.PushChar(meopCur.chImmediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImFloat4 : { meOwner.PushFloat4(meopCur.f4Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImFloat8 : { meOwner.PushFloat8(meopCur.f8Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImInt1 : { meOwner.PushInt1(meopCur.i1Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImInt2 : { meOwner.PushInt2(meopCur.i2Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushImInt4 : { meOwner.PushInt4(meopCur.i4Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushLocal : { // // The first index is the index of the local. In this // case, we are repushing a value already on the stack. // The offset of the local relative to the base pointer // is in the immediate field. // meOwner.RepushAt(c4BasePointer + meopCur[0]); break; } case tCIDMacroEng::EOpCodes::PushMember : { // The first index is the index of the member meOwner.PushValue ( &mecvInstance.mecvFind(meopCur[0], meOwner) , tCIDMacroEng::EStackItems::Member ); break; } case tCIDMacroEng::EOpCodes::PushParm : { // // The first index is the id of the parameter. In this // case, we are just repushing a value already on the // stack as a parameter. Subtracting the parm count plus // one get's us to the first parm. Then we add the parm // id minus one (they are 1 based) to get to the actual // value. // meOwner.RepushAt ( (c4BasePointer - (methiThis.c4ParmCount() + 1)) + meopCur[0] ); break; } case tCIDMacroEng::EOpCodes::PushStrPoolItem : { // Just push the pool item meOwner.PushValue ( &mecvFindPoolItem(meopCur[0]) , tCIDMacroEng::EStackItems::StringPool ); break; } case tCIDMacroEng::EOpCodes::PushTempConst : { // // The c2Immediate field holds the id of the type to push. // meOwner.PushPoolValue(meopCur.c2Immediate(), tCIDMacroEng::EConstTypes::Const); break; } case tCIDMacroEng::EOpCodes::PushTempVar : { // // The c2Immediate field holds the id of the type to push. // The context object has a method to push a value of a // give type id onto the stack from the temp pool. // meOwner.PushPoolValue ( meopCur.c2Immediate() , tCIDMacroEng::EConstTypes::NonConst ); break; } case tCIDMacroEng::EOpCodes::PushThis : { meOwner.PushValue(&mecvInstance, tCIDMacroEng::EStackItems::This); break; } case tCIDMacroEng::EOpCodes::Return : { // // There can be try blocks still on the stack at this // point, so we have to remove them. Any return value has // been extracted at this point, so there should only be // tries above the current base pointer. // tCIDLib::TCard4 c4New; while (kCIDLib::True) { const tCIDLib::TCard4 c4PopTo = meOwner.c4FindNextTry(c4New); if ((c4PopTo == kCIDLib::c4MaxCard) || (c4PopTo < c4BasePointer)) { break; } // We found one in our method scope, so pop back to there meOwner.PopBackTo(c4PopTo); } // Break out of this method bDone = kCIDLib::True; break; } case tCIDMacroEng::EOpCodes::TableJump : { // // This is an indirect table jump, probably for a switch // statement. The first index indicates index of the // jump table that we are to use. // TMEngJumpTable& jtblToUse = jtblById(meopCur[0]); // // The value to switch on must be no the top of the stack, // so get it and ask the table which one matches it. // TMEngClassVal& mecvCase = meOwner.mecvStackAtTop(); // // Look this guy up. Note that if it doesn't match, // we will use the deafult. // tCIDLib::TCard4 c4New; if (!jtblToUse.bFindMatch(mecvCase, c4New)) c4New = jtblToUse.c4DefCaseIP(); // We can trash the stack top now meOwner.PopTop(); // And set the IP to the IP of the target case block bNoIncIP = kCIDLib::True; c4IP = c4New; break; } case tCIDMacroEng::EOpCodes::Throw : { // // This can be either a throw, or a rethrow, according // to the immediate boolean value. If a throw, then // get the exception info set. // // There must be an enumerated type on the stack, which // is the error to throw. We will use this to set up an // exception instance that we keep around for this // purpose. // if (!meopCur.bImmediate()) { TMEngEnumVal& mecvErr = meOwner.mecvStackAtTopAs<TMEngEnumVal>(); TMEngEnumInfo& meciErr = static_cast<TMEngEnumInfo&> ( meOwner.meciFind(mecvErr.c2ClassId()) ); // And now we can set the exception info meOwner.SetException ( mecvErr.c2ClassId() , meciTarget.strClassPath() , mecvErr.c4Ordinal() , meciErr.strFullName(mecvErr) , meciErr.strTextValue(mecvErr) , meOwner.c4CurLine() ); } // // Look for the next try block up the call chain. If it // isn't within our call frame, then we throw a special // C++ exception to cause the propogation. Else, we will // unwind the stack back to (and including) the try // block, and jump to the offset that it indicates it's // catch block is at. // tCIDLib::TCard4 c4New; const tCIDLib::TCard4 c4Tmp = meOwner.c4FindNextTry(c4New); if ((c4Tmp < c4BasePointer) || (c4Tmp == kCIDLib::c4MaxCard)) { throw TExceptException(); } else { // Pop back to the indicated position meOwner.PopBackTo(c4Tmp); // And set the IP to the catch IP bNoIncIP = kCIDLib::True; c4IP = c4New; } break; } case tCIDMacroEng::EOpCodes::ThrowFmt : { // // This is a special form of throw that is used to // pass in values to be used to replace tokens in the // error text. c4Immediate indicates how many of them // there are, pushed after the error enum. So start // off by getting the error enum out, and get the // text that we will format tokens into. // TMEngEnumVal& mecvErr = meOwner.mecvStackAtAs<TMEngEnumVal> ( meOwner.c4StackTop() - (1 + meopCur.c4Immediate()) ); TMEngEnumInfo& meciErr = static_cast<TMEngEnumInfo&> ( meOwner.meciFind(mecvErr.c2ClassId()) ); TString strText(meciErr.strTextValue(mecvErr), 128); // // Now, according to how many tokens indicated in the // immediate value, work down and format each one and // replace that tokens. This requires a bit of code to // do, so we call a helper method to do it. // FormatErrTokens ( meOwner , meopCur.c4Immediate() , strText ); // And now we can set the exception info meOwner.SetException ( mecvErr.c2ClassId() , meciTarget.strClassPath() , mecvErr.c4Ordinal() , meciErr.strFullName(mecvErr) , strText , meOwner.c4CurLine() ); // // Look for the next try block up the call chain. If it // isn't within our call frame, then we throw a special // C++ exception to cause the propogation. Else, we will // unwind the stack back to (and including) the try // block, and jump to the offset that it indicates it's // catch block is at. // tCIDLib::TCard4 c4New; const tCIDLib::TCard4 c4Tmp = meOwner.c4FindNextTry(c4New); if ((c4Tmp < c4BasePointer) || (c4Tmp == kCIDLib::c4MaxCard)) { throw TExceptException(); } else { // Pop back to the indicated position meOwner.PopBackTo(c4Tmp); // And set the IP to the catch IP bNoIncIP = kCIDLib::True; c4IP = c4New; } break; } case tCIDMacroEng::EOpCodes::Try : { // // We need to push a try block on the stack. The opcode // has the IP of the start of the catch block in the // c4Immediate field, which we need to push along with it. // meOwner.PushTry(meopCur.c4Immediate()); break; } case tCIDMacroEng::EOpCodes::TypeCast : { // // The first index is the type to cast to. The value to // cast is on the top of stack, and must be a numeric or // enumerated type, as must be the type to cast to. // // So we need to get the value on the top of the stack, // convert it to the cast type, pop the old value off, // and replace it with a new value from the temp pool. // TMEngClassVal& mecvToCast = meOwner.mecvStackAtTop(); // Push a temp pool value of the target type meOwner.PushPoolValue ( meopCur.c2Immediate() , tCIDMacroEng::EConstTypes::Const ); TMEngClassVal& mecvTmp = meOwner.mecvStackAtTop(); // And ask the temp object to cast from the stack top value TMEngClassInfo& meciTarget = meOwner.meciFind(meopCur.c2Immediate()); const tCIDMacroEng::ECastRes eRes = meciTarget.eCastFrom ( meOwner , mecvToCast , mecvTmp ); if (eRes == tCIDMacroEng::ECastRes::Incompatible) { // This should have been checked up front facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcPrs_CannotCast , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Internal , meOwner.strClassPathForId(mecvToCast.c2ClassId()) , meciTarget.strClassPath() ); } // Flip and pop the original off meOwner.FlipStackTop(); meOwner.PopTop(); break; } case tCIDMacroEng::EOpCodes::None : { // // We shouldn't be see this one in the opcode stream // because it's just a place holder for internal use. // facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_NoneOpCode , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Format , TCardinal(meOwner.c4CurLine()) , meciTarget.strClassPath() , strName() ); break; } default : { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_UnknownOpCode , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Format , TInteger(tCIDLib::i4EnumOrd(meopCur.eOpCode())) , TCardinal(meOwner.c4CurLine()) , meciTarget.strClassPath() , strName() ); break; } } // Move forward to the next opcode if (bNoIncIP) bNoIncIP = kCIDLib::False; else c4IP++; // If at the end, we are done if (c4IP == c4EndIndex) break; } } catch(TError& errToCatch) { // // If we have a debug callback, tell him locals are being removed. // We don't even check if we really have any, since it just makes // him clear his window. // if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::False); // Pop the stack back to the base pointer and tell the debugger meOwner.PopBackTo(c4BasePointer); if (pmedbgToCall) pmedbgToCall->CallStackChange(); if (!bThrowReported) { facCIDMacroEng().LogMsg ( CID_FILE , CID_LINE , kMEngErrs::errcEng_ExceptionIn , tCIDLib::ESeverities::Status , tCIDLib::EErrClasses::AppStatus , meciTarget.strClassPath() , strName() ); // If the error itself hasn't been logged, then do it if (facCIDMacroEng().bShouldLog(errToCatch)) TModule::LogEventObj(errToCatch); // Let the engine know about it, if not already, then rethrow if (errToCatch.bReported()) meOwner.Exception(errToCatch); } errToCatch.AddStackLevel(CID_FILE, CID_LINE); throw; } catch(const TDbgExitException&) { // // If we have a debug callback, tell him locals are being removed. // We don't even check if we really have any, since it just makes // him clear his window. // if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::False); // Pop the stack back to the base pointer and tell the debugger meOwner.PopBackTo(c4BasePointer); if (pmedbgToCall) pmedbgToCall->CallStackChange(); throw; } catch(const TExceptException&) { // // If we have a debug callback, tell him locals are being removed. // We don't even check if we really have any, since it just makes // him clear his window. // if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::False); // Pop the stack back to the base pointer and tell the debugger meOwner.PopBackTo(c4BasePointer); if (pmedbgToCall) pmedbgToCall->CallStackChange(); throw; } catch(...) { // // If we have a debug callback, tell him locals are being removed. // We don't even check if we really have any, since it just makes // him clear his window. // if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::False); // Pop the stack back to the base pointer and tell the debugger meOwner.PopBackTo(c4BasePointer); if (pmedbgToCall) pmedbgToCall->CallStackChange(); if (!bThrowReported) { facCIDMacroEng().LogMsg ( CID_FILE , CID_LINE , kMEngErrs::errcEng_UnknownExceptIn , tCIDLib::ESeverities::Status , tCIDLib::EErrClasses::AppStatus , meciTarget.strClassPath() , strName() ); // Tell the engine about it and then rethrow meOwner.UnknownException(); } throw; } // // If we have a debug callback, tell him locals are being removed. // We don't even check if we really have any, since it just makes // him clear his window. // if (pmedbgToCall) pmedbgToCall->LocalsChange(kCIDLib::False); // Pop the stack back to the base pointer and tell the debugger meOwner.PopBackTo(c4BasePointer); if (pmedbgToCall) pmedbgToCall->CallStackChange(); } // --------------------------------------------------------------------------- // TMEngOpMethodImpl: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TMEngOpMethodImpl::bMoreLines(const tCIDLib::TCard4 c4LastIP) const { const tCIDLib::TCard4 c4Count = m_colOpCodes.c4ElemCount(); for (tCIDLib::TCard4 c4Index = c4LastIP + 1; c4Index < c4Count; c4Index++) { const TMEngOpCode& meopCur = m_colOpCodes[c4Index]; if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CurLine) { // // Check to see if the next opcode is the last one and a no-op. // If so, then this line is the one on the EndMethod, which is // really past the end of the method from a call stack point of // view, so we'll return false if so. // if ((c4Index + 2 == c4Count) && (m_colOpCodes[c4Index + 1].eOpCode() == tCIDMacroEng::EOpCodes::NoOp)) { return kCIDLib::False; } return kCIDLib::True; } } return kCIDLib::False; } tCIDLib::TCard2 TMEngOpMethodImpl::c2AddJumpTable() { if (!m_pjtblSwitches) m_pjtblSwitches = new TMEngJumpTableTable(tCIDLib::EAdoptOpts::Adopt); const tCIDLib::TCard4 c4Ret = m_pjtblSwitches->c4ElemCount(); m_pjtblSwitches->Add(new TMEngJumpTable); return tCIDLib::TCard2(c4Ret); } tCIDLib::TCard4 TMEngOpMethodImpl::c4AddOpCode(const TMEngOpCode& meopToAdd) { // // Add this opcode and return the index of the opcode, which is the // current (pre-addition) count. // tCIDLib::TCard4 c4Ret = m_colOpCodes.c4ElemCount(); m_colOpCodes.objAdd(meopToAdd); return c4Ret; } tCIDLib::TCard4 TMEngOpMethodImpl::c4CurOffset() const { return m_colOpCodes.c4ElemCount(); } tCIDLib::TCard4 TMEngOpMethodImpl::c4FirstLineNum() const { const tCIDLib::TCard4 c4Count = m_colOpCodes.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { const TMEngOpCode& meopCur = m_colOpCodes[c4Index]; if (meopCur.eOpCode() == tCIDMacroEng::EOpCodes::CurLine) return meopCur.c4Immediate(); } // Just return 1, since we didn't find any current line opcodes return 1; } tCIDLib::TVoid TMEngOpMethodImpl::DumpOpCodes( TTextOutStream& strmTarget , const TCIDMacroEngine& meOwner) const { const TTextOutStream::Width widNums(4); const TTextOutStream::Width widZero(0); TStreamJanitor janStream(&strmTarget); const tCIDLib::TCard4 c4Count = m_colOpCodes.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmTarget << widNums << c4Index << widZero << L"- "; m_colOpCodes[c4Index].Format(strmTarget, meOwner); strmTarget << kCIDLib::NewLn; } } TMEngJumpTable& TMEngOpMethodImpl::jtblById(const tCIDLib::TCard2 c2Id) { // Make sure this index is valid if (!m_pjtblSwitches || (c2Id >= m_pjtblSwitches->c4ElemCount())) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadJumpTableId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , TCardinal(c2Id) , strName() ); } return *m_pjtblSwitches->pobjAt(c2Id); } const TMEngOpCode& TMEngOpMethodImpl::meopAt(const tCIDLib::TCard4 c4At) const { if (c4At >= m_colOpCodes.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TCardinal(c4At) ); } return m_colOpCodes[c4At]; } TMEngOpCode& TMEngOpMethodImpl::meopAt(const tCIDLib::TCard4 c4At) { if (c4At >= m_colOpCodes.c4ElemCount()) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TCardinal(c4At) ); } return m_colOpCodes[c4At]; } const TMEngOpCode& TMEngOpMethodImpl::meopLast() const { const tCIDLib::TCard4 c4Count = m_colOpCodes.c4ElemCount(); if (!c4Count) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TInteger(0) ); } return m_colOpCodes[c4Count - 1]; } TMEngOpCode& TMEngOpMethodImpl::meopLast() { const tCIDLib::TCard4 c4Count = m_colOpCodes.c4ElemCount(); if (!c4Count) { facCIDMacroEng().ThrowErr ( CID_FILE , CID_LINE , kMEngErrs::errcMeth_BadIP , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Index , strName() , TInteger(0) ); } return m_colOpCodes[c4Count - 1]; } // --------------------------------------------------------------------------- // TMEngOpMethodImpl: Private, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TVoid TMEngOpMethodImpl::FormatErrTokens( TCIDMacroEngine& meOwner , const tCIDLib::TCard4 c4Tokens , TString& strToFill) { // Create a macro level string out stream TMEngClassInfo& meciStrm = meOwner.meciFind ( tCIDMacroEng::EIntrinsics::StringOutStream ); TMEngTextOutStreamVal* pmecvStrm = static_cast<TMEngTextOutStreamVal*> ( meciStrm.pmecvMakeStorage ( L"TempStream" , meOwner , tCIDMacroEng::EConstTypes::NonConst ) ); TJanitor<TMEngTextOutStreamVal> janStream(pmecvStrm); // // Give it a stream, since we won't be constructing it at the macro // language level, which normally is how it gets one. // TTextStringOutStream* pstrmTarget = new TTextStringOutStream(1024UL); pmecvStrm->SetStream(pstrmTarget, tCIDLib::EAdoptOpts::Adopt); tCIDLib::TCh chToken(kCIDLib::chDigit1); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Tokens; c4Index++) { // // Get the current formattable object. One gets us down to the actual // top item, then add the current index to get to the current one. // TMEngFormattableVal& mecvCur = meOwner.mecvStackAtAs<TMEngFormattableVal> ( (meOwner.c4StackTop() - c4Tokens) + c4Index ); TMEngClassInfo& meciTarget = meOwner.meciFind(mecvCur.c2ClassId()); // // Generate a macro level call to format this guy to the stream. Tell // the call stack that the stream is a 'repush', though its not, so // that it won't try to delete it on us. // meOwner.PushPoolValue(tCIDMacroEng::EIntrinsics::Void, tCIDMacroEng::EConstTypes::Const); meOwner.PushValue(pmecvStrm, tCIDMacroEng::EStackItems::Parm, kCIDLib::True); meOwner.meciPushMethodCall ( meciTarget.c2Id() , TMEngFormattableInfo::c2FormatToId() ); meciTarget.Invoke ( meOwner , mecvCur , TMEngFormattableInfo::c2FormatToId() , tCIDMacroEng::EDispatch::Poly ); // // We cheated this one, so we have to pop the method item as well // the parm and return! // meOwner.MultiPop(3); // And now replace the current token with this result. Flush first! pmecvStrm->Flush(); strToFill.eReplaceToken(pstrmTarget->strData(), chToken); // And reset it for the next round pstrmTarget->Reset(); // Move up to the next token digit chToken++; } }
36.562254
99
0.455294
eudora-jia
b445e2dc9ca4ec109952580e39c90db270548522
2,410
cpp
C++
Exams/Regular Exam - 12 September 2021/03. Diablo/Barbarian.cpp
AleksievAleksandar/Cpp-OOP
03b95e8378cc64e52bf49b4c719b5b1f2cd332a1
[ "MIT" ]
null
null
null
Exams/Regular Exam - 12 September 2021/03. Diablo/Barbarian.cpp
AleksievAleksandar/Cpp-OOP
03b95e8378cc64e52bf49b4c719b5b1f2cd332a1
[ "MIT" ]
null
null
null
Exams/Regular Exam - 12 September 2021/03. Diablo/Barbarian.cpp
AleksievAleksandar/Cpp-OOP
03b95e8378cc64e52bf49b4c719b5b1f2cd332a1
[ "MIT" ]
null
null
null
#include "Barbarian.h" #include <iostream> #include <sstream> #include <string> Barbarian::Barbarian(const VitalData& vitalData) : defendsTurns(1) { this->_name = BARBARIAN_NAME; this->_vitalData = vitalData; } void Barbarian::readSpellFromInput(SpellType spellType) { switch (spellType) { case SpellType::Weak: std::cin >> this->_spells[WEAKER_SPELL].name >> this->_spells[WEAKER_SPELL].damage; break; case SpellType::Strong: std::cin >> this->_spells[STRONGER_SPELL].name >> this->_spells[STRONGER_SPELL].damage >> this->_spells[STRONGER_SPELL].manaCost; break; default: break; } } int Barbarian::castSpell() { int calculateMana = this->_vitalData.currMana - this->_spells[STRONGER_SPELL].manaCost; std::string spellName = this->_spells[WEAKER_SPELL].name; int manaCost = this->_spells[WEAKER_SPELL].manaCost; int typeOfSpell = static_cast<int>(WEAKER_SPELL); if (calculateMana >= 0) { this->_vitalData.currMana -= this->_spells[STRONGER_SPELL].manaCost; spellName = this->_spells[STRONGER_SPELL].name; manaCost = this->_spells[STRONGER_SPELL].manaCost; typeOfSpell = STRONGER_SPELL; } std::cout << this->getName() << " casting " << spellName << " for " << manaCost << " mana " << std::endl; return this->_spells[typeOfSpell].damage; } void Barbarian::takeDamage(int damage) { if (this->defendsTurns == BARBARIAN_PASSIVE_ABILITY_COUNTER) { damage *= (BARBARIAN_DAMAGE_BLOCK_PERCENT / 100.0); this->defendsTurns = 1; } else { this->defendsTurns++; } this->_vitalData.health -= damage; std::cout << this->getName() << " took " << damage << " damage and is left with " << this->_vitalData.health << " health " << std::endl; } void Barbarian::regenerate() { int regenMana = 0; if (this->_vitalData.manaRegenRate + this->_vitalData.currMana <= this->_vitalData.maxMana) { this->_vitalData.currMana += this->_vitalData.manaRegenRate; regenMana = this->_vitalData.manaRegenRate; } else { regenMana = (this->_vitalData.manaRegenRate + this->_vitalData.currMana) - this->_vitalData.maxMana; this->_vitalData.currMana = this->_vitalData.maxMana; } std::cout << this->getName() << " regained " << regenMana << " mana for up to " << this->_vitalData.currMana << std::endl; } bool Barbarian::isDead() const { return this->_vitalData.health <= 0; }
26.777778
138
0.679253
AleksievAleksandar
b447d6c8653f4c4434ae41d81964325f6c402d0f
3,561
cpp
C++
src/presolve/PresolveAnalysis.cpp
ogmundur/HiGHS
ed3a64f589b3a1962783caef793dc20b158210d4
[ "MIT" ]
null
null
null
src/presolve/PresolveAnalysis.cpp
ogmundur/HiGHS
ed3a64f589b3a1962783caef793dc20b158210d4
[ "MIT" ]
null
null
null
src/presolve/PresolveAnalysis.cpp
ogmundur/HiGHS
ed3a64f589b3a1962783caef793dc20b158210d4
[ "MIT" ]
null
null
null
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the HiGHS linear optimization suite */ /* */ /* Written and engineered 2008-2021 at the University of Edinburgh */ /* */ /* Available as open-source under the MIT License */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file presolve/PresolveAnalysis.cpp * @brief * @author Julian Hall, Ivet Galabova, Qi Huangfu and Michael Feldmeier */ #include "presolve/PresolveAnalysis.h" #include <limits> namespace presolve { void initializePresolveRuleInfo(std::vector<PresolveRuleInfo>& rules) { assert((int)rules.size() == 0); rules.push_back(PresolveRuleInfo(EMPTY_ROW, "Empty row", "EMR")); rules.push_back(PresolveRuleInfo(FIXED_COL, "Fixed col", "FXC")); rules.push_back(PresolveRuleInfo(SING_ROW, "Sing row", "SGR")); rules.push_back(PresolveRuleInfo(DOUBLETON_EQUATION, "Doubleton eq", "DEQ")); rules.push_back( PresolveRuleInfo(REMOVE_FORCING_CONSTRAINTS, "Rm forcing cs", "RFC")); rules.push_back(PresolveRuleInfo(FORCING_ROW, "Forcing row", "FRR")); rules.push_back(PresolveRuleInfo(REDUNDANT_ROW, "Redundant row", "RDR")); rules.push_back( PresolveRuleInfo(DOMINATED_ROW_BOUNDS, "Dom row bounds", "DRB")); rules.push_back( PresolveRuleInfo(REMOVE_COLUMN_SINGLETONS, "Remove col sing", "RCS")); rules.push_back(PresolveRuleInfo(FREE_SING_COL, "Free sing col", "FSC")); rules.push_back( PresolveRuleInfo(SING_COL_DOUBLETON_INEQ, "Sing col dbtn ineq", "SCD")); rules.push_back( PresolveRuleInfo(IMPLIED_FREE_SING_COL, "Impl free sing col", "IFS")); rules.push_back( PresolveRuleInfo(REMOVE_DOMINATED_COLUMNS, "Rm dom col", "RDC")); rules.push_back(PresolveRuleInfo(MIP_DUAL_FIXING, "Mip dual fix", "MDF")); rules.push_back(PresolveRuleInfo(DOMINATED_COLS, "Dominated col", "DMC")); rules.push_back( PresolveRuleInfo(WEAKLY_DOMINATED_COLS, "Weakly dom col", "WDC")); rules.push_back( PresolveRuleInfo(DOMINATED_COL_BOUNDS, "Dom col bounds", "DCB")); rules.push_back(PresolveRuleInfo(EMPTY_COL, "Empty col", "EMC")); rules.push_back(PresolveRuleInfo(AGGREGATOR, "Aggregator", "AGG")); // rules.push_back(PresolveRuleInfo(KNAPSACK, "Knapsack", "KNP")); rules.push_back(PresolveRuleInfo(MATRIX_COPY, "Initialize matrix", "INM")); rules.push_back(PresolveRuleInfo(RESIZE_MATRIX, "Resize matrix", "RSM")); // rules.push_back(PresolveRuleInfo(RUN_PRESOLVERS, "Run Presolvers", "RPr")); rules.push_back( PresolveRuleInfo(REMOVE_ROW_SINGLETONS, "Rm row sing", "RRS")); rules.push_back( PresolveRuleInfo(REMOVE_DOUBLETON_EQUATIONS, "Rm dbleton eq", "RDE")); rules.push_back(PresolveRuleInfo(REMOVE_EMPTY_ROW, "Rm empty row", "RER")); // rules.push_back( PresolveRuleInfo(TOTAL_PRESOLVE_TIME, "Total presolve time", "TPT")); // rules.push_back( // PresolveRuleInfo(SING_ONLY, "Sing only row", "SOR")); // Plus one for the total resize time. assert((int)rules.size() == PRESOLVE_RULES_COUNT); } void PresolveTimer::updateInfo() { for (PresolveRuleInfo& rule : rules_) { rule.total_time = timer_.read(rule.clock_id); } } } // namespace presolve
46.246753
79
0.625948
ogmundur
b448d6988070721fc195dbe00ce828972096cdeb
1,307
cpp
C++
src/ColumnsImpl.cpp
zhangf911/SPLib
57ae498f61abe9c14670a974340251cd67ca99fb
[ "BSD-2-Clause" ]
1
2015-11-06T03:40:44.000Z
2015-11-06T03:40:44.000Z
src/ColumnsImpl.cpp
amyvmiwei/SPLib
57ae498f61abe9c14670a974340251cd67ca99fb
[ "BSD-2-Clause" ]
null
null
null
src/ColumnsImpl.cpp
amyvmiwei/SPLib
57ae498f61abe9c14670a974340251cd67ca99fb
[ "BSD-2-Clause" ]
1
2020-12-16T03:20:45.000Z
2020-12-16T03:20:45.000Z
// File: ColumnsImpl.cpp // ColumnsImpl implementation file // #include "ColumnsImpl.h" #include "IndexLimits.h" #include "Util.h" #include "splibint.h" namespace splib { Column& ColumnsImpl::get(int index) { if (!IndexLimits::validateColumn(index)) { throw IllegalArgumentException(); } return collection.get(index); } Column& ColumnsImpl::get(const _TCHAR* column) { int col; if (!Util::parseColumn(column, col)) { throw IllegalArgumentException(); } return get(col); } bool ColumnsImpl::contains(int index) { if (!IndexLimits::validateColumn(index)) { throw IllegalArgumentException(); } return collection.contains(index); } void ColumnsImpl::remove(int index) { if (!IndexLimits::validateColumn(index)) { throw IllegalArgumentException(); } return collection.remove(index); } int ColumnsImpl::size() const { return collection.size(); } bool ColumnsImpl::isEmpty() const { return collection.isEmpty(); } ColumnsImpl::Iterator* ColumnsImpl::iterator() { return collection.iterator(); } ColumnsImpl::Entry ColumnsImpl::first() { return collection.first(); } ColumnsImpl::Entry ColumnsImpl::last() { return collection.last(); } }
21.080645
49
0.648049
zhangf911
b4506fd678ceca1db0f7d07f686bafc87d988133
6,542
cpp
C++
src/plugins_pkgs/car_plugin/src/carlikerobot.cpp
ZeroTheRed/Simulator
d3e05cfe9cb8ac33abcfb4b501f1b8da2ff5ed67
[ "BSD-3-Clause" ]
1
2021-11-16T16:53:25.000Z
2021-11-16T16:53:25.000Z
src/plugins_pkgs/car_plugin/src/carlikerobot.cpp
ZeroTheRed/Simulator
d3e05cfe9cb8ac33abcfb4b501f1b8da2ff5ed67
[ "BSD-3-Clause" ]
4
2021-11-12T09:06:19.000Z
2021-12-09T14:35:38.000Z
src/plugins_pkgs/car_plugin/src/carlikerobot.cpp
ZeroTheRed/Simulator
d3e05cfe9cb8ac33abcfb4b501f1b8da2ff5ed67
[ "BSD-3-Clause" ]
10
2021-11-25T10:39:51.000Z
2022-03-09T10:21:26.000Z
#include "carlikerobot.hpp" #define DEBUG false namespace gazebo{ namespace carlikerobot{ /* axletrack : the distance between the wheels as you look the car frontal wheelbase : the distance between the wheels as you look the car from side */ /// FRONT CFrontWheelsSpeed::CFrontWheelsSpeed(float axletrack, float wheelbase, float wheelradius, physics::JointPtr jointRight, physics::JointPtr jointLeft, common::PID pidRight, common::PID pidLeft, physics::ModelPtr model) { this->_axletrack = axletrack; this->_wheelbase = wheelbase; this->_wheelradius = wheelradius; this->_jointRight = jointRight; this->_jointLeft = jointLeft; this->_pidRight = pidRight; this->_pidLeft = pidLeft; this->_model = model; this->_model->GetJointController()->SetVelocityPID(this->_jointRight->GetScopedName(), this->_pidRight); this->_model->GetJointController()->SetVelocityPID(this->_jointLeft->GetScopedName(), this->_pidLeft); } void CFrontWheelsSpeed::update(float steeringAngle_deg, float speed_meter_per_sec) { // Convert from m/s in rads/sec float speed_rad_per_sec = speed_meter_per_sec / this->_wheelradius; float l_K = tan(steeringAngle_deg / 180.0 * PI)/this->_wheelbase; float l_Vr_R = speed_rad_per_sec*sqrt((pow(2.0-this->_axletrack*l_K,2.0)+pow(2.0*l_K*this->_wheelbase,2))/(4.0*(1.0+pow(_wheelbase*l_K,2.0)))); float l_Vr_L = speed_rad_per_sec*sqrt((pow(2.0+_axletrack*l_K,2.0)+pow(2.0*l_K*_wheelbase,2))/(4.0*(1.0+pow(_wheelbase*l_K,2.0)))); if(DEBUG) { ROS_INFO("Front speed:\t\t[%f, %f]", l_Vr_L, l_Vr_R); } _model->GetJointController()->SetVelocityTarget(this->_jointLeft->GetScopedName(),l_Vr_L); _model->GetJointController()->SetVelocityTarget(this->_jointRight->GetScopedName(),l_Vr_R); } /// REAR CRearWheelsSpeed::CRearWheelsSpeed(float f_axletrack, float f_wheelbase, float f_wheelradius, physics::JointPtr f_jointRight, physics::JointPtr f_jointLeft, common::PID f_pidRight, common::PID f_pidLeft, physics::ModelPtr f_model) { this->_axletrack = f_axletrack; this->_wheelbase = f_wheelbase; this->_wheelradius = f_wheelradius; this->_jointRight = f_jointRight; this->_jointLeft = f_jointLeft; this->_pidRight = f_pidRight; this->_pidLeft = f_pidLeft; this->_model = f_model; this->_model->GetJointController()->SetVelocityPID(this->_jointRight->GetScopedName(), this->_pidRight); this->_model->GetJointController()->SetVelocityPID(this->_jointLeft->GetScopedName(), this->_pidLeft); } void CRearWheelsSpeed::update(float f_steerAngle_deg,float f_Vr_m_meterpsec) { float l_Vr_m_radpsec = f_Vr_m_meterpsec/_wheelradius; float l_K = tan(f_steerAngle_deg/180.0*PI)/this->_wheelbase; float l_Vr_R = l_Vr_m_radpsec*(2-_axletrack*l_K)/2; float l_Vr_L = l_Vr_m_radpsec*(2+_axletrack*l_K)/2; if(DEBUG) { ROS_INFO("Rear speed:\t\t[%f, %f]",l_Vr_L, l_Vr_R); } this->_model->GetJointController()->SetVelocityTarget(this->_jointLeft->GetScopedName(),l_Vr_L); this->_model->GetJointController()->SetVelocityTarget(this->_jointRight->GetScopedName(),l_Vr_R); } /// STEERING ANGLE CSteerWheelsAngle::CSteerWheelsAngle(float f_axletrack, float f_wheelbase, physics::JointPtr f_jointRight, physics::JointPtr f_jointLeft, common::PID f_pidRight, common::PID f_pidLeft, physics::ModelPtr f_model) { this->_axletrack = f_axletrack; this->_wheelbase = f_wheelbase; this->_jointRight = f_jointRight; this->_jointLeft = f_jointLeft; this->_pidRight = f_pidRight; this->_pidLeft = f_pidLeft; this->_model = f_model; this->_model->GetJointController()->SetPositionPID(this->_jointRight->GetScopedName(), this->_pidRight); this->_model->GetJointController()->SetPositionPID(this->_jointLeft->GetScopedName(), this->_pidLeft); } void CSteerWheelsAngle::update(float f_steerAngle_deg) { float l_K = tan(f_steerAngle_deg / 180.0 * PI) / this->_wheelbase; float l_steer_right = -1.0 * atan(_wheelbase * 2.0 * l_K / (2.0 - this->_axletrack * l_K)); float l_steer_left = -1.0 * atan(_wheelbase * 2.0 * l_K / (2.0 + this->_axletrack * l_K)); if(DEBUG) { ROS_INFO("Angle:\t\t\t[%f, %f]", l_steer_left*180.0/PI,l_steer_right*180.0/PI); ROS_INFO_STREAM("===================================================================="); } _model->GetJointController()->SetPositionTarget(this->_jointLeft->GetScopedName(), l_steer_left); _model->GetJointController()->SetPositionTarget(this->_jointRight->GetScopedName(), l_steer_right); } }; // namespace carlikerobot } // namespace gazebo
45.430556
155
0.503821
ZeroTheRed
b4530107b7876bf81974cc75b2e58f5fa33d34ca
3,469
cpp
C++
SpaceFighter/main.cpp
issuran/SpaceFighter
d0ff09bcb4d91b003d9dba3a7386e39d5471bc00
[ "MIT" ]
7
2017-11-10T13:04:24.000Z
2019-06-04T19:11:26.000Z
SpaceFighter/main.cpp
issuran/SpaceFighter
d0ff09bcb4d91b003d9dba3a7386e39d5471bc00
[ "MIT" ]
null
null
null
SpaceFighter/main.cpp
issuran/SpaceFighter
d0ff09bcb4d91b003d9dba3a7386e39d5471bc00
[ "MIT" ]
null
null
null
#include "SDL.h" #include "Game.h" #include "Splash.h" #include "MainMenu.h" #include "GameOver.h" Game *game = nullptr; Splash *splash = nullptr; MainMenu *main_menu = nullptr; GameOver *game_over = nullptr; SDL_Window *window = nullptr; SDL_Renderer* renderer = nullptr; SDL_Surface* surfaces = nullptr; SDL_Window* createWindow(const char* title, int xpos, int ypos, int width, int height, bool fullscreen) { int flags = 0; if (fullscreen) { flags = SDL_WINDOW_FULLSCREEN; } return SDL_CreateWindow(title, xpos, ypos, width, height, flags); } SDL_Renderer* createRenderer(SDL_Window *window) { return SDL_CreateRenderer(window, -1, 0); } SDL_Surface* createSurface(SDL_Window *window) { return SDL_GetWindowSurface(window); } int main(int argc, char *argv[]) { /*while (game is running) { handle any user input update all object eg. positions etc. render changes to the display }*/ const int FPS = 60; const int frameDelay = 1000 / FPS; Uint32 frameStart; int frameTime; splash = new Splash(); main_menu = new MainMenu(); game = new Game(); game_over = new GameOver(); bool isRunningGame = true; SDL_Init(SDL_INIT_EVERYTHING); //Create game window window = createWindow("Splash Screen", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 640, false); if (window) { std::cout << "Window created!" << std::endl; } renderer = createRenderer(window); if (renderer) { SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); std::cout << "Renderer created!" << std::endl; } surfaces = createSurface(window); splash->init(window, renderer, surfaces); while (splash->running()) { frameStart = SDL_GetTicks(); splash->update(); splash->render(); splash->handleEvents(); frameTime = SDL_GetTicks() - frameStart; if (frameDelay > frameTime) { SDL_Delay(frameDelay - frameTime); } } SDL_SetWindowTitle(window, "Main Menu Screen"); main_menu->init(window, renderer, surfaces); while (main_menu->running()) { frameStart = SDL_GetTicks(); main_menu->update(); main_menu->render(); main_menu->handleEvents(); frameTime = SDL_GetTicks() - frameStart; if (frameDelay > frameTime) { SDL_Delay(frameDelay - frameTime); } } while (isRunningGame) { SDL_Init(SDL_INIT_EVERYTHING); //Create game window window = createWindow("Splash Screen", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 640, false); if (window) { std::cout << "Window created!" << std::endl; } renderer = createRenderer(window); if (renderer) { SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); std::cout << "Renderer created!" << std::endl; } surfaces = createSurface(window); SDL_SetWindowTitle(window, "Game Screen"); game->init(window, renderer); while (game->running()) { frameStart = SDL_GetTicks(); game->handleEvents(); game->update(); game->render(); frameTime = SDL_GetTicks() - frameStart; if (frameDelay > frameTime) { SDL_Delay(frameDelay - frameTime); } } SDL_SetWindowTitle(window, "Game Over Screen"); game_over->init(window, renderer, surfaces); while (game_over->running()) { frameStart = SDL_GetTicks(); game_over->update(); game_over->render(); game_over->handleEvents(); frameTime = SDL_GetTicks() - frameStart; if (frameDelay > frameTime) { SDL_Delay(frameDelay - frameTime); } } game->clean(); game_over->clean(); } return 0; }
18.550802
106
0.6806
issuran
b45538c27aeaa03dfbc5201dddd787f282ae999f
1,201
hpp
C++
api-cpp-grpc/src/CloudGRPCMacros.hpp
nuralogix/dfx-api-client-cpp
6b45307ddf4b0036c107eebd7e8915f6c501c3b0
[ "MIT" ]
null
null
null
api-cpp-grpc/src/CloudGRPCMacros.hpp
nuralogix/dfx-api-client-cpp
6b45307ddf4b0036c107eebd7e8915f6c501c3b0
[ "MIT" ]
null
null
null
api-cpp-grpc/src/CloudGRPCMacros.hpp
nuralogix/dfx-api-client-cpp
6b45307ddf4b0036c107eebd7e8915f6c501c3b0
[ "MIT" ]
null
null
null
// Copyright (c) Nuralogix. All rights reserved. Licensed under the MIT license. // See LICENSE.txt in the project root for license information. #ifndef DFX_API_CLOUD_GRPC_MACROS_H #define DFX_API_CLOUD_GRPC_MACROS_H #else // This header should ONLY be used from source files and is not included from headers // So this define is only valid for the life of the compiled source module. #error GRPC Macros should only be included from source files, not headers #endif #define MACRO_RETURN_ERROR_IF_GRPC_STATUS_NOT_OK(call) \ { \ ::grpc::Status checkStatus = call; \ if (!checkStatus.ok()) { \ return CloudGRPC::translateGrpcStatus(checkStatus); \ } \ }
60.05
120
0.422981
nuralogix
b45c624a480605f419d51f6820c67637dc6fb2da
16,961
cpp
C++
src/tools/wasm-ctor-eval.cpp
brion/binaryen
977aa84f357d051b0ddc60f204c6b743463c3c6f
[ "Apache-2.0" ]
null
null
null
src/tools/wasm-ctor-eval.cpp
brion/binaryen
977aa84f357d051b0ddc60f204c6b743463c3c6f
[ "Apache-2.0" ]
null
null
null
src/tools/wasm-ctor-eval.cpp
brion/binaryen
977aa84f357d051b0ddc60f204c6b743463c3c6f
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2017 WebAssembly Community Group participants * * 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. */ // // Loads wasm plus a list of functions that are global ctors, i.e., // are to be executed. It then executes as many of them as it can, // applying their changes to memory as needed, then writes it. In // other words, this executes code at compile time to speed up // startup later. // #include <memory> #include "ir/global-utils.h" #include "ir/import-utils.h" #include "ir/literal-utils.h" #include "ir/memory-utils.h" #include "ir/module-utils.h" #include "pass.h" #include "support/colors.h" #include "support/file.h" #include "tool-options.h" #include "wasm-builder.h" #include "wasm-interpreter.h" #include "wasm-io.h" #include "wasm-validator.h" using namespace wasm; struct FailToEvalException { std::string why; FailToEvalException(std::string why) : why(why) {} }; // We do not have access to imported globals class EvallingGlobalManager { // values of globals std::map<Name, Literal> globals; // globals that are dangerous to modify in the module std::set<Name> dangerousGlobals; // whether we are done adding new globals bool sealed = false; public: void addDangerous(Name name) { dangerousGlobals.insert(name); } void seal() { sealed = true; } // for equality purposes, we just care about the globals // and whether they have changed bool operator==(const EvallingGlobalManager& other) { return globals == other.globals; } bool operator!=(const EvallingGlobalManager& other) { return !(*this == other); } Literal& operator[](Name name) { if (dangerousGlobals.count(name) > 0) { std::string extra; if (name == "___dso_handle") { extra = "\nrecommendation: build with -s NO_EXIT_RUNTIME=1 so that " "calls to atexit that use ___dso_handle are not emitted"; } throw FailToEvalException( std::string( "tried to access a dangerous (import-initialized) global: ") + name.str + extra); } return globals[name]; } struct Iterator { Name first; Literal second; bool found; Iterator() : found(false) {} Iterator(Name name, Literal value) : first(name), second(value), found(true) {} bool operator==(const Iterator& other) { return first == other.first && second == other.second && found == other.found; } bool operator!=(const Iterator& other) { return !(*this == other); } }; Iterator find(Name name) { if (globals.find(name) == globals.end()) { return end(); } return Iterator(name, globals[name]); } Iterator end() { return Iterator(); } }; // Use a ridiculously large stack size. static Index STACK_SIZE = 32 * 1024 * 1024; // Start the stack at a ridiculously large location, and do so in // a way that works regardless if the stack goes up or down. static Index STACK_START = 1024 * 1024 * 1024 + STACK_SIZE; // Bound the stack location in both directions, so we have bounds // that do not depend on the direction it grows. static Index STACK_LOWER_LIMIT = STACK_START - STACK_SIZE; static Index STACK_UPPER_LIMIT = STACK_START + STACK_SIZE; class EvallingModuleInstance : public ModuleInstanceBase<EvallingGlobalManager, EvallingModuleInstance> { public: EvallingModuleInstance(Module& wasm, ExternalInterface* externalInterface) : ModuleInstanceBase(wasm, externalInterface) { // if any global in the module has a non-const constructor, it is using a // global import, which we don't have, and is illegal to use ModuleUtils::iterDefinedGlobals(wasm, [&](Global* global) { if (!global->init->is<Const>()) { // some constants are ok to use if (auto* get = global->init->dynCast<GlobalGet>()) { auto name = get->name; auto* import = wasm.getGlobal(name); if (import->module == Name(ENV) && (import->base == STACKTOP || // stack constants are special, we handle them import->base == STACK_MAX)) { return; // this is fine } } // this global is dangerously initialized by an import, so if it is // used, we must fail globals.addDangerous(global->name); } }); } std::vector<char> stack; // create C stack space for us to use. We do *NOT* care about their contents, // assuming the stack top was unwound. the memory may have been modified, // but it should not be read afterwards, doing so would be undefined behavior void setupEnvironment() { // prepare scratch memory stack.resize(2 * STACK_SIZE); // tell the module to accept writes up to the stack end auto total = STACK_START + STACK_SIZE; memorySize = total / Memory::kPageSize; } }; struct CtorEvalExternalInterface : EvallingModuleInstance::ExternalInterface { Module* wasm; EvallingModuleInstance* instance; void init(Module& wasm_, EvallingModuleInstance& instance_) override { wasm = &wasm_; instance = &instance_; } void importGlobals(EvallingGlobalManager& globals, Module& wasm_) override { // fill usable values for stack imports, and globals initialized to them ImportInfo imports(wasm_); if (auto* stackTop = imports.getImportedGlobal(ENV, STACKTOP)) { globals[stackTop->name] = Literal(int32_t(STACK_START)); if (auto* stackTop = GlobalUtils::getGlobalInitializedToImport(wasm_, ENV, STACKTOP)) { globals[stackTop->name] = Literal(int32_t(STACK_START)); } } if (auto* stackMax = imports.getImportedGlobal(ENV, STACK_MAX)) { globals[stackMax->name] = Literal(int32_t(STACK_START)); if (auto* stackMax = GlobalUtils::getGlobalInitializedToImport(wasm_, ENV, STACK_MAX)) { globals[stackMax->name] = Literal(int32_t(STACK_START)); } } // fill in fake values for everything else, which is dangerous to use ModuleUtils::iterDefinedGlobals(wasm_, [&](Global* defined) { if (globals.find(defined->name) == globals.end()) { globals[defined->name] = Literal::makeZero(defined->type); } }); ModuleUtils::iterImportedGlobals(wasm_, [&](Global* import) { if (globals.find(import->name) == globals.end()) { globals[import->name] = Literal::makeZero(import->type); } }); } Literal callImport(Function* import, LiteralList& arguments) override { std::string extra; if (import->module == ENV && import->base == "___cxa_atexit") { extra = "\nrecommendation: build with -s NO_EXIT_RUNTIME=1 so that calls " "to atexit are not emitted"; } throw FailToEvalException(std::string("call import: ") + import->module.str + "." + import->base.str + extra); } Literal callTable(Index index, LiteralList& arguments, Type result, EvallingModuleInstance& instance) override { // we assume the table is not modified (hmm) // look through the segments, try to find the function for (auto& segment : wasm->table.segments) { Index start; // look for the index in this segment. if it has a constant offset, we // look in the proper range. if it instead gets a global, we rely on the // fact that when not dynamically linking then the table is loaded at // offset 0. if (auto* c = segment.offset->dynCast<Const>()) { start = c->value.getInteger(); } else if (segment.offset->is<GlobalGet>()) { start = 0; } else { // wasm spec only allows const and global.get there WASM_UNREACHABLE("invalid expr type"); } auto end = start + segment.data.size(); if (start <= index && index < end) { auto name = segment.data[index - start]; // if this is one of our functions, we can call it; if it was imported, // fail auto* func = wasm->getFunction(name); if (!func->imported()) { return instance.callFunctionInternal(name, arguments); } else { throw FailToEvalException( std::string("callTable on imported function: ") + name.str); } } } throw FailToEvalException( std::string("callTable on index not found in static segments: ") + std::to_string(index)); } int8_t load8s(Address addr) override { return doLoad<int8_t>(addr); } uint8_t load8u(Address addr) override { return doLoad<uint8_t>(addr); } int16_t load16s(Address addr) override { return doLoad<int16_t>(addr); } uint16_t load16u(Address addr) override { return doLoad<uint16_t>(addr); } int32_t load32s(Address addr) override { return doLoad<int32_t>(addr); } uint32_t load32u(Address addr) override { return doLoad<uint32_t>(addr); } int64_t load64s(Address addr) override { return doLoad<int64_t>(addr); } uint64_t load64u(Address addr) override { return doLoad<uint64_t>(addr); } void store8(Address addr, int8_t value) override { doStore<int8_t>(addr, value); } void store16(Address addr, int16_t value) override { doStore<int16_t>(addr, value); } void store32(Address addr, int32_t value) override { doStore<int32_t>(addr, value); } void store64(Address addr, int64_t value) override { doStore<int64_t>(addr, value); } // called during initialization, but we don't keep track of a table void tableStore(Address addr, Name value) override {} void growMemory(Address /*oldSize*/, Address newSize) override { throw FailToEvalException("grow memory"); } void trap(const char* why) override { throw FailToEvalException(std::string("trap: ") + why); } private: // TODO: handle unaligned too, see shell-interface template<typename T> T* getMemory(Address address) { // if memory is on the stack, use the stack if (address >= STACK_LOWER_LIMIT) { if (address >= STACK_UPPER_LIMIT) { throw FailToEvalException("stack usage too high"); } Address relative = address - STACK_LOWER_LIMIT; // in range, all is good, use the stack return (T*)(&instance->stack[relative]); } // otherwise, this must be in the singleton segment. resize as needed if (wasm->memory.segments.size() == 0) { std::vector<char> temp; Builder builder(*wasm); wasm->memory.segments.push_back( Memory::Segment(builder.makeConst(Literal(int32_t(0))), temp)); } // memory should already have been flattened assert(wasm->memory.segments[0].offset->cast<Const>()->value.getInteger() == 0); auto max = address + sizeof(T); auto& data = wasm->memory.segments[0].data; if (max > data.size()) { data.resize(max); } return (T*)(&data[address]); } template<typename T> void doStore(Address address, T value) { // do a memcpy to avoid undefined behavior if unaligned memcpy(getMemory<T>(address), &value, sizeof(T)); } template<typename T> T doLoad(Address address) { // do a memcpy to avoid undefined behavior if unaligned T ret; memcpy(&ret, getMemory<T>(address), sizeof(T)); return ret; } }; void evalCtors(Module& wasm, std::vector<std::string> ctors) { CtorEvalExternalInterface interface; try { // flatten memory, so we do not depend on the layout of data segments if (!MemoryUtils::flatten(wasm.memory)) { Fatal() << " ...stopping since could not flatten memory\n"; } // create an instance for evalling EvallingModuleInstance instance(wasm, &interface); // set up the stack area and other environment details instance.setupEnvironment(); // we should not add new globals from here on; as a result, using // an imported global will fail, as it is missing and so looks new instance.globals.seal(); // go one by one, in order, until we fail // TODO: if we knew priorities, we could reorder? for (auto& ctor : ctors) { std::cerr << "trying to eval " << ctor << '\n'; // snapshot memory, as either the entire function is done, or none auto memoryBefore = wasm.memory; // snapshot globals (note that STACKTOP might be modified, but should // be returned, so that works out) auto globalsBefore = instance.globals; Export* ex = wasm.getExportOrNull(ctor); if (!ex) { Fatal() << "export not found: " << ctor; } try { instance.callFunction(ex->value, LiteralList()); } catch (FailToEvalException& fail) { // that's it, we failed, so stop here, cleaning up partial // memory changes first std::cerr << " ...stopping since could not eval: " << fail.why << "\n"; wasm.memory = memoryBefore; return; } if (instance.globals != globalsBefore) { std::cerr << " ...stopping since globals modified\n"; wasm.memory = memoryBefore; return; } std::cerr << " ...success on " << ctor << ".\n"; // success, the entire function was evalled! // we can nop the function (which may be used elsewhere) // and remove the export auto* exp = wasm.getExport(ctor); auto* func = wasm.getFunction(exp->value); func->body = wasm.allocator.alloc<Nop>(); wasm.removeExport(exp->name); } } catch (FailToEvalException& fail) { // that's it, we failed to even create the instance std::cerr << " ...stopping since could not create module instance: " << fail.why << "\n"; return; } } // // main // int main(int argc, const char* argv[]) { Name entry; std::vector<std::string> passes; bool emitBinary = true; bool debugInfo = false; std::string ctorsString; ToolOptions options("wasm-ctor-eval", "Execute C++ global constructors ahead of time"); options .add("--output", "-o", "Output file (stdout if not specified)", Options::Arguments::One, [](Options* o, const std::string& argument) { o->extra["output"] = argument; Colors::setEnabled(false); }) .add("--emit-text", "-S", "Emit text instead of binary for the output file", Options::Arguments::Zero, [&](Options* o, const std::string& argument) { emitBinary = false; }) .add("--debuginfo", "-g", "Emit names section and debug info", Options::Arguments::Zero, [&](Options* o, const std::string& arguments) { debugInfo = true; }) .add( "--ctors", "-c", "Comma-separated list of global constructor functions to evaluate", Options::Arguments::One, [&](Options* o, const std::string& argument) { ctorsString = argument; }) .add_positional("INFILE", Options::Arguments::One, [](Options* o, const std::string& argument) { o->extra["infile"] = argument; }); options.parse(argc, argv); auto input(read_file<std::string>(options.extra["infile"], Flags::Text)); Module wasm; { if (options.debug) { std::cerr << "reading...\n"; } ModuleReader reader; try { reader.read(options.extra["infile"], wasm); } catch (ParseException& p) { p.dump(std::cerr); Fatal() << "error in parsing input"; } } options.applyFeatures(wasm); if (!WasmValidator().validate(wasm)) { WasmPrinter::printModule(&wasm); Fatal() << "error in validating input"; } // get list of ctors, and eval them std::vector<std::string> ctors; std::istringstream stream(ctorsString); std::string temp; while (std::getline(stream, temp, ',')) { ctors.push_back(temp); } evalCtors(wasm, ctors); // Do some useful optimizations after the evalling { PassRunner passRunner(&wasm); passRunner.add("memory-packing"); // we flattened it, so re-optimize passRunner.add("remove-unused-names"); passRunner.add("dce"); passRunner.add("merge-blocks"); passRunner.add("vacuum"); passRunner.add("remove-unused-module-elements"); passRunner.run(); } if (options.extra.count("output") > 0) { if (options.debug) { std::cerr << "writing..." << std::endl; } ModuleWriter writer; writer.setBinary(emitBinary); writer.setDebugInfo(debugInfo); writer.write(wasm, options.extra["output"]); } }
34.473577
80
0.638347
brion
b45c76c159dde7b08904e8bde372584caa32f7ef
270
cpp
C++
Command/InputHandler.cpp
Notidman/DesignPatterns
85f51dccde0f435b8837a6e985f16bbbe6165317
[ "MIT" ]
null
null
null
Command/InputHandler.cpp
Notidman/DesignPatterns
85f51dccde0f435b8837a6e985f16bbbe6165317
[ "MIT" ]
1
2022-02-02T13:09:27.000Z
2022-02-02T13:09:27.000Z
Command/InputHandler.cpp
Notidman/DesignPatterns
85f51dccde0f435b8837a6e985f16bbbe6165317
[ "MIT" ]
null
null
null
#include "InputHandler.hpp" void InputHandler::handleInput() { if(isPressed(BUTTON_X)) buttonX_->execute(); else if(isPressed(BUTTON_Y)) buttonY_->execute(); else if(isPressed(BUTTON_B)) buttonB_->execute(); else if(isPressed(BUTTON_A)) buttonA_->execute(); }
27
51
0.72963
Notidman
b45ea1aa735dad2ca78b59ed4def5f3f36398ef4
637
hpp
C++
impl/inc/defs.hpp
HMNoureldin/EmbeddedIntentRecognizer
6684a6724c982299973f4f29673915b261803a07
[ "Unlicense" ]
null
null
null
impl/inc/defs.hpp
HMNoureldin/EmbeddedIntentRecognizer
6684a6724c982299973f4f29673915b261803a07
[ "Unlicense" ]
null
null
null
impl/inc/defs.hpp
HMNoureldin/EmbeddedIntentRecognizer
6684a6724c982299973f4f29673915b261803a07
[ "Unlicense" ]
null
null
null
#ifndef _DEFS_H_ #define _DEFS_H_ #include<string> /// Different types of intents that system can recognize. enum IntentType { NONE, WEATHER, FACT}; /// Command for clearing the CMD. namespace Cmd{ const std::string clear_cmd = "\033[2J\033[1;1H"; } /// Different types of intents messages. namespace Intents { const std::string weather_intent = "Intent: Get Weather"; const std::string weather_intent_city = "Intent: Get Weather City"; const std::string fact_intent = "Intent: Get Fact"; const std::string unknown_intent = "Intent: Unknown Intent"; } #endif /* _DEFS_H_ */
27.695652
75
0.67033
HMNoureldin
b45eb090c56ac8649c230f76dba61ee9dd102455
3,176
hpp
C++
src/xray/Luabind/luabind/error.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
src/xray/Luabind/luabind/error.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
null
null
null
src/xray/Luabind/luabind/error.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #ifndef LUABIND_ERROR_HPP_INCLUDED #define LUABIND_ERROR_HPP_INCLUDED #include <luabind/prefix.hpp> #include <exception> #include <luabind/config.hpp> struct lua_State; namespace luabind { #ifndef LUABIND_NO_EXCEPTIONS // this exception usually means that the lua function you called // from C++ failed with an error code. You will have to // read the error code from the top of the lua stack // the reason why this exception class doesn't contain // the message itself is that string_class's copy constructor // may throw, if the copy constructor of an exception that is // being thrown throws another exception, terminate will be called // and the entire application is killed. class error : public std::exception { public: error(lua_State* L): m_L(L) {} lua_State* state() const throw() { return m_L; } virtual const char* what() const throw() { return "lua runtime error"; } private: lua_State* m_L; }; // if an object_cast<>() fails, this is thrown // it is also thrown if the return value of // a lua function cannot be converted class cast_failed : public std::exception { public: cast_failed(lua_State* L, LUABIND_TYPE_INFO i): m_L(L), m_info(i) {} lua_State* state() const throw() { return m_L; } LUABIND_TYPE_INFO info() const throw() { return m_info; } virtual const char* what() const throw() { return "unable to make cast"; } private: lua_State* m_L; LUABIND_TYPE_INFO m_info; }; #else typedef void(*error_callback_fun)(lua_State*); typedef void(*cast_failed_callback_fun)(lua_State*, LUABIND_TYPE_INFO); LUABIND_API void set_error_callback(error_callback_fun e); LUABIND_API void set_cast_failed_callback(cast_failed_callback_fun c); LUABIND_API error_callback_fun get_error_callback(); LUABIND_API cast_failed_callback_fun get_cast_failed_callback(); #endif typedef int (*pcall_callback_fun) (lua_State*); void LUABIND_API set_pcall_callback(pcall_callback_fun e); pcall_callback_fun LUABIND_API get_pcall_callback(); } #endif // LUABIND_ERROR_HPP_INCLUDED
34.150538
77
0.759446
OLR-xray
b4621d86929f24ee2360a3f9732f587d50f0d0f4
39,981
cpp
C++
tests/SelfTest/UsageTests/Matchers.tests.cpp
kjx98/Catch2
e0808bd18607ccfc14f48eab8044e1bb877bb7cc
[ "BSL-1.0" ]
1
2020-11-10T20:19:01.000Z
2020-11-10T20:19:01.000Z
tests/SelfTest/UsageTests/Matchers.tests.cpp
kjx98/Catch2
e0808bd18607ccfc14f48eab8044e1bb877bb7cc
[ "BSL-1.0" ]
null
null
null
tests/SelfTest/UsageTests/Matchers.tests.cpp
kjx98/Catch2
e0808bd18607ccfc14f48eab8044e1bb877bb7cc
[ "BSL-1.0" ]
null
null
null
/* * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include <catch2/catch_test_macros.hpp> #include <catch2/matchers/catch_matchers_exception.hpp> #include <catch2/matchers/catch_matchers_floating.hpp> #include <catch2/matchers/catch_matchers_predicate.hpp> #include <catch2/matchers/catch_matchers_string.hpp> #include <catch2/matchers/catch_matchers_vector.hpp> #include <catch2/matchers/catch_matchers_templated.hpp> #include <algorithm> #include <cmath> #include <list> #include <sstream> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wweak-vtables" #pragma clang diagnostic ignored "-Wpadded" #endif namespace { namespace MatchersTests { #ifndef MATCHERS_TEST_HELPERS_INCLUDED // Don't compile this more than once per TU #define MATCHERS_TEST_HELPERS_INCLUDED inline const char *testStringForMatching() { return "this string contains 'abc' as a substring"; } inline const char *testStringForMatching2() { return "some completely different text that contains one common word"; } inline bool alwaysTrue(int) { return true; } inline bool alwaysFalse(int) { return false; } #ifdef _MSC_VER #pragma warning(disable:4702) // Unreachable code -- MSVC 19 (VS 2015) sees right through the indirection #endif #include <exception> struct SpecialException : std::exception { SpecialException(int i_) : i(i_) {} char const* what() const noexcept override { return "SpecialException::what"; } int i; }; struct DerivedException : std::exception { char const* what() const noexcept override { return "DerivedException::what"; } }; void doesNotThrow() {} [[noreturn]] void throwsSpecialException(int i) { throw SpecialException{i}; } [[noreturn]] void throwsAsInt(int i) { throw i; } [[noreturn]] void throwsDerivedException() { throw DerivedException{}; } class ExceptionMatcher : public Catch::Matchers::MatcherBase<SpecialException> { int m_expected; public: ExceptionMatcher(int i) : m_expected(i) {} bool match(SpecialException const &se) const override { return se.i == m_expected; } std::string describe() const override { std::ostringstream ss; ss << "special exception has value of " << m_expected; return ss.str(); } }; #endif using namespace Catch::Matchers; #ifdef __DJGPP__ float nextafter(float from, float to) { return ::nextafterf(from, to); } double nextafter(double from, double to) { return ::nextafter(from, to); } #else using std::nextafter; #endif TEST_CASE("String matchers", "[matchers]") { REQUIRE_THAT(testStringForMatching(), Contains("string")); REQUIRE_THAT(testStringForMatching(), Contains("string", Catch::CaseSensitive::No)); CHECK_THAT(testStringForMatching(), Contains("abc")); CHECK_THAT(testStringForMatching(), Contains("aBC", Catch::CaseSensitive::No)); CHECK_THAT(testStringForMatching(), StartsWith("this")); CHECK_THAT(testStringForMatching(), StartsWith("THIS", Catch::CaseSensitive::No)); CHECK_THAT(testStringForMatching(), EndsWith("substring")); CHECK_THAT(testStringForMatching(), EndsWith(" SuBsTrInG", Catch::CaseSensitive::No)); } TEST_CASE("Contains string matcher", "[.][failing][matchers]") { CHECK_THAT(testStringForMatching(), Contains("not there", Catch::CaseSensitive::No)); CHECK_THAT(testStringForMatching(), Contains("STRING")); } TEST_CASE("StartsWith string matcher", "[.][failing][matchers]") { CHECK_THAT(testStringForMatching(), StartsWith("This String")); CHECK_THAT(testStringForMatching(), StartsWith("string", Catch::CaseSensitive::No)); } TEST_CASE("EndsWith string matcher", "[.][failing][matchers]") { CHECK_THAT(testStringForMatching(), EndsWith("Substring")); CHECK_THAT(testStringForMatching(), EndsWith("this", Catch::CaseSensitive::No)); } TEST_CASE("Equals string matcher", "[.][failing][matchers]") { CHECK_THAT(testStringForMatching(), Equals("this string contains 'ABC' as a substring")); CHECK_THAT(testStringForMatching(), Equals("something else", Catch::CaseSensitive::No)); } TEST_CASE("Equals", "[matchers]") { CHECK_THAT(testStringForMatching(), Equals("this string contains 'abc' as a substring")); CHECK_THAT(testStringForMatching(), Equals("this string contains 'ABC' as a substring", Catch::CaseSensitive::No)); } // <regex> does not work in libstdc++ 4.8, so we have to enable these tests only when they // are expected to pass and cannot have them in baselines TEST_CASE("Regex string matcher -- libstdc++-4.8 workaround", "[matchers][approvals]") { // This is fiiiine // Taken from an answer at // https://stackoverflow.com/questions/12530406/is-gcc-4-8-or-earlier-buggy-about-regular-expressions #if (!defined(__GNUC__)) || \ (__cplusplus >= 201103L && \ (!defined(__GLIBCXX__) || (__cplusplus >= 201402L) || \ (defined(_GLIBCXX_REGEX_DFS_QUANTIFIERS_LIMIT) || \ defined(_GLIBCXX_REGEX_STATE_LIMIT) || \ (defined(_GLIBCXX_RELEASE) && \ _GLIBCXX_RELEASE > 4)))) // DJGPP meets the above condition but <regex> does not work properly anyway #ifndef __DJGPP__ REQUIRE_THAT(testStringForMatching(), Matches("this string contains 'abc' as a substring")); REQUIRE_THAT(testStringForMatching(), Matches("this string CONTAINS 'abc' as a substring", Catch::CaseSensitive::No)); REQUIRE_THAT(testStringForMatching(), Matches("^this string contains 'abc' as a substring$")); REQUIRE_THAT(testStringForMatching(), Matches("^.* 'abc' .*$")); REQUIRE_THAT(testStringForMatching(), Matches("^.* 'ABC' .*$", Catch::CaseSensitive::No)); #endif #endif REQUIRE_THAT(testStringForMatching2(), !Matches("this string contains 'abc' as a substring")); } TEST_CASE("Regex string matcher", "[matchers][.failing]") { CHECK_THAT(testStringForMatching(), Matches("this STRING contains 'abc' as a substring")); CHECK_THAT(testStringForMatching(), Matches("contains 'abc' as a substring")); CHECK_THAT(testStringForMatching(), Matches("this string contains 'abc' as a")); } TEST_CASE("Matchers can be (AllOf) composed with the && operator", "[matchers][operators][operator&&]") { CHECK_THAT(testStringForMatching(), Contains("string") && Contains("abc") && Contains("substring") && Contains("contains")); } TEST_CASE("Matchers can be (AnyOf) composed with the || operator", "[matchers][operators][operator||]") { CHECK_THAT(testStringForMatching(), Contains("string") || Contains("different") || Contains("random")); CHECK_THAT(testStringForMatching2(), Contains("string") || Contains("different") || Contains("random")); } TEST_CASE("Matchers can be composed with both && and ||", "[matchers][operators][operator||][operator&&]") { CHECK_THAT(testStringForMatching(), (Contains("string") || Contains("different")) && Contains("substring")); } TEST_CASE("Matchers can be composed with both && and || - failing", "[matchers][operators][operator||][operator&&][.failing]") { CHECK_THAT(testStringForMatching(), (Contains("string") || Contains("different")) && Contains("random")); } TEST_CASE("Matchers can be negated (Not) with the ! operator", "[matchers][operators][not]") { CHECK_THAT(testStringForMatching(), !Contains("different")); } TEST_CASE("Matchers can be negated (Not) with the ! operator - failing", "[matchers][operators][not][.failing]") { CHECK_THAT(testStringForMatching(), !Contains("substring")); } template<typename T> struct CustomAllocator : private std::allocator<T> { using size_type = size_t; using difference_type = ptrdiff_t; using pointer = T*; using const_pointer = const T*; using reference = T&; using const_reference = const T&; using value_type = T; template<typename U> struct rebind { using other = CustomAllocator<U>; }; using propagate_on_container_move_assignment = std::true_type; using is_always_equal = std::true_type; CustomAllocator() = default; CustomAllocator(const CustomAllocator& other) : std::allocator<T>(other) { } template<typename U> CustomAllocator(const CustomAllocator<U>&) { } ~CustomAllocator() = default; using std::allocator<T>::address; using std::allocator<T>::allocate; using std::allocator<T>::construct; using std::allocator<T>::deallocate; using std::allocator<T>::max_size; using std::allocator<T>::destroy; }; TEST_CASE("Vector matchers", "[matchers][vector]") { std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); std::vector<int> v2; v2.push_back(1); v2.push_back(2); std::vector<double> v3; v3.push_back(1); v3.push_back(2); v3.push_back(3); std::vector<double> v4; v4.push_back(1 + 1e-8); v4.push_back(2 + 1e-8); v4.push_back(3 + 1e-8); std::vector<int, CustomAllocator<int>> v5; v5.push_back(1); v5.push_back(2); v5.push_back(3); std::vector<int, CustomAllocator<int>> v6; v6.push_back(1); v6.push_back(2); std::vector<int> empty; SECTION("Contains (element)") { CHECK_THAT(v, VectorContains(1)); CHECK_THAT(v, VectorContains(2)); CHECK_THAT(v5, (VectorContains<int, CustomAllocator<int>>(2))); } SECTION("Contains (vector)") { CHECK_THAT(v, Contains(v2)); CHECK_THAT(v, Contains<int>({ 1, 2 })); CHECK_THAT(v5, (Contains<int, std::allocator<int>, CustomAllocator<int>>(v2))); v2.push_back(3); // now exactly matches CHECK_THAT(v, Contains(v2)); CHECK_THAT(v, Contains(empty)); CHECK_THAT(empty, Contains(empty)); CHECK_THAT(v5, (Contains<int, std::allocator<int>, CustomAllocator<int>>(v2))); CHECK_THAT(v5, Contains(v6)); } SECTION("Contains (element), composed") { CHECK_THAT(v, VectorContains(1) && VectorContains(2)); } SECTION("Equals") { // Same vector CHECK_THAT(v, Equals(v)); CHECK_THAT(empty, Equals(empty)); // Different vector with same elements CHECK_THAT(v, Equals<int>({ 1, 2, 3 })); v2.push_back(3); CHECK_THAT(v, Equals(v2)); CHECK_THAT(v5, (Equals<int, std::allocator<int>, CustomAllocator<int>>(v2))); v6.push_back(3); CHECK_THAT(v5, Equals(v6)); } SECTION("UnorderedEquals") { CHECK_THAT(v, UnorderedEquals(v)); CHECK_THAT(v, UnorderedEquals<int>({ 3, 2, 1 })); CHECK_THAT(empty, UnorderedEquals(empty)); auto permuted = v; std::next_permutation(begin(permuted), end(permuted)); REQUIRE_THAT(permuted, UnorderedEquals(v)); std::reverse(begin(permuted), end(permuted)); REQUIRE_THAT(permuted, UnorderedEquals(v)); CHECK_THAT(v5, (UnorderedEquals<int, std::allocator<int>, CustomAllocator<int>>(permuted))); auto v5_permuted = v5; std::next_permutation(begin(v5_permuted), end(v5_permuted)); CHECK_THAT(v5_permuted, UnorderedEquals(v5)); } } TEST_CASE("Vector matchers that fail", "[matchers][vector][.][failing]") { std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); std::vector<int> v2; v2.push_back(1); v2.push_back(2); std::vector<double> v3; v3.push_back(1); v3.push_back(2); v3.push_back(3); std::vector<double> v4; v4.push_back(1.1); v4.push_back(2.1); v4.push_back(3.1); std::vector<int> empty; SECTION("Contains (element)") { CHECK_THAT(v, VectorContains(-1)); CHECK_THAT(empty, VectorContains(1)); } SECTION("Contains (vector)") { CHECK_THAT(empty, Contains(v)); v2.push_back(4); CHECK_THAT(v, Contains(v2)); } SECTION("Equals") { CHECK_THAT(v, Equals(v2)); CHECK_THAT(v2, Equals(v)); CHECK_THAT(empty, Equals(v)); CHECK_THAT(v, Equals(empty)); } SECTION("UnorderedEquals") { CHECK_THAT(v, UnorderedEquals(empty)); CHECK_THAT(empty, UnorderedEquals(v)); auto permuted = v; std::next_permutation(begin(permuted), end(permuted)); permuted.pop_back(); CHECK_THAT(permuted, UnorderedEquals(v)); std::reverse(begin(permuted), end(permuted)); CHECK_THAT(permuted, UnorderedEquals(v)); } } TEST_CASE("Exception matchers that succeed", "[matchers][exceptions][!throws]") { CHECK_THROWS_MATCHES(throwsSpecialException(1), SpecialException, ExceptionMatcher{1}); REQUIRE_THROWS_MATCHES(throwsSpecialException(2), SpecialException, ExceptionMatcher{2}); } TEST_CASE("Exception matchers that fail", "[matchers][exceptions][!throws][.failing]") { SECTION("No exception") { CHECK_THROWS_MATCHES(doesNotThrow(), SpecialException, ExceptionMatcher{1}); REQUIRE_THROWS_MATCHES(doesNotThrow(), SpecialException, ExceptionMatcher{1}); } SECTION("Type mismatch") { CHECK_THROWS_MATCHES(throwsAsInt(1), SpecialException, ExceptionMatcher{1}); REQUIRE_THROWS_MATCHES(throwsAsInt(1), SpecialException, ExceptionMatcher{1}); } SECTION("Contents are wrong") { CHECK_THROWS_MATCHES(throwsSpecialException(3), SpecialException, ExceptionMatcher{1}); REQUIRE_THROWS_MATCHES(throwsSpecialException(4), SpecialException, ExceptionMatcher{1}); } } TEST_CASE("Floating point matchers: float", "[matchers][floating-point]") { SECTION("Relative") { REQUIRE_THAT(10.f, WithinRel(11.1f, 0.1f)); REQUIRE_THAT(10.f, !WithinRel(11.2f, 0.1f)); REQUIRE_THAT( 1.f, !WithinRel(0.f, 0.99f)); REQUIRE_THAT(-0.f, WithinRel(0.f)); SECTION("Some subnormal values") { auto v1 = std::numeric_limits<float>::min(); auto v2 = v1; for (int i = 0; i < 5; ++i) { v2 = std::nextafter(v1, 0.f); } REQUIRE_THAT(v1, WithinRel(v2)); } } SECTION("Margin") { REQUIRE_THAT(1.f, WithinAbs(1.f, 0)); REQUIRE_THAT(0.f, WithinAbs(1.f, 1)); REQUIRE_THAT(0.f, !WithinAbs(1.f, 0.99f)); REQUIRE_THAT(0.f, !WithinAbs(1.f, 0.99f)); REQUIRE_THAT(0.f, WithinAbs(-0.f, 0)); REQUIRE_THAT(11.f, !WithinAbs(10.f, 0.5f)); REQUIRE_THAT(10.f, !WithinAbs(11.f, 0.5f)); REQUIRE_THAT(-10.f, WithinAbs(-10.f, 0.5f)); REQUIRE_THAT(-10.f, WithinAbs(-9.6f, 0.5f)); } SECTION("ULPs") { REQUIRE_THAT(1.f, WithinULP(1.f, 0)); REQUIRE_THAT(nextafter(1.f, 2.f), WithinULP(1.f, 1)); REQUIRE_THAT(0.f, WithinULP(nextafter(0.f, 1.f), 1)); REQUIRE_THAT(1.f, WithinULP(nextafter(1.f, 0.f), 1)); REQUIRE_THAT(1.f, !WithinULP(nextafter(1.f, 2.f), 0)); REQUIRE_THAT(1.f, WithinULP(1.f, 0)); REQUIRE_THAT(-0.f, WithinULP(0.f, 0)); } SECTION("Composed") { REQUIRE_THAT(1.f, WithinAbs(1.f, 0.5) || WithinULP(1.f, 1)); REQUIRE_THAT(1.f, WithinAbs(2.f, 0.5) || WithinULP(1.f, 0)); REQUIRE_THAT(0.0001f, WithinAbs(0.f, 0.001f) || WithinRel(0.f, 0.1f)); } SECTION("Constructor validation") { REQUIRE_NOTHROW(WithinAbs(1.f, 0.f)); REQUIRE_THROWS_AS(WithinAbs(1.f, -1.f), std::domain_error); REQUIRE_NOTHROW(WithinULP(1.f, 0)); REQUIRE_THROWS_AS(WithinULP(1.f, static_cast<uint64_t>(-1)), std::domain_error); REQUIRE_NOTHROW(WithinRel(1.f, 0.f)); REQUIRE_THROWS_AS(WithinRel(1.f, -0.2f), std::domain_error); REQUIRE_THROWS_AS(WithinRel(1.f, 1.f), std::domain_error); } } TEST_CASE("Floating point matchers: double", "[matchers][floating-point]") { SECTION("Relative") { REQUIRE_THAT(10., WithinRel(11.1, 0.1)); REQUIRE_THAT(10., !WithinRel(11.2, 0.1)); REQUIRE_THAT(1., !WithinRel(0., 0.99)); REQUIRE_THAT(-0., WithinRel(0.)); SECTION("Some subnormal values") { auto v1 = std::numeric_limits<double>::min(); auto v2 = v1; for (int i = 0; i < 5; ++i) { v2 = std::nextafter(v1, 0); } REQUIRE_THAT(v1, WithinRel(v2)); } } SECTION("Margin") { REQUIRE_THAT(1., WithinAbs(1., 0)); REQUIRE_THAT(0., WithinAbs(1., 1)); REQUIRE_THAT(0., !WithinAbs(1., 0.99)); REQUIRE_THAT(0., !WithinAbs(1., 0.99)); REQUIRE_THAT(11., !WithinAbs(10., 0.5)); REQUIRE_THAT(10., !WithinAbs(11., 0.5)); REQUIRE_THAT(-10., WithinAbs(-10., 0.5)); REQUIRE_THAT(-10., WithinAbs(-9.6, 0.5)); } SECTION("ULPs") { REQUIRE_THAT(1., WithinULP(1., 0)); REQUIRE_THAT(nextafter(1., 2.), WithinULP(1., 1)); REQUIRE_THAT(0., WithinULP(nextafter(0., 1.), 1)); REQUIRE_THAT(1., WithinULP(nextafter(1., 0.), 1)); REQUIRE_THAT(1., !WithinULP(nextafter(1., 2.), 0)); REQUIRE_THAT(1., WithinULP(1., 0)); REQUIRE_THAT(-0., WithinULP(0., 0)); } SECTION("Composed") { REQUIRE_THAT(1., WithinAbs(1., 0.5) || WithinULP(2., 1)); REQUIRE_THAT(1., WithinAbs(2., 0.5) || WithinULP(1., 0)); REQUIRE_THAT(0.0001, WithinAbs(0., 0.001) || WithinRel(0., 0.1)); } SECTION("Constructor validation") { REQUIRE_NOTHROW(WithinAbs(1., 0.)); REQUIRE_THROWS_AS(WithinAbs(1., -1.), std::domain_error); REQUIRE_NOTHROW(WithinULP(1., 0)); REQUIRE_NOTHROW(WithinRel(1., 0.)); REQUIRE_THROWS_AS(WithinRel(1., -0.2), std::domain_error); REQUIRE_THROWS_AS(WithinRel(1., 1.), std::domain_error); } } TEST_CASE("Floating point matchers that are problematic in approvals", "[approvals][matchers][floating-point]") { REQUIRE_THAT(NAN, !WithinAbs(NAN, 0)); REQUIRE_THAT(NAN, !(WithinAbs(NAN, 100) || WithinULP(NAN, 123))); REQUIRE_THAT(NAN, !WithinULP(NAN, 123)); REQUIRE_THAT(INFINITY, WithinRel(INFINITY)); REQUIRE_THAT(-INFINITY, !WithinRel(INFINITY)); REQUIRE_THAT(1., !WithinRel(INFINITY)); REQUIRE_THAT(INFINITY, !WithinRel(1.)); REQUIRE_THAT(NAN, !WithinRel(NAN)); REQUIRE_THAT(1., !WithinRel(NAN)); REQUIRE_THAT(NAN, !WithinRel(1.)); } TEST_CASE("Arbitrary predicate matcher", "[matchers][generic]") { SECTION("Function pointer") { REQUIRE_THAT(1, Predicate<int>(alwaysTrue, "always true")); REQUIRE_THAT(1, !Predicate<int>(alwaysFalse, "always false")); } SECTION("Lambdas + different type") { REQUIRE_THAT("Hello olleH", Predicate<std::string>( [] (std::string const& str) -> bool { return str.front() == str.back(); }, "First and last character should be equal") ); REQUIRE_THAT("This wouldn't pass", !Predicate<std::string>( [] (std::string const& str) -> bool { return str.front() == str.back(); } ) ); } } TEST_CASE("Regression test #1", "[matchers][vector]") { // At some point, UnorderedEqualsMatcher skipped // mismatched prefixed before doing the comparison itself std::vector<char> actual = { 'a', 'b' }; std::vector<char> expected = { 'c', 'b' }; CHECK_THAT(actual, !UnorderedEquals(expected)); } TEST_CASE("Predicate matcher can accept const char*", "[matchers][compilation]") { REQUIRE_THAT("foo", Predicate<const char*>([] (const char* const&) { return true; })); } TEST_CASE("Vector Approx matcher", "[matchers][approx][vector]") { using Catch::Matchers::Approx; SECTION("Empty vector is roughly equal to an empty vector") { std::vector<double> empty; REQUIRE_THAT(empty, Approx(empty)); } SECTION("Vectors with elements") { std::vector<double> v1({1., 2., 3.}); SECTION("A vector is approx equal to itself") { REQUIRE_THAT(v1, Approx(v1)); REQUIRE_THAT(v1, Approx<double>({ 1., 2., 3. })); } std::vector<double> v2({1.5, 2.5, 3.5}); SECTION("Different length") { auto temp(v1); temp.push_back(4); REQUIRE_THAT(v1, !Approx(temp)); } SECTION("Same length, different elements") { REQUIRE_THAT(v1, !Approx(v2)); REQUIRE_THAT(v1, Approx(v2).margin(0.5)); REQUIRE_THAT(v1, Approx(v2).epsilon(0.5)); REQUIRE_THAT(v1, Approx(v2).epsilon(0.1).scale(500)); } } } TEST_CASE("Vector Approx matcher -- failing", "[matchers][approx][vector][.failing]") { using Catch::Matchers::Approx; SECTION("Empty and non empty vectors are not approx equal") { std::vector<double> empty, t1({1, 2}); CHECK_THAT(empty, Approx(t1)); } SECTION("Just different vectors") { std::vector<double> v1({2., 4., 6.}), v2({1., 3., 5.}); CHECK_THAT(v1, Approx(v2)); } } TEST_CASE("Exceptions matchers", "[matchers][exceptions][!throws]") { REQUIRE_THROWS_MATCHES(throwsDerivedException(), DerivedException, Message("DerivedException::what")); REQUIRE_THROWS_MATCHES(throwsDerivedException(), DerivedException, !Message("derivedexception::what")); REQUIRE_THROWS_MATCHES(throwsSpecialException(2), SpecialException, !Message("DerivedException::what")); REQUIRE_THROWS_MATCHES(throwsSpecialException(2), SpecialException, Message("SpecialException::what")); } struct CheckedTestingMatcher : Catch::Matchers::MatcherBase<int> { mutable bool matchCalled = false; bool matchSucceeds = false; bool match(int const&) const override { matchCalled = true; return matchSucceeds; } std::string describe() const override { return "CheckedTestingMatcher set to " + (matchSucceeds ? std::string("succeed") : std::string("fail")); } }; TEST_CASE("Composed matchers shortcircuit", "[matchers][composed]") { // Check that if first returns false, second is not touched CheckedTestingMatcher first, second; SECTION("MatchAllOf") { first.matchSucceeds = false; Detail::MatchAllOf<int> matcher = Detail::MatchAllOf<int>{} && first && second; CHECK_FALSE( matcher.match( 1 ) ); // These two assertions are the important ones REQUIRE(first.matchCalled); REQUIRE(!second.matchCalled); } // Check that if first returns true, second is not touched SECTION("MatchAnyOf") { first.matchSucceeds = true; Detail::MatchAnyOf<int> matcher = Detail::MatchAnyOf<int>{} || first || second; CHECK( matcher.match( 1 ) ); // These two assertions are the important ones REQUIRE(first.matchCalled); REQUIRE(!second.matchCalled); } } struct CheckedTestingGenericMatcher : Catch::Matchers::MatcherGenericBase { mutable bool matchCalled = false; bool matchSucceeds = false; bool match(int const&) const { matchCalled = true; return matchSucceeds; } std::string describe() const override { return "CheckedTestingGenericMatcher set to " + (matchSucceeds ? std::string("succeed") : std::string("fail")); } }; TEST_CASE("Composed generic matchers shortcircuit", "[matchers][composed][generic]") { // Check that if first returns false, second is not touched CheckedTestingGenericMatcher first, second; SECTION("MatchAllOf") { first.matchSucceeds = false; Detail::MatchAllOfGeneric<CheckedTestingGenericMatcher, CheckedTestingGenericMatcher> matcher{ first, second }; CHECK_FALSE( matcher.match( 1 ) ); // These two assertions are the important ones REQUIRE(first.matchCalled); REQUIRE(!second.matchCalled); } // Check that if first returns true, second is not touched SECTION("MatchAnyOf") { first.matchSucceeds = true; Detail::MatchAnyOfGeneric<CheckedTestingGenericMatcher, CheckedTestingGenericMatcher> matcher{ first, second }; CHECK(matcher.match(1)); // These two assertions are the important ones REQUIRE(first.matchCalled); REQUIRE(!second.matchCalled); } } template<typename Range> struct EqualsRangeMatcher : Catch::Matchers::MatcherGenericBase { EqualsRangeMatcher(Range const& range) : m_range{ range } {} template<typename OtherRange> bool match(OtherRange const& other) const { using std::begin; using std::end; return std::equal(begin(m_range), end(m_range), begin(other), end(other)); } std::string describe() const override { return "Equals: " + Catch::rangeToString(m_range); } private: Range const& m_range; }; template<typename Range> auto EqualsRange(const Range& range) -> EqualsRangeMatcher<Range> { return EqualsRangeMatcher<Range>{range}; } TEST_CASE("Combining templated matchers", "[matchers][templated]") { std::array<int, 3> container{{ 1,2,3 }}; std::array<int, 3> a{{ 1,2,3 }}; std::vector<int> b{ 0,1,2 }; std::list<int> c{ 4,5,6 }; REQUIRE_THAT(container, EqualsRange(a) || EqualsRange(b) || EqualsRange(c)); } TEST_CASE("Combining templated and concrete matchers", "[matchers][templated]") { std::vector<int> vec{ 1, 3, 5 }; std::array<int, 3> a{{ 5, 3, 1 }}; REQUIRE_THAT(vec, Predicate<std::vector<int>>([](auto const& v) { return std::all_of(v.begin(), v.end(), [](int elem) { return elem % 2 == 1; }); }, "All elements are odd") && !EqualsRange(a)); const std::string str = "foobar"; const std::array<char, 6> arr{{ 'f', 'o', 'o', 'b', 'a', 'r' }}; const std::array<char, 6> bad_arr{{ 'o', 'o', 'f', 'b', 'a', 'r' }}; using Catch::Matchers::StartsWith; using Catch::Matchers::EndsWith; REQUIRE_THAT(str, StartsWith("foo") && EqualsRange(arr) && EndsWith("bar")); REQUIRE_THAT(str, StartsWith("foo") && !EqualsRange(bad_arr) && EndsWith("bar")); REQUIRE_THAT(str, EqualsRange(arr) && StartsWith("foo") && EndsWith("bar")); REQUIRE_THAT(str, !EqualsRange(bad_arr) && StartsWith("foo") && EndsWith("bar")); REQUIRE_THAT(str, EqualsRange(bad_arr) || (StartsWith("foo") && EndsWith("bar"))); REQUIRE_THAT(str, (StartsWith("foo") && EndsWith("bar")) || EqualsRange(bad_arr)); } TEST_CASE("Combining concrete matchers does not use templated matchers", "[matchers][templated]") { using Catch::Matchers::StartsWith; using Catch::Matchers::EndsWith; STATIC_REQUIRE(std::is_same< decltype(StartsWith("foo") || (StartsWith("bar") && EndsWith("bar") && !EndsWith("foo"))), Catch::Matchers::Detail::MatchAnyOf<std::string> >::value); } struct MatcherA : Catch::Matchers::MatcherGenericBase { std::string describe() const override { return "equals: (int) 1 or (float) 1.0f"; } bool match(int i) const { return i == 1; } bool match(float f) const { return f == 1.0f; } }; struct MatcherB : Catch::Matchers::MatcherGenericBase { std::string describe() const override { return "equals: (long long) 1"; } bool match(long long l) const { return l == 1ll; } }; struct MatcherC : Catch::Matchers::MatcherGenericBase { std::string describe() const override { return "equals: (T) 1"; } template<typename T> bool match(T t) const { return t == T{1}; } }; struct MatcherD : Catch::Matchers::MatcherGenericBase { std::string describe() const override { return "equals: true"; } bool match(bool b) const { return b == true; } }; TEST_CASE("Combining only templated matchers", "[matchers][templated]") { STATIC_REQUIRE(std::is_same< decltype(MatcherA() || MatcherB()), Catch::Matchers::Detail::MatchAnyOfGeneric<MatcherA, MatcherB> >::value); REQUIRE_THAT(1, MatcherA() || MatcherB()); STATIC_REQUIRE(std::is_same< decltype(MatcherA() && MatcherB()), Catch::Matchers::Detail::MatchAllOfGeneric<MatcherA, MatcherB> >::value); REQUIRE_THAT(1, MatcherA() && MatcherB()); STATIC_REQUIRE(std::is_same< decltype(MatcherA() || !MatcherB()), Catch::Matchers::Detail::MatchAnyOfGeneric<MatcherA, Catch::Matchers::Detail::MatchNotOfGeneric<MatcherB>> >::value); REQUIRE_THAT(1, MatcherA() || !MatcherB()); } TEST_CASE("Combining MatchAnyOfGeneric does not nest", "[matchers][templated]") { // MatchAnyOfGeneric LHS + some matcher RHS STATIC_REQUIRE(std::is_same< decltype((MatcherA() || MatcherB()) || MatcherC()), Catch::Matchers::Detail::MatchAnyOfGeneric<MatcherA, MatcherB, MatcherC> >::value); REQUIRE_THAT(1, (MatcherA() || MatcherB()) || MatcherC()); // some matcher LHS + MatchAnyOfGeneric RHS STATIC_REQUIRE(std::is_same< decltype(MatcherA() || (MatcherB() || MatcherC())), Catch::Matchers::Detail::MatchAnyOfGeneric<MatcherA, MatcherB, MatcherC> >::value); REQUIRE_THAT(1, MatcherA() || (MatcherB() || MatcherC())); // MatchAnyOfGeneric LHS + MatchAnyOfGeneric RHS STATIC_REQUIRE(std::is_same< decltype((MatcherA() || MatcherB()) || (MatcherC() || MatcherD())), Catch::Matchers::Detail::MatchAnyOfGeneric<MatcherA, MatcherB, MatcherC, MatcherD> >::value); REQUIRE_THAT(1, (MatcherA() || MatcherB()) || (MatcherC() || MatcherD())); } TEST_CASE("Combining MatchAllOfGeneric does not nest", "[matchers][templated]") { // MatchAllOfGeneric lhs + some matcher RHS STATIC_REQUIRE(std::is_same< decltype((MatcherA() && MatcherB()) && MatcherC()), Catch::Matchers::Detail::MatchAllOfGeneric<MatcherA, MatcherB, MatcherC> >::value); REQUIRE_THAT(1, (MatcherA() && MatcherB()) && MatcherC()); // some matcher LHS + MatchAllOfGeneric RSH STATIC_REQUIRE(std::is_same< decltype(MatcherA() && (MatcherB() && MatcherC())), Catch::Matchers::Detail::MatchAllOfGeneric<MatcherA, MatcherB, MatcherC> >::value); REQUIRE_THAT(1, MatcherA() && (MatcherB() && MatcherC())); // MatchAllOfGeneric LHS + MatchAllOfGeneric RHS STATIC_REQUIRE(std::is_same< decltype((MatcherA() && MatcherB()) && (MatcherC() && MatcherD())), Catch::Matchers::Detail::MatchAllOfGeneric<MatcherA, MatcherB, MatcherC, MatcherD> >::value); REQUIRE_THAT(1, (MatcherA() && MatcherB()) && (MatcherC() && MatcherD())); } TEST_CASE("Combining MatchNotOfGeneric does not nest", "[matchers][templated]") { STATIC_REQUIRE(std::is_same< decltype(!MatcherA()), Catch::Matchers::Detail::MatchNotOfGeneric<MatcherA> >::value); REQUIRE_THAT(0, !MatcherA()); STATIC_REQUIRE(std::is_same< decltype(!!MatcherA()), MatcherA const& >::value); REQUIRE_THAT(1, !!MatcherA()); STATIC_REQUIRE(std::is_same< decltype(!!!MatcherA()), Catch::Matchers::Detail::MatchNotOfGeneric<MatcherA> >::value); REQUIRE_THAT(0, !!!MatcherA()); STATIC_REQUIRE(std::is_same< decltype(!!!!MatcherA()), MatcherA const & >::value); REQUIRE_THAT(1, !!!!MatcherA()); } struct EvilAddressOfOperatorUsed : std::exception { EvilAddressOfOperatorUsed() {} const char* what() const noexcept override { return "overloaded address-of operator of matcher was used instead of std::addressof"; } }; struct EvilCommaOperatorUsed : std::exception { EvilCommaOperatorUsed() {} const char* what() const noexcept override { return "overloaded comma operator of matcher was used"; } }; struct EvilMatcher : Catch::Matchers::MatcherGenericBase { std::string describe() const override { return "equals: 45"; } bool match(int i) const { return i == 45; } EvilMatcher const* operator& () const { throw EvilAddressOfOperatorUsed(); } int operator,(EvilMatcher const&) const { throw EvilCommaOperatorUsed(); } }; TEST_CASE("Overloaded comma or address-of operators are not used", "[matchers][templated]") { REQUIRE_THROWS_AS((EvilMatcher(), EvilMatcher()), EvilCommaOperatorUsed); REQUIRE_THROWS_AS(&EvilMatcher(), EvilAddressOfOperatorUsed); REQUIRE_NOTHROW(EvilMatcher() || (EvilMatcher() && !EvilMatcher())); REQUIRE_NOTHROW((EvilMatcher() && EvilMatcher()) || !EvilMatcher()); } struct ImmovableMatcher : Catch::Matchers::MatcherGenericBase { ImmovableMatcher() = default; ImmovableMatcher(ImmovableMatcher const&) = delete; ImmovableMatcher(ImmovableMatcher &&) = delete; ImmovableMatcher& operator=(ImmovableMatcher const&) = delete; ImmovableMatcher& operator=(ImmovableMatcher &&) = delete; std::string describe() const override { return "always false"; } template<typename T> bool match(T&&) const { return false; } }; struct MatcherWasMovedOrCopied : std::exception { MatcherWasMovedOrCopied() {} const char* what() const noexcept override { return "attempted to copy or move a matcher"; } }; struct ThrowOnCopyOrMoveMatcher : Catch::Matchers::MatcherGenericBase { ThrowOnCopyOrMoveMatcher() = default; [[noreturn]] ThrowOnCopyOrMoveMatcher(ThrowOnCopyOrMoveMatcher const&): Catch::Matchers::MatcherGenericBase() { throw MatcherWasMovedOrCopied(); } [[noreturn]] ThrowOnCopyOrMoveMatcher(ThrowOnCopyOrMoveMatcher &&): Catch::Matchers::MatcherGenericBase() { throw MatcherWasMovedOrCopied(); } ThrowOnCopyOrMoveMatcher& operator=(ThrowOnCopyOrMoveMatcher const&) { throw MatcherWasMovedOrCopied(); } ThrowOnCopyOrMoveMatcher& operator=(ThrowOnCopyOrMoveMatcher &&) { throw MatcherWasMovedOrCopied(); } std::string describe() const override { return "always false"; } template<typename T> bool match(T&&) const { return false; } }; TEST_CASE("Matchers are not moved or copied", "[matchers][templated][approvals]") { REQUIRE_NOTHROW((ThrowOnCopyOrMoveMatcher() && ThrowOnCopyOrMoveMatcher()) || !ThrowOnCopyOrMoveMatcher()); } TEST_CASE("Immovable matchers can be used", "[matchers][templated][approvals]") { REQUIRE_THAT(123, (ImmovableMatcher() && ImmovableMatcher()) || !ImmovableMatcher()); } struct ReferencingMatcher : Catch::Matchers::MatcherGenericBase { std::string describe() const override { return "takes reference"; } bool match(int& i) const { return i == 22; } }; TEST_CASE("Matchers can take references", "[matchers][templated][approvals]") { REQUIRE_THAT(22, ReferencingMatcher{}); } } } // namespace MatchersTests #ifdef __clang__ #pragma clang diagnostic pop #endif
38.741279
127
0.563017
kjx98
b463cfb4943abd37ed0ec839760eb7b1e73428d3
2,567
cpp
C++
codeforces/E - Kefa and Watch/Wrong answer on test 7 (2).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/E - Kefa and Watch/Wrong answer on test 7 (2).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/E - Kefa and Watch/Wrong answer on test 7 (2).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Nov/16/2018 17:20 * solution_verdict: Wrong answer on test 7 language: GNU C++14 * run_time: 15 ms memory_used: 9000 KB * problem: https://codeforces.com/contest/580/problem/E ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e5; const long mod=1e9+9,bs=29; long pw[N+2],seg[5*N+2],lazy[5*N+2]; int n,m,k,aa[N+2]; string s; void build(int node,int lo,int hi) { if(lo==hi) { seg[node]=(aa[lo]*(pw[lo]-pw[lo-1]+mod)%mod)%mod; return ; } int md=(lo+hi)/2; build(node*2,lo,md); build(node*2+1,md+1,hi); seg[node]=(seg[node*2]+seg[node*2+1])%mod; } void too_lazy(int node,int lo,int hi) { if(!lazy[node])return ; seg[node]=(lazy[node]*(pw[hi]-pw[lo-1]+mod)%mod)%mod; if(lo!=hi) { lazy[node*2]=lazy[node]; lazy[node*2+1]=lazy[node]; } lazy[node]=0; } void upd(int node,int lo,int hi,int lt,int rt,int vl) { too_lazy(node,lo,hi); if(lo>rt||hi<lt)return ; if(lo>=lt&&hi<=rt) { lazy[node]=vl; too_lazy(node,lo,hi); return ; } int md=(lo+hi)/2; upd(node*2,lo,md,lt,rt,vl); upd(node*2+1,md+1,hi,lt,rt,vl); seg[node]=(seg[node*2]+seg[node*2+1])%mod; } long qry(int node,int lo,int hi,int lt,int rt) { too_lazy(node,lo,hi); if(lo>rt||hi<lt)return 0; if(lo>=lt&&hi<=rt)return seg[node]; int md=(lo+hi)/2; long p1=qry(node*2,lo,md,lt,rt); long p2=qry(node*2+1,md+1,hi,lt,rt); return (p1+p2)%mod; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); pw[0]=1LL; for(int i=1;i<=N;i++) pw[i]=(pw[i-1]*bs)%mod; for(int i=1;i<=N;i++) pw[i]=(pw[i-1]+pw[i])%mod; cin>>n>>m>>k>>s; for(int i=0;i<n;i++)aa[i+1]=s[i]-'0'+1; build(1,1,n); for(int i=1;i<=m+k;i++) { int ty,lt,rt,vl;cin>>ty>>lt>>rt>>vl; if(ty==1) { vl++;upd(1,1,n,lt,rt,vl); } else { if(vl==rt-lt+1) { cout<<"YES"<<endl;continue; } int lt1=lt,lt2=lt+vl; int df=min(vl,rt-lt2+1); long p1=qry(1,1,n,lt1,lt1+df-1); long p2=qry(1,1,n,lt2,lt2+df-1); p1=(p1*(pw[vl]-pw[vl-1]+mod)%mod)%mod; if(p1==p2) { cout<<"YES"<<endl;continue; } cout<<"NO"<<endl; } } return 0; }
25.67
111
0.479548
kzvd4729
b46631edc9d66ac6944cd72ecfd73627d081e267
8,628
hpp
C++
include/primer/bound_function.hpp
cbeck88/lua-primer
f6b96a24f96bc3bf03896aea0f758d76ae388fb9
[ "BSL-1.0" ]
14
2016-07-27T18:14:47.000Z
2018-06-15T19:54:10.000Z
include/primer/bound_function.hpp
garbageslam/lua-primer
f6b96a24f96bc3bf03896aea0f758d76ae388fb9
[ "BSL-1.0" ]
5
2016-11-01T23:20:35.000Z
2016-11-29T21:09:53.000Z
include/primer/bound_function.hpp
cbeck88/lua-primer
f6b96a24f96bc3bf03896aea0f758d76ae388fb9
[ "BSL-1.0" ]
2
2021-02-07T03:42:22.000Z
2021-02-10T14:12:00.000Z
// (C) Copyright 2015 - 2018 Christopher Beck // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once /*** * A bound_function is a reference to an object of function type in a lua VM. * * This is a safe and convenience wrapper over lua_ref. The constructor provides * a check against `lua_isfunction`, and we provide several "call" methods which * are backed up by `primer/support/function.hpp`. These functions do not * require a lua_State * -- they attempt to lock the state that holds the * function, and the stack should be left unchanged, even if an error occurs. * * Calling this object will not raise a lua error or throw an exception. */ #include <primer/base.hpp> PRIMER_ASSERT_FILESCOPE; #include <primer/cpp_pcall.hpp> #include <primer/error.hpp> #include <primer/error_capture.hpp> #include <primer/expected.hpp> #include <primer/lua.hpp> #include <primer/lua_ref.hpp> #include <primer/lua_ref_seq.hpp> #include <primer/push.hpp> #include <primer/read.hpp> #include <primer/support/function.hpp> #include <primer/support/function_check_stack.hpp> #include <primer/support/function_return.hpp> #include <string> #include <utility> namespace primer { //[ primer_bound_function class bound_function { lua_ref ref_; //<- // Calls the bound_function in a protected context. This is no fail. template <typename return_type, typename... Args> expected<return_type> protected_call(Args &&... args) const noexcept { expected<return_type> result{primer::error::cant_lock_vm()}; if (lua_State * L = ref_.lock()) { if (auto stack_check = detail::check_stack_push_each<int, Args...>(L)) { // MSVC seems to struggle with this lambda capture, not sure why. // All versions, not just some, and the error message is unhelpful. // The simplest fix is to use [&] even though I don't like doing that. // auto ok = mem_pcall(L, [this, L, &result, &args...]() { auto ok = mem_pcall(L, [&]() { ref_.push(L); primer::push_each(L, std::forward<Args>(args)...); detail::fcn_call(result, L, sizeof...(args)); }); if (!ok) { result = std::move(ok.err()); } } else { result = std::move(stack_check.err()); } } return result; } // Another version, using `lua_ref_seq` as input instead of a parameter pack. template <typename return_type> expected<return_type> protected_call2(const lua_ref_seq & inputs) const noexcept { expected<return_type> result{primer::error::cant_lock_vm()}; if (lua_State * L = ref_.lock()) { if (auto stack_check = detail::check_stack_push_n(L, 1 + inputs.size())) { auto ok = primer::mem_pcall(L, [this, &result, L, &inputs]() { ref_.push(L); inputs.push_each(L); detail::fcn_call(result, L, inputs.size()); }); if (!ok) { result = std::move(ok.err()); } } else { result = std::move(stack_check.err()); } } return result; } //-> public: // Special member functions bound_function() noexcept = default; bound_function(const bound_function &) = default; bound_function(bound_function &&) noexcept = default; bound_function & operator=(const bound_function &) = default; bound_function & operator=(bound_function &&) noexcept = default; ~bound_function() noexcept = default; // Primary constructor: Bind to a function on top of the stack. // Only capture the top item if it is actually a function. // Pop the item *whether or not* it is a function. /*<< Note: Can cause lua memory allocation failure from `ref_` ctor. >>*/ explicit bound_function(lua_State * L); // Forwarded methods from lua_ref explicit operator bool() const noexcept { return static_cast<bool>(ref_); } lua_State * lock() const noexcept { return ref_.lock(); } lua_State * push() const noexcept { return ref_.push(); } bool push(lua_State * L) const noexcept { return ref_.push(L); } void reset() noexcept { ref_.reset(); } void swap(bound_function & other) noexcept { ref_.swap(other.ref_); } // Call methods // These methods attempt to lock the state which holds the lua function, // and perform the call there. They clean up after themselves and leave the // stack as they found it afterwards. // // If passed a lua_ref_seq, its members are the call arguments. If passed // any other sequence of C++ types, those objects are pushed onto the stack // and are the call arguments. template <typename... Args> expected<void> call_no_ret(Args &&... args) const noexcept; expected<void> call_no_ret(lua_ref_seq &) const noexcept; expected<void> call_no_ret(lua_ref_seq const &) const noexcept; expected<void> call_no_ret(lua_ref_seq &&) const noexcept; template <typename... Args> expected<lua_ref> call_one_ret(Args &&... args) const noexcept; expected<lua_ref> call_one_ret(lua_ref_seq &) const noexcept; expected<lua_ref> call_one_ret(lua_ref_seq const &) const noexcept; expected<lua_ref> call_one_ret(lua_ref_seq &&) const noexcept; template <typename... Args> expected<lua_ref_seq> call(Args &&... args) const noexcept; expected<lua_ref_seq> call(lua_ref_seq &) const noexcept; expected<lua_ref_seq> call(lua_ref_seq const &) const noexcept; expected<lua_ref_seq> call(lua_ref_seq &&) const noexcept; // Get a debug string describing what function is bound // Uses lua debug api std::string debug_string() const; }; //] inline bound_function::bound_function(lua_State * L) // : ref_((L && lua_gettop(L)) ? (lua_isfunction(L, -1) ? L : (lua_pop(L, 1), nullptr)) : nullptr) // {} inline std::string bound_function::debug_string() const { std::string result{"empty"}; if (lua_State * L = ref_.lock()) { int top = lua_gettop(L); ref_.push(); if (lua_isfunction(L, -1)) { result = "function "; lua_Debug ar; if (lua_getinfo(L, ">nS", &ar)) { result = ""; if (*ar.namewhat) { result = ar.namewhat + (" " + result); } if (ar.name) { result += ar.name; } result += " ["; result += ar.short_src; result += ":"; result += std::to_string(ar.linedefined); result += "]"; } else { result += "(unknown)"; } } lua_settop(L, top); } return result; } /// Same thing now but with a lua_ref_seq // Use a macro so that we can get const &, &&, and & qualifiers defined. #define CALL_ARGS_HELPER(N, T) \ template <typename... Args> \ inline expected<T> bound_function::N(Args &&... args) const noexcept { \ return this->protected_call<T>(std::forward<Args>(args)...); \ } #define CALL_REF_SEQ_HELPER(N, T, Q) \ inline expected<T> bound_function::N(lua_ref_seq Q inputs) const noexcept { \ return this->protected_call2<T>(inputs); \ } #define CALL_DEFINITIONS(N, T) \ CALL_ARGS_HELPER(N, T) \ CALL_REF_SEQ_HELPER(N, T, &) \ CALL_REF_SEQ_HELPER(N, T, const &) \ CALL_REF_SEQ_HELPER(N, T, &&) // Actual declarations CALL_DEFINITIONS(call_no_ret, void) CALL_DEFINITIONS(call_one_ret, lua_ref) CALL_DEFINITIONS(call, lua_ref_seq) #undef CALL_ARGS_HELPER #undef CALL_REF_SEQ_HELPER #undef CALL_DEFINITIONS inline void swap(bound_function & one, bound_function & other) noexcept { one.swap(other); } // Push and read specialization namespace traits { template <> struct push<primer::bound_function> { static void to_stack(lua_State * L, const bound_function & r) { r.push(L); } static constexpr int stack_space_needed{1}; }; template <> struct read<primer::bound_function> { static expected<bound_function> from_stack(lua_State * L, int idx) { expected<bound_function> result{}; if (lua_isnoneornil(L, idx)) { result = bound_function{}; } else if (lua_isfunction(L, idx)) { lua_pushvalue(L, idx); auto ok = mem_pcall<1>(L, [L, &result]() { result = bound_function{L}; }); if (!ok) { result = ok.err(); } } else { result = primer::arg_error(L, idx, "function"); } return result; } static constexpr int stack_space_needed{1}; }; } // end namespace traits } // end namespace primer
34.374502
80
0.642211
cbeck88
b4665e38ca3d59babe575d1a6fb6e462c5de443c
5,120
cc
C++
cpp/Closest_pair_points.cc
iskhanba/epicode
fda752e5e016ab64011083450be91bec9ee8358a
[ "MIT" ]
null
null
null
cpp/Closest_pair_points.cc
iskhanba/epicode
fda752e5e016ab64011083450be91bec9ee8358a
[ "MIT" ]
null
null
null
cpp/Closest_pair_points.cc
iskhanba/epicode
fda752e5e016ab64011083450be91bec9ee8358a
[ "MIT" ]
null
null
null
// Copyright (c) 2015 Elements of Programming Interviews. All rights reserved. #include <algorithm> #include <cassert> #include <cmath> #include <iostream> #include <limits> #include <random> #include <utility> #include <vector> using std::cout; using std::default_random_engine; using std::endl; using std::get; using std::numeric_limits; using std::ostream; using std::random_device; using std::uniform_int_distribution; using std::vector; struct Point; struct PairOfPoints; struct PairOfPointsWithDistance; PairOfPointsWithDistance FindClosestPairPointsInSubarray( const vector<Point>& points, int s, int e); PairOfPointsWithDistance SolveByEnumerateAllPairs(const vector<Point>& points, int s, int e); PairOfPointsWithDistance FindClosestPairInRemain(vector<Point>* points, double d); double Distance(const Point& a, const Point& b); // @include struct Point { int x, y; // @exclude friend ostream& operator<<(ostream& os, const Point& p) { os << "(" << p.x << ", " << p.y << ")"; return os; } // @include }; const int kBruteForceThreshold = 50; struct PairOfPoints { Point p1, p2; }; struct PairOfPointsWithDistance { Point p1, p2; double distance; }; PairOfPoints FindClosestPairPoints(vector<Point> points) { sort(begin(points), end(points), [](const Point& a, const Point& b) { return a.x < b.x; }); auto closest_two_points_with_distance = FindClosestPairPointsInSubarray(points, 0, points.size()); return {closest_two_points_with_distance.p1, closest_two_points_with_distance.p2}; } // Returns the closest two points and their distance as a tuple in // points[begin : end - 1]. PairOfPointsWithDistance FindClosestPairPointsInSubarray( const vector<Point>& points, int begin, int end) { if (end - begin <= kBruteForceThreshold) { // Switch to brute-force. return SolveByEnumerateAllPairs(points, begin, end); } int mid = begin + (end - begin) / 2; auto result0 = FindClosestPairPointsInSubarray(points, begin, mid); auto result1 = FindClosestPairPointsInSubarray(points, mid, end); auto best_result_in_subsets = result0.distance < result1.distance ? result0 : result1; // Stores the points whose separation along the X-axis is less than min_d. vector<Point> remain; for (const Point& p : points) { if (abs(p.x - points[mid].x) < best_result_in_subsets.distance) { remain.emplace_back(p); } } auto mid_ret = FindClosestPairInRemain(&remain, best_result_in_subsets.distance); return mid_ret.distance < best_result_in_subsets.distance ? mid_ret : best_result_in_subsets; } // Returns the closest two points and the distance between them. PairOfPointsWithDistance SolveByEnumerateAllPairs(const vector<Point>& points, int begin, int end) { PairOfPointsWithDistance ret; ret.distance = numeric_limits<double>::max(); for (int i = begin; i < end; ++i) { for (int j = i + 1; j < end; ++j) { double dis = Distance(points[i], points[j]); if (dis < ret.distance) { ret = {points[i], points[j], dis}; } } } return ret; } // Returns the closest two points and its distance as a tuple. PairOfPointsWithDistance FindClosestPairInRemain(vector<Point>* remain, double d) { sort(remain->begin(), remain->end(), [](const Point& a, const Point& b) { return a.y < b.y; }); // At most six points in remain. PairOfPointsWithDistance ret; ret.distance = numeric_limits<double>::max(); for (int i = 0; i < remain->size(); ++i) { for (int j = i + 1; j < remain->size() && (*remain)[j].y - (*remain)[i].y < d; ++j) { double dis = Distance((*remain)[i], (*remain)[j]); if (dis < ret.distance) { ret = {(*remain)[i], (*remain)[j], dis}; } } } return ret; } double Distance(const Point& a, const Point& b) { return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); } // @exclude int main(int argc, char* argv[]) { default_random_engine gen((random_device())()); for (int times = 0; times < 50; ++times) { int n; if (argc == 2) { n = atoi(argv[1]); } else { uniform_int_distribution<int> dis(1, 5000); n = dis(gen); } cout << "num of points = " << n << endl; vector<Point> points; uniform_int_distribution<int> dis(0, 9999); for (int i = 0; i < n; ++i) { points.emplace_back(Point{dis(gen), dis(gen)}); } auto p = FindClosestPairPoints(points); auto q = SolveByEnumerateAllPairs(points, 0, points.size()); cout << "p = " << p.p1 << " " << p.p2 << ", dis = " << Distance(p.p1, p.p2) << endl; cout << "q = " << q.p1 << " " << q.p2 << ", dis = " << Distance(q.p1, q.p2) << endl; assert(Distance(p.p1, p.p2) == q.distance); } return 0; }
31.411043
81
0.606836
iskhanba