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
108
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
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
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
813837762849dc9d9805a2597acc7eddf6b0ba26
1,245
hpp
C++
boost/numeric/bindings/blas/level1.hpp
rabauke/numeric_bindings
f4de93bd7a01a8b31c9367fad35c81d086768f99
[ "BSL-1.0" ]
null
null
null
boost/numeric/bindings/blas/level1.hpp
rabauke/numeric_bindings
f4de93bd7a01a8b31c9367fad35c81d086768f99
[ "BSL-1.0" ]
null
null
null
boost/numeric/bindings/blas/level1.hpp
rabauke/numeric_bindings
f4de93bd7a01a8b31c9367fad35c81d086768f99
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2009 Rutger ter Borg // // 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 BOOST_NUMERIC_BINDINGS_BLAS_LEVEL1_HPP #define BOOST_NUMERIC_BINDINGS_BLAS_LEVEL1_HPP #include <boost/numeric/bindings/blas/level1/asum.hpp> #include <boost/numeric/bindings/blas/level1/axpy.hpp> #include <boost/numeric/bindings/blas/level1/copy.hpp> #include <boost/numeric/bindings/blas/level1/dotc.hpp> #include <boost/numeric/bindings/blas/level1/dot.hpp> #include <boost/numeric/bindings/blas/level1/dotu.hpp> #include <boost/numeric/bindings/blas/level1/doth.hpp> #include <boost/numeric/bindings/blas/level1/iamax.hpp> #include <boost/numeric/bindings/blas/level1/nrm2.hpp> #include <boost/numeric/bindings/blas/level1/prec_dot.hpp> #include <boost/numeric/bindings/blas/level1/rotg.hpp> #include <boost/numeric/bindings/blas/level1/rot.hpp> #include <boost/numeric/bindings/blas/level1/rotmg.hpp> #include <boost/numeric/bindings/blas/level1/rotm.hpp> #include <boost/numeric/bindings/blas/level1/scal.hpp> #include <boost/numeric/bindings/blas/level1/set.hpp> #include <boost/numeric/bindings/blas/level1/swap.hpp> #endif
40.16129
61
0.794378
rabauke
8138fe5682e111533dd25d039815e6391a602cca
2,241
cpp
C++
embedded/common/src/azydev/embedded/pins/common/pins.cpp
azydevelopment/embedded
014afa0af3a3827f61efe45bc97f2d39e81bd201
[ "MIT" ]
2
2017-10-18T07:19:47.000Z
2017-10-18T07:19:50.000Z
embedded/common/src/azydev/embedded/pins/common/pins.cpp
azydevelopment/embedded
014afa0af3a3827f61efe45bc97f2d39e81bd201
[ "MIT" ]
null
null
null
embedded/common/src/azydev/embedded/pins/common/pins.cpp
azydevelopment/embedded
014afa0af3a3827f61efe45bc97f2d39e81bd201
[ "MIT" ]
null
null
null
/* The MIT License (MIT) * * Copyright (c) 2017 Andrew Yeung <azy.development@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <azydev/embedded/pins/common/pins.h> /* PUBLIC */ template<typename PIN_TYPE> CPins<PIN_TYPE>::~CPins() { } // NVI template<typename PIN_TYPE> void CPins<PIN_TYPE>::SetPinConfig(const PIN_TYPE pinId, const CONFIG_DESC& config) { SetPinConfig_impl(pinId, config); } template<typename PIN_TYPE> void CPins<PIN_TYPE>::PinWriteDigital(const PIN_TYPE pinId, const DIGITAL_STATE state) { PinWriteDigital_impl(pinId, state); } template<typename PIN_TYPE> uint8_t CPins<PIN_TYPE>::PinReadDigital(const PIN_TYPE pinId) const { return PinReadDigital_impl(pinId); } template<typename PIN_TYPE> void CPins<PIN_TYPE>::EnableInterrupt( const PIN_TYPE pinId, const INTERRUPT_TRIGGER trigger, const bool ignorePending) { EnableInterrupt_impl(pinId, trigger, ignorePending); } template<typename PIN_TYPE> void CPins<PIN_TYPE>::DisableInterrupt(const PIN_TYPE pinId) { DisableInterrupt_impl(pinId); } /* PROTECTED */ template<typename PIN_TYPE> CPins<PIN_TYPE>::CPins() { } /* FORWARD DECLARE TEMPLATES */ template class CPins<uint32_t>;
32.955882
88
0.761267
azydevelopment
813ad25b44dc4bd63a76670c8985ae40c07d9483
682
cpp
C++
samples/snippets/cpp/VS_Snippets_Data/XslTRansform.Transform7/CPP/trans_snip4.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_Data/XslTRansform.Transform7/CPP/trans_snip4.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_Data/XslTRansform.Transform7/CPP/trans_snip4.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
#using <System.Xml.dll> #using <System.dll> using namespace System; using namespace System::IO; using namespace System::Xml; using namespace System::Xml::Xsl; int main() { //<snippet1> // Create a resolver with default credentials. XmlUrlResolver^ resolver = gcnew XmlUrlResolver; resolver->Credentials = System::Net::CredentialCache::DefaultCredentials; // Create the XslTransform object. XslTransform^ xslt = gcnew XslTransform; // Load the stylesheet. xslt->Load( "http://myServer/data/authors.xsl", resolver ); // Transform the file. xslt->Transform( "books.xml", "books.html", resolver ); //</snippet1> }
26.230769
77
0.670088
hamarb123
813b435911b65488fcd847bc841643cbe045b3db
1,116
cpp
C++
src/calcutron.cpp
deitry/LittleCalcutron
6bda9a51c88d3d14fbbd9a161bc66188664fcc3c
[ "MIT" ]
null
null
null
src/calcutron.cpp
deitry/LittleCalcutron
6bda9a51c88d3d14fbbd9a161bc66188664fcc3c
[ "MIT" ]
null
null
null
src/calcutron.cpp
deitry/LittleCalcutron
6bda9a51c88d3d14fbbd9a161bc66188664fcc3c
[ "MIT" ]
null
null
null
#include "../include/calcutron.h" #include <iostream> namespace calcutron { map<TokenType, regex> tokenRegExMap = { {VALUE, regex("[0-9]*[.,]?[0-9]*") }, {OPERATOR, regex("[<*/a-zA-Z+>=-]+")}, {LP, regex(R"([(\x5b{])")}, // проверяем на соответствие только левые скобки - для входа в парсер {RP, regex(R"([)\x5d}])")}, // проверяем на соответствие только правые скобки - для выхода из парсера {PAR, regex(R"([(][)]|[\x5b][\x5d]|[{][}])")}, {WS, regex(R"([ \t])")}, {END, regex(R"([\n\xff])")} // символы конца строк }; int error(const string& msg) { cerr << "error: " << msg << '\n'; return 1; } Value* Value::readValue(const string& input) { try { auto tmp = input; // во-первых, если в качестве используемого разделителя дробной части используется запятая, заменяем её точкой std::replace(tmp.begin(), tmp.end(), ',', '.'); // а во-вторых, спокойно конвертируем в число double a = stod(tmp.c_str()); Value* val = new Value(a); return val; } catch (exception& e) { throw runtime_error("cannot read value: " + input); } return nullptr; } }
24.8
113
0.59319
deitry
813dbf53c3fdfd011e9e291877d36d8111ccc28d
12,945
hh
C++
addmc/src/common.hh
vuphan314/dpo
e24fe63fc3321c0cd6d2179c3300596b91082ab5
[ "MIT" ]
null
null
null
addmc/src/common.hh
vuphan314/dpo
e24fe63fc3321c0cd6d2179c3300596b91082ab5
[ "MIT" ]
null
null
null
addmc/src/common.hh
vuphan314/dpo
e24fe63fc3321c0cd6d2179c3300596b91082ab5
[ "MIT" ]
null
null
null
#pragma once /* inclusions =============================================================== */ #include <cassert> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <mutex> #include <queue> #include <random> #include <signal.h> #include <sys/time.h> #include <thread> #include <unordered_set> #include <gmpxx.h> /* uses ===================================================================== */ using std::cout; using std::greater; using std::istream_iterator; using std::left; using std::map; using std::max; using std::min; using std::multimap; using std::mutex; using std::next; using std::ostream; using std::pair; using std::right; using std::setw; using std::string; using std::thread; using std::to_string; using std::vector; /* types ==================================================================== */ using Float = long double; using Int = long long; using TimePoint = std::chrono::time_point<std::chrono::steady_clock>; template<typename K, typename V> using Map = std::unordered_map<K, V>; template<typename T> using Set = std::unordered_set<T>; /* consts =================================================================== */ const Float INF = std::numeric_limits<Float>::infinity(); const Int MIN_INT = std::numeric_limits<Int>::min(); const Int MAX_INT = std::numeric_limits<Int>::max(); const string JOIN_TREE_WORD = "jt"; const string ELIM_VARS_WORD = "e"; const string WARNING = "c MY_WARNING: "; const string DASH_LINE = "c ------------------------------------------------------------------\n"; const string CNF_FILE_OPTION = "cf"; const string PROJECTED_COUNTING_OPTION = "pc"; const string DD_PACKAGE_OPTION = "dp"; const string RANDOM_SEED_OPTION = "rs"; const string VERBOSE_CNF_OPTION = "vc"; const string VERBOSE_SOLVING_OPTION = "vs"; /* diagram packages: */ const string CUDD = "c"; const string SYLVAN = "s"; const map<string, string> DD_PACKAGES = { {CUDD, "CUDD"}, {SYLVAN, "SYLVAN"} }; /* CNF var order heuristics: */ const Int RANDOM = 0; const Int DECLARATION = 1; const Int MOST_CLAUSES = 2; const Int MIN_FILL = 3; const Int MCS = 4; const Int LEX_P = 5; const Int LEX_M = 6; const map<Int, string> CNF_VAR_ORDER_HEURISTICS = { {RANDOM, "RANDOM"}, {DECLARATION, "DECLARATION"}, {MOST_CLAUSES, "MOST_CLAUSES"}, {MIN_FILL, "MIN_FILL"}, {MCS, "MCS"}, {LEX_P, "LEX_P"}, {LEX_M, "LEX_M"} }; /* JT var order heuristics: */ const Int BIGGEST_NODE = 7; const Int HIGHEST_NODE = 8; const map<Int, string> JOIN_TREE_VAR_ORDER_HEURISTICS = { {BIGGEST_NODE, "BIGGEST_NODE"}, {HIGHEST_NODE, "HIGHEST_NODE"} }; /* clustering heuristics: */ const string BUCKET_ELIM_LIST = "bel"; const string BUCKET_ELIM_TREE = "bet"; const string BOUQUET_METHOD_LIST = "bml"; const string BOUQUET_METHOD_TREE = "bmt"; const map<string, string> CLUSTERING_HEURISTICS = { {BUCKET_ELIM_LIST, "BUCKET_ELIM_LIST"}, {BUCKET_ELIM_TREE, "BUCKET_ELIM_TREE"}, {BOUQUET_METHOD_LIST, "BOUQUET_METHOD_LIST"}, {BOUQUET_METHOD_TREE, "BOUQUET_METHOD_TREE"} }; /* CNF/JT verbosity levels: */ const Int PARSED_INPUT = 1; const Int RAW_INPUT = 2; const string INPUT_VERBOSITY_LEVELS = "0, " + to_string(PARSED_INPUT) + ", " + to_string(RAW_INPUT) + "; int"; /* global vars ============================================================== */ extern bool weightedCounting; extern bool projectedCounting; extern Int randomSeed; // for reproducibility extern bool multiplePrecision; extern Int verboseCnf; // 1: parsed CNF, 2: raw CNF too extern Int verboseSolving; // 0: solution, 1: parsed options too, 2: more info extern TimePoint toolStartPoint; /* namespaces =============================================================== */ namespace util { vector<Int> getSortedNums(const Set<Int>& nums); string useOption(string optionName, string optionValue, string comparator = "="); string useDdPackage(string ddPackageArg); map<Int, string> getVarOrderHeuristics(); string helpVarOrderHeuristic(string prefix); // `prefix` is "diagram", "slice", or "cluster" string helpVerboseSolving(); TimePoint getTimePoint(); Float getDuration(TimePoint start); // in seconds vector<string> splitInputLine(string line); void printInputLine(string line, Int lineIndex); void printRowKey(string key, size_t keyWidth); template<typename T> void printRow(string key, const T& val, size_t keyWidth = 32) { printRowKey(key, keyWidth); Int p = cout.precision(); cout.precision(std::numeric_limits<Float>::digits10); cout << val << "\n"; cout.precision(p); } template<typename T, typename U> pair<U, T> flipPair(const pair<T, U>& p) { return pair<U, T>(p.second, p.first); } template<typename T, typename U> multimap<U, T, greater<U>> flipMap(const Map<T, U>& inMap) { // decreasing multimap<U, T, greater<U>> outMap; transform(inMap.begin(), inMap.end(), inserter(outMap, outMap.begin()), flipPair<T, U>); return outMap; } template<typename T, typename U> bool isFound(const T& element, const vector<U>& container) { return std::find(begin(container), end(container), element) != end(container); } template<typename T> Set<T> getIntersection(const Set<T>& container1, const Set<T>& container2) { Set<T> intersection; for (const T& member : container1) { if (container2.contains(member)) { intersection.insert(member); } } return intersection; } template<typename T, typename U> Set<T> getDiff(const Set<T>& members, const U& nonMembers) { Set<T> diff; for (const T& member : members) { if (!nonMembers.contains(member)) { diff.insert(member); } } return diff; } template<typename T, typename U> void unionize(Set<T>& unionSet, const U& container) { for (const auto& member : container) { unionSet.insert(member); } } template<typename T> Set<T> getUnion(const vector<Set<T>>& containers) { Set<T> s; for (const Set<T>& container : containers) { unionize(s, container); } return s; } template<typename T> bool isDisjoint(const Set<T>& container1, const Set<T>& container2) { for (const T& member : container1) { if (container2.contains(member)) { return false; } } return true; } } /* classes for exceptions =================================================== */ class UnsatException : public std::exception {}; class EmptyClauseException : public UnsatException { public: EmptyClauseException(Int lineIndex, string line); }; class UnsatSolverException : public UnsatException { public: UnsatSolverException(); }; class MyError : public std::exception { public: template<typename ... Ts> MyError(const Ts& ... args) { // en.cppreference.com/w/cpp/language/fold cout << "\n"; cout << "c ******************************************************************\n"; cout << "c MY_ERROR: "; (cout << ... << args); // fold expression cout << "\n"; } }; /* classes for CNF formulas ================================================= */ class Number { public: mpq_class quotient; Float fraction; Number(const mpq_class& q); // multiplePrecision Number(Float f); // !multiplePrecision Number(const Number& n); Number(string repr = "0"); // `repr` is `<int>/<int>` or `<float>` Number getAbsolute() const; Float getLog10() const; Float getLogSumExp(const Number& n) const; bool operator==(const Number& n) const; bool operator!=(const Number& n) const; bool operator<(const Number& n) const; bool operator<=(const Number& n) const; bool operator>(const Number& n) const; bool operator>=(const Number& n) const; Number operator*(const Number& n) const; Number& operator*=(const Number& n); Number operator+(const Number& n) const; Number& operator+=(const Number& n); Number operator-(const Number& n) const; }; class Graph { // undirected public: Set<Int> vertices; Map<Int, Set<Int>> adjacencyMap; Graph(const Set<Int>& vs); void addEdge(Int v1, Int v2); bool isNeighbor(Int v1, Int v2) const; bool hasPath(Int from, Int to, Set<Int>& visitedVertices) const; // path length >= 0 bool hasPath(Int from, Int to) const; void removeVertex(Int v); // also removes edges from and to `v` void fillInEdges(Int v); // does not remove `v` Int getFillInEdgeCount(Int v) const; Int getMinFillVertex() const; }; class Label : public vector<Int> { // for lexicographic search public: void addNumber(Int i); // retains descending order static bool hasSmallerLabel(const pair<Int, Label>& a, const pair <Int, Label>& b); }; class Clause : public Set<Int> { public: bool xorFlag; Clause(bool xorFlag); void insertLiteral(Int literal); void printClause() const; Set<Int> getClauseVars() const; }; class Cnf { public: vector<Clause> clauses; Int declaredVarCount = 0; Set<Int> apparentVars; // as opposed to hidden vars that are declared but appear in no clause Set<Int> outerVars; Map<Int, Number> literalWeights; Map<Int, Set<Int>> varToClauses; // var |-> clause indices void printClauses() const; void printLiteralWeights() const; Set<Int> getInnerVars() const; void addClause(const Clause& clause); void setApparentVars(); Graph getPrimalGraph() const; vector<Int> getRandomVarOrder() const; vector<Int> getDeclarationVarOrder() const; vector<Int> getMostClausesVarOrder() const; vector<Int> getMinFillVarOrder() const; vector<Int> getMcsVarOrder() const; vector<Int> getLexPVarOrder() const; vector<Int> getLexMVarOrder() const; vector<Int> getCnfVarOrder(Int cnfVarOrderHeuristic) const; bool isMc21WeightLine(const vector<string> &words) const; // c p weight <literal> <weight> [0] bool isMc21ShowLine(const vector<string> &words) const; // c p show <vars> [0] void completeLiteralWeights(); Cnf(); // empty conjunction Cnf(string filePath); }; /* classes for join trees =================================================== */ class Assignment : public Map<Int, bool> { // partial var assignment public: Assignment(); Assignment(Int var, bool val); Assignment(string bitString); bool getValue(Int var) const; // returns `true` if `var` is unassigned void printAssignment() const; static vector<Assignment> getExtendedAssignments(const vector<Assignment>& assignments, Int var); }; class JoinNode { // abstract public: static Int nodeCount; static Int terminalCount; static Set<Int> nonterminalIndices; static Int backupNodeCount; static Int backupTerminalCount; static Set<Int> backupNonterminalIndices; static Cnf cnf; // this field must be set exactly once before any JoinNode object is constructed Int nodeIndex = MIN_INT; // 0-indexing (equal to clauseIndex for JoinTerminal) vector<JoinNode*> children; // empty for JoinTerminal Set<Int> projectionVars; // empty for JoinTerminal Set<Int> preProjectionVars; // set by constructor static void resetStaticFields(); // backs up and re-initializes static fields static void restoreStaticFields(); // from backup virtual Int getWidth(const Assignment& assignment = Assignment()) const = 0; // of subtree virtual void updateVarSizes( Map<Int, size_t>& varSizes // var x |-> size of biggest node containing x ) const = 0; Set<Int> getPostProjectionVars() const; Int chooseClusterIndex( Int clusterIndex, // of this node const vector<Set<Int>>& projectableVarSets, // Z_1, ..., Z_m string clusteringHeuristic ); // target = |projectableVarSets| if projectableVars \cap postProjectionVars = \emptyset else clusterIndex < target < |projectableVarSets| Int getNodeRank( const vector<Int>& restrictedVarOrder, string clusteringHeuristic ); // rank = |restrictedVarOrder| if restrictedVarOrder \cap postProjectionVars = \emptyset else 0 \le rank < |restrictedVarOrder| bool isTerminal() const; }; class JoinTerminal : public JoinNode { public: Int getWidth(const Assignment& assignment = Assignment()) const override; void updateVarSizes(Map<Int, size_t>& varSizes) const override; JoinTerminal(); }; class JoinNonterminal : public JoinNode { public: void printNode(string startWord) const; // 1-indexing void printSubtree(string startWord = "") const; // post-order traversal Int getWidth(const Assignment& assignment = Assignment()) const override; void updateVarSizes(Map<Int, size_t>& varSizes) const override; vector<Int> getBiggestNodeVarOrder() const; vector<Int> getHighestNodeVarOrder() const; vector<Int> getVarOrder(Int varOrderHeuristic) const; vector<Assignment> getOuterAssignments(Int varOrderHeuristic, Int sliceVarCount) const; JoinNonterminal( const vector<JoinNode*>& children, const Set<Int>& projectionVars = Set<Int>(), Int requestedNodeIndex = MIN_INT ); }; /* global functions ========================================================= */ ostream& operator<<(ostream& stream, const Number& n);
30.387324
142
0.664813
vuphan314
813fde77aeaa105930602973b021fd6f950fd6b4
5,887
cc
C++
ash/fast_ink/laser/laser_pointer_controller.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
ash/fast_ink/laser/laser_pointer_controller.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
ash/fast_ink/laser/laser_pointer_controller.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/fast_ink/laser/laser_pointer_controller.h" #include <memory> #include "ash/fast_ink/laser/laser_pointer_view.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/shell.h" #include "ash/system/palette/palette_utils.h" #include "base/bind.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #include "ui/views/widget/widget.h" #include "ui/wm/core/coordinate_conversion.h" namespace ash { namespace { // A point gets removed from the collection if it is older than // |kPointLifeDurationMs|. const int kPointLifeDurationMs = 200; // When no move events are being received we add a new point every // |kAddStationaryPointsDelayMs| so that points older than // |kPointLifeDurationMs| can get removed. // Note: Using a delay less than the screen refresh interval will not // provide a visual benefit but instead just waste time performing // unnecessary updates. 16ms is the refresh interval on most devices. // TODO(reveman): Use real VSYNC interval instead of a hard-coded delay. const int kAddStationaryPointsDelayMs = 16; } // namespace // A class to hide and lock mouse cursor while it is alive. class LaserPointerController::ScopedLockedHiddenCursor { public: ScopedLockedHiddenCursor() : cursor_manager_(Shell::Get()->cursor_manager()) { DCHECK(cursor_manager_); // Hide and lock the cursor. cursor_manager_->HideCursor(); cursor_manager_->LockCursor(); } ~ScopedLockedHiddenCursor() { // Unlock the cursor. cursor_manager_->UnlockCursor(); } private: wm::CursorManager* const cursor_manager_; }; LaserPointerController::LaserPointerController() { Shell::Get()->AddPreTargetHandler(this); } LaserPointerController::~LaserPointerController() { Shell::Get()->RemovePreTargetHandler(this); } void LaserPointerController::AddObserver(LaserPointerObserver* observer) { observers_.AddObserver(observer); } void LaserPointerController::RemoveObserver(LaserPointerObserver* observer) { observers_.RemoveObserver(observer); } void LaserPointerController::SetEnabled(bool enabled) { if (enabled == is_enabled()) return; FastInkPointerController::SetEnabled(enabled); if (!enabled) { DestroyPointerView(); // Unlock mouse cursor when disabling. scoped_locked_hidden_cursor_.reset(); } NotifyStateChanged(enabled); } views::View* LaserPointerController::GetPointerView() const { return laser_pointer_view_widget_ ? laser_pointer_view_widget_->GetContentsView() : nullptr; } void LaserPointerController::CreatePointerView( base::TimeDelta presentation_delay, aura::Window* root_window) { laser_pointer_view_widget_ = LaserPointerView::Create( base::Milliseconds(kPointLifeDurationMs), presentation_delay, base::Milliseconds(kAddStationaryPointsDelayMs), Shell::GetContainer(root_window, kShellWindowId_OverlayContainer)); } void LaserPointerController::UpdatePointerView(ui::TouchEvent* event) { LaserPointerView* laser_pointer_view = GetLaserPointerView(); if (IsPointerInExcludedWindows(event)) { // Destroy the |LaserPointerView| since the pointer is in the bound of // excluded windows. DestroyPointerView(); return; } // Unlock mouse cursor when switch to touch event. scoped_locked_hidden_cursor_.reset(); laser_pointer_view->AddNewPoint(event->root_location_f(), event->time_stamp()); if (event->type() == ui::ET_TOUCH_RELEASED) { laser_pointer_view->FadeOut(base::BindOnce( &LaserPointerController::DestroyPointerView, base::Unretained(this))); } } void LaserPointerController::UpdatePointerView(ui::MouseEvent* event) { LaserPointerView* laser_pointer_view = GetLaserPointerView(); if (event->type() == ui::ET_MOUSE_MOVED) { if (IsPointerInExcludedWindows(event)) { // Destroy the |LaserPointerView| and unlock the cursor since the cursor // is in the bound of excluded windows. DestroyPointerView(); scoped_locked_hidden_cursor_.reset(); return; } if (!scoped_locked_hidden_cursor_) { scoped_locked_hidden_cursor_ = std::make_unique<ScopedLockedHiddenCursor>(); } } laser_pointer_view->AddNewPoint(event->root_location_f(), event->time_stamp()); if (event->type() == ui::ET_MOUSE_RELEASED) { laser_pointer_view->FadeOut(base::BindOnce( &LaserPointerController::DestroyPointerView, base::Unretained(this))); } } void LaserPointerController::DestroyPointerView() { laser_pointer_view_widget_.reset(); } bool LaserPointerController::CanStartNewGesture(ui::LocatedEvent* event) { // Ignore events over the palette. // TODO(llin): Register palette as a excluded window instead. aura::Window* target = static_cast<aura::Window*>(event->target()); gfx::Point screen_point = event->location(); wm::ConvertPointToScreen(target, &screen_point); if (palette_utils::PaletteContainsPointInScreen(screen_point)) return false; return FastInkPointerController::CanStartNewGesture(event); } bool LaserPointerController::ShouldProcessEvent(ui::LocatedEvent* event) { // Allow clicking when laser pointer is enabled. if (event->type() == ui::ET_MOUSE_PRESSED || event->type() == ui::ET_MOUSE_RELEASED) { return false; } return FastInkPointerController::ShouldProcessEvent(event); } void LaserPointerController::NotifyStateChanged(bool enabled) { for (LaserPointerObserver& observer : observers_) observer.OnLaserPointerStateChanged(enabled); } LaserPointerView* LaserPointerController::GetLaserPointerView() const { return static_cast<LaserPointerView*>(GetPointerView()); } } // namespace ash
32.705556
80
0.741974
zealoussnow
8140b91b3b1cc4a6bddd6d526275b5ced5198f3a
219
cpp
C++
Game/Client/WXClient/Network/PacketHandler/CGUseAbilityHandler.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/Client/WXClient/Network/PacketHandler/CGUseAbilityHandler.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/Client/WXClient/Network/PacketHandler/CGUseAbilityHandler.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
#include "StdAfx.h" #include "CGUseAbility.h" uint CGUseAbilityHandler::Execute(CGUseAbility* pPacket,Player* pPlayer) { __ENTER_FUNCTION return PACKET_EXE_CONTINUE; __LEAVE_FUNCTION return PACKET_EXE_ERROR; }
14.6
72
0.799087
hackerlank
8142e9cc0f56c4ca53093a4af96536fcce47aaac
2,486
hpp
C++
include/Nazara/Graphics/BasicMaterial.hpp
waruqi/NazaraEngine
a64de1ffe8b0790622a0b1cae5759c96b4f86907
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/Graphics/BasicMaterial.hpp
waruqi/NazaraEngine
a64de1ffe8b0790622a0b1cae5759c96b4f86907
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/Graphics/BasicMaterial.hpp
waruqi/NazaraEngine
a64de1ffe8b0790622a0b1cae5759c96b4f86907
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_BASIC_MATERIAL_HPP #define NAZARA_BASIC_MATERIAL_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Graphics/Material.hpp> namespace Nz { class NAZARA_GRAPHICS_API BasicMaterial { friend class MaterialPipeline; public: struct UniformOffsets; BasicMaterial(Material& material); inline void EnableAlphaTest(bool alphaTest); inline const std::shared_ptr<Texture>& GetAlphaMap() const; inline const TextureSamplerInfo& GetAlphaSampler() const; float GetAlphaTestThreshold() const; Color GetDiffuseColor() const; inline const std::shared_ptr<Texture>& GetDiffuseMap() const; inline const TextureSamplerInfo& GetDiffuseSampler() const; inline bool HasAlphaMap() const; inline bool HasAlphaTest() const; inline bool HasAlphaTestThreshold() const; inline bool HasDiffuseColor() const; inline bool HasDiffuseMap() const; inline void SetAlphaMap(std::shared_ptr<Texture> alphaMap); inline void SetAlphaSampler(TextureSamplerInfo alphaSampler); void SetAlphaTestThreshold(float alphaThreshold); void SetDiffuseColor(const Color& diffuse); inline void SetDiffuseMap(std::shared_ptr<Texture> diffuseMap); inline void SetDiffuseSampler(TextureSamplerInfo diffuseSampler); static inline const UniformOffsets& GetOffsets(); static inline const std::shared_ptr<MaterialSettings>& GetSettings(); struct UniformOffsets { std::size_t alphaThreshold; std::size_t diffuseColor; std::size_t totalSize; }; private: struct ConditionIndexes { std::size_t alphaTest; std::size_t hasAlphaMap; std::size_t hasDiffuseMap; }; struct TextureIndexes { std::size_t alpha; std::size_t diffuse; }; static bool Initialize(); static void Uninitialize(); Material& m_material; std::size_t m_uniformBlockIndex; ConditionIndexes m_conditionIndexes; TextureIndexes m_textureIndexes; UniformOffsets m_uniformOffsets; static std::shared_ptr<MaterialSettings> s_materialSettings; static std::size_t s_uniformBlockIndex; static ConditionIndexes s_conditionIndexes; static TextureIndexes s_textureIndexes; static UniformOffsets s_uniformOffsets; }; } #include <Nazara/Graphics/BasicMaterial.inl> #endif // NAZARA_BASIC_MATERIAL_HPP
27.622222
77
0.763475
waruqi
8143adae3f1c11eae4809957553d6be45b20e7d1
3,322
cpp
C++
firmware/stm32/f746/src/mcu/quadratureTimer.cpp
AlanFord/self-balancing-stick
c805f3136effbceed71b7b6fe086c471a698899b
[ "MIT" ]
64
2018-08-13T07:02:33.000Z
2022-03-18T09:21:28.000Z
firmware/stm32/f746/src/mcu/quadratureTimer.cpp
AlanFord/self-balancing-stick
c805f3136effbceed71b7b6fe086c471a698899b
[ "MIT" ]
7
2019-04-29T15:11:33.000Z
2022-02-19T14:15:25.000Z
firmware/stm32/f746/src/mcu/quadratureTimer.cpp
AlanFord/self-balancing-stick
c805f3136effbceed71b7b6fe086c471a698899b
[ "MIT" ]
15
2019-01-22T20:53:44.000Z
2021-11-26T14:53:20.000Z
/* timer.cpp - Implementation file for the Timer class. */ #include <nodate.h> #include "quadratureTimer.h" /*---------------------------------------------------------------------------*/ /** @brief TIMER PWM Timer Initialization This configures a timer perpheral in PWM output mode. */ QuadratureTimer::QuadratureTimer(TimerDevice device, GPIO_pin pinA, uint16_t psc, uint32_t arr, uint32_t ccr, EncoderMode mode) : Timer(device) { this->device = device; Timer_device &instance = TimerList[this->device]; // make sure arr isn't too large for a 16-bit timer // 0xFFFFFFFF is ok as it is the reset value for the 32-bit register (upper 16-bits are ignored) if (!(IS_TIM_32B_COUNTER_INSTANCE(instance.regs)) && (arr != 0xFFFFFFFF)) { if (arr > 0xFFFF) { instance.active = false; return; } } // configure the appropriate GPIO pins if (!GPIO::set_af(pinA.port, pinA.pin, pinA.af)) { Rcc::disablePort((RccPort) pinA.port); instance.active = false; } // Start timer clock if needed. if (!instance.active) { if (Rcc::enable(instance.per)) { instance.active = true; } } // Configure the timer // turn the counter off instance.regs->CR1 &= ~(TIM_CR1_CEN); // reset the peripheral Rcc::reset(instance.per); // set the prescaler and autoreload values instance.regs->PSC = psc; instance.regs->ARR = arr; // setup for pwm instance.regs->CCR1 = ccr; instance.regs->CCMR1 &= ~TIM_CCMR1_CC1S; // CC4 channel is configured as output instance.regs->CCER &= ~TIM_CCER_CC1P; // Output Polarity set to Active High instance.regs->CCMR1 &= ~TIM_CCMR1_OC1M; // Output Compare 4 Mode set as PWM Mode 1. instance.regs->CCMR1 |= TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2; // Output Compare 4 Mode set as PWM Mode 1. instance.regs->CCMR1 |= TIM_CCMR1_OC1PE; // Enable the corresponding preload register instance.regs->CCER |= TIM_CCER_CC1E; // Capture/Compare 4 Output Enable instance.regs->EGR |= TIM_EGR_UG; // Before starting the counter, you have to initialize all the registers instance.regs->BDTR |= TIM_BDTR_MOE; instance.regs->CR1 |= TIM_CR1_CEN; // Start Timer // select both TI1 and TI2 inputs instance.regs->CCMR1 &= ~(TIM_CCMR1_CC1S_Msk); instance.regs->CCMR1 |= 0x01 << TIM_CCMR1_CC1S_Pos; instance.regs->CCMR1 &= ~(TIM_CCMR1_CC2S_Msk); instance.regs->CCMR1 |= 0x01 << TIM_CCMR1_CC2S_Pos; // set input polarities instance.regs->CCER &= ~(TIM_CCER_CC1P_Msk); instance.regs->CCER &= ~(TIM_CCER_CC1NP_Msk); instance.regs->CCER &= ~(TIM_CCER_CC2P_Msk); instance.regs->CCER &= ~(TIM_CCER_CC1NP_Msk); // set encoder mode switch (mode) { case Mode1: instance.regs->SMCR &= ~(TIM_SMCR_SMS_Msk); instance.regs->SMCR |= 0x01 << TIM_SMCR_SMS_Pos;; case Mode2: instance.regs->SMCR &= ~(TIM_SMCR_SMS_Msk); instance.regs->SMCR |= 0x10 << TIM_SMCR_SMS_Pos;; case Mode3: instance.regs->SMCR &= ~(TIM_SMCR_SMS_Msk); instance.regs->SMCR |= 0x11 << TIM_SMCR_SMS_Pos;; default: instance.active = false; } //TODO: enable the timer, but can't use 'start' PSC and ARR should be cleared } /*---------------------------------------------------------------------------*/ /** @brief TIMER Destructor This configures a timer perpheral in PWM output mode. */ QuadratureTimer::~QuadratureTimer() { // TODO: release the associated peripheral }
33.22
145
0.674293
AlanFord
81441bc97bffee6cee32a6c0c9e264d55c0608c2
66,054
hpp
C++
third_party/jsoncons/include/jsoncons_ext/cbor/cbor_parser.hpp
yotann/alive2
ee6f38748c4278d1d261a1a399772da0f1d61dd9
[ "MIT" ]
1
2021-11-03T02:26:36.000Z
2021-11-03T02:26:36.000Z
third_party/jsoncons/include/jsoncons_ext/cbor/cbor_parser.hpp
yotann/alive2
ee6f38748c4278d1d261a1a399772da0f1d61dd9
[ "MIT" ]
3
2021-10-22T03:48:11.000Z
2021-11-03T03:39:48.000Z
third_party/jsoncons/include/jsoncons_ext/cbor/cbor_parser.hpp
yotann/alive2
ee6f38748c4278d1d261a1a399772da0f1d61dd9
[ "MIT" ]
null
null
null
// Copyright 2017 Daniel Parker // Distributed under the Boost license, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See https://github.com/danielaparker/jsoncons for latest version #ifndef JSONCONS_CBOR_CBOR_PARSER_HPP #define JSONCONS_CBOR_CBOR_PARSER_HPP #include <string> #include <vector> #include <memory> #include <utility> // std::move #include <bitset> // std::bitset #include <jsoncons/json.hpp> #include <jsoncons/source.hpp> #include <jsoncons/json_visitor.hpp> #include <jsoncons/config/jsoncons_config.hpp> #include <jsoncons_ext/cbor/cbor_error.hpp> #include <jsoncons_ext/cbor/cbor_detail.hpp> #include <jsoncons_ext/cbor/cbor_options.hpp> #include <jsoncons/json_visitor2.hpp> namespace jsoncons { namespace cbor { enum class parse_mode {root,before_done,array,indefinite_array,map_key,map_value,indefinite_map_key,indefinite_map_value,multi_dim}; struct mapped_string { jsoncons::cbor::detail::cbor_major_type type; std::string s; std::vector<uint8_t> bytes; mapped_string(const std::string& s) : type(jsoncons::cbor::detail::cbor_major_type::text_string), s(s) { } mapped_string(std::string&& s) : type(jsoncons::cbor::detail::cbor_major_type::text_string), s(std::move(s)) { } mapped_string(const std::vector<uint8_t>& bytes) : type(jsoncons::cbor::detail::cbor_major_type::byte_string), bytes(bytes) { } mapped_string(std::vector<uint8_t>&& bytes) : type(jsoncons::cbor::detail::cbor_major_type::byte_string), bytes(std::move(bytes)) { } mapped_string(const mapped_string&) = default; mapped_string(mapped_string&&) = default; mapped_string& operator=(const mapped_string&) = default; mapped_string& operator=(mapped_string&&) = default; }; struct parse_state { parse_mode mode; std::size_t length; std::size_t index; bool pop_stringref_map_stack; parse_state(parse_mode mode, std::size_t length, bool pop_stringref_map_stack = false) noexcept : mode(mode), length(length), index(0), pop_stringref_map_stack(pop_stringref_map_stack) { } parse_state(const parse_state&) = default; parse_state(parse_state&&) = default; }; template <class Source,class Allocator=std::allocator<char>> class basic_cbor_parser : public ser_context { using char_type = char; using char_traits_type = std::char_traits<char>; using allocator_type = Allocator; using char_allocator_type = typename std::allocator_traits<allocator_type>:: template rebind_alloc<char_type>; using byte_allocator_type = typename std::allocator_traits<allocator_type>:: template rebind_alloc<uint8_t>; using tag_allocator_type = typename std::allocator_traits<allocator_type>:: template rebind_alloc<uint64_t>; using parse_state_allocator_type = typename std::allocator_traits<allocator_type>:: template rebind_alloc<parse_state>; using stringref_map = std::vector<mapped_string>; using stringref_map_allocator_type = typename std::allocator_traits<allocator_type>:: template rebind_alloc<stringref_map>; using string_type = std::basic_string<char_type,char_traits_type,char_allocator_type>; enum {stringref_tag, // 25 stringref_namespace_tag, // 256 item_tag, num_of_tags}; std::bitset<num_of_tags> other_tags_; allocator_type alloc_; Source source_; cbor_decode_options options_; bool more_; bool done_; string_type text_buffer_; std::vector<uint8_t,byte_allocator_type> bytes_buffer_; uint64_t item_tag_; std::vector<parse_state,parse_state_allocator_type> state_stack_; std::vector<uint8_t,byte_allocator_type> typed_array_; std::vector<std::size_t> shape_; std::size_t index_; std::vector<stringref_map,stringref_map_allocator_type> stringref_map_stack_; int nesting_depth_; struct read_byte_string_from_buffer { byte_string_view bytes; read_byte_string_from_buffer(const byte_string_view& b) : bytes(b) { } template <class Container> void operator()(Container& c, std::error_code&) { c.clear(); c.reserve(bytes.size()); for (auto b : bytes) { c.push_back(b); } } }; struct read_byte_string_from_source { basic_cbor_parser<Source,Allocator>* source; read_byte_string_from_source(basic_cbor_parser<Source,Allocator>* source) : source(source) { } template <class Container> void operator()(Container& c, std::error_code& ec) { source->read_byte_string(c,ec); } }; public: template <class Sourceable> basic_cbor_parser(Sourceable&& source, const cbor_decode_options& options = cbor_decode_options(), const Allocator alloc = Allocator()) : alloc_(alloc), source_(std::forward<Sourceable>(source)), options_(options), more_(true), done_(false), text_buffer_(alloc), bytes_buffer_(alloc), item_tag_(0), state_stack_(alloc), typed_array_(alloc), index_(0), stringref_map_stack_(alloc), nesting_depth_(0) { state_stack_.emplace_back(parse_mode::root,0); } void restart() { more_ = true; } void reset() { state_stack_.clear(); state_stack_.emplace_back(parse_mode::root,0); more_ = true; done_ = false; } bool done() const { return done_; } bool stopped() const { return !more_; } std::size_t line() const override { return 0; } std::size_t column() const override { return source_.position(); } void parse(json_visitor2& visitor, std::error_code& ec) { while (!done_ && more_) { switch (state_stack_.back().mode) { case parse_mode::multi_dim: { if (state_stack_.back().index == 0) { ++state_stack_.back().index; read_item(visitor, ec); } else { produce_end_multi_dim(visitor, ec); } break; } case parse_mode::array: { if (state_stack_.back().index < state_stack_.back().length) { ++state_stack_.back().index; read_item(visitor, ec); } else { end_array(visitor, ec); } break; } case parse_mode::indefinite_array: { auto c = source_.peek(); if (c.eof) { ec = cbor_errc::unexpected_eof; more_ = false; return; } if (c.value == 0xff) { source_.ignore(1); end_array(visitor, ec); } else { read_item(visitor, ec); } break; } case parse_mode::map_key: { if (state_stack_.back().index < state_stack_.back().length) { ++state_stack_.back().index; state_stack_.back().mode = parse_mode::map_value; read_item(visitor, ec); } else { end_object(visitor, ec); } break; } case parse_mode::map_value: { state_stack_.back().mode = parse_mode::map_key; read_item(visitor, ec); break; } case parse_mode::indefinite_map_key: { auto c = source_.peek(); if (c.eof) { ec = cbor_errc::unexpected_eof; more_ = false; return; } if (c.value == 0xff) { source_.ignore(1); end_object(visitor, ec); } else { state_stack_.back().mode = parse_mode::indefinite_map_value; read_item(visitor, ec); } break; } case parse_mode::indefinite_map_value: { state_stack_.back().mode = parse_mode::indefinite_map_key; read_item(visitor, ec); break; } case parse_mode::root: { state_stack_.back().mode = parse_mode::before_done; read_item(visitor, ec); break; } case parse_mode::before_done: { JSONCONS_ASSERT(state_stack_.size() == 1); state_stack_.clear(); more_ = false; done_ = true; visitor.flush(); break; } } } } private: void read_item(json_visitor2& visitor, std::error_code& ec) { read_tags(ec); if (!more_) { return; } auto c = source_.peek(); if (c.eof) { ec = cbor_errc::unexpected_eof; more_ = false; return; } jsoncons::cbor::detail::cbor_major_type major_type = get_major_type(c.value); uint8_t info = get_additional_information_value(c.value); switch (major_type) { case jsoncons::cbor::detail::cbor_major_type::unsigned_integer: { uint64_t val = get_uint64_value(ec); if (ec) { return; } if (!stringref_map_stack_.empty() && other_tags_[stringref_tag]) { other_tags_[stringref_tag] = false; if (val >= stringref_map_stack_.back().size()) { ec = cbor_errc::stringref_too_large; more_ = false; return; } stringref_map::size_type index = (stringref_map::size_type)val; if (index != val) { ec = cbor_errc::number_too_large; more_ = false; return; } auto& str = stringref_map_stack_.back().at(index); switch (str.type) { case jsoncons::cbor::detail::cbor_major_type::text_string: { handle_string(visitor, jsoncons::basic_string_view<char>(str.s.data(),str.s.length()),ec); if (ec) { return; } break; } case jsoncons::cbor::detail::cbor_major_type::byte_string: { read_byte_string_from_buffer read(byte_string_view(str.bytes)); write_byte_string(read, visitor, ec); if (ec) { return; } break; } default: JSONCONS_UNREACHABLE(); break; } } else { semantic_tag tag = semantic_tag::none; if (other_tags_[item_tag]) { if (item_tag_ == 1) { tag = semantic_tag::epoch_second; } other_tags_[item_tag] = false; } more_ = visitor.uint64_value(val, tag, *this, ec); } break; } case jsoncons::cbor::detail::cbor_major_type::negative_integer: { int64_t val = get_int64_value(ec); if (ec) { return; } semantic_tag tag = semantic_tag::none; if (other_tags_[item_tag]) { if (item_tag_ == 1) { tag = semantic_tag::epoch_second; } other_tags_[item_tag] = false; } more_ = visitor.int64_value(val, tag, *this, ec); break; } case jsoncons::cbor::detail::cbor_major_type::byte_string: { read_byte_string_from_source read(this); write_byte_string(read, visitor, ec); if (ec) { return; } break; } case jsoncons::cbor::detail::cbor_major_type::text_string: { text_buffer_.clear(); read_text_string(text_buffer_, ec); if (ec) { return; } auto result = unicode_traits::validate(text_buffer_.data(),text_buffer_.size()); if (result.ec != unicode_traits::conv_errc()) { ec = cbor_errc::invalid_utf8_text_string; more_ = false; return; } handle_string(visitor, jsoncons::basic_string_view<char>(text_buffer_.data(),text_buffer_.length()),ec); if (ec) { return; } break; } case jsoncons::cbor::detail::cbor_major_type::semantic_tag: { JSONCONS_UNREACHABLE(); break; } case jsoncons::cbor::detail::cbor_major_type::simple: { switch (info) { case 0x14: more_ = visitor.bool_value(false, semantic_tag::none, *this, ec); source_.ignore(1); break; case 0x15: more_ = visitor.bool_value(true, semantic_tag::none, *this, ec); source_.ignore(1); break; case 0x16: more_ = visitor.null_value(semantic_tag::none, *this, ec); source_.ignore(1); break; case 0x17: more_ = visitor.null_value(semantic_tag::undefined, *this, ec); source_.ignore(1); break; case 0x19: // Half-Precision Float (two-byte IEEE 754) { uint64_t val = get_uint64_value(ec); if (ec) { return; } more_ = visitor.half_value(static_cast<uint16_t>(val), semantic_tag::none, *this, ec); break; } case 0x1a: // Single-Precision Float (four-byte IEEE 754) case 0x1b: // Double-Precision Float (eight-byte IEEE 754) { double val = get_double(ec); if (ec) { return; } semantic_tag tag = semantic_tag::none; if (other_tags_[item_tag]) { if (item_tag_ == 1) { tag = semantic_tag::epoch_second; } other_tags_[item_tag] = false; } more_ = visitor.double_value(val, tag, *this, ec); break; } default: { ec = cbor_errc::unknown_type; more_ = false; return; } } break; } case jsoncons::cbor::detail::cbor_major_type::array: { if (other_tags_[item_tag]) { switch (item_tag_) { case 0x04: text_buffer_.clear(); read_decimal_fraction(text_buffer_, ec); if (ec) { return; } more_ = visitor.string_value(text_buffer_, semantic_tag::bigdec, *this, ec); break; case 0x05: text_buffer_.clear(); read_bigfloat(text_buffer_, ec); if (ec) { return; } more_ = visitor.string_value(text_buffer_, semantic_tag::bigfloat, *this, ec); break; case 40: // row major storage produce_begin_multi_dim(visitor, semantic_tag::multi_dim_row_major, ec); break; case 1040: // column major storage produce_begin_multi_dim(visitor, semantic_tag::multi_dim_column_major, ec); break; default: begin_array(visitor, info, ec); break; } other_tags_[item_tag] = false; } else { begin_array(visitor, info, ec); } break; } case jsoncons::cbor::detail::cbor_major_type::map: { begin_object(visitor, info, ec); break; } default: break; } other_tags_[item_tag] = false; } void begin_array(json_visitor2& visitor, uint8_t info, std::error_code& ec) { if (JSONCONS_UNLIKELY(++nesting_depth_ > options_.max_nesting_depth())) { ec = cbor_errc::max_nesting_depth_exceeded; more_ = false; return; } semantic_tag tag = semantic_tag::none; bool pop_stringref_map_stack = false; if (other_tags_[stringref_namespace_tag]) { stringref_map_stack_.emplace_back(alloc_); other_tags_[stringref_namespace_tag] = false; pop_stringref_map_stack = true; } switch (info) { case jsoncons::cbor::detail::additional_info::indefinite_length: { state_stack_.emplace_back(parse_mode::indefinite_array,0,pop_stringref_map_stack); more_ = visitor.begin_array(tag, *this, ec); source_.ignore(1); break; } default: // definite length { std::size_t len = get_size(ec); if (!more_) { return; } state_stack_.emplace_back(parse_mode::array,len,pop_stringref_map_stack); more_ = visitor.begin_array(len, tag, *this, ec); break; } } } void end_array(json_visitor2& visitor, std::error_code& ec) { --nesting_depth_; more_ = visitor.end_array(*this, ec); if (state_stack_.back().pop_stringref_map_stack) { stringref_map_stack_.pop_back(); } state_stack_.pop_back(); } void begin_object(json_visitor2& visitor, uint8_t info, std::error_code& ec) { if (JSONCONS_UNLIKELY(++nesting_depth_ > options_.max_nesting_depth())) { ec = cbor_errc::max_nesting_depth_exceeded; more_ = false; return; } bool pop_stringref_map_stack = false; if (other_tags_[stringref_namespace_tag]) { stringref_map_stack_.emplace_back(alloc_); other_tags_[stringref_namespace_tag] = false; pop_stringref_map_stack = true; } switch (info) { case jsoncons::cbor::detail::additional_info::indefinite_length: { state_stack_.emplace_back(parse_mode::indefinite_map_key,0,pop_stringref_map_stack); more_ = visitor.begin_object(semantic_tag::none, *this, ec); source_.ignore(1); break; } default: // definite_length { std::size_t len = get_size(ec); if (!more_) { return; } state_stack_.emplace_back(parse_mode::map_key,len,pop_stringref_map_stack); more_ = visitor.begin_object(len, semantic_tag::none, *this, ec); break; } } } void end_object(json_visitor2& visitor, std::error_code& ec) { --nesting_depth_; more_ = visitor.end_object(*this, ec); if (state_stack_.back().pop_stringref_map_stack) { stringref_map_stack_.pop_back(); } state_stack_.pop_back(); } void read_text_string(string_type& s, std::error_code& ec) { auto c = source_.peek(); if (c.eof) { ec = cbor_errc::unexpected_eof; more_ = false; return; } jsoncons::cbor::detail::cbor_major_type major_type = get_major_type(c.value); uint8_t info = get_additional_information_value(c.value); JSONCONS_ASSERT(major_type == jsoncons::cbor::detail::cbor_major_type::text_string); auto func = [&s](Source& source, std::size_t length, std::error_code& ec) -> bool { if (source_reader<Source>::read(source, s, length) != length) { ec = cbor_errc::unexpected_eof; return false; } return true; }; iterate_string_chunks(func, major_type, ec); if (!stringref_map_stack_.empty() && info != jsoncons::cbor::detail::additional_info::indefinite_length && s.length() >= jsoncons::cbor::detail::min_length_for_stringref(stringref_map_stack_.back().size())) { stringref_map_stack_.back().emplace_back(s); } } std::size_t get_size(std::error_code& ec) { uint64_t u = get_uint64_value(ec); if (!more_) { return 0; } std::size_t len = static_cast<std::size_t>(u); if (len != u) { ec = cbor_errc::number_too_large; more_ = false; } return len; } bool read_byte_string(std::vector<uint8_t,byte_allocator_type>& v, std::error_code& ec) { bool more = true; v.clear(); auto c = source_.peek(); if (c.eof) { ec = cbor_errc::unexpected_eof; more = false; return more; } jsoncons::cbor::detail::cbor_major_type major_type = get_major_type(c.value); uint8_t info = get_additional_information_value(c.value); JSONCONS_ASSERT(major_type == jsoncons::cbor::detail::cbor_major_type::byte_string); switch(info) { case jsoncons::cbor::detail::additional_info::indefinite_length: { auto func = [&v,&more](Source& source, std::size_t length, std::error_code& ec) -> bool { if (source_reader<Source>::read(source, v, length) != length) { ec = cbor_errc::unexpected_eof; more = false; return more; } return true; }; iterate_string_chunks(func, major_type, ec); break; } default: { std::size_t length = get_size(ec); if (ec) { more = false; return more; } if (source_reader<Source>::read(source_, v, length) != length) { ec = cbor_errc::unexpected_eof; more = false; return more; } if (!stringref_map_stack_.empty() && v.size() >= jsoncons::cbor::detail::min_length_for_stringref(stringref_map_stack_.back().size())) { stringref_map_stack_.back().emplace_back(v); } break; } } return more; } template <class Function> void iterate_string_chunks(Function& func, jsoncons::cbor::detail::cbor_major_type type, std::error_code& ec) { int nesting_level = 0; bool done = false; while (!done) { auto c = source_.peek(); if (c.eof) { ec = cbor_errc::unexpected_eof; more_ = false; return; } if (nesting_level > 0 && c.value == 0xff) { --nesting_level; if (nesting_level == 0) { done = true; } source_.ignore(1); continue; } jsoncons::cbor::detail::cbor_major_type major_type = get_major_type(c.value); if (major_type != type) { ec = cbor_errc::illegal_chunked_string; more_ = false; return; } uint8_t info = get_additional_information_value(c.value); switch (info) { case jsoncons::cbor::detail::additional_info::indefinite_length: { ++nesting_level; source_.ignore(1); break; } default: // definite length { std::size_t length = get_size(ec); if (!more_) { return; } more_ = func(source_, length, ec); if (!more_) { return; } if (nesting_level == 0) { done = true; } break; } } } } uint64_t get_uint64_value(std::error_code& ec) { uint64_t val = 0; uint8_t initial_b; if (source_.read(&initial_b, 1) == 0) { ec = cbor_errc::unexpected_eof; more_ = false; return 0; } uint8_t info = get_additional_information_value(initial_b); switch (info) { case JSONCONS_CBOR_0x00_0x17: // Integer 0x00..0x17 (0..23) { val = info; break; } case 0x18: // Unsigned integer (one-byte uint8_t follows) { uint8_t b; if (source_.read(&b, 1) == 0) { ec = cbor_errc::unexpected_eof; more_ = false; return val; } val = b; break; } case 0x19: // Unsigned integer (two-byte uint16_t follows) { uint8_t buf[sizeof(uint16_t)]; source_.read(buf, sizeof(uint16_t)); val = binary::big_to_native<uint16_t>(buf, sizeof(buf)); break; } case 0x1a: // Unsigned integer (four-byte uint32_t follows) { uint8_t buf[sizeof(uint32_t)]; source_.read(buf, sizeof(uint32_t)); val = binary::big_to_native<uint32_t>(buf, sizeof(buf)); break; } case 0x1b: // Unsigned integer (eight-byte uint64_t follows) { uint8_t buf[sizeof(uint64_t)]; source_.read(buf, sizeof(uint64_t)); val = binary::big_to_native<uint64_t>(buf, sizeof(buf)); break; } default: break; } return val; } int64_t get_int64_value(std::error_code& ec) { int64_t val = 0; auto ch = source_.peek(); if (ch.eof) { ec = cbor_errc::unexpected_eof; more_ = false; return val; } jsoncons::cbor::detail::cbor_major_type major_type = get_major_type(ch.value); uint8_t info = get_additional_information_value(ch.value); switch (major_type) { case jsoncons::cbor::detail::cbor_major_type::negative_integer: source_.ignore(1); switch (info) { case JSONCONS_CBOR_0x00_0x17: // 0x00..0x17 (0..23) { val = static_cast<int8_t>(- 1 - info); break; } case 0x18: // Negative integer (one-byte uint8_t follows) { uint8_t b; if (source_.read(&b, 1) == 0) { ec = cbor_errc::unexpected_eof; more_ = false; return val; } val = static_cast<int64_t>(-1) - static_cast<int64_t>(b); break; } case 0x19: // Negative integer -1-n (two-byte uint16_t follows) { uint8_t buf[sizeof(uint16_t)]; if (source_.read(buf, sizeof(uint16_t)) != sizeof(uint16_t)) { ec = cbor_errc::unexpected_eof; more_ = false; return val; } auto x = binary::big_to_native<uint16_t>(buf, sizeof(buf)); val = static_cast<int64_t>(-1)- x; break; } case 0x1a: // Negative integer -1-n (four-byte uint32_t follows) { uint8_t buf[sizeof(uint32_t)]; if (source_.read(buf, sizeof(uint32_t)) != sizeof(uint32_t)) { ec = cbor_errc::unexpected_eof; more_ = false; return val; } auto x = binary::big_to_native<uint32_t>(buf, sizeof(buf)); val = static_cast<int64_t>(-1)- x; break; } case 0x1b: // Negative integer -1-n (eight-byte uint64_t follows) { uint8_t buf[sizeof(uint64_t)]; if (source_.read(buf, sizeof(uint64_t)) != sizeof(uint64_t)) { ec = cbor_errc::unexpected_eof; more_ = false; return val; } auto x = binary::big_to_native<uint64_t>(buf, sizeof(buf)); val = static_cast<int64_t>(-1)- static_cast<int64_t>(x); break; } } break; case jsoncons::cbor::detail::cbor_major_type::unsigned_integer: { uint64_t x = get_uint64_value(ec); if (ec) { return 0; } if (x <= static_cast<uint64_t>((std::numeric_limits<int64_t>::max)())) { val = x; } else { // error; } break; } break; default: break; } return val; } double get_double(std::error_code& ec) { double val = 0; uint8_t b; if (source_.read(&b, 1) == 0) { ec = cbor_errc::unexpected_eof; more_ = false; return 0; } uint8_t info = get_additional_information_value(b); switch (info) { case 0x1a: // Single-Precision Float (four-byte IEEE 754) { uint8_t buf[sizeof(float)]; if (source_.read(buf, sizeof(float)) !=sizeof(float)) { ec = cbor_errc::unexpected_eof; more_ = false; return 0; } val = binary::big_to_native<float>(buf, sizeof(buf)); break; } case 0x1b: // Double-Precision Float (eight-byte IEEE 754) { uint8_t buf[sizeof(double)]; if (source_.read(buf, sizeof(double)) != sizeof(double)) { ec = cbor_errc::unexpected_eof; more_ = false; return 0; } val = binary::big_to_native<double>(buf, sizeof(buf)); break; } default: break; } return val; } void read_decimal_fraction(string_type& result, std::error_code& ec) { std::size_t size = get_size(ec); if (!more_) { return; } if (size != 2) { ec = cbor_errc::invalid_decimal_fraction; more_ = false; return; } auto c = source_.peek(); if (c.eof) { ec = cbor_errc::unexpected_eof; more_ = false; return; } int64_t exponent = 0; switch (get_major_type(c.value)) { case jsoncons::cbor::detail::cbor_major_type::unsigned_integer: { exponent = get_uint64_value(ec); if (ec) { return; } break; } case jsoncons::cbor::detail::cbor_major_type::negative_integer: { exponent = get_int64_value(ec); if (ec) { return; } break; } default: { ec = cbor_errc::invalid_decimal_fraction; more_ = false; return; } } string_type s; c = source_.peek(); if (c.eof) { ec = cbor_errc::unexpected_eof; more_ = false; return; } switch (get_major_type(c.value)) { case jsoncons::cbor::detail::cbor_major_type::unsigned_integer: { uint64_t val = get_uint64_value(ec); if (ec) { return; } jsoncons::detail::from_integer(val, s); break; } case jsoncons::cbor::detail::cbor_major_type::negative_integer: { int64_t val = get_int64_value(ec); if (ec) { return; } jsoncons::detail::from_integer(val, s); break; } case jsoncons::cbor::detail::cbor_major_type::semantic_tag: { uint8_t b; if (source_.read(&b, 1) == 0) { ec = cbor_errc::unexpected_eof; more_ = false; return; } uint8_t tag = get_additional_information_value(b); c = source_.peek(); if (c.eof) { ec = cbor_errc::unexpected_eof; more_ = false; return; } if (get_major_type(c.value) == jsoncons::cbor::detail::cbor_major_type::byte_string) { bytes_buffer_.clear(); read_byte_string(bytes_buffer_, ec); if (ec) { more_ = false; return; } if (tag == 2) { bigint n = bigint::from_bytes_be(1, bytes_buffer_.data(), bytes_buffer_.size()); n.write_string(s); } else if (tag == 3) { bigint n = bigint::from_bytes_be(1, bytes_buffer_.data(), bytes_buffer_.size()); n = -1 - n; n.write_string(s); } } break; } default: { ec = cbor_errc::invalid_decimal_fraction; more_ = false; return; } } if (s.size() >= static_cast<std::size_t>((std::numeric_limits<int32_t>::max)()) || exponent >= (std::numeric_limits<int32_t>::max)() || exponent <= (std::numeric_limits<int32_t>::min)()) { ec = cbor_errc::invalid_decimal_fraction; more_ = false; return; } else if (s.size() > 0) { if (s[0] == '-') { result.push_back('-'); jsoncons::detail::prettify_string(s.c_str()+1, s.size()-1, (int)exponent, -4, 17, result); } else { jsoncons::detail::prettify_string(s.c_str(), s.size(), (int)exponent, -4, 17, result); } } else { ec = cbor_errc::invalid_decimal_fraction; more_ = false; return; } } void read_bigfloat(string_type& s, std::error_code& ec) { std::size_t size = get_size(ec); if (!more_) { return; } if (size != 2) { ec = cbor_errc::invalid_bigfloat; more_ = false; return; } auto c = source_.peek(); if (c.eof) { ec = cbor_errc::unexpected_eof; more_ = false; return; } int64_t exponent = 0; switch (get_major_type(c.value)) { case jsoncons::cbor::detail::cbor_major_type::unsigned_integer: { exponent = get_uint64_value(ec); if (ec) { return; } break; } case jsoncons::cbor::detail::cbor_major_type::negative_integer: { exponent = get_int64_value(ec); if (ec) { return; } break; } default: { ec = cbor_errc::invalid_bigfloat; more_ = false; return; } } c = source_.peek(); if (c.eof) { ec = cbor_errc::unexpected_eof; more_ = false; return; } switch (get_major_type(c.value)) { case jsoncons::cbor::detail::cbor_major_type::unsigned_integer: { uint64_t val = get_uint64_value(ec); if (ec) { return; } s.push_back('0'); s.push_back('x'); jsoncons::detail::integer_to_string_hex(val, s); break; } case jsoncons::cbor::detail::cbor_major_type::negative_integer: { int64_t val = get_int64_value(ec); if (ec) { return; } s.push_back('-'); s.push_back('0'); s.push_back('x'); jsoncons::detail::integer_to_string_hex(static_cast<uint64_t>(-val), s); break; } case jsoncons::cbor::detail::cbor_major_type::semantic_tag: { uint8_t b; if (source_.read(&b, 1) == 0) { ec = cbor_errc::unexpected_eof; more_ = false; return; } uint8_t tag = get_additional_information_value(b); c = source_.peek(); if (c.eof) { ec = cbor_errc::unexpected_eof; more_ = false; return; } if (get_major_type(c.value) == jsoncons::cbor::detail::cbor_major_type::byte_string) { bytes_buffer_.clear(); more_ = read_byte_string(bytes_buffer_, ec); if (!more_) { return; } if (tag == 2) { s.push_back('0'); s.push_back('x'); bigint n = bigint::from_bytes_be(1, bytes_buffer_.data(), bytes_buffer_.size()); n.write_string_hex(s); } else if (tag == 3) { s.push_back('-'); s.push_back('0'); bigint n = bigint::from_bytes_be(1, bytes_buffer_.data(), bytes_buffer_.size()); n = -1 - n; n.write_string_hex(s); s[2] = 'x'; // overwrite minus } } break; } default: { ec = cbor_errc::invalid_bigfloat; more_ = false; return; } } s.push_back('p'); if (exponent >=0) { jsoncons::detail::integer_to_string_hex(static_cast<uint64_t>(exponent), s); } else { s.push_back('-'); jsoncons::detail::integer_to_string_hex(static_cast<uint64_t>(-exponent), s); } } static jsoncons::cbor::detail::cbor_major_type get_major_type(uint8_t type) { static constexpr uint8_t major_type_shift = 0x05; uint8_t value = type >> major_type_shift; return static_cast<jsoncons::cbor::detail::cbor_major_type>(value); } static uint8_t get_additional_information_value(uint8_t type) { static constexpr uint8_t additional_information_mask = (1U << 5) - 1; uint8_t value = type & additional_information_mask; return value; } void read_tags(std::error_code& ec) { auto c = source_.peek(); if (c.eof) { ec = cbor_errc::unexpected_eof; more_ = false; return; } jsoncons::cbor::detail::cbor_major_type major_type = get_major_type(c.value); while (major_type == jsoncons::cbor::detail::cbor_major_type::semantic_tag) { uint64_t val = get_uint64_value(ec); if (!more_) { return; } switch(val) { case 25: // stringref other_tags_[stringref_tag] = true; break; case 256: // stringref-namespace other_tags_[stringref_namespace_tag] = true; break; default: other_tags_[item_tag] = true; item_tag_ = val; break; } c = source_.peek(); if (c.eof) { ec = cbor_errc::unexpected_eof; more_ = false; return; } major_type = get_major_type(c.value); } } void handle_string(json_visitor2& visitor, const jsoncons::basic_string_view<char>& v, std::error_code& ec) { semantic_tag tag = semantic_tag::none; if (other_tags_[item_tag]) { switch (item_tag_) { case 0: tag = semantic_tag::datetime; break; case 32: tag = semantic_tag::uri; break; case 33: tag = semantic_tag::base64url; break; case 34: tag = semantic_tag::base64; break; default: break; } other_tags_[item_tag] = false; } more_ = visitor.string_value(v, tag, *this, ec); } static jsoncons::endian get_typed_array_endianness(const uint8_t tag) { return ((tag & detail::cbor_array_tags_e_mask) >> detail::cbor_array_tags_e_shift) == 0 ? jsoncons::endian::big : jsoncons::endian::little; } static std::size_t get_typed_array_bytes_per_element(const uint8_t tag) { const uint8_t f = (tag & detail::cbor_array_tags_f_mask) >> detail::cbor_array_tags_f_shift; const uint8_t ll = (tag & detail::cbor_array_tags_ll_mask) >> detail::cbor_array_tags_ll_shift; return std::size_t(1) << (f + ll); } template <typename Read> void write_byte_string(Read read, json_visitor2& visitor, std::error_code& ec) { if (other_tags_[item_tag]) { switch (item_tag_) { case 0x2: { bytes_buffer_.clear(); read(bytes_buffer_,ec); if (ec) { more_ = false; return; } bigint n = bigint::from_bytes_be(1, bytes_buffer_.data(), bytes_buffer_.size()); text_buffer_.clear(); n.write_string(text_buffer_); more_ = visitor.string_value(text_buffer_, semantic_tag::bigint, *this, ec); break; } case 0x3: { bytes_buffer_.clear(); read(bytes_buffer_,ec); if (ec) { more_ = false; return; } bigint n = bigint::from_bytes_be(1, bytes_buffer_.data(), bytes_buffer_.size()); n = -1 - n; text_buffer_.clear(); n.write_string(text_buffer_); more_ = visitor.string_value(text_buffer_, semantic_tag::bigint, *this, ec); break; } case 0x15: { read(bytes_buffer_,ec); if (ec) { more_ = false; return; } more_ = visitor.byte_string_value(bytes_buffer_, semantic_tag::base64url, *this, ec); break; } case 0x16: { read(bytes_buffer_,ec); if (ec) { more_ = false; return; } more_ = visitor.byte_string_value(bytes_buffer_, semantic_tag::base64, *this, ec); break; } case 0x17: { read(bytes_buffer_,ec); if (ec) { more_ = false; return; } more_ = visitor.byte_string_value(bytes_buffer_, semantic_tag::base16, *this, ec); break; } case 0x40: { typed_array_.clear(); read(typed_array_,ec); if (ec) { more_ = false; return; } uint8_t* data = reinterpret_cast<uint8_t*>(typed_array_.data()); std::size_t size = typed_array_.size(); more_ = visitor.typed_array(jsoncons::span<const uint8_t>(data,size), semantic_tag::none, *this, ec); break; } case 0x44: { typed_array_.clear(); read(typed_array_,ec); if (ec) { more_ = false; return; } uint8_t* data = reinterpret_cast<uint8_t*>(typed_array_.data()); std::size_t size = typed_array_.size(); more_ = visitor.typed_array(jsoncons::span<const uint8_t>(data,size), semantic_tag::clamped, *this, ec); break; } case 0x41: case 0x45: { typed_array_.clear(); read(typed_array_,ec); if (ec) { more_ = false; return; } const uint8_t tag = (uint8_t)item_tag_; jsoncons::endian e = get_typed_array_endianness(tag); const size_t bytes_per_elem = get_typed_array_bytes_per_element(tag); uint16_t* data = reinterpret_cast<uint16_t*>(typed_array_.data()); std::size_t size = typed_array_.size()/bytes_per_elem; if (e != jsoncons::endian::native) { for (std::size_t i = 0; i < size; ++i) { data[i] = binary::byte_swap<uint16_t>(data[i]); } } more_ = visitor.typed_array(jsoncons::span<const uint16_t>(data,size), semantic_tag::none, *this, ec); break; } case 0x42: case 0x46: { typed_array_.clear(); read(typed_array_,ec); if (ec) { more_ = false; return; } const uint8_t tag = (uint8_t)item_tag_; jsoncons::endian e = get_typed_array_endianness(tag); const size_t bytes_per_elem = get_typed_array_bytes_per_element(tag); uint32_t* data = reinterpret_cast<uint32_t*>(typed_array_.data()); std::size_t size = typed_array_.size()/bytes_per_elem; if (e != jsoncons::endian::native) { for (std::size_t i = 0; i < size; ++i) { data[i] = binary::byte_swap<uint32_t>(data[i]); } } more_ = visitor.typed_array(jsoncons::span<const uint32_t>(data,size), semantic_tag::none, *this, ec); break; } case 0x43: case 0x47: { typed_array_.clear(); read(typed_array_,ec); if (ec) { more_ = false; return; } const uint8_t tag = (uint8_t)item_tag_; jsoncons::endian e = get_typed_array_endianness(tag); const size_t bytes_per_elem = get_typed_array_bytes_per_element(tag); uint64_t* data = reinterpret_cast<uint64_t*>(typed_array_.data()); std::size_t size = typed_array_.size()/bytes_per_elem; if (e != jsoncons::endian::native) { for (std::size_t i = 0; i < size; ++i) { data[i] = binary::byte_swap<uint64_t>(data[i]); } } more_ = visitor.typed_array(jsoncons::span<const uint64_t>(data,size), semantic_tag::none, *this, ec); break; } case 0x48: { typed_array_.clear(); read(typed_array_,ec); if (ec) { more_ = false; return; } int8_t* data = reinterpret_cast<int8_t*>(typed_array_.data()); std::size_t size = typed_array_.size(); more_ = visitor.typed_array(jsoncons::span<const int8_t>(data,size), semantic_tag::none, *this, ec); break; } case 0x49: case 0x4d: { typed_array_.clear(); read(typed_array_,ec); if (ec) { more_ = false; return; } const uint8_t tag = (uint8_t)item_tag_; jsoncons::endian e = get_typed_array_endianness(tag); const size_t bytes_per_elem = get_typed_array_bytes_per_element(tag); int16_t* data = reinterpret_cast<int16_t*>(typed_array_.data()); std::size_t size = typed_array_.size()/bytes_per_elem; if (e != jsoncons::endian::native) { for (std::size_t i = 0; i < size; ++i) { data[i] = binary::byte_swap<int16_t>(data[i]); } } more_ = visitor.typed_array(jsoncons::span<const int16_t>(data,size), semantic_tag::none, *this, ec); break; } case 0x4a: case 0x4e: { typed_array_.clear(); read(typed_array_,ec); if (ec) { more_ = false; return; } const uint8_t tag = (uint8_t)item_tag_; jsoncons::endian e = get_typed_array_endianness(tag); const size_t bytes_per_elem = get_typed_array_bytes_per_element(tag); int32_t* data = reinterpret_cast<int32_t*>(typed_array_.data()); std::size_t size = typed_array_.size()/bytes_per_elem; if (e != jsoncons::endian::native) { for (std::size_t i = 0; i < size; ++i) { data[i] = binary::byte_swap<int32_t>(data[i]); } } more_ = visitor.typed_array(jsoncons::span<const int32_t>(data,size), semantic_tag::none, *this, ec); break; } case 0x4b: case 0x4f: { typed_array_.clear(); read(typed_array_,ec); if (ec) { more_ = false; return; } const uint8_t tag = (uint8_t)item_tag_; jsoncons::endian e = get_typed_array_endianness(tag); const size_t bytes_per_elem = get_typed_array_bytes_per_element(tag); int64_t* data = reinterpret_cast<int64_t*>(typed_array_.data()); std::size_t size = typed_array_.size()/bytes_per_elem; if (e != jsoncons::endian::native) { for (std::size_t i = 0; i < size; ++i) { data[i] = binary::byte_swap<int64_t>(data[i]); } } more_ = visitor.typed_array(jsoncons::span<const int64_t>(data,size), semantic_tag::none, *this, ec); break; } case 0x50: case 0x54: { typed_array_.clear(); read(typed_array_,ec); if (ec) { more_ = false; return; } const uint8_t tag = (uint8_t)item_tag_; jsoncons::endian e = get_typed_array_endianness(tag); const size_t bytes_per_elem = get_typed_array_bytes_per_element(tag); uint16_t* data = reinterpret_cast<uint16_t*>(typed_array_.data()); std::size_t size = typed_array_.size()/bytes_per_elem; if (e != jsoncons::endian::native) { for (std::size_t i = 0; i < size; ++i) { data[i] = binary::byte_swap<uint16_t>(data[i]); } } more_ = visitor.typed_array(half_arg, jsoncons::span<const uint16_t>(data,size), semantic_tag::none, *this, ec); break; } case 0x51: case 0x55: { typed_array_.clear(); read(typed_array_,ec); if (ec) { more_ = false; return; } const uint8_t tag = (uint8_t)item_tag_; jsoncons::endian e = get_typed_array_endianness(tag); const size_t bytes_per_elem = get_typed_array_bytes_per_element(tag); float* data = reinterpret_cast<float*>(typed_array_.data()); std::size_t size = typed_array_.size()/bytes_per_elem; if (e != jsoncons::endian::native) { for (std::size_t i = 0; i < size; ++i) { data[i] = binary::byte_swap<float>(data[i]); } } more_ = visitor.typed_array(jsoncons::span<const float>(data,size), semantic_tag::none, *this, ec); break; } case 0x52: case 0x56: { typed_array_.clear(); read(typed_array_,ec); if (ec) { more_ = false; return; } const uint8_t tag = (uint8_t)item_tag_; jsoncons::endian e = get_typed_array_endianness(tag); const size_t bytes_per_elem = get_typed_array_bytes_per_element(tag); double* data = reinterpret_cast<double*>(typed_array_.data()); std::size_t size = typed_array_.size()/bytes_per_elem; if (e != jsoncons::endian::native) { for (std::size_t i = 0; i < size; ++i) { data[i] = binary::byte_swap<double>(data[i]); } } more_ = visitor.typed_array(jsoncons::span<const double>(data,size), semantic_tag::none, *this, ec); break; } default: { read(bytes_buffer_,ec); if (ec) { more_ = false; return; } more_ = visitor.byte_string_value(bytes_buffer_, item_tag_, *this, ec); break; } } other_tags_[item_tag] = false; } else { read(bytes_buffer_,ec); if (ec) { return; } more_ = visitor.byte_string_value(bytes_buffer_, semantic_tag::none, *this, ec); } } void produce_begin_multi_dim(json_visitor2& visitor, semantic_tag tag, std::error_code& ec) { uint8_t b; if (source_.read(&b, 1) == 0) { ec = cbor_errc::unexpected_eof; more_ = false; return; } jsoncons::cbor::detail::cbor_major_type major_type = get_major_type(b); JSONCONS_ASSERT(major_type == jsoncons::cbor::detail::cbor_major_type::array); uint8_t info = get_additional_information_value(b); read_shape(info, ec); if (ec) { return; } state_stack_.emplace_back(parse_mode::multi_dim, 0); more_ = visitor.begin_multi_dim(shape_, tag, *this, ec); } void produce_end_multi_dim(json_visitor2& visitor, std::error_code& ec) { more_ = visitor.end_multi_dim(*this, ec); state_stack_.pop_back(); } void read_shape(uint8_t info, std::error_code& ec) { shape_.clear(); switch (info) { case jsoncons::cbor::detail::additional_info::indefinite_length: { while (true) { auto c = source_.peek(); if (c.eof) { ec = cbor_errc::unexpected_eof; more_ = false; return; } if (c.value == 0xff) { source_.ignore(1); } else { std::size_t dim = get_size(ec); if (!more_) { return; } shape_.push_back(dim); } } break; } default: { std::size_t size = get_size(ec); if (!more_) { return; } for (std::size_t i = 0; more_ && i < size; ++i) { std::size_t dim = get_size(ec); if (!more_) { return; } shape_.push_back(dim); } break; } } } }; }} #endif
34.22487
154
0.422155
yotann
8144d1d8d9d4cc9fe3abade76beadea112159d0a
923
cpp
C++
src/binary_tree.cpp
israni/CPP2
b917c85dbde217360ba3c469e6a4aa2c5e794716
[ "MIT" ]
null
null
null
src/binary_tree.cpp
israni/CPP2
b917c85dbde217360ba3c469e6a4aa2c5e794716
[ "MIT" ]
null
null
null
src/binary_tree.cpp
israni/CPP2
b917c85dbde217360ba3c469e6a4aa2c5e794716
[ "MIT" ]
null
null
null
#include<iostream> #include"node.h" int main() { node<int> mynode1(10); node<int> mynode2 (20); std::cout << mynode1.get_data() << "," << mynode2.get_data() << std::endl; if (mynode1==mynode2){ std::cout << "EQUAL" << std::endl; } else{ std::cout << "NOT EQUAL" << std::endl; } std::cout << "mynode1: " << mynode1 << std::endl; // The data attribute is deep copied as it is defined in the stack at compile time. node<int> mynode3(30); std::cout << "mynode3: " << mynode3 << std::endl; mynode3 = mynode1; std::cout << "mynode3: " << mynode3 << std::endl; mynode3.set_data(50); std::cout << "mynode3: " << mynode3 << std::endl; std::cout << "mynode1: " << mynode1 << std::endl; // Need to show that the pointers left, right would not be deep copied as they would be defined in the heap. std::cout << "Done" << std::endl; }
28.84375
112
0.566631
israni
8144ed50732ba0b82562bd70868885087d717e49
3,719
cpp
C++
src/Output/Output_Flux.cpp
zhulianhua/Daino
db88f5738aba76fa8a28d7672450e0c5c832b3de
[ "MIT" ]
3
2019-04-13T02:08:01.000Z
2020-11-17T12:45:37.000Z
src/Output/Output_Flux.cpp
zhulianhua/Daino
db88f5738aba76fa8a28d7672450e0c5c832b3de
[ "MIT" ]
null
null
null
src/Output/Output_Flux.cpp
zhulianhua/Daino
db88f5738aba76fa8a28d7672450e0c5c832b3de
[ "MIT" ]
2
2019-11-12T02:00:20.000Z
2019-12-09T14:52:31.000Z
#include "DAINO.h" //------------------------------------------------------------------------------------------------------- // Function : Output_Flux // Description : Output the flux of a single patch // // Parameter : lv : Targeted refinement level // PID : Targeted patch ID // Sib : Targeted sibling direction of the flux : ( 0,1,2,3,4,5 ) <--> ( -x,+x,-y,+y,-z,+z ) // comment : String to attach to the end of the file name //------------------------------------------------------------------------------------------------------- void Output_Flux( const int lv, const int PID, const int Sib, const char *comment ) { // check if ( lv < 0 || lv >= NLEVEL ) Aux_Error( ERROR_INFO, "incorrect parameter %s = %d !!\n", "lv", lv ); if ( PID < 0 || PID >= MAX_PATCH ) Aux_Error( ERROR_INFO, "incorrect parameter %s = %d (MAX_PATCH = %d) !!\n", "PID", PID, MAX_PATCH ); if ( !patch->WithFlux ) Aux_Message( stderr, "WARNING : invoking %s is useless since no flux is required !!\n", __FUNCTION__ ); if ( patch->ptr[0][lv][PID] == NULL ) { Aux_Message( stderr, "WARNING : level = %d, PID = %d does NOT exist !!\n", lv, PID ); return; } patch_t *Relation = patch->ptr[0][lv][PID]; char FileName[100]; sprintf( FileName, "Flux_r%d_lv%d_p%d%c%c", DAINO_RANK, lv, PID, 45-2*(Sib%2), 120+Sib/2 ); if ( comment != NULL ) { strcat( FileName, "_" ); strcat( FileName, comment ); } FILE *File_Check = fopen( FileName, "r" ); if ( File_Check != NULL ) { Aux_Message( stderr, "WARNING : the file \"%s\" already exists and will be overwritten !!\n", FileName ); fclose( File_Check ); } real (*FluxPtr)[PATCH_SIZE][PATCH_SIZE] = patch->ptr[0][lv][PID]->flux[Sib]; char label[2] = { '?', '?' }; switch ( Sib ) { case 0: case 1: label[0] = 'y'; label[1] = 'z'; break; case 2: case 3: label[0] = 'z'; label[1] = 'x'; break; case 4: case 5: label[0] = 'x'; label[1] = 'y'; break; default: Aux_Error( ERROR_INFO, "incorrect parameter %s = %d !!\n", "Sib", Sib ); } // output header FILE *File = fopen( FileName, "w" ); fprintf( File, "Rank %d Level %d Patch %d Local ID %d Time %13.7e Counter %u\n", DAINO_RANK, lv, PID, PID%8, Time[lv], AdvanceCounter[lv] ); fprintf( File, "Father %d Son %d Corner (%4d,%4d,%4d)\n\n", Relation->father, Relation->son, Relation->corner[0], Relation->corner[1], Relation->corner[2] ); fprintf( File, "Flux at %c%c surface\n\n", 45-2*(Sib%2), 120+Sib/2 ); // output flux if ( FluxPtr != NULL ) { # if ( MODEL == HYDRO ) fprintf( File, "( %c, %c )%16s%16s%16s%16s%16s\n", label[0], label[1], "Density Flux", "Px Flux", "Py Flux", "Pz Flux", "Energy Flux" ); # elif ( MODEL == MHD ) # warning : WAIT MHD !!! # elif ( MODEL != ELBDM ) # warning : WARNING : DO YOU WANT TO ADD the FILE HEADER HERE FOR THE NEW MODEL ?? # endif // MODEL for (int m=0; m<PATCH_SIZE; m++) for (int n=0; n<PATCH_SIZE; n++) { fprintf( File, "( %d, %d )", n, m ); for (int v=0; v<NCOMP; v++) fprintf( File, " %14.7e", FluxPtr[v][m][n] ); fprintf( File, "\n" ); } } // if ( FluxPtr != NULL ) else { fprintf( File, "\nNULL\n" ); Aux_Message( stderr, "WARNING : lv %d, PID %d, Sib %d, the requested flux does NOT exist !!\n", lv, PID, Sib ); } fclose( File ); } // FUNCTION : Output_Flux
33.809091
112
0.491799
zhulianhua
81465f3944cfea695e3e5bf03dd2cc3a7a109860
4,953
hpp
C++
include/sobfu/solver.hpp
LuyaooChen/sobfu
688e06a2e81fdf30bd2d019516dc025a951bcbc2
[ "BSD-3-Clause" ]
142
2019-01-10T14:38:03.000Z
2022-03-18T08:45:30.000Z
include/sobfu/solver.hpp
GucciPrada/sobfu
c83646582a146a3f4b8d8ad62de31ec60f8004d6
[ "BSD-3-Clause" ]
17
2019-01-18T05:15:33.000Z
2021-12-22T15:00:44.000Z
include/sobfu/solver.hpp
GucciPrada/sobfu
c83646582a146a3f4b8d8ad62de31ec60f8004d6
[ "BSD-3-Clause" ]
27
2019-02-16T10:11:49.000Z
2021-11-02T19:51:28.000Z
#pragma once /* kinfu incldues */ #include <kfusion/cuda/tsdf_volume.hpp> #include <kfusion/safe_call.hpp> /* sobfu includes */ #include <sobfu/reductor.hpp> #include <sobfu/scalar_fields.hpp> #include <sobfu/vector_fields.hpp> /* * SOLVER PARAMETERS */ struct SolverParams { int verbosity, max_iter, s; float max_update_norm, lambda, alpha, w_reg; }; /* * SDF'S USED IN THE SOLVER */ struct SDFs { SDFs(kfusion::device::TsdfVolume &phi_global_, kfusion::device::TsdfVolume &phi_global_psi_inv_, kfusion::device::TsdfVolume &phi_n_, kfusion::device::TsdfVolume &phi_n_psi_) : phi_global(phi_global_), phi_global_psi_inv(phi_global_psi_inv_), phi_n(phi_n_), phi_n_psi(phi_n_psi_) {} kfusion::device::TsdfVolume phi_global, phi_global_psi_inv, phi_n, phi_n_psi; }; /* * SPATIAL DIFFERENTIATORS */ struct Differentiators { Differentiators(sobfu::device::TsdfDifferentiator &tsdf_diff_, sobfu::device::Differentiator &diff_, sobfu::device::Differentiator &diff_inv_, sobfu::device::SecondOrderDifferentiator &second_order_diff_) : tsdf_diff(tsdf_diff_), diff(diff_), diff_inv(diff_inv_), second_order_diff(second_order_diff_) {} sobfu::device::TsdfDifferentiator tsdf_diff; sobfu::device::Differentiator diff, diff_inv; sobfu::device::SecondOrderDifferentiator second_order_diff; }; namespace sobfu { namespace cuda { /* * SOLVER */ class Solver { public: /* constructor */ Solver(Params &params); /* destructor */ ~Solver(); void estimate_psi(const cv::Ptr<kfusion::cuda::TsdfVolume> phi_global, cv::Ptr<kfusion::cuda::TsdfVolume> phi_global_psi_inv, const cv::Ptr<kfusion::cuda::TsdfVolume> phi_n, cv::Ptr<kfusion::cuda::TsdfVolume> phi_n_psi, std::shared_ptr<sobfu::cuda::DeformationField> psi, std::shared_ptr<sobfu::cuda::DeformationField> psi_inv); private: /* volume params */ int3 dims; float3 voxel_sizes; int no_voxels; float trunc_dist, eta, max_weight; /* solver params */ SolverParams solver_params; /* gradients */ sobfu::cuda::SpatialGradients *spatial_grads; sobfu::device::SpatialGradients *spatial_grads_device; sobfu::device::TsdfGradient *nabla_phi_n, *nabla_phi_n_o_psi; sobfu::device::Jacobian *J, *J_inv; sobfu::device::Laplacian *L, *L_o_psi_inv; sobfu::device::PotentialGradient *nabla_U, *nabla_U_S; /* used to calculate value of the energy functional */ sobfu::device::Reductor *r; /* sobolev filter */ float *h_S_i, *d_S_i; }; /* get 3d sobolev filter */ static void get_3d_sobolev_filter(SolverParams &params, float *h_S_i); /* calculate 1d filters from a separable 3d filter */ static void decompose_sobolev_filter(SolverParams &params, float *h_S_i); } // namespace cuda namespace device { /* potential gradient */ __global__ void calculate_potential_gradient_kernel(float2 *phi_n_psi, float2 *phi_global, float4 *nabla_phi_n_o_psi, float4 *L, float4 *nabla_U, float w_reg, int dim_x, int dim_y, int dim_z); void calculate_potential_gradient(kfusion::device::TsdfVolume &phi_n_psi, kfusion::device::TsdfVolume &phi_global, sobfu::device::TsdfGradient &nabla_phi_n_o_psi, sobfu::device::Laplacian &L, sobfu::device::PotentialGradient &nabla_U, float w_reg); /* estimate psi */ void estimate_psi(SDFs &sdfs, sobfu::device::DeformationField &psi, sobfu::device::DeformationField &psi_inv, sobfu::device::SpatialGradients *spatial_grads, Differentiators &diffs, float *d_S_i, sobfu::device::Reductor *r, SolverParams &params); /* DEFORMATION FIELD UPDATES */ __global__ void update_psi_kernel(float4 *psi, float4 *nabla_U_S, float4 *updates, float alpha, int dim_x, int dim_y, int dim_z); void update_psi(sobfu::device::DeformationField &psi, sobfu::device::PotentialGradient &nabla_U_S, float4 *updates, float alpha); /* * CONVOLUTIONS */ void set_convolution_kernel(float *d_kernel); __global__ void convolution_rows_kernel(float4 *d_dst, float4 *d_src, int image_w, int image_h, int image_d); __global__ void convolution_columns_kernel(float4 *d_dst, float4 *d_src, int image_w, int image_h, int image_d); __global__ void convolution_depth_kernel(float4 *d_dst, float4 *d_src, int image_w, int image_h, int image_d); void convolution_rows(float4 *d_dst, float4 *updates, int image_w, int image_h, int image_d); void convolution_columns(float4 *d_dst, float4 *updates, int image_w, int image_h, int image_d); void convolution_depth(float4 *d_dst, float4 *updates, int image_w, int image_h, int image_d); } // namespace device } // namespace sobfu
35.378571
117
0.689885
LuyaooChen
814731bcac3d648cf8ea63e921eba768b679e9ce
1,301
hpp
C++
include/panoc/entities.hpp
Zilleplus/PANOCPP
f228afec92e0fdff557f85cb27b0b368fea585ae
[ "MIT" ]
3
2018-09-12T06:12:48.000Z
2022-01-31T12:47:47.000Z
include/panoc/entities.hpp
Zilleplus/PANOCPP
f228afec92e0fdff557f85cb27b0b368fea585ae
[ "MIT" ]
21
2020-05-21T17:26:13.000Z
2021-12-19T19:49:09.000Z
include/panoc/entities.hpp
Zilleplus/PANOCPP
f228afec92e0fdff557f85cb27b0b368fea585ae
[ "MIT" ]
1
2018-09-09T07:43:49.000Z
2018-09-09T07:43:49.000Z
#pragma once #include<utility> namespace pnc { template < typename TVectorRef, typename TVector = std::remove_reference_t<TVectorRef>, typename TConstant = typename TVector::data_type, typename TSize = typename TVector::size_type > struct Location { Location( TVectorRef&& location, TVectorRef&& gradient, TConstant cost, TConstant gamma) : location(std::forward<TVectorRef>(location)), gradient(std::forward<TVectorRef>(gradient)), gamma(gamma), cost(cost) { } Location(TSize dimension) : location(dimension), gradient(dimension), gamma(0), cost(0) { } template<typename TVec> Location(Location<TVec>&& other) : location(std::move(other.location)), gradient(std::move(other.gradient)), cost(cost), gamma(gamma){} template<typename TVec> Location(const Location<TVec>& other) : location(other.location), gradient(other.gradient), gamma(other.gamma), cost(other.cost) { } //template<typename TVec> //Location<TVec>& operator=(const Location<TVec>& other) //{ // location = other.location; // gradient = other.gradient; // gamma = other.gamma; // cost = other.cost; // return this; //} TVectorRef location; TVectorRef gradient; TConstant gamma; TConstant cost; }; }
19.132353
58
0.670254
Zilleplus
8147c0ad2a81e17f7cdda544e1bb7bdc1be524cd
3,431
cpp
C++
tests/services_unit/check_adaptation.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
tests/services_unit/check_adaptation.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
tests/services_unit/check_adaptation.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#include "check_adaptation.hpp" double stan::test::unit::stod(const std::string& val) { char tmp[val.length()]; strcpy(tmp, val.c_str()); return atof(tmp); } void stan::test::unit::check_adaptation( const size_t& num_params, const std::vector<double>& param_vals, stan::test::unit::instrumented_writer& report, const double& err_margin) { std::vector<std::string> param_strings = report.string_values(); size_t offset = 0; for (size_t i = 0; i < param_strings.size(); i++) { offset++; if (param_strings[i].find("lements of inverse mass matrix:") != std::string::npos) { break; } } std::vector<std::string> strs; boost::split(strs, param_strings[offset], boost::is_any_of(", "), boost::token_compress_on); EXPECT_EQ(num_params, strs.size()); for (size_t i = 0; i < num_params; i++) { ASSERT_NEAR(param_vals[i], test::unit::stod(strs[i]), err_margin); } } void stan::test::unit::check_adaptation( const size_t& num_rows, const size_t& num_cols, const std::vector<double>& param_vals, stan::test::unit::instrumented_writer& report, const double& err_margin) { std::vector<std::string> param_strings = report.string_values(); size_t offset = 0; for (size_t i = 0; i < param_strings.size(); i++) { offset++; if (param_strings[i].find("lements of inverse mass matrix:") != std::string::npos) { break; } } for (size_t i = 0, ij = 0; i < num_rows; i++) { std::vector<std::string> strs; boost::split(strs, param_strings[offset + i], boost::is_any_of(", "), boost::token_compress_on); EXPECT_EQ(num_cols, strs.size()); for (size_t j = 0; j < num_cols; j++, ij++) { ASSERT_NEAR(param_vals[ij], test::unit::stod(strs[j]), err_margin); } } } void stan::test::unit::check_different( const size_t& num_params, const std::vector<double>& param_vals, stan::test::unit::instrumented_writer& report, const double& margin) { std::vector<std::string> param_strings = report.string_values(); size_t offset = 0; for (size_t i = 0; i < param_strings.size(); i++) { offset++; if (param_strings[i].find("lements of inverse mass matrix:") != std::string::npos) { break; } } std::vector<std::string> strs; boost::split(strs, param_strings[offset], boost::is_any_of(", "), boost::token_compress_on); EXPECT_EQ(num_params, strs.size()); for (size_t i = 0; i < num_params; i++) { ASSERT_GT(fabs(param_vals[i] - test::unit::stod(strs[i])), margin); } } void stan::test::unit::check_different( const size_t& num_rows, const size_t& num_cols, const std::vector<double>& param_vals, stan::test::unit::instrumented_writer& report, const double& margin) { std::vector<std::string> param_strings = report.string_values(); size_t offset = 0; for (size_t i = 0; i < param_strings.size(); i++) { offset++; if (param_strings[i].find("lements of inverse mass matrix:") != std::string::npos) { break; } } for (size_t i = 0, ij = 0; i < num_rows; i++) { std::vector<std::string> strs; boost::split(strs, param_strings[offset + i], boost::is_any_of(", "), boost::token_compress_on); EXPECT_EQ(num_cols, strs.size()); for (size_t j = 0; j < num_cols; j++, ij++) { ASSERT_GT(fabs(param_vals[ij] - test::unit::stod(strs[j])), margin); } } }
35.010204
78
0.628097
alashworth
814899dbbbf43143638a90b8eec6cbfd933041e1
323
inl
C++
args/core/math/glm/gtx/normal.inl
Developer-The-Great/Args-Engine
1eee1eaadc5e203778896c803e8fa4e9f52b4f7b
[ "MIT" ]
null
null
null
args/core/math/glm/gtx/normal.inl
Developer-The-Great/Args-Engine
1eee1eaadc5e203778896c803e8fa4e9f52b4f7b
[ "MIT" ]
null
null
null
args/core/math/glm/gtx/normal.inl
Developer-The-Great/Args-Engine
1eee1eaadc5e203778896c803e8fa4e9f52b4f7b
[ "MIT" ]
null
null
null
/// @ref gtx_normal namespace args::core::math::detail::glm { template<typename T, qualifier Q> GLM_FUNC_QUALIFIER vec<3, T, Q> triangleNormal ( vec<3, T, Q> const& p1, vec<3, T, Q> const& p2, vec<3, T, Q> const& p3 ) { return normalize(cross(p1 - p2, p1 - p3)); } }//namespace args::core::math::detail::glm
20.1875
47
0.634675
Developer-The-Great
8148cbda6dfe1de16596d2b90a3b0b12f731efa0
704
cpp
C++
source/testing/tests/stoichiometric.cpp
0u812/roadrunner
f464c2649e388fa1f5a015592b0b29b65cc84b4b
[ "Apache-2.0" ]
null
null
null
source/testing/tests/stoichiometric.cpp
0u812/roadrunner
f464c2649e388fa1f5a015592b0b29b65cc84b4b
[ "Apache-2.0" ]
null
null
null
source/testing/tests/stoichiometric.cpp
0u812/roadrunner
f464c2649e388fa1f5a015592b0b29b65cc84b4b
[ "Apache-2.0" ]
null
null
null
#include "unit_test/UnitTest++.h" #include "rrLogger.h" #include "rrRoadRunner.h" #include "rrException.h" #include "rrStringUtils.h" using namespace UnitTest; using namespace rr; extern RoadRunner* gRR; extern string gSBMLModelsPath; extern string gCompiler; extern string gSupportCodeFolder; extern string gTempFolder; extern vector<string> gModels; SUITE(Stoichiometric) { TEST(AllocateRR) { if(!gRR) { gRR = new RoadRunner(gCompiler, gTempFolder, gSupportCodeFolder); } CHECK(gRR!=NULL); } TEST(MODEL_FILES) //Test that model files for the tests are present { } }
21.333333
77
0.627841
0u812
814acf2c8156d42d7e1bd760d51c914f75c62762
617
hpp
C++
unit-tests/test-files/template/full-base.hpp
Mirinth/Plexiglass
d5e1e83a4863ae764c951d79a574ab5f4970793e
[ "Unlicense" ]
null
null
null
unit-tests/test-files/template/full-base.hpp
Mirinth/Plexiglass
d5e1e83a4863ae764c951d79a574ab5f4970793e
[ "Unlicense" ]
39
2021-10-10T20:50:02.000Z
2021-11-29T01:42:09.000Z
unit-tests/test-files/template/full-base.hpp
Mirinth/Plexiglass
d5e1e83a4863ae764c951d79a574ab5f4970793e
[ "Unlicense" ]
null
null
null
#pragma once #include <filesystem> #include <string> #include <string_view> enum class LexerState; enum class TokenType { __eof__, __jam__, __nothing__, secondToken, }; std::string ToString(TokenType type, const std::string& text); class full { public: full(const std::filesystem::path& path); size_t PeekLine() const; TokenType PeekToken() const; std::string PeekText() const; void Shift(); private: std::string m_reference; std::string_view m_view; LexerState m_state; size_t m_line; TokenType m_type; std::string m_text; void ShiftHelper(); };
16.675676
62
0.677472
Mirinth
814bae8a4c2db99b0d6c3246c0537fae451df490
2,787
cc
C++
cluster/spanning_tree_main.cc
MoniFarsang/vowpal_wabbit
e37d4505a4830c73306180adadb5b3abbb5c0fc1
[ "BSD-3-Clause" ]
null
null
null
cluster/spanning_tree_main.cc
MoniFarsang/vowpal_wabbit
e37d4505a4830c73306180adadb5b3abbb5c0fc1
[ "BSD-3-Clause" ]
null
null
null
cluster/spanning_tree_main.cc
MoniFarsang/vowpal_wabbit
e37d4505a4830c73306180adadb5b3abbb5c0fc1
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2011 Yahoo! Inc. All rights reserved. The copyrights embodied in the content of this file are licensed under the BSD (revised) open source license This creates a binary tree topology over a set of n nodes that connect. */ #include "config/cli_help_formatter.h" #include "config/option_builder.h" #include "config/options_cli.h" #include "config/option_group_definition.h" #include "spanning_tree.h" #include "vw_exception.h" #ifdef _WIN32 int daemon(int a, int b) { return 0; } int getpid() { return (int)::GetCurrentProcessId(); } #endif #include <iostream> #include <fstream> using namespace VW; void usage(const VW::config::options_cli& desc) { std::cout << "usage: spanning_tree [--port,-p number] [--nondaemon] [--help,-h] [pid_file]" << std::endl; VW::config::cli_help_formatter help_formatter; std::cout << help_formatter.format_help(desc.get_all_option_group_definitions()) << std::endl; } int main(int argc, char* argv[]) { int port = 26543; bool nondaemon = false; bool help = false; VW::config::options_cli opts(std::vector<std::string>(argv + 1, argv + argc)); VW::config::option_group_definition desc("Spanning Tree"); desc.add(VW::config::make_option("nondaemon", nondaemon).help("Run spanning tree in foreground")) .add(VW::config::make_option("help", help).short_name("h").help("Print help message")) .add(VW::config::make_option("port", port) .short_name("p") .default_value(26543) .help("Port number for spanning tree to listen on")); opts.add_and_parse(desc); // Return value is ignored as option reachability is not relevant here. auto warnings = opts.check_unregistered(); _UNUSED(warnings); auto positional = opts.get_positional_tokens(); std::string pid_file_name; if (!positional.empty()) { pid_file_name = positional.front(); if (positional.size() > 1) { std::cerr << "Too many positional arguments" << std::endl; usage(opts); return 1; } } if (help) { usage(opts); return 0; } try { if (!nondaemon) { VW_WARNING_STATE_PUSH VW_WARNING_DISABLE_DEPRECATED_USAGE if (daemon(1, 1)) { THROWERRNO("daemon: "); } VW_WARNING_STATE_POP } SpanningTree spanningTree(port); if (!pid_file_name.empty()) { std::ofstream pid_file; pid_file.open(pid_file_name); if (!pid_file.is_open()) { std::cerr << "error writing pid file" << std::endl; return 1; } pid_file << getpid() << std::endl; pid_file.close(); } spanningTree.Run(); } catch (VW::vw_exception& e) { std::cerr << "spanning tree (" << e.Filename() << ":" << e.LineNumber() << "): " << e.what() << std::endl; } }
26.542857
110
0.645856
MoniFarsang
814c50fbccf2abaa393ce8b25c38c0c925145572
1,735
cpp
C++
src/util/runnable_time_source.cpp
MelbourneSpaceProgram/msp_flight_software_public
de290a2e7181ac43af1232b2ffbca2db8ec4ecd2
[ "MIT" ]
10
2018-04-28T04:44:56.000Z
2022-02-06T21:12:13.000Z
src/util/runnable_time_source.cpp
MelbourneSpaceProgram/msp_flight_software_public
de290a2e7181ac43af1232b2ffbca2db8ec4ecd2
[ "MIT" ]
null
null
null
src/util/runnable_time_source.cpp
MelbourneSpaceProgram/msp_flight_software_public
de290a2e7181ac43af1232b2ffbca2db8ec4ecd2
[ "MIT" ]
3
2019-02-16T03:22:26.000Z
2022-02-03T14:54:22.000Z
#include <src/board/board.h> #include <src/board/i2c/i2c.h> #include <src/board/i2c/multiplexers/i2c_multiplexer.h> #include <src/config/satellite.h> #include <src/sensors/i2c_sensors/rtc.h> #include <src/util/msp_exception.h> #include <src/util/runnable_time_source.h> #include <src/util/satellite_time_source.h> #include <src/util/tirtos_utils.h> #include <xdc/runtime/Log.h> fnptr RunnableTimeSource::GetRunnablePointer() { return &RunnableTimeSource::UpdateSatelliteTime; } void RunnableTimeSource::UpdateSatelliteTime() { I2c bus(I2C_BUS_A); I2cMultiplexer multiplexer(&bus, kMuxAddress); Rtc rtc(&bus, kRtcAddress, &multiplexer, I2cMultiplexer::kMuxChannel0); while (1) { try { RTime time; try { time = rtc.GetTime(); } catch (MspException& e) { MspException::LogException(e, kUpdateSatelliteTimeCatch); Log_error0("Unable to retrieve time from RTC"); TirtosUtils::SleepMilli(kTimeUpdatePeriodMs); continue; } if (rtc.ValidTime(time)) { SatelliteTimeSource::SetTime(time); } TirtosUtils::SleepMilli(kTimeUpdatePeriodMs); } catch (MspException& e) { // TODO(crozone): Temp ugly hack, should be logging top level // exception here but for some reason the previous catch block is // not catching the exception properly so instead it is caught here MspException::LogException(e, kUpdateSatelliteTimeCatch); Log_error0("Unable to retrieve time from RTC"); TirtosUtils::SleepMilli(kTimeUpdatePeriodMs); continue; } } }
36.145833
79
0.640346
MelbourneSpaceProgram
814ce30a05e959d89df4fba2a0c36c417c9df7de
15,463
cpp
C++
mitsuba/src/integrators/erpt/erpt_proc.cpp
anadodik/sdmm-mitsuba
6103cb8ea36ec4ab0cfb5fcc792c7f1565637d9a
[ "MIT" ]
6
2020-07-07T09:46:21.000Z
2022-03-08T14:16:27.000Z
mitsuba/src/integrators/erpt/erpt_proc.cpp
anadodik/sdmm-mitsuba
6103cb8ea36ec4ab0cfb5fcc792c7f1565637d9a
[ "MIT" ]
null
null
null
mitsuba/src/integrators/erpt/erpt_proc.cpp
anadodik/sdmm-mitsuba
6103cb8ea36ec4ab0cfb5fcc792c7f1565637d9a
[ "MIT" ]
null
null
null
/* This file is part of Mitsuba, a physically based rendering system. Copyright (c) 2007-2014 by Wenzel Jakob and others. Mitsuba is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 3 as published by the Free Software Foundation. Mitsuba is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <mitsuba/bidir/mut_bidir.h> #include <mitsuba/bidir/mut_lens.h> #include <mitsuba/bidir/mut_caustic.h> #include <mitsuba/bidir/mut_mchain.h> #include <mitsuba/bidir/mut_manifold.h> #include <mitsuba/bidir/pathsampler.h> #include <mitsuba/bidir/util.h> #include <mitsuba/core/sfcurve.h> #include <boost/bind.hpp> #include "erpt_proc.h" //#define MTS_BD_DEBUG_HEAVY MTS_NAMESPACE_BEGIN static StatsCounter statsAccepted("Energy redistribution path tracing", "Accepted mutations", EPercentage); static StatsCounter statsChainsPerPixel("Energy redistribution path tracing", "Chains started per pixel", EAverage); /* ==================================================================== */ /* Worker result implementation */ /* ==================================================================== */ class ERPTWorkResult : public ImageBlock { public: Point2i origOffset; Vector2i origSize; ERPTWorkResult(const Vector2i &size, const ReconstructionFilter *filter) : ImageBlock(Bitmap::ESpectrum, size, filter) { } void load(Stream *stream) { ImageBlock::load(stream); origOffset = Point2i(stream); origSize = Vector2i(stream); } void save(Stream *stream) const { ImageBlock::save(stream); origOffset.serialize(stream); origSize.serialize(stream); } }; /* ==================================================================== */ /* Worker implementation */ /* ==================================================================== */ class ERPTRenderer : public WorkProcessor { public: ERPTRenderer(const ERPTConfiguration &conf) : m_config(conf) { } ERPTRenderer(Stream *stream, InstanceManager *manager) : WorkProcessor(stream, manager) { m_config = ERPTConfiguration(stream); } void serialize(Stream *stream, InstanceManager *manager) const { m_config.serialize(stream); } ref<WorkUnit> createWorkUnit() const { return new RectangularWorkUnit(); } ref<WorkResult> createWorkResult() const { return new ERPTWorkResult( m_sensor->getFilm()->getCropSize(), m_sensor->getFilm()->getReconstructionFilter()); } void prepare() { Scene *scene = static_cast<Scene *>(getResource("scene")); m_scene = new Scene(scene); m_sampler = static_cast<Sampler *>(getResource("sampler")); m_indepSampler = static_cast<Sampler *>(getResource("indepSampler")); m_sensor = static_cast<Sensor *>(getResource("sensor")); m_scene->removeSensor(scene->getSensor()); m_scene->addSensor(m_sensor); m_scene->setSensor(m_sensor); m_scene->setSampler(m_sampler); m_scene->wakeup(NULL, m_resources); m_scene->initializeBidirectional(); m_pathSampler = new PathSampler(PathSampler::EBidirectional, m_scene, m_sampler, m_sampler, m_sampler, m_config.maxDepth, 10, m_config.separateDirect, true, true); m_pool = &m_pathSampler->getMemoryPool(); /* Jump sizes recommended by Eric Veach */ Float minJump = 0.1f, coveredArea = 0.05f; /* Register all available mutators */ if (m_config.bidirectionalMutation) m_mutators.push_back(new BidirectionalMutator(m_scene, m_indepSampler, *m_pool, 3, m_config.maxDepth == -1 ? INT_MAX : m_config.maxDepth + 2)); if (m_config.lensPerturbation) m_mutators.push_back(new LensPerturbation(m_scene, m_indepSampler, *m_pool, minJump, coveredArea)); if (m_config.multiChainPerturbation) m_mutators.push_back(new MultiChainPerturbation(m_scene, m_indepSampler, *m_pool, minJump, coveredArea)); if (m_config.causticPerturbation) m_mutators.push_back(new CausticPerturbation(m_scene, m_indepSampler, *m_pool, minJump, coveredArea)); if (m_config.manifoldPerturbation) m_mutators.push_back(new ManifoldPerturbation(m_scene, m_indepSampler, *m_pool, m_config.probFactor, true, true, m_config.avgAngleChangeSurface, m_config.avgAngleChangeMedium)); if (m_mutators.size() == 0) Log(EError, "There must be at least one mutator!"); } void pathCallback(int s, int t, Float weight, Path &path, const bool *stop) { if (std::isnan(weight) || std::isinf(weight) || weight < 0) Log(EWarn, "Invalid path weight: %f, ignoring path!", weight); #if 0 /* Don't run ERPT on paths that start with two diffuse vertices. It's usually safe to assume that these are handled well enough by BDPT */ int k = path.length(); if (path.vertex(k-2)->isDiffuseInteraction() && path.vertex(k-3)->isDiffuseInteraction()) { Spectrum value = path.getRelativeWeight() * weight / m_sampler->getSampleCount(); m_result->put(path.getSamplePosition(), &value[0]); return; } #endif Float meanChains = m_config.numChains * weight / (m_config.luminance * m_sampler->getSampleCount()); /* Optional: do not launch too many chains if this is desired by the user */ if (m_config.maxChains > 0 && meanChains > m_config.maxChains) meanChains = std::min(meanChains, (Float) m_config.maxChains); /* Decide the actual number of chains that will be launched, as well as their deposition energy */ int numChains = (int) std::floor(m_indepSampler->next1D() + meanChains); if (numChains == 0) return; Float depositionEnergy = weight / (m_sampler->getSampleCount() * meanChains * m_config.chainLength); DiscreteDistribution suitabilities(m_mutators.size()); std::ostringstream oss; Spectrum relWeight(0.0f); Float accumulatedWeight = 0; MutationRecord muRec, currentMuRec(Mutator::EMutationTypeCount, 0, 0, 0, Spectrum(0.f)); Path *current = new Path(), *proposed = new Path(); size_t mutations = 0; #if defined(MTS_BD_DEBUG_HEAVY) if (!path.verify(m_scene, EImportance, oss)) Log(EError, "Started ERPT with an invalid path: %s", oss.str().c_str()); #endif for (int chain=0; chain<numChains && !*stop; ++chain) { relWeight = path.getRelativeWeight(); path.clone(*current, *m_pool); accumulatedWeight = 0; ++statsChainsPerPixel; for (size_t it=0; it<m_config.chainLength; ++it) { /* Query all mutators for their suitability */ suitabilities.clear(); for (size_t j=0; j<m_mutators.size(); ++j) suitabilities.append(m_mutators[j]->suitability(*current)); /* Pick a mutator according to the suitabilities */ int mutatorIdx = -1; bool success = false; Mutator *mutator = NULL; if (suitabilities.normalize() == 0) { /* No mutator can handle this path -- give up */ accumulatedWeight += m_config.chainLength - it; break; } mutatorIdx = (int) suitabilities.sample(m_indepSampler->next1D()); mutator = m_mutators[mutatorIdx].get(); /* Sample a mutated path */ success = mutator->sampleMutation(*current, *proposed, muRec, currentMuRec); statsAccepted.incrementBase(1); if (success) { Float Qxy = mutator->Q(*current, *proposed, muRec) * suitabilities[mutatorIdx]; suitabilities.clear(); for (size_t j=0; j<m_mutators.size(); ++j) suitabilities.append(m_mutators[j]->suitability(*proposed)); suitabilities.normalize(); Float Qyx = mutator->Q(*proposed, *current, muRec.reverse()) * suitabilities[mutatorIdx]; Float a = std::min((Float) 1, Qyx / Qxy); #if defined(MTS_BD_DEBUG_HEAVY) if (!proposed->verify(m_scene, EImportance, oss)) { Log(EWarn, "%s proposed as %s, Qxy=%f, Qyx=%f", oss.str().c_str(), muRec.toString().c_str(), Qxy, Qyx); Log(EWarn, "Original path: %s", current->toString().c_str()); proposed->release(muRec.l, muRec.l + muRec.ka + 1, *m_pool); oss.str(""); continue; } #endif if (Qxy == 0) { // be tolerant of this (can occasionally happen due to floating point inaccuracies) a = 0; } else if (Qxy < 0 || Qyx < 0 || std::isnan(Qxy) || std::isnan(Qyx)) { #if defined(MTS_BD_DEBUG) Log(EDebug, "Source path: %s", current->toString().c_str()); Log(EDebug, "Proposal path: %s", proposed->toString().c_str()); Log(EWarn, "Internal error while computing acceptance probabilities: " "Qxy=%f, Qyx=%f, muRec=%s", Qxy, Qyx, muRec.toString().c_str()); #endif a = 0; } accumulatedWeight += 1-a; /* Accept with probability 'a' */ if (a == 1 || m_indepSampler->next1D() < a) { Spectrum value = relWeight * (accumulatedWeight * depositionEnergy); m_result->put(current->getSamplePosition(), &value[0]); /* The mutation was accepted */ current->release(muRec.l, muRec.m+1, *m_pool); std::swap(current, proposed); relWeight = current->getRelativeWeight(); mutator->accept(muRec); currentMuRec = muRec; accumulatedWeight = a; ++statsAccepted; ++mutations; } else { if (a > 0) { Spectrum value = proposed->getRelativeWeight() * (a * depositionEnergy); m_result->put(proposed->getSamplePosition(), &value[0]); } /* The mutation was rejected */ proposed->release(muRec.l, muRec.l + muRec.ka + 1, *m_pool); } } else { accumulatedWeight += 1; } } if (accumulatedWeight > 0) { Spectrum value = relWeight * (accumulatedWeight * depositionEnergy); m_result->put(current->getSamplePosition(), &value[0]); } current->release(*m_pool); } /*if (mutations == 0) { cout << "Path was never mutated: " << path.summarize() << endl; cout << path.toString() << endl; }*/ delete current; delete proposed; } void process(const WorkUnit *workUnit, WorkResult *workResult, const bool &stop) { const RectangularWorkUnit *rect = static_cast<const RectangularWorkUnit *>(workUnit); m_result = static_cast<ERPTWorkResult *>(workResult); m_result->origOffset = rect->getOffset(); m_result->origSize = rect->getSize(); m_hilbertCurve.initialize(TVector2<uint8_t>(rect->getSize())); m_result->clear(); boost::function<void (int, int, Float, Path &)> callback = boost::bind(&ERPTRenderer::pathCallback, this, _1, _2, _3, _4, &stop); for (size_t i=0; i<m_hilbertCurve.getPointCount(); ++i) { if (stop) break; statsChainsPerPixel.incrementBase(); Point2i offset = Point2i(m_hilbertCurve[i]) + Vector2i(rect->getOffset()); m_sampler->generate(offset); for (size_t j = 0; j<m_sampler->getSampleCount(); j++) { m_pathSampler->samplePaths(offset, callback); m_sampler->advance(); } } if (!m_pool->unused()) Log(EError, "Internal error: detected a memory pool leak!"); m_result = NULL; } ref<WorkProcessor> clone() const { return new ERPTRenderer(m_config); } MTS_DECLARE_CLASS() private: ERPTConfiguration m_config; ref<Sensor> m_sensor; ref<Scene> m_scene; ref<Sampler> m_sampler, m_indepSampler; ref<PathSampler> m_pathSampler; ref_vector<Mutator> m_mutators; HilbertCurve2D<uint8_t> m_hilbertCurve; ERPTWorkResult *m_result; MemoryPool *m_pool; }; /* ==================================================================== */ /* Parallel process */ /* ==================================================================== */ ERPTProcess::ERPTProcess(const RenderJob *job, RenderQueue *queue, const ERPTConfiguration &conf, const Bitmap *directImage) : BlockedRenderProcess(job, queue, conf.blockSize), m_job(job), m_config(conf) { m_directImage = directImage; } ref<WorkProcessor> ERPTProcess::createWorkProcessor() const { return new ERPTRenderer(m_config); } void ERPTProcess::develop() { LockGuard lock(m_resultMutex); m_film->setBitmap(m_accum->getBitmap()); if (m_directImage) m_film->addBitmap(m_directImage); m_queue->signalRefresh(m_job); } void ERPTProcess::processResult(const WorkResult *wr, bool cancelled) { const ERPTWorkResult *result = static_cast<const ERPTWorkResult *>(wr); UniqueLock lock(m_resultMutex); m_progress->update(++m_resultCount); m_accum->put(result); develop(); lock.unlock(); m_queue->signalWorkCanceled(m_parent, result->origOffset, result->origSize); } void ERPTProcess::bindResource(const std::string &name, int id) { BlockedRenderProcess::bindResource(name, id); if (name == "sensor") { Film *film = static_cast<Sensor *>(Scheduler::getInstance()->getResource(id))->getFilm(); m_accum = new ImageBlock(Bitmap::ESpectrum, film->getCropSize()); m_accum->clear(); } } MTS_IMPLEMENT_CLASS_S(ERPTRenderer, false, WorkProcessor) MTS_IMPLEMENT_CLASS(ERPTProcess, false, BlockedRenderProcess) MTS_NAMESPACE_END
39.956072
119
0.566902
anadodik
814e9c0a2e5498b167b42b6d991997f4f76585f9
1,292
hpp
C++
android-31/android/app/LocalActivityManager.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/app/LocalActivityManager.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/app/LocalActivityManager.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../JObject.hpp" namespace android::app { class Activity; } namespace android::content { class Intent; } namespace android::os { class Bundle; } namespace android::view { class Window; } class JString; namespace android::app { class LocalActivityManager : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit LocalActivityManager(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} LocalActivityManager(QJniObject obj); // Constructors LocalActivityManager(android::app::Activity arg0, jboolean arg1); // Methods android::view::Window destroyActivity(JString arg0, jboolean arg1) const; void dispatchCreate(android::os::Bundle arg0) const; void dispatchDestroy(jboolean arg0) const; void dispatchPause(jboolean arg0) const; void dispatchResume() const; void dispatchStop() const; android::app::Activity getActivity(JString arg0) const; android::app::Activity getCurrentActivity() const; JString getCurrentId() const; void removeAllActivities() const; android::os::Bundle saveInstanceState() const; android::view::Window startActivity(JString arg0, android::content::Intent arg1) const; }; } // namespace android::app
24.377358
161
0.736842
YJBeetle
814ea14782e84bacbc2ba747321dee746bc44d2c
1,514
cpp
C++
scratch/src/resources/shader_library.cpp
jaideng123/Scratch
91ff6de4f9f1e4f801441d3da45a4a001871a7ac
[ "MIT", "Unlicense" ]
null
null
null
scratch/src/resources/shader_library.cpp
jaideng123/Scratch
91ff6de4f9f1e4f801441d3da45a4a001871a7ac
[ "MIT", "Unlicense" ]
null
null
null
scratch/src/resources/shader_library.cpp
jaideng123/Scratch
91ff6de4f9f1e4f801441d3da45a4a001871a7ac
[ "MIT", "Unlicense" ]
null
null
null
// // Created by JJJai on 12/18/2021. // #include <iostream> #include <utilities/assert.h> #include "shader_library.h" std::shared_ptr<scratch::Shader> scratch::ShaderLibrary::addShader(const std::string &name, const std::string &vertexPath, const std::string &fragPath) { std::cout << "Loading Shader: " << name << std::endl; XXH64_hash_t hash = XXH64(name.c_str(), name.length(), HASH_SEED); std::cout << "Generated Hash:" << std::to_string(hash) << std::endl; std::shared_ptr<scratch::Shader> shader = std::make_shared<scratch::Shader>(hash, name, vertexPath, fragPath); if (loadedShaders.find(hash) != loadedShaders.end()) { std::cout << "Warning: Shader already loaded, replacing..." << std::to_string(hash) << std::endl; } loadedShaders.insert({hash, shader}); return shader; } std::shared_ptr<scratch::Shader> scratch::ShaderLibrary::findShader(const std::string &name) { std::cout << "Looking Up Shader: " << name << std::endl; XXH64_hash_t hash = XXH64(name.c_str(), name.length(), HASH_SEED); std::cout << "Generated Hash:" << std::to_string(hash) << std::endl; if (loadedShaders.find(hash) != loadedShaders.end()) { return loadedShaders[hash]; } else { SCRATCH_ASSERT_NEVER("Could not find shader: " + name); } } void scratch::ShaderLibrary::reloadAllShaders() { for (auto pair: loadedShaders) { pair.second->reload(); } }
38.820513
120
0.622853
jaideng123
814fcf6666cb8d4e930ef6625462ee9575842d0a
9,312
cpp
C++
src/webots/nodes/WbSpeaker.cpp
awesome-archive/webots
8e74fb8393d1e3a6540749afc492635c43f1b30f
[ "Apache-2.0" ]
1
2018-12-24T04:31:14.000Z
2018-12-24T04:31:14.000Z
src/webots/nodes/WbSpeaker.cpp
golbh/webots
8e74fb8393d1e3a6540749afc492635c43f1b30f
[ "Apache-2.0" ]
null
null
null
src/webots/nodes/WbSpeaker.cpp
golbh/webots
8e74fb8393d1e3a6540749afc492635c43f1b30f
[ "Apache-2.0" ]
1
2019-07-13T17:58:04.000Z
2019-07-13T17:58:04.000Z
// Copyright 1996-2018 Cyberbotics Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "WbSpeaker.hpp" #include "WbNodeUtilities.hpp" #include "WbProtoList.hpp" #include "WbProtoModel.hpp" #include "WbRobot.hpp" #include "WbSimulationState.hpp" #include "WbSoundClip.hpp" #include "WbSoundEngine.hpp" #include "WbSoundSource.hpp" #include "../../lib/Controller/api/messages.h" #include <QtCore/QDataStream> #include <QtCore/QDir> #include <cassert> #define TEXT_TO_SPEECH_KEY "WB_TEXT_TO_SPEECH" void WbSpeaker::init() { mControllerDir = ""; mSoundSourcesMap.clear(); mPlayingSoundSourcesMap.clear(); mEngine = QString("pico"); mLanguage = QString("en-US"); } WbSpeaker::WbSpeaker(WbTokenizer *tokenizer) : WbSolidDevice("Speaker", tokenizer) { init(); } WbSpeaker::WbSpeaker(const WbSpeaker &other) : WbSolidDevice(other) { init(); } WbSpeaker::WbSpeaker(const WbNode &other) : WbSolidDevice(other) { init(); } WbSpeaker::~WbSpeaker() { foreach (WbSoundSource *source, mSoundSourcesMap) { if (source) WbSoundEngine::deleteSource(source); } mSoundSourcesMap.clear(); mPlayingSoundSourcesMap.clear(); } void WbSpeaker::postFinalize() { WbSolidDevice::postFinalize(); WbRobot *robot = const_cast<WbRobot *>(static_cast<const WbRobot *>(WbNodeUtilities::findTopNode(this))); if (robot) mControllerDir = robot->controllerDir(); } void WbSpeaker::handleMessage(QDataStream &stream) { unsigned char command; stream >> (unsigned char &)command; switch (command) { case C_SPEAKER_PLAY_SOUND: { int numberOfSound; stream >> (int &)numberOfSound; for (int i = 0; i < numberOfSound; ++i) { short size; short side; double volume; double pitch; double balance; unsigned char loop; stream >> (short &)size; char soundFile[size]; stream.readRawData(soundFile, size); stream >> (double &)volume; stream >> (double &)pitch; stream >> (double &)balance; stream >> (short &)side; stream >> (unsigned char &)loop; playSound(soundFile, volume, pitch, balance, (bool)loop, (int)side); } return; } case C_SPEAKER_STOP: { short numberOfSound; stream >> (short &)numberOfSound; if (numberOfSound == 0) stopAll(); else { for (int i = 0; i < numberOfSound; ++i) { short size; stream >> (short &)size; char sound[size]; stream.readRawData(sound, size); stop(sound); } } return; } case C_SPEAKER_SET_ENGINE: { short size; stream >> (short &)size; char engine[size]; stream.readRawData(engine, size); mEngine = QString(engine); return; } case C_SPEAKER_SET_LANGUAGE: { short size; stream >> (short &)size; char language[size]; stream.readRawData(language, size); mLanguage = QString(language); return; } case C_SPEAKER_SPEAK: { short size; double volume; stream >> (short &)size; char text[size]; stream.readRawData(text, size); stream >> (double &)volume; playText(text, volume); return; } default: assert(0); } } void WbSpeaker::writeAnswer(QDataStream &stream) { foreach (const WbSoundSource *source, mPlayingSoundSourcesMap) { if (!source->isPlaying()) { if (mPlayingSoundSourcesMap.key(source) == TEXT_TO_SPEECH_KEY) { stream << (short unsigned int)tag(); stream << (unsigned char)C_SPEAKER_SPEAK_OVER; } else { stream << (short unsigned int)tag(); stream << (unsigned char)C_SPEAKER_SOUND_OVER; const QByteArray name = mPlayingSoundSourcesMap.key(source).toUtf8(); stream.writeRawData(name.constData(), name.size() + 1); } mPlayingSoundSourcesMap.remove(mPlayingSoundSourcesMap.key(source)); } } } void WbSpeaker::postPhysicsStep() { WbSolidDevice::postPhysicsStep(); foreach (WbSoundSource *source, mSoundSourcesMap) { if (source) updateSoundSource(source); } } void WbSpeaker::playText(const char *text, double volume) { if (!mSoundSourcesMap.contains(TEXT_TO_SPEECH_KEY)) { // text-to-speech was never used WbSoundSource *source = WbSoundEngine::createSource(); updateSoundSource(source); mSoundSourcesMap[TEXT_TO_SPEECH_KEY] = source; } WbSoundSource *source = mSoundSourcesMap.value(TEXT_TO_SPEECH_KEY, NULL); if (source) { source->stop(); // cd to the controller directory (because some tags in the text // may refeer to file relatively to the controller) QDir initialDir = QDir::current(); if (!QDir::setCurrent(mControllerDir)) this->warn(tr("Cannot change directory to: '%1'").arg(mControllerDir)); WbSoundClip *soundClip = WbSoundEngine::soundFromText(text, mEngine, mLanguage); QDir::setCurrent(initialDir.path()); if (soundClip) { source->setSoundClip(soundClip); source->play(); source->setGain(volume); mPlayingSoundSourcesMap[TEXT_TO_SPEECH_KEY] = source; } } } void WbSpeaker::playSound(const char *file, double volume, double pitch, double balance, bool loop, int side) { QString filename = QString(file); QString key = filename; if (side == -1) key += "_left"; else if (side == 1) key += "_right"; if (!mSoundSourcesMap.contains(key)) { // this sound was never played QString path = ""; if (QFile::exists(mControllerDir + filename)) // check if path is relative to the controller path = mControllerDir; else { // check if path is relative to the PROTO (or any ancestor PROTO) WbRobot *robot = const_cast<WbRobot *>(static_cast<const WbRobot *>(WbNodeUtilities::findTopNode(this))); if (robot && robot->isProtoInstance()) { WbProtoModel *protoModel = robot->proto(); do { if (!protoModel->path().isEmpty()) { path = protoModel->path(); if (QFile::exists(path + filename)) break; } protoModel = WbProtoList::current()->findModel(protoModel->ancestorProtoName(), ""); } while (protoModel); } } if (!QFile::exists(path + filename)) { // sound file not found relatively to the PROTOs or controller if (!QFile::exists(filename)) { // check if path is absolute this->warn(tr("Sound file '%1' not found. The sound file should be defined relatively to the controller, the PROTO or " "absolutely.\n") .arg(filename)); return; } path = ""; } WbSoundSource *source = WbSoundEngine::createSource(); updateSoundSource(source); // cd to the path directory if required QDir initialDir = QDir::current(); if (!path.isEmpty()) { if (!QDir::setCurrent(path)) this->warn(tr("Cannot change directory to: '%1'").arg(path)); } WbSoundClip *soundClip = WbSoundEngine::sound(filename, balance, side); if (!path.isEmpty()) QDir::setCurrent(initialDir.path()); if (!soundClip) { this->warn(tr("Impossible to play '%1'. Make sure the file format is supported (8 or 16 bits, mono or stereo wave).\n") .arg(filename)); return; } source->setSoundClip(soundClip); source->play(); mSoundSourcesMap[key] = source; } WbSoundSource *source = mSoundSourcesMap.value(key, NULL); if (source) { mPlayingSoundSourcesMap[key] = source; if (!source->isPlaying()) // this sound was already played but is over source->play(); source->setLooping(loop); source->setGain(volume); source->setPitch(pitch); if (WbSimulationState::instance()->isPaused() || WbSimulationState::instance()->isStep()) source->pause(); } } void WbSpeaker::stop(const char *sound) { QString key = QString(sound); WbSoundSource *source = mSoundSourcesMap.value(key, NULL); if (!source) { key = QString(sound) + "_left"; source = mSoundSourcesMap.value(key, NULL); } if (!source) { key = QString(sound) + "_right"; source = mSoundSourcesMap.value(key, NULL); } if (source) { source->stop(); WbSoundEngine::deleteSource(source); mSoundSourcesMap.remove(key); } mPlayingSoundSourcesMap.remove(key); } void WbSpeaker::stopAll() { foreach (WbSoundSource *source, mSoundSourcesMap) { if (source) { source->stop(); WbSoundEngine::deleteSource(source); } } mSoundSourcesMap.clear(); mPlayingSoundSourcesMap.clear(); } void WbSpeaker::updateSoundSource(WbSoundSource *source) { source->setPosition(position()); source->setVelocity(linearVelocity()); source->setDirection(rotationMatrix() * WbVector3(0, 1, 0)); }
31.04
127
0.646155
awesome-archive
81523bf46d7dfb1d7c97c029c1399accaf859d74
1,972
cpp
C++
libutt/libutt/test/TestIBE.cpp
definitelyNotFBI/utt
1695e3a1f81848e19b042cdc4db9cf1d263c26a9
[ "Apache-2.0" ]
null
null
null
libutt/libutt/test/TestIBE.cpp
definitelyNotFBI/utt
1695e3a1f81848e19b042cdc4db9cf1d263c26a9
[ "Apache-2.0" ]
null
null
null
libutt/libutt/test/TestIBE.cpp
definitelyNotFBI/utt
1695e3a1f81848e19b042cdc4db9cf1d263c26a9
[ "Apache-2.0" ]
null
null
null
#include <utt/Configuration.h> #include <utt/IBE.h> #include <xassert/XAssert.h> #include <xutils/Log.h> #include <xutils/Utils.h> using namespace std; using namespace libutt; int main(int argc, char *argv[]) { libutt::initialize(nullptr, 0); //srand(static_cast<unsigned int>(time(NULL))); (void)argc; (void)argv; IBE::Params p = IBE::Params::random(); IBE::MSK msk = IBE::MSK::random(); IBE::MPK mpk = msk.toMPK(p); std::string pid = "testuser@testdomain.com"; IBE::EncSK encsk = msk.deriveEncSK(p, pid); // test EncSK serializes well std::stringstream ss; ss << encsk; IBE::EncSK sameEncSK; ss >> sameEncSK; testAssertEqual(encsk, sameEncSK); Fr v = Fr::random_element(); Fr r_1 = Fr::random_element(); Fr r_2 = Fr::random_element(); logdbg << "v init: " << v << endl; logdbg << "r_1 init: " << r_1 << endl; logdbg << "r_2 init: " << r_2 << endl; IBE::Ctxt ctxt = mpk.encrypt(pid, frsToBytes({ v, r_1, r_2 })), sameCtxt; ss << ctxt; ss >> sameCtxt; testAssertEqual(ctxt, sameCtxt); Fr samev = Fr::random_element(), samer_1 = Fr::random_element(), samer_2 = Fr::random_element(); bool success; AutoBuf<unsigned char> ptxt; std::tie(success, ptxt) = encsk.decrypt(ctxt); testAssertTrue(success); auto vec = bytesToFrs(ptxt); samev = vec[0]; samer_1 = vec[1]; samer_2 = vec[2]; logdbg << "v decr: " << samev << endl; logdbg << "r_1 decr: " << samer_1 << endl; logdbg << "r_2 decr: " << samer_2 << endl; testAssertEqual(r_2, samer_2); testAssertEqual(r_1, samer_1); testAssertEqual(v, samev); // Test (in)equality auto ctxtCopy = ctxt; testAssertEqual(ctxt, ctxtCopy); testAssertNotEqual(ctxt, mpk.encrypt(pid, frsToBytes({ Fr::random_element(), Fr::random_element(), Fr::random_element() }))); loginfo << "All is well." << endl; return 0; }
25.947368
129
0.606491
definitelyNotFBI
8154cf4b468e1ff4151241449113a50ff29629f4
17,156
cpp
C++
src/model/AdditionalProperties.cpp
mehrdad-shokri/OpenStudio
1773b54ce1cb660818ac0114dd7eefae6639ca36
[ "blessing" ]
null
null
null
src/model/AdditionalProperties.cpp
mehrdad-shokri/OpenStudio
1773b54ce1cb660818ac0114dd7eefae6639ca36
[ "blessing" ]
null
null
null
src/model/AdditionalProperties.cpp
mehrdad-shokri/OpenStudio
1773b54ce1cb660818ac0114dd7eefae6639ca36
[ "blessing" ]
null
null
null
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2020, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ #include <string> #include <memory> #include "AdditionalProperties.hpp" #include "AdditionalProperties_Impl.hpp" #include "Model.hpp" #include "Model_Impl.hpp" #include "ModelObject.hpp" #include "ModelObject_Impl.hpp" #include "ModelExtensibleGroup.hpp" #include "ResourceObject.hpp" #include <utilities/idd/OS_AdditionalProperties_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> #include <utilities/idd/IddFactory.hxx> namespace openstudio { namespace model { namespace detail { AdditionalProperties_Impl::AdditionalProperties_Impl(const IdfObject &idfObject, Model_Impl *model, bool keepHandle) : ModelObject_Impl(idfObject, model, keepHandle) { OS_ASSERT(idfObject.iddObject().type() == AdditionalProperties::iddObjectType()); } AdditionalProperties_Impl::AdditionalProperties_Impl(const openstudio::detail::WorkspaceObject_Impl &other, Model_Impl *model, bool keepHandle) : ModelObject_Impl(other, model, keepHandle) { OS_ASSERT(other.iddObject().type() == AdditionalProperties::iddObjectType()); } AdditionalProperties_Impl::AdditionalProperties_Impl(const AdditionalProperties_Impl &other, Model_Impl *model, bool keepHandle) : ModelObject_Impl(other, model, keepHandle) {} ModelObject AdditionalProperties_Impl::modelObject() const { boost::optional<ModelObject> result = getObject<AdditionalProperties>().getModelObjectTarget<ModelObject>( OS_AdditionalPropertiesFields::ObjectName); if (!result){ // DLM: should we remove ourself? probably worse to do that since user may call other methods and cause a crash //this->remove(); LOG_AND_THROW("Cannot retrieve associated ModelObject"); } OS_ASSERT(result); return *result; } const std::vector<std::string>& AdditionalProperties_Impl::outputVariableNames() const { static const std::vector<std::string> result; return result; } IddObjectType AdditionalProperties_Impl::iddObjectType() const { return AdditionalProperties::iddObjectType(); } boost::optional<ParentObject> AdditionalProperties_Impl::parent() const { // DLM: should this return the model object? no because model object is not a parent object. return boost::optional<ParentObject>(); } bool AdditionalProperties_Impl::setParent(ParentObject& newParent) { // DLM: should we allow this? no because model object is not a parent object. return false; } std::vector<ResourceObject> AdditionalProperties_Impl::resources() const { return std::vector<ResourceObject>(); } std::vector<std::string> AdditionalProperties_Impl::featureNames() const { std::set<std::string> nameSet; for (const ModelExtensibleGroup& group : castVector<ModelExtensibleGroup>(extensibleGroups())) { boost::optional<std::string> name = group.getString(OS_AdditionalPropertiesExtensibleFields::FeatureName); OS_ASSERT(name); nameSet.insert(*name); } std::vector<std::string> names; names.assign(nameSet.begin(), nameSet.end()); return names; } boost::optional<ModelExtensibleGroup> AdditionalProperties_Impl::getFeatureGroupByName(const std::string &name) const { for (ModelExtensibleGroup& group : castVector<ModelExtensibleGroup>(extensibleGroups())) { const boost::optional<std::string> featureName(group.getString(OS_AdditionalPropertiesExtensibleFields::FeatureName)); OS_ASSERT(featureName); if (*featureName == name) { return group; } } return boost::none; } bool AdditionalProperties_Impl::hasFeature(const std::string &name) const { return getFeatureGroupByName(name).has_value(); } boost::optional<std::string> AdditionalProperties_Impl::getFeatureDataType(const std::string &name) const { boost::optional<std::string> dataType; boost::optional<ModelExtensibleGroup> group(getFeatureGroupByName(name)); if (group) { dataType = group->getString(OS_AdditionalPropertiesExtensibleFields::FeatureDataType); OS_ASSERT(dataType); } else { dataType = boost::none; } return dataType; } boost::optional<std::string> AdditionalProperties_Impl::getFeatureStringAndCheckForType(const std::string& name, const std::string& expectedDataType) const { boost::optional<std::string> value; boost::optional<ModelExtensibleGroup> group(getFeatureGroupByName(name)); if (group) { boost::optional<std::string> dataType(group->getString(OS_AdditionalPropertiesExtensibleFields::FeatureDataType)); OS_ASSERT(dataType); if (*dataType == expectedDataType) { value = group->getString(OS_AdditionalPropertiesExtensibleFields::FeatureValue); } else { value = boost::none; } } else { value = boost::none; } return value; } boost::optional<std::string> AdditionalProperties_Impl::getFeatureAsString(const std::string& name) const { return getFeatureStringAndCheckForType(name, "String"); } boost::optional<double> AdditionalProperties_Impl::getFeatureAsDouble(const std::string& name) const { boost::optional<std::string> strValue(getFeatureStringAndCheckForType(name, "Double")); boost::optional<double> value; if (strValue) { try { value = boost::lexical_cast<double>(*strValue); } catch (boost::bad_lexical_cast) { LOG(Error, "Value: " + *strValue + ", not castable to type double.") value = boost::none; } } else { value = boost::none; } return value; } boost::optional<int> AdditionalProperties_Impl::getFeatureAsInteger(const std::string& name) const { boost::optional<std::string> strValue(getFeatureStringAndCheckForType(name, "Integer")); boost::optional<int> value; if (strValue) { try { value = boost::lexical_cast<int>(*strValue); } catch (boost::bad_lexical_cast) { LOG(Error, "Value: " + *strValue + ", not castable to type integer.") value = boost::none; } } else { value = boost::none; } return value; } boost::optional<bool> AdditionalProperties_Impl::getFeatureAsBoolean(const std::string& name) const { boost::optional<std::string> strValue(getFeatureStringAndCheckForType(name, "Boolean")); boost::optional<bool> value; if (strValue) { if (*strValue == "false") { value = false; } else if (*strValue == "true") { value = true; } else { LOG(Error, "Value: " + *strValue + ", not castable to type boolean.") value = boost::none; } } else { value = boost::none; } return value; } std::vector<std::string> AdditionalProperties_Impl::suggestedFeatureNames() const { std::set<std::string> availableFeatureNames; // DLM: this should be based on the model object type right? // DLM: should we create a virtual method for all model objects similar to outputVariableNames // DLM: long term, this should pull from a list that can be updated at run time, possibly related to OpenStudio standards for (const AdditionalProperties& addlProps : this->model().getConcreteModelObjects<AdditionalProperties>()) { for (const std::string& featureName : addlProps.featureNames()) { availableFeatureNames.insert(featureName); } } std::vector<std::string> retvals; retvals.assign(availableFeatureNames.begin(), availableFeatureNames.end()); return retvals; } bool AdditionalProperties_Impl::setFeatureGroupDataTypeAndValue(const std::string& name, const std::string& dataType, const std::string& value) { boost::optional<ModelExtensibleGroup> group(getFeatureGroupByName(name)); if (group) { const bool dataTypeOK = group->setString(OS_AdditionalPropertiesExtensibleFields::FeatureDataType, dataType, false); const bool valueOK = group->setString(OS_AdditionalPropertiesExtensibleFields::FeatureValue, value, false); // Since we're doing this checking in the public setters, these should always return true. OS_ASSERT(dataTypeOK); OS_ASSERT(valueOK); this->emitChangeSignals(); return true; } else { std::vector<std::string> temp; temp.push_back(name); temp.push_back(dataType); temp.push_back(value); ModelExtensibleGroup newgroup = pushExtensibleGroup(temp).cast<ModelExtensibleGroup>(); return (!newgroup.empty()); } } bool AdditionalProperties_Impl::setFeature(const std::string& name, const std::string& value) { return setFeatureGroupDataTypeAndValue(name, "String", value); } bool AdditionalProperties_Impl::setFeature(const std::string& name, const char* value) { return setFeature(name, std::string(value)); } bool AdditionalProperties_Impl::setFeature(const std::string& name, double value) { return setFeatureGroupDataTypeAndValue(name, "Double", boost::lexical_cast<std::string>(value)); } bool AdditionalProperties_Impl::setFeature(const std::string& name, int value) { return setFeatureGroupDataTypeAndValue(name, "Integer", boost::lexical_cast<std::string>(value)); } bool AdditionalProperties_Impl::setFeature(const std::string& name, bool value) { std::string strValue(boost::lexical_cast<std::string>(value)); if (value) { strValue = "true"; } else { strValue = "false"; } return setFeatureGroupDataTypeAndValue(name, "Boolean", strValue); } bool AdditionalProperties_Impl::resetFeature(const std::string& name) { unsigned n_groups = numExtensibleGroups(); for (unsigned i=0; i < n_groups; ++i) { ModelExtensibleGroup group = getExtensibleGroup(i).cast<ModelExtensibleGroup>(); const boost::optional<std::string> featureName(group.getString(OS_AdditionalPropertiesExtensibleFields::FeatureName)); OS_ASSERT(featureName); if (*featureName == name) { eraseExtensibleGroup(i); return true; } } return false; } void AdditionalProperties_Impl::merge(const AdditionalProperties& other, bool overwrite) { if (other.handle() == this->handle()){ return; } for (const auto& featureName : other.featureNames()){ // check if we already have this key if ((!overwrite) && this->getFeatureDataType(featureName)){ continue; } boost::optional<std::string> dataType = other.getFeatureDataType(featureName); OS_ASSERT(dataType); if (istringEqual("String", *dataType)){ boost::optional<std::string> v = other.getFeatureAsString(featureName); OS_ASSERT(v); this->setFeature(featureName, *v); } else if (istringEqual("Double", *dataType)){ boost::optional<double> v = other.getFeatureAsDouble(featureName); OS_ASSERT(v); this->setFeature(featureName, *v); } else if (istringEqual("Boolean", *dataType)){ boost::optional<bool> v = other.getFeatureAsBoolean(featureName); OS_ASSERT(v); this->setFeature(featureName, *v); } else if (istringEqual("Integer", *dataType)){ boost::optional<int> v = other.getFeatureAsInteger(featureName); OS_ASSERT(v); this->setFeature(featureName, *v); } } } } //detail AdditionalProperties::AdditionalProperties(const ModelObject& modelObject) : ModelObject(AdditionalProperties::iddObjectType(), modelObject.model()) { OS_ASSERT(getImpl<detail::AdditionalProperties_Impl>()); if (modelObject.optionalCast<AdditionalProperties>()){ this->remove(); LOG_AND_THROW("Cannot create a AdditionalProperties object for AdditionalProperties object"); } bool ok = setPointer(OS_AdditionalPropertiesFields::ObjectName, modelObject.handle()); OS_ASSERT(ok); } ModelObject AdditionalProperties::modelObject() const { return getImpl<detail::AdditionalProperties_Impl>()->modelObject(); } IddObjectType AdditionalProperties::iddObjectType() { IddObjectType result(IddObjectType::OS_AdditionalProperties); return result; } std::vector<std::string> AdditionalProperties::featureNames() const { return getImpl<detail::AdditionalProperties_Impl>()->featureNames(); } bool AdditionalProperties::hasFeature(const std::string& name) const { return getImpl<detail::AdditionalProperties_Impl>()->hasFeature(name); } boost::optional<std::string> AdditionalProperties::getFeatureDataType(const std::string& name) const { return getImpl<detail::AdditionalProperties_Impl>()->getFeatureDataType(name); } boost::optional<std::string> AdditionalProperties::getFeatureAsString(const std::string& name) const { return getImpl<detail::AdditionalProperties_Impl>()->getFeatureAsString(name); } boost::optional<double> AdditionalProperties::getFeatureAsDouble(const std::string& name) const { return getImpl<detail::AdditionalProperties_Impl>()->getFeatureAsDouble(name); } boost::optional<int> AdditionalProperties::getFeatureAsInteger(const std::string& name) const { return getImpl<detail::AdditionalProperties_Impl>()->getFeatureAsInteger(name); } boost::optional<bool> AdditionalProperties::getFeatureAsBoolean(const std::string& name) const { return getImpl<detail::AdditionalProperties_Impl>()->getFeatureAsBoolean(name); } std::vector<std::string> AdditionalProperties::suggestedFeatureNames() const { return getImpl<detail::AdditionalProperties_Impl>()->suggestedFeatureNames(); } bool AdditionalProperties::setFeature(const std::string& name, const std::string& value) { return getImpl<detail::AdditionalProperties_Impl>()->setFeature(name, value); } bool AdditionalProperties::setFeature(const std::string& name, const char* value) { return getImpl<detail::AdditionalProperties_Impl>()->setFeature(name, value); } bool AdditionalProperties::setFeature(const std::string& name, double value) { return getImpl<detail::AdditionalProperties_Impl>()->setFeature(name, value); } bool AdditionalProperties::setFeature(const std::string& name, int value) { return getImpl<detail::AdditionalProperties_Impl>()->setFeature(name, value); } bool AdditionalProperties::setFeature(const std::string& name, bool value) { return getImpl<detail::AdditionalProperties_Impl>()->setFeature(name, value); } bool AdditionalProperties::resetFeature(const std::string& name) { return getImpl<detail::AdditionalProperties_Impl>()->resetFeature(name); } void AdditionalProperties::merge(const AdditionalProperties& other, bool overwrite) { getImpl<detail::AdditionalProperties_Impl>()->merge(other, overwrite); } /// @cond AdditionalProperties::AdditionalProperties(std::shared_ptr<detail::AdditionalProperties_Impl> impl) : ModelObject(std::move(impl)) {} /// @endcond } //model } //openstudio
37.705495
157
0.709839
mehrdad-shokri
8154d0d229468dcfc47708c22f46ea0367c975e9
5,853
cpp
C++
lib/ST_Anything/IS_DoorControl.cpp
hansaya/GarageDoorOpener
946b1431143d4c5b1c9493f951f6d8f09a7e52f5
[ "MIT" ]
1
2020-12-07T22:32:27.000Z
2020-12-07T22:32:27.000Z
lib/ST_Anything/IS_DoorControl.cpp
hansaya/GarageDoorOpener
946b1431143d4c5b1c9493f951f6d8f09a7e52f5
[ "MIT" ]
null
null
null
lib/ST_Anything/IS_DoorControl.cpp
hansaya/GarageDoorOpener
946b1431143d4c5b1c9493f951f6d8f09a7e52f5
[ "MIT" ]
null
null
null
//****************************************************************************************** // File: IS_DoorControl.h // Authors: Dan G Ogorchock & Daniel J Ogorchock (Father and Son) // // Summary: IS_DoorControl is a class which implements the SmartThings "Door Control" device capability. It features // an automatic-turn-off time delay for a relay to actuate a button press. This is useful for controlling // a garage door. Use the input to monitor a magnetic door contact sensor. Use the output to control a relay to // "press the garage door button" to open/close the garage door. // // It inherits from the st::InterruptSensor class and clones much from the st::Executor Class // // Create an instance of this class in your sketch's global variable section // For Example: st::IS_DoorControl sensor3(F("doorControl1"), PIN_CONTACT_DOOR_1, LOW, true, PIN_RELAY_DOOR_1, LOW, true, 1000, 1000, true); // // st::IS_DoorControl() constructor requires the following arguments // - String &name - REQUIRED - the name of the object - must match the Groovy ST_Anything DeviceType tile name // - byte pinInput - REQUIRED - the Arduino Pin to be used as a digital input // - bool iState - REQUIRED - LOW or HIGH - determines which value indicates the interrupt is true // - bool internalPullup - REQUIRED - true == INTERNAL_PULLUP // - byte pinOutput - REQUIRED - the Arduino Pin to be used as a digital output // - bool startingState - REQUIRED - the value desired for the initial state of the switch. LOW = "off", HIGH = "on" // - bool invertLogic - REQUIRED - determines whether the Arduino Digital Output should use inverted logic // - long delayTime - REQUIRED - the number of milliseconds to keep the output on // - long numReqCounts - OPTIONAL - number of counts before changing state of input (prevent false alarms) // - bool useMomentary - OPTIONAL - use momentary output (true) or standard switch (false) (defaults to true) // // Change History: // // Date Who What // ---- --- ---- // 2015-01-07 Dan Ogorchock Original Creation // 2018-08-30 Dan Ogorchock Modified comment section above to comply with new Parent/Child Device Handler requirements // 2018-11-07 Dan Ogorchock Added optional "numReqCounts" constructor argument/capability // 2019-07-24 Dan Ogorchock Added parameter to use output as a simple switch instead of momentary output // // //****************************************************************************************** #include "IS_DoorControl.h" #include "Constants.h" #include "Everything.h" namespace st { //private void IS_DoorControl::writeStateToPin() { digitalWrite(m_nOutputPin, m_bInvertLogic ? !m_bCurrentState : m_bCurrentState); } //public //constructor IS_DoorControl::IS_DoorControl(const __FlashStringHelper *name, byte pinInput, bool iState, bool pullup, byte pinOutput, bool startingState, bool invertLogic, unsigned long delayTime, long numReqCounts, bool useMomentary) : InterruptSensor(name, pinInput, iState, pullup, numReqCounts), //use parent class' constructor m_bCurrentState(startingState), m_bInvertLogic(invertLogic), m_lDelayTime(delayTime), m_bUseMomentary(useMomentary), m_lTimeTurnedOn(0), m_bTimerPending(false) { setOutputPin(pinOutput); } //destructor IS_DoorControl::~IS_DoorControl() { } void IS_DoorControl::init() { //get current status of contact sensor by calling parent class's init() routine - no need to duplicate it here! InterruptSensor::init(); } //update function void IS_DoorControl::update() { if (m_bTimerPending) { //Turn off digital output if timer has expired if ((m_bCurrentState == HIGH) && (millis() - m_lTimeTurnedOn >= m_lDelayTime)) { m_bCurrentState = LOW; writeStateToPin(); //Decrement number of active timers if (st::Everything::bTimersPending > 0) st::Everything::bTimersPending--; m_bTimerPending = false; } } //check to see if input pin has changed state InterruptSensor::update(); } void IS_DoorControl::beSmart(const String &str) { String s = str.substring(str.indexOf(' ') + 1); if (st::InterruptSensor::debug) { Serial.print(F("IS_ContactRelay::beSmart s = ")); Serial.println(s); } if ( (s == F("on")) || (m_bUseMomentary && (s == F("off")))) { m_bCurrentState = HIGH; if (m_bUseMomentary) { //Save time turned on m_lTimeTurnedOn = millis(); //Increment number of active timers if (!m_bTimerPending) { st::Everything::bTimersPending++; m_bTimerPending = true; } } if (m_bUseMomentary) { //Queue the door status update the ST Cloud Everything::sendSmartStringNow(getName() + (getStatus() ? F(" opening") : F(" closing"))); } } else if (s == F("off")) { m_bCurrentState = LOW; //Decrement number of active timers if (st::Everything::bTimersPending > 0) st::Everything::bTimersPending--; m_bTimerPending = false; } //update the digital output writeStateToPin(); } //called periodically by Everything class to ensure ST Cloud is kept consistent with the state of the contact sensor void IS_DoorControl::refresh() { Everything::sendSmartString(getName() + (getStatus() ? F(" closed") : F(" open"))); } void IS_DoorControl::runInterrupt() { //add the "closed" event to the buffer to be queued for transfer to the ST Shield Everything::sendSmartString(getName() + F(" closed")); } void IS_DoorControl::runInterruptEnded() { //add the "open" event to the buffer to be queued for transfer to the ST Shield Everything::sendSmartString(getName() + F(" open")); } void IS_DoorControl::setOutputPin(byte pin) { m_nOutputPin = pin; pinMode(m_nOutputPin, OUTPUT); writeStateToPin(); } }
36.12963
224
0.676064
hansaya
815502270af86215db65534b43b0d1f9e277c0f2
2,807
cpp
C++
ass4/testdepartment.cpp
starcraft66/COEN243-Fall-2019-Assignments
66caa4d6bf0f960218c86288e1c17bdae16b22b1
[ "BSD-3-Clause" ]
2
2021-07-24T15:01:50.000Z
2022-01-17T21:49:09.000Z
ass4/testdepartment.cpp
starcraft66/COEN243-Fall-2019-Assignments
66caa4d6bf0f960218c86288e1c17bdae16b22b1
[ "BSD-3-Clause" ]
null
null
null
ass4/testdepartment.cpp
starcraft66/COEN243-Fall-2019-Assignments
66caa4d6bf0f960218c86288e1c17bdae16b22b1
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <array> #include "department.hpp" int main(int argc, char *argv[]) { Employee lastemp; std::string id_number, name, history; std::cout << "Enter the name of the department: "; std::getline(std::cin, name); std::cout << "Enter the department's identification number: "; std::getline(std::cin, id_number); std::cout << "Enter the department's history: "; std::getline(std::cin, history); Department department = Department(id_number, name, history); for(int i = 0; i < 5; i++) { int id, year_hired, tel_area_code; std::string first_name, last_name, dob, address, tel_number; double salary; std::cout << "Entering information for employee #" << i + 1 << std::endl; std::cout << "Enter the first name: "; std::getline(std::cin, first_name); std::cout << "Enter the last name: "; std::getline(std::cin, last_name); std::cout << "Enter the address: "; std::getline(std::cin, address); std::cout << "Enter the id (int): "; std::cin >> id; std::cout << "Enter the year hired: "; std::cin >> year_hired; std::cout << "Enter the phone number area code (int): "; std::cin >> tel_area_code; std::cout << "Enter the phone number: "; std::getline(std::cin, tel_number); std::cout << "Enter the salary: "; std::cin >> salary; std::cout << "Enter the date of birth: "; std::getline(std::cin, dob); Employee emp = Employee(id, first_name, last_name, dob, address, year_hired, salary, tel_area_code, tel_number); department.AddEmployee(emp); lastemp = emp; } std::cout << "Department information" << std::endl; std::cout << "Identification Number: " << department.GetIdNumber() << std::endl; std::cout << "Name: " << department.GetName() << std::endl; std::cout << "History: " << department.GetHistory() << std::endl; std::cout << "Enter the new name of the department: "; std::getline(std::cin, name); department.SetName(name); std::cout << "Enter the department's new history: "; std::getline(std::cin, history); department.SetHistory(history); department.RemoveEmployee(lastemp); std::cout << "Removed the last employee" << std::endl; if(department.DoesEmployeeWorkInDepartment(2)) { std::cout << "Employee 2 works in the department." << std::endl; } else { std::cout << "Employee 2 doesn't work in the department." << std::endl; } std::cout << "List of employees working in the department:" << std::endl; department.PrintEmployeeList(); std::cout << "Number of employees working in the department: "; department.PrintNumberOfEmployees(); }
41.279412
120
0.604916
starcraft66
8155065d74e25fe0011fb3788409b9be64d6a4f5
699
cc
C++
geometry.cc
Computational-Camera/OPENCV_Tricks
e79957306ce8f267cc725f869769ffda92f47e7c
[ "MIT" ]
1
2019-10-30T06:07:52.000Z
2019-10-30T06:07:52.000Z
geometry.cc
Computational-Camera/OPENCV_Tricks
e79957306ce8f267cc725f869769ffda92f47e7c
[ "MIT" ]
null
null
null
geometry.cc
Computational-Camera/OPENCV_Tricks
e79957306ce8f267cc725f869769ffda92f47e7c
[ "MIT" ]
1
2019-11-19T05:56:19.000Z
2019-11-19T05:56:19.000Z
//=== Convert Point vector to Mat=== vector<Point2f> pt_vec; Mat pt_mat = Mat(pt_vec).clone(); //==== Convert Mat to vector === Point *pts = (const Point*) Mat(contour).data; //=== Warp image ==== warpPerspective ( src, dst, T, Size(w,h), INTER_LINEAR, BORDER_CONSTANT); //=== Points Transformation perspectiveTransform(p1, p2, T);//for points! src p1, dst p2 //=== Calculate distantce double cost = norm(Mat(p1), Mat(p2), NORM_L2); //=== Homography matrix estimation ==== findHomography( src_pt, dst_pt, RANSAC ); //=== Perspective matrix estimation ==== getPerspectiveTransform(const Point2f src[], const Point2f dst[]) //===Resize=== resize(src, dst, dst.size(), 0, 0, interpolation);
27.96
73
0.672389
Computational-Camera
8155df87a151d4b6930919d166cdc3c34cd207b8
5,053
hpp
C++
src/buffer.hpp
myfreeweb/zig
eeb4f376a31a0d6ca3f997becd2f247ebe71dfd6
[ "MIT" ]
null
null
null
src/buffer.hpp
myfreeweb/zig
eeb4f376a31a0d6ca3f997becd2f247ebe71dfd6
[ "MIT" ]
null
null
null
src/buffer.hpp
myfreeweb/zig
eeb4f376a31a0d6ca3f997becd2f247ebe71dfd6
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015 Andrew Kelley * * This file is part of zig, which is MIT licensed. * See http://opensource.org/licenses/MIT */ #ifndef ZIG_BUFFER_HPP #define ZIG_BUFFER_HPP #include "list.hpp" #include <assert.h> #include <stdint.h> #include <ctype.h> #include <stdarg.h> #define BUF_INIT {{0}} // Note, you must call one of the alloc, init, or resize functions to have an // initialized buffer. The assertions should help with this. struct Buf { ZigList<char> list; }; Buf *buf_sprintf(const char *format, ...) ATTRIBUTE_PRINTF(1, 2); Buf *buf_vprintf(const char *format, va_list ap); static inline size_t buf_len(Buf *buf) { assert(buf->list.length); return buf->list.length - 1; } static inline char *buf_ptr(Buf *buf) { assert(buf->list.length); return buf->list.items; } static inline void buf_resize(Buf *buf, size_t new_len) { buf->list.resize(new_len + 1); buf->list.at(buf_len(buf)) = 0; } static inline Buf *buf_alloc_fixed(size_t size) { Buf *buf = allocate<Buf>(1); buf_resize(buf, size); return buf; } static inline Buf *buf_alloc(void) { return buf_alloc_fixed(0); } static inline void buf_deinit(Buf *buf) { buf->list.deinit(); } static inline void buf_init_from_mem(Buf *buf, const char *ptr, size_t len) { assert(len != SIZE_MAX); buf->list.resize(len + 1); safe_memcpy(buf_ptr(buf), ptr, len); buf->list.at(buf_len(buf)) = 0; } static inline void buf_init_from_str(Buf *buf, const char *str) { buf_init_from_mem(buf, str, strlen(str)); } static inline void buf_init_from_buf(Buf *buf, Buf *other) { buf_init_from_mem(buf, buf_ptr(other), buf_len(other)); } static inline Buf *buf_create_from_mem(const char *ptr, size_t len) { assert(len != SIZE_MAX); Buf *buf = allocate<Buf>(1); buf_init_from_mem(buf, ptr, len); return buf; } static inline Buf *buf_create_from_slice(Slice<uint8_t> slice) { return buf_create_from_mem((const char *)slice.ptr, slice.len); } static inline Buf *buf_create_from_str(const char *str) { return buf_create_from_mem(str, strlen(str)); } static inline Buf *buf_create_from_buf(Buf *buf) { return buf_create_from_mem(buf_ptr(buf), buf_len(buf)); } static inline Buf *buf_slice(Buf *in_buf, size_t start, size_t end) { assert(in_buf->list.length); assert(start != SIZE_MAX); assert(end != SIZE_MAX); assert(start < buf_len(in_buf)); assert(end <= buf_len(in_buf)); Buf *out_buf = allocate<Buf>(1); out_buf->list.resize(end - start + 1); safe_memcpy(buf_ptr(out_buf), buf_ptr(in_buf) + start, end - start); out_buf->list.at(buf_len(out_buf)) = 0; return out_buf; } static inline void buf_append_mem(Buf *buf, const char *mem, size_t mem_len) { assert(buf->list.length); assert(mem_len != SIZE_MAX); size_t old_len = buf_len(buf); buf_resize(buf, old_len + mem_len); safe_memcpy(buf_ptr(buf) + old_len, mem, mem_len); buf->list.at(buf_len(buf)) = 0; } static inline void buf_append_str(Buf *buf, const char *str) { assert(buf->list.length); buf_append_mem(buf, str, strlen(str)); } static inline void buf_append_buf(Buf *buf, Buf *append_buf) { assert(buf->list.length); buf_append_mem(buf, buf_ptr(append_buf), buf_len(append_buf)); } static inline void buf_append_char(Buf *buf, uint8_t c) { assert(buf->list.length); buf_append_mem(buf, (const char *)&c, 1); } void buf_appendf(Buf *buf, const char *format, ...) ATTRIBUTE_PRINTF(2, 3); static inline bool buf_eql_mem(Buf *buf, const char *mem, size_t mem_len) { assert(buf->list.length); if (buf_len(buf) != mem_len) return false; return memcmp(buf_ptr(buf), mem, mem_len) == 0; } static inline bool buf_eql_str(Buf *buf, const char *str) { assert(buf->list.length); return buf_eql_mem(buf, str, strlen(str)); } static inline bool buf_starts_with_mem(Buf *buf, const char *mem, size_t mem_len) { if (buf_len(buf) < mem_len) { return false; } return memcmp(buf_ptr(buf), mem, mem_len) == 0; } static inline bool buf_starts_with_buf(Buf *buf, Buf *sub) { return buf_starts_with_mem(buf, buf_ptr(sub), buf_len(sub)); } static inline bool buf_starts_with_str(Buf *buf, const char *str) { return buf_starts_with_mem(buf, str, strlen(str)); } static inline bool buf_ends_with_mem(Buf *buf, const char *mem, size_t mem_len) { if (buf_len(buf) < mem_len) { return false; } return memcmp(buf_ptr(buf) + buf_len(buf) - mem_len, mem, mem_len) == 0; } static inline bool buf_ends_with_str(Buf *buf, const char *str) { return buf_ends_with_mem(buf, str, strlen(str)); } bool buf_eql_buf(Buf *buf, Buf *other); uint32_t buf_hash(Buf *buf); static inline void buf_upcase(Buf *buf) { for (size_t i = 0; i < buf_len(buf); i += 1) { buf_ptr(buf)[i] = (char)toupper(buf_ptr(buf)[i]); } } static inline Slice<uint8_t> buf_to_slice(Buf *buf) { return Slice<uint8_t>{reinterpret_cast<uint8_t*>(buf_ptr(buf)), buf_len(buf)}; } #endif
27.166667
83
0.681773
myfreeweb
8156392c8abad48c94d44fc3bb753aaa80872ca4
7,405
cpp
C++
test-suite/businessdayconventions.cpp
urgu00/QuantLib
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
[ "BSD-3-Clause" ]
1
2020-10-13T09:57:04.000Z
2020-10-13T09:57:04.000Z
test-suite/businessdayconventions.cpp
urgu00/QuantLib
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
[ "BSD-3-Clause" ]
19
2020-11-23T08:36:10.000Z
2022-03-28T10:06:53.000Z
test-suite/businessdayconventions.cpp
urgu00/QuantLib
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
[ "BSD-3-Clause" ]
5
2020-06-04T15:19:22.000Z
2020-06-18T08:24:37.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include "businessdayconventions.hpp" #include "utilities.hpp" #include <ql/time/businessdayconvention.hpp> #include <ql/time/daycounter.hpp> #include <ql/time/calendars/southafrica.hpp> #include <ql/time/period.hpp> using namespace QuantLib; using namespace boost::unit_test_framework; namespace business_day_conventions_test { struct SingleCase { SingleCase(const Calendar& calendar, const BusinessDayConvention& convention, const Date& start, const Period& period, const bool endOfMonth, Date result) : calendar(calendar), convention(convention), start(start), period(period), endOfMonth(endOfMonth), result(result) {} Calendar calendar; BusinessDayConvention convention; Date start; Period period; bool endOfMonth; Date result; }; } void BusinessDayConventionTest::testConventions() { BOOST_TEST_MESSAGE("Testing business day conventions..."); using namespace business_day_conventions_test; SingleCase testCases[] = { // Following SingleCase(SouthAfrica(), Following, Date(3,February,2015), Period(1,Months), false, Date(3,March,2015)), SingleCase(SouthAfrica(), Following, Date(3,February,2015), Period(4,Days), false, Date(9,February,2015)), SingleCase(SouthAfrica(), Following, Date(31,January,2015), Period(1,Months), true, Date(27,February,2015)), SingleCase(SouthAfrica(), Following, Date(31,January,2015), Period(1,Months), false, Date(2,March,2015)), //ModifiedFollowing SingleCase(SouthAfrica(), ModifiedFollowing, Date(3,February,2015), Period(1,Months), false, Date(3,March,2015)), SingleCase(SouthAfrica(), ModifiedFollowing, Date(3,February,2015), Period(4,Days), false, Date(9,February,2015)), SingleCase(SouthAfrica(), ModifiedFollowing, Date(31,January,2015), Period(1,Months), true, Date(27,February,2015)), SingleCase(SouthAfrica(), ModifiedFollowing, Date(31,January,2015), Period(1,Months), false, Date(27,February,2015)), SingleCase(SouthAfrica(), ModifiedFollowing, Date(25,March,2015), Period(1,Months), false, Date(28,April,2015)), SingleCase(SouthAfrica(), ModifiedFollowing, Date(7,February,2015), Period(1,Months), false, Date(9,March,2015)), //Preceding SingleCase(SouthAfrica(), Preceding, Date(3,March,2015), Period(-1,Months), false, Date(3,February,2015)), SingleCase(SouthAfrica(), Preceding, Date(3,February,2015), Period(-2,Days), false, Date(30,January,2015)), SingleCase(SouthAfrica(), Preceding, Date(1,March,2015), Period(-1,Months), true, Date(30,January,2015)), SingleCase(SouthAfrica(), Preceding, Date(1,March,2015), Period(-1,Months), false, Date(30,January,2015)), //ModifiedPreceding SingleCase(SouthAfrica(), ModifiedPreceding, Date(3,March,2015), Period(-1,Months), false, Date(3,February,2015)), SingleCase(SouthAfrica(), ModifiedPreceding, Date(3,February,2015), Period(-2,Days), false, Date(30,January,2015)), SingleCase(SouthAfrica(), ModifiedPreceding, Date(1,March,2015), Period(-1,Months), true, Date(2,February,2015)), SingleCase(SouthAfrica(), ModifiedPreceding, Date(1,March,2015), Period(-1,Months), false, Date(2,February,2015)), //Unadjusted SingleCase(SouthAfrica(), Unadjusted, Date(3,February,2015), Period(1,Months), false, Date(3,March,2015)), SingleCase(SouthAfrica(), Unadjusted, Date(3,February,2015), Period(4,Days), false, Date(9,February,2015)), SingleCase(SouthAfrica(), Unadjusted, Date(31,January,2015), Period(1,Months), true, Date(27,February,2015)), SingleCase(SouthAfrica(), Unadjusted, Date(31,January,2015), Period(1,Months), false, Date(28,February,2015)), //HalfMonthModifiedFollowing SingleCase(SouthAfrica(), HalfMonthModifiedFollowing, Date(3,February,2015), Period(1,Months), false, Date(3,March,2015)), SingleCase(SouthAfrica(), HalfMonthModifiedFollowing, Date(3,February,2015), Period(4,Days), false, Date(9,February,2015)), SingleCase(SouthAfrica(), HalfMonthModifiedFollowing, Date(31,January,2015), Period(1,Months), true, Date(27,February,2015)), SingleCase(SouthAfrica(), HalfMonthModifiedFollowing, Date(31,January,2015), Period(1,Months), false, Date(27,February,2015)), SingleCase(SouthAfrica(), HalfMonthModifiedFollowing, Date(3,January,2015), Period(1,Weeks), false, Date(12,January,2015)), SingleCase(SouthAfrica(), HalfMonthModifiedFollowing, Date(21,March,2015), Period(1,Weeks), false, Date(30,March,2015)), SingleCase(SouthAfrica(), HalfMonthModifiedFollowing, Date(7,February,2015), Period(1,Months), false, Date(9,March,2015)), //Nearest SingleCase(SouthAfrica(), Nearest, Date(3,February,2015), Period(1,Months), false, Date(3,March,2015)), SingleCase(SouthAfrica(), Nearest, Date(3,February,2015), Period(4,Days), false, Date(9,February,2015)), SingleCase(SouthAfrica(), Nearest, Date(16,April,2015), Period(1,Months), false, Date(15,May,2015)), SingleCase(SouthAfrica(), Nearest, Date(17,April,2015), Period(1,Months), false, Date(18,May,2015)), SingleCase(SouthAfrica(), Nearest, Date(4,March,2015), Period(1,Months), false, Date(2,April,2015)), SingleCase(SouthAfrica(), Nearest, Date(2,April,2015), Period(1,Months), false, Date(4,May,2015)) }; Size n = sizeof(testCases)/sizeof(SingleCase); for (Size i=0; i<n; i++) { Calendar calendar(testCases[i].calendar); Date result = calendar.advance( testCases[i].start, testCases[i].period, testCases[i].convention, testCases[i].endOfMonth); BOOST_CHECK_MESSAGE(result == testCases[i].result, "\ncase " << i << ":\n" //<< j << " ("<< desc << "): " << "start date: " << testCases[i].start << "\n" << "calendar: " << calendar << "\n" << "period: " << testCases[i].period << ", end of month: " << testCases[i].endOfMonth << "\n" << "convention: " << testCases[i].convention << "\n" << "expected: " << testCases[i].result << " vs. actual: " << result); } } test_suite* BusinessDayConventionTest::suite() { test_suite* suite = BOOST_TEST_SUITE("Business day convention tests"); suite->add(QUANTLIB_TEST_CASE(&BusinessDayConventionTest::testConventions)); return suite; }
56.098485
134
0.669413
urgu00
815725f6f0c76658b1c9bbb9f3e517267dd67b44
511
cpp
C++
SVEngine/src/detect/SVDetectBase.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
34
2018-09-28T08:28:27.000Z
2022-01-15T10:31:41.000Z
SVEngine/src/detect/SVDetectBase.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
null
null
null
SVEngine/src/detect/SVDetectBase.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
8
2018-10-11T13:36:35.000Z
2021-04-01T09:29:34.000Z
// // SVDetectBase.cpp // SVEngine // Copyright 2017-2020 // yizhou Fu,long Yin,longfei Lin,ziyu Xu,xiaofan Li,daming Li // #include "SVDetectBase.h" #include "SVPerson.h" SVDetectBase::SVDetectBase(SVInst *_app) :SVListenBase(_app) { } SVDetectBase::~SVDetectBase() { } void SVDetectBase::update(f32 _dt){ } void SVDetectBase::pushData(void *_faceData){ } s32 SVDetectBase::transformIndex(s32 index) { return 0; } BINDREGION SVDetectBase::getIndexRegion(s32 index) { return BD_REGION_CENTER; }
15.96875
62
0.729941
SVEChina
81574bf0f3315137e96cd4ee2f8a710ec6d6aadc
5,343
cpp
C++
P1/software/fuentes/localSearch2.cpp
dcabezas98/MH
98ced0552d6736004225aaafb5facd385a9a28d2
[ "MIT" ]
1
2021-07-18T16:33:12.000Z
2021-07-18T16:33:12.000Z
P1/software/fuentes/localSearch2.cpp
dcabezas98/MH
98ced0552d6736004225aaafb5facd385a9a28d2
[ "MIT" ]
null
null
null
P1/software/fuentes/localSearch2.cpp
dcabezas98/MH
98ced0552d6736004225aaafb5facd385a9a28d2
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <unordered_set> #include <stdlib.h> // srand y rand #include <algorithm> // advance #include <time.h> using namespace std; int CALLS=0; // Llamadas a evaluación const int LIMIT=100000; // Límite de evaluaciones // Lee la entrada y la almacena en una matriz void readInput (vector<vector<double>> &mat) { unsigned i, j; double f; int s = mat.size(); int iter = s*(s-1)/2; for (int k=0; k<iter; k++) { cin >> i >> j >> f; mat[i][j] = mat[j][i] = f; } } /********** Evaluación ***************/ // Contribución de un elemento double singleContribution(unordered_set<int> &solution, vector<vector<double> > &mat, int elem) { double result = 0; unordered_set<int>::iterator it; for (it = solution.begin(); it != solution.end(); it++) { result += mat[ elem ][ *it ]; } return result; } // Variedad de una solución double evaluateSolution(unordered_set<int> &solution, vector<vector<double> > &mat) { double fitness = 0; unordered_set<int>::iterator it; for (it = solution.begin(); it != solution.end(); it++) { fitness += singleContribution(solution, mat, *it); } return fitness /= 2; // Las cuenta doble } /******************* Local Search ********************/ // Más lejano a los seleccionados (de los que quedan por elegir) int farthestToSel(unordered_set<int> &non_selected, unordered_set<int> &selected, vector<vector<double> > &mat) { int farthest; double max_sum_dist, current_sum_dist; unordered_set<int>::iterator it; it = non_selected.begin(); farthest = *it; max_sum_dist = singleContribution(selected, mat, farthest); for ( ; it!=non_selected.end(); it++) { current_sum_dist = singleContribution(selected, mat, *it); // Suma distancias del elemento a los seleccionados if (current_sum_dist > max_sum_dist) { // Si la suma es mayor, lo reemplaza max_sum_dist = current_sum_dist; farthest = *it; } } return farthest; } // Genera solución aleatoria unordered_set<int> randomSol(unsigned m, unsigned n, unordered_set<int> &complement){ int elem,rnd; unordered_set<int> selected; unordered_set<int> elements; for (unsigned i=0; i<n; i++) { elements.insert(i); } unordered_set<int>::iterator it; while (selected.size()<m){ rnd=rand()%elements.size(); // Elijo un número aleatorio it=elements.begin(); advance(it,rnd); // Selecciono el elemento correspondiente elem=*it; elements.erase( elem ); selected.insert( elem ); } complement=elements; // Elementos que no están en la solución return selected; } int lowestContributor(unordered_set<int> &solution, vector<vector<double> > &mat, double &min_contrib){ int lowest; double current_contrib; unordered_set<int>::iterator it; it = solution.begin(); lowest = *it; min_contrib = singleContribution(solution, mat, lowest); it++; for ( ; it!=solution.end(); it++) { current_contrib = singleContribution(solution, mat, *it); // Suma distancias del elemento a los seleccionados if (current_contrib < min_contrib) { // Si la suma es menor, lo reemplaza min_contrib = current_contrib; lowest = *it; } } return lowest; } // random generator function: int rndGen (int i) { return rand()%i;} void localSearch(vector<vector<double> > &mat, unsigned m) { clock_t t_start, t_total; t_start = clock(); unordered_set<int> non_selected; // Elementos no seleccionados unordered_set<int> solution = randomSol(m,mat.size(), non_selected); double diversity=evaluateSolution(solution, mat); vector<int>::iterator it; // Para iterar sobre los candidatos int lowest, best_candidate; double contrib, min_contrib; bool carryon = true; while (carryon && CALLS < LIMIT){ carryon=false; lowest=lowestContributor(solution, mat, min_contrib); // Menor contribuyente solution.erase(lowest); // Lo elimino best_candidate = farthestToSel(non_selected, solution,mat); // Candidato más lejano a los seleccionados CALLS+=non_selected.size(); // Elije la mejor entre todas estas soluciones contrib = singleContribution(solution, mat, best_candidate); if (contrib > min_contrib){ // Si encuentra una mejor en el entorno, se actualiza y continúa diversity = diversity + contrib - min_contrib; // Modificamos diversidad (sólo el factor que cambia) carryon=true; solution.insert(best_candidate); // Insertamos el candidato non_selected.erase(best_candidate); // Lo borramos de la lista de candidatos non_selected.insert(lowest); // Ahora el menor contribuyente es un candidato más } } /* if (solution.size() < m) solution.insert(lowest); // Si no se encontró uno mejor, recuperamos la solución */ t_total = clock() - t_start; // output: Diversidad - Tiempo cout << diversity << "\t" << (double) t_total / CLOCKS_PER_SEC << "\t" << CALLS << endl; } /******************* MAIN **********************/ int main( int argc, char *argv[] ) { int n, m; cin >> n >> m; // Leemos los parámetros n y m vector<double> v (n, 0); // Vector de ceros con n componentes vector<vector<double > > mat (n, v); // Matriz de nxn ceros readInput(mat); // Leemos la entrada cout << fixed; srand(stoi(argv[1])); // SEED as parameter localSearch(mat, m); }
30.357955
114
0.664982
dcabezas98
8158b3b9570f392bc42ac6e73e216775910e2b5c
38,558
hpp
C++
include/pstore/core/hamt_map_types.hpp
paulhuggett/pstore
067be94d87c87fce524c8d76c6f47c347d8f1853
[ "Apache-2.0" ]
null
null
null
include/pstore/core/hamt_map_types.hpp
paulhuggett/pstore
067be94d87c87fce524c8d76c6f47c347d8f1853
[ "Apache-2.0" ]
1
2021-03-09T21:33:38.000Z
2021-03-09T21:33:38.000Z
include/pstore/core/hamt_map_types.hpp
paulhuggett/pstore
067be94d87c87fce524c8d76c6f47c347d8f1853
[ "Apache-2.0" ]
null
null
null
//===- include/pstore/core/hamt_map_types.hpp -------------*- mode: C++ -*-===// //* _ _ _ * //* | |__ __ _ _ __ ___ | |_ _ __ ___ __ _ _ __ | |_ _ _ _ __ ___ ___ * //* | '_ \ / _` | '_ ` _ \| __| | '_ ` _ \ / _` | '_ \ | __| | | | '_ \ / _ \/ __| * //* | | | | (_| | | | | | | |_ | | | | | | (_| | |_) | | |_| |_| | |_) | __/\__ \ * //* |_| |_|\__,_|_| |_| |_|\__| |_| |_| |_|\__,_| .__/ \__|\__, | .__/ \___||___/ * //* |_| |___/|_| * //===----------------------------------------------------------------------===// // // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions. // See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license // information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// /// \file hamt_map_types.hpp #ifndef PSTORE_CORE_HAMT_MAP_TYPES_HPP #define PSTORE_CORE_HAMT_MAP_TYPES_HPP #include "pstore/adt/chunked_sequence.hpp" #include "pstore/core/array_stack.hpp" #include "pstore/core/db_archive.hpp" namespace pstore { class transaction_base; namespace index { namespace details { using hash_type = std::uint64_t; /// The number of bits in hash_type. This is the maximum number of children that an /// internal-node can carry. constexpr auto const hash_size = sizeof (hash_type) * 8; #ifdef _MSC_VER // TODO: VC2015RC won't allow pop_count to be constexpr. Sigh. This forces a (very // crude) population count implementation namespace details_count { constexpr inline unsigned bit_set (std::size_t v, unsigned bit) { return (v & (std::size_t{1} << bit)) >> bit; } constexpr inline unsigned crude_pop_count (std::size_t v) { return bit_set (v, 0x00) + bit_set (v, 0x01) + bit_set (v, 0x02) + bit_set (v, 0x03) + bit_set (v, 0x04) + bit_set (v, 0x05) + bit_set (v, 0x06) + bit_set (v, 0x07) + bit_set (v, 0x08) + bit_set (v, 0x09) + bit_set (v, 0x0A) + bit_set (v, 0x0B) + bit_set (v, 0x0C) + bit_set (v, 0x0D) + bit_set (v, 0x0E) + bit_set (v, 0x0F); } } // namespace details_count constexpr unsigned hash_index_bits = details_count::crude_pop_count (hash_size - 1); #else /// The number of bits that it takes to represent hash_size. constexpr unsigned hash_index_bits = bit_count::pop_count (hash_size - 1); #endif constexpr unsigned max_hash_bits = (hash_size + 7) / hash_index_bits * hash_index_bits; constexpr unsigned hash_index_mask = (1U << hash_index_bits) - 1U; constexpr unsigned max_internal_depth = max_hash_bits / hash_index_bits; /// The max depth of the hash trees include several levels internal nodes /// (max_internal_depth), one linear node and one leaf node. constexpr unsigned max_tree_depth = max_internal_depth + 2U; /// Using LSB for marking internal nodes constexpr std::uintptr_t internal_node_bit = 1; /// Using second LSB for marking newly allocated internal nodes constexpr std::uintptr_t heap_node_bit = 2; } // end namespace details //* _ _ _ _ _ * //* | |_ ___ __ _ __| |___ _ _ | |__| |___ __| |__ * //* | ' \/ -_) _` / _` / -_) '_| | '_ \ / _ \/ _| / / * //* |_||_\___\__,_\__,_\___|_| |_.__/_\___/\__|_\_\ * //* * /// The address of an instance of this type is passed to the hamt_map ctor to load an /// existing index, and it is returned by a call to hamt_map::flush(). struct header_block { std::array<std::uint8_t, 8> signature; /// The number of keys stored in the tree. std::uint64_t size; /// The store address of the tree's root node. address root; }; PSTORE_STATIC_ASSERT (sizeof (header_block) == 24); PSTORE_STATIC_ASSERT (offsetof (header_block, signature) == 0); PSTORE_STATIC_ASSERT (offsetof (header_block, size) == 8); PSTORE_STATIC_ASSERT (offsetof (header_block, root) == 16); namespace details { std::size_t const not_found = std::numeric_limits<std::size_t>::max (); class internal_node; class linear_node; constexpr bool depth_is_internal_node (unsigned const shift) noexcept { return shift < details::max_hash_bits; } struct nchildren { std::size_t n; }; //* _ _ _ _ * //* (_)_ _ __| |_____ __ _ __ ___(_)_ _| |_ ___ _ _ * //* | | ' \/ _` / -_) \ / | '_ \/ _ \ | ' \ _/ -_) '_| * //* |_|_||_\__,_\___/_\_\ | .__/\___/_|_||_\__\___|_| * //* |_| * /// An index pointer is either a database address or a pointer to volatile RAM. /// The type information (which of the two fields applies) is carried externally. union index_pointer { index_pointer () noexcept : internal{nullptr} {} explicit index_pointer (address const a) noexcept : addr (a) {} explicit index_pointer (typed_address<internal_node> const a) noexcept : addr (a.to_address ()) {} explicit index_pointer (typed_address<linear_node> const a) noexcept : addr (a.to_address ()) {} explicit index_pointer (internal_node * const p) noexcept : internal{tag_node (p)} {} explicit index_pointer (linear_node * const p) noexcept : linear{tag_node (p)} {} index_pointer (index_pointer const &) noexcept = default; index_pointer (index_pointer &&) noexcept = default; index_pointer & operator= (index_pointer const &) = default; index_pointer & operator= (index_pointer &&) noexcept = default; index_pointer & operator= (address const & a) noexcept { addr = a; return *this; } index_pointer & operator= (typed_address<internal_node> const & a) noexcept { addr = a.to_address (); return *this; } index_pointer & operator= (typed_address<linear_node> const & a) noexcept { addr = a.to_address (); return *this; } index_pointer & operator= (internal_node * const p) noexcept { internal = tag_node (p); return *this; } index_pointer & operator= (linear_node * const l) noexcept { linear = tag_node (l); return *this; } bool operator== (index_pointer const & other) const noexcept { return addr == other.addr; } bool operator!= (index_pointer const & other) const noexcept { return !operator== (other); } explicit operator bool () const noexcept { return !this->is_empty (); } /// Returns true if the index_pointer is pointing to an internal node, false /// otherwise. /// \sa is_leaf bool is_internal () const noexcept { return (reinterpret_cast<std::uintptr_t> (internal) & internal_node_bit) != 0; } /// Returns true if the index_pointer is pointing to a linear node, false otherwise. /// \sa is_leaf /// \note A linear node is always found at max_internal_depth. This function will /// return true for internal nodes at lower tree levels. bool is_linear () const noexcept { return is_internal (); } /// Returns true if the index_pointer is pointing to a value address in the store, /// false otherwise. /// \sa is_internal bool is_leaf () const noexcept { return !is_internal (); } /// Returns true if the index_pointer is pointing to a heap node, false otherwise. /// \sa is_addr bool is_heap () const noexcept { return (reinterpret_cast<std::uintptr_t> (internal) & heap_node_bit) != 0; } /// Returns true if the index_pointer is pointing to a store node, false otherwise. /// \sa is_heap bool is_address () const noexcept { return !is_heap (); } bool is_empty () const noexcept { return internal == nullptr; } template <typename T> T tag_node () const noexcept { return reinterpret_cast<T> (tag ()); } template <typename T> T untag_node () const noexcept { return reinterpret_cast<T> (untag ()); } typed_address<internal_node> untag_internal_address () const noexcept { return typed_address<internal_node>::make (addr.absolute () & ~internal_node_bit); } typed_address<linear_node> untag_linear_address () const noexcept { return typed_address<linear_node>::make (addr.absolute () & ~internal_node_bit); } address addr; internal_node * internal; linear_node * linear; private: static std::uintptr_t tag (void * const p) noexcept { return reinterpret_cast<std::uintptr_t> (p) | internal_node_bit | heap_node_bit; } std::uintptr_t tag () const noexcept { return tag (internal); } static internal_node * tag_node (internal_node * const p) noexcept { return reinterpret_cast<internal_node *> (tag (p)); } static linear_node * tag_node (linear_node * const p) noexcept { return reinterpret_cast<linear_node *> (tag (p)); } std::uintptr_t untag () const noexcept { return reinterpret_cast<std::uintptr_t> (internal) & ~internal_node_bit & ~heap_node_bit; } }; PSTORE_STATIC_ASSERT (sizeof (index_pointer) == 8); PSTORE_STATIC_ASSERT (alignof (index_pointer) == 8); PSTORE_STATIC_ASSERT (offsetof (index_pointer, addr) == 0); PSTORE_STATIC_ASSERT (sizeof (index_pointer::internal) == sizeof (index_pointer::addr)); PSTORE_STATIC_ASSERT (offsetof (index_pointer, internal) == 0); PSTORE_STATIC_ASSERT (sizeof (index_pointer::linear) == sizeof (index_pointer::addr)); PSTORE_STATIC_ASSERT (offsetof (index_pointer, linear) == 0); //* _ _ * //* _ __ __ _ _ _ ___ _ _| |_ | |_ _ _ _ __ ___ * //* | '_ \/ _` | '_/ -_) ' \ _| | _| || | '_ \/ -_) * //* | .__/\__,_|_| \___|_||_\__| \__|\_, | .__/\___| * //* |_| |__/|_| * /// \brief A class used to keep the pointer to parent node and the child slot. class parent_type { public: parent_type () = default; /// Constructs a parent type object. /// \param idx The pointer to either the parent node or a leaf node. /// \param pos If idx is a leaf node address, pos is set to the default value /// (not_found). Otherwise, pos refers to the child slot. parent_type (index_pointer const idx, std::size_t const pos = not_found) noexcept : node (idx) , position (pos) {} bool operator== (parent_type const & other) const { return position == other.position && node == other.node; } bool operator!= (parent_type const & other) const { return !operator== (other); } index_pointer node; std::size_t position = 0; }; using parent_stack = array_stack<parent_type, max_tree_depth>; //* _ _ _ * //* | (_)_ _ ___ __ _ _ _ _ _ ___ __| |___ * //* | | | ' \/ -_) _` | '_| | ' \/ _ \/ _` / -_) * //* |_|_|_||_\___\__,_|_| |_||_\___/\__,_\___| * //* * /// \brief A linear node. /// Linear nodes as used as the place of last resort for entries which cannot be /// distinguished by their hash value. class linear_node { public: using iterator = address *; using const_iterator = address const *; void * operator new (std::size_t) = delete; void operator delete (void * p); ~linear_node () noexcept = default; linear_node & operator= (linear_node const & rhs) = delete; linear_node & operator= (linear_node && rhs) = delete; /// \name Construction ///@{ /// \brief Allocates a new linear node in memory and copy the contents of an /// existing node into it. The new node is allocated with sufficient storage for the /// child of the supplied node plus the number passed in the 'extra_children' /// parameter. /// /// \param orig_node A node whose contents will be copied into the newly allocated /// linear node. /// \param extra_children The number of extra child for which space will be /// allocated. This number is added to the number of children in 'orig_node' in /// calculating the amount of storage to be allocated. /// \result A pointer to the newly allocated linear node. static std::unique_ptr<linear_node> allocate_from (linear_node const & orig_node, std::size_t extra_children); /// \brief Allocates a new in-memory linear node based on the contents of an /// existing store node. /// /// \param db The database from which the source node should be loaded. /// \param node A reference to the source node which may be either in-heap or /// in-store. /// \param extra_children The number of additional child nodes for which storage /// should be allocated. /// \result A pointer to the newly allocated linear node. static std::unique_ptr<linear_node> allocate_from (database const & db, index_pointer const node, std::size_t extra_children); /// \brief Allocates a new linear node in memory with sufficient space for two leaf /// addresses. /// /// \param a The first leaf address for the new linear node. /// \param b The second leaf address for the new linear node. /// \result A pointer to the newly allocated linear node. static std::unique_ptr<linear_node> allocate (address a, address b); /// \brief Returns a pointer to a linear node which may be in-heap or in-store. /// /// If the supplied index_pointer points to a heap-resident linear node then returns /// a pair whose first member is nullptr and whose second member contains the node /// pointer. If the index_pointer references an in-store linear node then the node /// is fetched and the function returns a pair whose first member is the store's /// shared_ptr and whose second member is the equivalent raw pointer (i.e. /// result.first.get () == result.second). In this case, the second pointer is only /// valid as long as the first pointer is "live". /// /// \param db The database from which the node should be loaded. /// \param node A pointer to the node location: either in the heap or in the store. /// \result A pair holding a pointer to the node in-store memory (if necessary) and /// its raw pointer. static auto get_node (database const & db, index_pointer const node) -> std::pair<std::shared_ptr<linear_node const>, linear_node const *>; ///@} /// \name Element access ///@{ address operator[] (std::size_t const i) const noexcept { PSTORE_ASSERT (i < size_); return leaves_[i]; } address & operator[] (std::size_t const i) noexcept { PSTORE_ASSERT (i < size_); return leaves_[i]; } ///@} /// \name Iterators ///@{ iterator begin () { return leaves_; } const_iterator begin () const { return leaves_; } const_iterator cbegin () const { return this->begin (); } iterator end () { return leaves_ + size_; } const_iterator end () const { return leaves_ + size_; } const_iterator cend () const { return this->end (); } ///@} /// \name Capacity ///@{ /// Checks whether the container is empty. bool empty () const { return size_ == 0; } /// Returns the number of elements. std::size_t size () const { return size_; } ///@} /// \name Storage ///@{ /// Returns the number of bytes of storage required for the node. std::size_t size_bytes () const { return linear_node::size_bytes (this->size ()); } /// Returns the number of bytes of storage required for a linear node with 'size' /// children. static constexpr std::size_t size_bytes (std::uint64_t const size) { return sizeof (linear_node) - sizeof (linear_node::leaves_) + sizeof (linear_node::leaves_[0]) * size; } ///@} /// Write this linear node to the store. /// /// \param transaction The transaction to which the linear node will be appended. /// \result The address at which the node was written. address flush (transaction_base & transaction) const; /// Search the linear node and return the child slot if the key exists. /// Otherwise, return the {nullptr, not_found} pair. /// \tparam KeyType The type of the keys stored in the linear node. /// \tparam OtherKeyType A type whose serialized value is compatible with KeyType /// \tparam KeyEqual The type of the key-comparison function. /// \param db The dataase instance from which child nodes should be loaded. /// \param key The key to be located. /// \param equal A comparison function which will be called to compare child nodes /// to the supplied key value. It should return true if the keys match and false /// otherwise. /// \result If found, returns an `index_pointer` reference to the child node and the /// position within the linear node instance of the child record. If not found, /// returns the pair index_pointer (), details::not_found. template <typename KeyType, typename OtherKeyType, typename KeyEqual, typename = typename std::enable_if< serialize::is_compatible<KeyType, OtherKeyType>::value>::type> auto lookup (database const & db, OtherKeyType const & key, KeyEqual equal) const -> std::pair<index_pointer const, std::size_t>; private: using signature_type = std::array<std::uint8_t, 8>; static signature_type const node_signature_; /// A placement-new implementation which allocates sufficient storage for a linear /// node with the number of children given by the size parameter. void * operator new (std::size_t s, nchildren size); // Non-allocating placement allocation functions. void * operator new (std::size_t const size, void * const ptr) noexcept { return ::operator new (size, ptr); } void operator delete (void * p, nchildren size); void operator delete (void * const p, void * const ptr) noexcept { ::operator delete (p, ptr); } /// \param size The capacity of this linear node. explicit linear_node (std::size_t size); linear_node (linear_node const & rhs); linear_node (linear_node && rhs) = delete; /// Allocates a new linear node in memory. /// /// \param num_children Sufficient space is allocated for the number of child nodes /// specified in this parameter. /// \param from_node A node whose contents will be copied into the new node. If the /// number of children requested is greater than the number of children in /// from_node, the remaining entries are zeroed; if less then the child node /// collection is truncated after the specified number of entries. /// \result A pointer to the newly allocated linear node. static std::unique_ptr<linear_node> allocate (std::size_t num_children, linear_node const & from_node); signature_type signature_ = node_signature_; std::uint64_t size_; address leaves_[1]; }; // lookup // ~~~~~~ template <typename KeyType, typename OtherKeyType, typename KeyEqual, typename> auto linear_node::lookup (database const & db, OtherKeyType const & key, KeyEqual equal) const -> std::pair<index_pointer const, std::size_t> { // Linear search. TODO: perhaps we should sort the nodes and use a binary // search? This would require a template compare method. std::size_t cnum = 0; for (auto const & child : *this) { KeyType const existing_key = serialize::read<KeyType> (serialize::archive::database_reader{db, child}); if (equal (existing_key, key)) { return {index_pointer{child}, cnum}; } ++cnum; } // Not found return {index_pointer (), details::not_found}; } //* _ _ _ _ * //* (_)_ _| |_ ___ _ _ _ _ __ _| | ___ ___ __| |___ * //* | | ' \ _/ -_) '_| ' \/ _` | | | \/ _ \/ _` / -_) * //* |_|_||_\__\___|_| |_||_\__,_|_| |_|\_\___/\__,_\___| * //* * /// An internal trie node. class internal_node { public: using iterator = index_pointer *; using const_iterator = index_pointer const *; /// Construct an internal node with a child. internal_node (index_pointer const & leaf, hash_type hash); /// Construct the internal node with two children. internal_node (index_pointer const & existing_leaf, index_pointer const & new_leaf, hash_type existing_hash, hash_type new_hash); internal_node (internal_node const & rhs); internal_node (internal_node && rhs) = delete; ~internal_node () noexcept = default; internal_node & operator= (internal_node const & rhs) = delete; internal_node & operator= (internal_node && rhs) = delete; /// Construct an internal node from existing internal-node instance. This may be /// used, for example, when copying an in-store node into memory in preparation for /// modifying it. /// /// \tparam SequenceContainer A container of internal_node instances which supports /// emplace_back(). /// \param container Points to the container which will own the new internal node /// instance. /// \param other A existing internal_node whose contents are copied into the newly /// allocated instance. /// \returns A new instance of internal_node which is owned by *container. template <typename SequenceContainer, typename = typename std::enable_if<std::is_same< typename SequenceContainer::value_type, internal_node>::value>::type> static internal_node * allocate (SequenceContainer * const container, internal_node const & other) { container->emplace_back (other); // TODO: in C++17 we can use the emplace_back return value. return &container->back (); } /// Construct an internal node with a single child. /// /// \tparam SequenceContainer A container of internal_node instances which supports /// emplace_back(). /// \param container Points to the container which will own the new internal node /// instance. /// \param leaf The child of the newly allocated internal node. /// \param hash The hash associated with the child node. /// \returns A new instance of internal_node which is owned by *container. template <typename SequenceContainer, typename = typename std::enable_if<std::is_same< typename SequenceContainer::value_type, internal_node>::value>::type> static internal_node * allocate (SequenceContainer * container, index_pointer const & leaf, hash_type const hash) { container->emplace_back (leaf, hash); // TODO: in C++17 we can use the emplace_back return value. return &container->back (); } /// Construct an internal node with two children. /// /// \tparam SequenceContainer A container of internal_node instances which supports /// emplace_back(). /// \param container Points to the container which will own the new internal node /// instance. /// \param existing_leaf One of the two child nodes of the new internal node. /// \param new_leaf One of the two child nodes of the new internal node. /// \param existing_hash The hash associated with the \p existing_leaf node. /// \param new_hash The hash associated with the \p new_leaf node. /// \returns A new instance of internal_node which is owned by *container. template <typename SequenceContainer, typename = typename std::enable_if<std::is_same< typename SequenceContainer::value_type, internal_node>::value>::type> static internal_node * allocate (SequenceContainer * container, index_pointer const & existing_leaf, index_pointer const & new_leaf, hash_type const existing_hash, hash_type const new_hash) { container->emplace_back (existing_leaf, new_leaf, existing_hash, new_hash); // TODO: in C++17 we can use the emplace_back return value. return &container->back (); } /// Return a pointer to an internal node. If the node is in-store, it is loaded and /// the internal heap node pointer if \p node is a heap internal node. /// Otherwise return the pointer which is pointed to the store node. /// /// \param db The database containing the node. /// \param node The node's location: either in-store or in-heap. /// \return A pair of which the first element is a in-store pointer to the node /// body. This may be null if called on a heap-resident node. The second element is /// the raw node pointer, that is, the address of a heap node or the result of /// calling .get() on the store-pointer. static auto get_node (database const & db, index_pointer const node) -> std::pair<std::shared_ptr<internal_node const>, internal_node const *>; /// Load an internal node from the store. static auto read_node (database const & db, typed_address<internal_node> const addr) -> std::shared_ptr<internal_node const>; /// Returns a writable reference to an internal node. If the \p node parameter /// references an in-heap node, then this pointer is returned otherwise a copy of /// the \p internal parameter is placed in heap-allocated memory. /// /// \note It is expected that both \p node and \p internal are references to the /// same node. /// /// \tparam SequenceContainer A container of internal_node instances which supports /// emplace_back(). /// \param container Points to the container which will own the new internal node /// instance. /// \param node A reference to an internal node. This may be either in-store on the /// heap. If on the heap the returned value is the underlying pointer. /// \param internal A read-only instance of an internal node. If the \p node /// parameter is in-store then a copy of this value is placed on the heap. /// \result See above. template <typename SequenceContainer, typename = typename std::enable_if<std::is_same< typename SequenceContainer::value_type, internal_node>::value>::type> static internal_node * make_writable (SequenceContainer * const container, index_pointer const node, internal_node const & internal) { if (node.is_heap ()) { internal_node * const inode = node.untag_node<internal_node *> (); PSTORE_ASSERT (inode->signature_ == node_signature_); return inode; } return allocate (container, internal); } /// Returns the number of bytes occupied by an in-store internal node with the given /// number of child nodes. Note that the storage occupied by an in-heap internal /// node with the same number of children may be greater. /// /// \param num_children The number of children to assume for the purpose of /// computing the number of bytes occupied. /// \return The number of bytes occupied by an in-store internal node with the given /// number of child nodes. static constexpr std::size_t size_bytes (std::size_t const num_children) noexcept { PSTORE_ASSERT (num_children > 0 && num_children <= hash_size); return sizeof (internal_node) - sizeof (internal_node::children_) + sizeof (decltype (internal_node::children_[0])) * num_children; } /// Returns the number of children contained by this node. unsigned size () const noexcept { PSTORE_ASSERT (this->bitmap_ != hash_type{0}); return bit_count::pop_count (this->bitmap_); } /// Return the new leaf child index number. static unsigned get_new_index (hash_type const new_hash, hash_type const existing_hash) noexcept { return static_cast<unsigned> (new_hash >= existing_hash); } std::pair<index_pointer, std::size_t> lookup (hash_type hash_index) const; /// Insert a child into the internal node (this). void insert_child (hash_type const hash, index_pointer const leaf, gsl::not_null<parent_stack *> parents); /// Write an internal node and its children into a store. address flush (transaction_base & transaction, unsigned shifts); index_pointer const & operator[] (std::size_t const i) const { PSTORE_ASSERT (i < size ()); return children_[i]; } index_pointer & operator[] (std::size_t const i) { PSTORE_ASSERT (i < size ()); return children_[i]; } hash_type get_bitmap () const noexcept { return bitmap_; } /// A function for deliberately creating illegal internal nodes in the unit test. DO /// NOT USE except for that purpose! void set_bitmap (hash_type const bm) noexcept { bitmap_ = bm; } /// \name Iterators ///@{ iterator begin () noexcept { return &children_[0]; } const_iterator begin () const { return &children_[0]; } const_iterator cbegin () const { return &children_[0]; } iterator end () noexcept { return this->begin () + this->size (); } const_iterator end () const { return this->begin () + this->size (); } const_iterator cend () const { return this->cbegin () + this->size (); } ///@} private: static bool validate_after_load (internal_node const & internal, typed_address<internal_node> const addr); /// Appends the internal node (which refers to a node in heap memory) to the /// store. Returns a new (in-store) internal store address. address store_node (transaction_base & transaction) const; using signature_type = std::array<std::uint8_t, 8>; static signature_type const node_signature_; /// A magic number for internal nodes in the store. Acts as a quick integrity test /// for the index structures. signature_type signature_ = node_signature_; /// For each index in the children array, the corresponding bit is set in this field /// if it is a reference to an internal node or an leaf node. In a linear node, the /// bitmap field contains the number of elements in the array. hash_type bitmap_ = 0; /// \brief The array of child node references. /// Each child may be in-memory or in-store. index_pointer children_[1U]; }; // lookup // ~~~~~~ inline auto internal_node::lookup (hash_type const hash_index) const -> std::pair<index_pointer, std::size_t> { PSTORE_ASSERT (hash_index < (hash_type{1} << hash_index_bits)); auto const bit_pos = hash_type{1} << hash_index; if ((bitmap_ & bit_pos) != 0) { //! OCLINT(PH - bitwise in conditional is ok) std::size_t const index = bit_count::pop_count (bitmap_ & (bit_pos - 1U)); return {children_[index], index}; } return {index_pointer{}, not_found}; } } // namespace details } // namespace index } // namespace pstore #endif // PSTORE_CORE_HAMT_MAP_TYPES_HPP
52.891632
100
0.518595
paulhuggett
815973aaedb1c5e015b94190a9004f77c1fa976e
15,111
cc
C++
be/src/formats/orc/apache-orc/c++/src/RleDecoderV2.cc
sparklezzz/starrocks
d445118c07a84ffa4e76efd2fd40a069b6a6423d
[ "ECL-2.0", "Zlib", "Apache-2.0", "MIT" ]
2,519
2021-09-08T01:41:12.000Z
2022-03-31T17:14:29.000Z
be/src/formats/orc/apache-orc/c++/src/RleDecoderV2.cc
sparklezzz/starrocks
d445118c07a84ffa4e76efd2fd40a069b6a6423d
[ "ECL-2.0", "Zlib", "Apache-2.0", "MIT" ]
2,671
2021-09-08T01:43:45.000Z
2022-03-31T23:45:52.000Z
be/src/formats/orc/apache-orc/c++/src/RleDecoderV2.cc
rickif/starrocks
94af746ec83cc1260e15dc1f5295e7b014c96598
[ "BSD-3-Clause-Clear", "Zlib", "PSF-2.0", "Apache-2.0" ]
499
2021-09-08T01:43:54.000Z
2022-03-31T07:14:17.000Z
// This file is made available under Elastic License 2.0. // This file is based on code available under the Apache license here: // https://github.com/apache/orc/tree/main/c++/src/RleDecoderV2.cc /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Adaptor.hh" #include "Compression.hh" #include "RLEV2Util.hh" #include "RLEv2.hh" namespace orc { int64_t RleDecoderV2::readLongBE(uint64_t bsz) { int64_t ret = 0, val; uint64_t n = bsz; while (n > 0) { n--; val = readByte(); ret |= (val << (n * 8)); } return ret; } inline int64_t RleDecoderV2::readVslong() { return unZigZag(readVulong()); } uint64_t RleDecoderV2::readVulong() { uint64_t ret = 0, b; uint64_t offset = 0; do { b = readByte(); ret |= (0x7f & b) << offset; offset += 7; } while (b >= 0x80); return ret; } RleDecoderV2::RleDecoderV2(std::unique_ptr<SeekableInputStream> input, bool _isSigned, MemoryPool& pool, DataBuffer<char>* _sharedBufferPtr) : inputStream(std::move(input)), isSigned(_isSigned), firstByte(0), runLength(0), runRead(0), bufferStart(nullptr), bufferEnd(bufferStart), deltaBase(0), byteSize(0), firstValue(0), prevValue(0), bitSize(0), bitsLeft(0), curByte(0), patchBitSize(0), unpackedIdx(0), patchIdx(0), base(0), curGap(0), curPatch(0), patchMask(0), actualGap(0), unpacked(pool, 0), unpackedPatch(pool, 0), direct(pool, 0), sharedBuffer(pool, 0) { // PASS if (_sharedBufferPtr != nullptr) { sharedBufferPtr = _sharedBufferPtr; } } void RleDecoderV2::seek(PositionProvider& location) { // move the input stream inputStream->seek(location); // clear state bufferEnd = bufferStart = nullptr; runRead = runLength = 0; // skip ahead the given number of records skip(location.next()); } void RleDecoderV2::skip(uint64_t numValues) { // simple for now, until perf tests indicate something encoding specific is // needed const uint64_t N = 64; int64_t dummy[N]; while (numValues) { uint64_t nRead = std::min(N, numValues); next(dummy, nRead, nullptr); numValues -= nRead; } } void RleDecoderV2::next(int64_t* const data, const uint64_t numValues, const char* const notNull) { uint64_t nRead = 0; while (nRead < numValues) { // Skip any nulls before attempting to read first byte. while (notNull && !notNull[nRead]) { if (++nRead == numValues) { return; // ended with null values } } if (runRead == runLength) { resetRun(); firstByte = readByte(); } uint64_t offset = nRead, length = numValues - nRead; EncodingType enc = static_cast<EncodingType>((firstByte >> 6) & 0x03); switch (static_cast<int64_t>(enc)) { case SHORT_REPEAT: nRead += nextShortRepeats(data, offset, length, notNull); break; case DIRECT: nRead += nextDirect(data, offset, length, notNull); break; case PATCHED_BASE: nRead += nextPatched(data, offset, length, notNull); break; case DELTA: nRead += nextDelta(data, offset, length, notNull); break; default: throw ParseError("unknown encoding"); } } } uint64_t RleDecoderV2::nextShortRepeats(int64_t* const data, uint64_t offset, uint64_t numValues, const char* const notNull) { if (runRead == runLength) { // extract the number of fixed bytes byteSize = (firstByte >> 3) & 0x07; byteSize += 1; runLength = firstByte & 0x07; // run lengths values are stored only after MIN_REPEAT value is met runLength += MIN_REPEAT; runRead = 0; // read the repeated value which is store using fixed bytes firstValue = readLongBE(byteSize); if (isSigned) { firstValue = unZigZag(static_cast<uint64_t>(firstValue)); } } uint64_t nRead = std::min(runLength - runRead, numValues); if (notNull) { for (uint64_t pos = offset; pos < offset + nRead; ++pos) { if (notNull[pos]) { data[pos] = firstValue; ++runRead; } } } else { for (uint64_t pos = offset; pos < offset + nRead; ++pos) { data[pos] = firstValue; ++runRead; } } return nRead; } #define OPT_RLE_V2 #ifndef OPT_RLE_V2 uint64_t RleDecoderV2::nextDirect(int64_t* const data, uint64_t offset, uint64_t numValues, const char* const notNull) { if (runRead == runLength) { // extract the number of fixed bits unsigned char fbo = (firstByte >> 1) & 0x1f; bitSize = decodeBitWidth(fbo); // extract the run length runLength = static_cast<uint64_t>(firstByte & 0x01) << 8; runLength |= readByte(); // runs are one off runLength += 1; runRead = 0; } uint64_t nRead = std::min(runLength - runRead, numValues); runRead += readLongs(data, offset, nRead, bitSize, notNull); if (isSigned) { if (notNull) { for (uint64_t pos = offset; pos < offset + nRead; ++pos) { if (notNull[pos]) { data[pos] = unZigZag(static_cast<uint64_t>(data[pos])); } } } else { for (uint64_t pos = offset; pos < offset + nRead; ++pos) { data[pos] = unZigZag(static_cast<uint64_t>(data[pos])); } } } return nRead; } #else uint64_t RleDecoderV2::nextDirect(int64_t* const data, uint64_t offset, uint64_t numValues, const char* const notNull) { if (runRead == runLength) { // extract the number of fixed bits unsigned char fbo = (firstByte >> 1) & 0x1f; bitSize = decodeBitWidth(fbo); // extract the run length runLength = static_cast<uint64_t>(firstByte & 0x01) << 8; runLength |= readByte(); // runs are one off runLength += 1; runRead = 0; direct.reserve(runLength); readLongsFully(direct.data(), runLength, bitSize); directIdx = 0; } uint64_t nRead = std::min(runLength - runRead, numValues); if (isSigned) { if (notNull) { for (uint64_t pos = offset; pos < offset + nRead; ++pos) { if (notNull[pos]) { data[pos] = unZigZag(static_cast<uint64_t>(direct[directIdx])); directIdx++; runRead++; } } } else { runRead += nRead; for (uint64_t pos = offset; pos < offset + nRead; ++pos) { data[pos] = unZigZag(static_cast<uint64_t>(direct[directIdx])); directIdx++; } } } else { if (notNull) { for (uint64_t pos = offset; pos < offset + nRead; ++pos) { if (notNull[pos]) { data[pos] = direct[directIdx]; directIdx++; runRead++; } } } else { runRead += nRead; memcpy(data + offset, direct.data() + directIdx, sizeof(data[0]) * nRead); directIdx += nRead; } } return nRead; } #endif uint64_t RleDecoderV2::nextPatched(int64_t* const data, uint64_t offset, uint64_t numValues, const char* const notNull) { if (runRead == runLength) { // extract the number of fixed bits unsigned char fbo = (firstByte >> 1) & 0x1f; bitSize = decodeBitWidth(fbo); // extract the run length runLength = static_cast<uint64_t>(firstByte & 0x01) << 8; runLength |= readByte(); // runs are one off runLength += 1; runRead = 0; // extract the number of bytes occupied by base uint64_t thirdByte = readByte(); byteSize = (thirdByte >> 5) & 0x07; // base width is one off byteSize += 1; // extract patch width uint32_t pwo = thirdByte & 0x1f; patchBitSize = decodeBitWidth(pwo); // read fourth byte and extract patch gap width uint64_t fourthByte = readByte(); uint32_t pgw = (fourthByte >> 5) & 0x07; // patch gap width is one off pgw += 1; // extract the length of the patch list size_t pl = fourthByte & 0x1f; if (pl == 0) { throw ParseError("Corrupt PATCHED_BASE encoded data (pl==0)!"); } // read the next base width number of bytes to extract base value base = readLongBE(byteSize); int64_t mask = (static_cast<int64_t>(1) << ((byteSize * 8) - 1)); // if mask of base value is 1 then base is negative value else positive if ((base & mask) != 0) { base = base & ~mask; base = -base; } // TODO: something more efficient than resize unpacked.resize(runLength); unpackedIdx = 0; readLongs(unpacked.data(), 0, runLength, bitSize); // any remaining bits are thrown out resetReadLongs(); // TODO: something more efficient than resize unpackedPatch.resize(pl); patchIdx = 0; // TODO: Skip corrupt? // if ((patchBitSize + pgw) > 64 && !skipCorrupt) { if ((patchBitSize + pgw) > 64) { throw ParseError( "Corrupt PATCHED_BASE encoded data " "(patchBitSize + pgw > 64)!"); } uint32_t cfb = getClosestFixedBits(patchBitSize + pgw); readLongs(unpackedPatch.data(), 0, pl, cfb); // any remaining bits are thrown out resetReadLongs(); // apply the patch directly when decoding the packed data patchMask = ((static_cast<int64_t>(1) << patchBitSize) - 1); adjustGapAndPatch(); } uint64_t nRead = std::min(runLength - runRead, numValues); for (uint64_t pos = offset; pos < offset + nRead; ++pos) { // skip null positions if (notNull && !notNull[pos]) { continue; } if (static_cast<int64_t>(unpackedIdx) != actualGap) { // no patching required. add base to unpacked value to get final value data[pos] = base + unpacked[unpackedIdx]; } else { // extract the patch value int64_t patchedVal = unpacked[unpackedIdx] | (curPatch << bitSize); // add base to patched value data[pos] = base + patchedVal; // increment the patch to point to next entry in patch list ++patchIdx; if (patchIdx < unpackedPatch.size()) { adjustGapAndPatch(); // next gap is relative to the current gap actualGap += unpackedIdx; } } ++runRead; ++unpackedIdx; } return nRead; } uint64_t RleDecoderV2::nextDelta(int64_t* const data, uint64_t offset, uint64_t numValues, const char* const notNull) { if (runRead == runLength) { // extract the number of fixed bits unsigned char fbo = (firstByte >> 1) & 0x1f; if (fbo != 0) { bitSize = decodeBitWidth(fbo); } else { bitSize = 0; } // extract the run length runLength = static_cast<uint64_t>(firstByte & 0x01) << 8; runLength |= readByte(); ++runLength; // account for first value runRead = deltaBase = 0; // read the first value stored as vint if (isSigned) { firstValue = static_cast<int64_t>(readVslong()); } else { firstValue = static_cast<int64_t>(readVulong()); } prevValue = firstValue; // read the fixed delta value stored as vint (deltas can be negative even // if all number are positive) deltaBase = static_cast<int64_t>(readVslong()); } uint64_t nRead = std::min(runLength - runRead, numValues); uint64_t pos = offset; for (; pos < offset + nRead; ++pos) { // skip null positions if (!notNull || notNull[pos]) break; } if (runRead == 0 && pos < offset + nRead) { data[pos++] = firstValue; ++runRead; } if (bitSize == 0) { // add fixed deltas to adjacent values for (; pos < offset + nRead; ++pos) { // skip null positions if (notNull && !notNull[pos]) { continue; } prevValue = data[pos] = prevValue + deltaBase; ++runRead; } } else { for (; pos < offset + nRead; ++pos) { // skip null positions if (!notNull || notNull[pos]) break; } if (runRead < 2 && pos < offset + nRead) { // add delta base and first value prevValue = data[pos++] = firstValue + deltaBase; ++runRead; } // write the unpacked values, add it to previous value and store final // value to result buffer. if the delta base value is negative then it // is a decreasing sequence else an increasing sequence uint64_t remaining = (offset + nRead) - pos; runRead += readLongs(data, pos, remaining, bitSize, notNull); if (deltaBase < 0) { for (; pos < offset + nRead; ++pos) { // skip null positions if (notNull && !notNull[pos]) { continue; } prevValue = data[pos] = prevValue - data[pos]; } } else { for (; pos < offset + nRead; ++pos) { // skip null positions if (notNull && !notNull[pos]) { continue; } prevValue = data[pos] = prevValue + data[pos]; } } } return nRead; } } // namespace orc
31.156701
120
0.548276
sparklezzz
8159bc85343f8fe0e59c9407461f8c301f538e1f
3,631
hh
C++
litecp/DBEndpoint.hh
couchbaselabs/couchbase-mobile-tools
b0d2c40cf5b6043b508434cc0ef310f29df2d2c1
[ "Apache-2.0" ]
27
2019-02-12T15:48:50.000Z
2022-03-31T10:03:42.000Z
litecp/DBEndpoint.hh
couchbaselabs/couchbase-mobile-tools
b0d2c40cf5b6043b508434cc0ef310f29df2d2c1
[ "Apache-2.0" ]
20
2019-02-20T19:57:05.000Z
2022-03-21T20:04:35.000Z
litecp/DBEndpoint.hh
couchbaselabs/couchbase-mobile-tools
b0d2c40cf5b6043b508434cc0ef310f29df2d2c1
[ "Apache-2.0" ]
18
2019-04-08T10:11:25.000Z
2022-03-29T04:55:25.000Z
// // DBEndpoint.hh // // Copyright (c) 2017 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include "Endpoint.hh" #include "c4Replicator.h" #include "Stopwatch.hh" #include "fleece/slice.hh" class JSONEndpoint; class RemoteEndpoint; class DbEndpoint : public Endpoint { public: explicit DbEndpoint(const std::string &spec); explicit DbEndpoint(C4Database*); #ifdef HAS_COLLECTIONS explicit DbEndpoint(C4Collection*); #endif virtual bool isDatabase() const override {return true;} fleece::alloc_slice path() const; virtual void prepare(bool isSource, bool mustExist, fleece::slice docIDProperty, const Endpoint*) override; void setBidirectional(bool bidi) {_bidirectional = bidi;} void setContinuous(bool cont) {_continuous = cont;} void setMaxRetries(unsigned n) {_maxRetries = n;} using credentials = std::pair<std::string, std::string>; void setCredentials(const credentials &cred) {_credentials = cred;} void setRootCerts(fleece::alloc_slice rootCerts){_rootCerts = rootCerts;} void setClientCert(fleece::alloc_slice client) {_clientCert = client;} void setClientCertKey(fleece::alloc_slice key) {_clientCertKey = key;} void setClientCertKeyPassword(fleece::alloc_slice p) {_clientCertKeyPassword = p;} virtual void copyTo(Endpoint *dst, uint64_t limit) override; virtual void writeJSON(fleece::slice docID, fleece::slice json) override; virtual void finish() override; void pushToLocal(DbEndpoint&); void replicateWith(RemoteEndpoint&, bool pushing =true); void startReplicationWith(RemoteEndpoint&, bool pushing); void waitTillIdle(); void stopReplication(); void finishReplication(); void exportTo(JSONEndpoint*); void importFrom(JSONEndpoint*); void onStateChanged(C4ReplicatorStatus status); void onDocsEnded(bool pushing, size_t count, const C4DocumentEnded* docs[]); private: void enterTransaction(); void commit(); void startLine(); void exportTo(Endpoint *dst, uint64_t limit); C4ReplicatorParameters replicatorParameters(C4ReplicatorMode push, C4ReplicatorMode pull); void startReplicator(C4Replicator*, C4Error&); c4::ref<C4Database> _db; #ifdef HAS_COLLECTIONS C4Collection* _collection {nullptr}; #endif bool _openedDB {false}; unsigned _transactionSize {0}; bool _inTransaction {false}; Endpoint* _otherEndpoint; fleece::Stopwatch _stopwatch; double _lastElapsed {0}; uint64_t _lastDocCount {0}; bool _needNewline {false}; // Replication mode only: bool _bidirectional {false}; bool _continuous {false}; unsigned _maxRetries = 0; // no retries by default credentials _credentials; fleece::alloc_slice _rootCerts; fleece::alloc_slice _clientCert, _clientCertKey, _clientCertKeyPassword; fleece::alloc_slice _options; c4::ref<C4Replicator> _replicator; static constexpr unsigned kMaxTransactionSize = 100000; };
33.62037
111
0.715505
couchbaselabs
815e6b183d2acb5cedfe2d6291338ba75c426576
1,339
hpp
C++
include/unifex/detail/unifex_fwd.hpp
ChuanqiXu9/libunifex
33c48459a86029e38a376f1d74799a0caee252a0
[ "Apache-2.0" ]
null
null
null
include/unifex/detail/unifex_fwd.hpp
ChuanqiXu9/libunifex
33c48459a86029e38a376f1d74799a0caee252a0
[ "Apache-2.0" ]
null
null
null
include/unifex/detail/unifex_fwd.hpp
ChuanqiXu9/libunifex
33c48459a86029e38a376f1d74799a0caee252a0
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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. */ #pragma once namespace unifex { namespace detail { template <typename, typename = void> extern const bool _is_executor; template <typename E, typename R, typename = void> extern const bool _can_execute; template <typename S, typename F, typename = void> extern const bool _can_submit; } // detail namespace _execute_cpo { extern const struct _fn execute; } // namespace _execute_cpo using _execute_cpo::execute; namespace _submit_cpo { extern const struct _fn submit; } // namespace _submit_cpo using _submit_cpo::submit; namespace _connect_cpo { extern const struct _fn connect; } // namespace _connect_cpo using _connect_cpo::connect; } // namespace unifex
29.108696
75
0.725915
ChuanqiXu9
815ee2a76eafc9b9f7cfd7310eab806dfc0d91c1
384
cc
C++
examples/0027.filelock/buffered_file_with_file_lock.cc
clayne/fast_io
1d7e12ea551d87e187a5a8881d9227ba3ea3b8a0
[ "MIT" ]
53
2022-02-19T18:28:36.000Z
2022-03-29T06:54:03.000Z
examples/0027.filelock/buffered_file_with_file_lock.cc
clayne/fast_io
1d7e12ea551d87e187a5a8881d9227ba3ea3b8a0
[ "MIT" ]
5
2022-03-05T14:10:29.000Z
2022-03-28T02:43:16.000Z
examples/0027.filelock/buffered_file_with_file_lock.cc
clayne/fast_io
1d7e12ea551d87e187a5a8881d9227ba3ea3b8a0
[ "MIT" ]
17
2022-02-19T20:16:18.000Z
2022-03-29T20:50:49.000Z
#include<fast_io.h> #include<fast_io_device.h> int main() try { fast_io::obuf_file pf(u8"example.txt",fast_io::open_mode::app); fast_io::file_lock_guard g(file_lock(pf.handle),fast_io::flock_request_l64{}); fast_io::io_flush_guard g2(pf); for(std::size_t i{};i!=1000000;++i) { print(pf,"Hello "); print(pf,"World\n"); } } catch(fast_io::error e) { perrln(e); return 1; }
19.2
79
0.6875
clayne
8160b80ef3e4474c4cf8162a6ed1209fd2d9abd9
3,529
cpp
C++
3rdParty/boost/1.71.0/libs/spirit/test/x3/with.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
3rdParty/boost/1.71.0/libs/spirit/test/x3/with.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
3rdParty/boost/1.71.0/libs/spirit/test/x3/with.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
/*============================================================================= Copyright (c) 2015 Joel de Guzman 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 <boost/detail/lightweight_test.hpp> #include <boost/spirit/home/x3.hpp> #include "test.hpp" namespace x3 = boost::spirit::x3; struct my_tag; struct my_rule_class { template <typename Iterator, typename Exception, typename Context> x3::error_handler_result on_error(Iterator&, Iterator const&, Exception const&, Context const& context) { x3::get<my_tag>(context)++; return x3::error_handler_result::fail; } template <typename Iterator, typename Attribute, typename Context> inline void on_success(Iterator const&, Iterator const&, Attribute&, Context const& context) { x3::get<my_tag>(context)++; } }; int main() { using spirit_test::test_attr; using spirit_test::test; using boost::spirit::x3::rule; using boost::spirit::x3::int_; using boost::spirit::x3::with; { // injecting data into the context in the grammar int val = 0; auto r = rule<my_rule_class, char const*>() = '(' > int_ > ',' > int_ > ')' ; auto start = with<my_tag>(std::ref(val)) [ r ] ; BOOST_TEST(test("(123,456)", start)); BOOST_TEST(!test("(abc,def)", start)); BOOST_TEST(val == 2); } { // injecting non-const lvalue into the context int val = 0; auto const r = int_[([](auto& ctx){ x3::get<my_tag>(ctx) += x3::_attr(ctx); })]; BOOST_TEST(test("123,456", with<my_tag>(val)[r % ','])); BOOST_TEST(579 == val); } { // injecting rvalue into the context auto const r1 = int_[([](auto& ctx){ x3::get<my_tag>(ctx) += x3::_attr(ctx); })]; auto const r2 = rule<struct my_rvalue_rule_class, int>() = x3::lit('(') >> (r1 % ',') >> x3::lit(')')[([](auto& ctx){ x3::_val(ctx) = x3::get<my_tag>(ctx); })]; int attr = 0; BOOST_TEST(test_attr("(1,2,3)", with<my_tag>(100)[r2], attr)); BOOST_TEST(106 == attr); } { // injecting const/non-const lvalue and rvalue into the context struct functor { int operator()(int& val) { return val * 10; // non-const ref returns 10 * injected val } int operator()(int const& val) { return val; // const ref returns injected val } }; auto f = [](auto& ctx){ x3::_val(ctx) = x3::_attr(ctx) + functor()(x3::get<my_tag>(ctx)); }; auto const r = rule<struct my_rule_class2, int>() = int_[f]; int attr = 0; int const cval = 10; BOOST_TEST(test_attr("5", with<my_tag>(cval)[r], attr)); BOOST_TEST(15 == attr); // x3::get returns const ref to cval attr = 0; int val = 10; BOOST_TEST(test_attr("5", with<my_tag>(val)[r], attr)); BOOST_TEST(105 == attr); // x3::get returns ref to val attr = 0; BOOST_TEST(test_attr("5", with<my_tag>(10)[r], attr)); // x3::get returns ref to member variable of with_directive BOOST_TEST(105 == attr); } return boost::report_errors(); }
30.686957
84
0.530462
rajeev02101987
8160bee4f91eb5159ea3f5bcd4fccae1c34ce01e
5,412
cpp
C++
modules/vectorfieldvisualizationgl/vectorfieldvisualizationglmodule.cpp
liu3xing3long/inviwo
69cca9b6ecd58037bda0ed9e6f53d02f189f19a7
[ "BSD-2-Clause" ]
1
2018-04-07T14:30:29.000Z
2018-04-07T14:30:29.000Z
modules/vectorfieldvisualizationgl/vectorfieldvisualizationglmodule.cpp
liu3xing3long/inviwo
69cca9b6ecd58037bda0ed9e6f53d02f189f19a7
[ "BSD-2-Clause" ]
null
null
null
modules/vectorfieldvisualizationgl/vectorfieldvisualizationglmodule.cpp
liu3xing3long/inviwo
69cca9b6ecd58037bda0ed9e6f53d02f189f19a7
[ "BSD-2-Clause" ]
null
null
null
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2015-2018 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <modules/vectorfieldvisualizationgl/vectorfieldvisualizationglmodule.h> #include <modules/opengl/shader/shadermanager.h> #include <modules/vectorfieldvisualizationgl/processors/datageneration/lorenzsystem.h> #include <modules/vectorfieldvisualizationgl/processors/datageneration/vectorfieldgenerator2d.h> #include <modules/vectorfieldvisualizationgl/processors/datageneration/vectorfieldgenerator3d.h> #include <modules/vectorfieldvisualizationgl/processors/datageneration/vectorfieldgenerator4d.h> #include <modules/vectorfieldvisualizationgl/processors/2d/lic2d.h> #include <modules/vectorfieldvisualizationgl/processors/2d/hedgehog2d.h> #include <modules/vectorfieldvisualizationgl/processors/2d/vector2dmagnitude.h> #include <modules/vectorfieldvisualizationgl/processors/2d/vector2dcurl.h> #include <modules/vectorfieldvisualizationgl/processors/2d/vector2ddivergence.h> #include <modules/vectorfieldvisualizationgl/processors/3d/lic3d.h> #include <modules/vectorfieldvisualizationgl/processors/3d/vector3dcurl.h> #include <modules/vectorfieldvisualizationgl/processors/3d/vector3ddivergence.h> #include <modules/vectorfieldvisualizationgl/processors/4d/tmip.h> // Autogenerated #include <modules/vectorfieldvisualizationgl/shader_resources.h> namespace inviwo { VectorFieldVisualizationGLModule::VectorFieldVisualizationGLModule(InviwoApplication* app) : InviwoModule(app, "VectorFieldVisualizationGL") { // Add a directory to the search path of the Shadermanager vectorfieldvisualizationgl::addShaderResources(ShaderManager::getPtr(), {getPath(ModulePath::GLSL)}); registerProcessor<LorenzSystem>(); registerProcessor<VectorFieldGenerator2D>(); registerProcessor<VectorFieldGenerator3D>(); registerProcessor<LIC2D>(); registerProcessor<HedgeHog2D>(); registerProcessor<Vector2DMagnitude>(); registerProcessor<Vector2DCurl>(); registerProcessor<Vector2DDivergence>(); registerProcessor<LIC3D>(); registerProcessor<Vector3DCurl>(); registerProcessor<Vector3DDivergence>(); registerProcessor<TMIP>(); registerProcessor<VectorFieldGenerator4D>(); } int VectorFieldVisualizationGLModule::getVersion() const { return 1; } std::unique_ptr<VersionConverter> VectorFieldVisualizationGLModule::getConverter(int version) const { return util::make_unique<Converter>(version); } VectorFieldVisualizationGLModule::Converter::Converter(int version) : version_(version) {} bool VectorFieldVisualizationGLModule::Converter::convert(TxElement* root) { std::vector<xml::IdentifierReplacement> repl = {}; const std::vector<std::pair<std::string, std::string>> volumeGLrepl = { {"Vector3DCurl", "vector3dcurl.frag"}, {"Vector3DDivergence", "vector3ddivergence.frag"}}; for (const auto& i : volumeGLrepl) { xml::IdentifierReplacement inport = { {xml::Kind::processor("org.inviwo." + i.first), xml::Kind::inport("org.inviwo.VolumeInport")}, i.second + "inport", "inputVolume" }; xml::IdentifierReplacement outport = { {xml::Kind::processor("org.inviwo." + i.first), xml::Kind::outport("org.inviwo.VolumeOutport")}, i.second + "outport", "outputVolume" }; repl.push_back(inport); repl.push_back(outport); } bool res = false; switch (version_) { case 0: { res |= xml::changeIdentifiers(root, repl); } return res; default: return false; // No changes } return true; } } // namespace
45.478992
101
0.696785
liu3xing3long
81621a6eb6c399668a684dc24a5b1db4162a7357
6,214
cpp
C++
Source/WebCore/platform/graphics/freetype/FontCustomPlatformDataFreeType.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebCore/platform/graphics/freetype/FontCustomPlatformDataFreeType.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebCore/platform/graphics/freetype/FontCustomPlatformDataFreeType.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2008 Alp Toker <alp@atoker.com> * Copyright (C) 2010 Igalia S.L. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #include "FontCustomPlatformData.h" #include "CairoUtilities.h" #include "FontCacheFreeType.h" #include "FontDescription.h" #include "FontPlatformData.h" #include "SharedBuffer.h" #include <cairo-ft.h> #include <cairo.h> #include <ft2build.h> #include FT_MODULE_H #include <mutex> namespace WebCore { static void releaseCustomFontData(void* data) { static_cast<SharedBuffer*>(data)->deref(); } static cairo_user_data_key_t freeTypeFaceKey; FontCustomPlatformData::FontCustomPlatformData(FT_Face freeTypeFace, SharedBuffer& buffer) : m_fontFace(adoptRef(cairo_ft_font_face_create_for_ft_face(freeTypeFace, FT_LOAD_DEFAULT))) { buffer.ref(); // This is balanced by the buffer->deref() in releaseCustomFontData. static cairo_user_data_key_t bufferKey; cairo_font_face_set_user_data(m_fontFace.get(), &bufferKey, &buffer, static_cast<cairo_destroy_func_t>(releaseCustomFontData)); // Cairo doesn't do FreeType reference counting, so we need to ensure that when // this cairo_font_face_t is destroyed, it cleans up the FreeType face as well. cairo_font_face_set_user_data(m_fontFace.get(), &freeTypeFaceKey, freeTypeFace, reinterpret_cast<cairo_destroy_func_t>(reinterpret_cast<void(*)(void)>(FT_Done_Face))); } static RefPtr<FcPattern> defaultFontconfigOptions() { // Get some generic default settings from fontconfig for web fonts. Strategy // from Behdad Esfahbod in https://code.google.com/p/chromium/issues/detail?id=173207#c35 static FcPattern* pattern = nullptr; static std::once_flag flag; std::call_once(flag, [](FcPattern*) { pattern = FcPatternCreate(); FcConfigSubstitute(nullptr, pattern, FcMatchPattern); cairo_ft_font_options_substitute(getDefaultCairoFontOptions(), pattern); FcDefaultSubstitute(pattern); FcPatternDel(pattern, FC_FAMILY); FcConfigSubstitute(nullptr, pattern, FcMatchFont); }, pattern); return adoptRef(FcPatternDuplicate(pattern)); } FontPlatformData FontCustomPlatformData::fontPlatformData(const FontDescription& description, bool bold, bool italic, const FontFeatureSettings& fontFaceFeatures, FontSelectionSpecifiedCapabilities) { auto* freeTypeFace = static_cast<FT_Face>(cairo_font_face_get_user_data(m_fontFace.get(), &freeTypeFaceKey)); ASSERT(freeTypeFace); RefPtr<FcPattern> pattern = defaultFontconfigOptions(); FcPatternAddString(pattern.get(), FC_FAMILY, reinterpret_cast<const FcChar8*>(freeTypeFace->family_name)); for (auto& fontFaceFeature : fontFaceFeatures) { if (fontFaceFeature.enabled()) { const auto& tag = fontFaceFeature.tag(); const char buffer[] = { tag[0], tag[1], tag[2], tag[3], '\0' }; FcPatternAddString(pattern.get(), FC_FONT_FEATURES, reinterpret_cast<const FcChar8*>(buffer)); } } #if ENABLE(VARIATION_FONTS) auto variants = buildVariationSettings(freeTypeFace, description); if (!variants.isEmpty()) { FcPatternAddString(pattern.get(), FC_FONT_VARIATIONS, reinterpret_cast<const FcChar8*>(variants.utf8().data())); } #endif return FontPlatformData(m_fontFace.get(), WTFMove(pattern), description.computedPixelSize(), freeTypeFace->face_flags & FT_FACE_FLAG_FIXED_WIDTH, bold, italic, description.orientation()); } static bool initializeFreeTypeLibrary(FT_Library& library) { // https://www.freetype.org/freetype2/docs/design/design-4.html // https://lists.nongnu.org/archive/html/freetype-devel/2004-10/msg00022.html FT_Memory memory = bitwise_cast<FT_Memory>(ft_smalloc(sizeof(*memory))); if (!memory) return false; memory->user = nullptr; memory->alloc = [](FT_Memory, long size) -> void* { return fastMalloc(size); }; memory->free = [](FT_Memory, void* block) -> void { fastFree(block); }; memory->realloc = [](FT_Memory, long, long newSize, void* block) -> void* { return fastRealloc(block, newSize); }; if (FT_New_Library(memory, &library)) { ft_sfree(memory); return false; } FT_Add_Default_Modules(library); return true; } std::unique_ptr<FontCustomPlatformData> createFontCustomPlatformData(SharedBuffer& buffer, const String&) { static FT_Library library; if (!library && !initializeFreeTypeLibrary(library)) { library = nullptr; return nullptr; } FT_Face freeTypeFace; if (FT_New_Memory_Face(library, reinterpret_cast<const FT_Byte*>(buffer.data()), buffer.size(), 0, &freeTypeFace)) return nullptr; return makeUnique<FontCustomPlatformData>(freeTypeFace, buffer); } bool FontCustomPlatformData::supportsFormat(const String& format) { return equalLettersIgnoringASCIICase(format, "truetype") || equalLettersIgnoringASCIICase(format, "opentype") #if USE(WOFF2) || equalLettersIgnoringASCIICase(format, "woff2") #if ENABLE(VARIATION_FONTS) || equalLettersIgnoringASCIICase(format, "woff2-variations") #endif #endif #if ENABLE(VARIATION_FONTS) || equalLettersIgnoringASCIICase(format, "woff-variations") || equalLettersIgnoringASCIICase(format, "truetype-variations") || equalLettersIgnoringASCIICase(format, "opentype-variations") #endif || equalLettersIgnoringASCIICase(format, "woff"); } }
38.358025
198
0.727873
jacadcaps
816278711cb11e8e796b3a24f2135f307fb43b95
7,671
hpp
C++
src/base/command/NonlinearConstraint.hpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
null
null
null
src/base/command/NonlinearConstraint.hpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
null
null
null
src/base/command/NonlinearConstraint.hpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
null
null
null
//$Id$ //------------------------------------------------------------------------------ // NonlinearConstraint //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002 - 2017 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number NNG04CC06P // // Author: Wendy Shoan (GSFC/MAB) // Created: 2006.08.14 // /** * Definition for the NonlinearConstraint command class */ //------------------------------------------------------------------------------ #ifndef NonlinearConstraint_hpp #define NonlinearConstraint_hpp #include "SolverSequenceCommand.hpp" #include "Solver.hpp" #include "Parameter.hpp" #include "ElementWrapper.hpp" /** * Command that manages processing for targeter goals. */ class GMAT_API NonlinearConstraint : public SolverSequenceCommand { public: NonlinearConstraint(); NonlinearConstraint(const NonlinearConstraint& nlc); NonlinearConstraint& operator=(const NonlinearConstraint& nlc); virtual ~NonlinearConstraint(); // inherited from GmatBase virtual GmatBase* Clone() const; virtual bool RenameRefObject(const Gmat::ObjectType type, const std::string &oldName, const std::string &newName); virtual const ObjectTypeArray& GetRefObjectTypeArray(); virtual const StringArray& GetRefObjectNameArray(const Gmat::ObjectType type); // Parameter accessors virtual std::string GetParameterText(const Integer id) const; virtual Integer GetParameterID(const std::string &str) const; virtual Gmat::ParameterType GetParameterType(const Integer id) const; virtual std::string GetParameterTypeString(const Integer id) const; virtual Real GetRealParameter(const Integer id) const; virtual Real SetRealParameter(const Integer id, const Real value); virtual std::string GetStringParameter(const Integer id) const; virtual bool SetStringParameter(const Integer id, const char *value); virtual bool SetStringParameter(const Integer id, const std::string &value); virtual bool SetRefObject(GmatBase *obj, const Gmat::ObjectType type, const std::string &name = ""); // Inherited methods overridden from the base class virtual bool InterpretAction(); virtual const StringArray& GetWrapperObjectNameArray(bool completeSet = false); virtual bool SetElementWrapper(ElementWrapper* toWrapper, const std::string &withName); virtual void ClearWrappers(); virtual bool Initialize(); virtual bool Execute(); virtual void RunComplete(); virtual const std::string& GetGeneratingString(Gmat::WriteMode mode, const std::string &prefix, const std::string &useName); DEFAULT_TO_NO_CLONES protected: // Parameter IDs enum { OPTIMIZER_NAME = SolverSequenceCommandParamCount, CONSTRAINT_ARG1, OPERATOR, CONSTRAINT_ARG2, TOLERANCE, NonlinearConstraintParamCount }; static const std::string PARAMETER_TEXT[NonlinearConstraintParamCount - SolverSequenceCommandParamCount]; static const Gmat::ParameterType PARAMETER_TYPE[NonlinearConstraintParamCount - SolverSequenceCommandParamCount]; enum Operator { LESS_THAN_OR_EQUAL = 0, GREATER_THAN_OR_EQUAL, EQUAL }; static const std::string OP_STRINGS[3]; /// The name of the spacecraft that gets maneuvered std::string optimizerName; /// The optimizer instance used to manage the optimizer state machine Solver *optimizer; /// Name of the variable to be constrained std::string arg1Name; // pointer to the Variable that is to be minimized //Parameter *constraint; ElementWrapper *arg1; /// most recent value of the variable Real constraintValue; // do I still need this? /// name of the parameter part of the right-hand-side std::string arg2Name; //Parameter *nlcParm; ElementWrapper *arg2; /// String of value array name // I don't think I need any of this stuff //std::string nlcArrName; /// constraint array row index variable name //std::string nlcArrRowStr; /// constraint array column index variable name //std::string nlcArrColStr; /// constraint array row index //Integer nlcArrRow; /// constraint array column index //Integer nlcArrCol; //Parameter *nlcArrRowParm; //Parameter *nlcArrColParm; /// flag indicating whether or not the constraint is an inequality /// constraint bool isInequality; /// string to send into the optimizer, based on isInequality std::string isIneqString; /// the desired value (right hand side of the constraint equation) Real desiredValue; /// indicates what type of operator was passed in for the generating /// string Operator op; /// tolerance for the constraint <future> Real tolerance; // <future> /// Flag used to finalize the targeter data during execution bool optimizerDataFinalized; /// ID for this constraint (returned from the optimizer) Integer constraintId; /// is the right hand side a parameter? //bool isNlcParm; /// is the right hand side an array? //bool isNlcArray; /// Pointer to the object that owns the goal //GmatBase *constraintObject; /// Object ID for the parameter //Integer parmId; /// flag indicating whether or not the generating string has been interpreted bool interpreted; std::string panelDescriptor; // Shows "(<=) Sat.SMA" or whatever Real panelDesired; Real panelAchieved; //bool InterpretParameter(const std::string text, // std::string &paramType, // std::string &paramObj, // std::string &parmSystem); //bool ConstructConstraint(const char* str); }; #endif // NonlinearConstraint_hpp
38.355
103
0.589754
supalogix
8162933c6885d340c9732ad206632cc6bf163620
41,979
cpp
C++
apps/hmt-slam-gui/hmt_slam_guiMain.cpp
ros2-gbp/mrpt2-release
ca80124f0c9bfccceab425bfd6c36e1ae29c254b
[ "BSD-3-Clause" ]
null
null
null
apps/hmt-slam-gui/hmt_slam_guiMain.cpp
ros2-gbp/mrpt2-release
ca80124f0c9bfccceab425bfd6c36e1ae29c254b
[ "BSD-3-Clause" ]
null
null
null
apps/hmt-slam-gui/hmt_slam_guiMain.cpp
ros2-gbp/mrpt2-release
ca80124f0c9bfccceab425bfd6c36e1ae29c254b
[ "BSD-3-Clause" ]
1
2020-12-30T14:06:37.000Z
2020-12-30T14:06:37.000Z
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2020, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "hmt_slam_guiMain.h" #include <mrpt/config/CConfigFileMemory.h> #include <mrpt/gui/about_box.h> #include <mrpt/io/CFileGZInputStream.h> #include <mrpt/serialization/CArchive.h> #include <wx/msgdlg.h> #include "MyArtProvider.h" //(*InternalHeaders(hmt_slam_guiFrame) #include <wx/artprov.h> #include <wx/bitmap.h> #include <wx/font.h> #include <wx/icon.h> #include <wx/image.h> #include <wx/intl.h> #include <wx/settings.h> #include <wx/string.h> #include <wx/tglbtn.h> //*) #include <mrpt/system/filesystem.h> #include <memory> using namespace std; using namespace mrpt; using namespace mrpt::hmtslam; using namespace mrpt::slam; using namespace mrpt::config; using namespace mrpt::io; using namespace mrpt::system; using namespace mrpt::poses; //(*IdInit(hmt_slam_guiFrame) const long hmt_slam_guiFrame::ID_BUTTON1 = wxNewId(); const long hmt_slam_guiFrame::ID_STATICLINE3 = wxNewId(); const long hmt_slam_guiFrame::ID_BUTTON2 = wxNewId(); const long hmt_slam_guiFrame::ID_BUTTON3 = wxNewId(); const long hmt_slam_guiFrame::ID_STATICLINE1 = wxNewId(); const long hmt_slam_guiFrame::ID_BUTTON4 = wxNewId(); const long hmt_slam_guiFrame::ID_BUTTON6 = wxNewId(); const long hmt_slam_guiFrame::ID_STATICLINE2 = wxNewId(); const long hmt_slam_guiFrame::ID_BUTTON12 = wxNewId(); const long hmt_slam_guiFrame::ID_BUTTON10 = wxNewId(); const long hmt_slam_guiFrame::ID_BUTTON5 = wxNewId(); const long hmt_slam_guiFrame::ID_PANEL1 = wxNewId(); const long hmt_slam_guiFrame::ID_STATICTEXT1 = wxNewId(); const long hmt_slam_guiFrame::ID_TEXTCTRL1 = wxNewId(); const long hmt_slam_guiFrame::ID_BUTTON11 = wxNewId(); const long hmt_slam_guiFrame::ID_STATICTEXT6 = wxNewId(); const long hmt_slam_guiFrame::ID_TEXTCTRL2 = wxNewId(); const long hmt_slam_guiFrame::ID_PANEL3 = wxNewId(); const long hmt_slam_guiFrame::ID_STATICTEXT2 = wxNewId(); const long hmt_slam_guiFrame::ID_CHOICE1 = wxNewId(); const long hmt_slam_guiFrame::ID_TREECTRL1 = wxNewId(); const long hmt_slam_guiFrame::ID_PANEL15 = wxNewId(); const long hmt_slam_guiFrame::ID_PANEL17 = wxNewId(); const long hmt_slam_guiFrame::ID_PANEL16 = wxNewId(); const long hmt_slam_guiFrame::ID_NOTEBOOK2 = wxNewId(); const long hmt_slam_guiFrame::ID_STATICTEXT5 = wxNewId(); const long hmt_slam_guiFrame::ID_BUTTON7 = wxNewId(); const long hmt_slam_guiFrame::ID_BUTTON8 = wxNewId(); const long hmt_slam_guiFrame::ID_BUTTON9 = wxNewId(); const long hmt_slam_guiFrame::ID_PANEL14 = wxNewId(); const long hmt_slam_guiFrame::ID_PANEL8 = wxNewId(); const long hmt_slam_guiFrame::ID_PANEL5 = wxNewId(); const long hmt_slam_guiFrame::ID_STATICTEXT3 = wxNewId(); const long hmt_slam_guiFrame::ID_XY_GLCANVAS = wxNewId(); const long hmt_slam_guiFrame::ID_PANEL11 = wxNewId(); const long hmt_slam_guiFrame::ID_PANEL10 = wxNewId(); const long hmt_slam_guiFrame::ID_STATICTEXT4 = wxNewId(); const long hmt_slam_guiFrame::ID_CUSTOM1 = wxNewId(); const long hmt_slam_guiFrame::ID_PANEL13 = wxNewId(); const long hmt_slam_guiFrame::ID_PANEL12 = wxNewId(); const long hmt_slam_guiFrame::ID_SPLITTERWINDOW2 = wxNewId(); const long hmt_slam_guiFrame::ID_PANEL7 = wxNewId(); const long hmt_slam_guiFrame::ID_SPLITTERWINDOW1 = wxNewId(); const long hmt_slam_guiFrame::ID_PANEL4 = wxNewId(); const long hmt_slam_guiFrame::ID_NOTEBOOK1 = wxNewId(); const long hmt_slam_guiFrame::ID_PANEL2 = wxNewId(); const long hmt_slam_guiFrame::ID_MENUITEM1 = wxNewId(); const long hmt_slam_guiFrame::ID_MENUITEM2 = wxNewId(); const long hmt_slam_guiFrame::ID_MENUITEM3 = wxNewId(); const long hmt_slam_guiFrame::idMenuQuit = wxNewId(); const long hmt_slam_guiFrame::ID_MENUITEM6 = wxNewId(); const long hmt_slam_guiFrame::ID_MENUITEM4 = wxNewId(); const long hmt_slam_guiFrame::ID_MENUITEM5 = wxNewId(); const long hmt_slam_guiFrame::idMenuAbout = wxNewId(); const long hmt_slam_guiFrame::ID_STATUSBAR1 = wxNewId(); //*) BEGIN_EVENT_TABLE(hmt_slam_guiFrame, wxFrame) //(*EventTable(hmt_slam_guiFrame) //*) END_EVENT_TABLE() hmt_slam_guiFrame::hmt_slam_guiFrame(wxWindow* parent, wxWindowID id) { // Load my custom icons: wxArtProvider::Push(new CMyArtProvider); //(*Initialize(hmt_slam_guiFrame) wxMenuItem* MenuItem2; wxMenuItem* MenuItem1; wxFlexGridSizer* FlexGridSizer8; wxFlexGridSizer* FlexGridSizer1; wxFlexGridSizer* FlexGridSizer2; wxFlexGridSizer* FlexGridSizer15; wxBoxSizer* BoxSizer3; wxMenu* Menu1; wxFlexGridSizer* FlexGridSizer17; wxFlexGridSizer* FlexGridSizer11; wxFlexGridSizer* FlexGridSizer7; wxFlexGridSizer* FlexGridSizer4; wxFlexGridSizer* FlexGridSizer9; wxFlexGridSizer* FlexGridSizer14; wxFlexGridSizer* FlexGridSizer6; wxFlexGridSizer* FlexGridSizer3; wxMenuItem* MenuItem5; wxFlexGridSizer* FlexGridSizer16; wxFlexGridSizer* FlexGridSizer10; wxBoxSizer* BoxSizer1; wxFlexGridSizer* FlexGridSizer13; wxMenuBar* MenuBar1; wxFlexGridSizer* FlexGridSizer18; wxMenuItem* MenuItem6; wxFlexGridSizer* FlexGridSizer12; wxMenu* Menu2; wxFlexGridSizer* FlexGridSizer5; wxMenuItem* MenuItem8; Create( parent, id, _("HTM-SLAM - Part of the MRPT project"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE, _T("id")); SetClientSize(wxSize(700, 400)); SetMinSize(wxSize(-1, 300)); { wxIcon FrameIcon; FrameIcon.CopyFromBitmap(wxArtProvider::GetBitmap( wxART_MAKE_ART_ID_FROM_STR(_T("MAIN_ICON")), wxART_FRAME_ICON)); SetIcon(FrameIcon); } FlexGridSizer1 = new wxFlexGridSizer(2, 1, 0, 0); FlexGridSizer1->AddGrowableCol(0); FlexGridSizer1->AddGrowableRow(1); Panel1 = new wxPanel( this, ID_PANEL1, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL1")); FlexGridSizer2 = new wxFlexGridSizer(0, 12, 0, 0); FlexGridSizer2->AddGrowableCol(8); btnReset = new wxCustomButton( Panel1, ID_BUTTON1, _("Reset"), wxArtProvider::GetBitmap( wxART_MAKE_ART_ID_FROM_STR(_T("ICON_RESET")), wxART_MAKE_CLIENT_ID_FROM_STR(wxString(wxEmptyString))), wxDefaultPosition, wxDefaultSize, wxCUSTBUT_BUTTON | wxCUSTBUT_BOTTOM | wxCUSTBUT_FLAT, wxDefaultValidator, _T("ID_BUTTON1")); btnReset->SetBitmapDisabled( btnReset->CreateBitmapDisabled(btnReset->GetBitmapLabel())); btnReset->SetLabelMargin(wxSize(10, 2)); btnReset->SetBitmapMargin(wxSize(-1, 3)); FlexGridSizer2->Add(btnReset, 1, wxALL | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); StaticLine3 = new wxStaticLine( Panel1, ID_STATICLINE3, wxDefaultPosition, wxSize(1, -1), wxLI_VERTICAL, _T("ID_STATICLINE3")); FlexGridSizer2->Add( StaticLine3, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); btnLoad = new wxCustomButton( Panel1, ID_BUTTON2, _("Load state..."), wxArtProvider::GetBitmap( wxART_MAKE_ART_ID_FROM_STR(_T("ICON_LOAD")), wxART_MAKE_CLIENT_ID_FROM_STR(wxString(wxEmptyString))), wxDefaultPosition, wxDefaultSize, wxCUSTBUT_BUTTON | wxCUSTBUT_BOTTOM | wxCUSTBUT_FLAT, wxDefaultValidator, _T("ID_BUTTON2")); btnLoad->SetBitmapDisabled( btnLoad->CreateBitmapDisabled(btnLoad->GetBitmapLabel())); btnLoad->SetLabelMargin(wxSize(10, 2)); btnLoad->SetBitmapMargin(wxSize(-1, 3)); FlexGridSizer2->Add(btnLoad, 1, wxALL | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); btnSave = new wxCustomButton( Panel1, ID_BUTTON3, _("Save state.."), wxArtProvider::GetBitmap( wxART_MAKE_ART_ID_FROM_STR(_T("ICON_SAVE")), wxART_MAKE_CLIENT_ID_FROM_STR(wxString(wxEmptyString))), wxDefaultPosition, wxDefaultSize, wxCUSTBUT_BUTTON | wxCUSTBUT_BOTTOM | wxCUSTBUT_FLAT, wxDefaultValidator, _T("ID_BUTTON3")); btnSave->SetBitmapDisabled( btnSave->CreateBitmapDisabled(btnSave->GetBitmapLabel())); btnSave->SetLabelMargin(wxSize(10, 2)); btnSave->SetBitmapMargin(wxSize(-1, 3)); FlexGridSizer2->Add(btnSave, 1, wxALL | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); StaticLine1 = new wxStaticLine( Panel1, ID_STATICLINE1, wxDefaultPosition, wxSize(1, -1), wxLI_VERTICAL, _T("ID_STATICLINE1")); FlexGridSizer2->Add( StaticLine1, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); btnStart = new wxCustomButton( Panel1, ID_BUTTON4, _("START"), wxArtProvider::GetBitmap( wxART_MAKE_ART_ID_FROM_STR(_T("ICON_PLAY")), wxART_MAKE_CLIENT_ID_FROM_STR(wxString(wxEmptyString))), wxDefaultPosition, wxDefaultSize, wxCUSTBUT_BUTTON | wxCUSTBUT_BOTTOM | wxCUSTBUT_FLAT, wxDefaultValidator, _T("ID_BUTTON4")); btnStart->SetBitmapDisabled( btnStart->CreateBitmapDisabled(btnStart->GetBitmapLabel())); btnStart->SetLabelMargin(wxSize(10, 2)); btnStart->SetBitmapMargin(wxSize(-1, 3)); FlexGridSizer2->Add(btnStart, 1, wxALL | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); btnPause = new wxCustomButton( Panel1, ID_BUTTON6, _("Pause"), wxArtProvider::GetBitmap( wxART_MAKE_ART_ID_FROM_STR(_T("ICON_STOP")), wxART_MAKE_CLIENT_ID_FROM_STR(wxString(wxEmptyString))), wxDefaultPosition, wxDefaultSize, wxCUSTBUT_BUTTON | wxCUSTBUT_BOTTOM | wxCUSTBUT_FLAT, wxDefaultValidator, _T("ID_BUTTON6")); btnPause->SetBitmapDisabled( btnPause->CreateBitmapDisabled(btnPause->GetBitmapLabel())); btnPause->SetLabelMargin(wxSize(10, 2)); btnPause->SetBitmapMargin(wxSize(-1, 3)); FlexGridSizer2->Add(btnPause, 1, wxALL | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); StaticLine2 = new wxStaticLine( Panel1, ID_STATICLINE2, wxDefaultPosition, wxSize(1, -1), wxLI_VERTICAL, _T("ID_STATICLINE2")); FlexGridSizer2->Add( StaticLine2, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); btnShowLogWin = new wxCustomButton( Panel1, ID_BUTTON12, _("Show log"), wxArtProvider::GetBitmap( wxART_MAKE_ART_ID_FROM_STR(_T("ICON_LOG")), wxART_MAKE_CLIENT_ID_FROM_STR(wxString(wxEmptyString))), wxDefaultPosition, wxDefaultSize, wxCUSTBUT_BUTTON | wxCUSTBUT_BOTTOM | wxCUSTBUT_FLAT, wxDefaultValidator, _T("ID_BUTTON12")); btnShowLogWin->SetBitmapDisabled( btnShowLogWin->CreateBitmapDisabled(btnShowLogWin->GetBitmapLabel())); btnShowLogWin->SetLabelMargin(wxSize(10, 2)); btnShowLogWin->SetBitmapMargin(wxSize(-1, 3)); FlexGridSizer2->Add( btnShowLogWin, 1, wxALL | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); FlexGridSizer2->Add( -1, -1, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); btnAbout = new wxCustomButton( Panel1, ID_BUTTON10, _("About..."), wxArtProvider::GetBitmap( wxART_MAKE_ART_ID_FROM_STR(_T("ICON_ABOUT")), wxART_MAKE_CLIENT_ID_FROM_STR(wxString(wxEmptyString))), wxDefaultPosition, wxDefaultSize, wxCUSTBUT_BUTTON | wxCUSTBUT_BOTTOM | wxCUSTBUT_FLAT, wxDefaultValidator, _T("ID_BUTTON10")); btnAbout->SetBitmapDisabled( btnAbout->CreateBitmapDisabled(btnAbout->GetBitmapLabel())); btnAbout->SetLabelMargin(wxSize(10, 2)); btnAbout->SetBitmapMargin(wxSize(-1, 3)); FlexGridSizer2->Add(btnAbout, 1, wxALL | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); btnQuit = new wxCustomButton( Panel1, ID_BUTTON5, _("Quit"), wxArtProvider::GetBitmap( wxART_MAKE_ART_ID_FROM_STR(_T("ICON_QUIT")), wxART_MAKE_CLIENT_ID_FROM_STR(wxString(wxEmptyString))), wxDefaultPosition, wxDefaultSize, wxCUSTBUT_BUTTON | wxCUSTBUT_BOTTOM | wxCUSTBUT_FLAT, wxDefaultValidator, _T("ID_BUTTON5")); btnQuit->SetBitmapDisabled( btnQuit->CreateBitmapDisabled(btnQuit->GetBitmapLabel())); btnQuit->SetLabelMargin(wxSize(10, 2)); btnQuit->SetBitmapMargin(wxSize(-1, 3)); FlexGridSizer2->Add(btnQuit, 1, wxALL | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); Panel1->SetSizer(FlexGridSizer2); FlexGridSizer2->Fit(Panel1); FlexGridSizer2->SetSizeHints(Panel1); FlexGridSizer1->Add( Panel1, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 0); Panel2 = new wxPanel( this, ID_PANEL2, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL2")); FlexGridSizer3 = new wxFlexGridSizer(1, 1, 0, 0); FlexGridSizer3->AddGrowableCol(0); FlexGridSizer3->AddGrowableRow(0); Notebook1 = new wxNotebook( Panel2, ID_NOTEBOOK1, wxDefaultPosition, wxDefaultSize, 0, _T("ID_NOTEBOOK1")); panConfig = new wxPanel( Notebook1, ID_PANEL3, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL3")); FlexGridSizer16 = new wxFlexGridSizer(2, 1, 0, 0); FlexGridSizer16->AddGrowableCol(0); FlexGridSizer16->AddGrowableRow(1); FlexGridSizer17 = new wxFlexGridSizer(1, 3, 0, 0); FlexGridSizer17->AddGrowableCol(1); StaticText1 = new wxStaticText( panConfig, ID_STATICTEXT1, _("Input rawlog file:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT1")); FlexGridSizer17->Add( StaticText1, 1, wxALL | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL, 5); edInputRawlog = new wxTextCtrl( panConfig, ID_TEXTCTRL1, _("dataset.rawlog"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL1")); FlexGridSizer17->Add( edInputRawlog, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); btnPickRawlog = new wxButton( panConfig, ID_BUTTON11, _("Pick..."), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON11")); FlexGridSizer17->Add( btnPickRawlog, 1, wxALL | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL, 5); FlexGridSizer16->Add( FlexGridSizer17, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 0); FlexGridSizer18 = new wxFlexGridSizer(2, 1, 0, 0); FlexGridSizer18->AddGrowableCol(0); FlexGridSizer18->AddGrowableRow(1); StaticText6 = new wxStaticText( panConfig, ID_STATICTEXT6, _("More parameters:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT6")); FlexGridSizer18->Add( StaticText6, 1, wxALL | wxALIGN_BOTTOM | wxALIGN_CENTER_HORIZONTAL, 5); edRestParams = new wxTextCtrl( panConfig, ID_TEXTCTRL2, _("//====================================================\n// " " HMT-SLAM\n// Here come global parameters for the " "app.\n//" "====================================================\n[HMT-SLAM]" "\n\n// The directory where the log files will be saved (left in " "blank if no log is required)\nLOG_OUTPUT_DIR\t= " "LOG_HTMSLAM_MALAGA\n\nrawlog_offset\t= 0\t\t// Whether to skip some " "rawlog entries \nLOG_FREQUENCY\t= 20\t// The frequency of log files " "generation:\nLOG_SHOW3D\t\t= 1\nrandom_seed\t\t= 1234\t// " "0:Randomize, !=0:use that seed.\n\n// " "--------------------------------\n// Local SLAM method " "selection:\n// 1: RBPF_2DLASER\n// " "--------------------------------\nSLAM_METHOD=1\n\n//" "SLAM_MIN_DIST_BETWEEN_OBS=1.0\t\t// Map updates threshold " "(meters)\n//SLAM_MIN_HEADING_BETWEEN_OBS_DEG=50\t// Map updates " "threshold (degrees)\n\nSLAM_MIN_DIST_BETWEEN_OBS=1.25\t\t// Map " "updates threshold (meters)\nSLAM_MIN_HEADING_BETWEEN_OBS_DEG=30\t// " "Map updates threshold (degrees)\n\nMIN_ODOMETRY_STD_XY\t\t= " "0.05\t\t// Minimum sigma in odometry increments " "(meters)\nMIN_ODOMETRY_STD_PHI\t= 2\t\t\t// Minimum sigma in " "odometry increments (deg)\n\n// Loop closure detectors:\n// " "gridmaps\n// images\nTLC_DETECTORS=gridmaps\n\n// " "====================================================\n// " "TLC_GRIDMATCHING\n//\n// Top. Loop-closure detector based on " "grid-matching\n// " "====================================================\n[TLC_" "GRIDMATCHING]\nfeatsPerSquareMeter\t\t= " "0.012\n\nthreshold_max\t\t\t= 0.20 \t\t// For considering candidate " "matches\nthreshold_delta\t\t\t= 0.09\n\nransac_prob_good_inliers = " "0.9999999999 // Prob. of a good inliers (for the number of " "iterations).\n\nmaxKLd_for_merge = 0.9\t\t// Merge of close " "SOG modes\n\nmin_ICP_goodness\t= 0.25\nmax_ICP_mahadist\t= 20 //10 " "// The maximum Mahalanobis distance between the initial and final " "poses in the ICP not to discard the hypothesis " "(default=10)\n\nransac_minSetSizeRatio\t= 0.15 // " "0.20\n\nransac_mahalanobisDistanceThreshold\t= 6\t\t// amRobust " "method only\nransac_chi2_quantile\t= 0.5 \t\t\t\t// " "amModifiedRANSAC method only\n\nsave_feat_coors\t\t\t= 0\t\t// Dump " "correspondences to grid_feats\ndebug_save_map_pairs\t= 1\t\t// Save " "the pair of maps with the best " "correspondences\ndebug_show_corrs\t\t= 0\t\t// Debug output of " "graphs\n\n\n// " "----------------------------------------------------------\n// All " "the params of the feature detectors/descriptors\n// " "----------------------------------------------------------" "\nfeatsType\t\t\t= 1\t\t// 0: KLT, 1: Harris, 3: SIFT, 4: " "SURF\n\n// The feature descriptor to use: 0=detector already has " "descriptor, \n// 1= SIFT, 2=SURF, 4=Spin images, 8=Polar images, " "16=log-polar images \nfeature_descriptor\t\t= 8\n\npatchSize\t\t\t= " "0 \t// Not needed\n\nKLTOptions.min_distance\t\t= 6\t\t\t// " "Pixels\nKLTOptions.threshold\t\t= 0.01 // 0.10 // " "0.20\n\nharrisOptions.min_distance\t= 6\t\t\t// " "Pixels\nharrisOptions.threshold \t= 0.10 // " "0.20\n\nSIFTOptions.implementation\t= 3\t\t\t// " "Hess\n\nSURFOptions.rotation_invariant\t= 1\t\t// 0=64 dims, " "1=128dims\n\nSpinImagesOptions.hist_size_distance\t= 10 " "\nSpinImagesOptions.hist_size_intensity\t= 10 " "\nSpinImagesOptions.radius\t\t\t= " "20\n\nPolarImagesOptions.bins_angle\t\t\t= " "8\nPolarImagesOptions.bins_distance\t\t= " "6\nPolarImagesOptions.radius\t\t\t= " "40\n\nLogPolarImagesOptions.radius\t\t\t= " "20\nLogPolarImagesOptions.num_angles\t\t= 8\n\n\n\n// " "====================================================\n//\n// " " \tPARTICLE_FILTER\n//\n// Parameters of the PARTICLE FILTER " "within each LMH,\n// invoked & implemented in " "CLSLAM_RBPF_2DLASER\n// " "====================================================\n[PARTICLE_" "FILTER]\n//" "--------------------------------------------------------------------" "--------------\n// The Particle Filter algorithm:\n//\t0: " "pfStandardProposal\n//\t1: pfAuxiliaryPFStandard\n//\t2: " "pfOptimalProposal *** (ICP,...)\n//\t3: pfAuxiliaryPFOptimal\t " " *** (Optimal SAMPLING)\n//\n// See: " "http://www.mrpt.org/Particle_Filters\n//" "--------------------------------------------------------------------" "--------------\nPF_algorithm=3\n\nadaptiveSampleSize\t= 0\t\t// 0: " "Fixed # of particles, 1: KLD " "adaptive\n\n//" "--------------------------------------------------------------------" "--------------\n// The Particle Filter Resampling method:\n//\t0: " "prMultinomial\n//\t1: prResidual\n//\t2: prStratified\n//\t3: " "prSystematic\n//\n// See: /docs/html/topic_resampling.html or " "http://www.mrpt.org/ " "topic_resampling.html\n//" "--------------------------------------------------------------------" "--------------\nresamplingMethod=0\npfAuxFilterOptimal_" "MaximumSearchSamples = 250\t\t// For PF " "algorithm=3\n\nsampleSize\t= 5\t\t// Number of particles (for fixed " "number algorithms)\nBETA\t\t= 0.50\t// Resampling ESS " "threshold\t\npowFactor\t= 0.01\t\t\t// A \"power factor\" for " "updating weights\t\t\t\n\n\n// " "====================================================\n//" "\t\tGRAPH_CUT\n//\n// Params for Area Abstraction (AA)\n// " "====================================================\n[GRAPH_CUT]" "\npartitionThreshold = 0.6 // In the range " "[0,1]. Lower gives larger clusters.\nminDistForCorrespondence " " = 0.50\nuseMapMatching = " "1\nminimumNumberElementsEachCluster = 5\n\n// " "====================================================\n//\n// " " MULTIMETRIC MAP CONFIGURATION\n//\n// The params for creating " "the metric maps for \n// each LMH.\n// " "====================================================\n[MetricMaps]" "\n// Creation of maps:\noccupancyGrid_count\t\t\t= " "1\ngasGrid_count\t\t\t\t= 0\nlandmarksMap_count\t\t\t= " "0\nbeaconMap_count\t\t\t\t= 0\npointsMap_count\t\t\t\t= 1\n\n// " "Selection of map for likelihood: (fuseAll=-1,occGrid=0, " "points=1,landmarks=2,gasGrid=3)\nlikelihoodMapSelection\t\t= " "0\n\n// Enables (1) / Disables (0) insertion into specific " "maps:\nenableInsertion_pointsMap\t= " "1\nenableInsertion_landmarksMap= 1\nenableInsertion_beaconMap\t= " "1\nenableInsertion_gridMaps\t= 1\nenableInsertion_gasGridMaps\t= " "1\n\n// ====================================================\n// " "MULTIMETRIC MAP: OccGrid #00\n// " "====================================================\n// Creation " "Options for OccupancyGridMap " "00:\n[MetricMaps_occupancyGrid_00_creationOpts]\nresolution=0." "07\ndisableSaveAs3DObject=0\n\n\n// Insertion Options for " "OccupancyGridMap " "00:\n[MetricMaps_occupancyGrid_00_insertOpts]" "\nmapAltitude\t\t\t\t\t\t\t= 0\nuseMapAltitude\t\t\t\t\t\t= " "0\nmaxDistanceInsertion\t\t\t\t= " "35\nmaxOccupancyUpdateCertainty\t\t\t= " "0.60\nconsiderInvalidRangesAsFreeSpace\t= " "1\nminLaserScanNoiseStd\t\t\t\t= " "0.001\nhorizontalTolerance\t\t\t\t\t= 0.9 // In " "degrees\n\nCFD_features_gaussian_size\t\t\t= " "3\nCFD_features_median_size\t\t\t= 3\n\n\n// Likelihood Options for " "OccupancyGridMap " "00:\n[MetricMaps_occupancyGrid_00_likelihoodOpts]" "\nlikelihoodMethod\t\t\t\t= 4 // 0=MI, 1=Beam Model, 2=RSLC, " "3=Cells Difs, 4=LF_Thrun, 5=LF_II\nLF_decimation\t\t\t\t\t= " "4\nLF_stdHit\t\t\t\t\t\t= 0.10\nLF_maxCorrsDistance\t\t\t\t= " "0.50\nLF_zHit\t\t\t\t\t\t\t= 0.999\nLF_zRandom\t\t\t\t\t\t= " "0.001\nLF_maxRange\t\t\t\t\t\t= 60\nLF_alternateAverageMethod\t\t= " "0\nenableLikelihoodCache\t\t\t= 1\n\n// " "====================================================\n// " "MULTIMETRIC MAP: PointMap #00\n// " "====================================================\n// Creation " "Options for Pointsmap 00:\n// Creation Options for OccupancyGridMap " "00:\n[MetricMaps_PointsMap_00_creationOpts]\ndisableSaveAs3DObject=" "0\n\n[MetricMaps_PointsMap_00_insertOpts]" "\nminDistBetweenLaserPoints=0.05 // The minimum distance between " "points (in 3D): If two points are too close, one of them is not " "inserted into the map.\nisPlanarMap=0 // If set " "to true, only HORIZONTAL (i.e. XY plane) measurements will be " "inserted in the map. Default value is false, thus 3D maps are " "generated\n"), wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER | wxTE_PROCESS_TAB | wxTE_MULTILINE | wxHSCROLL | wxALWAYS_SHOW_SB, wxDefaultValidator, _T("ID_TEXTCTRL2")); wxFont edRestParamsFont( 8, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL, wxNORMAL, false, wxEmptyString, wxFONTENCODING_DEFAULT); edRestParams->SetFont(edRestParamsFont); FlexGridSizer18->Add( edRestParams, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 1); FlexGridSizer16->Add( FlexGridSizer18, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 0); panConfig->SetSizer(FlexGridSizer16); FlexGridSizer16->Fit(panConfig); FlexGridSizer16->SetSizeHints(panConfig); panMapView = new wxPanel( Notebook1, ID_PANEL4, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL4")); FlexGridSizer4 = new wxFlexGridSizer(1, 1, 0, 0); FlexGridSizer4->AddGrowableCol(0); FlexGridSizer4->AddGrowableRow(0); SplitterWindow1 = new wxSplitterWindow( panMapView, ID_SPLITTERWINDOW1, wxPoint(176, 320), wxDefaultSize, wxSP_3D | wxSP_LIVE_UPDATE, _T("ID_SPLITTERWINDOW1")); SplitterWindow1->SetMinSize(wxSize(10, 10)); SplitterWindow1->SetMinimumPaneSize(10); Panel3 = new wxPanel( SplitterWindow1, ID_PANEL5, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL5")); FlexGridSizer5 = new wxFlexGridSizer(3, 1, 0, 0); FlexGridSizer5->AddGrowableCol(0); FlexGridSizer5->AddGrowableRow(1); FlexGridSizer7 = new wxFlexGridSizer(0, 2, 0, 0); StaticText2 = new wxStaticText( Panel3, ID_STATICTEXT2, _("Select hypothesis:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT2")); FlexGridSizer7->Add( StaticText2, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); cbHypos = new wxChoice( Panel3, ID_CHOICE1, wxDefaultPosition, wxDefaultSize, 0, nullptr, 0, wxDefaultValidator, _T("ID_CHOICE1")); FlexGridSizer7->Add( cbHypos, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); FlexGridSizer5->Add( FlexGridSizer7, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 0); Notebook2 = new wxNotebook( Panel3, ID_NOTEBOOK2, wxDefaultPosition, wxDefaultSize, wxNB_MULTILINE, _T("ID_NOTEBOOK2")); panTreeView = new wxPanel( Notebook2, ID_PANEL15, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL15")); FlexGridSizer15 = new wxFlexGridSizer(2, 1, 0, 0); FlexGridSizer15->AddGrowableCol(0); FlexGridSizer15->AddGrowableRow(0); treeView = new wxTreeCtrl( panTreeView, ID_TREECTRL1, wxDefaultPosition, wxDefaultSize, wxTR_LINES_AT_ROOT | wxTR_MULTIPLE | wxTR_DEFAULT_STYLE | wxVSCROLL | wxHSCROLL, wxDefaultValidator, _T("ID_TREECTRL1")); FlexGridSizer15->Add( treeView, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 0); panTreeView->SetSizer(FlexGridSizer15); FlexGridSizer15->Fit(panTreeView); FlexGridSizer15->SetSizeHints(panTreeView); Panel15 = new wxPanel( Notebook2, ID_PANEL17, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL17")); Panel14 = new wxPanel( Notebook2, ID_PANEL16, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL16")); Notebook2->AddPage(panTreeView, _("Tree view"), true); Notebook2->AddPage(Panel15, _("All nodes"), false); Notebook2->AddPage(Panel14, _("All arcs"), false); FlexGridSizer5->Add( Notebook2, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 1); Panel8 = new wxPanel( Panel3, ID_PANEL8, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL8")); FlexGridSizer8 = new wxFlexGridSizer(2, 1, 0, 0); FlexGridSizer8->AddGrowableCol(0); FlexGridSizer8->AddGrowableRow(0); BoxSizer3 = new wxBoxSizer(wxHORIZONTAL); StaticText5 = new wxStaticText( Panel8, ID_STATICTEXT5, _("Edit the map"), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTRE, _T("ID_STATICTEXT5")); wxFont StaticText5Font = wxSystemSettings::GetFont(wxSYS_SYSTEM_FONT); if (!StaticText5Font.Ok()) StaticText5Font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); StaticText5Font.SetPointSize( (int)(StaticText5Font.GetPointSize() * 1.000000)); StaticText5Font.SetWeight(wxFONTWEIGHT_BOLD); StaticText5->SetFont(StaticText5Font); BoxSizer3->Add( StaticText5, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); FlexGridSizer8->Add( BoxSizer3, 1, wxALL | wxALIGN_BOTTOM | wxALIGN_CENTER_HORIZONTAL, 0); Panel12 = new wxPanel( Panel8, ID_PANEL14, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL14")); FlexGridSizer14 = new wxFlexGridSizer(2, 1, 0, 0); FlexGridSizer14->AddGrowableCol(0); FlexGridSizer6 = new wxFlexGridSizer(0, 3, 0, 0); btnImportArea = new wxCustomButton( Panel12, ID_BUTTON7, _("Import area/metric map..."), wxNullBitmap, wxDefaultPosition, wxDefaultSize, wxCUSTBUT_BUTTON | wxCUSTBUT_BOTTOM | wxCUSTBUT_FLAT, wxDefaultValidator, _T("ID_BUTTON7")); btnImportArea->SetLabelMargin(wxSize(10, 2)); btnImportArea->SetBitmapMargin(wxSize(-1, 3)); FlexGridSizer6->Add( btnImportArea, 1, wxALL | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); FlexGridSizer14->Add( FlexGridSizer6, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 0); FlexGridSizer9 = new wxFlexGridSizer(0, 3, 0, 0); btnAddNode = new wxCustomButton( Panel12, ID_BUTTON8, _("Add node..."), wxNullBitmap, wxDefaultPosition, wxDefaultSize, wxCUSTBUT_BUTTON | wxCUSTBUT_BOTTOM | wxCUSTBUT_FLAT, wxDefaultValidator, _T("ID_BUTTON8")); btnAddNode->SetLabelMargin(wxSize(10, 2)); btnAddNode->SetBitmapMargin(wxSize(-1, 3)); FlexGridSizer9->Add( btnAddNode, 1, wxALL | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); btnAddArc = new wxCustomButton( Panel12, ID_BUTTON9, _("Add arc..."), wxNullBitmap, wxDefaultPosition, wxDefaultSize, wxCUSTBUT_BUTTON | wxCUSTBUT_BOTTOM | wxCUSTBUT_FLAT, wxDefaultValidator, _T("ID_BUTTON9")); btnAddArc->SetLabelMargin(wxSize(10, 2)); btnAddArc->SetBitmapMargin(wxSize(-1, 3)); FlexGridSizer9->Add(btnAddArc, 1, wxALL | wxALIGN_LEFT | wxALIGN_BOTTOM, 5); FlexGridSizer14->Add( FlexGridSizer9, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 0); Panel12->SetSizer(FlexGridSizer14); FlexGridSizer14->Fit(Panel12); FlexGridSizer14->SetSizeHints(Panel12); FlexGridSizer8->Add( Panel12, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 0); Panel8->SetSizer(FlexGridSizer8); FlexGridSizer8->Fit(Panel8); FlexGridSizer8->SetSizeHints(Panel8); FlexGridSizer5->Add( Panel8, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 0); Panel3->SetSizer(FlexGridSizer5); FlexGridSizer5->Fit(Panel3); FlexGridSizer5->SetSizeHints(Panel3); Panel4 = new wxPanel( SplitterWindow1, ID_PANEL7, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL7")); BoxSizer1 = new wxBoxSizer(wxHORIZONTAL); SplitterWindow2 = new wxSplitterWindow( Panel4, ID_SPLITTERWINDOW2, wxDefaultPosition, wxDefaultSize, wxSP_3D | wxSP_LIVE_UPDATE, _T("ID_SPLITTERWINDOW2")); SplitterWindow2->SetMinSize(wxSize(60, 60)); SplitterWindow2->SetMinimumPaneSize(60); Panel6 = new wxPanel( SplitterWindow2, ID_PANEL10, wxDefaultPosition, wxSize(100, 100), wxTAB_TRAVERSAL, _T("ID_PANEL10")); Panel6->SetMinSize(wxSize(100, 100)); FlexGridSizer10 = new wxFlexGridSizer(0, 1, 0, 0); FlexGridSizer10->AddGrowableCol(0); FlexGridSizer10->AddGrowableRow(1); StaticText3 = new wxStaticText( Panel6, ID_STATICTEXT3, _("Global HMT map"), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTRE, _T("ID_STATICTEXT3")); wxFont StaticText3Font = wxSystemSettings::GetFont(wxSYS_SYSTEM_FONT); if (!StaticText3Font.Ok()) StaticText3Font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); StaticText3Font.SetPointSize( (int)(StaticText3Font.GetPointSize() * 1.000000)); StaticText3Font.SetWeight(wxFONTWEIGHT_BOLD); StaticText3->SetFont(StaticText3Font); FlexGridSizer10->Add( StaticText3, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); Panel7 = new wxPanel( Panel6, ID_PANEL11, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL11")); FlexGridSizer11 = new wxFlexGridSizer(0, 1, 0, 0); FlexGridSizer11->AddGrowableCol(0); FlexGridSizer11->AddGrowableRow(0); m_glGlobalHMTMap = new CMyGLCanvas( Panel7, ID_XY_GLCANVAS, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_XY_GLCANVAS")); FlexGridSizer11->Add( m_glGlobalHMTMap, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 0); Panel7->SetSizer(FlexGridSizer11); FlexGridSizer11->Fit(Panel7); FlexGridSizer11->SetSizeHints(Panel7); FlexGridSizer10->Add( Panel7, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); Panel6->SetSizer(FlexGridSizer10); FlexGridSizer10->SetSizeHints(Panel6); Panel10 = new wxPanel( SplitterWindow2, ID_PANEL12, wxDefaultPosition, wxSize(100, 100), wxTAB_TRAVERSAL, _T("ID_PANEL12")); Panel10->SetMinSize(wxSize(100, 100)); FlexGridSizer12 = new wxFlexGridSizer(0, 1, 0, 0); FlexGridSizer12->AddGrowableCol(0); FlexGridSizer12->AddGrowableRow(1); StaticText4 = new wxStaticText( Panel10, ID_STATICTEXT4, _("Selected area local map"), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTRE, _T("ID_STATICTEXT4")); wxFont StaticText4Font = wxSystemSettings::GetFont(wxSYS_SYSTEM_FONT); if (!StaticText4Font.Ok()) StaticText4Font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); StaticText4Font.SetPointSize( (int)(StaticText4Font.GetPointSize() * 1.000000)); StaticText4Font.SetWeight(wxFONTWEIGHT_BOLD); StaticText4->SetFont(StaticText4Font); FlexGridSizer12->Add( StaticText4, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); Panel11 = new wxPanel( Panel10, ID_PANEL13, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL13")); FlexGridSizer13 = new wxFlexGridSizer(0, 1, 0, 0); FlexGridSizer13->AddGrowableCol(0); FlexGridSizer13->AddGrowableRow(0); m_glLocalArea = new CMyGLCanvas( Panel11, ID_CUSTOM1, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_CUSTOM1")); FlexGridSizer13->Add( m_glLocalArea, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 0); Panel11->SetSizer(FlexGridSizer13); FlexGridSizer13->Fit(Panel11); FlexGridSizer13->SetSizeHints(Panel11); FlexGridSizer12->Add( Panel11, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); Panel10->SetSizer(FlexGridSizer12); FlexGridSizer12->SetSizeHints(Panel10); SplitterWindow2->SplitHorizontally(Panel6, Panel10); BoxSizer1->Add( SplitterWindow2, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); Panel4->SetSizer(BoxSizer1); BoxSizer1->Fit(Panel4); BoxSizer1->SetSizeHints(Panel4); SplitterWindow1->SplitVertically(Panel3, Panel4); FlexGridSizer4->Add( SplitterWindow1, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 0); panMapView->SetSizer(FlexGridSizer4); FlexGridSizer4->Fit(panMapView); FlexGridSizer4->SetSizeHints(panMapView); Notebook1->AddPage(panConfig, _("SLAM parameters"), false); Notebook1->AddPage(panMapView, _("HMT-MAP view"), true); FlexGridSizer3->Add( Notebook1, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 1); Panel2->SetSizer(FlexGridSizer3); FlexGridSizer3->Fit(Panel2); FlexGridSizer3->SetSizeHints(Panel2); FlexGridSizer1->Add( Panel2, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_BOTTOM, 0); SetSizer(FlexGridSizer1); MenuBar1 = new wxMenuBar(); Menu1 = new wxMenu(); MenuItem3 = new wxMenuItem( Menu1, ID_MENUITEM1, _("Reset HMT map"), wxEmptyString, wxITEM_NORMAL); Menu1->Append(MenuItem3); Menu1->AppendSeparator(); MenuItem4 = new wxMenuItem( Menu1, ID_MENUITEM2, _("Load state..."), wxEmptyString, wxITEM_NORMAL); Menu1->Append(MenuItem4); MenuItem5 = new wxMenuItem( Menu1, ID_MENUITEM3, _("Save state..."), wxEmptyString, wxITEM_NORMAL); Menu1->Append(MenuItem5); Menu1->AppendSeparator(); MenuItem1 = new wxMenuItem( Menu1, idMenuQuit, _("Quit\tAlt-F4"), _("Quit the application"), wxITEM_NORMAL); Menu1->Append(MenuItem1); MenuBar1->Append(Menu1, _("&File")); Menu3 = new wxMenu(); MenuItem8 = new wxMenuItem( Menu3, ID_MENUITEM6, _("Set parameters"), wxEmptyString, wxITEM_NORMAL); Menu3->Append(MenuItem8); Menu3->AppendSeparator(); MenuItem6 = new wxMenuItem( Menu3, ID_MENUITEM4, _("Start SLAM"), wxEmptyString, wxITEM_NORMAL); Menu3->Append(MenuItem6); MenuItem7 = new wxMenuItem( Menu3, ID_MENUITEM5, _("Pause SLAM"), wxEmptyString, wxITEM_NORMAL); Menu3->Append(MenuItem7); MenuBar1->Append(Menu3, _("Map Building")); Menu2 = new wxMenu(); MenuItem2 = new wxMenuItem( Menu2, idMenuAbout, _("About\tF1"), _("Show info about this application"), wxITEM_NORMAL); Menu2->Append(MenuItem2); MenuBar1->Append(Menu2, _("Help")); SetMenuBar(MenuBar1); StatusBar1 = new wxStatusBar(this, ID_STATUSBAR1, 0, _T("ID_STATUSBAR1")); int __wxStatusBarWidths_1[1] = {-1}; int __wxStatusBarStyles_1[1] = {wxSB_NORMAL}; StatusBar1->SetFieldsCount(1, __wxStatusBarWidths_1); StatusBar1->SetStatusStyles(1, __wxStatusBarStyles_1); SetStatusBar(StatusBar1); FlexGridSizer1->SetSizeHints(this); Bind(wxEVT_BUTTON, &hmt_slam_guiFrame::OnbtnResetClick, this, ID_BUTTON1); Bind(wxEVT_BUTTON, &hmt_slam_guiFrame::OnbtnLoadClick, this, ID_BUTTON2); Bind(wxEVT_BUTTON, &hmt_slam_guiFrame::OnbtnSaveClick, this, ID_BUTTON3); Bind(wxEVT_BUTTON, &hmt_slam_guiFrame::OnbtnStartClick, this, ID_BUTTON4); Bind(wxEVT_BUTTON, &hmt_slam_guiFrame::OnbtnPauseClick, this, ID_BUTTON6); Bind( wxEVT_BUTTON, &hmt_slam_guiFrame::OnbtnShowLogWinClick, this, ID_BUTTON12); Bind(wxEVT_BUTTON, &hmt_slam_guiFrame::OnAbout, this, ID_BUTTON10); Bind(wxEVT_BUTTON, &hmt_slam_guiFrame::OnQuit, this, ID_BUTTON5); Bind( wxEVT_BUTTON, &hmt_slam_guiFrame::OnbtnPickRawlogClick, this, ID_BUTTON11); Bind( wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED, &hmt_slam_guiFrame::OnNotebook2PageChanged, this, ID_NOTEBOOK2); Bind(wxEVT_MENU, &hmt_slam_guiFrame::OnbtnResetClick, this, ID_MENUITEM1); Bind(wxEVT_MENU, &hmt_slam_guiFrame::OnbtnLoadClick, this, ID_MENUITEM2); Bind(wxEVT_MENU, &hmt_slam_guiFrame::OnbtnSaveClick, this, ID_MENUITEM3); Bind(wxEVT_MENU, &hmt_slam_guiFrame::OnQuit, this, idMenuQuit); Bind( wxEVT_MENU, &hmt_slam_guiFrame::OnMenuSetSLAMParameter, this, ID_MENUITEM6); Bind(wxEVT_MENU, &hmt_slam_guiFrame::OnbtnStartClick, this, ID_MENUITEM4); Bind(wxEVT_MENU, &hmt_slam_guiFrame::OnbtnPauseClick, this, ID_MENUITEM5); Bind(wxEVT_MENU, &hmt_slam_guiFrame::OnAbout, this, idMenuAbout); //*) // Initialize data ======================================================== // Create log window: m_logWin = new CDlgLog(this); // { wxCommandEvent dum; OnbtnShowLogWinClick(dum); } cout << "Initializing HMT-SLAM visual application...\n"; m_hmtslam = std::make_unique<CHMTSLAM>(); cout << "Initializing HMT-SLAM visual application DONE.\n"; // Reset HMT map: { wxCommandEvent dum; OnbtnResetClick(dum); } // Launch Thread: m_hThreadHMTSLAM = std::thread(&hmt_slam_guiFrame::thread_HMTSLAM, this); // Set default size of the window: this->SetSize(600, 500); this->Maximize(); } hmt_slam_guiFrame::~hmt_slam_guiFrame() { WX_START_TRY // Stop thread: m_thread_in_queue.push(new TThreadMsg(OP_QUIT_THREAD)); if (m_hThreadHMTSLAM.joinable()) m_hThreadHMTSLAM.join(); //(*Destroy(hmt_slam_guiFrame) //*) WX_END_TRY } void hmt_slam_guiFrame::OnQuit(wxCommandEvent&) { Close(); } void hmt_slam_guiFrame::OnAbout(wxCommandEvent&) { mrpt::gui::show_mrpt_about_box_wxWidgets(this, "htm-slam-gui"); } void hmt_slam_guiFrame::OnNotebook2PageChanged(wxNotebookEvent& event) {} void hmt_slam_guiFrame::loadHMTConfigFromSettings() { std::string s; // From the text block: s += std::string(edRestParams->GetValue().mb_str()); CConfigFileMemory cfg(s); // From GUI controls: cfg.write( "HMT-SLAM", "rawlog_file", std::string(this->edInputRawlog->GetValue().mb_str())); // Load m_hmtslam->loadOptions(cfg); } // RESET ======= void hmt_slam_guiFrame::OnbtnResetClick(wxCommandEvent& event) { WX_START_TRY this->loadHMTConfigFromSettings(); m_hmtslam->initializeEmptyMap(); updateAllMapViews(); WX_END_TRY } void hmt_slam_guiFrame::OnbtnLoadClick(wxCommandEvent& event) { string fil; if (AskForOpenHMTMap(fil)) loadHTMSLAMFromFile(fil); } bool hmt_slam_guiFrame::loadHTMSLAMFromFile(const std::string& filePath) { WX_START_TRY if (!fileExists(filePath)) { wxMessageBox( string(string("File doesn't exist:\n") + filePath).c_str(), _("Error loading file"), wxOK, this); return false; } wxBusyCursor busy; // Save the path WX_START_TRY string the_path(extractFileDirectory(filePath)); // iniFile->write(iniFileSect,"LastDir", the_path ); WX_END_TRY // Load { CFileGZInputStream f(filePath); mrpt::serialization::archiveFrom(f) >> *m_hmtslam; } m_curFileOpen = filePath; // Refresh views: // --------------------------- // The tree: rebuildTreeView(); // The global map: updateGlobalMapView(); return true; WX_END_TRY return false; } void hmt_slam_guiFrame::rebuildTreeView() { WX_START_TRY wxBusyCursor waitCursor; treeView->DeleteAllItems(); treeView->SetQuickBestSize(true); // Root element & Areas: wxTreeItemId root = treeView->AddRoot(_("Areas"), 0, -1, nullptr); CHierarchicalMHMap::const_iterator it; size_t i; for (i = 0, it = m_hmtslam->m_map.begin(); it != m_hmtslam->m_map.end(); it++, i++) { string str = format("Area %i", (int)it->second->getID()); // wxTreeItemId treeNode = treeView->AppendItem( root, str.c_str(), 0, -1, new CItemData(it->second, i)); } treeView->ExpandAll(); // List of hypotheses: cbHypos->Clear(); for (const auto& h : m_hmtslam->m_LMHs) cbHypos->Append(format("%i", (int)h.first)); cbHypos->SetSelection(0); WX_END_TRY } //------------------------------------------------------------------------ // Asks the user for a file, return false if user cancels //------------------------------------------------------------------------ bool hmt_slam_guiFrame::AskForOpenHMTMap(std::string& fil) { wxString caption = wxT("Choose a file to open"); wxString wildcard = wxT( "HMT-SLAM files (*.hmtslam;*.hmtslam.gz)|*.hmtslam;*.hmtslam.gz|All " "files (*.*)|*.*"); wxString defaultDir; wxString defaultFilename; wxFileDialog dialog( this, caption, defaultDir, defaultFilename, wildcard, wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (dialog.ShowModal() == wxID_OK) { fil = string(dialog.GetPath().mb_str()); return true; } else return false; } void hmt_slam_guiFrame::OnbtnSaveClick(wxCommandEvent& event) {} void hmt_slam_guiFrame::OnbtnStartClick(wxCommandEvent& event) { m_thread_in_queue.push(new TThreadMsg(OP_START_SLAM)); } void hmt_slam_guiFrame::OnbtnPauseClick(wxCommandEvent& event) { m_thread_in_queue.push(new TThreadMsg(OP_PAUSE_SLAM)); } void hmt_slam_guiFrame::OnMenuSetSLAMParameter(wxCommandEvent& event) {} void hmt_slam_guiFrame::OnbtnPickRawlogClick(wxCommandEvent& event) {} void hmt_slam_guiFrame::OnbtnShowLogWinClick(wxCommandEvent& event) { if (m_logWin->IsVisible()) { m_logWin->Hide(); btnShowLogWin->SetValue(false); btnShowLogWin->Refresh(); } else { m_logWin->Show(); btnShowLogWin->SetValue(true); btnShowLogWin->Refresh(); } }
40.756311
80
0.709545
ros2-gbp
816420d3307460a8cacc078101748f9e1e32d1ba
3,003
cpp
C++
test-suite/generated-src/wasm/NativeConstantsInterface.cpp
paulo-coutinho/djinni
72fc4f08e77338bd80f1f47071c5b541d89b9bc9
[ "Apache-2.0" ]
null
null
null
test-suite/generated-src/wasm/NativeConstantsInterface.cpp
paulo-coutinho/djinni
72fc4f08e77338bd80f1f47071c5b541d89b9bc9
[ "Apache-2.0" ]
null
null
null
test-suite/generated-src/wasm/NativeConstantsInterface.cpp
paulo-coutinho/djinni
72fc4f08e77338bd80f1f47071c5b541d89b9bc9
[ "Apache-2.0" ]
null
null
null
// AUTOGENERATED FILE - DO NOT MODIFY! // This file was generated by Djinni from constants.djinni #include "NativeConstantsInterface.hpp" // my header #include "NativeConstantRecord.hpp" namespace djinni_generated { em::val NativeConstantsInterface::cppProxyMethods() { static const em::val methods = em::val::array(std::vector<std::string> { "dummy", }); return methods; } void NativeConstantsInterface::dummy(const CppType& self) { self->dummy(); } EMSCRIPTEN_BINDINGS(testsuite_constants_interface) { ::djinni::DjinniClass_<::testsuite::ConstantsInterface>("testsuite_ConstantsInterface", "testsuite.ConstantsInterface") .smart_ptr<std::shared_ptr<::testsuite::ConstantsInterface>>("testsuite_ConstantsInterface") .function("nativeDestroy", &NativeConstantsInterface::nativeDestroy) .function("dummy", NativeConstantsInterface::dummy) ; } namespace { EM_JS(void, djinni_init_testsuite_constants_interface_consts, (), { if (!('testsuite_ConstantsInterface' in Module)) { Module.testsuite_ConstantsInterface = {}; } Module.testsuite_ConstantsInterface.BOOL_CONSTANT = true; Module.testsuite_ConstantsInterface.I8_CONSTANT = 1; Module.testsuite_ConstantsInterface.I16_CONSTANT = 2; Module.testsuite_ConstantsInterface.I32_CONSTANT = 3; Module.testsuite_ConstantsInterface.I64_CONSTANT = BigInt("4"); Module.testsuite_ConstantsInterface.F32_CONSTANT = 5.0; Module.testsuite_ConstantsInterface.F64_CONSTANT = 5.0; Module.testsuite_ConstantsInterface.OPT_BOOL_CONSTANT = true; Module.testsuite_ConstantsInterface.OPT_I8_CONSTANT = 1; Module.testsuite_ConstantsInterface.OPT_I16_CONSTANT = 2; Module.testsuite_ConstantsInterface.OPT_I32_CONSTANT = 3; Module.testsuite_ConstantsInterface.OPT_I64_CONSTANT = 4; Module.testsuite_ConstantsInterface.OPT_F32_CONSTANT = 5.0; Module.testsuite_ConstantsInterface.OPT_F64_CONSTANT = 5.0; Module.testsuite_ConstantsInterface.STRING_CONSTANT = "string-constant"; Module.testsuite_ConstantsInterface.OPT_STRING_CONSTANT = "string-constant"; Module.testsuite_ConstantsInterface.OBJECT_CONSTANT = { someInteger: Module.testsuite_ConstantsInterface.I32_CONSTANT, someString: Module.testsuite_ConstantsInterface.STRING_CONSTANT } ; Module.testsuite_ConstantsInterface.UPPER_CASE_CONSTANT = "upper-case-constant"; }) } void NativeConstantsInterface::staticInitializeConstants() { static std::once_flag initOnce; std::call_once(initOnce, [] { djinni_init_testsuite_constants_interface_consts(); ::djinni::djinni_register_name_in_ns("testsuite_ConstantsInterface", "testsuite.ConstantsInterface"); }); } EMSCRIPTEN_BINDINGS(testsuite_constants_interface_consts) { NativeConstantsInterface::staticInitializeConstants(); } } // namespace djinni_generated
42.9
123
0.744589
paulo-coutinho
8164481fa9f088871cfce32ada58ef4866d6305d
10,555
cpp
C++
sumo/src/netimport/NIImporter_MATSim.cpp
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
null
null
null
sumo/src/netimport/NIImporter_MATSim.cpp
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
null
null
null
sumo/src/netimport/NIImporter_MATSim.cpp
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
2
2017-12-14T16:41:59.000Z
2020-10-16T17:51:27.000Z
/****************************************************************************/ /// @file NIImporter_MATSim.cpp /// @author Daniel Krajzewicz /// @author Jakob Erdmann /// @author Michael Behrisch /// @date Tue, 26.04.2011 /// @version $Id$ /// // Importer for networks stored in MATSim format /****************************************************************************/ // SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/ // Copyright (C) 2001-2017 DLR (http://www.dlr.de/) and contributors /****************************************************************************/ // // This file is part of SUMO. // SUMO 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. // /****************************************************************************/ // =========================================================================== // included modules // =========================================================================== #ifdef _MSC_VER #include <windows_config.h> #else #include <config.h> #endif #include <set> #include <functional> #include <sstream> #include <utils/xml/SUMOSAXHandler.h> #include <utils/common/ToString.h> #include <utils/common/MsgHandler.h> #include <netbuild/NBEdge.h> #include <netbuild/NBEdgeCont.h> #include <netbuild/NBNode.h> #include <netbuild/NBNodeCont.h> #include <netbuild/NBNetBuilder.h> #include <utils/geom/GeoConvHelper.h> #include <utils/options/OptionsCont.h> #include <utils/common/FileHelpers.h> #include <utils/common/StringTokenizer.h> #include <utils/common/TplConvert.h> #include <utils/xml/XMLSubSys.h> #include "NILoader.h" #include "NIImporter_MATSim.h" // =========================================================================== // static variables // =========================================================================== StringBijection<int>::Entry NIImporter_MATSim::matsimTags[] = { { "network", NIImporter_MATSim::MATSIM_TAG_NETWORK }, { "node", NIImporter_MATSim::MATSIM_TAG_NODE }, { "link", NIImporter_MATSim::MATSIM_TAG_LINK }, { "links", NIImporter_MATSim::MATSIM_TAG_LINKS }, { "", NIImporter_MATSim::MATSIM_TAG_NOTHING } }; StringBijection<int>::Entry NIImporter_MATSim::matsimAttrs[] = { { "id", NIImporter_MATSim::MATSIM_ATTR_ID }, { "x", NIImporter_MATSim::MATSIM_ATTR_X }, { "y", NIImporter_MATSim::MATSIM_ATTR_Y }, { "from", NIImporter_MATSim::MATSIM_ATTR_FROM }, { "to", NIImporter_MATSim::MATSIM_ATTR_TO }, { "length", NIImporter_MATSim::MATSIM_ATTR_LENGTH }, { "freespeed", NIImporter_MATSim::MATSIM_ATTR_FREESPEED }, { "capacity", NIImporter_MATSim::MATSIM_ATTR_CAPACITY }, { "permlanes", NIImporter_MATSim::MATSIM_ATTR_PERMLANES }, { "oneway", NIImporter_MATSim::MATSIM_ATTR_ONEWAY }, { "modes", NIImporter_MATSim::MATSIM_ATTR_MODES }, { "origid", NIImporter_MATSim::MATSIM_ATTR_ORIGID }, { "capperiod", NIImporter_MATSim::MATSIM_ATTR_CAPPERIOD }, { "capDivider", NIImporter_MATSim::MATSIM_ATTR_CAPDIVIDER }, { "", NIImporter_MATSim::MATSIM_ATTR_NOTHING } }; // =========================================================================== // method definitions // =========================================================================== // --------------------------------------------------------------------------- // static methods // --------------------------------------------------------------------------- void NIImporter_MATSim::loadNetwork(const OptionsCont& oc, NBNetBuilder& nb) { // check whether the option is set (properly) if (!oc.isSet("matsim-files")) { return; } /* Parse file(s) * Each file is parsed twice: first for nodes, second for edges. */ std::vector<std::string> files = oc.getStringVector("matsim-files"); // load nodes, first NodesHandler nodesHandler(nb.getNodeCont()); for (std::vector<std::string>::const_iterator file = files.begin(); file != files.end(); ++file) { // nodes if (!FileHelpers::isReadable(*file)) { WRITE_ERROR("Could not open matsim-file '" + *file + "'."); return; } nodesHandler.setFileName(*file); PROGRESS_BEGIN_MESSAGE("Parsing nodes from matsim-file '" + *file + "'"); if (!XMLSubSys::runParser(nodesHandler, *file)) { return; } PROGRESS_DONE_MESSAGE(); } // load edges, then EdgesHandler edgesHandler(nb.getNodeCont(), nb.getEdgeCont(), oc.getBool("matsim.keep-length"), oc.getBool("matsim.lanes-from-capacity"), NBCapacity2Lanes(oc.getFloat("lanes-from-capacity.norm"))); for (std::vector<std::string>::const_iterator file = files.begin(); file != files.end(); ++file) { // edges edgesHandler.setFileName(*file); PROGRESS_BEGIN_MESSAGE("Parsing edges from matsim-file '" + *file + "'"); XMLSubSys::runParser(edgesHandler, *file); PROGRESS_DONE_MESSAGE(); } } // --------------------------------------------------------------------------- // definitions of NIImporter_MATSim::NodesHandler-methods // --------------------------------------------------------------------------- NIImporter_MATSim::NodesHandler::NodesHandler(NBNodeCont& toFill) : GenericSAXHandler(matsimTags, MATSIM_TAG_NOTHING, matsimAttrs, MATSIM_ATTR_NOTHING, "matsim - file"), myNodeCont(toFill) { } NIImporter_MATSim::NodesHandler::~NodesHandler() {} void NIImporter_MATSim::NodesHandler::myStartElement(int element, const SUMOSAXAttributes& attrs) { if (element != MATSIM_TAG_NODE) { return; } // get the id, report a warning if not given or empty... bool ok = true; std::string id = attrs.get<std::string>(MATSIM_ATTR_ID, 0, ok); double x = attrs.get<double>(MATSIM_ATTR_X, id.c_str(), ok); double y = attrs.get<double>(MATSIM_ATTR_Y, id.c_str(), ok); if (!ok) { return; } Position pos(x, y); if (!NBNetBuilder::transformCoordinate(pos)) { WRITE_ERROR("Unable to project coordinates for node '" + id + "'."); } NBNode* node = new NBNode(id, pos); if (!myNodeCont.insert(node)) { delete node; WRITE_ERROR("Could not add node '" + id + "'. Probably declared twice."); } } // --------------------------------------------------------------------------- // definitions of NIImporter_MATSim::EdgesHandler-methods // --------------------------------------------------------------------------- NIImporter_MATSim::EdgesHandler::EdgesHandler(const NBNodeCont& nc, NBEdgeCont& toFill, bool keepEdgeLengths, bool lanesFromCapacity, NBCapacity2Lanes capacity2Lanes) : GenericSAXHandler(matsimTags, MATSIM_TAG_NOTHING, matsimAttrs, MATSIM_ATTR_NOTHING, "matsim - file"), myNodeCont(nc), myEdgeCont(toFill), myCapacityNorm(3600), myKeepEdgeLengths(keepEdgeLengths), myLanesFromCapacity(lanesFromCapacity), myCapacity2Lanes(capacity2Lanes) { } NIImporter_MATSim::EdgesHandler::~EdgesHandler() { } void NIImporter_MATSim::EdgesHandler::myStartElement(int element, const SUMOSAXAttributes& attrs) { bool ok = true; if (element == MATSIM_TAG_NETWORK) { if (attrs.hasAttribute(MATSIM_ATTR_CAPDIVIDER)) { int capDivider = attrs.get<int>(MATSIM_ATTR_CAPDIVIDER, "network", ok); if (ok) { myCapacityNorm = (double)(capDivider * 3600); } } } if (element == MATSIM_TAG_LINKS) { bool ok = true; std::string capperiod = attrs.get<std::string>(MATSIM_ATTR_CAPPERIOD, "links", ok); StringTokenizer st(capperiod, ":"); if (st.size() != 3) { WRITE_ERROR("Bogus capacity period format; requires 'hh:mm:ss'."); return; } try { int hours = TplConvert::_2int(st.next().c_str()); int minutes = TplConvert::_2int(st.next().c_str()); int seconds = TplConvert::_2int(st.next().c_str()); myCapacityNorm = (double)(hours * 3600 + minutes * 60 + seconds); } catch (NumberFormatException&) { } catch (EmptyData&) { } return; } // parse "link" elements if (element != MATSIM_TAG_LINK) { return; } std::string id = attrs.get<std::string>(MATSIM_ATTR_ID, 0, ok); std::string fromNodeID = attrs.get<std::string>(MATSIM_ATTR_FROM, id.c_str(), ok); std::string toNodeID = attrs.get<std::string>(MATSIM_ATTR_TO, id.c_str(), ok); double length = attrs.get<double>(MATSIM_ATTR_LENGTH, id.c_str(), ok); // override computed? double freeSpeed = attrs.get<double>(MATSIM_ATTR_FREESPEED, id.c_str(), ok); // double capacity = attrs.get<double>(MATSIM_ATTR_CAPACITY, id.c_str(), ok); // override permLanes? double permLanes = attrs.get<double>(MATSIM_ATTR_PERMLANES, id.c_str(), ok); //bool oneWay = attrs.getOpt<bool>(MATSIM_ATTR_ONEWAY, id.c_str(), ok, true); // mandatory? std::string modes = attrs.getOpt<std::string>(MATSIM_ATTR_MODES, id.c_str(), ok, ""); // which values? std::string origid = attrs.getOpt<std::string>(MATSIM_ATTR_ORIGID, id.c_str(), ok, ""); NBNode* fromNode = myNodeCont.retrieve(fromNodeID); NBNode* toNode = myNodeCont.retrieve(toNodeID); if (fromNode == 0) { WRITE_ERROR("Could not find from-node for edge '" + id + "'."); } if (toNode == 0) { WRITE_ERROR("Could not find to-node for edge '" + id + "'."); } if (fromNode == 0 || toNode == 0) { return; } if (myLanesFromCapacity) { permLanes = myCapacity2Lanes.get(capacity); } NBEdge* edge = new NBEdge(id, fromNode, toNode, "", freeSpeed, (int) permLanes, -1, NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET); edge->addParameter("capacity", toString(capacity)); if (myKeepEdgeLengths) { edge->setLoadedLength(length); } if (!myEdgeCont.insert(edge)) { delete edge; WRITE_ERROR("Could not add edge '" + id + "'. Probably declared twice."); } } /****************************************************************************/
40.752896
143
0.560303
iltempe
81652283efc7751d4048f500d3d3bf43791cba7d
882
cpp
C++
D3D9_Renderer/D3D9_Renderer/source/utils/Time.cpp
codenameone-akshat/D3D9_Renderer
9925a827e45f987639f144aebd53974b27ddfb18
[ "MIT" ]
null
null
null
D3D9_Renderer/D3D9_Renderer/source/utils/Time.cpp
codenameone-akshat/D3D9_Renderer
9925a827e45f987639f144aebd53974b27ddfb18
[ "MIT" ]
null
null
null
D3D9_Renderer/D3D9_Renderer/source/utils/Time.cpp
codenameone-akshat/D3D9_Renderer
9925a827e45f987639f144aebd53974b27ddfb18
[ "MIT" ]
null
null
null
#include <sstream> #include <cmath> #include <windows.h> #include "Time.h" #include "Logger.h" namespace renderer { Time::Time() :m_tStart(), m_tEnd(), m_dt(0), m_systemTimer(0), m_numFrames(0), m_fps(0) { } Time::~Time() { } void Time::OnTimerEndCalled() { m_dt = abs(std::chrono::duration_cast<std::chrono::milliseconds>(m_tEnd - m_tStart).count()); if (m_systemTimer >= 1000) //1 second = 1000 milliseconds { OnSystemTimeStep(); } m_systemTimer += m_dt; ++m_numFrames; } void Time::OnSystemTimeStep() { m_fps = m_numFrames; //record number of frames passed in a second. m_systemTimer = 0; m_numFrames = 0; Logger::GetInstance().LogInfo(std::to_string(m_fps).c_str()); } }
21.512195
101
0.540816
codenameone-akshat
816619a9af82fa50d1964046d8dbb038685819f7
1,300
hpp
C++
source/vulkan/reshade_api_swapchain.hpp
Moroque/reshade
bf1d263780a817130f6547dca0432dfe64c8beda
[ "BSD-3-Clause" ]
1
2017-11-27T14:50:39.000Z
2017-11-27T14:50:39.000Z
source/vulkan/reshade_api_swapchain.hpp
kingeric1992/reshade
22f57c10ea87ee83ceb7a5d0cb737cdfb02dedb2
[ "BSD-3-Clause" ]
null
null
null
source/vulkan/reshade_api_swapchain.hpp
kingeric1992/reshade
22f57c10ea87ee83ceb7a5d0cb737cdfb02dedb2
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #pragma once #include "runtime.hpp" namespace reshade::vulkan { class device_impl; class command_queue_impl; class swapchain_impl : public api::api_object_impl<VkSwapchainKHR, runtime> { static const uint32_t NUM_SYNC_SEMAPHORES = 4; public: swapchain_impl(device_impl *device, command_queue_impl *graphics_queue); ~swapchain_impl(); void get_back_buffer(uint32_t index, api::resource *out) final; uint32_t get_back_buffer_count() const final; uint32_t get_current_back_buffer_index() const final; bool on_init(VkSwapchainKHR swapchain, const VkSwapchainCreateInfoKHR &desc, HWND hwnd); void on_reset(); void on_present(VkQueue queue, const uint32_t swapchain_image_index, std::vector<VkSemaphore> &wait); bool on_layer_submit(uint32_t eye, VkImage source, const VkExtent2D &source_extent, VkFormat source_format, VkSampleCountFlags source_samples, uint32_t source_layer_index, const float bounds[4], VkImage *target_image); private: VkQueue _queue = VK_NULL_HANDLE; uint32_t _queue_sync_index = 0; VkSemaphore _queue_sync_semaphores[NUM_SYNC_SEMAPHORES] = {}; uint32_t _swap_index = 0; std::vector<VkImage> _swapchain_images; }; }
30.952381
220
0.783077
Moroque
8167278acbb28ce040a314106f24dfd1162a1142
963
cpp
C++
src/burner/sdl/stringset.cpp
tt-arcade/fba-pi
10407847a98f0d315b05e44f0ecf01824f4558aa
[ "Apache-2.0" ]
null
null
null
src/burner/sdl/stringset.cpp
tt-arcade/fba-pi
10407847a98f0d315b05e44f0ecf01824f4558aa
[ "Apache-2.0" ]
null
null
null
src/burner/sdl/stringset.cpp
tt-arcade/fba-pi
10407847a98f0d315b05e44f0ecf01824f4558aa
[ "Apache-2.0" ]
null
null
null
// StringSet C++ class #include "burner.h" int __cdecl StringSet::Add(TCHAR* szFormat,...) { TCHAR szAdd[256]; int nAddLen = 0; TCHAR* NewMem; va_list Arg; va_start(Arg, szFormat); _vstprintf(szAdd, szFormat, Arg); nAddLen = _tcslen(szAdd); // find out the length of the new text NewMem = (TCHAR*)realloc(szText, (nLen + nAddLen + 1) * sizeof(TCHAR)); if (NewMem) { szText = NewMem; // copy the new text to the end _tcsncpy(szText + nLen, szAdd, nAddLen); nLen += nAddLen; szText[nLen] = 0; // zero-terminate } va_end(Arg); return 0; } int StringSet::Reset() { // Reset the text nLen = 0; szText= (TCHAR*)realloc(szText, sizeof(TCHAR)); if (szText == NULL) { return 1; } szText[0] = 0; return 0; } StringSet::StringSet() { szText = NULL; nLen = 0; Reset(); // reset string to nothing } StringSet::~StringSet() { realloc(szText, 0); // Free BZip text }
18.169811
73
0.598131
tt-arcade
8168533dc2ae946cecfb421b7b282272ac0b17b4
7,492
cxx
C++
src/vw/Image/tests/TestConvolution.cxx
tkeemon/visionworkbench
df59fcb31191e1fc4fecfe1901963da1614a52b1
[ "NASA-1.3" ]
1
2020-06-02T04:06:43.000Z
2020-06-02T04:06:43.000Z
src/vw/Image/tests/TestConvolution.cxx
tkeemon/visionworkbench
df59fcb31191e1fc4fecfe1901963da1614a52b1
[ "NASA-1.3" ]
null
null
null
src/vw/Image/tests/TestConvolution.cxx
tkeemon/visionworkbench
df59fcb31191e1fc4fecfe1901963da1614a52b1
[ "NASA-1.3" ]
null
null
null
// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ // TestConvolution.h #include <gtest/gtest.h> #include <vw/Image/Convolution.h> #include <vw/Image/ImageView.h> #include <vw/Image/PixelTypes.h> #include <vw/Image/Algorithms.h> #include <vw/Image/ImageViewRef.h> #include <vw/Image/Filter.h> #include <test/Helpers.h> using namespace vw; // Simple Comparison template <template<class> class TraitT, class T> static bool bool_trait( T const& /*arg*/ ) { return TraitT<T>::value; } template <class T1, class T2> static bool is_of_type( T2 ) { return boost::is_same<T1,T2>::value; } template <class T1, class T2> static bool has_pixel_type( T2 ) { return boost::is_same<T1,typename T2::pixel_type>::value; } TEST( Convolution, Point1D ) { ImageView<double> src(3,1); src(0,0)=1; src(1,0)=2; src(2,0)=3; double kernel[] = {2,3,-1}; EXPECT_EQ( correlate_1d_at_point(src.origin(), (double*)kernel,3), 5 ); ASSERT_TRUE( is_of_type<double>( correlate_1d_at_point( ImageView<double>().origin(), (double*)0, 0 ) ) ); ASSERT_TRUE( is_of_type<PixelRGB<float> >( correlate_1d_at_point( ImageView<PixelRGB<uint8> >().origin(), (float*)0, 0 ) ) ); } TEST( Convolution, Point2D ) { ImageView<double> src(2,2); src(0,0)=1; src(1,0)=2; src(0,1)=3; src(1,1)=4; ImageView<double> krn(2,2); krn(0,0)=2; krn(1,0)=-1; krn(0,1)=0; krn(1,1)=3; EXPECT_EQ( correlate_2d_at_point(src.origin(),krn.origin(),2,2), 12 ); ASSERT_TRUE( is_of_type<double>( correlate_2d_at_point( ImageView<double>().origin(), ImageView<double>().origin(), 0, 0 ) ) ); ASSERT_TRUE( is_of_type<PixelRGB<float> >( correlate_2d_at_point( ImageView<PixelRGB<uint8> >().origin(), ImageView<float>().origin(), 0, 0 ) ) ); } TEST( Convolution, View ) { ImageView<double> src(2,2); src(0,0)=1; src(1,0)=2; src(0,1)=3; src(1,1)=4; ImageView<double> krn(2,2); krn(0,0)=2; krn(1,0)=-1; krn(0,1)=0; krn(1,1)=3; ConvolutionView<ImageView<double>,ImageView<double>,ZeroEdgeExtension> cnv( src, krn ); // Test individual pixel access EXPECT_EQ( cnv.cols(), 2 ); EXPECT_EQ( cnv.rows(), 2 ); EXPECT_EQ( cnv.planes(), 1 ); EXPECT_EQ( cnv(0,0), 2 ); EXPECT_EQ( cnv(1,0), 3 ); EXPECT_EQ( cnv(0,1), 6 ); EXPECT_EQ( cnv(1,1), 8 ); // Test rasterization ImageView<double> dst = cnv; EXPECT_EQ( dst.cols(), 2 ); EXPECT_EQ( dst.rows(), 2 ); EXPECT_EQ( dst(0,0), 2 ); EXPECT_EQ( dst(1,0), 3 ); EXPECT_EQ( dst(0,1), 6 ); EXPECT_EQ( dst(1,1), 8 ); // Test the traits ASSERT_TRUE( is_of_type<double>( cnv(0,0) ) ); ASSERT_TRUE( is_of_type<double>( *(cnv.origin()) ) ); ASSERT_FALSE( bool_trait<IsResizable>( cnv ) ); ASSERT_FALSE( bool_trait<IsMultiplyAccessible>( cnv ) ); ASSERT_FALSE( bool_trait<IsFloatingPointIndexable>( cnv ) ); ASSERT_TRUE( bool_trait<IsImageView>( cnv ) ); } TEST( Convolution, SeparableView ) { ImageView<double> src(2,2); src(0,0)=1; src(1,0)=2; src(0,1)=3; src(1,1)=4; std::vector<double> krn; krn.push_back(1); krn.push_back(-1); SeparableConvolutionView<ImageView<double>,double,ZeroEdgeExtension> cnv( src, krn, krn ); // Test individual pixel access EXPECT_EQ( cnv.cols(), 2 ); EXPECT_EQ( cnv.rows(), 2 ); EXPECT_EQ( cnv.planes(), 1 ); EXPECT_EQ( cnv(0,0), 1 ); EXPECT_EQ( cnv(0,1), 2 ); EXPECT_EQ( cnv(1,0), 1 ); EXPECT_EQ( cnv(1,1), 0 ); // Test rasterization ImageView<double> dst = cnv; EXPECT_EQ( dst.cols(), 2 ); EXPECT_EQ( dst.rows(), 2 ); EXPECT_EQ( dst.planes(), 1 ); EXPECT_EQ( dst(0,0), 1 ); EXPECT_EQ( dst(0,1), 2 ); EXPECT_EQ( dst(1,0), 1 ); EXPECT_EQ( dst(1,1), 0 ); // Test the traits ASSERT_TRUE( is_of_type<double>( cnv(0,0) ) ); ASSERT_TRUE( is_of_type<double>( *(cnv.origin()) ) ); ASSERT_FALSE( bool_trait<IsResizable>( cnv ) ); ASSERT_FALSE( bool_trait<IsMultiplyAccessible>( cnv ) ); ASSERT_FALSE( bool_trait<IsFloatingPointIndexable>( cnv ) ); ASSERT_TRUE( bool_trait<IsImageView>( cnv ) ); } TEST( Convolution, SeparableView_0x2 ) { ImageView<double> src(2,2); src(0,0)=1; src(1,0)=2; src(0,1)=4; src(1,1)=6; std::vector<double> krnx; std::vector<double> krny; krny.push_back(1); krny.push_back(-1); SeparableConvolutionView<ImageView<double>,double,ZeroEdgeExtension> cnv( src, krnx, krny ); // Test individual pixel access EXPECT_EQ( cnv.cols(), 2 ); EXPECT_EQ( cnv.rows(), 2 ); EXPECT_EQ( cnv.planes(), 1 ); EXPECT_EQ( cnv(0,0), 1 ); EXPECT_EQ( cnv(0,1), 3 ); EXPECT_EQ( cnv(1,0), 2 ); EXPECT_EQ( cnv(1,1), 4 ); // Test rasterization ImageView<double> dst = cnv; EXPECT_EQ( dst.cols(), 2 ); EXPECT_EQ( dst.rows(), 2 ); EXPECT_EQ( dst.planes(), 1 ); EXPECT_EQ( dst(0,0), 1 ); EXPECT_EQ( dst(0,1), 3 ); EXPECT_EQ( dst(1,0), 2 ); EXPECT_EQ( dst(1,1), 4 ); // Test the traits ASSERT_TRUE( is_of_type<double>( cnv(0,0) ) ); ASSERT_TRUE( is_of_type<double>( *(cnv.origin()) ) ); ASSERT_FALSE( bool_trait<IsResizable>( cnv ) ); ASSERT_FALSE( bool_trait<IsMultiplyAccessible>( cnv ) ); ASSERT_FALSE( bool_trait<IsFloatingPointIndexable>( cnv ) ); ASSERT_TRUE( bool_trait<IsImageView>( cnv ) ); } TEST( Convolution, SeparableView_2x0 ) { ImageView<double> src(2,2); src(0,0)=1; src(1,0)=2; src(0,1)=3; src(1,1)=4; std::vector<double> krnx; krnx.push_back(1); krnx.push_back(-1); std::vector<double> krny; SeparableConvolutionView<ImageView<double>,double,ZeroEdgeExtension> cnv( src, krnx, krny ); // Test individual pixel access EXPECT_EQ( cnv.cols(), 2 ); EXPECT_EQ( cnv.rows(), 2 ); EXPECT_EQ( cnv.planes(), 1 ); EXPECT_EQ( cnv(0,0), 1 ); EXPECT_EQ( cnv(1,0), 1 ); EXPECT_EQ( cnv(0,1), 3 ); EXPECT_EQ( cnv(1,1), 1 ); // Test rasterization ImageView<double> dst = cnv; EXPECT_EQ( dst.cols(), 2 ); EXPECT_EQ( dst.rows(), 2 ); EXPECT_EQ( dst.planes(), 1 ); EXPECT_EQ( dst(0,0), 1 ); EXPECT_EQ( dst(1,0), 1 ); EXPECT_EQ( dst(0,1), 3 ); EXPECT_EQ( dst(1,1), 1 ); // Test the traits ASSERT_TRUE( is_of_type<double>( cnv(0,0) ) ); ASSERT_TRUE( is_of_type<double>( *(cnv.origin()) ) ); ASSERT_FALSE( bool_trait<IsResizable>( cnv ) ); ASSERT_FALSE( bool_trait<IsMultiplyAccessible>( cnv ) ); ASSERT_FALSE( bool_trait<IsFloatingPointIndexable>( cnv ) ); ASSERT_TRUE( bool_trait<IsImageView>( cnv ) ); } TEST( Convolution, SeparableView_Compound ) { ImageView<PixelGray<float32> > src(2,2); src(0,0)=1; src(1,0)=0.2; src(0,1)=0.3; src(1,1)=0.4; std::vector<double> krn; krn.push_back(1); krn.push_back(-1); SeparableConvolutionView<ImageView<PixelGray<float32> >,double,ZeroEdgeExtension> cnv( src, krn, krn ); PixelGray<float32> monkey = cnv(0,1); ASSERT_TRUE( is_of_type<PixelGray<float32> >( cnv(0,0) ) ); } // This unit test catches a bug in the separable convolution code // that was causing the shift due to a crop operation to be applied // twice to image view operations that included two layers of edge // extension or convolution. TEST( Convolution, Prerasterize ) { ImageView<float> test_image(1024,1024); fill(test_image,1.0); ImageViewRef<float> two_edge_extend_operations = edge_extend(gaussian_filter(channel_cast<float>(channels_to_planes(test_image)),1.5), ZeroEdgeExtension()); BBox2i bbox(100,0,1024,1024); ImageView<float> right_buf = crop( two_edge_extend_operations, bbox ); EXPECT_EQ(right_buf(1000,100), 0.0); EXPECT_EQ(right_buf(900,100), 1.0); }
35.507109
158
0.672317
tkeemon
816cc674d3229bf23f354530cd930799620878d1
1,417
hpp
C++
src/private/qhttpserverrequest_private.hpp
Targoman/qhttp
2351076d2e23c8820e6e94d064de689d99edb22f
[ "MIT" ]
2
2020-07-03T06:34:15.000Z
2020-07-03T19:19:09.000Z
src/private/qhttpserverrequest_private.hpp
Targoman/QHttp
55df46aab918a1f923e8b1b79674cf9f82490bc5
[ "MIT" ]
null
null
null
src/private/qhttpserverrequest_private.hpp
Targoman/QHttp
55df46aab918a1f923e8b1b79674cf9f82490bc5
[ "MIT" ]
null
null
null
/** private imeplementation. * https://github.com/azadkuh/qhttp * * @author amir zamani * @version 2.0.0 * @date 2014-07-11 */ #ifndef QHTTPSERVER_REQUEST_PRIVATE_HPP #define QHTTPSERVER_REQUEST_PRIVATE_HPP /////////////////////////////////////////////////////////////////////////////// #include "httpreader.hxx" #include "qhttpserverrequest.hpp" #include "qhttpserverconnection.hpp" /////////////////////////////////////////////////////////////////////////////// namespace qhttp { namespace server { /////////////////////////////////////////////////////////////////////////////// class QHttpRequestPrivate : public details::HttpReader<details::HttpRequestBase> { protected: Q_DECLARE_PUBLIC(QHttpRequest) QHttpRequest* const q_ptr; public: explicit QHttpRequestPrivate(QHttpConnection* conn, QHttpRequest* q) : q_ptr(q), iconnection(conn) { QHTTP_LINE_DEEPLOG } virtual ~QHttpRequestPrivate(); void initialize() { } public: QString iremoteAddress; quint16 iremotePort = 0; QList<QPair<QString, QString>> iuserDefinedValues; QHttpConnection* const iconnection = nullptr; }; /////////////////////////////////////////////////////////////////////////////// } // namespace server } // namespace qhttp /////////////////////////////////////////////////////////////////////////////// #endif // QHTTPSERVER_REQUEST_PRIVATE_HPP
27.784314
107
0.515879
Targoman
816d269f933970e64807ac5f19d34bf8482aa5a2
1,151
cpp
C++
CONTESTS/CODE MARSHAL/BAPS-BUBT16/D.cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
1
2021-11-22T02:26:43.000Z
2021-11-22T02:26:43.000Z
CONTESTS/CODE MARSHAL/BAPS-BUBT16/D.cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
null
null
null
CONTESTS/CODE MARSHAL/BAPS-BUBT16/D.cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int ara1[10001], ara2[10001]; int main() { // freopen("myInput.txt","r",stdin); // freopen("myOutput.txt","w",stdout); int tcase; scanf("%d",&tcase); for(int t=1; t<=tcase; t++) { int n,m; scanf("%d %d",&n,&m); for(int i=0; i<n; i++) scanf("%d",&ara1[i]); //printf("n %d m %d\n",n,m); for(int j=0; j<m; j++) scanf("%d",&ara2[j]); //printf("kak2\n"); long long time=0; for(int i=0,j=0;;) { if((i==n && j== m-1) || (i==n-1 && j== m)) { break; } if(i==n) { time += ara2[j]; j++; } else if(j==m) { time+= ara1[i]; i++; } else { if(ara1[i]<ara2[j]) { time+= ara1[i]; i++; } else { time += ara2[j]; j++; } } } printf("Case %d: %lld\n",t,time); } return 0; }
22.134615
57
0.316247
priojeetpriyom
816de890b819e1b27644a6e004949cfcf5075d9f
1,957
cpp
C++
src/board/agp01/Agp01Relays.cpp
amsobr/iotool
233ec320ee25c96d34332fe847663682c4aa0a91
[ "MIT" ]
null
null
null
src/board/agp01/Agp01Relays.cpp
amsobr/iotool
233ec320ee25c96d34332fe847663682c4aa0a91
[ "MIT" ]
4
2022-03-13T23:07:12.000Z
2022-03-13T23:10:09.000Z
src/board/agp01/Agp01Relays.cpp
amsobr/iotool
233ec320ee25c96d34332fe847663682c4aa0a91
[ "MIT" ]
null
null
null
#include <thread> #include <Poco/Format.h> #include <common/DigitalOut.hpp> #include "Agp01Relays.hpp" using namespace std; Agp01Relays::Agp01Relays( int id ) : DigitalOut(id) , myEN{gpiod::find_line("pioB21") } , myOHCL{ gpiod::find_line("pioB20") } , myOLCH{ gpiod::find_line("pioB19") } , mySel{ "relaySel" , {"pioB16","pioB17","pioB18"} , GpioBus::Direction::OUTPUT , 0 } { /* Populate the relay entries. * Note that the very first AGP01 board had a bug that inverted * the order of the Yn contacts. * For these versions, the software can circumvent the issue by * inverting the numerical order to put on the relay_sel bus, * which is most likely seen below in '7-i'. * With no bug the line should simply have 'i' */ myRelays.reserve(8); for ( int i=0 ; i<8 ; i++ ) { myRelays.emplace_back(Poco::format("Y%d",i+1),false,7-i); } gpiod::line_request req; req.request_type = gpiod::line_request::DIRECTION_OUTPUT; req.consumer = "agp01/relays/en"; myEN.request(req,1); req.consumer = "agp01/relays/ol_ch"; myOLCH.request(req,0); req.consumer = "agp01/relays/oh_cl"; myOHCL.request(req,0); mySel.setValue(0); } std::vector<DigitalOut::Output> Agp01Relays::getOutputs() const { std::vector<Output> outs; outs.reserve(myRelays.size()); for ( auto const& relay : myRelays ) { outs.emplace_back(relay.name,relay.state); } return outs; } int Agp01Relays::setOut( string name , bool value ) { for ( auto const&relay : myRelays ) { if ( relay.name==name ) { mySel.setValue(relay.id); myOLCH.set_value(value?1:0); myOHCL.set_value(value?0:1); myEN.set_value(0); std::this_thread::sleep_for(std::chrono::milliseconds{50}); myEN.set_value(1); } } return -1; }
26.808219
87
0.605008
amsobr
816eeab02ffaeb50fda608060ce3d91afd79b300
1,452
cpp
C++
sources/Device/src/Recorder/Sensor.cpp
Sasha7b9Work/S8-57M
24531cf6d285a400e8be20a939acb842a775a989
[ "MIT" ]
null
null
null
sources/Device/src/Recorder/Sensor.cpp
Sasha7b9Work/S8-57M
24531cf6d285a400e8be20a939acb842a775a989
[ "MIT" ]
null
null
null
sources/Device/src/Recorder/Sensor.cpp
Sasha7b9Work/S8-57M
24531cf6d285a400e8be20a939acb842a775a989
[ "MIT" ]
null
null
null
#include "defines.h" #include "log.h" #include "Hardware/Timer.h" #include "Recorder/Sensor.h" #include <usbh_cdc.h> #include <usbh_core.h> #include <usbh_def.h> static USBH_HandleTypeDef handle; static int requestForReceive = 0; #define RX_BUFF_SIZE 0x400 static uint8 bufferRX[RX_BUFF_SIZE]; static void USBH_UserProcess(USBH_HandleTypeDef *phost, uint8 id); void Sensor::Init() { USBH_Init(&handle, USBH_UserProcess, 0); USBH_RegisterClass(&handle, USBH_CDC_CLASS); USBH_Start(&handle); } void Sensor::DeInit() { USBH_Stop(&handle); USBH_DeInit(&handle); } void Sensor::Update() { USBH_Process(&handle); } void USBH_UserProcess(USBH_HandleTypeDef *, uint8 id) { switch(id) { case HOST_USER_SELECT_CONFIGURATION: break; case HOST_USER_DISCONNECTION: USBH_CDC_Stop(&handle); requestForReceive = 0; break; case HOST_USER_CLASS_ACTIVE: if(requestForReceive == 0) { USBH_CDC_Receive(&handle, bufferRX, RX_BUFF_SIZE); requestForReceive = 1; } break; case HOST_USER_CONNECTION: break; } } void USBH_CDC_ReceiveCallback(USBH_HandleTypeDef *) { uint16 size = USBH_CDC_GetLastReceivedDataSize(&handle); bufferRX[size] = 0; LOG_WRITE("%s", bufferRX); USBH_CDC_Receive(&handle, bufferRX, RX_BUFF_SIZE); } bool Sensor::IsActive() { return requestForReceive == 1; }
16.689655
66
0.672865
Sasha7b9Work
816f6d613d21c4f5bbf3317030577af202971215
5,297
cpp
C++
FileDialogEx.cpp
matthias-christen/CdCoverCreator
edb223c2cf33ab3fb72d84ce2a9bce8500408c2a
[ "MIT" ]
null
null
null
FileDialogEx.cpp
matthias-christen/CdCoverCreator
edb223c2cf33ab3fb72d84ce2a9bce8500408c2a
[ "MIT" ]
null
null
null
FileDialogEx.cpp
matthias-christen/CdCoverCreator
edb223c2cf33ab3fb72d84ce2a9bce8500408c2a
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////// // MSDN -- August 2000 // If this code works, it was written by Paul DiLascia. // If not, I don't know who wrote it. // Largely based on original implementation by Michael Lemley. // Compiles with Visual C++ 6.0, runs on Windows 98 and probably NT too. // // CFileDialogEx implements a CFileDialog that uses the new Windows // 2000 style open/save dialog. Use companion class CDocManagerEx in an // MFC framework app. // #include "stdafx.h" #include <afxpriv.h> #include "FileDialogEx.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static BOOL IsWin2000(); IMPLEMENT_DYNAMIC(CFileDialogEx, CFileDialog) CFileDialogEx::CFileDialogEx(BOOL bOpenFileDialog, LPCTSTR lpszDefExt, LPCTSTR lpszFileName, DWORD dwFlags, LPCTSTR lpszFilter, CWnd* pParentWnd) : CFileDialog(bOpenFileDialog, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd) { } BEGIN_MESSAGE_MAP(CFileDialogEx, CFileDialog) //{{AFX_MSG_MAP(CFileDialogEx) //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL IsWin2000() { OSVERSIONINFOEX osvi; BOOL bOsVersionInfoEx; // Try calling GetVersionEx using the OSVERSIONINFOEX structure, // which is supported on Windows 2000. // // If that fails, try using the OSVERSIONINFO structure. ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) ) { // If OSVERSIONINFOEX doesn't work, try OSVERSIONINFO. osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) ) return FALSE; } switch (osvi.dwPlatformId) { case VER_PLATFORM_WIN32_NT: if ( osvi.dwMajorVersion >= 5 ) return TRUE; break; } return FALSE; } ////////////////// // DoModal override copied mostly from MFC, with modification to use // m_ofnEx instead of m_ofn. // int CFileDialogEx::DoModal() { ASSERT_VALID(this); ASSERT(m_ofn.Flags & OFN_ENABLEHOOK); ASSERT(m_ofn.lpfnHook != NULL); // can still be a user hook // zero out the file buffer for consistent parsing later ASSERT(AfxIsValidAddress(m_ofn.lpstrFile, m_ofn.nMaxFile)); DWORD nOffset = lstrlen(m_ofn.lpstrFile)+1; ASSERT(nOffset <= m_ofn.nMaxFile); memset(m_ofn.lpstrFile+nOffset, 0, (m_ofn.nMaxFile-nOffset)*sizeof(TCHAR)); // WINBUG: This is a special case for the file open/save dialog, // which sometimes pumps while it is coming up but before it has // disabled the main window. HWND hWndFocus = ::GetFocus(); BOOL bEnableParent = FALSE; m_ofn.hwndOwner = PreModal(); AfxUnhookWindowCreate(); if (m_ofn.hwndOwner != NULL && ::IsWindowEnabled(m_ofn.hwndOwner)) { bEnableParent = TRUE; ::EnableWindow(m_ofn.hwndOwner, FALSE); } _AFX_THREAD_STATE* pThreadState = AfxGetThreadState(); ASSERT(pThreadState->m_pAlternateWndInit == NULL); if (m_ofn.Flags & OFN_EXPLORER) pThreadState->m_pAlternateWndInit = this; else AfxHookWindowCreate(this); memset(&m_ofnEx, 0, sizeof(m_ofnEx)); memcpy(&m_ofnEx, &m_ofn, sizeof(m_ofn)); if (IsWin2000()) m_ofnEx.lStructSize = sizeof(m_ofnEx); int nResult; if (m_bOpenFileDialog) nResult = ::GetOpenFileName((OPENFILENAME*)&m_ofnEx); else nResult = ::GetSaveFileName((OPENFILENAME*)&m_ofnEx); memcpy(&m_ofn, &m_ofnEx, sizeof(m_ofn)); m_ofn.lStructSize = sizeof(m_ofn); if (nResult) ASSERT(pThreadState->m_pAlternateWndInit == NULL); pThreadState->m_pAlternateWndInit = NULL; // WINBUG: Second part of special case for file open/save dialog. if (bEnableParent) ::EnableWindow(m_ofnEx.hwndOwner, TRUE); if (::IsWindow(hWndFocus)) ::SetFocus(hWndFocus); PostModal(); return nResult ? nResult : IDCANCEL; } ////////////////// // When the open dialog sends a notification, copy m_ofnEx to m_ofn in // case handler function is expecting updated information in the // OPENFILENAME struct. // BOOL CFileDialogEx::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult) { memcpy(&m_ofn, &m_ofnEx, sizeof(m_ofn)); m_ofn.lStructSize = sizeof(m_ofn); return CFileDialog::OnNotify( wParam, lParam, pResult); } //////////////////////////////////////////////////////////////// // The following functions are provided for testing purposes, to // demonstrate that they in fact called; ie, that MFC's internal dialog // proc is hooked up properly. Delete them if you like. // BOOL CFileDialogEx::OnFileNameOK() { TRACE(_T("CFileDialogEx::OnFileNameOK\n")); return CFileDialog::OnFileNameOK(); } void CFileDialogEx::OnInitDone() { TRACE(_T("CFileDialogEx::OnInitDone\n")); CFileDialog::OnInitDone(); } void CFileDialogEx::OnFileNameChange() { TRACE(_T("CFileDialogEx::OnFileNameChange\n")); CFileDialog::OnFileNameChange(); } void CFileDialogEx::OnFolderChange() { TRACE(_T("CFileDialogEx::OnFolderChange\n")); CFileDialog::OnFolderChange(); } void CFileDialogEx::OnTypeChange() { TRACE(_T("OnTypeChange(), index = %d\n"), m_ofn.nFilterIndex); CFileDialog::OnTypeChange(); }
28.326203
78
0.67963
matthias-christen
817037b84f1f4f00a59b9771d36da6ed7067e400
1,302
hpp
C++
include/filelib.hpp
Vortetty/cpp-linux-utils
b68ca876ce0f9efa50e0658bc0474896ee8811c8
[ "Apache-2.0" ]
null
null
null
include/filelib.hpp
Vortetty/cpp-linux-utils
b68ca876ce0f9efa50e0658bc0474896ee8811c8
[ "Apache-2.0" ]
null
null
null
include/filelib.hpp
Vortetty/cpp-linux-utils
b68ca876ce0f9efa50e0658bc0474896ee8811c8
[ "Apache-2.0" ]
null
null
null
#include <sstream> #include <fstream> #include <codecvt> #include <vector> std::wstring tokenize(const std::wstring& s, int n) { if (!s.size()) { return s; } std::wstringstream ss; ss << s[0]; for (int i = 1; i < s.size(); i+=n) { ss << ' ' << s[i]; } return ss.str(); } static std::vector<char> readAllBytes(char const* filename) { std::ifstream ifs(filename, std::ios::binary|std::ios::ate); std::ifstream::pos_type pos = ifs.tellg(); std::vector<char> result(pos); ifs.seekg(0, std::ios::beg); ifs.read(&result[0], pos); return result; } std::string readFilehex(const char* filename) { std::ifstream fin(filename, std::ios::binary); std::stringstream wss; wss << std::hex << fin.rdbuf(); //out = tokenize(out, 8); return wss.str(); } std::wstring readFile8(const char* filename) { std::wifstream wif(filename); wif.imbue(std::locale(std::locale(""), new std::codecvt_utf8<wchar_t>)); std::wstringstream wss; wss << wif.rdbuf(); return wss.str(); } std::wstring readFile16(const char* filename) { std::wifstream wif(filename); wif.imbue(std::locale(std::locale(""), new std::codecvt_utf16<wchar_t>)); std::wstringstream wss; wss << wif.rdbuf(); return wss.str(); }
23.25
77
0.605991
Vortetty
40c4660d7340fe6a5a09bd932db657d0c16bfe07
737
cpp
C++
Genome_Antivirus_10.0/thread.cpp
Rossterrrr/Qt
3e5c2934ce19675390d2ad6d513a14964d8cbe50
[ "MIT" ]
3
2019-09-02T05:17:08.000Z
2021-01-07T11:21:34.000Z
Genome_Antivirus_10.0/thread.cpp
Jhongesell/Qt
3fc548731435d3f6fffbaec1bdfd19371232088e
[ "MIT" ]
null
null
null
Genome_Antivirus_10.0/thread.cpp
Jhongesell/Qt
3fc548731435d3f6fffbaec1bdfd19371232088e
[ "MIT" ]
null
null
null
#include "thread.h" #include <QDebug> Thread::Thread(QStringList list, QStringList vList, QThread *parent) : QThread(parent), directories(list),virusList(vList) { } void Thread::run() { emit scanStart(); foreach (QString element, directories) { QDirIterator directory(element, QDirIterator::Subdirectories); while (directory.hasNext()) { if(!stopThread){ directory.next(); foreach (const QString &str, virusList) { if (directory.fileName() == str){ emit infectedFiles(directory.filePath()); } } } } } emit scanComplete(); }
24.566667
125
0.523745
Rossterrrr
40c63246f25bda155cd0ecd4ff9be5eda870da0f
3,514
cc
C++
src/RTT_Format_Reader/CellFlags.cc
hppritcha/Draco
6baa5688865eb6c6f38ce6ad1a40eb5ce943cf5c
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
src/RTT_Format_Reader/CellFlags.cc
hppritcha/Draco
6baa5688865eb6c6f38ce6ad1a40eb5ce943cf5c
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
src/RTT_Format_Reader/CellFlags.cc
hppritcha/Draco
6baa5688865eb6c6f38ce6ad1a40eb5ce943cf5c
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
//--------------------------------------------*-C++-*---------------------------------------------// /*! * \file RTT_Format_Reader/CellFlags.cc * \author B.T. Adams * \date Mon Jun 7 10:33:26 2000 * \brief Implementation file for RTT_Format_Reader/CellFlags class * \note Copyright (C) 2016-2020 Triad National Security, LLC., All rights reserved. */ //------------------------------------------------------------------------------------------------// #include "CellFlags.hh" namespace rtt_RTT_Format_Reader { //------------------------------------------------------------------------------------------------// /*! * \brief Parses the cell_flags data block of the mesh file via calls to private member functions. * \param meshfile Mesh file name. */ void CellFlags::readCellFlags(ifstream &meshfile) { readKeyword(meshfile); readFlagTypes(meshfile); readEndKeyword(meshfile); } //------------------------------------------------------------------------------------------------// /*! * \brief Reads and validates the cell_flags block keyword. * \param meshfile Mesh file name. */ void CellFlags::readKeyword(ifstream &meshfile) { string dummyString; meshfile >> dummyString; Insist(dummyString == "cell_flags", "Invalid mesh file: cell_flags block missing"); std::getline(meshfile, dummyString); } //------------------------------------------------------------------------------------------------// /*! * \brief Reads and validates the cell_flags block data. * \param meshfile Mesh file name. */ void CellFlags::readFlagTypes(ifstream &meshfile) { int flagTypeNum; string dummyString; for (size_t i = 0; i < static_cast<size_t>(dims.get_ncell_flag_types()); ++i) { meshfile >> flagTypeNum >> dummyString; Insist(static_cast<size_t>(flagTypeNum) == i + 1, "Invalid mesh file: cell flag type out of order"); Check(i < flagTypes.size()); Check(i < INT_MAX); flagTypes[i] = std::make_shared<Flags>(dims.get_ncell_flags(static_cast<int>(i)), dummyString); std::getline(meshfile, dummyString); flagTypes[i]->readFlags(meshfile); } } //------------------------------------------------------------------------------------------------// /*! * \brief Reads and validates the end_cell_flags block keyword. * \param meshfile Mesh file name. */ void CellFlags::readEndKeyword(ifstream &meshfile) { string dummyString; meshfile >> dummyString; Insist(dummyString == "end_cell_flags", "Invalid mesh file: cell_flags block missing end"); std::getline(meshfile, dummyString); // read and discard blank line. } //------------------------------------------------------------------------------------------------// /*! * \brief Returns the index to the cell flag type that contains the specified string. * \param desired_flag_type Flag type. * \return The cell flag type index. */ int CellFlags::get_flag_type_index(string &desired_flag_type) const { int flag_type_index = -1; for (size_t f = 0; f < dims.get_ncell_flag_types(); f++) { string flag_type = flagTypes[f]->getFlagType(); if (flag_type == desired_flag_type) { Check(f < INT_MAX); flag_type_index = static_cast<int>(f); } } return flag_type_index; } } // end namespace rtt_RTT_Format_Reader //------------------------------------------------------------------------------------------------// // end of RTT_Format_Reader/CellFlags.cc //------------------------------------------------------------------------------------------------//
36.989474
100
0.527604
hppritcha
40c88774a7c02cb268096c3107ab7d5a029ec234
3,816
hh
C++
src/BasicObjects.hh
hirdrac/rend
937fa3dc0eff23d831004766929c601862079791
[ "MIT" ]
2
2021-08-31T07:18:27.000Z
2021-11-15T22:02:26.000Z
src/BasicObjects.hh
hirdrac/rend
937fa3dc0eff23d831004766929c601862079791
[ "MIT" ]
null
null
null
src/BasicObjects.hh
hirdrac/rend
937fa3dc0eff23d831004766929c601862079791
[ "MIT" ]
null
null
null
// // BasicObjects.hh // Copyright (C) 2021 Richard Bradley // // Definitions for primitive object classes // #pragma once #include "Object.hh" // **** Types **** class Disc final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Disc>"; } // Object Functions int init(Scene& s, const Transform* tr) override; BBox bound(const Matrix* t) const override; int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; private: Vec3 _normal; }; class Cone final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Cone>"; } // Object Functions int init(Scene& s, const Transform* tr) override; int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; private: Vec3 _baseNormal; }; class Cube final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Cube>"; } // Object Functions int init(Scene& s, const Transform* tr) override; int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; private: Vec3 _sideNormal[6]; }; class Cylinder final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Cylinder>"; } // Object Functions int init(Scene& s, const Transform* tr) override; int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; private: Vec3 _endNormal[2]; }; class Paraboloid final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Paraboloid>"; } // Object Functions int init(Scene& s, const Transform* tr) override; int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; private: Vec3 _baseNormal; }; class Plane final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Plane>"; } // Object Functions int init(Scene& s, const Transform* tr) override; BBox bound(const Matrix* t) const override; int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; private: Vec3 _normal; }; class Sphere final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Sphere>"; } // Object Functions int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; }; class Torus final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Torus>"; } int setRadius(Flt r) override { _radius = r; return 0; } // Object Functions int init(Scene& s, const Transform* tr) override; BBox bound(const Matrix* t) const override; int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; private: Flt _radius = .5; };
24.461538
62
0.70414
hirdrac
40c98e19385b51a0f26c1f35a0bdcddc3234b7e7
423
cpp
C++
docs/mfc/codesnippet/CPP/implementing-working-areas-in-list-controls_2.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
965
2017-06-25T23:57:11.000Z
2022-03-31T14:17:32.000Z
docs/mfc/codesnippet/CPP/implementing-working-areas-in-list-controls_2.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
3,272
2017-06-24T00:26:34.000Z
2022-03-31T22:14:07.000Z
docs/mfc/codesnippet/CPP/implementing-working-areas-in-list-controls_2.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
951
2017-06-25T12:36:14.000Z
2022-03-26T22:49:06.000Z
// set insertion points for each work area CPoint rgptWork[4]; for (int i = 0; i < 4; i++) { rgptWork[i].x = rcWorkAreas[i].left + 10; rgptWork[i].y = rcWorkAreas[i].top + 10; } // now move all the items to the different quadrants for (int i = 0; i < 20; i++) { m_WorkAreaListCtrl.SetItemPosition(i, rgptWork[i % 4]); } // force the control to rearrange the shuffled items m_WorkAreaListCtrl.Arrange(LVA_DEFAULT);
28.2
58
0.683215
bobbrow
40cb196b7e0fd950deb4b0154b3e2dbb9f36f0d2
2,813
cpp
C++
Epoll.cpp
linnaeushuang/HttpServer
16753db84d95d123a6b0e8d36f04f7be49c49d0b
[ "Apache-2.0" ]
2
2021-02-22T04:56:43.000Z
2021-02-24T15:43:41.000Z
Epoll.cpp
linnaeushuang/webServer
16753db84d95d123a6b0e8d36f04f7be49c49d0b
[ "Apache-2.0" ]
null
null
null
Epoll.cpp
linnaeushuang/webServer
16753db84d95d123a6b0e8d36f04f7be49c49d0b
[ "Apache-2.0" ]
2
2021-11-24T03:26:20.000Z
2021-11-27T13:49:11.000Z
#include "Epoll.h" #include <assert.h> #include <errno.h> #include <netinet/in.h> #include <string.h> #include <sys/epoll.h> #include <sys/socket.h> #include <deque> #include <queue> #include "utils/SocketUtils.h" #include "utils/Logging.h" #include <arpa/inet.h> #include <iostream> //typedef shared_ptr<Event> SP_Event; define in Event.h // epoll_create1(flag) // EPOLL_CLOECEC: close epollfd on exec // this epollfd will close after fork a thread and exec this thread. Epoll::Epoll() : epollFd_(epoll_create1(EPOLL_CLOEXEC)), events_(EVENTSNUM) { assert(epollFd_ > 0); } Epoll::~Epoll() {} void Epoll::epoll_add(SP_Event request, int timeout) { int fd = request->getFd(); if (timeout > 0) { add_timer(request, timeout); fd2http_[fd] = request->getHttpHolder(); } struct epoll_event event; event.data.fd = fd; event.events = request->getEvents(); request->EqualAndUpdateLastEvents(); fd2event_[fd] = request; if (epoll_ctl(epollFd_, EPOLL_CTL_ADD, fd, &event) < 0) { perror("epoll_add error"); fd2event_[fd].reset(); } } void Epoll::epoll_mod(SP_Event request, int timeout) { if (timeout > 0) add_timer(request, timeout); int fd = request->getFd(); if (!request->EqualAndUpdateLastEvents()) { struct epoll_event event; event.data.fd = fd; event.events = request->getEvents(); if (epoll_ctl(epollFd_, EPOLL_CTL_MOD, fd, &event) < 0){ perror("epoll_mod error"); fd2event_[fd].reset(); } } } void Epoll::epoll_del(SP_Event request) { int fd = request->getFd(); struct epoll_event event; event.data.fd = fd; event.events = request->getLastEvents(); if (epoll_ctl(epollFd_, EPOLL_CTL_DEL, fd, &event) < 0) { perror("epoll_del error"); } fd2event_[fd].reset(); fd2http_[fd].reset(); } std::vector<SP_Event> Epoll::exec_epoll_wait() { while (true) { // std::vector's iterator is pointer int event_count = epoll_wait(epollFd_, &*events_.begin(), events_.size(), EPOLLWAIT_TIME); if (event_count < 0) perror("epoll wait error"); std::vector<SP_Event> req_data = getEventsRequest(event_count); if (req_data.size() > 0) return req_data; } } void Epoll::handleExpired() { timerManager_.handleExpiredEvent(); } std::vector<SP_Event> Epoll::getEventsRequest(int events_num) { std::vector<SP_Event> req_data; for (int i = 0; i < events_num; ++i) { // get fd which has a event create int fd = events_[i].data.fd; SP_Event cur_req = fd2event_[fd]; if (cur_req) { cur_req->setRevents(events_[i].events); cur_req->setEvents(0); req_data.push_back(cur_req); } else { LOG << "SP cur_req is invalid"; } } return req_data; } void Epoll::add_timer(SP_Event request_data, int timeout) { std::shared_ptr<HttpData> t = request_data->getHttpHolder(); if (t) timerManager_.addTimer(t, timeout); else LOG << "timer add fail"; }
25.572727
92
0.695343
linnaeushuang
40cc0771f8ed2721f0ca303695315f5b88b209c4
11,238
cc
C++
src/i18n_data/locale/sl_SI.cc
BornIncompetence/fast_io
4a2ce333d292753369df4202af090abe0142725a
[ "MIT" ]
null
null
null
src/i18n_data/locale/sl_SI.cc
BornIncompetence/fast_io
4a2ce333d292753369df4202af090abe0142725a
[ "MIT" ]
null
null
null
src/i18n_data/locale/sl_SI.cc
BornIncompetence/fast_io
4a2ce333d292753369df4202af090abe0142725a
[ "MIT" ]
null
null
null
#include"../localedef.h" namespace fast_io_i18n { namespace { inline constexpr std::size_t monetary_mon_grouping_storage[]{3}; inline constexpr lc_all lc_all_global{.identification={.title=tsc("Slovenian locale for Slovenia"),.source=tsc("USM//MZT\t\t;\t\tfast_io"),.address=tsc("Kotnikova 6,, Ljubljana, Slovenia\t\t;\t\thttps://github.com/expnkx/fast_io"),.contact=tsc("fast_io"),.email=tsc("bug-glibc-locales@gnu.org;euloanty@live.com"),.tel=tsc(""),.fax=tsc(""),.language=tsc("Slovenian"),.territory=tsc("Slovenia"),.revision=tsc("1.0"),.date=tsc("2000-06-29")},.monetary={.int_curr_symbol=tsc("EUR "),.currency_symbol=tsc("€"),.mon_decimal_point=tsc(","),.mon_thousands_sep=tsc("."),.mon_grouping={monetary_mon_grouping_storage,1},.positive_sign=tsc(""),.negative_sign=tsc("-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=0,.p_sep_by_space=1,.n_cs_precedes=0,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(","),.thousands_sep=tsc(".")},.time={.abday={tsc("ned"),tsc("pon"),tsc("tor"),tsc("sre"),tsc("čet"),tsc("pet"),tsc("sob")},.day={tsc("nedelja"),tsc("ponedeljek"),tsc("torek"),tsc("sreda"),tsc("četrtek"),tsc("petek"),tsc("sobota")},.abmon={tsc("jan"),tsc("feb"),tsc("mar"),tsc("apr"),tsc("maj"),tsc("jun"),tsc("jul"),tsc("avg"),tsc("sep"),tsc("okt"),tsc("nov"),tsc("dec")},.mon={tsc("januar"),tsc("februar"),tsc("marec"),tsc("april"),tsc("maj"),tsc("junij"),tsc("julij"),tsc("avgust"),tsc("september"),tsc("oktober"),tsc("november"),tsc("december")},.d_t_fmt=tsc("%a %d %b %Y %T"),.d_fmt=tsc("%d. %m. %Y"),.t_fmt=tsc("%T"),.t_fmt_ampm=tsc(""),.date_fmt=tsc("%a %d %b %Y %T %Z"),.am_pm={tsc(""),tsc("")},.week={7,19971130,1},.first_weekday=2},.messages={.yesexpr=tsc("^[+1YyJj]"),.noexpr=tsc("^[-0Nn]"),.yesstr=tsc("da"),.nostr=tsc("ne")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc("+%c %a %l"),.int_select=tsc("00"),.int_prefix=tsc("386")},.name={.name_fmt=tsc("%d%t%g%t%m%t%f")},.address={.postal_fmt=tsc("%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N"),.country_name=tsc("Slovenija"),.country_ab2=tsc("SI"),.country_ab3=tsc("SVN"),.country_num=705,.country_car=tsc("SLO"),.lang_name=tsc("slovenščina"),.lang_ab=tsc("sl"),.lang_term=tsc("slv"),.lang_lib=tsc("slv")},.measurement={.measurement=1}}; inline constexpr wlc_all wlc_all_global{.identification={.title=tsc(L"Slovenian locale for Slovenia"),.source=tsc(L"USM//MZT\t\t;\t\tfast_io"),.address=tsc(L"Kotnikova 6,, Ljubljana, Slovenia\t\t;\t\thttps://github.com/expnkx/fast_io"),.contact=tsc(L"fast_io"),.email=tsc(L"bug-glibc-locales@gnu.org;euloanty@live.com"),.tel=tsc(L""),.fax=tsc(L""),.language=tsc(L"Slovenian"),.territory=tsc(L"Slovenia"),.revision=tsc(L"1.0"),.date=tsc(L"2000-06-29")},.monetary={.int_curr_symbol=tsc(L"EUR "),.currency_symbol=tsc(L"€"),.mon_decimal_point=tsc(L","),.mon_thousands_sep=tsc(L"."),.mon_grouping={monetary_mon_grouping_storage,1},.positive_sign=tsc(L""),.negative_sign=tsc(L"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=0,.p_sep_by_space=1,.n_cs_precedes=0,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(L","),.thousands_sep=tsc(L".")},.time={.abday={tsc(L"ned"),tsc(L"pon"),tsc(L"tor"),tsc(L"sre"),tsc(L"čet"),tsc(L"pet"),tsc(L"sob")},.day={tsc(L"nedelja"),tsc(L"ponedeljek"),tsc(L"torek"),tsc(L"sreda"),tsc(L"četrtek"),tsc(L"petek"),tsc(L"sobota")},.abmon={tsc(L"jan"),tsc(L"feb"),tsc(L"mar"),tsc(L"apr"),tsc(L"maj"),tsc(L"jun"),tsc(L"jul"),tsc(L"avg"),tsc(L"sep"),tsc(L"okt"),tsc(L"nov"),tsc(L"dec")},.mon={tsc(L"januar"),tsc(L"februar"),tsc(L"marec"),tsc(L"april"),tsc(L"maj"),tsc(L"junij"),tsc(L"julij"),tsc(L"avgust"),tsc(L"september"),tsc(L"oktober"),tsc(L"november"),tsc(L"december")},.d_t_fmt=tsc(L"%a %d %b %Y %T"),.d_fmt=tsc(L"%d. %m. %Y"),.t_fmt=tsc(L"%T"),.t_fmt_ampm=tsc(L""),.date_fmt=tsc(L"%a %d %b %Y %T %Z"),.am_pm={tsc(L""),tsc(L"")},.week={7,19971130,1},.first_weekday=2},.messages={.yesexpr=tsc(L"^[+1YyJj]"),.noexpr=tsc(L"^[-0Nn]"),.yesstr=tsc(L"da"),.nostr=tsc(L"ne")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(L"+%c %a %l"),.int_select=tsc(L"00"),.int_prefix=tsc(L"386")},.name={.name_fmt=tsc(L"%d%t%g%t%m%t%f")},.address={.postal_fmt=tsc(L"%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N"),.country_name=tsc(L"Slovenija"),.country_ab2=tsc(L"SI"),.country_ab3=tsc(L"SVN"),.country_num=705,.country_car=tsc(L"SLO"),.lang_name=tsc(L"slovenščina"),.lang_ab=tsc(L"sl"),.lang_term=tsc(L"slv"),.lang_lib=tsc(L"slv")},.measurement={.measurement=1}}; inline constexpr u8lc_all u8lc_all_global{.identification={.title=tsc(u8"Slovenian locale for Slovenia"),.source=tsc(u8"USM//MZT\t\t;\t\tfast_io"),.address=tsc(u8"Kotnikova 6,, Ljubljana, Slovenia\t\t;\t\thttps://github.com/expnkx/fast_io"),.contact=tsc(u8"fast_io"),.email=tsc(u8"bug-glibc-locales@gnu.org;euloanty@live.com"),.tel=tsc(u8""),.fax=tsc(u8""),.language=tsc(u8"Slovenian"),.territory=tsc(u8"Slovenia"),.revision=tsc(u8"1.0"),.date=tsc(u8"2000-06-29")},.monetary={.int_curr_symbol=tsc(u8"EUR "),.currency_symbol=tsc(u8"€"),.mon_decimal_point=tsc(u8","),.mon_thousands_sep=tsc(u8"."),.mon_grouping={monetary_mon_grouping_storage,1},.positive_sign=tsc(u8""),.negative_sign=tsc(u8"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=0,.p_sep_by_space=1,.n_cs_precedes=0,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(u8","),.thousands_sep=tsc(u8".")},.time={.abday={tsc(u8"ned"),tsc(u8"pon"),tsc(u8"tor"),tsc(u8"sre"),tsc(u8"čet"),tsc(u8"pet"),tsc(u8"sob")},.day={tsc(u8"nedelja"),tsc(u8"ponedeljek"),tsc(u8"torek"),tsc(u8"sreda"),tsc(u8"četrtek"),tsc(u8"petek"),tsc(u8"sobota")},.abmon={tsc(u8"jan"),tsc(u8"feb"),tsc(u8"mar"),tsc(u8"apr"),tsc(u8"maj"),tsc(u8"jun"),tsc(u8"jul"),tsc(u8"avg"),tsc(u8"sep"),tsc(u8"okt"),tsc(u8"nov"),tsc(u8"dec")},.mon={tsc(u8"januar"),tsc(u8"februar"),tsc(u8"marec"),tsc(u8"april"),tsc(u8"maj"),tsc(u8"junij"),tsc(u8"julij"),tsc(u8"avgust"),tsc(u8"september"),tsc(u8"oktober"),tsc(u8"november"),tsc(u8"december")},.d_t_fmt=tsc(u8"%a %d %b %Y %T"),.d_fmt=tsc(u8"%d. %m. %Y"),.t_fmt=tsc(u8"%T"),.t_fmt_ampm=tsc(u8""),.date_fmt=tsc(u8"%a %d %b %Y %T %Z"),.am_pm={tsc(u8""),tsc(u8"")},.week={7,19971130,1},.first_weekday=2},.messages={.yesexpr=tsc(u8"^[+1YyJj]"),.noexpr=tsc(u8"^[-0Nn]"),.yesstr=tsc(u8"da"),.nostr=tsc(u8"ne")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(u8"+%c %a %l"),.int_select=tsc(u8"00"),.int_prefix=tsc(u8"386")},.name={.name_fmt=tsc(u8"%d%t%g%t%m%t%f")},.address={.postal_fmt=tsc(u8"%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N"),.country_name=tsc(u8"Slovenija"),.country_ab2=tsc(u8"SI"),.country_ab3=tsc(u8"SVN"),.country_num=705,.country_car=tsc(u8"SLO"),.lang_name=tsc(u8"slovenščina"),.lang_ab=tsc(u8"sl"),.lang_term=tsc(u8"slv"),.lang_lib=tsc(u8"slv")},.measurement={.measurement=1}}; inline constexpr u16lc_all u16lc_all_global{.identification={.title=tsc(u"Slovenian locale for Slovenia"),.source=tsc(u"USM//MZT\t\t;\t\tfast_io"),.address=tsc(u"Kotnikova 6,, Ljubljana, Slovenia\t\t;\t\thttps://github.com/expnkx/fast_io"),.contact=tsc(u"fast_io"),.email=tsc(u"bug-glibc-locales@gnu.org;euloanty@live.com"),.tel=tsc(u""),.fax=tsc(u""),.language=tsc(u"Slovenian"),.territory=tsc(u"Slovenia"),.revision=tsc(u"1.0"),.date=tsc(u"2000-06-29")},.monetary={.int_curr_symbol=tsc(u"EUR "),.currency_symbol=tsc(u"€"),.mon_decimal_point=tsc(u","),.mon_thousands_sep=tsc(u"."),.mon_grouping={monetary_mon_grouping_storage,1},.positive_sign=tsc(u""),.negative_sign=tsc(u"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=0,.p_sep_by_space=1,.n_cs_precedes=0,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(u","),.thousands_sep=tsc(u".")},.time={.abday={tsc(u"ned"),tsc(u"pon"),tsc(u"tor"),tsc(u"sre"),tsc(u"čet"),tsc(u"pet"),tsc(u"sob")},.day={tsc(u"nedelja"),tsc(u"ponedeljek"),tsc(u"torek"),tsc(u"sreda"),tsc(u"četrtek"),tsc(u"petek"),tsc(u"sobota")},.abmon={tsc(u"jan"),tsc(u"feb"),tsc(u"mar"),tsc(u"apr"),tsc(u"maj"),tsc(u"jun"),tsc(u"jul"),tsc(u"avg"),tsc(u"sep"),tsc(u"okt"),tsc(u"nov"),tsc(u"dec")},.mon={tsc(u"januar"),tsc(u"februar"),tsc(u"marec"),tsc(u"april"),tsc(u"maj"),tsc(u"junij"),tsc(u"julij"),tsc(u"avgust"),tsc(u"september"),tsc(u"oktober"),tsc(u"november"),tsc(u"december")},.d_t_fmt=tsc(u"%a %d %b %Y %T"),.d_fmt=tsc(u"%d. %m. %Y"),.t_fmt=tsc(u"%T"),.t_fmt_ampm=tsc(u""),.date_fmt=tsc(u"%a %d %b %Y %T %Z"),.am_pm={tsc(u""),tsc(u"")},.week={7,19971130,1},.first_weekday=2},.messages={.yesexpr=tsc(u"^[+1YyJj]"),.noexpr=tsc(u"^[-0Nn]"),.yesstr=tsc(u"da"),.nostr=tsc(u"ne")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(u"+%c %a %l"),.int_select=tsc(u"00"),.int_prefix=tsc(u"386")},.name={.name_fmt=tsc(u"%d%t%g%t%m%t%f")},.address={.postal_fmt=tsc(u"%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N"),.country_name=tsc(u"Slovenija"),.country_ab2=tsc(u"SI"),.country_ab3=tsc(u"SVN"),.country_num=705,.country_car=tsc(u"SLO"),.lang_name=tsc(u"slovenščina"),.lang_ab=tsc(u"sl"),.lang_term=tsc(u"slv"),.lang_lib=tsc(u"slv")},.measurement={.measurement=1}}; inline constexpr u32lc_all u32lc_all_global{.identification={.title=tsc(U"Slovenian locale for Slovenia"),.source=tsc(U"USM//MZT\t\t;\t\tfast_io"),.address=tsc(U"Kotnikova 6,, Ljubljana, Slovenia\t\t;\t\thttps://github.com/expnkx/fast_io"),.contact=tsc(U"fast_io"),.email=tsc(U"bug-glibc-locales@gnu.org;euloanty@live.com"),.tel=tsc(U""),.fax=tsc(U""),.language=tsc(U"Slovenian"),.territory=tsc(U"Slovenia"),.revision=tsc(U"1.0"),.date=tsc(U"2000-06-29")},.monetary={.int_curr_symbol=tsc(U"EUR "),.currency_symbol=tsc(U"€"),.mon_decimal_point=tsc(U","),.mon_thousands_sep=tsc(U"."),.mon_grouping={monetary_mon_grouping_storage,1},.positive_sign=tsc(U""),.negative_sign=tsc(U"-"),.int_frac_digits=2,.frac_digits=2,.p_cs_precedes=0,.p_sep_by_space=1,.n_cs_precedes=0,.n_sep_by_space=1,.p_sign_posn=1,.n_sign_posn=1},.numeric={.decimal_point=tsc(U","),.thousands_sep=tsc(U".")},.time={.abday={tsc(U"ned"),tsc(U"pon"),tsc(U"tor"),tsc(U"sre"),tsc(U"čet"),tsc(U"pet"),tsc(U"sob")},.day={tsc(U"nedelja"),tsc(U"ponedeljek"),tsc(U"torek"),tsc(U"sreda"),tsc(U"četrtek"),tsc(U"petek"),tsc(U"sobota")},.abmon={tsc(U"jan"),tsc(U"feb"),tsc(U"mar"),tsc(U"apr"),tsc(U"maj"),tsc(U"jun"),tsc(U"jul"),tsc(U"avg"),tsc(U"sep"),tsc(U"okt"),tsc(U"nov"),tsc(U"dec")},.mon={tsc(U"januar"),tsc(U"februar"),tsc(U"marec"),tsc(U"april"),tsc(U"maj"),tsc(U"junij"),tsc(U"julij"),tsc(U"avgust"),tsc(U"september"),tsc(U"oktober"),tsc(U"november"),tsc(U"december")},.d_t_fmt=tsc(U"%a %d %b %Y %T"),.d_fmt=tsc(U"%d. %m. %Y"),.t_fmt=tsc(U"%T"),.t_fmt_ampm=tsc(U""),.date_fmt=tsc(U"%a %d %b %Y %T %Z"),.am_pm={tsc(U""),tsc(U"")},.week={7,19971130,1},.first_weekday=2},.messages={.yesexpr=tsc(U"^[+1YyJj]"),.noexpr=tsc(U"^[-0Nn]"),.yesstr=tsc(U"da"),.nostr=tsc(U"ne")},.paper={.width=210,.height=297},.telephone={.tel_int_fmt=tsc(U"+%c %a %l"),.int_select=tsc(U"00"),.int_prefix=tsc(U"386")},.name={.name_fmt=tsc(U"%d%t%g%t%m%t%f")},.address={.postal_fmt=tsc(U"%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N"),.country_name=tsc(U"Slovenija"),.country_ab2=tsc(U"SI"),.country_ab3=tsc(U"SVN"),.country_num=705,.country_car=tsc(U"SLO"),.lang_name=tsc(U"slovenščina"),.lang_ab=tsc(U"sl"),.lang_term=tsc(U"slv"),.lang_lib=tsc(U"slv")},.measurement={.measurement=1}}; } } #include"../main.h"
468.25
2,296
0.675476
BornIncompetence
40cf717a9bf2f41129386946df187d083db7403a
303
cpp
C++
src/generator/ui/LitesqlMethodPanel.cpp
cshnick/liteSql_custom_generator
31f81ab13b689616672ab45805c3ffdfab3a1057
[ "BSD-3-Clause" ]
14
2018-04-20T03:11:34.000Z
2021-12-29T02:02:28.000Z
src/generator/ui/LitesqlMethodPanel.cpp
cshnick/liteSql_custom_generator
31f81ab13b689616672ab45805c3ffdfab3a1057
[ "BSD-3-Clause" ]
14
2016-05-24T00:20:42.000Z
2019-02-11T18:36:36.000Z
src/generator/ui/LitesqlMethodPanel.cpp
cshnick/liteSql_custom_generator
31f81ab13b689616672ab45805c3ffdfab3a1057
[ "BSD-3-Clause" ]
5
2019-08-31T17:07:08.000Z
2022-03-21T06:57:39.000Z
#include "LitesqlMethodPanel.h" #include "objectmodel.hpp" using namespace xml; LitesqlMethodPanel::LitesqlMethodPanel( wxWindow* parent , Method::Ptr& pMethod) : MethodPanel( parent ), m_pMethod(pMethod) { m_textCtrlName->SetValidator(StdStringValidator(wxFILTER_ALPHANUMERIC,&m_pMethod->name)); }
23.307692
91
0.79538
cshnick
40cfc6dceaf044e48a6a14da92c1e56a72526ce6
5,145
cpp
C++
src/items/items.cpp
Blackhawk-TA/GateKeeper
49a260bf7ba2304f1649b5ed487bc1e55028e672
[ "MIT" ]
1
2021-12-31T23:52:57.000Z
2021-12-31T23:52:57.000Z
src/items/items.cpp
Blackhawk-TA/GateKeeper
49a260bf7ba2304f1649b5ed487bc1e55028e672
[ "MIT" ]
null
null
null
src/items/items.cpp
Blackhawk-TA/GateKeeper
49a260bf7ba2304f1649b5ed487bc1e55028e672
[ "MIT" ]
null
null
null
// // Created by daniel on 24.09.21. // #include "items.hpp" namespace items { Listbox::Item create_inventory_item(INVENTORY_ITEM item_type) { Listbox::Item item; switch (item_type) { case INVENTORY_ITEM::GATE_PART: item = create_gate_part(INVENTORY_ITEM::GATE_PART); break; case INVENTORY_ITEM::APPLE: item = create_apple(INVENTORY_ITEM::APPLE); break; case INVENTORY_ITEM::CARROT: item = create_carrot(INVENTORY_ITEM::CARROT); break; case INVENTORY_ITEM::CARROT_SEED: item = create_carrot_seed(INVENTORY_ITEM::CARROT_SEED); break; case INVENTORY_ITEM::INVENTORY_BACK: item = create_back_entry(INVENTORY_ITEM::INVENTORY_BACK); break; } return item; } Listbox::Item create_sidemenu_item(SIDEMENU_ITEM item_type, uint8_t save_id) { Listbox::Item item; switch (item_type) { case SIDEMENU_ITEM::INVENTORY: item = create_inventory_entry(SIDEMENU_ITEM::INVENTORY); break; case SIDEMENU_ITEM::GEAR: item = create_gear_entry(SIDEMENU_ITEM::GEAR); break; case SIDEMENU_ITEM::SAVE: item = create_save_entry(SIDEMENU_ITEM::SAVE, save_id); break; case SIDEMENU_ITEM::SIDEMENU_OPTIONS: item = create_options_entry(SIDEMENU_ITEM::SIDEMENU_BACK, save_id); break; case SIDEMENU_ITEM::SIDEMENU_BACK: item = create_back_entry(SIDEMENU_ITEM::SIDEMENU_BACK); break; case SIDEMENU_ITEM::QUIT: item = create_quit_entry(SIDEMENU_ITEM::QUIT); break; } return item; } Listbox::Item create_menu_item(MENU_ITEM item_type, uint8_t save_id) { std::string save_id_str = std::to_string(save_id); Listbox::Item item; switch (item_type) { case MENU_ITEM::LOAD_SAVE: item = create_load_entry(MENU_ITEM::LOAD_SAVE, save_id); break; case MENU_ITEM::NEW_SAVE: item = create_new_save_entry(MENU_ITEM::NEW_SAVE, save_id); break; case MENU_ITEM::MENU_OPTIONS: item = create_options_entry(MENU_ITEM::MENU_OPTIONS); break; } return item; } Listbox::Item create_options_item(OPTIONS_ITEM item_type, uint8_t save_id) { Listbox::Item item; switch (item_type) { case OPTIONS_ITEM::SHOW_FPS: item = create_show_fps_entry(OPTIONS_ITEM::SHOW_FPS); break; case OPTIONS_ITEM::SHOW_TIME: item = create_show_time_entry(OPTIONS_ITEM::SHOW_TIME); break; case OPTIONS_ITEM::OPTIONS_BACK: item = create_options_exit_entry(OPTIONS_ITEM::OPTIONS_BACK, save_id); break; case RESET_ALL: item = create_reset_all_entries(OPTIONS_ITEM::RESET_ALL); break; } return item; } Listbox::Item create_combat_item(COMBAT_ITEM item_type, uint8_t save_id, combat::Player *player, combat::Enemy *enemy) { Listbox::Item item; switch (item_type) { case COMBAT_ITEM::ESCAPE: item = create_combat_escape(item_type, save_id); break; case ATTACK_SWORD: item = create_combat_attack_sword(item_type, player, enemy); break; case ATTACK_SPEAR: item = create_combat_attack_spear(item_type, player, enemy); break; case ATTACK_ARROW: item = create_combat_attack_arrow(item_type, player, enemy); break; case ATTACK_DAGGER: item = create_combat_attack_dagger(item_type, player, enemy); break; case ATTACK_MAGIC: item = create_combat_attack_magic(item_type, player, enemy); break; case ATTACK_FIRE: item = create_combat_attack_fire(item_type, player, enemy); break; case ATTACK_ICE: item = create_combat_attack_ice(item_type, player, enemy); break; case ATTACK_SHOCK: item = create_combat_attack_shock(item_type, player, enemy); break; } return item; } Listbox::Item create_gear_item(GEAR_TYPE item_type) { Listbox::Item item; switch (item_type) { case GEAR_SWORD: item = create_gear_sword(item_type); break; case GEAR_SPEAR: item = create_gear_spear(item_type); break; case GEAR_ARROW: item = create_gear_arrow(item_type); break; case GEAR_DAGGER: item = create_gear_dagger(item_type); break; case GEAR_MAGIC: item = create_gear_magic(item_type); break; case GEAR_FIRE: item = create_gear_fire(item_type); break; case GEAR_ICE: item = create_gear_ice(item_type); break; case GEAR_SHOCK: item = create_gear_shock(item_type); break; case GEAR_NAVIGATE_BACK: item = create_back_entry(item_type); break; default: break; } return item; } Listbox::Item create_shop_item(SHOP_ITEM item_type) { Listbox::Item item; switch (item_type) { case SHOP_APPLE: item = create_shop_apple(item_type); break; case SHOP_CARROT: item = create_shop_carrot(item_type); break; case SHOP_CARROT_SEED: item = create_shop_carrot_seed(item_type); break; case SHOP_SWORD: item = create_shop_sword(item_type); break; case SHOP_DAGGER: item = create_shop_dagger(item_type); break; case SHOP_ARROW: item = create_shop_arrow(item_type); break; case SHOP_SPEAR: item = create_shop_spear(item_type); break; case SHOP_BACK: item = create_back_entry(item_type); break; } return item; } }
24.975728
121
0.710982
Blackhawk-TA
40d092cfa1696d5905a37a26ae97ab2e05964f40
1,159
cpp
C++
src/ulib/FileFinder.cpp
vividos/UlibCpp
d96348844348a00523b7742b3e7a5c9764613877
[ "BSD-2-Clause" ]
null
null
null
src/ulib/FileFinder.cpp
vividos/UlibCpp
d96348844348a00523b7742b3e7a5c9764613877
[ "BSD-2-Clause" ]
null
null
null
src/ulib/FileFinder.cpp
vividos/UlibCpp
d96348844348a00523b7742b3e7a5c9764613877
[ "BSD-2-Clause" ]
null
null
null
// // ulib - a collection of useful classes // Copyright (C) 2008-2014,2017 Michael Fink // /// \file FileFinder.cpp File finder // // includes #include "stdafx.h" #include <ulib/FileFinder.hpp> #include <ulib/Path.hpp> std::vector<CString> FileFinder::FindAllInPath(const CString& path, const CString& fileSpec, bool findFolders, bool recursive) { std::vector<CString> filenamesList; FileFinder finder(path, fileSpec); if (finder.IsValid()) { do { if (finder.IsDot()) continue; if (recursive && finder.IsFolder()) { std::vector<CString> subfolderFilenamesList = FindAllInPath(finder.Filename(), fileSpec, findFolders, true); if (!subfolderFilenamesList.empty()) filenamesList.insert(filenamesList.end(), subfolderFilenamesList.begin(), subfolderFilenamesList.end()); } if (findFolders && finder.IsFile()) continue; if (!findFolders && finder.IsFolder()) continue; filenamesList.push_back(finder.Filename()); } while (finder.Next()); } return filenamesList; }
24.659574
126
0.620362
vividos
40d1852ec0aba78e9722ea095b77914a2264988c
4,657
cpp
C++
HCore/CCore/test/test4014.SysFile.cpp
SergeyStrukov/CCore-2-xx
118aa4011ee7cc587298d6373b6587540e044a83
[ "BSL-1.0" ]
8
2017-12-21T07:00:16.000Z
2020-04-02T09:05:55.000Z
HCore/CCore/test/test4014.SysFile.cpp
SergeyStrukov/CCore-2-99
1eca5b9b2de067bbab43326718b877465ae664fe
[ "BSL-1.0" ]
null
null
null
HCore/CCore/test/test4014.SysFile.cpp
SergeyStrukov/CCore-2-99
1eca5b9b2de067bbab43326718b877465ae664fe
[ "BSL-1.0" ]
1
2020-03-30T09:54:18.000Z
2020-03-30T09:54:18.000Z
/* test4014.SysFile.cpp */ //---------------------------------------------------------------------------------------- // // Project: CCore 2.00 // // Tag: HCore Mini // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2015 Sergey Strukov. All rights reserved. // //---------------------------------------------------------------------------------------- #include <CCore/test/test.h> #include <CCore/inc/sys/SysFile.h> namespace App { namespace Private_4014 { /* class File */ class File : NoCopy { Sys::File file; bool ok; public: File() : ok(false) {} void open(StrLen file_name,FileOpenFlags oflags) { if( ok ) return; FileError fe=file.open(file_name,oflags); Printf(Con,"open(#.q;,#;) : #;\n",file_name,oflags,fe); ok=!fe; } void close(bool preserve_file=false) { if( !ok ) return; FileMultiError errout; file.close(errout,preserve_file); Printf(Con,"close(#;) : #;\n",preserve_file,errout); ok=false; } ulen write(const uint8 *buf,ulen len) { if( !ok ) return 0; auto result=file.write(buf,len); Printf(Con,"write(...,#;) : #; #;\n",len,result.error,result.len); return result.len; } ulen read(uint8 *buf,ulen len) { if( !ok ) return 0; auto result=file.read(buf,len); Printf(Con,"read(...,#;) : #; #;\n",len,result.error,result.len); return result.len; } FilePosType getLen() { if( !ok ) return 0; auto result=file.getLen(); Printf(Con,"getLen() : #; #;\n",result.error,result.pos); return result.pos; } FilePosType getPos() { if( !ok ) return 0; auto result=file.getPos(); Printf(Con,"getPos() : #; #;\n",result.error,result.pos); return result.pos; } void setPos(FilePosType pos) { if( !ok ) return; FileError fe=file.setPos(pos); Printf(Con,"setPos(#;) : #;\n",pos,fe); } }; /* test1() */ void test1() { File file; // 1 file.open("not_exist.txt",Open_Read); file.open("z:not_exist.txt",Open_Read); file.open("no_write.txt",Open_Write); file.open("no_write.txt",Open_Read); file.close(); // 2 file.open("no_read.txt",Open_Read); file.open("no_read.txt",Open_Write); file.close(); // 3 file.open("temp.txt",Open_Write|Open_AutoDelete|Open_New); file.close(); file.open("temp.txt",Open_Write|Open_AutoDelete); file.close(); file.open("temp.txt",Open_Write|Open_AutoDelete|Open_Create|Open_Pos); file.getLen(); file.close(); file.open("temp.txt",Open_Write|Open_AutoDelete|Open_Erase); file.close(); file.open("temp.txt",Open_Write|Open_AutoDelete|Open_Create|Open_Erase|Open_Pos); file.getLen(); file.close(); // 4 const ulen Len = 100 ; uint8 buf[Len]; Range(buf).set('1'); // 5 file.open("temp_saved.txt",Open_Write|Open_New); file.close(); file.open("temp_saved.txt",Open_Write|Open_Pos); file.write(buf,Len); file.getLen(); file.close(); file.open("temp_saved.txt",Open_Write|Open_Create|Open_Pos); file.getLen(); file.close(); file.open("temp_saved.txt",Open_Write|Open_Erase|Open_Pos); file.getLen(); file.write(buf,Len); file.close(); file.open("temp_saved.txt",Open_Write|Open_AutoDelete|Open_Create|Open_Erase|Open_Pos); file.getLen(); file.close(true); } /* test2() */ void test2() { const ulen WLen = 100 ; const ulen RLen = 200 ; uint8 wbuf[WLen]; uint8 rbuf[RLen]; Range(wbuf).set('1'); // file File file; file.open("temp.txt",Open_AutoDelete); file.close(); file.open("temp.txt",Open_Create|Open_Write); file.write(wbuf,WLen); file.read(rbuf,RLen); file.setPos(WLen/2); file.close(); file.open("temp.txt",Open_Read); file.read(rbuf,RLen); if( !Range(wbuf).equal(Range(rbuf,WLen)) ) Printf(Con,"not equal\n"); file.close(); } /* test3() */ void test3() { const ulen WLen = 100 ; uint8 wbuf[WLen]; Range(wbuf).set('1'); // file File file; file.open("temp.txt",Open_ToWrite|Open_Pos|Open_AutoDelete); file.write(wbuf,WLen); file.getLen(); file.setPos(WLen/2); file.getPos(); file.setPos(WLen); file.getPos(); file.setPos(0); file.getPos(); file.close(); } } // namespace Private_4014 using namespace Private_4014; /* Testit<4014> */ template<> const char *const Testit<4014>::Name="Test4014 SysFile"; template<> bool Testit<4014>::Main() { test1(); test2(); test3(); return true; } } // namespace App
15.680135
90
0.591797
SergeyStrukov
40d3362406b38275b0edb6490753fad9cf0c904f
15,657
cpp
C++
cfgmgr/vxlanmgr.cpp
antony-rheneus/sonic-swss
4bb9142edacf013bdbd613dc5f5e8b2aa1265584
[ "Apache-2.0" ]
null
null
null
cfgmgr/vxlanmgr.cpp
antony-rheneus/sonic-swss
4bb9142edacf013bdbd613dc5f5e8b2aa1265584
[ "Apache-2.0" ]
null
null
null
cfgmgr/vxlanmgr.cpp
antony-rheneus/sonic-swss
4bb9142edacf013bdbd613dc5f5e8b2aa1265584
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <regex> #include <sstream> #include <string> #include <net/if.h> #include "logger.h" #include "producerstatetable.h" #include "macaddress.h" #include "vxlanmgr.h" #include "exec.h" #include "tokenize.h" #include "shellcmd.h" #include "warm_restart.h" using namespace std; using namespace swss; // Fields name #define VXLAN_TUNNEL "vxlan_tunnel" #define SOURCE_IP "src_ip" #define VNI "vni" #define VNET "vnet" #define VXLAN "vxlan" #define VXLAN_IF "vxlan_if" #define VXLAN_NAME_PREFIX "Vxlan" #define VXLAN_IF_NAME_PREFIX "Brvxlan" static std::string getVxlanName(const swss::VxlanMgr::VxlanInfo & info) { return std::string("") + VXLAN_NAME_PREFIX + info.m_vni; } static std::string getVxlanIfName(const swss::VxlanMgr::VxlanInfo & info) { return std::string("") + VXLAN_IF_NAME_PREFIX + info.m_vni; } // Commands #define RET_SUCCESS 0 #define EXECUTE(CMD, RESULT) swss::exec(std::string() + BASH_CMD + " -c \"" + CMD + "\"", RESULT); static int cmdCreateVxlan(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link add {{VXLAN}} type vxlan id {{VNI}} [local {{SOURCE IP}}] dstport 4789 const std::string cmd = std::string("") + IP_CMD " link add " + info.m_vxlan + " type vxlan id " + info.m_vni + " " + (info.m_sourceIp.empty() ? "" : (" local " + info.m_sourceIp)) + " dstport 4789"; return EXECUTE(cmd, res); } static int cmdUpVxlan(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link set dev {{VXLAN}} up const std::string cmd = std::string("") + IP_CMD " link set dev " + info.m_vxlan + " up"; return EXECUTE(cmd, res); } static int cmdCreateVxlanIf(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link add {{VXLAN_IF}} type bridge const std::string cmd = std::string("") + IP_CMD " link add " + info.m_vxlanIf + " type bridge"; return EXECUTE(cmd, res); } static int cmdAddVxlanIntoVxlanIf(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // brctl addif {{VXLAN_IF}} {{VXLAN}} const std::string cmd = std::string("") + BRCTL_CMD " addif " + info.m_vxlanIf + " " + info.m_vxlan; return EXECUTE(cmd, res); } static int cmdAttachVxlanIfToVnet(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link set dev {{VXLAN_IF}} master {{VNET}} const std::string cmd = std::string("") + IP_CMD " link set dev " + info.m_vxlanIf + " master " + info.m_vnet; return EXECUTE(cmd, res); } static int cmdUpVxlanIf(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link set dev {{VXLAN_IF}} up const std::string cmd = std::string("") + IP_CMD " link set dev " + info.m_vxlanIf + " up"; return EXECUTE(cmd, res); } static int cmdDeleteVxlan(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link del dev {{VXLAN}} const std::string cmd = std::string("") + IP_CMD " link del dev " + info.m_vxlan; return EXECUTE(cmd, res); } static int cmdDeleteVxlanFromVxlanIf(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // brctl delif {{VXLAN_IF}} {{VXLAN}} const std::string cmd = std::string("") + BRCTL_CMD " delif " + info.m_vxlanIf + " " + info.m_vxlan; return EXECUTE(cmd, res); } static int cmdDeleteVxlanIf(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link del {{VXLAN_IF}} const std::string cmd = std::string("") + IP_CMD " link del " + info.m_vxlanIf; return EXECUTE(cmd, res); } static int cmdDetachVxlanIfFromVnet(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link set dev {{VXLAN_IF}} nomaster const std::string cmd = std::string("") + IP_CMD " link set dev " + info.m_vxlanIf + " nomaster"; return EXECUTE(cmd, res); } // Vxlanmgr VxlanMgr::VxlanMgr(DBConnector *cfgDb, DBConnector *appDb, DBConnector *stateDb, const vector<std::string> &tables) : Orch(cfgDb, tables), m_appVxlanTunnelTable(appDb, APP_VXLAN_TUNNEL_TABLE_NAME), m_appVxlanTunnelMapTable(appDb, APP_VXLAN_TUNNEL_MAP_TABLE_NAME), m_cfgVxlanTunnelTable(cfgDb, CFG_VXLAN_TUNNEL_TABLE_NAME), m_cfgVnetTable(cfgDb, CFG_VNET_TABLE_NAME), m_stateVrfTable(stateDb, STATE_VRF_TABLE_NAME), m_stateVxlanTable(stateDb, STATE_VXLAN_TABLE_NAME) { // Clear old vxlan devices that were created at last time. clearAllVxlanDevices(); } VxlanMgr::~VxlanMgr() { clearAllVxlanDevices(); } void VxlanMgr::doTask(Consumer &consumer) { SWSS_LOG_ENTER(); const string & table_name = consumer.getTableName(); auto it = consumer.m_toSync.begin(); while (it != consumer.m_toSync.end()) { bool task_result = false; auto t = it->second; const std::string & op = kfvOp(t); if (op == SET_COMMAND) { if (table_name == CFG_VNET_TABLE_NAME) { task_result = doVxlanCreateTask(t); } else if (table_name == CFG_VXLAN_TUNNEL_TABLE_NAME) { task_result = doVxlanTunnelCreateTask(t); } else if (table_name == CFG_VXLAN_TUNNEL_MAP_TABLE_NAME) { task_result = doVxlanTunnelMapCreateTask(t); } else { SWSS_LOG_ERROR("Unknown table : %s", table_name.c_str()); } } else if (op == DEL_COMMAND) { if (table_name == CFG_VNET_TABLE_NAME) { task_result = doVxlanDeleteTask(t); } else if (table_name == CFG_VXLAN_TUNNEL_TABLE_NAME) { task_result = doVxlanTunnelDeleteTask(t); } else if (table_name == CFG_VXLAN_TUNNEL_MAP_TABLE_NAME) { task_result = doVxlanTunnelMapDeleteTask(t); } else { SWSS_LOG_ERROR("Unknown table : %s", table_name.c_str()); } } else { SWSS_LOG_ERROR("Unknown command : %s", op.c_str()); } if (task_result == true) { it = consumer.m_toSync.erase(it); } else { ++it; } } } bool VxlanMgr::doVxlanCreateTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); VxlanInfo info; info.m_vnet = kfvKey(t); for (auto i : kfvFieldsValues(t)) { const std::string & field = fvField(i); const std::string & value = fvValue(i); if (field == VXLAN_TUNNEL) { info.m_vxlanTunnel = value; } else if (field == VNI) { info.m_vni = value; } } // If all information of vnet has been set if (info.m_vxlanTunnel.empty() || info.m_vni.empty()) { SWSS_LOG_DEBUG("Vnet %s information is incomplete", info.m_vnet.c_str()); // if the information is incomplete, just ignore this message // because all information will be sent if the information was // completely set. return true; } // If the vxlan tunnel has been created auto it = m_vxlanTunnelCache.find(info.m_vxlanTunnel); if (it == m_vxlanTunnelCache.end()) { SWSS_LOG_DEBUG("Vxlan tunnel %s has not been created", info.m_vxlanTunnel.c_str()); // Suspend this message util the vxlan tunnel is created return false; } // If the VRF(Vnet is a special VRF) has been created if (!isVrfStateOk(info.m_vnet)) { SWSS_LOG_DEBUG("Vrf %s has not been created", info.m_vnet.c_str()); // Suspend this message util the vrf is created return false; } auto sourceIp = std::find_if( it->second.begin(), it->second.end(), [](const FieldValueTuple & fvt){ return fvt.first == SOURCE_IP; }); if (sourceIp != it->second.end()) { info.m_sourceIp = sourceIp->second; } info.m_vxlan = getVxlanName(info); info.m_vxlanIf = getVxlanIfName(info); // If this vxlan has been created if (isVxlanStateOk(info.m_vxlan)) { // Because the vxlan has been create, so this message is to update // the information of vxlan. // This program just delete the old vxlan and create a new one // according to this message. doVxlanDeleteTask(t); } if (!createVxlan(info)) { SWSS_LOG_ERROR("Cannot create vxlan %s", info.m_vxlan.c_str()); return true; } m_vnetCache[info.m_vnet] = info; SWSS_LOG_INFO("Create vxlan %s", info.m_vxlan.c_str()); return true; } bool VxlanMgr::doVxlanDeleteTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); const std::string & vnetName = kfvKey(t); auto it = m_vnetCache.find(vnetName); if (it == m_vnetCache.end()) { SWSS_LOG_WARN("Vxlan(Vnet %s) hasn't been created ", vnetName.c_str()); return true; } const VxlanInfo & info = it->second; if (isVxlanStateOk(info.m_vxlan)) { if ( ! deleteVxlan(info)) { SWSS_LOG_ERROR("Cannot delete vxlan %s", info.m_vxlan.c_str()); return false; } } else { SWSS_LOG_WARN("Vxlan %s hasn't been created ", info.m_vxlan.c_str()); } m_vnetCache.erase(it); SWSS_LOG_INFO("Delete vxlan %s", info.m_vxlan.c_str()); return true; } bool VxlanMgr::doVxlanTunnelCreateTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); const std::string & vxlanTunnelName = kfvKey(t); m_appVxlanTunnelTable.set(vxlanTunnelName, kfvFieldsValues(t)); // Update vxlan tunnel cache m_vxlanTunnelCache[vxlanTunnelName] = kfvFieldsValues(t); SWSS_LOG_INFO("Create vxlan tunnel %s", vxlanTunnelName.c_str()); return true; } bool VxlanMgr::doVxlanTunnelDeleteTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); const std::string & vxlanTunnelName = kfvKey(t); m_appVxlanTunnelTable.del(vxlanTunnelName); auto it = m_vxlanTunnelCache.find(vxlanTunnelName); if (it != m_vxlanTunnelCache.end()) { m_vxlanTunnelCache.erase(it); } SWSS_LOG_INFO("Delete vxlan tunnel %s", vxlanTunnelName.c_str()); return true; } bool VxlanMgr::doVxlanTunnelMapCreateTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); std::string vxlanTunnelMapName = kfvKey(t); std::replace(vxlanTunnelMapName.begin(), vxlanTunnelMapName.end(), config_db_key_delimiter, delimiter); m_appVxlanTunnelMapTable.set(vxlanTunnelMapName, kfvFieldsValues(t)); SWSS_LOG_NOTICE("Create vxlan tunnel map %s", vxlanTunnelMapName.c_str()); return true; } bool VxlanMgr::doVxlanTunnelMapDeleteTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); std::string vxlanTunnelMapName = kfvKey(t); std::replace(vxlanTunnelMapName.begin(), vxlanTunnelMapName.end(), config_db_key_delimiter, delimiter); m_appVxlanTunnelMapTable.del(vxlanTunnelMapName); SWSS_LOG_NOTICE("Delete vxlan tunnel map %s", vxlanTunnelMapName.c_str()); return true; } bool VxlanMgr::isVrfStateOk(const std::string & vrfName) { SWSS_LOG_ENTER(); std::vector<FieldValueTuple> temp; if (m_stateVrfTable.get(vrfName, temp)) { SWSS_LOG_DEBUG("Vrf %s is ready", vrfName.c_str()); return true; } SWSS_LOG_DEBUG("Vrf %s is not ready", vrfName.c_str()); return false; } bool VxlanMgr::isVxlanStateOk(const std::string & vxlanName) { SWSS_LOG_ENTER(); std::vector<FieldValueTuple> temp; if (m_stateVxlanTable.get(vxlanName, temp)) { SWSS_LOG_DEBUG("Vxlan %s is ready", vxlanName.c_str()); return true; } SWSS_LOG_DEBUG("Vxlan %s is not ready", vxlanName.c_str()); return false; } bool VxlanMgr::createVxlan(const VxlanInfo & info) { SWSS_LOG_ENTER(); std::string res; int ret = 0; // Create Vxlan ret = cmdCreateVxlan(info, res); if (ret != RET_SUCCESS) { SWSS_LOG_WARN( "Failed to create vxlan %s (vni: %s, source ip %s)", info.m_vxlan.c_str(), info.m_vni.c_str(), info.m_sourceIp.c_str()); return false; } // Up Vxlan ret = cmdUpVxlan(info, res); if (ret != RET_SUCCESS) { cmdDeleteVxlan(info, res); SWSS_LOG_WARN( "Fail to up vxlan %s", info.m_vxlan.c_str()); return false; } // Create Vxlan Interface ret = cmdCreateVxlanIf(info, res); if (ret != RET_SUCCESS) { cmdDeleteVxlan(info, res); SWSS_LOG_WARN( "Fail to create vxlan interface %s", info.m_vxlanIf.c_str()); return false; } // Add vxlan into vxlan interface ret = cmdAddVxlanIntoVxlanIf(info, res); if ( ret != RET_SUCCESS ) { cmdDeleteVxlanIf(info, res); cmdDeleteVxlan(info, res); SWSS_LOG_WARN( "Fail to add %s into %s", info.m_vxlan.c_str(), info.m_vxlanIf.c_str()); return false; } // Attach vxlan interface to vnet ret = cmdAttachVxlanIfToVnet(info, res); if ( ret != RET_SUCCESS ) { cmdDeleteVxlanFromVxlanIf(info, res); cmdDeleteVxlanIf(info, res); cmdDeleteVxlan(info, res); SWSS_LOG_WARN( "Fail to set %s master %s", info.m_vxlanIf.c_str(), info.m_vnet.c_str()); return false; } // Up Vxlan Interface ret = cmdUpVxlanIf(info, res); if ( ret != RET_SUCCESS ) { cmdDetachVxlanIfFromVnet(info, res); cmdDeleteVxlanFromVxlanIf(info, res); cmdDeleteVxlanIf(info, res); cmdDeleteVxlan(info, res); SWSS_LOG_WARN( "Fail to up bridge %s", info.m_vxlanIf.c_str()); return false; } std::vector<FieldValueTuple> fvVector; fvVector.emplace_back("state", "ok"); m_stateVxlanTable.set(info.m_vxlan, fvVector); return true; } bool VxlanMgr::deleteVxlan(const VxlanInfo & info) { SWSS_LOG_ENTER(); std::string res; cmdDetachVxlanIfFromVnet(info, res); cmdDeleteVxlanFromVxlanIf(info, res); cmdDeleteVxlanIf(info, res); cmdDeleteVxlan(info, res); m_stateVxlanTable.del(info.m_vxlan); return true; } void VxlanMgr::clearAllVxlanDevices() { std::string stdout; const std::string cmd = std::string("") + IP_CMD + " link"; int ret = EXECUTE(cmd, stdout); if (ret != 0) { SWSS_LOG_ERROR("Cannot get devices by command : %s", cmd.c_str()); return; } std::regex device_name_pattern("^\\d+:\\s+([^:]+)"); std::smatch match_result; auto lines = tokenize(stdout, '\n'); for (const std::string & line : lines) { if (!std::regex_search(line, match_result, device_name_pattern)) { continue; } std::string res; std::string device_name = match_result[1]; VxlanInfo info; if (device_name.find(VXLAN_NAME_PREFIX) == 0) { info.m_vxlan = device_name; cmdDeleteVxlan(info, res); } else if (device_name.find(VXLAN_IF_NAME_PREFIX) == 0) { info.m_vxlanIf = device_name; cmdDeleteVxlanIf(info, res); } } }
27.277003
117
0.605288
antony-rheneus
40d55c42fe669f510fc1d218f82bf4521d558aba
4,498
cpp
C++
Userland/userdel.cpp
howar6hill/serenity
3523071bb7527159f213d3710f4c74d10cf93b1a
[ "BSD-2-Clause" ]
null
null
null
Userland/userdel.cpp
howar6hill/serenity
3523071bb7527159f213d3710f4c74d10cf93b1a
[ "BSD-2-Clause" ]
null
null
null
Userland/userdel.cpp
howar6hill/serenity
3523071bb7527159f213d3710f4c74d10cf93b1a
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2019-2020, Fei Wu <f.eiwu@yahoo.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <AK/String.h> #include <AK/StringBuilder.h> #include <LibCore/ArgsParser.h> #include <ctype.h> #include <dirent.h> #include <errno.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> int main(int argc, char** argv) { const char* username = nullptr; bool remove_home = false; Core::ArgsParser args_parser; args_parser.add_option(remove_home, "Remove home directory", "remove", 'r'); args_parser.add_positional_argument(username, "Login user identity (username)", "login"); args_parser.parse(argc, argv); char temp_filename[] = "/etc/passwd.XXXXXX"; auto fd = mkstemp(temp_filename); if (fd == -1) { perror("failed to create temporary file"); return 1; } FILE* temp_file = fdopen(fd, "w"); if (!temp_file) { perror("fdopen"); if (unlink(temp_filename) < 0) { perror("unlink"); } return 1; } bool user_exists = false; String home_directory; int rc = 0; setpwent(); for (auto* pw = getpwent(); pw; pw = getpwent()) { if (strcmp(pw->pw_name, username)) { if (putpwent(pw, temp_file) != 0) { perror("failed to put an entry in the temporary passwd file"); rc = 1; break; } } else { user_exists = true; if (remove_home) home_directory = pw->pw_dir; } } endpwent(); if (fclose(temp_file)) { perror("fclose"); if (!rc) rc = 1; } if (rc == 0 && !user_exists) { fprintf(stderr, "specified user doesn't exist\n"); rc = 6; } if (rc == 0 && chmod(temp_filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) { perror("chmod"); rc = 1; } if (rc == 0 && rename(temp_filename, "/etc/passwd") < 0) { perror("failed to rename the temporary passwd file"); rc = 1; } if (rc) { if (unlink(temp_filename) < 0) { perror("unlink"); } return rc; } if (remove_home) { if (home_directory == "/") { fprintf(stderr, "home directory is /, not deleted!\n"); return 12; } if (access(home_directory.characters(), F_OK) != -1) { auto child = fork(); if (child < 0) { perror("fork"); return 12; } if (!child) { int rc = execl("/bin/rm", "rm", "-r", home_directory.characters(), nullptr); ASSERT(rc < 0); perror("execl"); exit(127); } int wstatus; if (waitpid(child, &wstatus, 0) < 0) { perror("waitpid"); return 12; } if (WEXITSTATUS(wstatus)) { fprintf(stderr, "failed to remove the home directory\n"); return 12; } } } return 0; }
29.592105
93
0.581147
howar6hill
40d65b0d5998de530a36e9fba1b2dbde81aa0165
228
cpp
C++
0006 - Beginner Series #3 Sum of Numbers/solution.cpp
dimitri-dev/CodeWars
da428b2f9da4e56080aac6196575e101b1395c6d
[ "MIT" ]
null
null
null
0006 - Beginner Series #3 Sum of Numbers/solution.cpp
dimitri-dev/CodeWars
da428b2f9da4e56080aac6196575e101b1395c6d
[ "MIT" ]
null
null
null
0006 - Beginner Series #3 Sum of Numbers/solution.cpp
dimitri-dev/CodeWars
da428b2f9da4e56080aac6196575e101b1395c6d
[ "MIT" ]
null
null
null
#include <iostream> using std::cin; using std::cout; int get_sum(int a, int b) { int n = (a < b ? b - a : a - b) + 1; return n * (a + b) / 2; } int main() { std::ios::sync_with_stdio(false); std::cin.tie(0); }
14.25
40
0.526316
dimitri-dev
40d742ae6cde6569ce9dd7d213a2241797716128
539
cpp
C++
Codeforces/1000~1999/1244/G.cpp
tiger0132/code-backup
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
[ "MIT" ]
6
2018-12-30T06:16:54.000Z
2022-03-23T08:03:33.000Z
Codeforces/1000~1999/1244/G.cpp
tiger0132/code-backup
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
[ "MIT" ]
null
null
null
Codeforces/1000~1999/1244/G.cpp
tiger0132/code-backup
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
[ "MIT" ]
null
null
null
#include <algorithm> #include <cstdio> #include <cstring> typedef long long ll; const int N = 1e6 + 61; int n, l, r, a[N]; ll k, c; int main() { scanf("%d%lld", &n, &k); if ((c = n * (n + 1ll) / 2) > k) return puts("-1"), 0; for (int i = 1; i <= n; i++) a[i] = i; l = 1, r = n; for (; l < r && c < k; l++, r--) { int rb = std::min((ll)r - l, k - c); std::swap(a[l], a[l + rb]), c += rb; } printf("%lld\n", c); for (int i = 1; i <= n; i++) printf("%d%c", i, " \n"[i == n]); for (int i = 1; i <= n; i++) printf("%d ", a[i]); }
24.5
63
0.445269
tiger0132
40d7a913383786c67a1d3eb9b5586bd8b0bb3050
3,482
cpp
C++
ReShade/Runtime/runtime_config.cpp
nipkownix/Silent-Hill-2-Enhancements
53f0990c0eb2ca1b81b6645d08a586075556bf64
[ "Zlib" ]
356
2017-11-24T21:59:54.000Z
2022-03-12T01:41:39.000Z
ReShade/Runtime/runtime_config.cpp
nipkownix/Silent-Hill-2-Enhancements
53f0990c0eb2ca1b81b6645d08a586075556bf64
[ "Zlib" ]
501
2017-11-24T23:32:16.000Z
2022-03-31T22:28:14.000Z
ReShade/Runtime/runtime_config.cpp
nipkownix/Silent-Hill-2-Enhancements
53f0990c0eb2ca1b81b6645d08a586075556bf64
[ "Zlib" ]
41
2018-04-22T19:24:56.000Z
2022-02-28T01:56:10.000Z
/** * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license * * Copyright (C) 2021 Elisha Riedlinger * * 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. */ #define RESHADE_FILE_LIST #include "runtime.hpp" #include "runtime_config.hpp" #include "runtime_objects.hpp" #include "Resources\sh2-enhce.h" #include <cassert> #include <fstream> #include <sstream> #include <iostream> extern DWORD GammaLevel; struct { bool loaded = false; reshade::ini_file cache; }g_ini_cache; reshade::ini_file::ini_file() { load(); } reshade::ini_file::~ini_file() {} void reshade::ini_file::load() { if (g_ini_cache.loaded) { return; } _sections.clear(); _modified = false; std::string GammaSection("[GammaLevel" + std::to_string(GammaLevel) + "]"); std::string file, section, line; g_ini_cache.loaded = read_resource(IDR_RESHADE_INI, file); std::istringstream s_file(file.c_str()); while (std::getline(s_file, line)) { trim(line); if (line.empty() || line[0] == ';' || line[0] == '/' || line[0] == '#') { continue; } if (line.compare(GammaSection) == 0) { line.assign("[" + GammaEffectName + ".fx]"); } // Read section name if (line[0] == '[') { section = trim(line.substr(0, line.find(']')), " \t[]"); continue; } // Read section content const auto assign_index = line.find('='); if (assign_index != std::string::npos) { const std::string key = trim(line.substr(0, assign_index)); const std::string value = trim(line.substr(assign_index + 1)); // Append to key if it already exists reshade::ini_file::value &elements = _sections[section][key]; for (size_t offset = 0, base = 0, len = value.size(); offset <= len;) { // Treat ",," as an escaped comma and only split on single "," const size_t found = std::min(value.find_first_of(',', offset), len); if (found + 1 < len && value[found + 1] == ',') { offset = found + 2; } else { std::string &element = elements.emplace_back(); element.reserve(found - base); while (base < found) { const char c = value[base++]; element += c; if (c == ',' && base < found && value[base] == ',') { base++; // Skip second comma in a ",," escape sequence } } base = offset = found + 1; } } } else { _sections[section].insert({ line, {} }); } } } void reshade::ini_file::reset_config() { g_ini_cache.loaded = false; g_ini_cache.cache.load(); } reshade::ini_file &reshade::ini_file::load_cache() { if (!g_ini_cache.loaded) { g_ini_cache.cache.load(); } return g_ini_cache.cache; }
25.985075
101
0.649339
nipkownix
40d8ff15adf3570c79c5f9e9a05603c15c8dd3a0
503
hpp
C++
addons/flag/CfgVehicles.hpp
61st-Cavalry-Regiment/61st-aux
bc6e956553fba774881c682a3f12c1b426256a30
[ "MIT" ]
2
2020-05-25T20:29:29.000Z
2020-05-26T21:11:23.000Z
addons/flag/CfgVehicles.hpp
61st-Cavalry-Regiment/61st-aux
bc6e956553fba774881c682a3f12c1b426256a30
[ "MIT" ]
3
2020-06-02T07:38:40.000Z
2021-11-13T04:54:28.000Z
addons/flag/CfgVehicles.hpp
61st-Cavalry-Regiment/61st-aux
bc6e956553fba774881c682a3f12c1b426256a30
[ "MIT" ]
1
2020-05-26T21:11:28.000Z
2020-05-26T21:11:28.000Z
class CfgVehicles { class Flag_White_F; class GVAR(Flag): Flag_White_F { author = ECSTRING(main, author); displayName = CSTRING(display); scopecurator = public; scope = public; class EventHandlers { init = QUOTE((_this select 0) setFlagTexture QUOTE(QPATHTOF(data\61stFlag.paa))); }; }; class GVAR(FlagYellow): GVAR(Flag){ displayName = CSTRING(displayYellow); class EventHandlers { init = QUOTE((_this select 0) setFlagTexture QUOTE(QPATHTOF(data\61stFlagY.paa))); }; }; };
27.944444
85
0.709742
61st-Cavalry-Regiment
40d96d3485682aa186723caedee313509a5f52f9
4,274
cpp
C++
modules/clientnotify.cpp
md-5/znc
39c741fcd2307d707a0d1bebbed3d80be9b1899b
[ "Apache-2.0" ]
null
null
null
modules/clientnotify.cpp
md-5/znc
39c741fcd2307d707a0d1bebbed3d80be9b1899b
[ "Apache-2.0" ]
null
null
null
modules/clientnotify.cpp
md-5/znc
39c741fcd2307d707a0d1bebbed3d80be9b1899b
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2004-2015 ZNC, see the NOTICE file for details. * * 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 <znc/znc.h> #include <znc/User.h> using std::set; class CClientNotifyMod : public CModule { protected: CString m_sMethod; bool m_bNewOnly; bool m_bOnDisconnect; set<CString> m_sClientsSeen; void SaveSettings() { SetNV("method", m_sMethod); SetNV("newonly", m_bNewOnly ? "1" : "0"); SetNV("ondisconnect", m_bOnDisconnect ? "1" : "0"); } void SendNotification(const CString& sMessage) { if(m_sMethod == "message") { GetUser()->PutStatus(sMessage, NULL, GetClient()); } else if(m_sMethod == "notice") { GetUser()->PutStatusNotice(sMessage, NULL, GetClient()); } } public: MODCONSTRUCTOR(CClientNotifyMod) { AddHelpCommand(); AddCommand("Method", static_cast<CModCommand::ModCmdFunc>(&CClientNotifyMod::OnMethodCommand), "<message|notice|off>", "Sets the notify method"); AddCommand("NewOnly", static_cast<CModCommand::ModCmdFunc>(&CClientNotifyMod::OnNewOnlyCommand), "<on|off>", "Turns notifies for unseen IP addresses only on or off"); AddCommand("OnDisconnect", static_cast<CModCommand::ModCmdFunc>(&CClientNotifyMod::OnDisconnectCommand), "<on|off>", "Turns notifies on disconnecting clients on or off"); AddCommand("Show", static_cast<CModCommand::ModCmdFunc>(&CClientNotifyMod::OnShowCommand), "", "Show the current settings"); } bool OnLoad(const CString& sArgs, CString& sMessage) override { m_sMethod = GetNV("method"); if(m_sMethod != "notice" && m_sMethod != "message" && m_sMethod != "off") { m_sMethod = "message"; } // default = off for these: m_bNewOnly = (GetNV("newonly") == "1"); m_bOnDisconnect = (GetNV("ondisconnect") == "1"); return true; } void OnClientLogin() override { CString sRemoteIP = GetClient()->GetRemoteIP(); if(!m_bNewOnly || m_sClientsSeen.find(sRemoteIP) == m_sClientsSeen.end()) { SendNotification("Another client authenticated as your user. " "Use the 'ListClients' command to see all " + CString(GetUser()->GetAllClients().size()) + " clients."); // the set<> will automatically disregard duplicates: m_sClientsSeen.insert(sRemoteIP); } } void OnClientDisconnect() override { if(m_bOnDisconnect) { SendNotification("A client disconnected from your user. " "Use the 'ListClients' command to see the " + CString(GetUser()->GetAllClients().size()) + " remaining client(s)."); } } void OnMethodCommand(const CString& sCommand) { const CString& sArg = sCommand.Token(1, true).AsLower(); if (sArg != "notice" && sArg != "message" && sArg != "off") { PutModule("Usage: Method <message|notice|off>"); return; } m_sMethod = sArg; SaveSettings(); PutModule("Saved."); } void OnNewOnlyCommand(const CString& sCommand) { const CString& sArg = sCommand.Token(1, true).AsLower(); if (sArg.empty()) { PutModule("Usage: NewOnly <on|off>"); return; } m_bNewOnly = sArg.ToBool(); SaveSettings(); PutModule("Saved."); } void OnDisconnectCommand(const CString& sCommand) { const CString& sArg = sCommand.Token(1, true).AsLower(); if (sArg.empty()) { PutModule("Usage: OnDisconnect <on|off>"); return; } m_bOnDisconnect = sArg.ToBool(); SaveSettings(); PutModule("Saved."); } void OnShowCommand(const CString& sLine) { PutModule("Current settings: Method: " + m_sMethod + ", for unseen IP addresses only: " + CString(m_bNewOnly) + ", notify on disconnecting clients: " + CString(m_bOnDisconnect)); } }; template<> void TModInfo<CClientNotifyMod>(CModInfo& Info) { Info.SetWikiPage("clientnotify"); } USERMODULEDEFS(CClientNotifyMod, "Notifies you when another IRC client logs into or out of your account. Configurable.")
30.528571
172
0.697005
md-5
40d96ee8a0e461a4548b0f59d840c3dfb9b8bce8
1,021
hpp
C++
trunk/win/Source/Includes/Boost/fusion/container/generation.hpp
dyzmapl/BumpTop
1329ea41411c7368516b942d19add694af3d602f
[ "Apache-2.0" ]
460
2016-01-13T12:49:34.000Z
2022-02-20T04:10:40.000Z
external/windows/boost/include/boost/fusion/container/generation.hpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
24
2016-11-07T04:59:49.000Z
2022-03-14T06:34:12.000Z
external/windows/boost/include/boost/fusion/container/generation.hpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
148
2016-01-17T03:16:43.000Z
2022-03-17T12:20:36.000Z
/*============================================================================= Copyright (c) 2001-2006 Joel de Guzman 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) ==============================================================================*/ #if !defined(FUSION_SEQUENCE_GENERATION_10022005_0615) #define FUSION_SEQUENCE_GENERATION_10022005_0615 #include <boost/fusion/container/generation/cons_tie.hpp> #include <boost/fusion/container/generation/ignore.hpp> #include <boost/fusion/container/generation/list_tie.hpp> #include <boost/fusion/container/generation/make_cons.hpp> #include <boost/fusion/container/generation/make_list.hpp> #include <boost/fusion/container/generation/make_map.hpp> #include <boost/fusion/container/generation/make_vector.hpp> #include <boost/fusion/container/generation/vector_tie.hpp> #include <boost/fusion/container/generation/make_set.hpp> #endif
48.619048
82
0.670911
dyzmapl
40dbcfa342afd32f1a1720e306ca54d697957d1c
1,251
hpp
C++
PUTM_EV_TELEMETRY_2022/Core/Inc/Data_Handling.hpp
PUT-Motorsport/PUTM_EV_TELEMETRY_2022
808ed3e7c9b4263b541a804233e5905f6a9b4240
[ "Apache-2.0" ]
null
null
null
PUTM_EV_TELEMETRY_2022/Core/Inc/Data_Handling.hpp
PUT-Motorsport/PUTM_EV_TELEMETRY_2022
808ed3e7c9b4263b541a804233e5905f6a9b4240
[ "Apache-2.0" ]
null
null
null
PUTM_EV_TELEMETRY_2022/Core/Inc/Data_Handling.hpp
PUT-Motorsport/PUTM_EV_TELEMETRY_2022
808ed3e7c9b4263b541a804233e5905f6a9b4240
[ "Apache-2.0" ]
1
2021-11-22T20:06:58.000Z
2021-11-22T20:06:58.000Z
#ifndef INC_DATA_HANDLING_HPP_ #define INC_DATA_HANDLING_HPP_ #include <stdlib.h> #include <cstring> #include "stdio.h" #include "main.h" enum struct HeartBeat { Buffer1, Buffer2, Buffer3, DEFAULT, FRAME_BY_FRAME }; class Data_management { private: // Buffers containing data and states. uint8_t DataBuffer1[32] = {0}; uint8_t DataBuffer2[32] = {0}; uint8_t DataBuffer3[32] = {0}; uint8_t StateBuffer1[10] = { 0 }; uint8_t StateBuffer2[10] = { 0 }; uint8_t StateBuffer3[10] = { 0 }; public: // flags used to track arriving frames. Each bit represent corresponding frame. uint8_t DataBuffer1_flag = 0; uint8_t DataBuffer2_flag = 0; uint8_t DataBuffer3_flag = 0; // Const values indicating full state of a buffer. const uint8_t Buffer1_full = 63; const uint8_t Buffer2_full = 3; const uint8_t Buffer3_full = 255; /* Methods */ void Init(); uint8_t * Check_Buffer1(); uint8_t * Check_Buffer2(); uint8_t * Check_Buffer3(); uint8_t * return_state1_pointer() {return StateBuffer1;} uint8_t * return_state2_pointer() {return StateBuffer2;} uint8_t * return_state3_pointer() {return StateBuffer3;} void Clear_msg1(); void Clear_msg2(); void Clear_msg3(); }; void Send_Frame(); void Cycle_frames(); #endif
19.246154
80
0.723421
PUT-Motorsport
40dc24da71519bd60392ec90b5ecbbd3cae32a58
121,192
cpp
C++
src/game/shared/choreoevent.cpp
Planimeter/hl2sb-src
8ffdae584f8e4837b7a1bd90286d199d934e4b7d
[ "MIT" ]
15
2016-04-07T21:29:55.000Z
2022-03-18T08:03:31.000Z
src/game/shared/choreoevent.cpp
Planimeter/hl2sb-src
8ffdae584f8e4837b7a1bd90286d199d934e4b7d
[ "MIT" ]
1
2021-12-05T23:46:21.000Z
2021-12-06T15:48:33.000Z
src/game/shared/choreoevent.cpp
Planimeter/hl2sb-src
8ffdae584f8e4837b7a1bd90286d199d934e4b7d
[ "MIT" ]
4
2020-10-02T00:28:21.000Z
2021-12-12T16:40:01.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "tier0/dbg.h" #include <stdio.h> #include <string.h> #include <ctype.h> #include "choreoevent.h" #include "choreoactor.h" #include "choreochannel.h" #include "minmax.h" #include "mathlib/mathlib.h" #include "tier1/strtools.h" #include "choreoscene.h" #include "ichoreoeventcallback.h" #include "tier1/utlbuffer.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" int CChoreoEvent::s_nGlobalID = 1; //----------------------------------------------------------------------------- // Purpose: // Input : *owner - // *name - // percentage - //----------------------------------------------------------------------------- CEventRelativeTag::CEventRelativeTag( CChoreoEvent *owner, const char *name, float percentage ) { Assert( owner ); Assert( name ); Assert( percentage >= 0.0f ); Assert( percentage <= 1.0f ); m_Name = name; m_flPercentage = percentage; m_pOwner = owner; } //----------------------------------------------------------------------------- // Purpose: // Input : src - //----------------------------------------------------------------------------- CEventRelativeTag::CEventRelativeTag( const CEventRelativeTag& src ) { m_Name = src.m_Name; m_flPercentage = src.m_flPercentage; m_pOwner = src.m_pOwner; } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CEventRelativeTag::GetName( void ) { return m_Name.Get(); } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CEventRelativeTag::GetPercentage( void ) { return m_flPercentage; } //----------------------------------------------------------------------------- // Purpose: // Input : percentage - //----------------------------------------------------------------------------- void CEventRelativeTag::SetPercentage( float percentage ) { m_flPercentage = percentage; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- CChoreoEvent *CEventRelativeTag::GetOwner( void ) { return m_pOwner; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventRelativeTag::SetOwner( CChoreoEvent *event ) { m_pOwner = event; } //----------------------------------------------------------------------------- // Purpose: Returns the corrected time based on the owner's length and start time // Output : float //----------------------------------------------------------------------------- float CEventRelativeTag::GetStartTime( void ) { Assert( m_pOwner ); if ( !m_pOwner ) { return 0.0f; } float ownerstart = m_pOwner->GetStartTime(); float ownerduration = m_pOwner->GetDuration(); return ( ownerstart + ownerduration * m_flPercentage ); } //----------------------------------------------------------------------------- // Purpose: // Input : *owner - // *name - // percentage - //----------------------------------------------------------------------------- CFlexTimingTag::CFlexTimingTag( CChoreoEvent *owner, const char *name, float percentage, bool locked ) : BaseClass( owner, name, percentage ) { m_bLocked = locked; } //----------------------------------------------------------------------------- // Purpose: // Input : src - //----------------------------------------------------------------------------- CFlexTimingTag::CFlexTimingTag( const CFlexTimingTag& src ) : BaseClass( src ) { m_bLocked = src.m_bLocked; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CFlexTimingTag::GetLocked( void ) { return m_bLocked; } //----------------------------------------------------------------------------- // Purpose: // Input : locked - //----------------------------------------------------------------------------- void CFlexTimingTag::SetLocked( bool locked ) { m_bLocked = locked; } //----------------------------------------------------------------------------- // Purpose: // Input : *owner - // *name - // percentage - //----------------------------------------------------------------------------- CEventAbsoluteTag::CEventAbsoluteTag( CChoreoEvent *owner, const char *name, float t ) { Assert( owner ); Assert( name ); Assert( t >= 0.0f ); m_Name = name; m_flPercentage = t; m_pOwner = owner; m_bLocked = false; m_bLinear = false; m_bEntry = false; m_bExit = false; } //----------------------------------------------------------------------------- // Purpose: // Input : src - //----------------------------------------------------------------------------- CEventAbsoluteTag::CEventAbsoluteTag( const CEventAbsoluteTag& src ) { m_Name = src.m_Name; m_flPercentage = src.m_flPercentage; m_pOwner = src.m_pOwner; m_bLocked = src.m_bLocked; m_bLinear = src.m_bLinear; m_bEntry = src.m_bEntry; m_bExit = src.m_bExit; } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CEventAbsoluteTag::GetName( void ) { return m_Name.Get(); } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CEventAbsoluteTag::GetPercentage( void ) { return m_flPercentage; } //----------------------------------------------------------------------------- // Purpose: // Input : percentage - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetPercentage( float percentage ) { m_flPercentage = percentage; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CEventAbsoluteTag::GetEventTime( void ) { Assert( m_pOwner ); if ( !m_pOwner ) { return 0.0f; } float ownerduration = m_pOwner->GetDuration(); return (m_flPercentage * ownerduration); } //----------------------------------------------------------------------------- // Purpose: // Input : percentage - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetEventTime( float t ) { Assert( m_pOwner ); if ( !m_pOwner ) { return; } float ownerduration = m_pOwner->GetDuration(); m_flPercentage = (t / ownerduration); } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CEventAbsoluteTag::GetAbsoluteTime( void ) { Assert( m_pOwner ); if ( !m_pOwner ) { return 0.0f; } float ownerstart = m_pOwner->GetStartTime(); float ownerduration = m_pOwner->GetDuration(); return (ownerstart + m_flPercentage * ownerduration); } //----------------------------------------------------------------------------- // Purpose: // Input : percentage - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetAbsoluteTime( float t ) { Assert( m_pOwner ); if ( !m_pOwner ) { return; } float ownerstart = m_pOwner->GetStartTime(); float ownerduration = m_pOwner->GetDuration(); m_flPercentage = (t - ownerstart) / ownerduration; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- CChoreoEvent *CEventAbsoluteTag::GetOwner( void ) { return m_pOwner; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetOwner( CChoreoEvent *event ) { m_pOwner = event; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetLocked( bool bLocked ) { m_bLocked = bLocked; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- bool CEventAbsoluteTag::GetLocked( void ) { return m_bLocked; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetLinear( bool bLinear ) { m_bLinear = bLinear; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- bool CEventAbsoluteTag::GetLinear( void ) { return m_bLinear; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetEntry( bool bEntry ) { m_bEntry = bEntry; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- bool CEventAbsoluteTag::GetEntry( void ) { return m_bEntry; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetExit( bool bExit ) { m_bExit = bExit; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- bool CEventAbsoluteTag::GetExit( void ) { return m_bExit; } // FLEX ANIMATIONS //----------------------------------------------------------------------------- // Purpose: Constructor // Input : *event - //----------------------------------------------------------------------------- CFlexAnimationTrack::CFlexAnimationTrack( CChoreoEvent *event ) { m_pEvent = event; m_pControllerName = NULL; m_bActive = false; m_bCombo = false; m_bServerSide = false; m_nFlexControllerIndex[ 0 ] = m_nFlexControllerIndex[ 1 ] = -1; m_nFlexControllerIndexRaw[ 0 ] = m_nFlexControllerIndexRaw[ 1 ] = LocalFlexController_t(-1); // base track has range, combo is always 0..1 m_flMin = 0.0f; m_flMax = 0.0f; } //----------------------------------------------------------------------------- // Purpose: // Input : src - //----------------------------------------------------------------------------- CFlexAnimationTrack::CFlexAnimationTrack( const CFlexAnimationTrack* src ) { m_pControllerName = NULL; SetFlexControllerName( src->m_pControllerName ? src->m_pControllerName : "" ); m_bActive = src->m_bActive; m_bCombo = src->m_bCombo; m_bServerSide = src->m_bServerSide; for ( int t = 0; t < 2; t++ ) { m_Samples[ t ].Purge(); for ( int i = 0 ;i < src->m_Samples[ t ].Size(); i++ ) { CExpressionSample s = src->m_Samples[ t ][ i ]; m_Samples[ t ].AddToTail( s ); } } for ( int side = 0; side < 2; side++ ) { m_nFlexControllerIndex[ side ] = src->m_nFlexControllerIndex[ side ]; m_nFlexControllerIndexRaw[ side ] = src->m_nFlexControllerIndexRaw[ side ]; } m_flMin = src->m_flMin; m_flMax = src->m_flMax; m_EdgeInfo[ 0 ] = src->m_EdgeInfo[ 0 ]; m_EdgeInfo[ 1 ] = src->m_EdgeInfo[ 1 ]; m_pEvent = NULL; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CFlexAnimationTrack::~CFlexAnimationTrack( void ) { delete[] m_pControllerName; for ( int t = 0; t < 2; t++ ) { m_Samples[ t ].Purge(); } } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetEvent( CChoreoEvent *event ) { m_pEvent = event; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFlexAnimationTrack::Clear( void ) { for ( int t = 0; t < 2; t++ ) { m_Samples[ t ].RemoveAll(); } } //----------------------------------------------------------------------------- // Purpose: // Input : index - //----------------------------------------------------------------------------- void CFlexAnimationTrack::RemoveSample( int index, int type /*=0*/ ) { Assert( type == 0 || type == 1 ); m_Samples[ type ].Remove( index ); } //----------------------------------------------------------------------------- // Purpose: // Input : *name - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetFlexControllerName( const char *name ) { delete[] m_pControllerName; int len = Q_strlen( name ) + 1; m_pControllerName = new char[ len ]; Q_strncpy( m_pControllerName, name, len ); } //----------------------------------------------------------------------------- // Purpose: // Output : char const //----------------------------------------------------------------------------- const char *CFlexAnimationTrack::GetFlexControllerName( void ) { return m_pControllerName ? m_pControllerName : ""; } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CFlexAnimationTrack::GetNumSamples( int type /*=0*/ ) { Assert( type == 0 || type == 1 ); return m_Samples[ type ].Size(); } //----------------------------------------------------------------------------- // Purpose: // Input : index - // Output : CExpressionSample //----------------------------------------------------------------------------- CExpressionSample *CFlexAnimationTrack::GetSample( int index, int type /*=0*/ ) { Assert( type == 0 || type == 1 ); if ( index < 0 || index >= GetNumSamples( type ) ) return NULL; return &m_Samples[ type ][ index ]; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CFlexAnimationTrack::IsTrackActive( void ) { return m_bActive; } //----------------------------------------------------------------------------- // Purpose: // Input : active - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetTrackActive( bool active ) { m_bActive = active; } void CFlexAnimationTrack::SetEdgeInfo( bool leftEdge, int curveType, float zero ) { int idx = leftEdge ? 0 : 1; m_EdgeInfo[ idx ].m_CurveType = curveType; m_EdgeInfo[ idx ].m_flZeroPos = zero; } void CFlexAnimationTrack::GetEdgeInfo( bool leftEdge, int& curveType, float& zero ) const { int idx = leftEdge ? 0 : 1; curveType = m_EdgeInfo[ idx ].m_CurveType; zero = m_EdgeInfo[ idx ].m_flZeroPos; } void CFlexAnimationTrack::SetEdgeActive( bool leftEdge, bool state ) { int idx = leftEdge ? 0 : 1; m_EdgeInfo[ idx ].m_bActive = state; } bool CFlexAnimationTrack::IsEdgeActive( bool leftEdge ) const { int idx = leftEdge ? 0 : 1; return m_EdgeInfo[ idx ].m_bActive; } int CFlexAnimationTrack::GetEdgeCurveType( bool leftEdge ) const { if ( !IsEdgeActive( leftEdge ) ) { return CURVE_DEFAULT; } int idx = leftEdge ? 0 : 1; return m_EdgeInfo[ idx ].m_CurveType; } float CFlexAnimationTrack::GetEdgeZeroValue( bool leftEdge ) const { if ( !IsEdgeActive( leftEdge ) ) { return 0.0f; } int idx = leftEdge ? 0 : 1; return m_EdgeInfo[ idx ].m_flZeroPos; } float CFlexAnimationTrack::GetDefaultEdgeZeroPos() const { float zero = 0.0f; if ( m_flMin != m_flMax ) { zero = ( 0.0f - m_flMin ) / ( m_flMax - m_flMin ); } return zero; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetZeroValue( int type, bool leftSide ) { // Stereo track is always clamped to 0.5 and doesn't care about l/r settings if ( type == 1 ) { return 0.5f; } if ( IsEdgeActive( leftSide ) ) { return GetEdgeZeroValue( leftSide ); } return GetDefaultEdgeZeroPos(); } //----------------------------------------------------------------------------- // Purpose: // Input : number - // Output : CExpressionSample //----------------------------------------------------------------------------- CExpressionSample *CFlexAnimationTrack::GetBoundedSample( int number, bool& bClamped, int type /*=0*/ ) { Assert( type == 0 || type == 1 ); if ( number < 0 ) { // Search for two samples which span time f static CExpressionSample nullstart; nullstart.time = 0.0f; nullstart.value = GetZeroValue( type, true ); if ( type == 0 ) { nullstart.SetCurveType( GetEdgeCurveType( true ) ); } else { nullstart.SetCurveType( CURVE_DEFAULT ); } bClamped = true; return &nullstart; } else if ( number >= GetNumSamples( type ) ) { static CExpressionSample nullend; nullend.time = m_pEvent->GetDuration(); nullend.value = GetZeroValue( type, false ); if ( type == 0 ) { nullend.SetCurveType( GetEdgeCurveType( false ) ); } else { nullend.SetCurveType( CURVE_DEFAULT ); } bClamped = true; return &nullend; } bClamped = false; return GetSample( number, type ); } //----------------------------------------------------------------------------- // Purpose: // Input : time - // type - // Output : float //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetIntensityInternal( float time, int type ) { Assert( type == 0 || type == 1 ); float retval = 0.0f; // find samples that span the time if ( !m_pEvent || !m_pEvent->HasEndTime() || time < m_pEvent->GetStartTime() ) { retval = GetZeroValue( type, true );; } else if ( time > m_pEvent->GetEndTime() ) { retval = GetZeroValue( type, false );; } else { float elapsed = time - m_pEvent->GetStartTime(); retval = GetFracIntensity( elapsed, type ); } // scale if (type == 0 && m_flMin != m_flMax) { retval = retval * (m_flMax - m_flMin) + m_flMin; } return retval; } //----------------------------------------------------------------------------- // Purpose: // Input : time - // type - // Output : float //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetFracIntensity( float time, int type ) { float zeroValueLeft = GetZeroValue( type, true ); Assert( type == 0 || type == 1 ); // find samples that span the time if ( !m_pEvent || !m_pEvent->HasEndTime() ) return zeroValueLeft; int rampCount = GetNumSamples( type ); if ( rampCount < 1 ) { return zeroValueLeft; } CExpressionSample *esStart = NULL; CExpressionSample *esEnd = NULL; // do binary search for sample in time period int j = MAX( rampCount / 2, 1 ); int i = j; while ( i > -2 && i < rampCount + 1 ) { bool dummy; esStart = GetBoundedSample( i, dummy, type ); esEnd = GetBoundedSample( i + 1, dummy, type ); j = MAX( j / 2, 1 ); if ( time < esStart->time) { i -= j; } else if ( time > esEnd->time) { i += j; } else { if ( time == esEnd->time ) { ++i; esStart = GetBoundedSample( i, dummy, type ); esEnd = GetBoundedSample( i + 1, dummy, type ); } break; } } if (!esStart) { return zeroValueLeft; } int prev = i - 1; int next = i + 2; prev = MAX( -1, prev ); next = MIN( next, rampCount ); bool bclamp[ 2 ]; CExpressionSample *esPre = GetBoundedSample( prev, bclamp[ 0 ], type ); CExpressionSample *esNext = GetBoundedSample( next, bclamp[ 1 ], type ); float dt = esEnd->time - esStart->time; Vector vPre( esPre->time, esPre->value, 0 ); Vector vStart( esStart->time, esStart->value, 0 ); Vector vEnd( esEnd->time, esEnd->value, 0 ); Vector vNext( esNext->time, esNext->value, 0 ); float f2 = 0.0f; if ( dt > 0.0f ) { f2 = ( time - esStart->time ) / ( dt ); } f2 = clamp( f2, 0.0f, 1.0f ); Vector vOut; int dummy; int earlypart, laterpart; // Not holding out value of previous curve... Interpolator_CurveInterpolatorsForType( esStart->GetCurveType(), dummy, earlypart ); Interpolator_CurveInterpolatorsForType( esEnd->GetCurveType(), laterpart, dummy ); if ( earlypart == INTERPOLATE_HOLD ) { // Hold "out" of previous sample (can cause a discontinuity) VectorLerp( vStart, vEnd, f2, vOut ); vOut.y = vStart.y; } else if ( laterpart == INTERPOLATE_HOLD ) { // Hold "out" of previous sample (can cause a discontinuity) VectorLerp( vStart, vEnd, f2, vOut ); vOut.y = vEnd.y; } else { bool sameCurveType = earlypart == laterpart ? true : false; if ( sameCurveType ) { Interpolator_CurveInterpolate( laterpart, vPre, vStart, vEnd, vNext, f2, vOut ); } else // curves differ, sigh { Vector vOut1, vOut2; Interpolator_CurveInterpolate( earlypart, vPre, vStart, vEnd, vNext, f2, vOut1 ); Interpolator_CurveInterpolate( laterpart, vPre, vStart, vEnd, vNext, f2, vOut2 ); VectorLerp( vOut1, vOut2, f2, vOut ); } } float retval = clamp( vOut.y, 0.0f, 1.0f ); return retval; } //----------------------------------------------------------------------------- // Purpose: // Input : time - // Output : float //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetSampleIntensity( float time ) { return GetIntensityInternal( time, 0 ); } //----------------------------------------------------------------------------- // Purpose: // Input : time - // Output : float //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetBalanceIntensity( float time ) { if ( IsComboType() ) { return GetIntensityInternal( time, 1 ); } return 1.0f; } // For a given time, computes 0->1 intensity value for the slider //----------------------------------------------------------------------------- // Purpose: // Input : time - // Output : float //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetIntensity( float time, int side ) { float mag = GetSampleIntensity( time ); float scale = 1.0f; if ( IsComboType() ) { float balance = GetBalanceIntensity( time ); // Asking for left but balance is to right, then fall off as we go // further right if ( side == 0 && balance > 0.5f ) { scale = (1.0f - balance ) / 0.5f; } // Asking for right, but balance is left, fall off as we go left. else if ( side == 1 && balance < 0.5f ) { scale = ( balance / 0.5f ); } } return mag * scale; } //----------------------------------------------------------------------------- // Purpose: // Input : time - // value - //----------------------------------------------------------------------------- CExpressionSample *CFlexAnimationTrack::AddSample( float time, float value, int type /*=0*/ ) { Assert( type == 0 || type == 1 ); CExpressionSample sample; sample.time = time; sample.value = value; sample.selected = false; int idx = m_Samples[ type ].AddToTail( sample ); // Resort( type ); return &m_Samples[ type ][ idx ]; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFlexAnimationTrack::Resort( int type /*=0*/ ) { Assert( type == 0 || type == 1 ); for ( int i = 0; i < m_Samples[ type ].Size(); i++ ) { for ( int j = i + 1; j < m_Samples[ type ].Size(); j++ ) { CExpressionSample src = m_Samples[ type ][ i ]; CExpressionSample dest = m_Samples[ type ][ j ]; if ( src.time > dest.time ) { m_Samples[ type ][ i ] = dest; m_Samples[ type ][ j ] = src; } } } // Make sure nothing is out of range RemoveOutOfRangeSamples( 0 ); RemoveOutOfRangeSamples( 1 ); } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- CChoreoEvent *CFlexAnimationTrack::GetEvent( void ) { return m_pEvent; } //----------------------------------------------------------------------------- // Purpose: // Input : side - // Output : int //----------------------------------------------------------------------------- int CFlexAnimationTrack::GetFlexControllerIndex( int side /*= 0*/ ) { Assert( side == 0 || side == 1 ); if ( IsComboType() ) { return m_nFlexControllerIndex[ side ]; } return m_nFlexControllerIndex[ 0 ]; } //----------------------------------------------------------------------------- // Purpose: // Input : side - // Output : int //----------------------------------------------------------------------------- LocalFlexController_t CFlexAnimationTrack::GetRawFlexControllerIndex( int side /*= 0*/ ) { Assert( side == 0 || side == 1 ); if ( IsComboType() ) { return m_nFlexControllerIndexRaw[ side ]; } return m_nFlexControllerIndexRaw[ 0 ]; } //----------------------------------------------------------------------------- // Purpose: // Input : index - // side - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetFlexControllerIndex( LocalFlexController_t raw, int index, int side /*= 0*/ ) { Assert( side == 0 || side == 1 ); m_nFlexControllerIndex[ side ] = index; // Model specific m_nFlexControllerIndexRaw[ side ] = raw; } //----------------------------------------------------------------------------- // Purpose: // Input : combo - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetComboType( bool combo ) { m_bCombo = combo; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CFlexAnimationTrack::IsComboType( void ) { return m_bCombo; } //----------------------------------------------------------------------------- // Purpose: True if this should be simulated on the server side always // Input : state - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetServerSide( bool state ) { m_bServerSide = state; } //----------------------------------------------------------------------------- // Purpose: // Input : - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CFlexAnimationTrack::IsServerSide() const { return m_bServerSide; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetMin( float value ) { m_flMin = value; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetMax( float value ) { m_flMax = value; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetMin( int type ) { if (type == 0) return m_flMin; else return 0.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetMax( int type ) { if (type == 0) return m_flMax; else return 1.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CFlexAnimationTrack::IsInverted( void ) { if (m_bInverted) return true; return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetInverted( bool isInverted ) { m_bInverted = isInverted; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- void CFlexAnimationTrack::RemoveOutOfRangeSamples( int type ) { Assert( m_pEvent ); if ( !m_pEvent ) return; Assert( m_pEvent->HasEndTime() ); float duration = m_pEvent->GetDuration(); int c = m_Samples[ type ].Size(); for ( int i = c-1; i >= 0; i-- ) { CExpressionSample src = m_Samples[ type ][ i ]; if ( src.time < 0 || src.time > duration ) { m_Samples[ type ].Remove( i ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CChoreoEvent::CChoreoEvent( CChoreoScene *scene ) { Init( scene ); } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *name - //----------------------------------------------------------------------------- CChoreoEvent::CChoreoEvent( CChoreoScene *scene, EVENTTYPE type, const char *name ) { Init( scene ); SetType( type ); SetName( name ); } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *name - // *param - //----------------------------------------------------------------------------- CChoreoEvent::CChoreoEvent( CChoreoScene *scene, EVENTTYPE type, const char *name, const char *param ) { Init( scene ); SetType( type ); SetName( name ); SetParameters( param ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CChoreoEvent::~CChoreoEvent( void ) { RemoveAllTracks(); ClearEventDependencies(); delete m_pSubScene; } //----------------------------------------------------------------------------- // Purpose: Assignment // Input : src - // Output : CChoreoEvent& //----------------------------------------------------------------------------- CChoreoEvent& CChoreoEvent::operator=( const CChoreoEvent& src ) { MEM_ALLOC_CREDIT(); // Copy global id when copying entity m_nGlobalID = src.m_nGlobalID; m_pActor = NULL; m_pChannel = NULL; m_nDefaultCurveType = src.m_nDefaultCurveType; m_fType = src.m_fType; m_Name = src.m_Name; m_Parameters = src.m_Parameters; m_Parameters2= src.m_Parameters2; m_Parameters3= src.m_Parameters3; m_flStartTime = src.m_flStartTime; m_flEndTime = src.m_flEndTime; m_bFixedLength = src.m_bFixedLength; m_flGestureSequenceDuration = src.m_flGestureSequenceDuration; m_bResumeCondition = src.m_bResumeCondition; m_bLockBodyFacing = src.m_bLockBodyFacing; m_flDistanceToTarget = src.m_flDistanceToTarget; m_bForceShortMovement = src.m_bForceShortMovement; m_bSyncToFollowingGesture = src.m_bSyncToFollowingGesture; m_bPlayOverScript = src.m_bPlayOverScript; m_bUsesTag = src.m_bUsesTag; m_TagName = src.m_TagName; m_TagWavName = src.m_TagWavName; ClearAllRelativeTags(); ClearAllTimingTags(); int t; for ( t = 0; t < NUM_ABS_TAG_TYPES; t++ ) { ClearAllAbsoluteTags( (AbsTagType)t ); } int i; for ( i = 0; i < src.m_RelativeTags.Size(); i++ ) { CEventRelativeTag newtag( src.m_RelativeTags[ i ] ); newtag.SetOwner( this ); m_RelativeTags.AddToTail( newtag ); } for ( i = 0; i < src.m_TimingTags.Size(); i++ ) { CFlexTimingTag newtag( src.m_TimingTags[ i ] ); newtag.SetOwner( this ); m_TimingTags.AddToTail( newtag ); } for ( t = 0; t < NUM_ABS_TAG_TYPES; t++ ) { for ( i = 0; i < src.m_AbsoluteTags[ t ].Size(); i++ ) { CEventAbsoluteTag newtag( src.m_AbsoluteTags[ t ][ i ] ); newtag.SetOwner( this ); m_AbsoluteTags[ t ].AddToTail( newtag ); } } RemoveAllTracks(); for ( i = 0 ; i < src.m_FlexAnimationTracks.Size(); i++ ) { CFlexAnimationTrack *newtrack = new CFlexAnimationTrack( src.m_FlexAnimationTracks[ i ] ); newtrack->SetEvent( this ); m_FlexAnimationTracks.AddToTail( newtrack ); } m_bTrackLookupSet = src.m_bTrackLookupSet; // FIXME: Use a safe handle? //m_pSubScene = src.m_pSubScene; m_bProcessing = src.m_bProcessing; m_pMixer = src.m_pMixer; m_pScene = src.m_pScene; m_nPitch = src.m_nPitch; m_nYaw = src.m_nYaw; m_nNumLoops = src.m_nNumLoops; m_nLoopsRemaining = src.m_nLoopsRemaining; // Copy ramp over m_Ramp = src.m_Ramp; m_ccType = src.m_ccType; m_CCToken = src.m_CCToken; m_bUsingCombinedSoundFile = src.m_bUsingCombinedSoundFile; m_uRequiredCombinedChecksum = src.m_uRequiredCombinedChecksum; m_nNumSlaves = src.m_nNumSlaves; m_flLastSlaveEndTime = src.m_flLastSlaveEndTime; m_bCCTokenValid = src.m_bCCTokenValid; m_bCombinedUsingGenderToken = src.m_bCombinedUsingGenderToken; m_bSuppressCaptionAttenuation = src.m_bSuppressCaptionAttenuation; m_bActive = src.m_bActive; return *this; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::Init( CChoreoScene *scene ) { m_nGlobalID = s_nGlobalID++; m_nDefaultCurveType = CURVE_CATMULL_ROM_TO_CATMULL_ROM; m_fType = UNSPECIFIED; m_Name.Set(""); m_Parameters.Set(""); m_Parameters2.Set(""); m_Parameters3.Set(""); m_flStartTime = 0.0f; m_flEndTime = -1.0f; m_pActor = NULL; m_pChannel = NULL; m_pScene = scene; m_bFixedLength = false; m_bResumeCondition = false; SetUsingRelativeTag( false, 0, 0 ); m_bTrackLookupSet = false; m_bLockBodyFacing = false; m_flDistanceToTarget = 0.0f; m_bForceShortMovement = false; m_bSyncToFollowingGesture = false; m_bPlayOverScript = false; m_pSubScene = NULL; m_bProcessing = false; m_pMixer = NULL; m_flGestureSequenceDuration = 0.0f; m_nPitch = m_nYaw = 0; m_nNumLoops = -1; m_nLoopsRemaining = 0; // Close captioning/localization support m_CCToken.Set(""); m_ccType = CC_MASTER; m_bUsingCombinedSoundFile = false; m_uRequiredCombinedChecksum = 0; m_nNumSlaves = 0; m_flLastSlaveEndTime = 0.0f; m_bCCTokenValid = false; m_bCombinedUsingGenderToken = false; m_bSuppressCaptionAttenuation = false; m_bActive = true; } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- CChoreoEvent::EVENTTYPE CChoreoEvent::GetType( void ) { return (EVENTTYPE)m_fType; } //----------------------------------------------------------------------------- // Purpose: // Input : type - //----------------------------------------------------------------------------- void CChoreoEvent::SetType( EVENTTYPE type ) { m_fType = type; if ( m_fType == SPEAK || m_fType == SUBSCENE ) { m_bFixedLength = true; } else { m_bFixedLength = false; } } //----------------------------------------------------------------------------- // Purpose: // Input : *name - //----------------------------------------------------------------------------- void CChoreoEvent::SetName( const char *name ) { m_Name = name; } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetName( void ) { return m_Name.Get(); } //----------------------------------------------------------------------------- // Purpose: // Input : *param - //----------------------------------------------------------------------------- void CChoreoEvent::SetParameters( const char *param ) { m_Parameters = param; } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetParameters( void ) { return m_Parameters.Get(); } //----------------------------------------------------------------------------- // Purpose: // Input : *param - //----------------------------------------------------------------------------- void CChoreoEvent::SetParameters2( const char *param ) { int iLength = Q_strlen( param ); m_Parameters2 = param; // HACK: Remove trailing " " until faceposer is fixed if ( iLength > 0 ) { if ( param[iLength-1] == ' ' ) { char tmp[1024]; Q_strncpy( tmp, param, sizeof(tmp) ); tmp[iLength-1] = 0; m_Parameters2.Set(tmp); } } } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetParameters2( void ) { return m_Parameters2.Get(); } //----------------------------------------------------------------------------- // Purpose: // Input : *param - //----------------------------------------------------------------------------- void CChoreoEvent::SetParameters3( const char *param ) { int iLength = Q_strlen( param ); m_Parameters3 = param; // HACK: Remove trailing " " until faceposer is fixed if ( iLength > 0 ) { if ( param[iLength-1] == ' ' ) { char tmp[1024]; Q_strncpy( tmp, param, sizeof(tmp) ); tmp[iLength-1] = 0; m_Parameters3.Set(tmp); } } } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetParameters3( void ) { return m_Parameters3.Get(); } //----------------------------------------------------------------------------- // Purpose: debugging description // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetDescription( void ) { static char description[ 256 ]; description[ 0 ] = 0; if ( !GetActor() ) { Q_snprintf( description,sizeof(description), "global %s", m_Name.Get() ); } else { Assert( m_pChannel ); Q_snprintf( description,sizeof(description), "%s : %s : %s -- %s \"%s\"", m_pActor->GetName(), m_pChannel->GetName(), GetName(), NameForType( GetType() ), GetParameters() ); if ( GetType() == EXPRESSION ) { char sz[ 256 ]; Q_snprintf( sz,sizeof(sz), " \"%s\"", GetParameters2() ); Q_strncat( description, sz, sizeof(description), COPY_ALL_CHARACTERS ); } } return description; } //----------------------------------------------------------------------------- // Purpose: // Input : starttime - //----------------------------------------------------------------------------- void CChoreoEvent::SetStartTime( float starttime ) { m_flStartTime = starttime; if ( m_flEndTime != -1.0f ) { if ( m_flEndTime < m_flStartTime ) { m_flEndTime = m_flStartTime; } } } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetStartTime( ) { return m_flStartTime; } //----------------------------------------------------------------------------- // Purpose: // Input : endtime - //----------------------------------------------------------------------------- void CChoreoEvent::SetEndTime( float endtime ) { bool changed = m_flEndTime != endtime; m_flEndTime = endtime; if ( endtime != -1.0f ) { if ( m_flEndTime < m_flStartTime ) { m_flEndTime = m_flStartTime; } if ( changed ) { OnEndTimeChanged(); } } } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetEndTime( ) { return m_flEndTime; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::HasEndTime( void ) { return m_flEndTime != -1.0f ? true : false; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetCompletion( float time ) { float t = (time - GetStartTime()) / (GetEndTime() - GetStartTime()); if (t < 0.0f) return 0.0f; else if (t > 1.0f) return 1.0f; return t; } // ICurveDataAccessor method bool CChoreoEvent::CurveHasEndTime() { return HasEndTime(); } //----------------------------------------------------------------------------- // Default curve type //----------------------------------------------------------------------------- void CChoreoEvent::SetDefaultCurveType( int nCurveType ) { m_nDefaultCurveType = nCurveType; } int CChoreoEvent::GetDefaultCurveType() { return m_nDefaultCurveType; } float CCurveData::GetIntensity( ICurveDataAccessor *data, float time ) { float zeroValue = 0.0f; // find samples that span the time if ( !data->CurveHasEndTime() ) { return zeroValue; } int rampCount = GetCount(); if ( rampCount < 1 ) { // Full intensity return 1.0f; } CExpressionSample *esStart = NULL; CExpressionSample *esEnd = NULL; // do binary search for sample in time period int j = MAX( rampCount / 2, 1 ); int i = j; while ( i > -2 && i < rampCount + 1 ) { bool dummy; esStart = GetBoundedSample( data, i, dummy ); esEnd = GetBoundedSample( data, i + 1, dummy ); j = MAX( j / 2, 1 ); if ( time < esStart->time) { i -= j; } else if ( time > esEnd->time) { i += j; } else { break; } } if (!esStart) { return 1.0f; } int prev = i - 1; int next = i + 2; prev = MAX( -1, prev ); next = MIN( next, rampCount ); bool bclamp[ 2 ]; CExpressionSample *esPre = GetBoundedSample( data, prev, bclamp[ 0 ] ); CExpressionSample *esNext = GetBoundedSample( data, next, bclamp[ 1 ] ); float dt = esEnd->time - esStart->time; Vector vPre( esPre->time, esPre->value, 0 ); Vector vStart( esStart->time, esStart->value, 0 ); Vector vEnd( esEnd->time, esEnd->value, 0 ); Vector vNext( esNext->time, esNext->value, 0 ); if ( bclamp[ 0 ] ) { vPre.x = vStart.x; } if ( bclamp[ 1 ] ) { vNext.x = vEnd.x; } float f2 = 0.0f; if ( dt > 0.0f ) { f2 = ( time - esStart->time ) / ( dt ); } f2 = clamp( f2, 0.0f, 1.0f ); Vector vOut; int dummy; int earlypart, laterpart; int startCurve = esStart->GetCurveType(); int endCurve = esEnd->GetCurveType(); if ( startCurve == CURVE_DEFAULT ) { startCurve = data->GetDefaultCurveType(); } if ( endCurve == CURVE_DEFAULT ) { endCurve = data->GetDefaultCurveType(); } // Not holding out value of previous curve... Interpolator_CurveInterpolatorsForType( startCurve, dummy, earlypart ); Interpolator_CurveInterpolatorsForType( endCurve, laterpart, dummy ); if ( earlypart == INTERPOLATE_HOLD ) { // Hold "out" of previous sample (can cause a discontinuity) VectorLerp( vStart, vEnd, f2, vOut ); vOut.y = vStart.y; } else if ( laterpart == INTERPOLATE_HOLD ) { // Hold "out" of previous sample (can cause a discontinuity) VectorLerp( vStart, vEnd, f2, vOut ); vOut.y = vEnd.y; } else { bool sameCurveType = earlypart == laterpart ? true : false; if ( sameCurveType ) { Interpolator_CurveInterpolate( laterpart, vPre, vStart, vEnd, vNext, f2, vOut ); } else // curves differ, sigh { Vector vOut1, vOut2; Interpolator_CurveInterpolate( earlypart, vPre, vStart, vEnd, vNext, f2, vOut1 ); Interpolator_CurveInterpolate( laterpart, vPre, vStart, vEnd, vNext, f2, vOut2 ); VectorLerp( vOut1, vOut2, f2, vOut ); } } float retval = clamp( vOut.y, 0.0f, 1.0f ); return retval; } //----------------------------------------------------------------------------- // Purpose: Get intensity for event, bounded by scene global intensity // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetIntensity( float scenetime ) { float global_intensity = 1.0f; if ( m_pScene ) { global_intensity = m_pScene->GetSceneRampIntensity( scenetime ); } else { Assert( 0 ); } float event_intensity = _GetIntensity( scenetime ); return global_intensity * event_intensity; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::_GetIntensity( float scenetime ) { // Convert to event local time float time = scenetime - GetStartTime(); return m_Ramp.GetIntensity( this, time ); } float CChoreoEvent::GetIntensityArea( float scenetime ) { // Convert to event local time float time = scenetime - GetStartTime(); return m_Ramp.GetIntensityArea( this, time ); } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CCurveData::GetIntensityArea( ICurveDataAccessor *data, float time ) { float zeroValue = 0.0f; // find samples that span the time if ( !data->CurveHasEndTime() ) { return zeroValue; } int rampCount = GetCount(); if ( rampCount < 1 ) { // Full intensity return 1.0f; } CExpressionSample *esStart = NULL; CExpressionSample *esEnd = NULL; // do binary search for sample in time period int j = MAX( rampCount / 2, 1 ); int i = j; while ( i > -2 && i < rampCount + 1 ) { bool dummy; esStart = GetBoundedSample( data, i, dummy ); esEnd = GetBoundedSample( data, i + 1, dummy ); j = MAX( j / 2, 1 ); if ( time < esStart->time) { i -= j; } else if ( time > esEnd->time) { i += j; } else { break; } } UpdateIntensityArea( data ); float flTotal = 0.0f; flTotal = m_RampAccumulator[i+1]; int prev = i - 1; int next = i + 2; prev = MAX( -1, prev ); next = MIN( next, rampCount ); bool bclamp[ 2 ]; CExpressionSample *esPre = GetBoundedSample( data, prev, bclamp[ 0 ] ); CExpressionSample *esNext = GetBoundedSample( data, next, bclamp[ 1 ] ); float dt = esEnd->time - esStart->time; Vector vPre( esPre->time, esPre->value, 0 ); Vector vStart( esStart->time, esStart->value, 0 ); Vector vEnd( esEnd->time, esEnd->value, 0 ); Vector vNext( esNext->time, esNext->value, 0 ); if ( bclamp[ 0 ] ) { vPre.x = vStart.x; } if ( bclamp[ 1 ] ) { vNext.x = vEnd.x; } float f2 = 0.0f; if ( dt > 0.0f ) { f2 = ( time - esStart->time ) / ( dt ); } f2 = clamp( f2, 0.0f, 1.0f ); Vector vOut; int dummy; int earlypart, laterpart; int startCurve = esStart->GetCurveType(); int endCurve = esEnd->GetCurveType(); if ( startCurve == CURVE_DEFAULT ) { startCurve = data->GetDefaultCurveType(); } if ( endCurve == CURVE_DEFAULT ) { endCurve = data->GetDefaultCurveType(); } // Not holding out value of previous curve... Interpolator_CurveInterpolatorsForType( startCurve, dummy, earlypart ); Interpolator_CurveInterpolatorsForType( endCurve, laterpart, dummy ); // FIXME: needs other curve types Catmull_Rom_Spline_Integral_Normalize( vPre, vStart, vEnd, vNext, f2, vOut ); // Con_Printf( "Accum %f : Partial %f\n", flTotal, vOut.y * (vEnd.x - vStart.x) * f2 ); flTotal = flTotal + clamp( vOut.y, 0.0f, 1.0f ) * (vEnd.x - vStart.x); return flTotal; } void CCurveData::UpdateIntensityArea( ICurveDataAccessor *data ) { int rampCount = GetCount();; if ( rampCount < 1 ) { return; } if (m_RampAccumulator.Count() == rampCount + 2) { return; } m_RampAccumulator.SetCount( rampCount + 2 ); int i = -1; bool dummy; CExpressionSample *esPre = GetBoundedSample( data, i - 1, dummy ); CExpressionSample *esStart = GetBoundedSample( data, i, dummy ); CExpressionSample *esEnd = GetBoundedSample( data, MIN( i + 1, rampCount ), dummy ); Vector vPre( esPre->time, esPre->value, 0 ); Vector vStart( esStart->time, esStart->value, 0 ); Vector vEnd( esEnd->time, esEnd->value, 0 ); Vector vOut; for (i = -1; i < rampCount; i++) { CExpressionSample *esNext = GetBoundedSample( data, MIN( i + 2, rampCount ), dummy ); Vector vNext( esNext->time, esNext->value, 0 ); Catmull_Rom_Spline_Integral_Normalize( vPre, vStart, vEnd, vNext, 1.0f, vOut ); m_RampAccumulator[i+1] = clamp( vOut.y, 0.0f, 1.0f ) * (vEnd.x - vStart.x); vPre = vStart; vStart = vEnd; vEnd = vNext; } } //----------------------------------------------------------------------------- // Purpose: // Input : dt - //----------------------------------------------------------------------------- void CChoreoEvent::OffsetStartTime( float dt ) { SetStartTime( GetStartTime() + dt ); } //----------------------------------------------------------------------------- // Purpose: // Input : dt - //----------------------------------------------------------------------------- void CChoreoEvent::OffsetEndTime( float dt ) { if ( HasEndTime() ) { SetEndTime( GetEndTime() + dt ); } } //----------------------------------------------------------------------------- // Purpose: // Input : dt - //----------------------------------------------------------------------------- void CChoreoEvent::OffsetTime( float dt ) { if ( HasEndTime() ) { m_flEndTime += dt; } m_flStartTime += dt; } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - //----------------------------------------------------------------------------- void CChoreoEvent::SetActor( CChoreoActor *actor ) { m_pActor = actor; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoActor //----------------------------------------------------------------------------- CChoreoActor *CChoreoEvent::GetActor( void ) { return m_pActor; } //----------------------------------------------------------------------------- // Purpose: // Input : *channel - //----------------------------------------------------------------------------- void CChoreoEvent::SetChannel( CChoreoChannel *channel ) { m_pChannel = channel; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoChannel //----------------------------------------------------------------------------- CChoreoChannel *CChoreoEvent::GetChannel( void ) { return m_pChannel; } //----------------------------------------------------------------------------- // Purpose: // Input : *scene - //----------------------------------------------------------------------------- void CChoreoEvent::SetSubScene( CChoreoScene *scene ) { m_pSubScene = scene; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoScene //----------------------------------------------------------------------------- CChoreoScene *CChoreoEvent::GetSubScene( void ) { return m_pSubScene; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- struct EventNameMap_t { CChoreoEvent::EVENTTYPE type; char const *name; }; static EventNameMap_t g_NameMap[] = { { CChoreoEvent::UNSPECIFIED, "unspecified" }, // error condition!!! { CChoreoEvent::SECTION, "section" }, { CChoreoEvent::EXPRESSION, "expression" }, { CChoreoEvent::LOOKAT, "lookat" }, { CChoreoEvent::MOVETO, "moveto" }, { CChoreoEvent::SPEAK, "speak" }, { CChoreoEvent::GESTURE, "gesture" }, { CChoreoEvent::SEQUENCE, "sequence" }, { CChoreoEvent::FACE, "face" }, { CChoreoEvent::FIRETRIGGER, "firetrigger" }, { CChoreoEvent::FLEXANIMATION, "flexanimation" }, { CChoreoEvent::SUBSCENE, "subscene" }, { CChoreoEvent::LOOP, "loop" }, { CChoreoEvent::INTERRUPT, "interrupt" }, { CChoreoEvent::STOPPOINT, "stoppoint" }, { CChoreoEvent::PERMIT_RESPONSES, "permitresponses" }, { CChoreoEvent::GENERIC, "generic" }, }; //----------------------------------------------------------------------------- // Purpose: A simple class to verify the names data above at runtime //----------------------------------------------------------------------------- class CCheckEventNames { public: CCheckEventNames() { if ( ARRAYSIZE( g_NameMap ) != CChoreoEvent::NUM_TYPES ) { Error( "g_NameMap contains %llu entries, CChoreoEvent::NUM_TYPES == %i!", (uint64)(ARRAYSIZE( g_NameMap )), CChoreoEvent::NUM_TYPES ); } for ( int i = 0; i < CChoreoEvent::NUM_TYPES; ++i ) { if ( !g_NameMap[ i ].name ) { Error( "g_NameMap: Event type at %i has NULL name string!", i ); } if ( (CChoreoEvent::EVENTTYPE)(i) == g_NameMap[ i ].type ) continue; Error( "g_NameMap: Event type at %i has wrong value (%i)!", i, (int)g_NameMap[ i ].type ); } } }; static CCheckEventNames g_CheckNamesSingleton; //----------------------------------------------------------------------------- // Purpose: // Input : *name - // Output : int //----------------------------------------------------------------------------- CChoreoEvent::EVENTTYPE CChoreoEvent::TypeForName( const char *name ) { for ( int i = 0; i < NUM_TYPES; ++i ) { EventNameMap_t *slot = &g_NameMap[ i ]; if ( !Q_stricmp( name, slot->name ) ) return slot->type; } Assert( !"CChoreoEvent::TypeForName failed!!!" ); return UNSPECIFIED; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::NameForType( EVENTTYPE type ) { int i = (int)type; if ( i < 0 || i >= NUM_TYPES ) { Assert( "!CChoreoEvent::NameForType: bogus type!" ); // returns "unspecified!!!"; return g_NameMap[ 0 ].name; } return g_NameMap[ i ].name; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- struct CCNameMap_t { CChoreoEvent::CLOSECAPTION type; char const *name; }; static CCNameMap_t g_CCNameMap[] = { { CChoreoEvent::CC_MASTER, "cc_master" }, // error condition!!! { CChoreoEvent::CC_SLAVE, "cc_slave" }, { CChoreoEvent::CC_DISABLED, "cc_disabled" }, }; //----------------------------------------------------------------------------- // Purpose: A simple class to verify the names data above at runtime //----------------------------------------------------------------------------- class CCheckCCNames { public: CCheckCCNames() { if ( ARRAYSIZE( g_CCNameMap ) != CChoreoEvent::NUM_CC_TYPES ) { Error( "g_CCNameMap contains %llu entries, CChoreoEvent::NUM_CC_TYPES == %i!", (uint64)(ARRAYSIZE( g_CCNameMap )), CChoreoEvent::NUM_CC_TYPES ); } for ( int i = 0; i < CChoreoEvent::NUM_CC_TYPES; ++i ) { if ( !g_CCNameMap[ i ].name ) { Error( "g_NameMap: CC type at %i has NULL name string!", i ); } if ( (CChoreoEvent::CLOSECAPTION)(i) == g_CCNameMap[ i ].type ) continue; Error( "g_CCNameMap: Event type at %i has wrong value (%i)!", i, (int)g_CCNameMap[ i ].type ); } } }; static CCheckCCNames g_CheckCCNamesSingleton; //----------------------------------------------------------------------------- // Purpose: // Input : *name - // Output : CLOSECAPTION //----------------------------------------------------------------------------- CChoreoEvent::CLOSECAPTION CChoreoEvent::CCTypeForName( const char *name ) { for ( int i = 0; i < NUM_CC_TYPES; ++i ) { CCNameMap_t *slot = &g_CCNameMap[ i ]; if ( !Q_stricmp( name, slot->name ) ) return slot->type; } Assert( !"CChoreoEvent::TypeForName failed!!!" ); return CC_MASTER; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::NameForCCType( CLOSECAPTION type ) { int i = (int)type; if ( i < 0 || i >= NUM_CC_TYPES ) { Assert( "!CChoreoEvent::NameForType: bogus type!" ); // returns "unspecified!!!"; return g_CCNameMap[ 0 ].name; } return g_CCNameMap[ i ].name; } //----------------------------------------------------------------------------- // Purpose: Is the event something that can be sized ( a wave file, e.g. ) // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::IsFixedLength( void ) { return m_bFixedLength; } //----------------------------------------------------------------------------- // Purpose: // Input : isfixedlength - //----------------------------------------------------------------------------- void CChoreoEvent::SetFixedLength( bool isfixedlength ) { m_bFixedLength = isfixedlength; } //----------------------------------------------------------------------------- // Purpose: // Input : resumecondition - //----------------------------------------------------------------------------- void CChoreoEvent::SetResumeCondition( bool resumecondition ) { m_bResumeCondition = resumecondition; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::IsResumeCondition( void ) { return m_bResumeCondition; } //----------------------------------------------------------------------------- // Purpose: // Input : lockbodyfacing - //----------------------------------------------------------------------------- void CChoreoEvent::SetLockBodyFacing( bool lockbodyfacing ) { m_bLockBodyFacing = lockbodyfacing; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::IsLockBodyFacing( void ) { return m_bLockBodyFacing; } //----------------------------------------------------------------------------- // Purpose: // Input : distancetotarget - //----------------------------------------------------------------------------- void CChoreoEvent::SetDistanceToTarget( float distancetotarget ) { m_flDistanceToTarget = distancetotarget; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns ideal distance to target //----------------------------------------------------------------------------- float CChoreoEvent::GetDistanceToTarget( void ) { return m_flDistanceToTarget; } //----------------------------------------------------------------------------- // Purpose: // Input : set if small (sub-1/2 bbox) movements are forced //----------------------------------------------------------------------------- void CChoreoEvent::SetForceShortMovement( bool bForceShortMovement ) { m_bForceShortMovement = bForceShortMovement; } //----------------------------------------------------------------------------- // Purpose: // Output : get if small (sub-1/2 bbox) movements are forced //----------------------------------------------------------------------------- bool CChoreoEvent::GetForceShortMovement( void ) { return m_bForceShortMovement; } //----------------------------------------------------------------------------- // Purpose: // Input : set if the gesture should sync its exit tag with the following gestures entry tag //----------------------------------------------------------------------------- void CChoreoEvent::SetSyncToFollowingGesture( bool bSyncToFollowingGesture ) { m_bSyncToFollowingGesture = bSyncToFollowingGesture; } //----------------------------------------------------------------------------- // Purpose: // Output : get if the gesture should sync its exit tag with the following gestures entry tag //----------------------------------------------------------------------------- bool CChoreoEvent::GetSyncToFollowingGesture( void ) { return m_bSyncToFollowingGesture; } //----------------------------------------------------------------------------- // Purpose: // Input : set if the sequence should player overtop of an underlying SS //----------------------------------------------------------------------------- void CChoreoEvent::SetPlayOverScript( bool bPlayOverScript ) { m_bPlayOverScript = bPlayOverScript; } //----------------------------------------------------------------------------- // Purpose: // Output : get if the sequence should player overtop of an underlying SS //----------------------------------------------------------------------------- bool CChoreoEvent::GetPlayOverScript( void ) { return m_bPlayOverScript; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetDuration( void ) { if ( HasEndTime() ) { return GetEndTime() - GetStartTime(); } return 0.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::ClearAllRelativeTags( void ) { m_RelativeTags.Purge(); } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetNumRelativeTags( void ) { return m_RelativeTags.Size(); } //----------------------------------------------------------------------------- // Purpose: // Input : tagnum - // Output : CEventRelativeTag //----------------------------------------------------------------------------- CEventRelativeTag *CChoreoEvent::GetRelativeTag( int tagnum ) { Assert( tagnum >= 0 && tagnum < m_RelativeTags.Size() ); return &m_RelativeTags[ tagnum ]; } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - // percentage - //----------------------------------------------------------------------------- void CChoreoEvent::AddRelativeTag( const char *tagname, float percentage ) { CEventRelativeTag rt( this, tagname, percentage ); m_RelativeTags.AddToTail( rt ); } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - //----------------------------------------------------------------------------- void CChoreoEvent::RemoveRelativeTag( const char *tagname ) { for ( int i = 0; i < m_RelativeTags.Size(); i++ ) { CEventRelativeTag *prt = &m_RelativeTags[ i ]; if ( !prt ) continue; if ( !stricmp( prt->GetName(), tagname ) ) { m_RelativeTags.Remove( i ); return; } } } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - // Output : CEventRelativeTag * //----------------------------------------------------------------------------- CEventRelativeTag * CChoreoEvent::FindRelativeTag( const char *tagname ) { for ( int i = 0; i < m_RelativeTags.Size(); i++ ) { CEventRelativeTag *prt = &m_RelativeTags[ i ]; if ( !prt ) continue; if ( !stricmp( prt->GetName(), tagname ) ) { return prt; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::IsUsingRelativeTag( void ) { return m_bUsesTag; } //----------------------------------------------------------------------------- // Purpose: // Input : usetag - // 0 - //----------------------------------------------------------------------------- void CChoreoEvent::SetUsingRelativeTag( bool usetag, const char *tagname /*= 0*/, const char *wavname /* = 0 */ ) { m_bUsesTag = usetag; if ( tagname ) { m_TagName = tagname; } else { m_TagName.Set(""); } if ( wavname ) { m_TagWavName = wavname; } else { m_TagWavName.Set(""); } } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetRelativeTagName( void ) { return m_TagName.Get(); } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetRelativeWavName( void ) { return m_TagWavName.Get(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::ClearAllTimingTags( void ) { m_TimingTags.Purge(); } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetNumTimingTags( void ) { return m_TimingTags.Size(); } //----------------------------------------------------------------------------- // Purpose: // Input : tagnum - // Output : CEventRelativeTag //----------------------------------------------------------------------------- CFlexTimingTag *CChoreoEvent::GetTimingTag( int tagnum ) { Assert( tagnum >= 0 && tagnum < m_TimingTags.Size() ); return &m_TimingTags[ tagnum ]; } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - // percentage - //----------------------------------------------------------------------------- void CChoreoEvent::AddTimingTag( const char *tagname, float percentage, bool locked ) { CFlexTimingTag tt( this, tagname, percentage, locked ); m_TimingTags.AddToTail( tt ); // Sort tags CFlexTimingTag temp( (CChoreoEvent *)0x1, "", 0.0f, false ); // ugly bubble sort for ( int i = 0; i < m_TimingTags.Size(); i++ ) { for ( int j = i + 1; j < m_TimingTags.Size(); j++ ) { CFlexTimingTag *t1 = &m_TimingTags[ i ]; CFlexTimingTag *t2 = &m_TimingTags[ j ]; if ( t1->GetPercentage() > t2->GetPercentage() ) { temp = *t1; *t1 = *t2; *t2 = temp; } } } } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - //----------------------------------------------------------------------------- void CChoreoEvent::RemoveTimingTag( const char *tagname ) { for ( int i = 0; i < m_TimingTags.Size(); i++ ) { CFlexTimingTag *ptt = &m_TimingTags[ i ]; if ( !ptt ) continue; if ( !stricmp( ptt->GetName(), tagname ) ) { m_TimingTags.Remove( i ); return; } } } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - // Output : CEventRelativeTag * //----------------------------------------------------------------------------- CFlexTimingTag * CChoreoEvent::FindTimingTag( const char *tagname ) { for ( int i = 0; i < m_TimingTags.Size(); i++ ) { CFlexTimingTag *ptt = &m_TimingTags[ i ]; if ( !ptt ) continue; if ( !stricmp( ptt->GetName(), tagname ) ) { return ptt; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::OnEndTimeChanged( void ) { int c = GetNumFlexAnimationTracks(); for ( int i = 0; i < c; i++ ) { CFlexAnimationTrack *track = GetFlexAnimationTrack( i ); Assert( track ); if ( !track ) continue; track->Resort( 0 ); } } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetNumFlexAnimationTracks( void ) { return m_FlexAnimationTracks.Size(); } //----------------------------------------------------------------------------- // Purpose: // Input : index - // Output : CFlexAnimationTrack //----------------------------------------------------------------------------- CFlexAnimationTrack *CChoreoEvent::GetFlexAnimationTrack( int index ) { if ( index < 0 || index >= GetNumFlexAnimationTracks() ) return NULL; return m_FlexAnimationTracks[ index ]; } //----------------------------------------------------------------------------- // Purpose: // Input : *controllername - // Output : CFlexAnimationTrack //----------------------------------------------------------------------------- CFlexAnimationTrack *CChoreoEvent::AddTrack( const char *controllername ) { CFlexAnimationTrack *newTrack = new CFlexAnimationTrack( this ); newTrack->SetFlexControllerName( controllername ); m_FlexAnimationTracks.AddToTail( newTrack ); return newTrack; } //----------------------------------------------------------------------------- // Purpose: // Input : index - //----------------------------------------------------------------------------- void CChoreoEvent::RemoveTrack( int index ) { CFlexAnimationTrack *track = GetFlexAnimationTrack( index ); if ( !track ) return; m_FlexAnimationTracks.Remove( index ); delete track; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::RemoveAllTracks( void ) { while ( GetNumFlexAnimationTracks() > 0 ) { RemoveTrack( 0 ); } } //----------------------------------------------------------------------------- // Purpose: // Input : *controllername - // Output : CFlexAnimationTrack //----------------------------------------------------------------------------- CFlexAnimationTrack *CChoreoEvent::FindTrack( const char *controllername ) { for ( int i = 0; i < GetNumFlexAnimationTracks(); i++ ) { CFlexAnimationTrack *t = GetFlexAnimationTrack( i ); if ( t && !stricmp( t->GetFlexControllerName(), controllername ) ) { return t; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::GetTrackLookupSet( void ) { return m_bTrackLookupSet; } //----------------------------------------------------------------------------- // Purpose: // Input : set - //----------------------------------------------------------------------------- void CChoreoEvent::SetTrackLookupSet( bool set ) { m_bTrackLookupSet = set; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::IsProcessing( void ) const { return m_bProcessing; } //----------------------------------------------------------------------------- // Purpose: // Input : *cb - // t - //----------------------------------------------------------------------------- void CChoreoEvent::StartProcessing( IChoreoEventCallback *cb, CChoreoScene *scene, float t ) { Assert( !m_bProcessing ); m_bProcessing = true; if ( cb ) { cb->StartEvent( t, scene, this ); } } //----------------------------------------------------------------------------- // Purpose: // Input : *cb - // t - //----------------------------------------------------------------------------- void CChoreoEvent::ContinueProcessing( IChoreoEventCallback *cb, CChoreoScene *scene, float t ) { Assert( m_bProcessing ); if ( cb ) { cb->ProcessEvent( t, scene, this ); } } //----------------------------------------------------------------------------- // Purpose: // Input : *cb - // t - //----------------------------------------------------------------------------- void CChoreoEvent::StopProcessing( IChoreoEventCallback *cb, CChoreoScene *scene, float t ) { Assert( m_bProcessing ); if ( cb ) { cb->EndEvent( t, scene, this ); } m_bProcessing = false; } //----------------------------------------------------------------------------- // Purpose: // Input : *cb - // t - //----------------------------------------------------------------------------- bool CChoreoEvent::CheckProcessing( IChoreoEventCallback *cb, CChoreoScene *scene, float t ) { //Assert( !m_bProcessing ); if ( cb ) { return cb->CheckEvent( t, scene, this ); } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::ResetProcessing( void ) { if ( GetType() == LOOP ) { m_nLoopsRemaining = m_nNumLoops; } m_bProcessing = false; } //----------------------------------------------------------------------------- // Purpose: // Input : *mixer - //----------------------------------------------------------------------------- void CChoreoEvent::SetMixer( CAudioMixer *mixer ) { m_pMixer = mixer; } //----------------------------------------------------------------------------- // Purpose: // Output : CAudioMixer //----------------------------------------------------------------------------- CAudioMixer *CChoreoEvent::GetMixer( void ) const { return m_pMixer; } // Snap to scene framerate //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::SnapTimes() { if ( HasEndTime() && !IsFixedLength() ) { m_flEndTime = SnapTime( m_flEndTime ); } float oldstart = m_flStartTime; m_flStartTime = SnapTime( m_flStartTime ); // Don't snap end time for fixed length events, just set based on new start time if ( IsFixedLength() ) { float dt = m_flStartTime - oldstart; m_flEndTime += dt; } } //----------------------------------------------------------------------------- // Purpose: // Input : t - // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::SnapTime( float t ) { CChoreoScene *scene = GetScene(); if ( !scene) { Assert( 0 ); return t; } return scene->SnapTime( t ); } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoScene //----------------------------------------------------------------------------- CChoreoScene *CChoreoEvent::GetScene( void ) { return m_pScene; } //----------------------------------------------------------------------------- // Purpose: // Input : *scene - //----------------------------------------------------------------------------- void CChoreoEvent::SetScene( CChoreoScene *scene ) { m_pScene = scene; } //----------------------------------------------------------------------------- // Purpose: // Input : t - // Output : char const //----------------------------------------------------------------------------- const char *CChoreoEvent::NameForAbsoluteTagType( AbsTagType t ) { switch ( t ) { case PLAYBACK: return "playback_time"; case ORIGINAL: return "shifted_time"; default: break; } return "AbsTagType(unknown)"; } //----------------------------------------------------------------------------- // Purpose: // Input : *name - // Output : AbsTagType //----------------------------------------------------------------------------- CChoreoEvent::AbsTagType CChoreoEvent::TypeForAbsoluteTagName( const char *name ) { if ( !Q_strcasecmp( name, "playback_time" ) ) { return PLAYBACK; } else if ( !Q_strcasecmp( name, "shifted_time" ) ) { return ORIGINAL; } return (AbsTagType)-1; } //----------------------------------------------------------------------------- // Purpose: // Input : type - //----------------------------------------------------------------------------- void CChoreoEvent::ClearAllAbsoluteTags( AbsTagType type ) { m_AbsoluteTags[ type ].Purge(); } //----------------------------------------------------------------------------- // Purpose: // Input : type - // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetNumAbsoluteTags( AbsTagType type ) { return m_AbsoluteTags[ type ].Size(); } //----------------------------------------------------------------------------- // Purpose: // Input : type - // tagnum - // Output : CEventAbsoluteTag //----------------------------------------------------------------------------- CEventAbsoluteTag *CChoreoEvent::GetAbsoluteTag( AbsTagType type, int tagnum ) { Assert( tagnum >= 0 && tagnum < m_AbsoluteTags[ type ].Size() ); return &m_AbsoluteTags[ type ][ tagnum ]; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *tagname - // Output : CEventAbsoluteTag //----------------------------------------------------------------------------- CEventAbsoluteTag *CChoreoEvent::FindAbsoluteTag( AbsTagType type, const char *tagname ) { for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ ) { CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ]; if ( !ptag ) continue; if ( !stricmp( ptag->GetName(), tagname ) ) { return ptag; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *tagname - // t - //----------------------------------------------------------------------------- void CChoreoEvent::AddAbsoluteTag( AbsTagType type, const char *tagname, float t ) { CEventAbsoluteTag at( this, tagname, t ); m_AbsoluteTags[ type ].AddToTail( at ); // Sort tags CEventAbsoluteTag temp( (CChoreoEvent *)0x1, "", 0.0f ); // ugly bubble sort for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ ) { for ( int j = i + 1; j < m_AbsoluteTags[ type ].Size(); j++ ) { CEventAbsoluteTag *t1 = &m_AbsoluteTags[ type ][ i ]; CEventAbsoluteTag *t2 = &m_AbsoluteTags[ type ][ j ]; if ( t1->GetPercentage() > t2->GetPercentage() ) { temp = *t1; *t1 = *t2; *t2 = temp; } } } } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *tagname - //----------------------------------------------------------------------------- void CChoreoEvent::RemoveAbsoluteTag( AbsTagType type, const char *tagname ) { for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ ) { CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ]; if ( !ptag ) continue; if ( !stricmp( ptag->GetName(), tagname ) ) { m_AbsoluteTags[ type ].Remove( i ); return; } } } //----------------------------------------------------------------------------- // Purpose: makes sure tags in PLAYBACK are in the same order as ORIGINAL // Input : // Output : true if they were in order, false if it has to reorder them //----------------------------------------------------------------------------- bool CChoreoEvent::VerifyTagOrder( ) { bool bInOrder = true; // Sort tags CEventAbsoluteTag temp( (CChoreoEvent *)0x1, "", 0.0f ); for ( int i = 0; i < m_AbsoluteTags[ CChoreoEvent::ORIGINAL ].Size(); i++ ) { CEventAbsoluteTag *ptag = &m_AbsoluteTags[ CChoreoEvent::ORIGINAL ][ i ]; if ( !ptag ) continue; CEventAbsoluteTag *t1 = &m_AbsoluteTags[ CChoreoEvent::PLAYBACK ][ i ]; if ( stricmp( ptag->GetName(), t1->GetName() ) == 0) continue; bInOrder = false; for ( int j = i + 1; j < m_AbsoluteTags[ CChoreoEvent::PLAYBACK ].Size(); j++ ) { CEventAbsoluteTag *t2 = &m_AbsoluteTags[ CChoreoEvent::PLAYBACK ][ j ]; if ( stricmp( ptag->GetName(), t2->GetName() ) == 0 ) { temp = *t1; *t1 = *t2; *t2 = temp; break; } } } return bInOrder; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *tagname - //----------------------------------------------------------------------------- float CChoreoEvent::GetBoundedAbsoluteTagPercentage( AbsTagType type, int tagnum ) { if ( tagnum <= -2 ) { /* if (GetNumAbsoluteTags( type ) >= 1) { CEventAbsoluteTag *tag = GetAbsoluteTag( type, 0 ); Assert( tag ); return -tag->GetTime(); } */ return 0.0f; // -0.5f; } else if ( tagnum == -1 ) { return 0.0f; } else if ( tagnum == GetNumAbsoluteTags( type ) ) { return 1.0; } else if ( tagnum > GetNumAbsoluteTags( type ) ) { /* if (GetNumAbsoluteTags( type ) >= 1) { CEventAbsoluteTag *tag = GetAbsoluteTag( type, tagnum - 2 ); Assert( tag ); return 2.0 - tag->GetTime(); } */ return 1.0; // 1.5; } /* { float duration = GetDuration(); if ( type == SHIFTED ) { float seqduration; GetGestureSequenceDuration( seqduration ); return seqduration; } return duration; } */ CEventAbsoluteTag *tag = GetAbsoluteTag( type, tagnum ); Assert( tag ); return tag->GetPercentage(); } //----------------------------------------------------------------------------- // Purpose: // Input : t - // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetOriginalPercentageFromPlaybackPercentage( float t ) { Assert( GetType() == GESTURE ); if ( GetType() != GESTURE ) return t; int count = GetNumAbsoluteTags( PLAYBACK ); if ( count != GetNumAbsoluteTags( ORIGINAL ) ) { return t; } if ( count <= 0 ) { return t; } if ( t <= 0.0f ) return 0.0f; float s = 0.0f, n = 0.0f; // find what tags this is between int i; for ( i = -1 ; i < count; i++ ) { s = GetBoundedAbsoluteTagPercentage( PLAYBACK, i ); n = GetBoundedAbsoluteTagPercentage( PLAYBACK, i + 1 ); if ( t >= s && t <= n ) { break; } } int prev = i - 1; int start = i; int end = i + 1; int next = i + 2; prev = MAX( -2, prev ); start = MAX( -1, start ); end = MIN( end, count ); next = MIN( next, count + 1 ); CEventAbsoluteTag *pStartTag = NULL; CEventAbsoluteTag *pEndTag = NULL; // check for linear portion of lookup if (start >= 0 && start < count) { pStartTag = GetAbsoluteTag( PLAYBACK, start ); } if (end >= 0 && end < count) { pEndTag = GetAbsoluteTag( PLAYBACK, end ); } if (pStartTag && pEndTag) { if (pStartTag->GetLinear() && pEndTag->GetLinear()) { CEventAbsoluteTag *pOrigStartTag = GetAbsoluteTag( ORIGINAL, start ); CEventAbsoluteTag *pOrigEndTag = GetAbsoluteTag( ORIGINAL, end ); if (pOrigStartTag && pOrigEndTag) { s = ( t - pStartTag->GetPercentage() ) / (pEndTag->GetPercentage() - pStartTag->GetPercentage()); return (1 - s) * pOrigStartTag->GetPercentage() + s * pOrigEndTag->GetPercentage(); } } } float dt = n - s; Vector vPre( GetBoundedAbsoluteTagPercentage( PLAYBACK, prev ), GetBoundedAbsoluteTagPercentage( ORIGINAL, prev ), 0 ); Vector vStart( GetBoundedAbsoluteTagPercentage( PLAYBACK, start ), GetBoundedAbsoluteTagPercentage( ORIGINAL, start ), 0 ); Vector vEnd( GetBoundedAbsoluteTagPercentage( PLAYBACK, end ), GetBoundedAbsoluteTagPercentage( ORIGINAL, end ), 0 ); Vector vNext( GetBoundedAbsoluteTagPercentage( PLAYBACK, next ), GetBoundedAbsoluteTagPercentage( ORIGINAL, next ), 0 ); // simulate sections of either side of "linear" portion of ramp as linear slope if (pStartTag && pStartTag->GetLinear()) { vPre.Init( vStart.x - (vEnd.x - vStart.x), vStart.y - (vEnd.y - vStart.y), 0 ); } if (pEndTag && pEndTag->GetLinear()) { vNext.Init( vEnd.x + (vEnd.x - vStart.x), vEnd.y + (vEnd.y - vStart.y), 0 ); } float f2 = 0.0f; if ( dt > 0.0f ) { f2 = ( t - s ) / ( dt ); } f2 = clamp( f2, 0.0f, 1.0f ); Vector vOut; Catmull_Rom_Spline_NormalizeX( vPre, vStart, vEnd, vNext, f2, vOut ); return vOut.y; /* float duration; GetGestureSequenceDuration( duration ); float retval = clamp( vOut.y, 0.0f, duration ); return retval; */ } //----------------------------------------------------------------------------- // Purpose: // Input : t - // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetPlaybackPercentageFromOriginalPercentage( float t ) { Assert( GetType() == GESTURE ); if ( GetType() != GESTURE ) return t; int count = GetNumAbsoluteTags( PLAYBACK ); if ( count != GetNumAbsoluteTags( ORIGINAL ) ) { return t; } if ( count <= 0 ) { return t; } if ( t <= 0.0f ) return 0.0f; float s = 0.0f, n = 0.0f; // find what tags this is between int i; for ( i = -1 ; i < count; i++ ) { s = GetBoundedAbsoluteTagPercentage( PLAYBACK, i ); n = GetBoundedAbsoluteTagPercentage( PLAYBACK, i + 1 ); if ( t >= s && t <= n ) { break; } } int prev = i - 1; int start = i; int end = i + 1; int next = i + 2; prev = MAX( -2, prev ); start = MAX( -1, start ); end = MIN( end, count ); next = MIN( next, count + 1 ); CEventAbsoluteTag *pStartTag = NULL; CEventAbsoluteTag *pEndTag = NULL; // check for linear portion of lookup if (start >= 0 && start < count) { pStartTag = GetAbsoluteTag( ORIGINAL, start ); } if (end >= 0 && end < count) { pEndTag = GetAbsoluteTag( ORIGINAL, end ); } // check for linear portion of lookup if (pStartTag && pEndTag) { if (pStartTag->GetLinear() && pEndTag->GetLinear()) { CEventAbsoluteTag *pPlaybackStartTag = GetAbsoluteTag( PLAYBACK, start ); CEventAbsoluteTag *pPlaybackEndTag = GetAbsoluteTag( PLAYBACK, end ); if (pPlaybackStartTag && pPlaybackEndTag) { s = ( t - pStartTag->GetPercentage() ) / (pEndTag->GetPercentage() - pStartTag->GetPercentage()); return (1 - s) * pPlaybackStartTag->GetPercentage() + s * pPlaybackEndTag->GetPercentage(); } } } float dt = n - s; Vector vPre( GetBoundedAbsoluteTagPercentage( ORIGINAL, prev ), GetBoundedAbsoluteTagPercentage( PLAYBACK, prev ), 0 ); Vector vStart( GetBoundedAbsoluteTagPercentage( ORIGINAL, start ), GetBoundedAbsoluteTagPercentage( PLAYBACK, start ), 0 ); Vector vEnd( GetBoundedAbsoluteTagPercentage( ORIGINAL, end ), GetBoundedAbsoluteTagPercentage( PLAYBACK, end ), 0 ); Vector vNext( GetBoundedAbsoluteTagPercentage( ORIGINAL, next ), GetBoundedAbsoluteTagPercentage( PLAYBACK, next ), 0 ); // simulate sections of either side of "linear" portion of ramp as linear slope if (pStartTag && pStartTag->GetLinear()) { vPre.Init( vStart.x - (vEnd.x - vStart.x), vStart.y - (vEnd.y - vStart.y), 0 ); } if (pEndTag && pEndTag->GetLinear()) { vNext.Init( vEnd.x + (vEnd.x - vStart.x), vEnd.y + (vEnd.y - vStart.y), 0 ); } float f2 = 0.0f; if ( dt > 0.0f ) { f2 = ( t - s ) / ( dt ); } f2 = clamp( f2, 0.0f, 1.0f ); Vector vOut; Catmull_Rom_Spline_NormalizeX( vPre, vStart, vEnd, vNext, f2, vOut ); return vOut.y; /* float duration; GetGestureSequenceDuration( duration ); float retval = clamp( vOut.y, 0.0f, duration ); return retval; */ } //----------------------------------------------------------------------------- // Purpose: // Input : duration - //----------------------------------------------------------------------------- void CChoreoEvent::SetGestureSequenceDuration( float duration ) { m_flGestureSequenceDuration = duration; } //----------------------------------------------------------------------------- // Purpose: // Input : duration - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::GetGestureSequenceDuration( float& duration ) { bool valid = m_flGestureSequenceDuration != 0.0f; if ( !valid ) { duration = GetDuration(); } else { duration = m_flGestureSequenceDuration; } return valid; } //----------------------------------------------------------------------------- // Purpose: // Input : pitch - //----------------------------------------------------------------------------- int CChoreoEvent::GetPitch( void ) const { return m_nPitch; } //----------------------------------------------------------------------------- // Purpose: // Input : pitch - //----------------------------------------------------------------------------- void CChoreoEvent::SetPitch( int pitch ) { m_nPitch = pitch; } //----------------------------------------------------------------------------- // Purpose: // Input : yaw - //----------------------------------------------------------------------------- int CChoreoEvent::GetYaw( void ) const { return m_nYaw; } //----------------------------------------------------------------------------- // Purpose: // Input : yaw - //----------------------------------------------------------------------------- void CChoreoEvent::SetYaw( int yaw ) { m_nYaw = yaw; } //----------------------------------------------------------------------------- // Purpose: // Input : t - // -1 - //----------------------------------------------------------------------------- void CChoreoEvent::SetLoopCount( int numloops ) { Assert( GetType() == LOOP ); // Never below -1 m_nNumLoops = MAX( numloops, -1 ); } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetNumLoopsRemaining( void ) { Assert( GetType() == LOOP ); return m_nLoopsRemaining; } //----------------------------------------------------------------------------- // Purpose: // Input : loops - //----------------------------------------------------------------------------- void CChoreoEvent::SetNumLoopsRemaining( int loops ) { Assert( GetType() == LOOP ); m_nLoopsRemaining = loops; } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetLoopCount( void ) { Assert( GetType() == LOOP ); return m_nNumLoops; } EdgeInfo_t *CCurveData::GetEdgeInfo( int idx ) { return &m_RampEdgeInfo[ idx ]; } int CCurveData::GetCount( void ) { return m_Ramp.Count(); } CExpressionSample *CCurveData::Get( int index ) { if ( index < 0 || index >= GetCount() ) return NULL; return &m_Ramp[ index ]; } CExpressionSample *CCurveData::Add( float time, float value, bool selected ) { CExpressionSample sample; sample.time = time; sample.value = value; sample.selected = selected; int idx = m_Ramp.AddToTail( sample ); return &m_Ramp[ idx ]; } void CCurveData::Delete( int index ) { if ( index < 0 || index >= GetCount() ) return; m_Ramp.Remove( index ); } void CCurveData::Clear( void ) { m_Ramp.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CCurveData::Resort( ICurveDataAccessor *data ) { for ( int i = 0; i < m_Ramp.Size(); i++ ) { for ( int j = i + 1; j < m_Ramp.Size(); j++ ) { CExpressionSample src = m_Ramp[ i ]; CExpressionSample dest = m_Ramp[ j ]; if ( src.time > dest.time ) { m_Ramp[ i ] = dest; m_Ramp[ j ] = src; } } } RemoveOutOfRangeSamples( data ); // m_RampAccumulator.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: // Input : number - // Output : CExpressionSample //----------------------------------------------------------------------------- CExpressionSample *CCurveData::GetBoundedSample( ICurveDataAccessor *data, int number, bool& bClamped ) { // Search for two samples which span time f if ( number < 0 ) { static CExpressionSample nullstart; nullstart.time = 0.0f; nullstart.value = GetEdgeZeroValue( true ); nullstart.SetCurveType( GetEdgeCurveType( true ) ); bClamped = true; return &nullstart; } else if ( number >= GetCount() ) { static CExpressionSample nullend; nullend.time = data->GetDuration(); nullend.value = GetEdgeZeroValue( false ); nullend.SetCurveType( GetEdgeCurveType( false ) ); bClamped = true; return &nullend; } bClamped = false; return Get( number ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CCurveData::RemoveOutOfRangeSamples( ICurveDataAccessor *data ) { float duration = data->GetDuration(); int c = GetCount(); for ( int i = c-1; i >= 0; i-- ) { CExpressionSample src = m_Ramp[ i ]; if ( src.time < 0 || src.time > duration + 0.01 ) { m_Ramp.Remove( i ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::RescaleGestureTimes( float newstart, float newend, bool bMaintainAbsoluteTagPositions ) { if ( GetType() != CChoreoEvent::GESTURE ) return; // Did it actually change if ( newstart == GetStartTime() && newend == GetEndTime() ) { return; } float newduration = newend - newstart; float dt = 0.0f; //If the end is moving, leave tags stay where they are (dt == 0.0f) if ( newstart != GetStartTime() ) { // Otherwise, if the new start is later, then tags need to be shifted backwards dt -= ( newstart - GetStartTime() ); } if ( bMaintainAbsoluteTagPositions ) { int i; int count = GetNumAbsoluteTags( CChoreoEvent::PLAYBACK ); for ( i = 0; i < count; i++ ) { CEventAbsoluteTag *tag = GetAbsoluteTag( CChoreoEvent::PLAYBACK, i ); float tagtime = tag->GetPercentage() * GetDuration(); tagtime += dt; tagtime = clamp( tagtime / newduration, 0.0f, 1.0f ); tag->SetPercentage( tagtime ); } } } //----------------------------------------------------------------------------- // Purpose: Make sure tags aren't co-located or out of order //----------------------------------------------------------------------------- bool CChoreoEvent::PreventTagOverlap( void ) { bool bHadOverlap = false; // FIXME: limit to single frame? float minDp = 0.01; float minP = 1.00; int count = GetNumAbsoluteTags( CChoreoEvent::PLAYBACK ); for ( int i = count - 1; i >= 0; i-- ) { CEventAbsoluteTag *tag = GetAbsoluteTag( CChoreoEvent::PLAYBACK, i ); if (tag->GetPercentage() > minP) { tag->SetPercentage( minP ); minDp = MIN( 0.01, minP / (i + 1) ); bHadOverlap = true; } else { minP = tag->GetPercentage(); } minP = MAX( minP - minDp, 0 ); } return bHadOverlap; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // Output : CEventAbsoluteTag //----------------------------------------------------------------------------- CEventAbsoluteTag *CChoreoEvent::FindEntryTag( AbsTagType type ) { for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ ) { CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ]; if ( !ptag ) continue; if ( ptag->GetEntry() ) { return ptag; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // Output : CEventAbsoluteTag //----------------------------------------------------------------------------- CEventAbsoluteTag *CChoreoEvent::FindExitTag( AbsTagType type ) { for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ ) { CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ]; if ( !ptag ) continue; if ( ptag->GetExit() ) { return ptag; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Input : *style - // maxlen - //----------------------------------------------------------------------------- void CChoreoEvent::GetMovementStyle( char *style, int maxlen ) { Assert( GetType() == MOVETO ); style[0] = 0; const char *in = m_Parameters2.Get(); char *out = style; while ( *in && *in != '\0' && *in != ' ' ) { if ( out - style >= maxlen - 1 ) break; *out++ = *in++; } *out = 0; } //----------------------------------------------------------------------------- // Purpose: // Input : *style - // maxlen - //----------------------------------------------------------------------------- void CChoreoEvent::GetDistanceStyle( char *style, int maxlen ) { Assert( GetType() == MOVETO ); style[0]= 0; const char *in = Q_strstr( m_Parameters2.Get(), " " ); if ( !in ) return; in++; char *out = style; while ( *in && *in != '\0' ) { if ( out - style >= maxlen - 1 ) break; *out++ = *in++; } *out = 0; } void CChoreoEvent::SetCloseCaptionType( CLOSECAPTION type ) { Assert( m_fType == SPEAK ); m_ccType = type; } CChoreoEvent::CLOSECAPTION CChoreoEvent::GetCloseCaptionType() const { Assert( m_fType == SPEAK ); return (CLOSECAPTION)m_ccType; } void CChoreoEvent::SetCloseCaptionToken( char const *token ) { Assert( m_fType == SPEAK ); Assert( token ); m_CCToken = token; } char const *CChoreoEvent::GetCloseCaptionToken() const { Assert( m_fType == SPEAK ); return m_CCToken.Get(); } bool CChoreoEvent::GetPlaybackCloseCaptionToken( char *dest, int destlen ) { dest[0] = 0; Assert( m_fType == SPEAK ); switch ( m_ccType ) { default: case CC_DISABLED: { return false; } case CC_SLAVE: { // If it's a slave, then only disable if we're not using the combined wave if ( IsUsingCombinedFile() ) { return false; } if ( m_CCToken[ 0 ] != 0 ) { Q_strncpy( dest, m_CCToken.Get(), destlen ); } else { Q_strncpy( dest, m_Parameters.Get(), destlen ); } return true; } case CC_MASTER: { // Always use the override if we're the master, otherwise always use the default // parameter if ( m_CCToken[ 0 ] != 0 ) { Q_strncpy( dest, m_CCToken.Get(), destlen ); } else { Q_strncpy( dest, m_Parameters.Get(), destlen ); } return true; } } return false; } void CChoreoEvent::SetUsingCombinedFile( bool isusing ) { Assert( m_fType == SPEAK ); m_bUsingCombinedSoundFile = isusing; } bool CChoreoEvent::IsUsingCombinedFile() const { Assert( m_fType == SPEAK ); return m_bUsingCombinedSoundFile; } void CChoreoEvent::SetRequiredCombinedChecksum( unsigned int checksum ) { Assert( m_fType == SPEAK ); m_uRequiredCombinedChecksum = checksum; } unsigned int CChoreoEvent::GetRequiredCombinedChecksum() { Assert( m_fType == SPEAK ); return m_uRequiredCombinedChecksum; } void CChoreoEvent::SetNumSlaves( int num ) { Assert( m_fType == SPEAK ); Assert( num >= 0 ); m_nNumSlaves = num; } int CChoreoEvent::GetNumSlaves() const { Assert( m_fType == SPEAK ); return m_nNumSlaves; } void CChoreoEvent::SetLastSlaveEndTime( float t ) { Assert( m_fType == SPEAK ); m_flLastSlaveEndTime = t; } float CChoreoEvent::GetLastSlaveEndTime() const { Assert( m_fType == SPEAK ); return m_flLastSlaveEndTime; } void CChoreoEvent::SetCloseCaptionTokenValid( bool valid ) { Assert( m_fType == SPEAK ); m_bCCTokenValid = valid; } bool CChoreoEvent::GetCloseCaptionTokenValid() const { Assert( m_fType == SPEAK ); return m_bCCTokenValid; } //----------------------------------------------------------------------------- // Purpose: Removes characters which can't appear in windows filenames // Input : *in - // *dest - // destlen - // Output : static void //----------------------------------------------------------------------------- static void CleanupTokenName( char const *in, char *dest, int destlen ) { char *out = dest; while ( *in && ( out - dest ) < destlen ) { if ( V_isalnum( *in ) || // lowercase, uppercase, digits and underscore are valid *in == '_' ) { *out++ = *in; } else { *out++ = '_'; // Put underscores in for bogus characters } in++; } *out = 0; } bool CChoreoEvent::ComputeCombinedBaseFileName( char *dest, int destlen, bool creategenderwildcard ) { if ( m_fType != SPEAK ) return false; if ( m_ccType != CC_MASTER ) return false; if ( GetNumSlaves() == 0 ) return false; if ( !m_pScene ) return false; char vcdpath[ 512 ]; char cleanedtoken[ MAX_CCTOKEN_STRING ]; CleanupTokenName( m_CCToken.Get(), cleanedtoken, sizeof( cleanedtoken ) ); if ( Q_strlen( cleanedtoken ) <= 0 ) return false; Q_strncpy( vcdpath, m_pScene->GetFilename(), sizeof( vcdpath ) ); Q_StripFilename( vcdpath ); Q_FixSlashes( vcdpath, '/' ); char *pvcd = vcdpath; char *offset = Q_strstr( vcdpath, "scenes" ); if ( offset ) { pvcd = offset + 6; if ( *pvcd == '/' ) { ++pvcd; } } int len = Q_strlen( pvcd ); if ( len > 0 && ( len + 1 ) < ( sizeof( vcdpath ) - 1 ) ) { pvcd[ len ] = '/'; pvcd[ len + 1 ] = 0; } Assert( !Q_strstr( pvcd, ":" ) ); if ( creategenderwildcard ) { Q_snprintf( dest, destlen, "sound/combined/%s%s_$gender.wav", pvcd, cleanedtoken ); } else { Q_snprintf( dest, destlen, "sound/combined/%s%s.wav", pvcd, cleanedtoken ); } return true; } bool CChoreoEvent::IsCombinedUsingGenderToken() const { return m_bCombinedUsingGenderToken; } void CChoreoEvent::SetCombinedUsingGenderToken( bool using_gender ) { m_bCombinedUsingGenderToken = using_gender; } int CChoreoEvent::ValidateCombinedFile() { return 0; } bool CChoreoEvent::IsSuppressingCaptionAttenuation() const { return m_bSuppressCaptionAttenuation; } void CChoreoEvent::SetSuppressingCaptionAttenuation( bool suppress ) { m_bSuppressCaptionAttenuation = suppress; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::ClearEventDependencies() { m_Dependencies.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: // Input : *other - //----------------------------------------------------------------------------- void CChoreoEvent::AddEventDependency( CChoreoEvent *other ) { if ( m_Dependencies.Find( other ) == m_Dependencies.InvalidIndex() ) { m_Dependencies.AddToTail( other ); } } //----------------------------------------------------------------------------- // Purpose: // Input : list - //----------------------------------------------------------------------------- void CChoreoEvent::GetEventDependencies( CUtlVector< CChoreoEvent * >& list ) { int c = m_Dependencies.Count(); for ( int i = 0; i < c; ++i ) { list.AddToTail( m_Dependencies[ i ] ); } } void CCurveData::SetEdgeInfo( bool leftEdge, int curveType, float zero ) { int idx = leftEdge ? 0 : 1; m_RampEdgeInfo[ idx ].m_CurveType = curveType; m_RampEdgeInfo[ idx ].m_flZeroPos = zero; } void CCurveData::GetEdgeInfo( bool leftEdge, int& curveType, float& zero ) const { int idx = leftEdge ? 0 : 1; curveType = m_RampEdgeInfo[ idx ].m_CurveType; zero = m_RampEdgeInfo[ idx ].m_flZeroPos; } void CCurveData::SetEdgeActive( bool leftEdge, bool state ) { int idx = leftEdge ? 0 : 1; m_RampEdgeInfo[ idx ].m_bActive = state; } bool CCurveData::IsEdgeActive( bool leftEdge ) const { int idx = leftEdge ? 0 : 1; return m_RampEdgeInfo[ idx ].m_bActive; } int CCurveData::GetEdgeCurveType( bool leftEdge ) const { if ( !IsEdgeActive( leftEdge ) ) { return CURVE_DEFAULT; } int idx = leftEdge ? 0 : 1; return m_RampEdgeInfo[ idx ].m_CurveType; } float CCurveData::GetEdgeZeroValue( bool leftEdge ) const { if ( !IsEdgeActive( leftEdge ) ) { return 0.0f; } int idx = leftEdge ? 0 : 1; return m_RampEdgeInfo[ idx ].m_flZeroPos; } void CChoreoEvent::SaveToBuffer( CUtlBuffer& buf, CChoreoScene *pScene, IChoreoStringPool *pStringPool ) { buf.PutChar( GetType() ); buf.PutShort( pStringPool->FindOrAddString( GetName() ) ); float st = GetStartTime(); buf.PutFloat( st ); float et = GetEndTime(); buf.PutFloat( et ); buf.PutShort( pStringPool->FindOrAddString( GetParameters() ) ); buf.PutShort( pStringPool->FindOrAddString( GetParameters2() ) ); buf.PutShort( pStringPool->FindOrAddString( GetParameters3() ) ); m_Ramp.SaveToBuffer( buf, pStringPool ); int flags = 0; flags |= IsResumeCondition() ? 1<<0 : 0; flags |= IsLockBodyFacing() ? 1<<1 : 0; flags |= IsFixedLength() ? 1<<2 : 0; flags |= GetActive() ? 1<<3 : 0; flags |= GetForceShortMovement() ? 1<<4 : 0; flags |= GetPlayOverScript() ? 1<<5 : 0; buf.PutUnsignedChar( flags ); buf.PutFloat( GetDistanceToTarget() ); int numRelativeTags = GetNumRelativeTags(); Assert( numRelativeTags <= 255 ); buf.PutUnsignedChar( numRelativeTags ); for ( int t = 0; t < numRelativeTags; t++ ) { CEventRelativeTag *rt = GetRelativeTag( t ); Assert( rt ); buf.PutShort( pStringPool->FindOrAddString( rt->GetName() ) ); Assert( rt->GetPercentage() >= 0.0f && rt->GetPercentage() <= 1.0f ); unsigned char p = rt->GetPercentage() * 255.0f; buf.PutUnsignedChar( p ); } int numTimingTags = GetNumTimingTags(); Assert( numTimingTags <= 255 ); buf.PutUnsignedChar( numTimingTags ); for ( int t = 0; t < numTimingTags; t++ ) { CFlexTimingTag *tt = GetTimingTag( t ); Assert( tt ); buf.PutShort( pStringPool->FindOrAddString( tt->GetName() ) ); // save as u0.8 Assert( tt->GetPercentage() >= 0.0f && tt->GetPercentage() <= 1.0f ); unsigned char p = tt->GetPercentage() * 255.0f; buf.PutUnsignedChar( p ); // Don't save locked state, it's only used by the editor tt->GetLocked() } int tagtype; for ( tagtype = 0; tagtype < CChoreoEvent::NUM_ABS_TAG_TYPES; tagtype++ ) { int num = GetNumAbsoluteTags( (CChoreoEvent::AbsTagType)tagtype ); Assert( num <= 255 ); buf.PutUnsignedChar( num ); for ( int i = 0; i < num ; ++i ) { CEventAbsoluteTag *abstag = GetAbsoluteTag( (CChoreoEvent::AbsTagType)tagtype, i ); Assert( abstag ); buf.PutShort( pStringPool->FindOrAddString( abstag->GetName() ) ); // save as u4.12 Assert( abstag->GetPercentage() >= 0.0f && abstag->GetPercentage() <= 15.0f ); unsigned short p = abstag->GetPercentage() * 4096.0f; buf.PutUnsignedShort( p ); } } if ( GetType() == CChoreoEvent::GESTURE ) { float duration; if ( GetGestureSequenceDuration( duration ) ) { buf.PutFloat( duration ); } else { buf.PutFloat( -1.0f ); } } buf.PutChar( IsUsingRelativeTag() ? 1 : 0 ); if ( IsUsingRelativeTag() ) { buf.PutShort( pStringPool->FindOrAddString( GetRelativeTagName() ) ); buf.PutShort( pStringPool->FindOrAddString( GetRelativeWavName() ) ); } SaveFlexAnimationsToBuffer( buf, pStringPool ); if ( GetType() == LOOP ) { buf.PutChar( GetLoopCount() ); } if ( GetType() == CChoreoEvent::SPEAK ) { buf.PutChar( GetCloseCaptionType() ); buf.PutShort( pStringPool->FindOrAddString( GetCloseCaptionToken() ) ); flags = 0; if ( GetCloseCaptionType() != CChoreoEvent::CC_DISABLED && IsUsingCombinedFile() ) { flags |= ( 1<<0 ); } if ( IsCombinedUsingGenderToken() ) { flags |= ( 1<<1 ); } if ( IsSuppressingCaptionAttenuation() ) { flags |= ( 1<<2 ); } buf.PutChar( flags ); } } bool CChoreoEvent::RestoreFromBuffer( CUtlBuffer& buf, CChoreoScene *pScene, IChoreoStringPool *pStringPool ) { MEM_ALLOC_CREDIT(); SetType( (EVENTTYPE)buf.GetChar() ); char sz[ 256 ]; pStringPool->GetString( buf.GetShort(), sz, sizeof( sz ) ); SetName( sz ); SetStartTime( buf.GetFloat() ); SetEndTime( buf.GetFloat() ); char params[ 2048 ]; pStringPool->GetString( buf.GetShort(), params, sizeof( params ) ); SetParameters( params ); pStringPool->GetString( buf.GetShort(), params, sizeof( params ) ); SetParameters2( params ); pStringPool->GetString( buf.GetShort(), params, sizeof( params ) ); SetParameters3( params ); if ( !m_Ramp.RestoreFromBuffer( buf, pStringPool ) ) return false; int flags = buf.GetUnsignedChar(); SetResumeCondition( ( flags & ( 1<<0 ) ) ? true : false ); SetLockBodyFacing( ( flags & ( 1<<1 ) ) ? true : false ); SetFixedLength( ( flags & ( 1<<2 ) ) ? true : false ); SetActive( ( flags & ( 1<<3 ) ) ? true : false ); SetForceShortMovement( ( flags & ( 1<<4 ) ) ? true : false ); SetPlayOverScript( ( flags & ( 1<<5 ) ) ? true : false ); SetDistanceToTarget( buf.GetFloat() ); int numRelTags = buf.GetUnsignedChar(); for ( int i = 0; i < numRelTags; ++i ) { char tagName[ 256 ]; pStringPool->GetString( buf.GetShort(), tagName, sizeof( tagName ) ); float percentage = (float)buf.GetUnsignedChar() * 1.0f/255.0f; AddRelativeTag( tagName, percentage ); } int numTimingTags = buf.GetUnsignedChar(); for ( int i = 0; i < numTimingTags; ++i ) { char tagName[ 256 ]; pStringPool->GetString( buf.GetShort(), tagName, sizeof( tagName ) ); float percentage = (float)buf.GetUnsignedChar() * 1.0f/255.0f; // Don't parse locked state, only used by editors AddTimingTag( tagName, percentage, false ); } int tagtype; for ( tagtype = 0; tagtype < CChoreoEvent::NUM_ABS_TAG_TYPES; tagtype++ ) { int num = buf.GetUnsignedChar(); for ( int i = 0; i < num; ++i ) { char tagName[ 256 ]; pStringPool->GetString( buf.GetShort(), tagName, sizeof( tagName ) ); float percentage = (float)buf.GetUnsignedShort() * 1.0f/4096.0f; // Don't parse locked state, only used by editors AddAbsoluteTag( (CChoreoEvent::AbsTagType)tagtype, tagName, percentage ); } } if ( GetType() == CChoreoEvent::GESTURE ) { float duration = buf.GetFloat(); if ( duration != -1 ) { SetGestureSequenceDuration( duration ); } } if ( buf.GetChar() == 1 ) { char tagname[ 256 ]; char wavname[ 256 ]; pStringPool->GetString( buf.GetShort(), tagname, sizeof( tagname ) ); pStringPool->GetString( buf.GetShort(), wavname, sizeof( wavname ) ); SetUsingRelativeTag( true, tagname, wavname ); } if ( !RestoreFlexAnimationsFromBuffer( buf, pStringPool ) ) return false; if ( GetType() == LOOP ) { SetLoopCount( buf.GetChar() ); } if ( GetType() == CChoreoEvent::SPEAK ) { SetCloseCaptionType( (CLOSECAPTION)buf.GetChar() ); char cctoken[ 256 ]; pStringPool->GetString( buf.GetShort(), cctoken, sizeof( cctoken ) ); SetCloseCaptionToken( cctoken ); int flags = buf.GetChar(); if ( flags & ( 1<<0 ) ) { SetUsingCombinedFile( true ); } if ( flags & ( 1<<1 ) ) { SetCombinedUsingGenderToken( true ); } if ( flags & ( 1<<2 ) ) { SetSuppressingCaptionAttenuation( true ); } } return true; } void CCurveData::SaveToBuffer( CUtlBuffer& buf, IChoreoStringPool *pStringPool ) { int c = GetCount(); Assert( c <= 255 ); buf.PutUnsignedChar( c ); for ( int i = 0; i < c; i++ ) { CExpressionSample *sample = Get( i ); buf.PutFloat( sample->time ); Assert( sample->value >= 0.0f && sample->value <= 1.0f ); unsigned char v = sample->value * 255.0f; buf.PutUnsignedChar( v ); } } bool CCurveData::RestoreFromBuffer( CUtlBuffer& buf, IChoreoStringPool *pStringPool ) { int c = buf.GetUnsignedChar(); for ( int i = 0; i < c; i++ ) { float t, v; t = buf.GetFloat(); v = (float)buf.GetUnsignedChar() * 1.0f/255.0f; Add( t, v, false ); } return true; } void CChoreoEvent::SaveFlexAnimationsToBuffer( CUtlBuffer& buf, IChoreoStringPool *pStringPool ) { int numFlexAnimationTracks = GetNumFlexAnimationTracks(); Assert( numFlexAnimationTracks <= 255 ); buf.PutUnsignedChar( numFlexAnimationTracks ); for ( int i = 0; i < numFlexAnimationTracks; i++ ) { CFlexAnimationTrack *track = GetFlexAnimationTrack( i ); buf.PutShort( pStringPool->FindOrAddString( track->GetFlexControllerName() ) ); int flags = 0; flags |= track->IsTrackActive() ? 1<<0 : 0; flags |= track->IsComboType() ? 1<<1 : 0; buf.PutUnsignedChar( flags ); buf.PutFloat( track->GetMin() ); buf.PutFloat( track->GetMax() ); buf.PutShort( track->GetNumSamples( 0 ) ); for ( int j = 0 ; j < track->GetNumSamples( 0 ) ; j++ ) { CExpressionSample *s = track->GetSample( j, 0 ); if ( !s ) continue; buf.PutFloat( s->time ); Assert( s->value >= 0.0f && s->value <= 1.0f ); unsigned char v = s->value * 255.0f; buf.PutUnsignedChar( v ); buf.PutUnsignedShort( s->GetCurveType() ); } // Write out combo samples if ( track->IsComboType() ) { int numSamples = track->GetNumSamples( 1 ); Assert( numSamples <= 32767 ); buf.PutUnsignedShort( numSamples ); for ( int j = 0; j < numSamples; j++ ) { CExpressionSample *s = track->GetSample( j, 1 ); if ( !s ) continue; buf.PutFloat( s->time ); Assert( s->value >= 0.0f && s->value <= 1.0f ); unsigned char v = s->value * 255.0f; buf.PutUnsignedChar( v ); buf.PutUnsignedShort( s->GetCurveType() ); } } } } bool CChoreoEvent::RestoreFlexAnimationsFromBuffer( CUtlBuffer& buf, IChoreoStringPool *pStringPool ) { int numTracks = buf.GetUnsignedChar(); for ( int i = 0; i < numTracks; i++ ) { char name[ 256 ]; pStringPool->GetString( buf.GetShort(), name, sizeof( name ) ); CFlexAnimationTrack *track = AddTrack( name ); int flags = buf.GetUnsignedChar(); track->SetTrackActive( ( flags & ( 1<<0 ) ) ? true : false ); track->SetComboType( ( flags & ( 1<<1 ) ) ? true : false ); track->SetMin( buf.GetFloat() ); track->SetMax( buf.GetFloat() ); int s = buf.GetShort(); for ( int j = 0; j < s; ++j ) { float t, v; t = buf.GetFloat(); v = (float)buf.GetUnsignedChar() * 1.0f/255.0f; CExpressionSample *pSample = track->AddSample( t, v, 0 ); pSample->SetCurveType( buf.GetUnsignedShort() ); } if ( track->IsComboType() ) { int s = buf.GetUnsignedShort(); for ( int j = 0; j < s; ++j ) { float t, v; t = buf.GetFloat(); v = (float)buf.GetUnsignedChar() * 1.0f/255.0f; CExpressionSample *pSample = track->AddSample( t, v, 1 ); pSample->SetCurveType( buf.GetUnsignedShort() ); } } } return true; } //----------------------------------------------------------------------------- // Purpose: Marks the event as enabled/disabled // Input : state - //----------------------------------------------------------------------------- void CChoreoEvent::SetActive( bool state ) { m_bActive = state; } bool CChoreoEvent::GetActive() const { return m_bActive; }
26.842082
176
0.459494
Planimeter
40de540be43e454c19ddb6c11050259be9da9466
7,760
cpp
C++
root/stat.cpp
amcghie/watchman
27ed35666681a48df42fc9a22f863fa99a2e1c85
[ "Apache-2.0" ]
null
null
null
root/stat.cpp
amcghie/watchman
27ed35666681a48df42fc9a22f863fa99a2e1c85
[ "Apache-2.0" ]
2
2020-02-27T11:22:22.000Z
2021-05-20T10:23:12.000Z
root/stat.cpp
amcghie/watchman
27ed35666681a48df42fc9a22f863fa99a2e1c85
[ "Apache-2.0" ]
null
null
null
/* Copyright 2012-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "watchman.h" #include "InMemoryView.h" #include "watchman_error_category.h" namespace watchman { void InMemoryView::statPath( const std::shared_ptr<w_root_t>& root, SyncView::LockedPtr& view, PendingCollection::LockedPtr& coll, const w_string& full_path, struct timeval now, int flags, const watchman_dir_ent* pre_stat) { watchman::FileInformation st; std::error_code errcode; char path[WATCHMAN_NAME_MAX]; bool recursive = flags & W_PENDING_RECURSIVE; bool via_notify = flags & W_PENDING_VIA_NOTIFY; if (root->ignore.isIgnoreDir(full_path)) { w_log( W_LOG_DBG, "%.*s matches ignore_dir rules\n", int(full_path.size()), full_path.data()); return; } if (full_path.size() > sizeof(path) - 1) { w_log( W_LOG_FATAL, "path %.*s is too big\n", int(full_path.size()), full_path.data()); } memcpy(path, full_path.data(), full_path.size()); path[full_path.size()] = 0; auto dir_name = full_path.dirName(); auto file_name = full_path.baseName(); auto parentDir = resolveDir(view, dir_name, true); auto file = parentDir->getChildFile(file_name); auto dir_ent = parentDir->getChildDir(file_name); if (pre_stat && pre_stat->has_stat) { st = pre_stat->stat; } else { try { st = getFileInformation(path, root->case_sensitive); log(DBG, "getFileInformation(", path, ") file=", file, " dir=", dir_ent, "\n"); } catch (const std::system_error &exc) { errcode = exc.code(); log(DBG, "getFileInformation(", path, ") file=", file, " dir=", dir_ent, " failed: ", exc.what(), "\n"); } } if (errcode == watchman::error_code::no_such_file_or_directory || errcode == watchman::error_code::not_a_directory) { /* it's not there, update our state */ if (dir_ent) { markDirDeleted(view, dir_ent, now, true); watchman::log( watchman::DBG, "getFileInformation(", path, ") -> ", errcode.message(), " so stopping watch\n"); } if (file) { if (file->exists) { watchman::log( watchman::DBG, "getFileInformation(", path, ") -> ", errcode.message(), " so marking ", file->getName(), " deleted\n"); file->exists = false; markFileChanged(view, file, now); } } else { // It was created and removed before we could ever observe it // in the filesystem. We need to generate a deleted file // representation of it now, so that subscription clients can // be notified of this event file = getOrCreateChildFile(view, parentDir, file_name, now); log(DBG, "getFileInformation(", path, ") -> ", errcode.message(), " and file node was NULL. " "Generating a deleted node.\n"); file->exists = false; markFileChanged(view, file, now); } if (root->case_sensitive == CaseSensitivity::CaseInSensitive && !w_string_equal(dir_name, root->root_path) && parentDir->last_check_existed) { /* If we rejected the name because it wasn't canonical, * we need to ensure that we look in the parent dir to discover * the new item(s) */ w_log( W_LOG_DBG, "we're case insensitive, and %s is ENOENT, " "speculatively look at parent dir %.*s\n", path, int(dir_name.size()), dir_name.data()); coll->add(dir_name, now, W_PENDING_CRAWL_ONLY); } } else if (errcode.value()) { log(ERR, "getFileInformation(", path, ") failed and not handled! -> ", errcode.message(), " value=", errcode.value(), " category=", errcode.category().name(), "\n"); } else { if (!file) { file = getOrCreateChildFile(view, parentDir, file_name, now); } if (!file->exists) { /* we're transitioning from deleted to existing, * so we're effectively new again */ file->ctime.ticks = view->mostRecentTick; file->ctime.timestamp = now.tv_sec; /* if a dir was deleted and now exists again, we want * to crawl it again */ recursive = true; } if (!file->exists || via_notify || did_file_change(&file->stat, &st)) { w_log( W_LOG_DBG, "file changed exists=%d via_notify=%d stat-changed=%d isdir=%d %s\n", (int)file->exists, (int)via_notify, (int)(file->exists && !via_notify), st.isDir(), path); file->exists = true; markFileChanged(view, file, now); } memcpy(&file->stat, &st, sizeof(file->stat)); // check for symbolic link if (st.isSymlink()) { try { auto target = readSymbolicLink(path); bool symlink_changed = false; if (file->symlink_target != target) { symlink_changed = true; } file->symlink_target = target; if (symlink_changed && root->config.getBool("watch_symlinks", false)) { root->inner.pending_symlink_targets.wlock()->add(full_path, now, 0); } } catch (const std::system_error& exc) { log(ERR, "readlink(", path, ") failed: ", exc.what(), "\n"); file->symlink_target.reset(); } } else { file->symlink_target.reset(); } if (st.isDir()) { if (dir_ent == NULL) { recursive = true; } else { // Ensure that we believe that this node exists dir_ent->last_check_existed = true; } // Don't recurse if our parent is an ignore dir if (!root->ignore.isIgnoreVCS(dir_name) || // but do if we're looking at the cookie dir (stat_path is never // called for the root itself) w_string_equal(full_path, root->cookies.cookieDir())) { if (!(watcher_->flags & WATCHER_HAS_PER_FILE_NOTIFICATIONS)) { /* we always need to crawl, but may not need to be fully recursive */ coll->add( full_path, now, W_PENDING_CRAWL_ONLY | (recursive ? W_PENDING_RECURSIVE : 0)); } else { /* we get told about changes on the child, so we only * need to crawl if we've never seen the dir before. * An exception is that fsevents will only report the root * of a dir rename and not a rename event for all of its * children. */ if (recursive) { coll->add( full_path, now, W_PENDING_RECURSIVE | W_PENDING_CRAWL_ONLY); } } } } else if (dir_ent) { // We transitioned from dir to file (see fishy.php), so we should prune // our former tree here markDirDeleted(view, dir_ent, now, true); } if ((watcher_->flags & WATCHER_HAS_PER_FILE_NOTIFICATIONS) && !st.isDir() && !w_string_equal(dir_name, root->root_path) && parentDir->last_check_existed) { /* Make sure we update the mtime on the parent directory. * We're deliberately not propagating any of the flags through; we * definitely don't want this to be a recursive evaluation and we * won'd want to treat this as VIA_NOTIFY to avoid spuriously * marking the node as changed when only its atime was changed. * https://github.com/facebook/watchman/issues/305 and * https://github.com/facebook/watchman/issues/307 have more * context on why this is. */ coll->add(dir_name, now, 0); } } } } /* vim:ts=2:sw=2:et: */
32.605042
80
0.581959
amcghie
40e23dda4ca58a0ffe1944e246c378314124fa2a
15,458
cpp
C++
CPUT/CPUT/CPUTModelOGL.cpp
GameTechDev/OpenGLESTessellation
b504ec95be716d1671dd55a61aa142d0c133fd1b
[ "Apache-2.0" ]
13
2016-03-06T12:05:52.000Z
2021-07-24T21:17:46.000Z
CPUT/CPUT/CPUTModelOGL.cpp
GameTechDev/OpenGLESTessellation
b504ec95be716d1671dd55a61aa142d0c133fd1b
[ "Apache-2.0" ]
null
null
null
CPUT/CPUT/CPUTModelOGL.cpp
GameTechDev/OpenGLESTessellation
b504ec95be716d1671dd55a61aa142d0c133fd1b
[ "Apache-2.0" ]
8
2016-05-06T14:08:44.000Z
2022-03-17T09:37:20.000Z
///////////////////////////////////////////////////////////////////////////////////////////// // Copyright 2017 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. ///////////////////////////////////////////////////////////////////////////////////////////// #include "CPUTModelOGL.h" #include "CPUTMaterialEffectOGL.h" #include "CPUTFrustum.h" #include "CPUTAssetLibraryOGL.h" #include "CPUTTextureOGL.h" DrawModelCallBackFunc CPUTModel::mDrawModelCallBackFunc = CPUTModelOGL::DrawModelCallBack; //----------------------------------------------------------------------------- CPUTMeshOGL* CPUTModelOGL::GetMesh(const UINT index) const { return ( 0==mMeshCount || index > mMeshCount) ? NULL : (CPUTMeshOGL*)mpMesh[index]; } // Set the render state before drawing this object //----------------------------------------------------------------------------- void CPUTModelOGL::UpdateShaderConstants(CPUTRenderParameters &renderParams) { float4x4 world(*GetWorldMatrix()); float4x4 NormalMatrix(*GetWorldMatrix()); //Local transform if node baked into animation if(mSkeleton && mpCurrentAnimation) { world = GetParentsWorldMatrix(); NormalMatrix = GetParentsWorldMatrix(); } if( renderParams.mpPerModelConstants ) { CPUTBufferOGL *pBuffer = (CPUTBufferOGL*)(renderParams.mpPerModelConstants); CPUTModelConstantBuffer cb; cb.World = world; cb.InverseWorld = cb.World; cb.InverseWorld.invert(); CPUTCamera *pCamera = renderParams.mpCamera; if(pCamera) { cb.WorldViewProjection = cb.World * *pCamera->GetViewMatrix() * *pCamera->GetProjectionMatrix(); } float4x4 shadowView, shadowProjection; CPUTCamera *pShadowCamera = gpSample->GetShadowCamera(); if( pShadowCamera ) { shadowView = *pShadowCamera->GetViewMatrix(); shadowProjection = *pShadowCamera->GetProjectionMatrix(); cb.LightWorldViewProjection = cb.World * shadowView * shadowProjection; } cb.BoundingBoxCenterWorldSpace = float4(mBoundingBoxCenterWorldSpace, 0); cb.BoundingBoxHalfWorldSpace = float4(mBoundingBoxHalfWorldSpace, 0); cb.BoundingBoxCenterObjectSpace = float4(mBoundingBoxCenterObjectSpace, 0); cb.BoundingBoxHalfObjectSpace = float4(mBoundingBoxHalfObjectSpace, 0); //TODO: Should this process if object not visible? //Only do this if Model has a skin and is animated if(mSkeleton && mpCurrentAnimation) { ASSERT(0, _L("Skinning constant buffer temporarily disabled")); //ASSERT(mSkeleton->mNumberOfJoints < 255, _L("Skin Exceeds maximum number of allowable joints: 255")); //for(UINT i = 0; i < mSkeleton->mNumberOfJoints; ++i) //{ // CPUTJoint *pJoint = &mSkeleton->mJointsList[i]; // cb.SkinMatrix[i] = pJoint->mInverseBindPoseMatrix * pJoint->mScaleMatrix * pJoint->mRTMatrix; // float4x4 skinNormalMatrix = cb.SkinMatrix[i]; // skinNormalMatrix.invert(); skinNormalMatrix.transpose(); // cb.SkinNormalMatrix[i] = skinNormalMatrix; //} } #ifndef CPUT_FOR_OGLES2 pBuffer->SetSubData(0, sizeof(CPUTModelConstantBuffer), &cb); #else #warning "Need to do something with uniform buffers here" #endif } } // Render - render this model (only) //----------------------------------------------------------------------------- void CPUTModelOGL::Render(CPUTRenderParameters &renderParams, int materialIndex) { UpdateShaderConstants(renderParams); // loop over all meshes in this model and draw them for(UINT ii=0; ii<mMeshCount; ii++) { UINT finalMaterialIndex = GetMaterialIndex(ii, materialIndex); ASSERT( finalMaterialIndex < mpLayoutCount[ii], _L("material index out of range.")); CPUTMaterialEffect *pMaterialEffect = (CPUTMaterialEffect*)(mpMaterialEffect[ii][finalMaterialIndex]); mDrawModelCallBackFunc(this, renderParams, mpMesh[ii], pMaterialEffect, NULL, NULL); } } //----------------------------------------------------------------------------- // DrawModelCallBack - default model rendering code can be overridden by a callback set in user side code //----------------------------------------------------------------------------- bool CPUTModelOGL::DrawModelCallBack(CPUTModel* pModel, CPUTRenderParameters &renderParams, CPUTMesh* pMesh, CPUTMaterialEffect* pMaterial, CPUTMaterialEffect* , void* ) { pMaterial->SetRenderStates(renderParams); if( ((CPUTMaterialEffectOGL*)pMaterial)->Tessellated() ) ((CPUTMeshOGL*)pMesh)->DrawPatches(renderParams, pModel); else ((CPUTMeshOGL*)pMesh)->Draw(renderParams, pModel); return true; } #ifdef SUPPORT_DRAWING_BOUNDING_BOXES //----------------------------------------------------------------------------- void CPUTModelOGL::DrawBoundingBox(CPUTRenderParameters &renderParams) { SetRenderStates(renderParams); CPUTMaterialOGL *pMaterial = (CPUTMaterialOGL*)mpBoundingBoxMaterial; mpBoundingBoxMaterial->SetRenderStates(renderParams); ((CPUTMeshOGL*)mpBoundingBoxMesh)->Draw(renderParams, this); } #endif // Load the set file definition of this object // 1. Parse the block of name/parent/transform info for model block // 2. Load the model's binary payload (i.e., the meshes) // 3. Assert the # of meshes matches # of materials // 4. Load each mesh's material //----------------------------------------------------------------------------- CPUTResult CPUTModelOGL::LoadModel(CPUTConfigBlock *pBlock, int *pParentID, CPUTModel *pMasterModel, int numSystemMaterials, cString *pSystemMaterialNames) { CPUTResult result = CPUT_SUCCESS; CPUTAssetLibraryOGL *pAssetLibrary = (CPUTAssetLibraryOGL*)CPUTAssetLibrary::GetAssetLibrary(); cString modelSuffix = ptoc(this); // set the model's name mName = pBlock->GetValueByName(_L("name"))->ValueAsString(); mName = mName + _L(".mdl"); // resolve the full path name cString modelLocation; cString resolvedPathAndFile; modelLocation = ((CPUTAssetLibraryOGL*)CPUTAssetLibrary::GetAssetLibrary())->GetModelDirectoryName(); modelLocation = modelLocation+mName; CPUTFileSystem::ResolveAbsolutePathAndFilename(modelLocation, &resolvedPathAndFile); // Get the parent ID. Note: the caller will use this to set the parent. *pParentID = pBlock->GetValueByName(_L("parent"))->ValueAsInt(); LoadParentMatrixFromParameterBlock( pBlock ); // Get the bounding box information float3 center(0.0f), half(0.0f); pBlock->GetValueByName(_L("BoundingBoxCenter"))->ValueAsFloatArray(center.f, 3); pBlock->GetValueByName(_L("BoundingBoxHalf"))->ValueAsFloatArray(half.f, 3); mBoundingBoxCenterObjectSpace = center; mBoundingBoxHalfObjectSpace = half; mMeshCount = pBlock->GetValueByName(_L("meshcount"))->ValueAsInt(); mpMesh = new CPUTMesh*[mMeshCount]; mpLayoutCount = new UINT[mMeshCount]; mpRootMaterial = new CPUTMaterial*[mMeshCount]; memset( mpRootMaterial, 0, mMeshCount * sizeof(CPUTMaterial*) ); mpMaterialEffect = new CPUTMaterialEffect**[mMeshCount]; memset( mpMaterialEffect, 0, mMeshCount * sizeof(CPUTMaterialEffect*) ); // get the material names, load them, and match them up with each mesh cString materialName,shadowMaterialName; char pNumber[4]; cString materialValueName; CPUTModelOGL *pMasterModelDX = (CPUTModelOGL*)pMasterModel; for(UINT ii=0; ii<mMeshCount; ii++) { if(pMasterModelDX) { // Reference the master model's mesh. Don't create a new one. mpMesh[ii] = pMasterModelDX->mpMesh[ii]; mpMesh[ii]->AddRef(); } else { mpMesh[ii] = new CPUTMeshOGL(); } } if( !pMasterModelDX ) { // Not a clone/instance. So, load the model's binary payload (i.e., vertex and index buffers) // TODO: Change to use GetModel() result = LoadModelPayload(resolvedPathAndFile); ASSERT( CPUTSUCCESS(result), _L("Failed loading model") ); } cString assetSetDirectoryName = pAssetLibrary->GetAssetSetDirectoryName(); cString modelDirectory = pAssetLibrary->GetModelDirectoryName(); cString materialDirectory = pAssetLibrary->GetMaterialDirectoryName(); cString textureDirectory = pAssetLibrary->GetTextureDirectoryName(); cString shaderDirectory = pAssetLibrary->GetShaderDirectoryName(); cString fontDirectory = pAssetLibrary->GetFontDirectoryName(); cString up2MediaDirName = assetSetDirectoryName + _L("../../"); pAssetLibrary->SetMediaDirectoryName( up2MediaDirName ); // mpShadowCastMaterial = pAssetLibrary->GetMaterial( _L("shadowCast"), false ); pAssetLibrary->SetAssetSetDirectoryName( assetSetDirectoryName ); pAssetLibrary->SetModelDirectoryName( modelDirectory ); pAssetLibrary->SetMaterialDirectoryName( materialDirectory ); pAssetLibrary->SetTextureDirectoryName( textureDirectory ); pAssetLibrary->SetShaderDirectoryName( shaderDirectory ); pAssetLibrary->SetFontDirectoryName( fontDirectory ); for(UINT ii=0; ii<mMeshCount; ii++) { // get the right material number ('material0', 'material1', 'material2', etc) materialValueName = _L("material"); snprintf(pNumber, 4, "%d", ii); // _itoa(ii, pNumber, 4, 10); materialValueName.append(s2ws(pNumber)); materialName = pBlock->GetValueByName(materialValueName)->ValueAsString(); shadowMaterialName = pBlock->GetValueByName(_L("shadowCast") + materialValueName)->ValueAsString(); bool isSkinned = pBlock->GetValueByName(_L("skeleton")) != &CPUTConfigEntry::sNullConfigValue; if( shadowMaterialName.length() == 0 ) { if(!isSkinned) { shadowMaterialName = _L("%shadowCast"); } else { shadowMaterialName = _L("%shadowCastSkinned"); } } // Get/load material for this mesh UINT totalNameCount = numSystemMaterials + NUM_GLOBAL_SYSTEM_MATERIALS; cString *pFinalSystemNames = new cString[totalNameCount]; // Copy "global" system materials to caller-supplied list for( int jj=0; jj<numSystemMaterials; jj++ ) { pFinalSystemNames[jj] = pSystemMaterialNames[jj]; } pFinalSystemNames[totalNameCount + CPUT_MATERIAL_INDEX_SHADOW_CAST] = shadowMaterialName; // pFinalSystemNames[totalNameCount + CPUT_MATERIAL_INDEX_BOUNDING_BOX] = _L("%BoundingBox"); int finalNumSystemMaterials = numSystemMaterials + NUM_GLOBAL_SYSTEM_MATERIALS; CPUTMaterial *pMaterial = pAssetLibrary->GetMaterial(materialName, false, this, ii, NULL, finalNumSystemMaterials, pFinalSystemNames); ASSERT( pMaterial, _L("Couldn't find material.") ); delete []pFinalSystemNames; mpLayoutCount[ii] = pMaterial->GetMaterialEffectCount(); SetMaterial(ii, pMaterial); // Release the extra refcount we're holding from the GetMaterial operation earlier // now the asset library, and this model have the only refcounts on that material pMaterial->Release(); // Create two ID3D11InputLayout objects, one for each material. // mpMesh[ii]->BindVertexShaderLayout( mpMaterial[ii], mpShadowCastMaterial); // mpShadowCastMaterial->Release() } return result; } // Set the material associated with this mesh and create/re-use a //----------------------------------------------------------------------------- void CPUTModelOGL::SetMaterial(UINT ii, CPUTMaterial *pMaterial) { CPUTModel::SetMaterial(ii, pMaterial); // Can't bind the layout if we haven't loaded the mesh yet. CPUTMeshOGL *pMesh = (CPUTMeshOGL*)mpMesh[ii]; // D3D11_INPUT_ELEMENT_DESC *pDesc = pMesh->GetLayoutDescription(); // if( pDesc ) { // pMesh->BindVertexShaderLayout(pMaterial, mpMaterial[ii]); } } #ifdef SUPPORT_DRAWING_BOUNDING_BOXES //----------------------------------------------------------------------------- void CPUTModelOGL::DrawBoundingBox(CPUTRenderParameters &renderParams) { UpdateShaderConstants(renderParams); UINT index = mpSubMaterialCount[0] + CPUT_MATERIAL_INDEX_BOUNDING_BOX; CPUTMaterialOGL *pMaterial = (CPUTMaterialOGL*)(mpMaterial[0][index]); pMaterial->SetRenderStates(renderParams); ((CPUTMeshOGL*)mpBoundingBoxMesh)->Draw(renderParams, mpInputLayout[0][index]); } // Note that we only need one of these. We don't need to re-create it for every model. //----------------------------------------------------------------------------- void CPUTModelDX11::CreateBoundingBoxMesh() { CPUTResult result = CPUT_SUCCESS; float3 pVertices[8] = { float3( 1.0f, 1.0f, 1.0f ), // 0 float3( 1.0f, 1.0f, -1.0f ), // 1 float3( -1.0f, 1.0f, 1.0f ), // 2 float3( -1.0f, 1.0f, -1.0f ), // 3 float3( 1.0f, -1.0f, 1.0f ), // 4 float3( 1.0f, -1.0f, -1.0f ), // 5 float3( -1.0f, -1.0f, 1.0f ), // 6 float3( -1.0f, -1.0f, -1.0f ) // 7 }; USHORT pIndices[24] = { 0,1, 1,3, 3,2, 2,0, // Top 4,5, 5,7, 7,6, 6,4, // Bottom 0,4, 1,5, 2,6, 3,7 // Verticals }; CPUTVertexElementDesc pVertexElements[] = { { CPUT_VERTEX_ELEMENT_POSITON, tFLOAT, 12, 0 }, }; CPUTMesh *pMesh = mpBoundingBoxMesh = new CPUTMeshDX11(); pMesh->SetMeshTopology(CPUT_TOPOLOGY_INDEXED_LINE_LIST); CPUTBufferElementInfo vertexElementInfo; vertexElementInfo.mpSemanticName = "POSITION"; vertexElementInfo.mSemanticIndex = 0; vertexElementInfo.mElementType = CPUT_F32; vertexElementInfo.mElementComponentCount = 3; vertexElementInfo.mElementSizeInBytes = 12; vertexElementInfo.mOffset = 0; CPUTBufferElementInfo indexDataInfo; indexDataInfo.mElementType = CPUT_U16; indexDataInfo.mElementComponentCount = 1; indexDataInfo.mElementSizeInBytes = sizeof(UINT16); indexDataInfo.mOffset = 0; indexDataInfo.mSemanticIndex = 0; indexDataInfo.mpSemanticName = NULL; result = pMesh->CreateNativeResources( this, -1, 1, &vertexElementInfo, 8, // vertexCount pVertices, &indexDataInfo, 24, // indexCount pIndices ); ASSERT( CPUTSUCCESS(result), _L("Failed building bounding box mesh") ); cString modelSuffix = ptoc(this); UINT index = mpSubMaterialCount[0] + CPUT_MATERIAL_INDEX_BOUNDING_BOX; CPUTMaterialOGL *pMaterial = (CPUTMaterialOGL*)(mpMaterial[0][index]); ((CPUTMeshOGL*)pMesh)->BindVertexShaderLayout( pMaterial, &mpInputLayout[0][index] ); } #endif
41.111702
169
0.64355
GameTechDev
40e2d5dd4597b18047d34d0bbba22d245005e884
2,697
cpp
C++
DirectX3D11/Objects/Model/Ninja.cpp
GyumLee/DirectX3D11
6158874aa12e790747e6fd8a53de608071c49574
[ "Apache-2.0" ]
null
null
null
DirectX3D11/Objects/Model/Ninja.cpp
GyumLee/DirectX3D11
6158874aa12e790747e6fd8a53de608071c49574
[ "Apache-2.0" ]
null
null
null
DirectX3D11/Objects/Model/Ninja.cpp
GyumLee/DirectX3D11
6158874aa12e790747e6fd8a53de608071c49574
[ "Apache-2.0" ]
null
null
null
#include "Framework.h" Ninja::Ninja(UINT instanceID) : instanceID(instanceID), state(IDLE) { collider = new SphereCollider(); collider->tag = "NinjaCollider"; collider->Load(); hpBar = new ProgressBar("Textures/UI/hp_bar.png", "Textures/UI/hp_bar_BG.png"); //hpBar->scale *= 0.1f; } Ninja::~Ninja() { delete collider; delete hpBar; } void Ninja::Update() { SetLeftHand(); SetHpBar(); //Trace(); Move(); collider->UpdateWorld(); } void Ninja::Render() { if (!ninja->isActive) return; float radius = ((SphereCollider*)collider)->Radius(); if (!FRUSTUM->ContainSphere(collider->GlobalPos(), radius)) return; collider->Render(); } void Ninja::PostRender() { if (!ninja->isActive) return; float radius = ((SphereCollider*)collider)->Radius(); if (!FRUSTUM->ContainSphere(collider->GlobalPos(), radius)) return; hpBar->Render(); } void Ninja::GUIRender() { collider->GUIRender(); } void Ninja::Move() { if (terrain) ninja->position.y = terrain->GetHeight(ninja->position); } void Ninja::Hit() { collider->isActive = false; hp -= 30.0f; hpBar->SetValue(hp); if (hp > 0) SetClip(HIT); else SetClip(DYING); } void Ninja::SetEvent() { instancing->AddEvent(instanceID, HIT, 0.8f, bind(&Ninja::EndHit, this)); } void Ninja::Trace() { if (!collider->isActive) return; if (!target) return; Vector3 dir = target->position - ninja->position; Vector3 cross = Vector3::Cross(dir, ninja->Forward()); if (cross.y > 0.01f) ninja->rotation.y += DELTA; else if (cross.y < -0.01f) ninja->rotation.y -= DELTA; ninja->position -= ninja->Forward() * DELTA; SetClip(RUN); } void Ninja::EndHit() { SetClip(IDLE); collider->isActive = true; } void Ninja::EndDie() { ninja->isActive = false; } void Ninja::SetHpBar() { float distance = Distance(CAM->position, ninja->position); hpBar->scale.x = 10 / distance; hpBar->scale.y = 10 / distance; Vector3 barPos = ninja->position + Vector3(0, 5, 0); hpBar->position = CAM->WorldToScreenPoint(barPos); lerpHp = LERP(lerpHp, hp, lerpSpeed * DELTA); hpBar->SetLerpValue(lerpHp); hpBar->Update(); } void Ninja::SetLeftHand() { leftHand = instancing->GetTransformByNode(instanceID, 11) * ninja->GetWorld(); } void Ninja::SetMotions() { //ReadClip("Idle"); //ReadClip("Run"); //ReadClip("Attack"); ////ReadClip("Hit"); // 1. BreakPoint here, Start Debugging, go to ReadClip() //ReadClip("Hit", 0, true); //ReadClip("Dying"); // //clips[HIT]->SetEvent(0.8f, bind(&Ninja::EndHit, this)); //clips[DYING]->SetEvent(0.9f, bind(&Ninja::EndDie, this)); } void Ninja::SetClip(AnimState state) { if (this->state != state) { this->state = state; instancing->PlayClip(instanceID, state); } }
17.860927
80
0.661846
GyumLee
40e6f4f88b09cbbd105a90a790c1f776b71c5f93
7,678
cpp
C++
src/BayesFilters/src/GaussianMixture.cpp
mfkiwl/bayes-filters-lib
8baabba1897bcc5634619fbc048bb5ab17a742da
[ "BSD-3-Clause" ]
50
2017-04-12T09:02:54.000Z
2022-02-15T20:01:35.000Z
src/BayesFilters/src/GaussianMixture.cpp
xEnVrE/bayes-filters-lib
8baabba1897bcc5634619fbc048bb5ab17a742da
[ "BSD-3-Clause" ]
79
2017-11-07T07:32:14.000Z
2021-06-20T17:12:08.000Z
src/BayesFilters/src/GaussianMixture.cpp
xEnVrE/bayes-filters-lib
8baabba1897bcc5634619fbc048bb5ab17a742da
[ "BSD-3-Clause" ]
23
2017-05-07T01:47:39.000Z
2022-02-28T10:15:59.000Z
/* * Copyright (C) 2016-2019 Istituto Italiano di Tecnologia (IIT) * * This software may be modified and distributed under the terms of the * BSD 3-Clause license. See the accompanying LICENSE file for details. */ #include <BayesFilters/GaussianMixture.h> using namespace bfl; using namespace Eigen; GaussianMixture::GaussianMixture() noexcept: GaussianMixture(1, 1, 0, false) { } GaussianMixture::GaussianMixture(const std::size_t components, const std::size_t dim) noexcept : GaussianMixture(components, dim, 0, false) { } GaussianMixture::GaussianMixture ( const std::size_t components, const std::size_t dim_linear, const std::size_t dim_circular, const bool use_quaternion ) noexcept : components(components), use_quaternion(use_quaternion), dim_circular_component(use_quaternion ? 4 : 1), dim(dim_linear + dim_circular * dim_circular_component), dim_linear(dim_linear), dim_circular(dim_circular), dim_noise(0), dim_covariance(use_quaternion ? dim_linear + dim_circular * (dim_circular_component - 1) : dim), mean_(dim, components), covariance_(dim_covariance, dim_covariance * components), weight_(components) { for (int i = 0; i < this->components; ++i) weight_(i) = 1.0 / this->components; /* Note: When using use_quaternion == false, the hypothesis is that there are dim_circular independent states each belonging to the manifold S1 (i.e. dim_circular angles). In this implementation they are treated as belonging to R^(dim_circular). Hence, the size of the covariance matrix is dim_covariance x (dim_covariance * components) where dim_covariance = dim. When using use_quaternion == true, instead the hypothesis is that there are dim_circular quaternions in the state, each belonging to the manifold S3. In this case, dim_circular_component = 4, since they are represented using 4 numbers. However, the covariance is represented using rotation vectors in R^3 that belong to the tangent space of the quaternion manifold. Hence, the size of the covariance matrix is dim_covariance x (dim_covariance * components) where dim_covariance = dim_linear + dim_circular * 3. */ } void GaussianMixture::resize(const std::size_t components, const std::size_t dim_linear, const std::size_t dim_circular) { std::size_t new_dim = dim_linear + dim_circular * dim_circular_component; std::size_t new_dim_covariance = use_quaternion ? dim_linear + dim_circular * (dim_circular_component - 1) : new_dim; if ((this->dim_linear == dim_linear) && (this->dim_circular == dim_circular) && (this->components == components)) return; else if ((this->dim == new_dim) && (this->components != components)) { mean_.conservativeResize(NoChange, components); covariance_.conservativeResize(NoChange, dim_covariance * components); weight_.conservativeResize(components); } else { // In any other case, it does not make sense to do conservative resize // since either old data is truncated or new data is incomplete mean_.resize(new_dim, components); covariance_.resize(new_dim_covariance, new_dim_covariance * components); weight_.resize(components); } this->components = components; this->dim = new_dim; this->dim_covariance = new_dim_covariance; this->dim_linear = dim_linear; this->dim_circular = dim_circular; } Ref<MatrixXd> GaussianMixture::mean() { return mean_; } Ref<VectorXd> GaussianMixture::mean(const std::size_t i) { return mean_.col(i); } double& GaussianMixture::mean(const std::size_t i, const std::size_t j) { return mean_(j, i); } const Ref<const MatrixXd> GaussianMixture::mean() const { return mean_; } const Ref<const VectorXd> GaussianMixture::mean(const std::size_t i) const { return mean_.col(i); } const double& GaussianMixture::mean(const std::size_t i, const std::size_t j) const { return mean_(j, i); } Ref<MatrixXd> GaussianMixture::covariance() { return covariance_; } Ref<MatrixXd> GaussianMixture::covariance(const std::size_t i) { return covariance_.middleCols(this->dim_covariance * i, this->dim_covariance); } double& GaussianMixture::covariance(const std::size_t i, const std::size_t j, const std::size_t k) { return covariance_(j, (this->dim_covariance * i) + k); } const Ref<const MatrixXd> GaussianMixture::covariance() const { return covariance_; } const Ref<const MatrixXd> GaussianMixture::covariance(const std::size_t i) const { return covariance_.middleCols(this->dim_covariance * i, this->dim_covariance); } const double& GaussianMixture::covariance(const std::size_t i, const std::size_t j, const std::size_t k) const { return covariance_(j, (this->dim_covariance * i) + k); } Ref<VectorXd> GaussianMixture::weight() { return weight_; } double& GaussianMixture::weight(const std::size_t i) { return weight_(i); } const Ref<const VectorXd> GaussianMixture::weight() const { return weight_; } const double& GaussianMixture::weight(const std::size_t i) const { return weight_(i); } bool GaussianMixture::augmentWithNoise(const Eigen::Ref<const Eigen::MatrixXd>& noise_covariance_matrix) { /* Augment each state with a noise component having zero mean and given covariance matrix. */ /* Check that covariance matrix is square. */ if (noise_covariance_matrix.rows() != noise_covariance_matrix.cols()) return false; dim_noise = noise_covariance_matrix.rows(); dim += dim_noise; dim_covariance += dim_noise; /* Add zero mean noise to each mean. */ mean_.conservativeResize(dim, NoChange); mean_.bottomRows(dim_noise) = MatrixXd::Zero(dim_noise, components); /* Resize covariance matrix. */ covariance_.conservativeResizeLike(MatrixXd::Zero(dim_covariance, dim_covariance * components)); /* Move old covariance matrices from right to left to avoid aliasing. Note that the covariance matrix of the 0-th coomponent, i.e. in the top-left corner of the matrix covariance_, is already in the correct place. */ std::size_t dim_old = use_quaternion ? dim_linear + dim_circular * (dim_circular_component - 1) : dim_linear + dim_circular; for (std::size_t i = 0; i < (components - 1); i++) { std::size_t i_index = components - 1 - i; Ref<MatrixXd> new_block = covariance_.block(0, i_index * dim_covariance, dim_old, dim_old); Ref<MatrixXd> old_block = covariance_.block(0, i_index * dim_old, dim_old, dim_old); /* Swap columns from to right to left to avoid aliasing. */ for (std::size_t j = 0; j < dim_old; j++) { std::size_t j_index = dim_old - 1 - j; new_block.col(j_index).swap(old_block.col(j_index)); } } for (std::size_t i = 0; i < components; i++) { /* Copy the noise covariance matrix in the bottom-right block of each covariance matrix. */ covariance_.block(dim_old, i * dim_covariance + dim_old, dim_noise, dim_noise) = noise_covariance_matrix; /* Clean part of the matrix that should be zero. */ covariance_.block(0, i * dim_covariance + dim_old, dim_old, dim_noise) = MatrixXd::Zero(dim_old, dim_noise); /* The part in covariance_.block(dim_old, i * dim_covariance, dim_noise, dim_old) was set to 0 when doing covariance_.conservativeResizeLike(MatrixXd::Zero(dim_covariance, dim_covariance * components)); since it is appended in order to expand the matrix. */ } return true; }
30.959677
128
0.700313
mfkiwl
40e7c855d098906bc67d132ecfd2f042c8d9318f
9,466
cpp
C++
source/adios2/toolkit/query/XmlWorker.cpp
taniabanerjee/ADIOS2
b32205071a22ea6319c34ed85fb1c47265c76a9d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
source/adios2/toolkit/query/XmlWorker.cpp
taniabanerjee/ADIOS2
b32205071a22ea6319c34ed85fb1c47265c76a9d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
source/adios2/toolkit/query/XmlWorker.cpp
taniabanerjee/ADIOS2
b32205071a22ea6319c34ed85fb1c47265c76a9d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#include "Worker.h" #include "adios2/helper/adiosLog.h" #include "adios2/helper/adiosXMLUtil.h" #include <pugixml.hpp> namespace adios2 { namespace query { void XmlWorker::ParseMe() { auto lf_FileContents = [&](const std::string &configXML) -> std::string { std::ifstream fileStream(configXML); if (!fileStream) { helper::Throw<std::ios_base::failure>( "Toolkit", "query::XmlWorker", "ParseMe", "file " + configXML + " not found"); } std::ostringstream fileSS; fileSS << fileStream.rdbuf(); fileStream.close(); if (fileSS.str().empty()) { helper::Throw<std::invalid_argument>("Toolkit", "query::XmlWorker", "ParseMe", "config xml file is empty"); } return fileSS.str(); }; // local function lf_FileContents const std::string fileContents = lf_FileContents(m_QueryFile); const std::unique_ptr<pugi::xml_document> document = adios2::helper::XMLDocument(fileContents, "in Query XMLWorker"); const std::unique_ptr<pugi::xml_node> config = adios2::helper::XMLNode( "adios-query", *document, "in adios-query", true); const pugi::xml_node ioNode = config->child("io"); ParseIONode(ioNode); } // Parse() void XmlWorker::ParseIONode(const pugi::xml_node &ioNode) { #ifdef PARSE_IO const std::unique_ptr<pugi::xml_attribute> ioName = adios2::helper::XMLAttribute("name", ioNode, "in query"); const std::unique_ptr<pugi::xml_attribute> fileName = adios2::helper::XMLAttribute("file", ioNode, "in query"); // must be unique per io const std::unique_ptr<pugi::xml_node> &engineNode = adios2::helper::XMLNode("engine", ioNode, "in query", false, true); m_IO = &(m_Adios2.DeclareIO(ioName->value())); if (engineNode) { const std::unique_ptr<pugi::xml_attribute> type = adios2::query::XmlUtil::XMLAttribute("type", engineNode, "in query"); m_IO->SetEngine(type->value()); const adios2::Params parameters = helper::GetParameters(engineNode, "in query"); m_IO->SetParameters(parameters); } else { m_IO->SetEngine("BPFile"); } // adios2::Engine reader = currIO.Open(fileName.value(), // adios2::Mode::Read, m_Comm); m_SourceReader = &(m_IO->Open(fileName.value(), adios2::Mode::Read, m_Comm)); #else const std::unique_ptr<pugi::xml_attribute> ioName = adios2::helper::XMLAttribute("name", ioNode, "in query"); if (m_SourceReader->m_IO.m_Name.compare(ioName->value()) != 0) { helper::Throw<std::ios_base::failure>( "Toolkit", "query::XmlWorker", "ParseIONode", "invalid query io. Expecting io name = " + m_SourceReader->m_IO.m_Name + " found:" + ioName->value()); } #endif std::map<std::string, QueryBase *> subqueries; adios2::Box<adios2::Dims> ref; for (const pugi::xml_node &qTagNode : ioNode.children("tag")) { const std::unique_ptr<pugi::xml_attribute> name = adios2::helper::XMLAttribute("name", qTagNode, "in query"); const pugi::xml_node &variable = qTagNode.child("var"); QueryVar *q = ParseVarNode(variable, m_SourceReader->m_IO, *m_SourceReader); if (!q) continue; if (ref.first.size() == 0) { ref = q->m_Selection; } else if (!q->IsCompatible(ref)) { helper::Throw<std::ios_base::failure>( "Toolkit", "query::XmlWorker", "ParseIONode", "impactible query found on var:" + q->GetVarName()); } subqueries[name->value()] = q; } const pugi::xml_node &qNode = ioNode.child("query"); if (qNode == nullptr) { const pugi::xml_node &variable = ioNode.child("var"); m_Query = ParseVarNode(variable, m_SourceReader->m_IO, *m_SourceReader); } else { const std::unique_ptr<pugi::xml_attribute> op = adios2::helper::XMLAttribute("op", qNode, "in query"); QueryComposite *q = new QueryComposite(adios2::query::strToRelation(op->value())); for (const pugi::xml_node &sub : qNode.children()) { q->AddNode(subqueries[sub.name()]); } m_Query = q; } } // parse_io_node // node is the variable node QueryVar *XmlWorker::ParseVarNode(const pugi::xml_node &node, adios2::core::IO &currentIO, adios2::core::Engine &reader) { const std::string variableName = std::string( adios2::helper::XMLAttribute("name", node, "in query")->value()); // const std::string varType = currentIO.VariableType(variableName); const DataType varType = currentIO.InquireVariableType(variableName); if (varType == DataType::None) { helper::Log("Query", "XmlWorker", "ParseVarNode", "No such variable: " + variableName, helper::LogMode::ERROR); helper::Throw<std::ios_base::failure>( "Toolkit", "query::XmlWorker", "ParseVarNode", "variable: " + variableName + " not found"); } #define declare_type(T) \ if (varType == helper::GetDataType<T>()) \ { \ core::Variable<T> *var = currentIO.InquireVariable<T>(variableName); \ if (var) \ { \ QueryVar *q = new QueryVar(variableName); \ adios2::Dims zero(var->Shape().size(), 0); \ adios2::Dims shape = var->Shape(); \ q->SetSelection(zero, shape); \ ConstructQuery(*q, node); \ return q; \ } \ } ADIOS2_FOREACH_ATTRIBUTE_PRIMITIVE_STDTYPE_1ARG(declare_type) #undef declare_type return nullptr; } // parse_var_node void XmlWorker::ConstructTree(RangeTree &host, const pugi::xml_node &node) { std::string relationStr = adios2::helper::XMLAttribute("value", node, "in query")->value(); host.SetRelation(adios2::query::strToRelation(relationStr)); for (const pugi::xml_node &rangeNode : node.children("range")) { std::string valStr = adios2::helper::XMLAttribute("value", rangeNode, "in query") ->value(); std::string opStr = adios2::helper::XMLAttribute("compare", rangeNode, "in query") ->value(); host.AddLeaf(adios2::query::strToQueryOp(opStr), valStr); } for (const pugi::xml_node &opNode : node.children("op")) { adios2::query::RangeTree subNode; ConstructTree(subNode, opNode); host.AddNode(subNode); } } void XmlWorker::ConstructQuery(QueryVar &simpleQ, const pugi::xml_node &node) { // QueryVar* simpleQ = new QueryVar(variableName); pugi::xml_node bbNode = node.child("boundingbox"); if (bbNode) { std::string startStr = adios2::helper::XMLAttribute("start", bbNode, "in query")->value(); std::string countStr = adios2::helper::XMLAttribute("count", bbNode, "in query")->value(); adios2::Dims start = split(startStr, ','); adios2::Dims count = split(countStr, ','); if (start.size() != count.size()) { helper::Throw<std::ios_base::failure>( "Toolkit", "query::XmlWorker", "ConstructQuery", "dim of startcount does match in the bounding box definition"); } // simpleQ.setSelection(box.first, box.second); adios2::Dims shape = simpleQ.m_Selection.second; // set at the creation for default simpleQ.SetSelection(start, count); if (!simpleQ.IsSelectionValid(shape)) { helper::Throw<std::ios_base::failure>( "Toolkit", "query::XmlWorker", "ConstructQuery", "invalid selections for selection of var: " + simpleQ.GetVarName()); } } #ifdef NEVER // don't know whether this is useful. pugi::xml_node tsNode = node.child("tstep"); if (tsNode) { std::string startStr = adios2::helper::XMLAttribute("start", tsNode, "in query").value(); std::string countStr = adios2::helper::XMLAttribute("count", tsNode, "in query").value(); if ((startStr.size() > 0) && (countStr.size() > 0)) { std::stringstream ss(startStr), cc(countStr); ss >> simpleQ.m_TimestepStart; cc >> simpleQ.m_TimestepCount; } } #endif pugi::xml_node relationNode = node.child("op"); ConstructTree(simpleQ.m_RangeTree, relationNode); } } // namespace query } // namespace adios2
36.407692
80
0.541728
taniabanerjee
40eae702315e8a8987a648df453c2b8dfc34299c
218
hpp
C++
Factory/include/Factory.hpp
crepuscularlight/DesignPattern
a561e2ff476f86c55f855c87b2ae6d9059be1ed0
[ "MIT" ]
null
null
null
Factory/include/Factory.hpp
crepuscularlight/DesignPattern
a561e2ff476f86c55f855c87b2ae6d9059be1ed0
[ "MIT" ]
null
null
null
Factory/include/Factory.hpp
crepuscularlight/DesignPattern
a561e2ff476f86c55f855c87b2ae6d9059be1ed0
[ "MIT" ]
null
null
null
// // Created by liudiyang1998 on 13.04.21. // #ifndef FACTORY_FACTORY_H #define FACTORY_FACTORY_H #include "LeiFeng.h" class Factory { public: virtual LeiFeng* createLeiFeng()=0; }; #endif //FACTORY_FACTORY_H
13.625
40
0.729358
crepuscularlight
40ed18ed5d8f20d9348cc350e3106ca6e8cb3801
3,686
cpp
C++
src/chrono/physics/ChNodeXYZ.cpp
lucasw/chrono
e79d8c761c718ecb4c796725cff37026f357da8c
[ "BSD-3-Clause" ]
null
null
null
src/chrono/physics/ChNodeXYZ.cpp
lucasw/chrono
e79d8c761c718ecb4c796725cff37026f357da8c
[ "BSD-3-Clause" ]
null
null
null
src/chrono/physics/ChNodeXYZ.cpp
lucasw/chrono
e79d8c761c718ecb4c796725cff37026f357da8c
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Alessandro Tasora, Radu Serban // ============================================================================= #include "chrono/physics/ChNodeXYZ.h" namespace chrono { ChNodeXYZ::ChNodeXYZ() : pos(VNULL), pos_dt(VNULL), pos_dtdt(VNULL) {} ChNodeXYZ::ChNodeXYZ(const ChVector<>& initial_pos) : pos(initial_pos), pos_dt(VNULL), pos_dtdt(VNULL) {} ChNodeXYZ::ChNodeXYZ(const ChNodeXYZ& other) : ChNodeBase(other) { pos = other.pos; pos_dt = other.pos_dt; pos_dtdt = other.pos_dtdt; } ChNodeXYZ& ChNodeXYZ::operator=(const ChNodeXYZ& other) { if (&other == this) return *this; ChNodeBase::operator=(other); pos = other.pos; pos_dt = other.pos_dt; pos_dtdt = other.pos_dtdt; return *this; } void ChNodeXYZ::LoadableGetStateBlock_x(int block_offset, ChState& mD) { mD.segment(block_offset, 3) = pos.eigen(); } void ChNodeXYZ::LoadableGetStateBlock_w(int block_offset, ChStateDelta& mD) { mD.segment(block_offset, 3) = pos_dt.eigen(); } void ChNodeXYZ::LoadableStateIncrement(const unsigned int off_x, ChState& x_new, const ChState& x, const unsigned int off_v, const ChStateDelta& Dv) { NodeIntStateIncrement(off_x, x_new, x, off_v, Dv); } void ChNodeXYZ::LoadableGetVariables(std::vector<ChVariables*>& mvars) { mvars.push_back(&Variables()); }; void ChNodeXYZ::ComputeNF( const double U, // x coordinate of application point in absolute space const double V, // y coordinate of application point in absolute space const double W, // z coordinate of application point in absolute space ChVectorDynamic<>& Qi, // Return result of N'*F here, maybe with offset block_offset double& detJ, // Return det[J] here const ChVectorDynamic<>& F, // Input F vector, size is 3, it is Force x,y,z in absolute coords. ChVectorDynamic<>* state_x, // if != 0, update state (pos. part) to this, then evaluate Q ChVectorDynamic<>* state_w // if != 0, update state (speed part) to this, then evaluate Q ) { // ChVector<> abs_pos(U,V,W); not needed, nodes has no torque. Assuming load is applied to node center ChVector<> absF(F.segment(0, 3)); Qi.segment(0, 3) = absF.eigen(); detJ = 1; // not needed because not used in quadrature. } void ChNodeXYZ::ArchiveOUT(ChArchiveOut& marchive) { // version number marchive.VersionWrite<ChNodeXYZ>(); // serialize parent class ChNodeBase::ArchiveOUT(marchive); // serialize all member data: marchive << CHNVP(pos); marchive << CHNVP(pos_dt); marchive << CHNVP(pos_dtdt); } /// Method to allow de serialization of transient data from archives. void ChNodeXYZ::ArchiveIN(ChArchiveIn& marchive) { // version number /*int version =*/marchive.VersionRead<ChNodeXYZ>(); // deserialize parent class: ChNodeBase::ArchiveIN(marchive); // deserialize all member data: marchive >> CHNVP(pos); marchive >> CHNVP(pos_dt); marchive >> CHNVP(pos_dtdt); } } // end namespace chrono
34.773585
106
0.610147
lucasw
40ede24a47a7e4ef4ea39f532d744d241801d6e5
1,572
cpp
C++
sunglasses/src/Scripting/LuaPrimitives.cpp
jonathanbuchanan/Sunglasses
ab82b66f32650a813234cee8963f9b598ef5c1c8
[ "MIT" ]
1
2016-04-01T02:21:27.000Z
2016-04-01T02:21:27.000Z
sunglasses/src/Scripting/LuaPrimitives.cpp
jonathanbuchanan/Sunglasses
ab82b66f32650a813234cee8963f9b598ef5c1c8
[ "MIT" ]
49
2015-07-08T13:48:06.000Z
2017-06-27T01:40:51.000Z
sunglasses/src/Scripting/LuaPrimitives.cpp
jonathanbuchanan/Sunglasses
ab82b66f32650a813234cee8963f9b598ef5c1c8
[ "MIT" ]
null
null
null
// Copyright 2016 Jonathan Buchanan. // This file is part of Sunglasses, which is licensed under the MIT License. // See LICENSE.md for details. #include <sunglasses/Scripting/LuaPrimitives.h> namespace sunglasses { namespace Scripting { template<> int getFromStack(lua_State *l, int index) { return lua_tointeger(l, index); } template<> double getFromStack(lua_State *l, int index) { return lua_tonumber(l, index); } template<> float getFromStack(lua_State *l, int index) { return (float)lua_tonumber(l, index); } template<> bool getFromStack(lua_State *l, int index) { return lua_toboolean(l, index); } template<> const char * getFromStack(lua_State *l, int index) { return lua_tostring(l, index); } template<> std::string getFromStack(lua_State *l, int index) { return std::string(lua_tostring(l, index)); } template<> void pushToStack(lua_State *l, int value) { lua_pushinteger(l, value); } template<> void pushToStack(lua_State *l, double value) { lua_pushnumber(l, value); } template<> void pushToStack(lua_State *l, float value) { lua_pushnumber(l, (double)value); } template<> void pushToStack(lua_State *l, bool value) { lua_pushboolean(l, value); } template<> void pushToStack(lua_State *l, const char *value) { lua_pushstring(l, value); } template<> void pushToStack(lua_State *l, std::string value) { lua_pushstring(l, value.c_str()); } } } // namespace
26.644068
76
0.646947
jonathanbuchanan
40ef077b8bff8414b22286841a8dfac7dd65deb8
1,649
cc
C++
tensorflow/core/tfrt/utils/error_util_test.cc
ashutom/tensorflow-upstream
c16069c19de9e286dd664abb78d0ea421e9f32d4
[ "Apache-2.0" ]
3
2021-07-24T07:19:49.000Z
2021-07-25T04:04:36.000Z
tensorflow/core/tfrt/utils/error_util_test.cc
ashutom/tensorflow-upstream
c16069c19de9e286dd664abb78d0ea421e9f32d4
[ "Apache-2.0" ]
null
null
null
tensorflow/core/tfrt/utils/error_util_test.cc
ashutom/tensorflow-upstream
c16069c19de9e286dd664abb78d0ea421e9f32d4
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 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/tfrt/utils/error_util.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tfrt/support/error_util.h" #include "tensorflow/core/platform/status.h" namespace tfrt { namespace { TEST(ErrorUtilTest, AllSupportedErrorConversion){ #define ERROR_TYPE(TFRT_ERROR, TF_ERROR) \ { \ tensorflow::Status status(tensorflow::error::TF_ERROR, "error_test"); \ EXPECT_EQ(ConvertTfErrorCodeToTfrtErrorCode(status), \ tfrt::ErrorCode::TFRT_ERROR); \ } #include "tensorflow/core/tfrt/utils/error_type.def" // NOLINT } TEST(ErrorUtilTest, UnsupportedErrorConversion) { tensorflow::Status status(tensorflow::error::UNAUTHENTICATED, "error_test"); EXPECT_EQ(ConvertTfErrorCodeToTfrtErrorCode(status), tfrt::ErrorCode::kUnknown); } } // namespace } // namespace tfrt
38.348837
80
0.654336
ashutom
40f10636b27f3620f1033ad997bb002bb04670da
1,616
cpp
C++
Volume108/10827 - Maximum sum on a torus/10827.cpp
rstancioiu/uva-online-judge
31c536d764462d389b48b4299b9731534824c9f5
[ "MIT" ]
1
2017-01-25T18:07:49.000Z
2017-01-25T18:07:49.000Z
Volume108/10827 - Maximum sum on a torus/10827.cpp
rstancioiu/uva-online-judge
31c536d764462d389b48b4299b9731534824c9f5
[ "MIT" ]
null
null
null
Volume108/10827 - Maximum sum on a torus/10827.cpp
rstancioiu/uva-online-judge
31c536d764462d389b48b4299b9731534824c9f5
[ "MIT" ]
null
null
null
#include <cstdio> #include <iostream> #include <sstream> #include <string> #include <cmath> #include <algorithm> #include <vector> #include <map> #include <queue> #include <set> #define X first #define Y second #define pb push_back #define ii pair<int,int> #define ll long long #define N 128 inline int MIN(int a,int b){return (a>b)?b:a;} inline int MAX(int a,int b){return (a<b)?b:a;} inline int ABS(int a){return (a>0)?a:-a;} using namespace std; int tt,n; int mat[N][N]; int row[N][N]; int col[N][N]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>tt; for(int t=0;t<tt;++t) { cin>>n; for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) cin>>mat[i][j]; for(int i=1;i<=n;++i) row[i][0]=col[0][i]=0; for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) row[i][j]=row[i][j-1]+mat[i][j]; for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) col[i][j]=col[i-1][j]+mat[i][j]; int ans=-0x7fffffff; int total = 0; for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) total+=mat[i][j]; for(int i=1;i<=n;++i) { for(int j=1;j<=n;++j) { int sum3=0; for(int k=j;k<=n;++k) { sum3+=col[n][k]-col[0][k]; int sum1=0; int sum2=0; for(int l=i;l<=n;++l) { sum1+=row[l][k]-row[l][j-1]; sum2+=row[l][n]-row[l][0]; ans = MAX(sum1,ans); if(n!=k || j!=1) { ans = MAX(sum2-sum1,ans); } if(n!=l || i!=1) { ans = MAX(sum3-sum1,ans); } if((n!=k || j!=1) && (n!=l || i!=1)) { ans=MAX(total-sum3-sum2+sum1,ans); } } } } } cout<<ans<<"\n"; } return 0; }
18.363636
46
0.502475
rstancioiu
40f14e72764036e435e6ed78ad0b700bcb9b7d46
4,773
hh
C++
src/Distributed/VoronoiRedistributeNodes.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/Distributed/VoronoiRedistributeNodes.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/Distributed/VoronoiRedistributeNodes.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // VoronoiRedistributeNodes // // This algorithm uses the Voronoi tessellation to decide how to domain // decompose our points. The idea is to relax a set of generator points into // the SPH node distribution -- the generators are attracted to the SPH points // repelled by one and other. These generator points then become the seeds to // draw the Voronoi tessellation about, each cell of which then represents a // computational domain. // // Created by JMO, Fri Jan 15 09:56:56 PST 2010 //----------------------------------------------------------------------------// #ifndef VoronoiRedistributeNodes_HH #define VoronoiRedistributeNodes_HH #include "RedistributeNodes.hh" #include "Utilities/KeyTraits.hh" #include <vector> #include <map> #ifdef USE_MPI #include <mpi.h> #endif namespace Spheral { template<typename Dimension> class DataBase; template<typename Dimension> class NodeList; template<typename Dimension> class Boundary; template<typename Dimension> class VoronoiRedistributeNodes: public RedistributeNodes<Dimension> { public: //--------------------------- Public Interface ---------------------------// typedef typename Dimension::Scalar Scalar; typedef typename Dimension::Vector Vector; typedef typename Dimension::Tensor Tensor; typedef typename Dimension::SymTensor SymTensor; typedef KeyTraits::Key Key; // Constructors VoronoiRedistributeNodes(const double dummy, const bool workBalance, const bool balanceGenerators, const double tolerance, const unsigned maxIterations); // Destructor virtual ~VoronoiRedistributeNodes(); // Given a Spheral++ data base of NodeLists, repartition it among the processors. // This is the method required of all descendent classes. virtual void redistributeNodes(DataBase<Dimension>& dataBase, std::vector<Boundary<Dimension>*> boundaries = std::vector<Boundary<Dimension>*>()) override; // Given the set of DomainNodes with their domain assignments, compute the // (work weighted) domain centroids. void computeCentroids(const std::vector<DomainNode<Dimension> >& nodes, std::vector<Vector>& generators) const; // Assign the nodes to the given generator positions, simultaneously computing the total // generator work load. void assignNodesToGenerators(const std::vector<Vector>& generators, const std::vector<int>& generatorFlags, std::vector<double>& generatorWork, std::vector<DomainNode<Dimension> >& nodes, double& minWork, double& maxWork, unsigned& minNodes, unsigned& maxNodes) const; // Look for any generator that has too much work, and unassign it's most // distant nodes. void cullGeneratorNodesByWork(const std::vector<Vector>& generators, const std::vector<double>& generatorWork, const double targetWork, std::vector<int>& generatorFlags, std::vector<DomainNode<Dimension> >& nodes) const; // Find the adjacent generators in the Voronoi diagram. std::vector<size_t> findNeighborGenerators(const size_t igen, const std::vector<Vector>& generators) const; // Flag for whether we should compute the work per node or strictly balance by // node count. bool workBalance() const; void workBalance(bool val); // Should we try to work balance between generators? // node count. bool balanceGenerators() const; void balanceGenerators(bool val); // The tolerance we're using to check for convergence of the generators. double tolerance() const; void tolerance(double val); // The maximum number of iterations to try and converge the generator positions. unsigned maxIterations() const; void maxIterations(unsigned val); private: //--------------------------- Private Interface ---------------------------// bool mWorkBalance, mBalanceGenerators; double mTolerance; unsigned mMaxIterations; // No copy or assignment operations. VoronoiRedistributeNodes(const VoronoiRedistributeNodes& nodes); VoronoiRedistributeNodes& operator=(const VoronoiRedistributeNodes& rhs); }; } #else // Forward declare the VoronoiRedistributeNodes class. namespace Spheral { template<typename Dimension> class VoronoiRedistributeNodes; } #endif
38.184
90
0.635659
jmikeowen
40f1d837ef4f8597647e34528cac584fa16008e2
2,118
hpp
C++
include/toy/memory/Allocator01.hpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
4
2017-07-06T22:18:41.000Z
2021-05-24T21:28:37.000Z
include/toy/memory/Allocator01.hpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
null
null
null
include/toy/memory/Allocator01.hpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
1
2020-08-02T13:00:38.000Z
2020-08-02T13:00:38.000Z
#pragma once #include <cstdlib> #include <cstring> #include "toy/Math.hpp" namespace toy{ namespace memory{ // The memory size of Allocator01 always base of 2. template<typename T> class Allocator01 { public: Allocator01() { ; } ~Allocator01() { free(); } Allocator01(const Allocator01 &other) { copy_mykind(const_cast<Allocator01&>(other)); } Allocator01 operator = (const Allocator01 &other) { copy_mykind(const_cast<Allocator01&>(other)); return *this; } T* allocate(std::size_t n) { (void)n; } void deallocate(T* p, std::size_t n) { (void)n; (void)p; } private: bool copy(void *p,size_t s) { size(s); std::memcpy(_data,p,s); return 1; } void free() { if(_data) { std::free(_data); _data = nullptr; _size = 0; _trueSize = 0; } } // Allocate memory for user. bool size(size_t s) { _size = s; if ( s>_trueSize ) { size_t new_size = ::toy::math::Exp1<size_t>(s); if ( _data==nullptr ) { _data = std::malloc(new_size); } else { _data = std::realloc(_data,new_size); } _trueSize = new_size; } return 1; } // Allocate memory for user, and release the memory unused. bool fitSize(size_t s) { _size = s; size_t new_size = ::toy::math::Exp1<size_t>(s); if ( new_size>_trueSize ) { if(_data==nullptr) { _data = std::malloc(new_size); } else { _data = std::realloc(_data,new_size); } _trueSize = new_size; } else if ( new_size<_trueSize ) { _data = std::realloc(_data,new_size); _trueSize = new_size; } return 1; } void* data() const { return _data; } size_t size() const { return _size; } void* _data = nullptr; std::size_t _size = 0; std::size_t _trueSize = 0; inline void copy_mykind(Allocator01 &other) { free(); _size = other._size; _trueSize = other._trueSize; _data = std::malloc(_trueSize); std::memcpy(_data,other._data,_size); } }; }//namespace memory }//namespace toy
14.408163
61
0.580264
ToyAuthor
40f2d4edc294a2c8d6ce2e049e487625902b155e
1,488
cpp
C++
src/utils/random.cpp
Thanduriel/func-renderer
99582272d8e34cb6e2f6bc9735c8eba5076bb29c
[ "MIT" ]
1
2019-01-27T17:54:45.000Z
2019-01-27T17:54:45.000Z
src/utils/random.cpp
Thanduriel/func-renderer
99582272d8e34cb6e2f6bc9735c8eba5076bb29c
[ "MIT" ]
null
null
null
src/utils/random.cpp
Thanduriel/func-renderer
99582272d8e34cb6e2f6bc9735c8eba5076bb29c
[ "MIT" ]
null
null
null
#include "random.hpp" #include <assert.h> namespace Util{ Random::Random(uint32_t _seed) { m_state[0] = 0xaffeaffe ^ _seed; m_state[1] = 0xf9b2a750 ^ (_seed * 0x804c8a24 + 0x68f699be); m_state[2] = 0x485eac66 ^ (_seed * 0x0fe56638 + 0xc917c8ce); m_state[3] = 0xcbd02714 ^ (_seed * 0x57571dae + 0xce2b3bd1); // Warmup Xorshift128(); Xorshift128(); Xorshift128(); Xorshift128(); } // ********************************************************************* // float Random::uniform(float _min, float _max) { double scale = (_max - _min) / 0xffffffff; return float(_min + scale * Xorshift128()); } // ********************************************************************* // int32_t Random::uniform(int32_t _min, int32_t _max) { uint32_t interval = uint32_t(_max - _min + 1); assert(interval != 0 && "Do not use integer maximum bounds!"); uint32_t value = Xorshift128(); return _min + value % interval; } // ********************************************************************* // Math::ArgVec<float, 2> Random::vector() { // Math::ArgVec<float, 2> vec; return Math::AVec2(uniform(-1.f,1.f), uniform(-1.f, 1.f)); } // ********************************************************************* // uint32_t Random::Xorshift128() { uint32_t tmp = m_state[0] ^ (m_state[0] << 11); m_state[0] = m_state[1]; m_state[1] = m_state[2]; m_state[2] = m_state[3]; m_state[3] ^= (m_state[3] >> 19) ^ tmp ^ (tmp >> 8); return m_state[3]; } }
27.054545
76
0.508065
Thanduriel
40f5ed080c871109c885e4cd200331d257b41c20
10,502
cpp
C++
Hercules0.1/src/Hercules/Scene/Level/LevelManager.cpp
CletusG/Hercules-Engine
d2e2e5a04b5149fd7779f7a1598070593fcc574d
[ "Apache-2.0" ]
null
null
null
Hercules0.1/src/Hercules/Scene/Level/LevelManager.cpp
CletusG/Hercules-Engine
d2e2e5a04b5149fd7779f7a1598070593fcc574d
[ "Apache-2.0" ]
null
null
null
Hercules0.1/src/Hercules/Scene/Level/LevelManager.cpp
CletusG/Hercules-Engine
d2e2e5a04b5149fd7779f7a1598070593fcc574d
[ "Apache-2.0" ]
null
null
null
#include "hcpch.h" #include "LevelManager.h" namespace Hercules { LevelData levelData; const void Hercules::LevelManager::OpenLevel(const char* levelPath, std::string projectPath) { HC_STAT("Opening {0}", levelPath); levelData.matColors.clear(); levelData.matShinies.clear(); SceneManager::GetEntites().clear(); SceneManager::GetTransformComponentList().clear(); SceneManager::GetLightComponentList().clear(); SceneManager::GetDemoComponentList().clear(); SceneManager::GetMeshComponentList().clear(); SceneManager::GetDirectionalLightList().clear(); SceneManager::GetPointLightList().clear(); SceneManager::GetSpotLightList().clear(); SceneManager::GetMaterialComponentList().clear(); SceneManager::GetTextureList().clear(); std::string line; std::ifstream levelFile(levelPath); int lineNR = 1; unsigned int id = 1; std::string delimiter = "#"; std::string colon = ":"; std::string pos = "P"; std::string rot = "R"; std::string scale = "S"; std::string color = "C"; std::string tex = "T"; std::string shiny = "H"; std::string mesh = "V"; std::string mat = "M"; //Read materials HC_CORE_STAT("Loading materials..."); for (auto& i : std::filesystem::directory_iterator(projectPath + "Assets/Materials")) { std::string path = i.path().string(); std::ifstream material(path); std::string name = ""; bool currentType = 0; while (std::getline(material, line)) { if (line.find(delimiter) != std::string::npos) { line.erase(0, line.find(delimiter) + delimiter.length()); currentType = std::stoi(line); } else if (line.find(tex) != std::string::npos) { line.erase(0, line.find(tex) + tex.length()); name = i.path().filename().string().substr(0, i.path().filename().string().find(".")); std::string path = projectPath + line; SceneManager::NewTexture(name, path.c_str(), currentType); } else if (line.find(color) != std::string::npos) { if (line.substr(0, 1) == color) { line.erase(0, line.find(color) + color.length()); std::string r = line.substr(0, line.find("r")); line.erase(0, line.find("r") + color.length()); std::string g = line.substr(0, color.find("g")); line.erase(0, line.find("g") + color.length()); std::string b = line.substr(0, line.find("b")); levelData.matColors.insert(std::pair<std::string, glm::vec3> (name, glm::vec3(std::stof(r), std::stof(g), std::stof(b)))); } } else if (line.find(shiny) != std::string::npos) { if (line.substr(0, 1) == shiny) { line.erase(0, line.find(shiny) + shiny.length()); levelData.matShinies.insert(std::pair<std::string, float>(name, std::stof(line))); } } } } HC_CORE_SUCCESS("Materials loaded"); //Read level file HC_CORE_STAT("Loading {0}...", levelPath); while (std::getline(levelFile, line)) { if (line.find(delimiter) != std::string::npos) { line.erase(0, line.find(delimiter) + delimiter.length()); std::string name = line.substr(0, line.find(colon)); line.erase(0, line.find(colon) + colon.length()); id = std::stoi(line.substr(0, line.find(colon))); SceneManager::NewEntity(name); } else if (line.find(pos) != std::string::npos) { if (line.substr(0, 1) == pos) { //Position line.erase(0, line.find(pos) + pos.length()); std::string px = line.substr(0, line.find("x")); line.erase(0, line.find("x") + pos.length()); std::string py = line.substr(0, line.find("y")); line.erase(0, line.find("y") + pos.length()); std::string pz = line.substr(0, line.find("z")); //Scale line.erase(0, line.find(scale) + scale.length()); std::string sx = line.substr(0, line.find("x")); line.erase(0, line.find("x") + scale.length()); std::string sy = line.substr(0, line.find("y")); line.erase(0, line.find("y") + scale.length()); std::string sz = line.substr(0, line.find("z")); //Rotation line.erase(0, line.find(rot) + rot.length()); std::string rx = line.substr(0, line.find("x")); line.erase(0, line.find("x") + rot.length()); std::string ry = line.substr(0, line.find("y")); line.erase(0, line.find("y") + rot.length()); std::string rz = line.substr(0, line.find("z")); SceneManager::NewComponent(TransformComponent(glm::vec3(std::stof(px), std::stof(py), std::stof(pz)), glm::vec3(std::stof(sx), std::stof(sy), std::stof(sz)), glm::vec3(std::stof(rx), std::stof(ry), std::stof(rz))), SceneManager::GetEntites().size()); } } else if (line.find("DL") != std::string::npos) { SceneManager::NewComponent(DirectionalLight(), id); } else if (line.find("T") != std::string::npos) { SceneManager::NewComponent(DemoComponent(), id); } if (line.find(mesh) != std::string::npos) { if (line.substr(0, 1) == mesh) { line.erase(0, line.find(mesh) + mesh.length()); SceneManager::NewComponent(MeshComponent(projectPath + line), id); } } if (line.find(mat) != std::string::npos) { if (line.substr(0, 1) == mat) { line.erase(0, line.find(mat) + mat.length()); std::string m = line.substr(0, line.find(mat)); SceneManager::NewComponent(MaterialComponent( SceneManager::GetTexture(m.c_str()), *GetColor(m)), id); SceneManager::GetMaterialComponent(id)->SetName(m); } } if (line.find(color) != std::string::npos) { if (line.substr(0, 1) == color) { line.erase(0, line.find(color) + color.length()); std::string r = line.substr(0, line.find("r")); line.erase(0, line.find("r") + color.length()); std::string g = line.substr(0, color.find("g")); line.erase(0, line.find("g") + color.length()); std::string b = line.substr(0, line.find("b")); SceneManager::GetMaterialComponent(id)->SetColor(glm::vec3( std::stof(r), std::stof(g), std::stof(b))); } } if (line.find(shiny) != std::string::npos) { if (line.substr(0, 1) == shiny) { line.erase(0, line.find(shiny) + shiny.length()); SceneManager::GetMaterialComponent(id)->SetShininess(std::stof(line)); } } } levelFile.close(); HC_CORE_SUCCESS("{0} loaded", levelPath); //ProcessMaterials(levelPath); } void LevelManager::ProcessMaterials(const char* levelPath) { std::ifstream levelFile(levelPath); std::string line; std::string mat = "M"; std::string delimiter = "#"; std::string colon = ":"; std::string color = "C"; std::string shiny = "H"; unsigned int id = 0; while (std::getline(levelFile, line)) { if (line.find(delimiter) != std::string::npos) { line.erase(0, line.find(delimiter) + delimiter.length()); line.erase(0, line.find(colon) + colon.length()); id = std::stoi(line.substr(0, line.find(colon))); } else if (line.find(mat) != std::string::npos) { if (line.substr(0, 1) == mat) { line.erase(0, line.find(mat) + mat.length()); std::string m = line.substr(0, line.find(mat)); SceneManager::NewComponent(MaterialComponent( SceneManager::GetTexture(m.c_str()), *GetColor(m)), id); SceneManager::GetMaterialComponent(id)->SetName(m); } } else if (line.find(color) != std::string::npos) { line.erase(0, line.find(color) + color.length()); std::string r = line.substr(0, line.find("r")); line.erase(0, line.find("r") + color.length()); std::string g = line.substr(0, color.find("g")); line.erase(0, line.find("g") + color.length()); std::string b = line.substr(0, line.find("b")); SceneManager::GetMaterialComponent(id)->SetColor(glm::vec3( std::stof(r), std::stof(g), std::stof(b))); } else if (line.find(shiny) != std::string::npos) { if (line.substr(0, 1) == shiny) { line.erase(0, line.find(shiny) + shiny.length()); SceneManager::GetMaterialComponent(id)->SetShininess(std::stof(line)); } } } } //Saving level const void LevelManager::WriteLevel(const char* levelPath, std::string projectPath) { std::fstream file_out; file_out.open(levelPath, std::ios::out); if (!file_out.is_open()) { HC_CORE_ERROR("Failed to open level"); } else { for (auto &i : SceneManager::GetEntites()) { TransformComponent t = *SceneManager::GetTransformComponent(i.first); //Every entity will have a transform file_out << "\n#" << i.second << ":" << i.first << std::endl; file_out << "P" << t.GetPos().x << "x" << t.GetPos().y << "y" << t.GetPos().z << "z" << "S" << t.GetScale().x << "x" << t.GetScale().y << "y" << t.GetScale().z << "z" << "R" << t.GetRotation().x << "x" << t.GetRotation().y << "y" << t.GetRotation().z << "z" << std::endl; if (SceneManager::HasDirectionalLight(i.first)) file_out << "DL" << std::endl; if (SceneManager::HasTestComponent(i.first)) file_out << "T" << std::endl; if (SceneManager::HasMaterialComponent(i.first)) { file_out << "M" << SceneManager::GetMaterialComponent(i.first)->GetName() << std::endl; file_out << "H" << SceneManager::GetMaterialComponent(i.first)->GetShininess() << std::endl; file_out << "C" << SceneManager::GetMaterialComponent(i.first)->GetColor().x << "r" << SceneManager::GetMaterialComponent(i.first)->GetColor().y << "g" << SceneManager::GetMaterialComponent(i.first)->GetColor().z << "b" << std::endl; } if (SceneManager::HasMeshComponent(i.first)) { std::string relativePath = SceneManager::GetMeshComponent(i.first)->GetPath(); std::string absolutePath = relativePath.erase(0, relativePath.find(projectPath) + projectPath.length()); HC_CORE_INFO(absolutePath); file_out << "V" << absolutePath << std::endl; } } HC_CORE_SUCCESS("{0} Saved succesfully!", levelPath); } file_out.close(); } const void LevelManager::NewLevel(std::string levelName) { std::string path = "Levels/" + levelName + ".hclvl"; std::ofstream file_out(path); HC_CORE_SUCCESS("New Level: {0}", path); } glm::vec3* LevelManager::GetColor(std::string name) { for (auto& i : levelData.matColors) { if (i.first == name) { return &i.second; } } } float* LevelManager::GetShininess(std::string name) { for (auto& i : levelData.matShinies) { if (i.first == name) { return &i.second; } } } }
30.618076
109
0.602838
CletusG
40f6fe7c97ebc4db67dacb0954972a09f8d8e217
2,460
cpp
C++
WebKit/Source/WebKit/qt/WebCoreSupport/InitWebCoreQt.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
1
2019-06-18T06:52:54.000Z
2019-06-18T06:52:54.000Z
WebKit/Source/WebKit/qt/WebCoreSupport/InitWebCoreQt.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
null
null
null
WebKit/Source/WebKit/qt/WebCoreSupport/InitWebCoreQt.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2011 Hewlett-Packard Development Company, L.P. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Hewlett-Packard 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 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER 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 "config.h" #include "InitWebCoreQt.h" #include "NotImplemented.h" #include "PlatformStrategiesQt.h" #include "ScriptController.h" #include "SecurityPolicy.h" #if USE(QTKIT) #include "WebSystemInterface.h" #endif #include "qwebelement_p.h" #include <runtime/InitializeThreading.h> #include <wtf/MainThread.h> namespace WebCore { void initializeWebCoreQt() { static bool initialized = false; if (initialized) return; WebCore::initializeLoggingChannelsIfNecessary(); ScriptController::initializeThreading(); WTF::initializeMainThread(); WebCore::SecurityPolicy::setLocalLoadPolicy(WebCore::SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData); PlatformStrategiesQt::initialize(); QtWebElementRuntime::initialize(); #if USE(QTKIT) InitWebCoreSystemInterface(); #endif initialized = true; } }
35.142857
115
0.761789
JavaScriptTesting
40f7c05a1763be34013bda382217301232b50fe7
3,949
cpp
C++
TemplePlus/fixes/light_load.cpp
edoipi/TemplePlus
f0e552289822fea908f16daa379fa568b1bd286d
[ "MIT" ]
69
2015-05-05T14:09:25.000Z
2022-02-15T06:13:04.000Z
TemplePlus/fixes/light_load.cpp
edoipi/TemplePlus
f0e552289822fea908f16daa379fa568b1bd286d
[ "MIT" ]
457
2015-05-01T22:07:45.000Z
2022-03-31T02:19:10.000Z
TemplePlus/fixes/light_load.cpp
edoipi/TemplePlus
f0e552289822fea908f16daa379fa568b1bd286d
[ "MIT" ]
25
2016-02-04T21:19:53.000Z
2021-11-15T23:14:51.000Z
#include "stdafx.h" #include "util/fixes.h" #include <obj.h> #include <temple_functions.h> #include "gamesystems/timeevents.h" #include <particles.h> #include <gamesystems/gamesystems.h> #include <gamesystems/map/sector.h> #include <gamesystems/particlesystems.h> /* This is the fix for bug #104, which causes particle systems to be duplicated when a diff file for a sector is loaded alongside the sector. ToEE first reads the light from the original sector @ 0x101063C3, apparently to get it's position. Then it reads the light from the diff file @ 0x10106452, *without* freeing the first light. This means the memory of the first light leaks (miniscule) and the particle systems created in the load function will also leak (major issue). The correct solution would be to a) free the light and b) not even create the particle systems in the first load function. This fix will simply free the light and kill the particle systems in the load-light-from-diff function as a quick fix. */ struct TioFile; // Fix for duplicate particle systems static class SectorLoadLightFix : TempleFix { public: void apply() override; private: static int ReadLight(TioFile* file, SectorLight** lightOut); static int ReadLightFromDiff(TioFile* file, SectorLight** lightOut); static int (*OrgReadLightFromDiff)(TioFile*, SectorLight**); static int (*OrgReadLight)(TioFile*, SectorLight**); } sectorCacheFix; int (*SectorLoadLightFix::OrgReadLightFromDiff)(TioFile*, SectorLight**); int (*SectorLoadLightFix::OrgReadLight)(TioFile*, SectorLight**); void SectorLoadLightFix::apply() { OrgReadLightFromDiff = replaceFunction(0x100A8050, ReadLightFromDiff); OrgReadLight = replaceFunction(0x100A6890, ReadLight); } int SectorLoadLightFix::ReadLight(TioFile* file, SectorLight** lightOut) { auto &particles = gameSystems->GetParticleSys(); SectorLight light; if (tio_fread(&light, 0x40, 1u, file) != 1) return 0; auto lightPos = light.position.ToInches3D(light.offsetZ); SectorLight *realLight; if (light.flags & 0x10) { realLight = (SectorLight *)malloc(0x48u); memcpy(realLight, &light, 0x40); if (tio_fread(&realLight->partSys, 8u, 1u, file) != 1) return 0; if (realLight->partSys.hashCode) { realLight->partSys.handle = particles.CreateAt(realLight->partSys.hashCode, lightPos); } else { realLight->partSys.handle = 0; } } else if (light.flags & 0x40) { realLight = (SectorLight *)malloc(0xB0u); memcpy(realLight, &light, 0x40); if (tio_fread(&realLight->partSys, 8u, 1u, file) != 1) return 0; if (tio_fread(&realLight->light2, 0x24u, 1u, file) != 1) return 0; // reset the handles so whatever the on-disk sector may say, the particle systems are not running realLight->partSys.handle = 0; realLight->light2.partSys.handle = 0; static auto& sIsNight = temple::GetRef<BOOL>(0x10B5DC80); SectorLightPartSys *partSys; if (sIsNight) { partSys = &realLight->light2.partSys; } else { partSys = &realLight->partSys; } if (partSys->hashCode) { partSys->handle = particles.CreateAt(partSys->hashCode, lightPos); } } else { realLight = (SectorLight *)malloc(0x40u); memcpy(realLight, &light, 0x40); } *lightOut = realLight; return 1; } int SectorLoadLightFix::ReadLightFromDiff(TioFile* file, SectorLight** lightOut) { auto& particles = gameSystems->GetParticleSys(); /* ToEE would let the light read from the original sector file leak, so we take care of it here and destroy the light and the particle systems that might have been created. */ auto lightOrg = *lightOut; if (lightOrg) { if (lightOrg->flags & 0x50) { auto partSys1 = lightOrg->partSys; if (partSys1.handle) { particles.Remove(partSys1.handle); } } if (lightOrg->flags & 0x40) { auto partSys2 = lightOrg->light2.partSys; if (partSys2.handle) { particles.Remove(partSys2.handle); } } free(lightOrg); } return ReadLight(file, lightOut); }
29.470149
99
0.72474
edoipi
40f99ccf7408edf201d3985d87537b535ed68eac
1,761
ipp
C++
implement/oglplus/enums/object_type_names.ipp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
implement/oglplus/enums/object_type_names.ipp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
implement/oglplus/enums/object_type_names.ipp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
// File implement/oglplus/enums/object_type_names.ipp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/object_type.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2017 Matus Chochlik. // 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 // namespace enums { OGLPLUS_LIB_FUNC StrCRef ValueName_( ObjectType*, GLenum value ) #if (!OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)) && \ !defined(OGLPLUS_IMPL_EVN_OBJECTTYPE) #define OGLPLUS_IMPL_EVN_OBJECTTYPE { switch(value) { #if defined GL_BUFFER case GL_BUFFER: return StrCRef("BUFFER"); #endif #if defined GL_FRAMEBUFFER case GL_FRAMEBUFFER: return StrCRef("FRAMEBUFFER"); #endif #if defined GL_PROGRAM_PIPELINE case GL_PROGRAM_PIPELINE: return StrCRef("PROGRAM_PIPELINE"); #endif #if defined GL_PROGRAM case GL_PROGRAM: return StrCRef("PROGRAM"); #endif #if defined GL_QUERY case GL_QUERY: return StrCRef("QUERY"); #endif #if defined GL_RENDERBUFFER case GL_RENDERBUFFER: return StrCRef("RENDERBUFFER"); #endif #if defined GL_SAMPLER case GL_SAMPLER: return StrCRef("SAMPLER"); #endif #if defined GL_SHADER case GL_SHADER: return StrCRef("SHADER"); #endif #if defined GL_TEXTURE case GL_TEXTURE: return StrCRef("TEXTURE"); #endif #if defined GL_TRANSFORM_FEEDBACK case GL_TRANSFORM_FEEDBACK: return StrCRef("TRANSFORM_FEEDBACK"); #endif #if defined GL_VERTEX_ARRAY case GL_VERTEX_ARRAY: return StrCRef("VERTEX_ARRAY"); #endif #if defined GL_NONE case GL_NONE: return StrCRef("NONE"); #endif default:; } OGLPLUS_FAKE_USE(value); return StrCRef(); } #else ; #endif } // namespace enums
25.521739
73
0.776263
jnbrq
40fb78161ebbab40e852536757f7d8380de74454
118,110
cpp
C++
private/parser.cpp
kociap/vush2
4002afb9c86638ff9882a44b1010a13348eed664
[ "MIT" ]
6
2021-04-27T22:17:30.000Z
2021-12-31T12:42:44.000Z
private/parser.cpp
kociap/vush2
4002afb9c86638ff9882a44b1010a13348eed664
[ "MIT" ]
1
2021-05-11T10:50:52.000Z
2021-05-11T10:50:52.000Z
private/parser.cpp
kociap/vush2
4002afb9c86638ff9882a44b1010a13348eed664
[ "MIT" ]
null
null
null
#include <parser.hpp> #include <anton/optional.hpp> #include <anton/string7_stream.hpp> #include <anton/string7_view.hpp> // TODO: When matching keywords, ensure that the keyword is followed by non-identifier character (Find a cleaner way). // TODO: Figure out a way to match operators that use overlapping symbols (+ and +=) in a clean way. // TODO: const types. // TODO: add constructors (currently function call which will break if we use an array type). namespace vush { using namespace anton::literals; // keywords static constexpr anton::String7_View kw_if = u8"if"; static constexpr anton::String7_View kw_else = u8"else"; static constexpr anton::String7_View kw_switch = u8"switch"; static constexpr anton::String7_View kw_case = u8"case"; static constexpr anton::String7_View kw_default = u8"default"; static constexpr anton::String7_View kw_for = u8"for"; static constexpr anton::String7_View kw_while = u8"while"; static constexpr anton::String7_View kw_do = u8"do"; static constexpr anton::String7_View kw_return = u8"return"; static constexpr anton::String7_View kw_break = u8"break"; static constexpr anton::String7_View kw_continue = u8"continue"; static constexpr anton::String7_View kw_discard = u8"discard"; static constexpr anton::String7_View kw_true = u8"true"; static constexpr anton::String7_View kw_false = u8"false"; static constexpr anton::String7_View kw_from = u8"from"; static constexpr anton::String7_View kw_struct = u8"struct"; static constexpr anton::String7_View kw_import = u8"import"; static constexpr anton::String7_View kw_const = u8"const"; static constexpr anton::String7_View kw_settings = u8"settings"; static constexpr anton::String7_View kw_reinterpret = u8"reinterpret"; static constexpr anton::String7_View kw_invariant = u8"invariant"; static constexpr anton::String7_View kw_smooth = u8"smooth"; static constexpr anton::String7_View kw_flat = u8"flat"; static constexpr anton::String7_View kw_noperspective = u8"noperspective"; // attributes static constexpr anton::String7_View attrib_workgroup = u8"workgroup"; // stages static constexpr anton::String7_View stage_vertex = u8"vertex"; static constexpr anton::String7_View stage_fragment = u8"fragment"; static constexpr anton::String7_View stage_compute = u8"compute"; // separators and operators static constexpr anton::String7_View token_brace_open = u8"{"; static constexpr anton::String7_View token_brace_close = u8"}"; static constexpr anton::String7_View token_bracket_open = u8"["; static constexpr anton::String7_View token_bracket_close = u8"]"; static constexpr anton::String7_View token_paren_open = u8"("; static constexpr anton::String7_View token_paren_close = u8")"; static constexpr anton::String7_View token_angle_open = u8"<"; static constexpr anton::String7_View token_angle_close = u8">"; static constexpr anton::String7_View token_semicolon = u8";"; static constexpr anton::String7_View token_colon = u8":"; static constexpr anton::String7_View token_scope_resolution = u8"::"; static constexpr anton::String7_View token_arrow = u8"=>"; static constexpr anton::String7_View token_comma = u8","; // static constexpr anton::String7_View token_question = u8"?"; static constexpr anton::String7_View token_dot = u8"."; static constexpr anton::String7_View token_double_quote = u8"\""; static constexpr anton::String7_View token_plus = u8"+"; static constexpr anton::String7_View token_minus = u8"-"; static constexpr anton::String7_View token_multiply = u8"*"; static constexpr anton::String7_View token_divide = u8"/"; static constexpr anton::String7_View token_remainder = u8"%"; static constexpr anton::String7_View token_logic_and = u8"&&"; static constexpr anton::String7_View token_bit_and = u8"&"; static constexpr anton::String7_View token_logic_or = u8"||"; static constexpr anton::String7_View token_logic_xor = u8"^^"; static constexpr anton::String7_View token_bit_or = u8"|"; static constexpr anton::String7_View token_bit_xor = u8"^"; static constexpr anton::String7_View token_logic_not = u8"!"; static constexpr anton::String7_View token_bit_not = u8"~"; static constexpr anton::String7_View token_bit_lshift = u8"<<"; static constexpr anton::String7_View token_bit_rshift = u8">>"; static constexpr anton::String7_View token_equal = u8"=="; static constexpr anton::String7_View token_not_equal = u8"!="; static constexpr anton::String7_View token_less = u8"<"; static constexpr anton::String7_View token_greater = u8">"; static constexpr anton::String7_View token_less_equal = u8"<="; static constexpr anton::String7_View token_greater_equal = u8">="; static constexpr anton::String7_View token_assign = u8"="; static constexpr anton::String7_View token_increment = u8"++"; static constexpr anton::String7_View token_decrement = u8"--"; static constexpr anton::String7_View token_compound_plus = u8"+="; static constexpr anton::String7_View token_compound_minus = u8"-="; static constexpr anton::String7_View token_compound_multiply = u8"*="; static constexpr anton::String7_View token_compound_divide = u8"/="; static constexpr anton::String7_View token_compound_remainder = u8"%="; static constexpr anton::String7_View token_compound_bit_and = u8"&="; static constexpr anton::String7_View token_compound_bit_or = u8"|="; static constexpr anton::String7_View token_compound_bit_xor = u8"^="; static constexpr anton::String7_View token_compound_bit_lshift = u8"<<="; static constexpr anton::String7_View token_compound_bit_rshift = u8">>="; [[nodiscard]] static bool is_whitespace(char32 c) { return (c <= 32) | (c == 127); } [[nodiscard]] static bool is_binary_digit(char32 c) { return c == 48 || c == 49; } [[nodiscard]] static bool is_hexadecimal_digit(char32 c) { return (c >= 48 && c <= 57) || (c >= 65 && c <= 70) || (c >= 97 && c <= 102); } [[nodiscard]] static bool is_octal_digit(char32 c) { return c >= 48 && c <= 55; } [[nodiscard]] static bool is_digit(char32 c) { return c >= 48 && c <= 57; } [[nodiscard]] static bool is_alpha(char32 c) { return (c >= 97 && c < 123) || (c >= 65 && c < 91); } [[nodiscard]] static bool is_first_identifier_character(char32 c) { return c == '_' || is_alpha(c); } [[nodiscard]] static bool is_identifier_character(char32 c) { return c == '_' || is_digit(c) || is_alpha(c); } [[nodiscard]] static bool is_keyword(anton::String_View string) { static constexpr anton::String7_View keywords[] = { kw_if, kw_else, kw_switch, kw_case, kw_default, kw_for, kw_while, kw_do, kw_return, kw_break, kw_continue, kw_discard, kw_true, kw_false, kw_from, kw_struct, kw_import, kw_const, kw_settings, kw_reinterpret, }; anton::String7_View string7{string.bytes_begin(), string.bytes_end()}; constexpr i64 array_size = sizeof(keywords) / sizeof(anton::String7_View); for(anton::String7_View const *i = keywords, *end = keywords + array_size; i != end; ++i) { if(*i == string7) { return true; } } return false; } class Lexer_State { public: i64 stream_offset; i64 line; i64 column; }; constexpr char8 eof_char8 = (char8)EOF; constexpr char32 eof_char32 = (char32)EOF; // TODO: Place this comment somewhere // The source string is ASCII only, so String7 will be the exact same size as String, // but String7 will avoid all Unicode function calls and thus accelerate parsing. class Lexer { public: Lexer(anton::String_View source): _begin(source.bytes_begin()), _end(source.bytes_end()), _current(source.bytes_begin()) {} bool match(anton::String7_View const string, bool const must_not_be_followed_by_identifier_char = false) { Lexer_State const state_backup = get_current_state(); for(char8 c: string) { if(_current != _end && *_current == c) { ++_current; ++_column; } else { restore_state(state_backup); return false; } } if(must_not_be_followed_by_identifier_char) { char32 const c = peek_next(); if(is_identifier_character(c)) { restore_state(state_backup); return false; } else { return true; } } else { return true; } } bool match_identifier(anton::String& out) { ignore_whitespace_and_comments(); if(_current != _end && !is_first_identifier_character(*_current)) { return false; } char8 const* identifier_end = _current + 1; while(identifier_end != _end && is_identifier_character(*identifier_end)) { ++identifier_end; } out += anton::String_View{_current, identifier_end}; _column += identifier_end - _current; _current = identifier_end; return true; } bool match_eof() { ignore_whitespace_and_comments(); return _current == _end || *_current == eof_char8; } void ignore_whitespace_and_comments() { while(true) { while(_current != _end && is_whitespace(*_current)) { if(*_current == '\n') { _line += 1; _column = 1; } else { ++_column; } ++_current; } if(_current != _end && *_current == '/' && _current + 1 != _end) { char32 const next_char = *(_current + 1); if(next_char == U'/') { for(; _current != _end && *_current != '\n'; ++_current) {} // The loop stops at the newline. Skip the newline. _current += 1; _line += 1; _column = 1; continue; } else if(next_char == U'*') { _current += 2; _column += 2; for(char32 c1 = get_next(), c2 = peek_next(); c1 != U'*' || c2 != U'/'; c1 = get_next(), c2 = peek_next()) {} get_next(); continue; } else { // Not a comment. End skipping. break; } } break; } } Lexer_State get_current_state() { ignore_whitespace_and_comments(); return {_current - _begin, _line, _column}; } Lexer_State get_current_state_no_skip() { return {_current - _begin, _line, _column}; } void restore_state(Lexer_State const state) { _current = _begin + state.stream_offset; _line = state.line; _column = state.column; } char32 get_next() { if(_current != _end) { char32 const c = *_current; ++_current; if(c == '\n') { _line += 1; _column = 1; } else { _column += 1; } return c; } else { return eof_char32; } } char32 peek_next() { if(_current != _end) { return *_current; } else { return eof_char32; } } void unget() { if(_current != _begin) { --_current; } } private: char8 const* _begin; char8 const* _end; char8 const* _current; i64 _line = 1; i64 _column = 1; }; class Parser { public: Parser(anton::String_View source_code, anton::String_View source_name): _source_name(source_name), _lexer(source_code) {} anton::Expected<Declaration_List, Parse_Error> build_ast() { Declaration_List ast; while(!_lexer.match_eof()) { if(Owning_Ptr declaration = try_declaration()) { ast.emplace_back(ANTON_MOV(declaration)); } else { return {anton::expected_error, _last_error}; } } return {anton::expected_value, ANTON_MOV(ast)}; } anton::Expected<Declaration_List, Parse_Error> parse_builtin_functions() { Declaration_List builtin_functions; while(!_lexer.match_eof()) { if(Owning_Ptr fn = try_function_declaration()) { fn->builtin = true; fn->source_info.line = 1; fn->source_info.end_line = 1; builtin_functions.emplace_back(ANTON_MOV(fn)); } else { return {anton::expected_error, _last_error}; } } return {anton::expected_value, ANTON_MOV(builtin_functions)}; } private: anton::String_View _source_name; Lexer _lexer; Parse_Error _last_error; void set_error(anton::String_View const message, Lexer_State const& state) { if(state.stream_offset >= _last_error.stream_offset) { _last_error.message = message; _last_error.line = state.line; _last_error.column = state.column; _last_error.stream_offset = state.stream_offset; } } void set_error(anton::String_View const message) { Lexer_State const state = _lexer.get_current_state_no_skip(); if(state.stream_offset >= _last_error.stream_offset) { _last_error.message = message; _last_error.line = state.line; _last_error.column = state.column; _last_error.stream_offset = state.stream_offset; } } Source_Info src_info(Lexer_State const& start, Lexer_State const& end) { return Source_Info{_source_name, start.line, start.column, start.stream_offset, end.line, end.column, end.stream_offset}; } Owning_Ptr<Declaration> try_declaration() { if(Owning_Ptr declaration_if = try_declaration_if()) { return declaration_if; } if(Owning_Ptr import_declaration = try_import_declaration()) { return import_declaration; } if(Owning_Ptr settings_declaration = try_settings_declaration()) { return settings_declaration; } if(Owning_Ptr struct_declaration = try_struct_declaration()) { return struct_declaration; } if(Owning_Ptr pass_stage = try_pass_stage_declaration()) { return pass_stage; } if(Owning_Ptr function_declaration = try_function_declaration()) { return function_declaration; } if(Owning_Ptr variable_declaration = try_variable_declaration()) { return variable_declaration; } if(Owning_Ptr constant = try_constant_declaration()) { return constant; } set_error(u8"expected declaration"); return nullptr; } Owning_Ptr<Declaration_If> try_declaration_if() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_if, true)) { set_error(u8"expected 'if'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } Declaration_List true_declarations; while(!_lexer.match(token_brace_close)) { if(_lexer.match_eof()) { set_error(u8"unexpected end of file"); _lexer.restore_state(state_backup); return nullptr; } if(Owning_Ptr declaration = try_declaration()) { true_declarations.emplace_back(ANTON_MOV(declaration)); } else { return nullptr; } } Declaration_List false_declarations; if(_lexer.match(kw_else, true)) { if(Owning_Ptr if_declaration = try_declaration_if()) { false_declarations.emplace_back(ANTON_MOV(if_declaration)); } else { if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } while(!_lexer.match(token_brace_close)) { if(Owning_Ptr declaration = try_declaration()) { false_declarations.emplace_back(ANTON_MOV(declaration)); } else { _lexer.restore_state(state_backup); return nullptr; } } } } return Owning_Ptr{ new Declaration_If(ANTON_MOV(condition), ANTON_MOV(true_declarations), ANTON_MOV(false_declarations), src_info(state_backup, state_backup))}; } Owning_Ptr<Import_Declaration> try_import_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_import, true)) { set_error(u8"expected 'import'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr string = try_string_literal()) { return Owning_Ptr{new Import_Declaration(ANTON_MOV(string), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } Owning_Ptr<Variable_Declaration> try_variable_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); Owning_Ptr var_type = try_type(); if(!var_type) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr var_name = try_identifier(); if(!var_name) { set_error(u8"expected variable name"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Expression> initializer = nullptr; if(_lexer.match(token_assign)) { initializer = try_expression(); if(!initializer) { _lexer.restore_state(state_backup); return nullptr; } } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';' after variable declaration"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Variable_Declaration(ANTON_MOV(var_type), ANTON_MOV(var_name), ANTON_MOV(initializer), src)}; } Owning_Ptr<Constant_Declaration> try_constant_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_const)) { set_error(u8"expected 'const'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr var_type = try_type(); if(!var_type) { set_error(u8"expected type"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr var_name = try_identifier(); if(!var_name) { set_error(u8"expected variable name"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Expression> initializer = nullptr; if(_lexer.match(token_assign)) { initializer = try_expression(); if(!initializer) { _lexer.restore_state(state_backup); return nullptr; } } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';' after constant declaration"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Constant_Declaration(ANTON_MOV(var_type), ANTON_MOV(var_name), ANTON_MOV(initializer), src)}; } Owning_Ptr<Struct_Member> try_struct_member() { Lexer_State const state_backup = _lexer.get_current_state(); bool has_invariant = false; bool has_interpolation = false; Interpolation interpolation = Interpolation::none; while(true) { if(_lexer.match(kw_invariant, true)) { if(has_invariant) { set_error(u8"multiple invariance qualifiers are not allowed"); _lexer.restore_state(state_backup); return nullptr; } has_invariant = true; continue; } if(_lexer.match(kw_smooth, true)) { if(has_interpolation) { set_error(u8"multiple interpolation qualifiers are not allowed"); _lexer.restore_state(state_backup); return nullptr; } interpolation = Interpolation::smooth; has_interpolation = true; continue; } if(_lexer.match(kw_flat, true)) { if(has_interpolation) { set_error(u8"multiple interpolation qualifiers are not allowed"); _lexer.restore_state(state_backup); return nullptr; } interpolation = Interpolation::flat; has_interpolation = true; continue; } if(_lexer.match(kw_noperspective, true)) { if(has_interpolation) { set_error(u8"multiple interpolation qualifiers are not allowed"); _lexer.restore_state(state_backup); return nullptr; } interpolation = Interpolation::noperspective; has_interpolation = true; continue; } break; } Owning_Ptr var_type = try_type(); if(!var_type) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr var_name = try_identifier(); if(!var_name) { set_error(u8"expected member name"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Expression> initializer = nullptr; if(_lexer.match(token_assign)) { initializer = try_expression(); if(!initializer) { _lexer.restore_state(state_backup); return nullptr; } } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Struct_Member(ANTON_MOV(var_type), ANTON_MOV(var_name), ANTON_MOV(initializer), interpolation, has_invariant, src)}; } Owning_Ptr<Struct_Declaration> try_struct_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_struct, true)) { set_error(u8"expected 'struct'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr struct_name = try_identifier(); if(!struct_name) { set_error(u8"expected struct name"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } anton::Array<Owning_Ptr<Struct_Member>> members; while(!_lexer.match(token_brace_close)) { if(Owning_Ptr decl = try_struct_member()) { members.emplace_back(ANTON_MOV(decl)); } else { _lexer.restore_state(state_backup); return nullptr; } } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Struct_Declaration(ANTON_MOV(struct_name), ANTON_MOV(members), src)}; } Owning_Ptr<Settings_Declaration> try_settings_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); auto match_string = [this, &state_backup]() -> anton::Optional<anton::String> { _lexer.ignore_whitespace_and_comments(); anton::String string; while(true) { char32 next_char = _lexer.peek_next(); if(next_char == eof_char32) { set_error(u8"unexpected end of file"); _lexer.restore_state(state_backup); return anton::null_optional; } else if(is_whitespace(next_char) || next_char == U':' || next_char == U'}' || next_char == U'{') { return {ANTON_MOV(string)}; } else { string += next_char; _lexer.get_next(); } } }; auto match_nested_settings = [this, &state_backup, &match_string](auto match_nested_settings, anton::Array<Setting_Key_Value>& settings, anton::String const& setting_name) -> bool { while(true) { if(_lexer.match(token_brace_close)) { return true; } auto key_name = match_string(); if(!key_name) { _lexer.restore_state(state_backup); return false; } if(key_name.value().size_bytes() == 0) { set_error(u8"expected name"); _lexer.restore_state(state_backup); return false; } if(!_lexer.match(token_colon)) { set_error(u8"expected ':'"); _lexer.restore_state(state_backup); return false; } anton::String setting_key = setting_name; if(setting_key.size_bytes() > 0) { setting_key += u8"_"; } setting_key += key_name.value(); if(_lexer.match(token_brace_open)) { if(!match_nested_settings(match_nested_settings, settings, setting_key)) { _lexer.restore_state(state_backup); return false; } } else { auto value = match_string(); if(!value) { _lexer.restore_state(state_backup); return false; } if(value.value().size_bytes() == 0) { set_error(u8"expected value string after ':'"); _lexer.restore_state(state_backup); return false; } settings.emplace_back(Setting_Key_Value{ANTON_MOV(setting_key), ANTON_MOV(value.value())}); } } }; if(!_lexer.match(kw_settings, true)) { set_error(u8"expected 'settings'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr pass_name = try_identifier(); if(!pass_name) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr settings_declaration{new Settings_Declaration(ANTON_MOV(pass_name), src_info(state_backup, state_backup))}; if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } if(!match_nested_settings(match_nested_settings, settings_declaration->settings, anton::String{})) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); settings_declaration->source_info = src; return settings_declaration; } Owning_Ptr<Attribute> try_attribute() { Lexer_State const state_backup = _lexer.get_current_state(); // workgroup attribute if(_lexer.match(attrib_workgroup, true)) { if(!_lexer.match(token_paren_open)) { set_error(u8"expected '('"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr x = try_integer_literal(); if(!x) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Integer_Literal> y; Owning_Ptr<Integer_Literal> z; if(_lexer.match(token_comma)) { y = try_integer_literal(); if(!y) { _lexer.restore_state(state_backup); return nullptr; } if(_lexer.match(token_comma)) { z = try_integer_literal(); if(!z) { _lexer.restore_state(state_backup); return nullptr; } } } if(!_lexer.match(token_paren_close)) { set_error(u8"expected ')'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Workgroup_Attribute(ANTON_MOV(x), ANTON_MOV(y), ANTON_MOV(z), src)}; } // TODO: Add a diagnostic for unrecognized attributes set_error(u8"expected identifier"); _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Attribute_List> try_attribute_list() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(token_bracket_open)) { set_error(u8"expected '['"); _lexer.restore_state(state_backup); return anton::null_optional; } if(_lexer.match(token_bracket_close)) { set_error(u8"empty attribute list (TODO: PROVIDE A PROPER DIAGNOSTIC MESSAGE WITH EXACT LOCATION AND CODE SNIPPET)"); _lexer.restore_state(state_backup); return anton::null_optional; } Attribute_List attributes; while(true) { Owning_Ptr attribute = try_attribute(); if(!attribute) { _lexer.restore_state(state_backup); return anton::null_optional; } attributes.emplace_back(ANTON_MOV(attribute)); if(!_lexer.match(token_comma)) { break; } } if(!_lexer.match(token_bracket_close)) { _lexer.restore_state(state_backup); return anton::null_optional; } return ANTON_MOV(attributes); } Owning_Ptr<Image_Layout_Qualifier> try_image_layout_qualifier() { Image_Layout_Type qualifiers[] = {Image_Layout_Type::rgba32f, Image_Layout_Type::rgba16f, Image_Layout_Type::rg32f, Image_Layout_Type::rg16f, Image_Layout_Type::r11f_g11f_b10f, Image_Layout_Type::r32f, Image_Layout_Type::r16f, Image_Layout_Type::rgba16, Image_Layout_Type::rgb10_a2, Image_Layout_Type::rgba8, Image_Layout_Type::rg16, Image_Layout_Type::rg8, Image_Layout_Type::r16, Image_Layout_Type::r8, Image_Layout_Type::rgba16_snorm, Image_Layout_Type::rgba8_snorm, Image_Layout_Type::rg16_snorm, Image_Layout_Type::rg8_snorm, Image_Layout_Type::r16_snorm, Image_Layout_Type::r8_snorm, Image_Layout_Type::rgba32i, Image_Layout_Type::rgba16i, Image_Layout_Type::rgba8i, Image_Layout_Type::rg32i, Image_Layout_Type::rg16i, Image_Layout_Type::rg8i, Image_Layout_Type::r32i, Image_Layout_Type::r16i, Image_Layout_Type::r8i, Image_Layout_Type::rgba32ui, Image_Layout_Type::rgba16ui, Image_Layout_Type::rgb10_a2ui, Image_Layout_Type::rgba8ui, Image_Layout_Type::rg32ui, Image_Layout_Type::rg16ui, Image_Layout_Type::rg8ui, Image_Layout_Type::r32ui, Image_Layout_Type::r16ui, Image_Layout_Type::r8ui}; Lexer_State const state_backup = _lexer.get_current_state(); constexpr i64 array_size = sizeof(qualifiers) / sizeof(Image_Layout_Type); for(i64 i = 0; i < array_size; ++i) { anton::String_View const string{stringify(qualifiers[i])}; anton::String7_View const string7{string.bytes_begin(), string.bytes_end()}; if(_lexer.match(string7, true)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Image_Layout_Qualifier(qualifiers[i], src)}; } } return nullptr; } Owning_Ptr<Pass_Stage_Declaration> try_pass_stage_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); // Parse the attribute lists. We allow many attribute lists // to be present on a stage declaration. We merge the lists into // a single attribute array. Attribute_List attributes; while(true) { anton::Optional<Attribute_List> attributes_result = try_attribute_list(); if(!attributes_result) { break; } for(auto& attribute: attributes_result.value()) { attributes.emplace_back(ANTON_MOV(attribute)); } } Owning_Ptr return_type = try_type(); if(!return_type) { set_error(u8"expected type"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr pass = try_identifier(); if(!pass) { set_error(u8"expected pass name"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_scope_resolution)) { set_error(u8"expected '::' after pass name"); _lexer.restore_state(state_backup); return nullptr; } static constexpr anton::String7_View stage_types_strings[] = {stage_vertex, stage_fragment, stage_compute}; static constexpr Stage_Type stage_types[] = {Stage_Type::vertex, Stage_Type::fragment, Stage_Type::compute}; Stage_Type stage_type; { bool found = false; for(i64 i = 0; i < 3; ++i) { if(_lexer.match(stage_types_strings[i], true)) { stage_type = stage_types[i]; found = true; break; } } if(!found) { set_error(u8"expected stage type"); _lexer.restore_state(state_backup); return nullptr; } } anton::Optional<Parameter_List> parameter_list = try_function_param_list(); if(!parameter_list) { _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Pass_Stage_Declaration(ANTON_MOV(attributes), ANTON_MOV(return_type), ANTON_MOV(pass), stage_type, ANTON_MOV(parameter_list.value()), ANTON_MOV(statements.value()), src)}; } Owning_Ptr<Function_Declaration> try_function_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); // Parse the attribute lists. We allow many attribute lists // to be present on a function declaration. We merge the lists // into a single attribute array. Attribute_List attributes; while(true) { anton::Optional<Attribute_List> attributes_result = try_attribute_list(); if(!attributes_result) { break; } for(auto& attribute: attributes_result.value()) { attributes.emplace_back(ANTON_MOV(attribute)); } } Owning_Ptr return_type = try_type(); if(!return_type) { set_error(u8"expected type"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr name = try_identifier(); if(!name) { set_error(u8"expected function name"); _lexer.restore_state(state_backup); return nullptr; } auto param_list = try_function_param_list(); if(!param_list) { _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Function_Declaration(ANTON_MOV(attributes), ANTON_MOV(return_type), ANTON_MOV(name), ANTON_MOV(param_list.value()), ANTON_MOV(statements.value()), src)}; } anton::Optional<Parameter_List> try_function_param_list() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(token_paren_open)) { set_error(u8"expected '('"); _lexer.restore_state(state_backup); return anton::null_optional; } if(_lexer.match(token_paren_close)) { return Parameter_List{}; } Parameter_List param_list; // Match parameters do { Owning_Ptr param = try_function_parameter(); if(param) { param_list.emplace_back(ANTON_MOV(param)); } else { _lexer.restore_state(state_backup); return anton::null_optional; } } while(_lexer.match(token_comma)); if(!_lexer.match(token_paren_close)) { set_error(u8"expected ')' after function parameter list"); _lexer.restore_state(state_backup); return anton::null_optional; } return ANTON_MOV(param_list); } Owning_Ptr<Function_Parameter_Node> try_function_parameter() { Lexer_State const state_backup = _lexer.get_current_state(); if(Owning_Ptr param_if = try_function_param_if()) { return param_if; } Owning_Ptr image_layout = try_image_layout_qualifier(); Owning_Ptr parameter_type = try_type(); if(!parameter_type) { set_error(u8"expected parameter type"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr identifier = try_identifier(); if(!identifier) { set_error(u8"expected parameter name"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Identifier> source; if(_lexer.match(kw_from, true)) { source = try_identifier(); if(!source) { set_error(u8"expected parameter source after 'from'"); _lexer.restore_state(state_backup); return nullptr; } } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Function_Parameter(ANTON_MOV(identifier), ANTON_MOV(parameter_type), ANTON_MOV(source), ANTON_MOV(image_layout), src)}; } Owning_Ptr<Function_Param_If> try_function_param_if() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_if, true)) { set_error(u8"expected 'if'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr true_param = try_function_parameter(); if(!true_param) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_close)) { set_error(u8"expected '}'"); _lexer.restore_state(state_backup); return nullptr; } if(_lexer.match(kw_else, true)) { if(Owning_Ptr param_if = try_function_param_if()) { return Owning_Ptr{ new Function_Param_If(ANTON_MOV(condition), ANTON_MOV(true_param), ANTON_MOV(param_if), src_info(state_backup, state_backup))}; } else { if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr false_param = try_function_parameter(); if(!false_param) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_close)) { set_error(u8"expected '}'"); _lexer.restore_state(state_backup); return nullptr; } return Owning_Ptr{ new Function_Param_If(ANTON_MOV(condition), ANTON_MOV(true_param), ANTON_MOV(false_param), src_info(state_backup, state_backup))}; } } else { return Owning_Ptr{new Function_Param_If(ANTON_MOV(condition), ANTON_MOV(true_param), nullptr, src_info(state_backup, state_backup))}; } } // try_empty_statament // Match empty statement ';'. // bool try_empty_statement() { return _lexer.match(token_semicolon); } Owning_Ptr<Statement> try_statement() { if(Owning_Ptr block_statement = try_block_statement()) { return block_statement; } if(Owning_Ptr if_statement = try_if_statement()) { return if_statement; } if(Owning_Ptr switch_statement = try_switch_statement()) { return switch_statement; } if(Owning_Ptr for_statement = try_for_statement()) { return for_statement; } if(Owning_Ptr while_statement = try_while_statement()) { return while_statement; } if(Owning_Ptr do_while_statement = try_do_while_statement()) { return do_while_statement; } if(Owning_Ptr return_statement = try_return_statement()) { return return_statement; } if(Owning_Ptr break_statement = try_break_statement()) { return break_statement; } if(Owning_Ptr continue_statement = try_continue_statement()) { return continue_statement; } if(Owning_Ptr discard_statement = try_discard_statement()) { return discard_statement; } if(Owning_Ptr decl = try_variable_declaration()) { Source_Info const src = decl->source_info; Owning_Ptr decl_stmt{new Declaration_Statement(ANTON_MOV(decl), src)}; return decl_stmt; } if(Owning_Ptr decl = try_constant_declaration()) { Source_Info const src = decl->source_info; Owning_Ptr decl_stmt{new Declaration_Statement(ANTON_MOV(decl), src)}; return decl_stmt; } if(Owning_Ptr expr_stmt = try_expression_statement()) { return expr_stmt; } set_error(u8"expected a statement"); return nullptr; } // try_braced_statement_list // Match '{' statements '}' anton::Optional<Statement_List> try_braced_statement_list() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return anton::null_optional; } Statement_List body; while(true) { if(_lexer.match(token_brace_close)) { return {ANTON_MOV(body)}; } if(try_empty_statement()) { continue; } Owning_Ptr<Statement> statement = try_statement(); if(statement) { body.emplace_back(ANTON_MOV(statement)); continue; } _lexer.restore_state(state_backup); return anton::null_optional; } } Owning_Ptr<Type> try_type() { Lexer_State const state_backup = _lexer.get_current_state(); anton::String type_name; if(!_lexer.match_identifier(type_name)) { set_error(u8"expected type identifier"); return nullptr; } if(is_keyword(type_name)) { anton::String msg = u8"expected type name, got '" + type_name + "' instead"; set_error(msg, state_backup); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Type> base_type; if(anton::Optional<Builtin_GLSL_Type> res = enumify_builtin_glsl_type(type_name); res) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); base_type = Owning_Ptr{new Builtin_Type(res.value(), src)}; } else { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); base_type = Owning_Ptr{new User_Defined_Type(ANTON_MOV(type_name), src)}; } if(!_lexer.match(token_bracket_open)) { return base_type; } else { Owning_Ptr array_size = try_integer_literal(); if(!_lexer.match(token_bracket_close)) { set_error(u8"expected ']'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); // We don't support nested array types (yet), so we don't continue checking for brackets. return Owning_Ptr{new Array_Type(ANTON_MOV(base_type), ANTON_MOV(array_size), src)}; } } Owning_Ptr<Block_Statement> try_block_statement() { Lexer_State const state_backup = _lexer.get_current_state(); anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Block_Statement(ANTON_MOV(statements.value()), src)}; } Owning_Ptr<If_Statement> try_if_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_if, true)) { set_error(u8"expected 'if'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> true_statements = try_braced_statement_list(); if(!true_statements) { _lexer.restore_state(state_backup); return nullptr; } Statement_List false_statements; if(_lexer.match(kw_else, true)) { if(Owning_Ptr if_statement = try_if_statement()) { false_statements.emplace_back(ANTON_MOV(if_statement)); } else { anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } false_statements = ANTON_MOV(statements.value()); } } return Owning_Ptr{ new If_Statement(ANTON_MOV(condition), ANTON_MOV(true_statements.value()), ANTON_MOV(false_statements), src_info(state_backup, state_backup))}; } Owning_Ptr<Switch_Statement> try_switch_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_switch, true)) { set_error(u8"expected 'switch'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr match_expression = try_expression(); if(!match_expression) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } anton::Array<Owning_Ptr<Case_Statement>> cases; while(true) { Lexer_State const case_state = _lexer.get_current_state(); if(_lexer.match(token_brace_close)) { break; } Expression_List labels; do { Lexer_State const label_state = _lexer.get_current_state(); if(_lexer.match(kw_default, true)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(label_state, end_state); labels.emplace_back(Owning_Ptr{new Default_Expression(src)}); } else if(Owning_Ptr literal = try_integer_literal()) { labels.emplace_back(ANTON_MOV(literal)); } else { _lexer.restore_state(state_backup); return nullptr; } } while(_lexer.match(token_comma)); if(!_lexer.match(token_arrow)) { set_error(u8"expected '=>'"_sv); _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(case_state, end_state); Owning_Ptr case_statement = Owning_Ptr{new Case_Statement(ANTON_MOV(labels), ANTON_MOV(statements.value()), src)}; cases.emplace_back(ANTON_MOV(case_statement)); } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Switch_Statement(ANTON_MOV(match_expression), ANTON_MOV(cases), src)}; } Owning_Ptr<For_Statement> try_for_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_for, true)) { set_error("expected 'for'"); _lexer.restore_state(state_backup); return nullptr; } if(_lexer.match(token_paren_open)) { set_error("unexpected '(' after 'for'"); _lexer.restore_state(state_backup); return nullptr; } // Match variable Owning_Ptr<Variable_Declaration> variable_declaration; if(!_lexer.match(token_semicolon)) { Lexer_State const var_decl_state = _lexer.get_current_state(); Owning_Ptr var_type = try_type(); if(!var_type) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr var_name = try_identifier(); if(!var_name) { set_error("expected variable name"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Expression> initializer; if(_lexer.match(token_assign)) { initializer = try_expression(); if(!initializer) { _lexer.restore_state(state_backup); return nullptr; } } if(!_lexer.match(token_semicolon)) { set_error("expected ';' in 'for' statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(var_decl_state, end_state); variable_declaration = Owning_Ptr{new Variable_Declaration(ANTON_MOV(var_type), ANTON_MOV(var_name), ANTON_MOV(initializer), src)}; } Owning_Ptr<Expression> condition; if(!_lexer.match(token_semicolon)) { condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error("expected ';' in 'for' statement"); _lexer.restore_state(state_backup); return nullptr; } } Owning_Ptr post_expression = try_expression(); anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{ new For_Statement(ANTON_MOV(variable_declaration), ANTON_MOV(condition), ANTON_MOV(post_expression), ANTON_MOV(statements.value()), src)}; } Owning_Ptr<While_Statement> try_while_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_while, true)) { set_error("expected 'while'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new While_Statement(ANTON_MOV(condition), ANTON_MOV(statements.value()), src)}; } Owning_Ptr<Do_While_Statement> try_do_while_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_do, true)) { set_error("expected 'do'"); _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(kw_while, true)) { set_error("expected 'while'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error("expected ';' after do-while statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Do_While_Statement(ANTON_MOV(condition), ANTON_MOV(statements.value()), src)}; } Owning_Ptr<Return_Statement> try_return_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_return, true)) { set_error("expected 'return'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr return_expression = try_expression(); if(!_lexer.match(token_semicolon)) { set_error("expected ';' after return statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Return_Statement(ANTON_MOV(return_expression), src)}; } Owning_Ptr<Break_Statement> try_break_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_break, true)) { set_error(u8"expected 'break'"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';' after break statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Break_Statement(src)}; } Owning_Ptr<Continue_Statement> try_continue_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_continue, true)) { set_error(u8"expected 'continue'"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';' after continue statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Continue_Statement(src)}; } Owning_Ptr<Discard_Statement> try_discard_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_discard, true)) { set_error(u8"expected 'discard'"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';' after discard statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Discard_Statement(src)}; } Owning_Ptr<Expression_Statement> try_expression_statement() { Lexer_State const state_backup = _lexer.get_current_state(); Owning_Ptr expression = try_expression(); if(!expression) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error("expected ';' at the end of statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Expression_Statement(ANTON_MOV(expression), src)}; } Owning_Ptr<Expression> try_expression() { return try_assignment_expression(); } Owning_Ptr<Expression> try_assignment_expression() { Lexer_State const state_backup = _lexer.get_current_state(); Owning_Ptr lhs = try_binary_expression(); if(!lhs) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const op_state = _lexer.get_current_state(); Arithmetic_Assignment_Type type; bool is_direct = false; if(_lexer.match(token_assign)) { is_direct = true; } else if(_lexer.match(token_compound_plus)) { type = Arithmetic_Assignment_Type::plus; } else if(_lexer.match(token_compound_minus)) { type = Arithmetic_Assignment_Type::minus; } else if(_lexer.match(token_compound_multiply)) { type = Arithmetic_Assignment_Type::multiply; } else if(_lexer.match(token_compound_divide)) { type = Arithmetic_Assignment_Type::divide; } else if(_lexer.match(token_compound_remainder)) { type = Arithmetic_Assignment_Type::remainder; } else if(_lexer.match(token_compound_bit_lshift)) { type = Arithmetic_Assignment_Type::lshift; } else if(_lexer.match(token_compound_bit_rshift)) { type = Arithmetic_Assignment_Type::rshift; } else if(_lexer.match(token_compound_bit_and)) { type = Arithmetic_Assignment_Type::bit_and; } else if(_lexer.match(token_compound_bit_or)) { type = Arithmetic_Assignment_Type::bit_or; } else if(_lexer.match(token_compound_bit_xor)) { type = Arithmetic_Assignment_Type::bit_xor; } else { return lhs; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr rhs = try_assignment_expression(); if(!rhs) { _lexer.restore_state(state_backup); return nullptr; } if(is_direct) { return Owning_Ptr{new Assignment_Expression(ANTON_MOV(lhs), ANTON_MOV(rhs), src)}; } else { return Owning_Ptr{new Arithmetic_Assignment_Expression(type, ANTON_MOV(lhs), ANTON_MOV(rhs), src)}; } } // Owning_Ptr<Expression> try_elvis_expression() { // Lexer_State const state_backup = _lexer.get_current_state(); // Owning_Ptr cond = try_logic_or_expr(); // if(!cond) { // _lexer.restore_state(state_backup); // return nullptr; // } // if(!_lexer.match(token_question)) { // return cond; // } // // TODO: is using try_expression here correct? // Owning_Ptr true_expression = try_expression(); // if(!true_expression) { // _lexer.restore_state(state_backup); // return nullptr; // } // if(!_lexer.match(token_colon)) { // set_error(u8"expected ':'"); // _lexer.restore_state(state_backup); // return nullptr; // } // Owning_Ptr false_expression = try_expression(); // if(!false_expression) { // _lexer.restore_state(state_backup); // return nullptr; // } // Lexer_State const end_state = _lexer.get_current_state_no_skip(); // Source_Info const src = src_info(state_backup, end_state); // return Owning_Ptr{new Elvis_Expression(ANTON_MOV(cond), ANTON_MOV(true_expression), ANTON_MOV(false_expression), src)}; // } Owning_Ptr<Expression> try_binary_expression() { auto insert_node = [](Owning_Ptr<Expression> root, Owning_Ptr<Binary_Expression> node) -> Owning_Ptr<Expression> { auto get_precedence = [](Binary_Expression& expression) -> i32 { switch(expression.type) { case Binary_Expression_Type::logic_or: return 11; case Binary_Expression_Type::logic_xor: return 10; case Binary_Expression_Type::logic_and: return 9; case Binary_Expression_Type::equal: return 5; case Binary_Expression_Type::unequal: return 5; case Binary_Expression_Type::greater_than: return 4; case Binary_Expression_Type::less_than: return 4; case Binary_Expression_Type::greater_equal: return 4; case Binary_Expression_Type::less_equal: return 4; case Binary_Expression_Type::bit_or: return 8; case Binary_Expression_Type::bit_xor: return 7; case Binary_Expression_Type::bit_and: return 6; case Binary_Expression_Type::lshift: return 3; case Binary_Expression_Type::rshift: return 3; case Binary_Expression_Type::add: return 2; case Binary_Expression_Type::sub: return 2; case Binary_Expression_Type::mul: return 1; case Binary_Expression_Type::div: return 1; case Binary_Expression_Type::mod: return 1; } }; i32 const node_precedence = get_precedence(*node); Owning_Ptr<Expression>* insertion_node = &root; while(true) { if((**insertion_node).node_type != AST_Node_Type::binary_expression) { break; } Binary_Expression& expression = static_cast<Binary_Expression&>(**insertion_node); i32 const expression_precedence = get_precedence(expression); if(expression_precedence < node_precedence) { // Precedence is smaller insertion_node = &expression.rhs; } else { break; } } node->lhs = ANTON_MOV(*insertion_node); *insertion_node = ANTON_MOV(node); return root; }; Owning_Ptr<Expression> root = try_unary_expression(); if(!root) { return nullptr; } while(true) { Lexer_State const op_state = _lexer.get_current_state(); if(_lexer.match(token_compound_bit_and) || _lexer.match(token_compound_bit_or) || _lexer.match(token_compound_bit_xor) || _lexer.match(token_compound_bit_lshift) || _lexer.match(token_compound_bit_rshift) || _lexer.match(token_compound_remainder) || _lexer.match(token_compound_divide) || _lexer.match(token_compound_multiply) || _lexer.match(token_compound_plus) || _lexer.match(token_compound_minus)) { _lexer.restore_state(op_state); return root; } if(_lexer.match(token_logic_or)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::logic_or, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_logic_xor)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::logic_xor, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_logic_and)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::logic_and, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_bit_or)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::bit_or, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_bit_xor)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::bit_xor, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_bit_and)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::bit_and, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_bit_lshift)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::lshift, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_bit_rshift)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::rshift, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_equal)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::equal, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_not_equal)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::unequal, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_less_equal)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::less_equal, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_greater_equal)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::greater_equal, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_greater)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::greater_than, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_less)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::less_than, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_plus)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::add, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_minus)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::sub, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_multiply)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::mul, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_divide)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::div, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_remainder)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::mod, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else { break; } } return root; } Owning_Ptr<Expression> try_unary_expression() { Lexer_State const state_backup = _lexer.get_current_state(); if(_lexer.match(token_increment)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Prefix_Increment_Expression(ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_decrement)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Prefix_Decrement_Expression(ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_plus)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Unary_Expression(Unary_Type::plus, ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_minus)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Unary_Expression(Unary_Type::minus, ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_logic_not)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Unary_Expression(Unary_Type::logic_not, ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_bit_not)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Unary_Expression(Unary_Type::bit_not, ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else { return try_postfix_expression(); } } Owning_Ptr<Expression> try_postfix_expression() { Lexer_State const state_backup = _lexer.get_current_state(); Owning_Ptr primary_expr = try_primary_expression(); if(!primary_expr) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Expression> expr = ANTON_MOV(primary_expr); while(true) { if(_lexer.match(token_dot)) { if(Owning_Ptr member_name = try_identifier()) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); expr = Owning_Ptr{new Member_Access_Expression(ANTON_MOV(expr), ANTON_MOV(member_name), src)}; } else { set_error(u8"expected member name"); _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_bracket_open)) { Owning_Ptr index = try_expression(); if(!index) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_bracket_close)) { set_error(u8"expected ']'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); expr = Owning_Ptr{new Array_Access_Expression(ANTON_MOV(expr), ANTON_MOV(index), src)}; } else if(_lexer.match(token_increment)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); expr = Owning_Ptr{new Postfix_Increment_Expression(ANTON_MOV(expr), src)}; } else if(_lexer.match(token_decrement)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); expr = Owning_Ptr{new Postfix_Decrement_Expression(ANTON_MOV(expr), src)}; } else { break; } } return expr; } Owning_Ptr<Expression> try_primary_expression() { if(Owning_Ptr parenthesised_expression = try_paren_expr()) { return parenthesised_expression; } if(Owning_Ptr expr = try_reinterpret_expr()) { return expr; } if(Owning_Ptr expression_if = try_expression_if()) { return expression_if; } if(Owning_Ptr float_literal = try_float_literal()) { return float_literal; } if(Owning_Ptr integer_literal = try_integer_literal()) { return integer_literal; } if(Owning_Ptr bool_literal = try_bool_literal()) { return bool_literal; } if(Owning_Ptr function_call = try_function_call_expression()) { return function_call; } if(Owning_Ptr identifier_expression = try_identifier_expression()) { return identifier_expression; } return nullptr; } Owning_Ptr<Parenthesised_Expression> try_paren_expr() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(token_paren_open)) { set_error(u8"expected '('"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr paren_expression = try_expression(); if(!paren_expression) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_paren_close)) { set_error(u8"expected ')'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Parenthesised_Expression(ANTON_MOV(paren_expression), src)}; } Owning_Ptr<Reinterpret_Expression> try_reinterpret_expr() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_reinterpret, true)) { set_error(u8"expected 'reinterpret'"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_angle_open)) { set_error(u8"expected '<'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr target_type = try_type(); if(!target_type) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_angle_close)) { set_error(u8"expected '>'"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_paren_open)) { set_error(u8"expected '('"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr source = try_expression(); if(!source) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_comma)) { set_error(u8"expected ','"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr index = try_expression(); if(!index) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_paren_close)) { set_error(u8"expected ')'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Reinterpret_Expression{ANTON_MOV(target_type), ANTON_MOV(source), ANTON_MOV(index), src}}; } Owning_Ptr<Expression_If> try_expression_if() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_if, true)) { set_error(u8"expected 'if'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } if(_lexer.match(token_brace_close)) { set_error(u8"expected an expression before '}'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr true_expression = try_expression(); if(!true_expression) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_close)) { set_error(u8"expected '}' after expression"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(kw_else, true)) { set_error(u8"expected an 'else' branch"); _lexer.restore_state(state_backup); return nullptr; } if(Owning_Ptr expression_if = try_expression_if()) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Expression_If(ANTON_MOV(condition), ANTON_MOV(true_expression), ANTON_MOV(expression_if), src)}; } else { if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } if(_lexer.match(token_brace_close)) { set_error(u8"expected an expression before '}'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr false_expression = try_expression(); if(!false_expression) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_close)) { set_error(u8"expected '}' after expression"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Expression_If(ANTON_MOV(condition), ANTON_MOV(true_expression), ANTON_MOV(false_expression), src)}; } } Owning_Ptr<Function_Call_Expression> try_function_call_expression() { Lexer_State const state_backup = _lexer.get_current_state(); Owning_Ptr identifier = try_identifier(); if(!identifier) { set_error(u8"expected function name"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_paren_open)) { set_error(u8"expected '(' after function name"); _lexer.restore_state(state_backup); return nullptr; } anton::Array<Owning_Ptr<Expression>> arguments; if(_lexer.match(token_paren_close)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Function_Call_Expression(ANTON_MOV(identifier), ANTON_MOV(arguments), src)}; } do { if(Owning_Ptr expression = try_expression()) { arguments.emplace_back(ANTON_MOV(expression)); } else { _lexer.restore_state(state_backup); return nullptr; } } while(_lexer.match(token_comma)); if(!_lexer.match(token_paren_close)) { set_error(u8"expected ')'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Function_Call_Expression(ANTON_MOV(identifier), ANTON_MOV(arguments), src)}; } Owning_Ptr<Float_Literal> try_float_literal() { Lexer_State const state_backup = _lexer.get_current_state(); anton::String number; if(char32 const next_char = _lexer.peek_next(); next_char == '-' || next_char == U'+') { number += next_char; _lexer.get_next(); } i64 pre_point_digits = 0; for(char32 next_char = _lexer.peek_next(); is_digit(next_char); ++pre_point_digits) { number += next_char; _lexer.get_next(); next_char = _lexer.peek_next(); } // A decimal number must not have leading 0 except when the number is 0 if(number.size_bytes() > 1 && number.data()[0] == '0') { _lexer.restore_state(state_backup); return nullptr; } if(pre_point_digits == 0) { number += '0'; } bool has_period = false; i64 post_point_digits = 0; if(_lexer.peek_next() == '.') { has_period = true; number += '.'; _lexer.get_next(); for(char32 next_char = _lexer.peek_next(); is_digit(next_char); ++post_point_digits) { number += next_char; _lexer.get_next(); next_char = _lexer.peek_next(); } if(post_point_digits == 0) { number += '0'; } } if(pre_point_digits == 0 && post_point_digits == 0) { set_error(u8"not a floating point constant", state_backup); _lexer.restore_state(state_backup); return nullptr; } bool has_e = false; if(char32 const e = _lexer.peek_next(); e == U'e' || e == U'E') { has_e = true; number += 'E'; _lexer.get_next(); if(char32 const sign = _lexer.peek_next(); sign == '-' || sign == U'+') { number += sign; _lexer.get_next(); } i64 e_digits = 0; for(char32 next_char = _lexer.peek_next(); is_digit(next_char); ++e_digits) { number += next_char; _lexer.get_next(); next_char = _lexer.peek_next(); } if(e_digits == 0) { set_error("exponent has no digits"); _lexer.restore_state(state_backup); return nullptr; } } if(!has_e && !has_period) { set_error(u8"not a floating point constant", state_backup); _lexer.restore_state(state_backup); return nullptr; } Float_Literal_Type type = Float_Literal_Type::f32; Lexer_State const suffix_backup = _lexer.get_current_state_no_skip(); anton::String suffix; for(char32 next = _lexer.peek_next(); is_identifier_character(next); next = _lexer.peek_next()) { suffix += next; _lexer.get_next(); } if(suffix == u8"d" || suffix == u8"D") { type = Float_Literal_Type::f64; } else if(suffix != u8"") { set_error(u8"invalid suffix '" + suffix + u8"' on floating point literal", suffix_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Float_Literal(ANTON_MOV(number), type, src)}; } Owning_Ptr<Integer_Literal> try_integer_literal() { // Section 4.1.3 of The OpenGL Shading Language 4.60.7 states that integer literals are never negative. // Instead the leading '-' is always interpreted as a unary minus operator. We follow the same convention. Lexer_State const state_backup = _lexer.get_current_state(); // Binary literal bool const has_bin_prefix = _lexer.match(u8"0b") || _lexer.match(u8"0B"); if(has_bin_prefix) { anton::String out; while(is_binary_digit(_lexer.peek_next())) { char32 const digit = _lexer.get_next(); out += digit; } if(char32 const next = _lexer.peek_next(); is_digit(next)) { set_error(u8"invalid digit '" + anton::String::from_utf32(&next, 4) + u8"' in binary integer literal"); _lexer.restore_state(state_backup); return nullptr; } Integer_Literal_Type type = Integer_Literal_Type::i32; Lexer_State const suffix_backup = _lexer.get_current_state_no_skip(); anton::String suffix; for(char32 next = _lexer.peek_next(); is_identifier_character(next); next = _lexer.peek_next()) { suffix += next; _lexer.get_next(); } if(suffix == u8"u" || suffix == u8"U") { type = Integer_Literal_Type::u32; } else if(suffix != u8"") { set_error(u8"invalid suffix '" + suffix + u8"' on integer literal", suffix_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Integer_Literal{ANTON_MOV(out), type, Integer_Literal_Base::bin, src}}; } // Octal literal bool const has_oct_prefix = _lexer.match(u8"0o") || _lexer.match(u8"0O"); if(has_oct_prefix) { anton::String out; while(is_octal_digit(_lexer.peek_next())) { char32 const digit = _lexer.get_next(); out += digit; } if(char32 const next = _lexer.peek_next(); is_digit(next)) { set_error(u8"invalid digit '" + anton::String::from_utf32(&next, 4) + u8"' in octal integer literal"); _lexer.restore_state(state_backup); return nullptr; } Integer_Literal_Type type = Integer_Literal_Type::i32; Lexer_State const suffix_backup = _lexer.get_current_state_no_skip(); anton::String suffix; for(char32 next = _lexer.peek_next(); is_identifier_character(next); next = _lexer.peek_next()) { suffix += next; _lexer.get_next(); } if(suffix == u8"u" || suffix == u8"U") { type = Integer_Literal_Type::u32; } else if(suffix != u8"") { set_error(u8"invalid suffix '" + suffix + u8"' on integer literal", suffix_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Integer_Literal{ANTON_MOV(out), type, Integer_Literal_Base::oct, src}}; } // Hexadecimal literal bool const has_hex_prefix = _lexer.match(u8"0x") || _lexer.match(u8"0X"); if(has_hex_prefix) { anton::String out; while(is_hexadecimal_digit(_lexer.peek_next())) { char32 const digit = _lexer.get_next(); out += digit; } Integer_Literal_Type type = Integer_Literal_Type::i32; Lexer_State const suffix_backup = _lexer.get_current_state_no_skip(); anton::String suffix; for(char32 next = _lexer.peek_next(); is_identifier_character(next); next = _lexer.peek_next()) { suffix += next; _lexer.get_next(); } if(suffix == u8"u" || suffix == u8"U") { type = Integer_Literal_Type::u32; } else if(suffix != u8"") { set_error(u8"invalid suffix '" + suffix + u8"' on integer literal", suffix_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Integer_Literal{ANTON_MOV(out), type, Integer_Literal_Base::hex, src}}; } // Decimal literal anton::String out; if(char32 const next = _lexer.peek_next(); !is_digit(next)) { set_error(u8"expected integer literal"); _lexer.restore_state(state_backup); return nullptr; } while(is_digit(_lexer.peek_next())) { char32 const digit = _lexer.get_next(); out += digit; } Integer_Literal_Type type = Integer_Literal_Type::i32; Lexer_State const suffix_backup = _lexer.get_current_state_no_skip(); anton::String suffix; for(char32 next = _lexer.peek_next(); is_identifier_character(next); next = _lexer.peek_next()) { suffix += next; _lexer.get_next(); } if(suffix == u8"u" || suffix == u8"U") { type = Integer_Literal_Type::u32; } else if(suffix != u8"") { set_error(u8"invalid suffix '" + suffix + "' on integer literal", suffix_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Integer_Literal{ANTON_MOV(out), type, Integer_Literal_Base::dec, src}}; } Owning_Ptr<Bool_Literal> try_bool_literal() { Lexer_State const state_backup = _lexer.get_current_state(); if(_lexer.match(kw_true, true)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Bool_Literal(true, src)}; } else if(_lexer.match(kw_false, true)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Bool_Literal(false, src)}; } else { set_error("expected bool literal"); return nullptr; } } Owning_Ptr<String_Literal> try_string_literal() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(token_double_quote)) { set_error(u8"expected \""); return nullptr; } anton::String string; while(true) { char32 next_char = _lexer.peek_next(); if(next_char == U'\n') { // We disallow newlines inside string literals set_error(u8"newlines are not allowed in string literals"); _lexer.restore_state(state_backup); return nullptr; } else if(next_char == eof_char32) { set_error(u8"unexpected end of file"); _lexer.restore_state(state_backup); return nullptr; } else if(next_char == U'\\') { string += _lexer.get_next(); string += _lexer.get_next(); } else if(next_char == U'\"') { _lexer.get_next(); break; } else { string += next_char; _lexer.get_next(); } } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new String_Literal(ANTON_MOV(string), src)}; } Owning_Ptr<Identifier> try_identifier() { Lexer_State const state_backup = _lexer.get_current_state(); anton::String identifier; if(!_lexer.match_identifier(identifier)) { set_error(u8"expected an identifier"); _lexer.restore_state(state_backup); return nullptr; } if(is_keyword(identifier)) { anton::String msg = u8"keyword '" + identifier + "' may not be used as identifier"; set_error(msg, state_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Identifier(ANTON_MOV(identifier), src)}; } Owning_Ptr<Identifier_Expression> try_identifier_expression() { Lexer_State const state_backup = _lexer.get_current_state(); anton::String identifier; if(!_lexer.match_identifier(identifier)) { set_error(u8"expected an identifier"); _lexer.restore_state(state_backup); return nullptr; } if(is_keyword(identifier)) { anton::String msg = u8"keyword '" + identifier + "' may not be used as identifier"; set_error(msg, state_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Identifier_Expression(ANTON_MOV(identifier), src)}; } }; anton::Expected<Declaration_List, Parse_Error> parse_source(anton::String_View const source_name, anton::String_View const source_code) { Parser parser(source_code, source_name); anton::Expected<Declaration_List, Parse_Error> ast = parser.build_ast(); return ast; } anton::Expected<Declaration_List, Parse_Error> parse_builtin_functions(anton::String_View const source_name, anton::String_View const source_code) { Parser parser(source_code, source_name); anton::Expected<Declaration_List, Parse_Error> ast = parser.parse_builtin_functions(); return ast; } } // namespace vush
42.303009
159
0.53683
kociap
40fc507049c01c817acbcd05a85f57847877e8eb
1,719
cpp
C++
2015/Black_Box-RankTree-Treap.cpp
jasha64/jasha64
653881f0f79075a628f98857e77eac27aef1919d
[ "MIT" ]
null
null
null
2015/Black_Box-RankTree-Treap.cpp
jasha64/jasha64
653881f0f79075a628f98857e77eac27aef1919d
[ "MIT" ]
null
null
null
2015/Black_Box-RankTree-Treap.cpp
jasha64/jasha64
653881f0f79075a628f98857e77eac27aef1919d
[ "MIT" ]
1
2020-06-15T07:58:13.000Z
2020-06-15T07:58:13.000Z
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; const int N = 30007; struct Node { int p, v, s; Node* ch[2]; Node(int v):v(v) {p = rand(); ch[0] = ch[1] = NULL; s = 1;} int cmp(int x) const { if (x == v) return -1; return x < v ? 0 : 1; } void Maintain() { s = 1; if (ch[0]) s += ch[0] -> s; if (ch[1]) s += ch[1] -> s; } }; Node* Root; int i, v, a[N]; void Rotate(Node* &o, int d) { Node* k = o -> ch[d ^ 1]; o -> ch[d ^ 1] = k -> ch[d]; k -> ch[d] = o; o -> Maintain(); k -> Maintain(); o = k; } void Insert(Node* &o) { if (o == NULL) {o = new Node(v); o -> Maintain(); return;} int d = o -> cmp(v); Insert(o -> ch[d]); if (o -> ch[d] -> p > o -> p) Rotate(o, d ^ 1); o -> Maintain(); } void Remove(Node* &o) { int d = o -> cmp(v); if (d == -1) { if (o -> ch[0] == NULL) o = o -> ch[1]; else if (o -> ch[1] == NULL) o = o -> ch[0]; else { int d2 = o -> ch[0] -> p > o -> ch[1] -> p ? 1 : 0; Rotate(o, d2); Remove(o -> ch[d2]); } } else Remove(o -> ch[d]); if (o) o -> Maintain(); } bool Find(Node* o) { int d; while (o) { d = o -> cmp(v); if (d == -1) return true; o = o -> ch[d]; } return false; } int Kth(Node* o, int k) { if (o == NULL || k <= 0 || k > o -> s) return 0; int s = o -> ch[0] == NULL ? 0 : o -> ch[0] -> s; if (s + 1 == k) return o -> v; else if (k <= s) return Kth(o -> ch[0], k); else return Kth(o -> ch[1], k - s - 1); } int main() { int n, m, q, s = 0; srand(time(NULL)); ios::sync_with_stdio(false); cin >> n >> q; for (int j = 1; j <= n; ++j) cin >> a[j]; i = 0; while (q--) { cin >> m; while (s < m) {v = a[++s]; Insert(Root);} cout << Kth(Root, ++i) << endl; } return 0; }
18.094737
85
0.456079
jasha64
40fc8a3500e2175276cbde8bb96f4ecb566f3421
8,730
cpp
C++
9_1_TP2_SideScrollingFighter/account_model.cpp
Arganancer/SideScrollingFighter
667f502cdce887f154b5e9e32a28f570aa949db0
[ "MIT" ]
null
null
null
9_1_TP2_SideScrollingFighter/account_model.cpp
Arganancer/SideScrollingFighter
667f502cdce887f154b5e9e32a28f570aa949db0
[ "MIT" ]
null
null
null
9_1_TP2_SideScrollingFighter/account_model.cpp
Arganancer/SideScrollingFighter
667f502cdce887f154b5e9e32a28f570aa949db0
[ "MIT" ]
null
null
null
#include "account_model.h" #include <fstream> #include <tuple> std::string account_model::accounts_file_location_; sf::String account_model::current_user_internal_representation_; sf::String account_model::current_user_screen_name_; using namespace std; bool account_model::init() { current_user_internal_representation_ = ""; current_user_screen_name_ = ""; accounts_file_location_ = "Data\\accounts.txt"; return true; } void account_model::add_account(sf::String internal_and_account_and_password) { const string temp_sf_to_std = internal_and_account_and_password + "\n"; ofstream output_file(accounts_file_location_, std::ios_base::app | std::ios_base::out); output_file << temp_sf_to_std; } bool account_model::get_account(sf::String account_name, sf::String& account_password, sf::String& internal_representation) { ifstream ifs(accounts_file_location_); string line; string username = ""; string password = ""; while (getline(ifs, line)) { const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { username = line.substr(pos + 1, pos2 - pos - 1); // username is in between both pipes. if (username == account_name) { internal_representation = line.substr(0, pos); // internal representation is before the first pipe. account_password = line.substr(pos2 + 1); // password is after the second pipe. return true; } } } } return false; } sf::String account_model::get_screen_name_from_internal(sf::String internal) { ifstream ifs(accounts_file_location_); string line; string internal_representation = ""; string username = ""; while (getline(ifs, line)) { const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { internal_representation = line.substr(0, pos); // internal representation is before the first pipe. if (internal_representation == internal) { username = line.substr(pos + 1, pos2 - pos - 1); // username is in between both pipes. return username; } } } } return username; } // Returns " " if username not found. sf::String account_model::get_internal_from_screen_name(sf::String username) { ifstream ifs(accounts_file_location_); string line; string internal_representation = ""; string username_2 = ""; while (getline(ifs, line)) { const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { username_2 = line.substr(pos + 1, pos2 - pos - 1); // username is in between both pipes. if (username_2 == username) { internal_representation = line.substr(0, pos); // internal representation is before the first pipe. return internal_representation; } } } } return " "; } sf::String account_model::get_next_internal_value() { int highest_internal = 0; ifstream ifs(accounts_file_location_); string line; while (getline(ifs, line)) { string internal = ""; const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { internal = line.substr(0, pos); // internal representation is before the first pipe. if (highest_internal < stoi(internal)) { highest_internal = stoi(internal); } } } } return to_string(highest_internal + 1); } int account_model::get_nb_of_accounts() { auto nb_of_accounts = 0; ifstream ifs(accounts_file_location_); string line; while (getline(ifs, line)) { const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { nb_of_accounts++; } } } return nb_of_accounts; } std::vector<sf::String> account_model::get_accounts() { std::vector<sf::String> accounts; ifstream ifs(accounts_file_location_); string line; while (getline(ifs, line)) { string username = ""; string internal = ""; const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { username = line.substr(pos + 1, pos2 - pos - 1); // username is in between both pipes. accounts.push_back(username); } } } return accounts; } void account_model::delete_account(sf::String internal) { sf::String internal_representation = ""; ifstream ifs(accounts_file_location_); ofstream temp("Data\\temp.txt"); string line; while (getline(ifs, line)) { const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { internal_representation = line.substr(0, pos); // internal representation is before the first pipe. const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { if(internal_representation != internal) { temp << line << endl; } } } } ifs.close(); temp.close(); if(remove(accounts_file_location_.c_str()) == 0) { rename("Data\\temp.txt", accounts_file_location_.c_str()); } else { remove("Data\\temp.txt"); } } void account_model::modify_account_password(sf::String internal, sf::String new_password) { sf::String internal_representation = ""; sf::String username = ""; ifstream ifs(accounts_file_location_); ofstream temp("Data\\temp.txt"); string line; while (getline(ifs, line)) { const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { internal_representation = line.substr(0, pos); // internal representation is before the first pipe. const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { if (internal_representation == internal) { username = line.substr(pos + 1, pos2 - pos - 1); // username is in between both pipes. const std::string new_line = internal + "|" + username + "|" + new_password; temp << new_line << endl; } else { temp << line << endl; } } } } ifs.close(); temp.close(); if (remove(accounts_file_location_.c_str()) == 0) { rename("Data\\temp.txt", accounts_file_location_.c_str()); } else { remove("Data\\temp.txt"); } } void account_model::modify_account_username(sf::String internal, sf::String new_screen_name) { sf::String internal_representation = ""; sf::String password = ""; ifstream ifs(accounts_file_location_); ofstream temp("Data\\temp.txt"); string line; while (getline(ifs, line)) { const auto pos = line.find('|'); // Find first occurence of the separating character. if (pos != string::npos) { internal_representation = line.substr(0, pos); // internal representation is before the first pipe. const auto pos2 = line.find('|', pos + 1);// Find second occurence of the separating character. if (pos2 != string::npos) { if (internal_representation == internal) { password = line.substr(pos2 + 1); // password is after the second pipe. const std::string new_line = internal + "|" + new_screen_name + "|" + password; temp << new_line << endl; } else { temp << line << endl; } } } } ifs.close(); temp.close(); if (remove(accounts_file_location_.c_str()) == 0) { rename("Data\\temp.txt", accounts_file_location_.c_str()); } else { remove("Data\\temp.txt"); } } sf::String account_model::get_current_user_screen_name() { return current_user_screen_name_; } sf::String account_model::get_current_user_internal_representation() { return current_user_internal_representation_; } void account_model::set_current_user(sf::String current_user_screen_name, sf::String current_user_internal_representation) { current_user_screen_name_ = current_user_screen_name; current_user_internal_representation_ = current_user_internal_representation; } void account_model::log_out_current_user() { current_user_screen_name_ = ""; current_user_internal_representation_ = ""; }
28.07074
123
0.686712
Arganancer
40fed3f5a24832f1966e65bd113d10f7cf450340
5,283
cpp
C++
Polyhedron/demo/Polyhedron/Plugins/PMP/Polyhedron_stitching_plugin.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
1
2022-01-19T03:07:22.000Z
2022-01-19T03:07:22.000Z
Polyhedron/demo/Polyhedron/Plugins/PMP/Polyhedron_stitching_plugin.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
null
null
null
Polyhedron/demo/Polyhedron/Plugins/PMP/Polyhedron_stitching_plugin.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
null
null
null
#include <QApplication> #include <QMessageBox> #include <QMainWindow> #include "Kernel_type.h" #include "Scene_surface_mesh_item.h" #include "Scene_polylines_item.h" #include <CGAL/Three/Polyhedron_demo_plugin_helper.h> #include <CGAL/Three/Polyhedron_demo_plugin_interface.h> #include <CGAL/Polygon_mesh_processing/stitch_borders.h> #include <CGAL/boost/graph/split_graph_into_polylines.h> #include <CGAL/boost/graph/helpers.h> #include <boost/graph/filtered_graph.hpp> using namespace CGAL::Three; class Polyhedron_demo_polyhedron_stitching_plugin : public QObject, public Polyhedron_demo_plugin_helper { Q_OBJECT Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface) Q_PLUGIN_METADATA(IID "com.geometryfactory.PolyhedronDemo.PluginInterface/1.0" FILE "polyhedron_stitching_plugin.json") QAction* actionDetectBorders; QAction* actionStitchBorders; QAction* actionStitchByCC; public: QList<QAction*> actions() const { return QList<QAction*>() << actionDetectBorders << actionStitchBorders << actionStitchByCC; } void init(QMainWindow* mainWindow, CGAL::Three::Scene_interface* scene_interface, Messages_interface* /* m */) { scene = scene_interface; actionDetectBorders= new QAction(tr("Detect Boundaries"), mainWindow); actionDetectBorders->setObjectName("actionDetectBorders"); actionDetectBorders->setProperty("subMenuName", "Polygon Mesh Processing"); actionStitchBorders= new QAction(tr("Stitch Duplicated Boundaries"), mainWindow); actionStitchBorders->setObjectName("actionStitchBorders"); actionStitchBorders->setProperty("subMenuName", "Polygon Mesh Processing/Repair"); actionStitchByCC= new QAction(tr("Stitch Borders Per Connected Components"), mainWindow); actionStitchByCC->setObjectName("actionStitchByCC"); actionStitchByCC->setProperty("subMenuName", "Polygon Mesh Processing/Repair"); autoConnectActions(); } bool applicable(QAction*) const { Q_FOREACH(int index, scene->selectionIndices()) { if ( qobject_cast<Scene_surface_mesh_item*>(scene->item(index)) ) return true; } return false; } template <typename Item> void on_actionDetectBorders_triggered(Scene_interface::Item_id index); template <typename Item> void on_actionStitchBorders_triggered(Scene_interface::Item_id index); template <typename Item> void on_actionStitchByCC_triggered(Scene_interface::Item_id index); public Q_SLOTS: void on_actionDetectBorders_triggered(); void on_actionStitchBorders_triggered(); void on_actionStitchByCC_triggered(); }; // end Polyhedron_demo_polyhedron_stitching_plugin template <typename Item> void Polyhedron_demo_polyhedron_stitching_plugin::on_actionDetectBorders_triggered(Scene_interface::Item_id index) { typedef typename Item::Face_graph FaceGraph; Item* item = qobject_cast<Item*>(scene->item(index)); if(item) { Scene_polylines_item* new_item = new Scene_polylines_item(); FaceGraph* pMesh = item->polyhedron(); normalize_border(*pMesh); for(auto ed : edges(*pMesh)) { if(pMesh->is_border(ed)) { new_item->polylines.push_back(Scene_polylines_item::Polyline()); new_item->polylines.back().push_back(pMesh->point(pMesh->source(pMesh->halfedge(ed)))); new_item->polylines.back().push_back(pMesh->point(pMesh->target(pMesh->halfedge(ed)))); } } if (new_item->polylines.empty()) { delete new_item; } else { new_item->setName(tr("Boundary of %1").arg(item->name())); new_item->setColor(Qt::red); scene->addItem(new_item); new_item->invalidateOpenGLBuffers(); } } } void Polyhedron_demo_polyhedron_stitching_plugin::on_actionDetectBorders_triggered() { Q_FOREACH(int index, scene->selectionIndices()){ on_actionDetectBorders_triggered<Scene_surface_mesh_item>(index); } } template <typename Item> void Polyhedron_demo_polyhedron_stitching_plugin::on_actionStitchBorders_triggered(Scene_interface::Item_id index) { Item* item = qobject_cast<Item*>(scene->item(index)); if(item){ typename Item::Face_graph* pMesh = item->polyhedron(); CGAL::Polygon_mesh_processing::stitch_borders(*pMesh); item->invalidateOpenGLBuffers(); scene->itemChanged(item); } } void Polyhedron_demo_polyhedron_stitching_plugin::on_actionStitchBorders_triggered() { Q_FOREACH(int index, scene->selectionIndices()){ on_actionStitchBorders_triggered<Scene_surface_mesh_item>(index); } } template <typename Item> void Polyhedron_demo_polyhedron_stitching_plugin::on_actionStitchByCC_triggered(Scene_interface::Item_id index) { Item* item = qobject_cast<Item*>(scene->item(index)); if(!item) return; CGAL::Polygon_mesh_processing::stitch_borders(*item->polyhedron(), CGAL::parameters::apply_per_connected_component(true)); item->invalidateOpenGLBuffers(); scene->itemChanged(item); } void Polyhedron_demo_polyhedron_stitching_plugin::on_actionStitchByCC_triggered() { Q_FOREACH(int index, scene->selectionIndices()){ on_actionStitchByCC_triggered<Scene_surface_mesh_item>(index); } } #include "Polyhedron_stitching_plugin.moc"
32.611111
129
0.744085
ffteja
dc00533bb54e9c48d6a576582fdb11acc068166e
1,545
cc
C++
components/ntp_tiles/json_unsafe_parser.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
components/ntp_tiles/json_unsafe_parser.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
components/ntp_tiles/json_unsafe_parser.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/ntp_tiles/json_unsafe_parser.h" #include "base/bind.h" #include "base/callback.h" #include "base/json/json_parser.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" namespace ntp_tiles { void JsonUnsafeParser::Parse(const std::string& unsafe_json, const SuccessCallback& success_callback, const ErrorCallback& error_callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind( [](const std::string& unsafe_json, const SuccessCallback& success_callback, const ErrorCallback& error_callback) { std::string error_msg; int error_line, error_column; std::unique_ptr<base::Value> value = base::JSONReader::ReadAndReturnError( unsafe_json, base::JSON_ALLOW_TRAILING_COMMAS, nullptr, &error_msg, &error_line, &error_column); if (value) { success_callback.Run(std::move(value)); } else { error_callback.Run(base::StringPrintf( "%s (%d:%d)", error_msg.c_str(), error_line, error_column)); } }, unsafe_json, success_callback, error_callback)); } } // namespace ntp_tiles
36.785714
78
0.624595
google-ar
dc02062a536129a1a7d87e8adfeb18bcfa3ca812
3,703
cpp
C++
td08/src/main.cpp
asassoye/ESI-DEV3-TD
074c7ec4c81bcf3a927079202050d5d05e4e29ca
[ "MIT" ]
4
2020-12-31T14:57:20.000Z
2020-12-31T15:15:49.000Z
td08/src/main.cpp
asassoye/ESI-DEV3-TD
074c7ec4c81bcf3a927079202050d5d05e4e29ca
[ "MIT" ]
null
null
null
td08/src/main.cpp
asassoye/ESI-DEV3-TD
074c7ec4c81bcf3a927079202050d5d05e4e29ca
[ "MIT" ]
1
2021-01-03T13:23:14.000Z
2021-01-03T13:23:14.000Z
/** * @file main.cpp * @author Andrew SASSOYE */ #include <iostream> #include <algorithm> #include <functional> #include "../resources/utilscpp.hpp" #include "../src/sign.hpp" #include "../resources/data_fraction.h" #include "fraction_constexpr.hpp" using namespace std; using namespace g54327; const size_t N_FRACTIONS = 50; void exe2(); void exe6(); void exe89(); static void printFraction(std::string, const std::vector<Fraction> &); static void printFraction(std::string, const std::vector<const Fraction *> &); static void printFraction(std::string, const std::vector<std::reference_wrapper<Fraction>> &); int main() { utils::exercise("Exercice 8.2", exe2); utils::exercise("Exercice 8.6 + 8.7", exe6); utils::exercise("Exercice 8.8 + 8.9", exe89); } void exe2() { cout << "cout << Sign::PLUS => " << Sign::PLUS << endl; cout << "cout << Sign::MINUS => " << Sign::MINUS << endl; cout << "cout << Sign::ZERO => " << Sign::ZERO << endl; } void exe6() { auto v = nvs::data_signed(N_FRACTIONS); std::vector<Fraction> fractions{N_FRACTIONS}; size_t errors{}; for (auto tuple : v) { try { fractions.emplace_back( Fraction{ std::get<0>(tuple), std::get<1>(tuple) }); } catch (std::invalid_argument &e) { ++errors; } } cout << "error_count: " << errors << endl << "fractions.size(): " << fractions.size() << endl << endl; printFraction("fractions content: ", fractions); std::vector<const Fraction *> fractions_ptr{fractions.size()}; std::generate(fractions_ptr.begin(), fractions_ptr.end(), [&fractions]() -> const Fraction * { static int i = 0; return &fractions[i++]; } ); printFraction("before sorting (pointer): ", fractions_ptr); std::sort( fractions_ptr.begin(), fractions_ptr.end(), [](const Fraction *f1, const Fraction *f2) { return *f1 < *f2; }); printFraction("after sorting (pointer): ", fractions_ptr); } void exe89() { auto v = nvs::data_unsigned(N_FRACTIONS); std::vector<Fraction> fractions{N_FRACTIONS}; size_t errors{}; for (auto tuple : v) { try { fractions.emplace_back( Fraction{ g54327::sign(std::get<0>(tuple)), std::get<1>(tuple), std::get<2>(tuple) }); } catch (std::invalid_argument &e) { ++errors; } } cout << "error_count: " << errors << endl << "fractions.size(): " << fractions.size() << endl << endl; printFraction("fractions content: ", fractions); std::vector<std::reference_wrapper<Fraction>> rw{fractions.begin(), fractions.end()}; printFraction("before sorting (reference wrapper): ", rw); std::sort(rw.begin(), rw.end(), std::less<>()); printFraction("after sorting (reference wrapper): ", rw); } void printFraction(std::string description, const vector<Fraction> &fractions) { int i = 1; cout << description.data() << endl; for (const auto &fraction : fractions) { cout << fraction << (i++ % 16 == 0 ? "\n" : " "); } cout << endl << endl; } void printFraction(std::string description, const vector<const Fraction *> &fractions) { int i = 1; cout << description.data() << endl; for (const auto fraction : fractions) { cout << *fraction << (i++ % 16 == 0 ? "\n" : " "); } cout << endl << endl; } void printFraction(std::string description, const vector<std::reference_wrapper<Fraction>> &fractions) { int i = 1; cout << description.data() << endl; for (const auto &fraction : fractions) { cout << fraction << (i++ % 16 == 0 ? "\n" : " "); } cout << endl << endl; }
26.45
104
0.594923
asassoye
dc07c6a88c77000ad10ff33d1bc6243b2c0bf212
703
cpp
C++
Source/Engine/Old/Private/Component.cpp
cyj0912/Construct3
7a24c59e830e26762e02af98419392b881198933
[ "WTFPL" ]
null
null
null
Source/Engine/Old/Private/Component.cpp
cyj0912/Construct3
7a24c59e830e26762e02af98419392b881198933
[ "WTFPL" ]
null
null
null
Source/Engine/Old/Private/Component.cpp
cyj0912/Construct3
7a24c59e830e26762e02af98419392b881198933
[ "WTFPL" ]
null
null
null
#include "Component.h" C3_NAMESPACE_BEGIN CBaseComponent::CBaseComponent() { RefCount = 0; } void CBaseComponent::AddRef() { RefCount++; } void CBaseComponent::Release() { auto count = RefCount--; if (count == 0) delete this; } TypeId CBaseComponent::RealType() { return GetTypeId<IComponent>(); } bool CBaseComponent::IsType(TypeId id) { if (id == GetTypeId<IComponent>()) return true; return false; } bool CBaseComponent::QueryInterface(TypeId iid, void **outPtr) { bool success = false; if (iid == GetTypeId<IComponent>()) { success = true; *outPtr = static_cast<IComponent*>(this); } return success; } CMovable::CMovable() { } CMovable::~CMovable() { } C3_NAMESPACE_END
13.264151
62
0.692745
cyj0912
dc088ec29b504b6cba126846e4f5513a380338bd
2,191
hpp
C++
ReactNativeFrontend/ios/Pods/boost/boost/geometry/index/detail/rtree/node/pairs.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
ios/Pods/boost-for-react-native/boost/geometry/index/detail/rtree/node/pairs.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
ios/Pods/boost-for-react-native/boost/geometry/index/detail/rtree/node/pairs.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
// Boost.Geometry Index // // Pairs intended to be used internally in nodes. // // Copyright (c) 2011-2013 Adam Wulkiewicz, Lodz, Poland. // // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_INDEX_DETAIL_RTREE_NODE_PAIRS_HPP #define BOOST_GEOMETRY_INDEX_DETAIL_RTREE_NODE_PAIRS_HPP #include <boost/move/move.hpp> namespace boost { namespace geometry { namespace index { namespace detail { namespace rtree { template <typename First, typename Pointer> class ptr_pair { public: typedef First first_type; typedef Pointer second_type; ptr_pair(First const& f, Pointer s) : first(f), second(s) {} //ptr_pair(ptr_pair const& p) : first(p.first), second(p.second) {} //ptr_pair & operator=(ptr_pair const& p) { first = p.first; second = p.second; return *this; } first_type first; second_type second; }; template <typename First, typename Pointer> inline ptr_pair<First, Pointer> make_ptr_pair(First const& f, Pointer s) { return ptr_pair<First, Pointer>(f, s); } // TODO: It this will be used, rename it to unique_ptr_pair and possibly use unique_ptr. template <typename First, typename Pointer> class exclusive_ptr_pair { BOOST_MOVABLE_BUT_NOT_COPYABLE(exclusive_ptr_pair) public: typedef First first_type; typedef Pointer second_type; exclusive_ptr_pair(First const& f, Pointer s) : first(f), second(s) {} // INFO - members aren't really moved! exclusive_ptr_pair(BOOST_RV_REF(exclusive_ptr_pair) p) : first(p.first), second(p.second) { p.second = 0; } exclusive_ptr_pair & operator=(BOOST_RV_REF(exclusive_ptr_pair) p) { first = p.first; second = p.second; p.second = 0; return *this; } first_type first; second_type second; }; template <typename First, typename Pointer> inline exclusive_ptr_pair<First, Pointer> make_exclusive_ptr_pair(First const& f, Pointer s) { return exclusive_ptr_pair<First, Pointer>(f, s); } }} // namespace detail::rtree }}} // namespace boost::geometry::index #endif // BOOST_GEOMETRY_INDEX_DETAIL_RTREE_NODE_PAIRS_HPP
30.430556
138
0.740301
Harshitha91