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
d7ef285c805d115f3739bf9c295f6c1f37a00f1e
954
cpp
C++
src/binary/socket-server/test/MainTest.cpp
heaven-chp/base-server-cpp
87213259c61c93a791d087f4b284f79f0f05574c
[ "Apache-2.0" ]
null
null
null
src/binary/socket-server/test/MainTest.cpp
heaven-chp/base-server-cpp
87213259c61c93a791d087f4b284f79f0f05574c
[ "Apache-2.0" ]
1
2021-12-19T13:36:19.000Z
2021-12-19T14:07:14.000Z
src/binary/socket-server/test/MainTest.cpp
heaven-chp/base-server-cpp
87213259c61c93a791d087f4b284f79f0f05574c
[ "Apache-2.0" ]
null
null
null
#include "test.h" #include "../Main.h" #include "gtest/gtest.h" #include "Singleton.h" #include "EnvironmentVariable.h" static void test(int iArgc, char *pcArgv[]) { const int iPid = fork(); ASSERT_NE(iPid, -1); extern int optind; optind = 1; if(iPid == 0) { EXPECT_TRUE(Main().Run(iArgc, pcArgv)); exit(testing::Test::HasFailure()); } this_thread::sleep_for(chrono::seconds(2)); EXPECT_FALSE(Main().Run(iArgc, pcArgv)); EXPECT_STREQ(send_command("stop", true).c_str(), "200 ok\r\n"); this_thread::sleep_for(chrono::seconds(2)); } TEST(MainTest, Run) { EXPECT_FALSE(Main().Run(0, nullptr)); } TEST(MainTest, StandAlone) { int iArgc = 4; char *pcArgv[] = {(char *)"./MainTest", (char *)"-c", (char *)GstrConfigPath.c_str(), (char *)"-s"}; test(iArgc, pcArgv); } TEST(MainTest, NonStandAlone) { int iArgc = 3; char *pcArgv[] = {(char *)"./MainTest", (char *)"-c", (char *)GstrConfigPath.c_str()}; test(iArgc, pcArgv); }
18.346154
101
0.644654
heaven-chp
d7f002903117701f16c8e4bd4c26b09523c853a8
1,882
cpp
C++
src/views/oscilloscope/LCurve.cpp
lotusczp/Lobster
ceb5ec720fdbbd5eddba5eeccc2f875a62d4332e
[ "Apache-2.0", "MIT" ]
6
2021-01-30T00:06:22.000Z
2022-02-16T08:20:09.000Z
src/views/oscilloscope/LCurve.cpp
lotusczp/Lobster
ceb5ec720fdbbd5eddba5eeccc2f875a62d4332e
[ "Apache-2.0", "MIT" ]
null
null
null
src/views/oscilloscope/LCurve.cpp
lotusczp/Lobster
ceb5ec720fdbbd5eddba5eeccc2f875a62d4332e
[ "Apache-2.0", "MIT" ]
1
2021-08-11T05:19:11.000Z
2021-08-11T05:19:11.000Z
#include "LCurve.h" LCurve::LCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) { m_pLine = new QCPGraph(keyAxis, valueAxis); connect(m_pLine, SIGNAL(selectionChanged(bool)), this, SLOT(receiveCurveSelected(bool))); } LCurve::~LCurve() { //! \note No need to delete m_pLine, its ownership belongs to QCustomPlot instance } void LCurve::setName(const QString &a_rName) { m_pLine->setName(a_rName); } QString LCurve::getName() const { return m_pLine->name(); } void LCurve::addPoint(const QPointF &a_rPoint) { m_pLine->addData(a_rPoint.x(), a_rPoint.y()); } void LCurve::clear() { m_pLine->setData(QVector<double>(), QVector<double>()); } void LCurve::setColor(const QColor& a_rColor) { QPen pen = m_pLine->pen(); pen.setColor(a_rColor); m_pLine->setPen(pen); #if 0 pen = m_pLine->keyAxis()->basePen(); pen.setColor(a_rColor); m_pLine->valueAxis()->setBasePen(pen); pen = m_pLine->keyAxis()->tickPen(); pen.setColor(a_rColor); m_pLine->valueAxis()->setTickPen(pen); pen = m_pLine->keyAxis()->subTickPen(); pen.setColor(a_rColor); m_pLine->valueAxis()->setSubTickPen(pen); #endif } void LCurve::setPenStyle(const Qt::PenStyle &a_rPenStyle) { QPen pen = m_pLine->pen(); if(pen.style() != a_rPenStyle) { pen.setStyle(a_rPenStyle); m_pLine->setPen(pen); } } void LCurve::setSelected(bool a_bSelected) { if(a_bSelected) { QCPDataRange range; // Select the last 2 points if(m_pLine->data()->size() >= 2) { range.setEnd(m_pLine->data()->size()-1); range.setBegin(m_pLine->data()->size()-2); } m_pLine->setSelection(QCPDataSelection(range)); } else { m_pLine->setSelection(QCPDataSelection()); } } void LCurve::receiveCurveSelected(bool a_bSelected) { emit sendCurveSelected(a_bSelected); }
23.234568
93
0.648778
lotusczp
d7f1175d285cbcdd2f16afacb3d11608ff254ee0
784
cpp
C++
Codeforces/711A.cpp
Alipashaimani/Competitive-programming
5d55567b71ea61e69a6450cda7323c41956d3cb9
[ "MIT" ]
null
null
null
Codeforces/711A.cpp
Alipashaimani/Competitive-programming
5d55567b71ea61e69a6450cda7323c41956d3cb9
[ "MIT" ]
null
null
null
Codeforces/711A.cpp
Alipashaimani/Competitive-programming
5d55567b71ea61e69a6450cda7323c41956d3cb9
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; string s[1010][2]; int n; bool flag = false; int main(){ cin >> n; for ( int i = 0 ; i < n ; i++){ string x ; cin >> x; string s1 =""; s1 += x[0]; s1 += x[1]; s[i][0] = s1; s1 = ""; s1 += x[3];s1+=x[4]; s[i][1] = s1; } for ( int i = 0 ; i < n ; i++){ if ( s[i][0] == "OO"){ s[i][0] = "++"; flag = true; break; } else if ( s[i][1] == "OO"){ s[i][1] ="++"; flag = true; break; } } if (!flag) return cout <<"NO\n" , 0; cout << "YES\n"; for ( int i = 0 ; i < n ; i++) cout << s[i][0] << '|' << s[i][1] << '\n'; return 0; }
21.189189
50
0.317602
Alipashaimani
d7f1dee1657f8b89b7415600ec6bdde58e6b9d3e
1,285
cpp
C++
backup/2/codewars/c++/spanish-conjugator.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/codewars/c++/spanish-conjugator.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/codewars/c++/spanish-conjugator.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/codewars/spanish-conjugator.html . using namespace std; using V = std::vector<std::string>; using R = std::unordered_map<std::string, V>; R conjugate(const std::string &verb) { const static R suffix = {{"ar", {"o", "as", "a", "amos", "áis", "an"}}, {"er", {"o", "es", "e", "emos", "éis", "en"}}, {"ir", {"o", "es", "e", "imos", "ís", "en"}}}; int S = verb.size() >= 2 ? verb.size() - 2 : 0; std::string base = verb.substr(0, S), infinitiveSuffix = verb.substr(S); auto it = suffix.find(infinitiveSuffix); R r; if (it != suffix.end()) { for (const auto &i : it->second) { r[verb].push_back(base + i); } } return r; }
42.833333
345
0.607004
yangyanzhan
d7f2c24c55d79b5d81a31bfcf47e661548680f1b
986
hpp
C++
osx-main/src/key_window.hpp
m4c0/m4c0-stl
5e47439528faee466270706534143c87b4af8cbb
[ "MIT" ]
null
null
null
osx-main/src/key_window.hpp
m4c0/m4c0-stl
5e47439528faee466270706534143c87b4af8cbb
[ "MIT" ]
null
null
null
osx-main/src/key_window.hpp
m4c0/m4c0-stl
5e47439528faee466270706534143c87b4af8cbb
[ "MIT" ]
null
null
null
#pragma once #include "m4c0/objc/geometry.hpp" #include "m4c0/objc/ns_window.hpp" #include "metal_view.hpp" namespace m4c0::osx::details { class window : public objc::ns_window { view m_view {}; public: explicit window(const char * title) : ns_window() { using namespace m4c0::objc; constexpr const auto window_width = 800; constexpr const auto window_height = 600; set_content_view(m_view); set_accepts_mouse_moved_events(true); set_title(title); set_style_mask( ns_window_style_mask::titled | ns_window_style_mask::closable | ns_window_style_mask::miniaturizable | ns_window_style_mask::resizable); set_collection_behavior(ns_window_collection_behavior::full_screen_primary); set_frame(cg_rect { {}, { window_width, window_height } }, true); center(); make_key_and_order_front(); } [[nodiscard]] constexpr const auto * content_view() { return &m_view; } }; }
27.388889
110
0.685598
m4c0
d7f2ede87d36e0c112ec2812f082072eb07dde89
12,511
cpp
C++
test/catch/scheduler-test.cpp
malachi-iot/embr-netbuf
501c0ceb251f880d85e112d6eb4e20738791085a
[ "MIT" ]
1
2019-11-17T11:13:05.000Z
2019-11-17T11:13:05.000Z
test/catch/scheduler-test.cpp
malachi-iot/embr
9790f4745dd9ac4a3e927a5167cc49f8947acd92
[ "MIT" ]
null
null
null
test/catch/scheduler-test.cpp
malachi-iot/embr
9790f4745dd9ac4a3e927a5167cc49f8947acd92
[ "MIT" ]
null
null
null
#include <catch.hpp> #include <bitset> #include <embr/scheduler.h> // Not available because we test against C++11 //using namespace std::literals::chrono_literals; struct Item { int event_due; int* counter; }; struct ItemTraits { typedef Item value_type; typedef int time_point; static time_point get_time_point(const Item& item) { return item.event_due; } static bool process(Item& item, time_point) { if(item.counter != nullptr) ++(*item.counter); return false; } }; struct Item2Traits { typedef unsigned time_point; // NOTE: It's preferred to keep app state such as counter off in a pointed to struct // somewhere, since value_type here is copied around a lot during heap sorts. That said, // it's not any kind of specific violation to keep app data in here struct value_type { int counter = 0; time_point wakeup; // DEBT: needed because vector doesn't currently know how to do unassigned by itself // that said, it is partially spec behavior of vector: // https://stackoverflow.com/questions/29920394/vector-of-class-without-default-constructor // however ours deviates because we out of necessity pre allocate value_type() = default; value_type(time_point wakeup) : wakeup{wakeup} {} value_type(const value_type&) = default; /* although enabling all the following works, it hits me we prefer to lean heavily towards * copy-only because move operations imply greater short term overhead and we want this struct * as lightweight as possible value_type(value_type&&) = default; value_type& operator=(const value_type&) = default; value_type& operator=(value_type&&) = default; */ }; static time_point get_time_point(const value_type& v) { return v.wakeup; } static bool process(value_type& v, time_point) { v.wakeup += 10; ++v.counter; return true; } }; struct Item3Traits { typedef estd::chrono::steady_clock::time_point time_point; struct control_structure { typedef Item3Traits::time_point time_point; time_point t; virtual bool process(time_point current_time) = 0; }; typedef control_structure* value_type; static time_point get_time_point(value_type v) { return v->t; } static bool process(value_type v, time_point t) { return v->process(t); } }; struct Item3ControlStructure1 : Item3Traits::control_structure { int counter = 0; virtual bool process(time_point current_time) { ++counter; // DEBT: Looks like estd::chrono doesn't have these overloads sorted yet t += std::chrono::seconds(10); return true; } }; struct Item3ControlStructure2 : Item3Traits::control_structure { int counter = 0; virtual bool process(time_point current_time) { ++counter; //t += std::chrono::seconds(5); return false; } }; struct TraditionalTraitsBase { typedef unsigned long time_point; struct control_structure { typedef bool (*handler_type)(control_structure* c, time_point current_time); time_point wake_time; handler_type handler; void* data; }; }; template <bool is_inline> struct TraditionalTraits; template <> struct TraditionalTraits<true> : TraditionalTraitsBase { typedef control_structure value_type; static time_point get_time_point(const value_type& v) { return v.wake_time; } static bool process(value_type& v, time_point current_time) { return v.handler(&v, current_time); } }; template <> struct TraditionalTraits<false> : TraditionalTraitsBase { typedef control_structure* value_type; static time_point get_time_point(value_type v) { return v->wake_time; } static bool process(value_type v, time_point current_time) { return v->handler(v, current_time); } }; bool traditional_handler( TraditionalTraitsBase::control_structure* c, unsigned long current_time) { ++(*(int*)c->data); return false; } using FunctorTraits = embr::internal::experimental::FunctorTraits<unsigned>; struct StatefulFunctorTraits : FunctorTraits { time_point now_ = 0; time_point now() { return now_++; } }; TEST_CASE("scheduler test", "[scheduler]") { SECTION("impl operations") { SECTION("copy") { FunctorTraits::control_structure s1, s2(s1); FunctorTraits::control_structure s3, *ps3 = &s3, *ps1 = &s1; *ps3 = std::move(*ps1); } } SECTION("one-shot") { // doesn't have 'accessor', and maybe array isn't a good fit for priority_queue anyway //typedef estd::array<int, 4> container_type; typedef estd::layer1::vector<Item, 20> container_type; embr::internal::Scheduler<container_type, ItemTraits> scheduler; int counter = 0; scheduler.schedule(Item{5, &counter}); scheduler.schedule(Item{6, &counter}); scheduler.schedule(Item{10, &counter}); scheduler.schedule(Item{11, &counter}); auto top = scheduler.top(); const Item& value = top.clock(); REQUIRE(value.event_due == 5); top.cunlock(); scheduler.process(10); REQUIRE(counter == 3); REQUIRE(scheduler.size() == 1); } SECTION("repeating") { embr::internal::layer1::Scheduler<Item2Traits, 5> scheduler; scheduler.schedule(5); scheduler.schedule(99); // should never reach this one for(Item2Traits::time_point i = 0; i < 50; i++) { scheduler.process(i); } // being that we continually reschedule, we'll always be at the top auto& v = scheduler.top().clock(); // Should wake up 5 times at 5, 15, 25, 35 and 45 REQUIRE(v.counter == 5); } SECTION("events (aux)") { int counter = 0; int _counter = 0; typedef estd::layer1::vector<Item, 20> container_type; auto o1 = embr::experimental::make_delegate_observer([&counter]( const embr::internal::events::Scheduled<ItemTraits>& scheduled) { ++counter; }); auto o2 = embr::experimental::make_delegate_observer([&counter]( const embr::internal::events::Removed<ItemTraits>& removed) { --counter; }); // NOTE: May be wanting a ref evaporator not a struct evaporator for scheduler auto s = embr::layer1::make_subject(o1, o2); typedef decltype(s) subject_type; embr::internal::Scheduler<container_type, ItemTraits, subject_type> scheduler(std::move(s)); scheduler.schedule(Item{5}); REQUIRE(counter == 1); scheduler.schedule(Item{7}); REQUIRE(counter == 2); scheduler.process(6); // process removes one, so that will bump down our counter REQUIRE(counter == 1); } SECTION("virtual") { embr::internal::layer1::Scheduler<Item3Traits, 5> scheduler; Item3ControlStructure1 schedule1; Item3ControlStructure2 schedule2; scheduler.schedule(&schedule1); scheduler.schedule(&schedule2); estd::chrono::steady_clock::time_point now; estd::chrono::steady_clock::time_point end = now + std::chrono::seconds(60); for(; now < end; now += std::chrono::seconds(2)) { scheduler.process(now); } REQUIRE(schedule1.counter == 6); REQUIRE(schedule2.counter == 1); } SECTION("traditional") { SECTION("inline") { typedef TraditionalTraits<true> traits_type; typedef traits_type::value_type value_type; int counter = 0; embr::internal::layer1::Scheduler<traits_type, 5> scheduler; scheduler.schedule(value_type{10, traditional_handler, &counter}); scheduler.schedule(value_type{20, traditional_handler, &counter}); scheduler.process(5); scheduler.process(10); scheduler.process(19); scheduler.process(21); REQUIRE(counter == 2); } SECTION("user allocated") { typedef TraditionalTraits<false> traits_type; typedef traits_type::value_type value_type; int counter = 0; embr::internal::layer1::Scheduler<traits_type, 5> scheduler; traits_type::control_structure scheduled1{10, traditional_handler, &counter}, scheduled2{20, traditional_handler, &counter}; scheduler.schedule(&scheduled1); scheduler.schedule(&scheduled2); scheduler.process(5); scheduler.process(10); scheduler.process(19); scheduler.process(21); REQUIRE(counter == 2); } } SECTION("experimental") { // Works well, but overly verbose on account of estd::experimental::function // indeed being in progress and experimental SECTION("estd::function style") { std::bitset<32> arrived; embr::internal::layer1::Scheduler<FunctorTraits, 5> scheduler; SECTION("trivial scheduling") { auto f_set_only = FunctorTraits::make_function([&arrived](unsigned* wake, unsigned current_time) { arrived.set(*wake); }); auto f_set_and_repeat = FunctorTraits::make_function([&arrived](unsigned* wake, unsigned current_time) { arrived.set(*wake); *wake += 2; }); scheduler.schedule(11, f_set_and_repeat); scheduler.schedule(3, f_set_only); scheduler.schedule(9, f_set_only); scheduler.process(0); scheduler.process(4); scheduler.process(9); scheduler.process(11); scheduler.process(20); REQUIRE(!arrived[0]); REQUIRE(arrived[3]); REQUIRE(!arrived[4]); REQUIRE(arrived[9]); REQUIRE(arrived[11]); REQUIRE(!arrived[12]); REQUIRE(arrived[13]); REQUIRE(arrived[15]); REQUIRE(arrived[17]); REQUIRE(!arrived[18]); REQUIRE(arrived[19]); } SECTION("overly smart scheduling") { auto _f = estd::experimental::function<void(unsigned*, unsigned)>::make_inline( [&arrived](unsigned* wake, unsigned current_time) { arrived.set(*wake); if (*wake < 11 || *wake > 20) { } else { *wake = *wake + 2; } }); estd::experimental::function_base<void(unsigned*, unsigned)> f(&_f); scheduler.schedule(11, f); scheduler.schedule(3, f); scheduler.schedule(9, f); scheduler.process(0); REQUIRE(!arrived[0]); scheduler.process(4); REQUIRE(arrived[3]); REQUIRE(!arrived[9]); scheduler.process(9); REQUIRE(arrived[9]); scheduler.process(11); REQUIRE(arrived[11]); scheduler.process(20); REQUIRE(!arrived[12]); REQUIRE(arrived[13]); REQUIRE(!arrived[14]); REQUIRE(arrived[15]); REQUIRE(!arrived[16]); } } SECTION("stateful") { std::bitset<32> arrived; embr::internal::layer1::Scheduler<StatefulFunctorTraits, 5> scheduler; auto f = StatefulFunctorTraits::make_function( [&](unsigned* wake, unsigned current) { arrived.set(*wake); }); scheduler.schedule_now(f); scheduler.process(10); REQUIRE(arrived.count() == 1); REQUIRE(arrived[0]); } } }
28.369615
118
0.572456
malachi-iot
d7f9365a88328554992d812629a1e659be898815
559
hpp
C++
include/ttl/nn/bits/ops/impl/col2im1d.hpp
stdml/stdnn-ops
0e6132bd65319e318f918094e482482698482e9e
[ "MIT" ]
3
2018-10-23T18:46:39.000Z
2019-06-24T00:46:10.000Z
include/ttl/nn/bits/ops/impl/col2im1d.hpp
stdml/stdnn-ops
0e6132bd65319e318f918094e482482698482e9e
[ "MIT" ]
27
2018-11-10T14:19:16.000Z
2020-03-08T23:33:01.000Z
include/ttl/nn/bits/ops/impl/col2im1d.hpp
stdml/stdnn-ops
0e6132bd65319e318f918094e482482698482e9e
[ "MIT" ]
1
2018-11-05T06:17:12.000Z
2018-11-05T06:17:12.000Z
#pragma once #include <ttl/algorithm> #include <ttl/nn/bits/ops/col2im1d.hpp> namespace ttl::nn::ops { template <typename R> void col2im1d::operator()(const ttl::tensor_ref<R, 1> &y, const ttl::tensor_view<R, 2> &x) const { const auto [n] = y.shape().dims(); ttl::fill(y, static_cast<R>(0)); for (auto j : ttl::range<0>(x)) { for (auto k : ttl::range<1>(x)) { const int i = (*this)(j, k); if (inside(i, n)) { y.at(unpad(i)) += x.at(j, k); } } } } } // namespace ttl::nn::ops
26.619048
64
0.525939
stdml
cc0096c9c2da939173d886e91a4447129ce0a14f
11,599
cpp
C++
libtr101290/src/Demux.cpp
codetalks-new/libeasyice
56781ff4a1c5a070526c87790fc34594c25a5846
[ "MIT" ]
null
null
null
libtr101290/src/Demux.cpp
codetalks-new/libeasyice
56781ff4a1c5a070526c87790fc34594c25a5846
[ "MIT" ]
null
null
null
libtr101290/src/Demux.cpp
codetalks-new/libeasyice
56781ff4a1c5a070526c87790fc34594c25a5846
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2009-2019 easyice 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 "Demux.h" #include "global.h" #include "TrCore.h" #include "csysclock.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "EiLog.h" using namespace tr101290; using namespace std; CDemux::CDemux(CTrCore* pParent) { m_pParent = pParent; m_pPsiCk = new CPsiCheck(pParent); m_h_dvbpsi_pat = dvbpsi_AttachPAT(DumpPAT, this); m_bDemuxFinish = false; m_nUsedPcrPid = -1; m_pOldOccurTime = new long long[8192]; m_pKnownPid = new bool[8192]; for (int i = 0; i < 8192; i++) { m_pOldOccurTime[i] = -1; if (i <=0x1F) m_pKnownPid[i] = true; else m_pKnownPid[i] = false; } m_pKnownPid[0x1FFF] = true; m_llFirstPcr = -1; } CDemux::~CDemux() { delete m_pPsiCk; delete [] m_pOldOccurTime; delete [] m_pKnownPid; vector<PROGRAM_INFO>::iterator it = m_vecDemuxInfoBuf.begin(); for (;it != m_vecDemuxInfoBuf.end(); ++it) { delete it->pCalcPcrN1; } dvbpsi_DetachPAT(m_h_dvbpsi_pat); map<int,PMTINFO>::iterator itmap = m_mapPmtmInfo.begin(); for (; itmap != m_mapPmtmInfo.end(); ++itmap) { dvbpsi_DetachPMT(itmap->second.handle); } } void CDemux::Demux(uint8_t* pPacket) { uint16_t i_pid = ((uint16_t)(pPacket[1] & 0x1f) << 8) + pPacket[2]; if (m_mapPmtmInfo.empty()) { if(i_pid == 0x0) { dvbpsi_PushPacket(m_h_dvbpsi_pat, pPacket); } return; } else // pmt { map<int,PMTINFO>::iterator it = m_mapPmtmInfo.begin(); for (; it != m_mapPmtmInfo.end(); ++it) { if (it->second.pmt_pid == i_pid) { dvbpsi_PushPacket (it->second.handle,pPacket); } } } //判断是否解析完毕 map<int,PMTINFO>::iterator it = m_mapPmtmInfo.begin(); for (; it != m_mapPmtmInfo.end(); ++it) { if (!it->second.parsed) { //m_vecDemuxInfoBuf.clear(); return; } } m_bDemuxFinish = true; } /***************************************************************************** * DumpPAT *****************************************************************************/ void CDemux::DumpPAT(void* p_zero, dvbpsi_pat_t* p_pat) { CDemux * lpthis = (CDemux*) p_zero; dvbpsi_pat_program_t* p_program = p_pat->p_first_program; int count = 0; while(p_program) { count++; if (p_program->i_number != 0) // 0 is nit { PMTINFO pmtinfo; pmtinfo.pmt_pid = p_program->i_pid; pmtinfo.handle = dvbpsi_AttachPMT(p_program->i_number, DumpPMT, p_zero); lpthis->m_mapPmtmInfo[p_program->i_number] = pmtinfo; lpthis->m_pPsiCk->AddPmtPid(p_program->i_pid,p_program->i_number); } //else if (m_pCrcCkHds[p_program->i_pid] != NULL), newHadle.... lpthis->m_pKnownPid[p_program->i_pid] = true; lpthis->m_mapUnReferPid.erase(p_program->i_pid); p_program = p_program->p_next; } ei_log(LV_DEBUG,"libtr101290", "PAT decode finish,program count:%d",count); dvbpsi_DeletePAT(p_pat); } /***************************************************************************** * DumpPMT *****************************************************************************/ void CDemux::DumpPMT(void* p_zero, dvbpsi_pmt_t* p_pmt) { CDemux * lpthis = (CDemux*) p_zero; dvbpsi_pmt_es_t* p_es = p_pmt->p_first_es; ei_log(LV_DEBUG,"libtr101290","PMT decode info: program_number=0x%02x (%d) ",p_pmt->i_program_number,p_pmt->i_program_number); ei_log( LV_DEBUG,"libtr101290", "PCR_PID=0x%x (%d)",p_pmt->i_pcr_pid, p_pmt->i_pcr_pid); map<int,PMTINFO>::iterator it = lpthis->m_mapPmtmInfo.find(p_pmt->i_program_number); if (it == lpthis->m_mapPmtmInfo.end()) return; lpthis->m_pKnownPid[p_pmt->i_pcr_pid] = true; lpthis->m_mapUnReferPid.erase(p_pmt->i_pcr_pid); PROGRAM_INFO prog_info; while(p_es != NULL) { ei_log(LV_DEBUG,"libtr101290","es_pid=0x%02x (%d) stream_type=0x%x",p_es->i_pid, p_es->i_pid,p_es->i_type); ES_INFO es_info; es_info.pid = p_es->i_pid; es_info.stream_type = p_es->i_type; prog_info.vecPayloadPid.push_back(es_info); lpthis->m_pKnownPid[p_es->i_pid] = true; lpthis->m_mapUnReferPid.erase(p_es->i_pid); p_es = p_es->p_next; } it->second.pcr_pid = p_pmt->i_pcr_pid; prog_info.nPcrPid = p_pmt->i_pcr_pid; prog_info.nPmtPid = it->second.pmt_pid; prog_info.pCalcPcrN1 = new CCalcPcrN1(); it->second.parsed = true; lpthis->m_vecDemuxInfoBuf.push_back(prog_info); dvbpsi_DeletePMT(p_pmt); } void CDemux::AddPacket(uint8_t* pPacket) { //demux if (!m_bDemuxFinish) { Demux(pPacket); } UpdateClock(pPacket); ProcessPacket(pPacket); } void CDemux::UpdateClock(uint8_t* pPacket) { CTsPacket tsPacket; tsPacket.SetPacket(pPacket); int pid = tsPacket.Get_PID(); //find first eff pcr if (m_nUsedPcrPid < 0) { vector<PROGRAM_INFO>::iterator it = m_vecDemuxInfoBuf.begin(); for (;it != m_vecDemuxInfoBuf.end(); ++it) { if (pid == it->nPcrPid && tsPacket.Get_PCR_flag()) { m_nUsedPcrPid = pid; } } } if (m_nUsedPcrPid < 0) { return; } if (pid == m_nUsedPcrPid && tsPacket.Get_PCR_flag()) { //检测PCR跳变 long long calcPCr = m_pParent->m_pSysClock->GetPcr(); long long curPcr = tsPacket.Get_PCR(); if ( calcPCr >= 0 && llabs( diff_pcr(calcPCr,curPcr)) > 270000 ) { m_pParent->m_pSysClock->Reset(); //10ms认为跳变 } m_pParent->m_pSysClock->AddPcrPacket(curPcr); if (m_llFirstPcr < 0) { m_llFirstPcr = curPcr; } } else { m_pParent->m_pSysClock->AddPayloadPacket(); } } inline bool CDemux::IsPmtPid(int pid) { vector<PROGRAM_INFO>::iterator it = m_vecDemuxInfoBuf.begin(); for (;it != m_vecDemuxInfoBuf.end(); ++it) { if (pid == it->nPmtPid) { return true; } } return false; } inline long long CDemux::CheckOccTime(int pid,long long llCurTime) { if (m_pOldOccurTime[pid] == -1 || llCurTime == -1) { return -1; } long long interval = diff_pcr(llCurTime, m_pOldOccurTime[pid]) /*/ 27000*/; return interval; } bool CDemux::CheckEsPid(int pid,long long llCurTime,CTsPacket& tsPacket) { bool bEsPid = false; vector<PROGRAM_INFO>::iterator it = m_vecDemuxInfoBuf.begin(); for (;it != m_vecDemuxInfoBuf.end(); ++it) { vector<ES_INFO>::iterator ites = it->vecPayloadPid.begin(); for (; ites != it->vecPayloadPid.end(); ++ites) { if (m_pOldOccurTime[ites->pid] != -2) { //check timeout if (m_pOldOccurTime[ites->pid] != -1) //pid dis aper { long long interval = diff_pcr(llCurTime, m_pOldOccurTime[ites->pid]) / 27000; if (interval > 5000) { m_pOldOccurTime[ites->pid] = -2;//for never report agein m_pParent->Report(1,LV1_PID_ERROR,ites->pid,-1,-1); } } else //pid never occur { long long interval = diff_pcr(llCurTime, m_llFirstPcr ) / 27000; if (interval > 5000) { m_pOldOccurTime[ites->pid] = -2;//for never report agein m_pParent->Report(1,LV1_PID_ERROR,ites->pid,-1,-1); } } } if (ites->pid == pid) { bEsPid = true; //check pts long long pts; long long calcPCr = m_pParent->m_pSysClock->GetPcr(); if (tsPacket.Get_PTS(pts) && ites->llPrevPts_occ >= 0) { m_pParent->Report(2,LV2_PTS_ERROR,pid,diff_pcr(calcPCr, ites->llPrevPts_occ),-1); //Report(2,LV2_PTS_ERROR,pid,pts-ites->llPrevPts,-1); ites->llPrevPts = pts; ites->llPrevPts_occ = calcPCr; } } } //!for ites } //!for it return bEsPid; } void CDemux::CheckPCR(int pid,CTsPacket& tsPacket) { vector<PROGRAM_INFO>::iterator it = m_vecDemuxInfoBuf.begin(); for (;it != m_vecDemuxInfoBuf.end(); ++it) { if (pid == it->nPcrPid && tsPacket.Get_PCR_flag()) { long long pcr = tsPacket.Get_PCR(); BYTE afLen; BYTE* pAf = tsPacket.Get_adaptation_field(afLen); int discontinuity_indicator = 0; if (pAf != NULL) { if (tsPacket.Get_discontinuity_indicator(pAf)) discontinuity_indicator = 1; } //check pcr it long long pcr_prev = it->pCalcPcrN1->GetPcrPrev(); if (pcr_prev != -1) { m_pParent->Report(2,LV2_PCR_REPETITION_ERROR,pid, pcr - pcr_prev,discontinuity_indicator); } //check pcr ac long long pcr_calc = it->pCalcPcrN1->GetPcr(); if (pcr_calc != -1) { m_pParent->Report(2,LV2_PCR_ACCURACY_ERROR,pid, pcr - pcr_calc,-1); } it->pCalcPcrN1->AddPcrPacket(pcr); } else { it->pCalcPcrN1->AddPayloadPacket(); } } } void CDemux::CheckUnreferPid(int pid,long long llCurTime) { long long interval = 0; //添加一种新的PID if (!m_pKnownPid[pid]) { m_pKnownPid[pid] = true; m_mapUnReferPid[pid] = llCurTime; return; } //检测超时 map<int,long long>::iterator it = m_mapUnReferPid.begin(); for (;it != m_mapUnReferPid.end();++it) { if (it->second != -1) { interval = diff_pcr(llCurTime, it->second) / 27000; if (interval > 500) { //error here m_pParent->Report(3,LV3_UNREFERENCED_PID,pid,-1,-1); m_pKnownPid[pid] = true; m_mapUnReferPid.erase(it); return; } } else { it->second = llCurTime; } } } void CDemux::ProcessPacket(uint8_t* pPacket) { CTsPacket tsPacket; tsPacket.SetPacket(pPacket); int pid = tsPacket.Get_PID(); long long llCurTime = m_pParent->m_pSysClock->GetPcr(); long long interval; bool bPsi = false; //pat err if (pid == 0) { //check occ if ((interval=CheckOccTime(0,llCurTime)) > 0) { m_pParent->Report(1,LV1_PAT_ERROR_OCC,0,interval,-1); } //check tid CPrivate_Section cs; if (cs.SetPacket(tsPacket)) { if (cs.Get_table_id() != 0) { m_pParent->Report(1,LV1_PAT_ERROR_TID,0,-1,-1); } } //check scf if (tsPacket.Get_transport_scrambling_control() != 0) { m_pParent->Report(1,LV1_PAT_ERROR_SCF,0,-1,-1); } bPsi = true; } //pmt err if (IsPmtPid(pid)) { //check occ if ((interval = CheckOccTime(pid,llCurTime)) > 0) { m_pParent->Report(1,LV1_PMT_ERROR_OCC,pid,interval,-1); } //check scf if (tsPacket.Get_transport_scrambling_control() != 0) { m_pParent->Report(1,LV1_PMT_ERROR_SCF,pid,-1,-1); } bPsi = true; } //cat err if (pid == 1) { //check tid CPrivate_Section cs; if (cs.SetPacket(tsPacket)) { if (cs.Get_table_id() != 1) { m_pParent->Report(2,LV2_CAT_ERROR_TID,1,-1,-1); } } bPsi = true; } bool bEsPid = false; //pid err and pts err if (llCurTime > 0) { bEsPid = CheckEsPid(pid,llCurTime,tsPacket); } m_pPsiCk->AddPacket(pPacket,bEsPid,pid); //check pcr error CheckPCR(pid,tsPacket); if (!bPsi) { CheckUnreferPid(pid,llCurTime); } if (llCurTime < 0) { //当没有计算到时去码流中遇到的第一个PCR。 //当收到第二个PCR包的时候,N1 PCR 已经计算成功了 m_pOldOccurTime[pid] = m_llFirstPcr; } else { m_pOldOccurTime[pid] = llCurTime; } } bool CDemux::IsDemuxFinish() { return m_bDemuxFinish; }
21.802632
460
0.654625
codetalks-new
cc0450c7063ad045812f9d9183e3788b462ab683
9,673
cpp
C++
Source/Core/LibJob/Job.cpp
dzik143/tegenaria
a6c138633ab14232a2229d7498875d9d869d25a9
[ "MIT" ]
3
2020-12-28T06:18:47.000Z
2021-08-01T06:18:12.000Z
Source/Core/LibJob/Job.cpp
dzik143/tegenaria
a6c138633ab14232a2229d7498875d9d869d25a9
[ "MIT" ]
null
null
null
Source/Core/LibJob/Job.cpp
dzik143/tegenaria
a6c138633ab14232a2229d7498875d9d869d25a9
[ "MIT" ]
null
null
null
/******************************************************************************/ /* */ /* Copyright (c) 2010, 2014 Sylwester Wysocki <sw143@wp.pl> */ /* */ /* 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 <cmath> #include <Tegenaria/Debug.h> #include "Job.h" namespace Tegenaria { // // Create job object. // // title - job's title (IN/OPT). // notifyCallback - callback called when job changed state or progress meter (IN/OPT). // notifyCallbackCtx - caller context passed to notifyCallback() directly (IN/OPT). // workerCallback - callback function performing real job work (IN). // workerCallbackCtx - caller context passed to workerCallback() directly (IN/OPT). // Job::Job(const char *title, JobNotifyCallbackProto notifyCallback, void *notifyCallbackCtx, JobWorkerCallbackProto workerCallback, void *workerCallbackCtx) { DBG_ENTER3("Job::Job"); // // Set job title. // if (title) { title_ = title; } else { char title[64]; snprintf(title, sizeof(title) - 1, "Anonymous job %p.\n", this); title_ = title; } // // Add object to debug set. // DBG_SET_ADD("Job", this, "%s", getTitle()); // // Set notify callback. // notifyCallback_ = notifyCallback; notifyCallbackCtx_ = notifyCallbackCtx; // // Set worker function. // workerCallback_ = workerCallback; workerCallbackCtx_ = workerCallbackCtx; // // Zero refference counter. // refCount_ = 1; // // Set state to initializing. // setState(JOB_STATE_INITIALIZING); // // Create worker thread performing real job. // workerThread_ = ThreadCreate(workerLoop, this); // // Zero statistics. // percentCompleted_ = 0.0; errorCode_ = 0; DBG_SET_RENAME("thread", workerThread_, getTitle()); DBG_LEAVE3("Job::Job"); } // // Call underlying notify callback set in constructor. // // code - one of JOB_NOTIFY_XXX codes (IN). // void Job::triggerNotifyCallback(int code) { if (notifyCallback_) { notifyCallback_(code, this, notifyCallbackCtx_); } } // // Increase refference counter. // // WARNING! Every call to addRef() MUSTS be followed by one release() call. // // TIP #1: Object will not be destroyed until refference counter is greater // than 0. // // TIP #2: Don't call destructor directly, use release() instead. If // refference counter achieve 0, object will be destroyed // automatically. // void Job::addRef() { refCountMutex_.lock(); refCount_ ++; DEBUG2("Increased refference counter to %d for job '%s'.\n", refCount_, getTitle()); refCountMutex_.unlock(); } // // Decrease refference counter increased by addRef() before. // void Job::release() { int deleteNeeded = 0; // // Decrease refference counter by 1. // refCountMutex_.lock(); refCount_ --; DEBUG2("Decreased refference counter to %d for job '%s'.\n", refCount_, getTitle()); if (refCount_ == 0) { deleteNeeded = 1; } refCountMutex_.unlock(); // // Delete object if refference counter goes down to 0. // if (deleteNeeded) { delete this; } } // // Worker loop performing real job in background thread. // This function calls underlying doTheJob() function implemented in child class. // // jobPtr - pointer to related Job object (this pointer) (IN/OUT). // int Job::workerLoop(void *jobPtr) { Job *this_ = (Job *) jobPtr; this_ -> addRef(); this_ -> setState(JOB_STATE_PENDING); if (this_ -> workerCallback_) { this_ -> workerCallback_(this_, this_ -> workerCallbackCtx_); } else { Error("ERROR: Worker callback is NULL for '%s'.\n", this_ -> getTitle()); } this_ -> release(); return 0; } // // Change current state. See JOB_STATE_XXX defines in Job.h. // // state - new state to set (IN). // void Job::setState(int state) { state_ = state; DEBUG2("%s: changed state to [%s].\n", getTitle(), getStateString()); switch(state) { case JOB_STATE_ERROR: DBG_INFO("%s : finished with error.\n", getTitle()); break; case JOB_STATE_INITIALIZING: DEBUG2("%s : initializing.\n", getTitle()); break; case JOB_STATE_PENDING: DEBUG2("%s : pending.\n", getTitle()); break; case JOB_STATE_FINISHED: DBG_INFO("%s : finished with success.\n", getTitle()); break; case JOB_STATE_STOPPED: DBG_INFO("%s : stopped.\n", getTitle()); break; } // // Call notify callback if set. // triggerNotifyCallback(JOB_NOTIFY_STATE_CHANGED); } // // Get current state code. See JOB_STATE_XXX defines in Job.h. // // RETURNS: Current state code. // int Job::getState() { return state_; } // // Get current state as human readable string. // // RETURNS: Name of current job's state. // const char *Job::getStateString() { switch(state_) { case JOB_STATE_ERROR: return "Error"; case JOB_STATE_INITIALIZING: return "Initializing"; case JOB_STATE_PENDING: return "Pending"; case JOB_STATE_FINISHED: return "Finished"; case JOB_STATE_STOPPED: return "Stopped"; }; return "Unknown"; } // // Wait until job finished or stopped with error. // // timeout - maximum time to wait in ms. Set to -1 for infinite (IN). // // RETURNS: 0 if OK (job finished/stopped on exit), // -1 otherwise (job still active on exit). int Job::wait(int timeout) { DBG_ENTER2("Job::wait"); int exitCode = -1; int timeLeft = timeout; while(state_ == JOB_STATE_INITIALIZING || state_ == JOB_STATE_PENDING) { ThreadSleepMs(50); if (timeout > 0) { timeLeft -= 50; if (timeLeft <= 0) { Error("ERROR: Timeout while waiting for job '%s'.\n", this -> getTitle()); goto fail; } } } // // Error handler. // exitCode = 0; fail: DBG_LEAVE2("SftpJob::wait"); return exitCode; } // // Send stop signal for pending job object. // After that related thread should stop working and state // should change to JOB_STATE_STOPPED. // // WARNING#1: Job object MUSTS be still released with release() method. // // TIP#1: To stop and release resources related with job use below code: // // job -> cancel(); // job -> release(); // void Job::cancel() { this -> setState(JOB_STATE_STOPPED); } // // Retrieve job's title set in constructor before. // const char *Job::getTitle() { return title_.c_str(); } Job::~Job() { ThreadWait(workerThread_); ThreadClose(workerThread_); DBG_SET_DEL("Job", this); } // // Get current job's progress in percentages (0-100%). // double Job::getPercentCompleted() { return percentCompleted_; } // // Get error code related with object. // This function should be used when job finished with error state. // int Job::getErrorCode() { return errorCode_; } // // Set current error code related with job. // This function should be used to inform caller why job object // finished with error state. // void Job::setErrorCode(int code) { errorCode_ = code; } // // Set current job's progress in percentages (0-100%). // void Job::setPercentCompleted(double percentCompleted) { int notifyNeeded = 0; if (fabs(percentCompleted_ - percentCompleted) > 0.01) { notifyNeeded = 1; } percentCompleted_ = percentCompleted; if (notifyNeeded) { triggerNotifyCallback(JOB_NOTIFY_PROGRESS); } } } /* namespace Tegenaria */
23.708333
96
0.572005
dzik143
cc05eb814f2b793eec7079778810c61bacb14f7b
6,502
cpp
C++
DeviceCode/Drivers/BatteryModel/IML200425_2/IML200425_2_config.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
529
2015-03-10T00:17:45.000Z
2022-03-17T02:21:19.000Z
DeviceCode/Drivers/BatteryModel/IML200425_2/IML200425_2_config.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
495
2015-03-10T22:02:46.000Z
2019-05-16T13:05:00.000Z
DeviceCode/Drivers/BatteryModel/IML200425_2/IML200425_2_config.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
332
2015-03-10T08:04:36.000Z
2022-03-29T04:18:36.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <tinyhal.h> //--// // some curve fits of this battery discharge vs. voltage/temp // X is range as (MilliVolts - MinVoltage) / VoltageToX, and below MinVoltage, 0% state of charge // the upper limit is then X=Max // this allows the coefficients to fit into the poly evaluator const STATE_OF_CHARGE_SINGLE_CURVE_FIT g_IML200425_2_DATA[] = { // -10C // y = - 2.921848049979300000E-02 // + 8.782307948443700000E-03x // - 2.333808204045830000E-04x2 // + 3.856237912002600000E-06x3 // - 2.214094332551320000E-08x4 // + 4.117594055691850000E-11x5 { -100, // INT16 Temperature; 6, // INT8 NumCoefficients; 56, // INT8 CoefficientsScalerBits; 3105, // UINT16 MinVoltage; 210, // UINT16 MaxX; 5, // UINT16 VoltageToX; { // INT64 Coefficients[10]; -2105413406259200LL, 632831980865024LL, -16816860412952LL, 277871225976LL, -1595423106LL, 2967039LL, 0LL, 0LL, 0LL, 0LL, } }, // 0C // y = + 2.047522162115460000E-02 // - 4.275968405409000000E-03x // + 3.272098642863600000E-04x2 // - 6.454859570126370000E-06x3 // + 6.073919354325840000E-08x4 // - 2.543781333968020000E-10x5 // + 3.846397268909590000E-13x6 { 0, // INT16 Temperature; 7, // INT8 NumCoefficients; 56, // INT8 CoefficientsScalerBits; 3101, // UINT16 MinVoltage; 209, // UINT16 MaxX; 5, // UINT16 VoltageToX; { // INT64 Coefficients[10]; 1475395207413760LL, -308115995475968LL, 23577955565952LL, -465121650476LL, 4376720150LL, -18329877LL, 27716LL, 0LL, 0LL, 0LL, } }, // 10C // y = + 2.411092941110840000E-02 // - 4.693360087401290000E-03x // + 2.525245543836260000E-04x2 // - 4.017030204306330000E-06x3 // + 3.082229605788980000E-08x4 // - 1.006704638813020000E-10x5 // + 1.071946769614940000E-13x6 { 100, // INT16 Temperature; 7, // INT8 NumCoefficients; 56, // INT8 CoefficientsScalerBits; 3094, // UINT16 MinVoltage; 209, // UINT16 MaxX; 5, // UINT16 VoltageToX; { // INT64 Coefficients[10]; 1737375563382790LL, -338192235851776LL, 18196311824384LL, -289457531700LL, 2220980496LL, -7254072LL, 7724LL, 0LL, 0LL, 0LL, } }, // 20C // y = + 3.337666242396150000E-02 // - 6.122761342908230000E-03x // + 2.778481003815610000E-04x2 // - 3.921589108946130000E-06x3 // + 2.666577843908270000E-08x4 // - 7.656661606751900000E-11x5 // + 6.677988717433050000E-14x6 { 200, // INT16 Temperature; 7, // INT8 NumCoefficients; 56, // INT8 CoefficientsScalerBits; 3095, // UINT16 MinVoltage; 209, // UINT16 MaxX; 5, // UINT16 VoltageToX; { // INT64 Coefficients[10]; 2405041991286780LL, -441191451238400LL, 20021065621504LL, -282580275996LL, 1921471837LL, -5517207LL, 4811LL, 0LL, 0LL, 0LL, } }, // 30C // y = + 2.283453822883530000E-02 // - 3.790126855165000000E-03x // + 1.648931592157510000E-04x2 // - 1.697413976042840000E-06x3 // + 5.926739318935780000E-09x4 // + 1.259643704311840000E-11x5 // - 7.520650690460260000E-14x6 { 300, // INT16 Temperature; 7, // INT8 NumCoefficients; 56, // INT8 CoefficientsScalerBits; 3095, // UINT16 MinVoltage; 209, // UINT16 MaxX; 5, // UINT16 VoltageToX; { // INT64 Coefficients[10]; 1645401885736960LL, -273107422281728LL, 11881804326400LL, -122311567200LL, 427066575LL, 907668LL, -5420LL, 0LL, 0LL, 0LL, } } }; STATE_OF_CHARGE_CURVE_FIT g_BATTERY_MEASUREMENT_CurveFit = { { TRUE }, // HAL_DRIVER_CONFIG_HEADER Header; //--// ARRAYSIZE(g_IML200425_2_DATA), g_IML200425_2_DATA, };
37.802326
201
0.375884
PervasiveDigital
cc088855eecd363b32f02609132bab024347bf22
1,029
cpp
C++
src/main.cpp
arccos0/Strip-Packing-Algorithm
d7093db2ef1dee6a06c5299b3512bca47a83e1ec
[ "MIT" ]
7
2021-09-25T07:35:11.000Z
2021-12-24T12:50:55.000Z
src/main.cpp
arccos0/Strip-Packing-Algorithm
d7093db2ef1dee6a06c5299b3512bca47a83e1ec
[ "MIT" ]
1
2021-11-04T11:45:50.000Z
2021-12-21T06:42:56.000Z
src/main.cpp
arccos0/Strip-Packing-Algorithm
d7093db2ef1dee6a06c5299b3512bca47a83e1ec
[ "MIT" ]
9
2021-09-25T04:56:43.000Z
2021-11-26T03:09:18.000Z
#include <experimental/filesystem> #include <iostream> #include <map> #include <string> #include "BLEU.h" #include "datareader.h" #include "heuristic.h" #include "spp.h" int main() { const std::string instancesFolder = "./2sp/"; for (int i = 0; i < 1; ++i) { for (const auto& entry : std::experimental::filesystem::directory_iterator(instancesFolder)) { std::string filePath = entry.path().relative_path().string(); std::cout << filePath; std::vector<const StripPacking::item*> allItems; StripPacking::Heuristic hrs; int W = readData(filePath, allItems); std::vector<const StripPacking::item*> copyItems(allItems.begin(), allItems.end()); int totalArea = 0; StripPacking::BLEU alg(allItems, W, 20, 1000); auto status = alg.evaluate(); std::cout << "The status is " << status << "\n"; for (auto it = allItems.begin(); it != allItems.end(); ++it) delete (*it); } } system("pause"); }
33.193548
80
0.594752
arccos0
cc098edc2353ea7587be178498d1d10575db91af
85,164
cpp
C++
InterfaceManager.cpp
cjcoimbra/ChessterOSX
89c6cbdfb295b3d929faa0bf036440b96a0007c6
[ "AML" ]
null
null
null
InterfaceManager.cpp
cjcoimbra/ChessterOSX
89c6cbdfb295b3d929faa0bf036440b96a0007c6
[ "AML" ]
null
null
null
InterfaceManager.cpp
cjcoimbra/ChessterOSX
89c6cbdfb295b3d929faa0bf036440b96a0007c6
[ "AML" ]
null
null
null
#include "StdAfx.h" #include "InterfaceManager.h" InterfaceManager::InterfaceManager(sf::RenderWindow * rw, ResourceManager * rm, float factor, float max_tile_size) { //ctor wptr = rw; resource_manager = rm; isIncreasingScore = false; isDecreasingScore = false; currentScore = 0; //title_screen_spt.SetImage(resource_manager->GetImageResource(11)); next_treasure_banner.SetImage(resource_manager->GetImageResource(72)); next_treasure_banner.Resize((float)(358 * wptr->GetWidth())/1920, (float)(110 * wptr->GetHeight())/1080); next_treasure_banner.SetPosition((float)(wptr->GetWidth() * 1508) / 1920, (float)(wptr->GetHeight() * 156) / 1080); moves_spt.SetImage(resource_manager->GetImageResource(17)); info_frame_spt.SetImage(resource_manager->GetImageResource(18)); turns_spt.SetImage(resource_manager->GetImageResource(19)); moves_bluecrest_spt.SetImage(resource_manager->GetImageResource(43)); turns_bluecrest_spt.SetImage(resource_manager->GetImageResource(43)); moves_spt.Resize((float)(263 * wptr->GetWidth())/1920, (float)(86 * wptr->GetHeight())/1080); turns_spt.Resize((float)(262 * wptr->GetWidth())/1920, (float)(85 * wptr->GetHeight())/1080); //info_frame_spt.Resize((411 * wptr->GetWidth())/1920, (714 * wptr->GetHeight())/1080); info_frame_spt.Resize((float)(391 * wptr->GetWidth())/1920, (float)(703 * wptr->GetHeight())/1080); std::cout << "Panel size: [" << info_frame_spt.GetSize().x << "," << info_frame_spt.GetSize().y << "]\n"; moves_bluecrest_spt.Resize((float)(135 * wptr->GetWidth())/1920, (float)(135 * wptr->GetHeight())/1080); turns_bluecrest_spt.Resize((float)(135 * wptr->GetWidth())/1920, (float)(135 * wptr->GetHeight())/1080); int right_panel = (float)(wptr->GetWidth()/2 + 4 * factor * max_tile_size); //1480x330 - position of the panel in the mockup moves_spt.SetPosition((float)(wptr->GetWidth() * 31) / 1920, (float)(wptr->GetHeight() * 66) / 1080); turns_spt.SetPosition((float)(wptr->GetWidth() * 196) / 1920, (float)(wptr->GetHeight() * 170) / 1080); //info_frame_spt.SetPosition((wptr->GetWidth() * 1478) / 1920, (wptr->GetHeight() * 207) / 1080); info_frame_spt.SetPosition((float)(wptr->GetWidth() * 1490) / 1920, (float)(wptr->GetHeight() * 340) / 1080); moves_bluecrest_spt.SetPosition((float)(wptr->GetWidth() * 94) / 1920, (float)(wptr->GetHeight() * 95) / 1080); turns_bluecrest_spt.SetPosition((float)(wptr->GetWidth() * 256) / 1920, (float)(wptr->GetHeight() * 195) / 1080); //Font for growing score and combo size this->original_font_size = 48; chesster_font.LoadFromFile("GFX/Font/Deutsch.ttf"); temp_new_game.SetFont(chesster_font); temp_new_game.SetText("[R]esume game"); temp_new_game.SetSize(42); temp_new_game.SetColor(sf::Color(200,0,0)); temp_new_game.SetPosition((float)wptr->GetWidth()/2 - temp_new_game.GetRect().GetWidth()/2, (float)wptr->GetHeight()/2 - temp_new_game.GetRect().GetHeight() - 20); temp_resume_game.SetFont(chesster_font); temp_resume_game.SetText("[N]ew game"); temp_resume_game.SetSize(42); temp_resume_game.SetColor(sf::Color(200,0,0)); temp_resume_game.SetPosition((float)wptr->GetWidth()/2 - temp_resume_game.GetRect().GetWidth()/2, (float)temp_new_game.GetPosition().y + temp_new_game.GetRect().GetHeight() + 20); temp_cancel.SetFont(chesster_font); temp_cancel.SetText("[C]ancel"); temp_cancel.SetSize(42); temp_cancel.SetColor(sf::Color(200,0,0)); temp_cancel.SetPosition((float)wptr->GetWidth()/2 - temp_cancel.GetRect().GetWidth()/2,(float) temp_resume_game.GetPosition().y + temp_resume_game.GetRect().GetHeight() + 20); deselect_info.SetFont(chesster_font); deselect_info.SetText("'right button' to deselect current piece" ); deselect_info.SetSize(24); deselect_info.SetColor(sf::Color(200,0,0)); deselect_info.SetPosition((float)wptr->GetWidth()/2 - deselect_info.GetRect().GetWidth()/2, (float)wptr->GetHeight() - deselect_info.GetRect().GetHeight() - 10); temp_info.SetFont(chesster_font); temp_info.SetText("Chesster - OSX v0.931 Demo (C) 2013 - Team Checkmate" ); temp_info.SetSize(22); temp_info.SetColor(sf::Color(255,255,255)); temp_info.SetPosition((float)wptr->GetWidth() - temp_info.GetRect().GetWidth() - 5 , (float)wptr->GetHeight() - temp_info.GetRect().GetHeight() - 10); loading_info.SetFont(chesster_font); loading_info.SetText("loading..." ); loading_info.SetSize(24); loading_info.SetColor(sf::Color(255,255,255)); loading_info.SetPosition((float)wptr->GetWidth()/2 - loading_info.GetRect().GetWidth()/2,(float) wptr->GetHeight()/2 - loading_info.GetRect().GetHeight()/2); turn_label.SetFont(chesster_font); turn_label.SetText("turn"); turn_label.SetSize(32); turn_label.SetColor(sf::Color(197,198,141)); turn_label.SetPosition(80, (float)wptr->GetHeight()/2 - 300); turn_info.SetFont(chesster_font); turn_info.SetText(""); turn_info.SetSize(42); turn_info.SetColor(sf::Color(255,255,255)); turn_info.SetPosition((float)(wptr->GetWidth() * 304) / 1920,(float) (wptr->GetHeight() * 235) / 1080); moves_label.SetFont(chesster_font); moves_label.SetText("moves"); moves_label.SetSize(32); moves_label.SetColor(sf::Color(197,198,141)); //moves_label.SetPosition(wptr->GetWidth() - 200, wptr->GetHeight()/2 - 300); //moves_label.SetPosition(moves_spt.GetPosition().x + moves_spt.GetSize().x/2 - 5, moves_spt.GetPosition().y + moves_spt.GetSize().y + 100); moves_info.SetFont(chesster_font); moves_info.SetText(""); moves_info.SetSize(42); moves_info.SetColor(sf::Color(255,255,255)); moves_info.SetPosition((float)(wptr->GetWidth() * 148) / 1920, (float)(wptr->GetHeight() * 142) / 1080); //moves_info.SetPosition(moves_spt.GetPosition().x + moves_spt.GetSize().x/2 - 10, moves_spt.GetPosition().y + moves_spt.GetSize().y - 15); turn_points_label.SetFont(chesster_font); turn_points_label.SetText("turn points"); turn_points_label.SetSize(32); turn_points_label.SetColor(sf::Color(197,198,141)); turn_points_label.SetPosition((float)wptr->GetWidth() - 200,(float) wptr->GetHeight()/2 - 150); turn_points_info.SetFont(chesster_font); turn_points_info.SetText(""); turn_points_info.SetSize(42); turn_points_info.SetColor(sf::Color(255,255,255)); turn_points_info.SetPosition((float)(wptr->GetWidth() * 1670) / 1920, (float)(wptr->GetHeight() * 508) / 1080); //turn_points_info.SetPosition(info_frame_spt.GetPosition().x + 65, info_frame_spt.GetPosition().y + 90); //520 demand_label.SetFont(chesster_font); demand_label.SetText("demand" ); demand_label.SetSize(32); demand_label.SetColor(sf::Color(197,198,141)); demand_label.SetPosition((float)wptr->GetWidth() - 200 + 12,(float) wptr->GetHeight()/2 + 133); //((wptr->GetWidth() * x) / 1920) //((wptr->GetHeight() * y) / 1080) demand_info.SetFont(chesster_font); demand_info.SetText(""); demand_info.SetSize(42); demand_info.SetColor(sf::Color(255,255,255)); demand_info.SetPosition((float)((wptr->GetWidth() * 1670) / 1920) - demand_info.GetRect().GetWidth()/2, (float)(wptr->GetHeight() * 688) / 1080); //demand_info.SetPosition(info_frame_spt.GetPosition().x + 65, info_frame_spt.GetPosition().y + 185); //706 total_points_label.SetFont(chesster_font); total_points_label.SetText("total"); total_points_label.SetSize(32); total_points_label.SetColor(sf::Color(197,198,141)); total_points_label.SetPosition((float)wptr->GetWidth() - 200,(float) wptr->GetHeight()/2 + 150); total_points_info.SetFont(chesster_font); total_points_info.SetText(""); total_points_info.SetSize(42); total_points_info.SetColor(sf::Color(255,255,255)); total_points_info.SetPosition((float)(wptr->GetWidth() * 1670) / 1920,(float) (wptr->GetHeight() * 896) / 1080); //total_points_info.SetPosition(info_frame_spt.GetPosition().x + 65, info_frame_spt.GetPosition().y + 300); //908 match_label.SetFont(chesster_font); match_label.SetText(""); match_label.SetSize(62); match_label.SetColor(sf::Color(255,255,255)); match_label.SetPosition(50,(float) wptr->GetHeight()/2 - 100); x_label.SetFont(chesster_font); x_label.SetText(""); x_label.SetSize(48); x_label.SetColor(sf::Color(255,255,255)); x_label.SetPosition((float)(wptr->GetWidth() * 200) / 1920, (float)(wptr->GetHeight() * 590) / 1080); match_points_info.SetFont(chesster_font); match_points_info.SetText(""); match_points_info.SetSize((float)this->original_font_size); match_points_info.SetColor(sf::Color(255,255,255)); //match_points_info.SetPosition((wptr->GetWidth() * 180) / 1920, (wptr->GetHeight() * 680) / 1080); match_points_info.SetPosition((float)(wptr->GetWidth() * 200) / 1920,(float) (wptr->GetHeight() * 590) / 1080); multiply_spt.SetImage(resource_manager->GetImageResource(71)); multiply_spt.Resize((float)(83 * wptr->GetWidth())/1920, (float)(90 * wptr->GetHeight())/1080); //multiply_spt.SetPosition((wptr->GetWidth() * 200) / 1920, (wptr->GetHeight() * 590) / 1080); multiply_spt.SetPosition((float)(wptr->GetWidth() * 200) / 1920,(float) match_points_info.GetPosition().y + match_points_info.GetRect().GetHeight() + 110); match_amount_info.SetFont(chesster_font); match_amount_info.SetText(""); match_amount_info.SetSize((float)this->original_font_size); match_amount_info.SetColor(sf::Color(255,255,255)); //match_amount_info.SetPosition((wptr->GetWidth() * 290) / 1920,(wptr->GetHeight() * 590) / 1080); match_amount_info.SetPosition((float)multiply_spt.GetPosition().x + multiply_spt.GetSize().x + 20, (float)multiply_spt.GetPosition().y); play_button_normal.SetImage(resource_manager->GetImageResource(21)); play_button_focus.SetImage(resource_manager->GetImageResource(22)); play_button_normal.Resize((float)(307 * wptr->GetWidth())/1920,(float) (113 * wptr->GetHeight())/1080); play_button_focus.Resize((float)(307 * wptr->GetWidth())/1920,(float) (113 * wptr->GetHeight())/1080); play_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - play_button_normal.GetSize().x/2,(float) (wptr->GetHeight() * 465) / 1080); play_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - play_button_focus.GetSize().x/2,(float) (wptr->GetHeight() * 465) / 1080); tutorial_button_normal.SetImage(resource_manager->GetImageResource(23)); tutorial_button_focus.SetImage(resource_manager->GetImageResource(24)); tutorial_button_normal.Resize((float)(419 * wptr->GetWidth())/1920, (float)(106 * wptr->GetHeight())/1080); tutorial_button_focus.Resize((float)(419 * wptr->GetWidth())/1920, (float)(106 * wptr->GetHeight())/1080); tutorial_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - tutorial_button_normal.GetSize().x/2,(float) (wptr->GetHeight() * 575) / 1080); tutorial_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - tutorial_button_focus.GetSize().x/2, (float)(wptr->GetHeight() * 575) / 1080); // Version with Puzzle puzzle_button_normal.SetImage(resource_manager->GetImageResource(25)); puzzle_button_focus.SetImage(resource_manager->GetImageResource(26)); puzzle_button_normal.Resize((float)(396 * wptr->GetWidth())/1920, (float)(91 * wptr->GetHeight())/1080); puzzle_button_focus.Resize((float)(396 * wptr->GetWidth())/1920,(float) (91 * wptr->GetHeight())/1080); puzzle_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - puzzle_button_normal.GetSize().x/2, (float)(wptr->GetHeight() * 690) / 1080); puzzle_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - puzzle_button_focus.GetSize().x/2,(float) (wptr->GetHeight() * 690) / 1080); scores_button_normal.SetImage(resource_manager->GetImageResource(27)); scores_button_focus.SetImage(resource_manager->GetImageResource(28)); scores_button_normal.Resize((float)(385 * wptr->GetWidth())/1920,(float) (90 * wptr->GetHeight())/1080); scores_button_focus.Resize((float)(385 * wptr->GetWidth())/1920, (float)(90 * wptr->GetHeight())/1080); scores_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - scores_button_normal.GetSize().x/2,(float) (wptr->GetHeight() * 805) / 1080); scores_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - scores_button_focus.GetSize().x/2,(float) (wptr->GetHeight() * 805) / 1080); credits_button_normal.SetImage(resource_manager->GetImageResource(29)); credits_button_focus.SetImage(resource_manager->GetImageResource(30)); credits_button_normal.Resize((float)(402 * wptr->GetWidth())/1920,(float) (90 * wptr->GetHeight())/1080); credits_button_focus.Resize((float)(402 * wptr->GetWidth())/1920, (float)(90 * wptr->GetHeight())/1080); credits_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - credits_button_normal.GetSize().x/2,(float) (wptr->GetHeight() * 920) / 1080); credits_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - credits_button_focus.GetSize().x/2, (float)(wptr->GetHeight() * 920) / 1080); //Version without Puzzle /* scores_button_normal.SetImage(resource_manager->GetImageResource(27)); scores_button_focus.SetImage(resource_manager->GetImageResource(28)); scores_button_normal.Resize((385 * wptr->GetWidth())/1920, (90 * wptr->GetHeight())/1080); scores_button_focus.Resize((385 * wptr->GetWidth())/1920, (90 * wptr->GetHeight())/1080); scores_button_normal.SetPosition(this->wptr->GetWidth()/2 - scores_button_normal.GetSize().x/2, (wptr->GetHeight() * 690) / 1080); scores_button_focus.SetPosition(this->wptr->GetWidth()/2 - scores_button_focus.GetSize().x/2, (wptr->GetHeight() * 690) / 1080); credits_button_normal.SetImage(resource_manager->GetImageResource(29)); credits_button_focus.SetImage(resource_manager->GetImageResource(30)); credits_button_normal.Resize((402 * wptr->GetWidth())/1920, (90 * wptr->GetHeight())/1080); credits_button_focus.Resize((402 * wptr->GetWidth())/1920, (90 * wptr->GetHeight())/1080); credits_button_normal.SetPosition(this->wptr->GetWidth()/2 - credits_button_normal.GetSize().x/2, (wptr->GetHeight() * 805) / 1080); credits_button_focus.SetPosition(this->wptr->GetWidth()/2 - credits_button_focus.GetSize().x/2, (wptr->GetHeight() * 805) / 1080); */ quit_button_normal.SetImage(resource_manager->GetImageResource(69)); quit_button_focus.SetImage(resource_manager->GetImageResource(70)); quit_button_normal.Resize((float)(140 * wptr->GetWidth())/1920,(float) (80 * wptr->GetHeight())/1080); quit_button_focus.Resize((float)(140 * wptr->GetWidth())/1920,(float) (80 * wptr->GetHeight())/1080); quit_button_normal.SetPosition(20, (float)wptr->GetHeight() - quit_button_focus.GetSize().y - 20); quit_button_focus.SetPosition(20,(float) wptr->GetHeight() - quit_button_focus.GetSize().y - 20); new_button_normal.SetImage(resource_manager->GetImageResource(76)); new_button_focus.SetImage(resource_manager->GetImageResource(77)); new_button_normal.Resize((float)(145 * wptr->GetWidth())/1920, (float)(80 * wptr->GetHeight())/1080); new_button_focus.Resize((float)(145 * wptr->GetWidth())/1920, (float)(80 * wptr->GetHeight())/1080); new_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - new_button_normal.GetSize().x/2,(float) (wptr->GetHeight() * 465) / 1080); new_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - new_button_focus.GetSize().x/2, (float)(wptr->GetHeight() * 465) / 1080); resume_button_normal.SetImage(resource_manager->GetImageResource(78)); resume_button_focus.SetImage(resource_manager->GetImageResource(79)); resume_button_normal.Resize((float)(254 * wptr->GetWidth())/1920,(float) (80 * wptr->GetHeight())/1080); resume_button_focus.Resize((float)(254 * wptr->GetWidth())/1920,(float) (80 * wptr->GetHeight())/1080); resume_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - resume_button_normal.GetSize().x/2, (float)(wptr->GetHeight() * 575) / 1080); resume_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - resume_button_focus.GetSize().x/2,(float) (wptr->GetHeight() * 575) / 1080); back_button_normal.SetImage(resource_manager->GetImageResource(80)); back_button_focus.SetImage(resource_manager->GetImageResource(81)); back_button_normal.Resize((float)(170 * wptr->GetWidth())/1920, (float)(84 * wptr->GetHeight())/1080); back_button_focus.Resize((float)(170 * wptr->GetWidth())/1920,(float) (84 * wptr->GetHeight())/1080); back_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - back_button_normal.GetSize().x/2, (float)(wptr->GetHeight() * 690) / 1080); back_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - back_button_focus.GetSize().x/2, (float)(wptr->GetHeight() * 690) / 1080); combos_button_focus.SetImage(resource_manager->GetImageResource(33)); combos_button_focus.Resize((float)(146 * wptr->GetWidth())/1920,(float) (146 * wptr->GetHeight())/1080); combos_button_focus.SetPosition((float)(wptr->GetWidth() * 301) / 1920,(float) (wptr->GetHeight() * 886) / 1080); //combos_button_focus.SetPosition((wptr->GetWidth() * 22) / 1920, (wptr->GetHeight() * 26) / 1080); combos_button_off.SetImage(resource_manager->GetImageResource(31)); combos_button_off.Resize((float)(146 * wptr->GetWidth())/1920, (float)(146 * wptr->GetHeight())/1080); combos_button_off.SetPosition((float)(wptr->GetWidth() * 301) / 1920, (float)(wptr->GetHeight() * 886) / 1080); //combos_button_off.SetPosition((wptr->GetWidth() * 153) / 1920, (wptr->GetHeight() * 26) / 1080); combos_button_on.SetImage(resource_manager->GetImageResource(32)); combos_button_on.Resize((float)(146 * wptr->GetWidth())/1920, (float)(146 * wptr->GetHeight())/1080); combos_button_on.SetPosition((float)(wptr->GetWidth() * 301) / 1920, (float)(wptr->GetHeight() * 886) / 1080); combos_button_state = "off"; movement_button_focus.SetImage(resource_manager->GetImageResource(36)); movement_button_focus.Resize((float)(146 * wptr->GetWidth())/1920,(float) (146 * wptr->GetHeight())/1080); movement_button_focus.SetPosition((float)(wptr->GetWidth() * 42) / 1920, (float)(wptr->GetHeight() * 886) / 1080); movement_button_off.SetImage(resource_manager->GetImageResource(34)); movement_button_off.Resize((float)(146 * wptr->GetWidth())/1920, (float)(146 * wptr->GetHeight())/1080); movement_button_off.SetPosition((float)(wptr->GetWidth() * 42) / 1920,(float) (wptr->GetHeight() * 886) / 1080); movement_button_on.SetImage(resource_manager->GetImageResource(35)); movement_button_on.Resize((float)(146 * wptr->GetWidth())/1920, (float)(146 * wptr->GetHeight())/1080); movement_button_on.SetPosition((float)(wptr->GetWidth() * 42) / 1920,(float) (wptr->GetHeight() * 886) / 1080); movement_button_state = "off"; treasure_button_focus.SetImage(resource_manager->GetImageResource(39)); treasure_button_focus.Resize((float)(146 * wptr->GetWidth())/1920,(float) (147 * wptr->GetHeight())/1080); treasure_button_focus.SetPosition((float)(wptr->GetWidth() * 174) / 1920, (float)(wptr->GetHeight() * 886) / 1080); treasure_button_off.SetImage(resource_manager->GetImageResource(37)); treasure_button_off.Resize((float)(146 * wptr->GetWidth())/1920, (float)(146 * wptr->GetHeight())/1080); treasure_button_off.SetPosition((float)(wptr->GetWidth() * 174) / 1920, (float)(wptr->GetHeight() * 886) / 1080); treasure_button_on.SetImage(resource_manager->GetImageResource(38)); treasure_button_on.Resize((float)(146 * wptr->GetWidth())/1920, (float)(146 * wptr->GetHeight())/1080); treasure_button_on.SetPosition((float)(wptr->GetWidth() * 174) / 1920,(float) (wptr->GetHeight() * 886) / 1080); treasure_button_state = "off"; combos_board.SetImage(resource_manager->GetImageResource(40)); combos_board.Resize((float)(483 * wptr->GetWidth())/1920,(float) (809 * wptr->GetHeight())/1080); //combos_board.SetPosition((wptr->GetWidth() * 44) / 1920, (wptr->GetHeight() * 80) / 1080); combos_board.SetPosition((float)0 - combos_board.GetSize().x - 20,(float) (wptr->GetHeight() * 80) / 1080); combosboard_x = combos_board.GetPosition().x; combos_board_state = "off"; movement_board.SetImage(resource_manager->GetImageResource(41)); movement_board.Resize((float)(483 * wptr->GetWidth())/1920,(float) (809 * wptr->GetHeight())/1080); //movement_board.SetPosition((wptr->GetWidth() * 44) / 1920, (wptr->GetHeight() * 80) / 1080); movement_board.SetPosition((float)0 - combos_board.GetSize().x - 20,(float) (wptr->GetHeight() * 80) / 1080); movesboard_x = movement_board.GetPosition().x; movement_board_state = "off"; treasure_board.SetImage(resource_manager->GetImageResource(42)); treasure_board.Resize((float)(483 * wptr->GetWidth())/1920, (float)(809 * wptr->GetHeight())/1080); //treasure_board.SetPosition((wptr->GetWidth() * 44) / 1920, (wptr->GetHeight() * 80) / 1080); treasure_board.SetPosition((float)0 - combos_board.GetSize().x - 20, (float)(wptr->GetHeight() * 80) / 1080); treasuresboard_x = treasure_board.GetPosition().x; treasure_board_state = "off"; is_sliding_out = false; textboard_to_show = "null"; textboard_to_hide = "null"; slide_speed = 2000; next_treasure_info[0].SetFont(chesster_font); next_treasure_info[0].SetText("200pts"); next_treasure_info[0].SetSize(48); next_treasure_info[0].SetColor(sf::Color(0,0,0)); next_treasure_info[0].SetPosition((float)(wptr->GetWidth() * 1600) / 1920,(float) (wptr->GetHeight() * 238) / 1080); next_treasure_info[1].SetFont(chesster_font); next_treasure_info[1].SetText("300pts"); next_treasure_info[1].SetSize(48); next_treasure_info[1].SetColor(sf::Color(0,0,0)); next_treasure_info[1].SetPosition((float)(wptr->GetWidth() * 1600) / 1920,(float) (wptr->GetHeight() * 238) / 1080); next_treasure_info[2].SetFont(chesster_font); next_treasure_info[2].SetText("400pts"); next_treasure_info[2].SetSize(48); next_treasure_info[2].SetColor(sf::Color(0,0,0)); next_treasure_info[2].SetPosition((float)(wptr->GetWidth() * 1600) / 1920, (float)(wptr->GetHeight() * 238) / 1080); next_treasure_info[3].SetFont(chesster_font); next_treasure_info[3].SetText("500pts"); next_treasure_info[3].SetSize(48); next_treasure_info[3].SetColor(sf::Color(0,0,0)); next_treasure_info[3].SetPosition((float)(wptr->GetWidth() * 1600) / 1920, (float)(wptr->GetHeight() * 238) / 1080); demand_animation[0].SetImage(resource_manager->LoadDemandAnimation(0)); demand_animation[0].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[0].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[1].SetImage(resource_manager->LoadDemandAnimation(1)); demand_animation[1].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[1].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[2].SetImage(resource_manager->LoadDemandAnimation(2)); demand_animation[2].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[2].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[3].SetImage(resource_manager->LoadDemandAnimation(3)); demand_animation[3].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[3].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[4].SetImage(resource_manager->LoadDemandAnimation(0)); demand_animation[4].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[4].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[5].SetImage(resource_manager->LoadDemandAnimation(5)); demand_animation[5].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[5].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[6].SetImage(resource_manager->LoadDemandAnimation(6)); demand_animation[6].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[6].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[7].SetImage(resource_manager->LoadDemandAnimation(7)); demand_animation[7].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[7].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[8].SetImage(resource_manager->LoadDemandAnimation(8)); demand_animation[8].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[8].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[9].SetImage(resource_manager->LoadDemandAnimation(9)); demand_animation[9].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[9].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[10].SetImage(resource_manager->LoadDemandAnimation(10)); demand_animation[10].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[10].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[11].SetImage(resource_manager->LoadDemandAnimation(11)); demand_animation[11].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[11].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[12].SetImage(resource_manager->LoadDemandAnimation(12)); demand_animation[12].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[12].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[13].SetImage(resource_manager->LoadDemandAnimation(13)); demand_animation[13].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[13].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[14].SetImage(resource_manager->LoadDemandAnimation(14)); demand_animation[14].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[14].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[15].SetImage(resource_manager->LoadDemandAnimation(15)); demand_animation[15].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[15].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[16].SetImage(resource_manager->LoadDemandAnimation(16)); demand_animation[16].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[16].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[17].SetImage(resource_manager->LoadDemandAnimation(17)); demand_animation[17].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[17].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[18].SetImage(resource_manager->LoadDemandAnimation(18)); demand_animation[18].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[18].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[19].SetImage(resource_manager->LoadDemandAnimation(19)); demand_animation[19].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[19].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[20].SetImage(resource_manager->LoadDemandAnimation(20)); demand_animation[20].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[20].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[21].SetImage(resource_manager->LoadDemandAnimation(21)); demand_animation[21].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[21].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[22].SetImage(resource_manager->LoadDemandAnimation(22)); demand_animation[22].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[22].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); positive_score_animation[0].SetImage(resource_manager->LoadPositiveScoreAnimation(0)); positive_score_animation[0].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[0].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[1].SetImage(resource_manager->LoadPositiveScoreAnimation(1)); positive_score_animation[1].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[1].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[2].SetImage(resource_manager->LoadPositiveScoreAnimation(2)); positive_score_animation[2].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[2].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[3].SetImage(resource_manager->LoadPositiveScoreAnimation(3)); positive_score_animation[3].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[3].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[4].SetImage(resource_manager->LoadPositiveScoreAnimation(4)); positive_score_animation[4].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[4].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[5].SetImage(resource_manager->LoadPositiveScoreAnimation(5)); positive_score_animation[5].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[5].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[6].SetImage(resource_manager->LoadPositiveScoreAnimation(6)); positive_score_animation[6].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[6].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[7].SetImage(resource_manager->LoadPositiveScoreAnimation(7)); positive_score_animation[7].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[7].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[8].SetImage(resource_manager->LoadPositiveScoreAnimation(8)); positive_score_animation[8].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[8].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[9].SetImage(resource_manager->LoadPositiveScoreAnimation(9)); positive_score_animation[9].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[9].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[10].SetImage(resource_manager->LoadPositiveScoreAnimation(10)); positive_score_animation[10].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[10].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[11].SetImage(resource_manager->LoadPositiveScoreAnimation(11)); positive_score_animation[11].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[11].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[12].SetImage(resource_manager->LoadPositiveScoreAnimation(12)); positive_score_animation[12].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[12].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[13].SetImage(resource_manager->LoadPositiveScoreAnimation(13)); positive_score_animation[13].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[13].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[14].SetImage(resource_manager->LoadPositiveScoreAnimation(14)); positive_score_animation[14].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[14].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[15].SetImage(resource_manager->LoadPositiveScoreAnimation(15)); positive_score_animation[15].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[15].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[16].SetImage(resource_manager->LoadPositiveScoreAnimation(16)); positive_score_animation[16].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[16].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[17].SetImage(resource_manager->LoadPositiveScoreAnimation(17)); positive_score_animation[17].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[17].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[18].SetImage(resource_manager->LoadPositiveScoreAnimation(18)); positive_score_animation[18].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[18].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[19].SetImage(resource_manager->LoadPositiveScoreAnimation(19)); positive_score_animation[19].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[19].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[20].SetImage(resource_manager->LoadPositiveScoreAnimation(20)); positive_score_animation[20].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[20].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[21].SetImage(resource_manager->LoadPositiveScoreAnimation(21)); positive_score_animation[21].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[21].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[22].SetImage(resource_manager->LoadPositiveScoreAnimation(22)); positive_score_animation[22].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[22].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[23].SetImage(resource_manager->LoadPositiveScoreAnimation(23)); positive_score_animation[23].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[23].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[24].SetImage(resource_manager->LoadPositiveScoreAnimation(24)); positive_score_animation[24].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[24].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_total_score_animation[0].SetImage(resource_manager->LoadPositiveScoreAnimation(0)); positive_total_score_animation[0].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[0].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[1].SetImage(resource_manager->LoadPositiveScoreAnimation(1)); positive_total_score_animation[1].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[1].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[2].SetImage(resource_manager->LoadPositiveScoreAnimation(2)); positive_total_score_animation[2].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[2].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[3].SetImage(resource_manager->LoadPositiveScoreAnimation(3)); positive_total_score_animation[3].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[3].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[4].SetImage(resource_manager->LoadPositiveScoreAnimation(4)); positive_total_score_animation[4].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[4].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[5].SetImage(resource_manager->LoadPositiveScoreAnimation(5)); positive_total_score_animation[5].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[5].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[6].SetImage(resource_manager->LoadPositiveScoreAnimation(6)); positive_total_score_animation[6].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[6].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[7].SetImage(resource_manager->LoadPositiveScoreAnimation(7)); positive_total_score_animation[7].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[7].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[8].SetImage(resource_manager->LoadPositiveScoreAnimation(8)); positive_total_score_animation[8].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[8].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[9].SetImage(resource_manager->LoadPositiveScoreAnimation(9)); positive_total_score_animation[9].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[9].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[10].SetImage(resource_manager->LoadPositiveScoreAnimation(10)); positive_total_score_animation[10].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[10].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[11].SetImage(resource_manager->LoadPositiveScoreAnimation(11)); positive_total_score_animation[11].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[11].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[12].SetImage(resource_manager->LoadPositiveScoreAnimation(12)); positive_total_score_animation[12].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[12].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[13].SetImage(resource_manager->LoadPositiveScoreAnimation(13)); positive_total_score_animation[13].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[13].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[14].SetImage(resource_manager->LoadPositiveScoreAnimation(14)); positive_total_score_animation[14].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[14].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[15].SetImage(resource_manager->LoadPositiveScoreAnimation(15)); positive_total_score_animation[15].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[15].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[16].SetImage(resource_manager->LoadPositiveScoreAnimation(16)); positive_total_score_animation[16].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[16].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[17].SetImage(resource_manager->LoadPositiveScoreAnimation(17)); positive_total_score_animation[17].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[17].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[18].SetImage(resource_manager->LoadPositiveScoreAnimation(18)); positive_total_score_animation[18].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[18].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[19].SetImage(resource_manager->LoadPositiveScoreAnimation(19)); positive_total_score_animation[19].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[19].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[20].SetImage(resource_manager->LoadPositiveScoreAnimation(20)); positive_total_score_animation[20].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[20].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[21].SetImage(resource_manager->LoadPositiveScoreAnimation(21)); positive_total_score_animation[21].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[21].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[22].SetImage(resource_manager->LoadPositiveScoreAnimation(22)); positive_total_score_animation[22].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[22].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[23].SetImage(resource_manager->LoadPositiveScoreAnimation(23)); positive_total_score_animation[23].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[23].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[24].SetImage(resource_manager->LoadPositiveScoreAnimation(24)); positive_total_score_animation[24].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[24].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[0].SetImage(resource_manager->LoadNegativeScoreAnimation(0)); negative_total_score_animation[0].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[0].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[1].SetImage(resource_manager->LoadNegativeScoreAnimation(1)); negative_total_score_animation[1].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[1].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[2].SetImage(resource_manager->LoadNegativeScoreAnimation(2)); negative_total_score_animation[2].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[2].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[3].SetImage(resource_manager->LoadNegativeScoreAnimation(3)); negative_total_score_animation[3].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[3].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[4].SetImage(resource_manager->LoadNegativeScoreAnimation(4)); negative_total_score_animation[4].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[4].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[5].SetImage(resource_manager->LoadNegativeScoreAnimation(5)); negative_total_score_animation[5].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[5].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[6].SetImage(resource_manager->LoadNegativeScoreAnimation(6)); negative_total_score_animation[6].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[6].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[7].SetImage(resource_manager->LoadNegativeScoreAnimation(7)); negative_total_score_animation[7].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[7].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[8].SetImage(resource_manager->LoadNegativeScoreAnimation(8)); negative_total_score_animation[8].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[8].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[9].SetImage(resource_manager->LoadNegativeScoreAnimation(9)); negative_total_score_animation[9].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[9].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[10].SetImage(resource_manager->LoadNegativeScoreAnimation(10)); negative_total_score_animation[10].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[10].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[11].SetImage(resource_manager->LoadNegativeScoreAnimation(11)); negative_total_score_animation[11].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[11].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[12].SetImage(resource_manager->LoadNegativeScoreAnimation(12)); negative_total_score_animation[12].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[12].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[13].SetImage(resource_manager->LoadNegativeScoreAnimation(13)); negative_total_score_animation[13].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[13].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[14].SetImage(resource_manager->LoadNegativeScoreAnimation(14)); negative_total_score_animation[14].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[14].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[15].SetImage(resource_manager->LoadNegativeScoreAnimation(15)); negative_total_score_animation[15].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[15].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[16].SetImage(resource_manager->LoadNegativeScoreAnimation(16)); negative_total_score_animation[16].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[16].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[17].SetImage(resource_manager->LoadNegativeScoreAnimation(17)); negative_total_score_animation[17].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[17].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[18].SetImage(resource_manager->LoadNegativeScoreAnimation(18)); negative_total_score_animation[18].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[18].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[19].SetImage(resource_manager->LoadNegativeScoreAnimation(19)); negative_total_score_animation[19].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[19].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[20].SetImage(resource_manager->LoadNegativeScoreAnimation(20)); negative_total_score_animation[20].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[20].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); } void InterfaceManager::SetupTreasureImagesForNewLevel() { treasure[0].SetImage(resource_manager->OnDemandLoadTreasures(0)); treasure[0].Resize((float)(120 * wptr->GetWidth())/1920, (float)(120 * wptr->GetHeight())/1080); treasure[0].SetPosition((float)(wptr->GetWidth() * 133) / 1920, (float)(wptr->GetHeight() * 327) / 1080); unlocked_treasures[0] = false; treasure_shadow[0].SetImage(resource_manager->OnDemandLoadTreasures(4)); treasure_shadow[0].Resize((float)(120 * wptr->GetWidth())/1920, (float)(120 * wptr->GetHeight())/1080); treasure_shadow[0].SetPosition((float)(wptr->GetWidth() * 133) / 1920, (float)(wptr->GetHeight() * 327) / 1080); next_treasure[0].SetImage(resource_manager->OnDemandLoadTreasures(0)); next_treasure[0].Resize((float)(160 * wptr->GetWidth())/1920, (float)(160 * wptr->GetHeight())/1080); next_treasure[0].SetPosition((float)(wptr->GetWidth() * 1598) / 1920, (float)(wptr->GetHeight() * 51) / 1080); treasure[1].SetImage(resource_manager->OnDemandLoadTreasures(1)); treasure[1].Resize((float)(120 * wptr->GetWidth())/1920, (float)(120 * wptr->GetHeight())/1080); treasure[1].SetPosition((float)(wptr->GetWidth() * 294) / 1920, (float)(wptr->GetHeight() * 326) / 1080); unlocked_treasures[1] = false; treasure_shadow[1].SetImage(resource_manager->OnDemandLoadTreasures(5)); treasure_shadow[1].Resize((float)(120 * wptr->GetWidth())/1920, (float)(120 * wptr->GetHeight())/1080); treasure_shadow[1].SetPosition((float)(wptr->GetWidth() * 294) / 1920, (float)(wptr->GetHeight() * 326) / 1080); next_treasure[1].SetImage(resource_manager->OnDemandLoadTreasures(1)); next_treasure[1].Resize((float)(160 * wptr->GetWidth())/1920, (float)(160 * wptr->GetHeight())/1080); next_treasure[1].SetPosition((float)(wptr->GetWidth() * 1598) / 1920, (float)(wptr->GetHeight() * 51) / 1080); treasure[2].SetImage(resource_manager->OnDemandLoadTreasures(2)); treasure[2].Resize((float)(120 * wptr->GetWidth())/1920, (float)(120 * wptr->GetHeight())/1080); treasure[2].SetPosition((float)(wptr->GetWidth() * 141) / 1920, (float)(wptr->GetHeight() * 554) / 1080); unlocked_treasures[2] = false; treasure_shadow[2].SetImage(resource_manager->OnDemandLoadTreasures(6)); treasure_shadow[2].Resize((float)(120 * wptr->GetWidth())/1920,(float) (120 * wptr->GetHeight())/1080); treasure_shadow[2].SetPosition((float)(wptr->GetWidth() * 141) / 1920, (float)(wptr->GetHeight() * 554) / 1080); next_treasure[2].SetImage(resource_manager->OnDemandLoadTreasures(2)); next_treasure[2].Resize((float)(160 * wptr->GetWidth())/1920, (float)(160 * wptr->GetHeight())/1080); next_treasure[2].SetPosition((float)(wptr->GetWidth() * 1598) / 1920, (float)(wptr->GetHeight() * 51) / 1080); treasure[3].SetImage(resource_manager->OnDemandLoadTreasures(3)); treasure[3].Resize((float)(120 * wptr->GetWidth())/1920, (float)(120 * wptr->GetHeight())/1080); treasure[3].SetPosition((float)(wptr->GetWidth() * 301) / 1920, (float)(wptr->GetHeight() * 538) / 1080); unlocked_treasures[3] = false; treasure_shadow[3].SetImage(resource_manager->OnDemandLoadTreasures(7)); treasure_shadow[3].Resize((float)(120 * wptr->GetWidth())/1920, (float)(120 * wptr->GetHeight())/1080); treasure_shadow[3].SetPosition((float)(wptr->GetWidth() * 301) / 1920, (float)(wptr->GetHeight() * 538) / 1080); next_treasure[3].SetImage(resource_manager->OnDemandLoadTreasures(3)); next_treasure[3].Resize((float)(160 * wptr->GetWidth())/1920, (float)(160 * wptr->GetHeight())/1080); next_treasure[3].SetPosition((float)(wptr->GetWidth() * 1598) / 1920, (float)(wptr->GetHeight() * 51) / 1080); } void InterfaceManager::PerformTextboardSlide() { if (is_sliding_out) { if (textboard_to_hide == "treasure") { if (treasuresboard_x > moving_textboard_target_x) { treasuresboard_x -= slide_speed * wptr->GetFrameTime(); treasure_board.SetPosition(treasuresboard_x, (wptr->GetHeight() * 80) / 1080); } else { textboard_to_hide = "null"; treasure_board_state = "off"; if (textboard_to_show == "moves") { movement_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } else if (textboard_to_show == "combos") { combos_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } is_sliding_out = false; } } else if (textboard_to_hide == "moves") { if (movesboard_x > moving_textboard_target_x) { movesboard_x -= slide_speed * wptr->GetFrameTime(); movement_board.SetPosition((float)movesboard_x, (float)(wptr->GetHeight() * 80) / 1080); } else { textboard_to_hide = "null"; movement_board_state = "off"; if (textboard_to_show == "treasure") { treasure_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } else if (textboard_to_show == "combos") { combos_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } is_sliding_out = false; } } else if (textboard_to_hide == "combos") { if (combosboard_x > moving_textboard_target_x) { combosboard_x -= slide_speed * wptr->GetFrameTime(); combos_board.SetPosition((float)combosboard_x , (float)(wptr->GetHeight() * 80) / 1080); } else { textboard_to_hide = "null"; combos_board_state = "off"; if (textboard_to_show == "moves") { movement_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } else if (textboard_to_show == "treasure") { treasure_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } is_sliding_out = false; } } } else // Slide in { if (textboard_to_show == "treasure") { if (treasuresboard_x < moving_textboard_target_x) { treasuresboard_x += slide_speed * wptr->GetFrameTime(); treasure_board.SetPosition((float)treasuresboard_x, (float)(wptr->GetHeight() * 80) / 1080); } else { textboard_to_show = "null"; } } else if (textboard_to_show == "moves") { if (movesboard_x < moving_textboard_target_x) { movesboard_x += slide_speed * wptr->GetFrameTime(); movement_board.SetPosition((float)movesboard_x, (float)(wptr->GetHeight() * 80) / 1080); } else { textboard_to_show = "null"; } } else if (textboard_to_show == "combos") { if (combosboard_x < moving_textboard_target_x) { combosboard_x += slide_speed * wptr->GetFrameTime(); combos_board.SetPosition((float)combosboard_x , (float)(wptr->GetHeight() * 80) / 1080); } else { textboard_to_show = "null"; } } } } void InterfaceManager::SetupTextboardTransition(std::string in, std::string out) { //one going out and another going in if (in != "null" && out != "null") { //std::cout <<"ONE IN ANOTHER OUT \n\n"; if (out == "combos") { textboard_to_hide = "combos"; moving_textboard_target_x = 0 - combos_board.GetSize().x - 20; } else if (out == "moves") { textboard_to_hide = "moves"; moving_textboard_target_x = 0 - movement_board.GetSize().x - 20; } else if (out == "treasure") { textboard_to_hide = "treasure"; moving_textboard_target_x = 0 - treasure_board.GetSize().x - 20; } textboard_to_show = in; is_sliding_out = true; } //just one going out else if (in == "null" && out != "null") { //std::cout <<"JUST ONE OUT \n\n"; if (out == "combos") { textboard_to_hide = "combos"; moving_textboard_target_x = 0 - combos_board.GetSize().x - 20; } else if (out == "moves") { textboard_to_hide = "moves"; moving_textboard_target_x = 0 - movement_board.GetSize().x - 20; } else if (out == "treasure") { textboard_to_hide = "treasure"; moving_textboard_target_x = 0 - treasure_board.GetSize().x - 20; } textboard_to_show = "null"; is_sliding_out = true; } //just one going in else if (in != "null" && out == "null") { //std::cout <<"JUST ONE IN \n\n"; if (in == "combos") { textboard_to_show = "combos"; combos_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } else if (in == "moves") { textboard_to_show = "moves"; movement_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } else if (in == "treasure") { textboard_to_show = "treasure"; treasure_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } textboard_to_hide = "null"; is_sliding_out = false; } } void InterfaceManager::ShowNextTreasure() { if (!this->unlocked_treasures[3] && !this->unlocked_treasures[2] && !this->unlocked_treasures[1] && !this->unlocked_treasures[0]) { //show first treasure this->wptr->Draw(this->next_treasure[0]); this->wptr->Draw(this->next_treasure_info[0]); this->wptr->Draw(this->next_treasure_banner); } else if (!this->unlocked_treasures[3] && !this->unlocked_treasures[2] && !this->unlocked_treasures[1] && this->unlocked_treasures[0]) { //show second treasure this->wptr->Draw(this->next_treasure[1]); this->wptr->Draw(this->next_treasure_info[1]); this->wptr->Draw(this->next_treasure_banner); } else if (!this->unlocked_treasures[3] && !this->unlocked_treasures[2] && this->unlocked_treasures[1] && this->unlocked_treasures[0]) { //show third treasure this->wptr->Draw(this->next_treasure[2]); this->wptr->Draw(this->next_treasure_info[2]); this->wptr->Draw(this->next_treasure_banner); } else if (!this->unlocked_treasures[3] && this->unlocked_treasures[2] && this->unlocked_treasures[1] && this->unlocked_treasures[0]) { //show fourth treasure this->wptr->Draw(this->next_treasure[3]); this->wptr->Draw(this->next_treasure_info[3]); this->wptr->Draw(this->next_treasure_banner); } } void InterfaceManager::RetifyTextPositions() { demand_info.SetPosition((float)((wptr->GetWidth() * 1670) / 1920) - demand_info.GetRect().GetWidth()/2, (float)(wptr->GetHeight() * 688) / 1080); turn_points_info.SetPosition((float)((wptr->GetWidth() * 1670) / 1920) - turn_points_info.GetRect().GetWidth()/2, (float)(wptr->GetHeight() * 508) / 1080); total_points_info.SetPosition((float)((wptr->GetWidth() * 1670) / 1920) - total_points_info.GetRect().GetWidth()/2, (float)(wptr->GetHeight() * 896) / 1080); } void InterfaceManager::ResetFontSize() { this->match_amount_info.SetSize((float)this->original_font_size); this->match_points_info.SetSize((float)this->original_font_size); } void InterfaceManager::IncreaseFontSize() { if (this->match_amount_info.GetSize() < 68) { this->match_amount_info.SetSize((float)this->match_amount_info.GetSize() + 4); this->match_points_info.SetSize((float)this->match_points_info.GetSize() + 4); } } void InterfaceManager::UnlockTreasure(int id) { this->unlocked_treasures[id] = true; } void InterfaceManager::ResetSlidingConditions() { is_sliding_out = false; textboard_to_show = "null"; textboard_to_hide = "null"; combos_board_state = "off"; movement_board_state = "off"; treasure_board_state = "off"; combos_button_state = "off"; movement_button_state = "off"; treasure_button_state = "off"; treasure_board.SetPosition((float)0 - combos_board.GetSize().x - 20, (float)(wptr->GetHeight() * 80) / 1080); treasuresboard_x = treasure_board.GetPosition().x; combos_board.SetPosition((float)0 - combos_board.GetSize().x - 20, (float)(wptr->GetHeight() * 80) / 1080); combosboard_x = combos_board.GetPosition().x; movement_board.SetPosition((float)0 - combos_board.GetSize().x - 20, (float)(wptr->GetHeight() * 80) / 1080); movesboard_x = movement_board.GetPosition().x; } std::string InterfaceManager::ButtonInput(int game_state, int x, int y) { std::string response; if (game_state == 0) { if (x > play_button_normal.GetPosition().x && x < play_button_normal.GetPosition().x + play_button_normal.GetSize().x && y > play_button_normal.GetPosition().y && y < play_button_normal.GetPosition().y + play_button_normal.GetSize().y) response = "Play"; if (x > tutorial_button_normal.GetPosition().x && x < tutorial_button_normal.GetPosition().x + tutorial_button_normal.GetSize().x && y > tutorial_button_normal.GetPosition().y && y < tutorial_button_normal.GetPosition().y + tutorial_button_normal.GetSize().y) response = "Tutorial"; if (x > puzzle_button_normal.GetPosition().x && x < puzzle_button_normal.GetPosition().x + puzzle_button_normal.GetSize().x && y > puzzle_button_normal.GetPosition().y && y < puzzle_button_normal.GetPosition().y + puzzle_button_normal.GetSize().y) response = "Puzzle"; if (x > scores_button_normal.GetPosition().x && x < scores_button_normal.GetPosition().x + scores_button_normal.GetSize().x && y > scores_button_normal.GetPosition().y && y < scores_button_normal.GetPosition().y + scores_button_normal.GetSize().y) response = "Scores"; if (x > credits_button_normal.GetPosition().x && x < credits_button_normal.GetPosition().x + credits_button_normal.GetSize().x && y > credits_button_normal.GetPosition().y && y < credits_button_normal.GetPosition().y + credits_button_normal.GetSize().y) response = "Credits"; if (x > quit_button_normal.GetPosition().x && x < quit_button_normal.GetPosition().x + quit_button_normal.GetSize().x && y > quit_button_normal.GetPosition().y && y < quit_button_normal.GetPosition().y + quit_button_normal.GetSize().y) response = "Quit"; return response; } else if (game_state == 30) { if (x > new_button_normal.GetPosition().x && x < new_button_normal.GetPosition().x + new_button_normal.GetSize().x && y > new_button_normal.GetPosition().y && y < new_button_normal.GetPosition().y + new_button_normal.GetSize().y) response = "New"; if (x > resume_button_normal.GetPosition().x && x < resume_button_normal.GetPosition().x + resume_button_normal.GetSize().x && y > resume_button_normal.GetPosition().y && y < resume_button_normal.GetPosition().y + resume_button_normal.GetSize().y) response = "Resume"; if (x > back_button_normal.GetPosition().x && x < back_button_normal.GetPosition().x + back_button_normal.GetSize().x && y > back_button_normal.GetPosition().y && y < back_button_normal.GetPosition().y + back_button_normal.GetSize().y) response = "Back"; return response; } else if (game_state == 1) { if (x > combos_button_off.GetPosition().x && x < combos_button_off.GetPosition().x + combos_button_off.GetSize().x && y > combos_button_off.GetPosition().y && y < combos_button_off.GetPosition().y + combos_button_off.GetSize().y) { if (combos_button_state == "focused") { //ReloadBoard(1); //std::cout << "Combos button was clicked\n\n"; if (movement_board_state == "on") { //std::cout << "Movement textboard is on\n\n"; SetupTextboardTransition("combos", "moves"); } else if (treasure_board_state == "on") { //std::cout << "Treasure textboard is on\n\n"; SetupTextboardTransition("combos", "treasure"); } else if (combos_board_state == "off" && movement_board_state == "off" && treasure_board_state == "off") { //std::cout << "All textboards are off\n\n"; SetupTextboardTransition("combos", "null"); } //combos_board_state = "on"; combos_button_state = "on"; //movement_board_state = "off"; movement_button_state = "off"; //treasure_board_state = "off"; treasure_button_state = "off"; } else if (combos_button_state == "on") { combos_button_state = "off"; //combos_board_state = "off"; SetupTextboardTransition("null", "combos"); } } else if (x > movement_button_off.GetPosition().x && x < movement_button_off.GetPosition().x + movement_button_off.GetSize().x && y > movement_button_off.GetPosition().y && y < movement_button_off.GetPosition().y + movement_button_off.GetSize().y) { if (movement_button_state == "focused") { //ReloadBoard(0); //std::cout << "Movement button was clicked\n\n"; if (combos_board_state == "on") { //std::cout << "Combos textboard is on\n\n"; SetupTextboardTransition("moves", "combos"); } else if (treasure_board_state == "on") { //std::cout << "Treasure textboard is on\n\n"; SetupTextboardTransition("moves", "treasure"); } else if (movement_board_state == "off" && combos_board_state == "off" && treasure_board_state == "off") { //std::cout << "All textboards are off\n\n"; SetupTextboardTransition("moves", "null"); } movement_button_state = "on"; //movement_board_state = "on"; //combos_board_state = "off"; combos_button_state = "off"; //treasure_board_state = "off"; treasure_button_state = "off"; } else if (movement_button_state == "on") { movement_button_state = "off"; //movement_board_state = "off"; SetupTextboardTransition("null", "moves"); } } else if (x > treasure_button_off.GetPosition().x && x < treasure_button_off.GetPosition().x + treasure_button_off.GetSize().x && y > treasure_button_off.GetPosition().y && y < treasure_button_off.GetPosition().y + treasure_button_off.GetSize().y) { if (treasure_button_state == "focused") { //ReloadBoard(2); if (combos_board_state == "on") { SetupTextboardTransition("treasure", "combos"); } else if (movement_board_state == "on") { SetupTextboardTransition("treasure", "moves"); } else if (treasure_board_state == "off" && combos_board_state == "off" && movement_board_state == "off") { SetupTextboardTransition("treasure", "null"); } treasure_button_state = "on"; //treasure_board_state = "on"; movement_button_state = "off"; //movement_board_state = "off"; //combos_board_state = "off"; combos_button_state = "off"; } else if (treasure_button_state == "on") { treasure_button_state = "off"; //treasure_board_state = "off"; SetupTextboardTransition("null", "treasure"); } } return "Null"; } } void InterfaceManager::ResetTreasures() { for (int i = 0; i < 4; i++) { this->unlocked_treasures[i] = false; } this->SetupTreasureImagesForNewLevel(); } void InterfaceManager::LoadSavedTreasures(int t1, int t2, int t3, int t4) { if (t1 == 1) this->unlocked_treasures[0] = true; if (t2 == 1) this->unlocked_treasures[1] = true; if (t3 == 1) this->unlocked_treasures[2] = true; if (t4 == 1) this->unlocked_treasures[3] = true; } void InterfaceManager::ReloadBoard(int brd) { if (brd == 2) { treasure_board.SetImage(resource_manager->OnDemandLoadForBoards(2)); treasure_board.Resize((float)(483 * wptr->GetWidth())/1920, (float)(809 * wptr->GetHeight())/1080); treasure_board.SetPosition((float)(wptr->GetWidth() * 44) / 1920, (float)(wptr->GetHeight() * 80) / 1080); } else if (brd == 0) { movement_board.SetImage(resource_manager->OnDemandLoadForBoards(0)); movement_board.Resize((float)(483 * wptr->GetWidth())/1920, (float)(809 * wptr->GetHeight())/1080); movement_board.SetPosition((float)(wptr->GetWidth() * 44) / 1920, (float)(wptr->GetHeight() * 80) / 1080); } else if (brd == 1) { combos_board.SetImage(resource_manager->OnDemandLoadForBoards(1)); combos_board.Resize((float)(483 * wptr->GetWidth())/1920, (float)(809 * wptr->GetHeight())/1080); combos_board.SetPosition((float)(wptr->GetWidth() * 44) / 1920, (float)(wptr->GetHeight() * 80) / 1080); } } void InterfaceManager::HandleGameButtons(int game_state) { int x = wptr->GetInput().GetMouseX(); int y = wptr->GetInput().GetMouseY(); if (combos_button_state == "off") this->wptr->Draw(combos_button_off); else if (combos_button_state == "on") this->wptr->Draw(combos_button_on); else if (combos_button_state == "focused") this->wptr->Draw(combos_button_focus); if (movement_button_state == "off") this->wptr->Draw(movement_button_off); else if (movement_button_state == "on") this->wptr->Draw(movement_button_on); else if (movement_button_state == "focused") this->wptr->Draw(movement_button_focus); if (treasure_button_state == "off") this->wptr->Draw(treasure_button_off); else if (treasure_button_state == "on") this->wptr->Draw(treasure_button_on); else if (treasure_button_state == "focused") this->wptr->Draw(treasure_button_focus); if (game_state == 1) //show textboards only when the player has control over the board { if (combos_board_state == "on") this->wptr->Draw(combos_board); if (movement_board_state == "on") this->wptr->Draw(movement_board); if (treasure_board_state == "on") { this->wptr->Draw(treasure_board); if (!is_sliding_out && treasure_board.GetPosition().x >= moving_textboard_target_x) { for (int i = 0; i < 4; i++) { if (this->unlocked_treasures[i]) this->wptr->Draw(this->treasure[i]); else this->wptr->Draw(this->treasure_shadow[i]); } } } } if (x > combos_button_off.GetPosition().x && x < combos_button_off.GetPosition().x + combos_button_off.GetSize().x && y > combos_button_off.GetPosition().y && y < combos_button_off.GetPosition().y + combos_button_off.GetSize().y) { if (combos_button_state == "off") combos_button_state = "focused"; } else { if (combos_button_state == "focused") combos_button_state = "off"; } if (x > movement_button_off.GetPosition().x && x < movement_button_off.GetPosition().x + movement_button_off.GetSize().x && y > movement_button_off.GetPosition().y && y < movement_button_off.GetPosition().y + movement_button_off.GetSize().y) { if (movement_button_state == "off") movement_button_state = "focused"; } else { if (movement_button_state == "focused") movement_button_state = "off"; } if (x > treasure_button_off.GetPosition().x && x < treasure_button_off.GetPosition().x + treasure_button_off.GetSize().x && y > treasure_button_off.GetPosition().y && y < treasure_button_off.GetPosition().y + treasure_button_off.GetSize().y) { if (treasure_button_state == "off") treasure_button_state = "focused"; } else { if (treasure_button_state == "focused") treasure_button_state = "off"; } this->PerformTextboardSlide(); } void InterfaceManager::HandleMainMenuButtons(int screenId) { int x = wptr->GetInput().GetMouseX(); int y = wptr->GetInput().GetMouseY(); if (screenId == 0) // Main Menu { if (x > play_button_normal.GetPosition().x && x < play_button_normal.GetPosition().x + play_button_normal.GetSize().x && y > play_button_normal.GetPosition().y && y < play_button_normal.GetPosition().y + play_button_normal.GetSize().y) wptr->Draw(play_button_focus); else wptr->Draw(play_button_normal); if (x > tutorial_button_normal.GetPosition().x && x < tutorial_button_normal.GetPosition().x + tutorial_button_normal.GetSize().x && y > tutorial_button_normal.GetPosition().y && y < tutorial_button_normal.GetPosition().y + tutorial_button_normal.GetSize().y) wptr->Draw(tutorial_button_focus); else wptr->Draw(tutorial_button_normal); if (x > puzzle_button_normal.GetPosition().x && x < puzzle_button_normal.GetPosition().x + puzzle_button_normal.GetSize().x && y > puzzle_button_normal.GetPosition().y && y < puzzle_button_normal.GetPosition().y + puzzle_button_normal.GetSize().y) wptr->Draw(puzzle_button_focus); else wptr->Draw(puzzle_button_normal); if (x > scores_button_normal.GetPosition().x && x < scores_button_normal.GetPosition().x + scores_button_normal.GetSize().x && y > scores_button_normal.GetPosition().y && y < scores_button_normal.GetPosition().y + scores_button_normal.GetSize().y) wptr->Draw(scores_button_focus); else wptr->Draw(scores_button_normal); if (x > credits_button_normal.GetPosition().x && x < credits_button_normal.GetPosition().x + credits_button_normal.GetSize().x && y > credits_button_normal.GetPosition().y && y < credits_button_normal.GetPosition().y + credits_button_normal.GetSize().y) wptr->Draw(credits_button_focus); else wptr->Draw(credits_button_normal); if (x > quit_button_normal.GetPosition().x && x < quit_button_normal.GetPosition().x + quit_button_normal.GetSize().x && y > quit_button_normal.GetPosition().y && y < quit_button_normal.GetPosition().y + quit_button_normal.GetSize().y) wptr->Draw(quit_button_focus); else wptr->Draw(quit_button_normal); } else if (screenId == 1) //New or Resume selection submenu { if (x > new_button_normal.GetPosition().x && x < new_button_normal.GetPosition().x + new_button_normal.GetSize().x && y > new_button_normal.GetPosition().y && y < new_button_normal.GetPosition().y + new_button_normal.GetSize().y) wptr->Draw(new_button_focus); else wptr->Draw(new_button_normal); if (x > resume_button_normal.GetPosition().x && x < resume_button_normal.GetPosition().x + resume_button_normal.GetSize().x && y > resume_button_normal.GetPosition().y && y < resume_button_normal.GetPosition().y + resume_button_normal.GetSize().y) wptr->Draw(resume_button_focus); else wptr->Draw(resume_button_normal); if (x > back_button_normal.GetPosition().x && x < back_button_normal.GetPosition().x + back_button_normal.GetSize().x && y > back_button_normal.GetPosition().y && y < back_button_normal.GetPosition().y + back_button_normal.GetSize().y) wptr->Draw(back_button_focus); else wptr->Draw(back_button_normal); } } void InterfaceManager::SetupScoreUpdate(int tScore, int mode, bool remainder) { if (mode == 0) //Add turn points { targetScore = tScore + currentScore; isIncreasingScore = true; isDecreasingScore = false; isAnimating = true; positive_score_animation_frame = 0; positive_score_animation_timer.Reset(); } else if (mode == 1) //Decrease demand { targetScore = currentScore - 100; isIncreasingScore = false; isDecreasingScore = false; isAnimating = true; demand_animation_timer.Reset(); demand_animation_frame = 0; hasEndTimerStarted = false; } else if (mode == 2) { isIncreasingScore = false; isDecreasingScore = true; targetScore = 0; isAnimating = true; positive_score_animation_frame = 0; positive_score_animation_timer.Reset(); hasPositiveRemainder = remainder; } scoreUpdateTimer.Reset(); } void InterfaceManager::UpdateScore(int mode) { if (mode == 0) //Add turn points { if (scoreUpdateTimer.GetElapsedTime() >= 0.0001f && isIncreasingScore) { currentScore++; std::stringstream out; out << currentScore; this->turn_points_info.SetText(out.str()); if (currentScore >= targetScore) { isIncreasingScore = false; return; } else { scoreUpdateTimer.Reset(); } currentScore++; std::stringstream out2; out2 << currentScore; this->turn_points_info.SetText(out2.str()); if (currentScore >= targetScore) { isIncreasingScore = false; return; } else { scoreUpdateTimer.Reset(); } } if (isAnimating) { if (positive_score_animation_timer.GetElapsedTime() >= 0.04f) { if (positive_score_animation_frame < 24) { positive_score_animation_frame++; positive_score_animation_timer.Reset(); } else { isAnimating = false; } } } } else if (mode == 1) //Decrease demand { if (scoreUpdateTimer.GetElapsedTime() >= 0.01f && isDecreasingScore) { currentScore--; std::stringstream out; out << currentScore; this->turn_points_info.SetText(out.str()); if (currentScore <= targetScore) { isDecreasingScore = false; return; } else { scoreUpdateTimer.Reset(); } } if (isAnimating) { if (demand_animation_timer.GetElapsedTime() >= 0.04f) { if (demand_animation_frame < 22) { demand_animation_frame++; demand_animation_timer.Reset(); if (demand_animation_frame >= 10 && isDecreasingScore == false) isDecreasingScore = true; } else { isAnimating = false; } } } } else if (mode == 2) //Total calculation { if (scoreUpdateTimer.GetElapsedTime() >= 0.01f && isDecreasingScore) { if (hasPositiveRemainder) { currentScore--; std::stringstream out; out << currentScore; this->turn_points_info.SetText(out.str()); currentTotalScore++; std::stringstream out2; out2 << currentTotalScore; this->total_points_info.SetText(out2.str()); if (currentScore <= targetScore) { isDecreasingScore = false; return; } else { scoreUpdateTimer.Reset(); } currentScore--; std::stringstream out3; out3 << currentScore; this->turn_points_info.SetText(out3.str()); currentTotalScore++; std::stringstream out4; out4 << currentTotalScore; this->total_points_info.SetText(out4.str()); if (currentScore <= targetScore) { isDecreasingScore = false; return; } else { scoreUpdateTimer.Reset(); } } else { if(currentScore != 0) { currentScore++; std::stringstream out5; out5 << currentScore; this->turn_points_info.SetText(out5.str()); currentTotalScore--; std::stringstream out6; out6 << currentTotalScore; this->total_points_info.SetText(out6.str()); } if (currentScore >= targetScore) { isDecreasingScore = false; return; } else { scoreUpdateTimer.Reset(); } } } if (isAnimating) { if (hasPositiveRemainder) { if (positive_score_animation_timer.GetElapsedTime() >= 0.04f) { if (positive_score_animation_frame < 24) { positive_score_animation_frame++; positive_score_animation_timer.Reset(); } else { isAnimating = false; } } } else { if (positive_score_animation_timer.GetElapsedTime() >= 0.04f) { if (positive_score_animation_frame < 20) { positive_score_animation_frame++; positive_score_animation_timer.Reset(); } else { isAnimating = false; } } } } } }
49.861827
181
0.699439
cjcoimbra
cc152ed8c9aee502fdebf84cfb612afa33c1e52a
945
hh
C++
gazebo/physics/roki/RokiFixedJoint.hh
nyxrobotics/gazebo
4a9b733a8af9a13cd7f3b23d5414d322a3666a55
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/physics/roki/RokiFixedJoint.hh
nyxrobotics/gazebo
4a9b733a8af9a13cd7f3b23d5414d322a3666a55
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/physics/roki/RokiFixedJoint.hh
nyxrobotics/gazebo
4a9b733a8af9a13cd7f3b23d5414d322a3666a55
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#ifndef _ROKIFIXEDJOINT_HH_ #define _ROKIFIXEDJOINT_HH_ #include "ignition/math/Angle.hh" #include "ignition/math/Vector3.hh" #include "gazebo/util/system.hh" #include "gazebo/physics/FixedJoint.hh" #include "gazebo/physics/roki/RokiJoint.hh" namespace gazebo { namespace physics { class GZ_PHYSICS_VISIBLE RokiFixedJoint : public FixedJoint<RokiJoint> { public: explicit RokiFixedJoint(BasePtr _parent); public: virtual ~RokiFixedJoint(); public: virtual void Load(sdf::ElementPtr _sdf); public: virtual void Init(); public: virtual double PositionImpl(const unsigned int _index) const; public: virtual void SetVelocity(unsigned int _index, double _vel); public: virtual double GetVelocity(unsigned int _index) const; protected: virtual void SetForceImpl(unsigned int _index, double _effort); protected: virtual double GetForceImpl(unsigned int _index); }; } } #endif
30.483871
80
0.740741
nyxrobotics
cc1d8404cce1393b8064f3f064102a54d8cdc892
844
hpp
C++
ltl2fsm/base/exception/Invalid_Vertex_Name.hpp
arafato/ltl2fsm
58d96c40fe0890c2bcc90593469668e6369c0f1b
[ "MIT" ]
2
2016-11-23T14:31:55.000Z
2018-05-10T01:11:54.000Z
ltl2fsm/base/exception/Invalid_Vertex_Name.hpp
arafato/ltl2fsm
58d96c40fe0890c2bcc90593469668e6369c0f1b
[ "MIT" ]
null
null
null
ltl2fsm/base/exception/Invalid_Vertex_Name.hpp
arafato/ltl2fsm
58d96c40fe0890c2bcc90593469668e6369c0f1b
[ "MIT" ]
null
null
null
/** * @file ltl2fsm/base/exception/Invalid_Vertex_Name.hpp * * $Id$ * * @author Oliver Arafat * * @brief @ref * * @note DOCUMENTED * * @test * * @todo */ #ifndef LTL2FSM__BASE__EXCEPTION__INVALID_VERTEX_NAME__HPP #define LTL2FSM__BASE__EXCEPTION__INVALID_VERTEX_NAME__HPP #include<ltl2fsm/base/exception/Exception.hpp> LTL2FSM__BEGIN__NAMESPACE__LTL2FSM; class Invalid_Vertex_Name : public Exception { //////////////////////////////////////////////////////////////////////////////// /** * @name Construction / Destruction * @{ */ public: Invalid_Vertex_Name(Source_Location const & source_location, ::std::string const & what); virtual ~Invalid_Vertex_Name() throw(); // @} public: virtual char const * class_name() const; }; LTL2FSM__END__NAMESPACE__LTL2FSM; #endif
16.88
84
0.627962
arafato
cc1fbd9849223de739927cfa2f2d8b36cebd54ff
5,367
cpp
C++
src/dispatcher.cpp
ornl-epics/epicsipmi
788bf6a815e2c0c3a17df219a5becf7f9a376d65
[ "BSD-3-Clause" ]
1
2019-11-15T08:21:52.000Z
2019-11-15T08:21:52.000Z
src/dispatcher.cpp
ornl-epics/epicsipmi
788bf6a815e2c0c3a17df219a5becf7f9a376d65
[ "BSD-3-Clause" ]
1
2020-11-09T17:48:19.000Z
2020-11-11T17:41:09.000Z
src/dispatcher.cpp
klemenv/epicsipmi
05daec62f5bb003361836708a348e13cea0b9474
[ "BSD-3-Clause" ]
null
null
null
/* dispatcher.cpp * * Copyright (c) 2018 Oak Ridge National Laboratory. * All rights reserved. * See file LICENSE that is included with this distribution. * * @author Klemen Vodopivec * @date Oct 2018 */ #include "common.h" #include "freeipmiprovider.h" #include "print.h" #include "dispatcher.h" #include <cstring> #include <map> #include <string> // EPICS records that we support #include <aiRecord.h> #include <stringinRecord.h> namespace dispatcher { static std::map<std::string, std::shared_ptr<FreeIpmiProvider>> g_connections; //!< Global map of connections. static epicsMutex g_mutex; //!< Global mutex to protect g_connections. static std::pair<std::string, std::string> _parseLink(const std::string& link) { auto tokens = common::split(link, ' ', 2); if (tokens.size() < 3 || tokens[0] != "ipmi") return std::make_pair(std::string(""), std::string("")); return std::make_pair(tokens[1], tokens[2]); } static std::string _createLink(const std::string& conn_id, const std::string& addr) { return "@ipmi " + conn_id + " " + addr; } static std::shared_ptr<FreeIpmiProvider> _getConnection(const std::string& conn_id) { common::ScopedLock lock(g_mutex); auto it = g_connections.find(conn_id); if (it != g_connections.end()) return it->second; return nullptr; } bool connect(const std::string& conn_id, const std::string& hostname, const std::string& username, const std::string& password, const std::string& authtype, const std::string& protocol, const std::string& privlevel) { common::ScopedLock lock(g_mutex); if (g_connections.find(conn_id) != g_connections.end()) return false; std::shared_ptr<FreeIpmiProvider> conn; try { conn.reset(new FreeIpmiProvider(conn_id, hostname, username, password, authtype, protocol, privlevel)); } catch (std::bad_alloc& e) { LOG_ERROR("can't allocate FreeIPMI provider\n"); return false; } catch (std::runtime_error& e) { if (username.empty()) LOG_ERROR("can't connect to %s - %s", hostname.c_str(), e.what()); else LOG_ERROR("can't connect to %s as user %s - %s", hostname.c_str(), username.c_str(), e.what()); return false; } g_connections[conn_id] = conn; return true; } void scan(const std::string& conn_id, const std::vector<EntityType>& types) { g_mutex.lock(); auto it = g_connections.find(conn_id); bool found = (it != g_connections.end()); g_mutex.unlock(); if (!found) { LOG_ERROR("no such connection " + conn_id); return; } auto conn = it->second; for (auto& type: types) { try { std::vector<Provider::Entity> entities; std::string header; if (type == EntityType::SENSOR) { entities = conn->getSensors(); header = "Sensors:"; } else if (type == EntityType::FRU) { entities = conn->getFrus(); header = "FRUs:"; } else if (type == EntityType::PICMG_LED) { entities = conn->getPicmgLeds(); header = "PICMG LEDs:"; } print::printScanReport(header, entities); } catch (std::runtime_error& e) { LOG_ERROR(e.what()); } } } void printDb(const std::string& conn_id, const std::string& path, const std::string& pv_prefix) { g_mutex.lock(); auto it = g_connections.find(conn_id); bool found = (it != g_connections.end()); g_mutex.unlock(); if (!found) { LOG_ERROR("no such connection " + conn_id); return; } auto conn = it->second; FILE *dbfile = fopen(path.c_str(), "w+"); if (dbfile == nullptr) LOG_ERROR("Failed to open output database file - %s", strerror(errno)); try { auto sensors = conn->getSensors(); for (auto& sensor: sensors) { auto inp = sensor.getField<std::string>("INP", ""); if (!inp.empty()) { sensor["INP"] = _createLink(conn_id, inp); print::printRecord(dbfile, pv_prefix, sensor); } } auto frus = conn->getFrus(); for (auto& fru: frus) { auto inp = fru.getField<std::string>("INP", ""); if (!inp.empty()) { fru["INP"] = _createLink(conn_id, inp); print::printRecord(dbfile, pv_prefix, fru); } } auto leds = conn->getPicmgLeds(); for (auto& led: leds) { auto inp = led.getField<std::string>("INP", ""); if (!inp.empty()) { led["INP"] = _createLink(conn_id, inp); print::printRecord(dbfile, pv_prefix, led); } } } catch (...) { // TODO: do we need to log } fclose(dbfile); } bool checkLink(const std::string& address) { auto conn = _getConnection( _parseLink(address).first ); return (!!conn); } bool scheduleGet(const std::string& address, const std::function<void()>& cb, Provider::Entity& entity) { auto addr = _parseLink(address); auto conn = _getConnection(addr.first); if (!conn) return false; return conn->schedule( Provider::Task(std::move(addr.second), cb, entity) ); } }; // namespace dispatcher
29.327869
111
0.584312
ornl-epics
cc2d80af346a576a7ad097c9f3e4ed58e0e24533
19,936
cpp
C++
OpenDriveMap.cpp
chacha95/libOpendrive
69400a60bd7e4de331396f92c7d20d1a795f4ca9
[ "Apache-2.0" ]
1
2021-12-06T02:03:09.000Z
2021-12-06T02:03:09.000Z
OpenDriveMap.cpp
chacha95/libOpendrive
69400a60bd7e4de331396f92c7d20d1a795f4ca9
[ "Apache-2.0" ]
null
null
null
OpenDriveMap.cpp
chacha95/libOpendrive
69400a60bd7e4de331396f92c7d20d1a795f4ca9
[ "Apache-2.0" ]
1
2021-12-06T02:03:46.000Z
2021-12-06T02:03:46.000Z
#include "OpenDriveMap.h" #include "Geometries/Arc.h" #include "Geometries/CubicSpline.h" #include "Geometries/Line.h" #include "Geometries/ParamPoly3.h" #include "Geometries/Spiral.h" #include "LaneSection.h" #include "Lanes.h" #include "RefLine.h" #include "Road.h" #include "pugixml/pugixml.hpp" #include <iostream> #include <string> #include <utility> namespace odr { OpenDriveMap::OpenDriveMap(std::string xodr_file, bool with_lateralProfile, bool with_laneHeight, bool center_map) : xodr_file(xodr_file) { pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(xodr_file.c_str()); if (!result) printf("%s\n", result.description()); pugi::xml_node odr_node = doc.child("OpenDRIVE"); if (auto geoReference_node = odr_node.child("header").child("geoReference")) this->proj4 = geoReference_node.text().as_string(); size_t cnt = 1; if (center_map) { for (pugi::xml_node road_node : odr_node.children("road")) { for (pugi::xml_node geometry_hdr_node : road_node.child("planView").children("geometry")) { const double x0 = geometry_hdr_node.attribute("x").as_double(); this->x_offs = this->x_offs + ((x0 - this->x_offs) / cnt); const double y0 = geometry_hdr_node.attribute("y").as_double(); this->y_offs = this->y_offs + ((y0 - this->y_offs) / cnt); cnt++; } } } for (pugi::xml_node road_node : odr_node.children("road")) { /* make road */ std::shared_ptr<Road> road = std::make_shared<Road>(); road->length = road_node.attribute("length").as_double(); road->id = road_node.attribute("id").as_string(); road->junction = road_node.attribute("junction").as_string(); road->name = road_node.attribute("name").as_string(); this->roads[road->id] = road; /* parse road links */ for (bool is_predecessor : {true, false}) { pugi::xml_node road_link_node = is_predecessor ? road_node.child("link").child("predecessor") : road_node.child("link").child("successor"); if (road_link_node) { RoadLink& link = is_predecessor ? road->predecessor : road->successor; link.elementId = road_link_node.child("elementId").text().as_string(); link.elementType = road_link_node.child("elementType").text().as_string(); link.contactPoint = road_link_node.child("contactPoint").text().as_string(); } } /* parse road neighbors */ for (pugi::xml_node road_neighbor_node : road_node.child("link").children("neighbor")) { RoadNeighbor road_neighbor; road_neighbor.elementId = road_neighbor_node.attribute("elementId").as_string(); road_neighbor.side = road_neighbor_node.attribute("side").as_string(); road_neighbor.direction = road_neighbor_node.attribute("direction").as_string(); road->neighbors.push_back(road_neighbor); } /* parse road type and speed */ for (pugi::xml_node road_type_node : road_node.children("type")) { double s = road_type_node.attribute("s").as_double(); std::string type = road_type_node.attribute("type").as_string(); road->s_to_type[s] = type; if (pugi::xml_node node = road_type_node.child("speed")) { SpeedRecord speed_record; speed_record.max = node.attribute("max").as_string(); speed_record.unit = node.attribute("unit").as_string(); road->s_to_speed[s] = speed_record; } } /* make ref_line - parse road geometries */ road->ref_line = std::make_shared<RefLine>(road->length); for (pugi::xml_node geometry_hdr_node : road_node.child("planView").children("geometry")) { double s0 = geometry_hdr_node.attribute("s").as_double(); double x0 = geometry_hdr_node.attribute("x").as_double() - this->x_offs; double y0 = geometry_hdr_node.attribute("y").as_double() - this->y_offs; double hdg0 = geometry_hdr_node.attribute("hdg").as_double(); double length = geometry_hdr_node.attribute("length").as_double(); pugi::xml_node geometry_node = geometry_hdr_node.first_child(); std::string geometry_type = geometry_node.name(); if (geometry_type == "line") { road->ref_line->s0_to_geometry[s0] = std::make_shared<Line>(s0, x0, y0, hdg0, length); } else if (geometry_type == "spiral") { double curv_start = geometry_node.attribute("curvStart").as_double(); double curv_end = geometry_node.attribute("curvEnd").as_double(); road->ref_line->s0_to_geometry[s0] = std::make_shared<Spiral>(s0, x0, y0, hdg0, length, curv_start, curv_end); } else if (geometry_type == "arc") { double curvature = geometry_node.attribute("curvature").as_double(); road->ref_line->s0_to_geometry[s0] = std::make_shared<Arc>(s0, x0, y0, hdg0, length, curvature); } else if (geometry_type == "paramPoly3") { double aU = geometry_node.attribute("aU").as_double(); double bU = geometry_node.attribute("bU").as_double(); double cU = geometry_node.attribute("cU").as_double(); double dU = geometry_node.attribute("dU").as_double(); double aV = geometry_node.attribute("aV").as_double(); double bV = geometry_node.attribute("bV").as_double(); double cV = geometry_node.attribute("cV").as_double(); double dV = geometry_node.attribute("dV").as_double(); bool pRange_normalized = true; if (geometry_node.attribute("pRange")) { std::string pRange_str = geometry_node.attribute("pRange").as_string(); std::transform(pRange_str.begin(), pRange_str.end(), pRange_str.begin(), [](unsigned char c) { return std::tolower(c); }); if (pRange_str == "arclength") pRange_normalized = false; } road->ref_line->s0_to_geometry[s0] = std::make_shared<ParamPoly3>(s0, x0, y0, hdg0, length, aU, bU, cU, dU, aV, bV, cV, dV, pRange_normalized); } else { printf("Could not parse %s\n", geometry_type.c_str()); } } std::map<std::string /*x path query*/, CubicSpline&> cubic_spline_fields{ {".//elevationProfile//elevation", road->ref_line->elevation_profile}, {".//lanes//laneOffset", road->lane_offset}}; if (with_lateralProfile) cubic_spline_fields.insert({".//lateralProfile//superelevation", road->superelevation}); /* parse elevation profiles, lane offsets, superelevation */ for (auto entry : cubic_spline_fields) { pugi::xpath_node_set nodes = road_node.select_nodes(entry.first.c_str()); for (pugi::xpath_node node : nodes) { double s0 = node.node().attribute("s").as_double(); double a = node.node().attribute("a").as_double(); double b = node.node().attribute("b").as_double(); double c = node.node().attribute("c").as_double(); double d = node.node().attribute("d").as_double(); entry.second.s0_to_poly[s0] = Poly3(s0, a, b, c, d); } } /* parse crossfall - has extra attribute side */ if (with_lateralProfile) { for (pugi::xml_node crossfall_node : road_node.child("lateralProfile").children("crossfall")) { double s0 = crossfall_node.attribute("s").as_double(); double a = crossfall_node.attribute("a").as_double(); double b = crossfall_node.attribute("b").as_double(); double c = crossfall_node.attribute("c").as_double(); double d = crossfall_node.attribute("d").as_double(); Poly3 crossfall_poly(s0, a, b, c, d); road->crossfall.s0_to_poly[s0] = crossfall_poly; if (pugi::xml_attribute side = crossfall_node.attribute("side")) { std::string side_str = side.as_string(); std::transform(side_str.begin(), side_str.end(), side_str.begin(), [](unsigned char c) { return std::tolower(c); }); if (side_str == "left") road->crossfall.sides[s0] = Crossfall::Side::Left; else if (side_str == "right") road->crossfall.sides[s0] = Crossfall::Side::Right; else road->crossfall.sides[s0] = Crossfall::Side::Both; } } /* check for lateralProfile shape - not implemented yet */ for (auto road_shape_node : road_node.child("lateralProfile").children("shape")) printf("Lateral Profile Shape not supported\n"); } /* parse road lane sections and lanes */ for (pugi::xml_node lane_section_node : road_node.child("lanes").children("laneSection")) { double s0 = lane_section_node.attribute("s").as_double(); std::shared_ptr<LaneSection> lane_section = std::make_shared<LaneSection>(s0); lane_section->road = road; road->s_to_lanesection[lane_section->s0] = lane_section; for (pugi::xpath_node lane_node : lane_section_node.select_nodes(".//lane")) { int lane_id = lane_node.node().attribute("id").as_int(); std::string lane_type = lane_node.node().attribute("type").as_string(); bool level = lane_node.node().attribute("level").as_bool(); std::shared_ptr<Lane> lane = std::make_shared<Lane>(lane_id, level, lane_type); lane->road = road; lane_section->id_to_lane[lane->id] = lane; for (pugi::xml_node lane_width_node : lane_node.node().children("width")) { double sOffs = lane_width_node.attribute("sOffset").as_double(); double a = lane_width_node.attribute("a").as_double(); double b = lane_width_node.attribute("b").as_double(); double c = lane_width_node.attribute("c").as_double(); double d = lane_width_node.attribute("d").as_double(); lane->lane_width.s0_to_poly[s0 + sOffs] = Poly3(s0 + sOffs, a, b, c, d); } if (with_laneHeight) { for (pugi::xml_node lane_height_node : lane_node.node().children("height")) { double s_offset = lane_height_node.attribute("sOffset").as_double(); double inner = lane_height_node.attribute("inner").as_double(); double outer = lane_height_node.attribute("outer").as_double(); lane->s_to_height_offset[s0 + s_offset] = HeightOffset{inner, outer}; } } for (pugi::xml_node roadmark_node : lane_node.node().children("roadMark")) { double sOffsetRoadMark = roadmark_node.attribute("sOffset").as_double(0); double width = roadmark_node.attribute("width").as_double(-1); double height = roadmark_node.attribute("height").as_double(0); std::string type = roadmark_node.attribute("type").as_string("none"); std::string weight = roadmark_node.attribute("weight").as_string("standard"); std::string color = roadmark_node.attribute("color").as_string("standard"); std::string material = roadmark_node.attribute("material").as_string("standard"); std::string laneChange = roadmark_node.attribute("laneChange").as_string("both"); RoadMarkGroup roadmark_group{width, height, sOffsetRoadMark, type, weight, color, material, laneChange}; if (pugi::xml_node roadmark_type_node = roadmark_node.child("type")) { std::string name = roadmark_type_node.attribute("name").as_string(""); double line_width_1 = roadmark_type_node.attribute("width").as_double(-1); for (pugi::xml_node roadmarks_line_node : roadmark_type_node.children("line")) { double length = roadmarks_line_node.attribute("length").as_double(0); double space = roadmarks_line_node.attribute("space").as_double(0); double tOffset = roadmarks_line_node.attribute("tOffset").as_double(0); double sOffsetRoadMarksLine = roadmarks_line_node.attribute("sOffset").as_double(0); double line_width_0 = roadmarks_line_node.attribute("width").as_double(-1); double line_width = line_width_0 < 0 ? line_width_1 : line_width_0; std::string rule = roadmarks_line_node.attribute("rule").as_string("none"); RoadMarksLine roadmarks_line{line_width, length, space, tOffset, sOffsetRoadMarksLine, name, rule}; roadmark_group.s_to_roadmarks_line[s0 + sOffsetRoadMark + sOffsetRoadMarksLine] = roadmarks_line; } } lane->s_to_roadmark_group[s0 + sOffsetRoadMark] = roadmark_group; } if (pugi::xml_node node = lane_node.node().child("link").child("predecessor")) lane->predecessor = node.attribute("id").as_int(); if (pugi::xml_node node = lane_node.node().child("link").child("successor")) lane->successor = node.attribute("id").as_int(); } /* derive lane borders from lane widths */ auto id_lane_iter0 = lane_section->id_to_lane.find(0); if (id_lane_iter0 == lane_section->id_to_lane.end()) throw std::runtime_error("lane section does not have lane #0"); /* iterate from id #0 towards +inf */ auto id_lane_iter1 = std::next(id_lane_iter0); for (auto iter = id_lane_iter1; iter != lane_section->id_to_lane.end(); iter++) { if (iter == id_lane_iter0) { iter->second->outer_border = iter->second->lane_width; } else { iter->second->inner_border = std::prev(iter)->second->outer_border; iter->second->outer_border = std::prev(iter)->second->outer_border.add(iter->second->lane_width); } } /* iterate from id #0 towards -inf */ std::map<int, std::shared_ptr<Lane>>::const_reverse_iterator r_id_lane_iter_1(id_lane_iter0); for (auto r_iter = r_id_lane_iter_1; r_iter != lane_section->id_to_lane.rend(); r_iter++) { if (r_iter == r_id_lane_iter_1) { r_iter->second->outer_border = r_iter->second->lane_width.negate(); } else { r_iter->second->inner_border = std::prev(r_iter)->second->outer_border; r_iter->second->outer_border = std::prev(r_iter)->second->outer_border.add(r_iter->second->lane_width.negate()); } } for (auto& id_lane : lane_section->id_to_lane) { id_lane.second->inner_border = id_lane.second->inner_border.add(road->lane_offset); id_lane.second->outer_border = id_lane.second->outer_border.add(road->lane_offset); } } } } ConstRoadSet OpenDriveMap::get_roads() const { ConstRoadSet roads; for (const auto& id_road : this->roads) roads.insert(id_road.second); return roads; } RoadSet OpenDriveMap::get_roads() { RoadSet roads; for (const auto& id_road : this->roads) roads.insert(id_road.second); return roads; } Mesh3D OpenDriveMap::get_refline_lines(double eps) const { /* indices are pairs of vertices representing line segments */ Mesh3D reflines; for (std::shared_ptr<const Road> road : this->get_roads()) { const size_t idx_offset = reflines.vertices.size(); const Line3D refl_pts = road->ref_line->get_line(0.0, road->length, eps); reflines.vertices.insert(reflines.vertices.end(), refl_pts.begin(), refl_pts.end()); for (size_t idx = idx_offset; idx < (idx_offset + refl_pts.size() - 1); idx++) { reflines.indices.push_back(idx); reflines.indices.push_back(idx + 1); } } return reflines; } RoadNetworkMesh OpenDriveMap::get_mesh(double eps) const { RoadNetworkMesh out_mesh; LaneMeshUnion& lanes_union = out_mesh.lane_mesh_union; RoadmarkMeshUnion& roadmarks_union = out_mesh.roadmark_mesh_union; for (std::shared_ptr<const Road> road : this->get_roads()) { lanes_union.road_start_indices[lanes_union.vertices.size()] = road->id; roadmarks_union.road_start_indices[roadmarks_union.vertices.size()] = road->id; for (std::shared_ptr<const LaneSection> lanesec : road->get_lanesections()) { lanes_union.lanesec_start_indices[lanes_union.vertices.size()] = lanesec->s0; roadmarks_union.lanesec_start_indices[roadmarks_union.vertices.size()] = lanesec->s0; for (std::shared_ptr<const Lane> lane : lanesec->get_lanes()) { size_t idx_offset = lanes_union.vertices.size(); lanes_union.lane_start_indices[idx_offset] = lane->id; Mesh3D lane_mesh = lane->get_mesh(lanesec->s0, lanesec->get_end(), eps); lanes_union.st_coordinates.insert(lanes_union.st_coordinates.end(), lane_mesh.st_coordinates.begin(), lane_mesh.st_coordinates.end()); lanes_union.vertices.insert(lanes_union.vertices.end(), lane_mesh.vertices.begin(), lane_mesh.vertices.end()); for (const size_t& idx : lane_mesh.indices) lanes_union.indices.push_back(idx + idx_offset); idx_offset = roadmarks_union.vertices.size(); roadmarks_union.lane_start_indices[idx_offset] = lane->id; const std::vector<RoadMark> roadmarks = lane->get_roadmarks(lanesec->s0, lanesec->get_end()); for (const RoadMark& roadmark : roadmarks) { idx_offset = roadmarks_union.vertices.size(); const Mesh3D roadmark_mesh = lane->get_roadmark_mesh(roadmark, eps); roadmarks_union.vertices.insert(roadmarks_union.vertices.end(), roadmark_mesh.vertices.begin(), roadmark_mesh.vertices.end()); for (const size_t& idx : roadmark_mesh.indices) roadmarks_union.indices.push_back(idx + idx_offset); roadmarks_union.roadmark_type_start_indices[idx_offset] = roadmark.type; } } } } return out_mesh; } } // namespace odr
48.743276
150
0.575492
chacha95
cc3009926544a974144c920dcdc5e96803c64a14
4,590
cc
C++
graphics/sphere.cc
Tibonium/genecis
4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc
[ "BSD-2-Clause" ]
null
null
null
graphics/sphere.cc
Tibonium/genecis
4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc
[ "BSD-2-Clause" ]
null
null
null
graphics/sphere.cc
Tibonium/genecis
4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc
[ "BSD-2-Clause" ]
null
null
null
#include <genecis/graphics/sphere.h> #include <ctime> #include <cstring> using namespace genecis::graphics ; /** * Constructor */ Sphere::Sphere(integral_type radius, size_type rings, size_type sectors) : _vertices(rings * sectors * 3, 0), _normals(rings * sectors * 3, 0), _texcoords(rings * sectors * 2, 0), _colors(rings * sectors * 3, 0), _position(3, 0), _velocity(3, 0), _acceleration(3,0), _indices(rings * sectors * 4, 0), _red(0), _green(0), _blue(0), _id(0) { integral_type const R = 1./(integral_type)(rings-1) ; integral_type const S = 1./(integral_type)(sectors-1) ; container_type::iterator v = _vertices.begin() ; container_type::iterator n = _normals.begin() ; container_type::iterator t = _texcoords.begin() ; for(size_type r=0; r<rings; ++r) { for(size_type s=0; s<sectors; ++s) { integral_type const y = std::sin(-M_PI_2 + M_PI * r * R) ; integral_type const x = std::cos(2*M_PI * s * S) * std::sin(M_PI * r * R) ; integral_type const z = std::sin(2*M_PI * s * S) * std::sin(M_PI * r * R) ; *t++ = s * S ; *t++ = r * R ; *v++ = x * radius ; *v++ = y * radius ; *v++ = z * radius ; *n++ = x ; *n++ = y ; *n++ = z ; } } container::array<GLushort>::iterator i = _indices.begin() ; for(size_type r=0; r<(rings - 1); ++r) { for(size_type s=0; s<(sectors - 1); ++s) { *i++ = r * sectors + s ; *i++ = r * sectors + (s + 1) ; *i++ = (r + 1) * sectors + (s + 1) ; *i++ = (r + 1) * sectors + s ; } } _rotation = new GLfloat[rings * sectors * 3] ; std::fill_n( _rotation, rings*sectors*3, 0) ; } /** * Destructor */ Sphere::~Sphere() { if( _rotation ) { delete _rotation ; _rotation = NULL ; } } void Sphere::draw(container::array<double> center, double dt) { draw(center(0), center(1), center(2), dt) ; } /** * Draws the sphere centered at (x,y,z) */ void Sphere::draw(GLfloat x, GLfloat y, GLfloat z, double dt) { glMatrixMode( GL_MODELVIEW ) ; glPushMatrix() ; glRotatef( _velocity(1)*dt, 0.0, 1.0, 0.0 ) ; glRotatef( _velocity(2)*dt, 0.0, 0.0, 1.0 ) ; glMultMatrixf( _rotation ) ; glGetFloatv( GL_MODELVIEW_MATRIX, _rotation ) ; glTranslatef( x, y, z ) ; glEnableClientState( GL_VERTEX_ARRAY ) ; glEnableClientState( GL_NORMAL_ARRAY ) ; glEnableClientState( GL_TEXTURE_COORD_ARRAY ) ; glEnableClientState( GL_COLOR_ARRAY ) ; glVertexPointer( 3, GL_FLOAT, 0, _vertices.begin() ) ; glNormalPointer( GL_FLOAT, 0, _normals.begin() ) ; glTexCoordPointer( 2, GL_FLOAT, 0, _texcoords.begin() ) ; glColorPointer( 3, GL_FLOAT, 0, _colors.begin() ) ; glDrawElements( GL_QUADS, _indices.size(), GL_UNSIGNED_SHORT, _indices.begin() ) ; glPopMatrix() ; // glGenBuffers( 1, &_id ) ; // glBindBuffer( GL_ARRAY_BUFFER, _id ) ; // glBufferData( GL_ARRAY_BUFFER, sizeof(GL_FLOAT)*_vertices.size(), _vertices.begin(), GL_DYNAMIC_DRAW ) ; // glEnableVertexAttribArray( 0 ) ; // glVertexAttribPointer( _id, 4, GL_FLOAT, GL_FALSE, 0, 0 ) ; // // glGenBuffers( 1, &_id ) ; // glBindBuffer( GL_ARRAY_BUFFER, _id ) ; // glBufferData( GL_ARRAY_BUFFER, sizeof(GL_FLOAT)*_indices.size(), _indices.begin(), GL_DYNAMIC_DRAW ) ; // glEnableVertexAttribArray( 0 ) ; // glVertexAttribPointer( _id, 4, GL_FLOAT, GL_FALSE, 0, 0 ) ; // glBufferData( GL_ARRAY_BUFFER, sizeof(_vertices) + sizeof(_indices), 0, GL_STATIC_DRAW ) ; // glBufferSubData( GL_ARRAY_BUFFER, 0, _vertices.size(), _vertices.begin() ) ; // glBufferSubData( GL_ARRAY_BUFFER, _vertices.size(), _indices.size(), _indices.begin() ) ; // glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, _indices.begin() ) ; // glBufferSubData( GL_ELEMENT_ARRAY_BUFFER, 0, _indices.size(), _indicies.begin() ) ; // glDrawArrays( GL_QUADS, 0, _vertices.size() ) ; // glDisableVertexAttribArray( _id ) ; // glDrawElements( GL_QUADS, _indices.size(), GL_UNSIGNED_SHORT, _indices.begin() ) ; } /** * Sets the color of the sphere */ void Sphere::color(GLfloat r, GLfloat g, GLfloat b) { std::srand(0) ; //_red = r ; //_green = g ; //_blue = b ; int N = _colors.size() ; double res = 1.0 / N ; for(int i=0; i<N; i+=3) { _colors[i] = std::fmod((r + i*res), 1.0) ; _colors[i+1] = std::fmod((g + i*res), 1.0) ; _colors[i+2] = std::fmod((b + i*res), 1.0) ; } }
32.323944
110
0.586928
Tibonium
cc311d45d444f0d9532b9acba940f32b958936d2
94
cpp
C++
src/Graphics/UI/Font.cpp
noche-x/Stardust-Engine
1b6f295650c7b6b7faced0577b04557d5dc23d9b
[ "MIT" ]
null
null
null
src/Graphics/UI/Font.cpp
noche-x/Stardust-Engine
1b6f295650c7b6b7faced0577b04557d5dc23d9b
[ "MIT" ]
null
null
null
src/Graphics/UI/Font.cpp
noche-x/Stardust-Engine
1b6f295650c7b6b7faced0577b04557d5dc23d9b
[ "MIT" ]
null
null
null
#include <Graphics/UI/Font.h> namespace Stardust::Graphics::UI { intraFont* g_DefaultFont; }
18.8
34
0.755319
noche-x
cc3cdda7f2949416f9ab8a752fd735675b92beab
1,763
cpp
C++
SPOJ/SPOJ - BITMAP/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
SPOJ/SPOJ - BITMAP/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
SPOJ/SPOJ - BITMAP/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: 2018-03-15 23:37:16 * solution_verdict: Accepted language: C++ * run_time (ms): 640 memory_used (MB): 15.4 * problem: https://vjudge.net/problem/SPOJ-BITMAP ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int inf=1e9; int t,n,m,mat[202][202],dis[202][202]; string s; vector<pair<int,int> >v; int dx[]={0,0,1,-1}; int dy[]={1,-1,0,0}; void bfs(int r,int c) { queue<pair<int,int> >q; pair<int,int>x; dis[r][c]=0; q.push({r,c}); while(q.size()) { x=q.front(); q.pop(); int rw=x.first; int cl=x.second; for(int i=0;i<4;i++) { int xx=rw+dx[i]; int yy=cl+dy[i]; if(xx<1||xx>n||yy<1||yy>m)continue; if(dis[rw][cl]+1<dis[xx][yy]) { q.push({xx,yy}); dis[xx][yy]=dis[rw][cl]+1; } } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>t; while(t--) { cin>>n>>m; v.clear(); for(int i=1;i<=n;i++) { cin>>s; for(int j=1;j<=m;j++) { mat[i][j]=s[j-1]; if(mat[i][j]=='1')v.push_back({i,j}); } } for(int i=0;i<=200;i++) { for(int j=0;j<=200;j++)dis[i][j]=inf; } for(auto x:v)bfs(x.first,x.second); for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { cout<<dis[i][j]<<" "; } cout<<endl; } } return 0; }
23.197368
111
0.384005
kzvd4729
cc4321d1811a4f615623f91d4739193c6797c760
118
hpp
C++
test/TestHeaders.hpp
coderkd10/EternalTerminal
d15bb726d987bd147480125d694de44a2ea6ce83
[ "Apache-2.0" ]
1,783
2018-02-28T16:28:42.000Z
2022-03-31T18:45:01.000Z
test/TestHeaders.hpp
coderkd10/EternalTerminal
d15bb726d987bd147480125d694de44a2ea6ce83
[ "Apache-2.0" ]
337
2018-02-27T06:38:39.000Z
2022-03-22T02:50:58.000Z
test/TestHeaders.hpp
coderkd10/EternalTerminal
d15bb726d987bd147480125d694de44a2ea6ce83
[ "Apache-2.0" ]
135
2018-04-30T14:48:36.000Z
2022-03-21T16:51:09.000Z
#ifndef __TEST_HEADERS_HPP__ #define __TEST_HEADERS_HPP__ #include "Headers.hpp" #include "catch2/catch.hpp" #endif
14.75
28
0.805085
coderkd10
cc546e5155e60885bab5412fe212be512930dd84
428
cpp
C++
COS1511/Part2/Lesson11/a.cpp
GalliWare/UNISA-studies
32bab94930b176c4dfe943439781ef102896fab5
[ "Unlicense" ]
null
null
null
COS1511/Part2/Lesson11/a.cpp
GalliWare/UNISA-studies
32bab94930b176c4dfe943439781ef102896fab5
[ "Unlicense" ]
null
null
null
COS1511/Part2/Lesson11/a.cpp
GalliWare/UNISA-studies
32bab94930b176c4dfe943439781ef102896fab5
[ "Unlicense" ]
null
null
null
#include <iostream> using namespace std; int main() { // set constants const int LOWEST_NUMBER = 10, LARGEST_NUMBER = 20; // set variables int number; bool loop = true; // as we set loop we can start the loop while (loop) { cout << "Please provide number between 10 and 20: "; cin >> number; if (number > LOWEST_NUMBER && number < LARGEST_NUMBER) { loop = false; } } return 0; }
17.12
58
0.614486
GalliWare
cc57d9e33d0a16a25da90bdd209d1bfb0b63bb8e
1,843
cpp
C++
PAT-A/PATA1114_2.cpp
GRAYCN/Algorithm-notebook
04fa7b759a797fb47e11bcdd1f8cc7bef297578c
[ "Apache-2.0" ]
1
2019-07-06T10:40:28.000Z
2019-07-06T10:40:28.000Z
PAT-A/PATA1114_2.cpp
GRAYCN/Algorithm-notebook
04fa7b759a797fb47e11bcdd1f8cc7bef297578c
[ "Apache-2.0" ]
null
null
null
PAT-A/PATA1114_2.cpp
GRAYCN/Algorithm-notebook
04fa7b759a797fb47e11bcdd1f8cc7bef297578c
[ "Apache-2.0" ]
null
null
null
//PATA1114_2 //UFS #include<iostream> #include<cstdio> #include<algorithm> using namespace std; #define maxn 1005 #define maxm 10005 struct People{ int id,fid,mid,num,area; int cid[8]; }peo[maxn]; struct Answer{ int id; double num,area; int people; bool flag; }ans[maxm]; bool visit[maxm]; int father[maxm]; int find(int x){ int a=x; while(x!=father[x]){ x=father[x]; } while(a!=father[a]){ int z=a; a=father[a]; father[z]=x; } return x; } bool cmp(Answer a,Answer b){ if(a.area!=b.area) return a.area>b.area; else return a.id<b.id; } void Union(int a,int b){ int fa=find(a); int fb=find(b); if(fa>fb){ //fb=father[fa]; father[fa]=fb; }else if(fa<fb){ //fa=father[fb]; father[fb]=fa; } } int main(){ int N,k; for(int i=0;i<maxm;i++) father[i]=i; cin>>N; for(int i=0;i<N;i++){ cin>>peo[i].id>>peo[i].fid>>peo[i].mid>>k; visit[peo[i].id]=true; if(peo[i].fid!=-1){ visit[peo[i].fid]=true; Union(peo[i].id,peo[i].fid); } if(peo[i].mid!=-1){ visit[peo[i].mid]=true; Union(peo[i].id,peo[i].mid); } for(int j=0;j<k;j++){ cin>>peo[i].cid[j]; visit[peo[i].cid[j]]=true; Union(peo[i].id,peo[i].cid[j]); } cin>>peo[i].num>>peo[i].area; } for(int i=0;i<N;i++){ if(visit[peo[i].id]){ int id=find(peo[i].id); ans[id].id=id; // ans[id].people++; ans[id].num+=peo[i].num; ans[id].area+=peo[i].area; ans[id].flag=true; } } for(int i=0;i<maxm;i++){ if(visit[i]){ int id=find(i); ans[id].people++; } } int cnt=0; for(int i=0;i<maxm;i++){ if(ans[i].flag==true){ cnt++; ans[i].num=(float)(ans[i].num/ans[i].people); ans[i].area=(float)(ans[i].area/ans[i].people); } } sort(ans,ans+maxm,cmp); cout<<cnt<<endl; for(int i=0;i<cnt;i++){ printf("%04d %d %.3f %.3f\n",ans[i].id,ans[i].people,ans[i].num,ans[i].area); } }
16.908257
79
0.568095
GRAYCN
cc5c176217bad9eea703faeea08e8da56812d72c
13,573
cpp
C++
windows/c++/visualstudio/src/WorkerManager.cpp
afskylia/bachelor-starcraft-bot
e9d53345d77f6243f5a2db1781cdfcb7838ebcfd
[ "MIT" ]
null
null
null
windows/c++/visualstudio/src/WorkerManager.cpp
afskylia/bachelor-starcraft-bot
e9d53345d77f6243f5a2db1781cdfcb7838ebcfd
[ "MIT" ]
2
2021-06-27T18:57:39.000Z
2021-06-27T18:57:52.000Z
windows/c++/visualstudio/src/WorkerManager.cpp
afskylia/bachelor-starcraft-bot
e9d53345d77f6243f5a2db1781cdfcb7838ebcfd
[ "MIT" ]
null
null
null
#include "WorkerManager.h" #include <BWAPI/Client/Client.h> #include "Global.h" #include "BWEM/src/bwem.h" #include "Tools.h" using namespace MiraBot; WorkerManager::WorkerManager() { } void WorkerManager::onFrame() { // Update workers, e.g. set job as 'Idle' when job completed updateWorkerStatus(); // Send idle workers to gather resources activateIdleWorkers(); // Send out a new scout if needed if (BWAPI::Broodwar->getFrameCount() % 7919 == 0 && should_have_new_scout) { auto* new_scout = getAnyWorker(); m_workerData.setWorkerJob(new_scout, WorkerData::Scout, scout_last_known_position); should_have_new_scout = false; } if (lateScout) { // Hotfix while (Global::combat().m_attack_units.size() > 30 && m_workerData.getWorkers(WorkerData::Repair).size() < 6) { if (m_workerData.getWorkers(WorkerData::Minerals).size() <= 40) break; std::cout << "Making late game scout\n"; m_workerData.setLateGameScout(getAnyWorker()); } } } void WorkerManager::updateWorkerStatus() { for (const auto& worker : m_workerData.getWorkers()) { const auto job = m_workerData.getWorkerJob(worker); if (!worker->isCompleted()) continue; // Workers can be idle for various reasons, e.g. a builder waiting to build if (worker->isIdle() || job == WorkerData::Scout && worker->isStuck() ) { switch (job) { case WorkerData::Build: { /* Builder is idle when it has reached the build location and is waiting to build, * or it has gotten stuck along the way*/ handleIdleBuildWorker(worker); break; } case WorkerData::Scout: { // Scout is idle when it has reached its current scouting target handleIdleScout(worker); break; } case WorkerData::Repair: { auto random_pos = Global::map().map.RandomPosition(); auto pos = BWAPI::Position(Global::production().m_building_placer_.getBuildLocationNear( BWAPI::TilePosition(random_pos), BWAPI::UnitTypes::Protoss_Nexus)); worker->move(pos); break; } case WorkerData::Move: { // Mover is idle when it has reached its destination break; } default: { if (!getWorkerScout() && getScoutPosition(worker)) setScout(worker); else m_workerData.setWorkerJob(worker, WorkerData::Idle, nullptr); } } } } } void WorkerManager::setScout(BWAPI::Unit unit) { m_workerData.setWorkerJob(unit, WorkerData::Scout, getScoutPosition(unit)); } // Assign jobs to idle workers // TODO: 2 workers per mineral patch is optimal // TODO: Look at total minerals and gas - e.g. maybe we have plenty of gas but no minerals void WorkerManager::activateIdleWorkers() { const auto mineral_worker_count = m_workerData.getWorkers(WorkerData::Minerals).size(); const auto gas_worker_count = m_workerData.getWorkers(WorkerData::Gas).size(); for (auto& worker : m_workerData.getWorkers()) { if (m_workerData.getWorkerJob(worker) == WorkerData::Idle) { const auto refinery_type = BWAPI::Broodwar->self()->getRace().getRefinery(); const auto refinery_count = Tools::countUnitsOfType(refinery_type); // We don't want more than 3 gas workers per refinery if (refinery_count > 0 && gas_worker_count < mineral_worker_count / 4 && gas_worker_count < Tools::countUnitsOfType(refinery_type) * 4) setGasWorker(worker); else setMineralWorker(worker); } } } void WorkerManager::setMineralWorker(BWAPI::Unit unit) { BWAPI::Unit closestDepot = getClosestDepot(unit); if (closestDepot) { m_workerData.setWorkerJob(unit, WorkerData::Minerals, closestDepot); } } void WorkerManager::setGasWorker(BWAPI::Unit unit) { BWAPI::Unit closestDepot = getClosestDepot(unit); if (closestDepot) { m_workerData.setWorkerJob(unit, WorkerData::Gas, closestDepot); } } void WorkerManager::setBuildingWorker(BWAPI::Unit unit, WorkerData::BuildJob buildJob) { m_workerData.setWorkerJob(unit, WorkerData::Build, buildJob); } void WorkerManager::onUnitComplete(BWAPI::Unit unit) { if (!unit->getType().isWorker()) return; updateWorkerCounts(); m_workerData.addWorker(unit, WorkerData::Idle, nullptr); } void WorkerManager::onUnitDestroy(BWAPI::Unit unit) { m_workerData.workerDestroyed(unit); } void WorkerManager::updateWorkerCounts() { auto num_patches = 0; auto num_geysers = 0; for (const auto* base : Global::map().expos) { num_patches += base->Minerals().size(); num_geysers += base->Geysers().size(); } //max_workers = num_patches * 3 + m_workerData.getWorkers(WorkerData::Scout).size() + 5; max_workers = 65; } void WorkerManager::sendScouts(int num) { } BWAPI::Unit WorkerManager::getClosestDepot(BWAPI::Unit worker) { BWAPI::Unit closestDepot = nullptr; double closestDistance = 0; for (auto& unit : BWAPI::Broodwar->self()->getUnits()) { if (unit->getType().isResourceDepot() && unit->isCompleted()) { const double distance = unit->getDistance(worker); if (!closestDepot || distance < closestDistance) { closestDepot = unit; closestDistance = distance; } } } return closestDepot; } // Returns next scouting location for scout, favoring closest locations BWAPI::Position WorkerManager::getScoutPosition(BWAPI::Unit scout) { // if we found enemy, we don't have more positions //if (Global::information().enemy_start_location) return BWAPI::Positions::None; auto& startLocations = BWAPI::Broodwar->getStartLocations(); BWAPI::Position closestPosition = BWAPI::Positions::None; double closestDistance = 0; for (BWAPI::TilePosition position : startLocations) { auto pos = BWAPI::Position(position); if (!BWAPI::Broodwar->isExplored(position) || (Global::map().lastSeen(position) > 5000 && !BWAPI::Broodwar-> isVisible(position))) { const BWAPI::Position pos(position); const double distance = scout->getDistance(pos); if (!closestPosition || distance < closestDistance) { closestPosition = pos; closestDistance = distance; } } } return closestPosition; } // Returns the scout BWAPI::Unit WorkerManager::getWorkerScout() { for (auto& worker : m_workerData.getWorkers()) { if (!worker) continue; if (m_workerData.getWorkerJob(worker) == WorkerData::Scout) { return worker; } } return nullptr; } // Looks through mineral workers and returns the closest candidate to given position BWAPI::Unit WorkerManager::getBuilder(BWAPI::UnitType type, BWAPI::Position pos) { BWAPI::Unit closestUnit = nullptr; auto unitSet = m_workerData.getWorkers(WorkerData::Minerals); for (auto& unit : unitSet) { // If worker isn't of required type or hasn't been trained yet, continue if (!(unit->getType() == type && unit->isCompleted())) continue; // Set initially closest worker if (!closestUnit) { closestUnit = unit; continue; } // If position doesn't matter, use the first found candidate if (pos == BWAPI::Positions::None) break; // Check if this unit is closer to the position than closestUnit if (closestUnit->getDistance(pos) > unit->getDistance(pos)) { closestUnit = unit; } } // Return the closest worker, or nullptr if none was found return closestUnit; } // Returns a worker: used when you just need a worker asap BWAPI::Unit WorkerManager::getAnyWorker(BWAPI::Position pos) { // Prioritized job order: Prefers Idle, Default, Minerals, ..., Combat, Repair for (auto& job : m_workerData.prioritized_jobs) { const auto workers = m_workerData.getWorkers(job); if (workers.empty()) continue; // If position doesn't matter, use first found candidate if (pos == BWAPI::Positions::None) { for (auto& unit : workers) return unit; } // Return closest candidate auto sorted_workers = Tools::sortUnitsByClosest(pos, workers); return sorted_workers[0]; } return nullptr; } // Handles a build-worker who is idling void WorkerManager::handleIdleBuildWorker(BWAPI::Unit worker) { // Get build job assigned to worker const auto building_type = m_workerData.m_workerBuildingTypeMap[worker]; auto building_pos = m_workerData.m_buildPosMap[worker]; auto initiatedBuilding = m_workerData.m_initiatedBuildingMap[worker]; if (building_type == BWAPI::UnitTypes::Protoss_Nexus) { int i = 0; } // If worker idling because build job is completed, set job to idle if (initiatedBuilding && !worker->isConstructing()) { if (Tools::getUnitsOfType(building_type, false, false).empty()) { } else { m_workerData.setWorkerJob(worker, WorkerData::Idle, nullptr); return; } } if (building_type == BWAPI::UnitTypes::None || worker->isConstructing()) { } // Otherwise, worker is idling because it is waiting for the required resources if (building_type.mineralPrice() > 0 && building_type.mineralPrice() + 10 > BWAPI::Broodwar->self()->minerals()) return; if (building_type.gasPrice() > 0 && building_type.gasPrice() + 10 > BWAPI::Broodwar->self()->gas()) return; // Check build position validity auto canbuild = BWAPI::Broodwar->canBuildHere(building_pos, building_type, worker); if (!canbuild) { if (building_pos != BWAPI::TilePositions::None) { building_pos = Global::production().m_building_placer_.getBuildLocationNear(building_pos, building_type); canbuild = BWAPI::Broodwar->canBuildHere(building_pos, building_type, worker); if (canbuild) { goto sup; } } // First attempt: Build position based on builder position building_pos = Global::production().m_building_placer_.getBuildLocationNear( worker->getTilePosition(), building_type); canbuild = BWAPI::Broodwar->canBuildHere(building_pos, building_type, worker); if (canbuild) { goto sup; } // Second attempt: Build position using built-in StarCraft building placer building_pos = BWAPI::Broodwar->getBuildLocation(building_type, worker->getTilePosition(), 400); canbuild = BWAPI::Broodwar->canBuildHere(building_pos, building_type, worker); if (canbuild) { goto sup; } // Final attempt: Get any damn build position building_pos = Global::production().m_building_placer_.getBuildLocation(building_type); canbuild = BWAPI::Broodwar->canBuildHere(building_pos, building_type, worker); if (canbuild) { goto sup; } m_workerData.setWorkerJob(worker, WorkerData::Idle, nullptr); return; } sup: // Try to place the building and generate new position if the first one fails bool built = worker->build(building_type, building_pos); if (!built) { std::cout << "Failed to build " << building_type.getName() << "\n"; m_workerData.setWorkerJob(worker, WorkerData::Idle, nullptr); return; } // Used in the beginning of the function next frame //m_workerData.m_workerBuildingTypeMap[worker] = BWAPI::UnitTypes::None; m_workerData.m_initiatedBuildingMap[worker] = true; //BWAPI::Broodwar->printf("Building %s", building_type.getName().c_str()); } // Send worker to unexplored scout position void WorkerManager::handleIdleScout(BWAPI::Unit worker) { const auto scout_position = getScoutPosition(worker); if (!scout_position) { auto enemy_area = Global::map().map.GetNearestArea(Global::information().enemy_start_location); auto top_right = BWAPI::Position(BWAPI::TilePosition(enemy_area->BottomRight().x, enemy_area->TopLeft().y)); auto bottom_left = BWAPI::Position(BWAPI::TilePosition(enemy_area->TopLeft().x, enemy_area->BottomRight().y)); auto top_left = BWAPI::Position(enemy_area->TopLeft()); auto bottom_right = BWAPI::Position(enemy_area->BottomRight()); auto go_to_pos = top_left; // All starting positions have been explored // If worker is away from enemy base keep going in and out if (top_left.getApproxDistance(worker->getPosition()) <= 400) { go_to_pos = top_right; } else if (top_right.getApproxDistance(worker->getPosition()) <= 400) { go_to_pos = bottom_right; } else if (bottom_right.getApproxDistance(worker->getPosition()) <= 400) { go_to_pos = bottom_left; } else if (bottom_left.getApproxDistance(worker->getPosition()) <= 400) { go_to_pos = top_left; } m_workerData.setWorkerJob(worker, WorkerData::Scout, BWAPI::Position(BWAPI::WalkPosition(go_to_pos))); } else { // Set scout's new target position m_workerData.setWorkerJob(worker, WorkerData::Scout, scout_position); } } // Returns a vector of all active (=unfinished) build jobs std::vector<WorkerData::BuildJob> WorkerManager::getActiveBuildJobs() { std::vector<WorkerData::BuildJob> build_jobs; auto builders = m_workerData.getWorkers(WorkerData::Build); for (const auto& unit : builders) { auto unit_building_type = m_workerData.m_workerBuildingTypeMap[unit]; if (unit_building_type == BWAPI::UnitTypes::None) continue; // TODO: safer way to check map, this can cause exceptions - use find instead auto build_job = WorkerData::BuildJob{m_workerData.m_buildPosMap[unit], unit_building_type}; build_jobs.push_back(build_job); } return build_jobs; } // Returns a vector of active (=unfinished) build jobs of given unit type std::vector<WorkerData::BuildJob> WorkerManager::getActiveBuildJobs(BWAPI::UnitType unit_type) { std::vector<WorkerData::BuildJob> build_jobs; auto builders = m_workerData.getWorkers(WorkerData::Build); for (const auto& unit : builders) { // If unit has build job for this unit type, add to vector const auto it = m_workerData.m_workerBuildingTypeMap.find(unit); if (it != m_workerData.m_workerBuildingTypeMap.end() && it->second == unit_type) { auto build_job = WorkerData::BuildJob{m_workerData.m_buildPosMap[unit], unit_type}; build_jobs.push_back(build_job); } } return build_jobs; }
29.002137
113
0.719959
afskylia
cc5cc401a2e71fc0ab458087c6a939940671fadf
812
cc
C++
src/Vec3.cc
alexander-koch/airfoil
4c7afa81d6166b463de6afde5c2d491226fffa52
[ "MIT" ]
null
null
null
src/Vec3.cc
alexander-koch/airfoil
4c7afa81d6166b463de6afde5c2d491226fffa52
[ "MIT" ]
null
null
null
src/Vec3.cc
alexander-koch/airfoil
4c7afa81d6166b463de6afde5c2d491226fffa52
[ "MIT" ]
null
null
null
#include "Vec3.hpp" Vec3 Vec3::operator+(Vec3 v2) { return Vec3(x + v2.x, y + v2.y, z + v2.z); } void Vec3::operator+=(Vec3 v2) { x += v2.x; y += v2.y; z += v2.z; } Vec3 Vec3::operator*(double f) { return Vec3(x * f, y * f, z * f); } Vec3 Vec3::operator-(Vec3 v2) { return Vec3(x - v2.x, y - v2.y, z - v2.z); } Vec3 Vec3::cross(Vec3 v2) { return Vec3( y * v2.z - v2.y * z, z * v2.x - v2.z * x, x * v2.y - v2.x * y); } double Vec3::dot(Vec3 v2) { return x * v2.x + y * v2.y + z * v2.z; } double Vec3::length() { return sqrt(dot(*this)); } Vec3 Vec3::normalize() { double len = length(); return Vec3(x / len, y / len, z / len); } Vec3 Vec3::zero() { return Vec3(0.0, 0.0, 0.0); } Vec3 Vec3::up() { return Vec3(0.0, 0.0, 1.0); }
16.916667
46
0.5
alexander-koch
7fe7ce4dda7d7f0e2b562fe539c2e264ad229ee8
905
cpp
C++
main.cpp
birdiFVZ/neuralNetwork
4e1eeb5a2641feff9a6b71c83cb7c09de499c50d
[ "MIT" ]
null
null
null
main.cpp
birdiFVZ/neuralNetwork
4e1eeb5a2641feff9a6b71c83cb7c09de499c50d
[ "MIT" ]
null
null
null
main.cpp
birdiFVZ/neuralNetwork
4e1eeb5a2641feff9a6b71c83cb7c09de499c50d
[ "MIT" ]
null
null
null
#include <iostream> #include "src/MyMatrix.h" #include "src/MyNetwork.h" #include "src/functions.h" #include "src/MyFile.h" #include "src/MyBodyData.h" using namespace std; int main() { string trainingPath = "/home/birdi/Schreibtisch/neuralNetwork07022018/data/training.csv"; MyFile trainingFile(trainingPath); //MyBodyData trainingData(training); /* MyMatrix weight(4,4); MyMatrix biasTraining(10,1); MyMatrix biasValidation(10,1); MyMatrix biasTest(10,1); biasTraining.fill(1); biasValidation.fill(1); biasTest.fill(1); weight.fillRandomize(0,0.5); MyNetwork network; network.set("weight", weight); network.set("biasTrainig", biasTraining); network.set("biasValidation", biasValidation); network.set("biasTest", biasTest); int whileCount = 0; while(whileCount < 500) { whileCount++; } */ return 0; }
20.568182
93
0.672928
birdiFVZ
7fe89aa59cb2b88b5b6003541db2e75b4dc9a7d5
729
cpp
C++
libKBEClient/KBEGameSocket.cpp
ypfsoul/kbengine-client-cocos2dx-3.11-MyGame
3729c4457feaf9540ad5f274b6fe42542b0d9608
[ "MIT" ]
3
2017-07-23T23:37:34.000Z
2017-09-22T06:28:34.000Z
libKBEClient/KBEGameSocket.cpp
ypfsoul/kbengine-client-cocos2dx-3.11-MyGame
3729c4457feaf9540ad5f274b6fe42542b0d9608
[ "MIT" ]
null
null
null
libKBEClient/KBEGameSocket.cpp
ypfsoul/kbengine-client-cocos2dx-3.11-MyGame
3729c4457feaf9540ad5f274b6fe42542b0d9608
[ "MIT" ]
null
null
null
#include "KBEGameSocket.h" KBEGameSocket::KBEGameSocket() { gameSocket = NULL; } KBEGameSocket::~KBEGameSocket() { releaseSocket(); } bool KBEGameSocket::connectionServer(const char* ipStr, uint32 port) { ip = ipStr; port = port; releaseSocket(); createSocket(); if(gameSocket->connect(ip.c_str(), port)) { return true; } return false; } void KBEGameSocket::releaseSocket() { if (gameSocket) { gameSocket->close(); gameSocket->release(); gameSocket = NULL; } } void KBEGameSocket::createSocket() { gameSocket = new GameNetClient(); gameSocket->autorelease(); gameSocket->retain(); } void KBEGameSocket::sendData( char* data ,int size) { if (gameSocket) { gameSocket->sendData(data,size); } }
14.877551
68
0.694102
ypfsoul
7fee15b624e398e4620c86ea0754e1f806ab1020
26,361
cpp
C++
Source/Tests/Replica/SceneSynchronization.cpp
jayrulez/rbfx
8641813787d558b6e8318c1b8e9da86c0e52f9dc
[ "MIT" ]
48
2016-11-14T00:39:35.000Z
2018-12-18T16:37:43.000Z
Source/Tests/Replica/SceneSynchronization.cpp
jayrulez/rbfx
8641813787d558b6e8318c1b8e9da86c0e52f9dc
[ "MIT" ]
54
2017-10-18T07:18:12.000Z
2018-12-23T14:09:30.000Z
Source/Tests/Replica/SceneSynchronization.cpp
jayrulez/rbfx
8641813787d558b6e8318c1b8e9da86c0e52f9dc
[ "MIT" ]
10
2017-11-10T11:46:15.000Z
2018-12-18T11:58:44.000Z
// // Copyright (c) 2017-2021 the rbfx project. // // 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 rhs // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR rhsWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR rhs DEALINGS IN // THE SOFTWARE. // #include "../CommonUtils.h" #include "../NetworkUtils.h" #include "../SceneUtils.h" #include <Urho3D/Graphics/Light.h> #include <Urho3D/Graphics/StaticModel.h> #include <Urho3D/Network/Network.h> #include <Urho3D/Network/NetworkEvents.h> #include <Urho3D/Physics/PhysicsEvents.h> #include <Urho3D/Physics/PhysicsWorld.h> #include <Urho3D/Scene/Scene.h> #include <Urho3D/Scene/SceneEvents.h> #include <Urho3D/Replica/BehaviorNetworkObject.h> #include <Urho3D/Replica/ReplicationManager.h> #include <Urho3D/Replica/NetworkObject.h> #include <Urho3D/Replica/NetworkValue.h> #include <Urho3D/Replica/ReplicatedTransform.h> #include <Urho3D/Resource/XMLFile.h> namespace { SharedPtr<XMLFile> CreateComplexTestPrefab(Context* context) { auto node = MakeShared<Node>(context); node->CreateComponent<ReplicatedTransform>(); auto staticModel = node->CreateComponent<StaticModel>(); staticModel->SetCastShadows(true); auto childNode = node->CreateChild("Child"); childNode->SetPosition({0.0f, 1.0f, 0.0f}); auto light = childNode->CreateComponent<Light>(); light->SetCastShadows(true); light->SetColor(Color::RED); return Tests::ConvertNodeToPrefab(node); } SharedPtr<XMLFile> CreateSimpleTestPrefab(Context* context) { auto node = MakeShared<Node>(context); node->CreateComponent<ReplicatedTransform>(); return Tests::ConvertNodeToPrefab(node); } } TEST_CASE("Scene is synchronized between client and server") { auto context = Tests::GetOrCreateContext(Tests::CreateCompleteContext); context->GetSubsystem<Network>()->SetUpdateFps(Tests::NetworkSimulator::FramesInSecond); const float syncDelay = 0.25f; auto prefab = Tests::GetOrCreateResource<XMLFile>(context, "@/SceneSynchronization/SimpleTestPrefab.xml", CreateSimpleTestPrefab); // Setup scenes const auto quality = Tests::ConnectionQuality{ 0.08f, 0.12f, 0.20f, 0.02f, 0.02f }; auto serverScene = MakeShared<Scene>(context); SharedPtr<Scene> clientScenes[] = { MakeShared<Scene>(context), MakeShared<Scene>(context), MakeShared<Scene>(context) }; // Reference transforms, should stay the same Matrix3x4 transformReplicatedNodeA; Matrix3x4 transformReplicatedNodeB; Matrix3x4 transformReplicatedNodeChild1; Matrix3x4 transformReplicatedNodeChild2; Matrix3x4 transformReplicatedNodeChild4; { for (Scene* clientScene : clientScenes) clientScene->CreateChild("Client Only Node", LOCAL); auto serverOnlyNode = serverScene->CreateChild("Server Only Node", LOCAL); auto replicatedNodeA = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Replicated Node A"); replicatedNodeA->SetScale(2.0f); transformReplicatedNodeA = replicatedNodeA->GetWorldTransform(); auto replicatedNodeB = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Replicated Node B"); replicatedNodeB->SetPosition({ -1.0f, 2.0f, 0.5f }); transformReplicatedNodeB = replicatedNodeB->GetWorldTransform(); auto replicatedNodeChild1 = Tests::SpawnOnServer<BehaviorNetworkObject>(replicatedNodeA, prefab, "Replicated Node Child 1"); replicatedNodeChild1->SetPosition({ -2.0f, 3.0f, 1.5f }); transformReplicatedNodeChild1 = replicatedNodeChild1->GetWorldTransform(); auto replicatedNodeChild2 = Tests::SpawnOnServer<BehaviorNetworkObject>(replicatedNodeChild1, prefab, "Replicated Node Child 2"); replicatedNodeChild2->SetRotation({ 90.0f, Vector3::UP }); transformReplicatedNodeChild2 = replicatedNodeChild2->GetWorldTransform(); auto serverOnlyChild3 = replicatedNodeB->CreateChild("Server Only Child 3", LOCAL); serverOnlyChild3->SetPosition({ -1.0f, 0.0f, 0.0f }); auto replicatedNodeChild4 = Tests::SpawnOnServer<BehaviorNetworkObject>(serverOnlyChild3, prefab, "Replicated Node Child 4"); transformReplicatedNodeChild4 = replicatedNodeChild4->GetWorldTransform(); } // Spend some time alone Tests::NetworkSimulator sim(serverScene); sim.SimulateTime(10.0f); // Add clients and wait for synchronization for (Scene* clientScene : clientScenes) sim.AddClient(clientScene, quality); sim.SimulateTime(10.0f); for (Scene* clientScene : clientScenes) { auto clientOnlyNode = clientScene->GetChild("Client Only Node", true); auto replicatedNodeA = clientScene->GetChild("Replicated Node A", true); auto replicatedNodeB = clientScene->GetChild("Replicated Node B", true); auto replicatedNodeChild1 = clientScene->GetChild("Replicated Node Child 1", true); auto replicatedNodeChild2 = clientScene->GetChild("Replicated Node Child 2", true); auto replicatedNodeChild4 = clientScene->GetChild("Replicated Node Child 4", true); REQUIRE(clientScene->GetNumChildren() == 3); REQUIRE(clientScene == clientOnlyNode->GetParent()); REQUIRE(clientScene == replicatedNodeA->GetParent()); REQUIRE(clientScene == replicatedNodeB->GetParent()); REQUIRE(clientOnlyNode->GetNumChildren() == 0); REQUIRE(replicatedNodeA->GetNumChildren() == 1); REQUIRE(replicatedNodeA == replicatedNodeChild1->GetParent()); REQUIRE(replicatedNodeChild1->GetNumChildren() == 1); REQUIRE(replicatedNodeChild1 == replicatedNodeChild2->GetParent()); REQUIRE(replicatedNodeChild2->GetNumChildren() == 0); REQUIRE(replicatedNodeB->GetNumChildren() == 1); REQUIRE(replicatedNodeB == replicatedNodeChild4->GetParent()); REQUIRE(replicatedNodeChild4->GetNumChildren() == 0); REQUIRE(replicatedNodeA->GetWorldTransform().Equals(transformReplicatedNodeA)); REQUIRE(replicatedNodeB->GetWorldTransform().Equals(transformReplicatedNodeB)); REQUIRE(replicatedNodeChild1->GetWorldTransform().Equals(transformReplicatedNodeChild1)); REQUIRE(replicatedNodeChild2->GetWorldTransform().Equals(transformReplicatedNodeChild2)); REQUIRE(replicatedNodeChild4->GetWorldTransform().Equals(transformReplicatedNodeChild4)); } // Re-parent "Server Only Child 3" to "Replicated Node A" // Re-parent "Replicated Node Child 1" to Scene // Wait for synchronization { auto serverOnlyChild3 = serverScene->GetChild("Server Only Child 3", true); auto replicatedNodeA = serverScene->GetChild("Replicated Node A", true); auto replicatedNodeChild1 = serverScene->GetChild("Replicated Node Child 1", true); serverOnlyChild3->SetParent(replicatedNodeA); replicatedNodeChild1->SetParent(serverScene); } sim.SimulateTime(syncDelay); for (Scene* clientScene : clientScenes) { auto clientOnlyNode = clientScene->GetChild("Client Only Node", true); auto replicatedNodeA = clientScene->GetChild("Replicated Node A", true); auto replicatedNodeB = clientScene->GetChild("Replicated Node B", true); auto replicatedNodeChild1 = clientScene->GetChild("Replicated Node Child 1", true); auto replicatedNodeChild2 = clientScene->GetChild("Replicated Node Child 2", true); auto replicatedNodeChild4 = clientScene->GetChild("Replicated Node Child 4", true); REQUIRE(clientScene->GetNumChildren() == 4); REQUIRE(clientScene == clientOnlyNode->GetParent()); REQUIRE(clientScene == replicatedNodeA->GetParent()); REQUIRE(clientScene == replicatedNodeB->GetParent()); REQUIRE(clientScene == replicatedNodeChild1->GetParent()); REQUIRE(clientOnlyNode->GetNumChildren() == 0); REQUIRE(replicatedNodeA->GetNumChildren() == 1); REQUIRE(replicatedNodeA == replicatedNodeChild4->GetParent()); REQUIRE(replicatedNodeChild4->GetNumChildren() == 0); REQUIRE(replicatedNodeB->GetNumChildren() == 0); REQUIRE(replicatedNodeChild1->GetNumChildren() == 1); REQUIRE(replicatedNodeChild1 == replicatedNodeChild2->GetParent()); REQUIRE(replicatedNodeChild2->GetNumChildren() == 0); REQUIRE(replicatedNodeA->GetWorldTransform().Equals(transformReplicatedNodeA, M_LARGE_EPSILON)); REQUIRE(replicatedNodeB->GetWorldTransform().Equals(transformReplicatedNodeB, M_LARGE_EPSILON)); REQUIRE(replicatedNodeChild1->GetWorldTransform().Equals(transformReplicatedNodeChild1, M_LARGE_EPSILON)); REQUIRE(replicatedNodeChild2->GetWorldTransform().Equals(transformReplicatedNodeChild2, M_LARGE_EPSILON)); REQUIRE(replicatedNodeChild4->GetWorldTransform().Equals(transformReplicatedNodeChild4, M_LARGE_EPSILON)); } // Remove "Replicated Node A" // Add "Replicated Node C" { auto replicatedNodeA = serverScene->GetChild("Replicated Node A", true); replicatedNodeA->Remove(); auto replicatedNodeC = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Replicated Node C"); } sim.SimulateTime(syncDelay); for (Scene* clientScene : clientScenes) { auto clientOnlyNode = clientScene->GetChild("Client Only Node", true); auto replicatedNodeB = clientScene->GetChild("Replicated Node B", true); auto replicatedNodeC = clientScene->GetChild("Replicated Node C", true); auto replicatedNodeChild1 = clientScene->GetChild("Replicated Node Child 1", true); auto replicatedNodeChild2 = clientScene->GetChild("Replicated Node Child 2", true); REQUIRE(clientScene->GetNumChildren() == 4); REQUIRE(clientScene == clientOnlyNode->GetParent()); REQUIRE(clientScene == replicatedNodeB->GetParent()); REQUIRE(clientScene == replicatedNodeC->GetParent()); REQUIRE(clientScene == replicatedNodeChild1->GetParent()); REQUIRE(clientOnlyNode->GetNumChildren() == 0); REQUIRE(replicatedNodeB->GetNumChildren() == 0); REQUIRE(replicatedNodeChild1->GetNumChildren() == 1); REQUIRE(replicatedNodeChild1 == replicatedNodeChild2->GetParent()); REQUIRE(replicatedNodeChild2->GetNumChildren() == 0); REQUIRE(replicatedNodeB->GetWorldTransform().Equals(transformReplicatedNodeB, M_LARGE_EPSILON)); REQUIRE(replicatedNodeC->GetWorldTransform().Equals(Matrix3x4::IDENTITY, M_LARGE_EPSILON)); REQUIRE(replicatedNodeChild1->GetWorldTransform().Equals(transformReplicatedNodeChild1, M_LARGE_EPSILON)); REQUIRE(replicatedNodeChild2->GetWorldTransform().Equals(transformReplicatedNodeChild2, M_LARGE_EPSILON)); } // Re-parent "Replicated Node Child 2" to Scene // Remove "Replicated Node Child 1", "Replicated Node B", "Replicated Node C" { auto replicatedNodeChild1 = serverScene->GetChild("Replicated Node Child 1", true); auto replicatedNodeChild2 = serverScene->GetChild("Replicated Node Child 2", true); auto replicatedNodeB = serverScene->GetChild("Replicated Node B", true); auto replicatedNodeC = serverScene->GetChild("Replicated Node C", true); replicatedNodeChild2->SetParent(serverScene); replicatedNodeChild1->Remove(); replicatedNodeB->Remove(); replicatedNodeC->Remove(); } sim.SimulateTime(syncDelay); for (Scene* clientScene : clientScenes) { auto clientOnlyNode = clientScene->GetChild("Client Only Node", true); auto replicatedNodeChild2 = clientScene->GetChild("Replicated Node Child 2", true); REQUIRE(clientScene->GetNumChildren() == 2); REQUIRE(clientScene == clientOnlyNode->GetParent()); REQUIRE(clientScene == replicatedNodeChild2->GetParent()); REQUIRE(replicatedNodeChild2->GetWorldTransform().Equals(transformReplicatedNodeChild2, M_LARGE_EPSILON)); } } TEST_CASE("Position and rotation are synchronized between client and server") { auto context = Tests::GetOrCreateContext(Tests::CreateCompleteContext); context->GetSubsystem<Network>()->SetUpdateFps(Tests::NetworkSimulator::FramesInSecond); auto prefab = Tests::GetOrCreateResource<XMLFile>(context, "@/SceneSynchronization/SimpleTestPrefab.xml", CreateSimpleTestPrefab); // Setup scenes const auto interpolationQuality = Tests::ConnectionQuality{0.08f, 0.12f, 0.20f, 0, 0}; const auto extrapolationQuality = Tests::ConnectionQuality{0.25f, 0.35f, 0.40f, 0, 0}; const float positionError = ReplicatedTransform::DefaultMovementThreshold; const float moveSpeedNodeA = 1.0f; const float rotationSpeedNodeA = 10.0f; const float moveSpeedNodeB = 0.1f; auto serverScene = MakeShared<Scene>(context); SharedPtr<Scene> interpolatingClientScene = MakeShared<Scene>(context); interpolatingClientScene->SetName("Interpolating Scene"); SharedPtr<Scene> extrapolatingClientScene = MakeShared<Scene>(context); extrapolatingClientScene->SetName("Extrapolation Scene"); Node* serverNodeA = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Node"); auto serverTransformA = serverNodeA->GetComponent<ReplicatedTransform>(); serverTransformA->SetExtrapolateRotation(true); Node* serverNodeB = Tests::SpawnOnServer<BehaviorNetworkObject>(serverNodeA, prefab, "Node Child", { 0.0f, 0.0f, 1.0f }); auto serverTransformB = serverNodeB->GetComponent<ReplicatedTransform>(); serverTransformB->SetExtrapolateRotation(true); // Animate objects forever serverScene->SubscribeToEvent(serverScene, E_SCENEUPDATE, [&](StringHash, VariantMap& eventData) { const float timeStep = eventData[SceneUpdate::P_TIMESTEP].GetFloat(); serverNodeA->Translate(timeStep * moveSpeedNodeA * Vector3::LEFT, TS_PARENT); serverNodeA->Rotate({ timeStep * rotationSpeedNodeA, Vector3::UP }, TS_PARENT); serverNodeB->Translate(timeStep * moveSpeedNodeB * Vector3::FORWARD, TS_PARENT); }); // Spend some time alone Tests::NetworkSimulator sim(serverScene); const auto& serverReplicator = *serverScene->GetComponent<ReplicationManager>()->GetServerReplicator(); sim.SimulateTime(9.0f); // Add clients and wait for synchronization sim.AddClient(interpolatingClientScene, interpolationQuality); sim.AddClient(extrapolatingClientScene, extrapolationQuality); sim.SimulateTime(9.0f); // Expect positions and rotations to be precisely synchronized on interpolating client { const auto& clientReplica = *interpolatingClientScene->GetComponent<ReplicationManager>()->GetClientReplica(); const NetworkTime replicaTime = clientReplica.GetReplicaTime(); const double delay = serverReplicator.GetServerTime() - replicaTime; auto clientNodeA = interpolatingClientScene->GetChild("Node", true); auto clientNodeB = interpolatingClientScene->GetChild("Node Child", true); REQUIRE(delay / Tests::NetworkSimulator::FramesInSecond == Catch::Approx(0.2).margin(0.03)); REQUIRE(serverTransformA->SampleTemporalPosition(replicaTime).value_.Equals(clientNodeA->GetWorldPosition(), positionError)); REQUIRE(serverTransformA->SampleTemporalRotation(replicaTime).value_.Equivalent(clientNodeA->GetWorldRotation(), M_EPSILON)); REQUIRE(serverTransformB->SampleTemporalPosition(replicaTime).value_.Equals(clientNodeB->GetWorldPosition(), positionError)); REQUIRE(serverTransformB->SampleTemporalRotation(replicaTime).value_.Equivalent(clientNodeB->GetWorldRotation(), M_EPSILON)); } // Expect positions and rotations to be roughly synchronized on extrapolating client { const auto& clientReplica = *extrapolatingClientScene->GetComponent<ReplicationManager>()->GetClientReplica(); const NetworkTime replicaTime = clientReplica.GetReplicaTime(); const double delay = serverReplicator.GetServerTime() - replicaTime; auto clientNodeA = extrapolatingClientScene->GetChild("Node", true); auto clientNodeB = extrapolatingClientScene->GetChild("Node Child", true); REQUIRE(delay / Tests::NetworkSimulator::FramesInSecond == Catch::Approx(0.25).margin(0.03)); REQUIRE(serverTransformA->SampleTemporalPosition(replicaTime).value_.Equals(clientNodeA->GetWorldPosition(), positionError)); REQUIRE(serverTransformA->SampleTemporalRotation(replicaTime).value_.Equivalent(clientNodeA->GetWorldRotation(), M_EPSILON)); REQUIRE(serverTransformB->SampleTemporalPosition(replicaTime).value_.Equals(clientNodeB->GetWorldPosition(), 0.002f)); REQUIRE(serverTransformB->SampleTemporalRotation(replicaTime).value_.Equivalent(clientNodeB->GetWorldRotation(), M_EPSILON)); } } TEST_CASE("Prefabs are replicated on clients") { auto context = Tests::GetOrCreateContext(Tests::CreateCompleteContext); context->GetSubsystem<Network>()->SetUpdateFps(Tests::NetworkSimulator::FramesInSecond); auto prefab = Tests::GetOrCreateResource<XMLFile>(context, "@/SceneSynchronization/ComplexTestPrefab.xml", CreateComplexTestPrefab); // Setup scenes const auto quality = Tests::ConnectionQuality{ 0.08f, 0.12f, 0.20f, 0.02f, 0.02f }; auto serverScene = MakeShared<Scene>(context); SharedPtr<Scene> clientScenes[] = { MakeShared<Scene>(context), MakeShared<Scene>(context), MakeShared<Scene>(context) }; // Start simulation Tests::NetworkSimulator sim(serverScene); for (Scene* clientScene : clientScenes) sim.AddClient(clientScene, quality); // Create nodes { Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Node 1", {1.0f, 0.0f, 0.0f}); Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Node 2", {2.0f, 0.0f, 0.0f}); } sim.SimulateTime(10.0f); // Expect prefabs replicated for (Scene* clientScene : clientScenes) { auto node1 = clientScene->GetChild("Node 1", true); REQUIRE(node1); auto node2 = clientScene->GetChild("Node 2", true); REQUIRE(node2); auto node1Child = node1->GetChild("Child"); REQUIRE(node1Child); auto node2Child = node2->GetChild("Child"); REQUIRE(node2Child); CHECK(node1->GetWorldPosition().Equals({1.0f, 0.0f, 0.0f})); CHECK(node1Child->GetWorldPosition().Equals({1.0f, 1.0f, 0.0f})); CHECK(node2->GetWorldPosition().Equals({2.0f, 0.0f, 0.0f})); CHECK(node2Child->GetWorldPosition().Equals({2.0f, 1.0f, 0.0f})); auto staticModel1 = node1->GetComponent<StaticModel>(); REQUIRE(staticModel1); auto staticModel2 = node2->GetComponent<StaticModel>(); REQUIRE(staticModel2); auto light1 = node1Child->GetComponent<Light>(); REQUIRE(light1); auto light2 = node2Child->GetComponent<Light>(); REQUIRE(light2); CHECK(staticModel1->GetCastShadows() == true); CHECK(staticModel2->GetCastShadows() == true); CHECK(light1->GetCastShadows() == true); CHECK(light2->GetCastShadows() == true); CHECK(light1->GetColor() == Color::RED); CHECK(light2->GetColor() == Color::RED); } } TEST_CASE("Ownership is consistent on server and on clients") { auto context = Tests::GetOrCreateContext(Tests::CreateCompleteContext); context->GetSubsystem<Network>()->SetUpdateFps(Tests::NetworkSimulator::FramesInSecond); auto prefab = Tests::GetOrCreateResource<XMLFile>(context, "@/SceneSynchronization/SimpleTestPrefab.xml", CreateSimpleTestPrefab); // Setup scenes const auto quality = Tests::ConnectionQuality{ 0.08f, 0.12f, 0.20f, 0.02f, 0.02f }; auto serverScene = MakeShared<Scene>(context); SharedPtr<Scene> clientScenes[] = { MakeShared<Scene>(context), MakeShared<Scene>(context), MakeShared<Scene>(context) }; // Start simulation Tests::NetworkSimulator sim(serverScene); for (Scene* clientScene : clientScenes) sim.AddClient(clientScene, quality); // Create nodes { Node* node = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Unowned Node"); auto object = node->GetDerivedComponent<NetworkObject>(); REQUIRE(object->GetNetworkMode() == NetworkObjectMode::Standalone); } { Node* node = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Owned Node 0"); auto object = node->GetDerivedComponent<NetworkObject>(); object->SetOwner(sim.GetServerToClientConnection(clientScenes[0])); REQUIRE(object->GetNetworkMode() == NetworkObjectMode::Standalone); } { Node* node = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Owned Node 1"); auto object = node->GetDerivedComponent<NetworkObject>(); object->SetOwner(sim.GetServerToClientConnection(clientScenes[1])); REQUIRE(object->GetNetworkMode() == NetworkObjectMode::Standalone); } { Node* node = Tests::SpawnOnServer<BehaviorNetworkObject>(serverScene, prefab, "Owned Node 2"); auto object = node->GetDerivedComponent<NetworkObject>(); object->SetOwner(sim.GetServerToClientConnection(clientScenes[2])); REQUIRE(object->GetNetworkMode() == NetworkObjectMode::Standalone); } sim.SimulateTime(10.0f); // Check ownership of objects const auto getObject = [](Scene* scene, const ea::string& name) { return scene->GetChild(name, true)->GetDerivedComponent<NetworkObject>(); }; REQUIRE(getObject(serverScene, "Unowned Node")->GetNetworkMode() == NetworkObjectMode::Server); REQUIRE(getObject(serverScene, "Owned Node 0")->GetNetworkMode() == NetworkObjectMode::Server); REQUIRE(getObject(serverScene, "Owned Node 1")->GetNetworkMode() == NetworkObjectMode::Server); REQUIRE(getObject(serverScene, "Owned Node 2")->GetNetworkMode() == NetworkObjectMode::Server); REQUIRE(getObject(clientScenes[0], "Unowned Node")->GetNetworkMode() == NetworkObjectMode::ClientReplicated); REQUIRE(getObject(clientScenes[0], "Owned Node 0")->GetNetworkMode() == NetworkObjectMode::ClientOwned); REQUIRE(getObject(clientScenes[0], "Owned Node 1")->GetNetworkMode() == NetworkObjectMode::ClientReplicated); REQUIRE(getObject(clientScenes[0], "Owned Node 2")->GetNetworkMode() == NetworkObjectMode::ClientReplicated); REQUIRE(getObject(clientScenes[1], "Unowned Node")->GetNetworkMode() == NetworkObjectMode::ClientReplicated); REQUIRE(getObject(clientScenes[1], "Owned Node 0")->GetNetworkMode() == NetworkObjectMode::ClientReplicated); REQUIRE(getObject(clientScenes[1], "Owned Node 1")->GetNetworkMode() == NetworkObjectMode::ClientOwned); REQUIRE(getObject(clientScenes[1], "Owned Node 2")->GetNetworkMode() == NetworkObjectMode::ClientReplicated); REQUIRE(getObject(clientScenes[2], "Unowned Node")->GetNetworkMode() == NetworkObjectMode::ClientReplicated); REQUIRE(getObject(clientScenes[2], "Owned Node 0")->GetNetworkMode() == NetworkObjectMode::ClientReplicated); REQUIRE(getObject(clientScenes[2], "Owned Node 1")->GetNetworkMode() == NetworkObjectMode::ClientReplicated); REQUIRE(getObject(clientScenes[2], "Owned Node 2")->GetNetworkMode() == NetworkObjectMode::ClientOwned); // Check client-side arrays const auto getClientReplica = [](Scene* scene) { return scene->GetComponent<ReplicationManager>()->GetClientReplica(); }; REQUIRE(getClientReplica(clientScenes[0])->GetOwnedNetworkObject() == getObject(clientScenes[0], "Owned Node 0")); REQUIRE(getClientReplica(clientScenes[1])->GetOwnedNetworkObject() == getObject(clientScenes[1], "Owned Node 1")); REQUIRE(getClientReplica(clientScenes[2])->GetOwnedNetworkObject() == getObject(clientScenes[2], "Owned Node 2")); // Check server-side arrays auto serverReplicator = serverScene->GetComponent<ReplicationManager>()->GetServerReplicator(); REQUIRE(serverReplicator->GetNetworkObjectOwnedByConnection(sim.GetServerToClientConnection(clientScenes[0])) == getObject(serverScene, "Owned Node 0")); REQUIRE(serverReplicator->GetNetworkObjectOwnedByConnection(sim.GetServerToClientConnection(clientScenes[1])) == getObject(serverScene, "Owned Node 1")); REQUIRE(serverReplicator->GetNetworkObjectOwnedByConnection(sim.GetServerToClientConnection(clientScenes[2])) == getObject(serverScene, "Owned Node 2")); // Remove all owned nodes serverScene->GetChild("Owned Node 0", true)->Remove(); serverScene->GetChild("Owned Node 1", true)->Remove(); serverScene->GetChild("Owned Node 2", true)->Remove(); sim.SimulateTime(10.0f); REQUIRE(getClientReplica(clientScenes[0])->GetOwnedNetworkObject() == nullptr); REQUIRE(getClientReplica(clientScenes[1])->GetOwnedNetworkObject() == nullptr); REQUIRE(getClientReplica(clientScenes[2])->GetOwnedNetworkObject() == nullptr); REQUIRE(serverReplicator->GetNetworkObjectOwnedByConnection(sim.GetServerToClientConnection(clientScenes[0])) == nullptr); REQUIRE(serverReplicator->GetNetworkObjectOwnedByConnection(sim.GetServerToClientConnection(clientScenes[1])) == nullptr); REQUIRE(serverReplicator->GetNetworkObjectOwnedByConnection(sim.GetServerToClientConnection(clientScenes[2])) == nullptr); }
47.669078
157
0.721672
jayrulez
7ff2642d55b39b8c6c655072137a1d1a3f17cdc4
739
cpp
C++
STL_C++/Iterators.cpp
prabhash-varma/DSA-CP
685b13d960d2045d003e30f235d678b9f05548b3
[ "MIT" ]
null
null
null
STL_C++/Iterators.cpp
prabhash-varma/DSA-CP
685b13d960d2045d003e30f235d678b9f05548b3
[ "MIT" ]
null
null
null
STL_C++/Iterators.cpp
prabhash-varma/DSA-CP
685b13d960d2045d003e30f235d678b9f05548b3
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main(){ vector<int> v ={2,3,5,6,7}; // for(int i=0;i<v.size();i++){ // cout<<v[i]<< " "; // } // cout<<endl; //Iterator declaration vector<int> :: iterator it = v.begin(); //cout<<(*(it+1))<<endl; for(it=v.begin();it !=v.end();it++){ cout<<(*it)<<endl; } //vector of pair vector<pair<int,int>> v_p ={{1,2},{2,3},{3,4}}; vector<pair<int,int>> :: iterator ite; for(ite=v_p.begin();ite!=v_p.end();ite++){ cout<< (*ite).first<<" "<<(*ite).second<<endl; } // (*it).first == (it->first) for(ite=v_p.begin();ite!=v_p.end();ite++){ cout<< (ite->first)<<" "<<(ite->second)<<endl; } }
18.02439
54
0.470907
prabhash-varma
7ff59dcffba8ef64c7f8d3e79b5160afe82ecb15
2,727
cpp
C++
C++/rectangle-area-ii.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/rectangle-area-ii.cpp
pnandini/LeetCode
e746c3298be96dec8e160da9378940568ef631b1
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/rectangle-area-ii.cpp
pnandini/LeetCode
e746c3298be96dec8e160da9378940568ef631b1
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(nlogn) // Space: O(n) class Solution { public: enum { OPEN = 1, CLOSE = -1}; int rectangleArea(vector<vector<int>>& rectangles) { vector<vector<int>> events; set<int> Xvals; for (const auto& rec: rectangles) { events.emplace_back(vector<int>{rec[1], OPEN, rec[0], rec[2]}); events.emplace_back(vector<int>{rec[3], CLOSE, rec[0], rec[2]}); Xvals.emplace(rec[0]); Xvals.emplace(rec[2]); } sort(events.begin(), events.end()); vector<int> X(Xvals.cbegin(), Xvals.cend()); unordered_map<int, int> Xi; for (int i = 0; i < X.size(); ++i) { Xi[X[i]] = i; } auto st = new SegmentTreeNode(0, X.size() - 1, X); int64_t result = 0; int64_t cur_x_sum = 0; int cur_y = events[0][0]; for (const auto& event: events) { int y = event[0], type = event[1], x1 = event[2], x2 = event[3]; result += cur_x_sum * (y - cur_y); cur_x_sum = st->update(Xi[x1], Xi[x2], type); cur_y = y; } return result % static_cast<int64_t>(1e9 + 7); } class SegmentTreeNode { public: SegmentTreeNode(int start, int end, const vector<int>& X) : start_(start), end_(end), X_(X), left_(nullptr), right_(nullptr), count_(0), total_(0) { } int mid() const { return start_ + (end_ - start_) / 2; } SegmentTreeNode *left() { if (left_ == nullptr) { left_ = new SegmentTreeNode(start_, mid(), X_); } return left_; } SegmentTreeNode *right() { if (right_ == nullptr) { right_ = new SegmentTreeNode(mid(), end_, X_); } return right_; } int64_t total() const { return total_; } int64_t update(int i, int j, int val) { if (i >= j) { return 0; } if (start_ == i && end_ == j) { count_ += val; } else { left()->update(i, min(mid(), j), val); right()->update(max(mid(), i), j, val); } if (count_ > 0) { total_ = X_[end_] - X_[start_]; } else { total_ = left()->total() + right()->total(); } return total_; } private: int start_, end_; const vector<int>& X_; SegmentTreeNode *left_, *right_; int count_; int64_t total_; }; };
28.113402
76
0.441511
jaiskid
7ff873a32d8231c89f28f48b8804cbd12e64d12a
968
cpp
C++
Angel/Libraries/FTGL/src/FTLibrary.cpp
Tifox/Grog-Knight
377a661286cda7ee3b2b2d0099641897938c2f8f
[ "Apache-2.0" ]
171
2015-01-08T10:35:56.000Z
2021-07-03T12:35:10.000Z
Angel/Libraries/FTGL/src/FTLibrary.cpp
Tifox/Grog-Knight
377a661286cda7ee3b2b2d0099641897938c2f8f
[ "Apache-2.0" ]
11
2015-01-30T05:30:54.000Z
2017-04-08T23:34:33.000Z
Angel/Libraries/FTGL/src/FTLibrary.cpp
Tifox/Grog-Knight
377a661286cda7ee3b2b2d0099641897938c2f8f
[ "Apache-2.0" ]
59
2015-02-01T03:43:00.000Z
2020-12-01T02:08:57.000Z
#include "FTLibrary.h" const FTLibrary& FTLibrary::Instance() { static FTLibrary ftlib; return ftlib; } FTLibrary::~FTLibrary() { if( library != 0) { FT_Done_FreeType( *library); delete library; library= 0; } // if( manager != 0) // { // FTC_Manager_Done( manager ); // // delete manager; // manager= 0; // } } FTLibrary::FTLibrary() : library(0), err(0) { Initialise(); } bool FTLibrary::Initialise() { if( library != 0) return true; library = new FT_Library; err = FT_Init_FreeType( library); if( err) { delete library; library = 0; return false; } // FTC_Manager* manager; // // if( FTC_Manager_New( lib, 0, 0, 0, my_face_requester, 0, manager ) // { // delete manager; // manager= 0; // return false; // } return true; }
14.892308
71
0.494835
Tifox
3d00d94ec5c106e63b74c91e2e0d40c6ff05aa35
6,403
cpp
C++
src/QtManagers/Images/nSubgroupPictures.cpp
Vladimir-Lin/QtManagers
2f906b165f773bff054a8349c577b7d07c2345d9
[ "MIT" ]
null
null
null
src/QtManagers/Images/nSubgroupPictures.cpp
Vladimir-Lin/QtManagers
2f906b165f773bff054a8349c577b7d07c2345d9
[ "MIT" ]
null
null
null
src/QtManagers/Images/nSubgroupPictures.cpp
Vladimir-Lin/QtManagers
2f906b165f773bff054a8349c577b7d07c2345d9
[ "MIT" ]
null
null
null
#include <qtmanagers.h> N::SubgroupPictures:: SubgroupPictures (QWidget * parent,Plan * p) : SubgroupLists ( parent, p) { WidgetClass ; Configure ( ) ; } N::SubgroupPictures::~SubgroupPictures(void) { } void N::SubgroupPictures::Configure(void) { } void N::SubgroupPictures::DeletePictures(QListWidgetItem * it) { SUID u = nListUuid(it) ; QString M ; M = tr("Delete [%1] pictures").arg(it->text()) ; plan->showMessage(M) ; setEnabled ( false ) ; EnterSQL ( SC , plan->sql ) ; QString Q ; Q = SC.sql.DeleteFrom ( PlanTable(Groups) , FirstItem ( u , EachType() , Types::Picture , Groups::Subordination ) ) ; SC.Query(Q) ; LeaveSQL ( SC , plan->sql ) ; setEnabled ( true ) ; Alert ( Done ) ; } bool N::SubgroupPictures::Menu(QPoint pos) { nScopedMenu ( mm , this ) ; QMenu * me ; QMenu * mc ; QAction * aa ; QListWidgetItem * it ; SUID u = 0 ; /////////////////////////////////////////////////// it = itemAt(pos) ; if (NotNull(it) && !it->isSelected()) it = NULL ; if (NotNull(it)) u = nListUuid(it) ; /////////////////////////////////////////////////// mm.add(101,tr("New subgroup")) ; mm.add(201,tr("Reflush" )) ; if (NotNull(it)) mm.add(202,tr("Reflush item")) ; mm.addSeparator() ; me = mm.addMenu(tr("Edit" )) ; if (NotNull(it)) { mc = mm.addMenu(tr("Categorize")) ; } ; mm.addSeparator() ; mm.add(301,tr("Copy to clipboard")) ; mm.add(302,tr("Clear selection" )) ; mm.add(303,tr("Select all" )) ; /////////////////////////////////////////////////// if (NotNull(it)) { mm.add(me,102,tr("Rename")) ; mm.add(me,103,tr("Delete this subgroup")) ; mm.addSeparator() ; mm.add(me,104,tr("Delete all pictures")) ; mm.addSeparator() ; if (u>0) mm.add(me,401,tr("Pictures")) ; } ; mm.add(me,211,tr("Multilingual translations")) ; AdjustMenu(mm,me) ; /////////////////////////////////////////////////// if (NotNull(it)) { mm.add(mc,501,tr("Constraints")) ; mm.add(mc,502,tr("Rule tables")) ; } ; /////////////////////////////////////////////////// mm . setFont ( plan ) ; aa = mm.exec ( ) ; nKickOut ( IsNull(aa) , true ) ; /////////////////////////////////////////////////// UUIDs Tuids ; switch (mm[aa]) { case 101 : New ( ) ; break ; case 102 : Rename ( ) ; break ; case 103 : Delete ( ) ; break ; case 104 : DeletePictures ( it ) ; break ; case 201 : startup ( ) ; break ; case 202 : Refresh ( it ) ; break ; case 211 : Tuids = ItemUuids() ; emit Translations(windowTitle(),Tuids) ; break ; case 301 : CopyToClipboard ( ) ; break ; case 302 : SelectNone ( ) ; break ; case 303 : SelectAll ( ) ; break ; case 401 : if (u>0) { emit SeePictures(ObjectUuid(),u,it->text()) ; } ; break ; case 501 : emit Constraints ( windowTitle() , u ) ; break ; case 502 : emit RuleTables ( windowTitle() , u ) ; break ; default : RunAdjustment ( mm , aa ) ; break ; } ; return true ; }
46.737226
66
0.243948
Vladimir-Lin
3d049e20010fb075d1aae3832f07acdf5d61e1b7
1,291
cpp
C++
libraries/RTClib/src/RTC_Micros.cpp
FelipeJojoa28/MQTT_Iot
f35f74775ae9edacb4a456d74a6aa55c12734b17
[ "Apache-2.0" ]
1
2022-03-10T11:19:46.000Z
2022-03-10T11:19:46.000Z
libraries/RTClib/src/RTC_Micros.cpp
FelipeJojoa28/MQTT_Iot
f35f74775ae9edacb4a456d74a6aa55c12734b17
[ "Apache-2.0" ]
null
null
null
libraries/RTClib/src/RTC_Micros.cpp
FelipeJojoa28/MQTT_Iot
f35f74775ae9edacb4a456d74a6aa55c12734b17
[ "Apache-2.0" ]
1
2018-09-28T11:43:20.000Z
2018-09-28T11:43:20.000Z
#include "RTClib.h" /**************************************************************************/ /*! @brief Set the current date/time of the RTC_Micros clock. @param dt DateTime object with the desired date and time */ /**************************************************************************/ void RTC_Micros::adjust(const DateTime &dt) { lastMicros = micros(); lastUnix = dt.unixtime(); } /**************************************************************************/ /*! @brief Adjust the RTC_Micros clock to compensate for system clock drift @param ppm Adjustment to make. A positive adjustment makes the clock faster. */ /**************************************************************************/ void RTC_Micros::adjustDrift(int ppm) { microsPerSecond = 1000000 - ppm; } /**************************************************************************/ /*! @brief Get the current date/time from the RTC_Micros clock. @return DateTime object containing the current date/time */ /**************************************************************************/ DateTime RTC_Micros::now() { uint32_t elapsedSeconds = (micros() - lastMicros) / microsPerSecond; lastMicros += elapsedSeconds * microsPerSecond; lastUnix += elapsedSeconds; return lastUnix; }
37.970588
80
0.463207
FelipeJojoa28
3d04c7c1aa478d4067a24bbaa522f7df232b5972
239
cpp
C++
Source/Borderlands/weapon/WeaponStateInactive.cpp
yongaro/Borderlands
39fbcf095400b53f4394cc115e59f40e59520484
[ "Apache-2.0" ]
1
2020-04-03T13:29:51.000Z
2020-04-03T13:29:51.000Z
Source/Borderlands/weapon/WeaponStateInactive.cpp
yongaro/Borderlands
39fbcf095400b53f4394cc115e59f40e59520484
[ "Apache-2.0" ]
null
null
null
Source/Borderlands/weapon/WeaponStateInactive.cpp
yongaro/Borderlands
39fbcf095400b53f4394cc115e59f40e59520484
[ "Apache-2.0" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "WeaponStateInactive.h" #include "Borderlands.h" UWeaponStateInactive::UWeaponStateInactive() { } UWeaponStateInactive::~UWeaponStateInactive() { }
18.384615
78
0.790795
yongaro
3d05e3dde5a40e2d905e87d8dc61665ba96ef62c
1,218
hpp
C++
src/Program.hpp
Fabio3rs/dbdhelp
1afeef265b826220e2a769353b932fc6b8436905
[ "MIT" ]
null
null
null
src/Program.hpp
Fabio3rs/dbdhelp
1afeef265b826220e2a769353b932fc6b8436905
[ "MIT" ]
null
null
null
src/Program.hpp
Fabio3rs/dbdhelp
1afeef265b826220e2a769353b932fc6b8436905
[ "MIT" ]
null
null
null
#pragma once #ifndef MIGRATIONMGR_PROGRAM_HPP #define MIGRATIONMGR_PROGRAM_HPP #include <deque> #include <cstdint> #include <string> #include "Database.hpp" #include "CLuaH.hpp" #include "CLuaFunctions.hpp" #include "CViewsManager.hpp" namespace migmgr { class Program { std::string config_script; std::string migrations_directory; std::deque<Database> dbs; CLuaH::scriptStorage scripts; bool loaded; static int registerFunctions(lua_State* L); static int registerGlobals(lua_State* L); // Lua functions static int select_database(lua_State* L); static int create_table(lua_State* L); static int alter_table(lua_State* L); static int set_table_nicename(lua_State *L); static int field_id(lua_State* L); static int field_timestamps(lua_State* L); static int create_field(lua_State *L); static int dumptbl(lua_State *L); public: bool load(); void run(); void output_models(); void output_migrations(); static Program &prog(); private: Program() noexcept; }; } #endif
22.981132
57
0.62069
Fabio3rs
3d0794c35948a79e6a18ccf73b93aa165aa37257
1,551
cpp
C++
Solutions/Candy/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
1
2015-04-13T10:58:30.000Z
2015-04-13T10:58:30.000Z
Solutions/Candy/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
null
null
null
Solutions/Candy/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <numeric> using namespace std; class Solution { public: //time limit exceeded int candy(vector<int> &ratings) { vector<int> res_v(ratings.size(), 1); vector<int>::size_type size = ratings.size(); for(vector<int>::size_type i = 1; i < size; i++) { if(ratings[i] > ratings[i-1]) { res_v[i] = res_v[i-1] + 1; } else { res_v[i] = 1; for(auto j = i; j>0 && ratings[j-1] > ratings[j] && res_v[j-1] <= res_v[j]; j--) { res_v[j-1] += 1; } } } int res = 0; return accumulate(res_v.begin(),res_v.end(),res); } int candy2(vector<int > &ratings) { vector<int>::size_type size = ratings.size(); vector<int> left(size,1), right(size,1); int res = 0; left[0] = 1; right[size-1] = 1; for(vector<int>::size_type i = 1; i< size; i++) { if (ratings[i] > ratings[i-1]) { left[i] = left[i-1] + 1; } if (ratings[size-i-1] > ratings[size-i]) { right[size-1-i] = right[size-i] + 1; } } for(vector<int>::size_type i = 0; i < size; i++) { res += max(left[i], right[i]); } return res; } }; int main() { Solution s; vector<int > ratings = {1,2,2}; cout<<s.candy(ratings)<<endl; cout<<endl; cout<<s.candy2(ratings)<<endl; return 0; }
27.210526
98
0.459059
Crayzero
3d0bf051397043a1671cf2fa0f9fe0964a689f4b
2,997
cpp
C++
lib/util/Configurations.cpp
GloomyGrave/Sinsy-NG
30c464b24eeb0d88caa9412286741889d1c84714
[ "Unlicense" ]
2
2021-03-20T10:29:29.000Z
2022-02-09T03:48:36.000Z
lib/util/Configurations.cpp
GloomyGrave/Sinsy-NG
30c464b24eeb0d88caa9412286741889d1c84714
[ "Unlicense" ]
null
null
null
lib/util/Configurations.cpp
GloomyGrave/Sinsy-NG
30c464b24eeb0d88caa9412286741889d1c84714
[ "Unlicense" ]
2
2020-10-24T02:51:41.000Z
2022-03-26T20:32:39.000Z
/* Created by Ghost Gloomy on 2018/11/8. */ #include <fstream> #include "Configurations.h" #include "util_log.h" #include "util_string.h" #include "StringTokenizer.h" namespace sinsy { namespace { const std::string SEPARATOR = "="; }; /*! constructor */ Configurations::Configurations() { } /*! destructor */ Configurations::~Configurations() { clear(); } /*! clear */ void Configurations::clear() { configs.clear(); } /*! read configurations from file */ bool Configurations::read(const std::string& fpath) { std::ifstream ifs(fpath.c_str()); if (!ifs) { ERR_MSG("Cannot open config file : " << fpath); return false; } clear(); std::string buffer; while (!ifs.eof()) { std::getline(ifs, buffer); // remove comments size_t idx = buffer.find("#"); if (idx != std::string::npos) { buffer.resize(idx); } StringTokenizer st(buffer, SEPARATOR); size_t sz(st.size()); if (0 == sz) { continue; } else if (2 != st.size()) { ERR_MSG("Syntax error : " << fpath); return false; } std::string key(st.at(0)); cutBlanks(key); std::string value(st.at(1)); cutBlanks(value); if (key.empty() || value.empty()) { ERR_MSG("Syntax error : " << fpath); return false; } // cut " and ' if (1 < value.size()) { if ((('\"' == value[0]) && ('\"' == value[value.size() - 1])) || (('\'' == value[0]) && ('\'' == value[value.size() - 1]))) { value = value.substr(1, value.size() - 2); cutBlanks(value); if (value.empty()) { ERR_MSG("Syntax error : " << fpath); return false; } } } configs.insert(std::make_pair/*<std::string, std::string>*/(key, value)); } return true; } /*! for std::string (need default) */ template<> std::string Configurations::get<std::string>(const std::string& key, const std::string& def) const { Configs::const_iterator itr(configs.find(key)); if (configs.end() != itr) { return itr->second; } return def; } /*! for std::string (not need default) */ std::string Configurations::get(const std::string& key) const { Configs::const_iterator itr(configs.find(key)); if (configs.end() != itr) { return itr->second; } return std::string(); } /*! for bool */ template<> bool Configurations::get<bool>(const std::string& key, const bool& def) const { Configs::const_iterator itr(configs.find(key)); if (configs.end() != itr) { std::string value(itr->second); toLower(value); if (value == "true") { return true; } else if (value == "false") { return false; } int i(-1); std::istringstream iss(value); iss >> i; if (0 == i) { return false; } else if (0 < i) { return true; } } return def; } }; // namespace sinsy
19.588235
134
0.539206
GloomyGrave
3d0e0842735b49023f5255f453912b41eceda925
999
hpp
C++
range.hpp
snir1551/Ex10_C-
70c0701aa7d130be19ace214c83f66ac17b96d8d
[ "MIT" ]
1
2021-05-31T13:09:48.000Z
2021-05-31T13:09:48.000Z
range.hpp
snir1551/Ex10_C-
70c0701aa7d130be19ace214c83f66ac17b96d8d
[ "MIT" ]
null
null
null
range.hpp
snir1551/Ex10_C-
70c0701aa7d130be19ace214c83f66ac17b96d8d
[ "MIT" ]
null
null
null
#ifndef _RANGE_HPP #define _RANGE_HPP #include <iostream> namespace itertools { //iterator class class iterator { private: int _num; //parameter public: iterator(int num): _num(num) { } void operator++() { ++(this->_num); } bool operator!=(const iterator& it) const { return (it._num != _num); } int operator*() const { return this->_num; } }; class range { private: int _begin, _end; public: typedef int value_type; range(int begin,int end): _begin(begin), _end(end) { } iterator begin() const { return iterator(_begin); } iterator end() const { return iterator(_end); } }; } #endif
16.932203
62
0.409409
snir1551
3d13ca4c6ef02ed64ada5a6e3f3b47f5da8f3f96
1,186
cpp
C++
LeetCode/Problems/Algorithms/#1337_TheKWeakestRowsInAMatrix_sol3_binary_search_and_heap_O(RlogC+RlogK)_time_O(R+K)_extra_space_12ms_10.5MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#1337_TheKWeakestRowsInAMatrix_sol3_binary_search_and_heap_O(RlogC+RlogK)_time_O(R+K)_extra_space_12ms_10.5MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#1337_TheKWeakestRowsInAMatrix_sol3_binary_search_and_heap_O(RlogC+RlogK)_time_O(R+K)_extra_space_12ms_10.5MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { private: int soldiersCount(const vector<int>& V){ int l = 0; int r = (int)V.size() - 1; while(l != r){ int mid = (l + r + 1) / 2; if(V[mid] == 1){ l = mid; }else{ r = mid - 1; } } int soldiers = 0; if(V[r] == 1){ soldiers = r + 1; } return soldiers; } public: vector<int> kWeakestRows(vector<vector<int>>& mat, int k) { const int N = mat.size(); vector<int> soldiers(N, 0); for(int row = 0; row < N; ++row){ soldiers[row] = soldiersCount(mat[row]); } priority_queue<pair<int, int>> maxHeap; for(int row = 0; row < N; ++row){ maxHeap.push({soldiers[row], row}); if(maxHeap.size() == k + 1){ maxHeap.pop(); } } vector<int> answer(k); for(int i = k - 1; i >= 0; --i){ answer[i] = maxHeap.top().second; maxHeap.pop(); } return answer; } };
25.782609
64
0.378583
Tudor67
3d1b9ec61abe0fea9930aa8f553b718ef1f3d5fe
1,282
hpp
C++
src/rynx/editor/tools/collisions_tool.hpp
Apodus/rynx
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
[ "MIT" ]
11
2019-08-19T08:44:14.000Z
2020-09-22T20:04:46.000Z
src/rynx/editor/tools/collisions_tool.hpp
Apodus/rynx
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
[ "MIT" ]
null
null
null
src/rynx/editor/tools/collisions_tool.hpp
Apodus/rynx
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
[ "MIT" ]
null
null
null
#pragma once #include <rynx/editor/tools/tool.hpp> namespace rynx { class ecs; namespace editor { namespace tools { class collisions_tool : public itool { public: collisions_tool(rynx::scheduler::context& ctx); virtual void update(rynx::scheduler::context& ctx) override; virtual void on_tool_selected() override {} virtual void on_tool_unselected() override {} virtual void verify(rynx::scheduler::context& ctx, error_emitter& emitter) override; virtual bool operates_on(const std::string& type_name) override { return type_name.find("rynx::components::collision") != std::string::npos; } virtual void on_entity_component_removed( rynx::scheduler::context* ctx, std::string componentTypeName, rynx::ecs& ecs, rynx::id id) override; // default removing collision type component is not ok, // need to know how to inform collision detection of the change. virtual bool allow_component_remove(const std::string& type_name) override { return !operates_on(type_name); } virtual std::string get_tool_name() override { return "collisions"; } virtual std::string get_button_texture() override { return "collisions_tool"; } private: rynx::ecs& m_ecs; }; } } }
25.64
114
0.695788
Apodus
3d20c199e6f8d433ba64037dc25b0f7ccdda1efd
3,768
cpp
C++
qws/src/gui/QTreeWidgetItem_DhClass.cpp
keera-studios/hsQt
8aa71a585cbec40005354d0ee43bce9794a55a9a
[ "BSD-2-Clause" ]
42
2015-02-16T19:29:16.000Z
2021-07-25T11:09:03.000Z
qws/src/gui/QTreeWidgetItem_DhClass.cpp
keera-studios/hsQt
8aa71a585cbec40005354d0ee43bce9794a55a9a
[ "BSD-2-Clause" ]
1
2017-11-23T12:49:25.000Z
2017-11-23T12:49:25.000Z
qws/src/gui/QTreeWidgetItem_DhClass.cpp
keera-studios/hsQt
8aa71a585cbec40005354d0ee43bce9794a55a9a
[ "BSD-2-Clause" ]
5
2015-10-15T21:25:30.000Z
2017-11-22T13:18:24.000Z
///////////////////////////////////////////////////////////////////////////// // // File : QTreeWidgetItem_DhClass.cpp // Copyright : (c) David Harley 2010 // Project : qtHaskell // Version : 1.1.4 // Modified : 2010-09-02 17:02:05 // // Warning : this file is machine generated - do not modify. // ///////////////////////////////////////////////////////////////////////////// #include <gui/QTreeWidgetItem_DhClass.h> void DhQTreeWidgetItem::userDefined(int x1) const { void* ro_ptr; void* rf_ptr; if(handlerSetud(x1,(void*&)ro_ptr,(void*&)rf_ptr,0)) (*(void(*)(void*))rf_ptr)(ro_ptr); } QVariant* DhQTreeWidgetItem::userDefinedVariant(int x1, QVariant* x2) const { void* ro_ptr; void* rf_ptr; if(handlerSetud(x1,(void*&)ro_ptr,(void*&)rf_ptr,1)) return (QVariant*)(*(void*(*)(void*,void*))rf_ptr)(ro_ptr, (void*)x2); return NULL ;} QTreeWidgetItem* DhQTreeWidgetItem::clone() const { void* ro_ptr; void* rf_ptr; if(handlerSet(0,(void*&)ro_ptr,(void*&)rf_ptr)) return (QTreeWidgetItem*)(*(void*(*)(void*))rf_ptr)(ro_ptr); return QTreeWidgetItem::clone(); } QTreeWidgetItem* DhQTreeWidgetItem::Dhclone() const { return QTreeWidgetItem::clone(); } QTreeWidgetItem* DhQTreeWidgetItem::Dvhclone() const { return clone(); } QVariant DhQTreeWidgetItem::data(int x1, int x2) const { void* ro_ptr; void* rf_ptr; if(handlerSet(1,(void*&)ro_ptr,(void*&)rf_ptr)) return *(QVariant*)(*(void*(*)(void*,int,int))rf_ptr)(ro_ptr, x1, x2); return QTreeWidgetItem::data(x1, x2); } QVariant DhQTreeWidgetItem::Dhdata(int x1, int x2) const { return QTreeWidgetItem::data(x1, x2); } QVariant DhQTreeWidgetItem::Dvhdata(int x1, int x2) const { return data(x1, x2); } void DhQTreeWidgetItem::setData(int x1, int x2, const QVariant& x3) { void* ro_ptr; void* rf_ptr; if(handlerSet(2,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,int,int,void*))rf_ptr)(ro_ptr, x1, x2, (void*)&x3); return QTreeWidgetItem::setData(x1, x2, x3); } void DhQTreeWidgetItem::DhsetData(int x1, int x2, const QVariant& x3) { return QTreeWidgetItem::setData(x1, x2, x3); } void DhQTreeWidgetItem::DvhsetData(int x1, int x2, const QVariant& x3) { return setData(x1, x2, x3); } QHash <QByteArray, int> DhQTreeWidgetItem::initXhHash() { QHash <QByteArray, int> txh; txh[QMetaObject::normalizedSignature("(QTreeWidgetItem*)clone()")] = 0; txh[QMetaObject::normalizedSignature("(QVariant)data(int,int)")] = 1; txh[QMetaObject::normalizedSignature("setData(int,int,const QVariant&)")] = 2; return txh; } QHash <QByteArray, int> DhQTreeWidgetItem::xhHash = DhQTreeWidgetItem::initXhHash(); bool DhQTreeWidgetItem::setDynamicQHandler(void * ro_ptr, char * eventId, void * rf_ptr, void * st_ptr, void * df_ptr) { QByteArray theHandler = QMetaObject::normalizedSignature(eventId); if (xhHash.contains(theHandler)) { int thir = xhHash.value(theHandler); return isetDynamicQHandler(ro_ptr, thir, rf_ptr, st_ptr, df_ptr); } return false; } bool DhQTreeWidgetItem::setDynamicQHandlerud(int udtyp, void * ro_ptr, int eventId, void * rf_ptr, void * st_ptr, void * df_ptr) { if ((udtyp < 0) || (udtyp > 2)) { return false; } return isetDynamicQHandlerud(ro_ptr, eventId, rf_ptr, st_ptr, df_ptr, udtyp); } bool DhQTreeWidgetItem::unSetDynamicQHandler(char * eventId) { QByteArray theHandler = QMetaObject::normalizedSignature(eventId); if (xhHash.contains(theHandler)) { int thir = xhHash.value(theHandler); return iunSetDynamicQHandler(thir); } return false; } bool DhQTreeWidgetItem::unSetDynamicQHandlerud(int udtyp, int eventId) { if ((udtyp < 0) || (udtyp > 2)) { return false; } return iunSetDynamicQHandlerud(eventId, udtyp); }
32.765217
130
0.666401
keera-studios
3d231a259d8b4b593c281eb60bdb2ef46b457ea1
49,307
cpp
C++
src/services/pcn-simplebridge/src/api/SimplebridgeApi.cpp
mbertrone/polycube
b35a6aa13273c000237d53c5f1bf286f12e4b9bd
[ "ECL-2.0", "Apache-2.0" ]
1
2020-07-16T04:49:29.000Z
2020-07-16T04:49:29.000Z
src/services/pcn-simplebridge/src/api/SimplebridgeApi.cpp
mbertrone/polycube
b35a6aa13273c000237d53c5f1bf286f12e4b9bd
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/services/pcn-simplebridge/src/api/SimplebridgeApi.cpp
mbertrone/polycube
b35a6aa13273c000237d53c5f1bf286f12e4b9bd
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/** * simplebridge API * Simple L2 Bridge Service * * OpenAPI spec version: 1.0.0 * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/polycube-network/swagger-codegen.git * branch polycube */ /* Do not edit this file manually */ #include "SimplebridgeApi.h" namespace io { namespace swagger { namespace server { namespace api { using namespace io::swagger::server::model; SimplebridgeApi::SimplebridgeApi() { setup_routes(); }; void SimplebridgeApi::control_handler(const HttpHandleRequest &request, HttpHandleResponse &response) { try { auto s = router.route(request, response); if (s == Rest::Router::Status::NotFound) { response.send(Http::Code::Not_Found); } } catch (const std::exception &e) { response.send(polycube::service::Http::Code::Bad_Request, e.what()); } } void SimplebridgeApi::setup_routes() { using namespace polycube::service::Rest; Routes::Post(router, base + ":name/", Routes::bind(&SimplebridgeApi::create_simplebridge_by_id_handler, this)); Routes::Post(router, base + ":name/fdb/", Routes::bind(&SimplebridgeApi::create_simplebridge_fdb_by_id_handler, this)); Routes::Post(router, base + ":name/fdb/entry/:address/", Routes::bind(&SimplebridgeApi::create_simplebridge_fdb_entry_by_id_handler, this)); Routes::Post(router, base + ":name/fdb/entry/", Routes::bind(&SimplebridgeApi::create_simplebridge_fdb_entry_list_by_id_handler, this)); Routes::Post(router, base + ":name/fdb/flush/", Routes::bind(&SimplebridgeApi::create_simplebridge_fdb_flush_by_id_handler, this)); Routes::Post(router, base + ":name/ports/:ports_name/", Routes::bind(&SimplebridgeApi::create_simplebridge_ports_by_id_handler, this)); Routes::Post(router, base + ":name/ports/", Routes::bind(&SimplebridgeApi::create_simplebridge_ports_list_by_id_handler, this)); Routes::Delete(router, base + ":name/", Routes::bind(&SimplebridgeApi::delete_simplebridge_by_id_handler, this)); Routes::Delete(router, base + ":name/fdb/", Routes::bind(&SimplebridgeApi::delete_simplebridge_fdb_by_id_handler, this)); Routes::Delete(router, base + ":name/fdb/entry/:address/", Routes::bind(&SimplebridgeApi::delete_simplebridge_fdb_entry_by_id_handler, this)); Routes::Delete(router, base + ":name/fdb/entry/", Routes::bind(&SimplebridgeApi::delete_simplebridge_fdb_entry_list_by_id_handler, this)); Routes::Delete(router, base + ":name/ports/:ports_name/", Routes::bind(&SimplebridgeApi::delete_simplebridge_ports_by_id_handler, this)); Routes::Delete(router, base + ":name/ports/", Routes::bind(&SimplebridgeApi::delete_simplebridge_ports_list_by_id_handler, this)); Routes::Get(router, base + ":name/", Routes::bind(&SimplebridgeApi::read_simplebridge_by_id_handler, this)); Routes::Get(router, base + ":name/fdb/aging-time/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_aging_time_by_id_handler, this)); Routes::Get(router, base + ":name/fdb/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_by_id_handler, this)); Routes::Get(router, base + ":name/fdb/entry/:address/age/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_entry_age_by_id_handler, this)); Routes::Get(router, base + ":name/fdb/entry/:address/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_entry_by_id_handler, this)); Routes::Get(router, base + ":name/fdb/entry/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_entry_list_by_id_handler, this)); Routes::Get(router, base + ":name/fdb/entry/:address/port/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_entry_port_by_id_handler, this)); Routes::Get(router, base + "", Routes::bind(&SimplebridgeApi::read_simplebridge_list_by_id_handler, this)); Routes::Get(router, base + ":name/loglevel/", Routes::bind(&SimplebridgeApi::read_simplebridge_loglevel_by_id_handler, this)); Routes::Get(router, base + ":name/ports/:ports_name/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_by_id_handler, this)); Routes::Get(router, base + ":name/ports/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_list_by_id_handler, this)); Routes::Get(router, base + ":name/ports/:ports_name/mac/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_mac_by_id_handler, this)); Routes::Get(router, base + ":name/ports/:ports_name/peer/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_peer_by_id_handler, this)); Routes::Get(router, base + ":name/ports/:ports_name/status/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_status_by_id_handler, this)); Routes::Get(router, base + ":name/ports/:ports_name/uuid/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_uuid_by_id_handler, this)); Routes::Get(router, base + ":name/type/", Routes::bind(&SimplebridgeApi::read_simplebridge_type_by_id_handler, this)); Routes::Get(router, base + ":name/uuid/", Routes::bind(&SimplebridgeApi::read_simplebridge_uuid_by_id_handler, this)); Routes::Put(router, base + ":name/", Routes::bind(&SimplebridgeApi::replace_simplebridge_by_id_handler, this)); Routes::Put(router, base + ":name/fdb/", Routes::bind(&SimplebridgeApi::replace_simplebridge_fdb_by_id_handler, this)); Routes::Put(router, base + ":name/fdb/entry/:address/", Routes::bind(&SimplebridgeApi::replace_simplebridge_fdb_entry_by_id_handler, this)); Routes::Put(router, base + ":name/fdb/entry/", Routes::bind(&SimplebridgeApi::replace_simplebridge_fdb_entry_list_by_id_handler, this)); Routes::Put(router, base + ":name/ports/:ports_name/", Routes::bind(&SimplebridgeApi::replace_simplebridge_ports_by_id_handler, this)); Routes::Put(router, base + ":name/ports/", Routes::bind(&SimplebridgeApi::replace_simplebridge_ports_list_by_id_handler, this)); Routes::Patch(router, base + ":name/", Routes::bind(&SimplebridgeApi::update_simplebridge_by_id_handler, this)); Routes::Patch(router, base + ":name/fdb/aging-time/", Routes::bind(&SimplebridgeApi::update_simplebridge_fdb_aging_time_by_id_handler, this)); Routes::Patch(router, base + ":name/fdb/", Routes::bind(&SimplebridgeApi::update_simplebridge_fdb_by_id_handler, this)); Routes::Patch(router, base + ":name/fdb/entry/:address/", Routes::bind(&SimplebridgeApi::update_simplebridge_fdb_entry_by_id_handler, this)); Routes::Patch(router, base + ":name/fdb/entry/", Routes::bind(&SimplebridgeApi::update_simplebridge_fdb_entry_list_by_id_handler, this)); Routes::Patch(router, base + ":name/fdb/entry/:address/port/", Routes::bind(&SimplebridgeApi::update_simplebridge_fdb_entry_port_by_id_handler, this)); Routes::Patch(router, base + "", Routes::bind(&SimplebridgeApi::update_simplebridge_list_by_id_handler, this)); Routes::Patch(router, base + ":name/loglevel/", Routes::bind(&SimplebridgeApi::update_simplebridge_loglevel_by_id_handler, this)); Routes::Patch(router, base + ":name/ports/:ports_name/", Routes::bind(&SimplebridgeApi::update_simplebridge_ports_by_id_handler, this)); Routes::Patch(router, base + ":name/ports/", Routes::bind(&SimplebridgeApi::update_simplebridge_ports_list_by_id_handler, this)); Routes::Patch(router, base + ":name/ports/:ports_name/peer/", Routes::bind(&SimplebridgeApi::update_simplebridge_ports_peer_by_id_handler, this)); Routes::Options(router, base + ":name/", Routes::bind(&SimplebridgeApi::read_simplebridge_by_id_help, this)); Routes::Options(router, base + ":name/fdb/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_by_id_help, this)); Routes::Options(router, base + ":name/fdb/entry/:address/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_entry_by_id_help, this)); Routes::Options(router, base + ":name/fdb/entry/", Routes::bind(&SimplebridgeApi::read_simplebridge_fdb_entry_list_by_id_help, this)); Routes::Options(router, base + "", Routes::bind(&SimplebridgeApi::read_simplebridge_list_by_id_help, this)); Routes::Options(router, base + ":name/ports/:ports_name/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_by_id_help, this)); Routes::Options(router, base + ":name/ports/", Routes::bind(&SimplebridgeApi::read_simplebridge_ports_list_by_id_help, this)); Routes::Options(router, base + ":name/fdb/flush/", Routes::bind(&SimplebridgeApi::create_simplebridge_fdb_flush_by_id_help, this)); } void SimplebridgeApi::create_simplebridge_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { // Getting the body param SimplebridgeJsonObject value; nlohmann::json request_body = nlohmann::json::parse(request.body()); value.fromJson(request_body); value.setName(name); value.validateMandatoryFields(); value.validateParams(); create_simplebridge_by_id(name, value); response.send(polycube::service::Http::Code::Created); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::create_simplebridge_fdb_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { // Getting the body param FdbJsonObject value; nlohmann::json request_body = nlohmann::json::parse(request.body()); value.fromJson(request_body); value.validateMandatoryFields(); value.validateParams(); create_simplebridge_fdb_by_id(name, value); response.send(polycube::service::Http::Code::Created); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::create_simplebridge_fdb_entry_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto address = request.param(":address").as<std::string>(); try { // Getting the body param FdbEntryJsonObject value; nlohmann::json request_body = nlohmann::json::parse(request.body()); value.fromJson(request_body); value.setAddress(address); value.validateMandatoryFields(); value.validateParams(); create_simplebridge_fdb_entry_by_id(name, address, value); response.send(polycube::service::Http::Code::Created); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::create_simplebridge_fdb_entry_list_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<FdbEntryJsonObject> value; try { nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { FdbEntryJsonObject a; a.fromJson(j); a.validateKeys(); a.validateMandatoryFields(); a.validateParams(); value.push_back(a); } create_simplebridge_fdb_entry_list_by_id(name, value); response.send(polycube::service::Http::Code::Created); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::create_simplebridge_fdb_flush_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { auto x = create_simplebridge_fdb_flush_by_id(name); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Created, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::create_simplebridge_ports_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); try { // Getting the body param PortsJsonObject value; nlohmann::json request_body = nlohmann::json::parse(request.body()); value.fromJson(request_body); value.setName(portsName); value.validateMandatoryFields(); value.validateParams(); create_simplebridge_ports_by_id(name, portsName, value); response.send(polycube::service::Http::Code::Created); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::create_simplebridge_ports_list_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<PortsJsonObject> value; try { nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsJsonObject a; a.fromJson(j); a.validateKeys(); a.validateMandatoryFields(); a.validateParams(); value.push_back(a); } create_simplebridge_ports_list_by_id(name, value); response.send(polycube::service::Http::Code::Created); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::delete_simplebridge_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { delete_simplebridge_by_id(name); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::delete_simplebridge_fdb_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { delete_simplebridge_fdb_by_id(name); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::delete_simplebridge_fdb_entry_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto address = request.param(":address").as<std::string>(); try { delete_simplebridge_fdb_entry_by_id(name, address); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::delete_simplebridge_fdb_entry_list_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { delete_simplebridge_fdb_entry_list_by_id(name); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::delete_simplebridge_ports_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); try { delete_simplebridge_ports_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::delete_simplebridge_ports_list_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { delete_simplebridge_ports_list_by_id(name); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { auto x = read_simplebridge_by_id(name); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_fdb_aging_time_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { auto x = read_simplebridge_fdb_aging_time_by_id(name); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_fdb_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { auto x = read_simplebridge_fdb_by_id(name); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_fdb_entry_age_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto address = request.param(":address").as<std::string>(); try { auto x = read_simplebridge_fdb_entry_age_by_id(name, address); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_fdb_entry_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto address = request.param(":address").as<std::string>(); try { auto x = read_simplebridge_fdb_entry_by_id(name, address); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_fdb_entry_list_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { auto x = read_simplebridge_fdb_entry_list_by_id(name); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_fdb_entry_port_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto address = request.param(":address").as<std::string>(); try { auto x = read_simplebridge_fdb_entry_port_by_id(name, address); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_list_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { try { auto x = read_simplebridge_list_by_id(); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_loglevel_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { auto x = read_simplebridge_loglevel_by_id(name); nlohmann::json response_body; response_body = SimplebridgeJsonObject::SimplebridgeLoglevelEnum_to_string(x); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_ports_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); try { auto x = read_simplebridge_ports_by_id(name, portsName); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_ports_list_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { auto x = read_simplebridge_ports_list_by_id(name); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_ports_mac_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); try { auto x = read_simplebridge_ports_mac_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_ports_peer_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); try { auto x = read_simplebridge_ports_peer_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_ports_status_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); try { auto x = read_simplebridge_ports_status_by_id(name, portsName); nlohmann::json response_body; response_body = PortsJsonObject::PortsStatusEnum_to_string(x); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_ports_uuid_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); try { auto x = read_simplebridge_ports_uuid_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_type_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { auto x = read_simplebridge_type_by_id(name); nlohmann::json response_body; response_body = SimplebridgeJsonObject::CubeType_to_string(x); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_uuid_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { auto x = read_simplebridge_uuid_by_id(name); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::replace_simplebridge_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { // Getting the body param SimplebridgeJsonObject value; nlohmann::json request_body = nlohmann::json::parse(request.body()); value.fromJson(request_body); value.setName(name); value.validateMandatoryFields(); value.validateParams(); replace_simplebridge_by_id(name, value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::replace_simplebridge_fdb_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { // Getting the body param FdbJsonObject value; nlohmann::json request_body = nlohmann::json::parse(request.body()); value.fromJson(request_body); value.validateMandatoryFields(); value.validateParams(); replace_simplebridge_fdb_by_id(name, value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::replace_simplebridge_fdb_entry_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto address = request.param(":address").as<std::string>(); try { // Getting the body param FdbEntryJsonObject value; nlohmann::json request_body = nlohmann::json::parse(request.body()); value.fromJson(request_body); value.setAddress(address); value.validateMandatoryFields(); value.validateParams(); replace_simplebridge_fdb_entry_by_id(name, address, value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::replace_simplebridge_fdb_entry_list_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<FdbEntryJsonObject> value; try { nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { FdbEntryJsonObject a; a.fromJson(j); a.validateKeys(); a.validateMandatoryFields(); a.validateParams(); value.push_back(a); } replace_simplebridge_fdb_entry_list_by_id(name, value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::replace_simplebridge_ports_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); try { // Getting the body param PortsJsonObject value; nlohmann::json request_body = nlohmann::json::parse(request.body()); value.fromJson(request_body); value.setName(portsName); value.validateMandatoryFields(); value.validateParams(); replace_simplebridge_ports_by_id(name, portsName, value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::replace_simplebridge_ports_list_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<PortsJsonObject> value; try { nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsJsonObject a; a.fromJson(j); a.validateKeys(); a.validateMandatoryFields(); a.validateParams(); value.push_back(a); } replace_simplebridge_ports_list_by_id(name, value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::update_simplebridge_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { // Getting the body param SimplebridgeJsonObject value; nlohmann::json request_body = nlohmann::json::parse(request.body()); value.fromJson(request_body); value.setName(name); value.validateParams(); update_simplebridge_by_id(name, value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::update_simplebridge_fdb_aging_time_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { // Getting the body param uint32_t value; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library value = request_body; update_simplebridge_fdb_aging_time_by_id(name, value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::update_simplebridge_fdb_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { // Getting the body param FdbJsonObject value; nlohmann::json request_body = nlohmann::json::parse(request.body()); value.fromJson(request_body); value.validateParams(); update_simplebridge_fdb_by_id(name, value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::update_simplebridge_fdb_entry_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto address = request.param(":address").as<std::string>(); try { // Getting the body param FdbEntryJsonObject value; nlohmann::json request_body = nlohmann::json::parse(request.body()); value.fromJson(request_body); value.setAddress(address); value.validateParams(); update_simplebridge_fdb_entry_by_id(name, address, value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::update_simplebridge_fdb_entry_list_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<FdbEntryJsonObject> value; try { nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { FdbEntryJsonObject a; a.fromJson(j); a.validateKeys(); a.validateParams(); value.push_back(a); } update_simplebridge_fdb_entry_list_by_id(name, value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::update_simplebridge_fdb_entry_port_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto address = request.param(":address").as<std::string>(); try { // Getting the body param std::string value; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library value = request_body; update_simplebridge_fdb_entry_port_by_id(name, address, value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::update_simplebridge_list_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the body param std::vector<SimplebridgeJsonObject> value; try { nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { SimplebridgeJsonObject a; a.fromJson(j); a.validateKeys(); a.validateParams(); value.push_back(a); } update_simplebridge_list_by_id(value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::update_simplebridge_loglevel_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); try { // Getting the body param SimplebridgeLoglevelEnum value_; nlohmann::json request_body = nlohmann::json::parse(request.body()); value_ = SimplebridgeJsonObject::string_to_SimplebridgeLoglevelEnum(request_body); update_simplebridge_loglevel_by_id(name, value_); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::update_simplebridge_ports_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); try { // Getting the body param PortsJsonObject value; nlohmann::json request_body = nlohmann::json::parse(request.body()); value.fromJson(request_body); value.setName(portsName); value.validateParams(); update_simplebridge_ports_by_id(name, portsName, value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::update_simplebridge_ports_list_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<PortsJsonObject> value; try { nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsJsonObject a; a.fromJson(j); a.validateKeys(); a.validateParams(); value.push_back(a); } update_simplebridge_ports_list_by_id(name, value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::update_simplebridge_ports_peer_by_id_handler( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); try { // Getting the body param std::string value; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library value = request_body; update_simplebridge_ports_peer_by_id(name, portsName, value); response.send(polycube::service::Http::Code::Ok); } catch(const std::exception &e) { response.send(polycube::service::Http::Code::Internal_Server_Error, e.what()); } } void SimplebridgeApi::read_simplebridge_by_id_help( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); switch (request.help_type()) { case HelpType::SHOW: val["params"] = SimplebridgeJsonObject::helpElements(); break; case HelpType::ADD: response.send(polycube::service::Http::Code::Bad_Request); return; case HelpType::SET: val["params"] = SimplebridgeJsonObject::helpWritableLeafs(); break; case HelpType::DEL: response.send(polycube::service::Http::Code::Bad_Request); return; case HelpType::NONE: val["commands"] = {"set", "show"}; val["params"] = SimplebridgeJsonObject::helpComplexElements(); val["actions"] = SimplebridgeJsonObject::helpActions(); break; case HelpType::NO_HELP: response.send(polycube::service::Http::Code::Bad_Request); return; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); } void SimplebridgeApi::read_simplebridge_fdb_by_id_help( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); switch (request.help_type()) { case HelpType::SHOW: val["params"] = FdbJsonObject::helpElements(); break; case HelpType::ADD: response.send(polycube::service::Http::Code::Bad_Request); return; case HelpType::SET: val["params"] = FdbJsonObject::helpWritableLeafs(); break; case HelpType::DEL: response.send(polycube::service::Http::Code::Bad_Request); return; case HelpType::NONE: val["commands"] = {"set", "show"}; val["params"] = FdbJsonObject::helpComplexElements(); val["actions"] = FdbJsonObject::helpActions(); break; case HelpType::NO_HELP: response.send(polycube::service::Http::Code::Bad_Request); return; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); } void SimplebridgeApi::read_simplebridge_fdb_entry_by_id_help( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto address = request.param(":address").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); switch (request.help_type()) { case HelpType::SHOW: val["params"] = FdbEntryJsonObject::helpElements(); break; case HelpType::ADD: response.send(polycube::service::Http::Code::Bad_Request); return; case HelpType::SET: val["params"] = FdbEntryJsonObject::helpWritableLeafs(); break; case HelpType::DEL: response.send(polycube::service::Http::Code::Bad_Request); return; case HelpType::NONE: val["commands"] = {"set", "show"}; val["params"] = FdbEntryJsonObject::helpComplexElements(); val["actions"] = FdbEntryJsonObject::helpActions(); break; case HelpType::NO_HELP: response.send(polycube::service::Http::Code::Bad_Request); return; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); } void SimplebridgeApi::read_simplebridge_fdb_entry_list_by_id_help( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); switch (request.help_type()) { case HelpType::SHOW: val["params"] = FdbEntryJsonObject::helpKeys(); val["elements"] = read_simplebridge_fdb_entry_list_by_id_get_list(name); break; case HelpType::ADD: val["params"] = FdbEntryJsonObject::helpKeys(); val["optional-params"] = FdbEntryJsonObject::helpWritableLeafs(); break; case HelpType::SET: response.send(polycube::service::Http::Code::Bad_Request); return; case HelpType::DEL: val["params"] = FdbEntryJsonObject::helpKeys(); val["elements"] = read_simplebridge_fdb_entry_list_by_id_get_list(name); break; case HelpType::NONE: val["commands"] = {"add", "del", "show"}; val["params"] = FdbEntryJsonObject::helpKeys(); val["elements"] = read_simplebridge_fdb_entry_list_by_id_get_list(name); break; case HelpType::NO_HELP: response.send(polycube::service::Http::Code::Bad_Request); return; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); } void SimplebridgeApi::read_simplebridge_list_by_id_help( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); switch (request.help_type()) { case HelpType::SHOW: val["params"] = SimplebridgeJsonObject::helpKeys(); val["elements"] = read_simplebridge_list_by_id_get_list(); break; case HelpType::ADD: val["params"] = SimplebridgeJsonObject::helpKeys(); val["optional-params"] = SimplebridgeJsonObject::helpWritableLeafs(); break; case HelpType::SET: response.send(polycube::service::Http::Code::Bad_Request); return; case HelpType::DEL: val["params"] = SimplebridgeJsonObject::helpKeys(); val["elements"] = read_simplebridge_list_by_id_get_list(); break; case HelpType::NONE: val["commands"] = {"add", "del", "show"}; val["params"] = SimplebridgeJsonObject::helpKeys(); val["elements"] = read_simplebridge_list_by_id_get_list(); break; case HelpType::NO_HELP: response.send(polycube::service::Http::Code::Bad_Request); return; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); } void SimplebridgeApi::read_simplebridge_ports_by_id_help( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); switch (request.help_type()) { case HelpType::SHOW: val["params"] = PortsJsonObject::helpElements(); break; case HelpType::ADD: response.send(polycube::service::Http::Code::Bad_Request); return; case HelpType::SET: val["params"] = PortsJsonObject::helpWritableLeafs(); break; case HelpType::DEL: response.send(polycube::service::Http::Code::Bad_Request); return; case HelpType::NONE: val["commands"] = {"set", "show"}; val["params"] = PortsJsonObject::helpComplexElements(); val["actions"] = PortsJsonObject::helpActions(); break; case HelpType::NO_HELP: response.send(polycube::service::Http::Code::Bad_Request); return; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); } void SimplebridgeApi::read_simplebridge_ports_list_by_id_help( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); switch (request.help_type()) { case HelpType::SHOW: val["params"] = PortsJsonObject::helpKeys(); val["elements"] = read_simplebridge_ports_list_by_id_get_list(name); break; case HelpType::ADD: val["params"] = PortsJsonObject::helpKeys(); val["optional-params"] = PortsJsonObject::helpWritableLeafs(); break; case HelpType::SET: response.send(polycube::service::Http::Code::Bad_Request); return; case HelpType::DEL: val["params"] = PortsJsonObject::helpKeys(); val["elements"] = read_simplebridge_ports_list_by_id_get_list(name); break; case HelpType::NONE: val["commands"] = {"add", "del", "show"}; val["params"] = PortsJsonObject::helpKeys(); val["elements"] = read_simplebridge_ports_list_by_id_get_list(name); break; case HelpType::NO_HELP: response.send(polycube::service::Http::Code::Bad_Request); return; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); } void SimplebridgeApi::create_simplebridge_fdb_flush_by_id_help( const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { nlohmann::json val = nlohmann::json::object(); response.send(polycube::service::Http::Code::Ok, val.dump(4)); } } } } }
36.0959
153
0.719614
mbertrone
3d23e625060917c46c7b12dd9ed6a76c4cc94211
647
cpp
C++
test_mdsplus.cpp
golfit/C-Mod
8132d1b1f21611d13f332a3770f5a94dfdecbb0a
[ "MIT" ]
null
null
null
test_mdsplus.cpp
golfit/C-Mod
8132d1b1f21611d13f332a3770f5a94dfdecbb0a
[ "MIT" ]
null
null
null
test_mdsplus.cpp
golfit/C-Mod
8132d1b1f21611d13f332a3770f5a94dfdecbb0a
[ "MIT" ]
null
null
null
//============================================================================ // Name : mode_survey.cpp // Author : Theodore Golfinopoulos // Version : // Copyright : 2018, All rights reserved, MIT License // Description : //============================================================================ #include <iostream> #include <stdio.h> #include <string.h> #include <mdslib.h> using namespace std; int main(int argc, char *argv[]) { //Local variables int socket; /* Connect to MDSplus */ socket=MdsConnect("alcdata.psfc.mit.edu"); //cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!! return 0; }
24.884615
78
0.48068
golfit
3d28a3b8e82ba15527a55961f00cf00fd63a9022
458
cpp
C++
src/output_writer/output_writer.cpp
kimkroener/NumSim
eb56fa90cb5717123d80a4b5711d2a5bcaf67a27
[ "MIT" ]
2
2021-12-09T23:20:23.000Z
2022-01-12T18:03:18.000Z
src/output_writer/output_writer.cpp
kimkroener/NumSim
eb56fa90cb5717123d80a4b5711d2a5bcaf67a27
[ "MIT" ]
31
2021-11-03T13:25:01.000Z
2021-12-09T12:27:08.000Z
src/output_writer/output_writer.cpp
kimkroener/NumSim
eb56fa90cb5717123d80a4b5711d2a5bcaf67a27
[ "MIT" ]
3
2021-11-09T13:41:08.000Z
2021-11-26T16:33:42.000Z
#include "output_writer/output_writer.h" #include <iostream> OutputWriter::OutputWriter(std::shared_ptr<Discretization> discretization, std::shared_ptr<Partitioning> partitioning) : discretization_(discretization), partitioning_(partitioning), fileNo_(0) { // create "out" subdirectory if it does not yet exist int returnValue = system("mkdir -p out"); if (returnValue != 0) std::cout << "Could not create subdirectory \"out\"." << std::endl; }
35.230769
118
0.740175
kimkroener
3d29352cacf853e6cc7ca59d6fb231c033b2b19b
138
cpp
C++
src/ComandList.cpp
Wason-Fok/Motor-command-generation
d85ef1e22b9ee8ba6b8025460563cd1a2c3f5c64
[ "Apache-2.0" ]
null
null
null
src/ComandList.cpp
Wason-Fok/Motor-command-generation
d85ef1e22b9ee8ba6b8025460563cd1a2c3f5c64
[ "Apache-2.0" ]
null
null
null
src/ComandList.cpp
Wason-Fok/Motor-command-generation
d85ef1e22b9ee8ba6b8025460563cd1a2c3f5c64
[ "Apache-2.0" ]
null
null
null
#include "ComandList.h" ComandList::ComandList(QWidget *parent) : QWidget(parent) { ui.setupUi(this); } ComandList::~ComandList() { }
11.5
39
0.702899
Wason-Fok
3d294aa09d23bf767e526fd94bd4c3ea7f7a88b7
4,489
cpp
C++
unit_tests/chustd_ut/File_Test.cpp
hadrien-psydk/pngoptimizer
d92946e63a57a4562af0feaa9e4cfd8628373777
[ "Zlib" ]
90
2016-08-23T00:13:04.000Z
2022-02-22T09:40:46.000Z
unit_tests/chustd_ut/File_Test.cpp
hadrien-psydk/pngoptimizer
d92946e63a57a4562af0feaa9e4cfd8628373777
[ "Zlib" ]
25
2016-09-01T07:09:03.000Z
2022-01-31T16:18:57.000Z
unit_tests/chustd_ut/File_Test.cpp
hadrien-psydk/pngoptimizer
d92946e63a57a4562af0feaa9e4cfd8628373777
[ "Zlib" ]
17
2017-05-03T17:49:25.000Z
2021-12-28T06:47:56.000Z
#include "stdafx.h" TEST(File, GetDrive) { String str0 = File::GetDrive("abc"); ASSERT_TRUE(str0.IsEmpty()); String str1 = File::GetDrive("/abc"); ASSERT_TRUE(str1.IsEmpty()); String str2 = File::GetDrive("\\abc"); ASSERT_TRUE(str2.IsEmpty()); String str3 = File::GetDrive("System:abc"); ASSERT_TRUE(str3 == "System"); String str4 = File::GetDrive("System:/abc"); ASSERT_TRUE(str4 == "System"); } TEST(File, Open) { String filePath = Process::GetCurrentDirectory(); filePath = FilePath::Combine(filePath, "testfile.bin"); File::Delete(filePath); // Ensure clean state // Write a new file { File file; ASSERT_TRUE( file.Open(filePath, File::modeWrite) ); ASSERT_TRUE( file.WriteStringUtf8("plop") ); file.Close(); } // Check content { File file; ASSERT_TRUE( file.Open(filePath, File::modeRead) ); char buf[100]; ASSERT_EQ( 4, file.Read(buf, sizeof(buf)) ); ASSERT_TRUE( memcmp(buf, "plop", 4) == 0 ); file.Close(); } // Reopen in write mode, the size should shrink to 0 upon Open { File file; ASSERT_TRUE( file.Open(filePath, File::modeWrite) ); ASSERT_TRUE( file.WriteStringUtf8("xy") ); file.Close(); } // Check content again { File file; ASSERT_TRUE( file.Open(filePath, File::modeRead) ); char buf[100]; ASSERT_EQ( 2, file.Read(buf, sizeof(buf)) ); ASSERT_TRUE( memcmp(buf, "xy", 2) == 0 ); file.Close(); } ASSERT_TRUE( File::Delete(filePath)); } TEST(File, Append) { String filePath = Process::GetCurrentDirectory(); filePath = FilePath::Combine(filePath, "testfile.txt"); if( File::Exists(filePath) ) { ASSERT_TRUE( File::Delete(filePath)); } File file0; for(int i = 0; i < 4; ++i) { ASSERT_TRUE( file0.Open(filePath, File::modeAppend) ); ASSERT_TRUE( file0.WriteString("A", TextEncoding::Windows1252()) == 1 ); file0.Close(); } uint32 nContent; ASSERT_TRUE( file0.Open(filePath) ); ASSERT_TRUE( file0.GetSize() == 4 ); ASSERT_TRUE( file0.Read32(nContent) ); // No more data uint8 buf[10]; ASSERT_EQ( 0, file0.Read(buf, 0) ); ASSERT_EQ( 0, file0.Read(buf, 10) ); file0.Close(); ASSERT_TRUE( nContent == MAKE32('A','A','A','A') ); ASSERT_TRUE( File::Delete(filePath) ); } TEST(File, LastWriteTime) { { File file; DateTime now = DateTime::GetNow(); ASSERT_TRUE( file.Open("test-file.txt", File::modeWrite) ); DateTime dt = file.GetLastWriteTime(); Duration dur = dt - now; ASSERT_TRUE( dur.GetTotalSeconds() < 10 ); file.Close(); } { File file; ASSERT_TRUE( file.Open("test-file2.txt", File::modeWrite) ); DateTime dt(1999, 9, 9, 0, 0, 42); ASSERT_TRUE( file.SetLastWriteTime(dt) ); file.Close(); ASSERT_TRUE( file.Open("test-file2.txt", File::modeRead) ); ASSERT_TRUE( dt == file.GetLastWriteTime() ); file.Close(); } ASSERT_TRUE( File::Delete("test-file.txt") ); ASSERT_TRUE( File::Delete("test-file2.txt") ); } TEST(File, Rename) { ASSERT_TRUE( File::WriteTextUtf8("test-file.txt", "rename") ); ASSERT_TRUE( File::Rename("test-file.txt", "test-file-renamed.txt") ); ASSERT_TRUE( File::Delete("test-file-renamed.txt") ); } TEST(File, SetByteOrder) { String filePath = "test-file.txt"; ByteArray bytes; bytes.Add(0x01); bytes.Add(0x02); bytes.Add(0x03); bytes.Add(0x04); ASSERT_TRUE( File::SetContent(filePath, bytes) ); File file; ASSERT_TRUE( file.Open(filePath, File::modeRead) ); uint32 val = 0; // By default, a file reads in big endian val = 0; ASSERT_TRUE( file.Read32(val) ); ASSERT_EQ( 0x01020304u, val ); ASSERT_TRUE( file.SetPosition(0) ); file.SetByteOrder(boLittleEndian); val = 0; ASSERT_TRUE( file.Read32(val) ); ASSERT_EQ( 0x04030201u, val ); // Back to big endian ASSERT_TRUE( file.SetPosition(0) ); file.SetByteOrder(boBigEndian); val = 0; ASSERT_TRUE( file.Read32(val) ); ASSERT_EQ( 0x01020304u, val ); file.Close(); File::Delete(filePath); } TEST(File, Attributes) { String filePath = "a.txt"; File::Delete(filePath); ASSERT_TRUE( File::WriteTextUtf8(filePath, "blah") ); bool isDir = false; bool readOnly = false; ASSERT_TRUE( File::GetFileAttributes(filePath, isDir, readOnly) ); ASSERT_FALSE( isDir ); ASSERT_FALSE( readOnly ); ASSERT_TRUE( File::SetReadOnly(filePath) ); ASSERT_TRUE( File::GetFileAttributes(filePath, isDir, readOnly) ); ASSERT_FALSE( isDir ); ASSERT_TRUE( readOnly ); ASSERT_TRUE( File::SetReadOnly(filePath, false) ); ASSERT_TRUE( File::GetFileAttributes(filePath, isDir, readOnly) ); ASSERT_FALSE( isDir ); ASSERT_FALSE( readOnly ); File::Delete(filePath); }
22.445
74
0.681889
hadrien-psydk
3d297601f2a9c6b177465239041f2c8df4023e0d
7,303
cpp
C++
src/opengl_class/VertexArray.cpp
hkzhugc/MyBreakOut
cbeb086195a5aa25113d6bd8d7ad30b96c385f2d
[ "MIT" ]
null
null
null
src/opengl_class/VertexArray.cpp
hkzhugc/MyBreakOut
cbeb086195a5aa25113d6bd8d7ad30b96c385f2d
[ "MIT" ]
null
null
null
src/opengl_class/VertexArray.cpp
hkzhugc/MyBreakOut
cbeb086195a5aa25113d6bd8d7ad30b96c385f2d
[ "MIT" ]
null
null
null
#include "VertexArray.h" using namespace std; static float quadVertices[] = { // vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates. // positions // texCoords -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f }; static float cubeVertices[] = { // back face -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // bottom-left 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, // top-right 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, // bottom-right 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, // top-right -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // bottom-left -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, // top-left // front face -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom-left 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, // bottom-right 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // top-right 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // top-right -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, // top-left -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom-left // left face -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-right -1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top-left -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-left -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-left -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // bottom-right -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-right // right face 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-left 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-right 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top-right 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-right 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-left 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // bottom-left // bottom face -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // top-right 1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, // top-left 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, // bottom-left 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, // bottom-left -1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, // bottom-right -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // top-right // top face -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top-left 1.0f, 1.0f , 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, // top-right 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top-left -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f // bottom-left }; VertexArray::VertexArray() { glCreateVertexArrays(1, &VAO_ID); VBO_ID = 0; EBO_ID = 0; num_indices = 0; num_vertices = 0; } VertexArray::~VertexArray() { glDeleteVertexArrays(1, &VAO_ID); } void VertexArray::draw() { bind(); if (VBO_ID && !EBO_ID) // only have vertex buffer { glDrawArrays(GL_TRIANGLES, 0, num_vertices); } else if (VBO_ID && EBO_ID) { glDrawElements(GL_TRIANGLE_STRIP, num_indices, GL_UNSIGNED_INT, (void *)0); } unbind(); } void VertexArray::drawInstance(size_t instance_num) { bind(); if (VBO_ID && !EBO_ID) // only have vertex buffer { glDrawArraysInstanced(GL_TRIANGLES, 0, num_vertices, instance_num); } else if (VBO_ID && EBO_ID) { glDrawElementsInstanced(GL_TRIANGLES, num_indices, GL_INT, (void *)0, instance_num); } unbind(); } void VertexArray::initAsQuad() { if (EBO_ID || VBO_ID) return; genArrayBuffer( sizeof(quadVertices), quadVertices, VertexAttributeConfig::genConfig<float, GL_FLOAT>({2, 2}) ); } void VertexArray::initAsCube() { if (EBO_ID || VBO_ID) return; genArrayBuffer( sizeof(cubeVertices), cubeVertices, VertexAttributeConfig::genConfig<float, GL_FLOAT>({ 3, 3, 2 }) ); } void VertexArray::initAsSphere(size_t segmentX, size_t segmentY) { if (EBO_ID || VBO_ID) return; vector<glm::vec3> positions; vector<glm::vec3> normals; vector<glm::vec2> uvs; vector<size_t> indices; const float PI = 3.14159265359; // calculate pos and uv for (size_t i = 0; i <= segmentY; i++) { for (size_t j = 0; j <= segmentX; j++) { float x = (float)j / (float)segmentX; float y = (float)i / (float)segmentY; float theta = y * PI; float phi = x * 2 * PI; glm::vec3 pos; pos.x = cos(phi) * sin(theta); pos.y = cos(theta); pos.z = sin(phi) * sin(theta); positions.push_back(pos); normals.push_back(pos); uvs.push_back(glm::vec2(x, y)); } } // calculate indices for (size_t y = 0; y < segmentY; y++) { if (y % 2 == 0) { for (int x = 0; x <= segmentX; x++) { indices.push_back( y * (segmentX + 1) + x); indices.push_back((y + 1) * (segmentX + 1) + x); } } else { for (int x = segmentX; x >= 0; x--) { indices.push_back((y + 1) * (segmentX + 1) + x); indices.push_back(y * (segmentX + 1) + x); } } } num_vertices = positions.size(); num_indices = indices.size(); size_t position_size, normal_size, uv_size, index_size; position_size = positions.size() * sizeof(glm::vec3); normal_size = normals.size() * sizeof(glm::vec3); uv_size = uvs.size() * sizeof(glm::vec2); index_size = indices.size() * sizeof(size_t); bind(); glGenBuffers(1, &VBO_ID); glBindBuffer(GL_ARRAY_BUFFER, VBO_ID); glBufferData(GL_ARRAY_BUFFER, position_size + normal_size + uv_size, nullptr, GL_STATIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0, position_size, positions.data()); glBufferSubData(GL_ARRAY_BUFFER, position_size, normal_size, normals.data()); glBufferSubData(GL_ARRAY_BUFFER, position_size + normal_size, uv_size, uvs.data()); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), (void *)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), (void *)position_size); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), (void *)(position_size + normal_size)); glGenBuffers(1, &EBO_ID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO_ID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_size, indices.data(), GL_STATIC_DRAW); unbind(); } void VertexArray::genArrayBuffer(size_t size, void* data, const std::vector<VertexAttributeConfig>& configs) { assert(configs.size()); glCreateBuffers(1, &VBO_ID); glNamedBufferStorage(VBO_ID, size, data, GL_DYNAMIC_STORAGE_BIT); glVertexArrayVertexBuffer(VAO_ID, 0, VBO_ID, 0, configs[0].stride); for (int i = 0; i < configs.size(); i++) { auto& config = configs[i]; glEnableVertexArrayAttrib(VAO_ID, i); glVertexArrayAttribFormat(VAO_ID, i, config.size, config.type, config.normalized, (size_t)(config.pointer)); glVertexArrayAttribBinding(VAO_ID, i, 0); } if (configs.size()) num_vertices = size / configs[0].stride; } void VertexArray::genElementBuffer() { // TODO : glCreateBuffers(1, &EBO_ID); }
32.030702
126
0.606737
hkzhugc
3d2d90b556cf380b03ecc3f04b4e1bc43112a254
524
cpp
C++
AtCoder/abc028/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
AtCoder/abc028/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
1
2021-10-19T08:47:23.000Z
2022-03-07T05:23:56.000Z
AtCoder/abc028/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <algorithm> #include <vector> using namespace std; int main() { string s; cin >> s; vector<int> v(6, 0); for (int i = 0; i < s.length(); i++) { if (s[i] == 'A') v[0]++; if (s[i] == 'B') v[1]++; if (s[i] == 'C') v[2]++; if (s[i] == 'D') v[3]++; if (s[i] == 'E') v[4]++; if (s[i] == 'F') v[5]++; } for (int i = 0; i < 6; i++) { if (i == 5) cout << v[i] << endl; else cout << v[i] << " "; } }
23.818182
42
0.375954
H-Tatsuhiro
3d3144e9ccc4e484e2d835b7502f739cccc29e8c
4,481
hpp
C++
src/common/KokkosKernels_SparseUtils_cusparse.hpp
dialecticDolt/kokkos-kernels
00189c0be23a70979aeaa162f0abd4c0e4d1c479
[ "BSD-3-Clause" ]
156
2017-03-01T23:38:10.000Z
2022-03-27T21:28:03.000Z
src/common/KokkosKernels_SparseUtils_cusparse.hpp
dialecticDolt/kokkos-kernels
00189c0be23a70979aeaa162f0abd4c0e4d1c479
[ "BSD-3-Clause" ]
1,257
2017-03-03T15:25:16.000Z
2022-03-31T19:46:09.000Z
src/common/KokkosKernels_SparseUtils_cusparse.hpp
dialecticDolt/kokkos-kernels
00189c0be23a70979aeaa162f0abd4c0e4d1c479
[ "BSD-3-Clause" ]
76
2017-03-01T17:03:59.000Z
2022-03-03T21:04:41.000Z
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE // 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. // // Questions? Contact Siva Rajamanickam (srajama@sandia.gov) // // ************************************************************************ //@HEADER */ #ifndef _KOKKOSKERNELS_SPARSEUTILS_CUSPARSE_HPP #define _KOKKOSKERNELS_SPARSEUTILS_CUSPARSE_HPP #ifdef KOKKOSKERNELS_ENABLE_TPL_CUSPARSE #include "cusparse.h" namespace KokkosSparse { namespace Impl { inline void cusparse_internal_error_throw(cusparseStatus_t cusparseStatus, const char *name, const char *file, const int line) { std::ostringstream out; #if defined(CUSPARSE_VERSION) && (10300 <= CUSPARSE_VERSION) out << name << " error( " << cusparseGetErrorName(cusparseStatus) << "): " << cusparseGetErrorString(cusparseStatus); #else out << name << " error( "; switch(cusparseStatus) { case CUSPARSE_STATUS_NOT_INITIALIZED: out << "CUSPARSE_STATUS_NOT_INITIALIZED): cusparse handle was not created correctly."; break; case CUSPARSE_STATUS_ALLOC_FAILED: out << "CUSPARSE_STATUS_ALLOC_FAILED): you might tried to allocate too much memory"; break; case CUSPARSE_STATUS_INVALID_VALUE: out << "CUSPARSE_STATUS_INVALID_VALUE)"; break; case CUSPARSE_STATUS_ARCH_MISMATCH: out << "CUSPARSE_STATUS_ARCH_MISMATCH)"; break; case CUSPARSE_STATUS_MAPPING_ERROR: out << "CUSPARSE_STATUS_MAPPING_ERROR)"; break; case CUSPARSE_STATUS_EXECUTION_FAILED: out << "CUSPARSE_STATUS_EXECUTION_FAILED)"; break; case CUSPARSE_STATUS_INTERNAL_ERROR: out << "CUSPARSE_STATUS_INTERNAL_ERROR)"; break; case CUSPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED: out << "CUSPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED)"; break; case CUSPARSE_STATUS_ZERO_PIVOT: out << "CUSPARSE_STATUS_ZERO_PIVOT)"; break; default: out << "unrecognized error code): this is bad!"; break; } #endif // CUSPARSE_VERSION if (file) { out << " " << file << ":" << line; } throw std::runtime_error(out.str()); } inline void cusparse_internal_safe_call(cusparseStatus_t cusparseStatus, const char* name, const char* file = nullptr, const int line = 0) { if (CUSPARSE_STATUS_SUCCESS != cusparseStatus) { cusparse_internal_error_throw(cusparseStatus, name, file, line); } } // The macro below defines is the public interface for the safe cusparse calls. // The functions themselves are protected by impl namespace. #define KOKKOS_CUSPARSE_SAFE_CALL(call) \ KokkosSparse::Impl::cusparse_internal_safe_call(call, #call, __FILE__, __LINE__) } // namespace Impl } // namespace KokkosSparse #endif // KOKKOSKERNELS_ENABLE_TPL_CUSPARSE #endif // _KOKKOSKERNELS_SPARSEUTILS_CUSPARSE_HPP
35.563492
90
0.714126
dialecticDolt
3d333ab8aabbda7ce88b3270521ab4ca68e61a96
1,408
cpp
C++
lib/common/src/Logging.cpp
CodeRancher/offcenter_trading
68526fdc0f27d611f748b2fa20f49e743d3ee5eb
[ "Apache-2.0" ]
null
null
null
lib/common/src/Logging.cpp
CodeRancher/offcenter_trading
68526fdc0f27d611f748b2fa20f49e743d3ee5eb
[ "Apache-2.0" ]
4
2021-12-27T17:56:21.000Z
2022-01-05T00:05:01.000Z
lib/common/src/Logging.cpp
CodeRancher/offcenter_trading
68526fdc0f27d611f748b2fa20f49e743d3ee5eb
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Scott Brauer * * Licensed under the Apache License, Version 2.0 (the ); * 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 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 Logging.cpp * @author Scott Brauer * @date 09-23-2021 */ #include "offcenter/trading/common/Logging.hpp" namespace offcenter { namespace trading { namespace common { namespace logging { /** * Calculates the logger ID for broker, brokerSource, instrument, and granularity. * * @param broker Broker * @param brokerSource Broker data source * @param instrument Instrument * @param granularity Granularity * * @return Combined string of all elements */ const std::string loggerID( const std::string& broker, const std::string& brokerSource, const std::string& instrument, const std::string& granularity) { return broker + "." + brokerSource + "." + instrument + "." + granularity; } } /* namespace logging */ } /* namespace common */ } /* namespace trading */ } /* namespace offcenter */
26.566038
82
0.713068
CodeRancher
3d371a9c9533f5ae8fce1b422670d3e146bb7f84
11,764
cpp
C++
src/plugins/imagefilter_texturelayer/filter.cpp
deiflou/anitools
9728f7569b59aa261dcaffc8332a1b02c2cd5fbe
[ "MIT" ]
6
2015-05-07T18:44:34.000Z
2018-12-12T15:57:40.000Z
src/plugins/imagefilter_texturelayer/filter.cpp
deiflou/anitools
9728f7569b59aa261dcaffc8332a1b02c2cd5fbe
[ "MIT" ]
null
null
null
src/plugins/imagefilter_texturelayer/filter.cpp
deiflou/anitools
9728f7569b59aa261dcaffc8332a1b02c2cd5fbe
[ "MIT" ]
2
2019-03-18T05:31:34.000Z
2019-11-19T21:17:54.000Z
// // MIT License // // Copyright (c) Deif Lou // // 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 <QRegularExpression> #include <QPainter> #include "filter.h" #include "filterwidget.h" #include <imgproc/util.h> #include <imgproc/pixelblending.h> #include <imgproc/lut.h> Filter::Filter() : mImage(), mPosition(Front), mColorCompositionMode(ColorCompositionMode_Normal), mOpacity(100) { } Filter::~Filter() { } ImageFilter *Filter::clone() { Filter * f = new Filter(); f->mImage = mImage; f->mPosition = mPosition; f->mColorCompositionMode = mColorCompositionMode; f->mOpacity = mOpacity; f->mTransformations = mTransformations; f->mBypasses = mBypasses; return f; } extern "C" QHash<QString, QString> getIBPPluginInfo(); QHash<QString, QString> Filter::info() { return getIBPPluginInfo(); } QImage Filter::process(const QImage &inputImage) { if (inputImage.isNull() || inputImage.format() != QImage::Format_ARGB32) return inputImage; // Create texture QImage texture(inputImage.width(), inputImage.height(), QImage::Format_ARGB32); QBrush brush(mImage); QTransform tfm; QPainter p(&texture); for (int i = mTransformations.size() - 1; i >= 0; i--) { if (mTransformations.at(i).type == Translation) tfm.translate(mTransformations.at(i).x, mTransformations.at(i).y); else if (mTransformations.at(i).type == Scaling) tfm.scale(mTransformations.at(i).x / 100., mTransformations.at(i).y / 100.); else if (mTransformations.at(i).type == Rotation) tfm.rotate(-mTransformations.at(i).z); else tfm.shear(mTransformations.at(i).x / 100., mTransformations.at(i).y / 100.); } tfm.translate(-mImage.width() / 2, -mImage.height() / 2); brush.setTransform(tfm); p.setRenderHint(QPainter::Antialiasing); p.setRenderHint(QPainter::SmoothPixmapTransform); p.setBrushOrigin(inputImage.width() >> 1, inputImage.height() >> 1); p.fillRect(texture.rect(), brush); // Paint Texture QImage i = QImage(inputImage.width(), inputImage.height(), QImage::Format_ARGB32); register BGRA * src = (BGRA *)texture.bits(), * dst = (BGRA *)inputImage.bits(), * blend = (BGRA *)i.bits(); register int totalPixels = i.width() * i.height(); const int opacity = qRound(mOpacity * 255 / 100.); if (mPosition == Front) { while (totalPixels--) { src->a = lut01[src->a][opacity]; blendColors[mColorCompositionMode](*src, *dst, *blend); src++; dst++; blend++; } } else if (mPosition == Inside) { if (mColorCompositionMode == ColorCompositionMode_Normal) { while (totalPixels--) { src->a = lut01[src->a][opacity]; blendSourceAtopDestination(*src, *dst, *blend); src++; dst++; blend++; } } else { while (totalPixels--) { src->a = lut01[src->a][opacity]; blendColors[mColorCompositionMode](*src, *dst, *blend); blendSourceAtopDestination(*blend, *dst, *blend); src++; dst++; blend++; } } } else { while (totalPixels--) { src->a = lut01[src->a][opacity]; blendDestinationOverSource(*src, *dst, *blend); src++; dst++; blend++; } } return i; } bool Filter::loadParameters(QSettings &s) { QVariant v; QString positionStr; QString colorCompositionModeStr; QImage image; Position position; ColorCompositionMode colorCompositionMode; int opacity; QString tfmStr; QStringList tfmList1, tfmList2; QList<AffineTransformation> transformations; QList<bool> bypasses; AffineTransformation transformation; bool bypass; bool ok; v = s.value("image", QImage()); if (!v.isValid() || !v.canConvert<QImage>()) image = QImage(); else image = v.value<QImage>(); positionStr = s.value("position", "front").toString(); if (positionStr == "front") position = Front; else if (positionStr == "behind") position = Behind; else if (positionStr == "inside") position = Inside; else return false; colorCompositionModeStr = s.value("colorcompositionmode", "normal").toString(); colorCompositionMode = colorCompositionModeStringToEnum(colorCompositionModeStr); if (colorCompositionMode == ColorCompositionMode_Unsupported) return false; opacity = s.value("opacity", 100).toInt(&ok); if (!ok || opacity < 0 || opacity > 100) return false; tfmStr = s.value("geometrictransformations").toString(); tfmList1 = tfmStr.split(QRegularExpression("\\s*,\\s*"), QString::SkipEmptyParts); for (int i = 0; i < tfmList1.size(); i++) { tfmList2 = tfmList1.at(i).split(QRegularExpression("\\s+"), QString::SkipEmptyParts); if (tfmList2.size() != 3 && tfmList2.size() != 4) return false; if (tfmList2.at(0) == "translation") transformation.type = Translation; else if (tfmList2.at(0) == "scaling") transformation.type = Scaling; else if (tfmList2.at(0) == "rotation") transformation.type = Rotation; else if (tfmList2.at(0) == "shearing") transformation.type = Shearing; else return false; if (tfmList2.at(1) == "false") bypass = false; else if (tfmList2.at(1) == "true") bypass = true; else return false; if (tfmList2.size() == 3) { transformation.z = tfmList2.at(2).toDouble(&ok); if (!ok) return false; transformation.x = transformation.y = 0; } else { transformation.x = tfmList2.at(2).toDouble(&ok); if (!ok) return false; transformation.y = tfmList2.at(3).toDouble(&ok); if (!ok) return false; transformation.z = 0; } transformations.append(transformation); bypasses.append(bypass); } setImage(image); setPosition(position); setColorCompositionMode(colorCompositionMode); setOpacity(opacity); setTransformations(transformations, bypasses); return true; } bool Filter::saveParameters(QSettings &s) { QStringList tfms; if (mTransformations.size() > 0) { AffineTransformation t; for (int i = 0; i < mTransformations.size(); i++) { t = mTransformations.at(i); if (t.type == Translation) tfms.append(QString("translation ") + (mBypasses.at(i) ? "true " : "false ") + QString::number(t.x, 'f', 2) + " " + QString::number(t.y, 'f', 2)); else if (t.type == Scaling) tfms.append(QString("scaling ") + (mBypasses.at(i) ? "true " : "false ") + QString::number(t.x, 'f', 2) + " " + QString::number(t.y, 'f', 2)); else if (t.type == Rotation) tfms.append(QString("rotation ") + (mBypasses.at(i) ? "true " : "false ") + QString::number(t.z, 'f', 2)); else tfms.append(QString("shearing ") + (mBypasses.at(i) ? "true " : "false ") + QString::number(t.x, 'f', 2) + " " + QString::number(t.y, 'f', 2)); } } s.setValue("image", mImage); s.setValue("position", mPosition == Front ? "front" : (mPosition == Behind ? "behind" : "inside")); s.setValue("colorcompositionmode", colorCompositionModeEnumToString(mColorCompositionMode)); s.setValue("opacity", mOpacity); s.setValue("geometrictransformations", tfms.join(", ")); return true; } QWidget *Filter::widget(QWidget *parent) { FilterWidget * fw = new FilterWidget(parent); fw->setImage(mImage); fw->setPosition(mPosition); fw->setColorCompositionMode(mColorCompositionMode); fw->setOpacity(mOpacity); fw->setTransformations(mTransformations, mBypasses); connect(this, SIGNAL(imageChanged(QImage)), fw, SLOT(setImage(QImage))); connect(this, SIGNAL(positionChanged(Filter::Position)), fw, SLOT(setPosition(Filter::Position))); connect(this, SIGNAL(colorCompositionModeChanged(ColorCompositionMode)), fw, SLOT(setColorCompositionMode(ColorCompositionMode))); connect(this, SIGNAL(opacityChanged(int)), fw, SLOT(setOpacity(int))); connect(this, SIGNAL(transformationsChanged(QList<AffineTransformation>,QList<bool>)), fw, SLOT(setTransformations(QList<AffineTransformation>,QList<bool>))); connect(fw, SIGNAL(imageChanged(QImage)), this, SLOT(setImage(QImage))); connect(fw, SIGNAL(positionChanged(Filter::Position)), this, SLOT(setPosition(Filter::Position))); connect(fw, SIGNAL(colorCompositionModeChanged(ColorCompositionMode)), this, SLOT(setColorCompositionMode(ColorCompositionMode))); connect(fw, SIGNAL(opacityChanged(int)), this, SLOT(setOpacity(int))); connect(fw, SIGNAL(transformationsChanged(QList<AffineTransformation>,QList<bool>)), this, SLOT(setTransformations(QList<AffineTransformation>,QList<bool>))); return fw; } void Filter::setImage(const QImage &i) { if (i == mImage) return; mImage = i; emit imageChanged(i); emit parametersChanged(); } void Filter::setPosition(Filter::Position v) { if (v == mPosition) return; mPosition = v; emit positionChanged(v); emit parametersChanged(); } void Filter::setColorCompositionMode(ColorCompositionMode v) { if (v == mColorCompositionMode) return; mColorCompositionMode = v; emit colorCompositionModeChanged(v); emit parametersChanged(); } void Filter::setOpacity(int v) { if (v == mOpacity) return; mOpacity = v; emit opacityChanged(v); emit parametersChanged(); } void Filter::setTransformations(const QList<AffineTransformation> &t, const QList<bool> &b) { if (t == mTransformations && b == mBypasses) return; mTransformations = t; mBypasses = b; emit transformationsChanged(t, b); emit parametersChanged(); }
32.768802
112
0.600221
deiflou
3d3a96804f5a336b976e1e6e51c866f9c83bd1c7
1,857
cpp
C++
src/components/net/fabric/unit_test/patience.cpp
fQuinzan/mcas
efaf438eb20cffa18b13f176c74a2b3153f89c07
[ "Apache-2.0" ]
60
2020-04-28T08:15:07.000Z
2022-03-08T10:35:15.000Z
src/components/net/fabric/unit_test/patience.cpp
fQuinzan/mcas
efaf438eb20cffa18b13f176c74a2b3153f89c07
[ "Apache-2.0" ]
66
2020-09-03T23:40:48.000Z
2022-03-07T20:34:52.000Z
src/components/net/fabric/unit_test/patience.cpp
fQuinzan/mcas
efaf438eb20cffa18b13f176c74a2b3153f89c07
[ "Apache-2.0" ]
13
2019-11-02T06:30:36.000Z
2022-01-26T01:56:42.000Z
/* Copyright [2017-2019] [IBM Corporation] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "patience.h" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" #pragma GCC diagnostic ignored "-Wsign-compare" #include <gtest/gtest.h> #pragma GCC diagnostic pop #include <api/fabric_itf.h> /* IFabric, IFabric_client, IFabric_client_grouped */ #include <system_error> component::IFabric_client * open_connection_patiently(component::IFabric_endpoint_unconnected_client *aep_) { component::IFabric_client *cnxn = nullptr; int try_count = 0; while ( ! cnxn ) { try { cnxn = aep_->make_open_client(); } catch ( std::system_error &e ) { if ( e.code().value() != ECONNREFUSED ) { throw; } } ++try_count; } EXPECT_LT(0U, cnxn->max_message_size()); return cnxn; } component::IFabric_client_grouped *open_connection_grouped_patiently(component::IFabric_endpoint_unconnected_client *aep_) { component::IFabric_client_grouped *cnxn = nullptr; int try_count = 0; while ( ! cnxn ) { try { cnxn = aep_->make_open_client_grouped(); } catch ( std::system_error &e ) { if ( e.code().value() != ECONNREFUSED ) { throw; } } ++try_count; } EXPECT_LT(0U, cnxn->max_message_size()); return cnxn; }
26.913043
122
0.682822
fQuinzan
3d3aa0927631e336549d23b7193c4de50b200666
1,217
cpp
C++
goodEatsSystem/src/Chef.cpp
PashaBarahimi/GoodEatsWeb
a8c173298323b072c973a8218bb63485fc1aba33
[ "MIT" ]
null
null
null
goodEatsSystem/src/Chef.cpp
PashaBarahimi/GoodEatsWeb
a8c173298323b072c973a8218bb63485fc1aba33
[ "MIT" ]
null
null
null
goodEatsSystem/src/Chef.cpp
PashaBarahimi/GoodEatsWeb
a8c173298323b072c973a8218bb63485fc1aba33
[ "MIT" ]
null
null
null
#include "include/Chef.hpp" #include "include/AlgorithmSideFunctions.hpp" Chef::Chef(const std::string& username, const std::string& password) : username_(username), password_(password) { } void Chef::addRecipe(Recipe* recipe) { recipes_.insert(std::upper_bound(recipes_.begin(), recipes_.end(), recipe, compareByName<Recipe*>), recipe); } void Chef::removeRecipe(Recipe* recipe) { for (unsigned i = 0; i < recipes_.size(); i++) if (recipe == recipes_[i]) { recipes_.erase(recipes_.begin() + i); return; } } bool Chef::doesRecipeExist(Recipe* recipe) const { for (Recipe* item : recipes_) if (recipe == item) return true; return false; } double Chef::getRatings() const { double sum = 0; int counter = 0; for (Recipe* recipe : recipes_) if (static_cast<int>(recipe->getRating()) != 0) { sum += recipe->getRating(); counter++; } if (counter == 0) return 0; sum /= counter; double tenXRate = 10 * sum; tenXRate = ceil(tenXRate); return tenXRate / 10; } std::vector<Recipe::InterfaceRecipe> Chef::getInterfaceRecipes() const { std::vector<Recipe::InterfaceRecipe> recipes; for (Recipe* rec : recipes_) recipes.push_back(rec->getInterfaceRecipe()); return recipes; }
22.537037
115
0.685292
PashaBarahimi
3d3c726d1b927ab53bf7a6f18573d4f41db9fc1b
2,183
cpp
C++
practice/sample2.cpp
xenowits/cp
963b3c7df65b5328d5ce5ef894a46691afefb98c
[ "MIT" ]
null
null
null
practice/sample2.cpp
xenowits/cp
963b3c7df65b5328d5ce5ef894a46691afefb98c
[ "MIT" ]
null
null
null
practice/sample2.cpp
xenowits/cp
963b3c7df65b5328d5ce5ef894a46691afefb98c
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define fori(i,a,b) for (long long int i = a; i <= b ; ++i) #define ford(i,a,b) for(long long int i = a;i >= b ; --i) #define mk make_pair #define mod 1000000007 #define pb push_back #define ll long long #define ld long double #define MAXN (ll)1e6+5 #define rnd mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().cnt()) #define pi pair<long long int,long long int> #define sc second #define fs first int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ll n, q, l, r; cin >> n; vector<ll> x(n+1,0), y(n+1,0); vector<ll> preX(n+1,0), preY(n+1,0); vector<ll> preX1(n+1,0), preY1(n+1,0); fori(i,1,n) { cin >> x[i] >> y[i]; } fori(i,1,n) { if (i == n) preX[i] = (x[i]*y[1])%mod; else preX[i] = (x[i]*y[i+1])%mod; } fori(i,1,n) { if (i == n) preY[i] = (x[1]*y[i])%mod; else preY[i] = (x[i+1]*y[i])%mod; } fori(i,1,n) { preX1[i] = (preX1[i-1]+preX[i])%mod; // cout << i << " preX1 " << preX1[i] << endl; } fori(i,1,n) { preY1[i] = (preY1[i-1]+preY[i])%mod; // cout << i << " preY1 " << preY1[i] << endl; } //total area of the polygon ll total = abs(preX1[n] - preY1[n]); total = total%mod; //cout << total << endl; cin >> q; while (q--) { cin >> l >> r; if (l > r) { swap(l,r); //cout << r-1 << " so " << l << " " << preX1[r-1] << " " << preX1[l-1] << endl; ll sum1 = ((preX1[r-1]-preX1[l-1])%mod + x[r]*y[l])%mod; ll sum2 = ((preY1[r-1]-preY1[l-1])%mod + y[r]*x[l])%mod; //cout << sum1 << " is sum1 and the next is sum2 " << sum2 << endl; ll sum3 = abs(sum1 - sum2)%mod; cout << (total - sum3)%mod << endl; } else if (l < r) { //cout << r-1 << " so " << l << " " << preX1[r-1] << " " << preX1[l-1] << endl; ll sum1 = ((preX1[r-1]-preX1[l-1])%mod + x[r]*y[l])%mod; ll sum2 = ((preY1[r-1]-preY1[l-1])%mod + y[r]*x[l])%mod; //cout << sum1 << " is sum1 and the next is sum2 " << sum2 << endl; ll sum3 = abs(sum1 - sum2)%mod; cout << sum3 << endl; } else { cout << 0 << endl; } } return 0; }
24.806818
89
0.496106
xenowits
3d3cbcdfe9fa044b30509207118e69e958eb93f1
1,714
cpp
C++
Array/1313. Decompress Run-Length Encoded List.cpp
KardseT/LeetCode
f020cff23f7d3ef8599b9e72bf5c2095bf069d01
[ "MIT" ]
null
null
null
Array/1313. Decompress Run-Length Encoded List.cpp
KardseT/LeetCode
f020cff23f7d3ef8599b9e72bf5c2095bf069d01
[ "MIT" ]
null
null
null
Array/1313. Decompress Run-Length Encoded List.cpp
KardseT/LeetCode
f020cff23f7d3ef8599b9e72bf5c2095bf069d01
[ "MIT" ]
null
null
null
// 1313. Decompress Run-Length Encoded List // Easy // We are given a list nums of integers representing a list compressed with run-length encoding. // Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. // Return the decompressed list. // Example 1: // Input: nums = [1,2,3,4] // Output: [2,4,4,4] // Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2]. // The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4]. // At the end the concatenation [2] + [4,4,4] is [2,4,4,4]. // Example 2: // Input: nums = [1,1,2,3] // Output: [1,3,3] // Constraints: // 2 <= nums.length <= 100 // nums.length % 2 == 0 // 1 <= nums[i] <= 100 class Solution { public: vector<int> decompressRLElist(vector<int>& nums) { vector<int> output; for (int i=0; i < nums.size(); i+=2) { for (int j=0; j < nums[i]; ++j) output.push_back(nums[i+1]); } return output; } }; // Runtime: 44 ms, faster than 78.12% of C++ online submissions for Decompress Run-Length Encoded List. // Memory Usage: 8.4 MB, less than 100.00% of C++ online submissions for Decompress Run-Length Encoded List. class Solution { public: vector<int> decompressRLElist(vector<int>& nums) { vector<int> output; for (int i=0; i < nums.size(); i+=2) output.insert(output.end(), nums[i], nums[i+1]); return output; } }; // Related Topics // Array
27.645161
266
0.614936
KardseT
3d3dc327947482dc6dc8fa038371a9792e962493
10,542
cpp
C++
src/state.cpp
nilern/kauno
a82f43bc535378afe9ce427ffb16921bf966fd47
[ "MIT" ]
null
null
null
src/state.cpp
nilern/kauno
a82f43bc535378afe9ce427ffb16921bf966fd47
[ "MIT" ]
null
null
null
src/state.cpp
nilern/kauno
a82f43bc535378afe9ce427ffb16921bf966fd47
[ "MIT" ]
null
null
null
#include "state.hpp" #include <cassert> #include <cstdlib> #include <cstring> #include <cstdalign> #include <utility> #include <algorithm> #include "arrays.hpp" #include "typesmap.hpp" #include "locals.hpp" #include "fn.hpp" namespace kauno { static inline AnySRef builtin_prn(State& state) { State_print_builtin(state, stdout, state.peek()); puts(""); state.pop_nth(1); // Pop self return state.peek(); // FIXME } State::State(size_t heap_size, size_t stack_size_) : heap(heap_size), stack_size(stack_size_), stack((char*)malloc(stack_size)), data_sp(stack + stack_size), type_sp((DynRef*)stack), type_hashes_(std::mt19937_64(std::random_device()())), symbols_(), globals(), Type(ORef<struct Type>(nullptr)), Field(ORef<struct Type>(nullptr)), UInt8(ORef<struct Type>(nullptr)), Int64(ORef<struct Type>(nullptr)), USize(ORef<struct Type>(nullptr)), Bool(ORef<struct Type>(nullptr)), Symbol(ORef<struct Type>(nullptr)), Var(ORef<struct Type>(nullptr)), AstFn(ORef<struct Type>(nullptr)), Call(ORef<struct Type>(nullptr)), CodePtr(ORef<struct Type>(nullptr)), Fn(ORef<struct Type>(nullptr)), Closure(ORef<struct Type>(nullptr)), NoneType(ORef<struct Type>(nullptr)), RefArray(ORef<struct Type>(nullptr)), NRefArray(ORef<struct Type>(nullptr)), TypesMap(ORef<struct Type>(nullptr)), Locals(ORef<struct Type>(nullptr)), None(ORef<struct None>(nullptr)) { // Sentinel to simplify (and optimize) popping: *type_sp = DynRef((ORef<void>*)data_sp); ++type_sp; size_t const Type_fields_count = 6; size_t const Type_size = sizeof(struct Type) + Type_fields_count*sizeof(Field); struct Type* tmp_Type = (struct Type*)malloc(Type_size); *tmp_Type = Type::create_indexed(*this, alignof(struct Type), sizeof(struct Type), Type_fields_count); size_t const Field_fields_count = 4; size_t const Field_size = sizeof(struct Type) + Field_fields_count*sizeof(Field); struct Type* const tmp_Field = (struct Type*)malloc(Field_size); *tmp_Field = Type::create_record(*this, alignof(struct Field), sizeof(struct Field), true, Field_fields_count); tmp_Type->fields[5] = (struct Field){NRef(tmp_Field), offsetof(struct Type, fields)}; Type = ORef((struct Type*)heap.alloc_indexed(tmp_Type, Type_fields_count)); Type.set_type(Type); *Type.data() = *tmp_Type; Type.data()->fields[5] = tmp_Type->fields[5]; Field = ORef((struct Type*)heap.alloc_indexed(tmp_Type, Field_fields_count)); Field.set_type(Type); *Field.data() = *tmp_Field; USize = ORef((struct Type*)heap.alloc_indexed(Type.data(), 0)); *USize.data() = Type::create_bits(*this, alignof(size_t), sizeof(size_t), true); Bool = ORef((struct Type*)heap.alloc_indexed(Type.data(), 0)); *Bool.data() = Type::create_bits(*this, alignof(bool), sizeof(bool), true); Type.data()->fields[0] = (struct Field){NRef(USize), offsetof(struct Type, align)}; Type.data()->fields[1] = (struct Field){NRef(USize), offsetof(struct Type, min_size)}; Type.data()->fields[2] = (struct Field){NRef(Bool), offsetof(struct Type, inlineable)}; Type.data()->fields[3] = (struct Field){NRef(Bool), offsetof(struct Type, is_bits)}; Type.data()->fields[4] = (struct Field){NRef(Bool), offsetof(struct Type, has_indexed)}; Type.data()->fields[5] = (struct Field){NRef(Field), offsetof(struct Type, fields)}; Field.data()->fields[0] = (struct Field){NRef(Type), offsetof(struct Field, type)}; Field.data()->fields[1] = (struct Field){NRef(USize), offsetof(struct Field, offset)}; Field.data()->fields[2] = (struct Field){NRef(USize), offsetof(struct Field, size)}; Field.data()->fields[3] = (struct Field){NRef(Bool), offsetof(struct Field, inlined)}; free(tmp_Type); free(tmp_Field); UInt8 = ORef((struct Type*)heap.alloc_indexed(Type.data(), 0)); *UInt8.data() = Type::create_bits(*this, alignof(uint8_t), sizeof(uint8_t), true); Int64 = ORef((struct Type*)heap.alloc_indexed(Type.data(), 0)); *Int64.data() = Type::create_bits(*this, alignof(int64_t), sizeof(int64_t), true); size_t const Symbol_fields_count = 2; Symbol = ORef((struct Type*)heap.alloc_indexed(Type.data(), Symbol_fields_count)); *Symbol.data() = Type::create_indexed(*this, alignof(struct Symbol), sizeof(struct Symbol), Symbol_fields_count); Symbol.data()->fields[0] = (struct Field){NRef(USize), offsetof(struct Symbol, hash)}; Symbol.data()->fields[1] = (struct Field){NRef(UInt8), offsetof(struct Symbol, name)}; size_t const Var_fields_count = 1; Var = ORef((struct Type*)heap.alloc_indexed(Type.data(), Var_fields_count)); *Var.data() = Type::create_record(*this, alignof(struct Var), sizeof(struct Var), false, Var_fields_count); Var.data()->fields[0] = (struct Field){NRef<struct Type>(), offsetof(struct Var, value)}; size_t const Call_fields_count = 2; Call = ORef((struct Type*)heap.alloc_indexed(Type.data(), Call_fields_count)); *Call.data() = Type::create_indexed(*this, alignof(kauno::ast::Call), sizeof(kauno::ast::Call), Call_fields_count); Call.data()->fields[0] = (struct Field){NRef<struct Type>(), offsetof(kauno::ast::Call, callee)}; Call.data()->fields[1] = (struct Field){NRef<struct Type>(), offsetof(kauno::ast::Call, args)}; CodePtr = ORef((struct Type*)heap.alloc_indexed(Type.data(), 0)); *CodePtr.data() = Type::create_bits(*this, alignof(kauno::fn::CodePtr), sizeof(kauno::fn::CodePtr), true); size_t const Fn_fields_count = 1; Fn = ORef((struct Type*)heap.alloc_indexed(Type.data(), Fn_fields_count)); *Fn.data() = Type::create_record(*this, alignof(kauno::fn::Fn), sizeof(kauno::fn::Fn), true, Fn_fields_count); Fn.data()->fields[0] = (struct Field){NRef(CodePtr), offsetof(kauno::fn::Fn, code)}; size_t const None_fields_count = 0; NoneType = ORef((struct Type*)heap.alloc_indexed(Type.data(), None_fields_count)); *NoneType.data() = Type::create_record(*this, alignof(struct None), sizeof(struct None), true, None_fields_count); size_t const RefArray_fields_count = 1; RefArray = ORef((struct Type*)heap.alloc_indexed(Type.data(), RefArray_fields_count)); *RefArray.data() = Type::create_indexed(*this, alignof(kauno::arrays::RefArray<ORef<void>>), sizeof(kauno::arrays::RefArray<ORef<void>>), RefArray_fields_count); RefArray.data()->fields[0] = (struct Field){NRef<struct Type>(), offsetof(kauno::arrays::RefArray<ORef<void>>, elements)}; size_t const NRefArray_fields_count = 1; NRefArray = ORef((struct Type*)heap.alloc_indexed(Type.data(), NRefArray_fields_count)); *NRefArray.data() = Type::create_indexed(*this, alignof(kauno::arrays::NRefArray<ORef<void>>), sizeof(kauno::arrays::NRefArray<ORef<void>>), NRefArray_fields_count); NRefArray.data()->fields[0] = (struct Field){NRef<struct Type>(), offsetof(kauno::arrays::NRefArray<ORef<void>>, elements)}; TypesMap = kauno::TypesMap::create_reified(*this); AstFn = ast::Fn::create_reified(*this); Locals = Locals::create_reified(*this); Closure = fn::Closure::create_reified(*this); None = ORef(static_cast<struct None*>(heap.alloc(NoneType.data()))); Handle<struct Type> const Type_handle = push_outlined(ORef(Type)); Handle<struct Symbol> const Type_symbol = Symbol_new(*this, "Type", 4); Handle<struct Var> const Type_var = Var_new(*this, Type_handle.as_void()); globals.insert(Type_symbol.oref(), Type_var.oref()); popn(3); ORef<kauno::fn::Fn> const prn = ORef((kauno::fn::Fn*)heap.alloc(Fn.data())); *prn.data() = (kauno::fn::Fn){ .code = builtin_prn, .domain_count = 1, .domain = {} }; prn.data()->domain[0] = None.as_void(); Handle<kauno::fn::Fn> const prn_handle = push_outlined(ORef(prn)); Handle<struct Symbol> const prn_symbol = Symbol_new(*this, "prn", 3); Handle<struct Var> const prn_var = Var_new(*this, prn_handle.as_void()); globals.insert(prn_symbol.oref(), prn_var.oref()); popn(3); } AnySRef State::peek() { assert((char*)type_sp > stack); return AnySRef(type_sp - 1); } AnySRef State::peek_nth(size_t n) { assert((char*)type_sp - n >= stack); return AnySRef(type_sp - 1 - n); } DynRef* State::peekn(size_t n) { assert((char*)type_sp - n >= stack); return type_sp - n; } void State::popn(size_t n) { assert((char*)(type_sp - n) > stack); type_sp -= n; data_sp = (char*)((type_sp - 1)->stack_ptr()); } void State::pop() { popn(1); } void State::popn_nth(size_t i, size_t n) { assert(n <= i + 1); assert((char*)(type_sp - i) > stack); size_t const top_count = i + 1 - n; DynRef* it = type_sp - top_count; type_sp -= i + 1; data_sp = (char*)((type_sp - 1)->stack_ptr()); for (size_t j = 0; j < top_count; ++j, ++it) { it->repush(*this); } } void State::pop_nth(size_t i) { popn_nth(i, 1); } static inline void State_print_builtin(State const& state, FILE* dest, AnySRef value) { ORef<Type> type = value.type(); void* data = value.data(); if (type == state.Type) { fprintf(dest, "<Type @ %p>", data); } else if (type == state.Field) { fprintf(dest, "<Field @ %p>", data); } else if (type == state.Symbol) { Symbol* symbol = (Symbol*)data; fputc('\'', dest); for (size_t i = 0; i < symbol->name_size; ++i) { fputc(symbol->name[i], dest); } } else if (type == state.Var) { fputs("<Var>", dest); } else if (type == state.AstFn) { fprintf(dest, "<AstFn @ %p>", data); } else if (type == state.Call) { fprintf(dest, "<Call @ %p>", data); } else if (type == state.Fn) { fprintf(dest, "<Fn @ %p>", data); } else if (type == state.CodePtr) { fprintf(dest, "<CodePtr @ %p>", data); } else if (type == state.Closure) { fprintf(dest, "<Closure @ %p>", data); } else if (type == state.UInt8) { fprintf(dest, "%u", *(uint8_t*)data); } else if (type == state.Int64) { fprintf(dest, "%ld", *(int64_t*)data); } else if (type == state.USize) { fprintf(dest, "%zu", *(size_t*)data); } else if (type == state.Bool) { fputs(*(bool*)data ? "True" : "False", dest); } else { fprintf(dest, "<??? @ %p>", data); } } }
38.474453
144
0.640106
nilern
3d43cdeba498bf65152e0c057b55c3615fc30f92
3,071
cpp
C++
src/passes/pass.cpp
ionlang/ir-c
f5be3d0a6bed76b3fe354018045b82ded7d792ae
[ "Unlicense" ]
3
2019-07-11T14:41:28.000Z
2019-07-12T10:29:08.000Z
src/passes/pass.cpp
ionlang/ir-c
f5be3d0a6bed76b3fe354018045b82ded7d792ae
[ "Unlicense" ]
22
2019-12-05T04:43:34.000Z
2020-11-05T23:29:25.000Z
src/passes/pass.cpp
ionlang/ir-c
f5be3d0a6bed76b3fe354018045b82ded7d792ae
[ "Unlicense" ]
3
2020-07-20T19:20:26.000Z
2020-10-12T15:24:47.000Z
#include <ionir/passes/pass.h> namespace ionir { Pass::Pass(std::shared_ptr<ionshared::PassContext> context) noexcept : ionshared::BasePass<Construct>(std::move(context)) { // } void Pass::visit(std::shared_ptr<Construct> construct) { construct->accept(*this); this->visitChildren(construct); } void Pass::visitChildren(std::shared_ptr<Construct> construct) { // TODO: Will it cause StackOverflow error with large ASTs? Ast children = construct->getChildrenNodes(); /** * After visiting the construct, attempt to * visit all its children as well. */ for (const auto& child : children) { // TODO: CRITICAL: What if 'child' (AstNode) is not boxed under Construct? this->visit(child); } } void Pass::visitFunction(std::shared_ptr<Function> construct) { // } void Pass::visitExtern(std::shared_ptr<Extern> construct) { // } void Pass::visitBasicBlock(std::shared_ptr<BasicBlock> construct) { // } void Pass::visitPrototype(std::shared_ptr<Prototype> construct) { // } void Pass::visitIntegerLiteral(std::shared_ptr<LiteralInteger> construct) { // } void Pass::visitCharLiteral(std::shared_ptr<LiteralChar> construct) { // } void Pass::visitStringLiteral(std::shared_ptr<LiteralString> construct) { // } void Pass::visitBooleanLiteral(std::shared_ptr<LiteralBoolean> construct) { // } void Pass::visitAllocaInst(std::shared_ptr<InstAlloca> construct) { // } void Pass::visitReturnInst(std::shared_ptr<InstReturn> construct) { // } void Pass::visitBranchInst(std::shared_ptr<InstBranch> construct) { // } void Pass::visitCallInst(std::shared_ptr<InstCall> construct) { // } void Pass::visitStoreInst(std::shared_ptr<InstStore> construct) { // } void Pass::visitJumpInst(std::shared_ptr<InstJump> construct) { // } void Pass::visitCompareInst(std::shared_ptr<InstCompare> construct) { // } void Pass::visitCastInst(std::shared_ptr<InstCast> construct) { // } void Pass::visitOperationValue(std::shared_ptr<OperationValue> construct) { // } void Pass::visitGlobal(std::shared_ptr<Global> construct) { // } void Pass::visitIntegerType(std::shared_ptr<TypeInteger> construct) { // } void Pass::visitDecimalType(std::shared_ptr<TypeDecimal> construct) { // } void Pass::visitVoidType(std::shared_ptr<TypeVoid> construct) { // } void Pass::visitBooleanType(std::shared_ptr<TypeBoolean> construct) { // } void Pass::visitPointerType(std::shared_ptr<TypePointer> construct) { // } void Pass::visitModule(std::shared_ptr<Module> construct) { // } void Pass::visitErrorMarker(std::shared_ptr<ErrorMarker> construct) { // } void Pass::visitIdentifier(std::shared_ptr<Identifier> construct) { // } void Pass::visitStructType(std::shared_ptr<TypeStruct> construct) { // } void Pass::visitStructDefinition(std::shared_ptr<StructDefinition> construct) { // } }
21.935714
81
0.669489
ionlang
3d452f4e374cf346d1d036ad22831286aebe9ab2
436
hpp
C++
include/ring_buffer/details/clz.hpp
Wizermil/ring_buffer
71ee2bb59aa268b462c43ed466d114c32f39dd19
[ "MIT" ]
null
null
null
include/ring_buffer/details/clz.hpp
Wizermil/ring_buffer
71ee2bb59aa268b462c43ed466d114c32f39dd19
[ "MIT" ]
null
null
null
include/ring_buffer/details/clz.hpp
Wizermil/ring_buffer
71ee2bb59aa268b462c43ed466d114c32f39dd19
[ "MIT" ]
null
null
null
#pragma once #include <ring_buffer/details/config.hpp> namespace wiz::details::bit { RING_BUFFER_HIDE_FROM_ABI constexpr int clz(unsigned x) noexcept { return __builtin_clz(x); } RING_BUFFER_HIDE_FROM_ABI constexpr int clz(unsigned long x) noexcept { return __builtin_clzl(x); } RING_BUFFER_HIDE_FROM_ABI constexpr int clz(unsigned long long x) noexcept { return __builtin_clzll(x); } } // namespace wiz::details::bit
31.142857
109
0.766055
Wizermil
3d4c7001300fec428fa66d91d6bb10c5cd946c06
714
hpp
C++
robots/robots.hpp
uncerso/code-graveyard
df875fd070022faf84374e260bd77663760b1e4c
[ "Apache-2.0" ]
1
2017-10-24T21:43:43.000Z
2017-10-24T21:43:43.000Z
robots/robots.hpp
uncerso/code-graveyard
df875fd070022faf84374e260bd77663760b1e4c
[ "Apache-2.0" ]
3
2017-12-02T08:15:29.000Z
2018-06-05T19:35:56.000Z
robots/robots.hpp
uncerso/code-graveyard
df875fd070022faf84374e260bd77663760b1e4c
[ "Apache-2.0" ]
null
null
null
#pragma once #include <vector> namespace robots { /// Solves the problem of destroying robots class Robots { using uint = unsigned int; uint amountOfRobots = 0; std::vector<bool> withRobot; std::vector<std::vector<uint> > graph; bool dfs(uint pos, bool color, std::vector<uint> & colors) noexcept; public: Robots() = default; ~Robots() = default; /// Add a vertice to the graph /// The smallest free number is assigned to it void addVertices(uint cnt) noexcept; /// Set a robot to the vertice void setRobot(uint pos) noexcept; /// Add an edge between two vertices void addEdge(uint first, uint second) noexcept; /// Checks whether robots can destroy each other bool solve() noexcept; }; }
21
69
0.710084
uncerso
3d4eedecab5d149018b6fc6786c77dfa2b69df38
3,345
hpp
C++
core/src/Concurrency/WorkStealingDeque.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
36
2015-03-12T10:42:36.000Z
2022-01-12T04:20:40.000Z
core/src/Concurrency/WorkStealingDeque.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
1
2015-12-17T00:25:43.000Z
2016-02-20T12:00:57.000Z
core/src/Concurrency/WorkStealingDeque.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
6
2017-06-17T07:57:53.000Z
2019-04-09T21:11:24.000Z
/* * Copyright (c) 2013, Hernan Saez * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CRIMILD_CORE_CONCURRENCY_WORK_STEALING_QUEUE_ #define CRIMILD_CORE_CONCURRENCY_WORK_STEALING_QUEUE_ #include "Foundation/SharedObject.hpp" #include <vector> #include <list> #include <mutex> namespace crimild { /** \brief A double-ended queue implemeting the work stealing pattern */ template< class T > class WorkStealingQueue : public SharedObject { using Mutex = std::mutex; using Lock = std::lock_guard< Mutex >; public: WorkStealingQueue( void ) { } ~WorkStealingQueue( void ) { } size_t size( void ) { Lock lock( _mutex ); return _elems.size(); } bool empty( void ) { return size() == 0; } void clear( void ) { Lock lock( _mutex ); _elems.clear(); } /** \brief Adds an element to the private end of the queue (LIFO) */ void push( T const &elem ) { Lock lock( _mutex ); _elems.push_back( elem ); } /** \brief Retrieves an element from the private end of the queue (LIFO) \warning You should check if the collection is empty before calling this method. */ T pop( void ) { Lock lock( _mutex ); if ( _elems.size() == 0 ) { return nullptr; } auto e = _elems.back(); _elems.pop_back(); return e; } /** \brief Retrieves an element from the public end of the queue (FIFO) \warning You should check if the collection is empty before calling this method */ T steal( void ) { Lock lock( _mutex ); if ( _elems.size() == 0 ) { return nullptr; } auto e = _elems.front(); _elems.pop_front(); return e; } private: std::list< T > _elems; std::mutex _mutex; }; } #endif
25.534351
85
0.666966
hhsaez
3d503972a27766dc485dce2235b71ab7dbf26d4e
2,983
hpp
C++
include/customWidgets.hpp
mousepawgames/infiltrator
b99152c31bebb683ea28c990e7d10e8bee0ffeb5
[ "MIT" ]
null
null
null
include/customWidgets.hpp
mousepawgames/infiltrator
b99152c31bebb683ea28c990e7d10e8bee0ffeb5
[ "MIT" ]
null
null
null
include/customWidgets.hpp
mousepawgames/infiltrator
b99152c31bebb683ea28c990e7d10e8bee0ffeb5
[ "MIT" ]
null
null
null
#ifndef CUSTOMWIDGETS_H #define CUSTOMWIDGETS_H #include <glibmm.h> #include <gtkmm/box.h> #include <gtkmm/button.h> #include <gtkmm/entry.h> #include <gtkmm/grid.h> #include <gtkmm/label.h> #include <gtkmm/liststore.h> #include <gtkmm/notebook.h> #include <gtkmm/scrolledwindow.h> #include <gtkmm/spinbutton.h> #include <gtkmm/treeview.h> #include <gtkmm/window.h> #include <iostream> #include <agentDatabase.hpp> class NumberEntry : public Gtk::Entry { public: NumberEntry(){} void on_insert_text(const Glib::ustring&, int*); ~NumberEntry(){} private: bool contains_only_numbers(const Glib::ustring&); }; class TimeSelectWindow : public Gtk::Window { public: enum TimeSelectMode { TIME_INTERCEPT, TIME_ENCRYPT, TIME_TRANSFER }; /**A constructor for popupWindow \param the Glib::ustring of the window's title \param the Glib::ustring of the window's message \param true in intercepting, false if encrypting \param agent being targeted \param agent setting the intercept/encrypt*/ TimeSelectWindow(Glib::ustring, Glib::ustring, AgentDatabase*, TimeSelectMode, int, int); private: AgentDatabase *db; int targetID; int fromID; Gtk::Button btn_OK, btn_Cancel; /*NumberEntry txt_time;*/ Gtk::SpinButton spn_time; Gtk::Label lbl_message; Gtk::Box box_main, box_message, box_time, box_buttons; /**closes the popup window*/ void closeWindow(); /**Takes intercept time and starts a countdown to intercept codes from selected person.*/ void processIntercept(); /**Takes encrypt time and starts a countdown to protect against intercepts for selected person*/ void processEncrypt(); /**Takes transfer time and transfer it to the selected teammate.*/ void processTransfer(); }; class TitleLabel : public Gtk::Label { public: TitleLabel(); ~TitleLabel(){} }; class RulesNotebook : public Gtk::Notebook { public: RulesNotebook(); ~RulesNotebook(){} private: class MarkupTextView : public Gtk::ScrolledWindow { public: MarkupTextView(); Gtk::Label label; void set_markup(Glib::ustring str){label.set_markup(str);} ~MarkupTextView(){} }; MarkupTextView view_about; MarkupTextView view_objectives; MarkupTextView view_setup; MarkupTextView view_gamescreen; MarkupTextView view_gettingstarted; MarkupTextView view_codes; MarkupTextView view_winning; MarkupTextView view_tricks; MarkupTextView view_teams; MarkupTextView view_infiltrator; MarkupTextView view_tech; }; #endif // CUSTOMWIDGETS_H
27.118182
104
0.624874
mousepawgames
3d50b7065737a577030b503e50480d9a2b218d4b
18,731
cpp
C++
thirdparty/qtiplot/qtiplot/src/plot2D/QwtPieCurve.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
6
2018-09-05T12:41:59.000Z
2021-07-01T05:34:23.000Z
thirdparty/qtiplot/qtiplot/src/plot2D/QwtPieCurve.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
2
2015-02-07T19:09:21.000Z
2015-08-14T03:15:42.000Z
thirdparty/qtiplot/qtiplot/src/plot2D/QwtPieCurve.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
2
2015-03-25T15:50:31.000Z
2017-12-06T12:16:47.000Z
/*************************************************************************** File : QwtPieCurve.cpp Project : QtiPlot -------------------------------------------------------------------- Copyright : (C) 2004 - 2008 by Ion Vasilie Email (use @ for *) : ion_vasilief*yahoo.fr Description : Pie plot class ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301 USA * * * ***************************************************************************/ #include "QwtPieCurve.h" #include "../ColorBox.h" #include "../Table.h" #include "../PenStyleBox.h" #include <QPaintDevice> #include <QPainter> #include <QPainterPath> #include <QVarLengthArray> QwtPieCurve::QwtPieCurve(Table *t, const QString& name, int startRow, int endRow): DataCurve(t, QString(), name, startRow, endRow), d_pie_ray(50), d_first_color(0), d_start_azimuth(270), d_view_angle(33), d_thickness(33), d_horizontal_offset(0), d_edge_dist(25), d_counter_clockwise(false), d_auto_labeling(true), d_values(false), d_percentages(true), d_categories(false), d_fixed_labels_pos(true) { setPen(QPen(QColor(Qt::black), 1, Qt::SolidLine)); setBrush(QBrush(Qt::SolidPattern)); setStyle(QwtPlotCurve::UserCurve); setType(Graph::Pie); setPlotStyle(Graph::Pie); d_table_rows = QVarLengthArray<int>(0); } void QwtPieCurve::clone(QwtPieCurve* c) { if (!c) return; d_pie_ray = c->radius(); d_first_color = c->firstColor(); d_start_azimuth = c->startAzimuth(); d_view_angle = c->viewAngle(); d_thickness = c->thickness(); d_horizontal_offset = c->horizontalOffset(); d_edge_dist = c->labelsEdgeDistance(); d_counter_clockwise = c->counterClockwise(); d_auto_labeling = c->labelsAutoFormat(); d_values = c->labelsValuesFormat(); d_percentages = c->labelsPercentagesFormat(); d_categories = c->labelCategories(); d_fixed_labels_pos = c->fixedLabelsPosition(); d_table_rows = c->d_table_rows; QList <PieLabel *> lst = c->labelsList(); foreach(PieLabel *t, lst){ PieLabel *nl = addLabel(t, true); if (nl && t->isHidden()) nl->hide(); } } void QwtPieCurve::draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const { int size = dataSize(); if ( !painter || size <= 0 ) return; if (to < 0) to = size - 1; if (size > 1) drawSlices(painter, xMap, yMap, from, to); else drawDisk(painter, xMap, yMap); } void QwtPieCurve::drawDisk(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap) const { const double x_width = fabs(xMap.p1() - xMap.p2()); const double x_center = (xMap.p1() + xMap.p2())*0.5 + d_horizontal_offset*0.01*x_width; const double y_center = (yMap.p1() + yMap.p2())*0.5; const double ray_x = d_pie_ray*0.005*qMin(x_width, fabs(yMap.p1() - yMap.p2())); const double view_angle_rad = d_view_angle*M_PI/180.0; const double ray_y = ray_x*sin(view_angle_rad); const double thick = 0.01*d_thickness*ray_x*cos(view_angle_rad); QRectF pieRect; pieRect.setX(x_center - ray_x); pieRect.setY(y_center - ray_y); pieRect.setWidth(2*ray_x); pieRect.setHeight(2*ray_y); QRectF pieRect2 = pieRect; pieRect2.translate(0, thick); painter->save(); painter->setPen(QwtPlotCurve::pen()); painter->setBrush(QBrush(color(0), QwtPlotCurve::brush().style())); QPointF start(x_center + ray_x, y_center); QPainterPath path(start); path.lineTo(start.x(), start.y() + thick); path.arcTo(pieRect2, 0, -180.0); QPointF aux = path.currentPosition(); path.lineTo(aux.x(), aux.y() - thick); path.arcTo(pieRect, -180.0, 180.0); painter->drawPath(path); painter->drawEllipse(pieRect); if (d_texts_list.size() > 0){ PieLabel* l = d_texts_list[0]; if (l){ QString s; if (d_auto_labeling){ if (d_categories) s += QString::number(d_table_rows[0]) + "\n"; if (d_values && d_percentages) s += ((Graph *)plot())->locale().toString(y(0), 'g', 4) + " (100%)"; else if (d_values) s += ((Graph *)plot())->locale().toString(y(0), 'g', 4); else if (d_percentages) s += "100%"; l->setText(s); if (l->isHidden()) l->show(); } else l->setText(l->customText()); if (d_fixed_labels_pos){ double a_deg = d_start_azimuth + 180.0; if (a_deg > 360) a_deg -= 360; double a_rad = a_deg*M_PI/180.0; double rx = ray_x*(1 + 0.01*d_edge_dist); const double x = x_center + rx*cos(a_rad); double ry = ray_y*(1 + 0.01*d_edge_dist); double y = y_center + ry*sin(a_rad); if (a_deg > 0 && a_deg < 180) y += thick; double dx = xMap.invTransform(x - l->width()/2); double dy = yMap.invTransform(y - l->height()/2); l->setOriginCoord(dx, dy); } } } painter->restore(); } void QwtPieCurve::drawSlices(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const { const double x_width = fabs(xMap.p1() - xMap.p2()); const double x_center = (xMap.p1() + xMap.p2())*0.5 + d_horizontal_offset*0.01*x_width; const double y_center = (yMap.p1() + yMap.p2())*0.5; const double ray_x = d_pie_ray*0.005*qMin(x_width, fabs(yMap.p1() - yMap.p2())); const double view_angle_rad = d_view_angle*M_PI/180.0; const double ray_y = ray_x*sin(view_angle_rad); const double thick = 0.01*d_thickness*ray_x*cos(view_angle_rad); QRectF pieRect; pieRect.setX(x_center - ray_x); pieRect.setY(y_center - ray_y); pieRect.setWidth(2*ray_x); pieRect.setHeight(2*ray_y); QRectF pieRect2 = pieRect; pieRect2.translate(0, thick); double sum = 0.0; for (int i = from; i <= to; i++) sum += y(i); const int sign = d_counter_clockwise ? 1 : -1; const int size = dataSize(); double *start_angle = new double[size]; double *end_angle = new double[size]; double aux_angle = d_start_azimuth; for (int i = from; i <= to; i++){ double a = -sign*y(i)/sum*360.0; start_angle[i] = aux_angle; double end = aux_angle + a; if (end >= 360) end -= 360; else if (end < 0) end += 360; end_angle[i] = end; aux_angle = end; } int angle = (int)(5760 * d_start_azimuth/360.0); if (d_counter_clockwise) angle = (int)(5760 * (1 - d_start_azimuth/360.0)); painter->save(); QLocale locale = ((Graph *)plot())->multiLayer()->locale(); for (int i = from; i <= to; i++){ const double yi = y(i); const double q = yi/sum; const int value = (int)(q*5760); painter->setPen(QwtPlotCurve::pen()); painter->setBrush(QBrush(color(i), QwtPlotCurve::brush().style())); double deg = q*360; double start_3D_view_angle = start_angle[i]; double end_3D_view_angle = end_angle[i]; if (d_counter_clockwise){ start_3D_view_angle = end_angle[i]; end_3D_view_angle = start_angle[i]; } bool draw3D = false; if (deg <= 180 && start_3D_view_angle >= 0 && start_3D_view_angle < 180){ if ((end_3D_view_angle > 180 && end_3D_view_angle > start_3D_view_angle)){ deg = 180 - start_3D_view_angle; end_3D_view_angle = 180.0; } draw3D = true; } else if (start_3D_view_angle >= 180 && end_3D_view_angle < start_3D_view_angle){ if (end_3D_view_angle > 180) end_3D_view_angle = 180; deg = end_3D_view_angle; start_3D_view_angle = 0; draw3D = true; } else if (deg > 180 && start_3D_view_angle >= 180){ deg = 180; end_3D_view_angle = 180; start_3D_view_angle = 0; draw3D = true; } if (draw3D){ double rad = start_3D_view_angle/180.0*M_PI; QPointF start(x_center + ray_x*cos(rad), y_center + ray_y*sin(rad)); QPainterPath path(start); path.lineTo(start.x(), start.y() + thick); path.arcTo(pieRect2, -start_3D_view_angle, -deg); QPointF aux = path.currentPosition(); path.lineTo(aux.x(), aux.y() - thick); path.arcTo(pieRect, -end_3D_view_angle, deg); painter->drawPath(path); } else { if (start_3D_view_angle >= 0 && start_3D_view_angle < 180){ if (end_3D_view_angle > 180) end_3D_view_angle = 0; double rad = start_3D_view_angle/180.0*M_PI; QPointF start(x_center + ray_x*cos(rad), y_center + ray_y*sin(rad)); QPainterPath path(start); path.lineTo(start.x(), start.y() + thick); deg = 180 - start_3D_view_angle; path.arcTo(pieRect2, -start_3D_view_angle, -deg); QPointF aux = path.currentPosition(); path.lineTo(aux.x(), aux.y() - thick); path.arcTo(pieRect, -180, deg); painter->drawPath(path); path.moveTo(QPointF(x_center + ray_x, y_center)); aux = path.currentPosition(); path.lineTo(aux.x(), aux.y() + thick); path.arcTo(pieRect2, 0, -end_3D_view_angle); aux = path.currentPosition(); path.lineTo(aux.x(), aux.y() - thick); path.arcTo(pieRect, -end_3D_view_angle, end_3D_view_angle); painter->drawPath(path); } } painter->drawPie(pieRect, sign*angle, sign*value); angle += value; if (i >= d_texts_list.size()) continue; PieLabel* l = d_texts_list[i]; if (l){ QString s; if (d_auto_labeling){ if (d_categories) s += QString::number(d_table_rows[i]) + "\n"; if (d_values && d_percentages) s += locale.toString(yi, 'g', 4) + " (" + locale.toString(q*100, 'g', 4) + "%)"; else if (d_values) s += locale.toString(yi, 'g', 4); else if (d_percentages) s += locale.toString(q*100, 'g', 4) + "%"; l->setText(s); if (l->isHidden()) l->show(); } else l->setText(l->customText()); if (d_fixed_labels_pos){ double a_deg = start_angle[i] - sign*q*180.0; if (a_deg > 360) a_deg -= 360.0; double a_rad = a_deg*M_PI/180.0; double rx = ray_x*(1 + 0.01*d_edge_dist); const double x = x_center + rx*cos(a_rad); double ry = ray_y*(1 + 0.01*d_edge_dist); double y = y_center + ry*sin(a_rad); if (a_deg > 0 && a_deg < 180) y += thick; double dx = xMap.invTransform(x - l->width()/2); double dy = yMap.invTransform(y - l->height()/2); l->setOriginCoord(dx, dy); } } } painter->restore(); delete [] start_angle; delete [] end_angle; } QColor QwtPieCurve::color(int i) const { return ColorBox::color((d_first_color + i) % ColorBox::numPredefinedColors()); } void QwtPieCurve::setBrushStyle(const Qt::BrushStyle& style) { QBrush br = QwtPlotCurve::brush(); if (br.style() == style) return; br.setStyle(style); setBrush(br); } void QwtPieCurve::loadData() { Graph *d_plot = (Graph *)plot(); QLocale locale = d_plot->multiLayer()->locale(); QVarLengthArray<double> X(abs(d_end_row - d_start_row) + 1); d_table_rows.resize(abs(d_end_row - d_start_row) + 1); int size = 0; int ycol = d_table->colIndex(title().text()); for (int i = d_start_row; i <= d_end_row; i++ ){ QString xval = d_table->text(i, ycol); bool valid_data = true; if (!xval.isEmpty()){ X[size] = locale.toDouble(xval, &valid_data); if (valid_data){ d_table_rows[size] = i + 1; size++; } } } X.resize(size); d_table_rows.resize(size); setData(X.data(), X.data(), size); int labels = d_texts_list.size(); //If there are no labels (initLabels() wasn't called yet) or if we have enough labels: do nothing! if(d_texts_list.isEmpty() || labels == size) return; //Else add new pie labels. for (int i = labels; i < size; i++ ){ PieLabel* l = new PieLabel(d_plot, this); d_texts_list << l; l->hide(); } } PieLabel* QwtPieCurve::addLabel(PieLabel *l, bool clone) { if (!l) return 0; Graph *g = (Graph *)plot(); if (clone){ PieLabel *newLabel = new PieLabel(g, this); newLabel->clone(l); newLabel->setCustomText(l->customText()); d_texts_list << newLabel; if (l->text().isEmpty()) newLabel->hide(); return newLabel; } else { l->setPieCurve(this); d_texts_list << l; if (l->text().isEmpty()) l->hide(); } return l; } void QwtPieCurve::initLabels() { int size = abs(d_end_row - d_start_row) + 1; int dataPoints = dataSize(); double sum = 0.0; for (int i = 0; i < dataPoints; i++) sum += y(i); Graph *d_plot = (Graph *)plot(); QLocale locale = d_plot->multiLayer()->locale(); for (int i = 0; i <size; i++ ){ PieLabel* l = new PieLabel(d_plot, this); d_texts_list << l; if (i < dataPoints) l->setText(locale.toString(y(i)/sum*100, 'g', 4) + "%"); else l->hide(); } } PieLabel::PieLabel(Graph *plot, QwtPieCurve *pie):LegendWidget(plot), d_pie_curve(pie), d_custom_text(QString::null) { setBackgroundColor(QColor(255, 255, 255, 0)); setFrameStyle(0); plot->add(this, false); } QString PieLabel::customText() { if (d_custom_text.isEmpty()) return text(); return d_custom_text; } void PieLabel::closeEvent(QCloseEvent* e) { setText(QString::null); hide(); e->ignore(); } QString PieLabel::saveToString() { if (!d_pie_curve) return LegendWidget::saveToString(); if (text().isEmpty()) return QString::null; QString s = "<PieText>\n"; s += "<index>" + QString::number(d_pie_curve->labelsList().indexOf(this)) + "</index>\n"; s += FrameWidget::saveToString(); s += "<Text>\n" + text() + "\n</Text>\n"; QFont f = font(); s += "<Font>" + f.family() + "\t"; s += QString::number(f.pointSize())+"\t"; s += QString::number(f.weight())+"\t"; s += QString::number(f.italic())+"\t"; s += QString::number(f.underline())+"\t"; s += QString::number(f.strikeOut())+"</Font>\n"; s += "<TextColor>" + textColor().name()+"</TextColor>\n"; QColor bc = backgroundColor(); s += "<Background>" + bc.name() + "</Background>\n"; s += "<Alpha>" + QString::number(bc.alpha()) + "</Alpha>\n"; s += "<Angle>" + QString::number(angle()) + "</Angle>\n"; return s + "</PieText>\n"; } void PieLabel::restore(Graph *g, const QStringList& lst) { PieLabel *l = NULL; QStringList::const_iterator line; QColor backgroundColor = Qt::white, textColor = Qt::black; QFont f = QFont(); double x = 0.0, y = 0.0; QString text; int frameStyle = 0, angle = 0; QPen framePen = QPen(Qt::black, 1, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin); for (line = lst.begin(); line != lst.end(); line++){ QString s = *line; if (s.contains("<index>")){ int index = s.remove("<index>").remove("</index>").toInt(); QwtPieCurve *pie = (QwtPieCurve *)g->curve(0); if(pie){ QList<PieLabel *> labels = pie->labelsList(); if (index >= 0 && index < labels.size()) l = labels.at(index); } } else if (s.contains("<Frame>")) frameStyle = s.remove("<Frame>").remove("</Frame>").toInt(); else if (s.contains("<Color>")) framePen.setColor((QColor(s.remove("<Color>").remove("</Color>")))); else if (s.contains("<FrameWidth>")) framePen.setWidth(s.remove("<FrameWidth>").remove("</FrameWidth>").toInt()); else if (s.contains("<LineStyle>")) framePen.setStyle(PenStyleBox::penStyle(s.remove("<LineStyle>").remove("</LineStyle>").toInt())); else if (s.contains("<x>")) x = s.remove("<x>").remove("</x>").toDouble(); else if (s.contains("<y>")) y = s.remove("<y>").remove("</y>").toDouble(); else if (s.contains("<Text>")){ QStringList txt; while ( s != "</Text>" ){ s = *(++line); txt << s; } txt.pop_back(); text = txt.join("\n"); } else if (s.contains("<Font>")){ QStringList lst = s.remove("<Font>").remove("</Font>").split("\t"); f = QFont(lst[0], lst[1].toInt(), lst[2].toInt(), lst[3].toInt()); f.setUnderline(lst[4].toInt()); f.setStrikeOut(lst[5].toInt()); } else if (s.contains("<TextColor>")) textColor = QColor(s.remove("<TextColor>").remove("</TextColor>")); else if (s.contains("<Background>")) backgroundColor = QColor(s.remove("<Background>").remove("</Background>")); else if (s.contains("<Alpha>")) backgroundColor.setAlpha(s.remove("<Alpha>").remove("</Alpha>").toInt()); else if (s.contains("<Angle>")) angle = s.remove("<Angle>").remove("</Angle>").toInt(); } if (l){ l->setFrameStyle(frameStyle); l->setFramePen(framePen); l->setText(text); l->setFont(f); l->setTextColor(textColor); l->setBackgroundColor(backgroundColor); l->setAngle(angle); l->setOriginCoord(x, y); } }
32.861404
121
0.559767
hoehnp
3d51c7983e152fb7ebb899aa17f569f836d3f915
2,193
cpp
C++
common/utility/src/Random.cpp
cbtek/SourceGen
6593300c658529acb06b83982bbc9e698c270aeb
[ "MIT" ]
null
null
null
common/utility/src/Random.cpp
cbtek/SourceGen
6593300c658529acb06b83982bbc9e698c270aeb
[ "MIT" ]
3
2017-07-12T17:10:52.000Z
2017-09-21T19:06:59.000Z
common/utility/src/Random.cpp
cbtek/SourceGen
6593300c658529acb06b83982bbc9e698c270aeb
[ "MIT" ]
null
null
null
/** MIT License Copyright (c) 2016 cbtek 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 "Random.h" namespace cbtek { namespace common { namespace utility { Random::Random(long seed) : m_ix(9123),m_iy(8844),m_iz(20846) { reseed(seed); m_mx=1/30269.0;m_my=1/30307.0;m_mz=1/30323.0; } void Random::reseed(long seed) { srand(seed); m_ix=rand(); m_iy=rand(); m_iz=rand(); } double Random::random() { m_ix = fmod(171*m_ix,30269); m_iy = fmod(172*m_iy,20207); m_iz = fmod(170*m_iz,30323); double modValue=(((double)m_ix)*m_mx+((double)m_iy)*m_my+((double)m_iz)*m_mz); double value = fmod(modValue,1.); if (value < 0) { value*=-1; } return value; } int Random::next(int mn, int mx) { if (mn==mx)return mn; int max=mx; int min=mn; max++; if (min < 0) { min*=-1; max = max + min; double rng=random(); int value = (int)((rng*(max))); return (value-min); } double rng=random(); return (int)(rng*(max-min))+min; } int Random::next(int max) { return next(0,max); } }}}//namespace
26.107143
83
0.657091
cbtek
87d4991530f3e0f2f835f9213fb87f8ac0f1af25
2,483
cpp
C++
RealSpace2/Samples/rs2testwf.cpp
WhyWolfie/source2007
324257e9c69bbaec872ebb7ae4f96ab2ce98f520
[ "FSFAP" ]
null
null
null
RealSpace2/Samples/rs2testwf.cpp
WhyWolfie/source2007
324257e9c69bbaec872ebb7ae4f96ab2ce98f520
[ "FSFAP" ]
null
null
null
RealSpace2/Samples/rs2testwf.cpp
WhyWolfie/source2007
324257e9c69bbaec872ebb7ae4f96ab2ce98f520
[ "FSFAP" ]
null
null
null
#include <windows.h> #include "MDebug.h" #include "RealSpace2.h" #include "RMaterialList.h" #include "RRoam.h" _USING_NAMESPACE_REALSPACE2 Landscape g_map; const int size=1024; unsigned char buffer[size*size+size*2]; RRESULT InitScene(void *param) { InitLog(); FILE *file=fopen("Height1024.raw","rb"); fread(buffer+size,size*size,1,file); fclose(file); // Copy the last row of the height map into the extra first row. memcpy( buffer, buffer + size * size, size ); // Copy the first row of the height map into the extra last row. memcpy( buffer + size * size + size, buffer + size, size ); g_map.Init(buffer); RSetCamera(rvector(10,10,100),rvector(0,0,0),rvector(0,0,1)); RSetProjection(pi/3,0.1f,3000.f); return R_OK; } RRESULT CloseScene(void *param) { g_map.Destroy(); return R_OK; } #define IsKeyDown(key) ((GetAsyncKeyState(key) & 0x8000)!=0) #pragma comment(lib,"winmm.lib") _NAMESPACE_REALSPACE2_BEGIN extern float gClipAngle ; _NAMESPACE_REALSPACE2_END void Update() { static DWORD thistime,lasttime=timeGetTime(),elapsed; thistime = timeGetTime(); elapsed = (thistime - lasttime)*(IsKeyDown(VK_SHIFT)?5:1); lasttime = thistime; static float rotatez=0.7f,rotatex=2.5f; float fRotateStep=elapsed*0.001f; float fMoveStep=elapsed*0.1f; if(IsKeyDown(VK_LEFT)) rotatez-=fRotateStep; if(IsKeyDown(VK_RIGHT)) rotatez+=fRotateStep; if(IsKeyDown(VK_UP)) rotatex-=fRotateStep; if(IsKeyDown(VK_DOWN)) rotatex+=fRotateStep; rvector pos=RCameraPosition,dir=rvector(cosf(rotatez)*sinf(rotatex),sinf(rotatez)*sinf(rotatex),cosf(rotatex)); D3DXVec3Normalize(&dir,&dir); rvector right; D3DXVec3Cross(&right,&dir,&rvector(0,0,1)); D3DXVec3Normalize(&right,&right); if(IsKeyDown('W')) pos+=fMoveStep*dir; if(IsKeyDown('S')) pos-=fMoveStep*dir; if(IsKeyDown('A')) pos+=fMoveStep*right; if(IsKeyDown('D')) pos-=fMoveStep*right; if(IsKeyDown(VK_SPACE)) pos+=fMoveStep*rvector(0,0,1); gClipAngle +=2.1f; gClipAngle=fmodf(gClipAngle,180); rvector at=pos+dir; //at.z=0; RSetCamera(pos,at,rvector(0,0,1)); // mlog("%3.3f %3.3f\n",rotatex,rotatez); } RRESULT RenderScene(void *param) { Update(); g_map.Reset(); g_map.Tessellate(); g_map.Render(); return R_OK; } int PASCAL WinMain(HINSTANCE this_inst, HINSTANCE prev_inst, LPSTR cmdline, int cmdshow) { RSetFunction(RF_CREATE,InitScene); RSetFunction(RF_RENDER,RenderScene); RSetFunction(RF_DESTROY ,CloseScene); return RMain("rs2test",this_inst,prev_inst,cmdline,cmdshow); }
23.205607
112
0.730971
WhyWolfie
87d4acf297378085da459b640471a243fe6a2f92
1,178
hpp
C++
include/opengv/optimization_tools/objective_function_tools/Plane3P3DRegistrationFunctionInfo.hpp
mateus03/2018AMMPoseSolver
787886846199cd0864c4e59a6545c40c3120010a
[ "BSD-3-Clause" ]
null
null
null
include/opengv/optimization_tools/objective_function_tools/Plane3P3DRegistrationFunctionInfo.hpp
mateus03/2018AMMPoseSolver
787886846199cd0864c4e59a6545c40c3120010a
[ "BSD-3-Clause" ]
null
null
null
include/opengv/optimization_tools/objective_function_tools/Plane3P3DRegistrationFunctionInfo.hpp
mateus03/2018AMMPoseSolver
787886846199cd0864c4e59a6545c40c3120010a
[ "BSD-3-Clause" ]
null
null
null
#ifndef PLANE3P3DREGISTRATIONFUNCTIONINFO_H #define PLANE3P3DREGISTRATIONFUNCTIONINFO_H #include <opengv/optimization_tools/objective_function_tools/ObjectiveFunctionInfo.hpp> #include <opengv/registration/PlaneRegistrationAdapter.hpp> #include <opengv/types.hpp> #include <iostream> class Plane3P3DRegistrationFunctionInfo : public ObjectiveFunctionInfo { public: Plane3P3DRegistrationFunctionInfo(const opengv::registration::PlaneRegistrationAdapter & adapter); ~Plane3P3DRegistrationFunctionInfo(); double objective_function_value(const opengv::rotation_t & rotation, const opengv::translation_t & translation); opengv::rotation_t rotation_gradient(const opengv::rotation_t & rotation, const opengv::translation_t & translation); opengv::translation_t translation_gradient(const opengv::rotation_t & rotation, const opengv::translation_t & translation); private: Eigen::Matrix<double,3,3> Mt; Eigen::Matrix<double,3,9> Mrt; Eigen::Matrix<double,9,9> Mr; Eigen::Matrix<double,1,1> pp; Eigen::Matrix<double,9,1> vr; Eigen::Matrix<double,3,1> vt; size_t numPlanes; double cP; }; #endif
34.647059
100
0.760611
mateus03
87d79b889f4a0561b15409ad00d9b4c124d107ab
5,193
cpp
C++
nodes/VelocityEstimationNode_ConstAccUKF.cpp
RobertMilijas/uav_ros_general
d9ef09e2da4802891296a9410e5031675c09c066
[ "BSD-3-Clause" ]
1
2021-12-20T13:43:22.000Z
2021-12-20T13:43:22.000Z
nodes/VelocityEstimationNode_ConstAccUKF.cpp
RobertMilijas/uav_ros_general
d9ef09e2da4802891296a9410e5031675c09c066
[ "BSD-3-Clause" ]
4
2020-12-21T15:15:13.000Z
2021-06-16T10:40:29.000Z
nodes/VelocityEstimationNode_ConstAccUKF.cpp
RobertMilijas/uav_ros_general
d9ef09e2da4802891296a9410e5031675c09c066
[ "BSD-3-Clause" ]
2
2021-02-15T13:35:18.000Z
2021-05-24T12:44:18.000Z
#include <boost/array.hpp> #include <uav_ros_lib/estimation/constant_acceleration_ukf.hpp> #include <geometry_msgs/PoseStamped.h> #include <list> #include <nav_msgs/Odometry.h> #include <sensor_msgs/Imu.h> int main(int argc, char **argv) { ros::init(argc, argv, "velocity_estimation_node"); ros::NodeHandle nhPrivate("~"); ros::NodeHandle nh; ConstantAccelerationUKF kWrapperXPos("const_acc_x", nhPrivate); ConstantAccelerationUKF kWrapperYPos("const_acc_y", nhPrivate); ConstantAccelerationUKF kWrapperZPos("const_acc_z", nhPrivate); geometry_msgs::PoseStamped poseMsg; bool newMeasurementFlag = false; const auto poseCb = [&](const geometry_msgs::PoseStampedConstPtr &msg) { poseMsg = *msg; newMeasurementFlag = true; }; sensor_msgs::Imu myImuMsg; sensor_msgs::Imu oldImuMsg; const auto imuCb = [&](const sensor_msgs::ImuConstPtr &msg) { // Only do acceleration correction when acceleration measurement changes if (oldImuMsg.linear_acceleration.x != msg->linear_acceleration.x || oldImuMsg.linear_acceleration.y != msg->linear_acceleration.y || oldImuMsg.linear_acceleration.z != msg->linear_acceleration.z) { myImuMsg = *msg; auto quat = Eigen::Quaternionf(msg->orientation.w, msg->orientation.x, msg->orientation.y, msg->orientation.z); auto lin_acc = Eigen::Vector3f(msg->linear_acceleration.x, msg->linear_acceleration.y, msg->linear_acceleration.z); auto correct_acc = quat * lin_acc; myImuMsg.linear_acceleration.x = correct_acc.x(); myImuMsg.linear_acceleration.y = correct_acc.y(); myImuMsg.linear_acceleration.z = correct_acc.z(); } oldImuMsg = *msg; }; auto imuSub = nh.subscribe<sensor_msgs::Imu>("imu", 1, imuCb); auto odomPub = nh.advertise<nav_msgs::Odometry>("odometry", 1); auto imuPub = nh.advertise<sensor_msgs::Imu>("/imu_est", 1); static constexpr auto dt = 0.02; static constexpr auto throttle_time = 2.0; const auto timerCb = [&](const ros::TimerEvent & /* unused */) { kWrapperXPos.estimateState( dt, {poseMsg.pose.position.x, myImuMsg.linear_acceleration.x}, newMeasurementFlag); kWrapperYPos.estimateState( dt, {poseMsg.pose.position.y, myImuMsg.linear_acceleration.y}, newMeasurementFlag); kWrapperZPos.estimateState( dt, {poseMsg.pose.position.z, (myImuMsg.linear_acceleration.z - 9.80689)}, newMeasurementFlag); nav_msgs::Odometry kalmanOdomMsg; kalmanOdomMsg.header.stamp = poseMsg.header.stamp; kalmanOdomMsg.header.frame_id = poseMsg.header.frame_id; kalmanOdomMsg.pose.pose.position.x = kWrapperXPos.getState()[0]; kalmanOdomMsg.pose.pose.position.y = kWrapperYPos.getState()[0]; kalmanOdomMsg.pose.pose.position.z = kWrapperZPos.getState()[0]; kalmanOdomMsg.pose.pose.orientation = poseMsg.pose.orientation; kalmanOdomMsg.twist.twist.linear.x = kWrapperXPos.getState()[1]; kalmanOdomMsg.twist.twist.linear.y = kWrapperYPos.getState()[1]; kalmanOdomMsg.twist.twist.linear.z = -kWrapperZPos.getState()[1]; kalmanOdomMsg.pose.covariance[0] = kWrapperXPos.getStateCovariance()(0, 0); kalmanOdomMsg.pose.covariance[1] = kWrapperYPos.getStateCovariance()(0, 0); kalmanOdomMsg.pose.covariance[2] = kWrapperZPos.getStateCovariance()(0, 0); kalmanOdomMsg.pose.covariance[3] = kWrapperXPos.getStateCovariance()(1, 1); kalmanOdomMsg.pose.covariance[4] = kWrapperYPos.getStateCovariance()(1, 1); kalmanOdomMsg.pose.covariance[5] = kWrapperZPos.getStateCovariance()(1, 1); kalmanOdomMsg.pose.covariance[6] = kWrapperXPos.getStateCovariance()(2, 2); kalmanOdomMsg.pose.covariance[7] = kWrapperYPos.getStateCovariance()(2, 2); kalmanOdomMsg.pose.covariance[8] = kWrapperZPos.getStateCovariance()(2, 2); kalmanOdomMsg.pose.covariance[9] = kWrapperXPos._nis; kalmanOdomMsg.pose.covariance[10] = kWrapperYPos._nis; kalmanOdomMsg.pose.covariance[11] = kWrapperZPos._nis; odomPub.publish(kalmanOdomMsg); sensor_msgs::Imu estImuMsg; estImuMsg.header.frame_id = myImuMsg.header.frame_id; estImuMsg.header.stamp = myImuMsg.header.stamp; estImuMsg.linear_acceleration.x = kWrapperXPos.getState()[2]; estImuMsg.linear_acceleration.y = kWrapperYPos.getState()[2]; estImuMsg.linear_acceleration.z = kWrapperZPos.getState()[2]; estImuMsg.angular_velocity.x = myImuMsg.linear_acceleration.x; estImuMsg.angular_velocity.y = myImuMsg.linear_acceleration.y; estImuMsg.angular_velocity.z = myImuMsg.linear_acceleration.z; imuPub.publish(estImuMsg); if (newMeasurementFlag) { newMeasurementFlag = false; } }; auto poseSub = nh.subscribe<geometry_msgs::PoseStamped>("poseStamped", 1, poseCb); while (poseSub.getNumPublishers() == 0) { ROS_WARN_STREAM("Waiting for " << poseSub.getTopic() << " topic publisher."); ros::Duration(0.5).sleep(); } ROS_INFO("Starting velocity_estimation_node..."); auto kalmanTimer = nh.createTimer(ros::Duration(dt), timerCb); ros::spin(); }
45.552632
79
0.706528
RobertMilijas
87dbdaefa11f64f8a235df3256b97dcb289d2165
9,678
hh
C++
src/mmutil_filter_row.hh
YPARK/mmutil
21729fc50ac4cefff58c1b71e8c5740d2045b111
[ "MIT" ]
null
null
null
src/mmutil_filter_row.hh
YPARK/mmutil
21729fc50ac4cefff58c1b71e8c5740d2045b111
[ "MIT" ]
null
null
null
src/mmutil_filter_row.hh
YPARK/mmutil
21729fc50ac4cefff58c1b71e8c5740d2045b111
[ "MIT" ]
null
null
null
#include <getopt.h> #include "mmutil.hh" #include "mmutil_io.hh" #include "mmutil_stat.hh" #include "mmutil_score.hh" #ifndef MMUTIL_FILTER_ROW_HH_ #define MMUTIL_FILTER_ROW_HH_ template <typename OPTIONS> int filter_row_by_score(OPTIONS &options); struct filter_row_options_t { typedef enum { NNZ, MEAN, CV, SD } row_score_t; const std::vector<std::string> SCORE_NAMES; explicit filter_row_options_t() : SCORE_NAMES { "NNZ", "MEAN", "CV", "SD" } { mtx_file = ""; row_file = ""; col_file = ""; output = "output"; Ntop = 0; cutoff = 0; COL_NNZ_CUTOFF = 0; row_score = NNZ; } Index Ntop; Scalar cutoff; Index COL_NNZ_CUTOFF; row_score_t row_score; std::string mtx_file; std::string row_file; std::string col_file; std::string output; void set_row_score(const std::string _score) { for (int j = 0; j < SCORE_NAMES.size(); ++j) { if (SCORE_NAMES.at(j) == _score) { row_score = static_cast<row_score_t>(j); break; } } } }; struct select_cv_t { inline Vec operator()(Vec &mu, Vec &sig, Vec &cv, Vec &nnz) { return cv; } }; struct select_mean_t { inline Vec operator()(Vec &mu, Vec &sig, Vec &cv, Vec &nnz) { return mu; } }; struct select_sd_t { inline Vec operator()(Vec &mu, Vec &sig, Vec &cv, Vec &nnz) { return sig; } }; struct select_nnz_t { inline Vec operator()(Vec &mu, Vec &sig, Vec &cv, Vec &nnz) { return nnz; } }; /** * @param select_row_score * @param options * @return temp_mtx_file */ template <typename FUN, typename OPTIONS> std::string _filter_row_by_score(FUN select_row_score, OPTIONS &options) { using namespace mmutil::io; std::vector<std::string> rows; CHECK(read_vector_file(options.row_file, rows)); Vec mu, sig, cv; Index max_row, max_col; std::vector<Index> Nvec; std::tie(mu, sig, cv, Nvec, max_row, max_col) = compute_mtx_row_stat(options.mtx_file); Vec nvec = eigen_vector_<Index, Scalar>(Nvec); Vec row_scores = select_row_score(mu, sig, cv, nvec); using copier_t = triplet_copier_remapped_rows_t<obgzf_stream, Index, Scalar>; using index_map_t = copier_t::index_map_t; const Index nmax = (options.Ntop > 0) ? std::min(options.Ntop, max_row) : max_row; auto order = eigen_argsort_descending(row_scores); TLOG("row scores: " << row_scores(order.at(0)) << " ~ " << row_scores(order.at(order.size() - 1))); std::vector<std::string> out_rows; out_rows.reserve(nmax); Index NNZ = 0; Index Nrow = 0; index_map_t remap; for (Index i = 0; i < nmax; ++i) { const Index j = order.at(i); const Scalar s = row_scores(j); if (s < options.cutoff) break; out_rows.emplace_back(rows.at(j)); NNZ += Nvec.at(j); remap[j] = i; Nrow++; } TLOG("Filter in " << Nrow << " rows with " << NNZ << " elements"); if (NNZ < 1) ELOG("Found no element to write out"); std::string temp_mtx_file = options.output + "_temp.mtx.gz"; std::string output_row_file = options.output + ".rows.gz"; if (file_exists(temp_mtx_file)) { WLOG("Delete this pre-existing temporary file: " << temp_mtx_file); std::remove(temp_mtx_file.c_str()); } copier_t copier(temp_mtx_file, remap, NNZ); visit_matrix_market_file(options.mtx_file, copier); write_vector_file(output_row_file, out_rows); return temp_mtx_file; } /** * @param mtx_temp_file * @param options */ template <typename OPTIONS> int squeeze_columns(const std::string mtx_temp_file, OPTIONS &options) { using namespace mmutil::io; std::vector<std::string> cols; CHECK(read_vector_file(options.col_file, cols)); using copier_t = triplet_copier_remapped_cols_t<obgzf_stream, Index, Scalar>; using index_map_t = copier_t::index_map_t; Index max_row, max_col; std::vector<Index> nnz_col; std::tie(std::ignore, std::ignore, std::ignore, nnz_col, max_row, max_col) = compute_mtx_col_stat(mtx_temp_file); index_map_t remap; Index Ncol = 0; Index NNZ = 0; std::vector<std::string> out_cols; for (Index i = 0; i < max_col; ++i) { const Scalar nnz = nnz_col.at(i); if (nnz > options.COL_NNZ_CUTOFF) { remap[i] = Ncol; out_cols.emplace_back(cols.at(i)); ++Ncol; NNZ += nnz_col.at(i); } } TLOG("Found " << Ncol << " columns with the nnz > " << options.COL_NNZ_CUTOFF << " from the total " << max_col << " columns"); ERR_RET(NNZ < 1, "Found no element to write out"); std::string output_mtx_file = options.output + ".mtx.gz"; copier_t copier(output_mtx_file, remap, NNZ); visit_matrix_market_file(mtx_temp_file, copier); if (file_exists(mtx_temp_file)) { std::remove(mtx_temp_file.c_str()); } std::string output_col_file = options.output + ".cols.gz"; write_vector_file(output_col_file, out_cols); return EXIT_SUCCESS; } template <typename OPTIONS> int filter_row_by_score(OPTIONS &options) { std::string mtx_temp_file; switch (options.row_score) { case filter_row_options_t::NNZ: mtx_temp_file = _filter_row_by_score(select_nnz_t {}, options); break; case filter_row_options_t::MEAN: mtx_temp_file = _filter_row_by_score(select_mean_t {}, options); break; case filter_row_options_t::SD: mtx_temp_file = _filter_row_by_score(select_sd_t {}, options); break; case filter_row_options_t::CV: mtx_temp_file = _filter_row_by_score(select_cv_t {}, options); break; default: break; } return squeeze_columns(mtx_temp_file, options); } template <typename OPTIONS> int parse_filter_row_options(const int argc, // const char *argv[], // OPTIONS &options) { const char *_usage = "\n" "[Arguments]\n" "--mtx (-m) : data MTX file (M x N)\n" "--data (-m) : data MTX file (M x N)\n" "--row (-f) : row file (M x 1)\n" "--feature (-f) : row file (M x 1)\n" "--col (-c) : data column file (N x 1)\n" "--out (-o) : Output file header\n" "\n" "[Options]\n" "\n" "--score (-S) : a type of row scores {NNZ, MEAN, CV}\n" "--ntop (-t) : number of top features\n" "--cutoff (-k) : cutoff of row-wise scores\n" "--col_cutoff (-C) : column's #non-zero cutoff\n" "\n" "[Output]\n" "${out}.mtx.gz, ${out}.rows.gz, ${out}.cols.gz\n" "\n"; const char *const short_opts = "m:c:f:o:t:k:C:S:"; const option long_opts[] = { { "mtx", required_argument, nullptr, 'm' }, // { "data", required_argument, nullptr, 'm' }, // { "feature", required_argument, nullptr, 'f' }, // { "row", required_argument, nullptr, 'f' }, // { "col", required_argument, nullptr, 'c' }, // { "out", required_argument, nullptr, 'o' }, // { "output", required_argument, nullptr, 'o' }, // { "ntop", required_argument, nullptr, 't' }, // { "Ntop", required_argument, nullptr, 't' }, // { "nTop", required_argument, nullptr, 't' }, // { "cutoff", required_argument, nullptr, 'k' }, // { "Cutoff", required_argument, nullptr, 'k' }, // { "col_cutoff", required_argument, nullptr, 'C' }, // { "col_nnz_cutoff", required_argument, nullptr, 'C' }, // { "score", required_argument, nullptr, 'S' }, // { nullptr, no_argument, nullptr, 0 } }; while (true) { const auto opt = getopt_long(argc, // const_cast<char **>(argv), // short_opts, // long_opts, // nullptr); if (-1 == opt) break; switch (opt) { case 'm': options.mtx_file = std::string(optarg); break; case 'f': options.row_file = std::string(optarg); break; case 'c': options.col_file = std::string(optarg); break; case 'o': options.output = std::string(optarg); break; case 'S': options.set_row_score(std::string(optarg)); break; case 't': options.Ntop = std::stoi(optarg); break; case 'k': options.cutoff = std::stof(optarg); break; case 'C': options.COL_NNZ_CUTOFF = std::stoi(optarg); break; case 'h': // -h or --help case '?': // Unrecognized option std::cerr << _usage << std::endl; return EXIT_FAILURE; default: // ; } } ERR_RET(!file_exists(options.mtx_file), "No MTX data file"); ERR_RET(!file_exists(options.col_file), "No COL data file"); ERR_RET(!file_exists(options.row_file), "No ROW data file"); ERR_RET(options.Ntop <= 0 && options.cutoff <= 0, "Must have positive Ntop or cutoff value"); return EXIT_SUCCESS; } #endif
27.971098
80
0.553007
YPARK
87e331558166674138bd74c4bbfc5ac03acb220d
758
cpp
C++
relacy/dyn_thread.cpp
pereckerdal/relacy
05d8a8fbb0b3600ff5bf34da0bab2bb148dff059
[ "BSD-3-Clause" ]
1
2020-05-30T13:06:12.000Z
2020-05-30T13:06:12.000Z
relacy/dyn_thread.cpp
pereckerdal/relacy
05d8a8fbb0b3600ff5bf34da0bab2bb148dff059
[ "BSD-3-Clause" ]
null
null
null
relacy/dyn_thread.cpp
pereckerdal/relacy
05d8a8fbb0b3600ff5bf34da0bab2bb148dff059
[ "BSD-3-Clause" ]
null
null
null
/* Relacy Race Detector * Copyright (c) 2008-2013, Dmitry S. Vyukov * All rights reserved. * This software is provided AS-IS with no warranty, either express or implied. * This software is distributed under a license and may not be copied, * modified or distributed except as expressly authorized under the * terms of the license contained in the file LICENSE in this distribution. */ #include "dyn_thread.hpp" #include "context_base.hpp" namespace rl { dyn_thread::dyn_thread() { handle_ = 0; } void dyn_thread::start(void*(*fn)(void*), void* arg) { RL_VERIFY(handle_ == 0); handle_ = ctx().create_thread(fn, arg); } void dyn_thread::join() { RL_VERIFY(handle_); handle_->wait(false, false, $); handle_ = 0; } }
21.055556
80
0.691293
pereckerdal
87e46074782715fbcf6ee032cd28ab6c633b4cb2
341
cpp
C++
src/Main.cpp
SMelanko/BattleCity
7d0042561f97ee9d1b61e027b1dd451494eaefee
[ "MIT" ]
null
null
null
src/Main.cpp
SMelanko/BattleCity
7d0042561f97ee9d1b61e027b1dd451494eaefee
[ "MIT" ]
null
null
null
src/Main.cpp
SMelanko/BattleCity
7d0042561f97ee9d1b61e027b1dd451494eaefee
[ "MIT" ]
null
null
null
#include "include/Game.h" #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); try { return Game{ argc, argv }.exec(); } catch (const std::exception& e) { qDebug() << e.what(); } catch (...) { qDebug() << QStringLiteral("Unhandled exception has been occurred"); } }
20.058824
70
0.656891
SMelanko
87e7b9dffaa130bdb830863c5ca11e02d1e1fb36
5,176
cpp
C++
src/viplist.cpp
Nakeib/RonClient
9e816c580ec2a6f1b15fdefd8e15ad62647ca29f
[ "MIT" ]
11
2020-11-07T19:35:24.000Z
2021-08-19T12:25:27.000Z
src/viplist.cpp
Nakeib/RonClient
9e816c580ec2a6f1b15fdefd8e15ad62647ca29f
[ "MIT" ]
null
null
null
src/viplist.cpp
Nakeib/RonClient
9e816c580ec2a6f1b15fdefd8e15ad62647ca29f
[ "MIT" ]
5
2020-11-06T20:52:11.000Z
2021-02-25T11:02:31.000Z
/* -------------------------------------------------------------------------- */ /* ------------- RonClient --- Oficial client for RonOTS servers ------------ */ /* -------------------------------------------------------------------------- */ #include "viplist.h" #include "allocator.h" #include "creature.h" #include "window.h" #include "tools.h" // ---- VIPList ---- // VIPList::VIPList() { container = NULL; } VIPList::~VIPList() { } void VIPList::AddCreature(unsigned int creatureID, std::string creatureName, bool online) { LOCKCLASS lockClass(lockVIPList); if (online) { std::map<unsigned int, std::string>::iterator it = viplist_online.find(creatureID); if (it == viplist_online.end()) viplist_online[creatureID] = creatureName; } else { std::map<unsigned int, std::string>::iterator it = viplist_offline.find(creatureID); if (it == viplist_offline.end()) viplist_offline[creatureID] = creatureName; } } void VIPList::LoginCreature(unsigned int creatureID) { LOCKCLASS lockClass(lockVIPList); std::map<unsigned int, std::string>::iterator it = viplist_offline.find(creatureID); if (it != viplist_offline.end()) { AddCreature(it->first, it->second, true); viplist_offline.erase(it); } } void VIPList::LogoutCreature(unsigned int creatureID) { LOCKCLASS lockClass(lockVIPList); std::map<unsigned int, std::string>::iterator it = viplist_online.find(creatureID); if (it != viplist_online.end()) { AddCreature(it->first, it->second, false); viplist_online.erase(it); } } void VIPList::RemoveCreature(unsigned int creatureID) { LOCKCLASS lockClass(lockVIPList); std::map<unsigned int, std::string>::iterator it = viplist_offline.find(creatureID); if (it != viplist_offline.end()) viplist_offline.erase(it); it = viplist_online.find(creatureID); if (it != viplist_online.end()) viplist_online.erase(it); } void VIPList::ClearVIPList() { LOCKCLASS lockClass(lockVIPList); viplist_offline.clear(); viplist_online.clear(); } unsigned int VIPList::GetCreatureID(std::string creatureName) { LOCKCLASS lockClass(lockVIPList); std::map<unsigned int, std::string>::iterator it = viplist_offline.begin(); for (it; it != viplist_offline.end(); it++) { if (it->second == creatureName) return it->first; } it = viplist_online.begin(); for (it; it != viplist_online.end(); it++) { if (it->second == creatureName) return it->first; } return 0; } std::string VIPList::GetCreatureName(unsigned int creatureID) { LOCKCLASS lockClass(lockVIPList); std::map<unsigned int, std::string>::iterator it = viplist_offline.find(creatureID); if (it != viplist_offline.end()) return it->second; it = viplist_online.find(creatureID); if (it != viplist_online.end()) return it->second; return ""; } void VIPList::SetContainer(WindowElementContainer* container) { LOCKCLASS lockClass(lockVIPList); this->container = container; } void VIPList::UpdateContainer() { LOCKCLASS lockClass1(Windows::lockWindows); LOCKCLASS lockClass2(lockVIPList); if (!container) return; container->DeleteAllElements(); Window* window = container->GetWindow(); window->SetActiveElement(NULL); POINT size = window->GetSize(true); WindowElementVIP* vip = new(M_PLACE) WindowElementVIP; vip->Create(0, 0, 0, 0xFFFF, 0xFFFF, false, false, window->GetWindowTemplate()); vip->SetVIPList(this); vip->SetCreatureID(0x00); window->AddElement(vip); std::map<std::string, unsigned int> s_online; std::map<std::string, unsigned int> s_offline; std::map<unsigned int, std::string>::iterator _it = viplist_online.begin(); for (_it; _it != viplist_online.end(); _it++) s_online[_it->second] = _it->first; _it = viplist_offline.begin(); for (_it; _it != viplist_offline.end(); _it++) s_offline[_it->second] = _it->first; int posY = 0; std::map<std::string, unsigned int>::iterator it = s_online.begin(); for (it; it != s_online.end(); it++) { std::string creatureName = it->first; unsigned int creatureID = it->second; WindowElementText* text = new(M_PLACE) WindowElementText; text->Create(0, 5, posY, 0xFFFF, window->GetWindowTemplate()); text->SetText(creatureName); text->SetColor(0.0f, 1.0f, 0.0f); text->SetBorder(1); posY += 15; WindowElementVIP* vip = new(M_PLACE) WindowElementVIP; vip->Create(0, 0, posY - 15, 0xFFFF, 15, false, false, window->GetWindowTemplate()); vip->SetVIPList(this); vip->SetCreatureID(creatureID); container->AddElement(text); container->AddElement(vip); } it = s_offline.begin(); for (it; it != s_offline.end(); it++) { std::string creatureName = it->first; unsigned int creatureID = it->second; WindowElementText* text = new(M_PLACE) WindowElementText; text->Create(0, 5, posY, 0xFFFF, window->GetWindowTemplate()); text->SetText(creatureName); text->SetColor(0.8f, 0.0f, 0.0f); text->SetBorder(1); posY += 15; WindowElementVIP* vip = new(M_PLACE) WindowElementVIP; vip->Create(0, 0, posY - 15, 0xFFFF, 15, false, false, window->GetWindowTemplate()); vip->SetVIPList(this); vip->SetCreatureID(creatureID); container->AddElement(text); container->AddElement(vip); } container->SetIntSize(0, posY); }
27.386243
91
0.680255
Nakeib
87e7be107549467a30f19389059476637237fe6f
4,317
cc
C++
caffe2/operators/summarize_op_hipdev.cc
ashishfarmer/rocm-caffe2
097fe3f71b0e4311340ff7eb797ed6c351073d54
[ "Apache-2.0" ]
12
2018-04-14T22:00:51.000Z
2018-07-26T16:44:20.000Z
caffe2/operators/summarize_op_hipdev.cc
ashishfarmer/rocm-caffe2
097fe3f71b0e4311340ff7eb797ed6c351073d54
[ "Apache-2.0" ]
27
2018-04-14T06:44:22.000Z
2018-08-01T18:02:39.000Z
caffe2/operators/summarize_op_hipdev.cc
ashishfarmer/rocm-caffe2
097fe3f71b0e4311340ff7eb797ed6c351073d54
[ "Apache-2.0" ]
2
2018-04-16T20:46:16.000Z
2018-06-01T21:00:10.000Z
/** * Copyright (c) 2016-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrust/device_vector.h> #include <thrust/transform_reduce.h> #include <thrust/system/cuda/execution_policy.h> #include "caffe2/operators/summarize_op.h" #include "caffe2/core/context_hip.h" namespace caffe2 { namespace { // structure used to accumulate the moments and other statistical properties // encountered so far. template <typename T> struct SummaryStatsData { T n; T min; T max; T mean; T M2; // initialize to the identity element void initialize() { n = mean = M2 = 0; min = std::numeric_limits<T>::max(); max = std::numeric_limits<T>::min(); } T variance() { return (n == 1 ? 0 : M2 / (n - 1)); } }; // stats_unary_op is a functor that takes in a value x and // returns a variace_data whose mean value is initialized to x. template <typename T> struct summary_stats_unary_op { __host__ __device__ SummaryStatsData<T> operator()(const T& x) const { SummaryStatsData<T> result; result.n = 1; result.min = x; result.max = x; result.mean = x; result.M2 = 0; return result; } }; // summary_stats_binary_op is a functor that accepts two SummaryStatsData // structs and returns a new SummaryStatsData which are an // approximation to the summary_stats for // all values that have been agregated so far template <typename T> struct summary_stats_binary_op : public thrust::binary_function<const SummaryStatsData<T>&, const SummaryStatsData<T>&, SummaryStatsData<T>> { __host__ __device__ SummaryStatsData<T> operator()(const SummaryStatsData<T>& x, const SummaryStatsData<T>& y) const { SummaryStatsData<T> result; T n = x.n + y.n; T delta = y.mean - x.mean; T delta2 = delta * delta; result.n = n; result.min = thrust::min(x.min, y.min); result.max = thrust::max(x.max, y.max); result.mean = x.mean + delta * y.n / n; result.M2 = x.M2 + y.M2; result.M2 += delta2 * x.n * y.n / n; return result; } }; } // namespace template <> bool SummarizeOp<float, HIPContext>::RunOnDevice() { auto& X = Input(0); const int N = X.size(); DCHECK_GT(N, 0); // TODO(Yangqing): Any better way to avoid having to const cast? thrust::device_ptr<float> Xdata(const_cast<float*>(X.data<float>())); summary_stats_unary_op<float> unary_op; summary_stats_binary_op<float> binary_op; SummaryStatsData<float> init; init.initialize(); // compute summary statistics SummaryStatsData<float> result = thrust::transform_reduce( #if THRUST_VERSION >= 100800 thrust::cuda::par.on(context_.hip_stream()), #endif // THRUST_VERSION >= 100800 Xdata, Xdata + N, unary_op, init, binary_op); float standard_deviation = std::sqrt(result.variance()); if(to_file_) { (*log_file_) << result.min << " " << result.max << " " << result.mean << " " << standard_deviation << std::endl; } if(OutputSize()) { auto* Y = OperatorBase::Output<TensorHIP>(0); Y->Resize(4); float output_buffer[NUM_STATS] = {result.min, result.max, result.mean, standard_deviation}; context_.Copy<float, CPUContext, HIPContext>( NUM_STATS, output_buffer, Y->mutable_data<float>()); } return true; } REGISTER_HIP_OPERATOR(Summarize, SummarizeOp<float, HIPContext>); } // namespace caffe2
31.510949
99
0.615242
ashishfarmer
87ee1f1ce6d84e0e971d1f07d3d50b2a8b9e0431
671
cpp
C++
Source/SFXUtilities/Utilities/FMathUtils.cpp
pro100watt/VolumetricAmbientDemo
3a0f877e51ca59984c1638a6592c55b5bb8e56b1
[ "MIT" ]
null
null
null
Source/SFXUtilities/Utilities/FMathUtils.cpp
pro100watt/VolumetricAmbientDemo
3a0f877e51ca59984c1638a6592c55b5bb8e56b1
[ "MIT" ]
null
null
null
Source/SFXUtilities/Utilities/FMathUtils.cpp
pro100watt/VolumetricAmbientDemo
3a0f877e51ca59984c1638a6592c55b5bb8e56b1
[ "MIT" ]
null
null
null
#include "FMathUtils.h" #include "Math/Vector2D.h" namespace Utils { namespace FMathExt { bool IsInsideTriangle2D(const FVector2D& A, const FVector2D& B, const FVector2D& C, const FVector2D& Point) { FVector2D ALocal = A - C; FVector2D BLocal = B - C; FVector2D PointLocal = Point - C; return IsInsideTriangleLocal2D(ALocal, BLocal, PointLocal); } bool IsInsideTriangleLocal2D(const FVector2D& A, const FVector2D& B, const FVector2D& Point) { float LCross = A ^ Point; float RCross = Point ^ B; ensure(LCross >= 0.f && RCross >= 0.f); float InvHalfArea = 1.f / (A ^ B); return 1.f >= InvHalfArea * (LCross + RCross); } } }
22.366667
109
0.66766
pro100watt
87f25ce11aa13e0204711b73553d5baa425c2f36
1,137
cc
C++
mycode/cpp/rvlue_SmartPointer/smartPointer.cc
stdbilly/CS_Note
a8a87e135a525d53c283a4c70fb942c9ca59a758
[ "MIT" ]
2
2020-12-09T09:55:51.000Z
2021-01-08T11:38:22.000Z
mycode/cpp/rvlue_SmartPointer/smartPointer.cc
stdbilly/CS_Note
a8a87e135a525d53c283a4c70fb942c9ca59a758
[ "MIT" ]
null
null
null
mycode/cpp/rvlue_SmartPointer/smartPointer.cc
stdbilly/CS_Note
a8a87e135a525d53c283a4c70fb942c9ca59a758
[ "MIT" ]
null
null
null
#include <iostream> using std::cout; using std::endl; template<typename T> class SmartPointer { public: SmartPointer(T* p) : _p(p) {} T* operator->() { return _p; } T& operator*() { return *_p; } T* get() { return _p; } void reset(T* p) { delete _p; _p = p; } ~SmartPointer() { if(_p) { delete _p; } } private: T* _p; }; class Point { public: Point(int ix = 0, int iy = 0) : _ix(ix) , _iy(iy) { cout << "Point(int,int)" << endl; } friend std::ostream & operator<<(std::ostream & os, const Point & rhs); void print() const { cout << "(" << _ix << "," << _iy << ")" << endl; } ~Point(){ cout << "~Point()" << endl; } private: int _ix; int _iy; }; std::ostream & operator<<(std::ostream & os, const Point & rhs) { os << "(" << rhs._ix << "," << rhs._iy << ")"; return os; } int main() { SmartPointer<Point> pointer(new Point(1, 2)); cout << *pointer << endl; return 0; }
14.766234
75
0.441513
stdbilly
87f3f49a9bb513dc0ecbbba5b880c84e82e815db
1,607
cpp
C++
Source/TreeSearch/PriorProbability.cpp
StuartRiffle/corvid
21fbea9bf585f3713354f33a205e9fd8b96da555
[ "MIT" ]
6
2019-05-29T03:22:41.000Z
2021-03-02T09:08:16.000Z
Source/TreeSearch/PriorProbability.cpp
StuartRiffle/corvid
21fbea9bf585f3713354f33a205e9fd8b96da555
[ "MIT" ]
1
2019-05-29T16:15:55.000Z
2019-05-29T16:15:55.000Z
Source/TreeSearch/PriorProbability.cpp
StuartRiffle/corvid
21fbea9bf585f3713354f33a205e9fd8b96da555
[ "MIT" ]
null
null
null
// JAGLAVAK CHESS ENGINE (c) 2019 Stuart Riffle #include "Jaglavak.h" #include "TreeSearch.h" #include "FEN.h" #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> using namespace boost; namespace pt = property_tree; #include "RpcClient.h" void TreeSearch::EstimatePriors( TreeNode* node ) { CallRef call( new RpcCall() ); call->_ServerType = "inference"; call->_Inputs.put( "type", "estimate_priors" ); call->_Inputs.put( "position", SerializePosition( node->_Pos ) ); _RpcClient->Call( call ); while( !call->_Done ) { // ------------------------ _SearchFibers.YieldFiber(); // ------------------------ } if( call->_Success ) { vector< string > moveList = SplitString( call->_Outputs.get< string >( "moves" ) ); vector< string > valueList = SplitString( call->_Outputs.get< string >( "values" ) ); assert( moveList.size() == valueList.size() ); assert( moveList.size() == node->_Branch.size() ); map< string, float > moveValue; for( int i = 0; i < (int) moveList.size(); i++ ) moveValue[moveList[i]] = (float) atof( valueList[i].c_str() ); for( int i = 0; i < node->_Branch.size(); i++ ) node->_Branch[i]._Prior = moveValue[SerializeMoveSpec( node->_Branch[i]._Move )]; } float scaleNoise = _Settings->Get< float >( "Search.PriorNoise" ); for( int i = 0; i < node->_Branch.size(); i++ ) { float noise = _RandomGen.GetNormal() * scaleNoise; node->_Branch[i]._Prior += noise; } }
29.759259
93
0.583696
StuartRiffle
87f975ec8a77a7396a33f198ac3a8e6207b29056
2,776
hpp
C++
include/response.hpp
pgul/fastlst
ce07baa06b0063f4c9e1374f24e67e1316ee5af4
[ "BSD-3-Clause" ]
2
2018-01-14T02:49:46.000Z
2021-04-11T11:29:11.000Z
include/response.hpp
pgul/fastlst
ce07baa06b0063f4c9e1374f24e67e1316ee5af4
[ "BSD-3-Clause" ]
null
null
null
include/response.hpp
pgul/fastlst
ce07baa06b0063f4c9e1374f24e67e1316ee5af4
[ "BSD-3-Clause" ]
1
2018-01-10T19:44:14.000Z
2018-01-10T19:44:14.000Z
/*****************************************************************************/ /* */ /* (C) Copyright 1991-1997 Alberto Pasquale */ /* */ /* A L L R I G H T S R E S E R V E D */ /* */ /*****************************************************************************/ /* */ /* This source code is NOT in the public domain and it CANNOT be used or */ /* distributed without written permission from the author. */ /* */ /*****************************************************************************/ /* */ /* How to contact the author: Alberto Pasquale of 2:332/504@fidonet */ /* Viale Verdi 106 */ /* 41100 Modena */ /* Italy */ /* */ /*****************************************************************************/ /* RESPONSE.Hpp */ #ifndef RESPONSE_HPP #define RESPONSE_HPP #include <time.h> #include <stdarg.h> #include "types.hpp" extern "C" { #include <smapi/msgapi.h> }; class _RSP { public: HAREA msg; /* Area handle */ XMSG rsphd; /* MSG header for response */ char *rsptxt; /* text (ASCIIZ); text + tear + Origin (MsgSize+160) */ char *origin; // Origin uint rsplen; /* Lenght of rsptxt */ uint part; /* Part # of message response */ uint partpos; /* "Part #" ofset in subject */ long unix4ascii; // Unix time for ASCII field, to avoid false DUPES with Squish _RSP (void); ~_RSP (void); }; // if origin == NULL -> no origin _RSP *writerspheader (HAREA msg, char *from, ADR *fmadr, char *to, ADR *toadr, char *subject, word flags, char *origin); void vwritersp (_RSP *rsp, char *strfmt, va_list args); void writersp (_RSP *rsp, char *strfmt,...); // if rsp == NULL, the function returns immediately, with no error void closersp (_RSP *rsp, BOOL thrash = FALSE); void getmsgdate(struct _stamp *date, time_t timer); dword uid (void); void SetOrigin (char *buffer, char *origin, ADR *adr); #endif
41.432836
90
0.355187
pgul
87fa386fcae8872b4912d097c8eb152807332d1a
103,061
cpp
C++
src/clocktree.cpp
eric830303/MAUI-Making-Aging-Useful-Intentionally-
0a55385057708b08d83169b32475266c093b94bc
[ "MIT" ]
null
null
null
src/clocktree.cpp
eric830303/MAUI-Making-Aging-Useful-Intentionally-
0a55385057708b08d83169b32475266c093b94bc
[ "MIT" ]
null
null
null
src/clocktree.cpp
eric830303/MAUI-Making-Aging-Useful-Intentionally-
0a55385057708b08d83169b32475266c093b94bc
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////// // // Source File // // File name: clocktree.cpp // Author: Ting-Wei Chang // Date: 2017-07 // ////////////////////////////////////////////////////////////// #include "clocktree.h" #include <iterator> #include <fstream> #include <queue> #include <fcntl.h> #include <sys/wait.h> #include <sys/stat.h> #define RED "\x1b[31m" #define GREEN "\x1b[32m" #define YELLOW "\x1b[33m" #define BLUE "\x1b[34m" #define MAGENTA "\x1b[35m" #define CYAN "\x1b[36m" #define RESET "\x1b[0m" ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Private Method // Skip the line when parsing the timing report // ///////////////////////////////////////////////////////////////////// bool ClockTree::ifSkipLine(string line) { if(line.empty()) return true; else if(line.find("(net)") != string::npos) return true; else if(line.find("-----") != string::npos) return true; else if(line.find("Path Group:") != string::npos) return true; else if(line.find("Path Type:") != string::npos) return true; else if(line.find("Point") != string::npos) return true; else if(line.find("clock reconvergence pessimism") != string::npos) return true; else if(line.find("clock network delay (propagated)") != string::npos) return true; else return false; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Private Method // Count each type of critical paths and disable unused critical path // ///////////////////////////////////////////////////////////////////// void ClockTree::pathTypeChecking(void) { switch(this->_pathlist.back()->getPathType()) { case PItoFF: this->_pitoffnum++; if(this->_pathselect == 2) this->_pathlist.back()->setPathType(NONE); else this->_pathusednum++; break; case FFtoPO: this->_fftoponum++; if((this->_pathselect == 2) || (this->_pathselect == 1)) this->_pathlist.back()->setPathType(NONE); else this->_pathusednum++; break; case FFtoFF: this->_fftoffnum++; this->_pathusednum++; break; default: break; } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Private Method // Record the clock path of the startpoint/endpoint // Input parameter: // who: 's' => startpoint // 'e' => endpoint // ///////////////////////////////////////////////////////////////////// void ClockTree::recordClockPath(char who) { CriticalPath *path = this->_pathlist.back(); ClockTreeNode *node = nullptr; switch(who) { // startpoint case 's': node = path->getStartPonitClkPath().at(0); while(node != nullptr) { node = node->getParent(); path->getStartPonitClkPath().resize(path->getStartPonitClkPath().size()+1); path->getStartPonitClkPath().back() = node; } path->getStartPonitClkPath().pop_back(); reverse(path->getStartPonitClkPath().begin(), path->getStartPonitClkPath().end()); path->getStartPonitClkPath().shrink_to_fit(); break; // endpoint case 'e': node = path->getEndPonitClkPath().at(0); while(node != nullptr) { node = node->getParent(); path->getEndPonitClkPath().resize(path->getEndPonitClkPath().size()+1); path->getEndPonitClkPath().back() = node; } path->getEndPonitClkPath().pop_back(); reverse(path->getEndPonitClkPath().begin(), path->getEndPonitClkPath().end()); path->getEndPonitClkPath().shrink_to_fit(); break; default: break; } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Private Method // Record the last common node of the clock tree, i.e., the first // node has children from clock source // ///////////////////////////////////////////////////////////////////// void ClockTree::checkFirstChildrenFormRoot(void) { ClockTreeNode *findnode = this->_clktreeroot; while(1) { if(findnode->getChildren().size() == 1) findnode = findnode->getChildren().at(0); else { long count = 0; ClockTreeNode *recordnode = nullptr; for(long loop = 0;loop < findnode->getChildren().size();loop++) { if(findnode->getChildren().at(loop)->ifUsed() == 1) { count++; recordnode = findnode->getChildren().at(loop); } } if(count == 1) findnode = recordnode; else break; } } this->_firstchildrennode = findnode; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Private Method // Initial the upper and lower bound of Tc using in the Binary search // The higher boundary for non-aging and the lower boundary for aging // ///////////////////////////////////////////////////////////////////// void ClockTree::initTcBound(void) { this->_tcupbound = ceilNPrecision( this->_tc * ((this->_aging) ? getAgingRateByDutyCycle(0.5) : 1.4), 1 ); this->_tclowbound = floorNPrecision(this->_tc * 2 - this->_tcupbound, 1 ); } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Private Method // Generate all DCC constraint clauses according to every combinations // Input parameter: // comblist: combinations (2 dimension array) // ///////////////////////////////////////////////////////////////////// void ClockTree::genDccConstraintClause( vector<vector<long> > *comblist ) { for( long loop1 = 0; loop1 < comblist->size(); loop1++ ) { if( comblist->at(loop1).size() == 2 ) { // Generate 4 clauses based on two clock nodes string clause1, clause2, clause3, clause4; long nodenum1 = comblist->at(loop1).at(0), nodenum2 = comblist->at(loop1).at(1); clause1 = to_string((nodenum1 * -1)) + " " + to_string((nodenum2 * -1)) + " 0"; clause2 = to_string((nodenum1 * -1)) + " " + to_string(((nodenum2 + 1) * -1)) + " 0"; clause3 = to_string(((nodenum1 + 1) * -1)) + " " + to_string((nodenum2 * -1)) + " 0"; clause4 = to_string(((nodenum1 + 1) * -1)) + " " + to_string(((nodenum2 + 1) * -1)) + " 0"; if(this->_dccconstraintlist.size() < (this->_dccconstraintlist.max_size()-4)) { this->_dccconstraintlist.insert(clause1); this->_dccconstraintlist.insert(clause2); this->_dccconstraintlist.insert(clause3); this->_dccconstraintlist.insert(clause4); } else { cerr << "\033[32m[Info]: DCC Constraint List Full!\033[0m\n"; return; } } // Deal with the combination containing the number of nodes greater than two // (reduce to two nodes) else { vector<long> gencomb, simplify = comblist->at(loop1); vector<vector<long> > simplifylist; for(long loop2 = 0;loop2 <= (simplify.size()-2);loop2++) combination(loop2+1, simplify.size(), 1, gencomb, &simplifylist); updateCombinationList(&simplify, &simplifylist); this->genDccConstraintClause(&simplifylist); } } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Private Method // Update the clause according to the type of DCC // None => 00 // 20% DCC => 01 // 40% DCC => 10 // 80% DCC => 11 // Input parameter: // dcctype: 0 => None // 20 => 20% DCC // 40 => 40% DCC // 80 => 80% DCC // ///////////////////////////////////////////////////////////////////// void ClockTree::writeClauseByDccType( ClockTreeNode *node, string *clause, int dcctype ) { if((node == nullptr) || (clause == nullptr) || !node->ifPlacedDcc()) return ; long nodenum = node->getNodeNumber(); switch(dcctype) { case 0: *clause += to_string(nodenum) + " " + to_string(nodenum + 1) + " "; break; case 20: *clause += to_string(nodenum) + " " + to_string((nodenum + 1) * -1) + " "; break; case 40: *clause += to_string(nodenum * -1) + " " + to_string(nodenum + 1) + " "; break; case 80: *clause += to_string(nodenum * -1) + " " + to_string((nodenum + 1) * -1) + " "; break; default: break; } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Private Method // Update timing information of the critical path in a given DCC // deployment // Input parameter: // update: 0 => do not update // 1 => update // ///////////////////////////////////////////////////////////////////// double ClockTree::updatePathTimingWithDcc(CriticalPath *path, bool update) { if((this->_besttc == 0) || (path == nullptr)) return -1; if(update) this->_tc = this->_besttc; ClockTreeNode *sdccnode = nullptr, *edccnode = nullptr; vector<ClockTreeNode *> tmp; double slack = 9999; switch(path->getPathType()) { // Path type: input to FF case PItoFF: edccnode = path->findDccInClockPath('e'); if(edccnode == nullptr) slack = this->assessTimingWithoutDcc(path, 0, update); else { vector<double> cjtime = this->calculateClockLatencyWithDcc(path->getEndPonitClkPath(), edccnode); slack = this->assessTimingWithDcc(path, 0, cjtime.front(), 0 ,0, nullptr, nullptr, tmp, tmp, 0, update); } break; // Path type: FF to output case FFtoPO: sdccnode = path->findDccInClockPath('s'); if(sdccnode == nullptr) slack = this->assessTimingWithoutDcc(path, 0, update); else { vector<double> citime = this->calculateClockLatencyWithDcc(path->getStartPonitClkPath(), sdccnode); slack = this->assessTimingWithDcc(path, citime.front(), 0, 0 ,0, nullptr, nullptr, tmp, tmp, 0, update); } break; // Path type: FF to FF case FFtoFF: sdccnode = path->findDccInClockPath('s'); edccnode = path->findDccInClockPath('e'); if((sdccnode == nullptr) && (edccnode == nullptr)) slack = this->assessTimingWithoutDcc(path, 0, update); else { vector<double> citime = this->calculateClockLatencyWithDcc(path->getStartPonitClkPath(), sdccnode); vector<double> cjtime = this->calculateClockLatencyWithDcc(path->getEndPonitClkPath(), edccnode); slack = this->assessTimingWithDcc(path, citime.front(), cjtime.front(), 0 ,0, nullptr, nullptr, tmp, tmp, 0, update); } break; default: break; } return slack; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Private Method // Delete the whole clock tree for releasing memory // ///////////////////////////////////////////////////////////////////// void ClockTree::deleteClockTree(void) { if(this->_clktreeroot == nullptr) return; queue<ClockTreeNode *> nodequeue; ClockTreeNode *deletenode = nullptr; nodequeue.push(this->_clktreeroot); // BFS while(!nodequeue.empty()) { if(!nodequeue.front()->getChildren().empty()) { for(auto const &nodeptr : nodequeue.front()->getChildren()) nodequeue.push(nodeptr); } deletenode = nodequeue.front(); nodequeue.pop(); delete deletenode; } this->_clktreeroot = nullptr; this->_firstchildrennode = nullptr; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Private Method // Dump all DCC information (location and type) to a file // Reperent in: buffer_name DCC_type // ///////////////////////////////////////////////////////////////////// void ClockTree::dumpDccListToFile(void) { if(!this->_dumpdcc) return; fstream dccfile; if(this->_dumpdcc && !isDirectoryExist(this->_outputdir)) mkdir(this->_outputdir.c_str(), 0775); string filename = this->_outputdir + this->_timingreportdesign + ".dcc"; dccfile.open(filename, ios::out | fstream::trunc); if(!dccfile.is_open()) { cerr << "\033[31m[Error]: Cannot open " << filename << "\033[0m\n"; dccfile.close(); return; } if(!this->_dumpdcc || this->_dcclist.empty()) dccfile << "\n"; else for(auto const& node: this->_dcclist) dccfile << node.first << " " << node.second->getDccType() << "\n"; dccfile.close(); } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Private Method // Dump all clock gating cell information (location and gating // probability) to a file // Reperent in: buffer_name gating_probability // ///////////////////////////////////////////////////////////////////// void ClockTree::dumpClockGatingListToFile(void) { if(!this->_dumpcg) return; fstream cgfile; if(this->_dumpcg && !isDirectoryExist(this->_outputdir)) mkdir(this->_outputdir.c_str(), 0775); string filename = this->_outputdir + this->_timingreportdesign + ".cg"; cgfile.open(filename, ios::out | fstream::trunc); if(!cgfile.is_open()) { cerr << "\033[31m[Error]: Cannot open " << filename << "\033[0m\n"; cgfile.close(); return; } if(!this->_dumpcg || this->_cglist.empty()) cgfile << "\n"; else for(auto const& node: this->_cglist) cgfile << node.first << " " << node.second->getGatingProbability() << "\n"; cgfile.close(); } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Private Method // Dump all inserted buffer information (location and buffer delay) // to a file // Reperent in: buffer_name buffer_delay // ///////////////////////////////////////////////////////////////////// void ClockTree::dumpBufferInsertionToFile(void) { if(!this->_dumpbufins || (this->_insertbufnum == 0)) return; fstream bufinsfile; if(this->_dumpbufins && !isDirectoryExist(this->_outputdir)) mkdir(this->_outputdir.c_str(), 0775); string filename = this->_outputdir + this->_timingreportdesign + ".bufins"; bufinsfile.open(filename, ios::out | fstream::trunc); if(!bufinsfile.is_open()) { cerr << "\033[31m[Error]: Cannot open " << filename << "\033[0m\n"; bufinsfile.close(); return; } if(!this->_dumpbufins || (this->_insertbufnum == 0)) bufinsfile << "\n"; else { for(auto const& node: this->_buflist) if(node.second->ifInsertBuffer()) bufinsfile << node.first << " " << node.second->getInsertBufferDelay() << "\n"; for(auto const& node: this->_ffsink) if(node.second->ifInsertBuffer()) bufinsfile << node.first << " " << node.second->getInsertBufferDelay() << "\n"; } bufinsfile.close(); } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Destructor // ///////////////////////////////////////////////////////////////////// ClockTree::~ClockTree(void) { this->deleteClockTree(); for(long loop = 0;loop < this->_pathlist.size();loop++) this->_pathlist.at(loop)->~CriticalPath(); this->_pathlist.clear(); this->_pathlist.shrink_to_fit(); this->_ffsink.clear(); this->_buflist.clear(); this->_cglist.clear(); this->_dcclist.clear(); this->_dccconstraintlist.clear(); this->_timingconstraintlist.clear(); } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Check the commands from input // Input parameter: // message: error message // ///////////////////////////////////////////////////////////////////// int ClockTree::checkParameter(int argc, char **argv, string *message) { if( argc == 1 ) { *message = "\033[31m[ERROR]: Missing operand!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } for(int loop = 1;loop < argc;loop++) { if(( strcmp(argv[loop], "-h") == 0 ) || ( strcmp(argv[loop], "--help") == 0) ) { message->clear(); return -1; } else if(strcmp(argv[loop], "-nondcc") == 0) this->_placedcc = 0; // Do not insert DCC else if(strcmp(argv[loop], "-nonaging") == 0) this->_aging = 0; // Non-aging else if(strcmp(argv[loop], "-mindcc") == 0) this->_mindccplace = 1; // Minimize DCC deployment else if(strcmp(argv[loop], "-tc_recheck") == 0) this->_tcrecheck = 1; // Recheck Tc else if(strcmp(argv[loop], "-print=Clause") == 0) this->_printClause = 1; // Recheck Tc else if(strcmp(argv[loop], "-print=Node") == 0) this->_printClkNode = 1; // Recheck Tc else if(strcmp(argv[loop], "-mask_leng") == 0) { if(!isRealNumber(string(argv[loop+1])) || (stod(string(argv[loop+1])) < 0) || (stod(string(argv[loop+1])) > 1)) { *message = "\033[31m[ERROR]: Wrong length of mask!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } this->_maskleng = stod(string(argv[loop+1])); loop++; } else if(strcmp(argv[loop], "-mask_level") == 0) { if(!isRealNumber(string(argv[loop+1])) || (stol(string(argv[loop+1])) < 0)) { *message = "\033[31m[ERROR]: Wrong level of mask!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } this->_masklevel = stol(string(argv[loop+1])); loop++; } else if(strcmp(argv[loop], "-agingrate_tcq") == 0) { if(!isRealNumber(string(argv[loop+1])) || (stod(string(argv[loop+1])) <= 0)) { *message = "\033[31m[ERROR]: Wrong aging rate of tcq!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } this->_agingtcq = stod(string(argv[loop+1])); loop++; } else if(strcmp(argv[loop], "-agingrate_dij") == 0) { if(!isRealNumber(string(argv[loop+1])) || (stod(string(argv[loop+1])) <= 0)) { *message = "\033[31m[ERROR]: Wrong aging rate of dij!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } this->_agingdij = stod(string(argv[loop+1])); loop++; } else if(strcmp(argv[loop], "-agingrate_tsu") == 0) { if(!isRealNumber(string(argv[loop+1])) || (stod(string(argv[loop+1])) <= 0)) { *message = "\033[31m[ERROR]: Wrong aging rate of tsu!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } this->_agingtsu = stod(string(argv[loop+1])); loop++; } else if(strcmp(argv[loop], "-cg_percent") == 0) { if(!isRealNumber(string(argv[loop+1])) || (stod(string(argv[loop+1])) < 0) || (stod(string(argv[loop+1])) > 1)) { *message = "\033[31m[ERROR]: Wrong percent of clock gating cells replacement!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } this->_cgpercent = stod(string(argv[loop+1])); loop++; } else if(strcmp(argv[loop], "-gp_upbound") == 0) { if(!isRealNumber(string(argv[loop+1])) || (stoi(string(argv[loop+1])) < 0) || (stoi(string(argv[loop+1])) > 100)) { *message = "\033[31m[ERROR]: Wrong upperbound probability of clock gating!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } this->_gpupbound = stoi(string(argv[loop+1])); loop++; } else if(strcmp(argv[loop], "-gp_lowbound") == 0) { if(!isRealNumber(string(argv[loop+1])) || (stoi(string(argv[loop+1])) < 0) || (stoi(string(argv[loop+1])) > 100)) { *message = "\033[31m[ERROR]: Wrong lowerbound probability of clock gating!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } this->_gplowbound = stoi(string(argv[loop+1])); loop++; } else if(strncmp(argv[loop], "-path=", 6) == 0) { vector<string> strspl = stringSplit(string(argv[loop]), "="); if(strspl.back().compare("all") == 0) this->_pathselect = 0; // PItoFF, FFtoPO, and FFtoFF else if(strspl.back().compare("pi_ff") == 0) this->_pathselect = 1; // PItoFF and FFtoFF else if(strspl.back().compare("onlyff") == 0) this->_pathselect = 2; // FFtoFF else { *message = "\033[31m[ERROR]: Wrong path selection!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } } else if(strncmp(argv[loop], "-clockgating=", 13) == 0) { vector<string> strspl = stringSplit(string(argv[loop]), "="); if(strspl.back().compare("no") == 0) this->_clkgating = 0; // Do not replace buffers else if(strspl.back().compare("yes") == 0) this->_clkgating = 1; // Replace buffers else { *message = "\033[31m[ERROR]: Wrong clock gating setting!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } } else if(strncmp(argv[loop], "-gatingfile=", 12) == 0) { vector<string> strspl = stringSplit(string(argv[loop]), "="); if(!isFileExist(strspl.back())) { *message = "\033[31m[ERROR]: Gating file not found!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } this->_cgfilename.assign(strspl.back()); } else if(strncmp(argv[loop], "-bufinsert=", 11) == 0) { vector<string> strspl = stringSplit(string(argv[loop]), "="); if(strspl.back().compare("insert") == 0) this->_bufinsert = 1; // Insert buffers else if(strspl.back().compare("min_insert") == 0) this->_bufinsert = 2; // Insert buffers and minimize buffer insertion else { *message = "\033[31m[ERROR]: Wrong Buffer insertion setting!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } } else if(strncmp(argv[loop], "-dump=", 6) == 0) { vector<string> strspl = stringSplit(string(argv[loop]), "="); if(strspl.back().compare("dcc") == 0) this->_dumpdcc = 1; // Dump DCC list else if(strspl.back().compare("cg") == 0) this->_dumpcg = 1; // Dump clock gating cell list else if(strspl.back().compare("buf_ins") == 0) this->_dumpbufins = 1; // Dump inserted buffer list else if(strspl.back().compare("all") == 0) { this->_dumpdcc = 1; this->_dumpcg = 1; this->_dumpbufins = 1; } } else if(isFileExist(string(argv[loop]))) { // Check if the timing report exist or not if(!this->_timingreportfilename.empty()) { *message = "\033[31m[ERROR]: Too many timing reports!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } char path[100] = {'\0'}, *pathptr = nullptr; this->_timingreport.assign(argv[loop]); vector<string> strspl = stringSplit(this->_timingreport, "/"); this->_timingreportfilename.assign(strspl.back()); realpath(argv[loop], path); pathptr = strrchr(path, '/'); path[pathptr - path + 1] = '\0'; this->_timingreportloc.assign(path); } else { *message = "\033[31m[ERROR]: Missing operand!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } } if(_timingreportfilename.empty()) { *message = "\033[31m[ERROR]: Missing timing report!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } if(this->_gplowbound > this->_gpupbound) { *message = "\033[31m[ERROR]: Lower bound probability can't greater than upper bound!!\033[0m\n"; *message += "Try \"--help\" for more information.\n"; return -1; } if(!this->_aging) { // Non-aging for Tcq, Dij, and Tsu this->_agingtcq = 1, this->_agingdij = 1, this->_agingtsu = 1; } return 0; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Parse the timing report // ///////////////////////////////////////////////////////////////////// void ClockTree::parseTimingReport(void) { fstream tim_max; long pathnum = -1, maxlevel = -1; bool startscratchfile = false, pathstart = false, firclkedge = false; double clksourlate = 0, clktime = 0; string line; ClockTreeNode *parentnode = nullptr; tim_max.open(this->_timingreport, ios::in); if(!tim_max.is_open()) { cerr << "\033[31m[Error]: Cannot open " << this->_timingreport << "\033[0m\n"; tim_max.close(); abort(); } while(!tim_max.eof()) { getline(tim_max, line); if(line.find("Design :") != string::npos) { vector<string> strspl; strspl = stringSplit(line, " "); this->_timingreportdesign = strspl.at(2); } if((startscratchfile == false) && (line.find("Startpoint") != string::npos)) { startscratchfile = true; cout << "\033[32m[Info]: Bilding clock tree...\033[0m\n"; } if(startscratchfile) { // End of the timing report if((line.length() == 1) && (line.compare("1") == 0)) { startscratchfile = false; cout << "\033[32m[Info]: Clock tree complete.\033[0m\n"; break; } if(this->ifSkipLine(line)) continue; else { vector<string> strspl; strspl = stringSplit(line, " "); if(strspl.empty()) continue; if(line.find("Startpoint") != string::npos) { int type = NONE; if(strspl.size() > 2) { if(line.find("input port") != string::npos) type = PItoPO; else if(line.find("flip-flop") != string::npos) type = FFtoPO; } else { getline(tim_max, line); if(line.find("input port") != string::npos) type = PItoPO; else if(line.find("flip-flop") != string::npos) type = FFtoPO; } pathnum++; CriticalPath *path = new CriticalPath(strspl.at(1), type, pathnum); this->_pathlist.resize(this->_pathlist.size()+1); this->_pathlist.back() = path; } else if(line.find("Endpoint") != string::npos) { CriticalPath *path = this->_pathlist.back(); path->setEndPointName(strspl.at(1)); if(strspl.size() > 2) { if(line.find("flip-flop") != string::npos) path->setPathType(path->getPathType()+1); } else { getline(tim_max, line); if(line.find("flip-flop") != string::npos) path->setPathType(path->getPathType()+1); } this->pathTypeChecking(); } else if(line.find("(rise edge)") != string::npos) { if(this->_clktreeroot == nullptr) { ClockTreeNode *node = new ClockTreeNode(nullptr, this->_totalnodenum, 0, 1); node->getGateData()->setGateName(strspl.at(1)); node->getGateData()->setWireTime(stod(strspl.at(4))); node->getGateData()->setGateTime(stod(strspl.at(4))); // Assign two numbers to a node this->_totalnodenum += 2; this->_clktreeroot = node; //this->_buflist.insert(pair<string, ClockTreeNode *> (strspl.at(1), node)); } if(firclkedge) { firclkedge = false; this->_origintc = stod(strspl.at(5)) - clktime; } else { firclkedge = true; clktime = stod(strspl.at(5)); } } else if(line.find("clock source latency") != string::npos) clksourlate = stod(strspl.at(3)); else if(line.find("data arrival time") != string::npos) this->_pathlist.back()->setArrivalTime(stod(strspl.at(3))); else if(line.find("data required time") != string::npos) this->_pathlist.back()->setRequiredTime(stod(strspl.at(3)) + abs(this->_pathlist.back()->getClockUncertainty())); else if(line.find("input external delay") != string::npos) { if((this->_pathlist.back()->getPathType() == PItoPO) || (this->_pathlist.back()->getPathType() == PItoFF)) this->_pathlist.back()->setTinDelay(stod(strspl.at(3))); } else if(line.find("output external delay") != string::npos) { // Assign to Tsu if((this->_pathlist.back()->getPathType() == PItoPO) || (this->_pathlist.back()->getPathType() == FFtoPO)) this->_pathlist.back()->setTsu(stod(strspl.at(3))); } else if(line.find("clock uncertainty") != string::npos) this->_pathlist.back()->setClockUncertainty(stod(strspl.at(2))); else if(line.find("library setup time") != string::npos) this->_pathlist.back()->setTsu(stod(strspl.at(3))); // Clock source else if(line.find("(in)") != string::npos) { if(strspl.at(0).compare(this->_clktreeroot->getGateData()->getGateName()) == 0) // clock input parentnode = this->_clktreeroot; else if(strspl.at(0).compare(this->_pathlist.back()->getStartPointName()) == 0) // input port { pathstart = true; GateData *pathnode = new GateData(this->_pathlist.back()->getStartPointName(), stod(strspl.at(3)), 0); this->_pathlist.back()->getGateList().resize(this->_pathlist.back()->getGateList().size()+1); this->_pathlist.back()->getGateList().back() = pathnode; } } else if(line.find("slack (") != string::npos) { this->_pathlist.back()->setSlack(stod(strspl.at(2)) + abs(this->_pathlist.back()->getClockUncertainty())); switch(this->_pathlist.back()->getPathType()) { case PItoFF: this->recordClockPath('e'); break; case FFtoPO: this->recordClockPath('s'); break; case FFtoFF: this->recordClockPath('s'); this->recordClockPath('e'); break; default: break; } this->_pathlist.back()->getGateList().shrink_to_fit(); pathstart = false, firclkedge = false, parentnode = nullptr; } else { CriticalPath *path = this->_pathlist.back(); vector<string> namespl; bool scratchnextline = false; namespl = stringSplit(strspl.at(0), "/"); if(line.find("/") != string::npos) scratchnextline = true; // Deal with combinational logic nodes if(pathstart) { GateData *pathnode = new GateData(namespl.at(0), stod(strspl.at(3)), 0); if(namespl.at(0).compare(path->getEndPointName()) == 0) { pathstart = false; path->setDij(stod(strspl.at(5)) - path->getCi() - path->getTcq() - path->getTinDelay()); } if(scratchnextline && pathstart) { getline(tim_max, line); strspl = stringSplit(line, " "); pathnode->setGateTime(stod(strspl.at(3))); } path->getGateList().resize(path->getGateList().size()+1); path->getGateList().back() = pathnode; } // Deal with clock tree buffers else { ClockTreeNode *findnode = nullptr; bool sameinsameout = false; if((this->_pathlist.back()->getStartPointName().compare(path->getEndPointName()) == 0) && (path->getStartPonitClkPath().size() > 0)) sameinsameout = true; // Meet the startpoint FF/input if((namespl.at(0).compare(path->getStartPointName()) == 0) && (sameinsameout == false)) { pathstart = true; findnode = parentnode->searchChildren(namespl.at(0)); path->setCi(stod(strspl.at(5))); if(findnode == nullptr) { ClockTreeNode *node = new ClockTreeNode(parentnode, this->_totalnodenum, parentnode->getDepth()+1); node->getGateData()->setGateName(namespl.at(0)); node->getGateData()->setWireTime(stod(strspl.at(3))); this->_ffsink.insert(pair<string, ClockTreeNode *> (namespl.at(0), node)); if((path->getPathType() == PItoPO) || (path->getPathType() == NONE)) node->setIfUsed(0); parentnode->getChildren().resize(parentnode->getChildren().size()+1); parentnode->getChildren().back() = node; if(node->getDepth() > maxlevel) maxlevel = node->getDepth(); // Assign two numbers to a node this->_totalnodenum += 2; findnode = node, parentnode = nullptr; } if(scratchnextline) { getline(tim_max, line); strspl = stringSplit(line, " "); findnode->getGateData()->setGateTime(stod(strspl.at(3))); } GateData *pathnode = new GateData(path->getStartPointName(), findnode->getGateData()->getWireTime(), findnode->getGateData()->getGateTime()); path->getGateList().resize(path->getGateList().size()+1); path->getGateList().back() = pathnode; path->getStartPonitClkPath().resize(path->getStartPonitClkPath().size()+1); path->getStartPonitClkPath().back() = findnode; if((path->getPathType() == PItoFF) || (path->getPathType() == FFtoPO) || (path->getPathType() == FFtoFF)) { if(findnode->ifUsed() != 1) this->_ffusednum++; findnode->setIfUsed(1); } if((path->getPathType() == FFtoPO) || (path->getPathType() == FFtoFF)) path->setTcq(findnode->getGateData()->getGateTime()); } // Meet the endpoint FF/output else if(!firclkedge && (namespl.at(0).compare(path->getEndPointName()) == 0)) { findnode = parentnode->searchChildren(namespl.at(0)); if(findnode == nullptr) { ClockTreeNode *node = new ClockTreeNode(parentnode, this->_totalnodenum, parentnode->getDepth()+1); node->getGateData()->setGateName(namespl.at(0)); node->getGateData()->setWireTime(stod(strspl.at(3))); this->_ffsink.insert(pair<string, ClockTreeNode *> (namespl.at(0), node)); if((path->getPathType() == PItoPO) || (path->getPathType() == NONE)) node->setIfUsed(0); parentnode->getChildren().resize(parentnode->getChildren().size()+1); parentnode->getChildren().back() = node; if(node->getDepth() > maxlevel) maxlevel = node->getDepth(); // Assign two numbers to a node this->_totalnodenum += 2; findnode = node, parentnode = nullptr; } path->getEndPonitClkPath().resize(path->getEndPonitClkPath().size()+1); path->getEndPonitClkPath().back() = findnode; path->setCj(stod(strspl.at(5)) - this->_origintc); if((path->getPathType() == PItoFF) || (path->getPathType() == FFtoPO) || (path->getPathType() == FFtoFF)) { if(findnode->ifUsed() != 1) this->_ffusednum++; findnode->setIfUsed(1); } } // Meet clock buffers else { findnode = parentnode->searchChildren(namespl.at(0)); if(findnode == nullptr) { ClockTreeNode *node = new ClockTreeNode(parentnode, this->_totalnodenum, parentnode->getDepth()+1); node->getGateData()->setGateName(namespl.at(0)); node->getGateData()->setWireTime(stod(strspl.at(3))); this->_buflist.insert(pair<string, ClockTreeNode *> (namespl.at(0), node)); if((path->getPathType() == PItoPO) || (path->getPathType() == NONE)) node->setIfUsed(0); parentnode->getChildren().resize(parentnode->getChildren().size()+1); parentnode->getChildren().back() = node; // Assign two numbers to a node this->_totalnodenum += 2; if(scratchnextline) { getline(tim_max, line); strspl = stringSplit(line, " "); node->getGateData()->setGateTime(stod(strspl.at(3))); } findnode = node, parentnode = node; } else { parentnode = findnode; if(scratchnextline) getline(tim_max, line); } if((path->getPathType() == PItoFF) || (path->getPathType() == FFtoPO) || (path->getPathType() == FFtoFF)) { if(findnode->ifUsed() != 1) this->_bufferusednum++; findnode->setIfUsed(1); } } } } } } } tim_max.close(); this->_totalnodenum /= 2; this->_maxlevel = maxlevel; this->checkFirstChildrenFormRoot(); this->_outputdir = "./" + this->_timingreportdesign + "_output/"; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Replace buffers to clock gating cells // ///////////////////////////////////////////////////////////////////// void ClockTree::clockGatingCellReplacement(void) { if( !this->_clkgating ) return; // Get the replacement from cg file if the cg file exist if(!this->_cgfilename.empty()) { fstream cgfile; string line; cout << "\033[32m[Info]: Open the setting file of clock gating cells.\033[0m\n"; cgfile.open(this->_cgfilename, ios::in); if(!cgfile.is_open()) { cerr << "\033[31m[Error]: Cannot open " << this->_cgfilename << "\033[0m\n"; cgfile.close(); return; } cout << "\033[32m[Info]: Replacing some buffers to clock gating cells...\033[0m\n"; while(!cgfile.eof()) { getline(cgfile, line); if(line.empty()) continue; vector<string> strspl = stringSplit(line, " "); map<string, ClockTreeNode *>::iterator findptr = this->_buflist.find(strspl.at(0)); if(findptr != this->_buflist.end()) { if((strspl.size() == 2) && isRealNumber(strspl.at(1))) findptr->second->setGatingProbability(stod(strspl.at(1))); else findptr->second->setGatingProbability(genRandomNum("float", this->_gpupbound, this->_gplowbound, 2)); findptr->second->setIfClockGating(1); this->_cglist.insert(pair<string, ClockTreeNode *> (findptr->second->getGateData()->getGateName(), findptr->second)); } } cgfile.close(); } // Replace buffers randomly to clock gating cells else { cout << "\033[32m[Info]: Replacing some buffers to clock gating cells...\033[0m\n"; map<string, ClockTreeNode *> buflist(this->_buflist); map<string, ClockTreeNode *>::iterator nodeitptr = buflist.begin(); for(long loop1 = 0;loop1 < (long)(this->_bufferusednum * this->_cgpercent);loop1++) { if(buflist.empty() || ((long)(this->_bufferusednum * this->_cgpercent) == 0)) break; long rannum = (long)genRandomNum("integer", 0, buflist.size()-1); nodeitptr = buflist.begin(), advance(nodeitptr, rannum); ClockTreeNode *picknode = nodeitptr->second; if((picknode->ifUsed() == 1) && (picknode->ifClockGating() == 0)) { bool breakflag = true; for(auto const &nodeptr : picknode->getChildren()) { if(!nodeptr->getChildren().empty()) { breakflag = false; break; } } if(breakflag) { loop1--; buflist.erase(nodeitptr); continue; } map<string, ClockTreeNode *>::iterator findptr; // Replace the buffer if it has brothers/sisters if((picknode->getParent()->getChildren().size() > 1) || (picknode->getParent() == this->_clktreeroot)) { picknode->setIfClockGating(1); picknode->setGatingProbability(genRandomNum("float", this->_gplowbound, this->_gpupbound, 2)); this->_cglist.insert(pair<string, ClockTreeNode *> (picknode->getGateData()->getGateName(), picknode)); } // Deal with the buffer if it does not has brothers/sisters // Replace the parent buffer of the buffer else { findptr = buflist.find(picknode->getParent()->getGateData()->getGateName()); if(findptr != buflist.end()) { ClockTreeNode *nodeptr = picknode->getParent(); while((nodeptr->getParent()->getChildren().size() == 1) && (nodeptr->getParent() != this->_clktreeroot)) nodeptr = nodeptr->getParent(); nodeptr->setIfClockGating(1); nodeptr->setGatingProbability(genRandomNum("float", this->_gplowbound, this->_gpupbound, 2)); this->_cglist.insert(pair<string, ClockTreeNode *> (nodeptr->getGateData()->getGateName(), nodeptr)); while(nodeptr != picknode) { findptr = buflist.find(nodeptr->getGateData()->getGateName()); if(findptr != buflist.end()) buflist.erase(findptr); nodeptr = nodeptr->getChildren().front(); } } else loop1--; } buflist.erase(picknode->getGateData()->getGateName()); if(picknode->getChildren().size() == 1) { findptr = buflist.find(picknode->getChildren().front()->getGateData()->getGateName()); if(findptr != buflist.end()) buflist.erase(findptr); } } else { loop1--; buflist.erase(nodeitptr); } } } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Adjust the primitive Tc in the timing report to a suitable Tc // using in the start of Binary search // ///////////////////////////////////////////////////////////////////// void ClockTree::adjustOriginTc(void) { double minslack = 999, tcdiff = 0; CriticalPath *minslackpath = nullptr; // Find the critical path dominating Tc for( auto const &pathptr : this->_pathlist ) { if(( pathptr->getPathType() == NONE) || pathptr->getPathType() == PItoPO ) continue; if( min(pathptr->getSlack(), minslack ) != minslack ) { minslack = min(pathptr->getSlack(), minslack); minslackpath = pathptr; } } if( minslack < 0 ) tcdiff = abs(minslackpath->getSlack()); else if(minslack > (this->_origintc * (roundNPrecision(getAgingRateByDutyCycle(0.5), PRECISION) - 1))) tcdiff = (this->_origintc - floorNPrecision(((this->_origintc - minslackpath->getSlack()) * 1.2), PRECISION)) * -1; if( tcdiff != 0 ) { // Update the required time and slack of each critical path for(auto const &pathptr : this->_pathlist ) { if( (pathptr->getPathType() == NONE) || (pathptr->getPathType() == PItoPO) ) continue; pathptr->setRequiredTime(pathptr->getRequiredTime() + tcdiff); pathptr->setSlack(pathptr->getSlack() + tcdiff); } } // Adjust Tc this->_tc = this->_origintc + tcdiff; // Initial the boundary of Tc using in Binary search this->initTcBound(); } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Prohibit DCCs inserting below the mask // ///////////////////////////////////////////////////////////////////// void ClockTree::dccPlacementByMasked(void) { if( !this->_placedcc )//-nondcc return ; long pathcount = 0; for( auto const &pathptr : this->_pathlist ) { //if(pathcount > (long)(this->_pathusednum * PATHMASKPERCENT)) // break; bool dealstart = 0, dealend = 0 ; ClockTreeNode *sameparent = this->_firstchildrennode; switch( pathptr->getPathType() ) { // Path type: input to FF case PItoFF: dealend = 1 ; break; // Path type: FF to output case FFtoPO: dealstart = 1 ; break; // Path type: FF to FF case FFtoFF: if( pathptr->isEndPointSameAsStartPoint() ) { pathcount++ ; continue ; } sameparent = pathptr->findLastSameParentNode(); dealstart = 1 ; dealend = 1 ; break ; default: continue; } pathcount++; // Deal with the clock path of the startpoint if( dealstart ) { vector< ClockTreeNode * > starttemp = pathptr->getStartPonitClkPath();//return by reference starttemp.pop_back() ; //front = root, back = FF reverse( starttemp.begin(), starttemp.end() ); //front = FF, back = root // Ignore the common nodes while( 1 ) { if( starttemp.back() != sameparent ) starttemp.pop_back(); else if(starttemp.back() == sameparent) { starttemp.pop_back(); reverse(starttemp.begin(), starttemp.end()); break; } } long clkpathlen = (long)(starttemp.size() * this->_maskleng); // Mask by length for( long loop = 0;loop < clkpathlen;loop++ )//when loop=0, it mean same parent-1 starttemp.pop_back() ; // Mask by level for( auto const &nodeptr : starttemp ) if( nodeptr->getDepth() <= (this->_maxlevel - this->_masklevel) ) nodeptr->setIfPlaceDcc(1); } // Deal with the clock path of the endpoint if( dealend ) { vector<ClockTreeNode *> endtemp = pathptr->getEndPonitClkPath();//return by reference endtemp.pop_back();//delete FF? //endtemp[0]=root, endtemp[tail]=FF+1 reverse(endtemp.begin(), endtemp.end()); //endtemp[0]=FF+1, endtemp[tail]=root // Ignore the common nodes while(1) { if( endtemp.back() != sameparent ) endtemp.pop_back(); else if( endtemp.back() == sameparent ) { endtemp.pop_back(); reverse(endtemp.begin(), endtemp.end()); //endtemp[0]=sameparent-1, endtemp[tail]=FF+1 break; } } long clkpathlen = (long)(endtemp.size() * this->_maskleng); // Mask by length for( long loop = 0;loop < clkpathlen;loop++ ) endtemp.pop_back(); // Mask by level for( auto const &nodeptr : endtemp ) if(nodeptr->getDepth() <= (this->_maxlevel - this->_masklevel)) nodeptr->setIfPlaceDcc(1); } } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // DCC constraint and generate clauses // ///////////////////////////////////////////////////////////////////// void ClockTree::dccConstraint(void) { if( !this->_placedcc ) { this->_nonplacedccbufnum = this->_buflist.size(); return; } // Generate two clauses for the clock tree root (clock source) if( this->_dccconstraintlist.size() < (this->_dccconstraintlist.max_size()-2) ) { string clause1 = to_string(this->_clktreeroot->getNodeNumber() * -1) + " 0"; string clause2 = to_string((this->_clktreeroot->getNodeNumber() + 1) * -1) + " 0"; this->_dccconstraintlist.insert(clause1); this->_dccconstraintlist.insert(clause2); } else { cerr << "\033[32m[Info]: DCC Constraint List Full!\033[0m\n"; return; } // Generate two clauses for each buffer can not insert DCC for( auto const& node: this->_buflist )//_buflist = map< string, clknode * > { if( !node.second->ifPlacedDcc() ) { string clause1, clause2; clause1 = to_string(node.second->getNodeNumber() * -1) + " 0"; clause2 = to_string((node.second->getNodeNumber() + 1) * -1) + " 0"; if(this->_dccconstraintlist.size() < (this->_dccconstraintlist.max_size()-2)) { this->_dccconstraintlist.insert(clause1); this->_dccconstraintlist.insert(clause2); } else { cerr << "\033[32m[Info]: DCC Constraint List Full!\033[0m\n"; return; } } } this->_nonplacedccbufnum = (this->_dccconstraintlist.size() / 2) - 1; // Generate clauses based on DCC constraint in each clock path for( auto const& node: this->_ffsink ) { //-- Don't Put DCC ahead of FF string clause1, clause2; clause1 = to_string(node.second->getNodeNumber() * -1) + " 0"; clause2 = to_string((node.second->getNodeNumber() + 1) * -1) + " 0"; if(this->_dccconstraintlist.size() < (this->_dccconstraintlist.max_size()-2)) { this->_dccconstraintlist.insert(clause1); this->_dccconstraintlist.insert(clause2); } else { cerr << "\033[32m[Info]: DCC Constraint List Full!\033[0m\n"; return; } ClockTreeNode *nodeptr = node.second->getParent() ;//FF's parent vector<long> path, gencomb; vector<vector<long> > comblist; while( nodeptr != this->_firstchildrennode ) { if( nodeptr->ifPlacedDcc() ) path.push_back( nodeptr->getNodeNumber() ); nodeptr = nodeptr->getParent(); } path.shrink_to_fit(); reverse(path.begin(), path.end()); // Combination of DCC constraint // Can't Put more than 2 DCC along the same clock path for( long loop = 0; loop <= ((long)path.size()) - 2; loop++ ) combination( loop+1, (int)(path.size()), 1, gencomb, &comblist ); updateCombinationList( &path, &comblist ); // Generate clauses this->genDccConstraintClause(&comblist); } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Generate all kinds of DCC deployment (location of DCC excluding // the types of DCC) in each critical path // ///////////////////////////////////////////////////////////////////// void ClockTree::genDccPlacementCandidate(void) { if( !this->_placedcc ) return ; for( auto const& path: this->_pathlist ) if( (path->getPathType() != NONE) && (path->getPathType() != PItoPO) ) path->setDccPlacementCandidate(); } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Timing constraint and generate clauses based on each DCC // deployment // ///////////////////////////////////////////////////////////////////// double ClockTree::timingConstraint(void) { printf( YELLOW"\t[Timing Constraint] " RESET"Tc range: %f - %f ...\033[0m\n", this->_tclowbound, this->_tcupbound ) ; double slack = 0 ; double minslack = 100 ;//Eric this->_timingconstraintlist.clear();//set<string> for( auto const& path: this->_pathlist ) { if( (path->getPathType() != PItoFF) && (path->getPathType() != FFtoPO) && (path->getPathType() != FFtoFF) ) continue; // Assess if the critical path occurs timing violation without inserting any DCC slack = this->assessTimingWithoutDcc(path); // Assess if the critical path occurs timing violation when inserting DCCs if( this->_placedcc )//-nodcc this->assessTimingWithDcc(path); /*Senior if( (slack < 0) && (!this->_placedcc) ) return slack; */ minslack = (slack<minslack)?(slack):(minslack); } return minslack; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Assess if the critical path occurs timing violation without // inserting any DCC (violating the setup time requirement) // Input parameter: // genclause: 0 => Do not generate a clause // 1 (default) => Generate clauses (default) // update: 0 (default) => Do not update the timing information of critical path // 1 => Update the timing information of critical path ///////////////////////////////////////////////////////////////////// double ClockTree::assessTimingWithoutDcc( CriticalPath *path, bool genclause, bool update ) { /* Note: writeClauseByDccType( nodeptr, &clause, 0 ), the last arg is 0, because as title imply we access timing without Dcc */ if( path == nullptr ) return -1 ; //------ Declare ------------------------------------------------------------------ double newslack = 0 ; double dataarrtime = 0 ; double datareqtime = 0 ; //------- Ci & Cj ------------------------------------------------------------------ this->calculateClockLatencyWithoutDcc( path, &datareqtime, &dataarrtime ); if( update ) { path->setCi(dataarrtime) ; path->setCj(datareqtime) ; } //------- Require time -------------------------------------------------------------- datareqtime += (path->getTsu() * this->_agingtsu) + this->_tc; //------- Arrival time -------------------------------------------------------------- dataarrtime += path->getTinDelay() + (path->getTcq() * this->_agingtcq) + (path->getDij() * this->_agingdij); newslack = datareqtime - dataarrtime ; if( update ) { path->setArrivalTime(dataarrtime) ; path->setRequiredTime(datareqtime); path->setSlack(newslack) ; } //-------- Timing Violation --------------------------------------------------------- if( (newslack < 0) && this->_placedcc && genclause) { string clause; //---- PItoFF or FFtoPO -------------------------------------------------------- if((path->getPathType() == PItoFF) || (path->getPathType() == FFtoPO)) { vector<ClockTreeNode *> clkpath = ((path->getPathType() == PItoFF) ? path->getEndPonitClkPath() : path->getStartPonitClkPath()); //- Generate Clause -------------------------------------------------------- for( auto const& nodeptr: clkpath ) { if( nodeptr->ifPlacedDcc() ) this->writeClauseByDccType( nodeptr, &clause, 0 ) ; } } else if( path->getPathType() == FFtoFF )//-- FFtoFF ----------------------------- { ClockTreeNode *sameparent = path->findLastSameParentNode(); //- Generate Clause/Left ---------------------------------------------------- long sameparentloc = path->nodeLocationInClockPath('s', sameparent); for( auto const& nodeptr: path->getStartPonitClkPath() ) if( nodeptr->ifPlacedDcc() ) this->writeClauseByDccType( nodeptr, &clause, 0 ) ; //- Generate Clause/Right --------------------------------------------------- for( long loop = (sameparentloc + 1);loop < path->getEndPonitClkPath().size(); loop++ ) if( path->getEndPonitClkPath().at(loop)->ifPlacedDcc() ) this->writeClauseByDccType( path->getEndPonitClkPath().at(loop), &clause, 0 ); } clause += "0"; if( this->_timingconstraintlist.size() < (this->_timingconstraintlist.max_size()-1) ) this->_timingconstraintlist.insert(clause) ; else cerr << "\033[32m[Info]: Timing Constraint List Full!\033[0m\n"; } return newslack; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // According to each DCC deployment, calculate the Ci and Cj and // assess if the critical path occurs timing violation when inserting // DCCs (violating the setup time requirement) // ///////////////////////////////////////////////////////////////////// void ClockTree::assessTimingWithDcc(CriticalPath *path) { if(path == nullptr) return; vector<vector<ClockTreeNode *> > dcccandi = path->getDccPlacementCandi(); // Consider every DCC deployment of this critical path for( long loop = 0; loop < dcccandi.size(); loop++ ) { vector<double> citime, cjtime; // Path type: input to FF if( path->getPathType() == PItoFF ) { // Calculate the Cj cjtime = this->calculateClockLatencyWithDcc(path->getEndPonitClkPath(), dcccandi.at(loop).front());//return a vector // Assess if the critical path occurs timing violation when inserting 20%/40%/80% DCC//back()? //Error here (maybe), argc is not consistent this->assessTimingWithDcc(path, 0, cjtime.at(0), 20, -1, dcccandi.at(loop).front(), nullptr, path->getEndPonitClkPath()); this->assessTimingWithDcc(path, 0, cjtime.at(1), 40, -1, dcccandi.at(loop).front(), nullptr, path->getEndPonitClkPath()); this->assessTimingWithDcc(path, 0, cjtime.at(2), 80, -1, dcccandi.at(loop).front(), nullptr, path->getEndPonitClkPath()); } // Path type: FF to output else if( path->getPathType() == FFtoPO ) { // Calculate the Ci citime = this->calculateClockLatencyWithDcc(path->getStartPonitClkPath(), dcccandi.at(loop).front()); // Assess if the critical path occurs timing violation when inserting 20%/40%/80% DCC this->assessTimingWithDcc(path, citime.at(0), 0, 20, -1, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath()); this->assessTimingWithDcc(path, citime.at(1), 0, 40, -1, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath()); this->assessTimingWithDcc(path, citime.at(2), 0, 80, -1, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath()); } // Path type: FF to FF else if( path->getPathType() == FFtoFF ) { long candilocleft = path->nodeLocationInClockPath('s', dcccandi.at(loop).back() /*Clk node*/ );//location id, 's' mean start clk path long candilocright = path->nodeLocationInClockPath('e', dcccandi.at(loop).back() /*Clk node*/ );//location id, 'e' mean end clk path long sameparentloc = path->nodeLocationInClockPath('s', path->findLastSameParentNode()); // Insert one DCC if( dcccandi.at(loop).size() == 1 ) { // Insert DCC on common node if((candilocleft != -1) && (candilocleft <= sameparentloc)) { // Calculate the Ci and Cj citime = this->calculateClockLatencyWithDcc(path->getStartPonitClkPath(), dcccandi.at(loop).front()); cjtime = this->calculateClockLatencyWithDcc(path->getEndPonitClkPath(), dcccandi.at(loop).front()); //citime.at(0), put 20% DCC on the location of dcccandi.at(loop).front() //citime.at(1), put 40% DCC on the location of dcccandi.at(loop).front() //citime.at(2), put 80% DCC on the location of dcccandi.at(loop).front() // Assess if the critical path occurs timing violation when inserting 20%/40%/80% DCC this->assessTimingWithDcc(path, citime.at(0), cjtime.at(0), 20, 20, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath(), path->getEndPonitClkPath()); this->assessTimingWithDcc(path, citime.at(1), cjtime.at(1), 40, 40, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath(), path->getEndPonitClkPath()); this->assessTimingWithDcc(path, citime.at(2), cjtime.at(2), 80, 80, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath(), path->getEndPonitClkPath()); } // Insert DCC on the branch part of right clk path:OK else if( candilocleft < candilocright ) { double newcitime = 0; // Calculate the Ci and Cj this->calculateClockLatencyWithoutDcc( path, nullptr, &newcitime ); cjtime = this->calculateClockLatencyWithDcc(path->getEndPonitClkPath(), dcccandi.at(loop).front()); // Assess if the critical path occurs timing violation when inserting 20%/40%/80% DCC // Generate clause here: this->assessTimingWithDcc(path, newcitime, cjtime.at(0), 20, 0, dcccandi.at(loop).front(), nullptr, path->getEndPonitClkPath(), path->getStartPonitClkPath()); this->assessTimingWithDcc(path, newcitime, cjtime.at(1), 40, 0, dcccandi.at(loop).front(), nullptr, path->getEndPonitClkPath(), path->getStartPonitClkPath()); this->assessTimingWithDcc(path, newcitime, cjtime.at(2), 80, 0, dcccandi.at(loop).front(), nullptr, path->getEndPonitClkPath(), path->getStartPonitClkPath()); } // Insert DCC on the branch part of left clk path:OK else if(candilocleft > candilocright) { double newcjtime = 0; // Calculate the Ci and Cj this->calculateClockLatencyWithoutDcc(path, &newcjtime, nullptr); citime = this->calculateClockLatencyWithDcc(path->getStartPonitClkPath(), dcccandi.at(loop).front()); // Assess if the critical path occurs timing violation when inserting 20%/40%/80% DCC this->assessTimingWithDcc(path, citime.at(0), newcjtime, 20, 0, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath(), path->getEndPonitClkPath()); this->assessTimingWithDcc(path, citime.at(1), newcjtime, 40, 0, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath(), path->getEndPonitClkPath()); this->assessTimingWithDcc(path, citime.at(2), newcjtime, 80, 0, dcccandi.at(loop).front(), nullptr, path->getStartPonitClkPath(), path->getEndPonitClkPath()); } } // Insert two DCCs:OK else if( dcccandi.at(loop).size() == 2 ) { // Calculate the Ci and Cj citime = this->calculateClockLatencyWithDcc(path->getStartPonitClkPath(), dcccandi.at(loop).front()); cjtime = this->calculateClockLatencyWithDcc(path->getEndPonitClkPath(), dcccandi.at(loop).back()); // Assess if the critical path occurs timing violation when inserting 20%/40%/80% DCC and 20%/40%/80% DCC // Total 9 combinations this->assessTimingWithDcc(path, citime.at(0), cjtime.at(0), 20, 20, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath()); this->assessTimingWithDcc(path, citime.at(0), cjtime.at(1), 20, 40, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath()); this->assessTimingWithDcc(path, citime.at(0), cjtime.at(2), 20, 80, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath()); this->assessTimingWithDcc(path, citime.at(1), cjtime.at(0), 40, 20, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath()); this->assessTimingWithDcc(path, citime.at(1), cjtime.at(1), 40, 40, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath()); this->assessTimingWithDcc(path, citime.at(1), cjtime.at(2), 40, 80, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath()); this->assessTimingWithDcc(path, citime.at(2), cjtime.at(0), 80, 20, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath()); this->assessTimingWithDcc(path, citime.at(2), cjtime.at(1), 80, 40, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath()); this->assessTimingWithDcc(path, citime.at(2), cjtime.at(2), 80, 80, dcccandi.at(loop).front(), dcccandi.at(loop).back(), path->getStartPonitClkPath(), path->getEndPonitClkPath()); } } } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Assess if the critical path occurs timing violation when inserting // DCCs (violating the setup time requirement) // Input parameter: // citime: clock latency of startpoint // cjtime: clock latency of endpoint // dcctype1: type of DCC 1 // dcctype2: type of DCC 2 // candinode1: pointer of DCC 1 (location) // candinode2: pointer of DCC 2 (location) // clkpath1: clock path 1 containing DCC 1 // clkpath2: clock path 2 containing DCC 2 // genclause: 0 => do not generate a clause // 1 (default)=> generate a clause // update: 0 (default) => do not update the timing information of critical path // 1 => update the timing information of critical path // ///////////////////////////////////////////////////////////////////// double ClockTree::assessTimingWithDcc( CriticalPath *path, double citime, double cjtime, int dcctype1, int dcctype2, ClockTreeNode *candinode1, ClockTreeNode *candinode2, vector<ClockTreeNode *> clkpath1, vector<ClockTreeNode *> clkpath2, bool genclause, bool update ) { double newslack = 0, dataarrtime = 0, datareqtime = 0; // Require time datareqtime = cjtime + (path->getTsu() * this->_agingtsu) + this->_tc; // Arrival time dataarrtime = citime + path->getTinDelay() + (path->getTcq() * this->_agingtcq) + (path->getDij() * this->_agingdij); newslack = datareqtime - dataarrtime; if( update ) { path->setCi(citime), path->setCj(cjtime); path->setArrivalTime(dataarrtime) ; path->setRequiredTime(datareqtime) ; path->setSlack(newslack) ; } //---- Timing violationprint ----------- if( (newslack < 0) && genclause ) { string clause; // Deal with two type of critical path (PItoFF and FFtoPO) if((path->getPathType() == PItoFF) || (path->getPathType() == FFtoPO)) { // Generate the clause for( auto const& nodeptr: clkpath1 ) { if((nodeptr != candinode1) && nodeptr->ifPlacedDcc()) this->writeClauseByDccType(nodeptr, &clause, 0); else if((nodeptr == candinode1) && nodeptr->ifPlacedDcc()) this->writeClauseByDccType(nodeptr, &clause, dcctype1); } } // Deal with the FF to FF critical path else if( path->getPathType() == FFtoFF ) { ClockTreeNode *sameparent = path->findLastSameParentNode(); long sameparentloc = path->nodeLocationInClockPath('s', sameparent); // Generate the clause based on the clock path 1 for( auto const& nodeptr: clkpath1 ) { if((nodeptr != candinode1) && nodeptr->ifPlacedDcc()) this->writeClauseByDccType(nodeptr, &clause, 0); else if((nodeptr == candinode1) && nodeptr->ifPlacedDcc()) this->writeClauseByDccType(nodeptr, &clause, dcctype1); } // Generate the clause based on the branch clock path 2 for(long loop = (sameparentloc + 1);loop < clkpath2.size();loop++) { if(candinode2 == nullptr) this->writeClauseByDccType(clkpath2.at(loop), &clause, 0); else { if((clkpath2.at(loop) != candinode2) && (clkpath2.at(loop)->ifPlacedDcc())) this->writeClauseByDccType(clkpath2.at(loop), &clause, 0); else if((clkpath2.at(loop) == candinode2) && (clkpath2.at(loop)->ifPlacedDcc())) this->writeClauseByDccType(clkpath2.at(loop), &clause, dcctype2); } } } clause += "0"; if(this->_timingconstraintlist.size() < (this->_timingconstraintlist.max_size()-1)) this->_timingconstraintlist.insert(clause); else cerr << "\033[32m[Info]: Timing Constraint List Full!\033[0m\n"; } return newslack; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Calculate the clock latency of the startpoint/endpoint without // any inserted DCCs // Input parameter: // datareqtime: clock latency of the endpoint // dataarrtime: clock latency of the startpoint // ///////////////////////////////////////////////////////////////////// void ClockTree::calculateClockLatencyWithoutDcc(CriticalPath *path, double *datareqtime, double *dataarrtime) { if(path == nullptr) return; bool dealstart = 0, dealend = 0; double agingrate = 1; switch(path->getPathType()) { // Path type: input to FF case PItoFF: dealend = 1; break; // Path type: FF to output case FFtoPO: dealstart = 1; break; // Path type: FF to FF case FFtoFF: dealstart = 1; dealend = 1; break; default: break; } // Calculate the clock latency of the startpoint if(dealstart && (dataarrtime != nullptr)) { double dutycycle = 0.5; vector<ClockTreeNode *> sclkpath = path->getStartPonitClkPath(); if(this->_aging) agingrate = getAgingRateByDutyCycle(dutycycle); for(long loop = 0;loop < (sclkpath.size() - 1);loop++) { *dataarrtime += (sclkpath.at(loop)->getGateData()->getWireTime() + sclkpath.at(loop)->getGateData()->getGateTime()) * agingrate; // Meet the clock gating cells if(sclkpath.at(loop)->ifClockGating() && this->_aging) { dutycycle = dutycycle * (1 - sclkpath.at(loop)->getGatingProbability()); agingrate = getAgingRateByDutyCycle(dutycycle); } } *dataarrtime += sclkpath.back()->getGateData()->getWireTime() * agingrate; } // Calculate the clock latency of the endpoint if(dealend && (datareqtime != nullptr)) { double dutycycle = 0.5; vector<ClockTreeNode *> eclkpath = path->getEndPonitClkPath(); if(this->_aging) agingrate = getAgingRateByDutyCycle(dutycycle); for(long loop = 0;loop < (eclkpath.size() - 1);loop++) { *datareqtime += (eclkpath.at(loop)->getGateData()->getWireTime() + eclkpath.at(loop)->getGateData()->getGateTime()) * agingrate; // Meet the clock gating cells if(eclkpath.at(loop)->ifClockGating() && this->_aging) { dutycycle = dutycycle * (1 - eclkpath.at(loop)->getGatingProbability()); agingrate = getAgingRateByDutyCycle(dutycycle); } } *datareqtime += eclkpath.back()->getGateData()->getWireTime() * agingrate; } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Calculate the clock latency of the startpoint/endpoint based on // specific dcc deployment // Input parameter: // clkpath: clock path of the critical path // candinode: pointer of DCC (location) // ///////////////////////////////////////////////////////////////////// vector<double> ClockTree::calculateClockLatencyWithDcc( vector<ClockTreeNode *> clkpath, ClockTreeNode *candinode ) { vector<double> clklatency(3, 0) ;//Calculate 3 possible latency of 3 DCC vector<double> oneclklatency(1, 0); bool isfront = 1 ; double minbufdelay = 999 ; double dutycycle20 = 0.5, dutycycle40 = 0.5, dutycycle80 = 0.5, dutycycleondcc = 0.5; double agingrate20dcc = getAgingRateByDutyCycle(dutycycle20); double agingrate40dcc = agingrate20dcc ; double agingrate80dcc = agingrate20dcc ; for( long loop = 0; loop < (clkpath.size() - 1); loop++ ) { ClockTreeNode *node = clkpath.at(loop); //wire_delay + gate_delay double buftime = node->getGateData()->getWireTime() + node->getGateData()->getGateTime(); // Find the minimization delay of buffer in the clock path if( node != this->_clktreeroot ) minbufdelay = min( buftime, minbufdelay ); // The node before the DCC (dir: root->FF) if( isfront ) { if((node != candinode) && (node->ifClockGating())) dutycycleondcc = dutycycleondcc * (1 - node->getGatingProbability()); // Meet the DCC else if(node == candinode) { isfront = 0; dutycycle20 = 0.2 ; dutycycle40 = 0.4 ; dutycycle80 = 0.8 ; agingrate20dcc = getAgingRateByDutyCycle(dutycycle20); agingrate40dcc = getAgingRateByDutyCycle(dutycycle40); agingrate80dcc = getAgingRateByDutyCycle(dutycycle80); } } clklatency.at(0) += buftime * agingrate20dcc; clklatency.at(1) += buftime * agingrate40dcc; clklatency.at(2) += buftime * agingrate80dcc; // Meet the clock gating cells if(node->ifClockGating()) { dutycycle20 = dutycycle20 * (1 - node->getGatingProbability()); dutycycle40 = dutycycle40 * (1 - node->getGatingProbability()); dutycycle80 = dutycycle80 * (1 - node->getGatingProbability()); agingrate20dcc = getAgingRateByDutyCycle(dutycycle20); agingrate40dcc = getAgingRateByDutyCycle(dutycycle40); agingrate80dcc = getAgingRateByDutyCycle(dutycycle80); } } clklatency.at(0) += clkpath.back()->getGateData()->getWireTime() * agingrate20dcc; clklatency.at(1) += clkpath.back()->getGateData()->getWireTime() * agingrate40dcc; clklatency.at(2) += clkpath.back()->getGateData()->getWireTime() * agingrate80dcc; if( candinode != nullptr ) { double dccagingrate = getAgingRateByDutyCycle(dutycycleondcc); clklatency.at(0) += minbufdelay * dccagingrate * DCCDELAY20PA; clklatency.at(1) += minbufdelay * dccagingrate * DCCDELAY40PA; clklatency.at(2) += minbufdelay * dccagingrate * DCCDELAY80PA; if(candinode->getDccType() == 20) oneclklatency.front() = clklatency.front(); else if(candinode->getDccType() == 40) oneclklatency.front() = clklatency.at(1); else if(candinode->getDccType() == 80) oneclklatency.front() = clklatency.back(); } if(oneclklatency.front() != 0) return oneclklatency; else return clklatency; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Dump all clauses (DCC constraints and timing constraints) to a // file // ///////////////////////////////////////////////////////////////////// void ClockTree::dumpClauseToCnfFile(void) { if( !this->_placedcc ) return ; fstream cnffile ; string cnfinput = this->_outputdir + "cnfinput_" + to_string(this->_tc); if( !isDirectoryExist(this->_outputdir) ) mkdir(this->_outputdir.c_str(), 0775); if( !isFileExist(cnfinput) ) { printf( YELLOW"\t[CNF] " RESET"Encoded as %s...\033[0m\n", cnfinput.c_str()); cnffile.open(cnfinput, ios::out | fstream::trunc); if( !cnffile.is_open() ) { cerr << RED"\t[Error]: Cannot open " << cnfinput << "\033[0m\n"; cnffile.close(); return; } //--- DCC constraint --------------------------------- for( auto const& clause: this->_dccconstraintlist ) { cnffile << clause << "\n" ; } //--- Timing constraint ------------------------------- for( auto const& clause: this->_timingconstraintlist ) { cnffile << clause << "\n" ; } cnffile.close(); } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Call MiniSat // ///////////////////////////////////////////////////////////////////// void ClockTree::execMinisat(void) { if(!this->_placedcc) return; // MiniSat input file string cnfinput = this->_outputdir + "cnfinput_" + to_string(this->_tc); // MiniSat output file string cnfoutput = this->_outputdir + "cnfoutput_" + to_string(this->_tc); if(!isDirectoryExist(this->_outputdir)) mkdir(this->_outputdir.c_str(), 0775); if(isFileExist(cnfinput)) { this->_minisatexecnum++; //string execmd = "minisat " + cnfinput + " " + cnfoutput; //system(execmd.c_str()); // Fork a process pid_t childpid = fork(); if(childpid == -1) cerr << RED"[Error]: Cannot fork child process!\033[0m\n"; else if(childpid == 0) { // Child process string minisatfile = this->_outputdir + "minisat_output"; int fp = open(minisatfile.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0664); if(fp == -1) cerr << RED"[Error]: Cannot dump the executive output of minisat!\033[0m\n"; else { dup2(fp, STDOUT_FILENO); dup2(fp, STDERR_FILENO); close(fp); } //this->~ClockTree(); // Call MiniSat if(execlp("./minisat", "./minisat", cnfinput.c_str(), cnfoutput.c_str(), (char *)0) == -1) { cerr << RED"[Error]: Cannot execute minisat!\033[0m\n"; this->_minisatexecnum--; } exit(0); } else { // Parent process int exitstatus; waitpid(childpid, &exitstatus, 0); } } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Change the boundary of Binary search and search for the optimal Tc // ///////////////////////////////////////////////////////////////////// void ClockTree::tcBinarySearch(double slack) { // Place DCCs if( this->_placedcc ) { fstream cnffile; string line, cnfoutput = this->_outputdir + "cnfoutput_" + to_string(this->_tc);//Minisat results if( !isFileExist(cnfoutput) ) return; cnffile.open(cnfoutput, ios::in); if( !cnffile.is_open() ) { cerr << RED"\t[Error]: Cannot open " << cnfoutput << "\033[0m\n"; cnffile.close(); return; } getline(cnffile, line); // Change the lower boundary if((line.size() == 5) && (line.find("UNSAT") != string::npos)) { this->_tclowbound = this->_tc; this->_tc = ceilNPrecision((this->_tcupbound + this->_tclowbound) / 2, PRECISION); printf( YELLOW"\t[Minisat] " RESET "Return: " RED"UNSAT \033[0m\n" ) ; printf( YELLOW"\t[Binary Search] " RESET"Next Tc range: %f - %f \033[0m\n", _tclowbound, _tcupbound ) ; } // Change the upper boundary else if((line.size() == 3) && (line.find("SAT") != string::npos)) { this->_besttc = this->_tc; this->_tcupbound = this->_tc; this->_tc = floorNPrecision((this->_tcupbound + this->_tclowbound) / 2, PRECISION); printf( YELLOW"\t[Minisat] " RESET"Return: " GREEN"SAT \033[0m\n" ) ; printf( YELLOW"\t[Binary Search] " RESET"Next Tc range: %f - %f \033[0m\n", _tclowbound, _tcupbound ) ; } cnffile.close(); } // Do not place DCCs else if(!this->_placedcc) { // Change the lower boundary if(slack <= 0) { this->_tclowbound = this->_tc; this->_tc = ceilNPrecision((this->_tcupbound + this->_tclowbound) / 2, PRECISION); } // Change the upper boundary else if(slack > 0) { this->_besttc = this->_tc; this->_tcupbound = this->_tc; this->_tc = floorNPrecision((this->_tcupbound + this->_tclowbound) / 2, PRECISION); } } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Update timing information of all critical path based on the // optimal Tc // ///////////////////////////////////////////////////////////////////// void ClockTree::updateAllPathTiming(void) { if( this->_besttc == 0 ) return; double minslack = 9999; this->_tc = this->_besttc; // Place DCCs if( this->_placedcc ) { for( auto const& node: this->_buflist ) node.second->setIfPlaceDcc(0) ; fstream cnffile; string line = "" ; string lastsatfile = this->_outputdir + "cnfoutput_" + to_string(this->_tc); if( !isFileExist(lastsatfile) ) { cerr << "\033[31m[Error]: File \"" << lastsatfile << "\" does not found!\033[0m\n"; return; } cnffile.open(lastsatfile, ios::in); if(!cnffile.is_open()) { cerr << "\033[31m[Error]: Cannot open " << lastsatfile << "\033[0m\n"; cnffile.close(); return; } // Get the DCC deployment from the MiniSat output file getline(cnffile, line); if( (line.size() == 3) && (line.find("SAT") != string::npos) ) { getline( cnffile, line ) ; vector<string> strspl = stringSplit(line, " "); for( long loop = 0; ; loop += 2 ) { if( stoi( strspl[loop] ) == 0 ) break ; if( (stoi(strspl.at(loop)) > 0) || (stoi(strspl.at(loop + 1)) > 0) ) { ClockTreeNode *findnode = this->searchClockTreeNode(abs(stoi(strspl.at(loop)))); if( findnode != nullptr ) { findnode->setIfPlaceDcc(1); findnode->setDccType(stoi(strspl.at(loop)), stoi(strspl.at(loop + 1))); this->_dcclist.insert(pair<string, ClockTreeNode *> (findnode->getGateData()->getGateName(), findnode)); } } } } else { cerr << "\033[31m[Error]: File \"" << lastsatfile << "\" is not SAT!\033[0m\n"; return; } cnffile.close(); for( auto const& path: this->_pathlist ) { if((path->getPathType() != PItoFF) && (path->getPathType() != FFtoPO) && (path->getPathType() != FFtoFF)) continue; // Update timing information double slack = this->updatePathTimingWithDcc(path, 1); if( slack < minslack ) { this->_mostcriticalpath = path; minslack = min( slack, minslack ); } } } // Do not place DCCs else { for(auto const& path: this->_pathlist) { if((path->getPathType() != PItoFF) && (path->getPathType() != FFtoPO) && (path->getPathType() != FFtoFF)) continue; // Update timing information double slack = this->assessTimingWithoutDcc(path, 0, 1); if( slack < minslack ) { this->_mostcriticalpath = path; minslack = min(slack, minslack); } } } // Count the DCCs inserting at final buffer for(auto const& node: this->_dcclist) if(node.second->ifPlacedDcc() && node.second->isFinalBuffer()) this->_dccatlastbufnum++; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Minimize the DCC deployment based on the optimal Tc // ///////////////////////////////////////////////////////////////////// void ClockTree::minimizeDccPlacement(void) { if(!this->_mindccplace || !this->_placedcc || (this->_besttc == 0)) return; cout << "\033[32m[Info]: Minimizing DCC Placement...\033[0m\n"; cout << "\033[32m Before DCC Placement Minimization\033[0m\n"; this->printDccList(); map<string, ClockTreeNode *> dcclist = this->_dcclist; map<string, ClockTreeNode *>::iterator finddccptr; // Reserve the DCCs locate before the critical path dominating the optimal Tc for(auto const& path: this->_pathlist) { ClockTreeNode *sdccnode = nullptr, *edccnode = nullptr; // If DCC locate in the clock path of startpoint sdccnode = path->findDccInClockPath('s'); // If DCC locate in the clock path of endpoint edccnode = path->findDccInClockPath('e'); if(sdccnode != nullptr) { finddccptr = dcclist.find(sdccnode->getGateData()->getGateName()); if(finddccptr != dcclist.end()) dcclist.erase(finddccptr); } if(edccnode != nullptr) { finddccptr = dcclist.find(edccnode->getGateData()->getGateName()); if(finddccptr != dcclist.end()) dcclist.erase(finddccptr); } if( path == this->_mostcriticalpath) break; } for(auto const& node: dcclist) node.second->setIfPlaceDcc(0); this->_tc = this->_besttc; // Greedy minimization while(1) { if(dcclist.empty()) break; bool endflag = 1, findstartpath = 1; // Reserve one of the rest of DCCs above if one of critical paths occurs timing violation for(auto const& path: this->_pathlist) { if((path->getPathType() != PItoFF) && (path->getPathType() != FFtoPO) && (path->getPathType() != FFtoFF)) continue; // Assess if the critical path occurs timing violation in the DCC deployment double slack = this->updatePathTimingWithDcc(path, 0); if(slack < 0) { endflag = 0; for(auto const& node: dcclist) if(node.second->ifPlacedDcc()) dcclist.erase(node.first); // Reserve the DCC locate in the clock path of endpoint for(auto const& node: path->getEndPonitClkPath()) { finddccptr = dcclist.find(node->getGateData()->getGateName()); if((finddccptr != dcclist.end()) && !finddccptr->second->ifPlacedDcc()) { finddccptr->second->setIfPlaceDcc(1); findstartpath = 0; } } // Reserve the DCC locate in the clock path of startpoint if(findstartpath) { for(auto const& node: path->getStartPonitClkPath()) { finddccptr = dcclist.find(node->getGateData()->getGateName()); if((finddccptr != dcclist.end()) && !finddccptr->second->ifPlacedDcc()) finddccptr->second->setIfPlaceDcc(1); } } break; } } if(endflag) break; } for(auto const& node: this->_dcclist) { if(!node.second->ifPlacedDcc()) { node.second->setDccType(0); this->_dcclist.erase(node.first); } } this->_dccatlastbufnum = 0; // Count the DCCs inserting at final buffer for(auto const& node: this->_dcclist) if(node.second->ifPlacedDcc() && node.second->isFinalBuffer()) this->_dccatlastbufnum++; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Recheck the optimal Tc if it is minimum // ///////////////////////////////////////////////////////////////////// void ClockTree::tcRecheck(void) { if(!this->_tcrecheck || (this->_besttc == 0)) return; cout << "\033[32m[Info]: Rechecking Tc...\033[0m\n"; cout << "\033[32m Before Tc Rechecked\033[0m\n"; cout << "\t*** Optimal tc : \033[36m" << this->_besttc << "\033[0m\n"; if(this->_mostcriticalpath->getSlack() < 0) this->_besttc += ceilNPrecision(abs(this->_mostcriticalpath->getSlack()), PRECISION); double oribesttc = this->_besttc; while(1) { bool endflag = 0; // Decrease the optimal Tc this->_tc = this->_besttc - (1 / pow(10, PRECISION)); if(this->_tc < 0) break; // Assess if the critical path occurs timing violation for(auto const& path: this->_pathlist) { if((path->getPathType() != PItoFF) && (path->getPathType() != FFtoPO) && (path->getPathType() != FFtoFF)) continue; double slack = 0; if(this->_placedcc) slack = this->updatePathTimingWithDcc(path, 0); else slack = this->assessTimingWithoutDcc(path, 0, 0); if(slack < 0) { endflag = 1; break; } } if(endflag) break; this->_besttc = this->_tc; } if(oribesttc == this->_besttc) return; this->_tc = this->_besttc; // Update timing information of all critical path based on the new optimal Tc for(auto const& path: this->_pathlist) { if((path->getPathType() != PItoFF) && (path->getPathType() != FFtoPO) && (path->getPathType() != FFtoFF)) continue; if(this->_placedcc) this->updatePathTimingWithDcc(path, 1); else this->assessTimingWithoutDcc(path, 0, 1); } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Insert buffers based on the optimal Tc determined by DCC insertion // ///////////////////////////////////////////////////////////////////// void ClockTree::bufferInsertion(void) { if((this->_bufinsert < 1) || (this->_bufinsert > 2)) return; cout << "\033[32m[Info]: Inserting Buffer (Tc = " << this->_besttc << " )...\033[0m\n"; this->_tc = this->_besttc; for(int counter = 1;;counter++) { bool insertflag = 0; for(auto const& path : this->_pathlist) { if((path->getPathType() == NONE) || (path->getPathType() == PItoPO)) continue; double dataarrtime = 0, datareqtime = 0; // Calculate the Ci and Cj this->calculateClockLatencyWithoutDcc(path, &datareqtime, &dataarrtime); // Require time datareqtime += (path->getTsu() * this->_agingtsu) + this->_tc; // Arrival time dataarrtime += path->getTinDelay() + (path->getTcq() * this->_agingtcq) + (path->getDij() * this->_agingdij); if((path->getPathType() == FFtoPO) || (path->getPathType() == FFtoFF)) if(!path->getStartPonitClkPath().empty() && path->getStartPonitClkPath().back()->ifInsertBuffer()) dataarrtime += path->getStartPonitClkPath().back()->getInsertBufferDelay(); if((path->getPathType() == PItoFF) || (path->getPathType() == FFtoFF)) if(!path->getEndPonitClkPath().empty() && path->getEndPonitClkPath().back()->ifInsertBuffer()) datareqtime += path->getEndPonitClkPath().back()->getInsertBufferDelay(); // Timing violation if((datareqtime - dataarrtime) < 0) { if(path->getPathType() == FFtoPO) { this->_insertbufnum = 0; return; } else { // Insert buffer insertflag = 1; if(!path->getEndPonitClkPath().back()->ifInsertBuffer()) this->_insertbufnum++; path->getEndPonitClkPath().back()->setIfInsertBuffer(1); double delay = path->getEndPonitClkPath().back()->getInsertBufferDelay(); delay = max(delay, (dataarrtime - datareqtime)); path->getEndPonitClkPath().back()->setInsertBufferDelay(delay); } } } if(!insertflag) break; // Check 3 times if((counter == 3) && insertflag) { this->_insertbufnum = 0; break; } } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Minimize the inserted buffers // ///////////////////////////////////////////////////////////////////// void ClockTree::minimizeBufferInsertion(void) { if((this->_bufinsert != 2) || (this->_insertbufnum < 2)) return; cout << "\033[32m[Info]: Minimizing Buffer Insertion...\033[0m\n"; cout << "\033[32m Before Buffer Insertion Minimization\033[0m\n"; this->printBufferInsertedList(); queue<ClockTreeNode *> nodequeue; nodequeue.push(this->_firstchildrennode); // BFS while(!nodequeue.empty()) { if(!nodequeue.front()->getChildren().empty()) for(auto const &nodeptr : nodequeue.front()->getChildren()) nodequeue.push(nodeptr); if(nodequeue.front()->isFFSink()) { nodequeue.pop(); continue; } vector<ClockTreeNode *> ffchildren = this->getFFChildren(nodequeue.front()); set<double, greater<double>> bufdelaylist; bool continueflag = 0, insertflag = 1; double adddelay = 0; // Do not reduce the buffers for(auto const& nodeptr : ffchildren) { if(nodeptr->ifInsertBuffer()) bufdelaylist.insert(nodeptr->getInsertBufferDelay()); else { continueflag = 1; break; } } if(continueflag || bufdelaylist.empty()) { nodequeue.pop(); continue; } // Assess if the buffers can be reduced for(auto const& bufdelay : bufdelaylist) { for(auto const& nodeptr : ffchildren) { // Get the critical path by startpoint vector<CriticalPath *> findpath = this->searchCriticalPath('s', nodeptr->getGateData()->getGateName()); for(auto const& path : findpath) { double dataarrtime = 0, datareqtime = 0; // Calculate the Ci and Cj this->calculateClockLatencyWithoutDcc(path, &datareqtime, &dataarrtime); // Require time datareqtime += (path->getTsu() * this->_agingtsu) + this->_tc; // Arrival time dataarrtime += path->getTinDelay() + (path->getTcq() * this->_agingtcq) + (path->getDij() * this->_agingdij); for(auto const& clknodeptr : path->getEndPonitClkPath()) { if((clknodeptr == nodequeue.front()) && (bufdelay >= path->getEndPonitClkPath().back()->getInsertBufferDelay())) datareqtime += (bufdelay - path->getEndPonitClkPath().back()->getInsertBufferDelay()); if(clknodeptr->ifInsertBuffer()) datareqtime += clknodeptr->getInsertBufferDelay(); } for(auto const& clknodeptr : path->getStartPonitClkPath()) if(clknodeptr->ifInsertBuffer()) dataarrtime += clknodeptr->getInsertBufferDelay(); if(bufdelay >= nodeptr->getInsertBufferDelay()) dataarrtime += (bufdelay - nodeptr->getInsertBufferDelay()); // Timing violation if((datareqtime - dataarrtime) < 0) { insertflag = 0; break; } } findpath.clear(); // Get the critical path by endpoint findpath = this->searchCriticalPath('e', nodeptr->getGateData()->getGateName()); for(auto const& path : findpath) { double dataarrtime = 0, datareqtime = 0; // Calculate the Ci and Cj this->calculateClockLatencyWithoutDcc(path, &datareqtime, &dataarrtime); // Require time datareqtime += (path->getTsu() * this->_agingtsu) + this->_tc; // Arrival time dataarrtime += path->getTinDelay() + (path->getTcq() * this->_agingtcq) + (path->getDij() * this->_agingdij); for(auto const& clknodeptr : path->getStartPonitClkPath()) { if((clknodeptr == nodequeue.front()) && (bufdelay >= path->getStartPonitClkPath().back()->getInsertBufferDelay())) datareqtime += (bufdelay - path->getStartPonitClkPath().back()->getInsertBufferDelay()); if(clknodeptr->ifInsertBuffer()) datareqtime += clknodeptr->getInsertBufferDelay(); } for(auto const& clknodeptr : path->getEndPonitClkPath()) if(clknodeptr->ifInsertBuffer()) dataarrtime += clknodeptr->getInsertBufferDelay(); if(bufdelay >= nodeptr->getInsertBufferDelay()) dataarrtime += (bufdelay - nodeptr->getInsertBufferDelay()); // Timing violation if((datareqtime - dataarrtime) < 0) { insertflag = 0; break; } } if(!insertflag) break; } if(insertflag) { adddelay = bufdelay; break; } } // Reduce the buffers if(insertflag && (adddelay != 0)) { nodequeue.front()->setIfInsertBuffer(1); nodequeue.front()->setInsertBufferDelay(adddelay); this->_insertbufnum++; for(auto const& nodeptr : ffchildren) { if(nodeptr->ifInsertBuffer()) { double delay = nodeptr->getInsertBufferDelay() - adddelay; nodeptr->setInsertBufferDelay(delay); if(delay <= 0) { this->_insertbufnum--; nodeptr->setIfInsertBuffer(0); nodeptr->setInsertBufferDelay(0); } } } } nodequeue.pop(); } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Search the node in clock tree with the specific gate name // Input parameter: // gatename: specific buffer/FF name // ///////////////////////////////////////////////////////////////////// ClockTreeNode *ClockTree::searchClockTreeNode(string gatename) { if(gatename.compare(this->_clktreeroot->getGateData()->getGateName()) == 0) return this->_clktreeroot; // Search in buffer list map<string, ClockTreeNode *>::iterator findnode = this->_buflist.find(gatename); if(findnode != this->_buflist.end()) return findnode->second; // Search in FF list findnode = this->_ffsink.find(gatename); if( findnode != this->_buflist.end() ) return findnode->second; return NULL ; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Search the node in clock tree with the specific node number // Input parameter: // nodenum: specific clock tree node number // ///////////////////////////////////////////////////////////////////// ClockTreeNode *ClockTree::searchClockTreeNode(long nodenum) { if(nodenum < 0) return nullptr; ClockTreeNode *findnode = nullptr; // Search in buffer list for(auto const& node: this->_buflist) { if(node.second->getNodeNumber() == nodenum) { findnode = node.second; break; } } if(findnode != nullptr) return findnode; // Search in FF list for(auto const& node: this->_ffsink) { if(node.second->getNodeNumber() == nodenum) { findnode = node.second; break; } } return findnode; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Search the critical path with the specific startpoint/endpoint // Input parameter: // selection: 's' => startpoint // 'e' => endpoint // pointname: specific name of startpoint/endpoint // ///////////////////////////////////////////////////////////////////// vector<CriticalPath *> ClockTree::searchCriticalPath(char selection, string pointname) { vector<CriticalPath *> findpathlist; if((selection != 's') || (selection != 'e')) return findpathlist; for(auto const &pathptr : this->_pathlist) { if((pathptr->getPathType() == NONE) || (pathptr->getPathType() == PItoPO)) continue; string name = ""; switch(selection) { // startpoint case 's': name = pathptr->getStartPointName(); break; // endpoint case 'e': name = pathptr->getEndPointName(); break; default: break; } if(pointname.compare(name) == 0) { findpathlist.resize(findpathlist.size() + 1); findpathlist.back() = pathptr; } } return findpathlist; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Report all FFs under the specific clock tree node // ///////////////////////////////////////////////////////////////////// vector<ClockTreeNode *> ClockTree::getFFChildren(ClockTreeNode *node) { vector<ClockTreeNode *> ffchildren; if((node == nullptr) || node->isFFSink()) return ffchildren; queue<ClockTreeNode *> nodequeue; nodequeue.push(node); // BFS while(!nodequeue.empty()) { if(!nodequeue.front()->getChildren().empty()) for(auto const &nodeptr : nodequeue.front()->getChildren()) nodequeue.push(nodeptr); if(nodequeue.front()->isFFSink() && nodequeue.front()->ifUsed()) { ffchildren.resize(ffchildren.size() + 1); ffchildren.back() = nodequeue.front(); } nodequeue.pop(); } return ffchildren; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Dump to files // 1. DCC // 2. Clock gating cell // 3. Insserted buffer // ///////////////////////////////////////////////////////////////////// void ClockTree::dumpToFile(void) { this->dumpDccListToFile(); this->dumpClockGatingListToFile(); this->dumpBufferInsertionToFile(); } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Print whole clock tree presented in depth // ///////////////////////////////////////////////////////////////////// void ClockTree::printClockTree(void) { cout << "\033[34m----- [ Clock Tree ] -----\033[0m\n"; if(this->_clktreeroot == nullptr) { cout << "\t[Info]: Empty clock tree.\n"; cout << "\033[34m----- [ Clock Tree End ] -----\033[0m\n"; return; } long bufnum = 0, ffnum = 0; queue<ClockTreeNode *> nodequeue; nodequeue.push(this->_clktreeroot); cout << "Depth: Node_name(Node_num, if_used, is_cg" << ((this->_placedcc) ? ", place_dcc)\n" : ")\n"); cout << "Depth: (buffer_num, ff_num)\n"; cout << this->_clktreeroot->getDepth() << ": "; // BFS while(!nodequeue.empty()) { long nowdepth = nodequeue.front()->getDepth(); cout << nodequeue.front()->getGateData()->getGateName() << "(" << nodequeue.front()->getNodeNumber() << ", "; cout << nodequeue.front()->ifUsed() << ", " << nodequeue.front()->ifClockGating(); (this->_placedcc) ? cout << ", " << nodequeue.front()->ifPlacedDcc() << ")" : cout << ")"; if((nodequeue.front() != this->_clktreeroot) && nodequeue.front()->ifUsed()) (nodequeue.front()->isFFSink()) ? ffnum++ : bufnum++; if(!nodequeue.front()->getChildren().empty()) for(auto const &nodeptr : nodequeue.front()->getChildren()) nodequeue.push(nodeptr); nodequeue.pop(); if(!nodequeue.empty()) { if(nowdepth == nodequeue.front()->getDepth()) cout << ", "; else { cout << "\n" << nowdepth << ": (" << bufnum << ", " << ffnum << ")\n"; bufnum = 0, ffnum = 0; cout << nodequeue.front()->getDepth() << ": "; } } } cout << "\n" << this->_maxlevel << ": (" << bufnum << ", " << ffnum << ")\n"; cout << "\033[34m----- [ Clock Tree End ] -----\033[0m\n"; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Print one of critical path with given specific critical path // number // Input parameter: // pathnum: specific critical path number // verbose: 0 => briefness // 1 => detail // ///////////////////////////////////////////////////////////////////// void ClockTree::printSingleCriticalPath(long pathnum, bool verbose) { cout << "\033[34m----- [ Single Critical Path ] -----\033[0m\n"; if((pathnum < 0) || (pathnum > this->_pathlist.size())) cout << "\033[34m[Info]: Path NO." << pathnum << " doesn't exist.\033[0m\n"; else this->_pathlist.at(pathnum)->printCriticalPath(verbose); cout << "\033[34m----- [ Single Critical Path end ] -----\033[0m\n"; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Print one of critical path with given a specific // startpoint/endpoint // Input parameter: // selection: 's' => startpoint // 'e' => endpoint // pointname: specific name of startpoint/endpoint // verbose: 0 => briefness // 1 => detail // ///////////////////////////////////////////////////////////////////// void ClockTree::printSingleCriticalPath(char selection, string pointname, bool verbose) { cout << "\033[34m----- [ Single Critical Path ] -----\033[0m\n"; vector<CriticalPath *> findpathlist = this->searchCriticalPath(selection, pointname); if(findpathlist.empty()) cout << "\033[34m[Info]: Ponit name " << pointname << " of path doesn't exist.\033[0m\n"; else for(auto const& path : findpathlist) path->printCriticalPath(verbose); cout << "\033[34m----- [ Single Critical Path end ] -----\033[0m\n"; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Print all critical path information // ///////////////////////////////////////////////////////////////////// void ClockTree::printAllCriticalPath(void) { cout << "\033[34m----- [ All Critical Paths List ] -----\033[0m\n"; if(this->_pathlist.empty()) { cout << "\t\033[34m[Info]: Non critical path.\033[0m\n"; cout << "\033[34m----- [ Critical Paths List End ] -----\033[0m\n"; return; } for(auto const& pathptr : this->_pathlist) pathptr->printCriticalPath(0); cout << "\033[34m----- [ Critical Path List End ] -----\033[0m\n"; } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Print all DCC information (location and type) // ///////////////////////////////////////////////////////////////////// void ClockTree::printDccList(void) { if( !this->_placedcc) return; cout << "\t*** # of inserted DCCs : " << this->_dcclist.size() << "\n"; cout << "\t*** # of DCCs placed at last buffer: " << this->_dccatlastbufnum << "\n"; cout << "\t*** Inserted DCCs List : " ; if( !this->_placedcc || this->_dcclist.empty() ) cout << "N/A\n"; else{ for( auto const& node: this->_dcclist ) cout << node.first << "(" << node.second->getNodeNumber() << ","<< node.second->getDccType() << ((node.second != this->_dcclist.rbegin()->second) ? "), " : ")\n"); cout << endl ; for( auto const& node: this->_dcclist ) printf("%ld -1 %f\n", (node.second->getNodeNumber()-1)/2*3+1, (double)node.second->getDccType()/100 ); } cout << "\t*** DCCs Placed at Last Buffer : "; if(!this->_placedcc || (this->_dccatlastbufnum == 0)) cout << "N/A\n"; else { bool firstprint = true; for(auto const& node: this->_dcclist) { if(node.second->isFinalBuffer()) { if( firstprint ) firstprint = false ; else cout << "), " ; cout << node.first << "(" << node.second->getNodeNumber() << ","<< node.second->getDccType(); } } cout << ")\n"; } } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Print all clock gating cell information (location and gating // probability) // ///////////////////////////////////////////////////////////////////// void ClockTree::printClockGatingList(void) { cout << "\t*** Clock Gating Cells List : "; if(!this->_clkgating || this->_cglist.empty()) cout << "N/A\n"; else for(auto const& node: this->_cglist) cout << node.first << "(" << node.second->getGatingProbability() << ((node.second != this->_cglist.rbegin()->second) ? "), " : ")\n"); } ///////////////////////////////////////////////////////////////////// // // ClockTree Class - Public Method // Print all inserted buffer information (location and buffer delay) // ///////////////////////////////////////////////////////////////////// void ClockTree::printBufferInsertedList(void) { if((this->_bufinsert < 1) || (this->_bufinsert > 2)) return; cout << "\t*** # of inserted buffers : " << this->_insertbufnum << "\n"; cout << "\t*** Inserted Buffers List : "; if((this->_bufinsert < 1) || (this->_bufinsert > 2) || (this->_insertbufnum == 0)) cout << "N/A\n"; else { long counter = 0; // Buffer list for(auto const& node: this->_buflist) { if(node.second->ifInsertBuffer()) { counter++; cout << node.first << "(" << node.second->getInsertBufferDelay(); cout << ((counter != this->_insertbufnum) ? "), " : ")\n"); } } // FF list for(auto const& node: this->_ffsink) { if(node.second->ifInsertBuffer()) { counter++; cout << node.first << "(" << node.second->getInsertBufferDelay(); cout << ((counter != this->_insertbufnum) ? "), " : ")\n"); } } } } void ClockTree::printClockNode() { //---- Iteration ---------------------------------------------------------------- int nodeID = 0 ; ClockTreeNode *node = NULL ; while( true ) { printf( "---------------------- " CYAN"Print Topology " RESET"----------------------------\n" ); printf(" Clk_Name( nodeID, parentID, " GREEN"O" RESET"/" RED"X" RESET" )\n"); printf( GREEN" O" RESET": those clk nodes that are Not masked\n"); printf( RED " X" RESET": those clk nodes that are masked\n"); printf(" number <= 0 : leave the loop\n"); printf(" number > 0 : The ID of clock node\n"); printf(" Please type the clknode ID:"); cin >> nodeID ; if( nodeID < 0 ) break ; else { node = searchClockTreeNode( nodeID ) ; if( node == NULL ) cerr << RED"[ERROR]" RESET<< "The node ID " << nodeID << " is not identified\n" ; else printClockNode( node, 0 ) ; } } } void ClockTree::printClockNode( ClockTreeNode*node, int layer ) { if( node == NULL ) return ; else { if( node->ifPlacedDcc() == false ) printf( "%s( %4ld, %4ld, " RED "X" RESET" ) ", node->getGateData()->getGateName().c_str(), node->getNodeNumber(), node->getParent()->getNodeNumber()); else printf( "%s( %4ld, %4ld, " GREEN"O" RESET" ) ", node->getGateData()->getGateName().c_str(), node->getNodeNumber(), node->getParent()->getNodeNumber()); for( int j = 0 ; j < node->getChildren().size(); j++ ) { if( j != 0 ) printNodeLayerSpace( layer + 1 ) ; printClockNode( node->getChildren().at(j), layer+1 ) ; } cout << endl ; } } void ClockTree::printNodeLayerSpace( int layer ) { for( int i = 0 ; i < layer ; i++ ) printf( " " ); } void ClockTree::dumpDcctoFile() { FILE *fPtr; string filename = this->_outputdir + "Dcc_master_" + to_string( this->_tc ) + ".txt"; fPtr = fopen( filename.c_str(), "w" ); if( !fPtr ) { cerr << RED"[Error]" RESET "Cannot open the DCC VTA file\n" ; return ; } fprintf( fPtr, "Tc %f\n", this->_tc ); for( auto node: this->_buflist ) { if( node.second->ifPlacedDcc() ) fprintf( fPtr, "%ld -1 %f\n", (node.second->getNodeNumber()-1)/2*3+1, ((float)node.second->getDccType())/100 ); } fclose(fPtr); }
35.090569
183
0.585905
eric830303
e203ea0a1c00fa15d3876e1ffe8d401c16c18701
416
hpp
C++
path.hpp
andybarry/peekmill
d990877ef943a791f66d19ed897f1421b8e6e0ea
[ "BSD-3-Clause" ]
1
2016-08-22T13:46:32.000Z
2016-08-22T13:46:32.000Z
path.hpp
andybarry/peekmill
d990877ef943a791f66d19ed897f1421b8e6e0ea
[ "BSD-3-Clause" ]
null
null
null
path.hpp
andybarry/peekmill
d990877ef943a791f66d19ed897f1421b8e6e0ea
[ "BSD-3-Clause" ]
null
null
null
#ifndef PATH_HPP #define PATH_HPP #include <opencv2/core/core.hpp> #include <vector> #include <iostream> using namespace std; using namespace cv; class Path{ private: Point2f path_start_; float units_; vector<Point2f> coords_; //like java generics public: Point2f GetPathStart(){return path_start_;} float GetUnits(){return units_;} Mat Draw(Mat image_in); Path();//add parameters }; #endif
16
47
0.725962
andybarry
e2050c55b5ad0efa8af19c8c4913c54c1a7d0cf0
4,341
cpp
C++
lib/ZumoShield/ZumoShieldEncoders.cpp
Wataru-Oshima-Tokyo/zumoShield
7d1c24c8fc6e3c95fe326923cf48215604ad3fc7
[ "MIT" ]
null
null
null
lib/ZumoShield/ZumoShieldEncoders.cpp
Wataru-Oshima-Tokyo/zumoShield
7d1c24c8fc6e3c95fe326923cf48215604ad3fc7
[ "MIT" ]
null
null
null
lib/ZumoShield/ZumoShieldEncoders.cpp
Wataru-Oshima-Tokyo/zumoShield
7d1c24c8fc6e3c95fe326923cf48215604ad3fc7
[ "MIT" ]
null
null
null
// Copyright Pololu Corporation. For more information, see http://www.pololu.com/ #include <ZumoShieldEncoders.h> #include <FastGPIO.h> #include <avr/interrupt.h> #include <Arduino.h> #define LEFT_XOR 8 #define LEFT_B IO_E2 #define RIGHT_XOR 7 #define RIGHT_B 23 #define RIGHT_CNT_FLAG 0x0001 #define LEFT_CNT_FLAG 0x0002 static volatile bool lastLeftA; static volatile bool lastLeftB; static volatile bool lastRightA; static volatile bool lastRightB; static volatile bool errorLeft; static volatile bool errorRight; // These count variables are uint16_t instead of int16_t because // signed integer overflow is undefined behavior in C++. static volatile uint16_t countLeft; static volatile uint16_t countRight; // int countLeft=0; // int countRight=0; int flag = 0; ISR(TIMER1_CAPT_vect) { bit_is_clear(TIFR1, ICF1); if (digitalRead(5) == HIGH) { countRight++; } else { countRight--; } flag |= RIGHT_CNT_FLAG; } ISR(TIMER3_CAPT_vect) { bit_is_clear(TIFR3, ICF3); if (digitalRead(11) == LOW) { countLeft++; } else { countLeft--; } flag |= LEFT_CNT_FLAG; } // static void rightISR() // { // bool newRightB = FastGPIO::Pin<RIGHT_B>::isInputHigh(); // bool newRightA = FastGPIO::Pin<RIGHT_XOR>::isInputHigh() ^ newRightB; // countRight += (newRightA ^ lastRightB) - (lastRightA ^ newRightB); // if((lastRightA ^ newRightA) & (lastRightB ^ newRightB)) // { // errorRight = true; // } // lastRightA = newRightA; // lastRightB = newRightB; // } void ZumoShieldEncoders::init2() { // Set the pins as pulled-up inputs. FastGPIO::Pin<LEFT_XOR>::setInputPulledUp(); FastGPIO::Pin<LEFT_B>::setInputPulledUp(); FastGPIO::Pin<RIGHT_XOR>::setInputPulledUp(); FastGPIO::Pin<RIGHT_B>::setInputPulledUp(); // Enable pin-change interrupt on PB4 for left encoder, and disable other // pin-change interrupts. PCICR = (1 << PCIE0); PCMSK0 = (1 << PCINT4); PCIFR = (1 << PCIF0); // Clear its interrupt flag by writing a 1. /* * ICP1はアナログコンパレータと機能を兼用しているので * それをDISABLEとする。 * 「0」でENABLE、「1」でDISABLE */ ACSR = 0x80; ADCSRB = 0x00; DIDR1 = 0x00; /* * ICP1(インプットキャプチャー)の設定 */ TCCR1A= 0x00; TCCR1B = 0x41; // Disable Input Capture Noise Canceler // Input Capture Edge : RISE TIMSK1 = 0x20; // Enable Input Capture Interrupt /* * ICP3(インプットキャプチャー)の設定 */ TCCR3A= 0x00; TCCR3B = 0x41; // Disable Input Capture Noise Canceler // Input Capture Edge : RISE TIMSK3 = 0x20; // Enable Input Capture Interrupt /* * DEBUGにシリアルモニタを使用 */ // Enable interrupt on PE6 for the right encoder. We use attachInterrupt // instead of defining ISR(INT6_vect) ourselves so that this class will be // compatible with other code that uses attachInterrupt. //attachInterrupt(4, rightISR, CHANGE); // Initialize the variables. It's good to do this after enabling the // interrupts in case the interrupts fired by accident as we were enabling // them. lastLeftB = FastGPIO::Pin<LEFT_B>::isInputHigh(); lastLeftA = FastGPIO::Pin<LEFT_XOR>::isInputHigh() ^ lastLeftB; countLeft = 0; errorLeft = 0; lastRightB = FastGPIO::Pin<RIGHT_B>::isInputHigh(); lastRightA = FastGPIO::Pin<RIGHT_XOR>::isInputHigh() ^ lastRightB; countRight = 0; errorRight = 0; } int16_t ZumoShieldEncoders::getCountsLeft() { init(); cli(); int16_t counts = countLeft; sei(); return counts; } int16_t ZumoShieldEncoders::getCountsRight() { init(); cli(); int16_t counts = countRight; sei(); return counts; } int16_t ZumoShieldEncoders::getCountsAndResetLeft() { init(); cli(); int16_t counts = countLeft; countLeft = 0; sei(); return counts; } int16_t ZumoShieldEncoders::getCountsAndResetRight() { init(); cli(); int16_t counts = countRight; countRight = 0; sei(); return counts; } bool ZumoShieldEncoders::checkErrorLeft() { init(); bool error = errorLeft; errorLeft = 0; return error; } bool ZumoShieldEncoders::checkErrorRight() { init(); bool error = errorRight; errorRight = 0; return error; }
23.464865
82
0.647086
Wataru-Oshima-Tokyo
e206e29c72baee3fd6a679c5b12cfab20e8e7c49
418
cpp
C++
Challenges/C++/ex2.cpp
ifyGecko/RE_Challenges
a7a86481d9a75d0dde81de77716ea42c81ce3d69
[ "Unlicense" ]
5
2019-08-24T00:19:42.000Z
2020-09-26T14:21:07.000Z
Challenges/C++/ex2.cpp
DJN1/RE_Challenges-1
4bc66ed6d8765f044322b297b69a156e2385d19f
[ "Unlicense" ]
1
2022-02-16T18:05:15.000Z
2022-02-16T18:05:15.000Z
Challenges/C++/ex2.cpp
DJN1/RE_Challenges-1
4bc66ed6d8765f044322b297b69a156e2385d19f
[ "Unlicense" ]
9
2019-08-31T21:10:31.000Z
2020-09-14T23:13:10.000Z
#include<iostream> #include<cstdlib> using namespace std; class a{ public: int b; a(){ b=2019; }; }; int main(int argc, char** argv){ a c; if(argc !=2){ cout << "Usage: ./prog input\n"; cout << "Hint: ./prog -h\n"; }else if(argv[1]==string("-h")){ cout << "Classes might need to undergo construction.\n"; }else{ atoi(argv[1])==c.b?cout << "Score!\n":cout << "Fail!\n"; } return 0; }
17.416667
60
0.557416
ifyGecko
e20956abe78d0338cd55dac2fa01cca43e31856c
503
cc
C++
function_ref/snippets/snippet-function_ref-spec-rev.cc
descender76/cpp_proposals
2eb7e2f59257b376dadd1b66464e076c3de23ab1
[ "BSL-1.0" ]
1
2022-01-21T20:10:46.000Z
2022-01-21T20:10:46.000Z
function_ref/snippets/snippet-function_ref-spec-rev.cc
descender76/cpp_proposals
2eb7e2f59257b376dadd1b66464e076c3de23ab1
[ "BSL-1.0" ]
null
null
null
function_ref/snippets/snippet-function_ref-spec-rev.cc
descender76/cpp_proposals
2eb7e2f59257b376dadd1b66464e076c3de23ab1
[ "BSL-1.0" ]
null
null
null
// namespace std { template <typename Signature> class function_ref { void* erased_object; R(*erased_function)(void*, Args...); // `R`, and `Args...` are the return type, and the parameter-type-list, // of the function type `Signature`, respectively. public: function_ref(void* obj_, R (*callback_)(void*,Args...)) noexcept : erased_object{obj_}, erased_function{callback_} {} function_ref(const function_ref&) noexcept = default; // ...
31.4375
125
0.630219
descender76
e20b30fbf131c7e7f69f867433bdfef197d5a881
1,195
hpp
C++
kjoin/src/util/util_func.hpp
lanpay-lulu/CPP-Intersection
2326a9f46a4d75d11ca0e20adab91b0acb8bcea0
[ "MIT" ]
null
null
null
kjoin/src/util/util_func.hpp
lanpay-lulu/CPP-Intersection
2326a9f46a4d75d11ca0e20adab91b0acb8bcea0
[ "MIT" ]
null
null
null
kjoin/src/util/util_func.hpp
lanpay-lulu/CPP-Intersection
2326a9f46a4d75d11ca0e20adab91b0acb8bcea0
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include <fstream> #include <sys/time.h> namespace wshfunc{ size_t get_line_cnt(std::string & filename) { std::ifstream infile(filename); size_t cnt = std::count(std::istreambuf_iterator<char>(infile), std::istreambuf_iterator<char>(), '\n'); infile.close(); return cnt; } bool is_file_empty(std::string & filename) { std::string line; std::ifstream fin(filename); while (std::getline(fin, line)) { if(line.length() > 2) { fin.close(); return false; } } fin.close(); return true; } size_t gettime() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec*1000 + tv.tv_usec/1000; } std::vector<std::string> split(std::string str, std::string delimeter) { std::vector<std::string> vec; size_t startIndex = 0; size_t endIndex = 0; while( (endIndex = str.find(delimeter, startIndex)) < str.size() ) { std::string val = str.substr(startIndex, endIndex - startIndex); vec.push_back(val); startIndex = endIndex + delimeter.size(); } if(startIndex < str.size()) { std::string val = str.substr(startIndex); vec.push_back(val); } return vec; } }; // end of namespace
22.54717
72
0.661088
lanpay-lulu
e20e3b57956618c03b09418745bb03ff0b3989bd
4,484
cpp
C++
src/arch/android/platform_android.cpp
nebular/PixEngine_core
fc5f928641ed8c0d14254fdfc68973b3b144297f
[ "BSD-3-Clause" ]
1
2020-10-23T21:16:49.000Z
2020-10-23T21:16:49.000Z
src/arch/android/platform_android.cpp
nebular/PixEngine_core
fc5f928641ed8c0d14254fdfc68973b3b144297f
[ "BSD-3-Clause" ]
2
2020-03-02T22:43:09.000Z
2020-03-02T22:46:44.000Z
src/arch/android/platform_android.cpp
nebular/PixFu
fc5f928641ed8c0d14254fdfc68973b3b144297f
[ "BSD-3-Clause" ]
null
null
null
#ifdef ANDROID // // Created by rodo on 2020-01-24. // #include "Fu.hpp" #include "Mouse.hpp" #include "Keyboard.hpp" #include "platform_android.hpp" #include "OpenGlUtils.h" #include "Utils.hpp" #include "androidapi.h" #include "VirtualKeys.hpp" #include <iostream> namespace Pix { void LogV(const std::string &tag, std::string text) { ALOGV("[V:%s] %s", tag.c_str(), text.c_str()); } void LogE(const std::string &tag, std::string text) { ALOGE("[E:%s] %s", tag.c_str(), text.c_str()); } static constexpr int ACTION_UP = 1; static constexpr int ACTION_DOWN = 0; static constexpr int ACTION_MOVE = 2; static constexpr int ACTION_CANCEL = 3; // other than primary finger static constexpr int ACTION_POINTER_DOWN = 5; static constexpr int ACTION_POINTER_UP = 6; PixFuPlatformAndroid::PixFuPlatformAndroid(Fu *bootInstance) { OpenGlUtils::VERSION = "v300es"; pBootInstance = bootInstance; } PixFuPlatformAndroid::~PixFuPlatformAndroid() { deinit(); } bool PixFuPlatformAndroid::init(Fu *engine) { Mouse::enable(); Keyboard::enable(); VirtualKeys::enable({ Colors::WHITE, 1, true}); cLoneKeys = VirtualKeys::instance(); cLoneKeys->reset(); return true; } std::pair<bool, bool> PixFuPlatformAndroid::events() { // onpause will route here bool focused = true; // window_is_focused(); bool active = true; // !get_window_is_closing(); return {active, focused}; } void PixFuPlatformAndroid::commit() { // no frame commit, android does that after returning from tick } void PixFuPlatformAndroid::deinit() { // something will come here for sure } void PixFuPlatformAndroid::onFps(Fu *engine, int fps) { std::string sTitle = "PixFu - FPS: " + std::to_string(fps); } void Mouse::poll() { // already done } void Keyboard::poll() { } void Fu::start() { // this platform does not run a loop } // called from Launcher to send a MotionEvent (Touch) void PixFuPlatformAndroid::inputMotionEvent(MotionEvent_t event) { Mouse *mouse = Mouse::instance(); if (mouse == nullptr) return; // we have touch information // lets simulate a mouse // // I tried an elaborate routine to simulate clicks on touch but it was getting too complicated and prone to fail // I came up with this simple approach that kind of works pretty well. It uses LoneKeys to paint // 2 virtual mouse buttons on screen, and multitouch is supported so you can move the pointer with one finger // and use the buttons with other. For implementing another mouse behavior, you have all details in tCurrentMotionEvent // tCurrentMotionEvent = event; int action = event.RawAction; // Iterate through virtual keys and set their state. // will return 0 -> key pressed with primary pointer (X0Y0), 1 -> with secondary (X1Y1), -1 No key pressed. int keysRegion = cLoneKeys->input(tCurrentMotionEvent.X0, tCurrentMotionEvent.Y0, tCurrentMotionEvent.X1, tCurrentMotionEvent.Y1, tCurrentMotionEvent.Action == ACTION_UP); bool twoFingers = event.PointersCount > 1; // LogV ("ANDR", SF("Event: buttons %d, action %d, index %d", tCurrentMotionEvent.PointersCount, tCurrentMotionEvent.RawAction, tCurrentMotionEvent.PointerId)); switch (action) { case ACTION_POINTER_UP: for (int i = 0; i < mouse->BUTTONS; i++) mouse->inputButton(i, false); break; case ACTION_UP: case ACTION_CANCEL: // end touch (no fingers on screen) // reset virtual mouse button status cLoneKeys->reset(); // break through to update coordinates and real state (that we have reset here) case ACTION_DOWN: case ACTION_POINTER_DOWN: if (twoFingers) for (int i = 0; i < mouse->BUTTONS; i++) mouse->inputButton(i, cLoneKeys->GetFakeMouse(i)); case ACTION_MOVE: // These actions update the engine mouse button status from // our local copy in cLoneKeys if (twoFingers) for (int i = 0; i < mouse->BUTTONS; i++) mouse->inputButton(i, cLoneKeys->GetFakeMouse(i)); // then updates the right coordinates: One of them is the finger in the buttons area, // the other the pointer finger. We select the right one ! if (keysRegion != 0) mouse->input(tCurrentMotionEvent.X0, tCurrentMotionEvent.Y0); else if (twoFingers) // may happen that only one finger is pressing buttons but none is pointing mouse->input(tCurrentMotionEvent.X1, tCurrentMotionEvent.Y1); break; default: break; } } } #endif
25.919075
161
0.695584
nebular
e20f94442b3d6cf4ae6ef4cb320e22ad706dee5f
11,268
cpp
C++
SphereNormals.cpp
Svengali/cblib
77ddfd452cff842575750b9e6d792790f5ec5fee
[ "Zlib" ]
1
2021-05-01T04:34:24.000Z
2021-05-01T04:34:24.000Z
SphereNormals.cpp
Svengali/cblib
77ddfd452cff842575750b9e6d792790f5ec5fee
[ "Zlib" ]
null
null
null
SphereNormals.cpp
Svengali/cblib
77ddfd452cff842575750b9e6d792790f5ec5fee
[ "Zlib" ]
null
null
null
#include "SphereNormals.h" /** this is generated by gMakeSphere::Normals() **/ START_CB const int c_numSphereNormals = 258; const int c_numSpherePositiveNormals = 42; static const float c_sphereVerts[] = { 0.426401f,0.639602f,0.639602f, 0.639602f,0.639602f,0.426401f, 0.639602f,0.426401f,0.639602f, 0.408248f,0.816497f,0.408248f, 0.816497f,0.408248f,0.408248f, 0.408248f,0.408248f,0.816497f, 0.577350f,0.788675f,0.211325f, 0.211325f,0.577350f,0.788675f, 0.577350f,0.211325f,0.788675f, 0.211325f,0.788675f,0.577350f, 0.788675f,0.577350f,0.211325f, 0.788675f,0.211325f,0.577350f, 0.208847f,0.404615f,0.890320f, 0.404615f,0.208847f,0.890320f, 0.890320f,0.404615f,0.208847f, 0.404615f,0.890320f,0.208847f, 0.890320f,0.208847f,0.404615f, 0.208847f,0.890320f,0.404615f, 0.198757f,0.198757f,0.959683f, 0.959683f,0.198757f,0.198757f, 0.198757f,0.959683f,0.198757f, 0.000000f,0.707107f,0.707107f, 0.707107f,0.707107f,0.000000f, 0.707107f,0.000000f,0.707107f, 0.555570f,0.831470f,0.000000f, 0.555570f,0.000000f,0.831470f, 0.000000f,0.555570f,0.831470f, 0.831470f,0.000000f,0.555570f, 0.831470f,0.555570f,0.000000f, 0.000000f,0.831470f,0.555570f, 0.923880f,0.382683f,0.000000f, 0.382683f,0.923880f,0.000000f, 0.382683f,0.000000f,0.923880f, 0.000000f,0.382683f,0.923880f, 0.923880f,0.000000f,0.382683f, 0.000000f,0.923880f,0.382683f, 0.195090f,0.980785f,0.000000f, 0.195090f,0.000000f,0.980785f, 0.000000f,0.195090f,0.980785f, 0.980785f,0.195090f,0.000000f, 0.000000f,0.980785f,0.195090f, 0.980785f,0.000000f,0.195090f, 0.577350f,-0.211325f,0.788675f, 0.788675f,0.577350f,-0.211325f, 0.577350f,0.788675f,-0.211325f, 0.788675f,-0.211325f,0.577350f, -0.211325f,0.788675f,0.577350f, -0.211325f,0.577350f,0.788675f, 0.404615f,0.890320f,-0.208847f, 0.404615f,-0.208847f,0.890320f, 0.890320f,0.404615f,-0.208847f, 0.890320f,-0.208847f,0.404615f, -0.208847f,0.404615f,0.890320f, -0.208847f,0.890320f,0.404615f, 0.000000f,0.000000f,1.000000f, 0.000000f,1.000000f,0.000000f, 1.000000f,0.000000f,0.000000f, -0.198757f,0.959683f,0.198757f, 0.959683f,0.198757f,-0.198757f, 0.198757f,0.959683f,-0.198757f, -0.198757f,0.198757f,0.959683f, 0.198757f,-0.198757f,0.959683f, 0.959683f,-0.198757f,0.198757f, 0.639602f,0.639602f,-0.426401f, 0.639602f,-0.426401f,0.639602f, -0.426401f,0.639602f,0.639602f, 0.408248f,0.816497f,-0.408248f, -0.408248f,0.408248f,0.816497f, 0.816497f,-0.408248f,0.408248f, -0.408248f,0.816497f,0.408248f, 0.816497f,0.408248f,-0.408248f, 0.408248f,-0.408248f,0.816497f, -0.404615f,0.890320f,0.208847f, 0.890320f,-0.404615f,0.208847f, -0.404615f,0.208847f,0.890320f, 0.890320f,0.208847f,-0.404615f, 0.208847f,0.890320f,-0.404615f, 0.208847f,-0.404615f,0.890320f, -0.639602f,0.426401f,0.639602f, 0.639602f,-0.639602f,0.426401f, 0.426401f,0.639602f,-0.639602f, -0.639602f,0.639602f,0.426401f, 0.426401f,-0.639602f,0.639602f, 0.639602f,0.426401f,-0.639602f, 0.211325f,-0.577350f,0.788675f, -0.577350f,0.211325f,0.788675f, 0.211325f,0.788675f,-0.577350f, 0.788675f,0.211325f,-0.577350f, 0.788675f,-0.577350f,0.211325f, -0.577350f,0.788675f,0.211325f, 0.408248f,0.408248f,-0.816497f, -0.816497f,0.408248f,0.408248f, 0.408248f,-0.816497f,0.408248f, 0.211325f,-0.788675f,0.577350f, 0.211325f,0.577350f,-0.788675f, 0.577350f,-0.788675f,0.211325f, -0.788675f,0.577350f,0.211325f, -0.788675f,0.211325f,0.577350f, 0.577350f,0.211325f,-0.788675f, 0.404615f,-0.890320f,0.208847f, 0.208847f,-0.890320f,0.404615f, 0.208847f,0.404615f,-0.890320f, -0.890320f,0.404615f,0.208847f, 0.404615f,0.208847f,-0.890320f, -0.890320f,0.208847f,0.404615f, -0.959683f,0.198757f,0.198757f, 0.198757f,-0.959683f,0.198757f, 0.198757f,0.198757f,-0.959683f, 0.000000f,0.980785f,-0.195090f, 0.000000f,-0.195090f,0.980785f, -0.195090f,0.000000f,0.980785f, 0.980785f,0.000000f,-0.195090f, 0.980785f,-0.195090f,0.000000f, -0.195090f,0.980785f,0.000000f, 0.923880f,0.000000f,-0.382683f, 0.923880f,-0.382683f,0.000000f, -0.382683f,0.000000f,0.923880f, 0.000000f,-0.382683f,0.923880f, 0.000000f,0.923880f,-0.382683f, -0.382683f,0.923880f,0.000000f, 0.000000f,0.831470f,-0.555570f, 0.000000f,-0.555570f,0.831470f, 0.831470f,-0.555570f,0.000000f, -0.555570f,0.000000f,0.831470f, 0.831470f,0.000000f,-0.555570f, -0.555570f,0.831470f,0.000000f, 0.000000f,0.707107f,-0.707107f, 0.707107f,0.000000f,-0.707107f, -0.707107f,0.000000f,0.707107f, 0.000000f,-0.707107f,0.707107f, -0.707107f,0.707107f,0.000000f, 0.707107f,-0.707107f,0.000000f, -0.831470f,0.555570f,0.000000f, -0.831470f,0.000000f,0.555570f, 0.555570f,-0.831470f,0.000000f, 0.555570f,0.000000f,-0.831470f, 0.000000f,-0.831470f,0.555570f, 0.000000f,0.555570f,-0.831470f, 0.382683f,-0.923880f,0.000000f, 0.382683f,0.000000f,-0.923880f, 0.000000f,-0.923880f,0.382683f, -0.923880f,0.382683f,0.000000f, 0.000000f,0.382683f,-0.923880f, -0.923880f,0.000000f,0.382683f, -0.980785f,0.195090f,0.000000f, -0.980785f,0.000000f,0.195090f, 0.000000f,0.195090f,-0.980785f, 0.195090f,0.000000f,-0.980785f, 0.195090f,-0.980785f,0.000000f, 0.000000f,-0.980785f,0.195090f, -0.198757f,-0.198757f,0.959683f, -0.198757f,0.959683f,-0.198757f, 0.959683f,-0.198757f,-0.198757f, 0.890320f,-0.404615f,-0.208847f, 0.890320f,-0.208847f,-0.404615f, -0.404615f,0.890320f,-0.208847f, -0.404615f,-0.208847f,0.890320f, -0.208847f,0.890320f,-0.404615f, -0.208847f,-0.404615f,0.890320f, -0.211325f,-0.577350f,0.788675f, -0.577350f,-0.211325f,0.788675f, -0.211325f,0.788675f,-0.577350f, 0.788675f,-0.577350f,-0.211325f, 0.788675f,-0.211325f,-0.577350f, -0.577350f,0.788675f,-0.211325f, 0.816497f,-0.408248f,-0.408248f, -0.408248f,-0.408248f,0.816497f, -0.408248f,0.816497f,-0.408248f, -0.788675f,-0.211325f,0.577350f, 0.577350f,-0.211325f,-0.788675f, 0.577350f,-0.788675f,-0.211325f, -0.788675f,0.577350f,-0.211325f, -0.211325f,0.577350f,-0.788675f, -0.211325f,-0.788675f,0.577350f, -0.639602f,-0.426401f,0.639602f, -0.426401f,-0.639602f,0.639602f, 0.639602f,-0.426401f,-0.639602f, 0.639602f,-0.639602f,-0.426401f, -0.639602f,0.639602f,-0.426401f, -0.426401f,0.639602f,-0.639602f, 0.404615f,-0.208847f,-0.890320f, -0.208847f,-0.890320f,0.404615f, -0.890320f,0.404615f,-0.208847f, -0.890320f,-0.208847f,0.404615f, -0.208847f,0.404615f,-0.890320f, 0.404615f,-0.890320f,-0.208847f, 0.408248f,-0.408248f,-0.816497f, -0.816497f,0.408248f,-0.408248f, -0.408248f,0.408248f,-0.816497f, -0.816497f,-0.408248f,0.408248f, 0.408248f,-0.816497f,-0.408248f, -0.408248f,-0.816497f,0.408248f, 0.426401f,-0.639602f,-0.639602f, -0.639602f,0.426401f,-0.639602f, -0.639602f,-0.639602f,0.426401f, 0.198757f,-0.198757f,-0.959683f, -0.959683f,0.198757f,-0.198757f, -0.198757f,-0.959683f,0.198757f, 0.198757f,-0.959683f,-0.198757f, -0.198757f,0.198757f,-0.959683f, -0.959683f,-0.198757f,0.198757f, 0.000000f,-1.000000f,0.000000f, 0.000000f,0.000000f,-1.000000f, -1.000000f,0.000000f,0.000000f, -0.890320f,0.208847f,-0.404615f, -0.404615f,0.208847f,-0.890320f, -0.404615f,-0.890320f,0.208847f, 0.208847f,-0.890320f,-0.404615f, 0.208847f,-0.404615f,-0.890320f, -0.890320f,-0.404615f,0.208847f, -0.577350f,-0.788675f,0.211325f, 0.211325f,-0.788675f,-0.577350f, 0.211325f,-0.577350f,-0.788675f, -0.788675f,-0.577350f,0.211325f, -0.577350f,0.211325f,-0.788675f, -0.788675f,0.211325f,-0.577350f, -0.195090f,0.000000f,-0.980785f, 0.000000f,-0.980785f,-0.195090f, 0.000000f,-0.195090f,-0.980785f, -0.980785f,-0.195090f,0.000000f, -0.195090f,-0.980785f,0.000000f, -0.980785f,0.000000f,-0.195090f, -0.923880f,-0.382683f,0.000000f, -0.382683f,-0.923880f,0.000000f, 0.000000f,-0.382683f,-0.923880f, 0.000000f,-0.923880f,-0.382683f, -0.382683f,0.000000f,-0.923880f, -0.923880f,0.000000f,-0.382683f, -0.555570f,0.000000f,-0.831470f, 0.000000f,-0.831470f,-0.555570f, -0.555570f,-0.831470f,0.000000f, -0.831470f,0.000000f,-0.555570f, 0.000000f,-0.555570f,-0.831470f, -0.831470f,-0.555570f,0.000000f, 0.000000f,-0.707107f,-0.707107f, -0.707107f,-0.707107f,0.000000f, -0.707107f,0.000000f,-0.707107f, -0.198757f,-0.959683f,-0.198757f, -0.198757f,-0.198757f,-0.959683f, -0.959683f,-0.198757f,-0.198757f, -0.208847f,-0.890320f,-0.404615f, -0.890320f,-0.404615f,-0.208847f, -0.404615f,-0.890320f,-0.208847f, -0.404615f,-0.208847f,-0.890320f, -0.890320f,-0.208847f,-0.404615f, -0.208847f,-0.404615f,-0.890320f, -0.211325f,-0.788675f,-0.577350f, -0.577350f,-0.788675f,-0.211325f, -0.211325f,-0.577350f,-0.788675f, -0.577350f,-0.211325f,-0.788675f, -0.788675f,-0.577350f,-0.211325f, -0.788675f,-0.211325f,-0.577350f, -0.408248f,-0.408248f,-0.816497f, -0.408248f,-0.816497f,-0.408248f, -0.816497f,-0.408248f,-0.408248f, -0.639602f,-0.639602f,-0.426401f, -0.639602f,-0.426401f,-0.639602f, -0.426401f,-0.639602f,-0.639602f }; static const int c_numSphereVerts = sizeof(c_sphereVerts)/sizeof(c_sphereVerts[0]); COMPILER_ASSERT(c_numSphereVerts == 3* c_numSphereNormals ); const Vec3 & GetSphereNormal(const int i) { ASSERT( i >= 0 && i < c_numSphereNormals ); const float * pF = c_sphereVerts + i*3; return *( (const Vec3 *)pF ); } const int c_numSphereNormalsSimple = 66; static const float c_sphereVertsSimple[] = { 0.408248f,0.408248f,0.816497f, 0.408248f,0.816497f,0.408248f, 0.816497f,0.408248f,0.408248f, 0.000000f,0.707107f,0.707107f, 0.707107f,0.000000f,0.707107f, 0.707107f,0.707107f,0.000000f, 0.000000f,0.382683f,0.923880f, 0.382683f,0.000000f,0.923880f, 0.000000f,0.923880f,0.382683f, 0.382683f,0.923880f,0.000000f, 0.923880f,0.000000f,0.382683f, 0.923880f,0.382683f,0.000000f, 1.000000f,0.000000f,0.000000f, 0.000000f,1.000000f,0.000000f, 0.000000f,0.000000f,1.000000f, 0.816497f,0.408248f,-0.408248f, 0.408248f,0.816497f,-0.408248f, -0.408248f,0.816497f,0.408248f, -0.408248f,0.408248f,0.816497f, 0.408248f,-0.408248f,0.816497f, 0.816497f,-0.408248f,0.408248f, -0.816497f,0.408248f,0.408248f, 0.408248f,-0.816497f,0.408248f, 0.408248f,0.408248f,-0.816497f, -0.382683f,0.000000f,0.923880f, 0.000000f,0.923880f,-0.382683f, -0.382683f,0.923880f,0.000000f, 0.923880f,0.000000f,-0.382683f, 0.000000f,-0.382683f,0.923880f, 0.923880f,-0.382683f,0.000000f, 0.707107f,0.000000f,-0.707107f, 0.000000f,0.707107f,-0.707107f, 0.000000f,-0.707107f,0.707107f, -0.707107f,0.707107f,0.000000f, 0.707107f,-0.707107f,0.000000f, -0.707107f,0.000000f,0.707107f, 0.382683f,0.000000f,-0.923880f, 0.000000f,0.382683f,-0.923880f, 0.000000f,-0.923880f,0.382683f, 0.382683f,-0.923880f,0.000000f, -0.923880f,0.382683f,0.000000f, -0.923880f,0.000000f,0.382683f, -0.408248f,-0.408248f,0.816497f, -0.408248f,0.816497f,-0.408248f, 0.816497f,-0.408248f,-0.408248f, 0.408248f,-0.408248f,-0.816497f, -0.408248f,0.408248f,-0.816497f, 0.408248f,-0.816497f,-0.408248f, -0.816497f,0.408248f,-0.408248f, -0.816497f,-0.408248f,0.408248f, -0.408248f,-0.816497f,0.408248f, -1.000000f,0.000000f,0.000000f, 0.000000f,0.000000f,-1.000000f, 0.000000f,-1.000000f,0.000000f, -0.382683f,0.000000f,-0.923880f, -0.923880f,0.000000f,-0.382683f, -0.382683f,-0.923880f,0.000000f, -0.923880f,-0.382683f,0.000000f, 0.000000f,-0.382683f,-0.923880f, 0.000000f,-0.923880f,-0.382683f, -0.707107f,-0.707107f,0.000000f, -0.707107f,0.000000f,-0.707107f, 0.000000f,-0.707107f,-0.707107f, -0.816497f,-0.408248f,-0.408248f, -0.408248f,-0.408248f,-0.816497f, -0.408248f,-0.816497f,-0.408248f }; const Vec3 & GetSphereNormalSimple(const int i) { ASSERT( i >= 0 && i < c_numSphereNormalsSimple ); const float * pF = c_sphereVertsSimple + i*3; return *( (const Vec3 *)pF ); } END_CB
30.454054
83
0.741392
Svengali
e20fe308ba9db266d014632a95718afebac3e0a7
4,067
cpp
C++
game/client/tfo/c_achievement_manager.cpp
BerntA/tfo-code
afa3ea06a64cbbf7a9370b214ea5e80e69d9d7a1
[ "MIT" ]
13
2016-04-05T23:23:16.000Z
2022-03-20T11:06:04.000Z
game/client/tfo/c_achievement_manager.cpp
BerntA/tfo-code
afa3ea06a64cbbf7a9370b214ea5e80e69d9d7a1
[ "MIT" ]
null
null
null
game/client/tfo/c_achievement_manager.cpp
BerntA/tfo-code
afa3ea06a64cbbf7a9370b214ea5e80e69d9d7a1
[ "MIT" ]
4
2016-04-05T23:23:19.000Z
2021-05-16T05:09:46.000Z
//========= Copyright Bernt Andreas Eide, All rights reserved. ============// // // Purpose: Achievement handler & manager. // //=============================================================================// #include "cbase.h" #include "c_achievement_manager.h" #include "hud.h" #include "hud_macros.h" #include "hudelement.h" #include "hud_achievement.h" // Contains a list of available achievements. const char *GameAchievements[] = { "ACH_HEALTHKIT", "ACH_WEAPON_SPECIAL_1", "ACH_WEAPON_SPECIAL_2", "ACH_WEAPON_SPECIAL_3", "ACH_EASTER_SLENDER", "ACH_TOURISTS_FRIEND", "ACH_WEAPON_BASH", "ACH_DARKBOOK", "ACH_NPC_BURN", "ACH_TOURISTS_BETRAY", "ACH_VENGEANCE", "ACH_ENDGAME", }; CAchievementManager::CAchievementManager() : m_CallbackUserStatsReceived(this, &CAchievementManager::OnUserStatsReceived), m_CallbackAchievementStored(this, &CAchievementManager::OnAchievementStored) { } CAchievementManager::~CAchievementManager() { } // Check if we have all the available achievements. bool CAchievementManager::HasAllAchievements(void) { int iCount = 0; for (int i = 0; i < _ARRAYSIZE(GameAchievements); i++) { bool bAchieved = false; steamapicontext->SteamUserStats()->GetAchievement(GameAchievements[i], &bAchieved); if (bAchieved) iCount++; } return (iCount >= _ARRAYSIZE(GameAchievements)); } // Check if a certain achievement has been achieved by the user. bool CAchievementManager::HasAchievement(const char *szAch, int iID) { if (iID >= _ARRAYSIZE(GameAchievements)) return false; bool bAchieved = false; const char *szAchievement = szAch; if (!szAchievement) szAchievement = GameAchievements[iID]; steamapicontext->SteamUserStats()->GetAchievement(szAchievement, &bAchieved); return bAchieved; } // Set an achievement from 0 to 1 = set to achieved. YOU CAN'T SET THE ACHIEVEMENT PROGRESS HERE. // To set the achievement progress you must first add a stat and link it to the achievement in Steamworks, increase the stat to see the progress update of the achievement in Steam, etc... bool CAchievementManager::WriteToAchievement(const char *szAchievement) { if (!CanWriteToAchievement(szAchievement)) { DevMsg("Failed to write to an achievement!\n"); return false; } // Do the change. if (steamapicontext->SteamUserStats()->SetAchievement(szAchievement)) { // Store the change. if (!steamapicontext->SteamUserStats()->StoreStats()) DevMsg("Failed to store the achievement!\n"); steamapicontext->SteamUserStats()->RequestCurrentStats(); return true; } return false; } // Make sure that we can write to the achievements before we actually write so we don't crash the game. bool CAchievementManager::CanWriteToAchievement(const char *szAchievement) { // Make sure that we're connected. if (!engine->IsInGame()) return false; // Make sure that we will not write to any achievements if we have cheats enabled. ConVar *varCheats = cvar->FindVar("sv_cheats"); if (varCheats) { if (varCheats->GetBool()) return false; } // Make sure our interface is running. if (!steamapicontext) return false; // Make sure that we're logged in. if (!steamapicontext->SteamUserStats()) return false; if (!steamapicontext->SteamUser()) return false; if (!steamapicontext->SteamUser()->BLoggedOn()) return false; bool bFound = false; for (int i = 0; i < _ARRAYSIZE(GameAchievements); i++) { if (!strcmp(GameAchievements[i], szAchievement)) { bFound = true; break; } } if (!bFound) return false; bool bAchieved = false; steamapicontext->SteamUserStats()->GetAchievement(szAchievement, &bAchieved); return !bAchieved; } void CAchievementManager::OnUserStatsReceived(UserStatsReceived_t *pCallback) { DevMsg("Loaded Stats and Achievements!\nResults %i\n", (int)pCallback->m_eResult); } void CAchievementManager::OnAchievementStored(UserAchievementStored_t *pCallback) { if (pCallback->m_nCurProgress == pCallback->m_nMaxProgress) { CHudAchievement *pHudHR = GET_HUDELEMENT(CHudAchievement); if (pHudHR) { pHudHR->ShowAchievement(); } } }
25.578616
199
0.722154
BerntA
e215335aafb37b69d3133fb403be1b810677aaea
3,755
cpp
C++
macos/wrapper.cpp
lulitao1997/nixcrpkgs
1f3045ed82dc31c35cff5fe8c1d9cdeeaee75691
[ "MIT" ]
105
2017-07-16T18:59:15.000Z
2022-03-25T19:26:25.000Z
macos/wrapper.cpp
lulitao1997/nixcrpkgs
1f3045ed82dc31c35cff5fe8c1d9cdeeaee75691
[ "MIT" ]
18
2017-01-21T03:25:51.000Z
2020-09-13T22:51:52.000Z
macos/wrapper.cpp
lulitao1997/nixcrpkgs
1f3045ed82dc31c35cff5fe8c1d9cdeeaee75691
[ "MIT" ]
10
2018-12-06T03:20:33.000Z
2022-03-25T13:48:27.000Z
#include <vector> #include <string> #include <iostream> #include <cstring> #include <cstdlib> #include <unistd.h> int do_exec(const std::string & compiler_name, const std::vector<std::string> & args) { char ** exec_args = new char *[args.size() + 1]; size_t i = 0; for (const std::string & arg : args) { exec_args[i++] = (char *)arg.c_str(); } exec_args[i] = nullptr; execvp(compiler_name.c_str(), exec_args); int result = errno; std::cerr << "execvp failed: " << compiler_name << ": " << strerror(result) << std::endl; return 1; } int compiler_main(int argc, char ** argv, const std::string & compiler_name) { std::vector<std::string> args; args.push_back(compiler_name); args.push_back("-target"); args.push_back(WRAPPER_HOST); args.push_back("-mmacosx-version-min=" WRAPPER_OS_VERSION_MIN); // The ld64 linker will just assume sdk_version is the same as // macosx-version-min if we don't supply it. That probably will not // do any harm. // args.push_back("-Wl,-sdk_version," WRAPPER_SDK_VERSION); // Suppress warnings about the -Wl arguments not being used when we're just // compiling and not linking. args.push_back("-Wno-unused-command-line-argument"); args.push_back("--sysroot"); args.push_back(WRAPPER_SDK_PATH); // Causes clang to pass -demangle, -no_deduplicate, and other // options that could be useful. Version 274.2 is the version number used here: // https://github.com/tpoechtrager/osxcross/blob/474f359/build.sh#L140 if (WRAPPER_LINKER_VERSION[0]) { args.push_back("-mlinker-version=" WRAPPER_LINKER_VERSION); } if (compiler_name == "clang++") { args.push_back("-stdlib=libc++"); args.push_back("-cxx-isystem"); args.push_back(WRAPPER_SDK_PATH "/usr/include/c++"); } for (int i = 1; i < argc; ++i) { args.push_back(argv[i]); } return do_exec(compiler_name, args); } int c_compiler_main(int argc, char ** argv) { return compiler_main(argc, argv, "clang"); } int cxx_compiler_main(int argc, char ** argv) { return compiler_main(argc, argv, "clang++"); } int wrapper_main(int argc, char ** argv) { std::cout << "host: " WRAPPER_HOST "\n" "path: " WRAPPER_PATH "\n" "sdk_path: " WRAPPER_SDK_PATH "\n"; return 0; } struct { const char * name; int (*main_func)(int argc, char ** argv); } prgms[] = { { WRAPPER_HOST "-gcc", c_compiler_main }, { WRAPPER_HOST "-cc", c_compiler_main }, { WRAPPER_HOST "-clang", c_compiler_main }, { WRAPPER_HOST "-g++", cxx_compiler_main }, { WRAPPER_HOST "-c++", cxx_compiler_main }, { WRAPPER_HOST "-clang++", cxx_compiler_main }, { WRAPPER_HOST "-wrapper", wrapper_main }, { nullptr, nullptr }, }; const char * get_program_name(const char * path) { const char * p = strrchr(path, '/'); if (p) { path = p + 1; } return path; } int main(int argc, char ** argv) { // We only want this wrapper and the compiler it invokes to access a certain // set of tools that are determined at build time. Ignore whatever is on the // user's path and use the path specified by our Nix expression instead. int result = setenv("PATH", WRAPPER_PATH, 1); if (result) { std::cerr << "wrapper failed to set PATH" << std::endl; return 1; } result = setenv("COMPILER_RT_PATH", WRAPPER_COMPILER_RT_PATH, 1); if (result) { std::cerr << "wrapper failed to set COMPILER_RT_PATH" << std::endl; return 1; } std::string program_name = get_program_name(argv[0]); for (auto * p = prgms; p->name; p++) { if (program_name == p->name) { return p->main_func(argc, argv); } } std::cerr << "compiler wrapper invoked with unknown program name: " << argv[0] << std::endl; return 1; }
25.544218
82
0.65273
lulitao1997
e21817e65b3c0693a268a50ca2b498418f37cadc
2,520
cpp
C++
examples/geodesic.cpp
mcpca/fsm
df4081fa0e595284ddbb1f30f20c5fb2063aa41f
[ "MIT" ]
2
2021-06-18T14:07:29.000Z
2022-01-14T11:35:29.000Z
examples/geodesic.cpp
mcpca/fsm
df4081fa0e595284ddbb1f30f20c5fb2063aa41f
[ "MIT" ]
null
null
null
examples/geodesic.cpp
mcpca/fsm
df4081fa0e595284ddbb1f30f20c5fb2063aa41f
[ "MIT" ]
2
2021-08-31T07:50:47.000Z
2021-09-03T17:30:14.000Z
#include <cmath> #include <iostream> #include <numeric> #include "marlin/solver.hpp" #include "hdf5.hpp" #include "timer.hpp" int main() { #if MARLIN_N_DIMS == 2 constexpr char const* filename = "../data/geodesic.h5"; constexpr std::array<std::pair<marlin::scalar_t, marlin::scalar_t>, marlin::dim> vertices = { { { -0.5, 0.5 }, { -0.5, 0.5 } } }; constexpr std::array<int, marlin::dim> npts = { { 201, 201 } }; auto pt = [&vertices, &npts](auto x) { std::array<marlin::scalar_t, marlin::dim> pt; for(auto i = 0ul; i < marlin::dim; ++i) { pt[i] = vertices[i].first + x[i] * (vertices[i].second - vertices[i].first) / (npts[i] - 1); } return pt; }; auto grad = [](auto const& x) { return marlin::vector_t{ static_cast<marlin::scalar_t>(0.9 * 2 * M_PI * std::cos(2 * M_PI * x[0]) * std::sin(2 * M_PI * x[1])), static_cast<marlin::scalar_t>(0.9 * 2 * M_PI * std::sin(2 * M_PI * x[0]) * std::cos(2 * M_PI * x[1])) }; }; auto speed = [&grad](auto const& x, auto omega) -> marlin::scalar_t { auto g = grad(x); auto s = std::sin(omega); auto ss = std::sin(2.0 * omega); auto c = std::cos(omega); auto num = 1 + g[0] * g[0] * s * s + g[1] * g[1] * c * c - g[0] * g[1] * ss; auto den = 1 + g[0] * g[0] + g[1] * g[1]; return std::sqrt(num / den); }; auto h = [&pt, &speed](auto x, auto const& p) -> marlin::scalar_t { auto z = pt(x); auto norm = std::sqrt( std::inner_product(std::begin(p), std::end(p), std::begin(p), 0.0)); auto omega = std::atan2(p[1], p[0]); return norm * speed(z, omega); }; auto viscosity = [](auto) { return marlin::vector_t{ 1.0, 1.0 }; }; auto ds = h5io::read(filename, "cost_function"); marlin::solver::params_t params; params.tolerance = 1.0e-4; params.maxval = 2.0; marlin::solver::solver_t s(std::move(ds.data), ds.size, vertices, params); timer::timer_t t; s.solve(h, viscosity); std::cout << "Took " << t.get_elapsed_sec<double>() << " seconds." << std::endl; h5io::write(filename, "value_function", s.steal(), ds.size); #endif return 0; }
29.647059
80
0.476984
mcpca
e21a53f7247e971e87cee55a7f45bffde6146402
290
cpp
C++
c++11/understanding-cpp11/chapter4/4-3-2.cpp
cuiwm/choe_lib
6992c7bf551e7d6d633399b21b028e6873d5e6e8
[ "MIT" ]
null
null
null
c++11/understanding-cpp11/chapter4/4-3-2.cpp
cuiwm/choe_lib
6992c7bf551e7d6d633399b21b028e6873d5e6e8
[ "MIT" ]
null
null
null
c++11/understanding-cpp11/chapter4/4-3-2.cpp
cuiwm/choe_lib
6992c7bf551e7d6d633399b21b028e6873d5e6e8
[ "MIT" ]
null
null
null
#include <typeinfo> #include <iostream> using namespace std; int main() { int i; decltype(i) j = 0; cout << typeid(j).name() << endl; // 打印出"i", g++表示integer float a; double b; decltype(a + b) c; cout << typeid(c).name() << endl; // 打印出"d", g++表示double }
19.333333
63
0.544828
cuiwm
e21fc60bc3e5611ff5b9d7606c686b5601eeb85e
2,877
cc
C++
lib/asm.cc
kibergus/photon_charmer
13d35da8de6a8a8739aea9a400265ba74e7d279a
[ "Apache-2.0" ]
null
null
null
lib/asm.cc
kibergus/photon_charmer
13d35da8de6a8a8739aea9a400265ba74e7d279a
[ "Apache-2.0" ]
null
null
null
lib/asm.cc
kibergus/photon_charmer
13d35da8de6a8a8739aea9a400265ba74e7d279a
[ "Apache-2.0" ]
null
null
null
#include "asm.h" #include "hal/pwm.h" #include "hal/ws2812/ws2812.h" namespace { constexpr int COMMAND_SIZE = 9; constexpr int BUFFER_SIZE = 250; uint8_t buffer[BUFFER_SIZE][COMMAND_SIZE]; // Instruction pointer. volatile int ip = 0; int read_pointer = 0; THD_WORKING_AREA(asmThreadArea, 256); __attribute__((noreturn)) THD_FUNCTION(asmThread, arg) { (void)arg; chRegSetThreadName("asm"); // Timer has a 16 bit resolution and we need more. int elapsed = 0; systime_t last_timer_value = chVTGetSystemTimeX(); for (;;) { uint8_t* command = buffer[ip]; uint8_t opcode = command[0]; if (opcode == 0) { chThdExit(0); } if (opcode == 1) { int delay = (int(command[1]) << 24) | (int(command[2]) << 16) | (int(command[3]) << 8) | int(command[4]); systime_t next_timer_value = chVTGetSystemTimeX(); elapsed += chTimeDiffX(last_timer_value, next_timer_value); last_timer_value = next_timer_value; // 2 is a magic constant. For some reason it is just 2 times faster than should. if (delay > int(TIME_I2MS(elapsed)) * 2) { chThdSleepMilliseconds(delay - elapsed); } } if (opcode == 2 || opcode == 3) { // PWM command. for (int offset = 0; offset < 4; ++offset) { int channel = offset + (opcode == 2 ? 0 : 4); int duty_cycle = int(command[offset * 2 + 1]) << 8 | command[offset * 2 + 2]; setPwm(channel, duty_cycle); } } if (opcode >= 4 || opcode <= 8) { // RGB command. for (int offset = 0; offset < 1; ++offset) { int channel = offset + (opcode - 4) * 2; ws2812_write_led(channel, command[offset * 3 + 1], command[offset * 3 + 2], command[offset * 3 + 3]); } } ip = (ip + 1) % BUFFER_SIZE; } } uint8_t decode_hex(uint8_t c) { if (c <= '9') { return c - '0'; } else { return c - 'a' + 10; } } void read_command(BaseSequentialStream *chp) { uint8_t hex_buffer[COMMAND_SIZE * 2]; for (int i = 0; i < COMMAND_SIZE * 2; ++i) { hex_buffer[i] = streamGet(chp); } for (int i = 0; i < COMMAND_SIZE; ++i) { buffer[read_pointer][i] = decode_hex(hex_buffer[i * 2]) << 4 | decode_hex(hex_buffer[i * 2 + 1]); } } } // namespace void execute_lamp_asm(BaseSequentialStream* chp) { ip = 0; read_pointer = 0; for (;;) { read_command(chp); if (buffer[read_pointer][0] == 0 || buffer[read_pointer][0] == 1) { break; } read_pointer = (read_pointer + 1) % BUFFER_SIZE; } chThdCreateStatic(asmThreadArea, sizeof(asmThreadArea), NORMALPRIO, asmThread, NULL); for (;;) { while (read_pointer == ip) { chThdSleepMilliseconds(1); } read_command(chp); if (buffer[read_pointer][0] == 0) { return; } read_pointer = (read_pointer + 1) % BUFFER_SIZE; } }
25.6875
109
0.587417
kibergus
e220a9eb6309ade06701242c5d9db5b2f37a1921
11,421
cpp
C++
CaWE/MapEditor/ToolNewBrush.cpp
dns/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
3
2020-04-11T13:00:31.000Z
2020-12-07T03:19:10.000Z
CaWE/MapEditor/ToolNewBrush.cpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
null
null
null
CaWE/MapEditor/ToolNewBrush.cpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
1
2020-04-11T13:00:04.000Z
2020-04-11T13:00:04.000Z
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ #include "ToolNewBrush.hpp" #include "CompMapEntity.hpp" #include "ChildFrame.hpp" #include "ChildFrameViewWin2D.hpp" #include "ChildFrameViewWin3D.hpp" #include "Group.hpp" #include "MapBrush.hpp" #include "MapDocument.hpp" #include "Renderer2D.hpp" #include "ToolManager.hpp" #include "ToolOptionsBars.hpp" #include "DialogCreateArch.hpp" #include "../CursorMan.hpp" #include "../CommandHistory.hpp" #include "../GameConfig.hpp" #include "Commands/AddPrim.hpp" #include "Commands/Group_Assign.hpp" #include "Commands/Group_New.hpp" #include "wx/wx.h" /*** Begin of TypeSys related definitions for this class. ***/ void* ToolNewBrushT::CreateInstance(const cf::TypeSys::CreateParamsT& Params) { const ToolCreateParamsT* TCPs=static_cast<const ToolCreateParamsT*>(&Params); return new ToolNewBrushT(TCPs->MapDoc, TCPs->ToolMan, TCPs->ParentOptionsBar); } const cf::TypeSys::TypeInfoT ToolNewBrushT::TypeInfo(GetToolTIM(), "ToolNewBrushT", "ToolT", ToolNewBrushT::CreateInstance, NULL); /*** End of TypeSys related definitions for this class. ***/ ToolNewBrushT::ToolNewBrushT(MapDocumentT& MapDoc, ToolManagerT& ToolMan, wxWindow* ParentOptionsBar) : ToolT(MapDoc, ToolMan), m_NewBrush(NULL), m_NewBrushType(0), m_DragBegin(), m_DragCurrent(), m_OptionsBar(new OptionsBar_NewBrushToolT(ParentOptionsBar)) { // TODO: OnActivate: Set Status bar: Click and drag in a 2D view in order to create a new brush. } ToolNewBrushT::~ToolNewBrushT() { delete m_NewBrush; m_NewBrush=NULL; } wxWindow* ToolNewBrushT::GetOptionsBar() { // Cannot define this method inline in the header file, because there the compiler // does not yet know that the type of m_OptionsBar is in fact related to wxWindow. return m_OptionsBar; } bool ToolNewBrushT::OnKeyDown2D(ViewWindow2DT& ViewWindow, wxKeyEvent& KE) { return OnKeyDown(ViewWindow, KE); } bool ToolNewBrushT::OnLMouseDown2D(ViewWindow2DT& ViewWindow, wxMouseEvent& ME) { const int ThirdAxis=ViewWindow.GetAxesInfo().ThirdAxis; const Vector3fT WorldPos =m_MapDoc.SnapToGrid(ViewWindow.WindowToWorld(ME.GetPosition(), 0.0f), ME.AltDown(), -1 /*Snap all axes.*/); // ViewWindow.SetCursor(CursorMan->GetCursor(CursorManT::NEW_BRUSH_TOOL)); // Not really neeeded - cursor is already set in OnMouseMove2D(). ViewWindow.CaptureMouse(); // (Try to) determine good initial points for the drag rectangle. // Especially the initial heights are problematic - can we further improve the current strategy? m_DragBegin =WorldPos; m_DragCurrent=WorldPos; m_DragBegin [ThirdAxis]=m_MapDoc.GetMostRecentSelBB().Min[ThirdAxis]; m_DragCurrent[ThirdAxis]=m_MapDoc.GetMostRecentSelBB().Max[ThirdAxis]; if (fabs(m_DragBegin[ThirdAxis]-m_DragCurrent[ThirdAxis])<8.0f) m_DragCurrent[ThirdAxis]=m_DragBegin[ThirdAxis]+8.0f; // Update the new brush instance according to the current drag rectangle. UpdateNewBrush(ViewWindow); m_ToolMan.UpdateAllObservers(this, UPDATE_NOW); return true; } bool ToolNewBrushT::OnLMouseUp2D(ViewWindow2DT& ViewWindow, wxMouseEvent& ME) { if (!ViewWindow.HasCapture()) return false; // Drag started outside of ViewWindow. ViewWindow.ReleaseMouse(); if (!m_NewBrush) return true; // Something went wrong - user has to try again. if (m_NewBrushType!=5) { // It's a normal brush, not an arch. const char* CmdDescr=""; // Describes the command that is submitted to the command history for actually adding m_NewBrush to the world. switch (m_NewBrushType) { case 0: CmdDescr="new block brush"; break; case 1: CmdDescr="new wedge brush"; break; case 2: CmdDescr="new cylinder brush"; break; case 3: CmdDescr="new pyramid brush"; break; case 4: CmdDescr="new sphere brush"; break; } m_MapDoc.CompatSubmitCommand(new CommandAddPrimT(m_MapDoc, m_NewBrush, m_MapDoc.GetRootMapEntity(), CmdDescr)); m_NewBrush=NULL; // Instance is now "owned" by the command. } else { // It's an arch. ArchDialogT ArchDlg(m_NewBrush->GetBB(), ViewWindow.GetAxesInfo()); // We *must* delete the brush before ArchDlg is shown - event processing continues (e.g. incoming mouse move events)! delete m_NewBrush; m_NewBrush = NULL; if (ArchDlg.ShowModal() == wxID_OK) { const ArrayT<MapPrimitiveT*> ArchSegments = ArchDlg.GetArch(m_MapDoc.GetGameConfig()->GetMatMan().GetDefaultMaterial()); ArrayT<CommandT*> SubCommands; // 1. Add the arch segments to the world. CommandAddPrimT* CmdAddSegments = new CommandAddPrimT(m_MapDoc, ArchSegments, m_MapDoc.GetRootMapEntity(), "new arch segments"); CmdAddSegments->Do(); SubCommands.PushBack(CmdAddSegments); // 2. Create a new group. CommandNewGroupT* CmdNewGroup = new CommandNewGroupT(m_MapDoc, wxString::Format("arch (%lu side%s)", ArchSegments.Size(), ArchSegments.Size()==1 ? "" : "s")); GroupT* NewGroup = CmdNewGroup->GetGroup(); NewGroup->SelectAsGroup = true; CmdNewGroup->Do(); SubCommands.PushBack(CmdNewGroup); // 3. Put the ArchSegments into the new group. ArrayT<MapElementT*> ArchSegmentsAsElems; for (unsigned long SegNr = 0; SegNr < ArchSegments.Size(); SegNr++) ArchSegmentsAsElems.PushBack(ArchSegments[SegNr]); CommandAssignGroupT* CmdAssign = new CommandAssignGroupT(m_MapDoc, ArchSegmentsAsElems, NewGroup); CmdAssign->Do(); SubCommands.PushBack(CmdAssign); // 4. Submit the composite macro command. m_MapDoc.CompatSubmitCommand(new CommandMacroT(SubCommands, "new arch")); } } m_ToolMan.UpdateAllObservers(this, UPDATE_SOON); return true; } bool ToolNewBrushT::OnMouseMove2D(ViewWindow2DT& ViewWindow, wxMouseEvent& ME) { const int HorzAxis=ViewWindow.GetAxesInfo().HorzAxis; const int VertAxis=ViewWindow.GetAxesInfo().VertAxis; ViewWindow.SetCursor(CursorMan->GetCursor(CursorManT::NEW_BRUSH_TOOL)); if (!m_NewBrush) return true; const Vector3fT WorldPos=m_MapDoc.SnapToGrid(ViewWindow.WindowToWorld(ME.GetPosition(), 0.0f), ME.AltDown(), -1 /*Snap all axes.*/); const Vector3fT OldPos =m_DragCurrent; // Update the drag rectangle. m_DragCurrent[HorzAxis]=WorldPos[HorzAxis]; m_DragCurrent[VertAxis]=WorldPos[VertAxis]; if (m_DragCurrent==OldPos) return true; // Update the new brush instance according to the current drag rectangle. UpdateNewBrush(ViewWindow); m_ToolMan.UpdateAllObservers(this, UPDATE_NOW); return true; } bool ToolNewBrushT::OnKeyDown3D(ViewWindow3DT& ViewWindow, wxKeyEvent& KE) { return OnKeyDown(ViewWindow, KE); } bool ToolNewBrushT::OnRMouseClick3D(ViewWindow3DT& ViewWindow, wxMouseEvent& ME) { if (ME.ShiftDown() && ME.ControlDown()) { // Create a brush in the shape of the current view frustum. // This has little practical relevance for the user, it is just a tool for debugging the view frustum computations. // It is in the RMB *up* instead of the RMB *down* handler in order to not have the context menu shown. ArrayT<Plane3fT> Planes; Planes.PushBackEmpty(6); ViewWindow.GetViewFrustum(&Planes[0]); MapBrushT* NewBrush=new MapBrushT(Planes, m_MapDoc.GetGameConfig()->GetMatMan().GetDefaultMaterial(), true); m_MapDoc.CompatSubmitCommand(new CommandAddPrimT(m_MapDoc, NewBrush, m_MapDoc.GetRootMapEntity(), "new view frustum brush")); return true; } return false; } bool ToolNewBrushT::OnMouseMove3D(ViewWindow3DT& ViewWindow, wxMouseEvent& ME) { ViewWindow.SetCursor(CursorMan->GetCursor(CursorManT::NEW_BRUSH_TOOL)); return true; } void ToolNewBrushT::RenderTool2D(Renderer2DT& Renderer) const { if (!IsActiveTool()) return; if (!m_NewBrush) return; const BoundingBox3fT BB =m_NewBrush->GetBB(); const ViewWindow2DT& ViewWin=Renderer.GetViewWin2D(); Renderer.SetLineColor(wxColor(128, 128, 0)); // I want "dirty yellow". Renderer.Rectangle(wxRect(ViewWin.WorldToTool(BB.Min), ViewWin.WorldToTool(BB.Max)), false); const bool WasSelected=m_NewBrush->IsSelected(); m_NewBrush->SetSelected(true); m_NewBrush->Render2D(Renderer); m_NewBrush->SetSelected(WasSelected); Renderer.DrawBoxDims(BB, wxRIGHT | wxTOP); } void ToolNewBrushT::RenderTool3D(Renderer3DT& Renderer) const { if (!IsActiveTool()) return; if (!m_NewBrush) return; for (unsigned long FaceNr=0; FaceNr<m_NewBrush->GetFaces().Size(); FaceNr++) m_NewBrush->GetFaces()[FaceNr].Render3DBasic(Renderer.GetRMatWireframe_OffsetZ(), *wxRED, 255); } bool ToolNewBrushT::OnKeyDown(ViewWindowT& ViewWindow, wxKeyEvent& KE) { switch (KE.GetKeyCode()) { case WXK_ESCAPE: if (m_NewBrush) { // Abort the dragging (while the mouse button is still down). delete m_NewBrush; m_NewBrush=NULL; } else { m_ToolMan.SetActiveTool(GetToolTIM().FindTypeInfoByName("ToolSelectionT")); } m_ToolMan.UpdateAllObservers(this, UPDATE_SOON); return true; } return false; } void ToolNewBrushT::UpdateNewBrush(ViewWindow2DT& ViewWindow) { const int HorzAxis=ViewWindow.GetAxesInfo().HorzAxis; const int VertAxis=ViewWindow.GetAxesInfo().VertAxis; Vector3fT Drag=m_DragCurrent-m_DragBegin; // If they have not yet made a choice, make one for them now. if (Drag[HorzAxis]==0.0f) Drag[HorzAxis]=ViewWindow.GetAxesInfo().MirrorHorz ? -1.0f : 1.0f; if (Drag[VertAxis]==0.0f) Drag[VertAxis]=ViewWindow.GetAxesInfo().MirrorVert ? -1.0f : 1.0f; // Make sure that the drag is large enough in the chosen direction. if (fabs(Drag.x)<8.0f) Drag.x=(Drag.x<0.0f) ? -8.0f : 8.0f; if (fabs(Drag.y)<8.0f) Drag.y=(Drag.y<0.0f) ? -8.0f : 8.0f; if (fabs(Drag.z)<8.0f) Drag.z=(Drag.z<0.0f) ? -8.0f : 8.0f; EditorMaterialI* Material =m_MapDoc.GetGameConfig()->GetMatMan().GetDefaultMaterial(); const BoundingBox3fT BrushBB =BoundingBox3fT(m_DragBegin, m_DragBegin+Drag); const unsigned long NrOfFaces=m_OptionsBar->GetNrOfFaces(); delete m_NewBrush; m_NewBrush=NULL; m_NewBrushType=m_OptionsBar->GetBrushIndex(); switch (m_NewBrushType) { case 0: m_NewBrush=MapBrushT::CreateBlock (BrushBB, Material); break; case 1: m_NewBrush=MapBrushT::CreateWedge (BrushBB, Material); break; case 2: m_NewBrush=MapBrushT::CreateCylinder(BrushBB, NrOfFaces, Material); break; case 3: m_NewBrush=MapBrushT::CreatePyramid (BrushBB, NrOfFaces, Material); break; case 4: m_NewBrush=MapBrushT::CreateSphere (BrushBB, NrOfFaces, Material); break; default: m_NewBrush=MapBrushT::CreateBlock (BrushBB, Material); break; } }
34.820122
170
0.686105
dns
e22516e826f334f0788e00b1520ed9cfe96376e7
6,923
cpp
C++
modules/ti.Desktop/win32/win32_desktop.cpp
mital/titanium
5e02a4406686d627f6828fd5cc18dc1a75d0714f
[ "Apache-2.0" ]
4
2016-01-02T17:14:06.000Z
2016-05-09T08:57:33.000Z
modules/ti.Desktop/win32/win32_desktop.cpp
mital/titanium
5e02a4406686d627f6828fd5cc18dc1a75d0714f
[ "Apache-2.0" ]
null
null
null
modules/ti.Desktop/win32/win32_desktop.cpp
mital/titanium
5e02a4406686d627f6828fd5cc18dc1a75d0714f
[ "Apache-2.0" ]
null
null
null
/** * Appcelerator Titanium - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved. */ #include "win32_desktop.h" #include <windows.h> #include <commdlg.h> #include <shellapi.h> #include <shlobj.h> #include <string> namespace ti { Win32Desktop::Win32Desktop() { } Win32Desktop::~Win32Desktop() { } bool Win32Desktop::OpenApplication(std::string &name) { // this can actually open applications or documents (wordpad, notepad, file-test.txt, etc.) char *dir = NULL; if (FileUtils::IsFile(name)) { // start with the current working directory as the directory of the program dir = (char*)FileUtils::GetDirectory(name).c_str(); } long response = (long)ShellExecuteA(NULL, "open", name.c_str(), NULL, dir, SW_SHOWNORMAL); return (response > 32); } bool Win32Desktop::OpenURL(std::string &url) { long response = (long)ShellExecuteA(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL); return (response > 32); } void Win32Desktop::TakeScreenshot(std::string &screenshotFile) { //ensure filename ends in bmp screenshotFile.append(".bmp"); HWND desktop = GetDesktopWindow(); RECT desktopRect; GetWindowRect(desktop, &desktopRect); int x = 0; int y = 0; int width = desktopRect.right; int height = desktopRect.bottom; // get a DC compat. w/ the screen HDC hDc = CreateCompatibleDC(0); // make a bmp in memory to store the capture in HBITMAP hBmp = CreateCompatibleBitmap(GetDC(0), width, height); // join em up SelectObject(hDc, hBmp); // copy from the screen to my bitmap BitBlt(hDc, 0, 0, width, height, GetDC(0), x, y, SRCCOPY); char tmpDir[MAX_PATH]; char tmpFile[MAX_PATH]; GetTempPathA(sizeof(tmpDir), tmpDir); GetTempFileNameA(tmpDir, "ti_", 0, tmpFile); bool saved = SaveBMPFile(tmpFile, hBmp, hDc, width, height); std::cout << "SCREEN SHOT file " << tmpFile << std::endl; if(saved) { CopyFileA(tmpFile, screenshotFile.c_str(), FALSE); } // free the bitmap memory DeleteObject(hBmp); } bool Win32Desktop::SaveBMPFile(const char *filename, HBITMAP bitmap, HDC bitmapDC, int width, int height) { bool Success = false; HDC SurfDC = NULL; // GDI-compatible device context for the surface HBITMAP OffscrBmp = NULL; // bitmap that is converted to a DIB HDC OffscrDC = NULL; // offscreen DC that we can select OffscrBmp into LPBITMAPINFO lpbi = NULL; // bitmap format info; used by GetDIBits LPVOID lpvBits = NULL; // pointer to bitmap bits array HANDLE BmpFile = INVALID_HANDLE_VALUE; // destination .bmp file BITMAPFILEHEADER bmfh; // .bmp file header // We need an HBITMAP to convert it to a DIB: if ((OffscrBmp = CreateCompatibleBitmap(bitmapDC, width, height)) == NULL) { return false; } // The bitmap is empty, so let's copy the contents of the surface to it. // For that we need to select it into a device context. We create one. if ((OffscrDC = CreateCompatibleDC(bitmapDC)) == NULL) { return false; } // Select OffscrBmp into OffscrDC: HBITMAP OldBmp = (HBITMAP)SelectObject(OffscrDC, OffscrBmp); // Now we can copy the contents of the surface to the offscreen bitmap: BitBlt(OffscrDC, 0, 0, width, height, bitmapDC, 0, 0, SRCCOPY); // GetDIBits requires format info about the bitmap. We can have GetDIBits // fill a structure with that info if we pass a NULL pointer for lpvBits: // Reserve memory for bitmap info (BITMAPINFOHEADER + largest possible // palette): if ((lpbi = (LPBITMAPINFO)(new char[sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD)])) == NULL) { return false; } ZeroMemory(&lpbi->bmiHeader, sizeof(BITMAPINFOHEADER)); lpbi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); // Get info but first de-select OffscrBmp because GetDIBits requires it: SelectObject(OffscrDC, OldBmp); if (!GetDIBits(OffscrDC, OffscrBmp, 0, height, NULL, lpbi, DIB_RGB_COLORS)) { return false; } // Reserve memory for bitmap bits: if ((lpvBits = new char[lpbi->bmiHeader.biSizeImage]) == NULL) { return false; } // Have GetDIBits convert OffscrBmp to a DIB (device-independent bitmap): if (!GetDIBits(OffscrDC, OffscrBmp, 0, height, lpvBits, lpbi, DIB_RGB_COLORS)) { return false; } // Create a file to save the DIB to: if ((BmpFile = ::CreateFileA(filename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,NULL)) == INVALID_HANDLE_VALUE) { return false; } DWORD Written; // number of bytes written by WriteFile // Write a file header to the file: bmfh.bfType = 19778; // 'BM' // bmfh.bfSize = ??? // we'll write that later bmfh.bfReserved1 = bmfh.bfReserved2 = 0; // bmfh.bfOffBits = ??? // we'll write that later if (!WriteFile(BmpFile, &bmfh, sizeof(bmfh), &Written, NULL)) { return false; } if (Written < sizeof(bmfh)) { return false; } // Write BITMAPINFOHEADER to the file: if (!WriteFile(BmpFile, &lpbi->bmiHeader, sizeof(BITMAPINFOHEADER), &Written, NULL)) { return false; } if (Written < sizeof(BITMAPINFOHEADER)) { return false; } // Calculate size of palette: int PalEntries; // 16-bit or 32-bit bitmaps require bit masks: if (lpbi->bmiHeader.biCompression == BI_BITFIELDS) { PalEntries = 3; } else { // bitmap is palettized? PalEntries = (lpbi->bmiHeader.biBitCount <= 8) ? // 2^biBitCount palette entries max.: (int)(1 << lpbi->bmiHeader.biBitCount) // bitmap is TrueColor -> no palette: : 0; } // If biClrUsed use only biClrUsed palette entries: if(lpbi->bmiHeader.biClrUsed) { PalEntries = lpbi->bmiHeader.biClrUsed; } // Write palette to the file: if(PalEntries){ if (!WriteFile(BmpFile, &lpbi->bmiColors, PalEntries * sizeof(RGBQUAD), &Written, NULL)) { return false; } if (Written < PalEntries * sizeof(RGBQUAD)) { return false; } } // The current position in the file (at the beginning of the bitmap bits) // will be saved to the BITMAPFILEHEADER: //bmfh.bfOffBits = GetFilePointer(BmpFile); bmfh.bfOffBits = SetFilePointer(BmpFile, 0, 0, FILE_CURRENT); // Write bitmap bits to the file: if (!WriteFile(BmpFile, lpvBits, lpbi->bmiHeader.biSizeImage, &Written, NULL)) { return false; } if (Written < lpbi->bmiHeader.biSizeImage) { return false; } // The current pos. in the file is the final file size and will be saved: //bmfh.bfSize = GetFilePointer(BmpFile); bmfh.bfSize = SetFilePointer(BmpFile, 0, 0, FILE_CURRENT); // We have all the info for the file header. Save the updated version: SetFilePointer(BmpFile, 0, 0, FILE_BEGIN); if (!WriteFile(BmpFile, &bmfh, sizeof(bmfh), &Written, NULL)) { return false; } if (Written < sizeof(bmfh)) { return false; } return true; } }
27.363636
147
0.680774
mital
e22826f308519fa30ed3979808c19e6562740ff4
6,511
cpp
C++
tests/benchmarks.cpp
jll63/yomm11
4d434ae548886faab5c16c98e1973dc8b6e368d4
[ "BSL-1.0" ]
108
2015-01-25T16:58:11.000Z
2021-09-23T06:47:07.000Z
tests/benchmarks.cpp
jll63/yomm11
4d434ae548886faab5c16c98e1973dc8b6e368d4
[ "BSL-1.0" ]
3
2015-06-07T17:40:27.000Z
2017-11-01T19:33:01.000Z
tests/benchmarks.cpp
jll63/yomm11
4d434ae548886faab5c16c98e1973dc8b6e368d4
[ "BSL-1.0" ]
19
2015-04-23T17:34:03.000Z
2019-06-28T09:18:45.000Z
// benchmarks.cpp // Copyright (c) 2013 Jean-Louis Leroy // 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) // chrt -f 99 ./benchmarks // 10000000 iterations, time in millisecs // virtual function, do_nothing : 75.50 // open method, intrusive, do_nothing : 100.56 // open method, foreign, do_nothing : 1397.75 // virtual function, do_something : 1541.11 // open method, intrusive, do_something : 1608.20 // open method, foreign, do_something : 2607.76 // virtual function, 2-dispatch, do_nothing : 250.75 // open method with 2 args, intrusive, do_nothing : 150.77 // open method with 2 args, foreign, do_nothing : 2832.26 // results obtained on my computer (ThinkPad x200s): // processor : 0 & 1 // vendor_id : GenuineIntel // cpu family : 6 // model : 23 // model name : Intel(R) Core(TM)2 Duo CPU L9400 @ 1.86GHz // stepping : 10 // microcode : 0xa0c // cpu MHz : 800.000 // cache size : 6144 KB // cpu cores : 2 // fpu : yes // fpu_exception: yes // cpuid level : 13 // wp : yes // bogomips : 3724.05 // clflush size : 64 #include <iostream> #include <iomanip> #include <chrono> #include "benchmarks.hpp" using namespace std; using namespace std::chrono; using yorel::multi_methods::virtual_; namespace intrusive { MULTI_METHOD(do_nothing, void, virtual_<object>&); BEGIN_SPECIALIZATION(do_nothing, void, object&) { } END_SPECIALIZATION; MULTI_METHOD(do_something, double, virtual_<object>&, double x, double a, double b, double c); BEGIN_SPECIALIZATION(do_something, double, object&, double x, double a, double b, double c) { return log(a * x * x + b * x + c); } END_SPECIALIZATION; MULTI_METHOD(do_nothing_2, void, virtual_<object>&, virtual_<object>&); BEGIN_SPECIALIZATION(do_nothing_2, void, object&, object&) { } END_SPECIALIZATION; } namespace vbase { MULTI_METHOD(do_nothing, void, virtual_<object>&); BEGIN_SPECIALIZATION(do_nothing, void, object&) { } END_SPECIALIZATION; MULTI_METHOD(do_something, double, virtual_<object>&, double x, double a, double b, double c); BEGIN_SPECIALIZATION(do_something, double, derived&, double x, double a, double b, double c) { return log(a * x * x + b * x + c); } END_SPECIALIZATION; MULTI_METHOD(do_nothing_2, void, virtual_<object>&, virtual_<object>&); BEGIN_SPECIALIZATION(do_nothing_2, void, object&, object&) { } END_SPECIALIZATION; } namespace foreign { struct object { virtual ~object() { } }; MM_FOREIGN_CLASS(object); MULTI_METHOD(do_nothing, void, virtual_<object>&); BEGIN_SPECIALIZATION(do_nothing, void, object&) { } END_SPECIALIZATION; MULTI_METHOD(do_nothing_2, void, virtual_<object>&, virtual_<object>&); BEGIN_SPECIALIZATION(do_nothing_2, void, object&, object&) { } END_SPECIALIZATION; MULTI_METHOD(do_something, double, virtual_<object>&, double x, double a, double b, double c); BEGIN_SPECIALIZATION(do_something, double, object&, double x, double a, double b, double c) { return log(a * x * x + b * x + c); } END_SPECIALIZATION; } using time_type = decltype(high_resolution_clock::now()); void post(const string& description, time_type start, time_type end) { cout << setw(50) << left << description << ": " << setw(8) << fixed << right << setprecision(2) << duration<double, milli>(end - start).count() << endl; } struct benchmark { benchmark(const string& label) : label(label), start(high_resolution_clock::now()) { } ~benchmark() { auto end = high_resolution_clock::now(); cout << setw(50) << left << label << ": " << setw(8) << fixed << right << setprecision(2) << duration<double, milli>(end - start).count() << endl; } const string label; decltype(high_resolution_clock::now()) start; }; int main() { yorel::multi_methods::initialize(); const int repeats = 10 * 1000 * 1000; { auto pf = new foreign::object; auto pi = intrusive::object::make(); cout << repeats << " iterations, time in millisecs\n"; { benchmark b("virtual function, do_nothing"); for (int i = 0; i < repeats; i++) pi->do_nothing(); } { benchmark b("open method, intrusive, do_nothing"); for (int i = 0; i < repeats; i++) intrusive::do_nothing(*pi); } { benchmark b("open method, foreign, do_nothing"); for (int i = 0; i < repeats; i++) foreign::do_nothing(*pf); } { benchmark b("virtual function, do_something"); for (int i = 0; i < repeats; i++) pi->do_something(1, 2, 3, 4); } { benchmark b("open method, intrusive, do_something"); for (int i = 0; i < repeats; i++) intrusive::do_something(*pi, 1, 2, 3, 4); } { benchmark b("open method, foreign, do_something"); for (int i = 0; i < repeats; i++) foreign::do_something(*pf, 1, 2, 3, 4); } // double dispatch { benchmark b("virtual function, 2-dispatch, do_nothing"); for (int i = 0; i < repeats; i++) pi->dd1_do_nothing(pi); } { benchmark b("open method with 2 args, intrusive, do_nothing"); for (int i = 0; i < repeats; i++) intrusive::do_nothing_2(*pi, *pi); } { benchmark b("open method with 2 args, foreign, do_nothing"); for (int i = 0; i < repeats; i++) foreign::do_nothing_2(*pf, *pf); } } // virtual inheritance { auto pi = vbase::object::make(); { benchmark b("virtual function, vbase, do_nothing"); for (int i = 0; i < repeats; i++) pi->do_nothing(); } { benchmark b("open method, vbase, do_nothing"); for (int i = 0; i < repeats; i++) vbase::do_nothing(*pi); } { benchmark b("virtual function, vbase, do_something"); for (int i = 0; i < repeats; i++) pi->do_something(1, 2, 3, 4); } { benchmark b("open method, vbase, do_something"); for (int i = 0; i < repeats; i++) vbase::do_something(*pi, 1, 2, 3, 4); } // double dispatch { benchmark b("virtual function, 2-dispatch, vbase, do_nothing"); for (int i = 0; i < repeats; i++) pi->dd1_do_nothing(pi); } { benchmark b("open method with 2 args, vbase, do_nothing"); for (int i = 0; i < repeats; i++) vbase::do_nothing_2(*pi, *pi); } } return 0; }
26.57551
154
0.620028
jll63
e22d3e98b006dad29d25a1241bf1c687a69d8eed
1,981
cpp
C++
libs/GameInput/RawController.cpp
max-delta/retrofit-public
5447fd6399fd74ffbb75494c103940751000db12
[ "X11" ]
3
2019-10-27T22:32:44.000Z
2020-05-21T04:00:46.000Z
libs/GameInput/RawController.cpp
max-delta/retrofit-public
5447fd6399fd74ffbb75494c103940751000db12
[ "X11" ]
null
null
null
libs/GameInput/RawController.cpp
max-delta/retrofit-public
5447fd6399fd74ffbb75494c103940751000db12
[ "X11" ]
null
null
null
#include "stdafx.h" #include "RawController.h" #include "rftl/limits" namespace RF::input { /////////////////////////////////////////////////////////////////////////////// void RawController::GetRawCommandStream( rftl::virtual_iterator<RawCommand>& parser ) const { return GetRawCommandStream( parser, rftl::numeric_limits<size_t>::max() ); } void RawController::GetRawCommandStream( rftl::virtual_iterator<RawCommand>& parser, time::CommonClock::time_point earliestTime, time::CommonClock::time_point latestTime ) const { auto const onElement = [&parser, &earliestTime, &latestTime]( RawCommand const& element ) -> void { if( element.mTime >= earliestTime && element.mTime <= latestTime ) { parser( element ); } }; rftl::virtual_callable_iterator<RawCommand, decltype( onElement )> filter( onElement ); GetRawCommandStream( filter ); } void RawController::GetKnownSignals( rftl::virtual_iterator<RawSignalType>& iter ) const { return GetKnownSignals( iter, rftl::numeric_limits<size_t>::max() ); } void RawController::GetRawSignalStream( rftl::virtual_iterator<RawSignal>& sampler, RawSignalType type ) const { return GetRawSignalStream( sampler, rftl::numeric_limits<size_t>::max(), type ); } void RawController::GetRawSignalStream( rftl::virtual_iterator<RawSignal>& sampler, time::CommonClock::time_point earliestTime, time::CommonClock::time_point latestTime, RawSignalType type ) const { auto const onElement = [&sampler, &earliestTime, &latestTime]( RawSignal const& element ) -> void { if( element.mTime >= earliestTime && element.mTime <= latestTime ) { sampler( element ); } }; rftl::virtual_callable_iterator<RawSignal, decltype( onElement )> filter( onElement ); GetRawSignalStream( filter, type ); } void RawController::GetTextStream( rftl::u16string& text ) const { return GetTextStream( text, rftl::numeric_limits<size_t>::max() ); } /////////////////////////////////////////////////////////////////////////////// }
30.015152
196
0.687027
max-delta
e22d685fc12753cf2dd50dc5be118f36572b8bb6
2,479
cpp
C++
tests/test-3bit-shift-register.cpp
AnandSaminathan/verification-algorithms
5ba499b6147dc6002b6e7a1b67ffc1da6a2e1549
[ "BSL-1.0" ]
null
null
null
tests/test-3bit-shift-register.cpp
AnandSaminathan/verification-algorithms
5ba499b6147dc6002b6e7a1b67ffc1da6a2e1549
[ "BSL-1.0" ]
null
null
null
tests/test-3bit-shift-register.cpp
AnandSaminathan/verification-algorithms
5ba499b6147dc6002b6e7a1b67ffc1da6a2e1549
[ "BSL-1.0" ]
null
null
null
#include "verification-algorithms/k-induction/k-induction.hpp" #include "verification-algorithms/ltl-bmc/ltl-bmc.hpp" #include "verification-algorithms/ic3/ic3.hpp" #include "catch2/catch.hpp" using namespace verifier; SCENARIO("three bit shift register", "[3bit-shift-register]") { std::vector<Symbol> symbols; for(int i = 0; i <= 2; ++i) { std::string name = "x" + std::to_string(i); symbols.emplace_back(Symbol(bool_const, name)); } std::string I = "(x0 == false && x1 == false && x2 == false)"; std::string T = "(next_x0 == x1 && next_x1 == x2 && next_x2 == true)"; GIVEN("safety properties") { kInduction k(symbols, I, T); IC3 i(symbols, I, T); std::string P; WHEN("property is allFalse") { P = "!x0 && !x1 && !x2"; THEN("property does not hold"){ REQUIRE(k.check(P) == false); REQUIRE(i.check(P) == false); } } } GIVEN("ltl properties") { ltlBmc l(symbols, I, T); l.setBound(3); std::string P; WHEN("property is always allFalse") { P = "G(x0 == false && x1 == false && x2 == false)"; THEN("property does not hold") { REQUIRE(l.check(P) == false); } } WHEN("property is eventuallyAllTrue") { P = "F(x0 == true && x1 == true && x2 == true)"; THEN("property holds") { REQUIRE(l.check(P) == true); } } WHEN("property is correctNextStep") { P = "X(x0 == false && x1 == false && x2 == true)"; THEN("property holds") { REQUIRE(l.check(P) == true); } } WHEN("property is wrongNextStep") { P = "X!(x0 == false && x1 == false && x2 == true)"; THEN("property does not hold") { REQUIRE(l.check(P) == false); } } WHEN("property is untilAllTrueAtleastOneFalse") { P = "!(x0 && x1 && x2) U (x0 && x1 && x2)"; THEN("property holds") { REQUIRE(l.check(P) == true); } } WHEN("property is releaseAtleastOneFalseAllTrue") { P = "(x0 && x1 && x2) R !(x0 && x1 && x2)"; THEN("property does not hold") { REQUIRE(l.check(P) == false); } } WHEN("property is releaseX2TrueX1false") { P = "(x2 R !x1)"; THEN("property holds") { REQUIRE(l.check(P) == true); } } WHEN("property has undeclared variable") { P = "G(x1 || dummy)"; THEN("throws exception") { REQUIRE_THROWS_AS(l.check(P), std::invalid_argument); } } } }
25.556701
72
0.534086
AnandSaminathan
e22e9ae17eea1dfda75559fcaa2056af277d2c84
4,867
cpp
C++
XLib-v1.2.0/src/Base/Host/fUtil.cpp
mangrove-univr/Mangrove
3d95096c7adfad5eb27625b020c222487e91ab4e
[ "MIT" ]
1
2019-12-28T09:30:24.000Z
2019-12-28T09:30:24.000Z
XLib-v1.2.0/src/Base/Host/fUtil.cpp
mangrove-univr/Mangrove
3d95096c7adfad5eb27625b020c222487e91ab4e
[ "MIT" ]
1
2020-08-25T10:57:11.000Z
2020-08-25T10:57:11.000Z
XLib-v1.2.0/src/Base/Host/fUtil.cpp
mangrove-univr/Mangrove
3d95096c7adfad5eb27625b020c222487e91ab4e
[ "MIT" ]
null
null
null
/*------------------------------------------------------------------------------ Copyright © 2016 by Nicola Bombieri XLib is provided under the terms of The MIT License (MIT): Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------*/ /** * @author Federico Busato * Univerity of Verona, Dept. of Computer Science * federico.busato@univr.it */ #include <iostream> #include <fstream> #include <locale> #include <iomanip> #include <stdexcept> #include "Base/Host/fUtil.hpp" #include "Base/Host/numeric.hpp" #if __linux__ #include <unistd.h> #endif namespace xlib { /// @cond std::ostream& operator<<(std::ostream& os, const Color& mod) { return os << "\033[" << (int) mod << "m"; } std::ostream& operator<<(std::ostream& os, const Emph& mod) { return os << "\033[" << (int) mod << "m"; } ThousandSep::ThousandSep() : sep(NULL) { sep = new myseps; std::cout.imbue(std::locale(std::locale(), sep)); } ThousandSep::~ThousandSep() { std::cout.imbue(std::locale()); } void fixedFloat() { std::cout.setf(std::ios::fixed, std::ios::floatfield); } void scientificFloat() { std::cout.setf(std::ios::scientific, std::ios::floatfield); } /// @endcond //} //@StreamModifier #if __linux__ void memInfoHost(std::size_t Req) { unsigned pages = static_cast<unsigned>(::sysconf(_SC_PHYS_PAGES)); unsigned page_size = static_cast<unsigned>(::sysconf(_SC_PAGE_SIZE)); memInfoPrint(pages * page_size, pages * page_size - 100u * (1u << 20u), Req); } #endif void memInfoPrint(std::size_t total, std::size_t free, std::size_t Req) { std::cout << " Total Memory:\t" << (total >> 20) << " MB" << std::endl << " Free Memory:\t" << (free >> 20) << " MB" << std::endl << "Request memory:\t" << (Req >> 20) << " MB" << std::endl << " Request (%):\t" << ((Req >> 20) * 100) / (total >> 20) << " %" << std::endl << std::endl; if (Req > free) throw std::runtime_error(" ! Memory too low"); } bool isDigit(std::string str) { return str.find_first_not_of("0123456789") == std::string::npos; } #if (__linux__) #include <sys/resource.h> #include <errno.h> stackManagement::stackManagement() { if (getrlimit(RLIMIT_STACK, &ActualLimit)) __ERROR("stackManagement::stackManagement() -> getrlimit()"); } stackManagement::~stackManagement() { this->restore(); } void stackManagement::setLimit(std::size_t size) { struct rlimit RL; RL.rlim_cur = size; RL.rlim_max = size; if (setrlimit(RLIMIT_STACK, &RL)) { if (errno == EFAULT) std::cout << "EFAULT" << std::endl; else if (errno == EINVAL) std::cout << "EINVAL" << std::endl; else if (errno == EPERM) std::cout << "EPERM" << std::endl; else if (errno == ESRCH) std::cout << "ESRCH" << std::endl; else std::cout << "?" << std::endl; __ERROR("stackManagement::setLimit() -> setrlimit()"); } } void stackManagement::restore() { if (setrlimit(RLIMIT_STACK, &ActualLimit)) __ERROR("stackManagement::restore() -> setrlimit()"); } void stackManagement::checkUnlimited() { if (ActualLimit.rlim_cur != RLIM_INFINITY) __ERROR("stack size != unlimited (" << ActualLimit.rlim_cur << ")"); } #include <signal.h> // our new library namespace { void ctrlC_HandleFun(int) { #if defined(__NVCC__) cudaDeviceReset(); #endif std::exit(EXIT_FAILURE); } } void ctrlC_Handle() { signal(SIGINT, ctrlC_HandleFun); } #else stackManagement::~stackManagement() {} stackManagement::stackManagement() {} void stackManagement::setLimit(std::size_t size) {} void stackManagement::restore() {} void ctrlC_Handle() {} #endif } //@xlib
29.676829
81
0.623998
mangrove-univr
e237fdd7e578881d884861f464e9cf27de724716
1,843
cpp
C++
cap8/pp8_3.cpp
Titan201/Jumping-to-cpp
467ba4d197ac2f5225b43732c42aa3fb5262d557
[ "MIT" ]
null
null
null
cap8/pp8_3.cpp
Titan201/Jumping-to-cpp
467ba4d197ac2f5225b43732c42aa3fb5262d557
[ "MIT" ]
null
null
null
cap8/pp8_3.cpp
Titan201/Jumping-to-cpp
467ba4d197ac2f5225b43732c42aa3fb5262d557
[ "MIT" ]
null
null
null
#include <cstdlib> #include <ctime> #include <iostream> using namespace std; int randRange (int low, int high) { return rand() % (high - low + 1) + low; } int GuessResponse(int response, int numberToGuess) { int signal; cout << "You need to guess a number who is between 1 and 100, what will be your guess?: "<< response<<"\n"; if (response > numberToGuess) { cout << "Too High!\n"; signal = 1; return signal; } else if (response == numberToGuess) { cout << "Just Right!\n"; signal = 0; return signal; } else if (response < numberToGuess) { cout << "Too low!\n"; signal = -1; return signal; } cout << "\n"; } int main() { srand( time (NULL)); int numberToGuess = randRange(1,100); int yourGuess, pastGuess, highGuess, lowGuess, signal, pastSignal, steps=1; yourGuess = randRange(1,100); pastGuess = yourGuess; signal = GuessResponse(yourGuess,numberToGuess) ; while(1) { if(signal == 1) { highGuess = pastGuess; yourGuess = randRange(1,highGuess-1); signal = GuessResponse(yourGuess, numberToGuess); } else if (signal == 0) { yourGuess = yourGuess; cout<< "JUST RIGHT!"; break; } else if (signal == -1) { lowGuess = pastGuess; yourGuess = randRange(lowGuess+1,100); signal = GuessResponse(yourGuess,numberToGuess); } pastGuess = yourGuess; pastSignal = signal ; steps++; } cout << "\nThe number to guess is: "<< numberToGuess << endl; cout << "The number of steps to guess the number was: "<< steps<< endl; }
23.0375
111
0.528486
Titan201
e239d9d37a2e275ded954003e6f858e7d771ec9b
2,426
cpp
C++
Ad-hoc/UVA11309 Counting Chaps/Code.cpp
adelnobel/Training-for-ACM-ICPC-problems
8030d24ab3ce1f50821b22647bf9195b41f932b1
[ "MIT" ]
1
2020-03-05T09:09:36.000Z
2020-03-05T09:09:36.000Z
Ad-hoc/UVA11309 Counting Chaps/Code.cpp
adelnobel/Training-for-ACM-ICPC-problems
8030d24ab3ce1f50821b22647bf9195b41f932b1
[ "MIT" ]
null
null
null
Ad-hoc/UVA11309 Counting Chaps/Code.cpp
adelnobel/Training-for-ACM-ICPC-problems
8030d24ab3ce1f50821b22647bf9195b41f932b1
[ "MIT" ]
null
null
null
#include <vector> #include <list> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <string> using namespace std; #define EPS 1e-7 #define N 10 char s[N]; char s1[N]; int main() { //freopen("in2.in", "r", stdin); int n; scanf("%d", &n, s); while(n--) { scanf("%s", s); bool valid = true, flag = true; int a1 = s[0] - '0', b1 = s[1] - '0', c1 = s[3] - '0', d1 = s[4] + 1 - '0'; while(flag) { for(int a = a1 + '0'; a <= '2' && flag; a++) { char to = '9'; if(a == '2') to = '3'; for(int b = b1 + '0'; b <= to && flag; b++) { for(int c = c1 + '0'; c <= '5' && flag; c++) { for(int d = d1 + '0'; d <= '9' && flag; d++) { valid = true; if( a != d ) valid = false; if( b != c ) valid = false; if(a == '0') { valid = false; if(b == '0') { if(c == '0') { valid = true; } else { if(c == d) valid = true; } } else { if(b == d) valid = true; } } if(valid) { printf("%c%c:%c%c\n", a, b, c, d); flag = false; } } d1 = 0; } c1 = 0; } b1 = 0; } a1 = 0; } } return 0; }
26.955556
83
0.240313
adelnobel
e247b6d7e88e51b12b1c8b917bb0007eb3b90c16
1,277
cpp
C++
examples/loop_interchange_kernel/loop_interchange.cpp
DavidPfander-UniStuttgart/AutoTuneTMP
f5fb836778b04c2ab0fbcc4d36c466e577e96e65
[ "BSD-3-Clause" ]
5
2019-11-06T15:02:41.000Z
2022-01-14T20:25:50.000Z
examples/loop_interchange_kernel/loop_interchange.cpp
DavidPfander-UniStuttgart/AutoTuneTMP
f5fb836778b04c2ab0fbcc4d36c466e577e96e65
[ "BSD-3-Clause" ]
3
2018-01-25T21:25:22.000Z
2022-03-14T17:35:27.000Z
examples/loop_interchange_kernel/loop_interchange.cpp
DavidPfander-UniStuttgart/AutoTuneTMP
f5fb836778b04c2ab0fbcc4d36c466e577e96e65
[ "BSD-3-Clause" ]
1
2020-07-15T11:05:43.000Z
2020-07-15T11:05:43.000Z
#include "parameters.hpp" #include <array> #include <iostream> #include <tuple> #include "opttmp/loop/loop_exchange.hpp" namespace detail { template <size_t depth, size_t index, size_t cur_depth> constexpr size_t extract_index_rec(const size_t perm_rem) { if constexpr (cur_depth == index) { return perm_rem % depth; } else { return extract_index_rec<depth, index, cur_depth + 1>(perm_rem / depth); } } } // namespace detail template <size_t depth, size_t index> constexpr size_t extract_index(const size_t perm_index) { return detail::extract_index_rec<depth, index, 0>(perm_index); } constexpr size_t N = 3; AUTOTUNE_EXPORT void loop_interchange() { std::array<std::tuple<size_t, size_t, size_t>, N> loop_bounds{ {{0, 2, 1}, {0, 2, 1}, {0, 2, 1}}}; // 0, 1, 2 // 0, 2, 1 // 1, ... // std::array<size_t, N> order{2, 0, 1}; std::array<size_t, N> order; order[0] = extract_index<N, 0>(LOOP_ORDER); order[1] = extract_index<N, 1>(LOOP_ORDER); order[2] = extract_index<N, 2>(LOOP_ORDER); opttmp::loop::loop_interchange( [](std::array<size_t, N> &i) { // int x, int y, int z std::cout << "i[0]: " << i[0] << " i[1]: " << i[1] << " i[2]: " << i[2] << std::endl; }, loop_bounds, order); }
27.170213
79
0.624119
DavidPfander-UniStuttgart
e247f91790f70a065e474772c701d8d80ff9ee09
287
cpp
C++
src/DescentEngine/src/EntityEngine/MultiVisualEntity.cpp
poseidn/KungFoo-legacy
9b79d65b596acc9dff4725ef5bfab8ecc4164afb
[ "MIT" ]
1
2017-11-24T03:01:31.000Z
2017-11-24T03:01:31.000Z
src/DescentEngine/src/EntityEngine/MultiVisualEntity.cpp
poseidn/KungFoo-legacy
9b79d65b596acc9dff4725ef5bfab8ecc4164afb
[ "MIT" ]
null
null
null
src/DescentEngine/src/EntityEngine/MultiVisualEntity.cpp
poseidn/KungFoo-legacy
9b79d65b596acc9dff4725ef5bfab8ecc4164afb
[ "MIT" ]
null
null
null
#include "MultiVisualEntity.h" #include "../Log.h" #include <algorithm> // DO NOT PUT THE METHOD DEFINITIONS in the .cpp file ! // otherwise the android compile produces link error, not sure why // one idea is that overrwiting virtual methods across library borders is // problematic
26.090909
73
0.752613
poseidn
f46c31106931df1fa55f2f90afa01dec9b8befa5
2,656
cpp
C++
source/common/generic_config/model/ChoiceParam.cpp
varunamachi/quartz
29b0cf7fb981ec95db894259e32af233f64fa616
[ "MIT" ]
6
2018-01-07T18:11:27.000Z
2022-03-25T03:32:45.000Z
source/common/generic_config/model/ChoiceParam.cpp
varunamachi/quartz
29b0cf7fb981ec95db894259e32af233f64fa616
[ "MIT" ]
8
2019-02-28T02:25:53.000Z
2019-02-28T15:47:18.000Z
source/common/generic_config/model/ChoiceParam.cpp
varunamachi/quartz
29b0cf7fb981ec95db894259e32af233f64fa616
[ "MIT" ]
4
2016-05-28T16:31:06.000Z
2019-09-25T07:13:45.000Z
#include <QVariant> #include <QString> #include <QHash> #include <QVector> #include "ChoiceParam.h" namespace Quartz { struct ChoiceParam::Data { Data() : m_defaultIndex(0) , m_index(m_defaultIndex) { } QVector<QString> m_names; QVector<QVariant> m_values; int m_defaultIndex; int m_index; }; ChoiceParam::ChoiceParam(const QString& id, const QString& name, const QString& description, TreeNode* parent) : Param(id, name, description, parent) , m_data{new Data{}} { } ChoiceParam::~ChoiceParam() { } void ChoiceParam::addOption(const QString& name, const QVariant& value) { if (!m_data->m_names.contains(name)) { m_data->m_names.append(name); m_data->m_values.append(value); } if (m_data->m_defaultIndex == -1) { m_data->m_defaultIndex = 0; m_data->m_index = 0; } } QPair<QString, QVariant> ChoiceParam::option(int index) const { QPair<QString, QVariant> result; if (m_data->m_names.size() > index && index >= 0) { result = QPair<QString, QVariant>{m_data->m_names[index], m_data->m_values[index]}; } return result; } ParamType ChoiceParam::type() const { return ParamType::Choice; } QVariant ChoiceParam::value() const { return this->option(m_data->m_index).second; } int ChoiceParam::index() const { return m_data->m_index; } void ChoiceParam::setValue(const QVariant& value) { m_data->m_index = m_data->m_values.indexOf(value.toString()); } int ChoiceParam::defaultIndex() const { return m_data->m_defaultIndex; } void ChoiceParam::setDefaultIndex(int defaultIndex) { m_data->m_defaultIndex = defaultIndex; } void ChoiceParam::setDefaultValue(const QVariant& value) { auto index = m_data->m_values.indexOf(value); if (index != -1) { m_data->m_defaultIndex = index; } } int ChoiceParam::numOption() const { return m_data->m_names.size(); } std::unique_ptr<Param> ChoiceParam::clone() const { auto param = std::make_unique<ChoiceParam>( id(), name(), description(), parent()); param->setDefaultIndex(this->defaultIndex()); for (auto i = 0; i < m_data->m_names.size(); ++i) { param->addOption(m_data->m_names[i], m_data->m_values[i]); } return std::move(param); } QVariant ChoiceParam::fieldValue(int field) const { if (field == 1) { auto index = m_data->m_index >= 0 ? m_data->m_index : 0; return m_data->m_names[index]; } return Param::fieldValue(field); } } // namespace Quartz
23.095652
73
0.626506
varunamachi
f46f1c6527f8e9eda363a9e2357a4e8d85e78624
4,411
cpp
C++
source/internal/curl.cpp
HeliosInteractive/libkeen
f31246c2f0a705b9f1c25e4400d96a62408c37e6
[ "MIT" ]
1
2016-04-26T04:16:55.000Z
2016-04-26T04:16:55.000Z
source/internal/curl.cpp
HeliosInteractive/libkeen
f31246c2f0a705b9f1c25e4400d96a62408c37e6
[ "MIT" ]
null
null
null
source/internal/curl.cpp
HeliosInteractive/libkeen
f31246c2f0a705b9f1c25e4400d96a62408c37e6
[ "MIT" ]
2
2016-04-14T16:57:03.000Z
2020-02-21T00:17:48.000Z
#include "internal/curl.hpp" #include "scoped.hpp" #include "logger.hpp" #include "curl/curl.h" namespace libkeen { namespace internal { class LibCurlHandle { public: static std::shared_ptr< LibCurlHandle > ref() { static std::shared_ptr< LibCurlHandle > instance{ new LibCurlHandle }; return instance; } LibCurlHandle(); ~LibCurlHandle(); bool isReady() const; private: bool mReady = false; std::vector<LoggerRef> mLoggerRefs; }; LibCurlHandle::LibCurlHandle() { LOG_INFO("Starting up cURL"); internal::Logger::pull(mLoggerRefs); mReady = (curl_global_init(CURL_GLOBAL_DEFAULT) == CURLE_OK); } LibCurlHandle::~LibCurlHandle() { LOG_INFO("Shutting down cURL"); if (isReady()) { curl_global_cleanup(); } } bool LibCurlHandle::isReady() const { return mReady; } bool Curl::sendEvent(const std::string& url, const std::string& json) { if (!mLibCurlHandle || !mLibCurlHandle->isReady()) { LOG_WARN("cURL is not ready. Invalid operation."); return false; } bool success = false; LOG_INFO("cURL is about to send an event to: " << url << " with json: " << json); if (auto curl = curl_easy_init()) { curl_slist *headers = nullptr; Scoped<CURL> scope_bound_curl(curl); Scoped<curl_slist> scope_bound_slist(headers); headers = curl_slist_append(headers, "Accept: application/json"); headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, "charsets: utf-8"); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); auto res = curl_easy_perform(curl); if (res == CURLE_OK) { long http_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); if (http_code == 200 || http_code == 201) success = true; // FROM https://keen.io/docs/api/#errors // Check the response body for individual event statuses. Some or all may have failed. // TODO ^^^ } } if (success) { LOG_INFO("cURL succesfully sent an event."); } else { LOG_ERROR("cURL failed to send an event."); } return success; } namespace { static size_t write_cb(void *contents, size_t size, size_t nmemb, void *userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; }} bool Curl::sendEvent(const std::string& url, const std::string& json, std::string& reply) { if (!mLibCurlHandle || !mLibCurlHandle->isReady()) { LOG_WARN("cURL is not ready. Invalid operation."); return false; } bool success = false; if (!reply.empty()) reply.clear(); LOG_INFO("cURL is about to send an event to: " << url << " with json: " << json); if (auto curl = curl_easy_init()) { curl_slist *headers = nullptr; Scoped<CURL> scope_bound_curl(curl); Scoped<curl_slist> scope_bound_slist(headers); headers = curl_slist_append(headers, "Accept: application/json"); headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, "charsets: utf-8"); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &reply); auto res = curl_easy_perform(curl); if (res == CURLE_OK) { long http_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); if (http_code == 200 || http_code == 201) success = true; } } if (success) { LOG_INFO("cURL succesfully sent an event."); } else { LOG_ERROR("cURL failed to send an event."); } return success; } Curl::Curl() : mLibCurlHandle(LibCurlHandle::ref()) { internal::Logger::pull(mLoggerRefs); if (mLibCurlHandle && mLibCurlHandle->isReady()) LOG_INFO("cURL is initialized successfully."); } }}
26.572289
98
0.622308
HeliosInteractive
f4756766856cdc7cf12e4a4226c7c2672a68509e
186
cpp
C++
src/component/component.cpp
MeTheFlea/flare
cf94019ef1a907fa33f29c5834616e05d891fb0d
[ "MIT" ]
3
2015-04-05T18:16:16.000Z
2016-05-02T19:00:48.000Z
src/component/component.cpp
MeTheFlea/flare
cf94019ef1a907fa33f29c5834616e05d891fb0d
[ "MIT" ]
null
null
null
src/component/component.cpp
MeTheFlea/flare
cf94019ef1a907fa33f29c5834616e05d891fb0d
[ "MIT" ]
null
null
null
#include "component/component.h" std::vector<std::function<void()>> flare::Components::s_updateFunctions; std::vector<std::function<void()>> flare::Components::s_renderFunctions;
31
73
0.741935
MeTheFlea