hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
βŒ€
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
βŒ€
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
βŒ€
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
βŒ€
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
βŒ€
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
βŒ€
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
βŒ€
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
βŒ€
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
βŒ€
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
bbb1648c52e622191533db49eef76b1e528b96eb
1,661
hpp
C++
modules/test/src/Test/gmTestController.hpp
GraphMIC/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
43
2016-04-11T11:34:05.000Z
2022-03-31T03:37:57.000Z
modules/test/src/Test/gmTestController.hpp
kevinlq/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
1
2016-05-17T12:58:16.000Z
2016-05-17T12:58:16.000Z
modules/test/src/Test/gmTestController.hpp
kevinlq/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
14
2016-05-13T20:23:16.000Z
2021-12-20T10:33:19.000Z
#pragma once #include <QQmlListProperty> #include <QObject> #include <QHash> namespace gm { namespace Node { class Object; } namespace Test { class List; class Instance; class Unit; class Controller : public QObject { Q_OBJECT Q_PROPERTY(QQmlListProperty<gm::Test::Unit> units READ getUnitList NOTIFY unitListChanged); Q_PROPERTY(QString stateString READ getStateString NOTIFY stateStringChanged); Q_PROPERTY(bool loading READ isLoading NOTIFY loadingChanged); Q_PROPERTY(bool running READ isRunning NOTIFY runningChanged); private: QList<Unit*> m_units; QString m_stateString; Unit* m_activeUnit = nullptr; bool m_abort = false;; bool m_running = false; bool m_loading = false; Controller(); public: static Controller* instance; static auto Create() -> Controller*; auto getUnitList() -> QQmlListProperty<Unit>; auto setStateString(const QString&) -> void; auto getStateString() -> QString; auto setActiveUnit(Unit*) -> void; auto setLoading(bool) -> void; auto isLoading() -> bool; auto setRunning(bool) -> void; auto isRunning() -> bool; public slots: void init(); void runUnits(); signals: void stateStringChanged(); void unitListChanged(); void runningChanged(); void loadingChanged(); }; } }
29.660714
103
0.556893
GraphMIC
bbb535048b0ade82e5d9714ad923177fb19a9c26
2,007
cpp
C++
library/dynamicProgramming/optimizationKnuth.cpp
bluedawnstar/algorithm_library
4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6
[ "Unlicense" ]
40
2017-11-26T05:29:18.000Z
2020-11-13T00:29:26.000Z
library/dynamicProgramming/optimizationKnuth.cpp
bluedawnstar/algorithm_library
4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6
[ "Unlicense" ]
101
2019-02-09T06:06:09.000Z
2021-12-25T16:55:37.000Z
library/dynamicProgramming/optimizationKnuth.cpp
bluedawnstar/algorithm_library
4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6
[ "Unlicense" ]
6
2017-01-03T14:17:58.000Z
2021-01-22T10:37:04.000Z
#include <cmath> #include <vector> #include <algorithm> using namespace std; #include "optimizationKnuth.h" /////////// For Testing /////////////////////////////////////////////////////// #include <time.h> #include <cassert> #include <string> #include <iostream> #include "../common/iostreamhelper.h" #include "../common/profile.h" #include "../common/rand.h" // https://www.acmicpc.net/problem/11066 static long long solve(const vector<long long>& A) { int N = int(A.size()); vector<long long> S(N + 1); for (int i = 1; i <= N; i++) S[i] = S[i - 1] + A[i - 1]; auto solver = makeKnuthOptimizer(N, 0x3f3f3f3f3f3f3f3fll, [&S](int i, int j) { return S[j] - S[i]; }); return solver.solve(); } static long long solveNaive(const vector<long long>& A) { int N = int(A.size()); vector<long long> S(N + 1); for (int i = 1; i <= N; i++) S[i] = S[i - 1] + A[i - 1]; vector<vector<long long>> dp(N + 1, vector<long long>(N + 1, 0x3f3f3f3f3f3f3f3fll)); for (int d = 0; d <= N; d++) { for (int i = 0; i + d <= N; i++) { int j = i + d; if (d < 2) { dp[i][j] = 0; continue; } dp[i][j] = 0x3f3f3f3f3f3f3f3fll; for (int k = i; k < j; k++) { long long val = dp[i][k] + dp[k][j]; if (val < dp[i][j]) dp[i][j] = val; } dp[i][j] += S[j] - S[i]; } } return dp[0][N]; } void testKnuthOptimization() { return; //TODO: if you want to test, make this line a comment. cout << "--- Knuth Optimization ------------------------" << endl; int N = 100; vector<long long> A(N); for (int i = 0; i < N; i++) A[i] = RandInt32::get() % 1000; auto gt = solveNaive(A); auto ans = solve(A); if (gt != ans) cout << "Mismatch! : gt = " << gt << ", ans = " << ans << endl; assert(gt == ans); cout << "OK!" << endl; }
25.0875
88
0.464873
bluedawnstar
bbb8814fee3e67a4ae25eb23997d9acb4616ef5f
1,180
cpp
C++
oop2_project/GameScreen.cpp
akivagold/Robbery-in-the-Depths
e4a2a1434dbe13af70635483c9c2098afdc0d93c
[ "Apache-2.0" ]
2
2020-08-19T10:19:22.000Z
2021-08-15T15:29:47.000Z
oop2_project/GameScreen.cpp
akivagold/Robbery-in-the-Depths
e4a2a1434dbe13af70635483c9c2098afdc0d93c
[ "Apache-2.0" ]
null
null
null
oop2_project/GameScreen.cpp
akivagold/Robbery-in-the-Depths
e4a2a1434dbe13af70635483c9c2098afdc0d93c
[ "Apache-2.0" ]
2
2020-10-06T08:42:04.000Z
2020-12-24T11:03:35.000Z
#include "GameScreen.h" GameScreen::GameScreen(sf::RenderWindow& window) : BaseScreen(window), m_gameMenu(std::make_shared<GameMenu>(window)), m_world(std::make_shared<World>(window)) { init(); } void GameScreen::loadLevel(const LevelInfo& levelInfo) { // play level music if include const string& backMusicName = levelInfo.getBackMusicName(); if(!backMusicName.empty()) GUI::SoundManager::getInterface().playBackgroundMusic(backMusicName); // update level name getGameMenu()->getLevelNumTV()->setText(levelInfo.getName()); // load world m_world->loadLevel(*this, levelInfo); m_gameAnimText->showText(GameAnimText::TextInfo("Start to play", sf::Color::Black)); } string GameScreen::toString() const { return "GameScreen: { " + m_world->toString() + ", " + BaseClass::toString() + " }"; } void GameScreen::init() { // remove backgroud getBackground().setColor(sf::Color::Transparent); // add world addBackRootView(m_world); // add game menu addView(m_gameMenu, sf::FloatRect(0.f, 0.f, 1.f, 0.2f)); // add game animate text m_gameAnimText = std::make_shared<GameAnimText>(getWindow()); addView(m_gameAnimText, sf::FloatRect(0.f, 0.08f, 1.f, 0.5)); }
28.095238
85
0.716949
akivagold
bbb89a697d12dbf8a53f98a4a0b5dbaf2407429f
2,403
cpp
C++
C++CodeSnippets/LCM of n numbers [With Prime and mod].cpp
Maruf-Tuhin/Online_Judge
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
1
2019-03-31T05:47:30.000Z
2019-03-31T05:47:30.000Z
C++CodeSnippets/LCM of n numbers [With Prime and mod].cpp
the-redback/competitive-programming
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
null
null
null
C++CodeSnippets/LCM of n numbers [With Prime and mod].cpp
the-redback/competitive-programming
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
null
null
null
/** * @author : Maruf Tuhin * @School : CUET CSE 11 * @Topcoder : the_redback * @CodeForces : the_redback * @UVA : the_redback * @link : http://www.fb.com/maruf.2hin */ #include <bits/stdc++.h> using namespace std; #define mp make_pair #define pb(x) push_back(x) #define all(x) x.begin(), x.end() #define mem(a, b) memset(a, b, sizeof(a)) #define inf 1e9 #define eps 1e-9 #define NN 100010 #define mod 1000000007 vector<int> arr; bool pr[350]; vector<int> prim; int mx; int fact[NN]; void sieve(int n) { memset(pr, 0, sizeof(pr)); long i, j, k, l; pr[1] = 1; prim.push_back(2); for (i = 4; i <= n; i += 2) pr[i] = 1; for (i = 3; i <= n; i += 2) { if (pr[i] == 0) { prim.push_back(i); for (j = i * i; j <= n; j += 2 * i) pr[j] = 1; } } } void factor(int n) { int i, j, count; for (j = 0; j < prim.size() && prim[j] * prim[j] <= n; j++) { i = prim[j]; count = 0; if (n % i == 0) { mx = max(i, mx); } while (n % i == 0) { n /= i; count++; } fact[i] = max(fact[i], count); if (n == 1) break; } if (n > 1) { mx = max(n, mx); fact[n] = max(fact[n], 1); } } int bigmod(int m, int n) { int sum; if (n == 0) return 1; if (n % 2 == 0) { sum = bigmod(m, n / 2); return ((sum % mod) * (sum % mod)) % mod; } else { sum = bigmod(m, n - 1); return ((m % mod) * (sum % mod)) % mod; } } int LCM(void) { // LCM of elemets of arr with mod long long sum; int i, j, k; mx = -inf; mem(fact, 0); for (i = 0; i < arr.size(); i++) factor(arr[i]); sum = 1; for (i = 2; i <= mx; i++) if (fact[i]) sum = (sum * bigmod(i, fact[i])) % mod; return sum; } main() { ios_base::sync_with_stdio(0); // cin.tie(0); int t, tc; cin >> tc; int cnt = 0, sum = 0; int i, j, k, l, n, m; sieve(345); // Sieve while (tc--) { cin >> n; arr.clear(); for (i = 1; i <= n; i++) cin >> k, arr.pb(k); sum = LCM(); printf("%d\n", sum); } return 0; } /* Input: 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7 1 2 3 4 5 6 7 5 7 11 13 19 21 Output: 60 60 420 57057 */
18.92126
65
0.426966
Maruf-Tuhin
c7e2caa53e1a1d18aed65f4758726fec42e18bdd
815
cpp
C++
GCC/rule_30.cpp
rondon1947/Zero-to-Hero
c08b036196f0eec016693375a8785c8ec97e940f
[ "MIT" ]
1
2019-11-19T13:22:56.000Z
2019-11-19T13:22:56.000Z
GCC/rule_30.cpp
rondon1947/Zero-to-Hero
c08b036196f0eec016693375a8785c8ec97e940f
[ "MIT" ]
null
null
null
GCC/rule_30.cpp
rondon1947/Zero-to-Hero
c08b036196f0eec016693375a8785c8ec97e940f
[ "MIT" ]
1
2020-06-16T20:11:30.000Z
2020-06-16T20:11:30.000Z
#include <map> #include<iostream> using namespace std; // an implementation of rule 30: // https://en.wikipedia.org/wiki/Rule_30 string step(string level, map<string, string> rules){ level = " " + level + " "; string result = ""; for (int i = 0; i < level.length() - 2; i++) { result = result + rules[level.substr(i, 3)]; } return result; } int main(){ map<string, string> rules; rules[" "] = " "; rules[" X"] = "X"; rules[" X "] = "X"; rules[" XX"] = "X"; rules["X "] = "X"; rules["X X"] = " "; rules["XX "] = " "; rules["XXX"] = " "; string level = "X"; int LEVELS = 20; for (int i = 0; i < LEVELS; i++) { cout << string(LEVELS - i, ' ') + level + "\n"; level = step(level, rules); } return 0; }
18.953488
55
0.483436
rondon1947
c7e7498ee65ed3804a1600b57e14b587727f7a80
379
cpp
C++
src/impl/matrix/populators.cpp
chiku/cmatrix
6fb7cdbe45abc3b0e0c5c4eea7793b0be36e72e8
[ "MIT" ]
2
2015-02-02T01:55:47.000Z
2017-03-25T11:53:16.000Z
src/impl/matrix/populators.cpp
chiku/cmatrix
6fb7cdbe45abc3b0e0c5c4eea7793b0be36e72e8
[ "MIT" ]
null
null
null
src/impl/matrix/populators.cpp
chiku/cmatrix
6fb7cdbe45abc3b0e0c5c4eea7793b0be36e72e8
[ "MIT" ]
null
null
null
// Written by : Chirantan Mitra namespace cmatrix { template <class Type> void Matrix<Type>::fillWith(Type value) { for (long int i = 0; i < rows(); i++) { for (long int j = 0; j < columns(); j++) { access(i, j) = value; } } } template <class Type> inline void Matrix<Type>::fillWithZeros() { fillWith(0); } } // namespace cmatrix
16.478261
50
0.564644
chiku
c7e775dcdd725f94aabb1fe12db1d3af946dee86
1,477
hpp
C++
StoryWriter/NumberSourceDataModel.hpp
hojjatabdollahi/StoryWriter
5df36618ebfa237f826a9965ff2699b7b2422177
[ "MIT" ]
null
null
null
StoryWriter/NumberSourceDataModel.hpp
hojjatabdollahi/StoryWriter
5df36618ebfa237f826a9965ff2699b7b2422177
[ "MIT" ]
null
null
null
StoryWriter/NumberSourceDataModel.hpp
hojjatabdollahi/StoryWriter
5df36618ebfa237f826a9965ff2699b7b2422177
[ "MIT" ]
null
null
null
#pragma once #include <QtCore/QObject> #include <QtWidgets/QLineEdit> #include <nodes/NodeDataModel> #include <iostream> #include "TextEdit/textedit.h" class DecimalData; using QtNodes::PortType; using QtNodes::PortIndex; using QtNodes::NodeData; using QtNodes::NodeDataType; using QtNodes::NodeDataModel; using QtNodes::NodeValidationState; /// The model dictates the number of inputs and outputs for the Node. /// In this example it has no logic. class NumberSourceDataModel : public NodeDataModel { Q_OBJECT public: NumberSourceDataModel(); virtual ~NumberSourceDataModel() {} public: QString caption() const override { return QStringLiteral("Number Source"); } bool captionVisible() const override { return false; } QString name() const override { return QStringLiteral("NumberSource"); } public: QJsonObject save() const override; void restore(QJsonObject const &p) override; public: unsigned int nPorts(PortType portType) const override; NodeDataType dataType(PortType portType, PortIndex portIndex) const override; std::shared_ptr<NodeData> outData(PortIndex port) override; void setInData(std::shared_ptr<NodeData>, int) override { } QWidget * embeddedWidget() override { return _editor; } private slots: void onTextEdited(); private: std::shared_ptr<DecimalData> _number; TextEdit * _editor; };
17.795181
70
0.698037
hojjatabdollahi
c7e7a7ae648fbe9b3ca731d5af3762ef8e022afc
413
cpp
C++
dataStructuresAndAlgorithms/Queue.cpp
ualikhansars/dataStructuresAndAlgorithms
3bf273bd56710579c8725fc509054bb539fe1c1e
[ "MIT" ]
null
null
null
dataStructuresAndAlgorithms/Queue.cpp
ualikhansars/dataStructuresAndAlgorithms
3bf273bd56710579c8725fc509054bb539fe1c1e
[ "MIT" ]
null
null
null
dataStructuresAndAlgorithms/Queue.cpp
ualikhansars/dataStructuresAndAlgorithms
3bf273bd56710579c8725fc509054bb539fe1c1e
[ "MIT" ]
null
null
null
#include <vector> class Queue { std::vector<int> elements; short head = 0; short tail = 0; const short MAX_SIZE = 1000; public: void Enqueue(int newElement) { elements[tail] = newElement; if (tail == MAX_SIZE) { tail = 0; } else { tail += 1; } } int Dequeue() { int element = elements[head]; if (head == MAX_SIZE) { head = 0; } else { head += 1; } return element; } };
13.766667
31
0.576271
ualikhansars
c7efffb3caf2529d4ae3da30181910c61d817251
1,024
hpp
C++
include/Camera.hpp
savageking-io/evelengine
f4f31419077e3467db271e82b05164eafa521eb7
[ "Apache-2.0" ]
null
null
null
include/Camera.hpp
savageking-io/evelengine
f4f31419077e3467db271e82b05164eafa521eb7
[ "Apache-2.0" ]
null
null
null
include/Camera.hpp
savageking-io/evelengine
f4f31419077e3467db271e82b05164eafa521eb7
[ "Apache-2.0" ]
null
null
null
#ifndef __EVEL_ENGINE_CAMERA_HPP__ #define __EVEL_ENGINE_CAMERA_HPP__ #include "Velocity.hpp" #include "Geometry.hpp" namespace EvelEngine { class Camera { public: //! Constructor Camera(int w, int h); //! Destructor ~Camera(); //! Update position of the camera in a game world void setPosition(int x, int y); //! Returns current position of the camera in a game world Vector2D getPosition(); //! Returns X coordinate of the camera (relative to game world) int x(); //! Returns Y coordinate of the camera (relative to game world) int y(); void tick(double delta); Velocity* velocity(); private: int _x; ///< X Position of the camera int _y; ///< Y Position of the camera int _w; ///< Width of the screen int _h; ///< Height of the screen Velocity _velocity; }; } #endif
23.813953
75
0.548828
savageking-io
c7f534ca764945ad6d12daa7b552c4d142707b4d
29,745
cpp
C++
Temp/il2cppOutput/il2cppOutput/Bulk_DOTween43_0.cpp
408794550/871AR
3f903d01ae05522413f7be7abb286d1944d00bbb
[ "Apache-2.0" ]
1
2018-08-16T10:43:30.000Z
2018-08-16T10:43:30.000Z
Temp/il2cppOutput/il2cppOutput/Bulk_DOTween43_0.cpp
408794550/871AR
3f903d01ae05522413f7be7abb286d1944d00bbb
[ "Apache-2.0" ]
null
null
null
Temp/il2cppOutput/il2cppOutput/Bulk_DOTween43_0.cpp
408794550/871AR
3f903d01ae05522413f7be7abb286d1944d00bbb
[ "Apache-2.0" ]
null
null
null
ο»Ώ#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include "class-internals.h" #include "codegen/il2cpp-codegen.h" #include "mscorlib_System_Array3829468939.h" #include "DOTween43_U3CModuleU3E3783534214.h" #include "DOTween43_DG_Tweening_ShortcutExtensions43301896125.h" #include "UnityEngine_UnityEngine_SpriteRenderer1209076198.h" #include "UnityEngine_UnityEngine_Color2020392075.h" #include "DOTween_DG_Tweening_Tweener760404022.h" #include "mscorlib_System_Single2076509932.h" #include "mscorlib_System_Object2689449295.h" #include "mscorlib_System_IntPtr2504060609.h" #include "DOTween43_DG_Tweening_ShortcutExtensions43_U3CU3Ec_426334720.h" #include "mscorlib_System_Void1841601450.h" #include "DOTween_DG_Tweening_Core_DOGetter_1_gen3802498217.h" #include "DOTween_DG_Tweening_Core_DOSetter_1_gen3678621061.h" #include "DOTween_DG_Tweening_Core_TweenerCore_3_gen2998039394.h" #include "DOTween43_DG_Tweening_ShortcutExtensions43_U3CU3Ec_426334751.h" #include "UnityEngine_UnityEngine_Rigidbody2D502193897.h" #include "UnityEngine_UnityEngine_Vector22243707579.h" #include "mscorlib_System_Boolean3825574718.h" #include "DOTween43_DG_Tweening_ShortcutExtensions43_U3CU3Ec_426334817.h" #include "DOTween_DG_Tweening_Core_DOGetter_1_gen4025813721.h" #include "DOTween_DG_Tweening_Core_DOSetter_1_gen3901936565.h" #include "DOTween_DG_Tweening_Core_TweenerCore_3_gen3250868854.h" #include "DOTween43_DG_Tweening_ShortcutExtensions43_U3CU3Ec_426334918.h" #include "DOTween_DG_Tweening_Core_DOGetter_1_gen3858616074.h" #include "DOTween_DG_Tweening_Core_DOSetter_1_gen3734738918.h" #include "DOTween_DG_Tweening_Core_TweenerCore_3_gen2279406887.h" // DG.Tweening.Tweener struct Tweener_t760404022; // UnityEngine.SpriteRenderer struct SpriteRenderer_t1209076198; // DG.Tweening.ShortcutExtensions43/<>c__DisplayClass2_0 struct U3CU3Ec__DisplayClass2_0_t426334720; // DG.Tweening.Core.DOGetter`1<UnityEngine.Color> struct DOGetter_1_t3802498217; // System.Object struct Il2CppObject; // DG.Tweening.Core.DOSetter`1<UnityEngine.Color> struct DOSetter_1_t3678621061; // DG.Tweening.Core.TweenerCore`3<UnityEngine.Color,UnityEngine.Color,DG.Tweening.Plugins.Options.ColorOptions> struct TweenerCore_3_t2998039394; // DG.Tweening.ShortcutExtensions43/<>c__DisplayClass3_0 struct U3CU3Ec__DisplayClass3_0_t426334751; // UnityEngine.Rigidbody2D struct Rigidbody2D_t502193897; // DG.Tweening.ShortcutExtensions43/<>c__DisplayClass5_0 struct U3CU3Ec__DisplayClass5_0_t426334817; // DG.Tweening.Core.DOGetter`1<UnityEngine.Vector2> struct DOGetter_1_t4025813721; // DG.Tweening.Core.DOSetter`1<UnityEngine.Vector2> struct DOSetter_1_t3901936565; // DG.Tweening.Core.TweenerCore`3<UnityEngine.Vector2,UnityEngine.Vector2,DG.Tweening.Plugins.Options.VectorOptions> struct TweenerCore_3_t3250868854; // DG.Tweening.ShortcutExtensions43/<>c__DisplayClass8_0 struct U3CU3Ec__DisplayClass8_0_t426334918; // DG.Tweening.Core.DOGetter`1<System.Single> struct DOGetter_1_t3858616074; // DG.Tweening.Core.DOSetter`1<System.Single> struct DOSetter_1_t3734738918; // DG.Tweening.Core.TweenerCore`3<System.Single,System.Single,DG.Tweening.Plugins.Options.FloatOptions> struct TweenerCore_3_t2279406887; extern Il2CppClass* U3CU3Ec__DisplayClass2_0_t426334720_il2cpp_TypeInfo_var; extern Il2CppClass* DOGetter_1_t3802498217_il2cpp_TypeInfo_var; extern Il2CppClass* DOSetter_1_t3678621061_il2cpp_TypeInfo_var; extern Il2CppClass* DOTween_t2276353038_il2cpp_TypeInfo_var; extern const MethodInfo* U3CU3Ec__DisplayClass2_0_U3CDOColorU3Eb__0_m100674497_MethodInfo_var; extern const MethodInfo* DOGetter_1__ctor_m4239784889_MethodInfo_var; extern const MethodInfo* U3CU3Ec__DisplayClass2_0_U3CDOColorU3Eb__1_m3987221727_MethodInfo_var; extern const MethodInfo* DOSetter_1__ctor_m3548377173_MethodInfo_var; extern const MethodInfo* TweenSettingsExtensions_SetTarget_TisTweenerCore_3_t2998039394_m176000339_MethodInfo_var; extern const uint32_t ShortcutExtensions43_DOColor_m243415068_MetadataUsageId; extern Il2CppClass* U3CU3Ec__DisplayClass3_0_t426334751_il2cpp_TypeInfo_var; extern const MethodInfo* U3CU3Ec__DisplayClass3_0_U3CDOFadeU3Eb__0_m3598030411_MethodInfo_var; extern const MethodInfo* U3CU3Ec__DisplayClass3_0_U3CDOFadeU3Eb__1_m934261309_MethodInfo_var; extern const MethodInfo* TweenSettingsExtensions_SetTarget_TisTweener_t760404022_m3764503309_MethodInfo_var; extern const uint32_t ShortcutExtensions43_DOFade_m996156756_MetadataUsageId; extern Il2CppClass* U3CU3Ec__DisplayClass5_0_t426334817_il2cpp_TypeInfo_var; extern Il2CppClass* DOGetter_1_t4025813721_il2cpp_TypeInfo_var; extern Il2CppClass* DOSetter_1_t3901936565_il2cpp_TypeInfo_var; extern const MethodInfo* U3CU3Ec__DisplayClass5_0_U3CDOMoveU3Eb__0_m1899174492_MethodInfo_var; extern const MethodInfo* DOGetter_1__ctor_m2878130562_MethodInfo_var; extern const MethodInfo* Rigidbody2D_MovePosition_m2716592358_MethodInfo_var; extern const MethodInfo* DOSetter_1__ctor_m3532836198_MethodInfo_var; extern const uint32_t ShortcutExtensions43_DOMove_m620609262_MetadataUsageId; extern Il2CppClass* U3CU3Ec__DisplayClass8_0_t426334918_il2cpp_TypeInfo_var; extern Il2CppClass* DOGetter_1_t3858616074_il2cpp_TypeInfo_var; extern Il2CppClass* DOSetter_1_t3734738918_il2cpp_TypeInfo_var; extern const MethodInfo* U3CU3Ec__DisplayClass8_0_U3CDORotateU3Eb__0_m2872299158_MethodInfo_var; extern const MethodInfo* DOGetter_1__ctor_m3288120768_MethodInfo_var; extern const MethodInfo* Rigidbody2D_MoveRotation_m1710763820_MethodInfo_var; extern const MethodInfo* DOSetter_1__ctor_m2613085532_MethodInfo_var; extern const MethodInfo* TweenSettingsExtensions_SetTarget_TisTweenerCore_3_t2279406887_m1304001650_MethodInfo_var; extern const uint32_t ShortcutExtensions43_DORotate_m177144424_MetadataUsageId; // System.Void DG.Tweening.Core.DOGetter`1<UnityEngine.Color>::.ctor(System.Object,System.IntPtr) extern "C" void DOGetter_1__ctor_m4239784889_gshared (DOGetter_1_t3802498217 * __this, Il2CppObject * p0, IntPtr_t p1, const MethodInfo* method); // System.Void DG.Tweening.Core.DOSetter`1<UnityEngine.Color>::.ctor(System.Object,System.IntPtr) extern "C" void DOSetter_1__ctor_m3548377173_gshared (DOSetter_1_t3678621061 * __this, Il2CppObject * p0, IntPtr_t p1, const MethodInfo* method); // !!0 DG.Tweening.TweenSettingsExtensions::SetTarget<System.Object>(!!0,System.Object) extern "C" Il2CppObject * TweenSettingsExtensions_SetTarget_TisIl2CppObject_m988600075_gshared (Il2CppObject * __this /* static, unused */, Il2CppObject * p0, Il2CppObject * p1, const MethodInfo* method); // System.Void DG.Tweening.Core.DOGetter`1<UnityEngine.Vector2>::.ctor(System.Object,System.IntPtr) extern "C" void DOGetter_1__ctor_m2878130562_gshared (DOGetter_1_t4025813721 * __this, Il2CppObject * p0, IntPtr_t p1, const MethodInfo* method); // System.Void DG.Tweening.Core.DOSetter`1<UnityEngine.Vector2>::.ctor(System.Object,System.IntPtr) extern "C" void DOSetter_1__ctor_m3532836198_gshared (DOSetter_1_t3901936565 * __this, Il2CppObject * p0, IntPtr_t p1, const MethodInfo* method); // System.Void DG.Tweening.Core.DOGetter`1<System.Single>::.ctor(System.Object,System.IntPtr) extern "C" void DOGetter_1__ctor_m3288120768_gshared (DOGetter_1_t3858616074 * __this, Il2CppObject * p0, IntPtr_t p1, const MethodInfo* method); // System.Void DG.Tweening.Core.DOSetter`1<System.Single>::.ctor(System.Object,System.IntPtr) extern "C" void DOSetter_1__ctor_m2613085532_gshared (DOSetter_1_t3734738918 * __this, Il2CppObject * p0, IntPtr_t p1, const MethodInfo* method); // System.Void DG.Tweening.ShortcutExtensions43/<>c__DisplayClass2_0::.ctor() extern "C" void U3CU3Ec__DisplayClass2_0__ctor_m610386080 (U3CU3Ec__DisplayClass2_0_t426334720 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Void DG.Tweening.Core.DOGetter`1<UnityEngine.Color>::.ctor(System.Object,System.IntPtr) #define DOGetter_1__ctor_m4239784889(__this, p0, p1, method) (( void (*) (DOGetter_1_t3802498217 *, Il2CppObject *, IntPtr_t, const MethodInfo*))DOGetter_1__ctor_m4239784889_gshared)(__this, p0, p1, method) // System.Void DG.Tweening.Core.DOSetter`1<UnityEngine.Color>::.ctor(System.Object,System.IntPtr) #define DOSetter_1__ctor_m3548377173(__this, p0, p1, method) (( void (*) (DOSetter_1_t3678621061 *, Il2CppObject *, IntPtr_t, const MethodInfo*))DOSetter_1__ctor_m3548377173_gshared)(__this, p0, p1, method) // DG.Tweening.Core.TweenerCore`3<UnityEngine.Color,UnityEngine.Color,DG.Tweening.Plugins.Options.ColorOptions> DG.Tweening.DOTween::To(DG.Tweening.Core.DOGetter`1<UnityEngine.Color>,DG.Tweening.Core.DOSetter`1<UnityEngine.Color>,UnityEngine.Color,System.Single) extern "C" TweenerCore_3_t2998039394 * DOTween_To_m3916872722 (Il2CppObject * __this /* static, unused */, DOGetter_1_t3802498217 * p0, DOSetter_1_t3678621061 * p1, Color_t2020392075 p2, float p3, const MethodInfo* method) IL2CPP_METHOD_ATTR; // !!0 DG.Tweening.TweenSettingsExtensions::SetTarget<DG.Tweening.Core.TweenerCore`3<UnityEngine.Color,UnityEngine.Color,DG.Tweening.Plugins.Options.ColorOptions>>(!!0,System.Object) #define TweenSettingsExtensions_SetTarget_TisTweenerCore_3_t2998039394_m176000339(__this /* static, unused */, p0, p1, method) (( TweenerCore_3_t2998039394 * (*) (Il2CppObject * /* static, unused */, TweenerCore_3_t2998039394 *, Il2CppObject *, const MethodInfo*))TweenSettingsExtensions_SetTarget_TisIl2CppObject_m988600075_gshared)(__this /* static, unused */, p0, p1, method) // System.Void DG.Tweening.ShortcutExtensions43/<>c__DisplayClass3_0::.ctor() extern "C" void U3CU3Ec__DisplayClass3_0__ctor_m647217151 (U3CU3Ec__DisplayClass3_0_t426334751 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // DG.Tweening.Tweener DG.Tweening.DOTween::ToAlpha(DG.Tweening.Core.DOGetter`1<UnityEngine.Color>,DG.Tweening.Core.DOSetter`1<UnityEngine.Color>,System.Single,System.Single) extern "C" Tweener_t760404022 * DOTween_ToAlpha_m4132971413 (Il2CppObject * __this /* static, unused */, DOGetter_1_t3802498217 * p0, DOSetter_1_t3678621061 * p1, float p2, float p3, const MethodInfo* method) IL2CPP_METHOD_ATTR; // !!0 DG.Tweening.TweenSettingsExtensions::SetTarget<DG.Tweening.Tweener>(!!0,System.Object) #define TweenSettingsExtensions_SetTarget_TisTweener_t760404022_m3764503309(__this /* static, unused */, p0, p1, method) (( Tweener_t760404022 * (*) (Il2CppObject * /* static, unused */, Tweener_t760404022 *, Il2CppObject *, const MethodInfo*))TweenSettingsExtensions_SetTarget_TisIl2CppObject_m988600075_gshared)(__this /* static, unused */, p0, p1, method) // System.Void DG.Tweening.ShortcutExtensions43/<>c__DisplayClass5_0::.ctor() extern "C" void U3CU3Ec__DisplayClass5_0__ctor_m725487805 (U3CU3Ec__DisplayClass5_0_t426334817 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Void DG.Tweening.Core.DOGetter`1<UnityEngine.Vector2>::.ctor(System.Object,System.IntPtr) #define DOGetter_1__ctor_m2878130562(__this, p0, p1, method) (( void (*) (DOGetter_1_t4025813721 *, Il2CppObject *, IntPtr_t, const MethodInfo*))DOGetter_1__ctor_m2878130562_gshared)(__this, p0, p1, method) // System.Void DG.Tweening.Core.DOSetter`1<UnityEngine.Vector2>::.ctor(System.Object,System.IntPtr) #define DOSetter_1__ctor_m3532836198(__this, p0, p1, method) (( void (*) (DOSetter_1_t3901936565 *, Il2CppObject *, IntPtr_t, const MethodInfo*))DOSetter_1__ctor_m3532836198_gshared)(__this, p0, p1, method) // DG.Tweening.Core.TweenerCore`3<UnityEngine.Vector2,UnityEngine.Vector2,DG.Tweening.Plugins.Options.VectorOptions> DG.Tweening.DOTween::To(DG.Tweening.Core.DOGetter`1<UnityEngine.Vector2>,DG.Tweening.Core.DOSetter`1<UnityEngine.Vector2>,UnityEngine.Vector2,System.Single) extern "C" TweenerCore_3_t3250868854 * DOTween_To_m432804578 (Il2CppObject * __this /* static, unused */, DOGetter_1_t4025813721 * p0, DOSetter_1_t3901936565 * p1, Vector2_t2243707579 p2, float p3, const MethodInfo* method) IL2CPP_METHOD_ATTR; // DG.Tweening.Tweener DG.Tweening.TweenSettingsExtensions::SetOptions(DG.Tweening.Core.TweenerCore`3<UnityEngine.Vector2,UnityEngine.Vector2,DG.Tweening.Plugins.Options.VectorOptions>,System.Boolean) extern "C" Tweener_t760404022 * TweenSettingsExtensions_SetOptions_m3823322733 (Il2CppObject * __this /* static, unused */, TweenerCore_3_t3250868854 * p0, bool p1, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Void DG.Tweening.ShortcutExtensions43/<>c__DisplayClass8_0::.ctor() extern "C" void U3CU3Ec__DisplayClass8_0__ctor_m844624090 (U3CU3Ec__DisplayClass8_0_t426334918 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Void DG.Tweening.Core.DOGetter`1<System.Single>::.ctor(System.Object,System.IntPtr) #define DOGetter_1__ctor_m3288120768(__this, p0, p1, method) (( void (*) (DOGetter_1_t3858616074 *, Il2CppObject *, IntPtr_t, const MethodInfo*))DOGetter_1__ctor_m3288120768_gshared)(__this, p0, p1, method) // System.Void DG.Tweening.Core.DOSetter`1<System.Single>::.ctor(System.Object,System.IntPtr) #define DOSetter_1__ctor_m2613085532(__this, p0, p1, method) (( void (*) (DOSetter_1_t3734738918 *, Il2CppObject *, IntPtr_t, const MethodInfo*))DOSetter_1__ctor_m2613085532_gshared)(__this, p0, p1, method) // DG.Tweening.Core.TweenerCore`3<System.Single,System.Single,DG.Tweening.Plugins.Options.FloatOptions> DG.Tweening.DOTween::To(DG.Tweening.Core.DOGetter`1<System.Single>,DG.Tweening.Core.DOSetter`1<System.Single>,System.Single,System.Single) extern "C" TweenerCore_3_t2279406887 * DOTween_To_m914278462 (Il2CppObject * __this /* static, unused */, DOGetter_1_t3858616074 * p0, DOSetter_1_t3734738918 * p1, float p2, float p3, const MethodInfo* method) IL2CPP_METHOD_ATTR; // !!0 DG.Tweening.TweenSettingsExtensions::SetTarget<DG.Tweening.Core.TweenerCore`3<System.Single,System.Single,DG.Tweening.Plugins.Options.FloatOptions>>(!!0,System.Object) #define TweenSettingsExtensions_SetTarget_TisTweenerCore_3_t2279406887_m1304001650(__this /* static, unused */, p0, p1, method) (( TweenerCore_3_t2279406887 * (*) (Il2CppObject * /* static, unused */, TweenerCore_3_t2279406887 *, Il2CppObject *, const MethodInfo*))TweenSettingsExtensions_SetTarget_TisIl2CppObject_m988600075_gshared)(__this /* static, unused */, p0, p1, method) // System.Void System.Object::.ctor() extern "C" void Object__ctor_m2551263788 (Il2CppObject * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // UnityEngine.Color UnityEngine.SpriteRenderer::get_color() extern "C" Color_t2020392075 SpriteRenderer_get_color_m345525162 (SpriteRenderer_t1209076198 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SpriteRenderer::set_color(UnityEngine.Color) extern "C" void SpriteRenderer_set_color_m2339931967 (SpriteRenderer_t1209076198 * __this, Color_t2020392075 p0, const MethodInfo* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.Rigidbody2D::get_position() extern "C" Vector2_t2243707579 Rigidbody2D_get_position_m1357256809 (Rigidbody2D_t502193897 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Single UnityEngine.Rigidbody2D::get_rotation() extern "C" float Rigidbody2D_get_rotation_m485450105 (Rigidbody2D_t502193897 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // DG.Tweening.Tweener DG.Tweening.ShortcutExtensions43::DOColor(UnityEngine.SpriteRenderer,UnityEngine.Color,System.Single) extern "C" Tweener_t760404022 * ShortcutExtensions43_DOColor_m243415068 (Il2CppObject * __this /* static, unused */, SpriteRenderer_t1209076198 * ___target0, Color_t2020392075 ___endValue1, float ___duration2, const MethodInfo* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (ShortcutExtensions43_DOColor_m243415068_MetadataUsageId); s_Il2CppMethodInitialized = true; } U3CU3Ec__DisplayClass2_0_t426334720 * V_0 = NULL; { U3CU3Ec__DisplayClass2_0_t426334720 * L_0 = (U3CU3Ec__DisplayClass2_0_t426334720 *)il2cpp_codegen_object_new(U3CU3Ec__DisplayClass2_0_t426334720_il2cpp_TypeInfo_var); U3CU3Ec__DisplayClass2_0__ctor_m610386080(L_0, /*hidden argument*/NULL); V_0 = L_0; U3CU3Ec__DisplayClass2_0_t426334720 * L_1 = V_0; SpriteRenderer_t1209076198 * L_2 = ___target0; NullCheck(L_1); L_1->set_target_0(L_2); U3CU3Ec__DisplayClass2_0_t426334720 * L_3 = V_0; IntPtr_t L_4; L_4.set_m_value_0((void*)(void*)U3CU3Ec__DisplayClass2_0_U3CDOColorU3Eb__0_m100674497_MethodInfo_var); DOGetter_1_t3802498217 * L_5 = (DOGetter_1_t3802498217 *)il2cpp_codegen_object_new(DOGetter_1_t3802498217_il2cpp_TypeInfo_var); DOGetter_1__ctor_m4239784889(L_5, L_3, L_4, /*hidden argument*/DOGetter_1__ctor_m4239784889_MethodInfo_var); U3CU3Ec__DisplayClass2_0_t426334720 * L_6 = V_0; IntPtr_t L_7; L_7.set_m_value_0((void*)(void*)U3CU3Ec__DisplayClass2_0_U3CDOColorU3Eb__1_m3987221727_MethodInfo_var); DOSetter_1_t3678621061 * L_8 = (DOSetter_1_t3678621061 *)il2cpp_codegen_object_new(DOSetter_1_t3678621061_il2cpp_TypeInfo_var); DOSetter_1__ctor_m3548377173(L_8, L_6, L_7, /*hidden argument*/DOSetter_1__ctor_m3548377173_MethodInfo_var); Color_t2020392075 L_9 = ___endValue1; float L_10 = ___duration2; IL2CPP_RUNTIME_CLASS_INIT(DOTween_t2276353038_il2cpp_TypeInfo_var); TweenerCore_3_t2998039394 * L_11 = DOTween_To_m3916872722(NULL /*static, unused*/, L_5, L_8, L_9, L_10, /*hidden argument*/NULL); U3CU3Ec__DisplayClass2_0_t426334720 * L_12 = V_0; NullCheck(L_12); SpriteRenderer_t1209076198 * L_13 = L_12->get_target_0(); TweenerCore_3_t2998039394 * L_14 = TweenSettingsExtensions_SetTarget_TisTweenerCore_3_t2998039394_m176000339(NULL /*static, unused*/, L_11, L_13, /*hidden argument*/TweenSettingsExtensions_SetTarget_TisTweenerCore_3_t2998039394_m176000339_MethodInfo_var); return L_14; } } // DG.Tweening.Tweener DG.Tweening.ShortcutExtensions43::DOFade(UnityEngine.SpriteRenderer,System.Single,System.Single) extern "C" Tweener_t760404022 * ShortcutExtensions43_DOFade_m996156756 (Il2CppObject * __this /* static, unused */, SpriteRenderer_t1209076198 * ___target0, float ___endValue1, float ___duration2, const MethodInfo* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (ShortcutExtensions43_DOFade_m996156756_MetadataUsageId); s_Il2CppMethodInitialized = true; } U3CU3Ec__DisplayClass3_0_t426334751 * V_0 = NULL; { U3CU3Ec__DisplayClass3_0_t426334751 * L_0 = (U3CU3Ec__DisplayClass3_0_t426334751 *)il2cpp_codegen_object_new(U3CU3Ec__DisplayClass3_0_t426334751_il2cpp_TypeInfo_var); U3CU3Ec__DisplayClass3_0__ctor_m647217151(L_0, /*hidden argument*/NULL); V_0 = L_0; U3CU3Ec__DisplayClass3_0_t426334751 * L_1 = V_0; SpriteRenderer_t1209076198 * L_2 = ___target0; NullCheck(L_1); L_1->set_target_0(L_2); U3CU3Ec__DisplayClass3_0_t426334751 * L_3 = V_0; IntPtr_t L_4; L_4.set_m_value_0((void*)(void*)U3CU3Ec__DisplayClass3_0_U3CDOFadeU3Eb__0_m3598030411_MethodInfo_var); DOGetter_1_t3802498217 * L_5 = (DOGetter_1_t3802498217 *)il2cpp_codegen_object_new(DOGetter_1_t3802498217_il2cpp_TypeInfo_var); DOGetter_1__ctor_m4239784889(L_5, L_3, L_4, /*hidden argument*/DOGetter_1__ctor_m4239784889_MethodInfo_var); U3CU3Ec__DisplayClass3_0_t426334751 * L_6 = V_0; IntPtr_t L_7; L_7.set_m_value_0((void*)(void*)U3CU3Ec__DisplayClass3_0_U3CDOFadeU3Eb__1_m934261309_MethodInfo_var); DOSetter_1_t3678621061 * L_8 = (DOSetter_1_t3678621061 *)il2cpp_codegen_object_new(DOSetter_1_t3678621061_il2cpp_TypeInfo_var); DOSetter_1__ctor_m3548377173(L_8, L_6, L_7, /*hidden argument*/DOSetter_1__ctor_m3548377173_MethodInfo_var); float L_9 = ___endValue1; float L_10 = ___duration2; IL2CPP_RUNTIME_CLASS_INIT(DOTween_t2276353038_il2cpp_TypeInfo_var); Tweener_t760404022 * L_11 = DOTween_ToAlpha_m4132971413(NULL /*static, unused*/, L_5, L_8, L_9, L_10, /*hidden argument*/NULL); U3CU3Ec__DisplayClass3_0_t426334751 * L_12 = V_0; NullCheck(L_12); SpriteRenderer_t1209076198 * L_13 = L_12->get_target_0(); Tweener_t760404022 * L_14 = TweenSettingsExtensions_SetTarget_TisTweener_t760404022_m3764503309(NULL /*static, unused*/, L_11, L_13, /*hidden argument*/TweenSettingsExtensions_SetTarget_TisTweener_t760404022_m3764503309_MethodInfo_var); return L_14; } } // DG.Tweening.Tweener DG.Tweening.ShortcutExtensions43::DOMove(UnityEngine.Rigidbody2D,UnityEngine.Vector2,System.Single,System.Boolean) extern "C" Tweener_t760404022 * ShortcutExtensions43_DOMove_m620609262 (Il2CppObject * __this /* static, unused */, Rigidbody2D_t502193897 * ___target0, Vector2_t2243707579 ___endValue1, float ___duration2, bool ___snapping3, const MethodInfo* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (ShortcutExtensions43_DOMove_m620609262_MetadataUsageId); s_Il2CppMethodInitialized = true; } U3CU3Ec__DisplayClass5_0_t426334817 * V_0 = NULL; { U3CU3Ec__DisplayClass5_0_t426334817 * L_0 = (U3CU3Ec__DisplayClass5_0_t426334817 *)il2cpp_codegen_object_new(U3CU3Ec__DisplayClass5_0_t426334817_il2cpp_TypeInfo_var); U3CU3Ec__DisplayClass5_0__ctor_m725487805(L_0, /*hidden argument*/NULL); V_0 = L_0; U3CU3Ec__DisplayClass5_0_t426334817 * L_1 = V_0; Rigidbody2D_t502193897 * L_2 = ___target0; NullCheck(L_1); L_1->set_target_0(L_2); U3CU3Ec__DisplayClass5_0_t426334817 * L_3 = V_0; IntPtr_t L_4; L_4.set_m_value_0((void*)(void*)U3CU3Ec__DisplayClass5_0_U3CDOMoveU3Eb__0_m1899174492_MethodInfo_var); DOGetter_1_t4025813721 * L_5 = (DOGetter_1_t4025813721 *)il2cpp_codegen_object_new(DOGetter_1_t4025813721_il2cpp_TypeInfo_var); DOGetter_1__ctor_m2878130562(L_5, L_3, L_4, /*hidden argument*/DOGetter_1__ctor_m2878130562_MethodInfo_var); U3CU3Ec__DisplayClass5_0_t426334817 * L_6 = V_0; NullCheck(L_6); Rigidbody2D_t502193897 * L_7 = L_6->get_target_0(); IntPtr_t L_8; L_8.set_m_value_0((void*)(void*)Rigidbody2D_MovePosition_m2716592358_MethodInfo_var); DOSetter_1_t3901936565 * L_9 = (DOSetter_1_t3901936565 *)il2cpp_codegen_object_new(DOSetter_1_t3901936565_il2cpp_TypeInfo_var); DOSetter_1__ctor_m3532836198(L_9, L_7, L_8, /*hidden argument*/DOSetter_1__ctor_m3532836198_MethodInfo_var); Vector2_t2243707579 L_10 = ___endValue1; float L_11 = ___duration2; IL2CPP_RUNTIME_CLASS_INIT(DOTween_t2276353038_il2cpp_TypeInfo_var); TweenerCore_3_t3250868854 * L_12 = DOTween_To_m432804578(NULL /*static, unused*/, L_5, L_9, L_10, L_11, /*hidden argument*/NULL); bool L_13 = ___snapping3; Tweener_t760404022 * L_14 = TweenSettingsExtensions_SetOptions_m3823322733(NULL /*static, unused*/, L_12, L_13, /*hidden argument*/NULL); U3CU3Ec__DisplayClass5_0_t426334817 * L_15 = V_0; NullCheck(L_15); Rigidbody2D_t502193897 * L_16 = L_15->get_target_0(); Tweener_t760404022 * L_17 = TweenSettingsExtensions_SetTarget_TisTweener_t760404022_m3764503309(NULL /*static, unused*/, L_14, L_16, /*hidden argument*/TweenSettingsExtensions_SetTarget_TisTweener_t760404022_m3764503309_MethodInfo_var); return L_17; } } // DG.Tweening.Tweener DG.Tweening.ShortcutExtensions43::DORotate(UnityEngine.Rigidbody2D,System.Single,System.Single) extern "C" Tweener_t760404022 * ShortcutExtensions43_DORotate_m177144424 (Il2CppObject * __this /* static, unused */, Rigidbody2D_t502193897 * ___target0, float ___endValue1, float ___duration2, const MethodInfo* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (ShortcutExtensions43_DORotate_m177144424_MetadataUsageId); s_Il2CppMethodInitialized = true; } U3CU3Ec__DisplayClass8_0_t426334918 * V_0 = NULL; { U3CU3Ec__DisplayClass8_0_t426334918 * L_0 = (U3CU3Ec__DisplayClass8_0_t426334918 *)il2cpp_codegen_object_new(U3CU3Ec__DisplayClass8_0_t426334918_il2cpp_TypeInfo_var); U3CU3Ec__DisplayClass8_0__ctor_m844624090(L_0, /*hidden argument*/NULL); V_0 = L_0; U3CU3Ec__DisplayClass8_0_t426334918 * L_1 = V_0; Rigidbody2D_t502193897 * L_2 = ___target0; NullCheck(L_1); L_1->set_target_0(L_2); U3CU3Ec__DisplayClass8_0_t426334918 * L_3 = V_0; IntPtr_t L_4; L_4.set_m_value_0((void*)(void*)U3CU3Ec__DisplayClass8_0_U3CDORotateU3Eb__0_m2872299158_MethodInfo_var); DOGetter_1_t3858616074 * L_5 = (DOGetter_1_t3858616074 *)il2cpp_codegen_object_new(DOGetter_1_t3858616074_il2cpp_TypeInfo_var); DOGetter_1__ctor_m3288120768(L_5, L_3, L_4, /*hidden argument*/DOGetter_1__ctor_m3288120768_MethodInfo_var); U3CU3Ec__DisplayClass8_0_t426334918 * L_6 = V_0; NullCheck(L_6); Rigidbody2D_t502193897 * L_7 = L_6->get_target_0(); IntPtr_t L_8; L_8.set_m_value_0((void*)(void*)Rigidbody2D_MoveRotation_m1710763820_MethodInfo_var); DOSetter_1_t3734738918 * L_9 = (DOSetter_1_t3734738918 *)il2cpp_codegen_object_new(DOSetter_1_t3734738918_il2cpp_TypeInfo_var); DOSetter_1__ctor_m2613085532(L_9, L_7, L_8, /*hidden argument*/DOSetter_1__ctor_m2613085532_MethodInfo_var); float L_10 = ___endValue1; float L_11 = ___duration2; IL2CPP_RUNTIME_CLASS_INIT(DOTween_t2276353038_il2cpp_TypeInfo_var); TweenerCore_3_t2279406887 * L_12 = DOTween_To_m914278462(NULL /*static, unused*/, L_5, L_9, L_10, L_11, /*hidden argument*/NULL); U3CU3Ec__DisplayClass8_0_t426334918 * L_13 = V_0; NullCheck(L_13); Rigidbody2D_t502193897 * L_14 = L_13->get_target_0(); TweenerCore_3_t2279406887 * L_15 = TweenSettingsExtensions_SetTarget_TisTweenerCore_3_t2279406887_m1304001650(NULL /*static, unused*/, L_12, L_14, /*hidden argument*/TweenSettingsExtensions_SetTarget_TisTweenerCore_3_t2279406887_m1304001650_MethodInfo_var); return L_15; } } // System.Void DG.Tweening.ShortcutExtensions43/<>c__DisplayClass2_0::.ctor() extern "C" void U3CU3Ec__DisplayClass2_0__ctor_m610386080 (U3CU3Ec__DisplayClass2_0_t426334720 * __this, const MethodInfo* method) { { Object__ctor_m2551263788(__this, /*hidden argument*/NULL); return; } } // UnityEngine.Color DG.Tweening.ShortcutExtensions43/<>c__DisplayClass2_0::<DOColor>b__0() extern "C" Color_t2020392075 U3CU3Ec__DisplayClass2_0_U3CDOColorU3Eb__0_m100674497 (U3CU3Ec__DisplayClass2_0_t426334720 * __this, const MethodInfo* method) { { SpriteRenderer_t1209076198 * L_0 = __this->get_target_0(); NullCheck(L_0); Color_t2020392075 L_1 = SpriteRenderer_get_color_m345525162(L_0, /*hidden argument*/NULL); return L_1; } } // System.Void DG.Tweening.ShortcutExtensions43/<>c__DisplayClass2_0::<DOColor>b__1(UnityEngine.Color) extern "C" void U3CU3Ec__DisplayClass2_0_U3CDOColorU3Eb__1_m3987221727 (U3CU3Ec__DisplayClass2_0_t426334720 * __this, Color_t2020392075 ___x0, const MethodInfo* method) { { SpriteRenderer_t1209076198 * L_0 = __this->get_target_0(); Color_t2020392075 L_1 = ___x0; NullCheck(L_0); SpriteRenderer_set_color_m2339931967(L_0, L_1, /*hidden argument*/NULL); return; } } // System.Void DG.Tweening.ShortcutExtensions43/<>c__DisplayClass3_0::.ctor() extern "C" void U3CU3Ec__DisplayClass3_0__ctor_m647217151 (U3CU3Ec__DisplayClass3_0_t426334751 * __this, const MethodInfo* method) { { Object__ctor_m2551263788(__this, /*hidden argument*/NULL); return; } } // UnityEngine.Color DG.Tweening.ShortcutExtensions43/<>c__DisplayClass3_0::<DOFade>b__0() extern "C" Color_t2020392075 U3CU3Ec__DisplayClass3_0_U3CDOFadeU3Eb__0_m3598030411 (U3CU3Ec__DisplayClass3_0_t426334751 * __this, const MethodInfo* method) { { SpriteRenderer_t1209076198 * L_0 = __this->get_target_0(); NullCheck(L_0); Color_t2020392075 L_1 = SpriteRenderer_get_color_m345525162(L_0, /*hidden argument*/NULL); return L_1; } } // System.Void DG.Tweening.ShortcutExtensions43/<>c__DisplayClass3_0::<DOFade>b__1(UnityEngine.Color) extern "C" void U3CU3Ec__DisplayClass3_0_U3CDOFadeU3Eb__1_m934261309 (U3CU3Ec__DisplayClass3_0_t426334751 * __this, Color_t2020392075 ___x0, const MethodInfo* method) { { SpriteRenderer_t1209076198 * L_0 = __this->get_target_0(); Color_t2020392075 L_1 = ___x0; NullCheck(L_0); SpriteRenderer_set_color_m2339931967(L_0, L_1, /*hidden argument*/NULL); return; } } // System.Void DG.Tweening.ShortcutExtensions43/<>c__DisplayClass5_0::.ctor() extern "C" void U3CU3Ec__DisplayClass5_0__ctor_m725487805 (U3CU3Ec__DisplayClass5_0_t426334817 * __this, const MethodInfo* method) { { Object__ctor_m2551263788(__this, /*hidden argument*/NULL); return; } } // UnityEngine.Vector2 DG.Tweening.ShortcutExtensions43/<>c__DisplayClass5_0::<DOMove>b__0() extern "C" Vector2_t2243707579 U3CU3Ec__DisplayClass5_0_U3CDOMoveU3Eb__0_m1899174492 (U3CU3Ec__DisplayClass5_0_t426334817 * __this, const MethodInfo* method) { { Rigidbody2D_t502193897 * L_0 = __this->get_target_0(); NullCheck(L_0); Vector2_t2243707579 L_1 = Rigidbody2D_get_position_m1357256809(L_0, /*hidden argument*/NULL); return L_1; } } // System.Void DG.Tweening.ShortcutExtensions43/<>c__DisplayClass8_0::.ctor() extern "C" void U3CU3Ec__DisplayClass8_0__ctor_m844624090 (U3CU3Ec__DisplayClass8_0_t426334918 * __this, const MethodInfo* method) { { Object__ctor_m2551263788(__this, /*hidden argument*/NULL); return; } } // System.Single DG.Tweening.ShortcutExtensions43/<>c__DisplayClass8_0::<DORotate>b__0() extern "C" float U3CU3Ec__DisplayClass8_0_U3CDORotateU3Eb__0_m2872299158 (U3CU3Ec__DisplayClass8_0_t426334918 * __this, const MethodInfo* method) { { Rigidbody2D_t502193897 * L_0 = __this->get_target_0(); NullCheck(L_0); float L_1 = Rigidbody2D_get_rotation_m485450105(L_0, /*hidden argument*/NULL); return L_1; } } #ifdef __clang__ #pragma clang diagnostic pop #endif
67.756264
380
0.830593
408794550
c7f56f8c54a8613c12f591efa6487059481829b5
809
cpp
C++
src/GM_SpecialStage.cpp
MainMemory/CuckySonic
af8e10f3c05b286b830001e73f79d9a7a8edc84e
[ "MIT" ]
2
2020-01-10T06:52:40.000Z
2020-12-17T02:57:30.000Z
src/GM_SpecialStage.cpp
MainMemory/CuckySonic
af8e10f3c05b286b830001e73f79d9a7a8edc84e
[ "MIT" ]
null
null
null
src/GM_SpecialStage.cpp
MainMemory/CuckySonic
af8e10f3c05b286b830001e73f79d9a7a8edc84e
[ "MIT" ]
null
null
null
#include "Game.h" #include "GameConstants.h" #include "Error.h" #include "Log.h" #include "Event.h" #include "Render.h" #include "Fade.h" #include "Input.h" #include "SpecialStage.h" bool GM_SpecialStage(bool *bError) { //Load the special stage SPECIALSTAGE stage("data/SpecialStage/Stage/1"); if (stage.fail != nullptr) return (*bError = true); //Our loop bool bExit = false; while (!(bExit || *bError)) { //Handle events bExit = HandleEvents(); //Update and draw stage stage.Update(); stage.Draw(); //Render our software buffer to the screen if ((*bError = gSoftwareBuffer->RenderToScreen(&stage.backgroundTexture->loadedPalette->colour[0])) == true) break; if (gController[0].press.a) break; } //Return to stage gGameMode = GAMEMODE_GAME; return bExit; }
19.261905
110
0.676143
MainMemory
c7fc8ee82e50b9c1192e93c81036e79d1184ecdc
4,091
cc
C++
steam/interfaces/networkdevicemanager.cc
TBK/argonx
0165caad474d83f020fe29d85e802fae9adecc23
[ "BSD-2-Clause" ]
22
2019-01-15T12:18:25.000Z
2022-03-24T03:39:59.000Z
steam/interfaces/networkdevicemanager.cc
TBK/argonx
0165caad474d83f020fe29d85e802fae9adecc23
[ "BSD-2-Clause" ]
3
2019-07-13T16:16:16.000Z
2020-07-30T10:07:30.000Z
steam/interfaces/networkdevicemanager.cc
TBK/argonx
0165caad474d83f020fe29d85e802fae9adecc23
[ "BSD-2-Clause" ]
2
2019-06-19T10:09:32.000Z
2020-06-29T15:16:58.000Z
#include <precompiled.hh> #include "helpers.hh" #include "steamplatform.hh" using namespace Steam; namespace Reference { #include "SteamStructs/IClientNetworkDeviceManager.h" } template <bool isServer> class ClientNetworkDeviceManager : public Reference::IClientNetworkDeviceManager { public: UserHandle userHandle; ClientNetworkDeviceManager(UserHandle h) : userHandle(h) {} unknown_ret IsInterfaceValid() override { return unknown_ret(); } unknown_ret RefreshDevices() override { return unknown_ret(); } unknown_ret EnumerateNetworkDevices(unsigned int, unsigned int *) override { return unknown_ret(); } unknown_ret GetDeviceType(unsigned int) override { return unknown_ret(); } unknown_ret IsCurrentDevice(unsigned int) override { return unknown_ret(); } unknown_ret IsCurrentlyConnected(unsigned int) override { return unknown_ret(); } unknown_ret GetDeviceIP4(unsigned int, unsigned int, unsigned int *) override { return unknown_ret(); } unknown_ret GetDeviceBroadcastIP4(unsigned int, unsigned int, unsigned int *) override { return unknown_ret(); } unknown_ret GetDeviceIPV6InterfaceIndex(unsigned int) override { return unknown_ret(); } unknown_ret GetDeviceVendor(unsigned int) override { return unknown_ret(); } unknown_ret GetDeviceProduct(unsigned int) override { return unknown_ret(); } unknown_ret GetMacAddress(unsigned int) override { return unknown_ret(); } unknown_ret GetSubnetMaskBitCount(unsigned int, unsigned int, unsigned int *) override { return unknown_ret(); } unknown_ret GetRouterAddressIP4(unsigned int, unsigned int, unsigned int *) override { return unknown_ret(); } unknown_ret GetDNSResolversIP4(unsigned int, unsigned int, unsigned int *) override { return unknown_ret(); } unknown_ret GetDeviceState(unsigned int) override { return unknown_ret(); } unknown_ret GetDevicePluggedState(unsigned int) override { return unknown_ret(); } unknown_ret EnumerateWirelessEndpoints(unsigned int, unsigned int, unsigned int *) override { return unknown_ret(); } unknown_ret GetConnectedWirelessEndpointSSID(unsigned int) override { return unknown_ret(); } unknown_ret GetWirelessSecurityCapabilities(unsigned int) override { return unknown_ret(); } unknown_ret GetWirelessEndpointSSIDUserDisplayString(unsigned int, unsigned int) override { return unknown_ret(); } unknown_ret GetWirelessEndpointStrength(unsigned int, unsigned int) override { return unknown_ret(); } unknown_ret IsSecurityRequired(unsigned int, unsigned int) override { return unknown_ret(); } unknown_ret GetCachedWirelessCredentials(unsigned int, unsigned int) override { return unknown_ret(); } unknown_ret DisconnectFromDevice(unsigned int, bool) override { return unknown_ret(); } unknown_ret SetCustomIPSettings(unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int) override { return unknown_ret(); } unknown_ret ConnectToDevice(unsigned int, unsigned int, char const *, char const *, unsigned int, bool, bool) override { return unknown_ret(); } unknown_ret IsWirelessEndpointForgettable(unsigned int, unsigned int) override { return unknown_ret(); } unknown_ret ForgetWirelessEndpointAutoconnect(unsigned int, unsigned int) override { return unknown_ret(); } unknown_ret IsUsingDHCP(unsigned int) override { return unknown_ret(); } unknown_ret GetCustomIPSettings(unsigned int, unsigned int *, unsigned int *, unsigned int *, unsigned int *, unsigned int *) override { return unknown_ret(); } }; AdaptExposeClientServer(ClientNetworkDeviceManager, "SteamNetworkDeviceManager"); using IClientNetworkDeviceManager = ClientNetworkDeviceManager<false>;
35.267241
140
0.708384
TBK
2a0653d635765a75c91a08f416967c69fca43747
864
cpp
C++
03Operators/03bitFliag.cpp
CedarChennn/myC
b4de17f332788e3e578d304f2a690d2c9a07c004
[ "Apache-2.0" ]
2
2021-01-13T08:55:41.000Z
2021-04-23T15:14:05.000Z
03Operators/03bitFliag.cpp
CedarChennn/myC
b4de17f332788e3e578d304f2a690d2c9a07c004
[ "Apache-2.0" ]
null
null
null
03Operators/03bitFliag.cpp
CedarChennn/myC
b4de17f332788e3e578d304f2a690d2c9a07c004
[ "Apache-2.0" ]
null
null
null
#include <bitset> #include <iostream> int main1() { std::bitset<4> x { 0b1100 }; std::cout << x << '\n'; std::cout << (x >> 1) << '\n'; // shift right by 1, yielding 0110 std::cout << (x << 1) << '\n'; // shift left by 1, yielding 1000 return 0; } // This prints: // 1100 // 0110 // 1000 /* 0 0 0 1 XOR 0 0 1 1 XOR 0 1 1 1 -------- 0 1 0 1 */ int main() { std::bitset<8> bits{ 0b0000'0101 }; // we need 8 bits, start with bit pattern 0000 0101 bits.set(3); // set bit position 3 to 1 (now we have 0000 1101) bits.flip(4); // flip bit 4 (now we have 0001 1101) bits.reset(4); // set bit 4 back to 0 (now we have 0000 1101) std::cout << "All the bits: " << bits << '\n'; std::cout << "Bit 3 has value: " << bits.test(3) << '\n'; std::cout << "Bit 4 has value: " << bits.test(4) << '\n'; return 0; }
20.093023
91
0.527778
CedarChennn
2a1ada77767c02ec5fef37f362bc41dab7ea2814
6,352
cpp
C++
src/playpen/upl_playpen_main.cpp
declued/upl
cf320c255555eb6067a5ab34cf8c5a00fb5e8f19
[ "MIT" ]
null
null
null
src/playpen/upl_playpen_main.cpp
declued/upl
cf320c255555eb6067a5ab34cf8c5a00fb5e8f19
[ "MIT" ]
null
null
null
src/playpen/upl_playpen_main.cpp
declued/upl
cf320c255555eb6067a5ab34cf8c5a00fb5e8f19
[ "MIT" ]
null
null
null
//====================================================================== #include <upl/st_code.hpp> #include <upl/lexer.hpp> #include <upl/input.hpp> #include <upl/errors.hpp> #include <upl/common.hpp> #include <cstdint> #include <iostream> //====================================================================== //====================================================================== //---------------------------------------------------------------------- //====================================================================== void ReportErrors (UPL::Error::Reporter const & err); void TestStringConversions (); void TestInputStream (); void TestLexer (); void TestSTCode (); //====================================================================== int main (int /*argc*/, char * /*argv*/[]) { std::cout << "This is the UPL playpen, where testing and tinkering happens.\n"; std::cout << std::endl; std::cout << "==========================" << std::endl; std::cout << "Testing string conversions" << std::endl; std::cout << "--------------------------" << std::endl; TestStringConversions (); std::cout << std::endl; std::cout << "=====================" << std::endl; std::cout << "Testing input streams" << std::endl; std::cout << "---------------------" << std::endl; TestInputStream (); std::cout << std::endl; std::cout << "=================" << std::endl; std::cout << "Testing the lexer" << std::endl; std::cout << "-----------------" << std::endl; TestLexer (); std::cout << std::endl; std::cout << "====================" << std::endl; std::cout << "Testing the ST Codec" << std::endl; std::cout << "--------------------" << std::endl; TestSTCode (); std::cout << std::endl; return 0; } //====================================================================== void ReportErrors (UPL::Error::Reporter const & err) { using std::wcout; using std::cout; using std::endl; wcout << "Errors: " << err.count() << endl; for (auto const & er : err.reports()) wcout << " " << UPL::ToString(er.file()) << ":" << er.location().line() << "," << er.location().column() << " (" << int(er.category()) << "," << int(er.severity()) << ") : (" << er.number() << ") " << er.message() << endl; } //---------------------------------------------------------------------- void TestStringConversions () { using std::wcout; using std::cout; using std::endl; wcout << UPL::ToString(-14414) << endl; wcout << UPL::ToString(int64_t(-14414LL)) << endl; wcout << UPL::ToString(-14414.0f) << endl; wcout << UPL::ToString(-14414.0) << endl; wcout << UPL::ToString(false) << endl; wcout << UPL::ToString("Hello, world!") << endl; wcout << endl; wcout << UPL::FromString<int>(L"-123456") << endl; wcout << UPL::FromString<uint64_t>(L"123456789012345") << endl; cout << UPL::FromString<std::string>(L"Hello, world!") << endl; } //---------------------------------------------------------------------- void TestInputStream () { using std::wcout; using std::endl; using std::hex; using std::dec; UPL::Error::Reporter err; UPL::UTF8FileStream inp ("sample-utf8-input.txt", err); if (!inp.eoi() && !inp.error()) do { wcout << ((inp.curr() < 32 || inp.curr() > 255) ? L'?' : inp.curr()); wcout << " (0x" << hex << int(inp.curr()) << dec << ")"; wcout << " @" << inp.location().line() << "," << inp.location().column(); wcout << endl; } while (inp.pop()); wcout << endl; ReportErrors (err); wcout << endl; } //---------------------------------------------------------------------- void TestLexer () { using std::wcout; using std::endl; UPL::Error::Reporter err; UPL::UTF8FileStream inp ("sample-program-00.upl", err); UPL::Lexer lex (inp, err); if (!lex.eoi() && !lex.error()) do { UPL::Token const & t = lex.curr(); wcout << "@" << t.location().line() << "," << t.location().column() << " : " << t.typeStr() << " (" << t.uncookedValue() << ")" << endl; } while (lex.pop()); wcout << endl; ReportErrors (err); wcout << endl; } //---------------------------------------------------------------------- void TestSTCode () { using std::wcout; using std::endl; using ST = UPL::Type::STCode; using UPL::Type::Tag; uint32_t test_ints [] = {2, 0, 7, 8, 15, 16, 255, 256, 4095, 4096, 24543563, 3000000000U}; for (auto ti : test_ints) { auto ci = UPL::Type::STCode::SerializeInt(ti); wcout << ti << " -> (" << ci.size() << ") "; //for (auto b : ci) wcout << " " << int(b); for (auto b : ci) wcout << (L"0123456789ABCDEF")[int(b)]; wcout << endl; } wcout << endl; UPL::Type::STContainer reg; auto ir0 = ST::MakeVariant(false, {reg.byTag(Tag::Int), reg.byTag(Tag::Nil), reg.byTag(Tag::String), reg.byTag(Tag::Any)}); auto p0 = ST::Pack(ir0); auto id0 = reg.createType(p0); auto ir1 = ST::MakeFuction(false, id0, {id0, id0, id0, reg.byTag(Tag::Bool)}); auto p1 = ST::Pack(ir1); auto id1 = reg.createType(p1); auto ir2 = ST::MakeMap(false, id1, id0); auto p2 = ST::Pack(ir2); auto id2 = reg.createType(p2); auto ir3 = ST::MakeArray(true, 2000000000, id1); auto p3 = ST::Pack(ir3); auto id3 = reg.createType(p3); auto ir4 = ST::MakeMap(false, id1, id0); auto p4 = ST::Pack(ir4); auto id4 = reg.createType(p4); assert (id4 == id2); auto ir5 = ST::MakeArray(true, 2000000000, id1); auto p5 = ST::Pack(ir5); auto id5 = reg.createType(p5); assert (id5 == id3); UPL::Type::STIR ir [] = {ir0, ir1, ir2, ir3, ir4, ir5}; UPL::Type::PackedST p [] = {p0, p1, p2, p3, p4, p5}; UPL::Type::ID id [] = {id0, id1, id2, id3, id4, id5}; wcout << endl; for (int i = 0; i < 6; ++i) { wcout << "(" << ir[i].size() << ")"; for (auto b : ir[i]) wcout << " " << std::hex << b; wcout << " , "; wcout << "(" << p[i].size() << ")"; for (auto b : p[i]) wcout << " " << std::hex << b; wcout << " , "; wcout << std::dec << id[i] << endl; } wcout << endl; for (unsigned i = 0; i < reg.size(); ++i) { wcout << i << " : "; auto u = reg.unpack(i); wcout << int(u.tag) << ", " << u.is_const << ", " << u.type1 << ", " << u.type2 << ", " << u.size << ", " << "("; for (auto v : u.type_list) wcout << " " << v; wcout << ")" << endl; } } //---------------------------------------------------------------------- //======================================================================
27.617391
124
0.462531
declued
2a1b9ffb29d524f3659a0e8eae06eac3099d3ad2
521
cpp
C++
chapter-13/13.35.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
chapter-13/13.35.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
chapter-13/13.35.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
// is using synthesized version of copy control members: // for copy constructor: no folder contains the pointer which points to this newly constructed Message object; // for destructor: even destructed, folders still contains the pointer which points to the invalid memory space which once stored this destructed object. // for copy assignment constructor: this case is a combination of copy constructor and destructor illustrated above, the folders-message relationship stays the same but it should have been updated.
86.833333
197
0.81382
zero4drift
2a1dec4cfa31f6d0e42fbabb4faf4cdf76307bed
4,472
cc
C++
xapian/xapian-core-1.2.13/backends/chert/chert_alldocsmodifiedpostlist.cc
pgs7179/xapian_modified
0229c9efb9eca19be4c9f463cd4b793672f24198
[ "MIT" ]
2
2021-01-13T21:17:42.000Z
2021-01-13T21:17:42.000Z
xapian/xapian-core-1.2.13/backends/chert/chert_alldocsmodifiedpostlist.cc
Loslove55/tailbench
fbbf3f31e3f0af1bb7db7f07c2e7193b84abb1eb
[ "MIT" ]
null
null
null
xapian/xapian-core-1.2.13/backends/chert/chert_alldocsmodifiedpostlist.cc
Loslove55/tailbench
fbbf3f31e3f0af1bb7db7f07c2e7193b84abb1eb
[ "MIT" ]
null
null
null
/** @file chert_alldocsmodifiedpostlist.cc * @brief A ChertAllDocsPostList plus pending modifications. */ /* Copyright (C) 2008 Lemur Consulting Ltd * Copyright (C) 2006,2007,2008,2009,2010 Olly Betts * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <config.h> #include "chert_alldocsmodifiedpostlist.h" #include "chert_database.h" #include "debuglog.h" #include "str.h" using namespace std; ChertAllDocsModifiedPostList::ChertAllDocsModifiedPostList(Xapian::Internal::RefCntPtr<const ChertDatabase> db_, Xapian::doccount doccount_, const map<Xapian::docid, Xapian::termcount> & doclens_) : ChertAllDocsPostList(db_, doccount_), doclens(doclens_), doclens_it(doclens.begin()) { LOGCALL_CTOR(DB, "ChertAllDocsModifiedPostList", db_.get() | doccount_ | doclens_); } void ChertAllDocsModifiedPostList::skip_deletes(Xapian::weight w_min) { LOGCALL_VOID(DB, "ChertAllDocsModifiedPostList::skip_deletes", w_min); while (!ChertAllDocsPostList::at_end()) { if (doclens_it == doclens.end()) return; if (doclens_it->first != ChertAllDocsPostList::get_docid()) return; if (doclens_it->second != static_cast<Xapian::termcount>(-1)) return; ++doclens_it; ChertAllDocsPostList::next(w_min); } while (doclens_it != doclens.end() && doclens_it->second == static_cast<Xapian::termcount>(-1)) { ++doclens_it; } } Xapian::docid ChertAllDocsModifiedPostList::get_docid() const { LOGCALL(DB, Xapian::docid, "ChertAllDocsModifiedPostList::get_docid()", NO_ARGS); if (doclens_it == doclens.end()) RETURN(ChertAllDocsPostList::get_docid()); if (ChertAllDocsPostList::at_end()) RETURN(doclens_it->first); RETURN(min(doclens_it->first, ChertAllDocsPostList::get_docid())); } Xapian::termcount ChertAllDocsModifiedPostList::get_doclength() const { LOGCALL(DB, Xapian::termcount, "ChertAllDocsModifiedPostList::get_doclength", NO_ARGS); // Override with value from doclens_it (which cannot be -1, because that // would have been skipped past). if (doclens_it != doclens.end() && (ChertAllDocsPostList::at_end() || doclens_it->first <= ChertAllDocsPostList::get_docid())) RETURN(doclens_it->second); RETURN(ChertAllDocsPostList::get_doclength()); } PostList * ChertAllDocsModifiedPostList::next(Xapian::weight w_min) { LOGCALL(DB, PostList *, "ChertAllDocsModifiedPostList::next", w_min); if (have_started) { if (ChertAllDocsPostList::at_end()) { ++doclens_it; skip_deletes(w_min); RETURN(NULL); } Xapian::docid unmod_did = ChertAllDocsPostList::get_docid(); if (doclens_it != doclens.end() && doclens_it->first <= unmod_did) { if (doclens_it->first < unmod_did && doclens_it->second != static_cast<Xapian::termcount>(-1)) { ++doclens_it; skip_deletes(w_min); RETURN(NULL); } ++doclens_it; } } ChertAllDocsPostList::next(w_min); skip_deletes(w_min); RETURN(NULL); } PostList * ChertAllDocsModifiedPostList::skip_to(Xapian::docid desired_did, Xapian::weight w_min) { LOGCALL(DB, PostList *, "ChertAllDocsModifiedPostList::skip_to", desired_did | w_min); if (!ChertAllDocsPostList::at_end()) ChertAllDocsPostList::skip_to(desired_did, w_min); /* FIXME: should we use lower_bound() on the map? */ while (doclens_it != doclens.end() && doclens_it->first < desired_did) { ++doclens_it; } skip_deletes(w_min); RETURN(NULL); } bool ChertAllDocsModifiedPostList::at_end() const { LOGCALL(DB, bool, "ChertAllDocsModifiedPostList::end", NO_ARGS); RETURN(doclens_it == doclens.end() && ChertAllDocsPostList::at_end()); } string ChertAllDocsModifiedPostList::get_description() const { string desc = "ChertAllDocsModifiedPostList(did="; desc += str(get_docid()); desc += ')'; return desc; }
32.882353
112
0.72093
pgs7179
2a1e8f5220dc900d64705852860731371ed7e83d
1,762
cc
C++
src/common/train_sgd.cc
karlmoritz/oxcvsm
02fd78231a8b3c4d48e9e759a3a075d04bcd0529
[ "Apache-2.0" ]
10
2015-02-06T01:41:41.000Z
2017-10-06T15:50:32.000Z
src/common/train_sgd.cc
karlmoritz/oxcvsm
02fd78231a8b3c4d48e9e759a3a075d04bcd0529
[ "Apache-2.0" ]
null
null
null
src/common/train_sgd.cc
karlmoritz/oxcvsm
02fd78231a8b3c4d48e9e759a3a075d04bcd0529
[ "Apache-2.0" ]
4
2015-01-02T10:49:15.000Z
2020-12-30T17:59:22.000Z
// File: train_sgd.cc // Author: Karl Moritz Hermann (mail@karlmoritz.com) // Created: 01-01-2013 // Last Update: Thu 03 Oct 2013 11:48:43 AM BST // STL #include <iostream> #include <cmath> // Boost #include <boost/program_options/variables_map.hpp> #include <boost/program_options/parsers.hpp> #include "shared_defs.h" // L-BFGS #include <lbfgs.h> // Local #include "train_sgd.h" #include "train_update.h" #include "recursive_autoencoder.h" #include "utils.h" using namespace std; namespace bpo = boost::program_options; int train_sgd(Model &model, int iterations, float eta) { Real* vars = nullptr; int number_vars = 0; setVarsAndNumber(vars,number_vars,model); cout << vars; float eta_t0 = eta; WeightVectorType theta(vars,number_vars); Real* dataOne = new Real[number_vars]; Real* dataTwo = new Real[number_vars]; Real* data1 = dataOne; Real* data2 = dataTwo; lbfgsfloatval_t error = 100000; lbfgsfloatval_t new_error = 100000; for (auto iteration = 0; iteration < iterations; ++iteration) { model.rae.debugSize(3); WeightVectorType grad(data1,number_vars); new_error = computeCostAndGrad(model,nullptr,data1,number_vars); cout << "Correct (error): " << new_error << " ... etc: " << eta << endl; cout << "Grad sum " << grad.sum(); cout << "Theta sum " << theta.sum(); grad *= eta; theta -= grad; if (data1 == dataOne) { data1 = dataTwo; data2 = dataOne; } else { data1 = dataOne; data2 = dataTwo; } if (new_error > error) eta *= 0.5; else eta *= 1.05; error = new_error; // if (eta*1000 < eta_t0) // eta = eta_t0; // Hack: if eta gets too small, we reset it and jump out of misery } delete [] dataOne; delete [] dataTwo; return 0; }
23.184211
87
0.658343
karlmoritz
2a2676124533b55eb30268fcb875cb637d7015f1
886
cpp
C++
03/program.cpp
wtrsltnk/adventofcode17
13ba6bd3a64413973971134ae17465029a884933
[ "MIT" ]
1
2017-12-06T08:00:35.000Z
2017-12-06T08:00:35.000Z
03/program.cpp
wtrsltnk/adventofcode17
13ba6bd3a64413973971134ae17465029a884933
[ "MIT" ]
null
null
null
03/program.cpp
wtrsltnk/adventofcode17
13ba6bd3a64413973971134ae17465029a884933
[ "MIT" ]
null
null
null
#include <iostream> #include <functional> #include <numeric> #include "library.h" int main(int argc, char* argv[]) { std::cout << "Advent of Code - 2017\n"; std::cout << "--- Day 3: Spiral Memory ---\n"; if (argc < 2) { std::cout << "*** ERROR *** No input value given, please provide an integer input value.\n"; return 0; } if (!is_positive_number(argv[1])) { std::cout << "*** ERROR *** No numeric value given, please provide an integer input value.\n"; return 0; } auto value = std::atoi(argv[1]); auto valueLocation = gridLocationOfIndex(value); auto answer1 = manhattanDistance(valueLocation); std::cout << "Answer for day 2 is: " << answer1 << "\n"; auto answer2 = firstValueLargerThanInput(value); std::cout << "Answer for day 2, part two is: " << answer2 << "\n"; return 0; }
23.945946
102
0.588036
wtrsltnk
2a27473128fb2fb6e83925d8b6b0d2c6f40f98f1
2,389
cpp
C++
android-31/java/io/ObjectStreamClass.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/java/io/ObjectStreamClass.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/java/io/ObjectStreamClass.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../JByteArray.hpp" #include "../../JArray.hpp" #include "../../JArray.hpp" #include "../../JArray.hpp" #include "../../JObjectArray.hpp" #include "../../JArray.hpp" #include "./ObjectInputStream.hpp" #include "./ObjectOutputStream.hpp" #include "./ObjectStreamField.hpp" #include "../../JClass.hpp" #include "../lang/ClassNotFoundException.hpp" #include "../lang/Long.hpp" #include "../../JObject.hpp" #include "../../JString.hpp" #include "../../JThrowable.hpp" #include "../lang/invoke/MethodHandle.hpp" #include "../lang/ref/ReferenceQueue.hpp" #include "../lang/reflect/Constructor.hpp" #include "../lang/reflect/Method.hpp" #include "../security/ProtectionDomain.hpp" #include "./ObjectStreamClass.hpp" namespace java::io { // Fields JArray ObjectStreamClass::NO_FIELDS() { return getStaticObjectField( "java.io.ObjectStreamClass", "NO_FIELDS", "[Ljava/io/ObjectStreamField;" ); } // QJniObject forward ObjectStreamClass::ObjectStreamClass(QJniObject obj) : JObject(obj) {} // Constructors // Methods java::io::ObjectStreamClass ObjectStreamClass::lookup(JClass arg0) { return callStaticObjectMethod( "java.io.ObjectStreamClass", "lookup", "(Ljava/lang/Class;)Ljava/io/ObjectStreamClass;", arg0.object<jclass>() ); } java::io::ObjectStreamClass ObjectStreamClass::lookupAny(JClass arg0) { return callStaticObjectMethod( "java.io.ObjectStreamClass", "lookupAny", "(Ljava/lang/Class;)Ljava/io/ObjectStreamClass;", arg0.object<jclass>() ); } JClass ObjectStreamClass::forClass() const { return callObjectMethod( "forClass", "()Ljava/lang/Class;" ); } java::io::ObjectStreamField ObjectStreamClass::getField(JString arg0) const { return callObjectMethod( "getField", "(Ljava/lang/String;)Ljava/io/ObjectStreamField;", arg0.object<jstring>() ); } JArray ObjectStreamClass::getFields() const { return callObjectMethod( "getFields", "()[Ljava/io/ObjectStreamField;" ); } JString ObjectStreamClass::getName() const { return callObjectMethod( "getName", "()Ljava/lang/String;" ); } jlong ObjectStreamClass::getSerialVersionUID() const { return callMethod<jlong>( "getSerialVersionUID", "()J" ); } JString ObjectStreamClass::toString() const { return callObjectMethod( "toString", "()Ljava/lang/String;" ); } } // namespace java::io
22.971154
76
0.690247
YJBeetle
2a2bd246011b018516de3b9fd3d93cf1b371a93e
3,421
cc
C++
src/Experimental/rotateContig.cc
sagrudd/amos
47643a1d238bff83421892cb74daaf6fff8d9548
[ "Artistic-1.0" ]
10
2015-03-20T18:25:56.000Z
2020-06-02T22:00:08.000Z
src/Experimental/rotateContig.cc
sagrudd/amos
47643a1d238bff83421892cb74daaf6fff8d9548
[ "Artistic-1.0" ]
5
2015-05-14T17:51:20.000Z
2020-07-19T04:17:47.000Z
src/Experimental/rotateContig.cc
sagrudd/amos
47643a1d238bff83421892cb74daaf6fff8d9548
[ "Artistic-1.0" ]
10
2015-05-17T16:01:23.000Z
2020-05-20T08:13:43.000Z
#include "foundation_AMOS.hh" #include "amp.hh" #include "fasta.hh" // Rotate a contig to a new offset using namespace AMOS; using namespace std; string bank_name; string contigeid; ID_t contigiid = 0; Pos_t gindex = 0; Pos_t uindex = 0; void PrintUsage(const char * name) { cerr << "Usage: " << name << " [-g gindex | -u uindex] [-E eid | -I iid] bankname" << endl; } void PrintHelp(const char * name) { PrintUsage(name); } void ParseArgs (int argc, char ** argv) { int ch, errflg = 0; optarg = NULL; while ( !errflg && ((ch = getopt (argc, argv, "hvE:I:g:u:")) != EOF) ) { switch (ch) { case 'h': PrintHelp (argv[0]); exit (EXIT_SUCCESS); break; case 'v': PrintBankVersion (argv[0]); exit (EXIT_SUCCESS); break; case 'E': contigeid = optarg; break; case 'I': contigiid = atoi(optarg); break; case 'g': gindex = atoi(optarg); break; case 'u': uindex = atoi(optarg); break; default: errflg ++; }; } if (errflg || optind != argc - 1) { PrintUsage (argv[0]); cerr << "Try '" << argv[0] << " -h' for more information.\n"; exit (EXIT_FAILURE); } bank_name = argv[optind++]; if ((contigeid.empty() && contigiid == NULL_ID) || (!contigeid.empty() && contigiid != NULL_ID)) { cerr << "Must specify one contig id" << endl; exit (EXIT_FAILURE); } if ((gindex == 0 && uindex == 0) || (gindex && uindex)) { cerr << "Must specify one rotation coordinate" << endl; exit (EXIT_FAILURE); } cerr << "Rotating contig eid: " << contigeid << " iid: " << contigiid << " to gindex: " << gindex << " uindex: " << uindex << " in " << bank_name << endl; } int main (int argc, char ** argv) { Bank_t contig_bank(Contig_t::NCODE); ParseArgs(argc, argv); Contig_t contig; cerr << "Processing " << bank_name << " at " << Date() << endl; try { contig_bank.open(bank_name, B_READ|B_WRITE); if (!contigeid.empty()) { contig_bank.fetch(contigeid, contig); } else { contig_bank.fetch(contigiid, contig); } string cons = contig.getSeqString(); string cqual = contig.getQualString(); if (uindex) { gindex = contig.gap2ungap(uindex); } if (gindex < 0 || gindex >= cons.length()) { cerr << "Specified offset " << gindex << " is outside of valid range" << endl; contig_bank.close(); AMOS_THROW("Offset out of range"); } // adjust consensus string left = cons.substr(0, gindex); string lqual = cqual.substr(0, gindex); cons = cons.substr(gindex, cons.length() - gindex); cqual = cqual.substr(gindex, cqual.length() - gindex); cons += left; cqual += lqual; // shift reads vector<Tile_t> & tiling = contig.getReadTiling(); vector<Tile_t>::iterator ti; for (ti = tiling.begin(); ti != tiling.end(); ti++) { ti->offset -= gindex; while (ti->offset < 0) { ti->offset += cons.length(); } while (ti->offset + ti->getGappedLength() - 1 >= cons.length()) { ti->offset -= cons.length(); } } contig.setSequence(cons, cqual); contig_bank.replace(contig.getIID(), contig); contig_bank.close(); } catch (Exception_t & e) { cerr << "ERROR: -- Fatal AMOS Exception --\n" << e; return EXIT_FAILURE; } cerr << "End: " << Date() << endl; return EXIT_SUCCESS; }
22.506579
93
0.572347
sagrudd
2a34d9f06e06a293ab34c292c95631e9054625dd
1,461
cpp
C++
graph/shortest_path/sol/wrong_dijkstra_2.cpp
jellc/library-checker-problems
d8570610d79cdbb70ef8af5a669b57c70556ea01
[ "Apache-2.0" ]
290
2019-06-06T22:20:36.000Z
2022-03-27T12:45:04.000Z
graph/shortest_path/sol/wrong_dijkstra_2.cpp
jellc/library-checker-problems
d8570610d79cdbb70ef8af5a669b57c70556ea01
[ "Apache-2.0" ]
536
2019-06-06T18:25:36.000Z
2022-03-29T11:46:36.000Z
graph/shortest_path/sol/wrong_dijkstra_2.cpp
jellc/library-checker-problems
d8570610d79cdbb70ef8af5a669b57c70556ea01
[ "Apache-2.0" ]
82
2019-06-06T18:17:55.000Z
2022-03-21T07:40:31.000Z
#include <stdio.h> #include <vector> #include <queue> #include <utility> #include <stdint.h> #include <inttypes.h> #include <algorithm> int ri() { int n; scanf("%d", &n); return n; } template<typename T> using pqueue_inv = std::priority_queue<T, std::vector<T>, std::greater<T> >; int main() { int n = ri(); int m = ri(); int s = ri(); int t = ri(); std::vector<std::vector<std::pair<int, int> > > hen(n); std::vector<std::vector<std::pair<int, int> > > rev(n); for (int i = 0; i < m; i++) { int a = ri(); int b = ri(); int c = ri(); hen[a].push_back({b, c}); rev[b].push_back({a, c}); } std::vector<int64_t> dist(n, -1); pqueue_inv<std::pair<int64_t, int> > que; que.push({0, s}); while (que.size()) { auto i = que.top(); que.pop(); if (dist[i.second] == -1) { dist[i.second] = i.first; for (auto j : hen[i.second]) que.push({i.first + j.second, j.first}); } } if (dist[t] == -1) puts("-1"); else { std::vector<int> path; std::vector<bool> used(n); int u = t; path.emplace_back(u); while (s != u) { for (auto [from, cost] : rev[u]) { if (!used[from] && dist[u] - dist[from] == cost) { path.emplace_back(from); used[u] = true; u = from; break; } } } std::reverse(path.begin(), path.end()); printf("%lld %d\n", (long long) dist[t], (int) path.size() - 1); for (int i = 0; i + 1 < (int) path.size(); i++) printf("%d %d\n", path[i], path[i + 1]); } return 0; }
22.476923
97
0.542779
jellc
2a3552f27515c1ae1f70cee690d27f996d263823
5,809
cc
C++
arcane/samples_build/samples/geometry/GeometryModule.cc
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
arcane/samples_build/samples/geometry/GeometryModule.cc
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
arcane/samples_build/samples/geometry/GeometryModule.cc
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
ο»Ώ// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- //----------------------------------------------------------------------------- // Copyright 2000-2021 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- #include <arcane/MathUtils.h> #include <arcane/ITimeLoopMng.h> #include <arcane/IMesh.h> #include <arcane/ItemPrinter.h> #include "Geometry_axl.h" using namespace Arcane; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Real Hexaedron8Volume(ItemWithNodes item,const VariableNodeReal3& n) { Real3 n0 = n[item.node(0)]; Real3 n1 = n[item.node(1)]; Real3 n2 = n[item.node(2)]; Real3 n3 = n[item.node(3)]; Real3 n4 = n[item.node(4)]; Real3 n5 = n[item.node(5)]; Real3 n6 = n[item.node(6)]; Real3 n7 = n[item.node(7)]; Real v1 = math::matDet((n6 - n1) + (n7 - n0), n6 - n3, n2 - n0); Real v2 = math::matDet(n7 - n0, (n6 - n3) + (n5 - n0), n6 - n4); Real v3 = math::matDet(n6 - n1, n5 - n0, (n6 - n4) + (n2 - n0)); Real res = (v1 + v2 + v3) / 12.0; return res; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Real Pyramid5Volume(ItemWithNodes item,const VariableNodeReal3& n) { Real3 n0 = n[item.node(0)]; Real3 n1 = n[item.node(1)]; Real3 n2 = n[item.node(2)]; Real3 n3 = n[item.node(3)]; Real3 n4 = n[item.node(4)]; return math::matDet(n1 - n0, n3 - n0, n4 - n0) + math::matDet(n3 - n2, n1 - n2, n4 - n2); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Real Quad4Surface(ItemWithNodes item,const VariableNodeReal3& n) { Real3 n0 = n[item.node(0)]; Real3 n1 = n[item.node(1)]; Real3 n2 = n[item.node(2)]; Real3 n3 = n[item.node(3)]; Real x1 = n1.x - n0.x; Real y1 = n1.y - n0.y; Real x2 = n2.x - n1.x; Real y2 = n2.y - n1.y; Real surface = x1 * y2 - y1 * x2; x1 = n2.x - n0.x; y1 = n2.y - n0.y; x2 = n3.x - n2.x; y2 = n3.y - n2.y; surface += x1 * y2 - y1 * x2; return surface; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Real Triangle3Surface(ItemWithNodes item,const VariableNodeReal3& n) { Real3 n0 = n[item.node(0)]; Real3 n1 = n[item.node(1)]; Real3 n2 = n[item.node(2)]; Real x1 = n1.x - n0.x; Real y1 = n1.y - n0.y; Real x2 = n2.x - n1.x; Real y2 = n2.y - n1.y; return x1 * y2 - y1 * x2; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ class GeometryDispatcher { public: GeometryDispatcher(VariableNodeReal3& node_coords) : m_node_coords(node_coords) { // Met Γ  null par dΓ©faut. for( Integer i=0; i<NB_BASIC_ITEM_TYPE; ++i ) m_functions[i] = nullptr; // SpΓ©cifie les fonctions pour chaque type qu'on supporte m_functions[IT_Triangle3] = Triangle3Surface; m_functions[IT_Quad4] = Quad4Surface; m_functions[IT_Pyramid5] = Pyramid5Volume; m_functions[IT_Hexaedron8] = Hexaedron8Volume; } public: Real apply(ItemWithNodes item) { Int32 item_type = item.type(); auto f = m_functions[item_type]; if (f!=nullptr) return f(item,m_node_coords); return (-1.0); } private: // Le nombre et les valeurs pour chaque type sont dΓ©finis dans ArcaneTypes.h std::function<Real(ItemWithNodes item,const VariableNodeReal3& n)> m_functions[NB_BASIC_ITEM_TYPE]; VariableNodeReal3 m_node_coords; }; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ class GeometryModule : public ArcaneGeometryObject { public: explicit GeometryModule(const ModuleBuildInfo& mbi) : ArcaneGeometryObject(mbi) { } ~GeometryModule() override = default; public: void init() override; void computeSurfacesAndVolumes() override; VersionInfo versionInfo() const override { return VersionInfo(1, 0, 0); } private: }; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void GeometryModule:: init() { } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void GeometryModule:: computeSurfacesAndVolumes() { // Test d'arrΓͺt de la boucle en temps if (m_global_iteration()>=options()->maxIteration()) subDomain()->timeLoopMng()->stopComputeLoop(true); GeometryDispatcher geom_dispatcher(mesh()->nodesCoordinates()); ENUMERATE_CELL(icell,allCells()){ Cell cell = *icell; Real v = geom_dispatcher.apply(cell); info() << "Cell " << ItemPrinter(cell) << " Volume=" << v; } ENUMERATE_FACE(iface,allFaces()){ Face face = *iface; Real v = geom_dispatcher.apply(face); info() << "Face " << ItemPrinter(face) << " Surface=" << v; } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ARCANE_REGISTER_MODULE_GEOMETRY(GeometryModule); /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
29.48731
101
0.454295
JeromeDuboisPro
2a38efa9c15239d155abe80adc91997ff68a765b
1,204
cpp
C++
src/homework/tic_tac_toe/tic_tac_toe_data.cpp
acc-cosc-1337-spring-2020-hl/acc-cosc-1337-spring-2020-ThomasGreenway115
3e9ccb09ee62cf1d7649cded3086ec76d9136175
[ "MIT" ]
null
null
null
src/homework/tic_tac_toe/tic_tac_toe_data.cpp
acc-cosc-1337-spring-2020-hl/acc-cosc-1337-spring-2020-ThomasGreenway115
3e9ccb09ee62cf1d7649cded3086ec76d9136175
[ "MIT" ]
null
null
null
src/homework/tic_tac_toe/tic_tac_toe_data.cpp
acc-cosc-1337-spring-2020-hl/acc-cosc-1337-spring-2020-ThomasGreenway115
3e9ccb09ee62cf1d7649cded3086ec76d9136175
[ "MIT" ]
1
2020-04-10T02:20:49.000Z
2020-04-10T02:20:49.000Z
#include "tic_tac_toe_data.h" //cpp void TicTacToeData::save_pegs(const std::vector<std::unique_ptr<TicTacToe>> & games) { std::ofstream file_out(file_name, std::ios_base::trunc); for (auto &game : games) { for (auto peg : game->get_pegs()) { file_out << peg ; } file_out << game->get_winner(); file_out << "\n"; } file_out.close(); } std::vector<std::unique_ptr<TicTacToe>> TicTacToeData::get_games() const { std::vector<std::unique_ptr<TicTacToe>> games; std::ifstream read_file(file_name); string line; string get_win; if (read_file.is_open()) { vector<string> peg; while (std::getline(read_file, line)) {} { for (int i = 0; i < line.size(); i++) { if (i == line.size() - 1) { get_win = string(1, line[i]); } else { string game(1, line[i]); peg.push_back(game); } } if (peg.size() < 10) { std::unique_ptr <TicTacToe> game = std::make_unique<TicTacToe3>(peg, get_win); games.push_back(std::move(game)); } else { std::unique_ptr <TicTacToe> game = std::make_unique<TicTacToe4>(peg, get_win); games.push_back(std::move(game)); } } } read_file.close(); return games; }
18.523077
84
0.608804
acc-cosc-1337-spring-2020-hl
2a3b6136813cee61b40036863f8625a041787838
10,671
cpp
C++
source/option/h2_option.cpp
lingjf/h2un
7735c2f07f58ea8b92a9e9608c9b45c98c94c670
[ "Apache-2.0" ]
null
null
null
source/option/h2_option.cpp
lingjf/h2un
7735c2f07f58ea8b92a9e9608c9b45c98c94c670
[ "Apache-2.0" ]
null
null
null
source/option/h2_option.cpp
lingjf/h2un
7735c2f07f58ea8b92a9e9608c9b45c98c94c670
[ "Apache-2.0" ]
null
null
null
/* clang-format off */ static inline void usage() { ::printf(" \033[90mhttps://github.com/lingjf/\033[0m\033[32mh2unit\033[0m \033[90mv\033[0m%s \033[90m%s\033[0m\n", H2PP_STR(H2UNIT_VERSION), H2PP_STR(H2UNIT_REVISION)); #define H2_USAGE_BR "\033[90mβ”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€\033[0m\n" ::printf("\033[90mβ”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”\033[0m\n" "\033[90mβ”‚\033[0m" " -\033[36mb\033[0m " "\033[90mβ”‚\033[0m" " \033[90m[\033[0mn=1\033[90m]\033[0m " "\033[90mβ”‚\033[0m" " \033[36mb\033[0mreak test once n (default 1) cases failed " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36mc\033[0m " "\033[90mβ”‚\033[0m" " " "\033[90mβ”‚\033[0m" " \033[36mc\033[0montinue asserts even if failure occurred " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36md\033[0m " "\033[90mβ”‚\033[0m" " " "\033[90mβ”‚\033[0m" " \033[36md\033[0mebug with gdb once failure occurred " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36mf\033[0m " "\033[90mβ”‚\033[0m" " " "\033[90mβ”‚\033[0m" " Only test last \033[36mf\033[0mailed cases " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36mF\033[0m " "\033[90mβ”‚\033[0m" " \033[90m[\033[0mn=max\033[90m]\033[0m " "\033[90mβ”‚\033[0m" " \033[36mF\033[0mold json print, 0:unfold 1:short 2:same 3:single " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36mi\033[0m\033[90m/\033[0m\033[36me\033[0m" "\033[90mβ”‚\033[0m" "\033[90m[\033[0mpattern .\033[90m]\033[0m" "\033[90mβ”‚\033[0m" " \033[36mi\033[0mnclude\033[90m/\033[0m\033[36me\033[0mxclude case suite or file by substr wildcard " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36ml\033[0m " "\033[90mβ”‚\033[0m" " \033[90m[\033[0mtype .\033[90m]\033[0m " "\033[90mβ”‚\033[0m" " \033[36ml\033[0mist suites cases and tags, type [suite case todo tags] " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36mm\033[0m " "\033[90mβ”‚\033[0m" " " "\033[90mβ”‚\033[0m" " Test cases without \033[36mm\033[0memory check " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36mo\033[0m " "\033[90mβ”‚\033[0m" " \033[90m[\033[0mpath\033[90m]\033[0m " "\033[90mβ”‚\033[0m" " \033[36mo\033[0mutput junit report, default is <executable>.junit.xml " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36mp\033[0m " "\033[90mβ”‚\033[0m" " " "\033[90mβ”‚\033[0m" " Disable test percentage \033[36mp\033[0mrogressing bar " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36mq\033[0m " "\033[90mβ”‚\033[0m" " " "\033[90mβ”‚\033[0m" " \033[36mq\033[0muit exit code as failed cases count " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36mr\033[0m " "\033[90mβ”‚\033[0m" " \033[90m[\033[0mn=2\033[90m]\033[0m " "\033[90mβ”‚\033[0m" " Repeat test n (default 2) \033[36mr\033[0mounds " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36ms\033[0m " "\033[90mβ”‚\033[0m" "\033[90m[\033[0mtype=rand\033[90m]\033[0m" "\033[90mβ”‚\033[0m" " \033[36ms\033[0mhuffle cases random/alphabet/reverse if no last failed " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36mS\033[0m " "\033[90mβ”‚\033[0m" " \033[90m[\033[0mtype=\\\"\033[90m]\033[0m " "\033[90mβ”‚\033[0m" " JSON C/C++ \033[36mS\033[0mource code, type [\\\'/single \\\"/double \\\\\\\"] " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36mt\033[0m " "\033[90mβ”‚\033[0m" " " "\033[90mβ”‚\033[0m" " \033[36mt\033[0mags include/exclude filter " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36mv\033[0m " "\033[90mβ”‚\033[0m" " \033[90m[\033[0mn=max\033[90m]\033[0m " "\033[90mβ”‚\033[0m" " \033[36mv\033[0merbose, 0:quiet 1/2:compact 3:normal 4:details " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36mw\033[0m " "\033[90mβ”‚\033[0m" " " "\033[90mβ”‚\033[0m" " Console output in black-\033[36mw\033[0mhite color style " "\033[90mβ”‚\033[0m\n" H2_USAGE_BR "\033[90mβ”‚\033[0m" " -\033[36mx\033[0m " "\033[90mβ”‚\033[0m" " " "\033[90mβ”‚\033[0m" " Thrown e\033[36mx\033[0mception is considered as failure " "\033[90mβ”‚\033[0m\n" "\033[90mβ””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜\033[0m\n"); } /* clang-format on */ struct getopt { int argc; const char** args; // argv + 1 int i = -1; const char* j = nullptr; getopt(int argc_, const char** args_) : argc(argc_), args(args_) {} const char* extract_next() { return ++i < argc ? args[i] : nullptr; } const char* extract_string() { return (i + 1 < argc && args[i + 1] && args[i + 1][0] != '-') ? args[++i] : nullptr; } const char next_option() { do { for (; j && *++j;) return *j; for (; (j = extract_next()) && j[0] != '-';) {} } while (j); return '\0'; } void extract_number(int& value) { if (j) { // j always not null auto l = strspn(j + 1, "0123456789"); if (l) { value = atoi(j + 1); j += l; return; } } if (i + 1 < argc) { auto l = strlen(args[i + 1]); if (l && strspn(args[i + 1], "0123456789") == l) value = atoi(args[++i]); } } void arguments(char* s) { for (int k = 0; k < argc; ++k) s += sprintf(s, " %s", args[k]); } }; h2_inline void h2_option::parse(int argc, const char** argv) { path = argv[0]; getopt get(argc - 1, argv + 1); get.arguments(args); for (const char* t;;) { switch (get.next_option()) { case '\0': return; case 'b': get.extract_number(break_after_fails = 1); break; case 'c': continue_assert = true; break; case 'd': debugger_trap = true; break; case 'e': while ((t = get.extract_string())) h2_array_append(excludes, t); break; case 'f': only_last_failed = true; break; case 'F': get.extract_number(fold_json = 0); break; case 'i': while ((t = get.extract_string())) h2_array_append(includes, t); break; case 'l': while ((t = get.extract_string())) { const char* r = h2_candidate(t, 4, "suite", "case", "todo", "tags"); if (!strcmp("suite", r)) lists |= ListSuite; else if (!strcmp("case", r)) lists |= ListCase; else if (!strcmp("todo", r)) lists |= ListTodo; else if (!strcmp("tags", r)) lists |= ListTag; else ::printf("-l %s\n", r), exit(-1); } if (!lists) lists = ListSuite | ListCase | ListTodo; break; case 'm': memory_check = !memory_check; break; case 'o': sprintf(junit_path, "%s.junit.xml", path); if ((t = get.extract_string())) strcpy(junit_path, t); break; case 'p': progressing = !progressing; break; case 'q': quit_exit_code = true; break; case 'r': get.extract_number(run_rounds = 2); break; case 's': while ((t = get.extract_string())) { const char* r = h2_candidate(t, 4, "random", "name", "file", "reverse"); if (!strcmp("random", r)) shuffles |= ShuffleRandom; else if (!strcmp("name", r)) shuffles |= ShuffleName; else if (!strcmp("file", r)) shuffles |= ShuffleFile; else if (!strcmp("reverse", r)) shuffles |= ShuffleReverse; else ::printf("-s %s\n", r), exit(-1); } if (!shuffles) shuffles = ShuffleRandom; break; case 'S': json_source_quote = "\\\""; if ((t = get.extract_string())) { const char* r = h2_candidate(t, 5, "\'", "single", "\"", "double", "\\\""); if (!strcmp("\'", r) || !strcmp("single", r)) json_source_quote = "\'"; else if (!strcmp("\"", r) || !strcmp("double", r)) json_source_quote = "\""; else if (!strcmp("\\\"", r)) json_source_quote = "\\\""; else ::printf("-S %s\n", r), exit(-1); if (!h2_in(json_source_quote, 3, "\'", "\"", "\\\"")) json_source_quote = "\\\""; } break; case 't': tags_filter = true; break; case 'v': get.extract_number(verbose = 8); break; case 'w': colorful = !colorful; break; case 'x': exception_as_fail = true; break; case 'h': case '?': usage(); exit(0); } } }
67.537975
310
0.427608
lingjf
2a3bfe978e50ab0e4945569e99cdd293c412a1da
1,585
cpp
C++
src/main.cpp
jhorisberger/ESP8266RGB_Server
9c4c1ad47234c1d14aa460888c7b4a04c7cb5422
[ "Unlicense" ]
null
null
null
src/main.cpp
jhorisberger/ESP8266RGB_Server
9c4c1ad47234c1d14aa460888c7b4a04c7cb5422
[ "Unlicense" ]
null
null
null
src/main.cpp
jhorisberger/ESP8266RGB_Server
9c4c1ad47234c1d14aa460888c7b4a04c7cb5422
[ "Unlicense" ]
null
null
null
#include <Arduino.h> #include "radio.h" #include "tft.h" EspNow32 radio; CustomTFT tft; struct_payload txdata; const byte numChars = 16; char receivedChars[numChars]; // an array to store the received data int testdata = 0; boolean newData = false; void setup() { // start serial port Serial.begin(115200); Serial.println("\n\nESP8266 RGB controller server Debug \n -----------------------------------"); // Setup TFT Display tft.setup(); // Setup Radio radio.setup(); } void recvWithEndMarker() { static byte ndx = 0; char endMarker = '\r'; char rc; //if (Serial.available() > 0) { while (Serial.available() > 0 && newData == false) { rc = Serial.read(); if (rc != endMarker) { receivedChars[ndx] = rc; ndx++; if (ndx >= numChars) { ndx = numChars - 1; } } else { receivedChars[ndx] = '\0'; // terminate the string ndx = 0; newData = true; } } } void showNewData() { if (newData == true) { Serial.print("\n This just in ... "); Serial.println(receivedChars); Serial.println("Sending Testdata..."); testdata = atoi(receivedChars); txdata.SubSet_Type = 1; // Select range txdata.Subset_Index = 1; // ID 1 txdata.SubSet_Range = 1; // Range 1 txdata.Data.Command = 0xF0; // Set Color Direct txdata.Data.Data0 = testdata; txdata.Data.Data1 = testdata/2; txdata.Data.Data2 = testdata/10; txdata.Data.Data3 = 0; radio.payloadTx(txdata); newData = false; } }; void loop() { recvWithEndMarker(); showNewData(); }
17.808989
99
0.596845
jhorisberger
2a3de33f980c986b26957204f7e6d3980dc0f709
6,194
cpp
C++
module/mpc-be/SRC/src/apps/mplayerc/controls/FloatEdit.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/apps/mplayerc/controls/FloatEdit.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/apps/mplayerc/controls/FloatEdit.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
/* * (C) 2003-2006 Gabest * (C) 2006-2018 see Authors.txt * * This file is part of MPC-BE. * * MPC-BE 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. * * MPC-BE 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 "stdafx.h" #include "FloatEdit.h" // CFloatEdit IMPLEMENT_DYNAMIC(CFloatEdit, CEdit) bool CFloatEdit::GetFloat(float& f) { CString s; GetWindowTextW(s); return (swscanf_s(s, L"%f", &f) == 1); } double CFloatEdit::operator = (double d) { CString s; s.Format(L"%.4f", d); s.TrimRight('0'); if (s[s.GetLength() - 1] == '.') s.Truncate(s.GetLength() - 1); SetWindowTextW(s); return d; } CFloatEdit::operator double() { CString s; GetWindowTextW(s); float f = 0; return (swscanf_s(s, L"%f", &f) == 1 ? f : 0); } BEGIN_MESSAGE_MAP(CFloatEdit, CEdit) ON_WM_CHAR() ON_MESSAGE(WM_PASTE, OnPaste) END_MESSAGE_MAP() void CFloatEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { if (nChar >= '0' && nChar <= '9' || nChar == '-' || nChar == '.') { CString str; GetWindowTextW(str); int nStartChar, nEndChar; GetSel(nStartChar, nEndChar); CEdit::OnChar(nChar, nRepCnt, nFlags); CString s; GetWindowTextW(s); float f = 0; wchar_t ch; if (swscanf_s(s, L"%f%c", &f, &ch, 1) != 1 && s != "-") { SetWindowTextW(str); SetSel(nStartChar, nEndChar); }; } else if (nChar == VK_BACK || nChar == 0x01 // Ctrl+A || nChar == 0x03 // Ctrl+C || nChar == 0x16 // Ctrl+V || nChar == 0x18) { // Ctrl+X CEdit::OnChar(nChar, nRepCnt, nFlags); } } LRESULT CFloatEdit::OnPaste(WPARAM wParam, LPARAM lParam) { CString str; GetWindowTextW(str); int nStartChar, nEndChar; GetSel(nStartChar, nEndChar); LRESULT lr = DefWindowProcW(WM_PASTE, wParam, lParam); if (lr == 1) { CString s; GetWindowTextW(s); float f = 0; wchar_t ch; if (swscanf_s(s, L"%f%c", &f, &ch, 1) != 1) { SetWindowTextW(str); SetSel(nStartChar, nEndChar); }; } return lr; } // CIntEdit IMPLEMENT_DYNAMIC(CIntEdit, CEdit) bool CIntEdit::GetInt(int& integer) { CString s; GetWindowTextW(s); return (swscanf_s(s, L"%d", &integer) == 1); } int CIntEdit::operator = (int integer) { CString s; s.Format(L"%d", integer); SetWindowTextW(s); return integer; } CIntEdit::operator int() { CString s; GetWindowTextW(s); int integer; if (swscanf_s(s, L"%d", &integer) != 1) { integer = 0; } integer = std::clamp(integer, m_lower, m_upper); // correction value after the simultaneous input and closing return integer; } void CIntEdit::SetRange(int nLower, int nUpper) { ASSERT(nLower < nUpper); m_lower = nLower; m_upper = nUpper; } BEGIN_MESSAGE_MAP(CIntEdit, CEdit) ON_WM_CHAR() ON_MESSAGE(WM_PASTE, OnPaste) ON_WM_KILLFOCUS() END_MESSAGE_MAP() void CIntEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { if (nChar >= '0' && nChar <= '9' || nChar == '-') { CString str; GetWindowTextW(str); int nStartChar, nEndChar; GetSel(nStartChar, nEndChar); CEdit::OnChar(nChar, nRepCnt, nFlags); CString s; GetWindowTextW(s); int d = 0; wchar_t ch; if (swscanf_s(s, L"%d%c", &d, &ch, 1) != 1 && s != "-") { SetWindowTextW(str); SetSel(nStartChar, nEndChar); }; } else if (nChar == VK_BACK || nChar == 0x01 // Ctrl+A || nChar == 0x03 // Ctrl+C || nChar == 0x16 // Ctrl+V || nChar == 0x18) { // Ctrl+X CEdit::OnChar(nChar, nRepCnt, nFlags); } } LRESULT CIntEdit::OnPaste(WPARAM wParam, LPARAM lParam) { CString str; GetWindowTextW(str); int nStartChar, nEndChar; GetSel(nStartChar, nEndChar); LRESULT lr = DefWindowProcW(WM_PASTE, wParam, lParam); if (lr == 1) { CString s; GetWindowTextW(s); int d = 0; wchar_t ch; if (swscanf_s(s, L"%d%c", &d, &ch, 1) != 1) { SetWindowTextW(str); SetSel(nStartChar, nEndChar); }; } return lr; } void CIntEdit::OnKillFocus (CWnd* pNewWnd) { CString s; GetWindowTextW(s); int integer; if (swscanf_s(s, L"%d", &integer) != 1) { integer = 0; } integer = std::clamp(integer, m_lower, m_upper); s.Format(L"%d", integer); SetWindowTextW(s); CEdit::OnKillFocus(pNewWnd); } // CHexEdit IMPLEMENT_DYNAMIC(CHexEdit, CEdit) bool CHexEdit::GetDWORD(DWORD& dw) { CString s; GetWindowTextW(s); return (swscanf_s(s, L"%x", &dw) == 1); } DWORD CHexEdit::operator = (DWORD dw) { CString s; s.Format(L"%08lx", dw); SetWindowTextW(s); return dw; } CHexEdit::operator DWORD() { CString s; GetWindowTextW(s); DWORD dw; return (swscanf_s(s, L"%x", &dw) == 1 ? dw : 0); } BEGIN_MESSAGE_MAP(CHexEdit, CEdit) ON_WM_CHAR() ON_MESSAGE(WM_PASTE, OnPaste) END_MESSAGE_MAP() void CHexEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { if (nChar >= '0' && nChar <= '9' || nChar >= 'A' && nChar <= 'F' || nChar >= 'a' && nChar <= 'f') { CString str; GetWindowTextW(str); int nStartChar, nEndChar; GetSel(nStartChar, nEndChar); CEdit::OnChar(nChar, nRepCnt, nFlags); CString s; GetWindowTextW(s); DWORD x = 0; wchar_t ch; if (swscanf_s(s, L"%x%c", &x, &ch, 1) != 1) { SetWindowTextW(str); SetSel(nStartChar, nEndChar); }; } else if (nChar == VK_BACK || nChar == 0x01 // Ctrl+A || nChar == 0x03 // Ctrl+C || nChar == 0x16 // Ctrl+V || nChar == 0x18) { // Ctrl+X CEdit::OnChar(nChar, nRepCnt, nFlags); } } LRESULT CHexEdit::OnPaste(WPARAM wParam, LPARAM lParam) { CString str; GetWindowTextW(str); int nStartChar, nEndChar; GetSel(nStartChar, nEndChar); LRESULT lr = DefWindowProcW(WM_PASTE, wParam, lParam); if (lr == 1) { CString s; GetWindowTextW(s); DWORD x = 0; wchar_t ch; if (swscanf_s(s, L"%x%c", &x, &ch, 1) != 1) { SetWindowTextW(str); SetSel(nStartChar, nEndChar); }; } return lr; }
19.601266
110
0.644172
1aq
2a3de877f88051b9707fc4527d0892e6cf659ea0
1,163
cpp
C++
Source/Entities/Sphere.cpp
Avalix/LittleRaytracer
e70c8629d7dc3d1e273c33ed88b75fc60d9ff65b
[ "MIT" ]
null
null
null
Source/Entities/Sphere.cpp
Avalix/LittleRaytracer
e70c8629d7dc3d1e273c33ed88b75fc60d9ff65b
[ "MIT" ]
null
null
null
Source/Entities/Sphere.cpp
Avalix/LittleRaytracer
e70c8629d7dc3d1e273c33ed88b75fc60d9ff65b
[ "MIT" ]
null
null
null
#include "Base.h" #include "Entities/Sphere.h" #include "Maths/HitResult.h" using namespace LittleRaytracer; bool Sphere::TryHitWithRay(const Ray& ray, float tIntervalMin, float tIntervalMax, HitResult& hitResultOut) const { assert(FMath::Equals(Vector3::Length(ray.Direction), 1.0f)); Vector3 RayOrigToCenter = ray.Origin - Center; //CB: Since direction is normalised, this should always be 1 float a = 1.0f; //Vector3::Dot(ray.Direction, ray.Direction); float b = 2.0f * Vector3::Dot(ray.Direction, RayOrigToCenter); float c = Vector3::Dot(RayOrigToCenter, RayOrigToCenter) - Radius * Radius; float t1; float t2; if(FMath::SolveQuadratic(a, b, c, t1, t2) == false) { return false; } if(t1 > t2) { std::swap(t1, t2); } if(t1 < tIntervalMin || t1 > tIntervalMax) { //outside interval, try next t t1 = t2; if(t1 < tIntervalMin || t1 > tIntervalMax) { //Both outside valid interval return false; } } Vector3 hitPoint = ray.PointAlongRayAtT(t1); hitResultOut = HitResult( ray, t1, hitPoint, (hitPoint - Center) / Radius, //Length == Radius, so manually normalise to save perf Material); return true; }
21.537037
87
0.688736
Avalix
2a3fde90a362a6dbda3f067130a247138e9c87cd
311
cc
C++
urionlinejudge.com.br/iniciante/1014_consumo.cc
andrewcpacifico/programming
bbbd16d41d34ea7316e207b8a82ae76377d80420
[ "Apache-2.0" ]
null
null
null
urionlinejudge.com.br/iniciante/1014_consumo.cc
andrewcpacifico/programming
bbbd16d41d34ea7316e207b8a82ae76377d80420
[ "Apache-2.0" ]
null
null
null
urionlinejudge.com.br/iniciante/1014_consumo.cc
andrewcpacifico/programming
bbbd16d41d34ea7316e207b8a82ae76377d80420
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2015 - Andrew C. Pacifico - All Rights Reserved. * @author Andrew C. Pacifico <andrewcpacifico@gmail.com> */ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { double c; int d; scanf("%d%lf", &d, &c); printf("%.3lf km/l\n", d/c); return 0; }
17.277778
65
0.585209
andrewcpacifico
2a42b23d9f3ef388041d2dd4d080d5136aac7420
2,244
cc
C++
src/crypto/passwords.cc
Kledsky/s3fuse
2f2670f16a926ed128ca7bd326e27f43da673d61
[ "Apache-2.0" ]
2
2016-05-26T14:58:48.000Z
2016-10-05T18:46:23.000Z
src/crypto/passwords.cc
Kledsky/s3fuse
2f2670f16a926ed128ca7bd326e27f43da673d61
[ "Apache-2.0" ]
5
2016-03-08T05:06:12.000Z
2017-11-13T07:30:55.000Z
src/crypto/passwords.cc
Kledsky/s3fuse
2f2670f16a926ed128ca7bd326e27f43da673d61
[ "Apache-2.0" ]
2
2018-04-02T09:09:20.000Z
2022-01-20T11:55:29.000Z
/* * crypto/passwords.cc * ------------------------------------------------------------------------- * Password management (implementation). * ------------------------------------------------------------------------- * * Copyright (c) 2012, Tarick Bedeir. * * 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 <signal.h> #include <stdlib.h> #include <string.h> #include <termios.h> #include <unistd.h> #include <iostream> #include <string> #include "crypto/passwords.h" using std::cin; using std::cout; using std::endl; using std::string; using s3::crypto::passwords; namespace { termios s_term_flags_orig; void reset_term_attrs(int, siginfo_t *, void *) { tcsetattr(STDIN_FILENO, TCSANOW, &s_term_flags_orig); exit(1); } } string passwords::read_from_stdin(const string &prompt) { string line; termios term_flags; struct sigaction new_action, old_int_action, old_term_action; memset(&new_action, 0, sizeof(new_action)); memset(&old_int_action, 0, sizeof(old_int_action)); memset(&old_term_action, 0, sizeof(old_term_action)); new_action.sa_sigaction = reset_term_attrs; new_action.sa_flags = SA_SIGINFO; tcgetattr(STDIN_FILENO, &s_term_flags_orig); memcpy(&term_flags, &s_term_flags_orig, sizeof(term_flags)); cout << prompt; term_flags.c_lflag &= ~ECHO; sigaction(SIGINT, &new_action, &old_int_action); sigaction(SIGTERM, &new_action, &old_term_action); tcsetattr(STDIN_FILENO, TCSANOW, &term_flags); try { getline(cin, line); } catch (...) { line.clear(); } tcsetattr(STDIN_FILENO, TCSANOW, &s_term_flags_orig); sigaction(SIGINT, &old_int_action, NULL); sigaction(SIGTERM, &old_term_action, NULL); cout << endl; return line; }
24.659341
76
0.673797
Kledsky
2a4ae5ba5dc501a750fff134fb7b2507953d9b29
732
hpp
C++
src/wstrip/W4AirContainBox.hpp
goroyabu/sim4py
44ae2a6a4adfe347a7ae899c849936ae6fe7caf3
[ "MIT" ]
null
null
null
src/wstrip/W4AirContainBox.hpp
goroyabu/sim4py
44ae2a6a4adfe347a7ae899c849936ae6fe7caf3
[ "MIT" ]
null
null
null
src/wstrip/W4AirContainBox.hpp
goroyabu/sim4py
44ae2a6a4adfe347a7ae899c849936ae6fe7caf3
[ "MIT" ]
null
null
null
/** @file W4AirContainBox.hpp @author Goro Yabu @date 2020/09/15 **/ #ifndef W4AirContainBox_hpp #define W4AirContainBox_hpp #include <P4PVConstruct.hpp> #include <vector> #include <G4VUserDetectorConstruction.hh> #include <G4ThreeVector.hh> #include <globals.hh> class W4AirContainBox : public P4PVConstruct { public: W4AirContainBox(); virtual ~W4AirContainBox(); virtual void Construct(G4LogicalVolume*) override; private: // struct parameter_list // { // int verbose_level; // std::string box_material; // double box_size; // double box_thickness; // G4ThreeVector box_center; // std::string content_material; // }; }; #endif
15.913043
54
0.659836
goroyabu
2a4bce9a9dddfd999f19e37a1a4e02d7638b318c
6,665
cpp
C++
src/RenderFarmUI/RF_SpreadsheetWizard.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
71
2015-12-15T19:32:27.000Z
2022-02-25T04:46:01.000Z
src/RenderFarmUI/RF_SpreadsheetWizard.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
19
2016-07-09T19:08:15.000Z
2021-07-29T10:30:20.000Z
src/RenderFarmUI/RF_SpreadsheetWizard.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
42
2015-12-14T19:13:02.000Z
2022-03-01T15:15:03.000Z
/* * Copyright (c) 2007, Laminar Research. * * 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 "RF_SpreadsheetWizard.h" #include "XPWidgets.h" #include "XPWidgetDialogs.h" #include "RF_Globals.h" #include "RF_Notify.h" #include "RF_Msgs.h" #include "DEMDefs.h" #include "GISTool_Globals.h" static XPWidgetID sWizard = NULL; struct RF_WizardParams { float elev_min; float elev_max; float slop_min; float slop_max; float temp_min; float temp_max; float tmpr_min; float tmpr_max; float rain_min; float rain_max; float sdir_min; float sdir_max; float relv_min; float relv_max; float erng_min; float erng_max; float uden_min; float uden_max; float ucen_min; float ucen_max; float utrn_min; float utrn_max; }; static RF_WizardParams sWizardParams = { 0 }; void RF_WizardAction(XPWidgetID); void RF_ShowSpreadsheetWizard(void) { if (sWizard != NULL) { if (!XPIsWidgetVisible(sWizard)) XPShowWidget(sWizard); else XPBringRootWidgetToFront(sWizard); } else { sWizard = XPCreateWidgetLayout( 0, XP_DIALOG_BOX, "Spreadsheet Params", XP_DIALOG_CLOSEBOX, 1, 0, NULL, XP_COLUMN, // Landuse // Climate // Rain XP_ROW, XP_CAPTION, "Elev Min/Max (M)", XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.elev_min, XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.elev_max, XP_END, XP_ROW, XP_CAPTION, "Slope Min/Max (D)", XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.slop_min, XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.slop_max, XP_END, XP_ROW, XP_CAPTION, "Temp Min/Max (M)", XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.temp_min, XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.temp_max, XP_END, XP_ROW, XP_CAPTION, "Temp Range Min/Max (M)", XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.tmpr_min, XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.tmpr_max, XP_END, XP_ROW, XP_CAPTION, "Rain Min/Max (mm)", XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.rain_min, XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.rain_max, XP_END, XP_ROW, XP_CAPTION, "Slope Dir Min/Max (D)", XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.sdir_min, XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.sdir_max, XP_END, XP_ROW, XP_CAPTION, "Relative Elevation Min/Max", XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.relv_min, XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.relv_max, XP_END, XP_ROW, XP_CAPTION, "Elevation Range Min/Max (M)", XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.erng_min, XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.erng_max, XP_END, XP_ROW, XP_CAPTION, "Urban Density Min/Max", XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.uden_min, XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.uden_max, XP_END, XP_ROW, XP_CAPTION, "Urban Centrality Min/Max", XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.ucen_min, XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.ucen_max, XP_END, XP_ROW, XP_CAPTION, "Urban Transport Min/Max", XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.utrn_min, XP_EDIT_FLOAT, 6, 6, 0, &sWizardParams.utrn_max, XP_END, XP_ROW, XP_BUTTON_ACTION, "Apply", RF_WizardAction, XP_END, XP_END, XP_END); XPShowWidget(sWizard); } } inline float InRange(float minv, float maxv, float vv) { return minv <= vv && vv <= maxv; } inline float FetchEquiv(const DEMGeo& master, const DEMGeo& slave, int x, int y) { if (master.mWidth == slave.mWidth && master.mHeight == slave.mHeight) return slave.get(x,y); else return slave.get(slave.lon_to_x(master.x_to_lon(x)), slave.lat_to_y(master.y_to_lat(y))); } #define TEST_RULE(__DEM, __MIN, __MAX) \ if (gDem.count(__DEM) == 0 || \ sWizardParams.__MIN == sWizardParams.__MAX || \ InRange(sWizardParams.__MIN, sWizardParams.__MAX, FetchEquiv(wizard, gDem[__DEM], x, y))) inline double cosdeg(double deg) { if (deg == 0.0) return 1.0; if (deg == 90.0) return 0.0; if (deg == 180.0) return -1.0; if (deg == -90.0) return 0.0; if (deg == -180.0) return -1.0; return cos(deg * DEG_TO_RAD); } void RF_WizardAction(XPWidgetID) { XPSendMessageToWidget(sWizard, xpMsg_DataFromDialog, xpMode_Recursive, 0, 0); float old_slop_min = sWizardParams.slop_min; float old_slop_max = sWizardParams.slop_max; float old_sdir_min = sWizardParams.sdir_min; float old_sdir_max = sWizardParams.sdir_max; sWizardParams.slop_min = 1.0 - cosdeg(sWizardParams.slop_min); sWizardParams.slop_max = 1.0 - cosdeg(sWizardParams.slop_max); sWizardParams.sdir_min = cosdeg(sWizardParams.sdir_min); sWizardParams.sdir_max = cosdeg(sWizardParams.sdir_max); DEMGeo * widest = NULL; for (DEMGeoMap::iterator dem = gDem.begin(); dem != gDem.end(); ++dem) { if (widest == NULL || (widest->mWidth * widest->mHeight) < (dem->second.mWidth * dem->second.mHeight)) widest = &dem->second; } if (widest == NULL) return; DEMGeo& wizard(gDem[dem_Wizard]); wizard = *widest; for (int y = 0; y < wizard.mHeight; ++y) for (int x = 0; x < wizard.mWidth ; ++x) { wizard(x,y) = 0.0; TEST_RULE(dem_Elevation, elev_min, elev_max) TEST_RULE(dem_Slope, slop_min, slop_max) TEST_RULE(dem_Temperature, temp_min, temp_max) TEST_RULE(dem_TemperatureRange, tmpr_min, tmpr_max) TEST_RULE(dem_Rainfall, rain_min, rain_max) TEST_RULE(dem_SlopeHeading, sdir_min, sdir_max) TEST_RULE(dem_RelativeElevation, relv_min, relv_max) TEST_RULE(dem_ElevationRange, erng_min, erng_max) TEST_RULE(dem_UrbanDensity, uden_min, uden_max) TEST_RULE(dem_UrbanRadial, ucen_min, ucen_max) TEST_RULE(dem_UrbanTransport, utrn_min, utrn_max) { wizard(x,y) = 1.0; } } sWizardParams.slop_min = old_slop_min; sWizardParams.slop_max = old_slop_max; sWizardParams.sdir_min = old_sdir_min; sWizardParams.sdir_max = old_sdir_max; RF_Notifiable::Notify(rf_Cat_File, rf_Msg_RasterChange, NULL); }
40.150602
161
0.727532
rromanchuk
2a4c32c29ef97e3fe10ce59e9189db2b32de8d7f
8,428
hh
C++
tests/Titon/Http/Server/DownloadResponseTest.hh
ciklon-z/framework
cbf44729173d3a83b91a2b0a217c6b3827512e44
[ "BSD-2-Clause" ]
206
2015-01-02T20:01:12.000Z
2021-04-15T09:49:56.000Z
tests/Titon/Http/Server/DownloadResponseTest.hh
ciklon-z/framework
cbf44729173d3a83b91a2b0a217c6b3827512e44
[ "BSD-2-Clause" ]
44
2015-01-02T06:03:43.000Z
2017-11-20T18:29:06.000Z
tests/Titon/Http/Server/DownloadResponseTest.hh
titon/framework
cbf44729173d3a83b91a2b0a217c6b3827512e44
[ "BSD-2-Clause" ]
27
2015-01-03T05:51:29.000Z
2022-02-21T13:50:40.000Z
<?hh namespace Titon\Http\Server; use Titon\Http\Http; use Titon\Test\TestCase; use Titon\Utility\State\Server; class DownloadResponseTest extends TestCase { protected function setUp(): void { parent::setUp(); $this->vfs()->createDirectory('/http/'); $this->vfs()->createFile('/http/download.txt', 'This will be downloaded! Let\'s fluff this file with even more data to increase the file size.'); } /** * @expectedException \Titon\Common\Exception\MissingFileException */ public function testMissingFileErrors(): void { new DownloadResponse($this->vfs()->path('/http/download-missing.txt')); } /** * @expectedException \Titon\Http\Exception\InvalidFileException */ public function testUnwritableFileErrors(): void { $this->vfs()->createFile('/http/download-unwritable.txt', '')->chmod(0300); new DownloadResponse($this->vfs()->path('/http/download-unwritable.txt')); } public function testSend(): void { $time = time(); $response = new DownloadResponse($this->vfs()->path('/http/download.txt')); $response->prepare(Request::createFromGlobals()); $response->date($time); ob_start(); $body = $response->send(); ob_end_clean(); $this->assertEquals([ 'Date' => [gmdate(Http::DATE_FORMAT, $time)], 'Connection' => ['keep-alive'], 'Content-Type' => ['text/plain; charset=UTF-8'], 'Status-Code' => ['200 OK'], 'Content-Disposition' => ['attachment; filename="download.txt"'], 'Accept-Ranges' => ['bytes'], 'Content-Transfer-Encoding' => ['binary'], 'Content-Length' => [93], ], $response->getHeaders()); $this->assertEquals('This will be downloaded! Let\'s fluff this file with even more data to increase the file size.', $body); } public function testSendNoType(): void { $this->vfs()->createFile('/http/download', 'This will be downloaded! Let\'s fluff this file with even more data to increase the file size.'); $time = time(); $response = new DownloadResponse($this->vfs()->path('/http/download')); $response->prepare(Request::createFromGlobals()); $response->date($time); ob_start(); $body = $response->send(); ob_end_clean(); $this->assertEquals([ 'Date' => [gmdate(Http::DATE_FORMAT, $time)], 'Connection' => ['keep-alive'], 'Content-Type' => ['application/octet-stream'], 'Status-Code' => ['200 OK'], 'Content-Disposition' => ['attachment; filename="download"'], 'Accept-Ranges' => ['bytes'], 'Content-Transfer-Encoding' => ['binary'], 'Content-Length' => [93], ], $response->getHeaders()); $this->assertEquals('This will be downloaded! Let\'s fluff this file with even more data to increase the file size.', $body); } public function testSendConfig(): void { $time = time(); $response = Response::download($this->vfs()->path('/http/download.txt'), 'custom-filename.txt', true, true); $response->prepare(Request::createFromGlobals()); $response->date($time); ob_start(); $body = $response->send(); ob_end_clean(); $this->assertEquals([ 'Date' => [gmdate(Http::DATE_FORMAT, $time)], 'Connection' => ['keep-alive'], 'Content-Type' => ['text/plain; charset=UTF-8'], 'Status-Code' => ['200 OK'], 'Content-Disposition' => ['attachment; filename="custom-filename.txt"'], 'Accept-Ranges' => ['bytes'], 'Content-Transfer-Encoding' => ['binary'], 'Last-Modified' => [gmdate(Http::DATE_FORMAT, filemtime($this->vfs()->path('/http/download.txt')))], 'ETag' => ['"3cefcf43cb525cb668db0cb67cccc41a8f90a727"'], 'Content-Length' => [93], ], $response->getHeaders()); $this->assertEquals('This will be downloaded! Let\'s fluff this file with even more data to increase the file size.', $body); } public function testFileRange(): void { $_SERVER['HTTP_RANGE'] = 'bytes=0-5'; Server::initialize($_SERVER); $response = new DownloadResponse($this->vfs()->path('/http/download.txt')); $response->prepare(Request::createFromGlobals()); ob_start(); $response->send(); ob_end_clean(); $this->assertEquals(206, $response->getStatusCode()); $this->assertEquals(6, $response->getHeader('Content-Length')); $this->assertEquals('bytes 0-5/93', $response->getHeader('Content-Range')); } public function testInvalidFileRange(): void { $_SERVER['HTTP_RANGE'] = 'bytes=5-3'; Server::initialize($_SERVER); $response = new DownloadResponse($this->vfs()->path('/http/download.txt')); $response->prepare(Request::createFromGlobals()); ob_start(); $response->send(); ob_end_clean(); $this->assertEquals(416, $response->getStatusCode()); $this->assertEquals(null, $response->getHeader('Content-Length')); $this->assertEquals(null, $response->getHeader('Content-Range')); } public function testSetFileRange(): void { $_SERVER['HTTP_RANGE'] = 'bytes=0-19'; Server::initialize($_SERVER); $path = $this->vfs()->path('/http/download.txt'); $response = new DownloadResponse($path); $response->prepare(Request::createFromGlobals()); $request = $response->getRequest(); invariant($request instanceof Request, 'Must be a Request.'); // Valid starting range $response->setFileRange($path); $this->assertEquals(206, $response->getStatusCode()); $this->assertEquals(20, $response->getHeader('Content-Length')); $this->assertEquals('bytes 0-19/93', $response->getHeader('Content-Range')); // No starting range $request->headers->set('Range', ['bytes=-35']); $response->setFileRange($path); $this->assertEquals(206, $response->getStatusCode()); $this->assertEquals(36, $response->getHeader('Content-Length')); $this->assertEquals('bytes 0-35/93', $response->getHeader('Content-Range')); // No ending range $request->headers->set('Range', ['bytes=45-']); $response->setFileRange($path); $this->assertEquals(206, $response->getStatusCode()); $this->assertEquals(48, $response->getHeader('Content-Length')); $this->assertEquals('bytes 45-92/93', $response->getHeader('Content-Range')); // Valid ending range $request->headers->set('Range', ['bytes=33-92']); $response->setFileRange($path); $this->assertEquals(206, $response->getStatusCode()); $this->assertEquals(60, $response->getHeader('Content-Length')); $this->assertEquals('bytes 33-92/93', $response->getHeader('Content-Range')); // No ranges at all $request->headers->set('Range', ['bytes=-']); $response->setFileRange($path); $this->assertEquals(206, $response->getStatusCode()); $this->assertEquals(93, $response->getHeader('Content-Length')); $this->assertEquals('bytes 0-92/93', $response->getHeader('Content-Range')); // Invalid ranges $request->headers->set('Range', ['bytes=100-0']); $response->setFileRange($path); $this->assertEquals(416, $response->getStatusCode()); $request->headers->set('Range', ['bytes=0-125']); $response->setFileRange($path); $this->assertEquals(416, $response->getStatusCode()); } public function testSetFileRangeIfRange(): void { $_SERVER['HTTP_RANGE'] = 'bytes=0-19'; $_SERVER['HTTP_IF_RANGE'] = 'ETAG'; $_SERVER['HTTP_ETAG'] = 'ETAG'; Server::initialize($_SERVER); $path = $this->vfs()->path('/http/download.txt'); $response = new DownloadResponse($path); $response->prepare(Request::createFromGlobals()); $response->setFileRange($path); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(null, $response->getHeader('Content-Length')); $this->assertEquals(null, $response->getHeader('Content-Range')); } }
37.963964
153
0.592667
ciklon-z
2a4fbcb198d254dfe4a9e5a96c8a2cf3d04c60e5
5,688
hpp
C++
include/json/number.hpp
tymonx/json-cxx-dev
9ff8570ab97df4b9cc9e6357d8c8e5762003de83
[ "Apache-2.0" ]
null
null
null
include/json/number.hpp
tymonx/json-cxx-dev
9ff8570ab97df4b9cc9e6357d8c8e5762003de83
[ "Apache-2.0" ]
null
null
null
include/json/number.hpp
tymonx/json-cxx-dev
9ff8570ab97df4b9cc9e6357d8c8e5762003de83
[ "Apache-2.0" ]
null
null
null
/*! * @copyright * Copyright 2017 Tymoteusz Blazejczyk * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file json/number.hpp * * @brief JSON number interface */ #ifndef JSON_NUMBER_HPP #define JSON_NUMBER_HPP #include "types.hpp" #include <type_traits> namespace json { class Number { public: template<typename T> using enable_int = typename std::enable_if< std::is_integral<T>::value && std::is_signed<T>::value, Int >::type; template<typename T> using enable_uint = typename std::enable_if< std::is_integral<T>::value && !std::is_signed<T>::value, Uint >::type; template<typename T> using enable_double = typename std::enable_if< std::is_floating_point<T>::value, char >::type; enum Type { INT, UINT, DOUBLE }; Number() noexcept = default; Number(Type value) noexcept; template<typename T, enable_int<T> = 0> Number(T value) noexcept; template<typename T, enable_uint<T> = 0> Number(T value) noexcept; template<typename T, enable_double<T> = 0> Number(T value) noexcept; Number& operator++() noexcept; Number& operator--() noexcept; Number operator++(int) noexcept; Number operator--(int) noexcept; Number& operator+=(const Number& other) noexcept; Number& operator-=(const Number& other) noexcept; Number& operator*=(const Number& other) noexcept; Number& operator/=(const Number& other) noexcept; bool operator==(const Number& other) const noexcept; bool operator!=(const Number& other) const noexcept; bool operator<(const Number& other) const noexcept; bool operator>(const Number& other) const noexcept; bool operator<=(const Number& other) const noexcept; bool operator>=(const Number& other) const noexcept; Number operator+() const noexcept; Number operator-() const noexcept; Number operator+(const Number& other) const noexcept; Number operator-(const Number& other) const noexcept; Number operator*(const Number& other) const noexcept; Number operator/(const Number& other) const noexcept; Number operator%(const Number& other) const noexcept; operator Int() const noexcept; operator Uint() const noexcept; operator Double() const noexcept; operator bool() const noexcept; bool operator!() const noexcept; bool is_signed() const noexcept; bool is_unsigned() const noexcept; bool is_integral() const noexcept; bool is_floating_point() const noexcept; Type type() const noexcept; private: Type m_type{INT}; union { Int m_int{0}; Uint m_uint; Double m_double; }; }; template<typename T, Number::enable_int<T>> inline Number::Number(T value) noexcept : m_type{INT}, m_int{Int(value)} { } template<typename T, Number::enable_uint<T>> inline Number::Number(T value) noexcept : m_type{UINT}, m_uint{Uint(value)} { } template<typename T, Number::enable_double<T>> inline Number::Number(T value) noexcept : m_type{DOUBLE}, m_double{Double(value)} { } inline auto Number::operator+=(const Number& other) noexcept -> Number& { return *this = (*this + other); } inline auto Number::operator-=(const Number& other) noexcept -> Number& { return *this = (*this - other); } inline auto Number::operator*=(const Number& other) noexcept -> Number& { return *this = (*this * other); } inline auto Number::operator/=(const Number& other) noexcept -> Number& { return *this = (*this / other); } inline auto Number::type() const noexcept -> Type { return m_type; } inline bool Number::is_signed() const noexcept { return (INT == type()) || (DOUBLE == type()); } inline bool Number::is_unsigned() const noexcept { return (UINT == type()); } inline bool Number::is_integral() const noexcept { return (INT == type()) || (UINT == type()); } inline bool Number::is_floating_point() const noexcept { return (DOUBLE == type()); } inline Number::operator bool() const noexcept { return !!*this; } inline bool Number::operator!=(const Number& other) const noexcept { return !(*this == other); } inline bool Number::operator>(const Number& other) const noexcept { return (other < *this); } inline bool Number::operator>=(const Number& other) const noexcept { return !(*this < other); } inline bool Number::operator<=(const Number& other) const noexcept { return !(other < *this); } inline auto Number::operator+() const noexcept -> Number { return *this; } inline auto Number::operator-() const noexcept -> Number { return (Number() - *this); } inline auto Number::operator++() noexcept -> Number& { return (*this += 1u); } inline auto Number::operator--() noexcept -> Number& { return (*this -= 1u); } inline auto Number::operator++(int) noexcept -> Number { auto value = *this; *this += 1u; return value; } inline auto Number::operator--(int) noexcept -> Number { auto value = *this; *this -= 1u; return value; } } #endif /* JSON_NUMBER_HPP */
21.383459
75
0.66192
tymonx
2a51766917c16ca8f17c68ede9ad5756f51cc37d
410
cpp
C++
DenseAlgebra/GEMM_Test_0_0/MatMatMultiply.cpp
hvenugopalan/CS639S20_Demos
52f0d40bedbb212c4287b7ed55b4ca5cb75d0f8b
[ "BSD-2-Clause" ]
17
2020-01-28T20:49:31.000Z
2021-06-17T03:10:53.000Z
DenseAlgebra/GEMM_Test_0_0/MatMatMultiply.cpp
hvenugopalan/CS639S20_Demos
52f0d40bedbb212c4287b7ed55b4ca5cb75d0f8b
[ "BSD-2-Clause" ]
1
2020-02-11T21:13:35.000Z
2020-02-11T21:13:35.000Z
DenseAlgebra/GEMM_Test_0_0/MatMatMultiply.cpp
hvenugopalan/CS639S20_Demos
52f0d40bedbb212c4287b7ed55b4ca5cb75d0f8b
[ "BSD-2-Clause" ]
11
2020-01-28T20:55:52.000Z
2021-04-29T02:15:06.000Z
#include "MatMatMultiply.h" void MatMatMultiply(const float (&A)[MATRIX_SIZE][MATRIX_SIZE], const float (&B)[MATRIX_SIZE][MATRIX_SIZE], float (&C)[MATRIX_SIZE][MATRIX_SIZE]) { #pragma omp parallel for for (int i = 0; i < MATRIX_SIZE; i++) for (int j = 0; j < MATRIX_SIZE; j++) { C[i][j] = 0.; for (int k = 0; k < MATRIX_SIZE; k++) C[i][j] += A[i][k] * B[k][j]; } }
29.285714
85
0.560976
hvenugopalan
2a5490f594d3e8acb7d350b3557b0dc704872aa1
838
cpp
C++
timus/1982v1.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
3
2018-01-08T02:52:51.000Z
2021-03-03T01:08:44.000Z
timus/1982v1.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
null
null
null
timus/1982v1.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
1
2020-08-13T18:07:35.000Z
2020-08-13T18:07:35.000Z
#include <bits/stdc++.h> #define le 103 #define ll long long int using namespace std; ll n[le][le]; int ve[le]; int main(){ //freopen("input.txt", "r", stdin); int e, len; scanf("%d %d", &e, &len); for(int i = 0; i < len; scanf("%d", &ve[i]), i++); for(int i = 0; i < e; i++){ for(int j = 0; j < e; j++) scanf("%lld", &n[i][j]); } for(int i = 0; i < len; i++){ for(int j = 0; j < len; j++){ int p = ve[i] - 1, q = ve[j] - 1; n[p][q] = 0; } } for(int k = 0; k < e; k++){ for(int i = 0; i < e; i++){ for(int j = 0; j < e; j++){ n[i][j] = min(n[i][j], n[i][k] + n[k][j]); } } } ll ans = 0; for(int i = 0; i < e; i++){ ll sum = INT_MAX; for(int j = 0; j < len; j++) sum = min(sum, n[i][ve[j] - 1]); ans += sum; } printf("%lld\n", ans); return 0; }
22.648649
65
0.420048
cosmicray001
2a58188d83430c99020dc8dbe5015fb6531d3285
22,833
cpp
C++
src/activemasternode.cpp
nexalt-project/nexalt-core
e0c2f3f8ee0eb3ab298dfbbdb1e9d5426c65670f
[ "MIT" ]
7
2021-01-30T11:20:46.000Z
2021-12-04T02:21:19.000Z
src/activemasternode.cpp
nexalt-project/nexalt-core
e0c2f3f8ee0eb3ab298dfbbdb1e9d5426c65670f
[ "MIT" ]
null
null
null
src/activemasternode.cpp
nexalt-project/nexalt-core
e0c2f3f8ee0eb3ab298dfbbdb1e9d5426c65670f
[ "MIT" ]
7
2021-01-17T11:48:40.000Z
2021-05-10T12:15:00.000Z
// Copyright (c) 2012-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The Luxcore developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "protocol.h" #include "activemasternode.h" #include <boost/lexical_cast.hpp> #include "key_io.h" #include "netmessagemaker.h" #include <consensus/validation.h> #include <net.h> #include <txmempool.h> #include <validation.h> #include <validationinterface.h> #include <node/transaction.h> #include "init.h" #include <future> #include "net_processing.h" // // Bootup the masternode, look for a 10000 Xlt input and register on the network // void CActiveMasternode::ManageStatus(CConnman* connman) { std::string errorMessage; if (!fMasterNode) return; if (fDebug) LogPrintf("CActiveMasternode::ManageStatus() - Begin\n"); //need correct adjusted time to send ping bool fIsInitialDownload = IsInitialBlockDownload(); if (fIsInitialDownload) { status = MASTERNODE_SYNC_IN_PROCESS; LogPrintf("CActiveMasternode::ManageStatus() - Sync in progress. Must wait until sync is complete to start masternode.\n"); return; } if (status == MASTERNODE_INPUT_TOO_NEW || status == MASTERNODE_NOT_CAPABLE || status == MASTERNODE_SYNC_IN_PROCESS) { status = MASTERNODE_NOT_PROCESSED; } if (status == MASTERNODE_NOT_PROCESSED) { if (strMasterNodeAddr.empty()) { if (!GetLocal(service)) { notCapableReason = "Can't detect external address. Please use the masternodeaddr configuration option."; status = MASTERNODE_NOT_CAPABLE; LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason.c_str()); return; } } else { service = CService(strMasterNodeAddr,true); } LogPrintf("CActiveMasternode::ManageStatus() - Checking inbound connection to '%s'\n", service.ToString().c_str()); const char *pszDest = service.ToString().c_str(); CAddress addrConnect = CAddress(service, NODE_NETWORK); if (!connman->ConnectNode(addrConnect, pszDest,true,true)) { notCapableReason = "Could not connect to " + service.ToString(); status = MASTERNODE_NOT_CAPABLE; LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason.c_str()); return; } std::string wallet_name = ""; std::shared_ptr<CWallet> pwallet = GetWallet(wallet_name); if (pwallet->IsLocked()) { notCapableReason = "Wallet is locked."; status = MASTERNODE_NOT_CAPABLE; LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason.c_str()); return; } // Set defaults status = MASTERNODE_NOT_CAPABLE; notCapableReason = "Unknown. Check debug.log for more information.\n"; // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; if (GetMasterNodeVin(vin, pubKeyCollateralAddress, keyCollateralAddress)) { if (GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS) { LogPrintf("CActiveMasternode::ManageStatus() - Input must have least %d confirmations - %d confirmations\n", MASTERNODE_MIN_CONFIRMATIONS, GetInputAge(vin)); status = MASTERNODE_INPUT_TOO_NEW; return; } LogPrintf("CActiveMasternode::ManageStatus() - Is capable master node!\n"); status = MASTERNODE_IS_CAPABLE; notCapableReason = ""; pwallet->LockCoin(vin.prevout); // send to all nodes CPubKey pubKeyMasternode; CKey keyMasternode; if (!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrintf("Register::ManageStatus() - Error upon calling SetKey: %s\n", errorMessage.c_str()); return; } if (!Register(connman, vin, service, keyCollateralAddress, pubKeyCollateralAddress, keyMasternode, pubKeyMasternode, errorMessage)) { LogPrintf("CActiveMasternode::ManageStatus() - Error on Register: %s\n", errorMessage.c_str()); } return; } else { LogPrintf("CActiveMasternode::ManageStatus() - Could not find suitable coins!\n"); } } //send to all peers if (!Dseep(connman, errorMessage)) { LogPrintf("CActiveMasternode::ManageStatus() - Error on Ping: %s", errorMessage.c_str()); } } // Send stop dseep to network for remote masternode bool CActiveMasternode::StopMasterNode(CConnman* connman ,std::string strService,std::string strColletralAddress, std::string strKeyMasternode, std::string& errorMessage) { CTxIn vin; CKey keyMasternode; CPubKey pubKeyMasternode; if (!darkSendSigner.SetKey(strKeyMasternode, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrintf("CActiveMasternode::StopMasterNode() - Error: %s\n", errorMessage.c_str()); return false; } if (!GetMasterNodeVinForPubKey(strColletralAddress, vin, pubKeyMasternode, keyMasternode)) { errorMessage = "could not allocate vin for collateralAddress"; LogPrintf("Register::Register() - Error: %s\n", errorMessage.c_str()); return false; } return StopMasterNode(connman,vin, CService(strService), keyMasternode, pubKeyMasternode, errorMessage); } // Send stop dseep to network for main masternode bool CActiveMasternode::StopMasterNode(CConnman* connman, std::string& errorMessage) { if (status != MASTERNODE_IS_CAPABLE && status != MASTERNODE_REMOTELY_ENABLED) { errorMessage = "masternode is not in a running status"; LogPrintf("CActiveMasternode::StopMasterNode() - Error: %s\n", errorMessage.c_str()); return false; } status = MASTERNODE_STOPPED; CPubKey pubKeyMasternode; CKey keyMasternode; if (!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrintf("Register::ManageStatus() - Error upon calling SetKey: %s\n", errorMessage.c_str()); return false; } return StopMasterNode(connman,vin, service, keyMasternode, pubKeyMasternode, errorMessage); } // Send stop dseep to network for any masternode bool CActiveMasternode::StopMasterNode(CConnman* connman, CTxIn vin, CService service, CKey keyMasternode, CPubKey pubKeyMasternode, std::string& errorMessage) { std::string wallet_name = ""; std::shared_ptr<CWallet> pwallet = GetWallet(wallet_name); pwallet->UnlockCoin(vin.prevout); return Dseep(connman, vin, service, keyMasternode, pubKeyMasternode, errorMessage, true); } bool CActiveMasternode::Dseep(CConnman* connman, std::string& errorMessage) { if (status != MASTERNODE_IS_CAPABLE && status != MASTERNODE_REMOTELY_ENABLED) { errorMessage = "masternode is not in a running status"; LogPrintf("CActiveMasternode::Dseep() - Error: %s\n", errorMessage.c_str()); return false; } CPubKey pubKeyMasternode; CKey keyMasternode; if (!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrintf("Register::ManageStatus() - Error upon calling SetKey: %s\n", errorMessage.c_str()); return false; } return Dseep(connman,vin, service, keyMasternode, pubKeyMasternode, errorMessage, false); } bool CActiveMasternode::Dseep(CConnman* connman, CTxIn vin, CService service, CKey keyMasternode, CPubKey pubKeyMasternode, std::string& retErrorMessage, bool stop) { std::string errorMessage; std::vector<unsigned char> vchMasterNodeSignature; std::string strMasterNodeSignMessage; int64_t masterNodeSignatureTime = GetAdjustedTime(); std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(masterNodeSignatureTime) + boost::lexical_cast<std::string>(stop); if (!darkSendSigner.SignMessage(strMessage, errorMessage, vchMasterNodeSignature, keyMasternode)) { retErrorMessage = "sign message failed: " + errorMessage; LogPrintf("CActiveMasternode::Dseep() - Error: %s\n", retErrorMessage.c_str()); return false; } if (!darkSendSigner.VerifyMessage(pubKeyMasternode, vchMasterNodeSignature, strMessage, errorMessage)) { retErrorMessage = "Verify message failed: " + errorMessage; LogPrintf("CActiveMasternode::Dseep() - Error: %s\n", retErrorMessage.c_str()); return false; } // Update Last Seen timestamp in masternode list bool found = false; for (CMasterNode& mn : vecMasternodes) { if (mn.vin == vin) { found = true; mn.UpdateLastSeen(); } } if (!found) { // Seems like we are trying to send a ping while the masternode is not registered in the network retErrorMessage = "Darksend Masternode List doesn't include our masternode, Shutting down masternode pinging service! " + vin.ToString(); LogPrintf("CActiveMasternode::Dseep() - Error: %s\n", retErrorMessage.c_str()); status = MASTERNODE_NOT_CAPABLE; notCapableReason = retErrorMessage; return false; } //send to all peers LogPrintf("CActiveMasternode::Dseep() - SendDarkSendElectionEntryPing vin = %s\n", vin.ToString().c_str()); connman->SendDarkSendElectionEntryPing(vin, vchMasterNodeSignature, masterNodeSignatureTime, stop); return true; } bool CActiveMasternode::RegisterByPubKey(CConnman *connman, std::string strService, std::string strKeyMasternode, std::string collateralAddress, std::string& errorMessage) { CTxIn vin; CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; CPubKey pubKeyMasternode; CKey keyMasternode; if (!darkSendSigner.SetKey(strKeyMasternode, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrintf("CActiveMasternode::RegisterByPubKey() - Error upon calling SetKey: %s\n", errorMessage.c_str()); return false; } if (!GetMasterNodeVinForPubKey(collateralAddress, vin, pubKeyCollateralAddress, keyCollateralAddress)) { errorMessage = "could not allocate vin for collateralAddress"; LogPrintf("Register::Register() - Error: %s\n", errorMessage.c_str()); return false; } //std::string errorMessage; std::vector<unsigned char> vchMasterNodeSignature; //std::string strMasterNodeSignMessage; int64_t masterNodeSignatureTime = GetAdjustedTime(); std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end()); std::string vchPubKey2(pubKeyMasternode.begin(), pubKeyMasternode.end()); std::string strMessage = strService + boost::lexical_cast<std::string>(masterNodeSignatureTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(PROTOCOL_VERSION); if (!darkSendSigner.SignMessage(strMessage, errorMessage, vchMasterNodeSignature, keyCollateralAddress)) { errorMessage = "sign message failed: " + errorMessage; LogPrintf("CActiveMasternode::Register() - Error: %s\n", errorMessage.c_str()); return false; } if (!darkSendSigner.VerifyMessage(pubKeyCollateralAddress, vchMasterNodeSignature, strMessage, errorMessage)) { errorMessage = "Verify message failed: " + errorMessage; LogPrintf("CActiveMasternode::Register() - Error: %s\n", errorMessage.c_str()); return false; } bool found = false; LOCK(cs_masternodes); for (CMasterNode& mn : vecMasternodes) if (mn.vin == vin) found = true; if (!found) { LogPrintf("CActiveMasternode::Register() - Adding to masternode list service: %s - vin: %s\n", strService, vin.ToString().c_str()); CMasterNode mn(CService(strService), vin, pubKeyCollateralAddress, vchMasterNodeSignature, masterNodeSignatureTime, pubKeyMasternode, PROTOCOL_VERSION); mn.UpdateLastSeen(masterNodeSignatureTime); vecMasternodes.push_back(mn); } std::vector<CNode*> vNodesCopy; { LOCK(connman->cs_vNodes); vNodesCopy = connman->vNodes; } const CNetMsgMaker msgMaker(PROTOCOL_VERSION); for (CNode* pnode : vNodesCopy) { //std::cout << "in for loop pnode in net.cpp\n"; if (pnode) { connman->PushMessage(pnode, msgMaker.Make("dsee", vin, CService(strService), vchMasterNodeSignature, masterNodeSignatureTime, pubKeyCollateralAddress, pubKeyMasternode, -1, -1, masterNodeSignatureTime, PROTOCOL_VERSION)); } } return Register(connman, vin, CService(strService), keyCollateralAddress, pubKeyCollateralAddress, keyMasternode, pubKeyMasternode, errorMessage); //return true; } bool CActiveMasternode::Register(CConnman* connman ,std::string strService, std::string strKeyMasternode, std::string txHash, std::string strOutputIndex, std::string& errorMessage) { CTxIn vin; CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; CPubKey pubKeyMasternode; CKey keyMasternode; if (!darkSendSigner.SetKey(strKeyMasternode, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrintf("CActiveMasternode::Register() - Error upon calling SetKey: %s\n", errorMessage.c_str()); return false; } if (!GetMasterNodeVin(vin, pubKeyCollateralAddress, keyCollateralAddress, txHash, strOutputIndex)) { errorMessage = "could not allocate vin"; LogPrintf("Register::Register() - Error: %s\n", errorMessage.c_str()); return false; } return Register(connman, vin, CService(strService), keyCollateralAddress, pubKeyCollateralAddress, keyMasternode, pubKeyMasternode, errorMessage); } bool CActiveMasternode::Register(CConnman* connman, CTxIn vin, CService service, CKey keyCollateralAddress, CPubKey pubKeyCollateralAddress, CKey keyMasternode, CPubKey pubKeyMasternode, std::string& retErrorMessage) { std::string errorMessage; std::vector<unsigned char> vchMasterNodeSignature; std::string strMasterNodeSignMessage; int64_t masterNodeSignatureTime = GetAdjustedTime(); std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end()); std::string vchPubKey2(pubKeyMasternode.begin(), pubKeyMasternode.end()); std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(masterNodeSignatureTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(PROTOCOL_VERSION); if (!darkSendSigner.SignMessage(strMessage, errorMessage, vchMasterNodeSignature, keyCollateralAddress)) { retErrorMessage = "sign message failed: " + errorMessage; LogPrintf("CActiveMasternode::Register() - Error: %s\n", retErrorMessage.c_str()); return false; } if (!darkSendSigner.VerifyMessage(pubKeyCollateralAddress, vchMasterNodeSignature, strMessage, errorMessage)) { retErrorMessage = "Verify message failed: " + errorMessage; LogPrintf("CActiveMasternode::Register() - Error: %s\n", retErrorMessage.c_str()); return false; } bool found = false; LOCK(cs_masternodes); for (CMasterNode& mn : vecMasternodes) if (mn.vin == vin) found = true; if (!found) { LogPrintf("CActiveMasternode::Register() - Adding to masternode list service: %s - vin: %s\n", service.ToString().c_str(), vin.ToString().c_str()); CMasterNode mn(service, vin, pubKeyCollateralAddress, vchMasterNodeSignature, masterNodeSignatureTime, pubKeyMasternode, PROTOCOL_VERSION); mn.UpdateLastSeen(masterNodeSignatureTime); vecMasternodes.push_back(mn); } //send to all peers LogPrintf("CActiveMasternode::Register() - SendDarkSendElectionEntry vin = %s\n", vin.ToString().c_str()); connman->SendDarkSendElectionEntry(vin, service, vchMasterNodeSignature, masterNodeSignatureTime, pubKeyCollateralAddress, pubKeyMasternode, -1, -1, masterNodeSignatureTime, PROTOCOL_VERSION); return true; } bool CActiveMasternode::GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey) { return GetMasterNodeVin(vin, pubkey, secretKey, "", ""); } bool CActiveMasternode::GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex) { CScript pubScript; // Find possible candidates vector <COutput> possibleCoins = SelectCoinsMasternode(); COutput* selectedOutput; // Find the vin if (!strTxHash.empty()) { // Let's find it arith_uint256 txHash(strTxHash); int outputIndex = 0; try { outputIndex = std::stoi(strOutputIndex.c_str()); } catch (const std::exception& e) { LogPrintf("%s: %s on strOutputIndex\n", __func__, e.what()); return false; } bool found = false; for (COutput& out : possibleCoins) { if (UintToArith256(out.tx->GetHash()) == txHash && out.i == outputIndex) { selectedOutput = &out; found = true; break; } } if (!found) { LogPrintf("CActiveMasternode::GetMasterNodeVin - Could not locate valid vin\n"); return false; } } else { // No output specified, Select the first one if (possibleCoins.size() > 0) { selectedOutput = &possibleCoins[0]; } else { LogPrintf("CActiveMasternode::GetMasterNodeVin - Could not locate specified vin from possible list\n"); return false; } } // At this point we have a selected output, retrieve the associated info return GetVinFromOutput(*selectedOutput, vin, pubkey, secretKey); } bool CActiveMasternode::GetMasterNodeVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey) { return GetMasterNodeVinForPubKey(collateralAddress, vin, pubkey, secretKey, "", ""); } bool CActiveMasternode::GetMasterNodeVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex) { CScript pubScript; // Find possible candidates vector<COutput> possibleCoins = SelectCoinsMasternodeForPubKey(collateralAddress); COutput* selectedOutput; // Find the vin if (!strTxHash.empty()) { // Let's find it arith_uint256 txHash(strTxHash); int outputIndex = boost::lexical_cast<int>(strOutputIndex); bool found = false; for (COutput& out : possibleCoins) { if (UintToArith256(out.tx->GetHash()) == txHash && out.i == outputIndex) { selectedOutput = &out; found = true; break; } } if (!found) { LogPrintf("CActiveMasternode::GetMasterNodeVinForPubKey - Could not locate valid vin\n"); return false; } } else { // No output specified, Select the first one if (possibleCoins.size() > 0) { selectedOutput = &possibleCoins[0]; } else { LogPrintf("CActiveMasternode::GetMasterNodeVinForPubKey - Could not locate specified vin from possible list\n"); return false; } } // At this point we have a selected output, retrieve the associated info return GetVinFromOutput(*selectedOutput, vin, pubkey, secretKey); } // Extract masternode vin information from output bool CActiveMasternode::GetVinFromOutput(COutput out, CTxIn& vin, CPubKey& pubkey, CKey& secretKey) { CScript pubScript; vin = CTxIn(out.tx->GetHash(), out.i); pubScript = out.tx->tx->vout[out.i].scriptPubKey; // the inputs PubKey CTxDestination address1; ExtractDestination(pubScript, address1); const CKeyID* keyID = boost::get<CKeyID>(&address1); if (!keyID) { LogPrintf("CActiveMasternode::GetMasterNodeVin - Address does not refer to a key\n"); return false; } std::string wallet_name = ""; std::shared_ptr<CWallet> pwallet = GetWallet(wallet_name); if (!pwallet->GetKey(*keyID, secretKey)) { LogPrintf ("CActiveMasternode::GetMasterNodeVin - Private key for address is not known\n"); return false; } pubkey = secretKey.GetPubKey(); return true; } // get all possible outputs for running masternode vector<COutput> CActiveMasternode::SelectCoinsMasternode() { vector<COutput> vCoins; vector<COutput> filteredCoins; // Retrieve all possible outputs std::string wallet_name = ""; std::shared_ptr<CWallet> pwallet = GetWallet(wallet_name); pwallet->AvailableCoinsMN(vCoins); // Filter for (const COutput& out : vCoins) { int mncolletral = chainActive.Height() >=30000 ? 10000 : 10000; if (out.tx->tx->vout[out.i].nValue == mncolletral * COIN) { //exactly DARKSEND_COLLATERAL XLT filteredCoins.push_back(out); } } return filteredCoins; } // get all possible outputs for running masternode for a specific pubkey vector <COutput> CActiveMasternode::SelectCoinsMasternodeForPubKey(std::string collateralAddress) { static const int64_t DARKSEND_COLLATERAL = GetMNCollateral(chainActive.Height()) * COIN; //(10000*COIN); //10000 XLT CTxDestination address = DecodeDestination(collateralAddress); CScript scriptPubKey = GetScriptForDestination(address); vector <COutput> vCoins; vector <COutput> filteredCoins; // Retrieve all possible outputs std::string wallet_name = ""; std::shared_ptr<CWallet> pwallet = GetWallet(wallet_name); pwallet->AvailableCoinsMN(vCoins); // Filter for (const COutput& out : vCoins) { if (out.tx->tx->vout[out.i].scriptPubKey == scriptPubKey && out.tx->tx->vout[out.i].nValue == DARKSEND_COLLATERAL) { //exactly 161.200 XLT filteredCoins.push_back(out); } } return filteredCoins; } // when starting a masternode, this can enable to run as a hot wallet with no funds bool CActiveMasternode::EnableHotColdMasterNode(CTxIn& newVin, CService& newService) { if (!fMasterNode) return false; status = MASTERNODE_REMOTELY_ENABLED; //The values below are needed for signing dseep messages going forward this->vin = newVin; this->service = newService; LogPrintf("CActiveMasternode::EnableHotColdMasterNode() - Enabled! You may shut down the cold daemon.\n"); return true; }
41.214801
218
0.680068
nexalt-project
3986bf0985dbdec61b5553ea12f2d3ee96b501ca
27,674
cpp
C++
namespace.cpp
JonathanGuthrie/wodin
bef3d5f0fa65f2148e7d8fb52606191689023bb0
[ "Apache-2.0" ]
3
2015-05-06T16:56:14.000Z
2017-03-22T05:25:21.000Z
namespace.cpp
JonathanGuthrie/wodin
bef3d5f0fa65f2148e7d8fb52606191689023bb0
[ "Apache-2.0" ]
null
null
null
namespace.cpp
JonathanGuthrie/wodin
bef3d5f0fa65f2148e7d8fb52606191689023bb0
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2013 Jonathan R. Guthrie * * 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 <iostream> #include <utility> #include "namespace.hpp" #include <algorithm> pthread_mutex_t Namespace::m_mailboxMapMutex; Namespace::MailboxMap Namespace::m_mailboxMap; pthread_mutex_t Namespace::m_orphanMapMutex; Namespace::MailStoreMap Namespace::m_orphanMap; Namespace::Namespace(ImapSession *session) : MailStore(session) { m_defaultNamespace = NULL; m_openMailboxName = NULL; m_defaultType = BAD_NAMESPACE; } MailStore *Namespace::nameSpace(std::string &name) { MailStore *result = m_defaultNamespace; NamespaceMap::const_iterator i; for (i = m_namespaces.begin(); i != m_namespaces.end(); ++i) { if (0 == name.compare(0, i->first.size(), i->first)) { name.erase(0, i->first.size()); result = i->second.store; break; } } #if 0 if (i != m_namespaces.end()) { std::cout << "The name is \"" << name << "\" and the key value is \"" << i->first << "\"" << std::endl; } else { std::cout << "Name \"" << name << "\" not found in any namespace" << std::endl; } #endif // 0 return result; } MailStore::MAIL_STORE_RESULT Namespace::createMailbox(const std::string &FullName) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; std::string changeableName = FullName; MailStore *store = nameSpace(changeableName); if (NULL != store) { result = store->createMailbox(changeableName); } return result; } // SYZYGY -- what are the consequences to deleting a mailbox that is open in another session? // SYZYGY -- probably not good. I should deal with it, shouldn't I? // SYZYGY -- I should refuse to allow a client to delete a mailbox if any clients have it open MailStore::MAIL_STORE_RESULT Namespace::deleteMailbox(const std::string &FullName) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; std::string changeableName = FullName; MailStore *store = nameSpace(changeableName); if (NULL != store) { result = store->deleteMailbox(changeableName); } else { if (NULL != m_defaultNamespace) { result = m_defaultNamespace->deleteMailbox(FullName); } } return result; } MailStore::MAIL_STORE_RESULT Namespace::renameMailbox(const std::string &SourceName, const std::string &DestinationName) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; std::string changeableSource = SourceName; std::string changeableDest = DestinationName; MailStore *sourceStore = nameSpace(changeableSource); MailStore *destStore = nameSpace(changeableDest); if (NULL != sourceStore) { if (sourceStore == destStore) { result = sourceStore->renameMailbox(SourceName, changeableDest); } else { result = NAMESPACES_DONT_MATCH; } } return result; } void Namespace::dump_message_session_info(const char *s, ExpungedMessageMap &m) { for (ExpungedMessageMap::iterator i = m.begin(); i != m.end(); ++i) { for (SessionList::iterator j = i->second.expungedSessions.begin(); j != i->second.expungedSessions.end(); ++j) { std::cout << s << " " << i->second.uid << " " << &*j << std::endl; } } } MailStore::MAIL_STORE_RESULT Namespace::mailboxClose() { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store) && (NULL != m_openMailboxName)) { // I reduce the reference count and remove this session from the list of those notified // about deleted messages wherever it appears. I also check to see if there are any more // to purge from the back end and call the purge function if there are any additional // and then I call MailboxFlushBuffers std::string mailboxUrl = m_selectedMailbox->store->generateUrl(*m_openMailboxName); pthread_mutex_lock(&Namespace::m_mailboxMapMutex); MailboxMap::iterator found = m_mailboxMap.find(mailboxUrl); if (found != m_mailboxMap.end()) { --(found->second.refcount); if (1 > found->second.refcount) { // If the reference count is zero, then call mailboxClose and remove this from the mailboxMap and then // delete the mailstore result = m_selectedMailbox->store->mailboxClose(); if (MailStore::CANNOT_COMPLETE_ACTION == result) { // The mail box is locked, but the user wants it gone, so it is now an orphan pthread_mutex_lock(&Namespace::m_orphanMapMutex); m_orphanMap.insert(MailStoreMap::value_type(mailboxUrl, m_selectedMailbox->store)); pthread_mutex_unlock(&Namespace::m_orphanMapMutex); } else { // if the close was successful, remove this from the mailboxMap and then delete the mailstore pthread_mutex_destroy(&found->second.mutex); delete m_selectedMailbox->store; } m_mailboxMap.erase(found); // no matter what, as far as the end user is concerned, everything worked just fine result = MailStore::SUCCESS; } else { // SYZYGY -- need to test the update of the list of sessions notified about messages from this mailstore dump_message_session_info("before_a", found->second.messages); for (ExpungedMessageMap::iterator i = found->second.messages.begin(); i != found->second.messages.end(); ++i) { for (SessionList::iterator j = i->second.expungedSessions.begin(); j != i->second.expungedSessions.end(); ++j) { if (m_session == *j) { i->second.expungedSessions.erase(j); i->second.expungedSessionCount--; break; } } } dump_message_session_info("after_a", found->second.messages); // and flush the buffers m_selectedMailbox->store->mailboxFlushBuffers(); } } pthread_mutex_unlock(&Namespace::m_mailboxMapMutex); // And I now have no selectedNamespace nor do I have an open mailbox m_selectedMailbox = NULL; m_openMailboxName = NULL; } return result; } void Namespace::mailboxList(const std::string &pattern, MAILBOX_LIST *result, bool listAll) { MailStore *store = NULL; std::string changeablePattern = pattern; store = nameSpace(changeablePattern); if (NULL != store) { store->mailboxList(changeablePattern, result, listAll); } } MailStore::MAIL_STORE_RESULT Namespace::subscribeMailbox(const std::string &MailboxName, bool isSubscribe) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; std::string changeableName = MailboxName; MailStore *store = nameSpace(changeableName); if (NULL != store) { result = store->subscribeMailbox(changeableName, isSubscribe); } return result; } MailStore::MAIL_STORE_RESULT Namespace::addMessageToMailbox(const std::string &MailboxName, const uint8_t *data, size_t length, DateTime &createTime, uint32_t messageFlags, size_t *newUid) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; std::string changeableName = MailboxName; MailStore *store = nameSpace(changeableName); if (NULL != store) { result = store->addMessageToMailbox(changeableName, data, length, createTime, messageFlags, newUid); } return result; } MailStore::MAIL_STORE_RESULT Namespace::appendDataToMessage(const std::string &MailboxName, size_t uid, const uint8_t *data, size_t length) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; std::string changeableName = MailboxName; MailStore *store = nameSpace(changeableName); if (NULL != store) { result = store->appendDataToMessage(changeableName, uid, data, length); } return result; } MailStore::MAIL_STORE_RESULT Namespace::doneAppendingDataToMessage(const std::string &MailboxName, size_t uid) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; std::string changeableName = MailboxName; MailStore *store = nameSpace(changeableName); if (NULL != store) { result = store->doneAppendingDataToMessage(changeableName, uid); } return result; } // The next seven methods only have meaning if a mailbox has been opened, something I expect to be // enforced by the IMAP server logic because they're only meaningful in the selected state unsigned Namespace::serialNumber() { unsigned result = 0; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = m_selectedMailbox->store->serialNumber(); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } unsigned Namespace::uidValidityNumber() { unsigned result = 0; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = m_selectedMailbox->store->uidValidityNumber(); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } // This needs to be called ONLY when the m_selectedMailbox->mutex has been locked bool Namespace::addSession(size_t refCount, expunged_message_t &message) { bool result = false; SessionList::iterator i = std::find(message.expungedSessions.begin(), message.expungedSessions.end(), m_session); if (message.expungedSessions.end() == i) { message.expungedSessions.push_back(m_session); ++(message.expungedSessionCount); --m_mailboxMessageCount; if (refCount > message.expungedSessionCount) { m_selectedMailbox->store->expungeThisUid(message.uid); result = true; } } return result; } void Namespace::removeUid(unsigned long uid) { MSN_TO_UID::iterator i = std::find(m_uidGivenMsn.begin(), m_uidGivenMsn.end(), uid); if (m_uidGivenMsn.end() != i) { m_uidGivenMsn.erase(i); } } MailStore::MAIL_STORE_RESULT Namespace::mailboxOpen(const std::string &MailboxName, bool readWrite) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; std::string changeableName = MailboxName; MailStore *store = nameSpace(changeableName); if (NULL != store) { int refCount; std::string mailboxUrl = store->generateUrl(changeableName); pthread_mutex_lock(&Namespace::m_mailboxMapMutex); MailboxMap::iterator found = m_mailboxMap.find(mailboxUrl); if (found == m_mailboxMap.end()) { std::pair<MailboxMap::iterator, bool> insert_result; pthread_mutex_lock(&Namespace::m_orphanMapMutex); MailStoreMap::iterator foundOrphan = m_orphanMap.find(mailboxUrl); if (foundOrphan == m_orphanMap.end()) { MailStore *selectedNamespace = store->clone(); // It's not an orphaned mail box, open it if (SUCCESS == (result = selectedNamespace->mailboxOpen(MailboxName, readWrite))) { m_openMailboxName = selectedNamespace->mailboxName(); mailbox_t boxToInsert; pthread_mutex_init(&boxToInsert.mutex, NULL); boxToInsert.store = selectedNamespace; refCount = boxToInsert.refcount = 1; boxToInsert.messages.clear(); insert_result = m_mailboxMap.insert(MailboxMap::value_type(mailboxUrl, boxToInsert)); m_selectedMailbox = &(insert_result.first->second); } else { delete selectedNamespace; selectedNamespace = NULL; m_openMailboxName = NULL; m_selectedMailbox = NULL; } } else { // It's an orphaned mail box. I don't need to really open it because it was never really closed. result = MailStore::SUCCESS; mailbox_t boxToInsert; pthread_mutex_init(&boxToInsert.mutex, NULL); boxToInsert.store = foundOrphan->second; refCount = boxToInsert.refcount = 1; boxToInsert.messages.clear(); insert_result = m_mailboxMap.insert(MailboxMap::value_type(mailboxUrl, boxToInsert)); m_selectedMailbox = &(insert_result.first->second); m_openMailboxName = foundOrphan->second->mailboxName(); m_orphanMap.erase(foundOrphan); } pthread_mutex_unlock(&Namespace::m_orphanMapMutex); } else { result = MailStore::SUCCESS; m_selectedMailbox = &(found->second); m_openMailboxName = found->second.store->mailboxName(); ++(found->second.refcount); refCount = found->second.refcount; } if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); // if selectedNamespace is not NULL then I need to generate the MSN/UID mapping for the // session and generate a message count m_mailboxMessageCount = m_selectedMailbox->store->mailboxMessageCount(); m_uidGivenMsn.assign(m_selectedMailbox->store->uidGivenMsn().begin(), m_selectedMailbox->store->uidGivenMsn().end()); for (ExpungedMessageMap::iterator i = m_selectedMailbox->messages.begin(); i!= m_selectedMailbox->messages.end(); ++i) { --m_mailboxMessageCount; removeUid(i->second.uid); if (addSession(refCount, i->second)) { m_selectedMailbox->messages.erase(i); } } pthread_mutex_unlock(&m_selectedMailbox->mutex); } pthread_mutex_unlock(&Namespace::m_mailboxMapMutex); } return result; } MailStore::MAIL_STORE_RESULT Namespace::listDeletedMessages(NUMBER_SET *nowGone) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); // This gets the messages that some other session has expunged and this one hasn't mailboxUpdateStatsInternal(nowGone); // This gets the messages that no sessions know about but which need to be expunged result = m_selectedMailbox->store->listDeletedMessages(nowGone); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } MailStore::MAIL_STORE_RESULT Namespace::expungeThisUid(unsigned long uid) { // SYZYGY -- find the uid in the map // SYZYGY -- then add this session to the list of those who have seen it as deleted // SYZYGY -- if addSession returns true, then actually expunge it and pull it out of the list of messages waiting to be expunged MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); dump_message_session_info("before_b", m_selectedMailbox->messages); ExpungedMessageMap::iterator found = m_selectedMailbox->messages.find(uid); if (m_selectedMailbox->messages.end() != found) { if (addSession(m_selectedMailbox->refcount, found->second)) { result = m_selectedMailbox->store->expungeThisUid(uid); } m_selectedMailbox->messages.erase(found); } else { // I have to add it, if the refcount is greater than one // if it's not greater than one, I can just purge it, no harm done if (1 < m_selectedMailbox->refcount) { std::pair<ExpungedMessageMap::iterator, bool> insert_result; expunged_message_t message; message.uid = uid; message.expungedSessionCount = 0; insert_result = m_selectedMailbox->messages.insert(ExpungedMessageMap::value_type(uid, message)); addSession(m_selectedMailbox->refcount, insert_result.first->second); } else { --m_mailboxMessageCount; result = m_selectedMailbox->store->expungeThisUid(uid); } } dump_message_session_info("after_b", m_selectedMailbox->messages); pthread_mutex_unlock(&m_selectedMailbox->mutex); } removeUid(uid); return result; } MailStore::MAIL_STORE_RESULT Namespace::getMailboxCounts(const std::string &MailboxName, uint32_t which, unsigned &messageCount, unsigned &recentCount, unsigned &uidNext, unsigned &uidValidity, unsigned &firstUnseen) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; std::string changeableName = MailboxName; MailStore *store = nameSpace(changeableName); if (NULL != store) { result = store->getMailboxCounts(MailboxName, which, messageCount, recentCount, uidNext, uidValidity, firstUnseen); } return result; } unsigned Namespace::mailboxMessageCount() { return m_mailboxMessageCount; } // SYZYGY -- Recent is now more complicted GRRR! unsigned Namespace::mailboxRecentCount() { unsigned result = 0; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = m_selectedMailbox->store->mailboxRecentCount(); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } unsigned Namespace::mailboxFirstUnseen() { unsigned result = 0; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = m_selectedMailbox->store->mailboxFirstUnseen(); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } const DateTime &Namespace::messageInternalDate(const unsigned long uid) { // SYZYGY -- I need something like a void cast to DateTime that returns an error static DateTime result; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = m_selectedMailbox->store->messageInternalDate(uid); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } NUMBER_LIST Namespace::mailboxMsnToUid(const NUMBER_LIST &msns) { NUMBER_LIST result; for (NUMBER_LIST::const_iterator i=msns.begin(); i!=msns.end(); ++i) { result.push_back(mailboxMsnToUid(*i)); } return result; } unsigned long Namespace::mailboxMsnToUid(const unsigned long msn) { unsigned long result = 0; if (msn <= m_uidGivenMsn.size()) { result = m_uidGivenMsn[msn-1]; } return result; } NUMBER_LIST Namespace::mailboxUidToMsn(const NUMBER_LIST &uids) { NUMBER_LIST result; for (NUMBER_LIST::const_iterator i=uids.begin(); i!=uids.end(); ++i) { result.push_back(mailboxUidToMsn(*i)); } return result; } unsigned long Namespace::mailboxUidToMsn(unsigned long uid) { unsigned long result = 0; MSN_TO_UID::const_iterator i = find(m_uidGivenMsn.begin(), m_uidGivenMsn.end(), uid); if (i != m_uidGivenMsn.end()) { result = (i - m_uidGivenMsn.begin()) + 1; } return result; } MailStore::MAIL_STORE_RESULT Namespace::messageUpdateFlags(unsigned long uid, uint32_t andMask, uint32_t orMask, uint32_t &flags) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = m_selectedMailbox->store->messageUpdateFlags(uid, andMask, orMask, flags); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } std::string Namespace::mailboxUserPath() const { std::string result = ""; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = m_selectedMailbox->store->mailboxUserPath(); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } MailStore::MAIL_STORE_RESULT Namespace::mailboxFlushBuffers(void) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = m_selectedMailbox->store->mailboxFlushBuffers(); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } // This does the work from MailboxUpdateStats and also some of the work for ListDeletedMessages // I can't just call MailboxUpdateStats from ListDeletedMessages because then I get a deadlock // because both of them MUST lock the m_selectedMailboxMutex but both of them can call this // function because this function doesn't lock anything. MailStore::MAIL_STORE_RESULT Namespace::mailboxUpdateStatsInternal(NUMBER_SET *nowGone) { MailStore::MAIL_STORE_RESULT result = MailStore::SUCCESS; for (ExpungedMessageMap::iterator i = m_selectedMailbox->messages.begin(); i!= m_selectedMailbox->messages.end(); ++i) { bool found = false; for (SessionList::iterator j = i->second.expungedSessions.begin(); j != i->second.expungedSessions.end(); ++j) { if (m_session == *j) { found = true; break; } } if (!found) { nowGone->insert(nowGone->begin(), i->first); } } return result; } MailStore::MAIL_STORE_RESULT Namespace::mailboxUpdateStats(NUMBER_SET *nowGone) { MailStore::MAIL_STORE_RESULT result = MailStore::GENERAL_FAILURE; if (NULL != m_selectedMailbox) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = mailboxUpdateStatsInternal(nowGone); pthread_mutex_unlock(&m_selectedMailbox->mutex); } // Attempt to close any orphaned mail stores pthread_mutex_lock(&Namespace::m_orphanMapMutex); for (MailStoreMap::iterator i = m_orphanMap.begin(); i!= m_orphanMap.end(); ++i) { if (MailStore::SUCCESS == i->second->mailboxClose()) { m_orphanMap.erase(i); } } pthread_mutex_unlock(&Namespace::m_orphanMapMutex); return result; } Namespace::~Namespace() { m_openMailboxName = NULL; for (NamespaceMap::iterator i = m_namespaces.begin(); i != m_namespaces.end(); ++i) { delete i->second.store; } m_namespaces.clear(); if (NULL != m_defaultNamespace) { delete m_defaultNamespace; } } void Namespace::addNamespace(NAMESPACE_TYPES type, const std::string &name, MailStore *handler, char separator) { if ("" == name) { if (NULL != m_defaultNamespace) { delete m_defaultNamespace; } m_defaultType = type; m_defaultNamespace = handler; m_defaultSeparator = separator; } else { namespace_t namespaceToInsert; namespaceToInsert.store = handler; namespaceToInsert.separator = separator; namespaceToInsert.type = type; m_namespaces.insert(NamespaceMap::value_type(name, namespaceToInsert)); } } // Do I really want to return the data in the form needed by IMAP, or // do I want to abstract it, somehow. It's abstracted....for now const std::string Namespace::listNamespaces(void) const { std::string result = ""; bool nilFlag; NAMESPACE_TYPES t = PERSONAL; do { nilFlag = true; if (t == m_defaultType) { nilFlag = false; result += "((\"\" "; if ('\0' != m_defaultSeparator) { result += "\""; result += m_defaultSeparator; result += "\""; } result += ")"; } for (NamespaceMap::const_iterator i = m_namespaces.begin(); i != m_namespaces.end(); ++i) { if (t == i->second.type) { if (nilFlag) { result += "("; } nilFlag = false; result += "(\""; result += i->first.c_str(); result += "\" "; if ('\0' != i->second.separator) { result += "\""; result += i->second.separator; result += "\""; } else { result += "NIL"; } result += ")"; } } if (nilFlag) { result += "NIL"; } else { result += ")"; } if (SHARED != t) { result += " "; } t = PERSONAL == t ? OTHERS : (OTHERS == t ? SHARED : BAD_NAMESPACE); } while (t < BAD_NAMESPACE); return result; } MailStore::MAIL_STORE_RESULT Namespace::deleteMessage(const std::string &MailboxName, unsigned long uid) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; std::string changeableName = MailboxName; MailStore *store = nameSpace(changeableName); if (NULL != store) { result = store->deleteMessage(changeableName, uid); } return result; } MailMessage::MAIL_MESSAGE_RESULT Namespace::messageData(MailMessage **message, unsigned long uid) { MailMessage::MAIL_MESSAGE_RESULT result = MailMessage::GENERAL_FAILURE; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = m_selectedMailbox->store->messageData(message, uid); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } MailStore::MAIL_STORE_RESULT Namespace::openMessageFile(unsigned long uid) { MailStore::MAIL_STORE_RESULT result = MailStore::GENERAL_FAILURE; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = m_selectedMailbox->store->openMessageFile(uid); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } size_t Namespace::bufferLength(unsigned long uid) { size_t result = 0; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = m_selectedMailbox->store->bufferLength(uid); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } size_t Namespace::readMessage(char *buffer, size_t offset, size_t length) { size_t result = 0; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = m_selectedMailbox->store->readMessage(buffer, offset, length); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } void Namespace::closeMessageFile(void) { if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); m_selectedMailbox->store->closeMessageFile(); pthread_mutex_unlock(&m_selectedMailbox->mutex); } } const SEARCH_RESULT *Namespace::searchMetaData(uint32_t xorMask, uint32_t andMask, size_t smallestSize, size_t largestSize, DateTime *beginInternalDate, DateTime *endInternalDate) { const SEARCH_RESULT *result = NULL; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = m_selectedMailbox->store->searchMetaData(xorMask, andMask, smallestSize, largestSize, beginInternalDate, endInternalDate); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } const std::string Namespace::generateUrl(const std::string MailboxName) const { std::string result; result = "namespace:///" + MailboxName; return result; } Namespace *Namespace::clone(void) { return new Namespace(m_session); } MailStore::MAIL_STORE_RESULT Namespace::lock(void) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = m_selectedMailbox->store->lock(); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } MailStore::MAIL_STORE_RESULT Namespace::lock(const std::string &mailboxName) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; std::string changeableName = mailboxName; MailStore *store = nameSpace(changeableName); if (NULL != store) { result = store->lock(); } return result; } MailStore::MAIL_STORE_RESULT Namespace::unlock(void) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; if ((NULL != m_selectedMailbox) && (NULL != m_selectedMailbox->store)) { pthread_mutex_lock(&m_selectedMailbox->mutex); result = m_selectedMailbox->store->unlock(); pthread_mutex_unlock(&m_selectedMailbox->mutex); } return result; } MailStore::MAIL_STORE_RESULT Namespace::unlock(const std::string &mailboxName) { MailStore::MAIL_STORE_RESULT result = GENERAL_FAILURE; std::string changeableName = mailboxName; MailStore *store = nameSpace(changeableName); if (NULL != store) { result = store->unlock(); } return result; } size_t Namespace::orphanCount(void) { size_t result; pthread_mutex_lock(&Namespace::m_orphanMapMutex); result = m_orphanMap.size(); pthread_mutex_unlock(&Namespace::m_orphanMapMutex); return result; }
36.033854
181
0.71616
JonathanGuthrie
398c8cb9dd1a525947665d657ac0bd0da3edde66
4,461
cpp
C++
lib/regi/sim_metrics_2d/xregImgSimMetric2DBoundaryEdgesCPU.cpp
rg2/xreg
c06440d7995f8a441420e311bb7b6524452843d3
[ "MIT" ]
30
2020-09-29T18:36:13.000Z
2022-03-28T09:25:13.000Z
lib/regi/sim_metrics_2d/xregImgSimMetric2DBoundaryEdgesCPU.cpp
gaocong13/Orthopedic-Robot-Navigation
bf36f7de116c1c99b86c9ba50f111c3796336af0
[ "MIT" ]
3
2020-10-09T01:21:27.000Z
2020-12-10T15:39:44.000Z
lib/regi/sim_metrics_2d/xregImgSimMetric2DBoundaryEdgesCPU.cpp
rg2/xreg
c06440d7995f8a441420e311bb7b6524452843d3
[ "MIT" ]
8
2021-05-25T05:14:48.000Z
2022-02-26T12:29:50.000Z
/* * MIT License * * Copyright (c) 2020 Robert Grupp * * 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 "xregImgSimMetric2DBoundaryEdgesCPU.h" #include "xregOpenCVUtils.h" #include "xregITKOpenCVUtils.h" #include "xregTBBUtils.h" #include "xregRayCastInterface.h" void xreg::ImgSimMetric2DBoundaryEdgesCPU::allocate_resources() { ImgSimMetric2DCPU::allocate_resources(); cv::Mat fixed_img = ShallowCopyItkToOpenCV(this->fixed_img_.GetPointer()); img_num_rows_ = fixed_img.rows; img_num_cols_ = fixed_img.cols; num_fixed_edges_ = 0; cv::Mat fixed_edges = ShallowCopyItkToOpenCV(fixed_img_edges_.GetPointer()).clone(); // Invert, 0 -> edge, 1 -> no edge // TODO: parallelize for (size_type r = 0; r < img_num_rows_; ++r) { auto* edge_row = &fixed_edges.at<EdgePixelScalar>(r,0); for (size_type c = 0; c < img_num_cols_; ++c) { if (edge_row[c]) { ++num_fixed_edges_; } edge_row[c] = !edge_row[c]; } } fixed_edge_dist_map_ = cv::Mat::zeros(fixed_img.size(), cv::DataType<Scalar>::type); cv::distanceTransform(fixed_edges, fixed_edge_dist_map_, CV_DIST_L2, CV_DIST_MASK_PRECISE); // create storage for moving image edges move_edge_imgs_ = AllocContiguousBufferForOpenCVImages<EdgePixelScalar>(img_num_rows_, img_num_cols_, this->num_mov_imgs_, &move_edges_buf_); } void xreg::ImgSimMetric2DBoundaryEdgesCPU::compute() { this->pre_compute(); auto compute_dists_fn = [&] (const RangeType& r) { const bool reg = this->regularize_; const Scalar num_edge_pts_low = 0.5 * this->num_fixed_edges_; const cv::Mat& fixed_dist_map = this->fixed_edge_dist_map_; const size_type nr = this->img_num_rows_; const size_type nc = this->img_num_cols_; const size_type num_pix_per_proj = nr * nc; for (size_type mov_idx = r.begin(); mov_idx < r.end(); ++mov_idx) { // compute the moving image edges cv::Mat& cur_mov_edges = this->move_edge_imgs_[mov_idx]; cv::Mat cur_mov_depth(nr, nc, cv::DataType<Scalar>::type, this->mov_imgs_buf_ + (mov_idx * num_pix_per_proj)); FindPixelsWithAdjacentIntensity(cur_mov_depth, &cur_mov_edges, kRAY_CAST_MAX_DEPTH, true); // Now compute the mean distance Scalar d = 0; size_type num_pts = 0; for (size_type r = 0; r < nr; ++r) { const auto* cur_edge_row = &cur_mov_edges.at<EdgePixelScalar>(r,0); const auto* cur_dist_row = &fixed_dist_map.at<Scalar>(r,0); for (size_type c = 0; c < nc; ++c) { if (cur_edge_row[c]) { ++num_pts; d += cur_dist_row[c]; } } } d /= num_pts; // TODO: come up with better regularization if (reg) { if (num_pts < num_edge_pts_low) { d += 1000; } } this->sim_vals_[mov_idx] = d; } }; ParallelFor(compute_dists_fn, RangeType(0, this->num_mov_imgs_)); } void xreg::ImgSimMetric2DBoundaryEdgesCPU::set_fixed_image_edges(FixedEdgeImagePtr fixed_edges) { fixed_img_edges_ = fixed_edges; } void xreg::ImgSimMetric2DBoundaryEdgesCPU::set_regularize(const bool r) { regularize_ = r; }
30.554795
103
0.654562
rg2
3994a19afa6a3b44787d87d571b673144d9c4b6f
427
cpp
C++
HW1and2/src/IArmyFactory.cpp
2ToThe10th/metaprogramming
34fc080185f5ed17c25651f150030e617d466e64
[ "MIT" ]
null
null
null
HW1and2/src/IArmyFactory.cpp
2ToThe10th/metaprogramming
34fc080185f5ed17c25651f150030e617d466e64
[ "MIT" ]
null
null
null
HW1and2/src/IArmyFactory.cpp
2ToThe10th/metaprogramming
34fc080185f5ed17c25651f150030e617d466e64
[ "MIT" ]
null
null
null
// // Created by 2ToThe10th on 25.04.2021. // #include "IArmyFactory.hpp" #include <utility> Soldier::Soldier(std::string type) : type_(std::move(type)) {} void Soldier::setColor(std::string color) { color_ = std::move(color); } const std::string &Soldier::getColor() { return color_; } Infantry::Infantry() : Soldier("Infantry") {} Archer::Archer() : Soldier("Archer") {} Cavalry::Cavalry() : Soldier("Cavalry") {}
18.565217
62
0.665105
2ToThe10th
3994a6c6385595ba686f41a443aee9801933e87a
7,355
hh
C++
include/benchmark/all_libraries/flann_test.hh
mlawsonca/benchmarking_suite_range_searching_libraries
85f2e6be47633836e56684636851eeb393c46d7d
[ "MIT" ]
1
2021-10-07T18:46:56.000Z
2021-10-07T18:46:56.000Z
include/benchmark/all_libraries/flann_test.hh
mlawsonca/benchmarking_suite_range_searching_libraries
85f2e6be47633836e56684636851eeb393c46d7d
[ "MIT" ]
null
null
null
include/benchmark/all_libraries/flann_test.hh
mlawsonca/benchmarking_suite_range_searching_libraries
85f2e6be47633836e56684636851eeb393c46d7d
[ "MIT" ]
null
null
null
#ifndef FLANN_TEST_HH #define FLANN_TEST_HH #include <flann/flann.h> using namespace std; namespace TestFLANN { class KDTree : public BboxIntersectionTest { private: flann::KDTreeSingleIndex<flann::L2_Simple<double>> *tree; //produces an error if the data is not kept accessible double *flattened; void build_tree(const std::vector<point> &pts, const std::vector<size_t> &indices, flann::IndexParams build_params) { int num_rows = pts.size(); if(num_rows == 0) { return; } int num_cols = pts[0].size(); flattened = (double*)malloc(sizeof(double)*num_rows*num_cols); for (int i = 0; i < num_rows; i++ ) { for (int j = 0; j < num_cols; j++ ) { flattened[i*num_cols+j] = pts[i][j]; } } tree = new flann::KDTreeSingleIndex<flann::L2_Simple<double>>(flann::Matrix<double>(flattened,num_rows,num_cols), build_params); tree -> buildIndex(); } public: bool intersections_exact() { return false ;} //using a circular radius is not exact KDTree() {} ~KDTree() { delete tree; free(flattened); } /*** note: FLANN supports many other index types but they aren't suitable for our problem //linear - don't want. is brute force //LSH - for matching binary features using hamming distances //KDTree - doesn't make sense to use more than one tree for an exact search //Kmeans, CompositeIndex, HierarchicalClustering, Autotuned - is designed for high dimensional data ***/ void build_tree(const std::vector<point> &pts, const std::vector<size_t> &indices) { bool reorder = false; build_tree(pts, indices, flann::KDTreeSingleIndexParams(NUM_ELEMS_PER_NODE,reorder)); } void build_tree(const std::vector<point> &pts, const std::vector<size_t> &indices, size_t bucket_size) { bool reorder = false; build_tree(pts, indices, flann::KDTreeSingleIndexParams(bucket_size,reorder)); } void get_intersections(const bbox &my_bbox, std::vector<size_t> &intersections_indices) { size_t num_rows = 1; //are only issuing one query int num_dims = my_bbox.first.size(); point mid_pt; double squared_radius_search_bound = 0; get_max_squared_radius(my_bbox, mid_pt, squared_radius_search_bound); squared_radius_search_bound += DEFAULT_TOLERANCE; //doens't include things right on the border so we add a tolerance Matrix<double> query(&mid_pt[0], num_rows, num_dims); vector<vector<double>> dists; vector<vector<int>> indices; size_t num_leaves_to_check = FLANN_CHECKS_UNLIMITED; bool search_for_approx_neighbors = false; bool sorted = false; size_t num_results = tree->radiusSearch( query, indices, dists, squared_radius_search_bound, flann::SearchParams(num_leaves_to_check, search_for_approx_neighbors, sorted) ); std::copy(indices[0].begin(), indices[0].begin()+num_results, std::back_inserter(intersections_indices)); } }; #if USE_GPU class CUDA : public BboxIntersectionTest { private: //note - could use other distance functions flann::KDTreeCuda3dIndex<flann::L2_Simple<float>> *tree; void build_tree(const std::vector<point> &pts, const std::vector<size_t> &indices, flann::IndexParams build_params) { int num_rows = pts.size(); if(num_rows == 0) { return; } int num_cols = pts[0].size(); float *flattened = new float[num_rows*num_cols]; for (int i = 0; i < num_rows; i++ ) { for (int j = 0; j < num_cols; j++ ) { flattened[i*num_cols+j] = pts[i][j]; } } tree = new flann::KDTreeCuda3dIndex<flann::L2_Simple<float>>(flann::Matrix<float>(flattened,num_rows,num_cols), build_params); tree -> buildIndex(); delete[] flattened; } public: bool intersections_exact() { return false ;} //using a circular radius is not exact CUDA() {} ~CUDA() { delete tree; } /*** note: FLANN supports many other index types but they aren't suitable for our problem //linear - don't want. is brute force //LSH - for matching binary features using hamming distances //KDTree - doesn't make sense to use more than one tree for an exact search //Kmeans, CompositeIndex, HierarchicalClustering, Autotuned - is designed for high dimensional data and produced very inexact results in low dimensions //Kmeans and Composite Index add too many points, Hierarchical clustering misses them ***/ void build_tree(const std::vector<point> &pts, const std::vector<size_t> &indices) { build_tree(pts, indices, flann::KDTreeCuda3dIndexParams(NUM_ELEMS_PER_NODE)); } void build_tree(const std::vector<point> &pts, const std::vector<size_t> &indices, size_t bucket_size) { build_tree(pts, indices, flann::KDTreeCuda3dIndexParams(bucket_size)); } void get_intersections(const bbox &my_bbox, std::vector<size_t> &intersections_indices) { size_t num_rows = 1; //are only issuing one query int num_dims = my_bbox.first.size(); point_f mid_pt; float squared_radius_search_bound = 0; get_max_squared_radius(my_bbox, mid_pt, squared_radius_search_bound); squared_radius_search_bound += DEFAULT_TOLERANCE; //doens't include things right on the border so we add a tolerance Matrix<float> query(&mid_pt[0], num_rows, num_dims); //has to be ints and floats vector<vector<int>> indices; vector<vector<float>> dists; size_t num_leaves_to_check = FLANN_CHECKS_UNLIMITED; bool search_for_approx_neighbors = false; bool sorted = false; size_t num_results = tree->radiusSearch( query, indices, dists, squared_radius_search_bound, flann::SearchParams(num_leaves_to_check, search_for_approx_neighbors, sorted) ); std::copy(indices[0].begin(), indices[0].begin() + num_results, std::back_inserter(intersections_indices)); } }; #endif } #endif //FLANN_TEST_HH
44.041916
193
0.559211
mlawsonca
399869a8104e74d72feaaeeeea2ca843eeeedb14
5,380
cpp
C++
Engine/SQ/Renderer/RenderContext.cpp
chry003/SqEngine
bb98881a29da48c8c92b33c3534da1fcdd46b92a
[ "MIT" ]
null
null
null
Engine/SQ/Renderer/RenderContext.cpp
chry003/SqEngine
bb98881a29da48c8c92b33c3534da1fcdd46b92a
[ "MIT" ]
null
null
null
Engine/SQ/Renderer/RenderContext.cpp
chry003/SqEngine
bb98881a29da48c8c92b33c3534da1fcdd46b92a
[ "MIT" ]
null
null
null
#include "pch.hpp" #include "RenderContext.hpp" #include "Core/Log.hpp" #include "Event/ApplicationEvent.hpp" #include "Event/KeyEvent.hpp" #include "Event/MouseEvent.hpp" namespace Sq { static bool isGLFWWindowCreated = false; GLFWwindow *RenderContext::m_Window = nullptr; RenderContext::WindowData RenderContext::m_WindowData; void RenderContext::Init(const WindowProps& props) { m_WindowData.Title = props.Title; m_WindowData.Width = props.Width; m_WindowData.Height = props.Height; m_WindowData.Alive = true; if (!isGLFWWindowCreated) { int glfwIniti = glfwInit(); isGLFWWindowCreated = true; ASSERT(glfwIniti, "GLFW Failed to Init!"); } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); m_Window = glfwCreateWindow((int)m_WindowData.Width, (int)m_WindowData.Height, m_WindowData.Title.c_str(), nullptr, nullptr); glfwSetWindowUserPointer(m_Window, &m_WindowData); glfwMakeContextCurrent(m_Window); int status = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); ASSERT(status, "GLAD Failed to Init!"); glViewport(0, 0, (int)m_WindowData.Width, (int)m_WindowData.Height); // Set Vsync true (cap at 60 fps) SetVSync(true); ////////////////////////////////////////////// // Window Event // ////////////////////////////////////////////// glfwSetWindowCloseCallback(m_Window, [](GLFWwindow* window) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); data.Alive = false; WindowCloseEvent event; data.EventCallback(event); }); glfwSetWindowSizeCallback(m_Window, [](GLFWwindow* window, int width, int height) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); data.Width = width; data.Height = height; glViewport(0, 0, (int)width, (int)height); WindowSizeEvent event(width, height); data.EventCallback(event); }); glfwSetWindowPosCallback(m_Window, [](GLFWwindow* window, int xpos, int ypos) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); WindowPosEvent event(xpos, ypos); data.EventCallback(event); }); glfwSetWindowRefreshCallback(m_Window, [](GLFWwindow* window) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); WindowRefreshEvent event; data.EventCallback(event); }); glfwSetWindowFocusCallback(m_Window, [](GLFWwindow* window, int focused) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); WindowFocusedEvent event(focused); data.EventCallback(event); }); ////////////////////////////////////////////// // Keyboard Event // ////////////////////////////////////////////// glfwSetKeyCallback(m_Window, [](GLFWwindow* window, int key, int scancode, int action, int mods) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); switch (action) { case GLFW_PRESS: { KeyPressedEvent event(key, 0); data.EventCallback(event); break; } case GLFW_RELEASE: { KeyReleasedEvent event(key); data.EventCallback(event); break; } case GLFW_REPEAT: { KeyPressedEvent event(key, 1); data.EventCallback(event); break; } } }); ////////////////////////////////////////////// // Mouse Event // ////////////////////////////////////////////// glfwSetCursorPosCallback(m_Window, [](GLFWwindow* window, double xpos, double ypos) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); MousePositionEvent event((float)xpos, (float)ypos); data.EventCallback(event); }); glfwSetMouseButtonCallback(m_Window, [](GLFWwindow* window, int button, int action, int mods) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); switch (action) { case GLFW_PRESS: { MouseButtonPressedEvent event(button); data.EventCallback(event); break; } case GLFW_RELEASE: { MouseButtonReleasedEvent event(button); data.EventCallback(event); break; } } }); glfwSetScrollCallback(m_Window, [](GLFWwindow* window, double xoffset, double yoffset) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); MouseScrollEvent event((float)xoffset, (float)yoffset); data.EventCallback(event); }); } void RenderContext::Terminate() { glfwDestroyWindow(m_Window); // glfwTerminate(); } void RenderContext::OnClear() { glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); } void RenderContext::OnUpdate() { glfwPollEvents(); glfwSwapBuffers(m_Window); } void RenderContext::SetVSync(bool enabled) { if(enabled) glfwSwapInterval(1); else glfwSwapInterval(0); m_WindowData.VSync = enabled; } }
27.309645
127
0.610223
chry003
3999905000dcb06b7bd5286edaac38a82a185b4a
3,675
cc
C++
dyn_prog/dyn_partition_set.cc
prashrock/C-
3ed46815d40b3e42cd9f36d23c8ee2a9de742323
[ "MIT" ]
1
2016-12-05T10:42:46.000Z
2016-12-05T10:42:46.000Z
dyn_prog/dyn_partition_set.cc
prashrock/CPP
3ed46815d40b3e42cd9f36d23c8ee2a9de742323
[ "MIT" ]
null
null
null
dyn_prog/dyn_partition_set.cc
prashrock/CPP
3ed46815d40b3e42cd9f36d23c8ee2a9de742323
[ "MIT" ]
null
null
null
#include <iostream> /* std::cout */ #include <iomanip> /* std::setw */ #include <cmath> /* pow */ #include <cassert> /* assert */ #include <algorithm> /* std::max */ #include <vector> /* std:vector */ #include <string> /* std::string */ #include "print_utils.h" /* print_table_row */ #include "rand_generator.h" /* init_rand() */ using namespace std; /* Determine whether given set can be partitioned* * into two subsets such that the sum of elements* * in both subsets is same. */ const int number_of_iterations = 20; const int max_set_size = 10; const int max_random_number = 10; /* DP Approach * * If sum is odd, then we cannot partition * * If sum is even, then do a DP approach with * * following Recursion * * - table[i][j-1] * * table[i][j] = | * * - table[i-val][j-1] * * Time Complexity = O(sum*n) * * Space Complexity= O(sum*n) */ template<typename T> bool partition_set_dp(const T v[], unsigned int n) { unsigned int total = 0; for(unsigned int i = 0; i < n; i++) total += v[i]; unsigned int partition_sum = total / 2; /*C++11 create 2D vector and initialize to 0*/ vector<vector<bool> > table(partition_sum+1, vector<bool>(n+1, 0)); /* Sum must be capable of being split into * * two equal parts for partitioning */ if(total % 2 != 0){ cout << "\tSum is odd. Cannot partition set." << endl; return false; } /* Initialize DP table */ for(unsigned int i = 0; i <= partition_sum; ++i) table[i][0] = false; for(unsigned int j = 0; j <= n; ++j) table[0][j] = true; for(unsigned int sum = 1; sum <= partition_sum; ++sum) { for(unsigned int j = 1; j <= n; ++j) { auto val = v[j-1]; /* If previous column is set, then set here as well */ table[sum][j] = table[sum][j-1]; /* If previous column is set, then set here as well * * Note: table[sum-val][j-1], has j-1 and not j to * * find if [sum-val] can be reached without using j */ if(val < 0 || (unsigned int)val <= sum) table[sum][j] = table[sum][j] | table[sum - val][j-1]; } } /* Can partition succesfully */ if(table[partition_sum][n] == true) return true; /* Print output table */ cout << "\tSUM = " << total << endl; vector<T> inp(1); for(unsigned int i=0; i <n; i++) inp.push_back(v[i]); print_table_row<T>("\tinput", inp); for(unsigned int sum = 0; sum <= partition_sum; ++sum) { std::string name = "\tsum:" + std::to_string(sum); print_table_row<bool>(name, table[sum]); } cout << "\tPartition failed" << endl; return table[partition_sum][n]; } /* Given set size, generate elements randomly * * and call partition set algorithm */ void partition_set_tester(size_t set_size) { std::vector<int> v(set_size); /* Generate vector contents randomly */ fill_vector_rand(v, 0, max_random_number); print_table_row<int>("input", v); partition_set_dp(&v[0], v.size()); } int main() { cout << "Running " << number_of_iterations << " iterations " << "each with set size " << max_set_size << endl; init_rand(); for(int i = 1; i <= number_of_iterations; i++) partition_set_tester(max_set_size); }
36.029412
72
0.530612
prashrock
39a50575ce53464c73c7ba4c42f63f9602b7512d
4,747
hpp
C++
SDX_Display.hpp
ffhighwind/DeferredShading
c8b765c5d1126ef8f337047db50e2eb63308baf9
[ "Apache-2.0" ]
1
2019-10-18T13:45:05.000Z
2019-10-18T13:45:05.000Z
SDX_Display.hpp
ffhighwind/DeferredShading
c8b765c5d1126ef8f337047db50e2eb63308baf9
[ "Apache-2.0" ]
1
2019-10-18T13:44:49.000Z
2019-11-29T23:26:27.000Z
SDX_Display.hpp
ffhighwind/DeferredShading
c8b765c5d1126ef8f337047db50e2eb63308baf9
[ "Apache-2.0" ]
null
null
null
/* * SDX Display classes * * Copyright (c) 2013 Wesley Hamilton * * 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. */ #pragma once #ifndef SDX_DISPLAY_HPP #define SDX_DISPLAY_HPP #include <SDL_video.h> #include <string> #include <vector> namespace sdx { class Window; enum class PixelFormat : Uint32 { UNKNOWN = SDL_PIXELFORMAT_UNKNOWN, INDEX1LSP = SDL_PIXELFORMAT_INDEX1LSB, INDEX1MSB = SDL_PIXELFORMAT_INDEX1MSB, INDEX4LSB = SDL_PIXELFORMAT_INDEX4LSB, INDEX4MSB = SDL_PIXELFORMAT_INDEX4MSB, INDEX8 = SDL_PIXELFORMAT_INDEX8, RGB332 = SDL_PIXELFORMAT_RGB332, RGB444 = SDL_PIXELFORMAT_RGB444, RGB555 = SDL_PIXELFORMAT_RGB555, BGR555 = SDL_PIXELFORMAT_BGR555, ARGB4444 = SDL_PIXELFORMAT_ARGB4444, RGBA4444 = SDL_PIXELFORMAT_RGBA4444, ABGR4444 = SDL_PIXELFORMAT_ABGR4444, BGRA4444 = SDL_PIXELFORMAT_BGRA4444, ARGB1555 = SDL_PIXELFORMAT_ARGB1555, RGBA5551 = SDL_PIXELFORMAT_RGBA5551, ABGR1555 = SDL_PIXELFORMAT_ABGR1555, BGRA5551 = SDL_PIXELFORMAT_BGRA5551, RGB565 = SDL_PIXELFORMAT_RGB565, BGR565 = SDL_PIXELFORMAT_BGR565, RGB24 = SDL_PIXELFORMAT_RGB24, BGR24 = SDL_PIXELFORMAT_BGR24, RGB888 = SDL_PIXELFORMAT_RGB888, RGBX8888 = SDL_PIXELFORMAT_RGBX8888, BGR888 = SDL_PIXELFORMAT_BGR888, BGRX8888 = SDL_PIXELFORMAT_BGRX8888, ARGB8888 = SDL_PIXELFORMAT_ARGB8888, RGBA8888 = SDL_PIXELFORMAT_RGBA8888, ABGR8888 = SDL_PIXELFORMAT_ABGR8888, BGRA8888 = SDL_PIXELFORMAT_BGRA8888, ARGB2101010 = SDL_PIXELFORMAT_ARGB2101010, RGBA32 = SDL_PIXELFORMAT_RGBA32, // alias for RGBA byte array of color data, for the current platform(>= SDL 2.0.5) ARGB32 = SDL_PIXELFORMAT_ARGB32, // alias for ARGB byte array of color data, for the current platform(>= SDL 2.0.5) BGRA32 = SDL_PIXELFORMAT_BGRA32, // alias for BGRA byte array of color data, for the current platform(>= SDL 2.0.5) ABGR32 = SDL_PIXELFORMAT_ABGR32, // alias for ABGR byte array of color data, for the current platform(>= SDL 2.0.5) YV12 = SDL_PIXELFORMAT_YV12, // planar mode : Y + V + U(3 planes) IYUV = SDL_PIXELFORMAT_IYUV, // planar mode : Y + U + V(3 planes) YUY2 = SDL_PIXELFORMAT_YUY2, // packed mode : Y0 + U0 + Y1 + V0(1 plane) UYVY = SDL_PIXELFORMAT_UYVY, // packed mode : U0 + Y0 + V0 + Y1(1 plane) YVYU = SDL_PIXELFORMAT_YVYU, // packed mode : Y0 + V0 + Y1 + U0(1 plane) NV12 = SDL_PIXELFORMAT_NV12, // planar mode : Y + U / V interleaved(2 planes) (>= SDL 2.0.4) NV21 = SDL_PIXELFORMAT_NV21, // planar mode : Y + V / U interleaved(2 planes) (>= SDL 2.0.4) }; class DisplayMode { protected: SDL_DisplayMode _mode; public: DisplayMode() {} DisplayMode(const SDL_DisplayMode &mode) : _mode(mode) {} DisplayMode(int width, int height, int refreshRate, PixelFormat format); int GetWidth() const; void SetWidth(int width); int GetHeight() const; void SetHeight(int height); int GetRefreshRate() const; void SetRefreshRate(int refreshRate); PixelFormat GetPixelFormat() const; void SetPixelFormat(PixelFormat format); std::string FormatName() const; int GetBitsPerPixel() const; friend class sdx::VideoDisplay; friend class sdx::Window; }; class VideoDisplay { protected: int _index; public: VideoDisplay(int index = 0) : _index(index) {} static int NumVideoDisplays(); static int NumVideoDrivers(); static std::string CurrentVideoDriver(); std::string GetVideoDriver() const; std::string GetDisplayName() const; void GetDisplayModes(std::vector<DisplayMode> &modes) const; DisplayMode GetClosestDisplayMode(const DisplayMode &mode); bool GetBounds(int *x, int *y, int *w, int *h) const; DisplayMode GetDesktopDisplayMode() const; DisplayMode GetCurrentDisplayMode() const; bool GetDPI(float *ddpi, float *hdpi, float *vdpi) const; }; } // namespace sdx #include "SDX_Display.inl" #endif // SDX_DISPLAY_HPP
36.236641
116
0.7668
ffhighwind
39a97a87d8b2d46e3c222a246311d3c79a0092e9
1,176
cpp
C++
engine/Engine.UI/src/ui/widget/button/CheckBox.cpp
Kartikeyapan598/Ghurund
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
[ "MIT" ]
null
null
null
engine/Engine.UI/src/ui/widget/button/CheckBox.cpp
Kartikeyapan598/Ghurund
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
[ "MIT" ]
10
2018-03-20T21:32:16.000Z
2018-04-23T19:42:59.000Z
engine/Engine.UI/src/ui/widget/button/CheckBox.cpp
Kartikeyapan598/Ghurund
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
[ "MIT" ]
null
null
null
#include "ghuipch.h" #include "CheckBox.h" #include "ui/control/ImageView.h" #include "ui/style/Theme.h" namespace Ghurund::UI { const Ghurund::Core::Type& CheckBox::GET_TYPE() { static const auto CONSTRUCTOR = Constructor<CheckBox>(); static const Ghurund::Core::Type TYPE = TypeBuilder<CheckBox>(NAMESPACE_NAME, GH_STRINGIFY(CheckBox)) .withConstructor(CONSTRUCTOR) .withSupertype(__super::GET_TYPE()); return TYPE; } void CheckBoxStyle::onStateChanged(Control& control) const { Theme* theme = control.Theme; if (!theme) return; /*CheckBox& checkBoxRadio = (CheckBox&)control; if (checkBoxRadio->selectable->Selected) { SharedPointer<ImageDrawable> image = (ImageDrawable*)theme->Images[Theme::IMAGE_CHECKBOX_CHECKED]->clone(); checkBoxRadio->image->Image = image; } else { SharedPointer<ImageDrawable> image = (ImageDrawable*)theme->Images[Theme::IMAGE_CHECKBOX_UNCHECKED]->clone(); checkBoxRadio->image->Image = image; }*/ __super::onStateChanged(control); } }
37.935484
125
0.630102
Kartikeyapan598
39a9add9ae261014115b0acbb2e30c457e705782
4,733
cpp
C++
Control Work - 04.04.2022/Project1/Fraction.cpp
ElitProffi/HW2021-2022
375abed060ad5a79e6486af0af367725294730d8
[ "Apache-2.0" ]
null
null
null
Control Work - 04.04.2022/Project1/Fraction.cpp
ElitProffi/HW2021-2022
375abed060ad5a79e6486af0af367725294730d8
[ "Apache-2.0" ]
null
null
null
Control Work - 04.04.2022/Project1/Fraction.cpp
ElitProffi/HW2021-2022
375abed060ad5a79e6486af0af367725294730d8
[ "Apache-2.0" ]
null
null
null
#include "Fraction.h" using namespace std; Fraction::Fraction() { a = 1; b = 1; } Fraction::Fraction(long long a, long long b) : a(a), b(b) {} Fraction::Fraction(const Fraction& fraction) : a(fraction.a), b(fraction.b) {} Fraction::~Fraction() { this->a = 0; this->b = 0; } long long Fraction::getA() { return this->a; } void Fraction::setA(long long a) { this->a = a; } long long Fraction::getB() { return this->b; } void Fraction::setB(long long b) { this->b = b; } void Fraction::set(long long a, long long b) { this->a = a; this->b = b; } std::ostream& operator<<(std::ostream& stream, const Fraction& fraction) { if (fraction.a * fraction.b < 0) { cout << "-"; } long long c1 = abs(fraction.a); long long c2 = abs(fraction.b); while (c1 != c2) { if (c1 > c2) { c1 = c1 - c2; } else { c2 = c2 - c1; } } stream << abs(fraction.a / c1) << "/" << abs(fraction.b / c1); return stream; } Fraction& Fraction::operator=(const Fraction& fraction) { this->a = fraction.a; this->b = fraction.b; return *this; } Fraction Fraction::operator-(const Fraction& fraction) { return Fraction(this->a * fraction.b - fraction.a * this->b, this->b * fraction.b); } Fraction operator-(const long long k, const Fraction& fraction) { return Fraction(k * fraction.b - fraction.a, fraction.b); } Fraction Fraction::operator+(const Fraction& fraction) { return Fraction(this->a * fraction.b + fraction.a * this->b, this->b * fraction.b); } Fraction operator+(const long long k, const Fraction& fraction) { return Fraction(fraction.a + k * fraction.b , fraction.b); } Fraction Fraction::operator*(const Fraction& fraction) { return Fraction(this->a * fraction.a, this->b * fraction.b); } Fraction operator*(const long long mult, const Fraction& fraction) { return Fraction(mult * fraction.a, fraction.b); } Fraction operator*(const Fraction& fraction, const long long mult) { return Fraction(mult * fraction.a, fraction.b); } Fraction Fraction::operator/(const Fraction& fraction) { return Fraction(this->a * fraction.b, this->b * fraction.a); } Fraction operator/(const long long k, const Fraction& fraction) { Fraction c = Fraction(k, 1); return (c / fraction); } Fraction operator/(Fraction& fraction, const long long k) { Fraction c = Fraction(k, 1); return (fraction / c); } Fraction Fraction::abs() { if ((this-> a > 0) and (this-> b > 0)) { return Fraction(this-> a, this-> b); } if ((this-> a < 0) and (this->b > 0)) { return Fraction(this->a * (-1), this->b); } if ((this->a > 0) and (this->b < 0)) { return Fraction(this->a, this->b * (-1)); } if ((this->a < 0) and (this->b < 0)) { return Fraction(this->a * (-1), this->b * (-1)); } } Fraction Fraction::reverse() { return Fraction(this->b, this->a); } Fraction Fraction::power(long long s) { long long c1 = 1; long long c2 = 1; for (int i = 0; i < s; ++i) { c1 = c1 * a; c2 = c2 * b; } return Fraction(c1, c2); } bool Fraction::operator==(const Fraction& fraction) { return bool(this->a * fraction.b == this->b * fraction.a); } bool operator==(const long long k, const Fraction& fraction) { Fraction c = Fraction(k, 1); return (c == fraction); } bool operator==(Fraction& fraction, const long long k) { Fraction c = Fraction(k, 1); return (fraction == c); } bool Fraction::operator>(const Fraction& fraction) { return bool((this->a / this->b) > (fraction.a / fraction.b)); } bool operator>(const long long k, const Fraction& fraction) { Fraction c = Fraction(k, 1); return (c > fraction); } bool operator>(Fraction& fraction, const long long k) { Fraction c = Fraction(k, 1); return (fraction > c); } bool Fraction::operator<(const Fraction& fraction) { return bool((this->a / this->b) < (fraction.a / fraction.b)); } bool operator<(const long long k, const Fraction& fraction) { Fraction c = Fraction(k, 1); return (c < fraction); } bool operator<(Fraction& fraction, const long long k) { Fraction c = Fraction(k, 1); return (fraction < c); } bool Fraction::operator<=(const Fraction& fraction) { return bool((this->a / this->b) <= (fraction.a / fraction.b)); } bool operator<=(const long long k, const Fraction& fraction) { Fraction c = Fraction(k, 1); return (c <= fraction); } bool operator<=(Fraction& fraction, const long long k) { Fraction c = Fraction(k, 1); return (fraction <= c); } bool Fraction::operator>=(const Fraction& fraction) { return bool((this->a / this->b) >= (fraction.a / fraction.b)); } bool operator>=(const long long k, const Fraction& fraction) { Fraction c = Fraction(k, 1); return (c >= fraction); } bool operator>=(Fraction& fraction, const long long k) { Fraction c = Fraction(k, 1); return (fraction >= c); }
18.781746
84
0.64251
ElitProffi
39b3c33544c2311e3319c6273cf6fff2df26ef10
5,811
hpp
C++
src/ropufu/sequential/cusum.hpp
ropufu/aftermath
ab9364c41672a188879d84ebebb5a23f2d6641ec
[ "MIT" ]
null
null
null
src/ropufu/sequential/cusum.hpp
ropufu/aftermath
ab9364c41672a188879d84ebebb5a23f2d6641ec
[ "MIT" ]
null
null
null
src/ropufu/sequential/cusum.hpp
ropufu/aftermath
ab9364c41672a188879d84ebebb5a23f2d6641ec
[ "MIT" ]
null
null
null
#ifndef ROPUFU_AFTERMATH_SEQUENTIAL_CUSUM_HPP_INCLUDED #define ROPUFU_AFTERMATH_SEQUENTIAL_CUSUM_HPP_INCLUDED #ifndef ROPUFU_NO_JSON #include <nlohmann/json.hpp> #include "../noexcept_json.hpp" #endif #include "../simple_vector.hpp" #include "statistic.hpp" #include <concepts> // std::same_as, std::totally_ordered #include <cstddef> // std::size_t #include <functional> // std::hash #include <ranges> // std::ranges::... #include <stdexcept> // std::runtime_error #include <string_view> // std::string_view #include <utility> // std::forward #ifdef ROPUFU_TMP_TYPENAME #undef ROPUFU_TMP_TYPENAME #endif #ifdef ROPUFU_TMP_TEMPLATE_SIGNATURE #undef ROPUFU_TMP_TEMPLATE_SIGNATURE #endif #define ROPUFU_TMP_TYPENAME cusum<t_value_type, t_container_type> #define ROPUFU_TMP_TEMPLATE_SIGNATURE \ template <std::totally_ordered t_value_type, std::ranges::random_access_range t_container_type> \ requires std::same_as<std::ranges::range_value_t<t_container_type>, t_value_type> \ namespace ropufu::aftermath::sequential { /** CUSUM statistic keeps trac of the maximum of all partial sums. */ template <std::totally_ordered t_value_type, std::ranges::random_access_range t_container_type = aftermath::simple_vector<t_value_type>> requires std::same_as<std::ranges::range_value_t<t_container_type>, t_value_type> struct cusum; #ifndef ROPUFU_NO_JSON ROPUFU_TMP_TEMPLATE_SIGNATURE void to_json(nlohmann::json& j, const ROPUFU_TMP_TYPENAME& x) noexcept; ROPUFU_TMP_TEMPLATE_SIGNATURE void from_json(const nlohmann::json& j, ROPUFU_TMP_TYPENAME& x); #endif ROPUFU_TMP_TEMPLATE_SIGNATURE struct cusum : public statistic<t_value_type, t_container_type> { using type = ROPUFU_TMP_TYPENAME; using value_type = t_value_type; using container_type = t_container_type; /** Names the statistic. */ static constexpr std::string_view name = "CUSUM"; // ~~ Json names ~~ static constexpr std::string_view jstr_type = "type"; static constexpr std::string_view jstr_window_size = "window"; #ifndef ROPUFU_NO_JSON friend ropufu::noexcept_json_serializer<type>; #endif friend std::hash<type>; private: // Latest statistic value. value_type m_latest_statistic = 0; public: cusum() noexcept = default; /** The underlying process has been cleared. */ void reset() noexcept override { this->m_latest_statistic = 0; } // reset(...) /** Observe a single value. */ value_type observe(const value_type& value) noexcept override { if (this->m_latest_statistic < 0) this->m_latest_statistic = 0; this->m_latest_statistic += value; return this->m_latest_statistic; } // observe(...) /** Observe a block of values. */ container_type observe(const container_type& values) noexcept override { container_type statistics = values; for (std::size_t i = 0; i < values.size(); ++i) { if (this->m_latest_statistic < 0) this->m_latest_statistic = 0; this->m_latest_statistic += values[i]; statistics[i] = this->m_latest_statistic; } // for (...) return statistics; } // observe(...) bool operator ==(const type& other) const noexcept { return this->m_latest_statistic == other.m_latest_statistic; } // operator ==(...) bool operator !=(const type& other) const noexcept { return !this->operator ==(other); } // operator !=(...) #ifndef ROPUFU_NO_JSON friend void to_json(nlohmann::json& j, const type& /*x*/) noexcept { j = nlohmann::json{ {type::jstr_type, type::name} }; } // to_json(...) friend void from_json(const nlohmann::json& j, type& x) { if (!ropufu::noexcept_json::try_get(j, x)) throw std::runtime_error("Parsing <cusum> failed: " + j.dump()); } // from_json(...) #endif }; // struct cusum } // namespace ropufu::aftermath::sequential #ifndef ROPUFU_NO_JSON namespace ropufu { ROPUFU_TMP_TEMPLATE_SIGNATURE struct noexcept_json_serializer<ropufu::aftermath::sequential::ROPUFU_TMP_TYPENAME> { using result_type = ropufu::aftermath::sequential::ROPUFU_TMP_TYPENAME; static bool try_get(const nlohmann::json& j, result_type& /*x*/) noexcept { std::string statistic_name; std::size_t window_size = 0; if (!noexcept_json::required(j, result_type::jstr_type, statistic_name)) return false; if (!noexcept_json::optional(j, result_type::jstr_window_size, window_size)) return false; if (window_size != 0) return false; if (statistic_name != result_type::name) return false; return true; } // try_get(...) }; // struct noexcept_json_serializer<...> } // namespace ropufu #endif namespace std { ROPUFU_TMP_TEMPLATE_SIGNATURE struct hash<ropufu::aftermath::sequential::ROPUFU_TMP_TYPENAME> { using argument_type = ropufu::aftermath::sequential::ROPUFU_TMP_TYPENAME; std::size_t operator ()(const argument_type& x) const noexcept { std::size_t result = 0; std::hash<typename argument_type::value_type> statistic_hasher = {}; result ^= statistic_hasher(x.m_latest_statistic); return result; } // operator ()(...) }; // struct hash<...> } // namespace std #endif // ROPUFU_AFTERMATH_SEQUENTIAL_CUSUM_HPP_INCLUDED
33.589595
102
0.641714
ropufu
39b3d201c4182d3721dc5b2e71c73c0f2c7e5641
374
cpp
C++
CPP/ex4.4.7virt.cpp
w1ld/StepikExercies
3efe07819a0456aa3846587b2a23bad9dd9710db
[ "MIT" ]
4
2019-05-11T17:26:24.000Z
2022-01-30T17:48:25.000Z
CPP/ex4.4.7virt.cpp
w1ld/StepikExercises
3efe07819a0456aa3846587b2a23bad9dd9710db
[ "MIT" ]
null
null
null
CPP/ex4.4.7virt.cpp
w1ld/StepikExercises
3efe07819a0456aa3846587b2a23bad9dd9710db
[ "MIT" ]
4
2019-01-24T22:15:21.000Z
2020-12-21T10:23:52.000Z
#include "ex4.3.8virt_methods.cpp" #include <iostream> bool check_equals(Expression const *left, Expression const *right) { return *((int**)left) ==*((int**)right); } int main() { Expression * sube = new BinaryOperation(new Number(4.5), '*', new Number(5)); Expression * another = new Number(4.5); std::cout << check_equals(sube, sube) << std::endl; }
24.933333
79
0.641711
w1ld
39b45753ad0befad2e75a1bddde980d432dc82d9
1,865
cpp
C++
main.cpp
SzalonyJohny/STM32_CAN_abstraction
4465c4c9bd8367429db6eed78cce001d294370ff
[ "MIT" ]
null
null
null
main.cpp
SzalonyJohny/STM32_CAN_abstraction
4465c4c9bd8367429db6eed78cce001d294370ff
[ "MIT" ]
null
null
null
main.cpp
SzalonyJohny/STM32_CAN_abstraction
4465c4c9bd8367429db6eed78cce001d294370ff
[ "MIT" ]
null
null
null
#include <cstdint> #include <iostream> #include "can_interface.hpp" using namespace new_can; // global HAL CUBE_MX initialized data CAN_HandleTypeDef hcan1; // global can interface handle Can_interface can; // uint32_t TxMailbox = 3; void interrupt_handler() { Can_rx_message rx{hcan1, 1}; if (rx.status == HAL_StatusTypeDef::HAL_OK) { can.get_message(rx); } else { // Error_handler("Error while reciving data from CAN"); } } void recive_example() { interrupt_handler(); [[maybe_unused]]auto apps = can.get_apps_data(); [[maybe_unused]]auto d = can.get_acquisition_card_data().wheel_time_interval_left; } void send_example() { Apps_data apps_test; apps_test.apps_value = 1300; apps_test.d_apps_dt = 3; apps_test.apps_status = Apps_status_struct::ALL_OK; // example sending senario` auto tx = Can_tx_message(apps_test, can_tx_header_apps); auto res = tx.send(hcan1, &TxMailbox); if (res != HAL_StatusTypeDef::HAL_OK) { // Error_Handler("CAN sending error"); }; } void test_case_can_tx_message() { Apps_data apps_test; apps_test.apps_status = Apps_status_struct::ALL_OK; apps_test.apps_value = 1300; apps_test.d_apps_dt = 3; // example sending senario auto tx = Can_tx_message(apps_test, can_tx_header_apps); auto res = tx.send(hcan1, &TxMailbox); if (res != HAL_StatusTypeDef::HAL_OK) { // Error_Handler("CAN sending error"); }; // copy tx to rx (CAN simulation) Can_rx_message rx{hcan1, 1}; std::copy(tx.buff, tx.buff + sizeof(Apps_data), rx.data); // print rx buffor printf("\nbuffor: "); for (std::size_t i = 0; i < sizeof(Apps_data); ++i) { printf(" %d", (int)rx.data[i]); } // CAN recive data can.get_message(rx); } int main() { test_case_can_tx_message(); }
21.686047
85
0.662198
SzalonyJohny
39b65f31eb34d053ae3030b968ec27bc0da5f9cc
601
hpp
C++
main.hpp
GGLinnk/Direct3D-9-Helpers
ac44882a6ebaf8abde2cc8d485dd0c821934aadd
[ "MIT" ]
null
null
null
main.hpp
GGLinnk/Direct3D-9-Helpers
ac44882a6ebaf8abde2cc8d485dd0c821934aadd
[ "MIT" ]
null
null
null
main.hpp
GGLinnk/Direct3D-9-Helpers
ac44882a6ebaf8abde2cc8d485dd0c821934aadd
[ "MIT" ]
null
null
null
#pragma once /// <summary> /// This function compares two D3DDISPLAYMODE allow qsort to sorts them by their width, then by their height and finally by their refresh rate. /// </summary> /// <param name="firstD3dDisplayMode">The first D3DDISPLAYMODE to be compared</param> /// <param name="secondD3dDisplayMode">The second D3DDISPLAYMODE to be compared</param> /// <returns> /// <para>If width, height or </para> /// <para>If modes are fully identical. Returns 0.</para> /// <para></para> /// </returns> int d3dDisplayModeCmp(const void *firstD3dDisplayMode, const void *secondD3dDisplayMode);
46.230769
145
0.727121
GGLinnk
39c22e2c5c798ca313a7c20a2cc54bc809d4352c
3,296
cpp
C++
sdl1/Bejeweled/Engine.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/Bejeweled/Engine.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/Bejeweled/Engine.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
#include <SDL.h> #include <SDL_image.h> #include <SDL_ttf.h> #include <SDL_mixer.h> #include "Engine.h" #include "GameObject.h" #include "SurfaceProxy.h" #include "GameException.h" #include "GameScene.h" #include "Point.h" namespace bejeweled { const int Engine::GAME_FPS = 10; const string Engine::WINDOW_TITLE = "Bejeweled"; const string Engine::ICON_IMG = "resources\\icon.ico"; Engine::Engine() : m_gameIcon(NULL), m_screen(NULL), m_curScene(NULL) { /// Initialize SDL subsystems. if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) || !IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG) || TTF_Init()) { throw GameException(); } // Detect the size of the background image // Must manually load icon, before calling to SDL_SetVideoMode. (Only under Windows) Point backgroundDimensions = SurfaceProxy::getImageDimensions(GameScene::BACKGROUND_IMG); m_gameIcon = m_resManager.loadSimpleImage(ICON_IMG); #if defined(_WIN64) || defined(_WIN32) SDL_WM_SetIcon(m_gameIcon, NULL); SDL_WM_SetCaption(WINDOW_TITLE.c_str(),NULL); #endif // Software rendering as this is a simple game. Can use hardware+doublebuf instead. m_screen = SDL_SetVideoMode(backgroundDimensions.first, backgroundDimensions.second, 32, SDL_SWSURFACE); if(!m_screen) { throw GameException(); } // Allow playing ogg audio files. if(!Mix_Init(MIX_INIT_OGG)) { throw GameException(); } // Initialize SDL_mixer if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096) == -1) { throw GameException(); } m_fpsTimer.start(); } Engine::~Engine() { delete m_curScene; SDL_FreeSurface(m_screen); Mix_Quit(); Mix_CloseAudio(); TTF_Quit(); SDL_Quit(); } void Engine::run() { // Set current scene to the game scene (we only have one scene in this game) m_curScene = new GameScene(0, 0, m_screen); if(!m_curScene) { throw GameException(); } SDL_Event event; // Note - Since we only have one scene (that is, one game state) - this "game over" check will do. // If we had multiple game states, such as introduction screen, main menu, etc., we could adapt the State pattern. while(!static_cast<GameScene*>(m_curScene)->isGameover()) { m_fpsTimer.start(); /// Engine handles exit events, and calls the handle method of the current scene. while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: return; case SDL_KEYDOWN: if(event.key.keysym.sym == SDLK_F4 && (event.key.keysym.mod == KMOD_LALT || event.key.keysym.mod == KMOD_RALT)) { return; } default: break; } m_curScene->handleEvent(&event); } m_curScene->update(); m_curScene->draw(); if(SDL_Flip(m_screen)) { throw GameException(); } // Regulate FPS if(m_fpsTimer.getTicks() < 1000.0 / GAME_FPS) { SDL_Delay((1000.0 / GAME_FPS) - m_fpsTimer.getTicks()); } } // Game exit - wait for 2 seconds and then exit. SDL_Delay(2000); } } // namespace bejeweled
30.238532
125
0.62409
pdpdds
39ca0caf927ec3d7e5548cc3e4fd05462eebfc91
779
cpp
C++
tggdhj2/Game.Avatar.Log.cpp
playdeezgames/tggdhj2
41c76ce27087bb4e53a6adc69c5b3fe7dcfbb7f7
[ "MIT" ]
null
null
null
tggdhj2/Game.Avatar.Log.cpp
playdeezgames/tggdhj2
41c76ce27087bb4e53a6adc69c5b3fe7dcfbb7f7
[ "MIT" ]
null
null
null
tggdhj2/Game.Avatar.Log.cpp
playdeezgames/tggdhj2
41c76ce27087bb4e53a6adc69c5b3fe7dcfbb7f7
[ "MIT" ]
null
null
null
#include "Data.Game.Avatar.Log.h" #include "Game.Avatar.Log.h" #include "Visuals.Data.Colors.h" namespace game::avatar::Log { const std::string WELCOME_TEXT = "Adventure awaits! HUZZAH!!"; const size_t ENTRY_COUNT = 12;//TODO: maybe this could be configurable somewhere? void Reset(const Difficulty&) { data::game::avatar::Log::Clear(); Write({ visuals::data::Colors::HIGHLIGHT, WELCOME_TEXT }); } std::list<LogEntry> Read() { std::list<LogEntry> results; auto entries = data::game::avatar::Log::Read(ENTRY_COUNT); for (auto entry : entries) { results.push_back( { std::get<0>(entry), std::get<1>(entry) }); } return results; } void Write(const LogEntry& entry) { data::game::avatar::Log::Write(entry.color, entry.text); } }
22.257143
82
0.664955
playdeezgames
39ccd04c3616205c774c2aec3134a8d391f7977d
3,995
cpp
C++
codebook/geometry/point-in-polygon.cpp
nella17/NYCU_gAwr_gurA
e168cafc9e728a2cab2d1cafa90a1cfd433b9f59
[ "CC0-1.0" ]
1
2022-01-23T11:18:52.000Z
2022-01-23T11:18:52.000Z
codebook/geometry/point-in-polygon.cpp
nella17/NYCU_gAwr_gurA
e168cafc9e728a2cab2d1cafa90a1cfd433b9f59
[ "CC0-1.0" ]
null
null
null
codebook/geometry/point-in-polygon.cpp
nella17/NYCU_gAwr_gurA
e168cafc9e728a2cab2d1cafa90a1cfd433b9f59
[ "CC0-1.0" ]
1
2022-02-02T15:24:39.000Z
2022-02-02T15:24:39.000Z
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; template <typename T> using rbt = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; using Double = __float128; using Point = pair<Double, Double>; #define x first #define y second Point operator+(const Point &a, const Point &b) { return {a.x + b.x, a.y + b.y}; } Point operator-(const Point &a, const Point &b) { return {a.x - b.x, a.y - b.y}; } Double dot(Point u, Point v) { return u.x * v.x + u.y * v.y; } Double cross(Point u, Point v) { return u.x * v.y - u.y * v.x; } int n, m; vector<Point> poly; vector<Point> query; vector<int> ans; struct Segment { Point a, b; int id; }; vector<Segment> segs; Double Xnow; inline Double get_y(const Segment &u, Double xnow = Xnow) { const Point &a = u.a; const Point &b = u.b; return (a.y * (b.x - xnow) + b.y * (xnow - a.x)) / (b.x - a.x); } bool operator<(Segment u, Segment v) { Double yu = get_y(u); Double yv = get_y(v); if (yu != yv) return yu < yv; return u.id < v.id; } rbt<Segment> st; struct Event { int type; // +1 insert seg, -1 remove seg, 0 query Double x, y; int id; }; bool operator<(Event a, Event b) { if (a.x != b.x) return a.x < b.x; if (a.type != b.type) return a.type < b.type; return a.y < b.y; } vector<Event> events; void solve() { set<Double> xs; set<Point> ps; for (int i = 0; i < n; i++) { xs.insert(poly[i].x); ps.insert(poly[i]); } for (int i = 0; i < n; i++) { Segment s{poly[i], poly[(i + 1) % n], i}; if (s.a.x > s.b.x || (s.a.x == s.b.x && s.a.y > s.b.y)) { swap(s.a, s.b); } segs.push_back(s); if (s.a.x != s.b.x) { events.push_back({+1, s.a.x + 0.2, s.a.y, i}); events.push_back({-1, s.b.x - 0.2, s.b.y, i}); } } for (int i = 0; i < m; i++) { events.push_back({0, query[i].x, query[i].y, i}); } sort(events.begin(), events.end()); int cnt = 0; for (Event e : events) { int i = e.id; Xnow = e.x; if (e.type == 0) { Double x = e.x; Double y = e.y; Segment tmp = {{x - 1, y}, {x + 1, y}, -1}; auto it = st.lower_bound(tmp); if (ps.count(query[i]) > 0) { ans[i] = 0; } else if (xs.count(x) > 0) { ans[i] = -2; } else if (it != st.end() && get_y(*it) == get_y(tmp)) { ans[i] = 0; } else if (it != st.begin() && get_y(*prev(it)) == get_y(tmp)) { ans[i] = 0; } else { int rk = st.order_of_key(tmp); if (rk % 2 == 1) { ans[i] = 1; } else { ans[i] = -1; } } } else if (e.type == 1) { st.insert(segs[i]); assert((int)st.size() == ++cnt); } else if (e.type == -1) { st.erase(segs[i]); assert((int)st.size() == --cnt); } } } int main() { cin.tie(0); cin.sync_with_stdio(0); cin >> n >> m; poly = vector<Point>(n); for (int i = 0; i < n; i++) { long long x, y; cin >> x >> y; poly[i] = {x * (2e9 + 1) + y, y}; } query = vector<Point>(m); ans = vector<int>(m); for (int i = 0; i < m; i++) { long long x, y; cin >> x >> y; query[i] = {x * (2e9 + 1) + y, y}; } solve(); for (int i = 0; i < m; i++) { int flag = ans[i]; if (flag == 1) { cout << "YES" << '\n'; } else if (flag == 0) { cout << "YES" << '\n'; } else if (flag == -1) { cout << "NO" << '\n'; } else { cout << "UNKNOWN" << '\n'; } } return 0; }
25.125786
80
0.442053
nella17
39cd5b5f3434757796e0e0b317a69253ea2abc12
1,359
cpp
C++
Engine/src/Managers/Sound.cpp
Proyecto03/Motor
9e7f379f1f64bc911293434fdfb8aa18bb8f99ab
[ "MIT" ]
1
2021-07-24T03:10:38.000Z
2021-07-24T03:10:38.000Z
Engine/src/Managers/Sound.cpp
Proyecto03/Motor
9e7f379f1f64bc911293434fdfb8aa18bb8f99ab
[ "MIT" ]
null
null
null
Engine/src/Managers/Sound.cpp
Proyecto03/Motor
9e7f379f1f64bc911293434fdfb8aa18bb8f99ab
[ "MIT" ]
2
2021-05-11T10:47:37.000Z
2021-07-24T03:10:39.000Z
#include "windows.h" #include "fmod.h" #include "fmod_errors.h" #include ".\sound.h" class Sound { public: Sound(char *fname); ~Sound(void); void createScene(float pos[]); void Sound::play(); void Sound::stop() ; }; FSOUND_SAMPLE *sample; char *filename; int m_channel; Sound::Sound(char *fname) { sample = 0; //sample = NULL; filename = fname; } Sound::~Sound(void) { if(sample != 0) FSOUND_Sample_Free(sample); } void Sound::createScene(float pos[]) { float vel[3] = { 0,0,0 }; int num2d, num3d; if((sample = FSOUND_Sample_Load(FSOUND_FREE, filename, FSOUND_HW3D, 0, 0)) == 0) { MessageBox( NULL, NULL, "bad wav file name!", MB_OK | MB_ICONERROR | MB_TASKMODAL ); } FSOUND_Sample_SetMinMaxDistance(sample, 4.0f, 10000.0f); FSOUND_Sample_SetMode(sample, FSOUND_LOOP_NORMAL); m_channel = FSOUND_PlaySoundEx(FSOUND_FREE, sample, 0, true); FSOUND_3D_SetAttributes(m_channel, pos, vel); FSOUND_GetNumHWChannels(&num2d, &num3d, 0); } void Sound::play() { //FSOUND_SetPaused(m_channel, FALSE); FSOUND_SetPaused(m_channel, false); } void Sound::stop() { //FSOUND_SetPaused(m_channel, TRUE); FSOUND_SetPaused(m_channel, true); } void Sound::createScene(Ogre::Vector3 vec) { int pos[] = { vec[0], vec[1], vec[2] }; createScene(pos); }
19.140845
90
0.649007
Proyecto03
39cdacb331070ffa5d245795242cb23aa905b58f
10,165
cpp
C++
VS/Graphics/VS_ShaderValues.cpp
vectorstorm/vectorstorm
7306214108b23fa97d4a1a598197bbaa52c17d3a
[ "Zlib" ]
19
2017-04-03T09:06:21.000Z
2022-03-05T19:06:07.000Z
VS/Graphics/VS_ShaderValues.cpp
vectorstorm/vectorstorm
7306214108b23fa97d4a1a598197bbaa52c17d3a
[ "Zlib" ]
2
2019-05-24T14:40:07.000Z
2020-04-15T01:10:23.000Z
VS/Graphics/VS_ShaderValues.cpp
vectorstorm/vectorstorm
7306214108b23fa97d4a1a598197bbaa52c17d3a
[ "Zlib" ]
2
2020-03-08T07:14:49.000Z
2020-03-09T10:39:52.000Z
/* * VS_ShaderValues.cpp * VectorStorm * * Created by Trevor Powell on 28/08/2015 * Copyright 2015 Trevor Powell. All rights reserved. * */ #include "VS_ShaderValues.h" #include "VS_Shader.h" #include "VS_ShaderUniformRegistry.h" #include "VS_OpenGL.h" #include "VS_Matrix.h" vsShaderValues::vsShaderValues(): m_parent(NULL), m_value(16) { } vsShaderValues::vsShaderValues( const vsShaderValues& other ): m_parent(NULL), m_value(16) { int valueCount = other.m_value.GetHashEntryCount(); for ( int i = 0; i < valueCount; i++ ) { const vsIntHashEntry<Value> *v = other.m_value.GetHashEntry(i); m_value[v->m_key] = v->m_item; } } void vsShaderValues::SetUniformF( const vsString& name, float value ) { { uint32_t id = vsShaderUniformRegistry::UID(name); m_value[id].f32 = value; m_value[id].type = Value::Type_Float; m_value[id].bound = false; } } void vsShaderValues::SetUniformB( const vsString& name, bool value ) { { uint32_t id = vsShaderUniformRegistry::UID(name); m_value[id].b = value; m_value[id].type = Value::Type_Bool; m_value[id].bound = false; } } void vsShaderValues::SetUniformI( const vsString& name, int value ) { { uint32_t id = vsShaderUniformRegistry::UID(name); m_value[id].i = value; m_value[id].type = Value::Type_Int; m_value[id].bound = false; } } void vsShaderValues::SetUniformColor( const vsString& name, const vsColor& value ) { { uint32_t id = vsShaderUniformRegistry::UID(name); m_value[id].vec4[0] = value.r; m_value[id].vec4[1] = value.g; m_value[id].vec4[2] = value.b; m_value[id].vec4[3] = value.a; m_value[id].type = Value::Type_Vec4; m_value[id].bound = false; } } void vsShaderValues::SetUniformVec2( const vsString& name, const vsVector2D& value ) { { uint32_t id = vsShaderUniformRegistry::UID(name); m_value[id].vec4[0] = value.x; m_value[id].vec4[1] = value.y; m_value[id].vec4[2] = 0.0; m_value[id].vec4[3] = 0.0; m_value[id].type = Value::Type_Vec4; m_value[id].bound = false; } } void vsShaderValues::SetUniformVec3( const vsString& name, const vsVector3D& value ) { { uint32_t id = vsShaderUniformRegistry::UID(name); m_value[id].vec4[0] = value.x; m_value[id].vec4[1] = value.y; m_value[id].vec4[2] = value.z; m_value[id].vec4[3] = 0.0; m_value[id].type = Value::Type_Vec4; m_value[id].bound = false; } } void vsShaderValues::SetUniformVec4( const vsString& name, const vsVector4D& value ) { { uint32_t id = vsShaderUniformRegistry::UID(name); m_value[id].vec4[0] = value.x; m_value[id].vec4[1] = value.y; m_value[id].vec4[2] = value.z; m_value[id].vec4[3] = value.w; m_value[id].type = Value::Type_Vec4; m_value[id].bound = false; } } bool vsShaderValues::BindUniformF( const vsString& name, const float* value ) { { uint32_t id = vsShaderUniformRegistry::UID(name); m_value[id].bind = value; m_value[id].type = Value::Type_Bind; m_value[id].bound = true; return true; } return false; } bool vsShaderValues::BindUniformB( const vsString& name, const bool* value ) { { uint32_t id = vsShaderUniformRegistry::UID(name); m_value[id].bind = value; m_value[id].type = Value::Type_Bind; m_value[id].bound = true; return true; } return false; } bool vsShaderValues::BindUniformI( const vsString& name, const int* value ) { { uint32_t id = vsShaderUniformRegistry::UID(name); m_value[id].bind = value; m_value[id].type = Value::Type_Bind; m_value[id].bound = true; return true; } return false; } bool vsShaderValues::BindUniformColor( const vsString& name, const vsColor* value ) { { uint32_t id = vsShaderUniformRegistry::UID(name); m_value[id].bind = value; m_value[id].type = Value::Type_Bind; m_value[id].bound = true; return true; } return false; } bool vsShaderValues::BindUniformVec2( const vsString& name, const vsVector2D* value ) { { uint32_t id = vsShaderUniformRegistry::UID(name); m_value[id].bind = value; m_value[id].type = Value::Type_Bind; m_value[id].bound = true; return true; } return false; } bool vsShaderValues::BindUniformVec3( const vsString& name, const vsVector3D* value ) { { uint32_t id = vsShaderUniformRegistry::UID(name); m_value[id].bind = value; m_value[id].type = Value::Type_Bind; m_value[id].bound = true; return true; } return false; } bool vsShaderValues::BindUniformVec4( const vsString& name, const vsVector4D* value ) { { uint32_t id = vsShaderUniformRegistry::UID(name); m_value[id].bind = value; m_value[id].type = Value::Type_Bind; m_value[id].bound = true; return true; } return false; } bool vsShaderValues::BindUniformMat4( const vsString& name, const vsMatrix4x4* value ) { { uint32_t id = vsShaderUniformRegistry::UID(name); m_value[id].bind = value; m_value[id].type = Value::Type_Bind; m_value[id].bound = true; return true; } return false; } bool vsShaderValues::Has( const vsString& name ) const { uint32_t id = vsShaderUniformRegistry::UID(name); return (m_value.FindItem(id) != NULL) || ( m_parent && m_parent->Has(name) ); } // float // vsShaderValues::UniformF( const vsString& id ) // { // Value* v = m_value.FindItem(id); // if ( !v ) // return 0.f; // if ( v->bound ) // return *(float*)v->bind; // else // return v->f32; // } // // bool // vsShaderValues::UniformB( const vsString& id ) // { // Value* v = m_value.FindItem(id); // if ( !v ) // return false; // if ( v->bound ) // return *(bool*)v->bind; // else // return v->b; // } // // vsVector4D // vsShaderValues::UniformVec4( const vsString& id ) // { // Value* v = m_value.FindItem(id); // if ( !v ) // return vsVector4D(); // if ( v->bound ) // return *(vsVector4D*)v->bind; // else // return *(vsVector4D*)v->vec4; // } // // vsVector3D // vsShaderValues::UniformVec3( const vsString& id ) // { // return vsVector3D( UniformVec4(id) ); // } // // vsVector2D // vsShaderValues::UniformVec2( const vsString& id ) // { // return vsVector2D( UniformVec4(id) ); // } // bool vsShaderValues::UniformF( uint32_t uid, float& out ) const { const Value* v = m_value.FindItem(uid); if ( !v ) { if ( m_parent ) return m_parent->UniformF(uid,out); return false; } if ( v->bound ) out = *(float*)v->bind; else out = v->f32; return true; } bool vsShaderValues::UniformB( uint32_t uid, bool& out ) const { const Value* v = m_value.FindItem(uid); if ( !v ) { if ( m_parent ) return m_parent->UniformB(uid,out); return false; } if ( v->bound ) out = *(bool*)v->bind; else out = v->b; return true; } bool vsShaderValues::UniformI( uint32_t uid, int& out ) const { const Value* v = m_value.FindItem(uid); if ( !v ) { if ( m_parent ) return m_parent->UniformI(uid,out); return false; } if ( v->bound ) out = *(int*)v->bind; else out = v->i; return true; } bool vsShaderValues::UniformVec2( uint32_t uid, vsVector2D& out ) const { const Value* v = m_value.FindItem(uid); if ( !v ) { if ( m_parent ) return m_parent->UniformVec2(uid,out); return false; } if ( v->bound ) out = *(vsVector2D*)v->bind; else out = *(vsVector2D*)v->vec4; return true; } bool vsShaderValues::UniformVec3( uint32_t uid, vsVector3D& out ) const { const Value* v = m_value.FindItem(uid); if ( !v ) { if ( m_parent ) return m_parent->UniformVec3(uid,out); return false; } if ( v->bound ) out = *(vsVector3D*)v->bind; else out = *(vsVector3D*)v->vec4; return true; } bool vsShaderValues::UniformVec4( uint32_t uid, vsVector4D& out ) const { const Value* v = m_value.FindItem(uid); if ( !v ) { if ( m_parent ) return m_parent->UniformVec4(uid,out); return false; } if ( v->bound ) out = *(vsVector4D*)v->bind; else out = *(vsVector4D*)v->vec4; return true; } bool vsShaderValues::UniformMat4( uint32_t uid, vsMatrix4x4& out ) const { const Value* v = m_value.FindItem(uid); if ( !v ) { if ( m_parent ) return m_parent->UniformMat4(uid,out); return false; } if ( v->bound ) out = *(vsMatrix4x4*)v->bind; // else // out = *(vsMatrix4x4*)v->mat4; return true; } bool vsShaderValues::operator==( const vsShaderValues& other ) const { if ( m_parent != other.m_parent ) return false; return m_value == other.m_value; // now check the values. // int valueCount = m_value.GetHashEntryCount(); // if ( other.m_value.GetHashEntryCount() != valueCount ) // return false; // // for ( int i = 0; i < valueCount; i++ ) // { // const vsHashEntry<Value> *v = m_value.GetHashEntry(i); // const vsHashEntry<Value> *ov = other.m_value.GetHashEntry(i); // // keys aren't of matching types? Fail. // if ( v->m_item.type != ov->m_item.type ) // return false; // // keys aren't of matching name? Fail. // if ( v->m_key != ov->m_key ) // return false; // // switch ( v->m_item.type ) // { // case Value::Type_Float: // if ( v->m_item.f32 != ov->m_item.f32 ) // return false; // break; // case Value::Type_Bool: // if ( v->m_item.b != ov->m_item.b ) // return false; // break; // case Value::Type_Int: // if ( v->m_item.i != ov->m_item.i ) // return false; // break; // case Value::Type_Vec4: // if ( v->m_item.vec4 != ov->m_item.vec4 ) // return false; // break; // case Value::Type_Bind: // // uhhhh.. should I be trying to check the value? // if ( v->m_item.bind != ov->m_item.bind ) // return false; // break; // case Value::Type_MAX: // break; // } // } // // return true; } bool vsShaderValues::Value::operator==( const struct Value& other ) const { if ( type != other.type ) return false; switch ( type ) { case Value::Type_Float: if ( f32 != other.f32 ) return false; break; case Value::Type_Bool: if ( b != other.b ) return false; break; case Value::Type_Int: if ( i != other.i ) return false; break; case Value::Type_Vec4: if ( vec4 != other.vec4 ) return false; break; case Value::Type_Bind: // uhhhh.. should I be trying to check the value? if ( bind != other.bind ) return false; break; case Value::Type_MAX: break; } return true; }
20.535354
81
0.64545
vectorstorm
39d31304a259f436a2d731216f4bd68cc3e988e2
2,365
cpp
C++
Gemastik/PenulisSoal/PenulisSoal-dewnan98.cpp
ajisubarkah/Programming-Event
6cb645ec24cb5c826b41c11334270fd3d0ece474
[ "MIT" ]
1
2018-09-18T06:28:45.000Z
2018-09-18T06:28:45.000Z
Gemastik/PenulisSoal/PenulisSoal-dewnan98.cpp
ajisubarkah/Programming-Event
6cb645ec24cb5c826b41c11334270fd3d0ece474
[ "MIT" ]
null
null
null
Gemastik/PenulisSoal/PenulisSoal-dewnan98.cpp
ajisubarkah/Programming-Event
6cb645ec24cb5c826b41c11334270fd3d0ece474
[ "MIT" ]
1
2018-09-05T06:34:04.000Z
2018-09-05T06:34:04.000Z
#include <iostream> #include <vector> using namespace std; void printVector(vector <int> vec) { cout<<"VECTOR : "; for (int a = 0 ; a<vec.size();a++) { cout<<vec[a]<<" | "; } cout<<endl; } bool vectorContain (vector<int>vec , int angka) { for (int a = 0 ; a<vec.size();a++) { if(vec[a]==angka) return true; } return false; } int penyisihanSoal(int jumlahPenulis ,vector <int>soal , vector<vector<int>> perusahaan) { vector <int> himpunan; int keragaman = 0; for (int a = 0 ; a<jumlahPenulis;a++) { keragaman++; cout<<soal[a]<<" SOAL dari penulis "<<a+1<<" dimiliki oleh {penulis "<<a+1; for(int b = 0 ; b<soal.size()-1;b++) { for(int c = 0 ; c<perusahaan[a].size();c++) { if(himpunan.empty() ||!vectorContain(himpunan ,perusahaan[a][c]) ) { himpunan.push_back(perusahaan[a][c]); keragaman++; cout<<",Perushaan "<<perusahaan[a][c]; } } } cout<<"}"<<endl; } //printVector(himpunan); return keragaman; } main() { int t; cin >>t; cout<<endl; int counter=0; do { vector <int> soals; vector<vector <int>> perusahaan; int penulis; cout<<"Masukan jumlah penulis : "; cin>>penulis; for(int a = 0 ;a<penulis;a++) { cout<<"Masukan Jumlah Soal dari penulus ["<<a+1<<"] : "; int soal; cin>>soal; soals.push_back(soal); cout<< " "; } cout<<endl; for(int a = 0 ;a<penulis;a++) { int jumlahPerusahaan; cout<<"Jumlah Perushaan penulis ke [ "<<a+1<<"] : " ; cin>>jumlahPerusahaan; perusahaan.push_back(std::vector<int>()); for (int b= 0 ; b<jumlahPerusahaan;b++) { int p; cout<<"Masukan perushaan : "; cin>>p; perusahaan[a].push_back(p); } } int hasil = penyisihanSoal(penulis , soals,perusahaan); cout<<endl; cout<<"OUTPUT : "<<hasil; cout<<endl; counter++; }while(counter<t); }
17.518519
88
0.454545
ajisubarkah
39db23b2a097a8136d98305dcc25df7d06506428
5,693
cpp
C++
src/ray.cpp
Chongyao/Monte-Carlo-Ray-Tracing
d175300f089a4ed61c9548e5a2587e63cd843403
[ "MIT" ]
null
null
null
src/ray.cpp
Chongyao/Monte-Carlo-Ray-Tracing
d175300f089a4ed61c9548e5a2587e63cd843403
[ "MIT" ]
null
null
null
src/ray.cpp
Chongyao/Monte-Carlo-Ray-Tracing
d175300f089a4ed61c9548e5a2587e63cd843403
[ "MIT" ]
null
null
null
#include "ray.h" #include <limits> #include <iostream> using namespace std; using namespace Eigen; const double MAX_DOUBLE = std::numeric_limits<double>::max(); Ray::Ray(const vec& origin, const vec& dire): origin_(origin), dire_(dire),final_offset_(MAX_DOUBLE){} enum axis{x, y, z}; bool project_dim(const Eigen::Vector3d& normal, axis& dim1, axis& dim2){ dim1 = x; dim2 = y; size_t count = 0; for(size_t i = 0; i < 3; ++i){ if(fabs(normal(i)) < 1e-6){ if(count == 0){ dim1 = static_cast<axis>(i); dim2 = static_cast<axis>((i + 1) % 3); ++count; } else if(count == 1){ dim2 = static_cast<axis>(i); ++count; } } } if(count > 2) return false; else return true; } bool get_cross_point(const vec& ori, const vec& dir, const vec& norm, const double& d, double& offset ){ const double deno = norm(0) * dir(0) + norm(1) * dir(1) + norm(2) * dir(2); if(fabs(deno) < 1e-5) return false; else{ offset = ( -d - norm(0) * ori(0) - norm(1) * ori(1) - norm(2) * ori(2) ) * (1 / deno); if (offset < 0) return false; else { // cross = ori + offset * dir; return true; } } } bool Ray::intersect_aabb(const aabb& bd_box_)const { bool is_inter = false; auto check_inside = [](const vec& cross_point, const aabb& bd, const size_t& dim)->bool{ if(cross_point( (dim + 1) % 3 ) >= bd.low_bd_((dim + 1) % 3) && cross_point( (dim + 1) % 3 ) <= bd.up_bd_((dim + 1) % 3) && cross_point( (dim + 2) % 3 ) >= bd.low_bd_((dim + 2) % 3) && cross_point( (dim + 2) % 3 ) <= bd.up_bd_((dim + 2) % 3)) return true; else return false; }; vec cross_point, normal; for(size_t dim = 0; dim < 3; ++dim){ if(fabs(dire_(dim)) < 1e-5) continue; normal = vec::Zero();{ normal(dim) = 1; } double para_d = - bd_box_.low_bd_(dim); double offset = (- para_d - origin_(dim)) * (1 / dire_(dim)); if(offset >0){ cross_point = origin_ + offset * dire_; if(check_inside(cross_point, bd_box_, dim)){ is_inter = true; break; } } para_d = - bd_box_.up_bd_(dim); offset = (- para_d - origin_(dim)) * (1 / dire_(dim)); if(offset >0){ cross_point = origin_ + offset * dire_; if(check_inside(cross_point, bd_box_, dim)){ is_inter = true; break; } } } return is_inter; } bool Ray::intersct_tri_aabb(const tri_aabb& tri, Ray&next)const{ axis dim1, dim2; double offset; if(!project_dim(tri.normal_, dim1, dim2) || !get_cross_point(origin_, dire_, tri.normal_, tri.d_, offset) || offset > final_offset_ || offset < 1e-4) return false; vec cross_point = origin_ + dire_ * offset; const double s = ( (cross_point(dim1) - tri.p_(dim1, 2)) * (tri.p_(dim2, 0) - tri.p_(dim2, 2)) - (cross_point(dim2) - tri.p_(dim2, 2)) * (tri.p_(dim1, 0) - tri.p_(dim1, 2)) ) / ( (tri.p_(dim1, 1) - tri.p_(dim1, 2)) * (tri.p_(dim2, 0) - tri.p_(dim2, 2)) -(tri.p_(dim2, 1) - tri.p_(dim2, 2)) * (tri.p_(dim1, 0) - tri.p_(dim1, 2)) ); const double t = ( (cross_point(dim1) - tri.p_(dim1, 2)) * (tri.p_(dim2, 1) - tri.p_(dim2, 2)) - (cross_point(dim2) - tri.p_(dim2, 2)) * (tri.p_(dim1, 1) - tri.p_(dim1, 2)) ) / ((tri.p_(dim1, 0) - tri.p_(dim1, 2)) * (tri.p_(dim2, 1) - tri.p_(dim2, 2)) - (tri.p_(dim2, 0) - tri.p_(dim2, 2)) * (tri.p_(dim1, 1) - tri.p_(dim1, 2))); assert(s == s); if ( s > 0 && s < 1 && t > 0 && t < 1 && (1 - s - t) > 0 && (1 - s - t) < 1 ){ final_offset_ = offset; next.origin_ = cross_point; next.dire_ = tri.n_.col(0) * t + tri.n_.col(1) * s + tri.n_.col(2) * (1 - s -t); next.dire_ /= next.dire_.norm(); return true; } else return false; } bool Ray::intersect(const unique_ptr<KD_tree_tris>& kd, size_t& face_id, Ray& next)const{ if(intersect_aabb(kd->bd_box_)){ if(kd->left_tree_ == nullptr || kd->right_tree_ == nullptr){//intersct triangles assert(kd->left_tree_ == nullptr); assert(kd->right_tree_ == nullptr); bool is_inter = false; for(size_t f_id = 0; f_id < kd->child_.size(); ++f_id){ if(intersct_tri_aabb(*(kd->child_[f_id]), next)){ is_inter = true; face_id = kd->child_[f_id]->id_; // break; } } return is_inter; } else return intersect(kd->left_tree_, face_id, next) | intersect(kd->right_tree_, face_id, next); } else{ return false; } } bool Ray::intersect_forest(const vector<unique_ptr<KD_tree_tris>>& KD_forest, size_t& face_id, Ray& next)const{ size_t num_model = KD_forest.size(); bool is_inter = false; for(size_t m_id = 0; m_id < num_model; ++m_id){ if(intersect(KD_forest[m_id], face_id, next)){ is_inter = true; } } return is_inter; } bool Ray::intersect_forest_loop(const std::vector<std::unique_ptr<KD_tree_tris>>& KD_forest, size_t& face_id, Ray& next)const{ bool is_inter = false; for(auto& kd : KD_forest){ size_t num_tris = kd->child_.size(); cout << "num tris is "<< num_tris << endl; for(int f_id = num_tris - 1; f_id >=0 ; --f_id){ if( intersct_tri_aabb(*(kd->child_[f_id]), next)){ is_inter = true; face_id = kd->child_[f_id]->id_; cout << "off set : " << final_offset_ << " f id " << f_id << endl; cout << kd->child_[f_id]->p_ << endl; cout << kd->child_[f_id]->n_ << endl; // break; } } // cout << is_inter << endl; } return is_inter; }
28.465
113
0.553311
Chongyao
39db87dbebd70cdc4705d1b588dcadb3462eb85a
11,723
cpp
C++
src/LLVMBackend/CtModule.cpp
CristianDragu/sparrow
49844c2329ac001c3a0779baae7a2f02743c4494
[ "MIT" ]
80
2015-05-05T12:21:50.000Z
2022-03-30T18:38:48.000Z
src/LLVMBackend/CtModule.cpp
CristianDragu/sparrow
49844c2329ac001c3a0779baae7a2f02743c4494
[ "MIT" ]
51
2016-09-09T13:44:50.000Z
2021-11-28T07:03:02.000Z
src/LLVMBackend/CtModule.cpp
CristianDragu/sparrow
49844c2329ac001c3a0779baae7a2f02743c4494
[ "MIT" ]
8
2015-07-28T11:34:15.000Z
2020-02-01T21:54:06.000Z
#include <StdInc.h> #include "CtModule.h" #include "Generator.h" #include <Tr/TrTopLevel.h> #include <Tr/TrFunction.h> #include <Tr/TrType.h> #include <Tr/GlobalContext.h> #include <Tr/PrepareTranslate.h> #include "Feather/Utils/FeatherUtils.hpp" #include "Feather/Utils/cppif/FeatherTypes.hpp" #include "Nest/Api/Node.h" #include "Nest/Api/Type.h" #include "Nest/Api/Compiler.h" #include "Nest/Utils/CompilerSettings.hpp" #include "Nest/Utils/Diagnostic.hpp" #include "Nest/Utils/Profiling.h" #include "Nest/Utils/CompilerStats.hpp" #include "Nest/Utils/cppif/StringRef.hpp" #include <llvm/IR/Verifier.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/MCJIT.h> // We need this include to instantiate the JIT engine #include <memory> using namespace LLVMB; using namespace LLVMB::Tr; using namespace Feather; CtModule::CtModule(const string& name) : Module(name) , llvmExecutionEngine_(nullptr) , llvmModule_(new llvm::Module(name, *llvmContext_)) , dataLayout_("") { auto& s = *Nest_compilerSettings(); llvmModule_->setDataLayout(s.dataLayout_); llvmModule_->setTargetTriple(s.targetTriple_); // Create the execution engine object string errStr; llvmExecutionEngine_ = llvm::EngineBuilder(move(llvmModule_)) .setErrorStr(&errStr) .setEngineKind(llvm::EngineKind::JIT) .setOptLevel(llvm::CodeGenOpt::None) .create(); if (!llvmExecutionEngine_) REP_INTERNAL(NOLOC, "Failed to construct LLVM ExecutionEngine: %1%") % errStr; ASSERT(llvmExecutionEngine_); assert(llvmExecutionEngine_); // Get the actual data layout to be used dataLayout_ = llvmExecutionEngine_->getDataLayout(); // The execution engine consumed the current LLVM module // Make sure to create another one. recreateModule(); } CtModule::~CtModule() { delete llvmExecutionEngine_; } void CtModule::ctProcess(Node* node) { // This should be called now only for BackendCode; the rest of CT declarations are processed // when referenced // Make sure the node is semantically checked if (!node->nodeSemanticallyChecked) REP_INTERNAL( node->location, "Node should be semantically checked when passed to the backend"); switch (node->nodeKind - Feather_getFirstFeatherNodeKind()) { case nkRelFeatherExpCtValue: return; case nkRelFeatherDeclVar: ctProcessVariable(node); break; case nkRelFeatherDeclFunction: ctProcessFunction(node); break; case nkRelFeatherDeclClass: ctProcessClass(node); break; case nkRelFeatherBackendCode: ctProcessBackendCode(node); break; default: REP_INTERNAL(node->location, "Don't know how to CT process node (%1%)") % node; } } Node* CtModule::ctEvaluate(Node* node) { // Make sure the node is semantically checked if (!node->nodeSemanticallyChecked) { REP_INTERNAL( node->location, "Node should be semantically checked when passed to the backend"); return nullptr; } // Make sure the type of the node can be used at compile time if (!Feather_isCt(node)) REP_INTERNAL( node->location, "Cannot CT evaluate this node: it has no meaning at compile-time"); if (!node->type->hasStorage && node->type->typeKind != typeKindVoid) REP_INTERNAL(node->location, "Cannot CT evaluate node with non-storage type (type: %1%)") % node->type; node = Nest_explanation(node); if (node->nodeKind == nkFeatherExpCtValue) { return node; // Nothing to do } else { return ctEvaluateExpression(node); } } void CtModule::ctApiRegisterFun(const char* name, void* funPtr) { ASSERT(llvmModule_); llvm::FunctionType* llvmFunType = llvm::FunctionType::get(llvm::Type::getVoidTy(*llvmContext_), {}, false); llvm::Function* fun = llvm::Function::Create( llvmFunType, llvm::Function::ExternalLinkage, name, llvmModule_.get()); llvmExecutionEngine_->addGlobalMapping(fun, funPtr); } void CtModule::addGlobalCtor(llvm::Function* /*fun*/) {} void CtModule::addGlobalDtor(llvm::Function* /*fun*/) {} CtModule::NodeFun CtModule::ctToRtTranslator() const { return NodeFun(); } void CtModule::recreateModule() { ASSERT(!llvmModule_); llvmModule_ = llvm::make_unique<llvm::Module>("CT module", *llvmContext_); ASSERT(llvmModule_); // Ensure we have exactly the same data layout as our execution engine llvmModule_->setDataLayout(dataLayout_); } void CtModule::syncModule() { PROFILING_ZONE(); if (!llvmModule_->empty() || !llvmModule_->global_empty()) { // Uncomment this for debugging // llvmModule_->dump(); // Generate a dump for the CT module - just for debugging const auto& s = *Nest_compilerSettings(); if (s.dumpCtAssembly_) generateCtAssembly(*llvmModule_); ASSERT(llvmModule_); llvmExecutionEngine_->addModule(move(llvmModule_)); // Recreate the module, to use it for the anonymous expression evaluation recreateModule(); } } void CtModule::ctProcessVariable(Node* node) { Tr::GlobalContext ctx(*llvmModule_, *this); Tr::translateGlobalVar(node, ctx); } void CtModule::ctProcessFunction(Node* node) { Tr::GlobalContext ctx(*llvmModule_, *this); llvm::Function* f = Tr::translateFunction(node, ctx); ((void)f); } void CtModule::ctProcessClass(Node* node) { Tr::GlobalContext ctx(*llvmModule_, *this); Tr::translateClass(node, ctx); } void CtModule::ctProcessBackendCode(Node* node) { Tr::GlobalContext ctx(*llvmModule_, *this); Tr::translateBackendCode(node, ctx); } Node* CtModule::ctEvaluateExpression(Node* node) { PROFILING_ZONE_TEXT(Nest_toStringEx(node)); ASSERT(llvmModule_); // Gather statistics if requested Nest::CompilerStats& stats = Nest::CompilerStats::instance(); if (stats.enabled) ++stats.numCtEvals; Nest::ScopedTimeCapture timeCapture(stats.enabled, stats.timeCtEvals); static int counter = 0; ostringstream oss; oss << "__anonExprEval." << counter++; const string& funName = oss.str(); // Ensure the node is prepared for translation. // This means we won't be doing any more semantic checks while translating, avoiding reentrant // calls. Tr::GlobalContext ctxMain(*llvmModule_, *this); Tr::prepareTranslate(node, ctxMain); // Check for re-entrant calls // static volatile int numActiveCalls = 0; // struct IncDec { // volatile int& val_; // IncDec(volatile int& val) // : val_(++val) {} // ~IncDec() { --val_; } // }; // IncDec scopeIncDec(numActiveCalls); // if (numActiveCalls > 1) { // static int numReentrantCalls = 0; // ++numReentrantCalls; // REP_INTERNAL(node->location, "Reentrant ctEval detected: %1%") % Nest_toStringEx(node); // } // If we've added some definitions so far, add them to the execution engine syncModule(); // We will add our anonymous expression into this module ASSERT(llvmModule_); const char* modName = "CT anonymous expression eval module"; // Debug info // ostringstream oss2; // oss2 << "CT eval - " << node->location; // string modName = oss2.str(); // Create a new LLVM module for this function, an a corresponding global context unique_ptr<llvm::Module> anonExprEvalModule(new llvm::Module(modName, *llvmContext_)); llvm::Module* tmpMod = anonExprEvalModule.get(); anonExprEvalModule->setDataLayout(dataLayout_); Tr::GlobalContext ctx(*anonExprEvalModule, *llvmModule_, *this); // Create a function of type 'void f(void*)', which will execute our expression node and put the // result at the address llvm::Function* f = Tr::makeFunThatCalls(node, ctx, funName.c_str(), node->type->hasStorage); (void)f; // Translate the type here, before adding the module to the execution engine llvm::Type* resLlvmType = nullptr; if (node->type->hasStorage) resLlvmType = Tr::getLLVMType(node->type, ctx); // Sync again, just for safety syncModule(); // Uncomment this for CT debugging // int old = Nest_isReportingEnabled(); // Nest_enableReporting(1); // REP_INFO(node->location, "CT eval %1%: %2%") % counter % Nest_toStringEx(node); // Nest_enableReporting(old); // cerr << "----------------------------" << endl; // f->print(llvm::errs()); // tmpMod->print(llvm::errs(), nullptr); // cerr << "----------------------------" << endl; // Generate a dump for the CT module - just for debugging const auto& s = *Nest_compilerSettings(); if (s.dumpCtAssembly_) generateCtAssembly(*anonExprEvalModule); // Add the module containing this into the execution engine llvmExecutionEngine_->addModule(move(anonExprEvalModule)); // Validate the generated code, checking for consistency. // string errMsg; // llvm::raw_string_ostream errStream(errMsg); // if ( llvm::verifyFunction(*f, &errStream) ) // { // REP_ERROR(node->location, "Error constructing CT evaluation function: %1%") % errMsg; // if ( Nest_isReportingEnabled() ) // f->print(llvm::errs()); // return nullptr; // } Node* res = nullptr; if (node->type->hasStorage) { // Create a memory space where to put the result size_t size = dataLayout_.getTypeAllocSize(resLlvmType); Nest::StringRefM dataBuffer{int(size)}; // The magic is here: // - finalize everything in the engine and get the function address // - transform this into a function pointer that receives the output as a parameter // - call the function, to fill up the data buffer using FunType = void (*)(const char*); FunType fptr; { PROFILING_ZONE_NAMED("CT getFunctionAddress"); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) fptr = (FunType)llvmExecutionEngine_->getFunctionAddress(funName); } ASSERT(fptr); { PROFILING_ZONE_NAMED("CT exec"); fptr(dataBuffer.begin); } // Create a CtValue containing the data resulted from expression evaluation Type t = node->type; if (t.mode() != modeCt) t = t.changeMode(modeCt, node->location); res = Feather_mkCtValue(node->location, t, dataBuffer); } else { // The magic is here: // - finalize everything in the engine and get the function address // - transform this into a function pointer with no parameters // - call the function using FunType = void (*)(); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) FunType fptr; { PROFILING_ZONE_NAMED("CT getFunctionAddress"); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) fptr = (FunType)llvmExecutionEngine_->getFunctionAddress(funName); } ASSERT(fptr); { PROFILING_ZONE_NAMED("CT exec"); fptr(); } // Create a Nop operation for return res = Feather_mkNop(node->location); } // Remove our anonymous function from the execution engine llvmExecutionEngine_->updateGlobalMapping(funName, 0); // Try to remove the module that we just added llvmExecutionEngine_->removeModule(tmpMod); return res; }
34.581121
100
0.65026
CristianDragu
39dbbae00ab1559d100daffd161095531451746f
1,061
hpp
C++
include/mizuiro/color/detail/dynamic/channel_to_pos.hpp
cpreh/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
1
2015-08-22T04:19:39.000Z
2015-08-22T04:19:39.000Z
include/mizuiro/color/detail/dynamic/channel_to_pos.hpp
freundlich/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
null
null
null
include/mizuiro/color/detail/dynamic/channel_to_pos.hpp
freundlich/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2016. // 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 MIZUIRO_COLOR_DETAIL_DYNAMIC_CHANNEL_TO_POS_HPP_INCLUDED #define MIZUIRO_COLOR_DETAIL_DYNAMIC_CHANNEL_TO_POS_HPP_INCLUDED #include <mizuiro/size_type.hpp> #include <mizuiro/color/channel/tag.hpp> #include <mizuiro/color/detail/dynamic/channel_index.hpp> #include <mizuiro/color/detail/dynamic/static_to_dynamic_channel.hpp> namespace mizuiro::color::detail::dynamic { template <typename Format> inline mizuiro::size_type channel_to_pos(mizuiro::color::detail::dynamic::channel_index const _channel) { return _channel.get(); } template <typename Format, typename Channel> inline mizuiro::size_type channel_to_pos(mizuiro::color::channel::tag<Channel> const &) { return mizuiro::color::detail::dynamic::channel_to_pos<Format>( mizuiro::color::detail::dynamic::static_to_dynamic_channel<Format>(Channel())); } } #endif
31.205882
87
0.777568
cpreh
39e18ce4e00f29614d9b35f8612c0c1eea12bbf8
54,767
cpp
C++
qflexprop.cpp
totalspectrum/qflexprop
ab3ca23b4f61b2c100acf7e917bacab18ee9614e
[ "BSD-3-Clause" ]
2
2022-02-09T02:25:29.000Z
2022-03-30T01:06:45.000Z
qflexprop.cpp
totalspectrum/qflexprop
ab3ca23b4f61b2c100acf7e917bacab18ee9614e
[ "BSD-3-Clause" ]
2
2021-03-09T17:39:15.000Z
2021-03-09T17:39:39.000Z
qflexprop.cpp
totalspectrum/qflexprop
ab3ca23b4f61b2c100acf7e917bacab18ee9614e
[ "BSD-3-Clause" ]
2
2021-03-07T18:40:11.000Z
2021-04-14T23:44:32.000Z
/***************************************************************************** * * Qt5 Propeller 2 main window for editor, compiler, terminal * * Copyright Β© 2021 JΓΌrgen BuchmΓΌller <pullmoll@t-online.de> * * See the file LICENSE for the details of the BSD-3-Clause terms. * *****************************************************************************/ #include <QFile> #include <QFileDialog> #include <QTemporaryFile> #include <QMessageBox> #include <QTextStream> #include <QSerialPort> #include <QSerialPortInfo> #include <QSettings> #include <QCryptographicHash> #include <QScrollArea> #include <QSplitter> #include <QFrame> #include <QSpacerItem> #include <QLineEdit> #include <QProgressBar> #include <QTextBrowser> #include <QHBoxLayout> #include <QVBoxLayout> #include <cinttypes> #include <fcntl.h> #include "util.h" #include "idstrings.h" #include "propedit.h" #include "qflexprop.h" #include "propload.h" #include "aboutdlg.h" #include "ui_qflexprop.h" #include "serterm.h" #include "flexspindlg.h" #include "serialportdlg.h" #include "settingsdlg.h" #include "textbrowserdlg.h" QFlexProp::QFlexProp(QWidget *parent) : QMainWindow(parent) , ui(new Ui::QFlexProp) , m_dev(nullptr) , m_fixedfont() , m_leds({ id_pwr, id_ri, id_dcd, id_dtr, id_dsr, id_rts, id_cts, id_txd, id_rxd, id_brk, id_fe, id_pe, }) , m_enabled_elements({ {id_baud_rate, true}, {id_parity_data_stop, true}, {id_flow_control, true}, {id_pwr, true }, {id_dtr, true }, {id_dsr, true }, {id_rts, true }, {id_cts, true }, {id_rxd, true }, {id_txd, true }, {id_ri, false }, {id_dcd, false }, {id_brk, false }, {id_fe, false }, {id_pe, false }, }) , m_labels() , m_stty_operation() , m_port_name() , m_baud_rate(Serial_Baud230400) , m_data_bits(QSerialPort::Data8) , m_parity(QSerialPort::NoParity) , m_stop_bits(QSerialPort::OneStop) , m_flow_control(QSerialPort::NoFlowControl) , m_local_echo(false) , m_flexspin_executable() , m_flexspin_include_paths() , m_flexspin_quiet(true) , m_flexspin_optimize(1) , m_flexspin_listing(false) , m_flexspin_warnings(true) , m_flexspin_errors(false) , m_flexspin_hub_address(0) , m_flexspin_skip_coginit(false) , m_compile_verbose_upload(false) , m_compile_switch_to_term(true) { ui->setupUi(this); setup_mainwindow(); setup_statusbar(); load_settings(); setup_port(); setup_signals(); tab_changed(0); QTimer::singleShot(100, this, &QFlexProp::configure_port); } QFlexProp::~QFlexProp() { save_settings(); delete ui; } /** * @brief Return a pointer to the currently active PropEdit in the tab widget * @return pointer to propEdit or nullptr if there is none in the selected tab */ PropEdit* QFlexProp::current_propedit(int index) const { const int tabidx = index < 0 ? ui->tabWidget->currentIndex() : index; QWidget *wdg = ui->tabWidget->widget(tabidx); if (!wdg) { qCritical("%s: current tab %d has no widget?", __func__, tabidx); return nullptr; } // Check if this tab has a PropEdit PropEdit *pe = wdg->findChild<PropEdit *>(id_propedit); if (!pe) { qDebug("%s: current tab %d has no PropEdit '%s'?", __func__, tabidx, qPrintable(id_propedit)); return nullptr; } return pe; } /** * @brief Return a pointer to the currently active QTextBrowser in the tab widget * @return pointer to QTextBrowser or nullptr if there is none in the selected tab */ QTextBrowser* QFlexProp::current_textbrowser(int index) const { const int tabidx = index < 0 ? ui->tabWidget->currentIndex() : index; QWidget *wdg = ui->tabWidget->widget(tabidx); if (!wdg) { qDebug("%s: current tab %d has no widget?", __func__, tabidx); return nullptr; } QTextBrowser *tb = wdg->findChild<QTextBrowser *>(id_textbrowser); if (!tb) { qDebug("%s: current tab %d has no text browser '%s'?", __func__, tabidx, qPrintable(id_textbrowser)); return nullptr; } return tb; } /** * @brief Preset a QFileDialog for loading an existing source file * @param title window title * @return QString with the full path, or empty if cancelled */ QString QFlexProp::load_file(const QString& title) { QFileDialog dlg(this); QSettings s; QString srcdflt = QString("%1/p2tools").arg(QDir::homePath()); QString srcdir = s.value(id_sourcedir, srcdflt).toString(); QString filename = s.value(id_filename).toString(); QStringList history = s.value(id_history).toStringList(); QStringList filetypes = { {"All files (*.*)"}, {"Basic (*.bas)"}, {"C source (*.c)"}, {"Spin (*.spin)"}, {"Assembler (*.p2asm)"}, }; dlg.setWindowTitle(title); dlg.setAcceptMode(QFileDialog::AcceptOpen); dlg.setDirectory(srcdir); dlg.setFileMode(QFileDialog::ExistingFile); dlg.setHistory(history); dlg.setNameFilters(filetypes); dlg.setOption(QFileDialog::DontUseNativeDialog, true); dlg.setViewMode(QFileDialog::Detail); if (!filename.isEmpty()) dlg.selectFile(filename); if (QFileDialog::Accepted != dlg.exec()) return QString(); QStringList files = dlg.selectedFiles(); if (files.isEmpty()) return QString(); filename = files.first(); QFileInfo info(filename); srcdir = info.dir().absolutePath(); s.setValue(id_sourcedir, srcdir); history.insert(0, filename); if (history.size() > 30) history.takeLast(); s.setValue(id_filename, info.fileName()); s.setValue(id_history, history); return filename; } /** * @brief Preset a QFileDialog for saving a source file * @param title window title * @return QString with the full path, or empty if cancelled */ QString QFlexProp::save_file(const QString& filename, const QString& title) { QFileDialog dlg(this); QSettings s; QString srcdflt = QString("%1/p2tools").arg(QDir::homePath()); QString srcdir = s.value(id_sourcedir, srcdflt).toString(); QStringList history = s.value(id_history).toStringList(); QStringList filetypes = { {"All files (*.*)"}, {"Basic (*.bas)"}, {"C source (*.c)"}, {"Spin (*.spin)"}, {"Assembler (*.p2asm)"}, }; dlg.setWindowTitle(title); dlg.setAcceptMode(QFileDialog::AcceptSave); dlg.setDirectory(srcdir); dlg.setFileMode(QFileDialog::AnyFile); dlg.setNameFilters(filetypes); dlg.setOption(QFileDialog::DontUseNativeDialog, true); dlg.setViewMode(QFileDialog::Detail); dlg.selectFile(filename); if (QFileDialog::Accepted != dlg.exec()) return QString(); QStringList files = dlg.selectedFiles(); if (files.isEmpty()) return QString(); QString save_filename = files.first(); QFileInfo info(save_filename); srcdir = info.dir().absolutePath(); s.setValue(id_sourcedir, srcdir); history.insert(0, save_filename); if (history.size() > 30) history.takeLast(); s.setValue(id_filename, info.fileName()); s.setValue(id_history, history); return save_filename; } /** * @brief Setup the main window title */ void QFlexProp::setup_mainwindow() { QString title = QString("%1 %2") .arg(qApp->applicationName()) .arg(qApp->applicationVersion()); if (m_dev) { if (m_dev->isOpen()) { title += tr(" (%1)").arg(m_port_name); } else { title += tr(" (%1 failed)").arg(m_port_name); } } else { title += tr(" (no port)"); } setWindowTitle(title); log_message(title); } /** * @brief Setup the one time signals connection the SerTerm and QMainWindow */ void QFlexProp::setup_signals() { SerTerm* st = ui->tabWidget->findChild<SerTerm*>(id_terminal); Q_ASSERT(st != nullptr); connect(st, &SerTerm::term_response, this, &QFlexProp::dev_write_data, Qt::UniqueConnection); connect(st, &SerTerm::update_pinout, this, &QFlexProp::update_pinout, Qt::UniqueConnection); connect(ui->tabWidget, &QTabWidget::currentChanged, this, &QFlexProp::tab_changed); connect(ui->tabWidget, &QTabWidget::tabCloseRequested, this, &QFlexProp::tab_close_requested); } /** * @brief Slot called when the serial device has data to be read */ void QFlexProp::dev_ready_read() { qint64 available = m_dev->bytesAvailable(); if (available > 0) { QByteArray data = m_dev->read(available); DBG_DATA("%s: recv %d bytes\n%s", __func__, data.length(), qPrintable(util.dump(__func__, data))); ui->terminal->write(data); update_pinout(true); } } /** * @brief Close the serial device and destroy it */ void QFlexProp::dev_close() { SerTerm* st = ui->tabWidget->findChild<SerTerm*>(id_terminal); Q_ASSERT(st != nullptr); if (m_dev) { qDebug("%s: deleting m_dev", __func__); m_dev->close(); m_dev->deleteLater(); m_dev = nullptr; st->set_device(m_dev); } } /** * @brief Write data to the serial device * @param data */ void QFlexProp::dev_write_data(const QByteArray& data) { Q_ASSERT(m_dev); DBG_DATA("%s: xmit %d bytes\n%s", __func__, data.length(), qPrintable(util.dump(__func__, data))); m_dev->write(data); } /** * @brief Return a LED image for a specific @p state * @param type string constant with type name (dcd, dsr, dtr, ...) * @param state LED state (off, red, green, yellow) * @return QPixmap with the LED scaled to 16x16 pixels */ QPixmap QFlexProp::led(const QString& type, int state) { // This is how the led_*.png resource images are laid out static const QHash<QString,int> leds_xpos = { {id_dcd, 0}, {id_dsr, 1}, {id_dtr, 2}, {id_cts, 3}, {id_rts, 4}, {id_rxd, 5}, {id_txd, 6}, {id_ri, 7}, {id_brk, 8}, {id_fe, 9}, {id_pe, 10}, {id_pwr, 11}, }; QString name = QString("led_%1.png").arg(state); QPixmap pix = QPixmap(QString(":/images/%1").arg(name)); QPixmap led = pix.copy(leds_xpos.value(type) * 64, 0, 64, 64); return led.scaled(16, 16, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } /** * @brief Load the previous settings of the application, serialport, and flexspin */ void QFlexProp::load_settings() { QSettings s; bool ok; s.beginGroup(id_grp_application); QByteArray geometry = s.value(id_window_geometry).toByteArray(); restoreGeometry(geometry); // TODO: sane defaults? #if defined(Q_OS_LINUX) QString font_default = QLatin1String("Monospace"); #elif defined(Q_OS_WIN) QString font_default = QLatin1String("Courier New"); #elif defined(Q_OS_MACOS) QString font_default = QLatin1String("Courier"); #endif // TODO: add preferences dialog for the font, weight and size const QString family = s.value(id_fixedfont_family, font_default).toString(); const int size = s.value(id_fixedfont_size, 12).toInt(); const int weight = s.value(id_fixedfont_weight, QFont::Normal).toInt(); s.endGroup(); m_fixedfont = QFont(family, size, weight); s.beginGroup(id_grp_serialport); m_port_name = s.value(id_port_name, QLatin1String("ttyUSB0")).toString(); s.beginGroup(m_port_name); m_baud_rate = static_cast<Serial_BaudRate>(s.value(id_baud_rate, Serial_Baud230400).toInt()); m_data_bits = static_cast<QSerialPort::DataBits>(s.value(id_data_bits, m_data_bits).toInt()); m_parity = static_cast<QSerialPort::Parity>(s.value(id_parity, m_parity).toInt()); m_stop_bits = static_cast<QSerialPort::StopBits>(s.value(id_stop_bits, m_stop_bits).toInt()); m_flow_control = static_cast<QSerialPort::FlowControl>(s.value(id_flow_control, m_flow_control).toInt()); m_local_echo = s.value(id_local_echo, false).toBool(); s.endGroup(); s.beginGroup(id_grp_enabled); foreach(const QString& id, m_enabled_elements.keys()) { QString key = id; key.remove(QLatin1String("id_")); bool on = m_enabled_elements.value(id); m_enabled_elements.insert(id, s.value(key, on).toBool()); } s.endGroup(); s.endGroup(); s.beginGroup(id_grp_flexspin); QString binary_dflt = QString("%1/bin/flexspin").arg(p2tools_path); m_flexspin_executable = s.value(id_flexspin_executable, binary_dflt).toString(); QStringList include_paths_default; include_paths_default += QString("%1/include").arg(p2tools_path); m_flexspin_include_paths = s.value(id_flexspin_include_paths, include_paths_default).toStringList(); m_flexspin_quiet = s.value(id_flexspin_quiet, true).toBool(); m_flexspin_optimize = s.value(id_flexspin_optimize, 1).toInt(&ok); if (!ok) { m_flexspin_optimize = 1; } m_flexspin_listing = s.value(id_flexspin_listing, false).toBool(); m_flexspin_warnings = s.value(id_flexspin_warnings, true).toBool(); m_flexspin_errors = s.value(id_flexspin_errors, false).toBool(); m_flexspin_hub_address = s.value(id_flexspin_hub_address, 0).toUInt(&ok); if (!ok) { m_flexspin_hub_address = 0; } m_flexspin_skip_coginit = s.value(id_flexspin_skip_coginit, false).toBool(); m_compile_verbose_upload = s.value(id_compile_verbose_upload, false).toBool(); m_compile_switch_to_term = s.value(id_compile_switch_to_term, true).toBool(); s.endGroup(); ui->action_Verbose_upload->setChecked(m_compile_verbose_upload); ui->action_Switch_to_term->setChecked(m_compile_switch_to_term); if (geometry.isEmpty()) { // First run: adjust the size of the main window adjustSize(); } } /** * @brief Save the settings for the application, serialport, and flexspin */ void QFlexProp::save_settings() { QSettings s; s.beginGroup(id_grp_application); // Save window geometry s.setValue(id_window_geometry, saveGeometry()); const QString& family = m_fixedfont.family(); const int size = m_fixedfont.pointSize(); const int weight = m_fixedfont.weight(); // Save fixed font configuration s.setValue(id_fixedfont_family, family); s.setValue(id_fixedfont_size, size); s.setValue(id_fixedfont_weight, weight); s.endGroup(); s.beginGroup(id_grp_serialport); s.setValue(id_port_name, m_port_name); s.beginGroup(m_port_name); s.setValue(id_baud_rate, m_baud_rate); s.setValue(id_data_bits, m_data_bits); s.setValue(id_parity, m_parity); s.setValue(id_stop_bits, m_stop_bits); s.setValue(id_flow_control, m_flow_control); s.setValue(id_local_echo, m_local_echo); s.endGroup(); s.beginGroup(id_grp_enabled); foreach(const QString& id, m_enabled_elements.keys()) { QString key = id; key.remove(QLatin1String("id_")); s.setValue(key, m_enabled_elements.value(id)); } s.endGroup(); s.endGroup(); s.beginGroup(id_grp_flexspin); s.setValue(id_flexspin_executable, m_flexspin_executable); s.setValue(id_flexspin_include_paths, m_flexspin_include_paths); s.setValue(id_flexspin_quiet, m_flexspin_quiet); s.setValue(id_flexspin_optimize, m_flexspin_optimize); s.setValue(id_flexspin_listing, m_flexspin_listing); s.setValue(id_flexspin_warnings, m_flexspin_warnings); s.setValue(id_flexspin_errors, m_flexspin_errors); s.setValue(id_flexspin_hub_address, m_flexspin_hub_address); s.setValue(id_flexspin_skip_coginit, m_flexspin_skip_coginit); s.setValue(id_compile_verbose_upload, m_compile_verbose_upload); s.setValue(id_compile_switch_to_term, m_compile_switch_to_term); s.endGroup(); } /** * @brief Update the statusbar items and LEDs for the current signal states * @param redo if true, redo this update after 25 milliseconds */ void QFlexProp::update_pinout(bool redo) { static const int off = 0; static const int red = 1; static const int grn = 2; static const int yel = 3; if (m_labels.contains(id_pwr)) { m_labels[id_pwr]->setPixmap(led(id_pwr, m_dev->isOpen() ? yel : off)); } if (m_labels.contains(id_rxd)) { m_labels[id_rxd]->setPixmap(led(id_rxd, m_dev->bytesAvailable() > 0 ? yel : grn)); } if (m_labels.contains(id_txd)) { m_labels[id_txd]->setPixmap(led(id_txd, m_dev->bytesToWrite() > 0 ? yel : grn)); } QSerialPort* stty = qobject_cast<QSerialPort*>(m_dev); if (stty) { QSerialPort::PinoutSignals pin = stty->pinoutSignals(); const QSerialPort::SerialPortError err = stty->error(); if (m_labels.contains(id_dcd)) { m_labels[id_dcd]->setPixmap(led(id_dcd, pin.testFlag(QSerialPort::DataCarrierDetectSignal) ? red : off)); } if (m_labels.contains(id_dtr)) { m_labels[id_dtr]->setPixmap(led(id_dtr, pin.testFlag(QSerialPort::DataTerminalReadySignal) ? grn : off)); } if (m_labels.contains(id_dsr)) { m_labels[id_dsr]->setPixmap(led(id_dsr, pin.testFlag(QSerialPort::DataSetReadySignal) ? red : off)); } if (m_labels.contains(id_rts)) { m_labels[id_rts]->setPixmap(led(id_rts, pin.testFlag(QSerialPort::RequestToSendSignal) ? grn : off)); } if (m_labels.contains(id_cts)) { m_labels[id_cts]->setPixmap(led(id_cts, pin.testFlag(QSerialPort::ClearToSendSignal) ? red : off)); } if (m_labels.contains(id_brk)) { m_labels[id_brk]->setPixmap(led(id_brk, stty->isBreakEnabled() ? red : off)); } if (m_labels.contains(id_ri)) { m_labels[id_ri]->setPixmap(led(id_ri, pin.testFlag(QSerialPort::RingIndicatorSignal) ? red : off)); } if (m_labels.contains(id_fe)) { m_labels[id_fe]->setPixmap(led(id_fe, QSerialPort::FramingError == err ? red : off)); } if (m_labels.contains(id_pe)) { m_labels[id_pe]->setPixmap(led(id_pe, QSerialPort::ParityError == err ? red : off)); } } if (redo) { update_baud_rate(); update_parity_data_stop(); update_flow_control(); QTimer::singleShot(25, this, SLOT(dev_ready_read())); } } /** * @brief Slot is called when the tab widget's tab (page) is changed * @param index zero based index of the tab */ void QFlexProp::tab_changed(int index) { Q_UNUSED(index) const PropEdit* pe = current_propedit(index); const bool enable = pe != nullptr; const bool has_listing = pe && !pe->property(id_tab_lst).isNull(); const bool has_intermediate = pe && !pe->property(id_tab_p2asm).isNull(); const bool has_binary = pe && !pe->property(id_tab_binary).isNull(); ui->action_Show_listing->setEnabled(enable && has_listing); ui->action_Show_intermediate->setEnabled(enable && has_intermediate); ui->action_Show_binary->setEnabled(enable && has_binary); ui->action_Verbose_upload->setEnabled(enable); ui->action_Switch_to_term->setEnabled(enable); ui->action_Build->setEnabled(enable); ui->action_Upload->setEnabled(enable); ui->action_Run->setEnabled(enable); if (index == ui->tabWidget->count() - 1) { // Make sure that instead of the tab the terminal has the focus ui->terminal->setFocus(); } } void QFlexProp::tab_close_requested(int index) { PropEdit* pe = current_propedit(index); if (!pe) return; if (pe->changed()) { int res = QMessageBox::information(this, tr("File '%1' changed!").arg(pe->filename()), tr("The file '%1' was modified. Do you want to save it before closing the tab?").arg(pe->filename()), QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel); if (res == QMessageBox::Cancel) { return; } if (res == QMessageBox::Yes) { pe->save(pe->filename()); } } ui->tabWidget->removeTab(index); } /** * @brief Log a message to the statusbar's QComboBox * @param message text to log */ void QFlexProp::log_message(const QString& message) { QEventLoop loop(this); log_status(message); loop.processEvents(); } /** * @brief Log a status message to the statusbar's QComboBox * @param message text to log * @param icon if true, display the status icon next to the message */ void QFlexProp::log_status(const QString& message, bool icon) { QEventLoop loop(this); QComboBox* cb_status = ui->statusbar->findChild<QComboBox*>(id_status); if (!cb_status) { qDebug("%s: %s", __func__, qPrintable(message)); return; } const int index = cb_status->count(); cb_status->addItem(message); if (icon) { cb_status->setItemData(index, QIcon(":/images/status.png"), Qt::DecorationRole); } cb_status->setCurrentIndex(index); loop.processEvents(); } /** * @brief Log an error message to the statusbar's QComboBox * @param message text to log * @param icon if true, display the error icon next to the message */ void QFlexProp::log_error(const QString& message, bool icon) { QEventLoop loop(this); QComboBox* cb_status = ui->statusbar->findChild<QComboBox*>(id_status); if (!cb_status) { qDebug("%s: %s", __func__, qPrintable(message)); return; } const int index = cb_status->count(); cb_status->addItem(message); if (icon) { cb_status->setItemData(index, QIcon(":/images/error.png"), Qt::DecorationRole); } cb_status->setItemData(index, QColor(qRgb(0xff,0x40,0x00)), Qt::ForegroundRole); cb_status->setCurrentIndex(index); loop.processEvents(); } /** * @brief Update the baud rate display in the statusbar */ void QFlexProp::update_baud_rate() { if (!m_labels.contains(id_baud_rate)) return; QSerialPort* stty = qobject_cast<QSerialPort*>(m_dev); if (stty) { QLocale locale = QLocale::system(); QSerialPort::Directions directions = stty->AllDirections; qint32 baud_rate = stty->baudRate(directions); QLabel* lbl_baud = m_labels[id_baud_rate]; QString baud = locale.toString(baud_rate); QString dir = direction_str.value(directions); QString str = QString("%1%2").arg(dir).arg(baud); // FIXME: does it make a difference to check for changed text? if (str != lbl_baud->text()) lbl_baud->setText(str); } } /** * @brief Update the parity, data bits, and stop bits display in the statusbar */ void QFlexProp::update_parity_data_stop() { if (!m_labels.contains(id_parity_data_stop)) return; QSerialPort* stty = qobject_cast<QSerialPort*>(m_dev); if (stty) { QLabel* lbl_pds = m_labels[id_parity_data_stop]; Q_ASSERT(lbl_pds); QString parity = m_dev ? QString(parity_char.value(stty->parity())) : str_unknown; QString data = m_dev ? data_bits_str.value(stty->dataBits()) : str_unknown; QString stop = m_dev ? stop_bits_str.value(stty->stopBits()) : str_unknown; QString str = QString("%1%2%3") .arg(parity) .arg(data) .arg(stop); // FIXME: does it make a difference to check for changed text? if (str != lbl_pds->text()) lbl_pds->setText(str); } } /** * @brief Update the data bits display in the statusbar */ void QFlexProp::update_data_bits() { update_parity_data_stop(); } /** * @brief Update the parity display in the statusbar */ void QFlexProp::update_parity() { update_parity_data_stop(); } /** * @brief Update the stop bits display in the statusbar */ void QFlexProp::update_stop_bits() { update_parity_data_stop(); } /** * @brief Update the flow control display in the statusbar */ void QFlexProp::update_flow_control() { if (!m_labels.contains(id_flow_control)) return; QSerialPort* stty = qobject_cast<QSerialPort*>(m_dev); if (stty) { QSerialPort::FlowControl flow_control = stty->flowControl(); QLabel* lbl_flow = m_labels[id_flow_control]; QString str = flow_ctrl_str.value(flow_control); if (str != lbl_flow->text()) { lbl_flow->setText(str); lbl_flow->setToolTip(flow_ctrl_tooltip.value(flow_control)); } } } /** * @brief Update the DTR display in the statusbar */ void QFlexProp::update_dtr(bool set) { Q_UNUSED(set) update_pinout(); } /** * @brief Update the RTS display in the statusbar */ void QFlexProp::update_rts(bool set) { Q_UNUSED(set) update_pinout(); } /** * @brief Slot is called when an error occured on the serial port * @param error SerialPortError code */ void QFlexProp::error_occured(QSerialPort::SerialPortError error) { QString message; switch (error) { case QSerialPort::NoError: message = tr("Opened device %1.").arg(m_port_name); log_status(message); return; case QSerialPort::DeviceNotFoundError: message = tr("Device %1 not found.").arg(m_port_name); break; case QSerialPort::PermissionError: message = tr("Insufficient permission to access device %1.").arg(m_port_name); break; case QSerialPort::OpenError: message = tr("Could not open device %1.").arg(m_port_name); break; case QSerialPort::ParityError: message = tr("Parity error on device %1.").arg(m_port_name); break; case QSerialPort::FramingError: message = tr("Framing error on device %1.").arg(m_port_name); break; case QSerialPort::BreakConditionError: message = tr("Break conidition error on device %1.").arg(m_port_name); break; case QSerialPort::WriteError: message = tr("Write error on device %1.").arg(m_port_name); break; case QSerialPort::ReadError: message = tr("Read error on device %1.").arg(m_port_name); break; case QSerialPort::ResourceError: message = tr("Resource error on device %1.").arg(m_port_name); break; case QSerialPort::UnsupportedOperationError: message = tr("Unsupported operation on device %1: %2.") .arg(m_port_name) .arg(m_stty_operation); break; case QSerialPort::UnknownError: message = tr("Unknown error on device %1.").arg(m_port_name); break; case QSerialPort::TimeoutError: // message = tr("Timeout on device %1.").arg(m_port_name); break; case QSerialPort::NotOpenError: message = tr("Device %1 is not opened.").arg(m_port_name); break; } if (!message.isEmpty()) log_error(message, true); } /** * @brief Update the break enable display in the status bar * @param set if true, break is set, otherwise it's reset */ void QFlexProp::update_break_enable(bool set) { Q_UNUSED(set) update_pinout(true); } /** * @brief Setup the status bar display elements */ void QFlexProp::setup_statusbar() { const QFrame::Shape shape = QFrame::WinPanel; const QFrame::Shadow shadow = QFrame::Raised; delete m_labels.value(id_baud_rate); QLabel* lbl_baud = new QLabel; m_labels.insert(id_baud_rate, lbl_baud); lbl_baud->setObjectName(id_baud_rate); lbl_baud->setFrameShape(shape); lbl_baud->setFrameShadow(shadow); lbl_baud->setText("-"); lbl_baud->setToolTip(tr("Currently selected baud rate (bits per second).")); ui->statusbar->addPermanentWidget(lbl_baud); delete m_labels.value(id_parity_data_stop); QLabel* lbl_dps = new QLabel; m_labels.insert(id_parity_data_stop, lbl_dps); lbl_dps->setObjectName(id_parity_data_stop); lbl_dps->setFrameShape(shape); lbl_dps->setFrameShadow(shadow); lbl_dps->setText("???"); lbl_dps->setToolTip(tr("Number of data bits, parity, and number of stop bits per character.")); ui->statusbar->addPermanentWidget(lbl_dps); delete m_labels.value(id_flow_control); QLabel* lbl_flow = new QLabel; m_labels.insert(id_flow_control, lbl_flow); lbl_flow->setObjectName(id_flow_control); lbl_flow->setFrameShape(shape); lbl_flow->setFrameShadow(shadow); lbl_flow->setText("-"); lbl_flow->setToolTip(tr("Type of flow control.")); ui->statusbar->addPermanentWidget(lbl_flow); foreach(const QString& key, m_leds) { delete m_labels.value(key); QLabel* lbl = new QLabel; m_labels.insert(key, lbl); lbl->setIndent(0); lbl->setObjectName(key); lbl->setPixmap(led(key, 0)); lbl->setToolTip(pinout_leds.value(key)); ui->statusbar->addPermanentWidget(lbl); } QProgressBar* pb_progress = new QProgressBar(); pb_progress->setObjectName(id_progress); pb_progress->setToolTip("Shows progress of the current activity."); pb_progress->setFixedWidth(160); ui->statusbar->addPermanentWidget(pb_progress); QComboBox* cb_status = ui->statusbar->findChild<QComboBox*>(id_status); delete cb_status; cb_status = new QComboBox; cb_status->setObjectName(id_status); cb_status->setToolTip(tr("Most recent status message.")); ui->statusbar->addWidget(cb_status, 1); log_status(tr("%1 %2 says \"%3\"") .arg(qApp->applicationName()) .arg(qApp->applicationVersion()) .arg(tr("Hello!"))); } /** * @brief Setup the serial port and connect to the QSerialPort signals */ void QFlexProp::setup_port() { SerTerm* st = ui->tabWidget->findChild<SerTerm*>(id_terminal); Q_ASSERT(st); bool ok; QSerialPortInfo si(m_port_name); if (si.isNull()) { m_dev = new QFile(m_port_name); m_labels[id_baud_rate]->setVisible(false); m_labels[id_parity_data_stop]->setVisible(false); m_labels[id_flow_control]->setVisible(false); foreach(const QString& key, m_leds) { m_labels[key]->setVisible(false); } m_labels[id_pwr]->setVisible(m_enabled_elements.value(id_pwr, false)); m_labels[id_rxd]->setVisible(m_enabled_elements.value(id_rxd, false)); m_labels[id_txd]->setVisible(m_enabled_elements.value(id_txd, false)); } else { m_dev = new QSerialPort(si); QSerialPort* stty = qobject_cast<QSerialPort*>(m_dev); if (stty) { m_labels[id_baud_rate]->setVisible(m_enabled_elements.value(id_baud_rate, false)); m_labels[id_parity_data_stop]->setVisible(m_enabled_elements.value(id_parity_data_stop, false)); m_labels[id_flow_control]->setVisible(m_enabled_elements.value(id_flow_control, false)); foreach(const QString& key, m_leds) { m_labels[key]->setVisible(m_enabled_elements.value(key, false)); } ok = connect(stty, &QSerialPort::baudRateChanged, this, &QFlexProp::update_baud_rate, Qt::UniqueConnection); Q_ASSERT(ok); ok = connect(stty, &QSerialPort::dataBitsChanged, this, &QFlexProp::update_data_bits, Qt::UniqueConnection); Q_ASSERT(ok); ok = connect(stty, &QSerialPort::parityChanged, this, &QFlexProp::update_parity, Qt::UniqueConnection); Q_ASSERT(ok); ok = connect(stty, &QSerialPort::stopBitsChanged, this, &QFlexProp::update_stop_bits, Qt::UniqueConnection); Q_ASSERT(ok); ok = connect(stty, &QSerialPort::flowControlChanged, this, &QFlexProp::update_flow_control, Qt::UniqueConnection); Q_ASSERT(ok); ok = connect(stty, &QSerialPort::dataTerminalReadyChanged, this, &QFlexProp::update_dtr, Qt::UniqueConnection); Q_ASSERT(ok); ok = connect(stty, &QSerialPort::requestToSendChanged, this, &QFlexProp::update_rts, Qt::UniqueConnection); Q_ASSERT(ok); ok = connect(stty, &QSerialPort::breakEnabledChanged, this, &QFlexProp::update_break_enable, Qt::UniqueConnection); Q_ASSERT(ok); ok = connect(stty, &QSerialPort::errorOccurred, this, &QFlexProp::error_occured, Qt::UniqueConnection); Q_ASSERT(ok); } } ok = connect(m_dev, &QSerialPort::readyRead, this, &QFlexProp::dev_ready_read, Qt::UniqueConnection); Q_ASSERT(ok); st->set_device(m_dev); } /** * @brief Configure the serial port by setting it's parameters */ void QFlexProp::configure_port() { setup_port(); QSerialPort* stty = qobject_cast<QSerialPort*>(m_dev); if (stty) { stty->setPortName(m_port_name); m_stty_operation = tr("setBaudRate(%1)").arg(m_baud_rate); stty->setBaudRate(m_baud_rate); m_stty_operation = tr("setParity(%1)").arg(parity_str.value(m_parity)); stty->setParity(m_parity); m_stty_operation = tr("setDataBits(%1)").arg(data_bits_str.value(m_data_bits)); stty->setDataBits(m_data_bits); m_stty_operation = tr("setStopBits(%1)").arg(stop_bits_str.value(m_stop_bits)); stty->setStopBits(m_stop_bits); m_stty_operation = tr("setFlowControl(%1)").arg(flow_control_str.value(m_flow_control)); stty->setFlowControl(m_flow_control); m_stty_operation = tr("open(%1)").arg(QLatin1String("QIODevice::ReadWrite")); if (stty->open(QIODevice::ReadWrite)) { m_stty_operation = tr("setDataTerminalReady(%1)").arg("true"); stty->setDataTerminalReady(true); if (m_flow_control == QSerialPort::HardwareControl) { m_stty_operation = tr("setRequestToSend(%1)").arg("true"); stty->setRequestToSend(true); } } else { qDebug("%s: failed to %s", __func__, qPrintable(m_stty_operation)); } } #if defined(Q_OS_LINUX) else do { int fdm = ::open(m_port_name.toLatin1().constData(), O_RDWR); if (fdm < 0) { log_error(tr("Could not open device %1: %2") .arg(m_port_name) .arg(strerror(errno))); break; } if (grantpt(fdm) < 0) { log_error(tr("Could not grant access to slave for %1 (%2): %3") .arg(m_port_name) .arg(fdm) .arg(strerror(errno))); break; } if (unlockpt(fdm) < 0) { log_error(tr("Could not clear slave's lock flag for %1 (%2): %3") .arg(m_port_name) .arg(fdm) .arg(strerror(errno))); break; } const char* pts = ptsname(fdm); if (nullptr == pts) { log_error(tr("Could not get ptsname for %1 (%2): %3") .arg(m_port_name) .arg(fdm) .arg(strerror(errno))); break; } m_dev = new QFile(QString::fromLatin1(pts)); if (!m_dev->open(QIODevice::ReadWrite)) { log_error(tr("Could not open device %1: %2") .arg(m_port_name) .arg(m_dev->errorString()), true); } break; } while (0); #endif setup_mainwindow(); update_parity_data_stop(); update_pinout(); } /** * @brief Close the serial port */ void QFlexProp::close_port() { disconnect(m_dev); m_dev->close(); setup_mainwindow(); update_pinout(); } /** * @brief Insert a new tab into the main window's QTabWidget * @param filename name of the file to load (if it exists) * @return tab identifier (zero based) */ int QFlexProp::insert_tab(const QString& filename) { QLocale locale = QLocale::system(); QSettings s; const int tabs = ui->tabWidget->count(); const int tabidx = tabs - 1; QWidget *tab; QVBoxLayout *vlay; QSplitter *spl; QScrollArea *sa; QTextBrowser *tb; PropEdit *pe; tab = new QWidget(); tab->setObjectName(QString("tab_%1").arg(tabidx)); vlay = new QVBoxLayout(tab); vlay->setObjectName(QLatin1String("vlay")); spl = new QSplitter(Qt::Vertical); spl->setObjectName(id_splitter); sa = new QScrollArea(); sa->setObjectName(id_scrollarea); sa->setWidgetResizable(true); pe = new PropEdit(); pe->setObjectName(id_propedit); pe->setGeometry(QRect(0, 0, 512, 512)); pe->setFont(m_fixedfont); sa->setWidget(pe); spl->addWidget(sa); tb = new QTextBrowser(); tb->setObjectName(id_textbrowser); tb->setWordWrapMode(QTextOption::NoWrap); tb->setFont(m_fixedfont); spl->addWidget(tb); vlay->addWidget(spl); spl->setStretchFactor(0, 8); spl->setStretchFactor(1, 1); QFileInfo info(filename); ui->tabWidget->insertTab(tabidx, tab, QString()); ui->tabWidget->setCurrentIndex(tabidx); if (info.exists()) { if (pe->load(info.absoluteFilePath())) { log_message(tr("Loaded file '%1' (%2 Bytes).") .arg(info.fileName()) .arg(locale.toString(info.size()))); ui->tabWidget->setCurrentIndex(tabidx); } else { log_message(tr("Could not load file '%1'.") .arg(info.fileName())); } } QString title = QString("%1 [%2]") .arg(info.fileName()) .arg(pe->filetype_name()); ui->tabWidget->setTabText(tabidx, title); return tabidx; } /** * @brief File -> New action */ void QFlexProp::on_action_New_triggered() { QSettings s; QString srcdflt = QString("%1/p2tools").arg(QDir::homePath()); const QString srcdir = s.value(id_sourcedir, srcdflt).toString(); const QString new_filename = QString("%1/newfile.spin").arg(srcdir); const QString bak_filename = QString("%1~").arg(new_filename); QFile::remove(bak_filename); QFile::rename(new_filename, bak_filename); insert_tab(new_filename); } /** * @brief File -> Open action */ void QFlexProp::on_action_Open_triggered() { QString filename = load_file(tr("Open source file")); if (filename.isEmpty()) return; insert_tab(filename); } /** * @brief File -> Save action */ void QFlexProp::on_action_Save_triggered() { QLocale locale = QLocale::system(); PropEdit *pe = current_propedit(); if (!pe) { return; } if (!pe->changed()) { QString text = pe->text(); QString filename = pe->filename(); QFileInfo info(filename); log_message(tr("File '%1' did not change.") .arg(info.fileName())); return; } QFileInfo info(pe->filename()); if (pe->save(info.absoluteFilePath())) { log_message(tr("Saved file '%1' (%2 Bytes).") .arg(info.absoluteFilePath()) .arg(locale.toString(info.size()))); } else { log_message(tr("Could not save file '%1'.") .arg(info.absoluteFilePath())); } } /** * @brief File -> Save as action */ void QFlexProp::on_action_Save_as_triggered() { QLocale locale = QLocale::system(); PropEdit *pe = current_propedit(); if (!pe) { QMessageBox::critical(this, tr("No propEdit widget!"), tr("There is selected does not contain a propEdit widget."), QMessageBox::Close, QMessageBox::Close); return; } QString filename = pe->filename(); QString save_as = save_file(filename, tr("Save source file")); if (save_as.isEmpty()) { log_message(tr("Saving file '%1' cancelled.") .arg(filename)); return; } QFileInfo info(save_as); if (pe->save(save_as)) { log_message(tr("Saved file '%1' (%2 bytes).") .arg(info.absoluteFilePath()) .arg(locale.toString(info.size()))); } else { log_message(tr("Could not save file '%1'.") .arg(info.absoluteFilePath())); } } /** * @brief File -> Close action */ void QFlexProp::on_action_Close_triggered() { PropEdit *pe = current_propedit(); if (!pe) { return; } if (pe->changed()) { int res = QMessageBox::information(this, tr("File '%1' changed!").arg(pe->filename()), tr("The file '%1' was modified. Do you want to save it before closing the tab?").arg(pe->filename()), QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel); if (res == QMessageBox::Cancel) { return; } if (res == QMessageBox::Yes) { pe->save(pe->filename()); } } ui->tabWidget->removeTab(ui->tabWidget->currentIndex()); } /** * @brief File -> Quit action */ void QFlexProp::on_action_Quit_triggered() { close(); } /** * @brief Edit -> Select all action */ void QFlexProp::on_action_Select_all_triggered() { PropEdit* pe = current_propedit(); if (!pe) return; pe->selectAll(); } /** * @brief Edit -> Delete action */ void QFlexProp::on_action_Delete_triggered() { PropEdit* pe = current_propedit(); if (!pe) return; pe->clear(); } /** * @brief Edit -> Cut action */ void QFlexProp::on_action_Cut_triggered() { PropEdit* pe = current_propedit(); if (!pe) return; pe->cut(); } /** * @brief Edit -> Copy action */ void QFlexProp::on_action_Copy_triggered() { PropEdit* pe = current_propedit(); if (!pe) return; pe->copy(); } /** * @brief Edit -> Paste action */ void QFlexProp::on_action_Paste_triggered() { PropEdit* pe = current_propedit(); if (!pe) return; pe->paste(); } void QFlexProp::on_action_Find_triggered() { } void QFlexProp::on_action_Find_Replace_triggered() { } void QFlexProp::line_number_finished() { QWidget* wdg = ui->tabWidget->widget(ui->tabWidget->currentIndex()); if (!wdg) return; QSplitter* spl = wdg->findChild<QSplitter*>(id_splitter); if (!spl) return; PropEdit* pe = spl->findChild<PropEdit*>(id_propedit); if (!pe) return; QFrame* frm = spl->findChild<QFrame*>(id_frame); if (!frm) return; QLineEdit* le = frm->findChild<QLineEdit*>(id_linenumber); if (!le) return; bool ok; int lnum = le->text().toInt(&ok); if (!ok) lnum = 0; delete spl->widget(spl->indexOf(frm)); pe->gotoLineNumber(lnum); } void QFlexProp::on_action_Goto_line_triggered() { QWidget* wdg = ui->tabWidget->widget(ui->tabWidget->currentIndex()); if (!wdg) return; QSplitter* spl = wdg->findChild<QSplitter*>(id_splitter); if (!spl) return; QFrame* frm = spl->findChild<QFrame*>(id_frame); // Return if this tab already has a line number frame if (frm) return; frm = new QFrame(); frm->setObjectName(id_frame); frm->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); QHBoxLayout* hlay = new QHBoxLayout(); QLabel* lbl = new QLabel(tr("Go to line number:")); lbl->setObjectName(id_label); QLineEdit* le = new QLineEdit(); le->setObjectName(id_linenumber); le->setFixedWidth(10*8); hlay->addWidget(lbl); hlay->addWidget(le); // add an empty widget to fill the space to the width hlay->addWidget(new QWidget()); hlay->setStretch(2, 1); frm->setLayout(hlay); spl->addWidget(frm); connect(le, &QLineEdit::editingFinished, this, &QFlexProp::line_number_finished); le->setFocus(); } /** * @brief Preferences -> Settings action */ void QFlexProp::on_action_Settings_triggered() { SettingsDlg dlg(this); dlg.set_font(m_fixedfont); dlg.set_elements(m_enabled_elements); if (QDialog::Accepted != dlg.exec()) return; m_fixedfont = dlg.font(); m_enabled_elements = dlg.elements(); // Setup the port again to update the displayed elements setup_port(); // Update any open PropEdit's fonts for(int i = 0; i < ui->tabWidget->count(); i++) { PropEdit* pe = ui->tabWidget->findChild<PropEdit*>(id_propedit); if (pe) pe->setFont(m_fixedfont); } } /** * @brief Preferences -> Configure serial port action */ void QFlexProp::on_action_Configure_serialport_triggered() { bool was_open = m_dev->isOpen(); QSettings s; SerialPortDlg::Settings settings; SerialPortDlg dlg(this); settings.name = m_port_name; settings.baud_rate = m_baud_rate; settings.data_bits = m_data_bits; settings.parity = m_parity; settings.stop_bits = m_stop_bits; settings.flow_control = m_flow_control; settings.local_echo = m_local_echo; dlg.set_settings(settings); if (QDialog::Accepted != dlg.exec()) return; settings = dlg.settings(); if (was_open) { close_port(); } // Use the selected settings for the global serial port settings m_port_name = settings.name; m_baud_rate = settings.baud_rate; m_parity = settings.parity; m_data_bits = settings.data_bits; m_stop_bits = settings.stop_bits; m_flow_control = settings.flow_control; m_local_echo = settings.local_echo; if (was_open) { configure_port(); } else { setup_mainwindow(); } } /** * @brief Preferences -> Configure flexspin action */ void QFlexProp::on_action_Configure_flexspin_triggered() { FlexspinDlg dlg(this); FlexspinDlg::Settings f; f.executable = m_flexspin_executable; f.include_paths = m_flexspin_include_paths; f.quiet = m_flexspin_quiet; f.optimize = m_flexspin_optimize; f.listing = m_flexspin_listing; f.warnings = m_flexspin_warnings; f.errors = m_flexspin_errors; f.hub_address = m_flexspin_hub_address; f.skip_coginit = m_flexspin_skip_coginit; dlg.set_settings(f); int res = dlg.exec(); if (QDialog::Accepted != res) return; f = dlg.settings(); m_flexspin_executable = f.executable; m_flexspin_quiet = f.quiet; m_flexspin_include_paths = f.include_paths; m_flexspin_optimize = f.optimize; m_flexspin_listing = f.listing; m_flexspin_warnings = f.warnings; m_flexspin_errors = f.errors; m_flexspin_hub_address = f.hub_address; m_flexspin_skip_coginit = f.skip_coginit; QSettings s; s.beginGroup(id_grp_flexspin); s.setValue(id_flexspin_executable, m_flexspin_executable); s.setValue(id_flexspin_include_paths, m_flexspin_include_paths); s.setValue(id_flexspin_quiet, m_flexspin_quiet); s.setValue(id_flexspin_optimize, m_flexspin_optimize); s.setValue(id_flexspin_listing, m_flexspin_listing); s.setValue(id_flexspin_warnings, m_flexspin_warnings); s.setValue(id_flexspin_errors, m_flexspin_errors); s.setValue(id_flexspin_hub_address, m_flexspin_hub_address); s.setValue(id_flexspin_skip_coginit, m_flexspin_skip_coginit); s.endGroup(); } /** * @brief View -> Show listing action */ void QFlexProp::on_action_Show_listing_triggered() { PropEdit* pe = current_propedit(); if (!pe) return; QString text = pe->property(id_tab_lst).toString(); TextBrowserDlg dlg(this); dlg.set_text(text); dlg.exec(); } void QFlexProp::on_action_Show_intermediate_triggered() { PropEdit* pe = current_propedit(); if (!pe) return; QString text = pe->property(id_tab_p2asm).toString(); TextBrowserDlg dlg(this); dlg.set_text(text); dlg.exec(); } /** * @brief View -> Show binary action */ void QFlexProp::on_action_Show_binary_triggered() { PropEdit* pe = current_propedit(); if (!pe) return; QByteArray data = pe->property(id_tab_binary).toByteArray(); QString dump = util.dump(QString(), data); TextBrowserDlg dlg(this); dlg.set_text(dump); dlg.exec(); } /** * @brief Toggle terminal between 80 and 132 column mode */ void QFlexProp::on_action_Toggle_80_132_mode_triggered() { ui->terminal->term_toggle_80_132(); } /** * @brief Compile -> Verbose upload action */ void QFlexProp::on_action_Verbose_upload_triggered() { m_compile_verbose_upload = ui->action_Verbose_upload->isChecked(); } /** * @brief Compile -> Switch to term action */ void QFlexProp::on_action_Switch_to_term_triggered() { m_compile_switch_to_term = ui->action_Switch_to_term->isChecked(); } /** * @brief Return a quoted string if @p src contains a space * @param src const reference to the source string * @param quote character to use for quoting * @return quoted or original string */ QString QFlexProp::quoted(const QString& src, const QChar quote) { if (src.contains(QChar::Space)) return QString("%1%2%3").arg(quote).arg(src).arg(quote); return src; } /** * @brief Run flexspin with the configured switches and return the results * @param p_binary pointer to a QByteArray for the binary result * @param p_p2asm pointer to a QString for the p2asm output * @param p_lst pointer to a QString for the listing * @return true on success, or false on error */ bool QFlexProp::flexspin(QByteArray* p_binary, QString* p_p2asm, QString* p_lst) { QTextBrowser *tb = current_textbrowser(); Q_ASSERT(tb); PropEdit *pe = current_propedit(); if (!pe) return false; tb->clear(); QFile src(pe->filename()); QStringList args; // compile for Prop2 args += QStringLiteral("-2"); // quiet mode if enabled if (m_flexspin_quiet) args += QStringLiteral("-q"); // append include paths foreach(const QString& include_path, m_flexspin_include_paths) { // We need to quote paths with embedded spaces (e.g. Windows) args += QString("-I %1").arg(quoted(include_path)); } // define the current terminal baud rate args += QString("-D _BAUD=%1").arg(m_baud_rate); // generate a listing if enabled if (m_flexspin_listing) args += QStringLiteral("-l"); // add option for warnings if enabled if (m_flexspin_warnings) args += QStringLiteral("-Wall"); // add option for errors if enabled if (m_flexspin_errors) args += QStringLiteral("-Werror"); // append a HUB address if configured if (m_flexspin_hub_address > 0) { args += QString("-H %1").arg(m_flexspin_hub_address, 4, 16, QChar('0')); // Add flag for skip coginit if (m_flexspin_skip_coginit) args += QStringLiteral("-E"); } // add source filename args += src.fileName(); // print the command to be executed tb->setTextColor(Qt::blue); tb->append(QString("%1 %2") .arg(m_flexspin_executable) .arg(args.join(QStringLiteral(" \\\n\t")))); QProcess process(this); process.setProperty(id_process_tb, QVariant::fromValue(tb)); process.setProgram(m_flexspin_executable); #if defined(Q_OS_WIN) // Windows really sucks: not even argument passing to a process works as elsewhere process.setNativeArguments(args.join(QChar::Space)); #else process.setArguments(args); #endif connect(&process, &QProcess::channelReadyRead, this, &QFlexProp::channelReadyRead); // run the command process.start(); if (QProcess::Starting == process.state()) { if (!process.waitForStarted()) { qCritical("%s: result code %d", __func__, process.exitCode()); tb->setTextColor(Qt::red); tb->append(tr("Result code %1.").arg(process.exitCode())); return false; } } // wait for the process to finish do { if (!process.waitForFinished()) { qCritical("%s: result code %d", __func__, process.exitCode()); tb->setTextColor(Qt::red); tb->append(tr("Result code %1.").arg(process.exitCode())); return false; } } while (QProcess::Running == process.state()); QFileInfo info(src.fileName()); // check, load, and remove listing file QString lst_filename = QString("%1/%2.lst") .arg(info.absoluteDir().path()) .arg(info.baseName()); QFile lst(lst_filename); if (lst.exists()) { if (lst.open(QIODevice::ReadOnly)) { QString listing = QString::fromUtf8(lst.readAll()); pe->setProperty(id_tab_lst, listing); if (p_lst) { // caller wants the listing *p_lst = listing; } lst.close(); } lst.remove(); } // check, load, and remove intermediate p2asm file QString p2asm_filename = QString("%1/%2.p2asm") .arg(info.absoluteDir().path()) .arg(info.baseName()); QFile p2asm(p2asm_filename); if (p2asm.exists()) { if (p2asm.open(QIODevice::ReadOnly)) { QString output = QString::fromUtf8(p2asm.readAll()); pe->setProperty(id_tab_p2asm, output); if (p_p2asm) { // caller wants the output *p_p2asm = output; } p2asm.close(); } p2asm.remove(); } // check, load, and remove resulting binary file QString binary_filename = QString("%1/%2.binary") .arg(info.absoluteDir().path()) .arg(info.baseName()); QFile binfile(binary_filename); if (binfile.exists()) { if (binfile.open(QIODevice::ReadOnly)) { QByteArray binary = binfile.readAll(); pe->setProperty(id_tab_binary, binary); if (p_binary) { // caller wants the binary *p_binary = binary; } binfile.close(); } binfile.remove(); } tab_changed(ui->tabWidget->currentIndex()); return true; } /** * @brief Compile -> Build action */ void QFlexProp::on_action_Build_triggered() { flexspin(); } /** * @brief Compile -> Upload action */ void QFlexProp::on_action_Upload_triggered() { PropEdit* pe = current_propedit(); Q_ASSERT(pe); QByteArray binary = pe->property(id_tab_binary).toByteArray(); if (binary.isEmpty()) { // Need to compile first flexspin(&binary); } } /** * @brief Compile -> Run action */ void QFlexProp::on_action_Run_triggered() { SerTerm* st = ui->tabWidget->findChild<SerTerm*>(id_terminal); Q_ASSERT(st); QTextBrowser* tb = current_textbrowser(); Q_ASSERT(tb); // compile and get resulting binary QByteArray binary; if (!flexspin(&binary)) return; // if binary is empty we do not upload, of course if (binary.isEmpty()) return; // disconnect from the readyRead() signal during upload disconnect(m_dev, &QSerialPort::readyRead, this, &QFlexProp::dev_ready_read); st->reset(); PropLoad propload(m_dev, this); // propload.set_mode(PropLoad::Prop_Txt); propload.set_verbose(m_compile_verbose_upload); propload.set_clock_freq(180000000); propload.set_clock_mode(0); propload.set_user_baud(m_baud_rate); // phex.set_use_checksum(false); propload.setProperty(id_process_tb, QVariant::fromValue(tb)); connect(&propload, &PropLoad::Error, this, &QFlexProp::printError); connect(&propload, &PropLoad::Message, this, &QFlexProp::printMessage); connect(&propload, &PropLoad::Progress, this, &QFlexProp::showProgress); bool ok = propload.load_data(binary); // re-connect to the readyRead() signal connect(m_dev, &QSerialPort::readyRead, this, &QFlexProp::dev_ready_read, Qt::UniqueConnection); if (ok) { if (m_compile_switch_to_term) { // Select the terminal tab ui->tabWidget->setCurrentWidget(ui->terminal); ui->terminal->setFocus(); } // Process any data which may have been received // while the readyRead signal was disconnected if (m_dev->bytesAvailable() > 0) { dev_ready_read(); } } } /** * @brief Help -> About action */ void QFlexProp::on_action_About_triggered() { AboutDlg dlg(this); dlg.exec(); } /** * @brief Help -> About Qt5 action */ void QFlexProp::on_action_About_Qt5_triggered() { qApp->aboutQt(); } /** * @brief Slot called when a process output channel has data to be read * @param channel which channel (stdout or stderr) */ void QFlexProp::channelReadyRead(int channel) { QProcess* process = qobject_cast<QProcess*>(sender()); if (!process) return; QTextBrowser* tb = qvariant_cast<QTextBrowser*>(process->property(id_process_tb)); if (!tb) return; process->setReadChannel(static_cast<QProcess::ProcessChannel>(channel)); QString message = QString::fromUtf8(process->readAll()); switch (channel) { case QProcess::StandardOutput: printMessage(message); break; case QProcess::StandardError: printError(message); break; } } /** * @brief Print an error message to the tab's QTextBrowser * @param message text to print */ void QFlexProp::printError(const QString& message) { QEventLoop loop(this); QTextBrowser* tb = qvariant_cast<QTextBrowser*>(sender()->property(id_process_tb)); if (!tb) return; tb->setTextColor(Qt::red); tb->append(message); loop.processEvents(); } /** * @brief Print a normal message to the tab's QTextBrowser * @param message text to print */ void QFlexProp::printMessage(const QString& message) { QEventLoop loop(this); QTextBrowser* tb = qvariant_cast<QTextBrowser*>(sender()->property(id_process_tb)); if (!tb) return; tb->setTextColor(Qt::black); tb->append(message); loop.processEvents(); } /** * @brief Update the statusbar's progress bar * @param value current value * @param total maximum value (which equals 100%) */ void QFlexProp::showProgress(qint64 value, qint64 total) { QEventLoop loop(this); QProgressBar* pb = ui->statusbar->findChild<QProgressBar*>(id_progress); if (!pb) return; // Scale down to 32 bit integer range while (total >= INT32_MAX) { total >>= 10; value >>= 10; } pb->setRange(0, total); pb->setValue(value); loop.processEvents(); }
28.215868
110
0.676904
totalspectrum
39e7819d4d441b831187d72d793aa13fcc428837
1,112
cpp
C++
03_generic_programming/04_selection_sort.cpp
cpptt-book/2nd
d710af6df9ed2561bc7432be7b0b0b93dafecb0a
[ "CC0-1.0" ]
17
2015-01-07T08:10:09.000Z
2021-06-21T13:07:25.000Z
03_generic_programming/04_selection_sort.cpp
cpptt-book/2nd
d710af6df9ed2561bc7432be7b0b0b93dafecb0a
[ "CC0-1.0" ]
null
null
null
03_generic_programming/04_selection_sort.cpp
cpptt-book/2nd
d710af6df9ed2561bc7432be7b0b0b93dafecb0a
[ "CC0-1.0" ]
5
2015-05-02T19:07:43.000Z
2021-11-14T21:21:32.000Z
// Copyright (c) 2014 // Akira Takahashi, Fumiki Fukuda. // Released under the CC0 1.0 Universal license. template <class Iterator> void selection_sort(Iterator first, Iterator last) { for (Iterator p = first; p != last; ++p) { Iterator min_position = p; for (Iterator q = p; q != last; ++q) { if (*min_position > *q) { min_position = q; } } auto tmp = *min_position; *min_position = *p; *p = tmp; } } template <class Iterator, class Compare> void selection_sort(Iterator first, Iterator last, Compare comp) { for (Iterator p = first; p != last; ++p) { Iterator min_position = p; for (Iterator q = p; q != last; ++q) { if (comp(*q, *min_position)) { min_position = q; } } auto tmp = *min_position; *min_position = *p; *p = tmp; } } #include <iostream> #include <functional> #include <iterator> int main() { int data[] = { 9, 7, 5, 3, 1, 8, 6, 4, 2, 0 }; selection_sort(std::begin(data), std::end(data), std::greater<int>()); for (int x : data) { std::cout << x << ' '; } std::cout << std::endl; }
21.803922
72
0.57464
cpptt-book
39e992056afed351c59751163b7e23bba8fbe410
1,527
hpp
C++
src/verbatim_bone_state.hpp
faemiyah/faemiyah-demoscene_2016-08_80k-intro_ghosts_of_mars
69a79a8cb68591c834989e89be530a1a94fb02c2
[ "BSD-3-Clause" ]
null
null
null
src/verbatim_bone_state.hpp
faemiyah/faemiyah-demoscene_2016-08_80k-intro_ghosts_of_mars
69a79a8cb68591c834989e89be530a1a94fb02c2
[ "BSD-3-Clause" ]
null
null
null
src/verbatim_bone_state.hpp
faemiyah/faemiyah-demoscene_2016-08_80k-intro_ghosts_of_mars
69a79a8cb68591c834989e89be530a1a94fb02c2
[ "BSD-3-Clause" ]
null
null
null
#ifndef VERBATIM_BONE_STATE_HPP #define VERBATIM_BONE_STATE_HPP #include "verbatim_mat4.hpp" /// One position of bone. /// /// Can be neutral position. class BoneState { private: /// Position data (neutral). vec3 m_pos; /// Quaternion data (neutral). quat m_rot; public: /// Empty constructor. BoneState() { } /// Constructor. /// /// \param pos Position. /// \param rot Rotation. BoneState(const vec3 &pos, const quat &rot) : m_pos(pos), m_rot(rot) { } public: /// Accessor. /// /// \return Position. vec3& getPosition() { return m_pos; } /// Const accessor. /// /// \return Position. const vec3& getPosition() const { return m_pos; } /// Accessor. /// /// \return Rotation. quat& getRotation() { return m_rot; } /// Const accessor. /// /// \return Rotation. const quat& getRotation() const { return m_rot; } #if defined(USE_LD) public: /// Output to stream. /// /// \param ostr Output stream. /// \return Output stream. std::ostream& put(std::ostream &ostr) const { return ostr << m_pos << " ; " << m_rot; } #endif }; #if defined(USE_LD) /// Output to stream operator. /// /// \param lhs Left-hand-side operand. /// \param rhs Right-hand-side operand. /// \return Output stream. inline std::ostream& operator<<(std::ostream &lhs, const BoneState &rhs) { return rhs.put(lhs); } #endif #endif
17.551724
72
0.568435
faemiyah
39eaafd2f5a38ebd835824908cd7cfedca3fe3a8
5,796
cpp
C++
camera.cpp
fvcaputo/openglframework
4b57547325297169c0412e06d7f2320731570d00
[ "MIT" ]
1
2016-01-26T02:44:28.000Z
2016-01-26T02:44:28.000Z
camera.cpp
fvcaputo/openglframework
4b57547325297169c0412e06d7f2320731570d00
[ "MIT" ]
null
null
null
camera.cpp
fvcaputo/openglframework
4b57547325297169c0412e06d7f2320731570d00
[ "MIT" ]
1
2021-11-08T15:02:38.000Z
2021-11-08T15:02:38.000Z
/* * camera.cpp * * Set up the camera. * * Authors: Felipe Victorino Caputo * */ #include "camera.h" /* * Camera * * INPUT: * type - the type of the projection. * * DESCRIPTION: * This is this class constructor. It creates a camera * with some default values (centered at the origin, looking * at the negative z axis, up vector is the world's positive y). * And it also defines a default projection that can be either * orthographic or prespective * */ Camera::Camera ( int type ) { float eyeVec[] = {0.0f,0.0f,0.0f,1.0f}; float lookVec[] = {0.0f,0.0f,-1.0f,1.0f}; float upVec[] = {0.0f,1.0f,0.0f,1.0f}; float rightVec[] = {1.0f,0.0f,0.0f,1.0f}; Vector4 eyeAux(4,1,eyeVec); eyePoint = eyeAux; Vector4 lookAux(4,1,lookVec); lookAt = lookAux; Vector4 upAux(4,1,upVec); up = upAux; Vector4 rightAux(4,1,rightVec); right = rightAux; viewMatrix = makeViewMatrix(eyePoint, lookAt, up); if (type == PROJ_PERSP) { projMatrix = makePerspectiveMatrix( 60.0f, 1.0f, 1.0f, 0.5f, 50.0f ); } else { projMatrix = makeOrthographicMatrix( -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 10.0f ); } } /* * ~Camera * * DESCRIPTION: * Default descontructor. * */ Camera::~Camera () { } /* * getViewMatrix * * RETURN: * The view matrix. * * DESCRIPTION: * This function simply returns the view matrix of * this camera object. * */ Matrix4 Camera::getViewMatrix () { return viewMatrix; } /* * getProjMatrix * * RETURN: * The projection matrix. * * DESCRIPTION: * This function simply returns the projection matrix of * this camera object. * */ Matrix4 Camera::getProjMatrix () { return projMatrix; } /* * moveForward * * DESCRIPTION: * This function simply moves the camera forward. * */ void Camera::moveForward () { eyePoint += lookAt * CAM_SPEED; viewMatrix = makeViewMatrix(eyePoint, eyePoint+lookAt, up); } /* * moveBackward * * DESCRIPTION: * This function simply moves the camera backwards. * */ void Camera::moveBackward () { eyePoint -= lookAt * CAM_SPEED; viewMatrix = makeViewMatrix(eyePoint, eyePoint+lookAt, up); } /* * strafeRight * * DESCRIPTION: * This function strafes the camera right. * */ void Camera::strafeRight () { eyePoint += right * CAM_SPEED; viewMatrix = makeViewMatrix(eyePoint, eyePoint+lookAt, up); } /* * strafeLeft * * DESCRIPTION: * This function strafes the camera left. * */ void Camera::strafeLeft () { eyePoint -= right * CAM_SPEED; viewMatrix = makeViewMatrix(eyePoint, eyePoint+lookAt, up); } /* * moveUp * * DESCRIPTION: * This function simply moves the camera up. * */ void Camera::moveUp () { eyePoint += up * CAM_SPEED; viewMatrix = makeViewMatrix(eyePoint, eyePoint+lookAt, up); } /* * moveDown * * DESCRIPTION: * This function simply moves the camera down. * */ void Camera::moveDown () { eyePoint -= up * CAM_SPEED; viewMatrix = makeViewMatrix(eyePoint, eyePoint+lookAt, up); } /* * setInitialMouseCoord * * INPUT: * x - the x coordinate of the mouse click. * y - the y coordinate of the mouse click. * * DESCRIPTION: * This function saves the position where the mouse just clicked, * this information will be used to move the scene given the mouse * movement. * */ void Camera::setInitialMouseCoord (int x, int y) { mouseOldX = x; mouseOldY = y; } /* * moveCameraTarget * * INPUT: * x - the x coordinate of the current mouse position. * y - the y coordinate of the current mouse position. * * DESCRIPTION: * This function will calculate the distance of the last mouse * position and the current one, and will move the camera accordingly. * It works jsut like the camera of most FPS games. * */ void Camera::moveCameraTarget (int x, int y) { float deltaX = (x - mouseOldX) * CAM_SPEED; float deltaY = (y - mouseOldY) * CAM_SPEED; // changes lookat lookAt = rotate(-deltaX, &up[0][0]) * rotate(-deltaY, &right[0][0]) * lookAt; // right changed because of the movement, update right = rotate(-deltaX, &up[0][0]) * right; viewMatrix = makeViewMatrix(eyePoint, eyePoint+lookAt, up); mouseOldX = x; mouseOldY = y; } void Camera::setCameraPosition (float x, float y, float z) { float eyeVec[] = { x, y, z, 1.0f}; Vector4 eyeAux(4,1,eyeVec); eyePoint = eyeAux; } void Camera::setLookAt (float x, float y, float z) { float lookVec[] = { x, y, z, 1.0f}; Vector4 lookVecAux(4,1,lookVec); lookAt = lookVecAux; } void Camera::setRight (float x, float y, float z) { float rightVec[] = { x, y, z, 1.0f}; Vector4 rightVecAux(4,1,rightVec); right = rightVecAux; } void Camera::setUp (float x, float y, float z) { float upVec[] = { x, y, z, 1.0f}; Vector4 upVecAux(4,1,upVec); up = upVecAux; } vector<float> Camera::getCameraPosition () { vector<float> pos; pos.push_back(eyePoint[0][0]); pos.push_back(eyePoint[1][0]); pos.push_back(eyePoint[2][0]); return pos; } vector<float> Camera::getLookAt () { vector<float> pos; pos.push_back(lookAt[0][0]); pos.push_back(lookAt[1][0]); pos.push_back(lookAt[2][0]); return pos; } vector<float> Camera::getRight () { vector<float> pos; pos.push_back(right[0][0]); pos.push_back(right[1][0]); pos.push_back(right[2][0]); return pos; } vector<float> Camera::getUp () { vector<float> pos; pos.push_back(up[0][0]); pos.push_back(up[1][0]); pos.push_back(up[2][0]); return pos; }
20.848921
85
0.613527
fvcaputo
39eb749edadd33e99099d326d463887048d607ce
390
hpp
C++
sources/_headers_std_cv_ogl.hpp
unvrtool/unvrtool
1f9601f1b3f7db16244cec6064e648a3df45d2f6
[ "BSD-3-Clause" ]
null
null
null
sources/_headers_std_cv_ogl.hpp
unvrtool/unvrtool
1f9601f1b3f7db16244cec6064e648a3df45d2f6
[ "BSD-3-Clause" ]
null
null
null
sources/_headers_std_cv_ogl.hpp
unvrtool/unvrtool
1f9601f1b3f7db16244cec6064e648a3df45d2f6
[ "BSD-3-Clause" ]
null
null
null
// // Copyright (c) 2020, Jan Ove Haaland, all rights reserved. // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #pragma once #include "_headers_std_cv.hpp" #include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp>
21.666667
72
0.733333
unvrtool
39f35f565f9c51c01fe191002eefe2a5aa9e61f5
9,887
cpp
C++
audio/common/Reasoning/jhcAssocMem.cpp
jconnell11/ALIA
f7a6c9dfd775fbd41239051aeed7775adb878b0a
[ "Apache-2.0" ]
null
null
null
audio/common/Reasoning/jhcAssocMem.cpp
jconnell11/ALIA
f7a6c9dfd775fbd41239051aeed7775adb878b0a
[ "Apache-2.0" ]
null
null
null
audio/common/Reasoning/jhcAssocMem.cpp
jconnell11/ALIA
f7a6c9dfd775fbd41239051aeed7775adb878b0a
[ "Apache-2.0" ]
null
null
null
// jhcAssocMem.cpp : deductive rules for use in halo of ALIA system // // Written by Jonathan H. Connell, jconnell@alum.mit.edu // /////////////////////////////////////////////////////////////////////////// // // Copyright 2017-2019 IBM Corporation // Copyright 2020-2021 Etaoin Systems // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////////// #include <stdio.h> #include "Interface/jprintf.h" // common video #include "Action/jhcAliaCore.h" // common robot - since only spec'd as class in header #include "Parse/jhcTxtLine.h" // common audio #include "Reasoning/jhcAssocMem.h" /////////////////////////////////////////////////////////////////////////// // Creation and Initialization // /////////////////////////////////////////////////////////////////////////// //= Default destructor does necessary cleanup. jhcAssocMem::~jhcAssocMem () { clear(); } //= Get rid of all loaded rules. // always returns 0 for convenience int jhcAssocMem::clear () { jhcAliaRule *r0, *r = rules; while (r != NULL) { r0 = r; r = r->next; delete r0; } rules = NULL; nr = 0; return 0; } //= Default constructor initializes certain values. jhcAssocMem::jhcAssocMem () { rules = NULL; nr = 0; noisy = 2; detail = 0; //detail = 14; // show detailed matching for some rule } /////////////////////////////////////////////////////////////////////////// // List Functions // /////////////////////////////////////////////////////////////////////////// //= Add new rule onto tail of list. // returns id number of item added, 0 if not added (consider deleting) int jhcAssocMem::AddRule (jhcAliaRule *r, int ann) { jhcAliaRule *r0 = rules, *prev = NULL; // check for likely duplication if (r == NULL) return 0; if (r->Tautology()) return jprintf(1, ann, " ... new rule rejected as a tautology\n\n"); while ((prev = NextRule(prev)) != NULL) if (r->Identical(*prev)) return jprintf(1, ann, " ... new rule rejected as identical to rule %d\n\n", prev->RuleNum()); // add to end of list if (r0 == NULL) rules = r; else { while (r0->next != NULL) r0 = r0->next; r0->next = r; } // assign rule id number r->next = NULL; r->id = ++nr; // possibly announce formation if ((ann > 0) && (noisy >= 1)) { jprintf("\n---------------------------------\n"); r->Print(); jprintf("---------------------------------\n\n"); } return nr; } //= Remove a rule from the list and permanently delete it. // must make sure original rem pointer is set to NULL in caller // used by jhcAliaDir to clean up incomplete ADD operator void jhcAssocMem::Remove (const jhcAliaRule *rem) { jhcAliaRule *prev = NULL, *r = rules; // look for rule in list if (rem == NULL) return; while (r != NULL) { // possibly splice out of list and delete if (r == rem) { if (prev != NULL) prev->next = r->next; else rules = r->next; delete r; return; } // move on to next list entry prev = r; r = r->next; } } /////////////////////////////////////////////////////////////////////////// // Main Functions // /////////////////////////////////////////////////////////////////////////// //= Apply all rules to main portion of working memory, results go to halo. // will not match conditions with blf < mth, or even try weak rules // returns number of invocations int jhcAssocMem::RefreshHalo (jhcWorkMem& wmem, int dbg) const { jhcAliaRule *r = NULL; double mth = wmem.MinBlf(); int cnt = 0, cnt2 = 0; //dbg = 2; // quick way to show halo inferences jtimer(13, "RefreshHalo"); // PASS 1 - erase all previous halo deductions jprintf(1, dbg, "HALO refresh ...\n"); wmem.ClearHalo(); wmem.SetMode(0); // only match to nodes in main pool jprintf(2, dbg, "1-step:\n"); while ((r = NextRule(r)) != NULL) { r->dbg = ((r->id == detail) ? 3 : 0); cnt += r->AssertMatches(wmem, mth, 0, dbg - 1); } // PASS 2 - mark start of 2-step inferences wmem.Horizon(); wmem.SetMode(1); // match to main pool and 1-step r = NULL; jprintf(2, dbg, "2-step:\n"); while ((r = NextRule(r)) != NULL) { r->dbg = ((r->id == detail) ? 3 : 0); cnt2 += r->AssertMatches(wmem, mth, 1, dbg - 1); } // report result jprintf(1, dbg, " %d + %d rule invocations\n\n", cnt, cnt2); //wmem.PrintHalo(); jtimer_x(13); return cnt; } //= If a two rule series used to infer an essential fact then combine the two rules. // needs raw bindings before halo migration (i.e. before modification by ReifyRules) // returns number of new rules created int jhcAssocMem::Consolidate (const jhcBindings& b, int dbg) { jhcBindings list, list2, m2c; jhcAliaRule *r2, *r1, *mix = NULL; jhcBindings *b2, *b1; int j, nc, nb = b.NumPairs(), i = -1, cnt = 0; // search through main fact inference bindings (length may change) list.Copy(b); while ((i = next_halo(&r2, &b2, list, i + 1)) < nb) { // look for halo facts used to trigger this step-2 halo rule list2.Copy(b2); nc = r2->NumPat(); j = -1; while ((j = next_halo(&r1, &b1, list2, j + 1)) < nc) { // merge step-1 halo rule into consolidated rule (possibly create) if (mix == NULL) { jprintf(1, dbg, "CONSOLIDATE: rule %d <== rule %d", r2->RuleNum(), r1->RuleNum()); mix = new jhcAliaRule; m2c.Clear(); } else jprintf(1, dbg, " + rule %d", r1->RuleNum()); mix->AddCombo(m2c, *r1, *b1); } // add complete rule to procedural memory if (mix != NULL) { jprintf(1, dbg, "\n"); mix->LinkCombo(m2c, *r2, *b2); if (AddRule(mix, 1 + dbg) <= 0) delete mix; // possibly a duplicate mix = NULL; cnt++; } } return cnt; } //= Look down list of bindings for next halo fact and return rule and binding used to infer it. // also alters original list to ignore items with similar provenance (or non-halo items) int jhcAssocMem::next_halo (jhcAliaRule **r, jhcBindings **b, jhcBindings& list, int start) const { const jhcNetNode *item; int i, j, nb = list.NumPairs(); // scan through remainder of list for (i = start; i < nb; i++) { // ignore non-halo items or already removed nodes if ((item = list.GetSub(i)) == NULL) continue; if (!item->Halo()) continue; *r = item->hrule; *b = item->hbind; // edit tail of list to have only halo items with different provenance for (j = i + 1; j < nb; j++) if ((item = list.GetSub(j)) != NULL) if (!item->Halo() || ((item->hrule == *r) && (item->hbind == *b))) list.SetSub(j, NULL); break; } return i; // start next at index after this } /////////////////////////////////////////////////////////////////////////// // File Functions // /////////////////////////////////////////////////////////////////////////// //= Read a list of declarative rules from a file. // appends to existing rules unless add <= 0 // level: 0 = kernel, 1 = extras, 2 = previous accumulation // ignores actual rule IDs from file and assigns new ones // returns number of rules read, 0 or negative for problem int jhcAssocMem::Load (const char *fname, int add, int rpt, int level) { jhcTxtLine in; jhcAliaRule *r; int ans = 1, n = 0; // possibly clear old stuff then try to open file if (add <= 0) clear(); if (!in.Open(fname)) { jprintf(">>> Could not open rule file: %s !\n", fname); return -1; } // try reading rules from file while (ans >= 0) { // make and load a new rule, delete if parse error r = new jhcAliaRule; if ((ans = r->Load(in)) <= 0) { // delete and purge input if parse error if (!in.End()) jprintf("Bad syntax at line %d in: %s\n", in.Last(), fname); delete r; if (in.NextBlank() == NULL) break; } else { // add rule to list if not a duplicate (unlikely) r->lvl = level; if (AddRule(r, 0) <= 0) delete r; n++; } } // possibly announce result if (n > 0) jprintf(2, rpt, " %3d inference rules from: %s\n", n, fname); else jprintf(2, rpt, " -- no inference rules from: %s\n", fname); return n; } //= Save all current rules at or above some level to a file. // level: 0 = kernel, 1 = extras, 2 = previous accumulation, 3 = newly added // returns number of rules saved, negative for problem int jhcAssocMem::Save (const char *fname, int level) const { FILE *out; int cnt; if (fopen_s(&out, fname, "w") != 0) return -1; cnt = save_rules(out, level); fclose(out); return cnt; } //= Save all rules in order. // returns number saved int jhcAssocMem::save_rules (FILE *out, int level) const { jhcAliaRule *r = rules; int cnt = 0; while (r != NULL) { if (r->lvl >= level) if (r->Save(out, 2) > 0) cnt++; r = r->next; } return cnt; }
26.506702
101
0.533731
jconnell11
39f711193ec635d02d99c505ed9ce89ff864ab32
1,334
cpp
C++
lge/2014/oct/1-2/jang1-2.cpp
seirion/code
3b8bf79764107255185061cec33decbc2235d03a
[ "Apache-2.0" ]
13
2015-06-07T09:26:26.000Z
2019-05-01T13:23:38.000Z
lge/2014/oct/1-2/jang1-2.cpp
seirion/code
3b8bf79764107255185061cec33decbc2235d03a
[ "Apache-2.0" ]
null
null
null
lge/2014/oct/1-2/jang1-2.cpp
seirion/code
3b8bf79764107255185061cec33decbc2235d03a
[ "Apache-2.0" ]
4
2016-03-05T06:21:05.000Z
2017-02-17T15:34:18.000Z
// hyungyu.jang@lge.com // 1-2 #include <iostream> #include <cstdio> #include <cstring> #include <vector> using namespace std; const int MAXNUM = 1000 * 1000 * 1000; enum { NOW = 0, PRE, SAME, }; enum { LEFT = 0, RIGHT, }; int size; void solve() { int from(1), to, pre, now, check; scanf("%d %d", &to, &size); scanf("%d %d", &pre, &check); bool flag = false; for (int i = 1; i < size; i++) { scanf("%d %d", &now, &check); if (pre == now) { printf("%d ", to - from + 1); continue; } int small = min(pre, now); int large = max(pre, now); if (pre < now && check == NOW) check = RIGHT; else if (pre < now && check == PRE) check = LEFT; else if (pre > now && check == NOW) check = LEFT; else if (pre > now && check == PRE) check = RIGHT; if (check == RIGHT) { from = max(from, ((small + large) / 2) + 1); } else if (check == LEFT) { to = min(to, (small + large - 1) / 2); } else { to = from = (small + large) / 2; flag = true; } printf("%d ", to - from + 1); pre = now; } printf("\n"); } int main() { int t; scanf("%d", &t); for (int i = 0; i < t; i++) { solve(); } return 0; }
22.610169
58
0.447526
seirion
39f9fe1e1a8bf964be71b0f351308d2c7503dd93
5,089
cpp
C++
Tests/TEST_Innovation.cpp
Georg-S/Neuro-Evolution
64e7b3c2bf3c1654d595f03d55fd6b24153ed171
[ "BSD-3-Clause" ]
null
null
null
Tests/TEST_Innovation.cpp
Georg-S/Neuro-Evolution
64e7b3c2bf3c1654d595f03d55fd6b24153ed171
[ "BSD-3-Clause" ]
null
null
null
Tests/TEST_Innovation.cpp
Georg-S/Neuro-Evolution
64e7b3c2bf3c1654d595f03d55fd6b24153ed171
[ "BSD-3-Clause" ]
null
null
null
#include <gtest/gtest.h> #include <Innovation.h> #include <Genotype.h> TEST(TEST_Innovation, 0by0GenotypeCreates0Innovations) { nev::Innovation inno = nev::Innovation(); nev::Genotype geno = nev::Genotype(inno, 0, 0, 1); EXPECT_EQ(inno.getTotalInnovationsCount(), 0); } TEST(TEST_Innovation, 1by1GenotypeCreates2Innovations) { nev::Innovation inno = nev::Innovation(); nev::Genotype geno = nev::Genotype(inno, 1, 1, 1); EXPECT_EQ(inno.getTotalInnovationsCount(), 2); } TEST(TEST_Innovation, 1by1GenotypeCreates2NewLinkInnovations) { nev::Innovation inno = nev::Innovation(); nev::Genotype geno = nev::Genotype(inno, 1, 1, 1); EXPECT_EQ(inno.getCountOfNewLinkInnovations(), 2); } TEST(TEST_Innovation, 1by1GenotypeCreates0NewNeuronInnovations) { nev::Innovation inno = nev::Innovation(); nev::Genotype geno = nev::Genotype(inno, 1, 1, 1); EXPECT_EQ(inno.getCountOfNewNeuronInnovations(), 0); } TEST(TEST_Innovation, 2_1by1GenotypesCreate2Innovations) { nev::Innovation inno = nev::Innovation(); nev::Genotype geno = nev::Genotype(inno, 1, 1, 1); nev::Genotype geno2 = nev::Genotype(inno, 1, 1, 1); EXPECT_EQ(inno.getTotalInnovationsCount(), 2); } TEST(TEST_Innovation, 2by1GenotypeCreates3Innovations) { nev::Innovation inno = nev::Innovation(); nev::Genotype geno = nev::Genotype(inno, 2, 1, 1); EXPECT_EQ(inno.getTotalInnovationsCount(), 3); } TEST(TEST_Innovation, 2_2by1GenotypesCreate3Innovations) { nev::Innovation inno = nev::Innovation(); nev::Genotype geno = nev::Genotype(inno, 2, 1, 1); nev::Genotype geno2 = nev::Genotype(inno, 2, 1, 1); EXPECT_EQ(inno.getTotalInnovationsCount(), 3); } TEST(TEST_Innovation, addNeuronAddsNewNeuronInnovation) { nev::Innovation inno = nev::Innovation(); nev::Genotype geno = nev::Genotype(inno, 1, 1, 1); geno.randomlyAddNeuron(inno, 1.f); EXPECT_EQ(inno.getCountOfNewNeuronInnovations(), 1); } TEST(TEST_Innovation, addNeuronAddsNewNeuronInnovationAndTheSecondNetDoesntAddAInnovation) { nev::Innovation inno = nev::Innovation(); nev::Genotype geno = nev::Genotype(inno, 1, 1, 1); nev::Genotype geno2 = nev::Genotype(inno, 1, 1, 2); geno.randomlyAddNeuron(inno, 1.f); geno2.randomlyAddNeuron(inno, 1.f); EXPECT_EQ(inno.getCountOfNewNeuronInnovations(), 1); } TEST(TEST_Innovation, addNeuronAddsNewNeuronInnovationAndButOnlyOnce) { nev::Innovation inno = nev::Innovation(); for (int i = 0; i < 10; i++) { nev::Genotype geno = nev::Genotype(inno, 1, 1, 2); geno.randomlyAddNeuron(inno, 1.f); } EXPECT_EQ(inno.getCountOfNewNeuronInnovations(), 1); } TEST(TEST_Innovation, addNeuronAdds2MoreNewLinkInnovations) { nev::Innovation inno = nev::Innovation(); nev::Genotype geno = nev::Genotype(inno, 1, 1, 1); int previousCountLinkInnovations = inno.getCountOfNewLinkInnovations(); geno.randomlyAddNeuron(inno, 1.0); EXPECT_EQ(previousCountLinkInnovations + 2, inno.getCountOfNewLinkInnovations()); } TEST(TEST_Innovation, addNeuronAdds2MoreNewLinkInnovationsButOnlyOnce) { nev::Innovation inno = nev::Innovation(); nev::Genotype geno = nev::Genotype(inno, 1, 1, 1); int previousCountLinkInnovations = inno.getCountOfNewLinkInnovations(); for (int i = 0; i < 10; i++) { geno = nev::Genotype(inno, 1, 1, 1); geno.randomlyAddNeuron(inno, 1.0); } EXPECT_EQ(previousCountLinkInnovations + 2, inno.getCountOfNewLinkInnovations()); } TEST(TEST_Innovation, addNeuronAdds3MoreTotalInnovations) { nev::Innovation inno = nev::Innovation(); nev::Genotype geno = nev::Genotype(inno, 1, 1, 1); int previousTotalInnovations = inno.getTotalInnovationsCount(); geno = nev::Genotype(inno, 1, 1, 1); geno.randomlyAddNeuron(inno, 1.0); EXPECT_EQ(previousTotalInnovations + 3, inno.getTotalInnovationsCount()); } TEST(TEST_Innovation, addNeuronAdds3MoreTotalInnovationsOnlyOnce) { nev::Innovation inno = nev::Innovation(); nev::Genotype geno = nev::Genotype(inno, 1, 1, 1); int previousTotalInnovations = inno.getTotalInnovationsCount(); for (int i = 0; i < 10; i++) { geno = nev::Genotype(inno, 1, 1, 1); geno.randomlyAddNeuron(inno, 1.0); } EXPECT_EQ(previousTotalInnovations + 3, inno.getTotalInnovationsCount()); } TEST(TEST_Innovation, addLinkRecurrentAllowedAddsNewLinkInnovation) { nev::Innovation inno = nev::Innovation(); nev::Genotype geno = nev::Genotype(inno, 2, 1, 1); geno.randomlyAddNeuron(inno, 1.0); int previousCountLinkInnovations = inno.getCountOfNewLinkInnovations(); geno.randomlyAddLink(inno, 1.0, true); EXPECT_EQ(previousCountLinkInnovations + 1, inno.getCountOfNewLinkInnovations()); } TEST(TEST_Innovation, addLinkAddsNewLinkInnovationsOnlyOneTime) { std::srand(time(NULL)); nev::Innovation inno = nev::Innovation(); nev::Genotype geno = nev::Genotype(inno, 2, 1, 1); geno.randomlyAddNeuron(inno, 1.0); nev::Genotype geno2 = geno; for (int i = 0; i < 100; i++) geno.randomlyAddLink(inno, 1.0, false); int previousCountLinkInnovations = inno.getCountOfNewLinkInnovations(); for (int i = 0; i < 100; i++) geno.randomlyAddLink(inno, 1.0, false); EXPECT_EQ(previousCountLinkInnovations, inno.getCountOfNewLinkInnovations()); }
33.701987
92
0.744351
Georg-S
39fd82a8faf3c1338584adf0d2ea4d05e9ee19ff
280
cc
C++
06/25/25.cc
williamgherman/cpp-solutions
cf947b3b8f49fa3071fbee96f522a4228e4207b8
[ "BSD-Source-Code" ]
5
2019-08-01T07:52:27.000Z
2022-03-27T08:09:35.000Z
06/25/25.cc
williamgherman/cpp-solutions
cf947b3b8f49fa3071fbee96f522a4228e4207b8
[ "BSD-Source-Code" ]
1
2020-10-03T17:29:59.000Z
2020-11-17T10:03:10.000Z
06/25/25.cc
williamgherman/cpp-solutions
cf947b3b8f49fa3071fbee96f522a4228e4207b8
[ "BSD-Source-Code" ]
6
2019-08-24T08:55:56.000Z
2022-02-09T08:41:44.000Z
#include <cstdlib> #include <iostream> int main(int argc, char **argv) { if (argc != 3) { std::cout << "Usage: " << argv[0] << " STR1 STR2" << std::endl; return EXIT_FAILURE; } std::cout << argv[1] << argv[2] << std::endl; return EXIT_SUCCESS; }
20
71
0.535714
williamgherman
260640db0c41959f956b8cdd1eef6ad62d63e702
1,955
cpp
C++
Client/src/common/FileManifest.cpp
kluete/ddt3
b8bf3b6daf275ec025b0c4a6401576560b671a3d
[ "Apache-2.0" ]
6
2020-04-20T04:54:44.000Z
2022-02-13T01:24:10.000Z
Client/src/common/FileManifest.cpp
kluete/ddt3
b8bf3b6daf275ec025b0c4a6401576560b671a3d
[ "Apache-2.0" ]
null
null
null
Client/src/common/FileManifest.cpp
kluete/ddt3
b8bf3b6daf275ec025b0c4a6401576560b671a3d
[ "Apache-2.0" ]
1
2022-02-13T01:24:35.000Z
2022-02-13T01:24:35.000Z
// ddt common File Manifest class (wx-free for daemon) #include <cassert> #include <algorithm> #include <iomanip> // stream formatting flags (for MD5) #include <sstream> #include <fstream> #include "ddt/FileSystem.h" #include "ddt/FileManifest.h" using namespace std; using namespace LX; //---- vanilla CTOR ----------------------------------------------------------- FileManifest::FileManifest(const string &full_path) : m_Split(FileName::SplitFullPath(full_path)) { m_Size = 0; m_ModifyStamp = 0; m_NumLines = 0; } //---- InputStream CTOR ------------------------------------------------------- FileManifest::FileManifest(DataInputStream &dis) : FileManifest(dis.ReadString()) { // don't care about correctness here, is only for display in Client m_Size = dis.Read32(); m_NumLines = dis.Read32(); m_ModifyStamp = (time_t) dis.Read32(); } //---- Empty / Missing File --------------------------------------------------- // static FileManifest FileManifest::MissingFile(const string &fullname) { return FileManifest(fullname); } //---- Get FileName (name + ext) ---------------------------------------------- string FileManifest::GetFileName(void) const { return m_Split.GetFullName(); } //---- Fill Properties -------------------------------------------------------- bool FileManifest::FillProperties(void) { const string fullpath = m_Split.GetFullPath(); if (fullpath.empty()) return false; // empty path m_Size = FileName::GetFileSize(fullpath); m_ModifyStamp = FileName::GetFileModifyStamp(fullpath); m_NumLines = FileName::CountTextLines(fullpath); return true; // ok } //---- Serialize FileManifest ------------------------------------------------- // LX:: must be EXPLICIT here or won't link LX::DataOutputStream& operator<<(LX::DataOutputStream &dos, const LX::FileManifest &fm) { dos << fm.GetFileName() << fm.m_Size << fm.m_NumLines << (uint32_t) fm.m_ModifyStamp ; return dos; } // nada mas
25.064103
87
0.595908
kluete
260a3b1d9acb9403aaebe09c78128752132790c6
6,505
cpp
C++
Operations/albaOpReparentTo.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
9
2018-11-19T10:15:29.000Z
2021-08-30T11:52:07.000Z
Operations/albaOpReparentTo.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Operations/albaOpReparentTo.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
3
2018-06-10T22:56:29.000Z
2019-12-12T06:22:56.000Z
/*========================================================================= Program: ALBA (Agile Library for Biomedical Applications) Module: albaOpReparentTo Authors: Paolo Quadrani Copyright (c) BIC All rights reserved. See Copyright.txt or This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "albaDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include "albaOpReparentTo.h" #include "albaDecl.h" #include "albaEvent.h" #include "albaVMERoot.h" #include "mmuTimeSet.h" #include "albaTransformFrame.h" #include "albaSmartPointer.h" #include "albaVMELandmarkCloud.h" #include "albaAbsMatrixPipe.h" #include "albaView.h" #include "vtkPolyData.h" #include "vtkTransform.h" #include "vtkTransformPolyDataFilter.h" #include <vector> //---------------------------------------------------------------------------- albaCxxTypeMacro(albaOpReparentTo); //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- albaOpReparentTo::albaOpReparentTo(const wxString &label) : albaOp(label) //---------------------------------------------------------------------------- { m_OpType = OPTYPE_OP; m_Canundo = true; m_OldParent = NULL; m_TargetVme = NULL; glo_VmeForReparent = NULL; } //---------------------------------------------------------------------------- albaOpReparentTo::~albaOpReparentTo( ) //---------------------------------------------------------------------------- { } //---------------------------------------------------------------------------- bool albaOpReparentTo::Accept(albaVME*node) //---------------------------------------------------------------------------- { return (node != NULL && node->IsALBAType(albaVME) && !node->IsALBAType(albaVMERoot) /*&& !node->IsALBAType(albaVMEExternalData)*/); } //---------------------------------------------------------------------------- albaOp* albaOpReparentTo::Copy() //---------------------------------------------------------------------------- { albaOpReparentTo *cp = new albaOpReparentTo(m_Label); cp->m_OldParent = m_OldParent; return cp; } //---------------------------------------------------------------------------- bool albaOpReparentTo::VMEAcceptForReparent(albaVME *vme) { return (glo_VmeForReparent->GetParent() != vme && glo_VmeForReparent->CanReparentTo(vme)); } //---------------------------------------------------------------------------- void albaOpReparentTo::OpRun() //---------------------------------------------------------------------------- { glo_VmeForReparent = m_Input; if (m_TargetVme == NULL) { albaEvent e(this,VME_CHOOSE); e.SetPointer(&VMEAcceptForReparent); albaEventMacro(e); m_TargetVme = e.GetVme(); } int result = OP_RUN_CANCEL; if((m_TargetVme != NULL) && (m_Input->CanReparentTo(m_TargetVme))) result = OP_RUN_OK; albaEventMacro(albaEvent(this,result)); } //---------------------------------------------------------------------------- void albaOpReparentTo::SetTargetVme(albaVME *target) //---------------------------------------------------------------------------- { m_TargetVme = target; if((m_TargetVme == NULL) || !m_Input->CanReparentTo(m_TargetVme)) { albaMessage(_("Cannot re-parent to specified node"),_("Error"),wxICON_ERROR); albaEventMacro(albaEvent(this,OP_RUN_CANCEL)); } } //---------------------------------------------------------------------------- void albaOpReparentTo::OpDo() //---------------------------------------------------------------------------- { m_OldParent = m_Input->GetParent(); albaEvent e(this, VIEW_SELECTED); albaEventMacro(e); int showed = e.GetView() && e.GetView()->IsVmeShowed(m_Input); int reparentOK=ReparentTo(m_Input, m_TargetVme, m_OldParent); if (reparentOK == ALBA_OK) { albaEventMacro(albaEvent(this, VME_SELECT, m_Input)); if(showed) GetLogicManager()->VmeShow(m_Input, true); } else { albaLogMessage(_("Something went wrong while re-parenting (bad pointer or memory errors)")); } } //---------------------------------------------------------------------------- int albaOpReparentTo::ReparentTo(albaVME * input, albaVME * targetVme, albaVME * oldParent) { int num, t; mmuTimeVector input_time; mmuTimeVector target_time; mmuTimeVector time; albaTimeStamp cTime, startTime; input->GetAbsTimeStamps(input_time); targetVme->GetAbsTimeStamps(target_time); mmuTimeSet::Merge(input_time,target_time,time); num = time.size(); startTime = targetVme->GetTimeStamp(); std::vector< albaAutoPointer<albaMatrix> > new_input_pose; new_input_pose.resize(num); for (t = 0; t < num; t++) { new_input_pose[t] = albaMatrix::New(); } //change reference system albaSmartPointer<albaTransformFrame> transform; for (t = 0; t < num; t++) { cTime = time[t]; input->SetTimeStamp(cTime); targetVme->SetTimeStamp(cTime); oldParent->SetTimeStamp(cTime); transform->SetTimeStamp(cTime); albaMatrixPipe *mp = input->GetMatrixPipe(); if (mp == NULL) { transform->SetInput(input->GetOutput()->GetMatrix()); } else { transform->SetInput(mp); } transform->SetInputFrame(oldParent->GetAbsMatrixPipe()); transform->SetTargetFrame(targetVme->GetAbsMatrixPipe()); transform->Update(); new_input_pose[t]->DeepCopy(transform->GetMatrixPointer()); } input->SetTimeStamp(startTime); targetVme->SetTimeStamp(startTime); oldParent->SetTimeStamp(startTime); for (t = 0; t < num; t++) { input->SetMatrix(*new_input_pose[t]); } return input->ReparentTo(targetVme); } //---------------------------------------------------------------------------- void albaOpReparentTo::OpUndo() //---------------------------------------------------------------------------- { albaVME *tmp = m_TargetVme; m_TargetVme = m_OldParent; OpDo(); m_TargetVme = tmp; }
30.829384
133
0.517294
IOR-BIC
260abcb4b2833b6184df0480368fe78d3b3cf5d6
41,222
cpp
C++
Code/Engine/Render/Renderers/WorldRenderer.cpp
JuanluMorales/KRG
f3a11de469586a4ef0db835af4bc4589e6b70779
[ "MIT" ]
419
2022-01-27T19:37:43.000Z
2022-03-31T06:14:22.000Z
Code/Engine/Render/Renderers/WorldRenderer.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
2
2022-01-28T20:35:33.000Z
2022-03-13T17:42:52.000Z
Code/Engine/Render/Renderers/WorldRenderer.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
20
2022-01-27T20:41:02.000Z
2022-03-26T16:16:57.000Z
#include "WorldRenderer.h" #include "Engine/Render/Components/Component_EnvironmentMaps.h" #include "Engine/Render/Components/Component_Lights.h" #include "Engine/Render/Components/Component_StaticMesh.h" #include "Engine/Render/Components/Component_SkeletalMesh.h" #include "Engine/Render/Shaders/EngineShaders.h" #include "Engine/Render/Systems/WorldSystem_Renderer.h" #include "Engine/Core/Entity/Entity.h" #include "Engine/Core/Entity/EntityWorldUpdateContext.h" #include "Engine/Core/Entity/EntityWorld.h" #include "System/Render/RenderDefaultResources.h" #include "System/Render/RenderViewport.h" #include "System/Core/Profiling/Profiling.h" //------------------------------------------------------------------------- namespace KRG::Render { static Matrix ComputeShadowMatrix( Viewport const& viewport, Transform const& lightWorldTransform, float shadowDistance ) { Transform lightTransform = lightWorldTransform; lightTransform.SetTranslation( Vector::Zero ); Transform const invLightTransform = lightTransform.GetInverse(); //Get a modified camera view volume that has the shadow distance as the z far. // This will get us the appropriate corners to translate into light space. // To make these cascade, you do this in a loop and move the depth range along by your // cascade distance. KRG::Math::ViewVolume camVolume = viewport.GetViewVolume(); camVolume.SetDepthRange( FloatRange( 1.0f, shadowDistance ) ); Math::ViewVolume::VolumeCorners corners = camVolume.GetCorners(); // Translate into light space. for ( int32 i = 0; i < 8; i++ ) { corners.m_points[i] = invLightTransform.TransformPoint( corners.m_points[i] ); } // Note for understanding, cornersMin and cornersMax are in light space, not world space. Vector cornersMin = Vector::One * FLT_MAX; Vector cornersMax = Vector::One * -FLT_MAX; for ( int32 i = 0; i < 8; i++ ) { cornersMin = Vector::Min( cornersMin, corners.m_points[i] ); cornersMax = Vector::Max( cornersMax, corners.m_points[i] ); } Vector lightPosition = Vector::Lerp( cornersMin, cornersMax, 0.5f ); lightPosition = Vector::Select( lightPosition, cornersMax, Vector::Select0100 ); //force lightPosition to the "back" of the box. lightPosition = lightTransform.TransformPoint( lightPosition ); //Light position now in world space. lightTransform.SetTranslation( lightPosition ); //Assign to the lightTransform, now it's positioned above our view frustrum. Vector delta = cornersMax - cornersMin; float dim = Math::Max( delta.m_x, delta.m_z ); Math::ViewVolume lightViewVolume( Float2( dim ), FloatRange( 1.0, delta.m_y ), lightTransform.ToMatrix() ); Matrix viewProjMatrix = lightViewVolume.GetViewProjectionMatrix(); Matrix viewMatrix = lightViewVolume.GetViewMatrix(); Matrix projMatrix = lightViewVolume.GetProjectionMatrix(); Matrix viewProj = lightViewVolume.GetViewProjectionMatrix(); // TODO: inverse z??? return viewProj; } //------------------------------------------------------------------------- bool WorldRenderer::Initialize( RenderDevice* pRenderDevice ) { KRG_ASSERT( m_pRenderDevice == nullptr && pRenderDevice != nullptr ); m_pRenderDevice = pRenderDevice; TVector<RenderBuffer> cbuffers; RenderBuffer buffer; // Create Static Mesh Vertex Shader //------------------------------------------------------------------------- cbuffers.clear(); // World transform const buffer buffer.m_byteSize = sizeof( ObjectTransforms ); buffer.m_byteStride = sizeof( Matrix ); // Vector4 aligned buffer.m_usage = RenderBuffer::Usage::CPU_and_GPU; buffer.m_type = RenderBuffer::Type::Constant; buffer.m_slot = 0; cbuffers.push_back( buffer ); // Shaders auto const vertexLayoutDescStatic = VertexLayoutRegistry::GetDescriptorForFormat( VertexFormat::StaticMesh ); m_vertexShaderStatic = VertexShader( g_byteCode_VS_StaticPrimitive, sizeof( g_byteCode_VS_StaticPrimitive ), cbuffers, vertexLayoutDescStatic ); m_pRenderDevice->CreateShader( m_vertexShaderStatic ); // Create Skeletal Mesh Vertex Shader //------------------------------------------------------------------------- // Vertex shader constant buffer - contains the world view projection matrix and bone transforms buffer.m_byteSize = sizeof( Matrix ) * 255; // ( 1 WVP matrix + 255 bone matrices ) buffer.m_byteStride = sizeof( Matrix ); // Vector4 aligned buffer.m_usage = RenderBuffer::Usage::CPU_and_GPU; buffer.m_type = RenderBuffer::Type::Constant; buffer.m_slot = 0; cbuffers.push_back( buffer ); auto const vertexLayoutDescSkeletal = VertexLayoutRegistry::GetDescriptorForFormat( VertexFormat::SkeletalMesh ); m_vertexShaderSkeletal = VertexShader( g_byteCode_VS_SkinnedPrimitive, sizeof( g_byteCode_VS_SkinnedPrimitive ), cbuffers, vertexLayoutDescSkeletal ); pRenderDevice->CreateShader( m_vertexShaderSkeletal ); if ( !m_vertexShaderStatic.IsValid() ) { return false; } // Create Skybox Vertex Shader //------------------------------------------------------------------------- cbuffers.clear(); // Transform constant buffer buffer.m_byteSize = sizeof( Matrix ); buffer.m_byteStride = sizeof( Matrix ); // Vector4 aligned buffer.m_usage = RenderBuffer::Usage::CPU_and_GPU; buffer.m_type = RenderBuffer::Type::Constant; buffer.m_slot = 0; cbuffers.push_back( buffer ); auto const vertexLayoutDescNone = VertexLayoutRegistry::GetDescriptorForFormat( VertexFormat::None ); m_vertexShaderSkybox = VertexShader( g_byteCode_VS_Cube, sizeof( g_byteCode_VS_Cube ), cbuffers, vertexLayoutDescNone ); m_pRenderDevice->CreateShader( m_vertexShaderSkybox ); if ( !m_vertexShaderSkybox.IsValid() ) { return false; } // Create Pixel Shader //------------------------------------------------------------------------- cbuffers.clear(); // Pixel shader constant buffer - contains light info buffer.m_byteSize = sizeof( LightData ); buffer.m_byteStride = sizeof( LightData ); buffer.m_usage = RenderBuffer::Usage::CPU_and_GPU; buffer.m_type = RenderBuffer::Type::Constant; buffer.m_slot = 0; cbuffers.push_back( buffer ); buffer.m_byteSize = sizeof( MaterialData ); buffer.m_byteStride = sizeof( MaterialData ); buffer.m_usage = RenderBuffer::Usage::CPU_and_GPU; buffer.m_type = RenderBuffer::Type::Constant; buffer.m_slot = 1; cbuffers.push_back( buffer ); m_pixelShader = PixelShader( g_byteCode_PS_Lit, sizeof( g_byteCode_PS_Lit ), cbuffers ); m_pRenderDevice->CreateShader( m_pixelShader ); if ( !m_pixelShader.IsValid() ) { return false; } // Create Skybox Pixel Shader //------------------------------------------------------------------------- m_pixelShaderSkybox = PixelShader( g_byteCode_PS_Skybox, sizeof( g_byteCode_PS_Skybox ), cbuffers ); m_pRenderDevice->CreateShader( m_pixelShaderSkybox ); if ( !m_pixelShaderSkybox.IsValid() ) { return false; } // Create Picking-Enabled Pixel Shader //------------------------------------------------------------------------- buffer.m_byteSize = sizeof( PickingData ); buffer.m_byteStride = sizeof( PickingData ); buffer.m_usage = RenderBuffer::Usage::CPU_and_GPU; buffer.m_type = RenderBuffer::Type::Constant; buffer.m_slot = 2; cbuffers.push_back( buffer ); m_pixelShaderPicking = PixelShader( g_byteCode_PS_LitPicking, sizeof( g_byteCode_PS_LitPicking ), cbuffers ); m_pRenderDevice->CreateShader( m_pixelShaderPicking ); if ( !m_pixelShaderPicking.IsValid() ) { return false; } // Create Empty Pixel Shader //------------------------------------------------------------------------- cbuffers.clear(); m_emptyPixelShader = PixelShader( g_byteCode_PS_Empty, sizeof( g_byteCode_PS_Empty ), cbuffers ); m_pRenderDevice->CreateShader( m_emptyPixelShader ); if ( !m_emptyPixelShader.IsValid() ) { return false; } // Create BRDF Integration Compute Shader //------------------------------------------------------------------------- cbuffers.clear(); m_precomputeDFGComputeShader = ComputeShader( g_byteCode_CS_PrecomputeDFG, sizeof( g_byteCode_CS_PrecomputeDFG ), cbuffers ); m_pRenderDevice->CreateShader( m_precomputeDFGComputeShader ); if ( !m_precomputeDFGComputeShader.IsValid() ) { return false; } // Create blend state //------------------------------------------------------------------------- m_blendState.m_srcValue = BlendValue::SourceAlpha; m_blendState.m_dstValue = BlendValue::InverseSourceAlpha; m_blendState.m_blendOp = BlendOp::Add; m_blendState.m_blendEnable = true; m_pRenderDevice->CreateBlendState( m_blendState ); if ( !m_blendState.IsValid() ) { return false; } // Create rasterizer state //------------------------------------------------------------------------- m_rasterizerState.m_cullMode = CullMode::BackFace; m_rasterizerState.m_windingMode = WindingMode::CounterClockwise; m_rasterizerState.m_fillMode = FillMode::Solid; m_pRenderDevice->CreateRasterizerState( m_rasterizerState ); if ( !m_rasterizerState.IsValid() ) { return false; } // Set up samplers //------------------------------------------------------------------------- m_pRenderDevice->CreateSamplerState( m_bilinearSampler ); if ( !m_bilinearSampler.IsValid() ) { return false; } m_bilinearClampedSampler.m_addressModeU = TextureAddressMode::Clamp; m_bilinearClampedSampler.m_addressModeV = TextureAddressMode::Clamp; m_bilinearClampedSampler.m_addressModeW = TextureAddressMode::Clamp; m_pRenderDevice->CreateSamplerState( m_bilinearClampedSampler ); if ( !m_bilinearClampedSampler.IsValid() ) { return false; } m_shadowSampler.m_addressModeU = TextureAddressMode::Border; m_shadowSampler.m_addressModeV = TextureAddressMode::Border; m_shadowSampler.m_addressModeW = TextureAddressMode::Border; m_shadowSampler.m_borderColor = Float4( 1.0f ); m_pRenderDevice->CreateSamplerState( m_shadowSampler ); if ( !m_shadowSampler.IsValid() ) { return false; } // Set up input bindings //------------------------------------------------------------------------- m_pRenderDevice->CreateShaderInputBinding( m_vertexShaderStatic, vertexLayoutDescStatic, m_inputBindingStatic ); if ( !m_inputBindingStatic.IsValid() ) { return false; } m_pRenderDevice->CreateShaderInputBinding( m_vertexShaderSkeletal, vertexLayoutDescSkeletal, m_inputBindingSkeletal ); if ( !m_inputBindingSkeletal.IsValid() ) { return false; } // Set up pipeline states //------------------------------------------------------------------------- m_pipelineStateStatic.m_pVertexShader = &m_vertexShaderStatic; m_pipelineStateStatic.m_pPixelShader = &m_pixelShader; m_pipelineStateStatic.m_pBlendState = &m_blendState; m_pipelineStateStatic.m_pRasterizerState = &m_rasterizerState; m_pipelineStateStaticPicking = m_pipelineStateStatic; m_pipelineStateStaticPicking.m_pPixelShader = &m_pixelShaderPicking; m_pipelineStateSkeletal.m_pVertexShader = &m_vertexShaderSkeletal; m_pipelineStateSkeletal.m_pPixelShader = &m_pixelShader; m_pipelineStateSkeletal.m_pBlendState = &m_blendState; m_pipelineStateSkeletal.m_pRasterizerState = &m_rasterizerState; m_pipelineStateSkeletalPicking = m_pipelineStateSkeletal; m_pipelineStateSkeletalPicking.m_pPixelShader = &m_pixelShaderPicking; m_pipelineStateStaticShadow.m_pVertexShader = &m_vertexShaderStatic; m_pipelineStateStaticShadow.m_pPixelShader = &m_emptyPixelShader; m_pipelineStateStaticShadow.m_pBlendState = &m_blendState; m_pipelineStateStaticShadow.m_pRasterizerState = &m_rasterizerState; m_pipelineStateSkeletalShadow.m_pVertexShader = &m_vertexShaderSkeletal; m_pipelineStateSkeletalShadow.m_pPixelShader = &m_emptyPixelShader; m_pipelineStateSkeletalShadow.m_pBlendState = &m_blendState; m_pipelineStateSkeletalShadow.m_pRasterizerState = &m_rasterizerState; m_pipelineSkybox.m_pVertexShader = &m_vertexShaderSkybox; m_pipelineSkybox.m_pPixelShader = &m_pixelShaderSkybox; m_pRenderDevice->CreateTexture( m_precomputedBRDF, DataFormat::Float_R16G16, Float2( 512, 512 ), USAGE_UAV | USAGE_SRV ); // TODO: load from memory? m_pipelinePrecomputeBRDF.m_pComputeShader = &m_precomputeDFGComputeShader; // TODO create on directional light add and destroy on remove m_pRenderDevice->CreateTexture( m_shadowMap, DataFormat::Float_X32, Float2( 1536, 1536 ), USAGE_SRV | USAGE_RT_DS ); { auto const& renderContext = m_pRenderDevice->GetImmediateContext(); renderContext.SetPipelineState( m_pipelinePrecomputeBRDF ); renderContext.SetUnorderedAccess( PipelineStage::Compute, 0, m_precomputedBRDF.GetUnorderedAccessView() ); renderContext.Dispatch( 512 / 16, 512 / 16, 1 ); renderContext.ClearUnorderedAccess( PipelineStage::Compute, 0 ); } m_initialized = true; return true; } void WorldRenderer::Shutdown() { m_pipelineStateStatic.Clear(); m_pipelineStateSkeletal.Clear(); if ( m_inputBindingStatic.IsValid() ) { m_pRenderDevice->DestroyShaderInputBinding( m_inputBindingStatic ); } if ( m_inputBindingSkeletal.IsValid() ) { m_pRenderDevice->DestroyShaderInputBinding( m_inputBindingSkeletal ); } if ( m_rasterizerState.IsValid() ) { m_pRenderDevice->DestroyRasterizerState( m_rasterizerState ); } if ( m_blendState.IsValid() ) { m_pRenderDevice->DestroyBlendState( m_blendState ); } if ( m_bilinearSampler.IsValid() ) { m_pRenderDevice->DestroySamplerState( m_bilinearSampler ); } if ( m_shadowSampler.IsValid() ) { m_pRenderDevice->DestroySamplerState( m_shadowSampler ); } if ( m_bilinearClampedSampler.IsValid() ) { m_pRenderDevice->DestroySamplerState( m_bilinearClampedSampler ); } if ( m_vertexShaderStatic.IsValid() ) { m_pRenderDevice->DestroyShader( m_vertexShaderStatic ); } if ( m_vertexShaderSkeletal.IsValid() ) { m_pRenderDevice->DestroyShader( m_vertexShaderSkeletal ); } if ( m_pixelShader.IsValid() ) { m_pRenderDevice->DestroyShader( m_pixelShader ); } if ( m_emptyPixelShader.IsValid() ) { m_pRenderDevice->DestroyShader( m_emptyPixelShader ); } if ( m_vertexShaderSkybox.IsValid() ) { m_pRenderDevice->DestroyShader( m_vertexShaderSkybox ); } if ( m_pixelShaderSkybox.IsValid() ) { m_pRenderDevice->DestroyShader( m_pixelShaderSkybox ); } if ( m_precomputeDFGComputeShader.IsValid() ) { m_pRenderDevice->DestroyShader( m_precomputeDFGComputeShader ); } if ( m_precomputedBRDF.IsValid() ) { m_pRenderDevice->DestroyTexture( m_precomputedBRDF ); } if ( m_shadowMap.IsValid() ) { m_pRenderDevice->DestroyTexture( m_shadowMap ); } if ( m_pixelShaderPicking.IsValid() ) { m_pRenderDevice->DestroyShader( m_pixelShaderPicking ); } m_pRenderDevice = nullptr; m_initialized = false; } //------------------------------------------------------------------------- void WorldRenderer::SetMaterial( RenderContext const& renderContext, PixelShader& pixelShader, Material const* pMaterial ) { KRG_ASSERT( pMaterial != nullptr ); ViewSRVHandle const& defaultSRV = DefaultResources::GetDefaultTexture()->GetShaderResourceView(); // TODO: cache on GPU in buffer MaterialData materialData; materialData.m_surfaceFlags |= pMaterial->HasAlbedoTexture() ? MATERIAL_USE_ALBEDO_TEXTURE : materialData.m_surfaceFlags; materialData.m_surfaceFlags |= pMaterial->HasMetalnessTexture() ? MATERIAL_USE_METALNESS_TEXTURE : materialData.m_surfaceFlags; materialData.m_surfaceFlags |= pMaterial->HasRoughnessTexture() ? MATERIAL_USE_ROUGHNESS_TEXTURE : materialData.m_surfaceFlags; materialData.m_surfaceFlags |= pMaterial->HasNormalMapTexture() ? MATERIAL_USE_NORMAL_TEXTURE : materialData.m_surfaceFlags; materialData.m_surfaceFlags |= pMaterial->HasAOTexture() ? MATERIAL_USE_AO_TEXTURE : materialData.m_surfaceFlags; materialData.m_metalness = pMaterial->GetMetalnessValue(); materialData.m_roughness = pMaterial->GetRoughnessValue(); materialData.m_normalScaler = pMaterial->GetNormalScalerValue(); materialData.m_albedo = pMaterial->GetAlbedoValue().ToFloat4(); renderContext.WriteToBuffer( pixelShader.GetConstBuffer( 1 ), &materialData, sizeof( materialData ) ); renderContext.SetShaderResource( PipelineStage::Pixel, 0, ( materialData.m_surfaceFlags & MATERIAL_USE_ALBEDO_TEXTURE ) ? pMaterial->GetAlbedoTexture()->GetShaderResourceView() : defaultSRV ); renderContext.SetShaderResource( PipelineStage::Pixel, 1, ( materialData.m_surfaceFlags & MATERIAL_USE_NORMAL_TEXTURE ) ? pMaterial->GetNormalMapTexture()->GetShaderResourceView() : defaultSRV ); renderContext.SetShaderResource( PipelineStage::Pixel, 2, ( materialData.m_surfaceFlags & MATERIAL_USE_METALNESS_TEXTURE ) ? pMaterial->GetMetalnessTexture()->GetShaderResourceView() : defaultSRV ); renderContext.SetShaderResource( PipelineStage::Pixel, 3, ( materialData.m_surfaceFlags & MATERIAL_USE_ROUGHNESS_TEXTURE ) ? pMaterial->GetRoughnessTexture()->GetShaderResourceView() : defaultSRV ); renderContext.SetShaderResource( PipelineStage::Pixel, 4, ( materialData.m_surfaceFlags & MATERIAL_USE_AO_TEXTURE ) ? pMaterial->GetAOTexture()->GetShaderResourceView() : defaultSRV ); } void WorldRenderer::SetDefaultMaterial( RenderContext const& renderContext, PixelShader& pixelShader ) { ViewSRVHandle const& defaultSRV = DefaultResources::GetDefaultTexture()->GetShaderResourceView(); MaterialData materialData{}; materialData.m_surfaceFlags |= MATERIAL_USE_ALBEDO_TEXTURE; materialData.m_metalness = 0.0f; materialData.m_roughness = 0.0f; materialData.m_normalScaler = 1.0f; materialData.m_albedo = Float4::One; renderContext.WriteToBuffer( pixelShader.GetConstBuffer( 1 ), &materialData, sizeof( materialData ) ); renderContext.SetShaderResource( PipelineStage::Pixel, 0, defaultSRV ); renderContext.SetShaderResource( PipelineStage::Pixel, 1, defaultSRV ); renderContext.SetShaderResource( PipelineStage::Pixel, 2, defaultSRV ); renderContext.SetShaderResource( PipelineStage::Pixel, 3, defaultSRV ); renderContext.SetShaderResource( PipelineStage::Pixel, 4, defaultSRV ); } //------------------------------------------------------------------------- void WorldRenderer::SetupRenderStates( Viewport const& viewport, PixelShader* pShader, RenderData const& data ) { KRG_ASSERT( pShader != nullptr && pShader->IsValid() ); auto const& renderContext = m_pRenderDevice->GetImmediateContext(); renderContext.SetViewport( Float2( viewport.GetDimensions() ), Float2( viewport.GetTopLeftPosition() ) ); renderContext.SetDepthTestMode( DepthTestMode::On ); renderContext.SetSampler( PipelineStage::Pixel, 0, m_bilinearSampler ); renderContext.SetSampler( PipelineStage::Pixel, 1, m_bilinearClampedSampler ); renderContext.SetSampler( PipelineStage::Pixel, 2, m_shadowSampler ); renderContext.WriteToBuffer( pShader->GetConstBuffer( 0 ), &data.m_lightData, sizeof( data.m_lightData ) ); // Shadows if ( data.m_lightData.m_lightingFlags & LIGHTING_ENABLE_SUN_SHADOW ) { renderContext.SetShaderResource( PipelineStage::Pixel, 10, m_shadowMap.GetShaderResourceView() ); } else { renderContext.SetShaderResource( PipelineStage::Pixel, 10, DefaultResources::GetDefaultTexture()->GetShaderResourceView() ); } // Skybox if ( data.m_pSkyboxRadianceTexture ) { renderContext.SetShaderResource( PipelineStage::Pixel, 11, m_precomputedBRDF.GetShaderResourceView() ); renderContext.SetShaderResource( PipelineStage::Pixel, 12, data.m_pSkyboxRadianceTexture->GetShaderResourceView() ); } else { renderContext.SetShaderResource( PipelineStage::Pixel, 11, DefaultResources::GetDefaultTexture()->GetShaderResourceView() ); renderContext.SetShaderResource( PipelineStage::Pixel, 12, ViewSRVHandle{} ); // TODO: fix add default cubemap resource } } void WorldRenderer::RenderStaticMeshes( Viewport const& viewport, RenderTarget const& renderTarget, RenderData const& data ) { KRG_PROFILE_FUNCTION_RENDER(); auto const& renderContext = m_pRenderDevice->GetImmediateContext(); // Set primary render state and clear the render buffer //------------------------------------------------------------------------- PipelineState* pPipelineState = renderTarget.HasPickingRT() ? &m_pipelineStateStaticPicking : &m_pipelineStateStatic; SetupRenderStates( viewport, pPipelineState->m_pPixelShader, data ); renderContext.SetPipelineState( *pPipelineState ); renderContext.SetShaderInputBinding( m_inputBindingStatic ); renderContext.SetPrimitiveTopology( Topology::TriangleList ); //------------------------------------------------------------------------- for ( StaticMeshComponent const* pMeshComponent : data.m_staticMeshComponents ) { auto pMesh = pMeshComponent->GetMesh(); Matrix worldTransform = pMeshComponent->GetWorldTransform().ToMatrix(); ObjectTransforms transforms = data.m_transforms; transforms.m_worldTransform = worldTransform; transforms.m_worldTransform.SetTranslation( worldTransform.GetTranslation() ); transforms.m_normalTransform = transforms.m_worldTransform.GetInverse().Transpose(); renderContext.WriteToBuffer( m_vertexShaderStatic.GetConstBuffer( 0 ), &transforms, sizeof( transforms ) ); if ( renderTarget.HasPickingRT() ) { PickingData const pd( pMeshComponent->GetEntityID().m_ID, pMeshComponent->GetID().m_ID ); renderContext.WriteToBuffer( m_pixelShaderPicking.GetConstBuffer( 2 ), &pd, sizeof( PickingData ) ); } renderContext.SetVertexBuffer( pMesh->GetVertexBuffer() ); renderContext.SetIndexBuffer( pMesh->GetIndexBuffer() ); TVector<Material const*> const& materials = pMeshComponent->GetMaterials(); auto const numSubMeshes = pMesh->GetNumSections(); for ( auto i = 0u; i < numSubMeshes; i++ ) { if ( i < materials.size() && materials[i] ) { SetMaterial( renderContext, *pPipelineState->m_pPixelShader, materials[i] ); } else // Use default material { SetDefaultMaterial( renderContext, *pPipelineState->m_pPixelShader ); } auto const& subMesh = pMesh->GetSection( i ); renderContext.DrawIndexed( subMesh.m_numIndices, subMesh.m_startIndex ); } } renderContext.ClearShaderResource( PipelineStage::Pixel, 10 ); } void WorldRenderer::RenderSkeletalMeshes( Viewport const& viewport, RenderTarget const& renderTarget, RenderData const& data ) { KRG_PROFILE_FUNCTION_RENDER(); auto const& renderContext = m_pRenderDevice->GetImmediateContext(); // Set primary render state and clear the render buffer //------------------------------------------------------------------------- PipelineState* pPipelineState = renderTarget.HasPickingRT() ? &m_pipelineStateSkeletalPicking : &m_pipelineStateSkeletal; SetupRenderStates( viewport, pPipelineState->m_pPixelShader, data ); renderContext.SetPipelineState( *pPipelineState ); renderContext.SetShaderInputBinding( m_inputBindingSkeletal ); renderContext.SetPrimitiveTopology( Topology::TriangleList ); //------------------------------------------------------------------------- SkeletalMesh const* pCurrentMesh = nullptr; for ( SkeletalMeshComponent const* pMeshComponent : data.m_skeletalMeshComponents ) { if ( pMeshComponent->GetMesh() != pCurrentMesh ) { pCurrentMesh = pMeshComponent->GetMesh(); KRG_ASSERT( pCurrentMesh != nullptr && pCurrentMesh->IsValid() ); renderContext.SetVertexBuffer( pCurrentMesh->GetVertexBuffer() ); renderContext.SetIndexBuffer( pCurrentMesh->GetIndexBuffer() ); } // Update Bones and Transforms //------------------------------------------------------------------------- Matrix worldTransform = pMeshComponent->GetWorldTransform().ToMatrix(); ObjectTransforms transforms = data.m_transforms; transforms.m_worldTransform = worldTransform; transforms.m_worldTransform.SetTranslation( worldTransform.GetTranslation() ); transforms.m_normalTransform = transforms.m_worldTransform.GetInverse().Transpose(); renderContext.WriteToBuffer( m_vertexShaderSkeletal.GetConstBuffer( 0 ), &transforms, sizeof( transforms ) ); auto const& bonesConstBuffer = m_vertexShaderSkeletal.GetConstBuffer( 1 ); auto const& boneTransforms = pMeshComponent->GetSkinningTransforms(); KRG_ASSERT( boneTransforms.size() == pCurrentMesh->GetNumBones() ); renderContext.WriteToBuffer( bonesConstBuffer, boneTransforms.data(), sizeof( Matrix ) * pCurrentMesh->GetNumBones() ); if ( renderTarget.HasPickingRT() ) { PickingData const pd( pMeshComponent->GetEntityID().m_ID, pMeshComponent->GetID().m_ID ); renderContext.WriteToBuffer( m_pixelShaderPicking.GetConstBuffer( 2 ), &pd, sizeof( PickingData ) ); } // Draw sub-meshes //------------------------------------------------------------------------- TVector<Material const*> const& materials = pMeshComponent->GetMaterials(); auto const numSubMeshes = pCurrentMesh->GetNumSections(); for ( auto i = 0u; i < numSubMeshes; i++ ) { if ( i < materials.size() && materials[i] ) { SetMaterial( renderContext, *pPipelineState->m_pPixelShader, materials[i] ); } else // Use default material { SetDefaultMaterial( renderContext, *pPipelineState->m_pPixelShader ); } // Draw mesh auto const& subMesh = pCurrentMesh->GetSection( i ); renderContext.DrawIndexed( subMesh.m_numIndices, subMesh.m_startIndex ); } } renderContext.ClearShaderResource( PipelineStage::Pixel, 10 ); } void WorldRenderer::RenderSkybox( Viewport const& viewport, RenderData const& data ) { KRG_PROFILE_FUNCTION_RENDER(); auto const& renderContext = m_pRenderDevice->GetImmediateContext(); if ( data.m_pSkyboxTexture ) { Matrix const skyboxTransform = Matrix( Quaternion::Identity, viewport.GetViewPosition() ) * data.m_transforms.m_viewprojTransform; renderContext.SetViewport( Float2( viewport.GetDimensions() ), Float2( viewport.GetTopLeftPosition() ), Float2( 1, 1 )/*TODO: fix for inv z*/ ); renderContext.SetPipelineState( m_pipelineSkybox ); renderContext.SetShaderInputBinding( ShaderInputBindingHandle() ); renderContext.SetPrimitiveTopology( Topology::TriangleStrip ); renderContext.WriteToBuffer( m_vertexShaderSkybox.GetConstBuffer( 0 ), &skyboxTransform, sizeof( Matrix ) ); renderContext.WriteToBuffer( m_pixelShaderSkybox.GetConstBuffer( 0 ), &data.m_lightData, sizeof( data.m_lightData ) ); renderContext.SetShaderResource( PipelineStage::Pixel, 0, data.m_pSkyboxTexture->GetShaderResourceView() ); renderContext.Draw( 14, 0 ); } } void WorldRenderer::RenderSunShadows( Viewport const& viewport, DirectionalLightComponent* pDirectionalLightComponent, RenderData const& data ) { KRG_PROFILE_FUNCTION_RENDER(); auto const& renderContext = m_pRenderDevice->GetImmediateContext(); if ( !pDirectionalLightComponent || !pDirectionalLightComponent->GetShadowed() ) return; // Set primary render state and clear the render buffer //------------------------------------------------------------------------- renderContext.ClearDepthStencilView( m_shadowMap.GetDepthStencilView(), 1.0f/*TODO: inverse z*/, 0 ); renderContext.SetRenderTarget( m_shadowMap.GetDepthStencilView() ); renderContext.SetViewport( Float2( (float) m_shadowMap.GetDimensions().m_x, (float) m_shadowMap.GetDimensions().m_y ), Float2( 0.0f, 0.0f ) ); renderContext.SetDepthTestMode( DepthTestMode::On ); ObjectTransforms transforms; transforms.m_viewprojTransform = data.m_lightData.m_sunShadowMapMatrix; // Static Meshes //------------------------------------------------------------------------- renderContext.SetPipelineState( m_pipelineStateStaticShadow ); renderContext.SetShaderInputBinding( m_inputBindingStatic ); renderContext.SetPrimitiveTopology( Topology::TriangleList ); for ( StaticMeshComponent const* pMeshComponent : data.m_staticMeshComponents ) { auto pMesh = pMeshComponent->GetMesh(); Matrix worldTransform = pMeshComponent->GetWorldTransform().ToMatrix(); transforms.m_worldTransform = worldTransform; renderContext.WriteToBuffer( m_vertexShaderStatic.GetConstBuffer( 0 ), &transforms, sizeof( transforms ) ); renderContext.SetVertexBuffer( pMesh->GetVertexBuffer() ); renderContext.SetIndexBuffer( pMesh->GetIndexBuffer() ); auto const numSubMeshes = pMesh->GetNumSections(); for ( auto i = 0u; i < numSubMeshes; i++ ) { auto const& subMesh = pMesh->GetSection( i ); renderContext.DrawIndexed( subMesh.m_numIndices, subMesh.m_startIndex ); } } // Skeletal Meshes //------------------------------------------------------------------------- renderContext.SetPipelineState( m_pipelineStateSkeletalShadow ); renderContext.SetShaderInputBinding( m_inputBindingSkeletal ); renderContext.SetPrimitiveTopology( Topology::TriangleList ); for ( SkeletalMeshComponent const* pMeshComponent : data.m_skeletalMeshComponents ) { auto pMesh = pMeshComponent->GetMesh(); // Update Bones and Transforms //------------------------------------------------------------------------- Matrix worldTransform = pMeshComponent->GetWorldTransform().ToMatrix(); transforms.m_worldTransform = worldTransform; transforms.m_worldTransform.SetTranslation( worldTransform.GetTranslation() ); renderContext.WriteToBuffer( m_vertexShaderSkeletal.GetConstBuffer( 0 ), &transforms, sizeof( transforms ) ); auto const& bonesConstBuffer = m_vertexShaderSkeletal.GetConstBuffer( 1 ); auto const& boneTransforms = pMeshComponent->GetSkinningTransforms(); KRG_ASSERT( boneTransforms.size() == pMesh->GetNumBones() ); renderContext.WriteToBuffer( bonesConstBuffer, boneTransforms.data(), sizeof( Matrix ) * pMesh->GetNumBones() ); renderContext.SetVertexBuffer( pMesh->GetVertexBuffer() ); renderContext.SetIndexBuffer( pMesh->GetIndexBuffer() ); // Draw sub-meshes //------------------------------------------------------------------------- auto const numSubMeshes = pMesh->GetNumSections(); for ( auto i = 0u; i < numSubMeshes; i++ ) { // Draw mesh auto const& subMesh = pMesh->GetSection( i ); renderContext.DrawIndexed( subMesh.m_numIndices, subMesh.m_startIndex ); } } } //------------------------------------------------------------------------- void WorldRenderer::RenderWorld( Seconds const deltaTime, Viewport const& viewport, RenderTarget const& renderTarget, EntityWorld* pWorld ) { KRG_ASSERT( IsInitialized() && Threading::IsMainThread() ); KRG_PROFILE_FUNCTION_RENDER(); if ( !viewport.IsValid() ) { return; } //------------------------------------------------------------------------- auto pWorldSystem = pWorld->GetWorldSystem<RendererWorldSystem>(); KRG_ASSERT( pWorldSystem != nullptr ); //------------------------------------------------------------------------- RenderData renderData { ObjectTransforms(), LightData(), nullptr, nullptr, pWorldSystem->m_visibleStaticMeshComponents, pWorldSystem->m_visibleSkeletalMeshComponents, }; renderData.m_transforms.m_viewprojTransform = viewport.GetViewVolume().GetViewProjectionMatrix(); //------------------------------------------------------------------------- uint32 lightingFlags = 0; DirectionalLightComponent* pDirectionalLightComponent = nullptr; if ( !pWorldSystem->m_registeredDirectionLightComponents.empty() ) { pDirectionalLightComponent = pWorldSystem->m_registeredDirectionLightComponents[0]; lightingFlags |= LIGHTING_ENABLE_SUN; lightingFlags |= pDirectionalLightComponent->GetShadowed() ? LIGHTING_ENABLE_SUN_SHADOW : 0; renderData.m_lightData.m_SunDirIndirectIntensity = -pDirectionalLightComponent->GetLightDirection(); Float4 colorIntensity = pDirectionalLightComponent->GetLightColor(); renderData.m_lightData.m_SunColorRoughnessOneLevel = colorIntensity * pDirectionalLightComponent->GetLightIntensity(); // TODO: conditional renderData.m_lightData.m_sunShadowMapMatrix = ComputeShadowMatrix( viewport, pDirectionalLightComponent->GetWorldTransform(), 50.0f/*TODO: configure*/ ); } renderData.m_lightData.m_SunColorRoughnessOneLevel.m_w = 0; if ( !pWorldSystem->m_registeredGlobalEnvironmentMaps.empty() ) { GlobalEnvironmentMapComponent* pGlobalEnvironmentMapComponent = pWorldSystem->m_registeredGlobalEnvironmentMaps[0]; if ( pGlobalEnvironmentMapComponent->HasSkyboxRadianceTexture() && pGlobalEnvironmentMapComponent->HasSkyboxTexture() ) { lightingFlags |= LIGHTING_ENABLE_SKYLIGHT; renderData.m_pSkyboxRadianceTexture = pGlobalEnvironmentMapComponent->GetSkyboxRadianceTexture(); renderData.m_pSkyboxTexture = pGlobalEnvironmentMapComponent->GetSkyboxTexture(); renderData.m_lightData.m_SunColorRoughnessOneLevel.m_w = std::max( floor( log2f( (float) renderData.m_pSkyboxRadianceTexture->GetDimensions().m_x ) ) - 1.0f, 0.0f ); renderData.m_lightData.m_SunDirIndirectIntensity.m_w = pGlobalEnvironmentMapComponent->GetSkyboxIntensity(); renderData.m_lightData.m_manualExposure = pGlobalEnvironmentMapComponent->GetExposure(); } } int32 const numPointLights = Math::Min( pWorldSystem->m_registeredPointLightComponents.size(), (int32) s_maxPunctualLights ); uint32 lightIndex = 0; for ( int32 i = 0; i < numPointLights; ++i ) { KRG_ASSERT( lightIndex < s_maxPunctualLights ); PointLightComponent* pPointLightComponent = pWorldSystem->m_registeredPointLightComponents[i]; renderData.m_lightData.m_punctualLights[lightIndex].m_positionInvRadiusSqr = pPointLightComponent->GetLightPosition(); renderData.m_lightData.m_punctualLights[lightIndex].m_positionInvRadiusSqr.m_w = Math::Sqr( 1.0f / pPointLightComponent->GetLightRadius() ); renderData.m_lightData.m_punctualLights[lightIndex].m_dir = Vector::Zero; renderData.m_lightData.m_punctualLights[lightIndex].m_color = Vector( pPointLightComponent->GetLightColor() ) * pPointLightComponent->GetLightIntensity(); renderData.m_lightData.m_punctualLights[lightIndex].m_spotAngles = Vector( -1.0f, 1.0f, 0.0f ); ++lightIndex; } int32 const numSpotLights = Math::Min( pWorldSystem->m_registeredSpotLightComponents.size(), (int32) s_maxPunctualLights - numPointLights ); for ( int32 i = 0; i < numSpotLights; ++i ) { KRG_ASSERT( lightIndex < s_maxPunctualLights ); SpotLightComponent* pSpotLightComponent = pWorldSystem->m_registeredSpotLightComponents[i]; renderData.m_lightData.m_punctualLights[lightIndex].m_positionInvRadiusSqr = pSpotLightComponent->GetLightPosition(); renderData.m_lightData.m_punctualLights[lightIndex].m_positionInvRadiusSqr.m_w = Math::Sqr( 1.0f / pSpotLightComponent->GetLightRadius() ); renderData.m_lightData.m_punctualLights[lightIndex].m_dir = -pSpotLightComponent->GetLightDirection(); renderData.m_lightData.m_punctualLights[lightIndex].m_color = Vector( pSpotLightComponent->GetLightColor() ) * pSpotLightComponent->GetLightIntensity(); Radians innerAngle = pSpotLightComponent->GetLightInnerUmbraAngle().ToRadians(); Radians outerAngle = pSpotLightComponent->GetLightOuterUmbraAngle().ToRadians(); innerAngle.Clamp( 0, Math::PiDivTwo ); outerAngle.Clamp( 0, Math::PiDivTwo ); float cosInner = Math::Cos( (float) innerAngle ); float cosOuter = Math::Cos( (float) outerAngle ); renderData.m_lightData.m_punctualLights[lightIndex].m_spotAngles = Vector( cosOuter, 1.0f / Math::Max( cosInner - cosOuter, 0.001f ), 0.0f ); ++lightIndex; } renderData.m_lightData.m_numPunctualLights = lightIndex; //------------------------------------------------------------------------- renderData.m_lightData.m_lightingFlags = lightingFlags; #if KRG_DEVELOPMENT_TOOLS renderData.m_lightData.m_lightingFlags = renderData.m_lightData.m_lightingFlags | ( (int32) pWorldSystem->GetVisualizationMode() << (int32) RendererWorldSystem::VisualizationMode::BitShift ); #endif //------------------------------------------------------------------------- auto const& immediateContext = m_pRenderDevice->GetImmediateContext(); RenderSunShadows( viewport, pDirectionalLightComponent, renderData ); { immediateContext.SetRenderTarget( renderTarget ); RenderStaticMeshes( viewport, renderTarget, renderData ); RenderSkeletalMeshes( viewport, renderTarget, renderData ); } RenderSkybox( viewport, renderData ); } }
46.949886
206
0.631265
JuanluMorales
260cab96b4ac4c4611732dd55651a505ed14ef0a
1,299
hpp
C++
src/include/database.hpp
mjgerdes/cg
be378b140df7d7e9bd16512a1d9a54d3439b03f7
[ "MIT" ]
null
null
null
src/include/database.hpp
mjgerdes/cg
be378b140df7d7e9bd16512a1d9a54d3439b03f7
[ "MIT" ]
null
null
null
src/include/database.hpp
mjgerdes/cg
be378b140df7d7e9bd16512a1d9a54d3439b03f7
[ "MIT" ]
null
null
null
#ifndef __DB_DATABASE_HPP__ #define __DB_DATABASE_HPP__ #include <string> #include <memory> // std::auto_ptr #include <cstdlib> // std::exit #include <iostream> #include <odb/connection.hxx> #include <odb/transaction.hxx> #include <odb/schema-catalog.hxx> #include <odb/database.hxx> #if defined(DATABASE_MYSQL) #include <odb/mysql/database.hxx> #elif defined(DATABASE_SQLITE) #include <odb/sqlite/database.hxx> #elif defined(DATABASE_PGSQL) #include <odb/pgsql/database.hxx> #elif defined(DATABASE_ORACLE) #include <odb/oracle/database.hxx> #elif defined(DATABASE_MSSQL) #include <odb/mssql/database.hxx> #else #error unknown database; did you forget to define the DATABASE_* macros? #endif #include <odb/connection.hxx> #include <odb/transaction.hxx> #include <odb/schema-catalog.hxx> namespace db { using DBServer = odb::database; using DBServer_ptr = std::unique_ptr<DBServer>; inline DBServer_ptr makeDatabaseServer() { using namespace odb::core; #if defined(DATABASE_MYSQL) auto db = DBServer_ptr{ new odb::mysql::database("cgserver", "password", "cgserver_db")}; #endif { connection_ptr c(db->connection()); transaction t(c->begin()); schema_catalog::create_schema(*db); t.commit(); } return db; } // end makeDatabaseConnection } // end namespace db #endif
21.295082
72
0.745958
mjgerdes
2610fd7c51ddeb5bee360a3bff2075b8c642f833
2,520
hpp
C++
sprig/reference_holder.hpp
bolero-MURAKAMI/Sprig
51ce4db4f4d093dee659a136f47249e4fe91fc7a
[ "BSL-1.0" ]
2
2017-10-24T13:56:24.000Z
2018-09-28T13:21:22.000Z
sprig/reference_holder.hpp
bolero-MURAKAMI/Sprig
51ce4db4f4d093dee659a136f47249e4fe91fc7a
[ "BSL-1.0" ]
null
null
null
sprig/reference_holder.hpp
bolero-MURAKAMI/Sprig
51ce4db4f4d093dee659a136f47249e4fe91fc7a
[ "BSL-1.0" ]
2
2016-04-12T03:26:06.000Z
2018-09-28T13:21:22.000Z
/*============================================================================= Copyright (c) 2010-2016 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprig 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 SPRIG_REFERENCE_HOLDER_HPP #define SPRIG_REFERENCE_HOLDER_HPP #include <sprig/config/config.hpp> #ifdef SPRIG_USING_PRAGMA_ONCE # pragma once #endif // #ifdef SPRIG_USING_PRAGMA_ONCE #include <boost/utility/addressof.hpp> namespace sprig { // // reference_holder // template<typename T> class reference_holder { public: typedef T type; typedef type& reference; typedef type const& const_reference; typedef type* pointer; typedef type const* const_pointer; private: pointer target_; public: reference_holder() : target_(0) {} reference_holder(reference target) : target_(boost::addressof(target)) {} bool operator==(reference_holder const& rhs) const { return target_ == rhs.target_; } bool operator!=(reference_holder const& rhs) const { return target_ != rhs.target_; } operator reference() { return *target_; } operator const_reference() const { return *target_; } reference operator*() { return *target_; } const_reference operator*() const { return *target_; } pointer operator->() { return target_; } const_pointer operator->() const { return target_; } reference get() { return *target_; } const_reference get() const { return *target_; } pointer get_pointer() { return target_; } const_pointer get_pointer() const { return target_; } reference get_mutable() const { return *target_; } pointer get_mutable_pointer() const { return target_; } bool null() const { return target_; } }; // // make_reference_holder // template<typename T> SPRIG_INLINE reference_holder<T> make_reference_holder(T& target) { return reference_holder<T>(target); } template<typename T> SPRIG_INLINE reference_holder<T const> make_reference_holder(T const& target) { return reference_holder<T const>(target); } // // make_const_reference_holder // template<typename T> SPRIG_INLINE reference_holder<T const> make_const_reference_holder(T const& target) { return reference_holder<T const>(target); } } // namespace sprig #endif // #ifndef SPRIG_REFERENCE_HOLDER_HPP
22.909091
84
0.671429
bolero-MURAKAMI
26150332f445e811b38dea683b9f5007c4adb465
2,991
cpp
C++
ManagedScripts/MConversationMgrClass.cpp
mpforums/RenSharp
5b3fb8bff2a1772a82a4148bcf3e1265a11aa097
[ "Apache-2.0" ]
1
2021-10-04T02:34:33.000Z
2021-10-04T02:34:33.000Z
ManagedScripts/MConversationMgrClass.cpp
TheUnstoppable/RenSharp
2a123c6018c18f3fc73501737d600e291ac3afa7
[ "Apache-2.0" ]
9
2019-07-03T19:19:59.000Z
2020-03-02T22:00:21.000Z
ManagedScripts/MConversationMgrClass.cpp
TheUnstoppable/RenSharp
2a123c6018c18f3fc73501737d600e291ac3afa7
[ "Apache-2.0" ]
2
2019-08-14T08:37:36.000Z
2020-09-29T06:44:26.000Z
/* Copyright 2020 Neijwiert 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 "stdafx.h" #include "MConversationMgrClass.h" #pragma managed(push, off) #pragma warning(push) #pragma warning(disable : 4251 4244 26495 26454) class ConversationClass; class ConversationMgrClass : public SaveLoadSubSystemClass { public: static ::ConversationClass* Find_Conversation(const char* name); static ::ConversationClass* Find_Conversation(int id); }; RENEGADE_FUNCTION ::ConversationClass* ::ConversationMgrClass::Find_Conversation(const char* name) AT2(0x006D6C30, 0x006D64D0); RENEGADE_FUNCTION ::ConversationClass* ::ConversationMgrClass::Find_Conversation(int id) AT2(0x006D6C90, 0x006D6530); ::ConversationClass* Find_Conversation(const char* name) { return ::ConversationMgrClass::Find_Conversation(name); } ::ConversationClass* Find_Conversation(int id) { return ::ConversationMgrClass::Find_Conversation(id); } #pragma warning(pop) #pragma managed(pop) #include "MConversationClass.h" #include "RefCountClassUnmanagedContainer.h" namespace RenSharp { ConversationMgrClass::ConversationMgrClass(IntPtr pointer) : SaveLoadSubSystemClass(pointer) { } IUnmanagedContainer<IConversationClass^>^ ConversationMgrClass::FindConversation(String^ name) { if (name == nullptr) { throw gcnew ArgumentNullException("name"); } IntPtr nameHandle = Marshal::StringToHGlobalAnsi(name); try { auto result = Find_Conversation(reinterpret_cast<char*>(nameHandle.ToPointer())); if (result == nullptr) { return nullptr; } else { return gcnew RefCountClassUnmanagedContainer<IConversationClass^>(gcnew ConversationClass(IntPtr(result))); } } finally { Marshal::FreeHGlobal(nameHandle); } } IUnmanagedContainer<IConversationClass^>^ ConversationMgrClass::FindConversation(int id) { auto result = Find_Conversation(id); if (result == nullptr) { return nullptr; } else { return gcnew RefCountClassUnmanagedContainer<IConversationClass^>(gcnew ConversationClass(IntPtr(result))); } } IntPtr ConversationMgrClass::ConversationMgrClassPointer::get() { return IntPtr(InternalConversationMgrClassPointer); } ::SaveLoadSubSystemClass* ConversationMgrClass::InternalSaveLoadSubSystemClassPointer::get() { return InternalConversationMgrClassPointer; } ::ConversationMgrClass* ConversationMgrClass::InternalConversationMgrClassPointer::get() { return reinterpret_cast<::ConversationMgrClass*>(Pointer.ToPointer()); } }
25.347458
111
0.774657
mpforums
261755edb23d44a8eafffd27aa079fcfbf08eeb2
1,353
cpp
C++
Data Structure/Trees/Binary Trees/Diameter_of_Tree.cpp
Rupali409/CPP-Questions-and-Solutions
a42664302f18b7d99aac2501bcf956950e3cc61a
[ "MIT" ]
42
2021-09-26T18:02:52.000Z
2022-03-15T01:52:15.000Z
Data Structure/Trees/Binary Trees/Diameter_of_Tree.cpp
Rupali409/CPP-Questions-and-Solutions
a42664302f18b7d99aac2501bcf956950e3cc61a
[ "MIT" ]
404
2021-09-24T19:55:10.000Z
2021-11-03T05:47:47.000Z
Data Structure/Trees/Binary Trees/Diameter_of_Tree.cpp
Rupali409/CPP-Questions-and-Solutions
a42664302f18b7d99aac2501bcf956950e3cc61a
[ "MIT" ]
140
2021-09-22T20:50:04.000Z
2022-01-22T16:59:09.000Z
// 4. Calculate Diamter of a Binary Tree #include <bits/stdc++.h> using namespace std; struct Node { int data; Node* left; Node* right; Node(int d) { data = d; left = NULL; right = NULL; } }; // Function to calculate height of the tree int HeightOfTree(Node* root) { if (!root) return 0; int x = HeightOfTree(root->left); int y = HeightOfTree(root->right); return (max(x, y) + 1); } // Function to calculate Diameter of the tree int DiameterOfTree(Node* root) { if (!root) return 0; int lh = HeightOfTree(root->left); // Height of left subtree int rh = HeightOfTree(root->right); // Height of right subtree int Dia = lh + rh + 1; // Current diameter int ld = DiameterOfTree(root->left); // Diameter of left subtree int rd = DiameterOfTree(root->right); // Diameter of right subtree return max(Dia , max(ld, rd)); } int main() { Node* root = new Node(15); root->left = new Node(8); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(11); root->right->left = new Node(10); root->right->right = new Node(7); root->left->right->right = new Node(6); root->right->right->right = new Node(7); root->left->right->right->left = new Node(14); int ans = DiameterOfTree (root); cout << ans; return 0; }
19.608696
68
0.613452
Rupali409
261c5a92e4189690b8fac14ecbaa719d096eda73
3,601
hpp
C++
Graphics/DearImGUI/TreeNode.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
2
2021-06-09T00:38:46.000Z
2021-09-04T21:55:33.000Z
Graphics/DearImGUI/TreeNode.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
null
null
null
Graphics/DearImGUI/TreeNode.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
1
2021-08-30T00:46:12.000Z
2021-08-30T00:46:12.000Z
#ifndef LANDESSDEVCORE_GRAPHICS_IMGUI_TREE_NODE_HPP #define LANDESSDEVCORE_GRAPHICS_IMGUI_TREE_NODE_HPP #include "Graphics/DearImGUI/imgui.h" #include "TypeTraits/Detection.hpp" //#include "Definitions/Common.hpp" #include "Memory/ElementReference.h" #include "Graphics/DearImGUI/imgui.h" #include "Primitives/General/Context.h" #include "TypeTraits/Iterable.h" namespace LD { namespace IMGUI { template<typename StringType,typename T, class = void> class TreeNode; template<typename StringType,typename T> class TreeNode<StringType,T,LD::Enable_If_T< LD::Require< LD::Either<LD::Require<LD::Exists<LD::Detail::CamelCaseBegin,T>,LD::Exists<LD::Detail::CameCaseEnd,T>>,LD::Require<LD::Exists<LD::Detail::ReverseCamelCaseBegin,T>,LD::Exists<LD::Detail::ReverseCamelCaseEnd,T>>> >>> { private: using BackendType = LD::Detail::Conditional_T<(LD::Detail::IsLValueReference<T>::value),LD::ElementReference <LD::Detail::Decay_T<T>>,LD::Detail::Decay_T<T>>; StringType mName; BackendType mBackend; public: TreeNode() = default; TreeNode(StringType && stringType,T && iterable) noexcept:mName{LD::Forward<StringType>(stringType)}, mBackend{LD::Forward<T>(iterable)} { } void operator()(const LD::IMGUI::RenderingContext & context) const noexcept { if (ImGui::TreeNode(this->mName.Data())) { if constexpr (LD::CT::IsElementReference(LD::Type<BackendType>{})) { for(auto it = LD::Begin(*this->mBackend);it!=LD::End(*this->mBackend);++it) { const auto & object = (*it); using UsableType = LD::Detail::Decay_T<decltype(object)>; if constexpr (LD::CT::CanBeAnImmutableString(LD::CT::RemoveQualifiers(LD::Type<UsableType>{}))) { auto string = LD::ToImmutableString((object)); ImGui::Text(string.Data()); }else if constexpr (LD::ConvertiblyCallable<UsableType,void(const LD::IMGUI::RenderingContext&)>::Value()) { object(context); } } }else { for(auto it = LD::Begin(this->mBackend);it!=LD::End(this->mBackend);++it) { const auto & object = (*it); using UsableType = decltype(object); if constexpr (LD::CT::CanBeAnImmutableString(LD::CT::RemoveQualifiers(LD::Type<UsableType>{}))) { auto string = LD::ToImmutableString((object)); ImGui::Text(string.Data()); }else if constexpr (LD::ConvertiblyCallable<UsableType,void(const LD::IMGUI::RenderingContext&)>::Value()) { object(context); } } } ImGui::TreePop(); } } }; template<typename StringType,typename T> TreeNode(StringType &&, T &&) -> TreeNode<StringType,T>; } } #endif
43.385542
218
0.49764
jlandess
261e607662e74d1f121e01dafee0d42b5eeeaa02
2,469
hpp
C++
src/gl_utils/FrameBufferObject.hpp
gchatelet/gl_utils
8691b8c4719efc6ec0a8ee4c0d4e1f1c8c141eac
[ "MIT" ]
2
2018-08-05T13:57:57.000Z
2020-01-08T16:11:37.000Z
src/gl_utils/FrameBufferObject.hpp
gchatelet/gl_utils
8691b8c4719efc6ec0a8ee4c0d4e1f1c8c141eac
[ "MIT" ]
null
null
null
src/gl_utils/FrameBufferObject.hpp
gchatelet/gl_utils
8691b8c4719efc6ec0a8ee4c0d4e1f1c8c141eac
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // /// Class to perform the management of an opengl FBO /// Typical use : Render to Texture /// Typical usage : /// GlFrameBufferObject fbo; /// fbo.bind(); /// fbo.attachTexture(GL_COLOR_ATTACHMENT0_EXT,... texId0); /// fbo.attachTexture(GL_COLOR_ATTACHMENT1_EXT,... texId1); /// fbo.checkFramebufferStatus(); // must return true /// ... drawing operations /// fbo.unbind(); /// to desactivate the FBO use GlFrameBufferObject::Disable(); /// Desactivate the FBO and release hand to OPENGL standard FrameBuffer object /// //////////////////////////////////////////////////////////////////////////////// #pragma once #include "RAIIBase.h" namespace gl { class FrameBufferObject : public ::gl::utils::GlObject { mutable GLint m_OldFboID; //The ID of the old FBO when we will bind our instance FBO (it's to restore the old FBO) public: FrameBufferObject(void); virtual ~FrameBufferObject(void); /// Bind this FBO as current render target virtual void bind() const; virtual void unbind() const; public: /// Bind a texture to the "attachment" point of this FBO (GL_COLOR_ATTACHMENT0, textarget, texID) /// A fbo must be binded. void attachTexture( GLenum attachment, GLenum texType, GLuint texId, int mipLevel = 0, int zSlice = 0); //-------------------------------------------------------------------- //Hardware capabilities -> Be carefull (initialize Opengl before calling those funcs) //--------------------- //Check if the active FBO is ready to do a render task static bool checkFramebufferStatus(); // BEGIN : Static methods global to all FBOs // Return number of color attachments permitted static int getMaxColorAttachments(); //-------------------------------------------------------------------- /// Disable all FBO rendering and return to classic opengl framebuffer pipeline /// NOTE: /// This is NOT an "unbind" for this specific FBO, but rather /// disables all FBO rendering. This call is intentionally "static" /// and named "Disable" instead of "Unbind" for this reason. The /// motivation for this strange semantic is performance. Providing "Unbind" /// would likely lead to a large number of unnecessary FBO enablings/disabling. static void disable(); /// END : Static methods global to all FBOs }; } /* namespace gl */
37.409091
116
0.601458
gchatelet
261ee0107040e37094dbdc4bcca389c25ed9af9e
2,365
cpp
C++
Stack/Stack_20_Minimum_of_Stack_Constant_Space.cpp
compl3xX/ROAD-TO-DSA
2261c112135a51d9d88c4b57e6f062f6b32550a7
[ "MIT" ]
null
null
null
Stack/Stack_20_Minimum_of_Stack_Constant_Space.cpp
compl3xX/ROAD-TO-DSA
2261c112135a51d9d88c4b57e6f062f6b32550a7
[ "MIT" ]
null
null
null
Stack/Stack_20_Minimum_of_Stack_Constant_Space.cpp
compl3xX/ROAD-TO-DSA
2261c112135a51d9d88c4b57e6f062f6b32550a7
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <stack> using namespace std; class MinStack { stack<int> data; int minVal; public: int size() { return data.size(); } public: void push(int val) { if (data.size() == 0) { data.push(val); minVal = val; } else if (val >= minVal) { data.push(val); } else { data.push(val + val - minVal); minVal = val; } } public: int pop() { if (data.size() == 0) { cout << "Stack underflow" << endl; return -1; } else if (data.top() < minVal) { int preV = minVal; minVal = 2 * minVal - data.top(); data.pop(); return preV; } else { int temp = data.top(); data.pop(); return temp; } } public: int top() { if (data.size() == 0) { cout << "Stack underflow" << endl; return -1; } else if (data.top() < minVal) { return minVal; } else { return data.top(); } } public: int min() { if (data.size() == 0) { cout << "Stack underflow" << endl; return -1; } else { return minVal; } } }; int main() { MinStack st; string str; cin >> str; while (str != "quit") { if (str == "push") { int val; cin >> val; st.push(val); } else if (str == "pop") { int val = st.pop(); if (val != -1) { cout << val << endl; } } else if (str == "top") { int val = st.top(); if (val != -1) { cout << val << endl; } } else if (str == "size") { cout << st.size() << endl; } else if (str == "min") { int val = st.min(); if (val != -1) { cout << val << endl; } } cin >> str; } }
16.77305
46
0.329387
compl3xX
2626924aa395369a68b7fdbf66e294e4afbc8bf0
431
hpp
C++
app/src/main/cpp/linux/LinuxFilesManager.hpp
simonppg/break_it_all
95e8f2df935e35a3aa851bc981f81e06623c49f6
[ "MIT" ]
null
null
null
app/src/main/cpp/linux/LinuxFilesManager.hpp
simonppg/break_it_all
95e8f2df935e35a3aa851bc981f81e06623c49f6
[ "MIT" ]
15
2021-09-23T23:46:54.000Z
2022-03-02T06:04:51.000Z
app/src/main/cpp/linux/LinuxFilesManager.hpp
simonppg/break_it_all
95e8f2df935e35a3aa851bc981f81e06623c49f6
[ "MIT" ]
2
2019-05-23T23:03:06.000Z
2020-06-14T15:33:59.000Z
// Copyright (c) 2021 Simon Puente #ifndef APP_SRC_MAIN_CPP_LINUX_LINUXFILESMANAGER_HPP_ #define APP_SRC_MAIN_CPP_LINUX_LINUXFILESMANAGER_HPP_ #include "../shared/FilesManager.hpp" class LinuxFilesManager : public FilesManager { private: const char *projectPath; public: explicit LinuxFilesManager(const char *projectPath); char *loadFile(const char *filePath); }; #endif // APP_SRC_MAIN_CPP_LINUX_LINUXFILESMANAGER_HPP_
25.352941
55
0.816705
simonppg
262a7a8d15925fdb781b302671f8684aa1c65168
567
cpp
C++
0441_Arranging Coins.cpp
RickTseng/Cpp_LeetCode
6a710b8abc268eba767bc17d91d046b90a7e34a9
[ "MIT" ]
1
2021-09-13T00:58:59.000Z
2021-09-13T00:58:59.000Z
0441_Arranging Coins.cpp
RickTseng/Cpp_LeetCode
6a710b8abc268eba767bc17d91d046b90a7e34a9
[ "MIT" ]
null
null
null
0441_Arranging Coins.cpp
RickTseng/Cpp_LeetCode
6a710b8abc268eba767bc17d91d046b90a7e34a9
[ "MIT" ]
null
null
null
#include <vector> #include <stdio.h> #include <stdlib.h> #include <string> #include <map> #include <algorithm> #include <stack> #include <queue> #include <iostream> using namespace std; class Solution { public: int arrangeCoins(int n) { long long b = 1; int count = 0; while (n>=0) { n -=b; if(n>=0){ count++; } b++; } return count; } }; int main() { Solution sol; int ans = sol.arrangeCoins(2147000000); } /* 1 <= n <= 2^31 - 1 */
14.175
43
0.488536
RickTseng
1c7b69efd635431047df4beb5774ef6d48f577c8
4,566
cc
C++
test/rtc_call_test.cc
lichao2014/rtc_call
3084df96c4986d0fa37f476f72e4c2cdc05857ca
[ "Apache-2.0" ]
3
2018-07-24T08:16:38.000Z
2018-08-03T02:16:11.000Z
test/rtc_call_test.cc
lichao2014/rtc_call
3084df96c4986d0fa37f476f72e4c2cdc05857ca
[ "Apache-2.0" ]
null
null
null
test/rtc_call_test.cc
lichao2014/rtc_call
3084df96c4986d0fa37f476f72e4c2cdc05857ca
[ "Apache-2.0" ]
1
2018-07-24T08:16:44.000Z
2018-07-24T08:16:44.000Z
#include <iostream> #include <thread> #include <chrono> #include <atomic> #include "rtc_base/flags.h" #include "rtc_base/logging.h" #include "rtc_base/logsinks.h" #include "rtc_base/fileutils.h" #include "rtc_call_interface.h" #include "render/interface.h" #include "render/sdl_util.h" DEFINE_bool(help, false, "print help info"); DEFINE_string(slog, "rtc_session_test.log", "session log file"); DEFINE_string(log, "rtc_log", "call log"); DEFINE_string(stun, "turn:101.132.33.178:3391", "ice server"); DEFINE_string(name, nullptr, "my name"); DEFINE_string(peer, nullptr, "peer name"); DEFINE_string(domain, "101.132.33.178", "login server"); DEFINE_int(sport, 3390, "login port"); DEFINE_int(port, 4455, "login port"); struct CallEnv : rtc::CallEngineOptions { std::shared_ptr<rtc::CallEngineInterface> call_engine; rtc::CallUserOptions comm_user_options; bool Init() { call_engine = rtc::CreateCallEngine(*this); return (bool)call_engine; } rtc::CallUserOptions MakeUserOptions(const std::string& name, const std::string& pwd = "123456") { auto user_config = comm_user_options; user_config.name = name; user_config.password = pwd; return user_config; } static std::unique_ptr<CallEnv> CreateDefault() { auto env = std::make_unique<CallEnv>(); env->session.udp_port = FLAG_port; rtc::IceServer ice_server; ice_server.urls.push_back(FLAG_stun); ice_server.username = FLAG_name; ice_server.password = "123456"; env->ice_servers.push_back(ice_server); env->session.login_keepalive_sec = 60; env->comm_user_options.domain = FLAG_domain; env->comm_user_options.login_server_port = FLAG_sport; env->Init(); return env; } }; class CallUser : public rtc::CallUserObserver , public rtc::CallObserver { public: explicit CallUser(CallEnv *env, const std::string& name) { video_renderer_ = rtc::VideoRendererInterface::Create(name.c_str(), 400, 500); user_ = env->call_engine->CreateUser(env->MakeUserOptions(name), this); } explicit CallUser(CallEnv *env, const std::string& name, const std::string& peer) { video_renderer_ = rtc::VideoRendererInterface::Create(name.c_str(), 400, 500); peer_ = peer; user_ = env->call_engine->CreateUser(env->MakeUserOptions(name), this); CheckCall(); } private: void OnLogin(bool ok) override { login_success_ = ok; CheckCall(); } void CheckCall() { if (login_success_ && user_ && !peer_.empty()) { call_ = user_->MakeCall(peer_, this); } } CallObserver *OnCallee(std::shared_ptr<rtc::CallInterface> callee) override { call_ = callee; return this; } void OnError() override { } std::unique_ptr<rtc::I420VideoSinkInterface> OnAddStream( bool remote, const std::string&stream_label, const std::string&track_id) { if (remote) { return video_renderer_->CreateSink(0, 0, 0.8, 0.8); } else { return video_renderer_->CreateSink(0.8, 0.8, 0.2, 0.2); } } std::shared_ptr<rtc::CallUserInterface> user_; std::shared_ptr<rtc::CallInterface> call_; std::string peer_; bool login_success_ = false; std::shared_ptr<rtc::VideoRendererInterface> video_renderer_; }; int main(int argc, char *argv[]) { std::atomic_init rtc::FlagList::SetFlagsFromCommandLine(&argc, argv, false); if (FLAG_help) { rtc::FlagList::Print(nullptr, true); return 0; } auto call_session_log = new rtc::FileRotatingLogSink(FLAG_log, "rtc_call", std::numeric_limits<uint16_t>::max(), 64); if (!call_session_log->Init()) { return -1; } rtc::LogMessage::LogThreads(); rtc::LogMessage::LogTimestamps(); rtc::LogMessage::AddLogToStream(call_session_log, rtc::LS_INFO); RTC_LOG(LS_INFO) << "webrtc log test" << std::endl; //rtc_session::SetLogger("file", "STACK", FLAG_slog); rtc::SDLInitializer _sdl_initializer; auto env = CallEnv::CreateDefault(); std::unique_ptr<CallUser> user; if (FLAG_peer) { user.reset(new CallUser(env.get(), FLAG_name, FLAG_peer)); } else { user.reset(new CallUser(env.get(), FLAG_name)); } rtc::SDLLoop(); return 0; }
29.458065
122
0.627464
lichao2014
1c7f4e86667ac807cb4c5f74a7eaeec045733185
2,812
cpp
C++
tcpip/tcpip_tx.cpp
UndefeatedSunny/sc-platform
5897c460bf7a4b9694324f09d2492f5e157a3955
[ "Apache-2.0" ]
8
2021-06-03T15:22:26.000Z
2022-03-18T19:09:10.000Z
tcpip/tcpip_tx.cpp
UndefeatedSunny/sc-platform
5897c460bf7a4b9694324f09d2492f5e157a3955
[ "Apache-2.0" ]
null
null
null
tcpip/tcpip_tx.cpp
UndefeatedSunny/sc-platform
5897c460bf7a4b9694324f09d2492f5e157a3955
[ "Apache-2.0" ]
1
2021-11-17T15:01:44.000Z
2021-11-17T15:01:44.000Z
#include "tcpip/tcpip_tx.hpp" // Nothing here except syntax check and self-test/example #ifdef TCPIP_EXAMPLE using namespace std; using namespace sc_core; #include "tcpip/tcpip_tx.hpp" #include "report/report.hpp" #include "report/summary.hpp" #include <iostream> SC_MODULE( Top_module ) { char const * const MSGID{ "/Doulos/Example/Config_example" }; //---------------------------------------------------------------------------- SC_CTOR( Top_module ) { SC_THREAD( test_thread ); } //---------------------------------------------------------------------------- void test_thread( void ) { string text = "Hello\nworld\n!\n"; Async_payload<string> msg{ Asynk_kind::stream, text }; tx.put( msg ); msg.set_data( string("Goodbye!") ); tx.put( msg ); sc_stop(); } // Local channels Tcpip_tx_channel tx{ "Tx", 0xE5C0ul }; // Attributes }; int sc_main( int argc, char* argv[] ) { for(int i=1; i<sc_core::sc_argc(); ++i) { std::string arg(sc_core::sc_argv()[i]); if (arg == "-debug") { sc_core::sc_report_handler::set_verbosity_level(SC_DEBUG); SC_REPORT_INFO( "/Doulos/Example/config_example", "Verbosity level set to DEBUG" ); } } //---------------------------------------------------------------------------- // Elaborate //---------------------------------------------------------------------------- Summary::starting_elaboration(); Top_module top( "top" ); if( Summary::errors() != 0 ) { return Summary::report(); } //---------------------------------------------------------------------------- // Begin simulator //---------------------------------------------------------------------------- sc_start(); //---------------------------------------------------------------------------- // Clean up //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- if ( not sc_end_of_simulation_invoked() ) { REPORT( INFO, "\nError: Simulation stopped without explicit sc_stop()" ); Summary::increment_errors(); try { sc_stop(); //< this will invoke end_of_simulation() callbacks Summary::finished_simulation(); // update } catch ( sc_exception& e ) { REPORT( WARNING, "Caught exception while stopping.\n" << e.what() ); } catch(...) { REPORT( WARNING, "Error: Caught unknown exception while stopping." ); Summary::increment_errors(); } }//endif }//endif return Summary::report(); } #endif //------------------------------------------------------------------------------ // Copyright 2019 by Doulos. All rights reserved. // For licensing information concerning this document see LICENSE-APACHE.txt. //END tcpip_tx.cpp @(#)$Id$
29.6
89
0.46266
UndefeatedSunny
1c82aabc0d002270385ca99dbfd43f78cab9c264
1,364
cpp
C++
Source/MultiverseLegends/Private/Ability Core/Ability Types/MLGameplayAbility.cpp
yasinallahdev/multiverse-legends
62b1562078b5c4882b581088b51ec153ec81dd2d
[ "MIT" ]
1
2020-05-26T14:09:09.000Z
2020-05-26T14:09:09.000Z
Source/MultiverseLegends/Private/Ability Core/Ability Types/MLGameplayAbility.cpp
yasinallahdev/multiverse-legends
62b1562078b5c4882b581088b51ec153ec81dd2d
[ "MIT" ]
null
null
null
Source/MultiverseLegends/Private/Ability Core/Ability Types/MLGameplayAbility.cpp
yasinallahdev/multiverse-legends
62b1562078b5c4882b581088b51ec153ec81dd2d
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "MLGameplayAbility.h" #include "Ability Core/Cooldown Effects/CooldownGameplayEffect.h" #include "Ability Core/Cost Effects/CostGameplayEffect.h" UMLGameplayAbility::UMLGameplayAbility() { CooldownGameplayEffectClass = UCooldownGameplayEffect::StaticClass(); CostGameplayEffectClass = UCostGameplayEffect::StaticClass(); } const FGameplayTagContainer* UMLGameplayAbility::GetCooldownTags() const { FGameplayTagContainer* MutableTags = const_cast<FGameplayTagContainer*>(&TempCooldownTags); const FGameplayTagContainer* ParentTags = Super::GetCooldownTags(); if (ParentTags) { MutableTags->AppendTags(*ParentTags); } MutableTags->AppendTags(CooldownTags); return MutableTags; } void UMLGameplayAbility::ApplyCooldown(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo * ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo) const { UCooldownGameplayEffect* CooldownGE = Cast<UCooldownGameplayEffect>(GetCooldownGameplayEffect()); if (CooldownGE) { FGameplayEffectSpecHandle SpecHandle = MakeOutgoingGameplayEffectSpec(CooldownGE->GetClass(), GetAbilityLevel()); SpecHandle.Data.Get()->DynamicGrantedTags.AppendTags(CooldownTags); ApplyGameplayEffectSpecToOwner(Handle, ActorInfo, ActivationInfo, SpecHandle); } }
37.888889
185
0.821114
yasinallahdev
1c84ebace2d4909d2da93c09981367b4ad73af5b
12,986
cpp
C++
src/engine/core.cpp
beyerleinf/3d-raycasting-game
03ffbe9efd5034f4cfcb22bcf87a6d38ea4f572e
[ "MIT" ]
null
null
null
src/engine/core.cpp
beyerleinf/3d-raycasting-game
03ffbe9efd5034f4cfcb22bcf87a6d38ea4f572e
[ "MIT" ]
null
null
null
src/engine/core.cpp
beyerleinf/3d-raycasting-game
03ffbe9efd5034f4cfcb22bcf87a6d38ea4f572e
[ "MIT" ]
null
null
null
#include "engine/core.hpp" #include <stdio.h> namespace ray3d { Core::Core(SDL_Renderer *r, int screenW, int screenH) { player = new Player(22, 12, -1, 0); world = new World(); world->load(); screenWidth = screenW; screenHeight = screenH; renderer = r; } Core::~Core() { SDL_DestroyTexture(framebuffer); } bool Core::init() { bool result = true; framebuffer = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STREAMING, screenWidth, screenHeight); textures[0] = IMG_Load("res/tex/test.png"); textures[1] = IMG_Load("res/tex/tex2.png"); if (textures[0] == NULL || textures[1] == NULL) { printf("Failed to load textures. SDL Error: %s\n", IMG_GetError()); } // Initialize the game loop bool quit = false; SDL_Event event; while (!quit) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { quit = true; } if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_ESCAPE) { quit = true; } } if (event.type == SDL_MOUSEMOTION) { handleMouseMovement(event.motion); } } handleKeyboardEvent(SDL_GetKeyboardState(NULL)); render(); } return result; } void Core::render() { tempbuffer = new Uint32[screenWidth * screenHeight]; SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF); SDL_RenderClear(renderer); for (int x = 0; x < screenWidth; x++) { // calculate ray position and direction double cameraX = 2 * x / static_cast<double>(screenWidth) - 1; // x-coordinate in camera space double rayDirX = player->direction.x + player->cameraPlane.x * cameraX; double rayDirY = player->direction.y + player->cameraPlane.y * cameraX; // which box of the map we're in int mapX = static_cast<int>(player->position.x); int mapY = static_cast<int>(player->position.y); // length of ray from current position to next x or y-side double sideDistX; double sideDistY; // length of ray from one x or y-side to next x or y-side double deltaDistX = std::abs(1 / rayDirX); double deltaDistY = std::abs(1 / rayDirY); double perpWallDist; // what direction to step in x or y-direction (either +1 or -1) int stepX; int stepY; int hit = 0; // was there a wall hit? int side; // was a NS or a EW wall hit? // calculate step and initial sideDist if (rayDirX < 0) { stepX = -1; sideDistX = (player->position.x - mapX) * deltaDistX; } else { stepX = 1; sideDistX = (mapX + 1.0 - player->position.x) * deltaDistX; } if (rayDirY < 0) { stepY = -1; sideDistY = (player->position.y - mapY) * deltaDistY; } else { stepY = 1; sideDistY = (mapY + 1.0 - player->position.y) * deltaDistY; } // perform DDA while (hit == 0) { // jump to next map square, OR in x-direction, OR in y-direction if (sideDistX < sideDistY) { sideDistX += deltaDistX; mapX += stepX; side = 0; } else { sideDistY += deltaDistY; mapY += stepY; side = 1; } WorldTile *tile = world->getTile(mapX, mapY); if (tile != NULL) { if (tile->type != WorldTileType::Floor) { hit = 1; } } else { printf("Tile was a nullptr... x%i y%i. Assuming I didn't hit a wall...\n", mapX, mapY); } } // calculate distance projected on camera direction // (Euclidean distance will give fisheye effect!) if (side == 0) { perpWallDist = (mapX - player->position.x + (1 - stepX) / 2) / rayDirX; } else { perpWallDist = (mapY - player->position.y + (1 - stepY) / 2) / rayDirY; } // calculate height of line to draw on screen int lineHeight = static_cast<int>(screenHeight / perpWallDist); // calculate lowest and highest pixel to fill in current stripe int drawStart = -lineHeight / 2 + screenHeight / 2; if (drawStart < 0) { drawStart = 0; } int drawEnd = lineHeight / 2 + screenHeight / 2; if (drawEnd >= screenHeight) { drawEnd = screenHeight - 1; } WorldTile *tile = world->getTile(mapX, mapY); int textureNumber = 0; if (tile != NULL) { textureNumber = tile->type - 1; } else { printf("Tile was a nullptr... x%i y%i. Cannot determine textureNumber. Will use %i\n", mapX, mapY, textureNumber); } double wallX; if (side == 0) { wallX = player->position.y + perpWallDist * rayDirY; } else { wallX = player->position.x + perpWallDist * rayDirX; } wallX -= floor(wallX); SDL_Surface *surface = textures[textureNumber]; int texWidth = surface->w; int texHeight = surface->h; int texX = static_cast<int>(wallX * static_cast<double>(texWidth)); if (side == 0 && rayDirX > 0) { texX = texWidth - texX - 1; } if (side == 1 && rayDirY < 0) { texX = texWidth - texX - 1; } // TODO: an integer-only bresenham or DDA like algorithm could make the // texture coordinate stepping faster // How much to increase the texture coordinate per screen pixel double step = static_cast<double>(texHeight) / static_cast<double>(lineHeight); double texPos = (drawStart - screenHeight / 2 + lineHeight / 2) * step; for (int y = drawStart; y < drawEnd; y++) { int texY = static_cast<int>(texPos) & (texHeight - 1); texPos += step; // TODO: put into function int bpp = surface->format->BytesPerPixel; Uint8 *p = (Uint8 *)surface->pixels + texY * surface->pitch + texX * bpp; Uint32 pixel = *(Uint32 *)p; // switch (bpp) // { // case 1: // pixel = *p; // break; // case 2: // pixel = *(Uint16 *)p; // break; // case 3: // if (SDL_BYTEORDER == SDL_BIG_ENDIAN) // { // pixel = p[0] << 16 | p[1] << 8 | p[2]; // } // else // { // pixel = p[0] | p[1] << 8 | p[2] << 16; // } // break; // case 4: // pixel = *(Uint32 *)p; // break; // default: // break; // } // make color darker for y-sides: R, G and B byte each divided through // two with a "shift" and an "and" if (side == 1) { pixel = (pixel >> 1) & 8355711; } tempbuffer[y * screenWidth + x] = pixel; // TODO: this shit is hella inefficient // SDL_Color color; // SDL_GetRGBA(pixel, surface->format, &color.r, &color.g, &color.b, &color.a); // SDL_SetRenderDrawColor(mRenderer, color.r, color.g, color.b, color.a); // SDL_RenderDrawPoint(mRenderer, x, y); } // switch (world->getTile(mapX, mapY)->type) // { // case 1: // color = {255, 0, 0}; // red // break; // case 2: // color = {0, 255, 0}; // green // break; // case 3: // color = {0, 0, 255}; // blue // break; // case 4: // color = {255, 255, 255}; // white // break; // default:; // color = {0, 255, 255}; // yellow // break; // } // give x and y sides different brightness // if (side == 1) // { // color.r = color.r / 2; // color.g = color.g / 2; // color.b = color.b / 2; // } // // draw the pixels of the stripe as a vertical line // SDL_SetRenderDrawColor(mRenderer, color.r, color.g, color.b, color.a); // SDL_RenderDrawLineF(mRenderer, x, drawStart, x, drawEnd); } previousTime = currentTime; currentTime = SDL_GetTicks(); frameTime = (currentTime - previousTime) / 1000.0; if (static_cast<int>(frameTime) % 1000 == 0) printf("FPS: %i\n", static_cast<int>(1.0 / frameTime)); movementSpeed = frameTime * movementSpeedModifier; rotationSpeed = frameTime * 3.0; SDL_UpdateTexture(framebuffer, NULL, tempbuffer, screenWidth * sizeof(Uint32)); SDL_RenderCopy(renderer, framebuffer, NULL, NULL); SDL_RenderPresent(renderer); // clean up delete[] tempbuffer; } void Core::handleKeyboardEvent(const Uint8 *keyStates) { if (keyStates[SDL_SCANCODE_LSHIFT]) { movementSpeedModifier = 5.0; } else { movementSpeedModifier = 2.0; } if (keyStates[SDL_SCANCODE_W] || keyStates[SDL_SCANCODE_UP]) { const double newXPosition = player->position.x + player->direction.x * movementSpeed; if (world->isValidPosition(static_cast<int>(newXPosition), static_cast<int>(player->position.y))) { player->position.x = newXPosition; } const double newYPosition = player->position.y + player->direction.y * movementSpeed; if (world->isValidPosition(static_cast<int>(player->position.x), static_cast<int>(newYPosition))) { player->position.y = newYPosition; } } else if (keyStates[SDL_SCANCODE_S] || keyStates[SDL_SCANCODE_DOWN]) { const double newXPosition = player->position.x - player->direction.x * movementSpeed; if (world->isValidPosition(static_cast<int>(newXPosition), static_cast<int>(player->position.y))) { player->position.x = newXPosition; } const double newYPosition = player->position.y - player->direction.y * movementSpeed; if (world->isValidPosition(static_cast<int>(player->position.x), static_cast<int>(newYPosition))) { player->position.y = newYPosition; } } if (keyStates[SDL_SCANCODE_A] || keyStates[SDL_SCANCODE_LEFT]) { const double newXPosition = player->position.x - player->direction.y * movementSpeed; if (world->isValidPosition(static_cast<int>(newXPosition), static_cast<int>(player->position.y))) { player->position.x = newXPosition; } const double newYPosition = player->position.y - (player->direction.x * -1) * movementSpeed; if (world->isValidPosition(static_cast<int>(player->position.x), static_cast<int>(newYPosition))) { player->position.y = newYPosition; } } else if (keyStates[SDL_SCANCODE_D] || keyStates[SDL_SCANCODE_RIGHT]) { const double newXPosition = player->position.x + player->direction.y * movementSpeed; if (world->isValidPosition(static_cast<int>(newXPosition), static_cast<int>(player->position.y))) { player->position.x = newXPosition; } const double newYPosition = player->position.y + (player->direction.x * -1) * movementSpeed; if (world->isValidPosition(static_cast<int>(player->position.x), static_cast<int>(newYPosition))) { player->position.y = newYPosition; } } } void Core::handleMouseMovement(SDL_MouseMotionEvent mouseMotion) { const double rotation = (double(mouseMotion.xrel) / 100) * -1; // both camera direction and camera plane must be rotated double oldDirX = player->direction.x; double newDirX = player->direction.x * cos(rotation) - player->direction.y * sin(rotation); double newDirY = oldDirX * sin(rotation) + player->direction.y * cos(rotation); player->direction.set(newDirX, newDirY); double oldPlaneX = player->cameraPlane.x; double newPlaneX = player->cameraPlane.x * cos(rotation) - player->cameraPlane.y * sin(rotation); double newPlaneY = oldPlaneX * sin(rotation) + player->cameraPlane.y * cos(rotation); player->cameraPlane.set(newPlaneX, newPlaneY); } } // namespace ray3d
30.627358
116
0.530263
beyerleinf
1c88ee1c406eef134f226eb0f22f8ce10108bfcd
3,515
cpp
C++
firing_char_single_img/main.cpp
phao/topshooter_xp
e5cc75e47751fa116ca106580b5b4d46cf781c4c
[ "MIT" ]
4
2018-07-09T19:38:27.000Z
2021-03-02T19:31:38.000Z
firing_char_single_img/main.cpp
phao/topshooter_xp
e5cc75e47751fa116ca106580b5b4d46cf781c4c
[ "MIT" ]
null
null
null
firing_char_single_img/main.cpp
phao/topshooter_xp
e5cc75e47751fa116ca106580b5b4d46cf781c4c
[ "MIT" ]
2
2020-04-25T18:05:30.000Z
2020-07-14T21:19:17.000Z
#include <ctime> #include <cstdlib> #include <cstdint> #include <stdexcept> #include <cmath> #include <algorithm> #include <iostream> #include "xSDL.hpp" #include "xSDL_image.hpp" #include "Graphical.hpp" #include "EngCharacter.hpp" #include "ParticlesSystem.hpp" #include "Atlas.hpp" #include "EngSkeleton.hpp" #include "xMath.hpp" using xMATH::Float2; namespace GAME { class Main { public: Main(const char * const title, const int width, const int height) : sdl {SDL_INIT_VIDEO}, win {title, width, height}, rend {&win, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC}, screen {&rend, width, height}, atlas {xIMG::load("atlas.png")}, skeleton {&screen, &atlas}, fire_particle {&screen, &atlas, ATLAS::piece_geom(ATLAS::CIRCLE_GRAD)}, player {Float2(0, 0), skeleton.images(), &fire_particle} { // I should learn how to use C++11's features for random numbers. I've read // in too many places that C's rand/srand are terrible. srand(time(0)); } int run() { player.set_speed(0.3f); auto last_update = SDL_GetTicks(); for (;;) { auto now = SDL_GetTicks(); SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { return 0; } consume_event(event, now); } rend.set_draw_color(xSDL::BLACK); rend.clear(); update_and_render(now, now-last_update); last_update = now; rend.present(); } } private: void update_and_render(uint32_t ms_now, uint32_t dt_ms) { player.update(&particles, ms_now, dt_ms); player.render(&screen); particles.update_and_render(&screen, ms_now); } void consume_event(SDL_Event &e, uint32_t ms_now) { switch (e.type) { case SDL_KEYDOWN: switch (e.key.keysym.sym) { case SDLK_a: player.walk_sideway_left(); break; case SDLK_s: player.walk_backward(); break; case SDLK_d: player.walk_sideway_right(); break; case SDLK_w: player.walk_forward(); break; case SDLK_f: if (!e.key.repeat) { player.start_firing(ms_now); } break; } break; case SDL_KEYUP: switch (e.key.keysym.sym) { case SDLK_a: player.stop_sideway_left(); break; case SDLK_s: player.stop_backward(); break; case SDLK_d: player.stop_sideway_right(); break; case SDLK_w: player.stop_forward(); break; case SDLK_f: player.stop_firing(); break; } break; case SDL_MOUSEMOTION: case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { int x, y; SDL_GetMouseState(&x, &y); y = screen.height() - 1 - y; player.weapon_face(Float2{float(x), float(y)}); break; } } } private: xSDL::SDL sdl; xSDL::Window win; xSDL::Renderer rend; GRAL::Screen screen; xSDL::Surface atlas; EngSkeleton skeleton; ParticlesSystem particles; GRAL::Image fire_particle; EngCharacter player; }; } int main(int argc, char **argv) { (void) argc; (void) argv; try { return GAME::Main("Walking Character", 800, 600).run(); } catch (std::exception &e) { std::cerr << "Error: " << e.what() << ".\n"; return 1; } }
23.590604
79
0.574395
phao
1c92482aefeade06c671c07d3a2e4461c6bd3af5
14,094
cpp
C++
Engine/Types/source/Types/CapModel.capnp.cpp
Pursche/PurEngine
9bc82309ee2773241e07ef1ec3335bbe449a791c
[ "MIT" ]
null
null
null
Engine/Types/source/Types/CapModel.capnp.cpp
Pursche/PurEngine
9bc82309ee2773241e07ef1ec3335bbe449a791c
[ "MIT" ]
null
null
null
Engine/Types/source/Types/CapModel.capnp.cpp
Pursche/PurEngine
9bc82309ee2773241e07ef1ec3335bbe449a791c
[ "MIT" ]
null
null
null
// Generated by Cap'n Proto compiler, DO NOT EDIT // source: CapModel.capnp #include "CapModel.capnp.h" namespace capnp { namespace schemas { static const ::capnp::_::AlignedData<63> b_b747ed917331d47a = { { 0, 0, 0, 0, 5, 0, 6, 0, 122, 212, 49, 115, 145, 237, 71, 183, 21, 0, 0, 0, 1, 0, 2, 0, 233, 16, 35, 54, 42, 37, 94, 162, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0, 2, 1, 0, 0, 33, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 29, 0, 0, 0, 175, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 121, 112, 101, 115, 47, 67, 97, 112, 77, 111, 100, 101, 108, 46, 99, 97, 112, 110, 112, 58, 67, 97, 112, 86, 101, 99, 116, 111, 114, 51, 0, 0, 0, 0, 0, 1, 0, 1, 0, 12, 0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 69, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 3, 0, 1, 0, 76, 0, 0, 0, 2, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 73, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 3, 0, 1, 0, 80, 0, 0, 0, 2, 0, 1, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 77, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 72, 0, 0, 0, 3, 0, 1, 0, 84, 0, 0, 0, 2, 0, 1, 0, 120, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 121, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 122, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, } }; ::capnp::word const* const bp_b747ed917331d47a = b_b747ed917331d47a.words; #if !CAPNP_LITE static const uint16_t m_b747ed917331d47a[] = {0, 1, 2}; static const uint16_t i_b747ed917331d47a[] = {0, 1, 2}; const ::capnp::_::RawSchema s_b747ed917331d47a = { 0xb747ed917331d47a, b_b747ed917331d47a.words, 63, nullptr, m_b747ed917331d47a, 0, 3, i_b747ed917331d47a, nullptr, nullptr, { &s_b747ed917331d47a, nullptr, nullptr, 0, 0, nullptr } }; #endif // !CAPNP_LITE static const ::capnp::_::AlignedData<48> b_8f4ec38ef88be8c5 = { { 0, 0, 0, 0, 5, 0, 6, 0, 197, 232, 139, 248, 142, 195, 78, 143, 21, 0, 0, 0, 1, 0, 1, 0, 233, 16, 35, 54, 42, 37, 94, 162, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0, 2, 1, 0, 0, 33, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 29, 0, 0, 0, 119, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 121, 112, 101, 115, 47, 67, 97, 112, 77, 111, 100, 101, 108, 46, 99, 97, 112, 110, 112, 58, 67, 97, 112, 86, 101, 99, 116, 111, 114, 50, 0, 0, 0, 0, 0, 1, 0, 1, 0, 8, 0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 41, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 3, 0, 1, 0, 48, 0, 0, 0, 2, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 45, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 0, 0, 0, 3, 0, 1, 0, 52, 0, 0, 0, 2, 0, 1, 0, 120, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 121, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, } }; ::capnp::word const* const bp_8f4ec38ef88be8c5 = b_8f4ec38ef88be8c5.words; #if !CAPNP_LITE static const uint16_t m_8f4ec38ef88be8c5[] = {0, 1}; static const uint16_t i_8f4ec38ef88be8c5[] = {0, 1}; const ::capnp::_::RawSchema s_8f4ec38ef88be8c5 = { 0x8f4ec38ef88be8c5, b_8f4ec38ef88be8c5.words, 48, nullptr, m_8f4ec38ef88be8c5, 0, 2, i_8f4ec38ef88be8c5, nullptr, nullptr, { &s_8f4ec38ef88be8c5, nullptr, nullptr, 0, 0, nullptr } }; #endif // !CAPNP_LITE static const ::capnp::_::AlignedData<65> b_df2a047c1f67783f = { { 0, 0, 0, 0, 5, 0, 6, 0, 63, 120, 103, 31, 124, 4, 42, 223, 21, 0, 0, 0, 1, 0, 0, 0, 233, 16, 35, 54, 42, 37, 94, 162, 3, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0, 250, 0, 0, 0, 33, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 29, 0, 0, 0, 175, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 121, 112, 101, 115, 47, 67, 97, 112, 77, 111, 100, 101, 108, 46, 99, 97, 112, 110, 112, 58, 67, 97, 112, 86, 101, 114, 116, 101, 120, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 12, 0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 69, 0, 0, 0, 74, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 3, 0, 1, 0, 80, 0, 0, 0, 2, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 77, 0, 0, 0, 58, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 72, 0, 0, 0, 3, 0, 1, 0, 84, 0, 0, 0, 2, 0, 1, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 81, 0, 0, 0, 74, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 80, 0, 0, 0, 3, 0, 1, 0, 92, 0, 0, 0, 2, 0, 1, 0, 112, 111, 115, 105, 116, 105, 111, 110, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 122, 212, 49, 115, 145, 237, 71, 183, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 110, 111, 114, 109, 97, 108, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 122, 212, 49, 115, 145, 237, 71, 183, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 116, 101, 120, 67, 111, 111, 114, 100, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 197, 232, 139, 248, 142, 195, 78, 143, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, } }; ::capnp::word const* const bp_df2a047c1f67783f = b_df2a047c1f67783f.words; #if !CAPNP_LITE static const ::capnp::_::RawSchema* const d_df2a047c1f67783f[] = { &s_8f4ec38ef88be8c5, &s_b747ed917331d47a, }; static const uint16_t m_df2a047c1f67783f[] = {1, 0, 2}; static const uint16_t i_df2a047c1f67783f[] = {0, 1, 2}; const ::capnp::_::RawSchema s_df2a047c1f67783f = { 0xdf2a047c1f67783f, b_df2a047c1f67783f.words, 65, d_df2a047c1f67783f, m_df2a047c1f67783f, 2, 3, i_df2a047c1f67783f, nullptr, nullptr, { &s_df2a047c1f67783f, nullptr, nullptr, 0, 0, nullptr } }; #endif // !CAPNP_LITE static const ::capnp::_::AlignedData<57> b_9edfc4cfa960c55d = { { 0, 0, 0, 0, 5, 0, 6, 0, 93, 197, 96, 169, 207, 196, 223, 158, 21, 0, 0, 0, 1, 0, 0, 0, 233, 16, 35, 54, 42, 37, 94, 162, 2, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0, 242, 0, 0, 0, 33, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 29, 0, 0, 0, 119, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 121, 112, 101, 115, 47, 67, 97, 112, 77, 111, 100, 101, 108, 46, 99, 97, 112, 110, 112, 58, 67, 97, 112, 77, 111, 100, 101, 108, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 8, 0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 41, 0, 0, 0, 74, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 0, 0, 0, 3, 0, 1, 0, 68, 0, 0, 0, 2, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 0, 0, 0, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0, 3, 0, 1, 0, 88, 0, 0, 0, 2, 0, 1, 0, 118, 101, 114, 116, 105, 99, 101, 115, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1, 0, 16, 0, 0, 0, 0, 0, 0, 0, 63, 120, 103, 31, 124, 4, 42, 223, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 105, 110, 100, 105, 99, 101, 115, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, } }; ::capnp::word const* const bp_9edfc4cfa960c55d = b_9edfc4cfa960c55d.words; #if !CAPNP_LITE static const ::capnp::_::RawSchema* const d_9edfc4cfa960c55d[] = { &s_df2a047c1f67783f, }; static const uint16_t m_9edfc4cfa960c55d[] = {1, 0}; static const uint16_t i_9edfc4cfa960c55d[] = {0, 1}; const ::capnp::_::RawSchema s_9edfc4cfa960c55d = { 0x9edfc4cfa960c55d, b_9edfc4cfa960c55d.words, 57, d_9edfc4cfa960c55d, m_9edfc4cfa960c55d, 1, 2, i_9edfc4cfa960c55d, nullptr, nullptr, { &s_9edfc4cfa960c55d, nullptr, nullptr, 0, 0, nullptr } }; #endif // !CAPNP_LITE } // namespace schemas } // namespace capnp // ======================================================================================= // CapVector3 constexpr uint16_t CapVector3::_capnpPrivate::dataWordSize; constexpr uint16_t CapVector3::_capnpPrivate::pointerCount; #if !CAPNP_LITE constexpr ::capnp::Kind CapVector3::_capnpPrivate::kind; constexpr ::capnp::_::RawSchema const* CapVector3::_capnpPrivate::schema; #endif // !CAPNP_LITE // CapVector2 constexpr uint16_t CapVector2::_capnpPrivate::dataWordSize; constexpr uint16_t CapVector2::_capnpPrivate::pointerCount; #if !CAPNP_LITE constexpr ::capnp::Kind CapVector2::_capnpPrivate::kind; constexpr ::capnp::_::RawSchema const* CapVector2::_capnpPrivate::schema; #endif // !CAPNP_LITE // CapVertex constexpr uint16_t CapVertex::_capnpPrivate::dataWordSize; constexpr uint16_t CapVertex::_capnpPrivate::pointerCount; #if !CAPNP_LITE constexpr ::capnp::Kind CapVertex::_capnpPrivate::kind; constexpr ::capnp::_::RawSchema const* CapVertex::_capnpPrivate::schema; #endif // !CAPNP_LITE // CapModel constexpr uint16_t CapModel::_capnpPrivate::dataWordSize; constexpr uint16_t CapModel::_capnpPrivate::pointerCount; #if !CAPNP_LITE constexpr ::capnp::Kind CapModel::_capnpPrivate::kind; constexpr ::capnp::_::RawSchema const* CapModel::_capnpPrivate::schema; #endif // !CAPNP_LITE
42.451807
102
0.371009
Pursche
1c94471cc1b91180aeb24553afdba4a5eb90d328
7,391
cpp
C++
clang/lib/CILToLLVM/CILToLLVMTypeConverter.cpp
compiler-tree-technologies/cil
195acc33e14715da9f5a1746b489814d56c015f7
[ "BSD-2-Clause" ]
21
2021-02-08T15:42:18.000Z
2022-02-23T03:25:10.000Z
clang/lib/CILToLLVM/CILToLLVMTypeConverter.cpp
compiler-tree-technologies/cil
195acc33e14715da9f5a1746b489814d56c015f7
[ "BSD-2-Clause" ]
3
2021-02-20T14:24:45.000Z
2021-08-04T04:20:05.000Z
clang/lib/CILToLLVM/CILToLLVMTypeConverter.cpp
compiler-tree-technologies/cil
195acc33e14715da9f5a1746b489814d56c015f7
[ "BSD-2-Clause" ]
6
2021-02-08T16:57:07.000Z
2022-01-13T11:32:34.000Z
// Copyright (c) 2019, Compiler Tree Technologies Pvt Ltd. // 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. //===- CILToLLVMLowering.cpp - Loop.for to affine.for conversion //-----------===// // //===----------------------------------------------------------------------===// // // This file implements lowering of mos to CIL dialect operations to LLVM // dialect // // NOTE: This code contains lot of repeated code. Needs lot of cleanup/ // refactoring. // TODO: Split patterns into multiple files liek ArrayOps patterns, etc.. //===----------------------------------------------------------------------===// #include "clang/cil/CILToLLVM/CILToLLVMLowering.h" #include "clang/cil/dialect/CIL/CILOps.h" #include "mlir/Conversion/AffineToStandard/AffineToStandard.h" #include "mlir/Conversion/LoopToStandard/ConvertLoopToStandard.h" #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h" #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h" #include "mlir/Dialect/AffineOps/AffineOps.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" #include "mlir/Dialect/LoopOps/LoopOps.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/Pass/Pass.h" #include "mlir/Transforms/DialectConversion.h" #include "llvm/ADT/Sequence.h" #define PASS_NAME "CILToLLVMLowering" #define DEBUG_TYPE PASS_NAME // TODO: Add DEBUG WITH TYPE and STATISTIC using namespace mlir; using namespace CIL; using namespace CIL::lowering; // TODO Should this be part of some class ? llvm::DenseMap<mlir::Type, LLVM::LLVMType> StructDeclTypes; CILTypeConverter::CILTypeConverter(MLIRContext *ctx) : LLVMTypeConverter(ctx) { addConversion([&](CIL::IntegerTy type) { return convertIntegerTy(type); }); addConversion([&](CIL::FloatingTy type) { return convertFloatingTy(type); }); addConversion( [&](CIL::PointerType type) { return convertPointerType(type); }); addConversion([&](CIL::CharTy type) { return convertCharType(type); }); addConversion( [&](mlir::FunctionType type) { return convertFunctionType(type); }); addConversion([&](CIL::ArrayType type) { return convertArrayType(type); }); addConversion([&](CIL::StructType type) { return convertStructType(type); }); addConversion([&](CIL::VoidType type) { return convertVoidType(type); }); // addConversion([&](CIL::UnsignedIntegerTy type) { // return convertUnsignedIntegerTy(type); // }); } LLVM::LLVMType CILTypeConverter::convertCharType(CIL::CharTy type) { return LLVM::LLVMType::getInt8Ty(llvmDialect); } LLVM::LLVMType CILTypeConverter::convertFunctionType(mlir::FunctionType type) { SmallVector<LLVM::LLVMType, 2> inputs; bool hasVarArg = false; for (auto type : type.getInputs()) { if (type.isa<CIL::VarArgTy>()) { hasVarArg = true; continue; } inputs.push_back(convertType(type).cast<LLVM::LLVMType>()); } LLVM::LLVMType result = LLVM::LLVMType::getVoidTy(llvmDialect); if (type.getNumResults() > 0) { assert(type.getNumResults() < 2); result = convertType(type.getResult(0)).cast<LLVM::LLVMType>(); } return LLVM::LLVMType::getFunctionTy(result, inputs, hasVarArg); } LLVM::LLVMType CILTypeConverter::convertArrayType(CIL::ArrayType type) { auto llTy = convertType(type.getEleTy()).cast<LLVM::LLVMType>(); assert(type.hasStaticShape()); return LLVM::LLVMType::getArrayTy(llTy, type.getShape().front()); } LLVM::LLVMType CILTypeConverter::convertVoidType(CIL::VoidType type) { return LLVM::LLVMType::getVoidTy(llvmDialect); } LLVM::LLVMType CILTypeConverter::convertIntegerTy(CIL::IntegerTy type) { switch (type.getIntegerKind()) { case BoolKind: return LLVM::LLVMType::getInt1Ty(llvmDialect); case Char8Kind: return LLVM::LLVMType::getInt8Ty(llvmDialect); case ShortKind: return LLVM::LLVMType::getInt16Ty(llvmDialect); case IntKind: return LLVM::LLVMType::getInt32Ty(llvmDialect); case LongKind: return LLVM::LLVMType::getInt64Ty(llvmDialect); case LongLongKind: return LLVM::LLVMType::getInt64Ty(llvmDialect); } return {}; } LLVM::LLVMType CILTypeConverter::convertFloatingTy(CIL::FloatingTy type) { switch (type.getFloatingKind()) { case Float: return LLVM::LLVMType::getFloatTy(llvmDialect); case Double: return LLVM::LLVMType::getDoubleTy(llvmDialect); case LongDouble: return LLVM::LLVMType::getFP128Ty(llvmDialect); default: llvm_unreachable("Unhandled float type"); } } LLVM::LLVMType CILTypeConverter::convertPointerType(CIL::PointerType type) { auto llTy = convertType(type.getEleTy()).cast<LLVM::LLVMType>(); return llTy.getPointerTo(); } LLVM::LLVMType CILTypeConverter::convertStructType(CIL::StructType type) { auto eleTypes = type.getElementTypes(); if (StructDeclTypes.find(type) == StructDeclTypes.end()) { StructDeclTypes[type] = LLVM::LLVMType::getOpaqueStructTy(llvmDialect); } else { return StructDeclTypes[type]; } // TODO We should not be using llvm type here. We are using because // there is no interface in LLVMType for forward decl. llvm::SmallVector<llvm::Type *, 2> actualTypes; for (auto eleTy : eleTypes) { actualTypes.push_back( convertType(eleTy).cast<LLVM::LLVMType>().getUnderlyingType()); } auto currType = StructDeclTypes[type]; auto structTy = llvm::dyn_cast<llvm::StructType>(currType.getUnderlyingType()); assert(structTy); if (type.getName() != "") { structTy->setName(type.getName()); } // if opaque type if (actualTypes.empty()) return currType; structTy->setBody(actualTypes); return currType; } // LLVM::LLVMType // CILTypeConverter::convertUnsignedIntegerTy(CIL::UnsignedIntegerTy type) { // switch (type.getIntegerKind()) { // case Char8Kind: // return LLVM::LLVMType::getInt8Ty(llvmDialect); // case ShortKind: // return LLVM::LLVMType::getInt16Ty(llvmDialect); // case IntKind: // return LLVM::LLVMType::getInt32Ty(llvmDialect); // case LongKind: // return LLVM::LLVMType::getInt64Ty(llvmDialect); // case LongLongKind: // return LLVM::LLVMType::getInt64Ty(llvmDialect); // } // return {}; // }
37.328283
80
0.715059
compiler-tree-technologies
1c9509e71c4bc3c9bc797d4a653467b18bc66302
1,212
hpp
C++
20/regex_labyrinth.hpp
ComicSansMS/AdventOfCode2018
936ebf5dad7a0317ed3db0f58a16d88c4a00eabb
[ "Unlicense" ]
null
null
null
20/regex_labyrinth.hpp
ComicSansMS/AdventOfCode2018
936ebf5dad7a0317ed3db0f58a16d88c4a00eabb
[ "Unlicense" ]
null
null
null
20/regex_labyrinth.hpp
ComicSansMS/AdventOfCode2018
936ebf5dad7a0317ed3db0f58a16d88c4a00eabb
[ "Unlicense" ]
null
null
null
#ifndef ADVENT_OF_CODE_20_REGEX_LABYRINTH_HPP_INCLUDE_GUARD #define ADVENT_OF_CODE_20_REGEX_LABYRINTH_HPP_INCLUDE_GUARD #include <array> #include <functional> #include <iosfwd> #include <string_view> #include <tuple> #include <unordered_map> #include <vector> struct Vec2 { int x; int y; Vec2() = default; Vec2(int xx, int yy) :x(xx), y(yy) {} }; bool operator==(Vec2 const& lhs, Vec2 const& rhs); struct Room { enum Direction { North = 0, South, West, East }; Vec2 position; std::array<bool, 4> adjacencies; Room() = default; explicit Room(Vec2 const& pos); }; namespace std { template<> struct hash<Vec2> { typedef Vec2 argument_type; typedef std::size_t result_type; result_type operator()(argument_type const& v) const noexcept { return (static_cast<std::size_t>(v.x) << static_cast<std::size_t>(16)) | static_cast<std::size_t>(v.y); } }; } struct Map { std::unordered_map<Vec2, Room> rooms; Vec2 min; Vec2 max; }; Map constructMap(std::string_view regex); std::ostream& operator<<(std::ostream& os, Map const& m); std::tuple<int, int> shortestPaths(Map const& m); #endif
18.9375
111
0.65264
ComicSansMS
1c9eee87f1d2157545d40f8037e138b9e4584038
691
hpp
C++
third_party/boost/libs/throw_exception/test/lib2_throw.hpp
Jackarain/tinyrpc
07060e3466776aa992df8574ded6c1616a1a31af
[ "BSL-1.0" ]
32
2019-02-27T06:57:07.000Z
2021-08-29T10:56:19.000Z
third_party/boost/libs/throw_exception/test/lib2_throw.hpp
avplayer/cxxrpc
7049b4079fac78b3828e68f787d04d699ce52f6d
[ "BSL-1.0" ]
1
2019-04-04T18:00:00.000Z
2019-04-04T18:00:00.000Z
third_party/boost/libs/throw_exception/test/lib2_throw.hpp
avplayer/cxxrpc
7049b4079fac78b3828e68f787d04d699ce52f6d
[ "BSL-1.0" ]
5
2019-08-20T13:45:04.000Z
2022-03-01T18:23:49.000Z
#ifndef LIB2_THROW_HPP_INCLUDED #define LIB2_THROW_HPP_INCLUDED // Copyright 2018 Peter Dimov // // 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/config.hpp> #include <exception> #if defined(LIB2_DYN_LINK) # if defined(LIB2_SOURCE) # define LIB2_DECL BOOST_SYMBOL_EXPORT # else # define LIB2_DECL BOOST_SYMBOL_IMPORT # endif #else # define LIB2_DECL #endif namespace lib2 { struct BOOST_SYMBOL_VISIBLE exception: public std::exception { }; LIB2_DECL void f(); } // namespace lib2 #endif // #ifndef LIB2_THROW_HPP_INCLUDED
19.194444
62
0.732272
Jackarain
1caf4b346c1651e1f388febc9153362d258f74ec
2,584
cxx
C++
source/common/log.cxx
bjadamson/BoomHS
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
[ "MIT" ]
2
2016-07-22T10:09:21.000Z
2017-09-16T06:50:01.000Z
source/common/log.cxx
bjadamson/BoomHS
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
[ "MIT" ]
14
2016-08-13T22:45:56.000Z
2018-12-16T03:56:36.000Z
source/common/log.cxx
bjadamson/BoomHS
60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4
[ "MIT" ]
null
null
null
#include <common/algorithm.hpp> #include <common/compiler.hpp> #include <common/log.hpp> #include <common/type_macros.hpp> #include <iostream> #include <memory> using namespace common; using namespace common::impl; namespace { auto threadunsafe_sink(char const* file_path) { // use single-threaded spdlog sink using SinkType = spdlog::sinks::simple_file_sink_st; return std::make_unique<SinkType>(file_path); } auto threadsafe_sink(char const* file_path) { // use multi-threaded spdlog sink using SinkType = spdlog::sinks::simple_file_sink_mt; return std::make_unique<SinkType>(file_path); // using SinkType = spdlog::sinks::daily_file_sink_st; // return std::make_unique<SinkType>(file_path, 23, 50); } auto threadsafe_stderr_sink() { using SinkType = spdlog::sinks::stderr_sink_st; return std::make_unique<SinkType>(); } LogFlusher make_logflusher(char const* file_path, spdlog::level::level_enum const level) { try { auto file_sink = threadsafe_sink(file_path); auto stderr_sink = threadsafe_stderr_sink(); stderr_sink->set_level(spdlog::level::err); auto const sinks = common::make_array<spdlog::sink_ptr>(MOVE(file_sink), MOVE(stderr_sink)); auto logger = std::make_unique<spdlog::logger>(file_path, sinks.cbegin(), sinks.cend()); logger->set_level(level); auto adapter = impl::LogAdapter{MOVE(logger)}; return LogFlusher{MOVE(adapter)}; } catch (spdlog::spdlog_ex const& ex) { std::cerr << ex.what() << "\n"; std::abort(); } } } // namespace namespace common { Logger LogFactory::make_default(char const* name) { // 1. Construct an instance of the default log group. // 2. Construct an instance of a logger that writes all log levels to a shared file. static char const prefix[] = "build-system/bin/logs/"; auto const path = prefix + std::string{name}; auto flusher = make_logflusher(path.c_str(), spdlog::level::trace); return Logger{MOVE(flusher)}; } Logger LogFactory::make_stderr() { auto const level = spdlog::level::err; try { auto stderr_sink = threadsafe_stderr_sink(); stderr_sink->set_level(level); auto const sinks = common::make_array<spdlog::sink_ptr>(MOVE(stderr_sink)); auto logger = std::make_unique<spdlog::logger>("", sinks.cbegin(), sinks.cend()); logger->set_level(level); auto adapter = impl::LogAdapter{MOVE(logger)}; return Logger{LogFlusher{MOVE(adapter)}}; } catch (spdlog::spdlog_ex const& ex) { std::cerr << ex.what() << "\n"; std::abort(); } } } // namespace common
25.84
98
0.694272
bjadamson
1cb17087c5744fc15685f61512d6ac28e2e27bae
363
cpp
C++
codeshef/SUMPOS.cpp
sonuKumar03/data-structure-and-algorithm
d1fd3cad494cbcc91ce7ff37ec611752369b50b6
[ "MIT" ]
null
null
null
codeshef/SUMPOS.cpp
sonuKumar03/data-structure-and-algorithm
d1fd3cad494cbcc91ce7ff37ec611752369b50b6
[ "MIT" ]
null
null
null
codeshef/SUMPOS.cpp
sonuKumar03/data-structure-and-algorithm
d1fd3cad494cbcc91ce7ff37ec611752369b50b6
[ "MIT" ]
null
null
null
#include<iostream> #include<queue> #include<vector> #include<algorithm> #include<climits> #include<math.h> using namespace std; typedef long long ll ; void solve(){ ll x,y,z; cin>>x>>y>>z; if(x+y ==z || x+z ==y || z+y==x ){ cout<<"YES\n"; }else{ cout<<"NO\n"; } } int main() { ll t; cin>>t; while(t--){ solve(); } return 0; }
12.1
37
0.545455
sonuKumar03
1cb80edd1b2de8683ffddb8ed7d8bc6fc382913a
950
cpp
C++
docs/parallel/concrt/codesnippet/CPP/cancellation-in-the-ppl_9.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
965
2017-06-25T23:57:11.000Z
2022-03-31T14:17:32.000Z
docs/parallel/concrt/codesnippet/CPP/cancellation-in-the-ppl_9.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/parallel/concrt/codesnippet/CPP/cancellation-in-the-ppl_9.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
951
2017-06-25T12:36:14.000Z
2022-03-26T22:49:06.000Z
structured_task_group tg2; // Create a child task. auto t4 = make_task([&] { // Perform work in a loop. for (int i = 0; i < 1000; ++i) { // Call a function to perform work. // If the work function fails, throw an exception to // cancel the parent task. bool succeeded = work(i); if (!succeeded) { throw exception("The task failed"); } } }); // Create a child task. auto t5 = make_task([&] { // TODO: Perform work here. }); // Run the child tasks. tg2.run(t4); tg2.run(t5); // Wait for the tasks to finish. The runtime marshals any exception // that occurs to the call to wait. try { tg2.wait(); } catch (const exception& e) { wcout << e.what() << endl; }
25.675676
73
0.454737
bobbrow
1cb821c0849832889abe41ff99312eedeb1837a0
660
cpp
C++
teas/iostream/iostream/iostream.cpp
benman64/buildhl
137f53d3817928d67b898653b612bbaa669d0112
[ "MIT" ]
null
null
null
teas/iostream/iostream/iostream.cpp
benman64/buildhl
137f53d3817928d67b898653b612bbaa669d0112
[ "MIT" ]
null
null
null
teas/iostream/iostream/iostream.cpp
benman64/buildhl
137f53d3817928d67b898653b612bbaa669d0112
[ "MIT" ]
null
null
null
#include "iostream.hpp" namespace ios { bout_ostream::bout_ostream() { mFile = stdout; } std::streamsize bout_ostream::write(const void*data, std::streamsize size) { return fwrite(data, 1, size, mFile); } void bout_ostream::flush() { fflush(mFile); } bin_istream::bin_istream() { mFile = stdin; } std::streamsize bin_istream::read(void *data, std::streamsize size) { return fread(data, 1, size, mFile); } berr_ostream::berr_ostream() { mFile = stderr; } std::streamsize berr_ostream::write(const void*data, std::streamsize size) { return fwrite(data, 1, size, mFile); } bout_ostream bout; bin_istream bin; berr_ostream berr; }
18.857143
76
0.69697
benman64
1cc6b226eea195cfc51cde987cf6d117754e4563
1,759
cpp
C++
7.Templates/i-Design/Q5/Main.cpp
Concept-Team/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
26
2021-03-17T03:15:22.000Z
2021-06-09T13:29:41.000Z
7.Templates/i-Design/Q5/Main.cpp
Servatom/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
6
2021-03-16T19:04:05.000Z
2021-06-03T13:41:04.000Z
7.Templates/i-Design/Q5/Main.cpp
Concept-Team/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
42
2021-03-17T03:16:22.000Z
2021-06-14T21:11:20.000Z
#include<iostream> #include<cstdlib> using std::cin; using std::cout; using std::endl; using std::string; template<class T> class Stack { private: int top; T *arr; int maxsize; public: Stack(int s){ maxsize=s; arr=new T[maxsize]; top=-1; } void push(T val){ cout<<"Inserting "<<val<<endl; top++; arr[top]=val; } T pop(){ cout<<"Removing "<<arr[top]<<endl; top--; return arr[top+1]; } void display(){ for(int i=0;i<=top;i++){ cout<<" "<<arr[i]; } cout<<endl; } T peek(){ return arr[top]; } int size(){ return top+1; } bool isEmpty(){ return (top==-1); } bool isFull(){ return (top==maxsize-1); } }; int main() { int s,n; string item; cin>>s; Stack<string>st(s); do { cout<<"1.Insertion"<<endl; cout<<"2.Deletion"<<endl; cout<<"3.Display Stack"<<endl; cout<<"4.Exit"<<endl; cout<<"Enter your Choice:"<<endl<<endl; cin>>n; if(n==1) { cin.get(); cout<<"Enter the element to insert : "<<endl; getline(cin,item); if(!st.isFull()) { st.push(item); } else cout<<"Stack is full!"<<endl; } else if(n==2) { if(!st.isEmpty()) { st.pop(); } else cout<<"Stack is empty!"<<endl; } else if(n==3) { if(!st.isEmpty()) { cout<<"Stack elements are : "; st.display(); } else cout<<"Stack is empty!"<<endl; } else if (n==4) { exit(0); } }while(n>=1&&n<5); return 0; }
17.07767
53
0.436043
Concept-Team
1ccb38f5558314586f831fafeb058fff81af0538
2,147
hpp
C++
test/unittest/rtps/flowcontrol/FlowControllerPublishModesTests.hpp
DimaRU/Fast-DDS
4874d11575f396f7787c0f93254a989e7f523e68
[ "Apache-2.0" ]
575
2015-01-22T20:05:04.000Z
2020-06-01T10:06:12.000Z
test/unittest/rtps/flowcontrol/FlowControllerPublishModesTests.hpp
DimaRU/Fast-DDS
4874d11575f396f7787c0f93254a989e7f523e68
[ "Apache-2.0" ]
1,110
2015-04-20T19:30:34.000Z
2020-06-01T08:13:52.000Z
test/unittest/rtps/flowcontrol/FlowControllerPublishModesTests.hpp
DimaRU/Fast-DDS
4874d11575f396f7787c0f93254a989e7f523e68
[ "Apache-2.0" ]
273
2015-08-10T23:34:42.000Z
2020-05-28T13:03:32.000Z
#ifndef _UNITTEST_RTPS_FLOWCONTROL_FLOWCONTROLLERPUBLISHMODESTESTS_HPP_ #define _UNITTEST_RTPS_FLOWCONTROL_FLOWCONTROLLERPUBLISHMODESTESTS_HPP_ #include <rtps/flowcontrol/FlowControllerImpl.hpp> #include <fastdds/rtps/flowcontrol/FlowControllerDescriptor.hpp> #include <gtest/gtest.h> namespace eprosima { namespace fastrtps { namespace rtps { std::ostream& operator <<( std::ostream& output, const RTPSWriter& writer); std::ostream& operator <<( std::ostream& output, const CacheChange_t* change); } // namespace rtps } // namespace fastrtps } // namespace eprosima template<typename T> class FlowControllerPublishModes : public testing::Test { protected: void TearDown() override { changes_delivered.clear(); current_bytes_processed = 0; } void wait_changes_was_delivered( size_t number_of_changes) { std::unique_lock<std::mutex> lock(changes_delivered_mutex); number_changes_delivered_cv.wait(lock, [&]() { return number_of_changes == changes_delivered.size(); }); } std::thread::id last_thread_delivering_sample; std::vector<eprosima::fastrtps::rtps::CacheChange_t*> changes_delivered; std::mutex changes_delivered_mutex; std::condition_variable number_changes_delivered_cv; uint32_t current_bytes_processed = 0; }; using Schedulers = ::testing::Types<eprosima::fastdds::rtps::FlowControllerFifoSchedule, eprosima::fastdds::rtps::FlowControllerRoundRobinSchedule, eprosima::fastdds::rtps::FlowControllerHighPrioritySchedule, eprosima::fastdds::rtps::FlowControllerPriorityWithReservationSchedule>; TYPED_TEST_SUITE(FlowControllerPublishModes, Schedulers, ); #define INIT_CACHE_CHANGE(change, writer, seq) \ change.writerGUID = writer.getGuid(); \ change.writer_info.previous = nullptr; \ change.writer_info.next = nullptr; \ change.sequenceNumber.low = uint32_t(seq); \ change.serializedPayload.length = 10000; #endif // _UNITTEST_RTPS_FLOWCONTROL_FLOWCONTROLLERPUBLISHMODESTESTS_HPP_
30.239437
88
0.721006
DimaRU
1cd0cf5ecbbe8841e0e7e2590602d3beb871fa74
23,191
cpp
C++
RenderCore/Assets/RawMaterial.cpp
pocketgems/XLE2
82771e9ab1fc3b12927f1687bbe05d4f7dce8765
[ "MIT" ]
3
2018-05-17T08:39:39.000Z
2020-12-09T13:20:26.000Z
RenderCore/Assets/RawMaterial.cpp
pocketgems/XLE2
82771e9ab1fc3b12927f1687bbe05d4f7dce8765
[ "MIT" ]
null
null
null
RenderCore/Assets/RawMaterial.cpp
pocketgems/XLE2
82771e9ab1fc3b12927f1687bbe05d4f7dce8765
[ "MIT" ]
1
2021-11-14T08:50:15.000Z
2021-11-14T08:50:15.000Z
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "RawMaterial.h" #include "../StateDesc.h" #include "../../Assets/Assets.h" #include "../../Assets/IntermediateAssets.h" // (for GetDependentFileState) #include "../../Assets/DeferredConstruction.h" #include "../../Assets/ConfigFileContainer.h" #include "../../Utility/Streams/StreamFormatter.h" #include "../../Utility/Streams/StreamDOM.h" #include "../../Utility/Streams/PathUtils.h" #include "../../Utility/StringFormat.h" namespace RenderCore { namespace Assets { static const auto s_MaterialCompileProcessType = ConstHash64<'RawM', 'at'>::Value; /////////////////////////////////////////////////////////////////////////////////////////////////// static const std::pair<Blend, const utf8*> s_blendNames[] = { std::make_pair(Blend::Zero, u("zero")), std::make_pair(Blend::One, u("one")), std::make_pair(Blend::SrcColor, u("srccolor")), std::make_pair(Blend::InvSrcColor, u("invsrccolor")), std::make_pair(Blend::DestColor, u("destcolor")), std::make_pair(Blend::InvDestColor, u("invdestcolor")), std::make_pair(Blend::SrcAlpha, u("srcalpha")), std::make_pair(Blend::InvSrcAlpha, u("invsrcalpha")), std::make_pair(Blend::DestAlpha, u("destalpha")), std::make_pair(Blend::InvDestAlpha, u("invdestalpha")), }; static const std::pair<BlendOp, const utf8*> s_blendOpNames[] = { std::make_pair(BlendOp::NoBlending, u("noblending")), std::make_pair(BlendOp::NoBlending, u("none")), std::make_pair(BlendOp::NoBlending, u("false")), std::make_pair(BlendOp::Add, u("add")), std::make_pair(BlendOp::Subtract, u("subtract")), std::make_pair(BlendOp::RevSubtract, u("revSubtract")), std::make_pair(BlendOp::Min, u("min")), std::make_pair(BlendOp::Max, u("max")) }; static Blend DeserializeBlend( DocElementHelper<InputStreamFormatter<utf8>> ele, const utf8 name[]) { if (ele) { auto child = ele.Attribute(name); if (child) { auto value = child.Value(); for (unsigned c=0; c<dimof(s_blendNames); ++c) if (XlEqStringI(value, s_blendNames[c].second)) return s_blendNames[c].first; return (Blend)XlAtoI32((const char*)child.Value().AsString().c_str()); } } return Blend::Zero; } static BlendOp DeserializeBlendOp( DocElementHelper<InputStreamFormatter<utf8>> ele, const utf8 name[]) { if (ele) { auto child = ele.Attribute(name); if (child) { auto value = child.Value(); for (unsigned c=0; c<dimof(s_blendOpNames); ++c) if (XlEqStringI(value, s_blendOpNames[c].second)) return s_blendOpNames[c].first; return (BlendOp)XlAtoI32((const char*)child.Value().AsString().c_str()); } } return BlendOp::NoBlending; } static RenderStateSet DeserializeStateSet(InputStreamFormatter<utf8>& formatter) { RenderStateSet result; Document<InputStreamFormatter<utf8>> doc(formatter); { auto child = doc.Attribute(u("DoubleSided")).As<bool>(); if (child.first) { result._doubleSided = child.second; result._flag |= RenderStateSet::Flag::DoubleSided; } } { auto child = doc.Attribute(u("Wireframe")).As<bool>(); if (child.first) { result._wireframe = child.second; result._flag |= RenderStateSet::Flag::Wireframe; } } { auto child = doc.Attribute(u("WriteMask")).As<unsigned>(); if (child.first) { result._writeMask = child.second; result._flag |= RenderStateSet::Flag::WriteMask; } } { auto child = doc.Attribute(u("BlendType")); if (child) { if (XlEqStringI(child.Value(), u("decal"))) { result._blendType = RenderStateSet::BlendType::DeferredDecal; } else if (XlEqStringI(child.Value(), u("ordered"))) { result._blendType = RenderStateSet::BlendType::Ordered; } else { result._blendType = RenderStateSet::BlendType::Basic; } result._flag |= RenderStateSet::Flag::BlendType; } } { auto child = doc.Attribute(u("DepthBias")).As<int>(); if (child.first) { result._depthBias = child.second; result._flag |= RenderStateSet::Flag::DepthBias; } } { auto child = doc.Element(u("ForwardBlend")); if (child) { result._forwardBlendSrc = DeserializeBlend(child, u("Src")); result._forwardBlendDst = DeserializeBlend(child, u("Dst")); result._forwardBlendOp = DeserializeBlendOp(child, u("Op")); result._flag |= RenderStateSet::Flag::ForwardBlend; } } return result; } static const utf8* AsString(RenderStateSet::BlendType blend) { switch (blend) { case RenderStateSet::BlendType::DeferredDecal: return u("decal"); case RenderStateSet::BlendType::Ordered: return u("ordered"); default: case RenderStateSet::BlendType::Basic: return u("basic"); } } static const utf8* AsString(Blend input) { for (unsigned c=0; c<dimof(s_blendNames); ++c) { if (s_blendNames[c].first == input) { return s_blendNames[c].second; } } return u("one"); } static const utf8* AsString(BlendOp input) { for (unsigned c=0; c<dimof(s_blendOpNames); ++c) { if (s_blendOpNames[c].first == input) { return s_blendOpNames[c].second; } } return u("noblending"); } template<typename Type> std::basic_string<utf8> AutoAsString(const Type& type) { return Conversion::Convert<std::basic_string<utf8>>( ImpliedTyping::AsString(type, true)); } static bool HasSomethingToSerialize(const RenderStateSet& stateSet) { return stateSet._flag != 0; } static void SerializeStateSet(OutputStreamFormatter& formatter, const RenderStateSet& stateSet) { if (stateSet._flag & RenderStateSet::Flag::DoubleSided) formatter.WriteAttribute(u("DoubleSided"), AutoAsString(stateSet._doubleSided)); if (stateSet._flag & RenderStateSet::Flag::Wireframe) formatter.WriteAttribute(u("Wireframe"), AutoAsString(stateSet._wireframe)); if (stateSet._flag & RenderStateSet::Flag::WriteMask) formatter.WriteAttribute(u("WriteMask"), AutoAsString(stateSet._writeMask)); if (stateSet._flag & RenderStateSet::Flag::BlendType) formatter.WriteAttribute(u("BlendType"), AsString(stateSet._blendType)); if (stateSet._flag & RenderStateSet::Flag::DepthBias) formatter.WriteAttribute(u("DepthBias"), AutoAsString(stateSet._depthBias)); if (stateSet._flag & RenderStateSet::Flag::ForwardBlend) { auto ele = formatter.BeginElement(u("ForwardBlend")); formatter.WriteAttribute(u("Src"), AsString(stateSet._forwardBlendSrc)); formatter.WriteAttribute(u("Dst"), AsString(stateSet._forwardBlendDst)); formatter.WriteAttribute(u("Op"), AsString(stateSet._forwardBlendOp)); formatter.EndElement(ele); } } RenderStateSet Merge(RenderStateSet underride, RenderStateSet override) { RenderStateSet result = underride; if (override._flag & RenderStateSet::Flag::DoubleSided) { result._doubleSided = override._doubleSided; result._flag |= RenderStateSet::Flag::DoubleSided; } if (override._flag & RenderStateSet::Flag::Wireframe) { result._wireframe = override._wireframe; result._flag |= RenderStateSet::Flag::Wireframe; } if (override._flag & RenderStateSet::Flag::WriteMask) { result._writeMask = override._writeMask; result._flag |= RenderStateSet::Flag::WriteMask; } if (override._flag & RenderStateSet::Flag::BlendType) { result._blendType = override._blendType; result._flag |= RenderStateSet::Flag::BlendType; } if (override._flag & RenderStateSet::Flag::ForwardBlend) { result._forwardBlendSrc = override._forwardBlendSrc; result._forwardBlendDst = override._forwardBlendDst; result._forwardBlendOp = override._forwardBlendOp; result._flag |= RenderStateSet::Flag::ForwardBlend; } if (override._flag & RenderStateSet::Flag::DepthBias) { result._depthBias = override._depthBias; result._flag |= RenderStateSet::Flag::DepthBias; } return result; } RawMaterial::RawMaterial() {} std::vector<::Assets::rstring> DeserializeInheritList(InputStreamFormatter<utf8>& formatter) { std::vector<::Assets::rstring> result; for (;;) { using Blob = InputStreamFormatter<utf8>::Blob; switch (formatter.PeekNext()) { case Blob::AttributeName: { InputStreamFormatter<utf8>::InteriorSection name, value; formatter.TryAttribute(name, value); result.push_back( Conversion::Convert<::Assets::rstring>(std::basic_string<utf8>(name._start, name._end))); break; } case Blob::BeginElement: { InputStreamFormatter<utf8>::InteriorSection eleName; formatter.TryBeginElement(eleName); break; } case Blob::AttributeValue: case Blob::CharacterData: Throw(FormatException("Unexpected element", formatter.GetLocation())); break; case Blob::EndElement: case Blob::None: return result; default: assert(0); } } } RawMaterial::RawMaterial( InputStreamFormatter<utf8>& formatter, const ::Assets::DirectorySearchRules& searchRules, const ::Assets::DepValPtr& depVal) : _depVal(depVal), _searchRules(searchRules) { for (;;) { using Blob = InputStreamFormatter<utf8>::Blob; switch (formatter.PeekNext()) { case Blob::AttributeName: { InputStreamFormatter<utf8>::InteriorSection name, value; formatter.TryAttribute(name, value); break; } case Blob::BeginElement: { InputStreamFormatter<utf8>::InteriorSection eleName; formatter.TryBeginElement(eleName); // first, load inherited settings. if (XlEqString(eleName, u("Inherit"))) { _inherit = DeserializeInheritList(formatter); } else if (XlEqString(eleName, u("ShaderParams"))) { _matParamBox = ParameterBox(formatter); } else if (XlEqString(eleName, u("Constants"))) { _constants = ParameterBox(formatter); } else if (XlEqString(eleName, u("ResourceBindings"))) { _resourceBindings = ParameterBox(formatter); } else if (XlEqString(eleName, u("States"))) { _stateSet = DeserializeStateSet(formatter); } else if (XlEqString(eleName, u("Patches"))) { _patchCollection = ShaderPatchCollection(formatter, searchRules, depVal); } else { formatter.SkipElement(); } if (!formatter.TryEndElement()) Throw(FormatException("Expecting end element", formatter.GetLocation())); break; } case Blob::AttributeValue: case Blob::CharacterData: Throw(FormatException("Unexpected element", formatter.GetLocation())); break; case Blob::EndElement: case Blob::None: return; default: assert(0); } } } RawMaterial::~RawMaterial() {} void RawMaterial::SerializeMethod(OutputStreamFormatter& formatter) const { if (!_patchCollection.GetPatches().empty()) { auto ele = formatter.BeginElement(u("Patches")); Serialize(formatter, _patchCollection); formatter.EndElement(ele); } if (!_inherit.empty()) { auto ele = formatter.BeginElement(u("Inherit")); for (auto i=_inherit.cbegin(); i!=_inherit.cend(); ++i) { auto str = Conversion::Convert<std::basic_string<utf8>>(*i); formatter.WriteAttribute( AsPointer(str.cbegin()), AsPointer(str.cend()), (const utf8*)nullptr, (const utf8*)nullptr); } formatter.EndElement(ele); } if (_matParamBox.GetCount() > 0) { auto ele = formatter.BeginElement(u("ShaderParams")); _matParamBox.SerializeWithCharType<utf8>(formatter); formatter.EndElement(ele); } if (_constants.GetCount() > 0) { auto ele = formatter.BeginElement(u("Constants")); _constants.SerializeWithCharType<utf8>(formatter); formatter.EndElement(ele); } if (_resourceBindings.GetCount() > 0) { auto ele = formatter.BeginElement(u("ResourceBindings")); _resourceBindings.SerializeWithCharType<utf8>(formatter); formatter.EndElement(ele); } if (HasSomethingToSerialize(_stateSet)) { auto ele = formatter.BeginElement(u("States")); SerializeStateSet(formatter, _stateSet); formatter.EndElement(ele); } } void RawMaterial::MergeInto(RawMaterial& dest) const { dest._matParamBox.MergeIn(_matParamBox); dest._stateSet = Merge(dest._stateSet, _stateSet); dest._constants.MergeIn(_constants); dest._resourceBindings.MergeIn(_resourceBindings); _patchCollection.MergeInto(dest._patchCollection); } void ResolveMaterialFilename( ::Assets::ResChar resolvedFile[], unsigned resolvedFileCount, const ::Assets::DirectorySearchRules& searchRules, StringSection<char> baseMatName) { auto splitName = MakeFileNameSplitter(baseMatName); searchRules.ResolveFile(resolvedFile, resolvedFileCount, splitName.AllExceptParameters()); XlCatString(resolvedFile, resolvedFileCount, splitName.ParametersWithDivider()); } auto RawMaterial::ResolveInherited( const ::Assets::DirectorySearchRules& searchRules) const -> std::vector<AssetName> { std::vector<AssetName> result; for (auto i=_inherit.cbegin(); i!=_inherit.cend(); ++i) { auto name = *i; auto* colon = XlFindCharReverse(name.c_str(), ':'); if (colon) { ::Assets::ResChar resolvedFile[MaxPath]; XlCopyNString(resolvedFile, name.c_str(), colon-name.c_str()); ResolveMaterialFilename(resolvedFile, dimof(resolvedFile), searchRules, resolvedFile); StringMeld<MaxPath, ::Assets::ResChar> finalRawMatName; finalRawMatName << resolvedFile << colon; result.push_back((AssetName)finalRawMatName); } else { result.push_back(name); } } return result; } RawMatConfigurations::RawMatConfigurations( const ::Assets::Blob& blob, const ::Assets::DepValPtr& depVal, StringSection<::Assets::ResChar>) { // Get associated "raw" material information. This is should contain the material information attached // to the geometry export (eg, .dae file). if (!blob || blob->size() == 0) Throw(::Exceptions::BasicLabel("Missing or empty file")); InputStreamFormatter<utf8> formatter( MemoryMappedInputStream(MakeIteratorRange(*blob))); Document<decltype(formatter)> doc(formatter); for (auto config=doc.FirstChild(); config; config=config.NextSibling()) { auto name = config.Name(); if (name.IsEmpty()) continue; _configurations.push_back(name.AsString()); } _validationCallback = depVal; } static bool IsMaterialFile(StringSection<::Assets::ResChar> extension) { return XlEqStringI(extension, "material") || XlEqStringI(extension, "hlsl"); } void RawMaterial::ConstructToFuture( ::Assets::AssetFuture<RawMaterial>& future, StringSection<::Assets::ResChar> initializer) { // If we're loading from a .material file, then just go head and use the // default asset construction // Otherwise, we need to invoke a compile and load of a ConfigFileContainer auto splitName = MakeFileNameSplitter(initializer); if (IsMaterialFile(splitName.Extension())) { AutoConstructToFutureDirect(future, initializer); return; } // auto containerInitializer = splitName.AllExceptParameters(); auto containerFuture = std::make_shared<::Assets::AssetFuture<::Assets::ConfigFileContainer<>>>(containerInitializer.AsString()); ::Assets::DefaultCompilerConstruction( *containerFuture, &containerInitializer, 1, s_MaterialCompileProcessType); std::string containerInitializerString = containerInitializer.AsString(); std::string section = splitName.Parameters().AsString(); future.SetPollingFunction( [containerFuture, section, containerInitializerString](::Assets::AssetFuture<RawMaterial>& thatFuture) -> bool { std::shared_ptr<::Assets::ConfigFileContainer<>> containerActual; ::Assets::DepValPtr containerDepVal; ::Assets::Blob containerLog; auto containerState = containerFuture->CheckStatusBkgrnd(containerActual, containerDepVal, containerLog); if (!containerActual) { if (containerState == ::Assets::AssetState::Invalid) { thatFuture.SetInvalidAsset(containerDepVal, containerLog); return false; } return true; } auto fmttr = containerActual->GetFormatter(MakeStringSection(section).Cast<utf8>()); auto newShader = std::make_shared<RawMaterial>( fmttr, ::Assets::DefaultDirectorySearchRules(containerInitializerString), containerActual->GetDependencyValidation()); thatFuture.SetAsset(std::move(newShader), {}); return false; }); } void MergeInto(MaterialScaffold::Material& dest, ShaderPatchCollection& destPatchCollection, const RawMaterial& source) { dest._matParams.MergeIn(source._matParamBox); dest._stateSet = Merge(dest._stateSet, source._stateSet); dest._constants.MergeIn(source._constants); // Resolve all of the directory names here, as we write into the Techniques::Material for (const auto&b:source._resourceBindings) { auto unresolvedName = b.ValueAsString(); if (!unresolvedName.empty()) { char resolvedName[MaxPath]; source.GetDirectorySearchRules().ResolveFile(resolvedName, unresolvedName); dest._bindings.SetParameter(b.Name(), MakeStringSection(resolvedName)); } else { dest._bindings.SetParameter(b.Name(), MakeStringSection(unresolvedName)); } } source._patchCollection.MergeInto(destPatchCollection); dest._patchCollection = destPatchCollection.GetHash(); } static void AddDep( std::vector<::Assets::DependentFileState>& deps, StringSection<::Assets::ResChar> newDep) { // we need to call "GetDependentFileState" first, because this can change the // format of the filename. String compares alone aren't working well for us here auto depState = ::Assets::IntermediateAssets::Store::GetDependentFileState(newDep); auto existing = std::find_if( deps.cbegin(), deps.cend(), [&](const ::Assets::DependentFileState& test) { return test._filename == depState._filename; }); if (existing == deps.cend()) deps.push_back(depState); } void MergeIn_Stall( MaterialScaffold::Material& result, ShaderPatchCollection& patchCollectionResult, StringSection<> sourceMaterialName, const ::Assets::DirectorySearchRules& searchRules, std::vector<::Assets::DependentFileState>& deps) { // resolve all of the inheritance options and generate a final // ResolvedMaterial object. We need to start at the bottom of the // inheritance tree, and merge in new parameters as we come across them. // we still need to add a dependency, even if it's a missing file AddDep(deps, MakeFileNameSplitter(sourceMaterialName).AllExceptParameters()); auto dependencyMat = ::Assets::MakeAsset<RawMaterial>(sourceMaterialName); auto state = dependencyMat->StallWhilePending(); if (state == ::Assets::AssetState::Ready) { auto source = dependencyMat->Actualize(); auto childSearchRules = source->GetDirectorySearchRules(); childSearchRules.Merge(searchRules); for (const auto& child: source->ResolveInherited(searchRules)) MergeIn_Stall(result, patchCollectionResult, child, childSearchRules, deps); MergeInto(result, patchCollectionResult, *source); } } void MergeIn_Stall( MaterialScaffold::Material& result, ShaderPatchCollection& patchCollectionResult, const RenderCore::Assets::RawMaterial& src, const ::Assets::DirectorySearchRules& searchRules) { auto childSearchRules = searchRules; childSearchRules.Merge(src.GetDirectorySearchRules()); for (const auto& child : src.ResolveInherited(childSearchRules)) { auto dependencyMat = ::Assets::MakeAsset<RawMaterial>(child); auto state = dependencyMat->StallWhilePending(); if (state == ::Assets::AssetState::Ready) { MergeIn_Stall(result, patchCollectionResult, *dependencyMat->Actualize(), childSearchRules); } } MergeInto(result, patchCollectionResult, src); } MaterialGuid MakeMaterialGuid(StringSection<utf8> name) { // If the material name is just a number, then we will use that // as the guid. Otherwise we hash the name. const char* parseEnd = nullptr; uint64 hashId = XlAtoI64((const char*)name.begin(), &parseEnd, 16); if (!parseEnd || parseEnd != (const char*)name.end()) { hashId = Hash64(name.begin(), name.end()); } return hashId; } }}
38.395695
152
0.61291
pocketgems
1cd0fba7ad7b9b9b41979c4fc1838b36feb30c63
1,719
cpp
C++
source/main.cpp
MatthewScholefield/musidy-app
24b1007619e3137bf97ad9e3917d3560fbbd9f21
[ "MIT" ]
null
null
null
source/main.cpp
MatthewScholefield/musidy-app
24b1007619e3137bf97ad9e3917d3560fbbd9f21
[ "MIT" ]
null
null
null
source/main.cpp
MatthewScholefield/musidy-app
24b1007619e3137bf97ad9e3917d3560fbbd9f21
[ "MIT" ]
null
null
null
#include <SDL_events.h> #include <iostream> #include "Renderer.hpp" #include "Instrument.hpp" #include "CLI11.hpp" #include "songCreation/ScorePlayer.hpp" #include "Interface.hpp" #include "SoundSystem.hpp" struct Arguments { Arguments(int argc, char **argv) : app("Dynamic Music Generation App") { app.ignore_case(); app.add_option("soundfont_file", instrument, "Soundfont file (.sf2) to play song with")->required(); app.add_option("-g,--gain", gain, "Volume gain of instrument (negative or positive decimal)"); } CLI::App app; std::string instrument; float gain = 0.f; }; int main(int argc, char **argv) { srand((unsigned int) time(nullptr)); Arguments args(argc, argv); CLI11_PARSE(args.app, argc, argv); std::cout << "Loading instrument..." << std::endl; Instrument instrument(args.instrument, args.gain); std::cout << "Starting app..." << std::endl; SdlWindow window; Renderer renderer(window); ParticleSystem particles; SoundSystem system([&](float *f, size_t n) { instrument.render(f, n); }); ScorePlayer generator(instrument, particles); Interface interface(generator, window, instrument); std::cout << "Tonality: " << tonalityToString(instrument.getTonality()) << std::endl; for (int chord : generator.getProgression()) { std::cout << ((chord + 7 * 100) % 7) + 1 << " "; } std::cout << std::endl; while (window.update()) { renderer.begin(30, 30, 30); particles.render(renderer); interface.render(renderer); renderer.finish(); double dt = renderer.getDelta(); generator.update(instrument, dt); particles.update(dt); } }
30.157895
108
0.63758
MatthewScholefield
1cd20ea69db65faa31c7758f34d5bd55d3601cd3
2,219
cc
C++
src/search_local/index_storage/common/shmem.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
3
2021-08-18T09:59:42.000Z
2021-09-07T03:11:28.000Z
src/search_local/index_storage/common/shmem.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
src/search_local/index_storage/common/shmem.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
/* * ===================================================================================== * * Filename: sheme.cc * * Description: * * Version: 1.0 * Created: 09/08/2020 10:02:05 PM * Revision: none * Compiler: gcc * * Author: qiulu, choulu@jd.com * Company: JD.com, Inc. * * ===================================================================================== */ #include <stddef.h> #include <stdio.h> #include <unistd.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/mman.h> #include "shmem.h" #include "system_lock.h" SharedMemory::SharedMemory() : m_key(0), m_id(0), m_size(0), m_ptr(NULL), lockfd(-1) { } SharedMemory::~SharedMemory() { Detach(); Unlock(); } unsigned long SharedMemory::Open(int key) { if (m_ptr) Detach(); if (key == 0) return 0; m_key = key; if ((m_id = shmget(m_key, 0, 0)) == -1) return 0; struct shmid_ds ds; if (shmctl(m_id, IPC_STAT, &ds) < 0) return 0; return m_size = ds.shm_segsz; } unsigned long SharedMemory::Create(int key, unsigned long size) { if (m_ptr) Detach(); m_key = key; if (m_key == 0) { m_ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (m_ptr != MAP_FAILED) m_size = size; else m_ptr = NULL; } else { if ((m_id = shmget(m_key, size, IPC_CREAT | IPC_EXCL | IPC_PERM)) == -1) return 0; struct shmid_ds ds; if (shmctl(m_id, IPC_STAT, &ds) < 0) return 0; m_size = ds.shm_segsz; } return m_size; } void *SharedMemory::Attach(int ro) { if (m_ptr) return m_ptr; m_ptr = shmat(m_id, NULL, ro ? SHM_RDONLY : 0); if (m_ptr == MAP_FAILED) m_ptr = NULL; return m_ptr; } void SharedMemory::Detach(void) { if (m_ptr) { if (m_key == 0) munmap(m_ptr, m_size); else shmdt(m_ptr); } m_ptr = NULL; } int SharedMemory::Lock(void) { if (lockfd > 0 || m_key == 0) return 0; lockfd = unix_socket_lock("tlock-shm-%u", m_key); if (lockfd < 0) return -1; return 0; } void SharedMemory::Unlock(void) { if (lockfd > 0) { close(lockfd); lockfd = -1; } } int SharedMemory::Delete(void) { Detach(); if (shmctl(m_id, IPC_RMID, NULL) < 0) return -1; return 0; }
16.07971
88
0.553853
jdisearch
1cd7023f82b12ca43c163864d644d886b6650211
359
cpp
C++
Raven/src/Application.cpp
IridescentRose/Raven-Client
e39a88eef8d56067387acaaad19ec44ddaab3869
[ "MIT" ]
10
2020-10-05T23:11:25.000Z
2022-01-30T13:22:33.000Z
Raven/src/Application.cpp
IridescentRose/Raven-Client
e39a88eef8d56067387acaaad19ec44ddaab3869
[ "MIT" ]
3
2020-07-09T16:08:54.000Z
2020-08-05T19:58:41.000Z
Raven/src/Application.cpp
NT-Bourgeois-Iridescence-Technologies/Raven-Client
e39a88eef8d56067387acaaad19ec44ddaab3869
[ "MIT" ]
2
2021-02-06T08:01:26.000Z
2021-06-19T07:39:59.000Z
#include "Application.h" #include "States/Logo.h" Application::Application() { stateMan = new Core::GameStateManager(); } Application::~Application() { } void Application::init() { Logo* logo = new Logo(); logo->init(); stateMan->addState(logo); } void Application::update() { stateMan->update(); } void Application::draw() { stateMan->draw(); }
11.580645
41
0.668524
IridescentRose
1cd7199367381b631390d66b84fbe8c2737220d6
2,084
cc
C++
src/q_51_100/q0094.cc
vNaonLu/daily-leetcode
2830c2cd413d950abe7c6d9b833c771f784443b0
[ "MIT" ]
2
2021-09-28T18:41:03.000Z
2021-09-28T18:42:57.000Z
src/q_51_100/q0094.cc
vNaonLu/Daily_LeetCode
30024b561611d390931cef1b22afd6a5060cf586
[ "MIT" ]
16
2021-09-26T11:44:20.000Z
2021-11-28T06:44:02.000Z
src/q_51_100/q0094.cc
vNaonLu/daily-leetcode
2830c2cd413d950abe7c6d9b833c771f784443b0
[ "MIT" ]
1
2021-11-22T09:11:36.000Z
2021-11-22T09:11:36.000Z
#include <gtest/gtest.h> #include <iostream> #include <leetcode/treenode.hpp> #include <vector> using namespace std; /** * This file is generated by leetcode_add.py v1.0 * * 94. * Binary Tree Inorder Traversal * * ––––––––––––––––––––––––––––– Description ––––––––––––––––––––––––––––– * * Given the β€˜root’ of a binary tree, return β€œthe inorder traversal of * its nodes' values” . * * ––––––––––––––––––––––––––––– Constraints ––––––––––––––––––––––––––––– * * β€’ The number of nodes in the tree is in the range β€˜[0, 100]’ . * β€’ β€˜-100 ≀ Node.val ≀ 100’ * */ struct q94 : public ::testing::Test { // Leetcode answer here class Solution { private: void helper(TreeNode *p, vector<int> &re) { if (p == nullptr) return; helper(p->left, re); re.push_back(p->val); helper(p->right, re); } public: vector<int> inorderTraversal(TreeNode *root) { vector<int> res; helper(root, res); return res; } }; class Solution *solution; }; TEST_F(q94, sample_input01) { solution = new Solution(); TreeNode* root = TreeNode::generate({1, NULL_TREENODE, 2, 3}); vector<int> exp = {1, 3, 2}; EXPECT_EQ(solution->inorderTraversal(root), exp); delete solution; } TEST_F(q94, sample_input02) { solution = new Solution(); TreeNode* root = TreeNode::generate({}); vector<int> exp = {}; EXPECT_EQ(solution->inorderTraversal(root), exp); delete solution; } TEST_F(q94, sample_input03) { solution = new Solution(); TreeNode* root = TreeNode::generate({1}); vector<int> exp = {1}; EXPECT_EQ(solution->inorderTraversal(root), exp); delete solution; } TEST_F(q94, sample_input04) { solution = new Solution(); TreeNode* root = TreeNode::generate({1, 2}); vector<int> exp = {2, 1}; EXPECT_EQ(solution->inorderTraversal(root), exp); delete solution; } TEST_F(q94, sample_input05) { solution = new Solution(); TreeNode* root = TreeNode::generate({1, NULL_TREENODE, 2}); vector<int> exp = {1, 2}; EXPECT_EQ(solution->inorderTraversal(root), exp); delete solution; }
24.517647
74
0.608925
vNaonLu
1cdccb774695f7fb9de9e7019b2cddf6a32e8cb5
1,556
hh
C++
mimosa/http/crud-handler.hh
abique/mimosa
42c0041b570b55a24c606a7da79c70c9933c07d4
[ "MIT" ]
24
2015-01-19T16:38:24.000Z
2022-01-15T01:25:30.000Z
mimosa/http/crud-handler.hh
abique/mimosa
42c0041b570b55a24c606a7da79c70c9933c07d4
[ "MIT" ]
2
2017-01-07T10:47:06.000Z
2018-01-16T07:19:57.000Z
mimosa/http/crud-handler.hh
abique/mimosa
42c0041b570b55a24c606a7da79c70c9933c07d4
[ "MIT" ]
7
2015-01-19T16:38:31.000Z
2020-12-12T19:10:30.000Z
#pragma once # include "handler.hh" namespace mimosa { namespace http { /** * This handler helps you to map CRUD web services. * You have to override methods you wish to implement, * and the other ones will reply 501 (NotImplemented). */ class CrudHandler : public Handler { public: /** * This method matches the INSERT SQL statement or the POST * HTTP request. */ virtual bool create(RequestReader & request, ResponseWriter & response) const; /** * This method matches the SELECT SQL statement or the GET * HTTP request. */ virtual bool read(RequestReader & request, ResponseWriter & response) const; /** * This method matches the UPDATE SQL statement or the PUT * HTTP request. */ virtual bool update(RequestReader & request, ResponseWriter & response) const; /** * This method matches the DELETE SQL statement or the DELETE * HTTP request. This method is not named delete because of the * C++ keyword delete. */ virtual bool destroy(RequestReader & request, ResponseWriter & response) const; /** * This method should not be overridden and dispatches requests, * over create/read/update/destroy. */ virtual bool handle(RequestReader & request, ResponseWriter & response) const override final; }; } }
27.785714
74
0.582262
abique