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
a262f7b192a34e3efee1f74fc4223861f275b0fd
4,487
cpp
C++
src/server/protocol/ServerProtocol.cpp
zminor/Zony_CPP
311c75a3d6acebb7f4265b63813b19eeaa9d8926
[ "MIT" ]
null
null
null
src/server/protocol/ServerProtocol.cpp
zminor/Zony_CPP
311c75a3d6acebb7f4265b63813b19eeaa9d8926
[ "MIT" ]
null
null
null
src/server/protocol/ServerProtocol.cpp
zminor/Zony_CPP
311c75a3d6acebb7f4265b63813b19eeaa9d8926
[ "MIT" ]
null
null
null
#include "ServerProtocol.h" #include "../../utils/Utils.h" namespace HttpServer { ServerProtocol::ServerProtocol( Socket::Adapter &sock, const ServerSettings &settings, ServerControls &controls ) noexcept : sock(sock), settings(settings), controls(controls) { } ServerProtocol::ServerProtocol(const ServerProtocol &prot) noexcept : sock(prot.sock), settings(prot.settings), controls(prot.controls) { } DataVariant::DataReceiver * ServerProtocol::createDataReceiver( const Transfer::request_data *rd, const std::unordered_map<std::string, DataVariant::Abstract *> &variants ) { auto const it = rd->incoming_headers.find("content-type"); if (rd->incoming_headers.cend() == it) { return nullptr; } // get the value of the header const std::string &header_value = it->second; std::string data_variant_name; // name of data query std::unordered_map<std::string, std::string> content_params; // to determine whether the data type query additional parameters size_t delimiter = header_value.find(';'); // if there are additional parameters - remove them if (std::string::npos != delimiter) { data_variant_name = header_value.substr(0, delimiter); Utils::trim(data_variant_name); for ( size_t str_param_cur = delimiter + 1, str_param_end = 0; std::string::npos != str_param_end; str_param_cur = str_param_end + 1 ) { str_param_end = header_value.find(';', str_param_cur); delimiter = header_value.find('=', str_param_cur); if (delimiter >= str_param_end) { std::string param_name = header_value.substr( str_param_cur, std::string::npos != str_param_end ? str_param_end - str_param_cur : std::string::npos ); Utils::trim(param_name); content_params.emplace( std::move(param_name), std::string() ); } else { std::string param_name = header_value.substr( str_param_cur, delimiter - str_param_cur ); Utils::trim(param_name); ++delimiter; std::string param_value = header_value.substr( delimiter, std::string::npos != str_param_end ? str_param_end - delimiter : std::string::npos ); Utils::trim(param_value); content_params.emplace( std::move(param_name), std::move(param_value) ); } } } else { data_variant_name = header_value; } auto const variant = variants.find(data_variant_name); if (variants.cend() == variant) { return nullptr; } const DataVariant::Abstract *data_variant = variant->second; size_t data_length = 0; auto const it_len = rd->incoming_headers.find("content-length"); if (rd->incoming_headers.cend() != it_len) { data_length = std::strtoull( it_len->second.c_str(), nullptr, 10 ); } return new DataVariant::DataReceiver { data_variant, data_variant->createStateStruct(rd, content_params), data_length, 0, 0, nullptr, }; } void ServerProtocol::destroyDataReceiver(void *src) { DataVariant::DataReceiver *dr = reinterpret_cast<DataVariant::DataReceiver *>(src); if (dr) { dr->data_variant->destroyStateStruct(dr->ss); if (dr->reserved) { delete reinterpret_cast<std::string *>(dr->reserved); dr->reserved = nullptr; } } delete dr; } void ServerProtocol::runApplication( struct Request &req, const ServerApplicationSettings &appSets ) const { std::vector<char> buf; buf.reserve(4096); if (this->packRequestParameters(buf, req, appSets.root_dir) == false) { return; } Transfer::app_request request { this->sock.get_handle(), this->sock.get_tls_session(), buf.data() }; Transfer::app_response response { nullptr, 0 }; try { // Launch application req.app_exit_code = appSets.application_call(&request, &response); } catch (std::exception &exc) { // TODO: exception output } if (response.response_data && response.data_size) { if (EXIT_SUCCESS == req.app_exit_code) { this->unpackResponseParameters(req, response.response_data); } // Clear outgoing data of application try { appSets.application_clear(response.response_data, response.data_size); } catch (std::exception &exc) { // TODO: exception output } } } }
23.615789
86
0.640517
zminor
a264baaa6da8b663d483dfc76c2506d201409a6f
2,434
hpp
C++
include/domain/structure/field/svector_center.hpp
hyperpower/Nablla
5a9be9f3b064a235572a1a2c9c5c2c19118697c5
[ "MIT" ]
null
null
null
include/domain/structure/field/svector_center.hpp
hyperpower/Nablla
5a9be9f3b064a235572a1a2c9c5c2c19118697c5
[ "MIT" ]
null
null
null
include/domain/structure/field/svector_center.hpp
hyperpower/Nablla
5a9be9f3b064a235572a1a2c9c5c2c19118697c5
[ "MIT" ]
null
null
null
#ifndef _S_VECTOR_CENTER_HPP_ #define _S_VECTOR_CENTER_HPP_ #include "sfield.hpp" #include "utility/tinyformat.hpp" #include "algebra/array/multi_array.hpp" #include <limits> namespace carpio{ template<St DIM, class FIELD> class SVectorCenter_{ public: typedef SIndex_<DIM> Index; typedef SGrid_<DIM> GridBase; typedef SGhost_<DIM> GhostBase; typedef SOrder_<DIM> OrderBase; typedef FIELD Field; typedef typename FIELD::Grid Grid; typedef typename FIELD::Ghost Ghost; typedef typename FIELD::Order Order; typedef std::shared_ptr<SIndex_<DIM> > spIndex; typedef std::shared_ptr<SGrid_<DIM> > spGrid; typedef std::shared_ptr<SGhost_<DIM> > spGhost; typedef std::shared_ptr<SOrder_<DIM> > spOrder; typedef MultiArrayV_<Vt, DIM> Mat; typedef typename Mat::reference reference; typedef typename Mat::const_reference const_reference; typedef SVectorCenter_<DIM, FIELD> Self; typedef std::shared_ptr<Field> spField; protected: std::array<spField, DIM> _arrs; public: SVectorCenter_() { FOR_EACH_DIM{ _arrs[d] = nullptr; } } SVectorCenter_( spField u, spField v = nullptr, spField w = nullptr){ spField a[] = {u,v,w}; FOR_EACH_DIM{ ASSERT(a[d] != nullptr); _arrs[d] = a[d]; } } void set(Axes a, spField sps){ ASSERT(a < DIM); _arrs[a] = sps; } const Order& order() const { return _arrs[_X_]->order(); } const Grid& grid() const { return _arrs[_X_]->grid(); } const Ghost& ghost() const { return _arrs[_X_]->ghost(); } Field& operator[](St d){ return *(_arrs[d]); } const Field& operator[](St d) const{ return *(_arrs[d]); } Vt max() const{ Vt m = _arrs[_X_]->max(); for(St d = 1; d< DIM; d++){ Vt md = _arrs[d]->max(); if(m < md){ m = md; } } return m; } Vt max_norm2() const{ if(DIM == 1){ return max(); }else if(DIM == 2){ auto sum = SqareSum(*(_arrs[_X_]), *(_arrs[_Y_])); return std::sqrt(sum.max()); }else{ auto sum = SqareSum(_arrs[_X_], _arrs[_Y_], _arrs[_Z_]); return std::sqrt(sum.max()); } } }; } #endif
21.927928
68
0.554232
hyperpower
a27073b60d9cad11e32d5c469bca677e37901975
3,951
cpp
C++
src_test/test_utils/TestCase.cpp
alinous-core/codable-cash
32a86a152a146c592bcfd8cc712f4e8cb38ee1a0
[ "MIT" ]
6
2019-01-06T05:02:39.000Z
2020-10-01T11:45:32.000Z
src_test/test_utils/TestCase.cpp
Codablecash/codablecash
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
[ "MIT" ]
209
2018-05-18T03:07:02.000Z
2022-03-26T11:42:41.000Z
src_test/test_utils/TestCase.cpp
Codablecash/codablecash
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
[ "MIT" ]
3
2019-07-06T09:16:36.000Z
2020-10-15T08:23:28.000Z
/* * TestCase.cpp * * Created on: 2018/05/06 * Author: iizuka */ #include "test_utils/TestCase.h" #include "test_utils/TestGroup.h" #include "test_utils/TestGroupActions.h" #include "test_utils/Check.h" #include "test_utils/TestEnv.h" #include "test_utils/TestParams.h" #include "base/UnicodeString.h" #include <chrono> #include "base_io_stream/Writer.h" using namespace std::chrono; namespace alinous { TestCase::TestCase(TestGroup* group, const wchar_t* name, TestGroupActions* setup, const char* file, int line) noexcept { this->group = group; this->name = new UnicodeString(name); this->setup = setup; this->file = new UnicodeString(file); this->line = line; this->checks = new ArrayList<Check>(); this->env = new TestEnv(this); this->done = false; this->failed = false; this->microsec = 0; this->setup->setNames(group->getName(), this->name); this->setup->setTestEnv(this->env); group->addTestCase(this->name, this); } TestCase::~TestCase() noexcept { delete this->name; delete this->setup; delete this->file; this->checks->deleteElements(); delete this->checks; } void TestCase::doTest(TestParams* params) { const char* result = "OK"; setDone(); try{ this->setup->setup(); }catch(...){ setFailed(); if(params->isV()){ printf(" %ls [%ls at %d]... failed in setup()\n", this->name->towString(), this->file->towString(), getLine()); } return; } uint64_t start, end; try{ Check::getThreadKeyRegistory()->registerTestCase(this); start = Os::getMicroSec(); testBody(); end = Os::getMicroSec(); }catch(...){ end = Os::getMicroSec(); setFailed(); if(params->isV()){ printf(" !!!!! %ls [%ls at %d]... failed. Exception was thrown on test body.\n", this->name->towString(), this->file->towString(), getLine()); } } this->microsec = end - start; try{ this->setup->teardown(); } catch(...){ setFailed(); if(params->isV()){ printf(" !!!!! %ls [%ls at %d]... failed in teardown()\n", this->name->towString(), this->file->towString(), getLine()); } return; } if(params->isV()){ if(isFailed()){ result = "Failed!!!!!!!!!!!"; }else{ result = "OK"; } double milli = ((double)this->microsec) / (double)1000; printf(" %ls() [%ls at %d]... %s(%lf ms)\n", this->name->towString(), this->file->towString(), getLine(), result, milli); } else{ printf("."); fflush( stdout ); } } Check* TestCase::addCheck(Check* check) noexcept { this->checks->addElement(check); return check; } const TestGroup* TestCase::getGroup() const noexcept { return this->group; } TestEnv* TestCase::getEnv() noexcept { return this->env; } const UnicodeString* TestCase::getName() const noexcept { return this->name; } const UnicodeString* TestCase::getFile() const noexcept { return this->file; } const int TestCase::getLine() const noexcept { return this->line; } bool TestCase::isDone() const noexcept { return this->done; } void TestCase::setDone() noexcept { this->done = true; } bool TestCase::isFailed() const noexcept { return this->failed; } void TestCase::setFailed() noexcept { this->failed = true; } ArrayList<Check>* TestCase::getChecks() const noexcept { return this->checks; } void TestCase::exportJUnitXML(Writer* writer) const { char buff[255]{}; double sec = ((double)this->microsec) / (double)1000000; ::sprintf(buff, "%lf", sec); UnicodeString milStr(buff); UnicodeString caseStr(L" <testcase classname=\""); caseStr.append(this->group->getName()).append(L"\" name=\"").append(this->name).append(L"\" time=\"") .append(&milStr).append(L"\">\n"); writer->write(&caseStr); if(failed){ writer->write(L" <failure>\n"); UnicodeString failure(L""); failure.append(this->file).append(L" at ").append(this->line).append(L"\n"); writer->write(L" "); writer->write(&failure); writer->write(L" </failure>\n"); } writer->write(L" </testcase>\n"); } } /* namespace alinous */
21.95
146
0.647684
alinous-core
a2746799b5f0e0552105b05d98da248b16a6d79b
6,463
cpp
C++
lib/dirac_domain_wall.cpp
Marcogarofalo/quda
7dd7ba316d5f872d1a332bdf55a2204a1a4a7dda
[ "MIT" ]
null
null
null
lib/dirac_domain_wall.cpp
Marcogarofalo/quda
7dd7ba316d5f872d1a332bdf55a2204a1a4a7dda
[ "MIT" ]
null
null
null
lib/dirac_domain_wall.cpp
Marcogarofalo/quda
7dd7ba316d5f872d1a332bdf55a2204a1a4a7dda
[ "MIT" ]
null
null
null
#include <iostream> #include <dirac_quda.h> #include <dslash_quda.h> #include <blas_quda.h> namespace quda { DiracDomainWall::DiracDomainWall(const DiracParam &param) : DiracWilson(param, 5), m5(param.m5), kappa5(0.5 / (5.0 + m5)), Ls(param.Ls) { } DiracDomainWall::DiracDomainWall(const DiracDomainWall &dirac) : DiracWilson(dirac), m5(dirac.m5), kappa5(0.5 / (5.0 + m5)), Ls(dirac.Ls) { } DiracDomainWall::~DiracDomainWall() { } DiracDomainWall& DiracDomainWall::operator=(const DiracDomainWall &dirac) { if (&dirac != this) { DiracWilson::operator=(dirac); m5 = dirac.m5; kappa5 = dirac.kappa5; } return *this; } void DiracDomainWall::checkDWF(const ColorSpinorField &out, const ColorSpinorField &in) const { if (in.Ndim() != 5 || out.Ndim() != 5) errorQuda("Wrong number of dimensions\n"); if (in.X(4) != Ls) errorQuda("Expected Ls = %d, not %d\n", Ls, in.X(4)); if (out.X(4) != Ls) errorQuda("Expected Ls = %d, not %d\n", Ls, out.X(4)); } void DiracDomainWall::Dslash(ColorSpinorField &out, const ColorSpinorField &in, const QudaParity parity) const { checkDWF(out, in); checkParitySpinor(in, out); checkSpinorAlias(in, out); ApplyDomainWall5D(out, in, *gauge, 0.0, mass, in, parity, dagger, commDim, profile); long long Ls = in.X(4); long long bulk = (Ls-2)*(in.Volume()/Ls); long long wall = 2*in.Volume()/Ls; flops += 1320LL*(long long)in.Volume() + 96LL*bulk + 120LL*wall; } void DiracDomainWall::DslashXpay(ColorSpinorField &out, const ColorSpinorField &in, const QudaParity parity, const ColorSpinorField &x, const double &k) const { checkDWF(out, in); checkParitySpinor(in, out); checkSpinorAlias(in, out); ApplyDomainWall5D(out, in, *gauge, k, mass, x, parity, dagger, commDim, profile); long long Ls = in.X(4); long long bulk = (Ls-2)*(in.Volume()/Ls); long long wall = 2*in.Volume()/Ls; flops += (1320LL+48LL)*(long long)in.Volume() + 96LL*bulk + 120LL*wall; } void DiracDomainWall::M(ColorSpinorField &out, const ColorSpinorField &in) const { checkFullSpinor(out, in); ApplyDomainWall5D(out, in, *gauge, -kappa5, mass, in, QUDA_INVALID_PARITY, dagger, commDim, profile); long long Ls = in.X(4); long long bulk = (Ls - 2) * (in.Volume() / Ls); long long wall = 2 * in.Volume() / Ls; flops += (1320LL + 48LL) * (long long)in.Volume() + 96LL * bulk + 120LL * wall; } void DiracDomainWall::MdagM(ColorSpinorField &out, const ColorSpinorField &in) const { checkFullSpinor(out, in); bool reset = newTmp(&tmp1, in); M(*tmp1, in); Mdag(out, *tmp1); deleteTmp(&tmp1, reset); } void DiracDomainWall::prepare(ColorSpinorField* &src, ColorSpinorField* &sol, ColorSpinorField &x, ColorSpinorField &b, const QudaSolutionType solType) const { if (solType == QUDA_MATPC_SOLUTION || solType == QUDA_MATPCDAG_MATPC_SOLUTION) { errorQuda("Preconditioned solution requires a preconditioned solve_type"); } src = &b; sol = &x; } void DiracDomainWall::reconstruct(ColorSpinorField &, const ColorSpinorField &, const QudaSolutionType) const { // do nothing } DiracDomainWallPC::DiracDomainWallPC(const DiracParam &param) : DiracDomainWall(param) { } DiracDomainWallPC::DiracDomainWallPC(const DiracDomainWallPC &dirac) : DiracDomainWall(dirac) { } DiracDomainWallPC::~DiracDomainWallPC() { } DiracDomainWallPC& DiracDomainWallPC::operator=(const DiracDomainWallPC &dirac) { if (&dirac != this) { DiracDomainWall::operator=(dirac); } return *this; } // Apply the even-odd preconditioned clover-improved Dirac operator void DiracDomainWallPC::M(ColorSpinorField &out, const ColorSpinorField &in) const { checkDWF(out, in); double kappa2 = -kappa5*kappa5; bool reset = newTmp(&tmp1, in); if (matpcType == QUDA_MATPC_EVEN_EVEN) { Dslash(*tmp1, in, QUDA_ODD_PARITY); DslashXpay(out, *tmp1, QUDA_EVEN_PARITY, in, kappa2); } else if (matpcType == QUDA_MATPC_ODD_ODD) { Dslash(*tmp1, in, QUDA_EVEN_PARITY); DslashXpay(out, *tmp1, QUDA_ODD_PARITY, in, kappa2); } else { errorQuda("MatPCType %d not valid for DiracDomainWallPC", matpcType); } deleteTmp(&tmp1, reset); } void DiracDomainWallPC::MdagM(ColorSpinorField &out, const ColorSpinorField &in) const { //M(out, in); //Mdag(out, out); bool reset = newTmp(&tmp2, in); M(*tmp2, in); Mdag(out, *tmp2); deleteTmp(&tmp2, reset); } void DiracDomainWallPC::prepare(ColorSpinorField* &src, ColorSpinorField* &sol, ColorSpinorField &x, ColorSpinorField &b, const QudaSolutionType solType) const { // we desire solution to preconditioned system if (solType == QUDA_MATPC_SOLUTION || solType == QUDA_MATPCDAG_MATPC_SOLUTION) { src = &b; sol = &x; } else { // we desire solution to full system if (matpcType == QUDA_MATPC_EVEN_EVEN) { // src = b_e + k D_eo b_o DslashXpay(x.Odd(), b.Odd(), QUDA_EVEN_PARITY, b.Even(), kappa5); src = &(x.Odd()); sol = &(x.Even()); } else if (matpcType == QUDA_MATPC_ODD_ODD) { // src = b_o + k D_oe b_e DslashXpay(x.Even(), b.Even(), QUDA_ODD_PARITY, b.Odd(), kappa5); src = &(x.Even()); sol = &(x.Odd()); } else { errorQuda("MatPCType %d not valid for DiracDomainWallPC", matpcType); } // here we use final solution to store parity solution and parity source // b is now up for grabs if we want } } void DiracDomainWallPC::reconstruct(ColorSpinorField &x, const ColorSpinorField &b, const QudaSolutionType solType) const { if (solType == QUDA_MATPC_SOLUTION || solType == QUDA_MATPCDAG_MATPC_SOLUTION) { return; } // create full solution checkFullSpinor(x, b); if (matpcType == QUDA_MATPC_EVEN_EVEN) { // x_o = b_o + k D_oe x_e DslashXpay(x.Odd(), x.Even(), QUDA_ODD_PARITY, b.Odd(), kappa5); } else if (matpcType == QUDA_MATPC_ODD_ODD) { // x_e = b_e + k D_eo x_o DslashXpay(x.Even(), x.Odd(), QUDA_EVEN_PARITY, b.Even(), kappa5); } else { errorQuda("MatPCType %d not valid for DiracDomainWallPC", matpcType); } } } // namespace quda
28.852679
111
0.63763
Marcogarofalo
a276a5c5b571915bbb078380db42a824cf878ed6
2,822
cpp
C++
modules/core/src/intrinsic.cpp
shreddered/imagestego
633b41bce2e653a3e8a46b812f05af814088ea51
[ "MIT" ]
2
2020-10-10T11:44:40.000Z
2020-10-25T01:55:21.000Z
modules/core/src/intrinsic.cpp
shreddered/imagestego
633b41bce2e653a3e8a46b812f05af814088ea51
[ "MIT" ]
9
2020-09-21T20:56:58.000Z
2021-01-26T13:04:05.000Z
modules/core/src/intrinsic.cpp
shreddered/imagestego
633b41bce2e653a3e8a46b812f05af814088ea51
[ "MIT" ]
2
2021-01-24T13:49:51.000Z
2021-03-13T23:14:15.000Z
/* * This file is a part of imagestego library. * * Copyright (c) 2020-2021 Dmitry Kalinin <[email protected]> * * 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. */ // imagestego headers #include "imagestego/core/intrinsic.hpp" // c++ headers #include <cstdlib> #if IMAGESTEGO_MSVC && HAVE_INTRIN_H #include <intrin.h> #pragma intrinsic(_BitScanReverse) #endif #if IMAGESTEGO_MSVC #define bswap_32(x) _byteswap_ulong(x) #elif IMAGESTEGO_ICC #define bswap_32(x) _bswap(x) #elif IMAGESTEGO_GCC || (IMAGESTEGO_CLANG && !defined(__APPLE__)) #define bswap_32(x) __builtin_bswap32(x) #elif defined(__APPLE__) #include <libkern/OSByteOrder.h> #define bswap_32(x) OSSwapInt32(x) #elif defined(__sun) || defined(sun) #include <sys/byteorder.h> #define bswap_32(x) BSWAP_32(x) #elif defined(__FreeBSD__) #include <sys/endian.h> #define bswap_32(x) bswap32(x) #elif defined(__OpenBSD__) #include <sys/types.h> #define bswap_32(x) swap32(x) #elif defined(__NetBSD__) #include <machine/bswap.h> #include <sys/types.h> #if defined(__BSWAP_RENAME) && !defined(__bswap_32) #define bswap_32(x) bswap32(x) #endif #endif namespace imagestego { uint8_t log2(uint32_t value) noexcept { #if IMAGESTEGO_CLANG || IMAGESTEGO_GCC return value ? 31 - __builtin_clz(value) : 0; #elif IMAGESTEGO_ICC uint32_t result = 0; _BitScanReverse(&result, value); return result; #elif IMAGESTEGO_MSVC unsigned long result = 0; _BitScanReverse(&result, value); return result; #else uint8_t res = 0; while (value >>= 1) ++res; return res; #endif } uint32_t bswap(uint32_t value) noexcept { #ifdef bswap_32 return bswap_32(value); #else char* tmp = reinterpret_cast<char*>(&value); std::reverse(tmp, tmp + 4); return value; #endif } } // namespace imagestego
30.673913
81
0.739546
shreddered
a278813e4ddaccac4036a265740e6d7bd98c0dcc
688
cpp
C++
win32/src/Display.cpp
deianvn/swt-plus-plus
e85236e8279b4e6f5993d94d1bd14e6fc7e1dd1b
[ "Apache-2.0" ]
null
null
null
win32/src/Display.cpp
deianvn/swt-plus-plus
e85236e8279b4e6f5993d94d1bd14e6fc7e1dd1b
[ "Apache-2.0" ]
null
null
null
win32/src/Display.cpp
deianvn/swt-plus-plus
e85236e8279b4e6f5993d94d1bd14e6fc7e1dd1b
[ "Apache-2.0" ]
null
null
null
#include "swt/widgets/Display.hpp" #include <windows.h> #include <iostream> namespace swt { int Display::readAndDispatch() { MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return static_cast<int>(msg.wParam); } const std::vector<Shell>& Display::getShells() { return shells; } Shell* Display::getCurrentShell() { return currentShell; } void Display::setCurrentShell(Shell* shell) { currentShell = shell; } void Display::addShell(Shell* shell) { shells.push_back(*shell); } }
17.2
50
0.55814
deianvn
a27a370fd9ee3abfa131633d8c39a1198ca07edf
416
cpp
C++
alex/chapter5/5.8_max_element.cpp
Alexhhhc/gay-school-cpp-homework
fa864ce1632367ef0fa269c25030e60d3a0aafac
[ "BSD-3-Clause" ]
null
null
null
alex/chapter5/5.8_max_element.cpp
Alexhhhc/gay-school-cpp-homework
fa864ce1632367ef0fa269c25030e60d3a0aafac
[ "BSD-3-Clause" ]
null
null
null
alex/chapter5/5.8_max_element.cpp
Alexhhhc/gay-school-cpp-homework
fa864ce1632367ef0fa269c25030e60d3a0aafac
[ "BSD-3-Clause" ]
null
null
null
//例5.8 //用函数求一个矩阵中的最大元 #include <iostream> using namespace std; int main() { int max_value(int array[3][4]); //函数声明 int a[3][4]={{11,32,45,67},{22,44,66,88},{15,72,43,37}}; //定义数组并初始化 cout<<"max_value is"<<max_value(a)<<endl; //输出最大值 return 0; } int max_value(int array[3][4]) { int i,j,max; max=array[0][0]; for(i=0;i<3;i++) for(j=0;j<4;j++) if(array[i][j]>max)max=array[i][j]; return max; //返回最大值 }
20.8
68
0.605769
Alexhhhc
a2840ffffa6f81dec80b567d6c793b5d06851f60
24,378
hpp
C++
include/boost/text/normalize.hpp
jan-moeller/text
c61e51c82dfb0ae6e74200c01ce040fa6db730c4
[ "BSL-1.0" ]
null
null
null
include/boost/text/normalize.hpp
jan-moeller/text
c61e51c82dfb0ae6e74200c01ce040fa6db730c4
[ "BSL-1.0" ]
null
null
null
include/boost/text/normalize.hpp
jan-moeller/text
c61e51c82dfb0ae6e74200c01ce040fa6db730c4
[ "BSL-1.0" ]
null
null
null
#ifndef BOOST_TEXT_NORMALIZE_HPP #define BOOST_TEXT_NORMALIZE_HPP #include <boost/text/utility.hpp> #include <boost/text/detail/normalization_data.hpp> #include <boost/container/static_vector.hpp> #include <algorithm> namespace boost { namespace text { namespace detail { template<typename Iter, std::size_t Capacity> void order_canonically( Iter first, Iter last, container::static_vector<int, Capacity> & cccs) noexcept { BOOST_ASSERT(first != last); std::transform(first, last, cccs.begin(), ccc); --last; while (first != last) { auto it = first; auto new_last = first; auto ccc_it = cccs.begin(); while (it != last) { auto next = std::next(it); auto ccc_next = std::next(ccc_it); auto const ccc_a = *ccc_it; auto const ccc_b = *ccc_next; if (0 < ccc_b && ccc_b < ccc_a) { std::iter_swap(it, next); std::iter_swap(ccc_it, ccc_next); new_last = it; } ++it; ++ccc_it; } last = new_last; } } template<std::size_t Capacity, typename FlushFunc> bool flush_buffer( container::static_vector<uint32_t, Capacity> & buffer, FlushFunc & flush) { container::static_vector<int, Capacity> cccs(buffer.size()); if (!buffer.empty()) order_canonically(buffer.begin(), buffer.end(), cccs); if (!flush(buffer.begin(), buffer.end())) return false; buffer.clear(); return true; } template< typename Iter, typename Sentinel, std::size_t Capacity, typename DecomposeFunc, typename FlushFunc> bool normalize_to_decomposed_impl( Iter first, Sentinel last, container::static_vector<uint32_t, Capacity> & buffer, DecomposeFunc && decompose, FlushFunc && flush) { while (first != last) { auto const decomp = decompose(*first); if (!ccc(decomp.storage_[0])) { if (!detail::flush_buffer(buffer, flush)) return false; } buffer.insert(buffer.end(), decomp.begin(), decomp.end()); ++first; } if (!detail::flush_buffer(buffer, flush)) return false; return true; } template< typename Iter, typename Sentinel, typename OutIter, typename DecomposeFunc> OutIter normalize_to_decomposed( Iter first, Sentinel last, OutIter out, DecomposeFunc && decompose) { container::static_vector<uint32_t, 64> buffer; using buffer_iterator = container::static_vector<uint32_t, 64>::iterator; normalize_to_decomposed_impl( first, last, buffer, decompose, [&out](buffer_iterator first, buffer_iterator last) { out = std::copy(first, last, out); return true; }); return out; } inline constexpr bool hangul_l(uint32_t cp) noexcept { return 0x1100 <= cp && cp <= 0x1112; } inline constexpr bool hangul_v(uint32_t cp) noexcept { return 0x1161 <= cp && cp <= 0x1175; } inline constexpr bool hangul_t(uint32_t cp) noexcept { return 0x11a8 <= cp && cp <= 0x11c2; } template<bool DisallowDiscontiguous, std::size_t Capacity> void compose( container::static_vector<uint32_t, Capacity> & buffer, container::static_vector<int, Capacity> & cccs) { BOOST_ASSERT(buffer.size() == cccs.size()); BOOST_ASSERT(2 <= buffer.size()); auto starter_it = buffer.begin(); auto it = std::next(buffer.begin()); auto ccc_it = std::next(cccs.begin()); while (it != buffer.end()) { // Hangul composition as described in Unicode 11.0 Section 3.12. auto const hangul_cp0 = *starter_it; auto const hangul_cp1 = *it; if (it == starter_it + 1 && hangul_l(hangul_cp0) && hangul_v(hangul_cp1)) { auto const cp2_it = it + 1; auto const hangul_cp2 = cp2_it == buffer.end() ? 0 : *cp2_it; if (hangul_t(hangul_cp2)) { *starter_it = compose_hangul(hangul_cp0, hangul_cp1, hangul_cp2); buffer.erase(it, it + 2); cccs.erase(ccc_it, ccc_it + 2); } else { *starter_it = compose_hangul(hangul_cp0, hangul_cp1); buffer.erase(it, it + 1); cccs.erase(ccc_it, ccc_it + 1); } } else { auto const prev_ccc = *std::prev(ccc_it); auto const ccc = *ccc_it; uint32_t composition = 0; if ((it == starter_it + 1 || (!DisallowDiscontiguous && (prev_ccc != 0 && prev_ccc < ccc))) && (composition = compose_unblocked(*starter_it, *it))) { *starter_it = composition; buffer.erase(it); cccs.erase(ccc_it); } else { ++it; ++ccc_it; if (it == buffer.end() && starter_it < buffer.end() - 2) { ++starter_it; it = std::next(starter_it); ccc_it = cccs.begin() + (it - buffer.begin()); } } } } } template< bool DisallowDiscontiguous, std::size_t Capacity, typename FlushFunc> bool compose_and_flush_buffer( container::static_vector<uint32_t, Capacity> & buffer, FlushFunc && flush) noexcept(noexcept(flush(buffer.begin(), buffer.end()))) { container::static_vector<int, Capacity> cccs(buffer.size()); if (!buffer.empty()) order_canonically(buffer.begin(), buffer.end(), cccs); if (2 <= buffer.size()) compose<DisallowDiscontiguous>(buffer, cccs); if (!flush(buffer.begin(), buffer.end())) return false; buffer.clear(); return true; } template<std::size_t Capacity> bool hangul_final_v( container::static_vector<uint32_t, Capacity> & buffer, uint32_t cp) noexcept { return !buffer.empty() && hangul_l(buffer.back()) && hangul_v(cp); } template<std::size_t Capacity> bool hangul_final_t( container::static_vector<uint32_t, Capacity> & buffer, uint32_t cp) noexcept { return 2 <= buffer.size() && hangul_l(buffer[buffer.size() - 2]) && hangul_v(buffer.back()) && hangul_t(cp); } template< bool DisallowDiscontiguous, typename Iter, typename Sentinel, std::size_t Capacity, typename DecomposeFunc, typename QuickCheckFunc, typename FlushFunc> bool normalize_to_composed_impl( Iter first, Sentinel last, container::static_vector<uint32_t, Capacity> & buffer, DecomposeFunc && decompose, QuickCheckFunc && quick_check_, FlushFunc && flush) noexcept { while (first != last) { auto const decomp = decompose(*first); auto const it = std::find_if( decomp.begin(), decomp.end(), [&quick_check_](uint32_t cp) { return !ccc(cp) && quick_check_(cp) == quick_check::yes; }); if (it != decomp.end() && !hangul_final_v(buffer, *it) && !hangul_final_t(buffer, *it)) { buffer.insert(buffer.end(), decomp.begin(), it); if (!detail::compose_and_flush_buffer< DisallowDiscontiguous>(buffer, flush)) { return false; } buffer.insert(buffer.end(), it, decomp.end()); } else { buffer.insert(buffer.end(), decomp.begin(), decomp.end()); } ++first; } if (!detail::compose_and_flush_buffer<DisallowDiscontiguous>( buffer, flush)) { return false; } return true; } template< bool DisallowDiscontiguous, typename Iter, typename Sentinel, typename OutIter, typename DecomposeFunc, typename QuickCheckFunc> OutIter normalize_to_composed( Iter first, Sentinel last, OutIter out, DecomposeFunc && decompose, QuickCheckFunc && quick_check_) { container::static_vector<uint32_t, 64> buffer; using buffer_iterator = container::static_vector<uint32_t, 64>::iterator; normalize_to_composed_impl<DisallowDiscontiguous>( first, last, buffer, decompose, quick_check_, [&out](buffer_iterator first, buffer_iterator last) { out = std::copy(first, last, out); return true; }); return out; } #if 0 // NOTE: The logic in // http://www.unicode.org/reports/tr15/tr15-45.html#Detecting_Normalization_Forms // seems to indicate that if a supplementary code point is encountered // in normalized_quick_check(), then we should proceed as normal for // this iteration, but then do a double increment of the loop control // variable. That looks wrong, so I'm leaving that out for now. bool supplemantary(uint32_t cp) { return 0x10000 <= cp && cp <= 0x10FFFF; } #endif // TODO: Experiment with writing out the ccc values for reuse in case // the result is not quick_check::yes. template<typename Iter, typename Sentinel, typename QuickCheckFunc> quick_check normalized_quick_check( Iter first, Sentinel last, QuickCheckFunc && quick_check_) noexcept { quick_check retval = quick_check::yes; int prev_ccc = 0; while (first != last) { auto const cp = *first; #if 0 // See note above. if (supplemantary(cp)) ++first; #endif auto const check = quick_check_(cp); if (check == quick_check::no) return quick_check::no; if (check == quick_check::maybe) retval = quick_check::maybe; auto const ccc_ = ccc(cp); if (ccc_ && ccc_ < prev_ccc) return quick_check::no; prev_ccc = ccc_; ++first; } return retval; } template< typename Iter, typename Sentinel, typename DecomposeFunc, typename QuickCheckFunc> bool normalized_decomposed( Iter first, Sentinel last, DecomposeFunc && decompose, QuickCheckFunc && quick_check_) noexcept { auto const check = normalized_quick_check(first, last, quick_check_); if (check == quick_check::maybe) { container::static_vector<uint32_t, 64> buffer; using buffer_iterator = container::static_vector<uint32_t, 64>::iterator; return normalize_to_decomposed_impl( first, last, buffer, decompose, [&first, last]( buffer_iterator buffer_first, buffer_iterator buffer_last) { while (first != last && buffer_first != buffer_last) { if (*first++ != *buffer_first++) return false; } return true; }); } return check == quick_check::yes; } template< typename Iter, typename Sentinel, typename DecomposeFunc, typename QuickCheckFunc> bool normalized_composed( Iter first, Sentinel last, DecomposeFunc && decompose, QuickCheckFunc && quick_check_) noexcept { auto const check = normalized_quick_check(first, last, quick_check_); if (check == quick_check::maybe) { container::static_vector<uint32_t, 64> buffer; using buffer_iterator = container::static_vector<uint32_t, 64>::iterator; return normalize_to_composed_impl<false>( first, last, buffer, decompose, quick_check_, [&first, last]( buffer_iterator buffer_first, buffer_iterator buffer_last) { while (first != last && buffer_first != buffer_last) { if (*first++ != *buffer_first++) return false; } return true; }); } return check == quick_check::yes; } } /** Writes sequence <code>[first, last)</code> in Unicode normalization form NFD to <code>out</code>. This function only participates in overload resolution if <code>CPIter</code> models the CPIter concept. */ template<typename CPIter, typename Sentinel, typename OutIter> inline auto normalize_to_nfd(CPIter first, Sentinel last, OutIter out) -> detail::cp_iter_ret_t<OutIter, CPIter> { return detail::normalize_to_decomposed( first, last, out, [](uint32_t cp) { return detail::canonical_decompose(cp); }); } /** Writes sequence <code>r</code> in Unicode normalization form NFD to <code>out</code>. */ template<typename CPRange, typename OutIter> inline OutIter normalize_to_nfd(CPRange const & r, OutIter out) { return normalize_to_nfd(std::begin(r), std::end(r), out); } /** Writes sequence <code>[first, last)</code> in Unicode normalization form NFKD to <code>out</code>. This function only participates in overload resolution if <code>CPIter</code> models the CPIter concept. */ template<typename CPIter, typename Sentinel, typename OutIter> inline auto normalize_to_nfkd(CPIter first, Sentinel last, OutIter out) -> detail::cp_iter_ret_t<OutIter, CPIter> { return detail::normalize_to_decomposed( first, last, out, [](uint32_t cp) { return detail::compatible_decompose(cp); }); } /** Writes sequence <code>r</code> in Unicode normalization form NFKD to * <code>out</code>. */ template<typename CPRange, typename OutIter> inline OutIter normalize_to_nfkd(CPRange const & r, OutIter out) { return normalize_to_nfkd(std::begin(r), std::end(r), out); } /** Writes sequence <code>[first, last)</code> in Unicode normalization form NFC to <code>out</code>. This function only participates in overload resolution if <code>CPIter</code> models the CPIter concept. */ template<typename CPIter, typename Sentinel, typename OutIter> inline auto normalize_to_nfc(CPIter first, Sentinel last, OutIter out) -> detail::cp_iter_ret_t<OutIter, CPIter> { return detail::normalize_to_composed<false>( first, last, out, [](uint32_t cp) { return detail::canonical_decompose(cp); }, [](uint32_t cp) { return detail::quick_check_nfc_code_point(cp); }); } /** Writes sequence <code>r</code> in Unicode normalization form NFC to * <code>out</code>. */ template<typename CPRange, typename OutIter> inline OutIter normalize_to_nfc(CPRange const & r, OutIter out) { return normalize_to_nfc(std::begin(r), std::end(r), out); } /** Writes sequence <code>[first, last)</code> in Unicode normalization form NFKC to <code>out</code>. This function only participates in overload resolution if <code>CPIter</code> models the CPIter concept. */ template<typename CPIter, typename Sentinel, typename OutIter> inline auto normalize_to_nfkc(CPIter first, Sentinel last, OutIter out) -> detail::cp_iter_ret_t<OutIter, CPIter> { return detail::normalize_to_composed<false>( first, last, out, [](uint32_t cp) { return detail::compatible_decompose(cp); }, [](uint32_t cp) { return detail::quick_check_nfkc_code_point(cp); }); } /** Writes sequence <code>r</code> in Unicode normalization form NFKC to * <code>out</code>. */ template<typename CPRange, typename OutIter> inline OutIter normalize_to_nfkc(CPRange const & r, OutIter out) { return normalize_to_nfkc(std::begin(r), std::end(r), out); } /** Returns true iff the given sequence of code points is normalized NFD. This function only participates in overload resolution if <code>CPIter</code> models the CPIter concept. */ template<typename CPIter, typename Sentinel> auto normalized_nfd(CPIter first, Sentinel last) noexcept -> detail::cp_iter_ret_t<bool, CPIter> { return detail::normalized_decomposed( first, last, [](uint32_t cp) { return detail::canonical_decompose(cp); }, [](uint32_t cp) { return detail::quick_check_nfd_code_point(cp); }); } /** Returns true iff the given range of code points is normalized NFD. */ template<typename CPRange> bool normalized_nfd(CPRange const & r) noexcept { return normalized_nfd(std::begin(r), std::end(r)); } /** Returns true iff the given sequence of code points is normalized NFKD. This function only participates in overload resolution if <code>CPIter</code> models the CPIter concept. */ template<typename CPIter, typename Sentinel> auto normalized_nfkd(CPIter first, Sentinel last) noexcept -> detail::cp_iter_ret_t<bool, CPIter> { return detail::normalized_decomposed( first, last, [](uint32_t cp) { return detail::compatible_decompose(cp); }, [](uint32_t cp) { return detail::quick_check_nfkd_code_point(cp); }); } /** Returns true iff the given range of code points is normalized NFKD. */ template<typename CPRange> bool normalized_nfkd(CPRange const & r) noexcept { return normalized_nfkd(std::begin(r), std::end(r)); } /** Returns true iff the given sequence of code points is normalized NFC. This function only participates in overload resolution if <code>CPIter</code> models the CPIter concept. */ template<typename CPIter, typename Sentinel> auto normalized_nfc(CPIter first, Sentinel last) noexcept -> detail::cp_iter_ret_t<bool, CPIter> { return detail::normalized_composed( first, last, [](uint32_t cp) { return detail::canonical_decompose(cp); }, [](uint32_t cp) { return detail::quick_check_nfc_code_point(cp); }); } /** Returns true iff the given range of code points is normalized NFC. */ template<typename CPRange> bool normalized_nfc(CPRange const & r) noexcept { return normalized_nfc(std::begin(r), std::end(r)); } /** Returns true iff the given sequence of code points is normalized NFKC. This function only participates in overload resolution if <code>CPIter</code> models the CPIter concept. */ template<typename CPIter, typename Sentinel> auto normalized_nfkc(CPIter first, Sentinel last) noexcept -> detail::cp_iter_ret_t<bool, CPIter> { return detail::normalized_composed( first, last, [](uint32_t cp) { return detail::compatible_decompose(cp); }, [](uint32_t cp) { return detail::quick_check_nfkc_code_point(cp); }); } /** Returns true iff the given range of code points is normalized NFKC. */ template<typename CPRange> bool normalized_nfkc(CPRange const & r) noexcept { return normalized_nfkc(std::begin(r), std::end(r)); } /** Returns true iff the given sequence of code points is in an FCD form. This function only participates in overload resolution if <code>CPIter</code> models the CPIter concept. */ template<typename CPIter, typename Sentinel> auto fcd_form(CPIter first, Sentinel last) noexcept -> detail::cp_iter_ret_t<bool, CPIter> { // http://www.unicode.org/notes/tn5/#FCD_Test int prev_ccc = 0; while (first != last) { auto const cp = *first; auto const decomp = detail::canonical_decompose(cp); auto const ccc = detail::ccc(*decomp.begin()); if (ccc && ccc < prev_ccc) return false; prev_ccc = decomp.size_ == 1 ? ccc : detail::ccc(*(decomp.end() - 1)); ++first; } return true; } /** Returns true iff the given range of code points is in an FCD form. */ template<typename CPRange> bool fcd_form(CPRange const & r) noexcept { return fcd_form(std::begin(r), std::end(r)); } /** Writes sequence <code>[first, last)</code> in normalization form FCC to <code>out</code>. This function only participates in overload resolution if <code>CPIter</code> models the CPIter concept. \see https://unicode.org/notes/tn5 */ template<typename CPIter, typename Sentinel, typename OutIter> inline auto normalize_to_fcc(CPIter first, Sentinel last, OutIter out) -> detail::cp_iter_ret_t<OutIter, CPIter> { return detail::normalize_to_composed<true>( first, last, out, [](uint32_t cp) { return detail::canonical_decompose(cp); }, [](uint32_t cp) { return detail::quick_check_nfc_code_point(cp); }); } /** Writes sequence <code>r</code> in normalization form FCC to <code>out</code>. \see https://unicode.org/notes/tn5 */ template<typename CPRange, typename OutIter> inline OutIter normalize_to_fcc(CPRange const & r, OutIter out) { return normalize_to_fcc(std::begin(r), std::end(r), out); } }} #endif
36.330849
89
0.533145
jan-moeller
a287bde9e3020f15b712a9521be0a95bb82b6aea
277
cpp
C++
A-set/405A. Gravity Flip/405A. Gravity Flip.cpp
AhmedRamadan6/Codeforces
efd61d610243160381491f44702b5634b004e5fb
[ "MIT" ]
1
2020-04-13T00:45:25.000Z
2020-04-13T00:45:25.000Z
A-set/405A. Gravity Flip/405A. Gravity Flip.cpp
AhmedRamadan6/Codeforces
efd61d610243160381491f44702b5634b004e5fb
[ "MIT" ]
null
null
null
A-set/405A. Gravity Flip/405A. Gravity Flip.cpp
AhmedRamadan6/Codeforces
efd61d610243160381491f44702b5634b004e5fb
[ "MIT" ]
null
null
null
#include <iostream> #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int c[n-1]; for (int i=0;i<n;i++) cin >> c[i]; sort(c,c+n); for (int i=0;i<n;i++) cout << c[i] << " " ; return 0; }
17.3125
30
0.418773
AhmedRamadan6
a2942b9f952745a967812b3fde5c4e6ddeac6068
12,519
cpp
C++
computation.cpp
hotzevzl/marxan
23ba3a0ada90e721c745b922363458bece3477dc
[ "MIT" ]
5
2021-02-16T07:50:47.000Z
2021-09-14T00:17:13.000Z
computation.cpp
hotzevzl/marxan
23ba3a0ada90e721c745b922363458bece3477dc
[ "MIT" ]
7
2021-02-17T00:03:09.000Z
2021-10-05T14:46:22.000Z
computation.cpp
hotzevzl/marxan
23ba3a0ada90e721c745b922363458bece3477dc
[ "MIT" ]
2
2020-10-02T18:08:17.000Z
2021-06-18T09:03:01.000Z
// All functions here should be unit and should not have dependencies on the core marxan files. #include <algorithm> #include "computation.hpp" #include "marxan.hpp" #include "utils.hpp" namespace marxan { // Sums all connectivity edges for a pu. double connectionCost1(const sconnections& connections, double cm, int asymmetricconnectivity) { double fcost; fcost = connections.fixedcost; for (const auto& p : connections.first) { if (asymmetricconnectivity) { if (p.connectionorigon) fcost += p.cost; } else { fcost += p.cost; } } return (fcost * cm); } /*** Counts the number of species missing from the reserve ****/ // compute the number of species whose representation fraction is less that the MISSLEVEL parameter int computeRepresentationMISSLEVEL(int spno, const vector<sspecies>& spec, double misslevel, double& shortfall, double& rMinimumProportionMet) { int i, isp = 0; double rProportionMet; shortfall = 0; rMinimumProportionMet = 1; for (i = 0; i < spno; i++) { checkAndUpdateTargetProportion(spec[i].target, spec[i].amount, shortfall, rMinimumProportionMet); // check regular target checkAndUpdateTargetProportion(spec[i].targetocc, spec[i].occurrence, shortfall, rMinimumProportionMet); // check occurence target if (spec[i].target) { if (spec[i].amount / spec[i].target < misslevel) { isp++; continue; } } if (spec[i].targetocc) { if ((double)spec[i].occurrence / (double)spec[i].targetocc < misslevel) { isp++; continue; } } if (spec[i].sepdistance && spec[i].separation < 3) { isp++; /* count species if not met separation and not already counted */ } } return(isp); } // compute connectivity total, in, edge, out for summary report void computeConnectivityIndices(double& rConnectivityTotal, double& rConnectivityIn, double& rConnectivityEdge, double& rConnectivityOut, int puno, const vector<int>& R, const vector<sconnections>& connections) // We record 4 categories for connectivity; // - total, all connections in the region // - in, all connections entirely within the reserve network (ie. both pu's in) // - edge, all connections on the edge of the reserve network (ie. one pu in & one pu out) // - out, all connections not captured in the reserve network (ie. both pu's out) // // Of these, we previously only recorded "edge", referring to it as boundary length. // The proportion of connections captured is given by; // in / total // // total = in + edge + out { int i; double rFixed; for (i = 0; i < puno; i++) { rFixed = connections[i].fixedcost; rConnectivityTotal += rFixed; if (R[i] == 1 || R[i] == 2) { // add to 'in' or 'edge' rConnectivityEdge += rFixed; for (sneighbour p : connections[i].first) { if (p.nbr > i) { if (R[p.nbr] == 1 || R[p.nbr] == 2) // add to 'in' rConnectivityIn += p.cost; else // add to 'edge' rConnectivityEdge += p.cost; // add to 'total' rConnectivityTotal += p.cost; } } } else { // add to 'out' or 'edge' rConnectivityOut += rFixed; for (sneighbour p : connections[i].first) { if (p.nbr > i) { if (R[p.nbr] == 1 || R[p.nbr] == 2) // add to 'edge' rConnectivityEdge += p.cost; else // add to 'out' rConnectivityOut += p.cost; // add to 'total' rConnectivityTotal += p.cost; } } } } } // Merging repeated area computation code. Recomputes TO, TA etc. from scratch. void computeOccurrencesAndAreas(int& puno, const vector<spustuff>& pu, const vector<spu>& SM, vector<int>& TotalOccurrences, vector<int>& TO_2, vector<int>& TO_3, vector<double>& TotalAreas, vector<double>& TA_2, vector<double>& TA_3) { int ism, isp; for (int ipu = 0; ipu < puno; ipu++) { if (pu[ipu].richness) { for (int i = 0; i < pu[ipu].richness; i++) { ism = pu[ipu].offset + i; isp = SM[ism].spindex; TotalOccurrences[isp]++; TotalAreas[isp] += SM[ism].amount; if (pu[ipu].status == 2) { TO_2[isp]++; TA_2[isp] += SM[ism].amount; } if (pu[ipu].status == 3) { TO_3[isp]++; TA_3[isp] += SM[ism].amount; } } } } } // Used in ReturnProbabilityAmounts1D and ReturnProbabilityAmounts2D void computeExpectedAndVariance(int ipu, const vector<spustuff>& pu, const vector<spu>& SM, vector<double>& variance, vector<double>& expected) { int i, ism, isp; if (pu[ipu].richness) { for (i = 0; i < pu[ipu].richness; i++) { ism = pu[ipu].offset + i; isp = SM[ism].spindex; if (SM[ism].amount) { expected[isp] += SM[ism].amount * (1 - pu[ipu].prob); variance[isp] += SM[ism].amount * SM[ism].amount * pu[ipu].prob * (1 - pu[ipu].prob); } } } } // Returns both index and species amount for a planning unit pair<int, double> returnAmountSpecAtPu(const spustuff& pu, const vector<spu>& SM, int iSpecIndex) { if (pu.richness > 0) { auto start_it = SM.begin() + pu.offset; auto end_it = start_it + pu.richness; auto spindex_cmp = [](const spu& lhs, int rhs) -> bool { return lhs.spindex < rhs; }; auto elem_it = std::lower_bound(start_it, end_it, iSpecIndex, spindex_cmp); if (elem_it != end_it && elem_it->spindex == iSpecIndex) { size_t index = elem_it - SM.begin(); return pair<int, double>(index, elem_it->amount); } } return pair<int, double>(-1, 0); } // Sums the total spec amount across all pu double computeTotalSpecAmtAllPu(const vector<spustuff>& PU, const vector<spu>& SM, int speciesInd) { double totalAmount = 0.0; for (int ipu = 0; ipu < PU.size(); ipu++) totalAmount += returnAmountSpecAtPu(PU[ipu], SM, speciesInd).second; return totalAmount; } // compute proportional target for species when prop target is specified // use the prop value from the conservation feature file to set a proportion target for species void computeSpecProp(int spno, vector<sspecies>& spec, int puno, const vector<spustuff>& pu, const vector<spu>& SM) { // compute and set target for species with a prop value for (int isp = 0; isp < spno; isp++) { if (spec[isp].prop > 0) { spec[isp].target = computeTotalSpecAmtAllPu(pu, SM, isp) * spec[isp].prop; } } } // Computes penalty for a species given a reserve, based on only fixed pu void computeFixedPenaltyForSpec(const vector<int>& R, const vector<spustuff>& pu, const vector<spu>& SM, const vector<sconnections>& connections, int spIndex, double& ftarget, int& itargetocc, double& penalty, double cm, int asymmetricconnectivity) { ftarget = 0, itargetocc = 0, penalty = 0; for (int j = 0; j < pu.size(); j++) { if (R[j] == 2) { ftarget += returnAmountSpecAtPu(pu[j], SM, spIndex).second; itargetocc++; penalty += computePlanningUnitValue(pu[j], connections[j], cm, asymmetricconnectivity); } } } // ********* Connection Cost Type 2 ************** // ** Requires R[]. imode2 = 0 there is no negative cost for removing connection, we are calling from ReserveCost // or 1 there is a negative cost for removing connection, we are calling from Annealing // imode = -1 we are removing the planning unit from a reserve, calling from Annealing // or 1 we are adding the planning unit to a reserve, or it is already in reserve // It seems that the behaviour of this function is undefined/unsupported if imode2=0 and imode=-1 double ConnectionCost2(const sconnections& connection, const vector<int>& R, int imode, int imode2, double cm, int asymmetricconnectivity, int fOptimiseConnectivityIn) { double fcost = connection.fixedcost * imode; int R_pu1; if (asymmetricconnectivity) { for (const sneighbour& p : connection.first) { if (imode2) // calling from Annealing { // determines if ipu is currently switched on or not // if imode==1 then we assume currently switched off, and will switch on. if (imode == 1) R_pu1 = 0; else R_pu1 = 1; if (p.connectionorigon) { if (R[p.nbr] == 0) { if (R_pu1 == 1) { fcost -= p.cost; } else { fcost += p.cost; } } } else { if (R[p.nbr] == 1 || R[p.nbr] == 2) { if (R_pu1 == 1) { fcost += p.cost; } else { fcost -= p.cost; } } } } else // calling from ReserveCost { if (R[p.nbr] == 0) if (p.connectionorigon) { fcost += p.cost; } } } } else { for (const sneighbour& p : connection.first) // treatment for symmetric connectivity { if (fOptimiseConnectivityIn == 1) { // optimise for "Connectivity In" if (R[p.nbr] == 1 || R[p.nbr] == 2) { fcost += imode * p.cost; } else { fcost += imode * imode2 * p.cost * -1; } } else { // optimise for "Connectivity Edge" if (R[p.nbr] == 1 || R[p.nbr] == 2) { fcost += imode * imode2 * p.cost * -1; } else { fcost += imode * p.cost; } } } } return (fcost * cm); } } // namespace marxan
35.974138
162
0.455627
hotzevzl
a2948dac22b52450e64e88418bbf4ea6981b03ad
442
cc
C++
src/interpreter/command/mc-cmd-list.cc
babynewton/mycurl
4701659ca5cb8b2f140ed07e9dc76764be3a9bc0
[ "MIT" ]
null
null
null
src/interpreter/command/mc-cmd-list.cc
babynewton/mycurl
4701659ca5cb8b2f140ed07e9dc76764be3a9bc0
[ "MIT" ]
null
null
null
src/interpreter/command/mc-cmd-list.cc
babynewton/mycurl
4701659ca5cb8b2f140ed07e9dc76764be3a9bc0
[ "MIT" ]
null
null
null
#include "command/mc-cmd-list.h" #include <cstdio> void mcCmdList::help(void){ fprintf(stdout, "Usage: list\n"); fprintf(stdout, " lists opend urls or alias\n"); } mcLanguageState mcCmdList::parse(mcScanner& scanner, mcIPerformer* performer){ mcToken token = scanner.tokenize(); if(token.id != MC_TOKEN_EOL) { fprintf(stderr, "invalid argument %s\n", token.buffer.c_str()); return MC_LANG_CONTINUE; } return performer->list(); }
26
78
0.717195
babynewton
a2948e60903235901f2f0b6f06b045b1eb45a3e8
19,455
cpp
C++
Source/BWEB/Station.cpp
Cmccrave/CMProtoBot
220cddaf41724004daf5aace5b48a07e28931279
[ "MIT" ]
32
2017-03-04T19:38:13.000Z
2022-03-16T02:03:01.000Z
libs/BWEB/Source/Station.cpp
krogenth/AdditionalPylons
60a2ba5503857de9c6aafa5261e911f39ad0ccf1
[ "MIT" ]
39
2022-01-10T22:23:20.000Z
2022-03-31T03:56:21.000Z
libs/BWEB/Source/Station.cpp
krogenth/AdditionalPylons
60a2ba5503857de9c6aafa5261e911f39ad0ccf1
[ "MIT" ]
8
2017-12-26T23:47:18.000Z
2021-09-15T04:25:28.000Z
#include "BWEB.h" using namespace std; using namespace BWAPI; namespace BWEB { namespace { vector<Station> stations; vector<const BWEM::Base *> mainBases; vector<const BWEM::Base *> natBases; } void Station::addResourceReserves() { const auto addReserve = [&](Unit resource) { TilePosition start(resource->getPosition()); vector<TilePosition> directions{ {1,0}, {-1,0}, {0, 1}, {0,-1} }; auto end = (base->Center() * 5 / 6) + (resourceCentroid / 6); // Get the starting tile auto distClosest = DBL_MAX; for (int x = resource->getTilePosition().x; x < resource->getTilePosition().x + resource->getType().tileWidth(); x++) { for (int y = resource->getTilePosition().y; y < resource->getTilePosition().y + resource->getType().tileHeight(); y++) { auto tile = TilePosition(x, y); auto center = Position(tile) + Position(16, 16); auto dist = center.getDistance(resourceCentroid); if (dist < distClosest) { start = tile; distClosest = dist; } } } TilePosition next = start; while (next != TilePosition(end)) { auto distBest = DBL_MAX; start = next; for (auto &t : directions) { auto tile = start + t; auto pos = Position(tile) + Position(16, 16); if (!tile.isValid()) continue; auto dist = pos.getDistance(end); if (dist <= distBest) { next = tile; distBest = dist; } } if (next.isValid()) { Map::addReserve(next, 1, 1); // Remove any defenses in the way of a geyser if (!resource->getType().isMineralField()) { for (auto &def : defenses) { if (next.x >= def.x && next.x < def.x + 2 && next.y >= def.y && next.y < def.y + 2) { defenses.erase(def); break; } } } } } }; // Add reserved tiles for (auto &m : base->Minerals()) { Map::addReserve(m->TopLeft(), 2, 1); addReserve(m->Unit()); } for (auto &g : base->Geysers()) { Map::addReserve(g->TopLeft(), 4, 2); addReserve(g->Unit()); } } void Station::initialize() { auto cnt = 0; // Resource and defense centroids for (auto &mineral : base->Minerals()) { resourceCentroid += mineral->Pos(); cnt++; } if (cnt > 0) defenseCentroid = resourceCentroid / cnt; for (auto &gas : base->Geysers()) { defenseCentroid = (defenseCentroid + gas->Pos()) / 2; resourceCentroid += gas->Pos(); cnt++; } if (cnt > 0) resourceCentroid = resourceCentroid / cnt; Map::addUsed(base->Location(), Broodwar->self()->getRace().getResourceDepot()); } void Station::findChoke() { // Only find a Chokepoint for mains or naturals if (!main && !natural) return; // Get closest partner base auto distBest = DBL_MAX; for (auto &potentialPartner : (main ? natBases : mainBases)) { auto dist = potentialPartner->Center().getDistance(base->Center()); if (dist < distBest) { partnerBase = potentialPartner; distBest = dist; } } if (!partnerBase) return; if (main && !Map::mapBWEM.GetPath(partnerBase->Center(), base->Center()).empty()) { choke = Map::mapBWEM.GetPath(partnerBase->Center(), base->Center()).front(); // Partner only has one chokepoint means we have a shared choke with this path if (partnerBase->GetArea()->ChokePoints().size() == 1) choke = Map::mapBWEM.GetPath(partnerBase->Center(), base->Center()).back(); } else { // Only one chokepoint in this area if (base->GetArea()->ChokePoints().size() == 1) { choke = base->GetArea()->ChokePoints().front(); return; } set<BWEM::ChokePoint const *> nonChokes; for (auto &choke : Map::mapBWEM.GetPath(partnerBase->Center(), base->Center())) nonChokes.insert(choke); auto distBest = DBL_MAX; const BWEM::Area* second = nullptr; // Iterate each neighboring area to get closest to this natural area for (auto &area : base->GetArea()->AccessibleNeighbours()) { auto center = area->Top(); const auto dist = Position(center).getDistance(Map::mapBWEM.Center()); bool wrongArea = false; for (auto &choke : area->ChokePoints()) { if ((!choke->Blocked() && choke->Pos(choke->end1).getDistance(choke->Pos(choke->end2)) <= 2) || nonChokes.find(choke) != nonChokes.end()) { wrongArea = true; } } if (wrongArea) continue; if (center.isValid() && dist < distBest) { second = area; distBest = dist; } } distBest = DBL_MAX; for (auto &c : base->GetArea()->ChokePoints()) { if (c->Center() == BWEB::Map::getMainChoke()->Center() || c->Blocked() || c->Geometry().size() <= 3 || (c->GetAreas().first != second && c->GetAreas().second != second)) continue; const auto dist = Position(c->Center()).getDistance(Position(partnerBase->Center())); if (dist < distBest) { choke = c; distBest = dist; } } } if (choke && !main) defenseCentroid = Position(choke->Center()); } void Station::findSecondaryLocations() { if (Broodwar->self()->getRace() != Races::Zerg) return; auto cnt = 0; if (main) cnt = 1; if (!main && !natural) cnt = 2; for (int i = 0; i < cnt; i++) { auto distBest = DBL_MAX; auto tileBest = TilePositions::Invalid; for (auto x = base->Location().x - 4; x <= base->Location().x + 4; x++) { for (auto y = base->Location().y - 3; y <= base->Location().y + 3; y++) { auto tile = TilePosition(x, y); auto center = Position(tile) + Position(64, 48); auto dist = center.getDistance(resourceCentroid); if (dist < distBest && Map::isPlaceable(Broodwar->self()->getRace().getResourceDepot(), tile)) { distBest = dist; tileBest = tile; } } } if (tileBest.isValid()) { secondaryLocations.insert(tileBest); Map::addUsed(tileBest, Broodwar->self()->getRace().getResourceDepot()); } } } void Station::findDefenses() { vector<TilePosition> basePlacements; vector<TilePosition> geyserPlacements ={ {-2, -2}, {-2, 0}, {-2, 2}, {0, -2}, {0, 2}, {2, -2}, {2, 2}, {4, -2}, {4, 0}, {4, 2} }; auto here = base->Location(); auto defenseType = UnitTypes::None; if (Broodwar->self()->getRace() == Races::Protoss) defenseType = UnitTypes::Protoss_Photon_Cannon; if (Broodwar->self()->getRace() == Races::Terran) defenseType = UnitTypes::Terran_Missile_Turret; if (Broodwar->self()->getRace() == Races::Zerg) defenseType = UnitTypes::Zerg_Creep_Colony; // Get angle of chokepoint if (choke && base && (main || natural)) { auto dist = min(480.0, getBase()->Center().getDistance(Position(choke->Center()))); baseAngle = fmod(Map::getAngle(make_pair(getBase()->Center(), Position(choke->Center()) + Position(4, 4))), 3.14); chokeAngle = fmod(Map::getAngle(make_pair(Position(choke->Pos(choke->end1)), Position(choke->Pos(choke->end2)))), 3.14); auto diff = baseAngle - chokeAngle; diff > 0.7 ? baseAngle -= 1.57 : baseAngle += 1.57; defenseAngle = max(0.0, (baseAngle * (dist / 480.0)) + (chokeAngle * (480.0 - dist) / 480.0)); if (base->GetArea()->ChokePoints().size() >= 3) { const BWEM::ChokePoint * validSecondChoke = nullptr; for (auto &otherChoke : base->GetArea()->ChokePoints()) { if (choke == otherChoke) continue; if ((choke->GetAreas().first == otherChoke->GetAreas().first && choke->GetAreas().second == otherChoke->GetAreas().second) || (choke->GetAreas().first == otherChoke->GetAreas().second && choke->GetAreas().second == otherChoke->GetAreas().first)) validSecondChoke = otherChoke; } if (validSecondChoke) defenseAngle = (Map::getAngle(make_pair(Position(choke->Center()), Position(validSecondChoke->Center()))) + Map::getAngle(make_pair(Position(choke->Pos(choke->end1)), Position(choke->Pos(choke->end2))))) / 2.0; } } else { defenseCentroid = BWEB::Map::mapBWEM.Center(); defenseAngle = fmod(Map::getAngle(make_pair(Position(getBase()->Center()), defenseCentroid)), 3.14) + 1.57; } // Round to nearest pi/8 rads auto nearestEight = int(round(defenseAngle / 0.3926991)); auto angle = nearestEight % 8; // Generate defenses if (main) basePlacements ={ {-2, -2}, {-2, 1}, {1, -2} }; else { if (angle == 0) basePlacements ={ {-2, 2}, {-2, 0}, {-2, -2}, {0, 3}, {0, -2}, {2, -2}, {4, -2}, {4, 0}, {4, 2} }; // 0/8 if (angle == 1 || angle == 7) basePlacements ={ {-2, 3}, {-2, 1}, {-2, -1}, {0, -2}, {1, 3}, {2, -2}, {4, -1}, {4, 1}, }; // pi/8 if (angle == 2 || angle == 6) basePlacements ={ {-2, 2}, {-2, 0}, {0, 3}, {0, -2}, {2, -2}, {4, -2}, {4, 0} }; // pi/4 if (angle == 3 || angle == 5) basePlacements ={ {-2, 2}, {-2, 0}, {-1, -2}, {0, 3}, {1, -2}, {2, 3}, {3, -2}, {4, 0} }; // 3pi/8 if (angle == 4) basePlacements ={ {-2, 2}, {-2, 0}, {-2, -2}, {0, 3}, {0, -2}, {2, 3}, {2, -2}, {4, 3}, {4, -2} }; // pi/2 } // Flip them vertically / horizontally as needed if (base->Center().y < defenseCentroid.y) { for (auto &placement : basePlacements) placement.y = -(placement.y - 1); } if (base->Center().x < defenseCentroid.x) { for (auto &placement : basePlacements) placement.x = -(placement.x - 2); } // Add scanner addon for Terran if (Broodwar->self()->getRace() == Races::Terran) { auto scannerTile = here + TilePosition(4, 1); defenses.insert(scannerTile); Map::addUsed(scannerTile, defenseType); } // Add a defense near each base placement if possible for (auto &placement : basePlacements) { auto tile = base->Location() + placement; if (Map::isPlaceable(defenseType, tile)) { defenses.insert(tile); Map::addUsed(tile, defenseType); } } // Add geyser defenses if (main) { for (auto &geyser : base->Geysers()) { for (auto &placement : geyserPlacements) { auto tile = geyser->TopLeft() + placement; auto center = Position(tile) + Position(16, 16); if (center.getDistance(base->Center()) > geyser->Pos().getDistance(base->Center()) && Map::isPlaceable(defenseType, tile)) { defenses.insert(tile); Map::addUsed(tile, defenseType); } } } } } void Station::draw() { int color = Broodwar->self()->getColor(); int textColor = color == 185 ? textColor = Text::DarkGreen : Broodwar->self()->getTextColor(); // Draw boxes around each feature for (auto &tile : defenses) { Broodwar->drawBoxMap(Position(tile), Position(tile) + Position(65, 65), color); Broodwar->drawTextMap(Position(tile) + Position(4, 52), "%cS", textColor); } // Draw corresponding choke if (choke && base && (main || natural)) { if (base->GetArea()->ChokePoints().size() >= 3) { const BWEM::ChokePoint * validSecondChoke = nullptr; for (auto &otherChoke : base->GetArea()->ChokePoints()) { if (choke == otherChoke) continue; if ((choke->GetAreas().first == otherChoke->GetAreas().first && choke->GetAreas().second == otherChoke->GetAreas().second) || (choke->GetAreas().first == otherChoke->GetAreas().second && choke->GetAreas().second == otherChoke->GetAreas().first)) validSecondChoke = choke; } if (validSecondChoke) { Broodwar->drawLineMap(Position(validSecondChoke->Pos(validSecondChoke->end1)), Position(validSecondChoke->Pos(validSecondChoke->end2)), Colors::Grey); Broodwar->drawLineMap(base->Center(), Position(validSecondChoke->Center()), Colors::Grey); Broodwar->drawLineMap(Position(choke->Center()), Position(validSecondChoke->Center()), Colors::Grey); } } Broodwar->drawLineMap(Position(choke->Pos(choke->end1)), Position(choke->Pos(choke->end2)), Colors::Grey); Broodwar->drawLineMap(base->Center(), Position(choke->Center()), Colors::Grey); } // Label angle Broodwar->drawTextMap(base->Center() - Position(0, 16), "%c%.2f", Text::White, baseAngle); Broodwar->drawTextMap(base->Center(), "%c%.2f", Text::White, chokeAngle); Broodwar->drawTextMap(base->Center() + Position(0, 16), "%c%.2f", Text::White, defenseAngle); Broodwar->drawBoxMap(Position(base->Location()), Position(base->Location()) + Position(129, 97), color); Broodwar->drawTextMap(Position(base->Location()) + Position(4, 84), "%cS", textColor); for (auto &location : secondaryLocations) { Broodwar->drawBoxMap(Position(location), Position(location) + Position(129, 97), color); Broodwar->drawTextMap(Position(location) + Position(4, 84), "%cS", textColor); } } void Station::cleanup() { // Remove used on defenses for (auto &tile : defenses) { Map::removeUsed(tile, 2, 2); Map::addReserve(tile, 2, 2); } // Remove used on secondary locations for (auto &tile : secondaryLocations) { Map::removeUsed(tile, 4, 3); Map::addReserve(tile, 4, 3); } // Remove used on main location Map::removeUsed(getBase()->Location(), 4, 3); Map::addReserve(getBase()->Location(), 4, 3); } } namespace BWEB::Stations { void findStations() { // Find all main bases for (auto &area : Map::mapBWEM.Areas()) { for (auto &base : area.Bases()) { if (base.Starting()) mainBases.push_back(&base); } } // Find all natural bases for (auto &main : mainBases) { const BWEM::Base * baseBest = nullptr; auto distBest = DBL_MAX; for (auto &area : Map::mapBWEM.Areas()) { for (auto &base : area.Bases()) { // Must have gas, be accesible and at least 5 mineral patches if (base.Starting() || base.Geysers().empty() || base.GetArea()->AccessibleNeighbours().empty() || base.Minerals().size() < 5) continue; const auto dist = Map::getGroundDistance(base.Center(), main->Center()); if (dist < distBest) { distBest = dist; baseBest = &base; } } } // Store any natural we found if (baseBest) natBases.push_back(baseBest); } // Create Stations for (auto &area : Map::mapBWEM.Areas()) { for (auto &base : area.Bases()) { auto isMain = find(mainBases.begin(), mainBases.end(), &base) != mainBases.end(); auto isNatural = find(natBases.begin(), natBases.end(), &base) != natBases.end(); // Add to our station lists Station newStation(&base, isMain, isNatural); stations.push_back(newStation); } } } void draw() { for (auto &station : Stations::getStations()) station.draw(); } Station * getClosestStation(TilePosition here) { auto distBest = DBL_MAX; Station* bestStation = nullptr; for (auto &station : stations) { const auto dist = here.getDistance(station.getBase()->Location()); if (dist < distBest) { distBest = dist; bestStation = &station; } } return bestStation; } Station * getClosestMainStation(TilePosition here) { auto distBest = DBL_MAX; Station * bestStation = nullptr; for (auto &station : stations) { if (!station.isMain()) continue; const auto dist = here.getDistance(station.getBase()->Location()); if (dist < distBest) { distBest = dist; bestStation = &station; } } return bestStation; } Station * getClosestNaturalStation(TilePosition here) { auto distBest = DBL_MAX; Station* bestStation = nullptr; for (auto &station : stations) { if (!station.isNatural()) continue; const auto dist = here.getDistance(station.getBase()->Location()); if (dist < distBest) { distBest = dist; bestStation = &station; } } return bestStation; } vector<Station>& getStations() { return stations; } }
38.448617
230
0.486199
Cmccrave
a29558a201889d425c1ff0f0cea1b6f5d0a907fa
125
cpp
C++
chapter-12/12.1.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
chapter-12/12.1.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
chapter-12/12.1.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
// b1 has 4 elements; // b2's code block has ended, os b2 is destroyed, there is no point in saying how many elements in b2.
41.666667
102
0.72
zero4drift
a299120c0bfba1ae5fd788d09a6a17dd01e38fb5
1,175
cpp
C++
vsedit/src/script_editor/script_completer.cpp
jkotra/vapoursynth-editor
ee028830d5d390bd3fbde5577577444c011f4987
[ "MIT" ]
null
null
null
vsedit/src/script_editor/script_completer.cpp
jkotra/vapoursynth-editor
ee028830d5d390bd3fbde5577577444c011f4987
[ "MIT" ]
null
null
null
vsedit/src/script_editor/script_completer.cpp
jkotra/vapoursynth-editor
ee028830d5d390bd3fbde5577577444c011f4987
[ "MIT" ]
null
null
null
#include "script_completer.h" //============================================================================== ScriptCompleter::ScriptCompleter(QAbstractItemModel *a_pModel, QObject *a_pParent) : QCompleter(a_pModel, a_pParent) { } //============================================================================== ScriptCompleter::~ScriptCompleter() { } //============================================================================== QString ScriptCompleter::pathFromIndex(const QModelIndex &a_index) const { if (!a_index.isValid()) { return QString(); } QString path = model()->data(a_index, Qt::EditRole).toString(); QModelIndex index = a_index; while (index.parent().isValid()) { index = index.parent(); path.prepend('.'); path.prepend(model()->data(index, Qt::EditRole).toString()); } return path; } //============================================================================== QStringList ScriptCompleter::splitPath(const QString &a_path) const { return a_path.split('.'); } //==============================================================================
25.543478
86
0.417872
jkotra
9478ba14e0f0a379ffba877339acfe10100a8e16
522
cpp
C++
gongen/src/version.cpp
Bitrium-Games/gongen
0a4a39d19e851c85d8e6a99b9a054c59ec32551d
[ "MIT" ]
3
2021-07-01T13:59:45.000Z
2021-07-07T13:53:09.000Z
gongen/src/version.cpp
Bitrium-Games/gongen
0a4a39d19e851c85d8e6a99b9a054c59ec32551d
[ "MIT" ]
null
null
null
gongen/src/version.cpp
Bitrium-Games/gongen
0a4a39d19e851c85d8e6a99b9a054c59ec32551d
[ "MIT" ]
2
2021-06-21T17:45:20.000Z
2021-06-21T19:22:19.000Z
#include <gen/version.hpp> #undef ERROR gen::gongen_version::gongen_version(uint16 milestone, uint16 major, uint16 minor, uint16 patch) : milestone(milestone), major(major), minor(minor), patch(patch) { } gen::string gen::gongen_version::toString() const { gen::string result; result.append(std::to_string(milestone)); result.append("."); result.append(std::to_string(major)); result.append("."); result.append(std::to_string(minor)); result.append("."); result.append(std::to_string(patch)); return result; }
27.473684
162
0.726054
Bitrium-Games
9478bf286211f52fd3d102c698c510a47899f840
3,938
cpp
C++
source/block.cpp
theKlanc/Z3
97c28f31483d1d5c8c7d1aa61155b256b3d4094a
[ "MIT" ]
4
2020-08-09T20:34:28.000Z
2021-07-22T23:30:40.000Z
source/block.cpp
theKlanc/Z3
97c28f31483d1d5c8c7d1aa61155b256b3d4094a
[ "MIT" ]
5
2020-02-18T23:19:14.000Z
2020-02-18T23:26:24.000Z
source/block.cpp
theKlanc/Z3
97c28f31483d1d5c8c7d1aa61155b256b3d4094a
[ "MIT" ]
null
null
null
#include <iostream> #include "services.hpp" #include "block.hpp" #include "json.hpp" using nlohmann::json; blockRotation operator++(blockRotation& a, int) { return a = (blockRotation)((static_cast<int>(a) + 1) % 4); } blockRotation operator--(blockRotation& a, int) { return a = (blockRotation)(( static_cast<int>(a) + 3) % 4); } bool baseBlock::operator==(const baseBlock& right) { return ID == right.ID; } void baseBlock::loadTerrainTable() { terrainTable.clear(); std::ifstream terrainTableFile(HI2::getDataPath().append("blockTable.json")); json j; terrainTableFile >> j; j.get_to(baseBlock::terrainTable); metaBlock::nullBlock.base = &baseBlock::terrainTable[0]; } reactphysics3d::Quaternion metaBlock::getRotationQuat() const { //return rp3d::Quaternion::identity(); double r = M_PI*0.5*(float) rotation; if(flip) r+=M_PI; double cz = cos(r*0.5); double sz = sin(r*0.5); rp3d::Quaternion q; q.w = cz; q.x = 0; q.y = 0; q.z = sz; return q; } bool metaBlock::operator==(const metaBlock& right) const { if(base->ID == 0 && right.base->ID == 0) return true; if (saveMeta == false && saveMeta == false) return base == right.base; return base == right.base && rotation == right.rotation && flip == right.flip; } std::ostream& operator<<(std::ostream& os, const metaBlock& m) { if (m.saveMeta) { return os << m.base->ID << ' ' << m.saveMeta << ' ' << static_cast<int>(m.rotation) << ' ' << m.flip; } else { return os << m.base->ID << ' ' << m.saveMeta; } } std::ostream& operator<<(std::ostream& os, const std::vector<metaBlock>& m) { metaBlock lastBlock = m[0]; unsigned accumulatedLength = 0; for (const metaBlock& b : m) { if (b != lastBlock) { os << lastBlock << ' ' << accumulatedLength << std::endl; lastBlock = b; accumulatedLength = 1; } else { accumulatedLength++; } } return os << lastBlock << ' ' << accumulatedLength << std::endl; } std::istream& operator>>(std::istream& is, std::vector<metaBlock>& m) { m.clear(); m.resize(0); unsigned blockID; blockRotation rotation; bool flip; bool savedMeta; unsigned length; std::string input; while (is >> input) { blockID = std::stoi(input); is >> input; savedMeta = std::stoi(input); if (savedMeta) { is >> input; rotation = (blockRotation)std::stoi(input); is >> flip; } is >> input; length = std::stoi(input); for (int i = 0; i < length; ++i) { m.push_back({ &baseBlock::terrainTable[blockID],(savedMeta ? rotation : (blockRotation)(rand() % 4)), (savedMeta ? flip : false),savedMeta }); } } return is; } void to_json(nlohmann::json& j, const baseBlock& b) { j = json{ {"name",b.name},{"ID",b.ID},{"visible",b.visible},{"solid",b.solid},{"opaque",b.opaque},{"mass",b.mass} }; if (b.spr != nullptr) { j.push_back({ "frames",b.spr->getAllFrames() }); } } void from_json(const nlohmann::json& j, baseBlock& b) { j.at("name").get_to(b.name); j.at("ID").get_to(b.ID); j.at("visible").get_to(b.visible); j.at("solid").get_to(b.solid); j.at("opaque").get_to(b.opaque); j.at("mass").get_to(b.mass); std::vector<frame> frames; if (j.contains("sprite")) { for (const nlohmann::json& element : j.at("sprite").at("frames")) { frames.push_back(element.get<frame>()); } b.spr = Services::graphics.loadSprite(b.name, "spritesheet", frames); } if(j.contains("collider")){ b.collider = j.at("collider").get<colliderType>(); } } std::vector<baseBlock> baseBlock::terrainTable; metaBlock metaBlock::nullBlock; void to_json(nlohmann::json &j, const metaBlock &b) { j = nlohmann::json{{"baseID",b.base->ID},{"flip",b.flip},{"rotation",b.rotation},{"save",b.saveMeta}}; } void from_json(const nlohmann::json &j, metaBlock &b) { b.base = &baseBlock::terrainTable[j.at("baseID").get<unsigned>()]; b.flip = j.at("flip").get<bool>(); b.rotation = j.at("rotation").get<blockRotation>(); b.saveMeta = j.at("save").get<bool>(); }
23.722892
145
0.636872
theKlanc
947a23c26e6596b74361c63d2aa235d8f1d1bf0f
361
cpp
C++
nodelibpd.cpp
teropa/node-libpd
3a07bb10fe7080473a4579ba851746cd9d0d72a2
[ "BSD-3-Clause" ]
1
2021-05-04T16:34:59.000Z
2021-05-04T16:34:59.000Z
nodelibpd.cpp
teropa/node-libpd
3a07bb10fe7080473a4579ba851746cd9d0d72a2
[ "BSD-3-Clause" ]
null
null
null
nodelibpd.cpp
teropa/node-libpd
3a07bb10fe7080473a4579ba851746cd9d0d72a2
[ "BSD-3-Clause" ]
null
null
null
#include "src/NodePd.hpp" using v8::FunctionTemplate; namespace nodePd { // NativeExtension.cc represents the top level of the module. // C++ constructs that are exposed to javascript are exported here NAN_MODULE_INIT(InitAll) { // Passing target down to the next NAN_MODULE_INIT NodePd::Init(target); } NODE_MODULE(nodelibpd, InitAll) }; // namespace
21.235294
66
0.756233
teropa
947a85f61825eec5c0801f30004ef88198c36edb
7,756
cpp
C++
tests/test_local_ham.cpp
chaeyeunpark/ExactDiagonalization
c93754e724486cc68453399c5dda6a2dadf45cb8
[ "MIT" ]
1
2021-04-24T08:47:05.000Z
2021-04-24T08:47:05.000Z
tests/test_local_ham.cpp
chaeyeunpark/ExactDiagonalization
c93754e724486cc68453399c5dda6a2dadf45cb8
[ "MIT" ]
1
2021-09-28T19:02:14.000Z
2021-09-28T19:02:14.000Z
tests/test_local_ham.cpp
chaeyeunpark/ExactDiagonalization
c93754e724486cc68453399c5dda6a2dadf45cb8
[ "MIT" ]
1
2020-03-22T18:59:11.000Z
2020-03-22T18:59:11.000Z
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <Eigen/Dense> #include <Eigen/Eigenvalues> #include <unsupported/Eigen/KroneckerProduct> #include <Spectra/MatOp/SparseSymMatProd.h> #include <Spectra/SymEigsSolver.h> #include <iostream> #include <cassert> #include <random> #include <algorithm> #include "edlib/EDP/LocalHamiltonian.hpp" #include "edlib/EDP/ConstructSparseMat.hpp" Eigen::SparseMatrix<double> getSX() { Eigen::SparseMatrix<double> res(2,2); res.insert(0,1) = 1.0; res.insert(1,0) = 1.0; res.makeCompressed(); return res; } Eigen::SparseMatrix<std::complex<double> > getSY() { Eigen::SparseMatrix<std::complex<double> > res(2,2); constexpr std::complex<double> I(0., 1.); res.insert(0,1) = -I; res.insert(1,0) = I; res.makeCompressed(); return res; } Eigen::SparseMatrix<double> getSZ() { Eigen::SparseMatrix<double> res(2,2); res.insert(0,0) = 1.0; res.insert(1,1) = -1.0; res.makeCompressed(); return res; } template<typename T> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> twoQubitOp(int N, int pos1, int pos2, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v1, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v2) { using namespace Eigen; const uint32_t dim = (1<<N); assert(pos1 < pos2); Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> res(1,1); res(0,0) = 1.0; for(int i = 0; i < pos1; i++) { res = Eigen::kroneckerProduct(MatrixXd::Identity(2,2), res).eval(); } res = Eigen::kroneckerProduct(v1, res).eval(); for(int i = pos1+1; i < pos2; i++) { res = Eigen::kroneckerProduct(MatrixXd::Identity(2,2), res).eval(); } res = Eigen::kroneckerProduct(v2, res).eval(); for(int i = pos2+1; i < N; i++) { res = Eigen::kroneckerProduct(MatrixXd::Identity(2,2), res).eval(); } return res; } template<typename T> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> singleQubitOp(int N, int pos, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v) { using namespace Eigen; const uint32_t dim = (1<<N); using MatrixT = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> ; MatrixT res(1,1); res(0,0) = 1.0; for(int i = 0; i < pos; i++) { res = Eigen::kroneckerProduct(MatrixT::Identity(2,2), res).eval(); } res = Eigen::kroneckerProduct(v, res).eval(); for(int i = pos+1; i < N; i++) { res = Eigen::kroneckerProduct(MatrixT::Identity(2,2), res).eval(); } return res; } Eigen::SparseMatrix<double> getSXXYY() { Eigen::SparseMatrix<double> res(4,4); res.insert(1,2) = 2.0; res.insert(2,1) = 2.0; res.makeCompressed(); return res; } Eigen::SparseMatrix<double> getSXX() { Eigen::SparseMatrix<double> res(4,4); res.insert(0,3) = 1.0; res.insert(1,2) = 1.0; res.insert(2,1) = 1.0; res.insert(3,0) = 1.0; res.makeCompressed(); return res; } Eigen::SparseMatrix<double> getSYY() { Eigen::SparseMatrix<double> res(4,4); res.insert(0,3) = -1.0; res.insert(1,2) = 1.0; res.insert(2,1) = 1.0; res.insert(3,0) = -1.0; res.makeCompressed(); return res; } Eigen::SparseMatrix<double> getSZZ() { Eigen::SparseMatrix<double> res(4,4); res.insert(0,0) = 1.0; res.insert(1,1) = -1.0; res.insert(2,2) = -1.0; res.insert(3,3) = 1.0; res.makeCompressed(); return res; } class GraphGenerator { private: int numVertices_; std::vector<std::pair<int,int> > allEdges_; std::vector<int> allVertices_; public: GraphGenerator(int numVertices) : numVertices_{numVertices} { for(int i = 0; i < numVertices-1; ++i) { for(int j = i+1; j < numVertices; ++j) { allEdges_.emplace_back(i,j); } } for(int i = 0; i < numVertices_; ++i) { allVertices_.emplace_back(i); } } std::vector<std::pair<int,int> > createRandomGraph(int numEdges) { std::vector<std::pair<int,int> > edges = allEdges_; std::random_shuffle(edges.begin(), edges.end()); edges.resize(numEdges); return edges; } std::vector<int> createRandomVertexSet(int n) { std::vector<int> v = allVertices_; std::random_shuffle(v.begin(), v.end()); v.resize(n); return v; } }; constexpr int N = 10; TEST_CASE("Test single qubit operators", "[LocalHamSingle]") { std::random_device rd; std::default_random_engine re{rd()}; std::uniform_int_distribution<> uid(0, N-1); std::uniform_real_distribution<> urd; using cx_double = std::complex<double>; SECTION("Test contructing pauli X") { edp::LocalHamiltonian<double> lh(N,2); for(int n = 0; n < 100; ++n) { lh.clearTerms(); int idx = uid(re); double val = urd(re); lh.addOneSiteTerm(idx, val*getSX()); auto mat1 = Eigen::MatrixXd(edp::constructSparseMat<double>(1<<N, lh)); auto mat2 = singleQubitOp<double>(N, idx, val*getSX()) ; REQUIRE((mat1-mat2).squaredNorm() < 1e-8); } } SECTION("Test contructing pauli Z") { edp::LocalHamiltonian<double> lh(N,2); for(int n = 0; n < 100; ++n) { lh.clearTerms(); int idx = uid(re); double val = urd(re); lh.addOneSiteTerm(idx, val*getSZ()); auto mat1 = Eigen::MatrixXd(edp::constructSparseMat<double>(1<<N, lh)); auto mat2 = singleQubitOp<double>(N, idx, val*getSZ()) ; REQUIRE((mat1-mat2).squaredNorm() < 1e-8); } } SECTION("Test contructing pauli Y") { edp::LocalHamiltonian<cx_double> lh(N,2); for(int n = 0; n < 100; ++n) { lh.clearTerms(); int idx = uid(re); double val = urd(re); lh.addOneSiteTerm(idx, val*getSY()); auto mat1 = Eigen::MatrixXcd(edp::constructSparseMat<cx_double>(1<<N, lh)); auto mat2 = singleQubitOp<cx_double>(N, idx, val*getSY()) ; REQUIRE((mat1-mat2).squaredNorm() < 1e-8); } } } TEST_CASE("Test 2-local Hamiltonians", "[LocalHam2loc]") { std::random_device rd; std::default_random_engine re{rd()}; std::uniform_int_distribution<> uid(0, N-1); std::uniform_int_distribution<> numEdgesRd(1, N*(N-1)/2); std::uniform_real_distribution<> urd; using cx_double = std::complex<double>; GraphGenerator ggen{N}; SECTION("Random XYZ Hamiltonian") { edp::LocalHamiltonian<double> lh(N,2); for(int n = 0; n < 10; ++n) { lh.clearTerms(); int numEdges = numEdgesRd(re); auto edges = ggen.createRandomGraph(numEdges); auto matEx = Eigen::MatrixXd(1<<N, 1<<N); matEx.setZero(); for(const auto& edge: edges) { double v1 = urd(re); double v2 = urd(re); double v3 = urd(re); lh.addTwoSiteTerm(edge, v1*getSXX()); lh.addTwoSiteTerm(edge, v2*getSYY()); lh.addTwoSiteTerm(edge, v3*getSZZ()); matEx += v1*twoQubitOp<double>(N, edge.first, edge.second, getSX(), getSX()); auto matYY = twoQubitOp<cx_double>(N, edge.first, edge.second, getSY(), getSY()); matEx += v2*matYY.real(); matEx += v3*twoQubitOp<double>(N, edge.first, edge.second, getSZ(), getSZ()); } auto mat = Eigen::MatrixXd(edp::constructSparseMat<double>(1<<N, lh)); REQUIRE((mat-matEx).squaredNorm() < 1e-8); } } SECTION("Random Field Ising Hamiltonian") { edp::LocalHamiltonian<double> lh(N,2); for(int n = 0; n < 20; ++n) { lh.clearTerms(); int numEdges = numEdgesRd(re); auto edges = ggen.createRandomGraph(numEdges); auto matEx = Eigen::MatrixXd(1<<N, 1<<N); matEx.setZero(); for(const auto& edge: edges) { double v = urd(re); lh.addTwoSiteTerm(edge, v*getSZZ()); matEx += v*twoQubitOp<double>(N, edge.first, edge.second, getSZ(), getSZ()); } auto numFields = uid(re); auto vs = ggen.createRandomVertexSet(numFields); for(auto v: vs) { double h1 = urd(re); double h3 = urd(re); lh.addOneSiteTerm(v, h1*getSX()); lh.addOneSiteTerm(v, h3*getSZ()); matEx += h1*singleQubitOp<double>(N, v, getSX()); matEx += h3*singleQubitOp<double>(N, v, getSZ()); } auto mat = Eigen::MatrixXd(edp::constructSparseMat<double>(1<<N, lh)); REQUIRE((mat-matEx).squaredNorm() < 1e-8); } } }
24.31348
85
0.647886
chaeyeunpark
947ffd82a8f2ee330e0277e49c4d1f0ddb1f328c
752
cc
C++
ext/snow-ext/hash.cc
nilium/snow
296466e49fd5ebd8d4d40dbf96b14903daa705a8
[ "Zlib", "BSD-2-Clause" ]
4
2015-10-01T20:10:20.000Z
2021-08-28T23:43:33.000Z
ext/snow-ext/hash.cc
nilium/snow
296466e49fd5ebd8d4d40dbf96b14903daa705a8
[ "Zlib", "BSD-2-Clause" ]
null
null
null
ext/snow-ext/hash.cc
nilium/snow
296466e49fd5ebd8d4d40dbf96b14903daa705a8
[ "Zlib", "BSD-2-Clause" ]
null
null
null
#include "hash.hh" #include "murmur3.h" namespace murmur3 { uint32_t hash32(const string &str, uint32_t seed) { return hash32(str.c_str(), str.size(), seed); } uint64_t hash64(const string &str, uint32_t seed) { return hash64(str.c_str(), str.size(), seed); } uint64_t hash64(const char *str, const size_t length, uint32_t seed) { union { struct { uint64_t lower; uint64_t upper; } block; char raw[16]; } buf; MurmurHash3_x86_128(str, static_cast<int>(length), seed, buf.raw); return buf.block.upper; } uint32_t hash32(const char *str, const size_t length, uint32_t seed) { uint32_t result = 0; MurmurHash3_x86_32(str, static_cast<int>(length), seed, static_cast<void *>(&result)); return result; } }
18.8
88
0.683511
nilium
9480e7c1a18f1682a67c7f2ee6baec0dfc9b7093
16,998
ipp
C++
include/native/async/ActionCallbackFinally.ipp
nodenative/nodenative
cf988c9399e0793b1b8c29a8ffd09e910d1a0cb3
[ "MIT" ]
16
2016-03-16T22:16:18.000Z
2021-04-05T04:46:38.000Z
include/native/async/ActionCallbackFinally.ipp
nodenative/nodenative
cf988c9399e0793b1b8c29a8ffd09e910d1a0cb3
[ "MIT" ]
11
2016-03-16T22:02:26.000Z
2021-04-04T02:20:51.000Z
include/native/async/ActionCallbackFinally.ipp
nodenative/nodenative
cf988c9399e0793b1b8c29a8ffd09e910d1a0cb3
[ "MIT" ]
5
2016-03-22T14:03:34.000Z
2021-01-06T18:08:46.000Z
#ifndef __NATIVE_ASYNC_ACTIONCALLBACKFINALLY_IPP__ #define __NATIVE_ASYNC_ACTIONCALLBACKFINALLY_IPP__ /*-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. * Propose : * -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.*/ #include "./ActionCallbackFinally.hpp" #include "./Future.hpp" namespace native { template <typename R, typename... Args> std::shared_ptr<ActionCallbackFinally<R, Args...>> ActionCallbackFinally<R, Args...>::Create(std::shared_ptr<Loop> iLoop, std::function<R(Args...)> f, Args &&... args) { return std::shared_ptr<ActionCallbackFinally<R, Args...>>( new ActionCallbackFinally<R, Args...>(iLoop, f, std::forward<Args>(args)...)); } template <typename R, typename... Args> std::shared_ptr<ActionCallbackFinally<Future<R>, Args...>> ActionCallbackFinally<Future<R>, Args...>::Create( std::shared_ptr<Loop> iLoop, std::function<Future<R>(Args...)> f, Args &&... args) { return std::shared_ptr<ActionCallbackFinally<Future<R>, Args...>>( new ActionCallbackFinally<Future<R>, Args...>(iLoop, f, std::forward<Args>(args)...)); } template <typename... Args> std::shared_ptr<ActionCallbackFinally<Future<void>, Args...>> ActionCallbackFinally<Future<void>, Args...>::Create( std::shared_ptr<Loop> iLoop, std::function<Future<void>(Args...)> f, Args &&... args) { return std::shared_ptr<ActionCallbackFinally<Future<void>, Args...>>( new ActionCallbackFinally<Future<void>, Args...>(iLoop, f, std::forward<Args>(args)...)); } template <typename... Args> std::shared_ptr<ActionCallbackFinally<void, Args...>> ActionCallbackFinally<void, Args...>::Create( std::shared_ptr<Loop> iLoop, std::function<void(Args...)> f, Args &&... args) { return std::shared_ptr<ActionCallbackFinally<void, Args...>>( new ActionCallbackFinally<void, Args...>(iLoop, f, std::forward<Args>(args)...)); } template <typename R, typename P, typename... Args> std::shared_ptr<ActionCallbackFinallyP1<R, P, Args...>> ActionCallbackFinallyP1<R, P, Args...>::Create( std::shared_ptr<Loop> iLoop, std::function<R(Args...)> f, Args &&... args) { return std::shared_ptr<ActionCallbackFinallyP1<R, P, Args...>>( new ActionCallbackFinallyP1<R, P, Args...>(iLoop, f, std::forward<Args>(args)...)); } template <typename R, typename P, typename... Args> std::shared_ptr<ActionCallbackFinallyP1<Future<R>, P, Args...>> ActionCallbackFinallyP1<Future<R>, P, Args...>::Create( std::shared_ptr<Loop> iLoop, std::function<Future<R>(Args...)> f, Args &&... args) { return std::shared_ptr<ActionCallbackFinallyP1<Future<R>, P, Args...>>( new ActionCallbackFinallyP1<Future<R>, P, Args...>(iLoop, f, std::forward<Args>(args)...)); } template <typename P, typename... Args> std::shared_ptr<ActionCallbackFinallyP1<Future<void>, P, Args...>> ActionCallbackFinallyP1<Future<void>, P, Args...>::Create(std::shared_ptr<Loop> iLoop, std::function<Future<void>(Args...)> f, Args &&... args) { return std::shared_ptr<ActionCallbackFinallyP1<Future<void>, P, Args...>>( new ActionCallbackFinallyP1<Future<void>, P, Args...>(iLoop, f, std::forward<Args>(args)...)); } template <typename P, typename... Args> std::shared_ptr<ActionCallbackFinallyP1<void, P, Args...>> ActionCallbackFinallyP1<void, P, Args...>::Create( std::shared_ptr<Loop> iLoop, std::function<void(Args...)> f, Args &&... args) { return std::shared_ptr<ActionCallbackFinallyP1<void, P, Args...>>( new ActionCallbackFinallyP1<void, P, Args...>(iLoop, f, std::forward<Args>(args)...)); } template <typename R, typename... Args> ActionCallbackFinally<R, Args...>::ActionCallbackFinally(std::shared_ptr<Loop> iLoop, std::function<R(Args...)> f, Args &&... args) : ActionCallbackBase<void>(iLoop), _f(f), _args(std::forward<Args>(args)...), _future(FutureShared<R>::Create(iLoop)) {} template <typename R, typename... Args> ActionCallbackFinally<Future<R>, Args...>::ActionCallbackFinally(std::shared_ptr<Loop> iLoop, std::function<Future<R>(Args...)> f, Args &&... args) : ActionCallbackBase<void>(iLoop), _f(f), _args(std::forward<Args>(args)...), _future(FutureShared<R>::Create(iLoop)) {} template <typename... Args> ActionCallbackFinally<Future<void>, Args...>::ActionCallbackFinally(std::shared_ptr<Loop> iLoop, std::function<Future<void>(Args...)> f, Args &&... args) : ActionCallbackBase<void>(iLoop), _f(f), _args(std::forward<Args>(args)...), _future(FutureShared<void>::Create(iLoop)) {} template <typename... Args> ActionCallbackFinally<void, Args...>::ActionCallbackFinally(std::shared_ptr<Loop> iLoop, std::function<void(Args...)> f, Args &&... args) : ActionCallbackBase<void>(iLoop), _f(f), _args(std::forward<Args>(args)...), _future(FutureShared<void>::Create(iLoop)) {} template <typename R, typename P, typename... Args> ActionCallbackFinallyP1<R, P, Args...>::ActionCallbackFinallyP1(std::shared_ptr<Loop> iLoop, std::function<R(Args...)> f, Args &&... args) : ActionCallbackBase<P>(iLoop), _f(f), _args(std::forward<Args>(args)...), _future(FutureShared<R>::Create(iLoop)) { } template <typename R, typename P, typename... Args> ActionCallbackFinallyP1<Future<R>, P, Args...>::ActionCallbackFinallyP1(std::shared_ptr<Loop> iLoop, std::function<Future<R>(Args...)> f, Args &&... args) : ActionCallbackBase<P>(iLoop), _f(f), _args(std::forward<Args>(args)...), _future(FutureShared<R>::Create(iLoop)) { } template <typename P, typename... Args> ActionCallbackFinallyP1<Future<void>, P, Args...>::ActionCallbackFinallyP1(std::shared_ptr<Loop> iLoop, std::function<Future<void>(Args...)> f, Args &&... args) : ActionCallbackBase<P>(iLoop), _f(f), _args(std::forward<Args>(args)...), _future(FutureShared<void>::Create(iLoop)) {} template <typename P, typename... Args> ActionCallbackFinallyP1<void, P, Args...>::ActionCallbackFinallyP1(std::shared_ptr<Loop> iLoop, std::function<void(Args...)> f, Args &&... args) : ActionCallbackBase<P>(iLoop), _f(f), _args(std::forward<Args>(args)...), _future(FutureShared<void>::Create(iLoop)) {} template <typename R, typename... Args> std::shared_ptr<FutureShared<R>> ActionCallbackFinally<R, Args...>::getFuture() { NNATIVE_ASSERT(this->_future); return this->_future; } template <typename R, typename... Args> std::shared_ptr<FutureShared<R>> ActionCallbackFinally<Future<R>, Args...>::getFuture() { NNATIVE_ASSERT(this->_future); return this->_future; } template <typename... Args> std::shared_ptr<FutureShared<void>> ActionCallbackFinally<Future<void>, Args...>::getFuture() { NNATIVE_ASSERT(this->_future); return this->_future; } template <typename... Args> std::shared_ptr<FutureShared<void>> ActionCallbackFinally<void, Args...>::getFuture() { NNATIVE_ASSERT(this->_future); return this->_future; } template <typename R, typename P, typename... Args> std::shared_ptr<FutureShared<R>> ActionCallbackFinallyP1<R, P, Args...>::getFuture() { NNATIVE_ASSERT(this->_future); return this->_future; } template <typename R, typename P, typename... Args> std::shared_ptr<FutureShared<R>> ActionCallbackFinallyP1<Future<R>, P, Args...>::getFuture() { NNATIVE_ASSERT(this->_future); return this->_future; } template <typename P, typename... Args> std::shared_ptr<FutureShared<void>> ActionCallbackFinallyP1<Future<void>, P, Args...>::getFuture() { NNATIVE_ASSERT(this->_future); return this->_future; } template <typename P, typename... Args> std::shared_ptr<FutureShared<void>> ActionCallbackFinallyP1<void, P, Args...>::getFuture() { NNATIVE_ASSERT(this->_future); return this->_future; } template <typename R, typename... Args> template <std::size_t... Is> void ActionCallbackFinally<R, Args...>::callFn(helper::TemplateSeqInd<Is...>) { try { this->getFuture()->resolve(this->_f(std::get<Is>(this->_args)...)); } catch (const FutureError &e) { this->getFuture()->reject(e); } } template <typename R, typename... Args> template <std::size_t... Is> void ActionCallbackFinally<Future<R>, Args...>::callFn(helper::TemplateSeqInd<Is...>) { std::shared_ptr<ActionCallbackBase<void>> iInstance = this->getInstance(); try { this->_f(std::get<Is>(this->_args)...) .template then<std::function<void(R)>>([iInstance](R &&r) { ActionCallbackFinally<Future<R>, Args...> *currPtr = static_cast<ActionCallbackFinally<Future<R>, Args...> *>(iInstance.get()); currPtr->getFuture()->resolve(std::forward<R>(r)); }) .template error<std::function<void(const FutureError &)>>([iInstance](const FutureError &iError) { ActionCallbackFinally<Future<R>, Args...> *currPtr = static_cast<ActionCallbackFinally<Future<R>, Args...> *>(iInstance.get()); currPtr->getFuture()->reject(iError); }); } catch (const FutureError &e) { this->getFuture()->reject(e); } } template <typename... Args> template <std::size_t... Is> void ActionCallbackFinally<Future<void>, Args...>::callFn(helper::TemplateSeqInd<Is...>) { std::shared_ptr<ActionCallbackBase<void>> iInstance = this->getInstance(); try { this->_f(std::get<Is>(this->_args)...) .template then<std::function<void()>>([iInstance]() { ActionCallbackFinally<Future<void>, Args...> *currPtr = static_cast<ActionCallbackFinally<Future<void>, Args...> *>(iInstance.get()); currPtr->getFuture()->resolve(); }) .template error<std::function<void(const FutureError &)>>([iInstance](const FutureError &iError) { ActionCallbackFinally<Future<void>, Args...> *currPtr = static_cast<ActionCallbackFinally<Future<void>, Args...> *>(iInstance.get()); currPtr->getFuture()->reject(iError); }); } catch (const FutureError &e) { this->getFuture()->reject(e); } } template <typename... Args> template <std::size_t... Is> void ActionCallbackFinally<void, Args...>::callFn(helper::TemplateSeqInd<Is...>) { try { this->_f(std::get<Is>(this->_args)...); this->getFuture()->resolve(); } catch (const FutureError &e) { this->getFuture()->reject(e); } } template <typename R, typename P, typename... Args> template <std::size_t... Is> void ActionCallbackFinallyP1<R, P, Args...>::callFn(helper::TemplateSeqInd<Is...>) { try { this->getFuture()->resolve(this->_f(std::get<Is>(this->_args)...)); } catch (const FutureError &e) { this->getFuture()->reject(e); } } template <typename R, typename P, typename... Args> template <std::size_t... Is> void ActionCallbackFinallyP1<Future<R>, P, Args...>::callFn(helper::TemplateSeqInd<Is...>) { std::shared_ptr<ActionCallbackBase<P>> iInstance = this->getInstance(); try { this->_f(std::get<Is>(this->_args)...) .template then<std::function<void(R)>>([iInstance](R &&r) { ActionCallbackFinallyP1<Future<R>, P, Args...> *currPtr = static_cast<ActionCallbackFinallyP1<Future<R>, P, Args...> *>(iInstance.get()); currPtr->getFuture()->resolve(std::forward<R>(r)); }) .template error<std::function<void(const FutureError &)>>([iInstance](const FutureError &iError) { ActionCallbackFinallyP1<Future<R>, P, Args...> *currPtr = static_cast<ActionCallbackFinallyP1<Future<R>, P, Args...> *>(iInstance.get()); currPtr->getFuture()->reject(iError); }); } catch (const FutureError &e) { this->getFuture()->reject(e); } } template <typename P, typename... Args> template <std::size_t... Is> void ActionCallbackFinallyP1<Future<void>, P, Args...>::callFn(helper::TemplateSeqInd<Is...>) { std::shared_ptr<ActionCallbackBase<P>> iInstance = this->getInstance(); try { this->_f(std::get<Is>(this->_args)...) .template then<std::function<void()>>([iInstance]() { ActionCallbackFinallyP1<Future<void>, P, Args...> *currPtr = static_cast<ActionCallbackFinallyP1<Future<void>, P, Args...> *>(iInstance.get()); currPtr->getFuture()->resolve(); }) .template error<std::function<void(const FutureError &)>>([iInstance](const FutureError &iError) { ActionCallbackFinallyP1<Future<void>, P, Args...> *currPtr = static_cast<ActionCallbackFinallyP1<Future<void>, P, Args...> *>(iInstance.get()); currPtr->getFuture()->reject(iError); }); } catch (const FutureError &e) { this->getFuture()->reject(e); } } template <typename P, typename... Args> template <std::size_t... Is> void ActionCallbackFinallyP1<void, P, Args...>::callFn(helper::TemplateSeqInd<Is...>) { try { this->_f(std::get<Is>(this->_args)...); this->getFuture()->resolve(); } catch (const FutureError &e) { this->getFuture()->reject(e); } } template <typename R, typename... Args> void ActionCallbackFinally<R, Args...>::resolveCb() { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } template <typename R, typename... Args> void ActionCallbackFinally<Future<R>, Args...>::resolveCb() { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } template <typename... Args> void ActionCallbackFinally<Future<void>, Args...>::resolveCb() { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } template <typename... Args> void ActionCallbackFinally<void, Args...>::resolveCb() { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } template <typename R, typename P, typename... Args> void ActionCallbackFinallyP1<R, P, Args...>::resolveCb(P p) { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } template <typename R, typename P, typename... Args> void ActionCallbackFinallyP1<Future<R>, P, Args...>::resolveCb(P p) { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } template <typename P, typename... Args> void ActionCallbackFinallyP1<Future<void>, P, Args...>::resolveCb(P p) { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } template <typename P, typename... Args> void ActionCallbackFinallyP1<void, P, Args...>::resolveCb(P p) { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } template <typename R, typename... Args> void ActionCallbackFinally<R, Args...>::rejectCb(const FutureError &iError) { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } template <typename R, typename... Args> void ActionCallbackFinally<Future<R>, Args...>::rejectCb(const FutureError &iError) { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } template <typename... Args> void ActionCallbackFinally<Future<void>, Args...>::rejectCb(const FutureError &iError) { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } template <typename... Args> void ActionCallbackFinally<void, Args...>::rejectCb(const FutureError &iError) { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } template <typename R, typename P, typename... Args> void ActionCallbackFinallyP1<R, P, Args...>::rejectCb(const FutureError &iError) { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } template <typename R, typename P, typename... Args> void ActionCallbackFinallyP1<Future<R>, P, Args...>::rejectCb(const FutureError &iError) { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } template <typename P, typename... Args> void ActionCallbackFinallyP1<Future<void>, P, Args...>::rejectCb(const FutureError &iError) { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } template <typename P, typename... Args> void ActionCallbackFinallyP1<void, P, Args...>::rejectCb(const FutureError &iError) { this->template callFn(helper::TemplateSeqIndGen<sizeof...(Args)>()); } } /* namespace native */ #endif /* __NATIVE_ASYNC_ACTIONCALLBACKFINALLY_IPP__ */
45.571046
120
0.628486
nodenative
9483cd23602c72ffc8cd854fe54102cea2e0eb0a
1,846
cc
C++
test/test_file_writer.cc
wobbals/barc
ce7a417b37941a696105904e67058adbf0a35c59
[ "Apache-2.0" ]
8
2017-02-21T21:07:44.000Z
2021-05-16T10:22:06.000Z
test/test_file_writer.cc
wobbals/barc
ce7a417b37941a696105904e67058adbf0a35c59
[ "Apache-2.0" ]
11
2017-03-06T22:09:34.000Z
2020-05-12T07:06:09.000Z
test/test_file_writer.cc
wobbals/barc
ce7a417b37941a696105904e67058adbf0a35c59
[ "Apache-2.0" ]
6
2017-02-21T21:35:48.000Z
2019-12-03T06:42:27.000Z
// // test_file_writer.c // barc // // Created by Charley Robinson on 3/16/17. // extern "C" { #include <unistd.h> #include "file_writer.h" } #include "gtest/gtest.h" TEST(FileWriter, AllocFileWriter) { struct file_writer_t* file_writer = NULL; file_writer_alloc(&file_writer); EXPECT_TRUE(file_writer != NULL); file_writer_free(file_writer); } AVFrame* empty_audio_frame() { AVFrame* frame = av_frame_alloc(); // TODO: Dig the format out of the file writer context for better flexibility frame->pts = 0; frame->format = AV_SAMPLE_FMT_FLTP; frame->nb_samples = 1024; frame->channel_layout = AV_CH_LAYOUT_MONO; frame->sample_rate = 48000; frame->channels = 1; frame->data[0] = NULL; EXPECT_TRUE(NULL == frame->data[0]); int ret = av_frame_get_buffer(frame, 0); EXPECT_TRUE(NULL != frame->data[0]); return frame; } /* This isn't working. I think it might be waiting for a video frame. * TODO: add a video frame. TEST(FileWriter, WriteFrame) { av_register_all(); avfilter_register_all(); int ret; const char* outfile = "/tmp/output.mp4"; struct file_writer_t* file_writer = NULL; file_writer_alloc(&file_writer); EXPECT_TRUE(NULL != file_writer); ret = file_writer_open(file_writer, outfile, 320, 240); EXPECT_TRUE(0 == ret); for (int i = 0; i < 1000; i++) { AVFrame* frame = empty_audio_frame(); frame->pts = (i * 48000) / 20; // probably the filtergraph resetting the frame. is this safe? ret = file_writer_push_audio_frame(file_writer, frame); // write frames until the filter graph is happy if (0 == ret) { break; } } if (ret) printf("%s\n", av_err2str(ret)); EXPECT_TRUE(0 == ret); ret = file_writer_close(file_writer); EXPECT_TRUE(0 == ret); EXPECT_TRUE(file_writer != NULL); file_writer_free(file_writer); unlink(outfile); } */
26.371429
79
0.684724
wobbals
9486169b2ea75e97af60597fe4737dea2993fe73
1,088
cpp
C++
codes/moderncpp/type_traits/is_function/is_function01/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
3
2022-01-25T07:33:43.000Z
2022-03-30T10:25:09.000Z
codes/moderncpp/type_traits/is_function/is_function01/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
null
null
null
codes/moderncpp/type_traits/is_function/is_function01/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
2
2022-01-17T13:39:12.000Z
2022-03-30T10:25:12.000Z
#include <iostream> #include <type_traits> int a(int i){return i;} // function int(*b)(int)=a; // pointer to function struct C { int operator()(int i){return i;} } c; // function-like class int main( int argc, char **argv ) { { # define REF(x) << #x " ?: " << x << '\n' std::cout << std::boolalpha REF( std::is_function<decltype(a)>::value ) REF( std::is_function<decltype(b)>::value ) REF( std::is_function<decltype(c)>::value ) REF( std::is_function<C>::value ) REF( std::is_function<int(int)>::value ) REF( std::is_function<int(*)(int)>::value ); # undef REF } { # define REF(x) << #x " ?: " << x << '\n' std::cout << std::boolalpha REF( std::is_function_v<decltype(a)> ) REF( std::is_function_v<decltype(b)> ) REF( std::is_function_v<decltype(c)> ) REF( std::is_function_v<C> ) REF( std::is_function_v<int(int)> ) REF( std::is_function_v<int(*)(int)> ); # undef REF } return 0; }
31.085714
72
0.517463
eric2003
94898f7becfe84ce195e0163ca94a9fdce0d90aa
2,735
cpp
C++
test/net/ReceiverTest.cpp
RoboTeamTwente/roboteam_mimir
fd62d50ca8dd3a6e35448e1d2eaca655546e5b21
[ "MIT" ]
1
2019-11-16T17:44:13.000Z
2019-11-16T17:44:13.000Z
test/net/ReceiverTest.cpp
RoboTeamTwente/roboteam_mimir
fd62d50ca8dd3a6e35448e1d2eaca655546e5b21
[ "MIT" ]
51
2019-09-29T09:16:22.000Z
2020-10-24T10:04:59.000Z
test/net/ReceiverTest.cpp
RoboTeamTwente/roboteam_mimir
fd62d50ca8dd3a6e35448e1d2eaca655546e5b21
[ "MIT" ]
null
null
null
// // Created by rolf on 19-09-19. // #include "net/Receiver.h" #include "gtest/gtest.h" TEST(ReceiverTest,receiveTest){ //We are going to manually send commands to test the receiver QUdpSocket sendSocket; QHostAddress address("127.0.0.1"); unsigned int port = 10006; net::Receiver receiver(address,port); // at this point the receiver should already be listening sendSocket.bind(address,port); mimir_robotcommand command; // values we use to test int id=7; bool teamIsYellow=false; float dribblespeed=0.5; float velx= 0.3; float vely= 0.4; float angle = 1.0; command.set_id(id); command.set_teamisyellow(false); command.set_dribblerspeed(0.5); globalVelocity vel; vel.set_angle(angle); vel.set_velx(velx); vel.set_vely(vely); command.mutable_globalvel()->CopyFrom(vel); bool chip=true; int geneva=4; float kickpower=0.8; Kicker kicker; kicker.set_chip(chip); kicker.set_genevaangle(geneva); kicker.set_kickchippower(kickpower); command.mutable_kicker()->CopyFrom(kicker); // now actually send the command twice! QByteArray datagram; datagram.resize(command.ByteSize()); ASSERT_TRUE(command.SerializeToArray(datagram.data(),datagram.size())); ASSERT_EQ(sendSocket.writeDatagram(datagram,address,port),command.ByteSize()); ASSERT_EQ(sendSocket.writeDatagram(datagram,address,port),command.ByteSize()); auto messages=receiver.readMessages(); ASSERT_EQ(messages.size(),2); auto msg=messages[0]; EXPECT_EQ(msg.id(),id); EXPECT_EQ(msg.teamisyellow(),teamIsYellow); EXPECT_FLOAT_EQ(msg.dribblerspeed(),dribblespeed); EXPECT_TRUE(msg.has_globalvel()); EXPECT_FALSE(msg.has_robotvel()); EXPECT_FALSE(msg.has_wheels()); EXPECT_FLOAT_EQ(msg.globalvel().vely(),vely); EXPECT_FLOAT_EQ(msg.globalvel().velx(),velx); EXPECT_EQ(msg.globalvel().angleControl_case(),msg.globalvel().kAngleFieldNumber); EXPECT_EQ(msg.globalvel().angle(),angle); EXPECT_TRUE(msg.has_kicker()); EXPECT_EQ(msg.kicker().chip(),chip); EXPECT_EQ(msg.kicker().genevaangle(),geneva); EXPECT_FLOAT_EQ(msg.kicker().kickchippower(),kickpower); } TEST(ReceiverTest,setterGetters){ QHostAddress address("127.0.0.1"); unsigned int port = 10006; net::Receiver receiver(address,port); EXPECT_EQ(receiver.getPort(),port); EXPECT_EQ(receiver.getIP(),"127.0.0.1"); int newPort=10005; receiver.setIP(QHostAddress("127.0.0.2")); receiver.setPort(newPort); EXPECT_NE(receiver.getPort(),port); EXPECT_NE(receiver.getIP(),"127.0.0.1"); EXPECT_EQ(receiver.getPort(),newPort); EXPECT_EQ(receiver.getIP(),"127.0.0.2"); }
31.079545
85
0.696527
RoboTeamTwente
948b863e1c8374f2af65293d88e38b9c4aacbf52
11,235
cpp
C++
src/caffe/layers/search_n_layer.cpp
suyuan32/atlas_200dk_caffe
119c7696ea787363e2f58c2a7fb6e7395098b0d1
[ "MIT" ]
1
2021-09-17T14:24:01.000Z
2021-09-17T14:24:01.000Z
src/caffe/layers/search_n_layer.cpp
suyuan32/atlas_200dk_caffe
119c7696ea787363e2f58c2a7fb6e7395098b0d1
[ "MIT" ]
null
null
null
src/caffe/layers/search_n_layer.cpp
suyuan32/atlas_200dk_caffe
119c7696ea787363e2f58c2a7fb6e7395098b0d1
[ "MIT" ]
null
null
null
/* * Copyright (c) Huawei Technologies Co., Ltd. 2019-2019. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the Apache License Version 2.0.You may not use this file except in compliance with the License. * * 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 * Apache License for more details at * http://www.apache.org/licenses/LICENSE-2.0 * * @brief search shift bit layer cpp source * * @version 1.0 */ #include <vector> #include <cmath> #include <fstream> #include <iostream> #include <map> #include "caffe/layers/search_n_layer.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/util/io.hpp" #include "caffe/util/amct_util.hpp" namespace caffe { const int LSTM_CHANNEL_NUM = 4; const int LSTM_XH_CHANNEL_AXIS = 2; const int LSTM_S_CHANNEL_AXIS = 1; const int CONV_HEIGHT_AXIS = 2; const int CONV_WIDTH_AXIS = 3; template <typename Dtype> void SearchNLayer<Dtype>::Reshape(const vector<Blob<Dtype>* >& bottom, const vector<Blob<Dtype>* >& top) { if (top.size() == 1) { top[0]->ReshapeLike(*bottom[0]); } return; } template <typename Dtype> void SearchNLayer<Dtype>::ReadRecord(ScaleOffsetRecord* records) { if (!ReadProtoFromTextFile(recordFileName.c_str(), records)) { LOG(ERROR) << "Read records from " << recordFileName << " failed."; } return; } template <typename Dtype> void SearchNLayer<Dtype>::GetBottomChannels() { ScaleOffsetRecord records; ReadRecord(&records); for (auto layerName : quantLayerNames) { bool found = false; for (int i = 0; i < records.record_size(); i++) { const ScaleOffsetRecord_MapFiledEntry& record = records.record(i); if (record.has_key() && record.key() == layerName) { found = true; const SingleLayerRecord& layerQuantInfo = record.value(); int channel = layerQuantInfo.scale_w_size(); CHECK_GE(channel, 1); bottomChannels.push_back(channel); } } CHECK(found) << "Layer " << layerName << " not found in " << recordFileName; } for (int i = 1; i < bottomChannels.size(); i++) { CHECK_EQ(bottomChannels[i], bottomChannels[0]) << "Channel number of layer " << quantLayerNames.Get(i) << "(" << bottomChannels[i] << ")" << " is different from layer " << quantLayerNames.Get(0) << "(" << bottomChannels[0] << ")."; } for (int i = 0; i < bottomChannels.size(); i++) { if (quantLayerTypes.Get(i) == string("InnerProduct")) { CHECK_EQ(bottomChannels[i], 1) << "The channel number of InnerProduct layer(" << quantLayerNames.Get(i) << ") should be 1, but actually is " << bottomChannels[i]; } } } template <typename Dtype> void SearchNLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>* >& bottom, const vector<Blob<Dtype>* >& top) { targetBatchNum = this->layer_param_.search_n_param().batch_num(); quantLayerNames = this->layer_param_.search_n_param().layer_name(); CHECK_GE(quantLayerNames.size(), 1); showQuantLayerNames = "["; for (auto layerName : quantLayerNames) { showQuantLayerNames += layerName; showQuantLayerNames += " "; } showQuantLayerNames[showQuantLayerNames.size() - 1] = ']'; quantLayerTypes = this->layer_param_.search_n_param().layer_type(); CHECK_EQ(quantLayerNames.size(), quantLayerTypes.size()) << "layer_name size(" << quantLayerNames.size() << ") must be equal to layer_type size(" << quantLayerTypes.size() << ")."; recordFileName = this->layer_param_.search_n_param().record_file_path(); GetBottomChannels(); channelNum = bottomChannels[0]; for (int index = 0; index < quantLayerTypes.size(); ++index) { if (quantLayerTypes.Get(index) == "Convolution" && channelNum > 1) { if (bottom[index]->shape(CONV_HEIGHT_AXIS) == 1 && bottom[index]->shape(CONV_WIDTH_AXIS) == 1) { globalConvFlag_ = true; channelNum = 1; LOG(INFO) << "Find layer \"" << quantLayerNames.Get(index) << "\" is global conv"; } } } storedData.resize(channelNum); } template <typename Dtype> void SearchNLayer<Dtype>::AccumulateData(const vector<Blob<Dtype>* >& bottom) { for (int i = 0; i < bottom.size(); i++) { CHECK_GE(bottom[i]->shape().size(), MIN_SHAPE_SIZE); if (quantLayerTypes.Get(0) != "LSTM_X" && quantLayerTypes.Get(0) != "LSTM_H" && quantLayerTypes.Get(0) != "LSTM_S") { if (channelNum != 1) { CHECK_EQ(bottom[i]->shape()[1], channelNum) << "Channel wise but scale size: " \ << channelNum << " != channel in: " << bottom[i]->shape()[1]; } } else { CHECK_EQ(channelNum, LSTM_CHANNEL_NUM); } } for (int i = 0; i < bottom.size(); i++) { Blob<Dtype>* curBottom = bottom[i]; int count = curBottom->count(); const Dtype* bottomData = curBottom->cpu_data(); unsigned int channelID = 0; unsigned int CHW = curBottom->count(C_INDEX); unsigned int HW = curBottom->count(H_INDEX); if (quantLayerTypes.Get(0) == "LSTM_X" || quantLayerTypes.Get(0) == "LSTM_H") { CHW = curBottom->count(LSTM_XH_CHANNEL_AXIS); HW = curBottom->shape(LSTM_XH_CHANNEL_AXIS) / LSTM_CHANNEL_NUM; } else if (quantLayerTypes.Get(0) == "LSTM_S") { CHW = curBottom->count(LSTM_S_CHANNEL_AXIS); HW = curBottom->shape(LSTM_S_CHANNEL_AXIS) / LSTM_CHANNEL_NUM; } if (channelNum > 1) { for (int offset = 0; offset < count; offset++) { channelID = (offset % CHW) / HW; storedData[channelID].push_back(bottomData[offset]); } } else { for (int offset = 0; offset < count; offset++) { storedData[channelID].push_back(bottomData[offset]); } } } return; } template <typename Dtype> void SearchNLayer<Dtype>::GetDeqScale() { ScaleOffsetRecord records; ReadRecord(&records); Dtype scaleD = 0; vector<vector<Dtype>> allDeqScales(quantLayerNames.size()); for (int i = 0; i < quantLayerNames.size(); i++) { string layerName(quantLayerNames.Get(i)); for (int j = 0; j < records.record_size(); j++) { const ScaleOffsetRecord_MapFiledEntry& record = records.record(j); if (record.has_key() && record.key() == layerName) { const SingleLayerRecord& layerQuantInfo = record.value(); int scaleWSize = layerQuantInfo.scale_w_size(); CHECK_EQ(layerQuantInfo.has_scale_d(), true); scaleD = layerQuantInfo.scale_d(); for (int k = 0; k < scaleWSize; k++) { allDeqScales[i].push_back(layerQuantInfo.scale_d() * layerQuantInfo.scale_w(k)); } } } } for (int i = 1; i < allDeqScales.size(); i++) { CHECK_EQ(allDeqScales[i].size(), allDeqScales[0].size()); for (int j = 0; j < allDeqScales[i].size(); j++) { CHECK_EQ(allDeqScales[i][j], allDeqScales[0][j]); } } for (int i = 0; i < allDeqScales[0].size(); i++) { deqScale.push_back(allDeqScales[0][i]); } if (globalConvFlag_) { Dtype maxDeqScale = 0; for (auto singleDeqScale : deqScale) { if (singleDeqScale > maxDeqScale) { maxDeqScale = singleDeqScale; } } for (int i = 0; i < deqScale.size(); i++) { deqScale[i] = maxDeqScale; } UpdateScaleW(deqScale, scaleD); } return; } template <typename Dtype> void SearchNLayer<Dtype>::RecordN(vector<int>& bestN) { ScaleOffsetRecord records; ReadRecord(&records); if (globalConvFlag_) { CHECK_EQ(bestN.size(), 1) << "Do global conv search_n, searched n should 1, actual " << bestN.size(); for (int i = 1; i < bottomChannels[0]; ++i) { bestN.push_back(bestN[0]); } } for (int i = 0; i < quantLayerNames.size(); i++) { string layerName(quantLayerNames.Get(i)); for (int j = 0; j < records.record_size(); j++) { ScaleOffsetRecord_MapFiledEntry* record = records.mutable_record(j); if (record->has_key() && record->key() == layerName) { SingleLayerRecord* layerQuantInfo = record->mutable_value(); for (int k = 0; k < bestN.size(); k++) { layerQuantInfo->add_shift_bit(bestN[k]); } } } } WriteProtoToTextFile(records, recordFileName.c_str()); return; } template <typename Dtype> void SearchNLayer<Dtype>::UpdateScaleW(vector<Dtype>& deqScale, Dtype scaleD) { ScaleOffsetRecord records; ReadRecord(&records); for (int i = 0; i < quantLayerNames.size(); i++) { string layerName(quantLayerNames.Get(i)); for (int j = 0; j < records.record_size(); j++) { ScaleOffsetRecord_MapFiledEntry* record = records.mutable_record(j); if (record->has_key() && record->key() == layerName) { SingleLayerRecord* layerQuantInfo = record->mutable_value(); for (int k = 0; k < deqScale.size(); k++) { layerQuantInfo->set_scale_w(k, deqScale[k] / scaleD); } } } } WriteProtoToTextFile(records, recordFileName.c_str()); return; } template <typename Dtype> void SearchNLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>* >& bottom, const vector<Blob<Dtype>* >& top) { if (curBatchNum < targetBatchNum) { AccumulateData(bottom); curBatchNum++; LOG(INFO) << "Doing layer: " << showQuantLayerNames << " search shift bits calibration, already store " << curBatchNum << "/" << targetBatchNum << " data."; } if (curBatchNum == targetBatchNum) { GetDeqScale(); vector<int> bestN; SearchShitBit(storedData, deqScale, bestN); RecordN(bestN); LOG(INFO) << "Do layer: " << showQuantLayerNames << " search shift bits calibration success!"; storedData.clear(); storedData.shrink_to_fit(); curBatchNum++; } if (top.size() == 1) { const int count = bottom[0]->count(); const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* top_data = top[0]->mutable_cpu_data(); caffe_copy(count, bottom_data, top_data); } } template <typename Dtype> void SearchNLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>* >& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>* >& bottom) { return; } #ifdef CPU_ONLY STUB_GPU(SearchNLayer); #endif INSTANTIATE_CLASS(SearchNLayer); REGISTER_LAYER_CLASS(SearchN); } // namespace caffe
35.330189
120
0.594482
suyuan32
948d4b4be64c30871044e059a320c622fa676986
1,919
cpp
C++
src/GreenFractals.cpp
ecssiah/Buddhabrot-Variations
cdc6c9c273c0e33036acf1850c1ad87e8432c37e
[ "MIT" ]
null
null
null
src/GreenFractals.cpp
ecssiah/Buddhabrot-Variations
cdc6c9c273c0e33036acf1850c1ad87e8432c37e
[ "MIT" ]
null
null
null
src/GreenFractals.cpp
ecssiah/Buddhabrot-Variations
cdc6c9c273c0e33036acf1850c1ad87e8432c37e
[ "MIT" ]
null
null
null
#include <cmath> #include <complex> #include <vector> #include <iostream> #include <Eigen/Geometry> #include <Magick++.h> #include "Constants.h" #include "ImageGenerator.h" #include "FractalInstance.h" using namespace std; using namespace Eigen; using namespace Magick; vector<FractalInstance> fractals; // user literal for millions (i.e. 1_m = 10000000) constexpr unsigned long long operator "" _m(unsigned long long l) { return l * 1000 * 1000; } int main(int argc, char** argv) { InitializeMagick(*argv); auto theta(0.0); auto delta(2 * M_PI / NUM_FRAMES); auto offset1(0.0); auto offset2(0.0); auto offset3(0.0); Vector3f axis1(1, 0, 0); Vector3f axis2(0, 1, 0); Vector3f axis3(0, 0, 1); axis1.normalize(); axis2.normalize(); axis3.normalize(); Vector3f vec(-1/6.0, 1/120.0, -1/5040.0); auto vec1(vec); auto vec2(vec); auto vec3(vec); FractalInstance::num_points = 10_m; FractalInstance::complex_range = 6.0; FractalInstance::default_iterations = 1e2; /* FractalInstance fi( */ /* {1, vec1.x(), vec1.y(), vec1.z()}, */ /* {1, 2, 4, 6}, */ /* {0, 0, 3.0, 3.0} */ /* ); */ /* ImageGenerator::generate(fi); */ for (auto frame(1); frame <= NUM_FRAMES; ++frame) { FractalInstance rfi( {1, vec1.x(), vec1.y(), vec1.z()}, {1, 2, 4, 6}, {0, 0, 4.0, 4.0} ); FractalInstance gfi( {1, vec2.x(), vec2.y(), vec2.z()}, {1, 2, 4, 6}, {0, 0, 4.0, 4.0} ); FractalInstance bfi( {1, vec3.x(), vec3.y(), vec3.z()}, {1, 2, 4, 6}, {0, 0, 4.0, 4.0} ); ImageGenerator::generate({rfi, gfi, bfi}, frame); theta += delta; auto t1(AngleAxis<float>(theta + offset1, axis1)); vec1 = t1 * vec; auto t2(AngleAxis<float>(theta + offset2, axis2)); vec2 = t2 * vec; auto t3(AngleAxis<float>(theta + offset3, axis3)); vec3 = t3 * vec; } return 0; }
20.634409
67
0.583116
ecssiah
948dff59d71da8ab5af5b4c07aaf0576684d3bcc
1,171
cpp
C++
Camp_2-2563/07_MST/39_CableCar.cpp
MasterIceZ/POSN_BUU
56e176fb843d7ddcee0cf4acf2bb141576c260cf
[ "MIT" ]
null
null
null
Camp_2-2563/07_MST/39_CableCar.cpp
MasterIceZ/POSN_BUU
56e176fb843d7ddcee0cf4acf2bb141576c260cf
[ "MIT" ]
null
null
null
Camp_2-2563/07_MST/39_CableCar.cpp
MasterIceZ/POSN_BUU
56e176fb843d7ddcee0cf4acf2bb141576c260cf
[ "MIT" ]
null
null
null
/* * AUTHOR : Hydrolyzed~ * SCHOOL : RYW * CENTER : BUU * TASK : Cable Car TOI12 * ALGO : Minimum Spanning Tree * DATE : 9 May 2021 * */ #include<bits/stdc++.h> using namespace std; #define dec(x,y) fixed << setprecision(y) << x #define all(x) (x).begin(), (x).end() #define endl '\n' #define int long long using LL = long long; int n, m; struct Node{ int v, w; bool operator < (const Node&o) const{ return w < o.w; } }; priority_queue<Node>pq; vector<Node> g[2555]; int dist[2555]; void solve(){ cin >> n >> m; for(int i=0; i<m; ++i){ int u, v, w; cin >> u >> v >> w; g[u].push_back({v, w}); g[v].push_back({u, w}); } int u, v, w; cin >> u >> v >> w; dist[u] = INT_MAX; pq.push({u, INT_MAX}); while(!pq.empty()){ Node now = pq.top(); pq.pop(); if(now.v == v){ cout << (int)ceil((double)w / (now.w-1)); break; } for(auto x: g[now.v]){ if(dist[x.v] >= min(now.w, x.w)){ continue; } dist[x.v] = min(now.w, x.w); pq.push({x.v, dist[x.v]}); } } return ; } int32_t main(){ cin.tie(nullptr)->ios::sync_with_stdio(false); int t=1; // cin >> t; while(t--){ solve(); cout << endl; } return 0; }
16.492958
49
0.541418
MasterIceZ
9497622dfd397a60d8fcf26e94920c41c83170e6
430
hpp
C++
CocoaPhoenix/include/cocoa_phx/PHXViewDelegate.hpp
phoenix-engine/phoenix
c3285482ee507b566a1c38da071439dab507a877
[ "MIT" ]
2
2019-05-04T19:33:26.000Z
2019-06-29T13:19:33.000Z
CocoaPhoenix/include/cocoa_phx/PHXViewDelegate.hpp
phoenix-engine/phoenix
c3285482ee507b566a1c38da071439dab507a877
[ "MIT" ]
13
2019-05-05T12:40:54.000Z
2020-02-29T20:32:11.000Z
CocoaPhoenix/include/cocoa_phx/PHXViewDelegate.hpp
phoenix-engine/phoenix
c3285482ee507b566a1c38da071439dab507a877
[ "MIT" ]
4
2018-09-15T21:59:08.000Z
2019-05-04T20:19:07.000Z
// // PHXViewDelegate.hpp // CocoaPhoenix // // Created by Bodie Solomon on 3/12/19. // #ifndef PHXViewDelegate_hpp #define PHXViewDelegate_hpp /// PHXViewDelegate responds to UI draw events by making the appropriate calls /// into the Phoenix engine object. @interface PHXViewDelegate : NSObject<MTKViewDelegate> + (instancetype _Nullable) makeWithPhoenix:(MetalPhoenix* _Nonnull)p; @end #endif /* PHXViewDelegate_hpp */
21.5
78
0.765116
phoenix-engine
949ca9f22fa28763a77c01cce817538524129fc5
3,809
cpp
C++
Projects/RealityEngine/source/Engine.cpp
Volta948/RealityEngine
1a9e4b7db00617176d06004af934d6602dd5920a
[ "BSD-3-Clause" ]
null
null
null
Projects/RealityEngine/source/Engine.cpp
Volta948/RealityEngine
1a9e4b7db00617176d06004af934d6602dd5920a
[ "BSD-3-Clause" ]
null
null
null
Projects/RealityEngine/source/Engine.cpp
Volta948/RealityEngine
1a9e4b7db00617176d06004af934d6602dd5920a
[ "BSD-3-Clause" ]
1
2021-11-05T02:55:27.000Z
2021-11-05T02:55:27.000Z
// Copyright Reality Engine. All Rights Reserved. #include "Engine.h" #define GLFW_INCLUDE_NONE #include <glfw/glfw3.h> Reality::GameEngine::GameEngine() { g_SceneManager = new SceneManager; g_Logger = new Logger; g_AudioEngine = new AudioEngine; g_Randomizer = new Randomizer; g_PlayerPref = new PlayerPref; g_Io = new IO; g_Io->Window = std::make_unique<GlfwWindow>(); g_Io->Input = std::make_unique<GlfwInput>(); g_Io->Time = std::make_unique<GlfwTime>(); GLContext::Init(reinterpret_cast<GLContext::ProcAddr>(glfwGetProcAddress)); g_ShaderHelper = new GLShaderHelper; g_DebugDrawing = new GLDebugDrawing; g_MeshHelper = new GLMeshHelper; g_MeshHelper->Quad.Material = g_MeshHelper->Circle.Material = g_MeshHelper->Cube.Material = g_MeshHelper->Sphere.Material = &g_MeshHelper->Default; g_ResourceManager = new ResourceManager; g_Io->Window->SetTitle("Reality Engine"); g_Io->Window->SetPos({ 250.f, 150.f }); auto& scene{ g_SceneManager->CreateScene("Scene0") }; SceneSerializer::Load("Resources/Scenes.json", scene); } Reality::GameEngine::~GameEngine() { SceneSerializer::Save("Resources/Scenes.json", *g_SceneManager->ActiveScene); delete g_ResourceManager; delete g_SceneManager; delete g_Logger; delete g_AudioEngine; delete g_ShaderHelper; delete g_MeshHelper; delete g_DebugDrawing; delete g_Randomizer; delete g_PlayerPref; delete g_Io; } void Reality::GameEngine::Update() { g_ResourceManager->Update(); } RE_CORE Reality::PlayerPref* Reality::g_PlayerPref{}; RE_CORE Reality::Randomizer* Reality::g_Randomizer{}; RE_CORE Reality::Logger* Reality::g_Logger{}; RE_CORE Reality::SceneManager* Reality::g_SceneManager{}; RE_CORE Reality::AudioEngine* Reality::g_AudioEngine{}; RE_CORE Reality::GLShaderHelper* Reality::g_ShaderHelper{}; RE_CORE Reality::GLDebugDrawing* Reality::g_DebugDrawing{}; RE_CORE Reality::GLMeshHelper* Reality::g_MeshHelper{}; RE_CORE Reality::IO* Reality::g_Io{}; RE_CORE Reality::ResourceManager* Reality::g_ResourceManager{}; const Reality::Quaternion Reality::Quaternion::Identity{ 0.f, 0.f, 0.f, 1.f }; const Reality::Matrix4 Reality::Matrix4::Zero{}; const Reality::Matrix4 Reality::Matrix4::Identity{ 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f }; const Reality::Vector4 Reality::Vector4::Back{ 0.f, 0.f, -1.f, 1.f }; const Reality::Vector4 Reality::Vector4::Down{ 0.f, -1.f, 0.f, 1.f }; const Reality::Vector4 Reality::Vector4::Forward{ 0.f, 0.f, 1.f, 1.f }; const Reality::Vector4 Reality::Vector4::Left{ -1.f, 0.f, 0.f, 1.f }; const Reality::Vector4 Reality::Vector4::One{ 1.f, 1.f, 1.f, 1.f }; const Reality::Vector4 Reality::Vector4::Right{ 1.f, 0.f, 0.f, 1.f }; const Reality::Vector4 Reality::Vector4::Up{ 0.f, 1.f, 0.f, 1.f }; const Reality::Vector4 Reality::Vector4::Zero{ 0.f, 0.f, 0.f, 0.f }; const Reality::Vector3 Reality::Vector3::Back{ 0.f, 0.f, -1.f }; const Reality::Vector3 Reality::Vector3::Down{ 0.f, -1.f, 0.f }; const Reality::Vector3 Reality::Vector3::Forward{ 0.f, 0.f, 1.f }; const Reality::Vector3 Reality::Vector3::Left{ -1.f, 0.f, 0.f }; const Reality::Vector3 Reality::Vector3::One{ 1.f, 1.f, 1.f }; const Reality::Vector3 Reality::Vector3::Right{ 1.f, 0.f, 0.f }; const Reality::Vector3 Reality::Vector3::Up{ 0.f, 1.f, 0.f }; const Reality::Vector3 Reality::Vector3::Zero{ 0.f, 0.f, 0.f }; const Reality::Vector2 Reality::Vector2::Down{ 0.f, -1.f }; const Reality::Vector2 Reality::Vector2::Left{ -1.f, 0.f }; const Reality::Vector2 Reality::Vector2::One{ 1.f, 1.f }; const Reality::Vector2 Reality::Vector2::Right{ 1.f, 0.f }; const Reality::Vector2 Reality::Vector2::Up{ 0.f, 1.f }; const Reality::Vector2 Reality::Vector2::Zero{ 0.f, 0.f };
38.474747
93
0.699396
Volta948
94a56834a38a173a81c91e308bac6853c89f697e
1,299
cpp
C++
llvm-clang/clang_mini_rpc/clang_mini_rpc_client.cpp
chromatic-universe/cci-llvm-clang-cpp
e2fcc54067237c5d68d629d00952cb0e525a1012
[ "MIT" ]
null
null
null
llvm-clang/clang_mini_rpc/clang_mini_rpc_client.cpp
chromatic-universe/cci-llvm-clang-cpp
e2fcc54067237c5d68d629d00952cb0e525a1012
[ "MIT" ]
null
null
null
llvm-clang/clang_mini_rpc/clang_mini_rpc_client.cpp
chromatic-universe/cci-llvm-clang-cpp
e2fcc54067237c5d68d629d00952cb0e525a1012
[ "MIT" ]
null
null
null
//clang_mini_rpc_client.cpp william k. johnson #include <iostream> #include <memory> #include <string> #include <thrift/protocol/TBinaryProtocol.h> #include <thrift/transport/TSocket.h> #include <thrift/transport/TTransportUtils.h> #include "gen-cpp/cci_mini_clang_rpc.h" using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace shared; using cci_rpc = cci_mini_clang_rpcClient; int main( int argc , char* argv[] ) { boost::shared_ptr<TTransport> socket( new TSocket( "localhost" , 9090 ) ); boost::shared_ptr<TTransport> transport( new TBufferedTransport( socket) ); boost::shared_ptr<TProtocol> protocol( new TBinaryProtocol(transport ) ); std::unique_ptr<cci_rpc> clang_rpc_client( new cci_rpc( protocol ) ); try { transport->open(); std::string str; std::string str_idx( "foo" ); try { clang_rpc_client->perform_diag( str , str_idx ); std::cout << str << "\n"; } catch( invalid_clang_op& err ) { std::cerr << err << "\n"; } transport->close(); } catch ( TException& tx ) { std::cerr << "error: " << tx.what() << std::endl; } return 0; }
24.055556
79
0.627406
chromatic-universe
94a5afc4e5dc980877c947b6ac3ec47d6ab1db74
26,883
cpp
C++
Extension.Viewer.ABR/Extension.Viewer.ABR.cpp
lusores/ABRViewer
64d3172651a904908589fc91276366ef3ef0489e
[ "MIT" ]
15
2017-05-15T15:52:24.000Z
2022-03-23T06:48:48.000Z
Extension.Viewer.ABR/Extension.Viewer.ABR.cpp
lusores/ABRViewer
64d3172651a904908589fc91276366ef3ef0489e
[ "MIT" ]
null
null
null
Extension.Viewer.ABR/Extension.Viewer.ABR.cpp
lusores/ABRViewer
64d3172651a904908589fc91276366ef3ef0489e
[ "MIT" ]
4
2017-09-07T10:55:36.000Z
2021-01-29T08:51:01.000Z
/* copyright (c) 1996 - 2008 Ivan Varzar. [email protected] All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "stdafx.h" #include "Helpers.h" #include "Resource.h" #include "DragDrop.h" #include "WalkingDead.h" #include "Extension.Viewer.ABR.h" namespace BigBrotherAndy { #define DEF_HELP L"navigate between brushes\tleft, right arrows, mouse wheel\r\nzoom in/out\t\t\tup, down arrows, mouse wheel with ctrl\r\ninverse color\t\t\tspace\r\nsend to photoshop\t\tenter (return)\r\nclose window\t\t\tright mouse click, escape\r\nnext file:\t\t\tpgdn \r\nprev file:\t\t\tpgup" CABRViewer::CABRViewer() : Window<CABRViewer>(0,0) { m_uItsShowTimeBaby = ShowBrokenHeart; m_dwMagicNumber = 0; m_pBrushes = 0; m_hDragCursor = m_hArrowCursor = 0; m_hDetailsFont = m_hSmileFont = m_hFont = m_hSmallFont = 0; m_hFrameBrush = m_hBackgroundBrush = 0; m_fZoomFactor = 1.0; m_clrBackground = 0x000000; m_clrHalfColor = 0x0F0F0F; m_clrQuaterColor = 0x9F9F9F; for ( unsigned int i = 0; i < 256; i++ ) { m_BlackPallette[i].rgbBlue = m_BlackPallette[i].rgbRed = m_BlackPallette[i].rgbGreen = 0xFF - i; m_BlackPallette[i].rgbReserved = 0; m_WhitePallette[i].rgbBlue = m_WhitePallette[i].rgbRed = m_WhitePallette[i].rgbGreen = i; m_WhitePallette[i].rgbReserved = 0; }; m_bIsDecodingIsActive = FALSE; m_bTerminateApplication = FALSE; m_pDropTarget = 0; } CABRViewer::~CABRViewer() { if ( m_pBrushes ) { m_pBrushes->Release(); }; if ( m_hDragCursor ) { DeleteObject ( m_hDragCursor ); }; if ( m_hArrowCursor ) { DeleteObject ( m_hArrowCursor ); }; if ( m_hSmallFont ) { DeleteObject ( m_hSmallFont ); }; if ( m_hFont ) { DeleteObject ( m_hFont ); }; if ( m_hSmileFont ) { DeleteObject ( m_hSmileFont ); }; if ( m_hDetailsFont ) { DeleteObject ( m_hDetailsFont ); }; if ( m_hFrameBrush ) { DeleteObject(m_hFrameBrush); }; if ( m_hBackgroundBrush ) { DeleteObject ( m_hBackgroundBrush ); }; } BOOL CABRViewer::Create(HINSTANCE hInstance) { // Take it m_hInstance = hInstance; //If the window class has not been registered, then do so. WNDCLASS wc; if ( !GetClassInfo ( m_hInstance, WINDOW_CLASS_NAME, &wc ) ) { wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = (WNDPROC)this->WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = m_hInstance; wc.hIcon = 0; wc.hCursor = LoadCursor ( 0, IDC_ARROW ); wc.hbrBackground = 0; wc.lpszMenuName = 0; wc.lpszClassName = WINDOW_CLASS_NAME; if ( !RegisterClass ( &wc ) ) { return FALSE; }; }; // Create the window. The WndProc will set m_hWnd if ( ! ( m_hWnd = CreateWindowEx ( WS_EX_ACCEPTFILES, WINDOW_CLASS_NAME, NULL, WS_OVERLAPPED | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, 500, 500, 0, 0, m_hInstance, (LPVOID)this )) ) { return FALSE; }; // Create arrow cursor m_hArrowCursor = LoadCursor ( NULL,IDC_ARROW ); m_hDragCursor = LoadCursor(NULL,IDC_CROSS); // Create font // Create font (lovely Tahoma family) m_hFont = CreateFont ( -112, 0, 0, 0, FW_DEMIBOLD, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Tahoma" ); m_hSmileFont = CreateFont ( -248, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Wingdings" ); m_hSmallFont = CreateFont ( -14, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Tahoma" ); m_hDetailsFont = CreateFont ( -11, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Tahoma" ); // Recolor(); // Show window ShowWindow ( m_hWnd, SW_SHOW ); // Update window UpdateWindow ( m_hWnd ); return TRUE; } void CABRViewer::Recolor() { m_clrBackground = ( ~m_clrBackground ) & 0x00FFFFFF; if ( m_clrBackground ) { m_clrHalfColor = 0x9F9F9F; m_clrQuaterColor = 0x0F0F0F; } else { m_clrHalfColor = 0x0F0F0F; m_clrQuaterColor = 0x9F9F9F; } // Clean-up if ( m_hFrameBrush ) { DeleteObject(m_hFrameBrush); }; if ( m_hBackgroundBrush ) { DeleteObject ( m_hBackgroundBrush ); }; // Yeah, baby! m_hFrameBrush = CreateSolidBrush ( m_clrHalfColor ); m_hBackgroundBrush = CreateSolidBrush ( m_clrBackground ); if ( m_pBrushes ) { for ( DWORD i = 0; i < m_pBrushes->Count(); i++ ) { if ( IAdobeBrush* pBrush = m_pBrushes->Get(i) ) { if ( pBrush->Type() == AdobeBrushTypeSampled ) { memcpy ( ((AdobeBrushDibData*)pBrush->Data())->oHeader->bmiColors + 1, m_clrBackground ? m_BlackPallette : m_WhitePallette, 256 * sizeof(RGBQUAD) ); }; pBrush->Release(); }; }; }; } LRESULT CABRViewer::OnDrop ( STGMEDIUM* pstgmed, FORMATETC* pFormatEtc ) { // if ( !pFormatEtc && !pstgmed ) { return 0; }; // if ( pFormatEtc->cfFormat == CF_HDROP && pFormatEtc->tymed == TYMED_HGLOBAL ) { // we asked for the data as a HGLOBAL, so access it appropriately HDROP hDrop = (HDROP)GlobalLock(pstgmed->hGlobal); OnDropFiles ( hDrop ); GlobalUnlock ( pstgmed->hGlobal ); }; return 0x00; }; LRESULT CABRViewer::OnDropFiles ( HDROP hDrop ) { if ( !hDrop ) { return 0; }; WCHAR wsFileName[MAX_PATH]; if ( DragQueryFile ( hDrop, 0, wsFileName, MAX_PATH ) ) { YetAnotherBeginUnpack ( wsFileName ); m_WalkingDead.reset(); }; DragFinish(hDrop); return 0; } void CABRViewer::YetAnotherBeginUnpack ( WCHAR* wcsFileName ) { if ( m_uItsShowTimeBaby != ShowLoadingBrushes ) { m_uItsShowTimeBaby = ShowLoadingBrushes; m_dwMagicNumber = 0; if ( HDC hDC = GetDC ( m_hWnd ) ) { RECT rc; GetClientRect ( m_hWnd, &rc ); BufferedDrawWindow ( CBufferDC ( m_hWnd, hDC ), &rc ); ReleaseDC ( m_hWnd, hDC ); }; if ( m_pBrushes ) { m_pBrushes->Release(); m_pBrushes = 0; }; BeginUnpackAdobeBrushesPresetFile ( wcsFileName ); SetWindowText ( m_hWnd, wcsFileName ); }; } void CABRViewer::BufferedDrawWindow ( HDC hDC, RECT* prc ) { DrawWindow ( CBufferDC ( m_hWnd, hDC ), prc ); } void CABRViewer::DrawWindow ( HDC hDC, RECT* prc ) { // Hey, bro! FillRect ( hDC, prc, m_hBackgroundBrush ); // What do you wand to do today? switch ( m_uItsShowTimeBaby ) { case ShowBrokenHeart: { HFONT hOldFont = (HFONT)SelectObject ( hDC, m_hSmileFont ); SetBkMode ( hDC, TRANSPARENT ); SetTextColor ( hDC, m_clrHalfColor ); DrawText ( hDC, L"J", -1, prc, DT_CENTER | DT_VCENTER | DT_SINGLELINE ); SetTextColor ( hDC, m_clrQuaterColor ); hOldFont = (HFONT)SelectObject ( hDC, m_hSmallFont ); DrawText ( hDC, L"Drop point ;)", -1, prc, DT_CENTER | DT_VCENTER | DT_SINGLELINE ); SelectObject ( hDC, m_hDetailsFont ); prc->left += 10; prc->top += 10; DrawText ( hDC, DEF_HELP, -1, prc, DT_WORDBREAK | DT_EXPANDTABS ); SelectObject ( hDC, hOldFont ); }; break; case ShowLoadingBrushes: { HFONT hOldFont = (HFONT)SelectObject ( hDC, m_hFont ); WCHAR wsProgress[10]; wsprintf ( wsProgress, L"%d", m_dwMagicNumber ); SetBkMode ( hDC, TRANSPARENT ); SetTextColor ( hDC, m_clrHalfColor ); DrawText ( hDC, wsProgress, -1, prc, DT_CENTER | DT_VCENTER | DT_SINGLELINE ); SetTextColor ( hDC, m_clrQuaterColor ); hOldFont = (HFONT)SelectObject ( hDC, m_hSmallFont ); DrawText ( hDC, L"One moment please...", -1, prc, DT_CENTER | DT_VCENTER | DT_SINGLELINE ); SelectObject ( hDC, m_hDetailsFont ); prc->left += 10; prc->top += 10; DrawText ( hDC, DEF_HELP, -1, prc, DT_WORDBREAK | DT_EXPANDTABS ); SelectObject ( hDC, hOldFont ); }; break; case ShowSingleBrush: if ( m_pBrushes ) { if ( IAdobeBrush* pBrush = m_pBrushes->Get ( m_dwCurrentBrush ) ) { RECT rc; memcpy ( &rc, prc, sizeof(RECT) ); OffsetRect ( &rc, -rc.left + 10, -rc.top + 10); double width = rc.right - rc.left - 20; double height = rc.bottom - rc.top - 20; double w = pBrush->Width(); double h = pBrush->Height(); double raten = min(1, min ((width/w), (height/h))); h *= ( raten * m_fZoomFactor ); w *= ( raten * m_fZoomFactor ); double pointx = ( width - w ) / 2 + 10 + m_ptOffset.x; double pointy = ( height - h ) / 2 + 10 + m_ptOffset.y; if ( pBrush->Type() == 1 ) { w = rc.right - rc.left; h = rc.bottom - rc.top; pointx = rc.left; pointy = rc.top; }; SetBkColor ( hDC,m_clrHalfColor ); SetBkMode ( hDC, TRANSPARENT ); if ( w < pBrush->Width() || h < pBrush->Height() ) { SetStretchBltMode(hDC, HALFTONE ); } else { SetStretchBltMode(hDC, BLACKONWHITE ); }; ////////////////////////////////////////////////////////////////////////// if ( pBrush->Type() == AdobeBrushTypeSampled ) { // Draw pixels to window StretchDIBits ( hDC, (int)pointx, (int)pointy, (int)w, (int)h, 0, 0, pBrush->Width(), pBrush->Height(), ((AdobeBrushDibData*)pBrush->Data())->pBits, ((AdobeBrushDibData*)pBrush->Data())->oHeader, DIB_RGB_COLORS, SRCCOPY ); } else { HFONT hOldFont = (HFONT)SelectObject ( hDC, m_hSmileFont ); SetTextColor ( hDC, m_clrHalfColor ); DrawText ( hDC, L"A", -1, prc, DT_CENTER | DT_VCENTER | DT_SINGLELINE ); SetTextColor ( hDC, m_clrQuaterColor ); SelectObject ( hDC, m_hSmallFont ); DrawText ( hDC, L"Sampled brush", -1, prc, DT_CENTER | DT_VCENTER | DT_SINGLELINE ); SelectObject ( hDC, hOldFont ); } RECT rcText; rcText.top = prc->bottom - 80; rcText.bottom = rcText.top + 50; rcText.left = 0; rcText.right = 180; FillRect ( hDC, &rcText, m_hFrameBrush ); SetTextColor ( hDC,0xFFFFFF ); rcText.left += 10; rcText.top += 10; HFONT hOldFont = (HFONT)SelectObject ( hDC, m_hDetailsFont ); if ( IAdobeProperty* pProperty = pBrush->GetProperty ( L"Nm ", 4, PropertyTypeText ) ) { WCHAR* Name = wcsstr ( pProperty->Value().wValue, L"=" ); DrawText ( hDC, Name ? Name + 1 : pProperty->Value().wValue, -1, &rcText, DT_LEFT | DT_TOP ); pProperty->Release(); } else { DrawText ( hDC, L"Unnamed brush", -1, &rcText, DT_LEFT | DT_TOP ); } rcText.top += 12; WCHAR wsSize[60]; wsprintf ( wsSize, L"%d of %d. Sample size: %dpx", m_dwCurrentBrush + 1, m_pBrushes->Count(), max(pBrush->Width(), pBrush->Height()) ); DrawText ( hDC, wsSize, -1, &rcText, DT_LEFT | DT_TOP ); SelectObject ( hDC, hOldFont ); ////////////////////////////////////////////////////////////////////////// HRGN hrgn = CreateRectRgn(min(m_rcClip.left,(long)pointx), min(m_rcClip.top,(long)pointy), max(m_rcClip.right,(long)(pointx+w)), max(m_rcClip.bottom,(long)(pointy+h)) ); SelectClipRgn ( hDC, hrgn ); m_rcClip.left = (long)pointx; m_rcClip.top = (long)pointy; m_rcClip.right = m_rcClip.left + (long)w; m_rcClip.bottom = m_rcClip.top + (long)h; pBrush->Release(); }; }; break; case ShowMultipleBrushes: // Always halftone stretch mode SetStretchBltMode(hDC, HALFTONE ); if ( m_pBrushes ) { RECT rc; memcpy ( &rc, prc, sizeof(RECT) ); OffsetRect ( &rc, -rc.left + 10, -rc.top + 10 ); rc.bottom -= 20; rc.right -= 20; int count = (int)(1 / m_fZoomFactor ); int offset = 10; int width = ( offset + rc.right - rc.left ) / (long)(1 / m_fZoomFactor) - offset; int height = ( offset + rc.bottom - rc.top ) / (long)(1 / m_fZoomFactor) - offset; for ( int y = 0; y < count ; y++ ) { for ( int x = 0; x < count; x++ ) { if ( IAdobeBrush* pBrush = m_pBrushes->Get ( m_dwCurrentBrush + y * count + x ) ) { RECT rcBrush; rcBrush.left = rc.left + ( width + offset ) * x; rcBrush.right = rcBrush.left + width; rcBrush.top = rc.top + ( height + offset ) * y; rcBrush.bottom = rcBrush.top + height; FrameRect ( hDC, &rcBrush, m_hFrameBrush ); double raten = min(1, min (((width-4.0)/pBrush->Width()), ((height-4.0)/pBrush->Height()))); int w = (int)(raten * pBrush->Width()); int h = (int)(raten * pBrush->Height()); if ( pBrush->Type() == AdobeBrushTypeSampled ) { // Draw pixels to window StretchDIBits ( hDC, rcBrush.left + ( width - w ) / 2, rcBrush.top + ( height - h ) / 2, (int)w, (int)h, 0, 0, pBrush->Width(), pBrush->Height(), ((AdobeBrushDibData*)pBrush->Data())->pBits, ((AdobeBrushDibData*)pBrush->Data())->oHeader, DIB_RGB_COLORS, SRCCOPY ); }; pBrush->Release(); }; }; }; }; break; }; } LRESULT CABRViewer::OnPaint() { // Small and simple PAINTSTRUCT ps; HDC hDC = BeginPaint ( m_hWnd, &ps ); RECT rc; GetClientRect ( m_hWnd, &rc ); BufferedDrawWindow( hDC, &rc ); EndPaint ( m_hWnd, &ps ); return 0; } LRESULT CABRViewer::OnEraseBkgnd(HDC hDC) { return 0x0; }; LRESULT CABRViewer::OnDestroy() { if ( m_bIsDecodingIsActive ) { m_bTerminateApplication = TRUE; ShowWindow ( m_hWnd, SW_HIDE ); } else { if ( m_pDropTarget ) { CDropTarget::UnregisterDropWindow ( m_hWnd, m_pDropTarget ); }; PostQuitMessage(0); }; return 0; } LRESULT CABRViewer::OnMouseMove(UINT uVirtualKey, int x, int y) { if ((uVirtualKey && MK_LBUTTON) && m_fBrushDrag ) { m_ptOffset.x += ( x - m_ptDragPoint.x ); m_ptOffset.y += ( y - m_ptDragPoint.y ); InvalidateRect ( m_hWnd, 0, FALSE ); // Save the coordinates of the mouse cursor. m_ptDragPoint.x = x; m_ptDragPoint.y = y; } return 0; } LRESULT CABRViewer::OnLButtonDown(UINT uVirtualKey, int x, int y) { RECT rc; GetWindowRect ( m_hWnd, &rc ); // Restrict the mouse cursor to the client area. This // ensures that the window receives a matching // WM_LBUTTONUP message. ClipCursor(&rc); // Save the coordinates of the mouse cursor. m_ptDragPoint.x = x; m_ptDragPoint.y = y; SetCursor ( m_hDragCursor ); SetClassLong ( m_hWnd, GCL_HCURSOR, (__int3264)(LONG_PTR)m_hDragCursor ); m_fBrushDrag = TRUE; return 0; } LRESULT CABRViewer::OnLButtonUp(UINT uVirtualKey, int x, int y) { // Check if ( m_fBrushDrag ) { m_fBrushDrag = FALSE; SetCursor ( m_hArrowCursor ); SetClassLong ( m_hWnd, GCL_HCURSOR, (__int3264)(LONG_PTR)m_hArrowCursor); // Release the mouse cursor. ClipCursor(0); }; return 0; } LRESULT CABRViewer::OnRButtonUp(UINT uVirtualKey, int x, int y) { return OnDestroy(); } LRESULT CABRViewer::OnLButtonDblClk ( UINT vkCode, int x, int y ) { if ( m_bIsDecodingIsActive || !m_wBrushesFile ) { return 0; }; // Lookup for photoshop executable if ( !m_wPhotoshopExecutable.get() ) { IEnumAssocHandlers* pEnumAssocHandlers = 0; if ( SUCCEEDED ( SHAssocEnumHandlers ( L".abr", ASSOC_FILTER_RECOMMENDED, &pEnumAssocHandlers ) ) && pEnumAssocHandlers ) { ULONG ulFetched = 0; IAssocHandler* pAssocHandler = 0; while ( SUCCEEDED ( pEnumAssocHandlers->Next(1, &pAssocHandler, &ulFetched ) ) && pAssocHandler ) { LPWSTR lpwExecutableName = 0; if ( SUCCEEDED ( pAssocHandler->GetName(&lpwExecutableName) ) && lpwExecutableName ) { if ( wcsstr ( lpwExecutableName, L"otoshop.exe" ) ) { size_t dwLenght; StringCchLength ( lpwExecutableName, MAX_PATH, &dwLenght ); m_wPhotoshopExecutable.reset ( new WCHAR[dwLenght+1] ); StringCchCopy ( m_wPhotoshopExecutable, dwLenght + 1, lpwExecutableName ); pAssocHandler->Release(); break; }; }; pAssocHandler->Release(); }; pEnumAssocHandlers->Release(); }; }; if ( m_wPhotoshopExecutable.get() ) { ShellExecute ( m_hWnd, 0, m_wPhotoshopExecutable, m_wBrushesFile, 0, SW_SHOW ); }; return 0; }; LRESULT CABRViewer::OnNcHitTest(WPARAM wParam, LPARAM lParam) { if ( ( GetKeyState (VK_CONTROL) & 0x8000 ) || ( GetKeyState ( GetSystemMetrics(SM_SWAPBUTTON) ? VK_LBUTTON : VK_RBUTTON ) & 0x8000 ) ) { return HTCLIENT; } else { return HTCAPTION; } } void CABRViewer::Zoom ( BOOL bOut, WORD xPos, WORD yPos ) { if ( bOut ) { if ( m_fZoomFactor == 1 ) { m_fZoomFactor = 0.5; m_uItsShowTimeBaby = ShowMultipleBrushes; InvalidateRect ( m_hWnd, 0, FALSE ); } else if ( m_fZoomFactor < 1 ) { if ( m_fZoomFactor != 0.125 ) { m_fZoomFactor /= 2; }; InvalidateRect ( m_hWnd, 0, FALSE ); } else { if ( m_fZoomFactor != 1 ) { m_fZoomFactor--; if ( m_fZoomFactor < 1 ) { m_fZoomFactor = 1; }; m_ptOffset.x /= 2; m_ptOffset.y /= 2; InvalidateRect ( m_hWnd, 0, FALSE ); }; } } else { if ( m_fZoomFactor < 1 ) { int count = (int)(1 / m_fZoomFactor ); RECT rcRect; GetWindowRect(m_hWnd, &rcRect); int x = ( xPos - rcRect.left ) / (( rcRect.right - rcRect.left ) / count ); int y = ( yPos - rcRect.top ) / (( rcRect.bottom - rcRect.top ) / count ); m_dwCurrentBrush += ( count * y + x ); if ( m_dwCurrentBrush >= m_pBrushes->Count() ) { m_dwCurrentBrush = m_pBrushes->Count() - 1; } m_fZoomFactor *= 2; if ( m_fZoomFactor == 1 ) { m_uItsShowTimeBaby = ShowSingleBrush; }; InvalidateRect ( m_hWnd, 0, FALSE ); } else if ( m_fZoomFactor != 10 ) { m_fZoomFactor++; if ( m_fZoomFactor > 10 ) { m_fZoomFactor = 10; }; InvalidateRect( m_hWnd, 0, FALSE ); }; }; } void CABRViewer::Move ( BOOL bForward ) { if ( m_pBrushes ) { switch ( m_uItsShowTimeBaby ) { case ShowSingleBrush: if ( bForward ) { if ( m_dwCurrentBrush != ( m_pBrushes->Count() - 1 ) ) { m_dwCurrentBrush++; m_fZoomFactor = 1; ZeroMemory ( &m_ptOffset, sizeof(POINT) ); InvalidateRect ( m_hWnd, 0, FALSE); }; } else { if ( m_dwCurrentBrush != 0 ) { m_dwCurrentBrush--; m_fZoomFactor = 1; ZeroMemory ( &m_ptOffset, sizeof(POINT) ); InvalidateRect ( m_hWnd, 0, FALSE); }; }; break; case ShowMultipleBrushes: { unsigned int count = (int)(1 / m_fZoomFactor ); count *= count; if ( bForward ) { if ( ( m_dwCurrentBrush + count ) < m_pBrushes->Count() ) { m_dwCurrentBrush += count; InvalidateRect ( m_hWnd, 0, FALSE); }; } else { if ( m_dwCurrentBrush && ( m_dwCurrentBrush < count ) ) { m_dwCurrentBrush = 0; InvalidateRect ( m_hWnd, 0, FALSE); } if ( m_dwCurrentBrush >= count ) { m_dwCurrentBrush -= count; InvalidateRect ( m_hWnd, 0, FALSE); }; }; } break; } }; } LRESULT CABRViewer::OnMouseWheel ( WORD wKeys, short zDelta, WORD xPos, WORD yPos ) { wKeys & MK_CONTROL ? Zoom ( ((short)zDelta) < 0, xPos, yPos ) : Move ( ((short)zDelta) < 0 ); return 0L; } LRESULT CABRViewer::OnKeyUp ( UINT vkKeyCode, UINT vkParams ) { BOOL bUpdate = FALSE; switch ( vkKeyCode ) { case VK_SPACE: Recolor(); bUpdate = TRUE; break; case VK_LEFT: Move ( FALSE ); bUpdate = TRUE; break; case VK_RIGHT: Move ( TRUE ); bUpdate = TRUE; break; case VK_UP: Zoom ( FALSE, 0, 0 ); bUpdate = TRUE; break; case VK_DOWN: Zoom ( TRUE, 0, 0 ); bUpdate = TRUE; break; case VK_ESCAPE: OnRButtonUp(0,0,0); break; case VK_RETURN: OnLButtonDblClk (0,0,0); break; case VK_NEXT: if ( !m_WalkingDead ) { m_WalkingDead.reset ( new _WalkingDead() ); m_WalkingDead->Enum ( m_wBrushesFile ); }; if ( m_WalkingDead->IsValid() ) { if ( WCHAR* wcsNewFile = m_WalkingDead->Next() ) { if ( m_uItsShowTimeBaby != ShowLoadingBrushes ) { YetAnotherBeginUnpack(wcsNewFile); }; }; } break; case VK_PRIOR: if ( !m_WalkingDead ) { m_WalkingDead.reset ( new _WalkingDead() ); m_WalkingDead->Enum ( m_wBrushesFile ); }; if ( m_WalkingDead->IsValid() ) { if ( WCHAR* wcsNewFile = m_WalkingDead->Prev() ) { if ( m_uItsShowTimeBaby != ShowLoadingBrushes ) { YetAnotherBeginUnpack(wcsNewFile); }; }; }; break; }; if ( bUpdate ) { if ( HDC hDC = GetDC ( m_hWnd ) ) { RECT rc; GetClientRect ( m_hWnd, &rc ); BufferedDrawWindow ( CBufferDC ( m_hWnd, hDC ), &rc ); ReleaseDC ( m_hWnd, hDC ); }; }; return 0xFF01; }; LRESULT CABRViewer::OnABRJobInProgress ( DWORD dwTotalBrushes, DWORD dwCurrentBrush ) { m_uItsShowTimeBaby = ShowLoadingBrushes; m_dwMagicNumber = dwCurrentBrush; if ( HDC hOriginalDC = GetDC ( m_hWnd ) ) { RECT rc; GetClientRect ( m_hWnd, &rc ); BufferedDrawWindow ( CBufferDC ( m_hWnd, hOriginalDC ), &rc ); ReleaseDC ( m_hWnd, hOriginalDC ); }; return 0L; } LRESULT CABRViewer::OnABRJobComplete ( DWORD dwTotalBrushes, IAdobeBrushes* pBrushes ) { m_uItsShowTimeBaby = ( dwTotalBrushes && pBrushes ) ? ShowSingleBrush : ShowBrokenHeart; m_dwCurrentBrush = 0; m_fZoomFactor = 1.0; if ( m_pBrushes ) { m_pBrushes->Release(); }; // // m_clrBackground = 0x000000; // Recolor(); m_pBrushes = pBrushes; m_dwMagicNumber = dwTotalBrushes; m_uItsShowTimeBaby = ShowMultipleBrushes; m_fZoomFactor = 0.5; if ( HDC hOriginalDC = GetDC ( m_hWnd ) ) { RECT rc; GetClientRect ( m_hWnd, &rc ); BufferedDrawWindow ( CBufferDC ( m_hWnd, hOriginalDC ), &rc ); ReleaseDC ( m_hWnd, hOriginalDC ); }; m_bIsDecodingIsActive = FALSE; if ( m_bTerminateApplication ) { if ( m_pDropTarget ) { CDropTarget::UnregisterDropWindow ( m_hWnd, m_pDropTarget ); }; PostQuitMessage(0); }; return 0L; } BOOL CABRViewer::BeginUnpackAdobeBrushesPresetFile(WCHAR* wcsFileName) { // // m_clrBackground = 0xFFFFFF; // Recolor(); m_bIsDecodingIsActive = TRUE; size_t dwLenght; StringCchLength ( wcsFileName, MAX_PATH, &dwLenght ); m_wBrushesFile.reset ( new WCHAR[dwLenght+1] ); StringCchCopy ( m_wBrushesFile, dwLenght+1, wcsFileName ); ReadAdobePhotoshopBrushFile ( wcsFileName, AdobeBrushDataTypeFile, AdobeBrushDataTypeDIB, UnpackingJobCallback, this ); return TRUE; } BOOL CABRViewer::UnpackingJobCallback ( ABRPARSER_JOB* pJobStatus ) { if ( pJobStatus ) { if ( pJobStatus->bJobFinished ) { SendMessage ( ((CABRViewer*)(pJobStatus->pParam))->m_hWnd, WM_ABRJOBCOMPLETE, (WPARAM)pJobStatus->dwBrushesTotal, (LPARAM)pJobStatus->pBrushes ); } else { SendMessage ( ((CABRViewer*)(pJobStatus->pParam))->m_hWnd, WM_ABRJOBINPROGRESS, (WPARAM)pJobStatus->dwBrushesTotal, (LPARAM)pJobStatus->dwCurrentBrush ); } }; return TRUE; } } CABRViewer g_AdobeBrushViewerApp; typedef BOOL (__stdcall *CHANGEWINDOWMESSAGEFILTER)( UINT message, DWORD dwFlag); int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { // MSG msg; HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_EXTENSIONVIEWERABR)); WCHAR** szArgList; int argCount; g_AdobeBrushViewerApp.m_uItsShowTimeBaby = ShowLoadingBrushes; // Create application instance g_AdobeBrushViewerApp.Create ( hInstance ); // Parse command line szArgList = CommandLineToArgvW ( GetCommandLine(), &argCount ); if ( szArgList && argCount >= 2 ) { g_AdobeBrushViewerApp.BeginUnpackAdobeBrushesPresetFile ( szArgList[1] ); SetWindowText ( g_AdobeBrushViewerApp.m_hWnd, szArgList[1] ); } else { g_AdobeBrushViewerApp.m_uItsShowTimeBaby = ShowBrokenHeart; SetWindowText ( g_AdobeBrushViewerApp.m_hWnd, L"Lightweight .ABR Viewer" ); InvalidateRect ( g_AdobeBrushViewerApp.m_hWnd, 0, FALSE ); }; if ( OleInitialize(0) != S_OK || !CDropTarget::RegisterDropWindow ( g_AdobeBrushViewerApp.m_hWnd, &g_AdobeBrushViewerApp.m_pDropTarget ) ) { if ( HMODULE hUser32 = LoadLibrary(L"user32.dll" ) ) { if ( CHANGEWINDOWMESSAGEFILTER fnChangeWindowMessageFilter = (CHANGEWINDOWMESSAGEFILTER)GetProcAddress ( hUser32, "ChangeWindowMessageFilter") ) { fnChangeWindowMessageFilter ( 73 , MSGFLT_ADD ); fnChangeWindowMessageFilter ( WM_DROPFILES, MSGFLT_ADD); } FreeLibrary(hUser32); }; DragAcceptFiles ( g_AdobeBrushViewerApp.m_hWnd, TRUE ); } // Enter main message loop while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); }; }; // anyway we're going out of there // so one and only one failed call is not a bug // ... // i think OleUninitialize(); return (int) msg.wParam; }
29.803769
301
0.621582
lusores
94a7e264c212454507fb4d9832d699e9d812651f
2,727
cpp
C++
unit_tests/test_supportvectormachine.cpp
BrentP-tmx/Pamplemousse
6cd69d3369bf557c344d9a3a82b9c15f2381c366
[ "Apache-2.0" ]
6
2020-09-23T15:38:28.000Z
2021-11-16T20:39:21.000Z
unit_tests/test_supportvectormachine.cpp
BrentP-tmx/Pamplemousse
6cd69d3369bf557c344d9a3a82b9c15f2381c366
[ "Apache-2.0" ]
null
null
null
unit_tests/test_supportvectormachine.cpp
BrentP-tmx/Pamplemousse
6cd69d3369bf557c344d9a3a82b9c15f2381c366
[ "Apache-2.0" ]
2
2021-10-04T22:16:48.000Z
2022-02-25T00:32:40.000Z
// Copyright 2018-2020 Lexis Nexis Risk Solutions // // 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. // // Created by Caleb Moore on 24/11/18. // #include <stdio.h> #include "Cuti.h" #include "document.hpp" #include "testutils.hpp" using namespace TestUtils; TEST_CLASS (TestSupportVectorMachine) { public: void testSVM() { tinyxml2::XMLDocument document; CPPUNIT_ASSERT_EQUAL(tinyxml2::XML_SUCCESS, document.LoadFile(getPathToFile("SupportVectorXor.pmml").c_str())); lua_State * L; std::string prediction; L = makeState(document); CPPUNIT_ASSERT(L != nullptr); // This model is just an xor function... treat it like that for (int testCase = 0; testCase < 4; ++testCase) { int x = testCase % 2; int y = testCase / 2; CPPUNIT_ASSERT(executeModel(L, "x1", x , "x2", y)); CPPUNIT_ASSERT_EQUAL(true, getValue(L, "class", prediction)); CPPUNIT_ASSERT_EQUAL(std::string(x != y ? "yes" : "no"), prediction); } } void testBinaryClass() { tinyxml2::XMLDocument document; CPPUNIT_ASSERT_EQUAL(tinyxml2::XML_SUCCESS, document.LoadFile(getPathToFile("SupportVectorBinary.pmml").c_str())); lua_State * L; std::string prediction; L = makeState(document); CPPUNIT_ASSERT(L != nullptr); CPPUNIT_ASSERT(executeModel(L, "Age", 14 , "Employment", "Consultant")); CPPUNIT_ASSERT_EQUAL(true, getValue(L, "TARGET", prediction)); CPPUNIT_ASSERT_EQUAL(std::string("1"), prediction); CPPUNIT_ASSERT(executeModel(L, "Age", 14 , "Employment", "SelfEmp")); CPPUNIT_ASSERT_EQUAL(true, getValue(L, "TARGET", prediction)); CPPUNIT_ASSERT_EQUAL(std::string("0"), prediction); CPPUNIT_ASSERT(executeModel(L, "Age", 34 , "Employment", "SelfEmp")); CPPUNIT_ASSERT_EQUAL(true, getValue(L, "TARGET", prediction)); CPPUNIT_ASSERT_EQUAL(std::string("1"), prediction); } CPPUNIT_TEST_SUITE(TestSupportVectorMachine); CPPUNIT_TEST(testSVM); CPPUNIT_TEST(testBinaryClass); CPPUNIT_TEST_SUITE_END(); };
34.518987
122
0.650532
BrentP-tmx
94ad15b7992a92d00844ca3b0402a9c6b2cd0ec0
311
cpp
C++
Get_Started_contest/8.find_me.cpp
MadanParth786/Codeshef_DSA_learning_Series
0582c5a1598c2233c9ab433ce71feb9816166bc7
[ "MIT" ]
2
2021-07-03T09:00:06.000Z
2021-07-03T09:46:27.000Z
Get_Started_contest/8.find_me.cpp
MadanParth786/Codeshef_DSA_learning_Series
0582c5a1598c2233c9ab433ce71feb9816166bc7
[ "MIT" ]
null
null
null
Get_Started_contest/8.find_me.cpp
MadanParth786/Codeshef_DSA_learning_Series
0582c5a1598c2233c9ab433ce71feb9816166bc7
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main(void) { int n,k; bool found=false; int a[n]; cin>>n>>k; for(int i=0;i<n;i++) { cin>>a[i]; if(a[i]==k){ found=true; break; } } if(found){ cout<<"1"<<"\n"; } else{ cout<<"-1"<<"\n"; } }
11.518519
24
0.418006
MadanParth786
94b0fee0885891546ad81efcc2e98b090642d5d4
782
cpp
C++
Section 8/Video 3/locks.cpp
irshadqemu/C-Standard-Template-Library-in-Practice
05a52a03c2fc50031f065da41d89cfbf651499f9
[ "MIT" ]
17
2019-10-10T21:09:51.000Z
2022-01-13T15:54:24.000Z
Section 8/Video 3/locks.cpp
irshadqemu/C-Standard-Template-Library-in-Practice
05a52a03c2fc50031f065da41d89cfbf651499f9
[ "MIT" ]
null
null
null
Section 8/Video 3/locks.cpp
irshadqemu/C-Standard-Template-Library-in-Practice
05a52a03c2fc50031f065da41d89cfbf651499f9
[ "MIT" ]
16
2019-10-10T21:09:55.000Z
2022-02-13T11:42:52.000Z
#include <thread> #include <iostream> #include <mutex> #define TRANSACTIONS 100000 using namespace std; void deposit(int& account, mutex& m) { for (int i = 0; i < TRANSACTIONS; i++) { { lock_guard<mutex> lock(m); ++account; } } } void withdraw(int& account, mutex& m) { for (int i = 0; i < TRANSACTIONS; i++) { { lock_guard<mutex> lock(m); --account; } } } int main() { unsigned int threads = thread::hardware_concurrency(); cout << threads << " Threads supported\n"; int account = 0; mutex m; thread t1 (deposit, std::ref(account), std::ref(m)); thread t2 (withdraw, std::ref(account), std::ref(m)); t1.join(); t2.join(); cout << "After the threads, account value is: " << account << "\n"; return 0; }
17.377778
69
0.589514
irshadqemu
94b6a75b96c61ac067d3fa7995e4942a579bbe9a
3,092
cpp
C++
codeforces/F - Music in Car/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/F - Music in Car/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/F - Music in Car/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Jun/09/2020 16:14 * solution_verdict: Accepted language: GNU C++14 * run_time: 608 ms memory_used: 85600 KB * problem: https://codeforces.com/contest/746/problem/F ****************************************************************************************/ #include<iostream> #include<vector> #include<cstring> #include<map> #include<bitset> #include<assert.h> #include<algorithm> #include<iomanip> #include<cmath> #include<set> #include<queue> #include<unordered_map> #include<random> #include<chrono> #include<stack> #include<deque> #define long long long using namespace std; const int N=2e5; struct persistent { int l,r,sm,cn,od; }seg[N*20+2]; int rot[N+2],nw; void upd(int node,int pnode,int lo,int hi,int id,int vl) { if(lo==hi) { seg[node].sm=seg[pnode].sm+vl;seg[node].cn=seg[pnode].cn+1; seg[node].od=seg[pnode].od+vl%2;return ; } int md=(lo+hi)/2; if(id<=md) { if(!seg[node].l)seg[node].l=++nw;upd(seg[node].l,seg[pnode].l,lo,md,id,vl); seg[node].r=seg[pnode].r; } else { if(!seg[node].r)seg[node].r=++nw;upd(seg[node].r,seg[pnode].r,md+1,hi,id,vl); seg[node].l=seg[pnode].l; } seg[node].sm=seg[seg[node].l].sm+seg[seg[node].r].sm; seg[node].cn=seg[seg[node].l].cn+seg[seg[node].r].cn; seg[node].od=seg[seg[node].l].od+seg[seg[node].r].od; } pair<int,int>get(int node,int pnode,int lo,int hi,int k) { if(lo==hi) { assert(k==1);return {seg[node].sm-seg[pnode].sm,seg[node].od-seg[pnode].od}; } int md=(lo+hi)/2; int rm=seg[seg[node].l].cn-seg[seg[pnode].l].cn; if(rm>=k)return get(seg[node].l,seg[pnode].l,lo,md,k); else { pair<int,int>p=get(seg[node].r,seg[pnode].r,md+1,hi,k-rm); return {p.first+seg[seg[node].l].sm-seg[seg[pnode].l].sm,p.second+seg[seg[node].l].od-seg[seg[pnode].l].od}; } } int a[N+2],t[N+2],id[N+2]; int qm[N+2],od[N+2],w,k,n; pair<int,int>p[N+2]; bool ok(int i,int j) { long tt=0;int s=qm[j-1]-qm[i-1],o=od[j-1]-od[i-1]; if(j-i<=w)return (s+o)/2<=k; int rm=(j-i)-w; pair<int,int>p=get(rot[i],rot[j],1,n,rm); s-=p.first,o-=p.second; return p.first+(s+o)/2<=k; } int aa[N+2]; int main() { ios_base::sync_with_stdio(0);cin.tie(0); cin>>n>>w>>k; for(int i=1;i<=n;i++)cin>>a[i],aa[i]=aa[i-1]+a[i]; for(int i=1;i<=n;i++)cin>>t[i],p[i]={t[i],i}; for(int i=1;i<=n;i++) { qm[i]=qm[i-1]+t[i]; od[i]=od[i-1]+t[i]%2; } sort(p+1,p+n+1); for(int i=1;i<=n;i++)id[p[i].second]=i; int ans=0; for(int i=n;i>=1;i--) { rot[i]=++nw;upd(rot[i],rot[i+1],1,n,id[i],t[i]); if((t[i]+1)/2>k)continue; int lo=i,hi=n,md; while(hi-lo>2) { md=(lo+hi)/2; if(ok(i,md+1))lo=md; else hi=md; } for(md=hi;md>=lo;md--)if(ok(i,md+1))break; ans=max(ans,aa[md]-aa[i-1]); } cout<<ans<<endl; return 0; }
27.855856
112
0.518758
kzvd4729
94b71997dcf168861cb127f7c6f17f6248a1201b
7,968
hpp
C++
src/arch/pico/video/ssd1351.hpp
yocto-8/yocto-8
4911a82f399776731d3030234c731c15593f1910
[ "MIT" ]
22
2021-06-20T21:23:29.000Z
2022-03-26T01:46:10.000Z
src/arch/pico/video/ssd1351.hpp
yocto-8/yocto-8
4911a82f399776731d3030234c731c15593f1910
[ "MIT" ]
2
2021-09-06T12:08:32.000Z
2021-09-06T12:23:55.000Z
src/arch/pico/video/ssd1351.hpp
yocto-8/yocto-8
4911a82f399776731d3030234c731c15593f1910
[ "MIT" ]
1
2021-11-26T08:34:59.000Z
2021-11-26T08:34:59.000Z
#pragma once #include <hardware/gpio.h> #include <hardware/spi.h> #include <hardware/dma.h> #include <array> #include <cstdint> #include <cmath> #include <span> #include <emu/emulator.hpp> #include <devices/image.hpp> #include <devices/screenpalette.hpp> #include <video/palette.hpp> namespace arch::pico::video { static constexpr std::array<std::uint16_t, 32> rgb_palette_to_ssd1351_format(std::span<const std::uint32_t, 32> palette) { std::array<std::uint16_t, 32> ret{}; for (std::size_t i = 0; i < 32; ++i) { const std::uint32_t rgb8 = palette[i]; std::uint8_t r5 = ((rgb8 >> 16) & 0xFF) >> (8 - 5), g6 = ((rgb8 >> 8) & 0xFF) >> (8 - 6), b5 = ((rgb8 >> 0) & 0xFF) >> (8 - 5); ret[i] = (r5 << (5 + 6)) | (g6 << 5) | b5; // Swap LSB/MSB ret[i] = ((ret[i] & 0xFF) << 8) | (ret[i] >> 8); } return ret; } class SSD1351 { public: enum class Command : std::uint8_t { SET_COLUMN = 0x15, SET_ROW = 0x75, RAM_WRITE = 0x5C, RAM_READ = 0x5D, SET_REMAP = 0xA0, SET_START_LINE = 0xA1, SET_DISPLAY_OFFSET = 0xA2, DISPLAY_ALL_OFF = 0xA4, DISPLAY_ALL_ON = 0xA5, NORMAL_DISPLAY = 0xA6, INVERT_DISPLAY = 0xA7, SET_FUNCTION = 0xAB, DISPLAY_OFF = 0xAE, DISPLAY_ON = 0xAF, SET_PRECHARGE_PERIOD = 0xB1, MAGIC_ENHANCE_DISPLAY = 0xB2, //< no idea what this does, the datasheet is not any more clear SET_CLOCK_DIVIDER = 0xB3, SET_VSL = 0xB4, SET_GPIO = 0xB5, SET_PRECHARGE2_PERIOD = 0xB6, SET_GRAYSCALE_LUT = 0xB8, SET_DEFAULT_LUT = 0xB9, SET_PRECHARGE_VOLTAGE = 0xBB, SET_COM_DESELECT_VOLTAGE = 0xBE, SET_CHANNEL_CONTRAST = 0xC1, SET_GLOBAL_CONTRAST = 0xC7, SET_MUX_RATIO = 0xCA, SET_COMMAND_LOCK = 0xFD, SET_HORIZONTAL_SCROLL = 0x96, STOP_HORIZONTAL_SCROLL = 0x9E, START_HORIZONTAL_SCROLL = 0x9F }; struct Pinout { std::uint32_t sclk, tx, rst, cs, dc; }; struct Config { spi_inst_t* spi; Pinout pinout; }; void init(Config config) { _spi = config.spi; _pinout = config.pinout; gpio_set_function(_pinout.sclk, GPIO_FUNC_SPI); gpio_set_function(_pinout.tx, GPIO_FUNC_SPI); gpio_init(_pinout.rst); gpio_set_dir(_pinout.rst, GPIO_OUT); gpio_put(_pinout.rst, 1); gpio_init(_pinout.cs); gpio_set_dir(_pinout.cs, GPIO_OUT); gpio_put(_pinout.cs, 1); gpio_init(_pinout.dc); gpio_set_dir(_pinout.dc, GPIO_OUT); gpio_put(_pinout.dc, 0); reset_blocking(); submit_init_sequence(); /*_dma_channel = dma_claim_unused_channel(true); dma_channel_config dma_cfg = dma_channel_get_default_config(_dma_channel); channel_config_set_transfer_data_size(&dma_cfg, DMA_SIZE_32); channel_config_set_dreq(&dma_cfg, spi_get_index(spi_default) ? DREQ_SPI1_TX : DREQ_SPI0_TX);*/ } void load_rgb_palette(std::span<const std::uint32_t, 32> new_rgb_palette) { palette = rgb_palette_to_ssd1351_format(new_rgb_palette); } void reset_blocking() { gpio_put(_pinout.rst, 1); sleep_ms(1); gpio_put(_pinout.rst, 0); sleep_ms(1); gpio_put(_pinout.rst, 1); sleep_ms(1); } template<std::size_t N> using DataBuffer = std::array<std::uint8_t, N>; // scale 0x0..0xF void set_brightness(std::uint8_t scale) { write(Command::SET_GLOBAL_CONTRAST, DataBuffer<1>{scale}); } void submit_init_sequence() { // Enable MCU interface (else some commands will be dropped) write(Command::SET_COMMAND_LOCK, DataBuffer<1>{0x12}); write(Command::SET_COMMAND_LOCK, DataBuffer<1>{0xB1}); // Shut off the display while we set it up write(Command::DISPLAY_OFF); // Set clock division stuff and cover the entire screen write(Command::SET_CLOCK_DIVIDER, DataBuffer<1>{0xF0}); write(Command::SET_MUX_RATIO, DataBuffer<1>{127}); // 64K 16-bit format, enable split, CBA, correct rotation write(Command::SET_REMAP, DataBuffer<1>{0b01110100}); // Set display offsets write(Command::SET_START_LINE, DataBuffer<1>{0}); write(Command::SET_DISPLAY_OFFSET, DataBuffer<1>{0}); // Disable both GPIO pins write(Command::SET_GPIO, DataBuffer<1>{0x00}); // Set SPI interface, disable sleep mode write(Command::SET_FUNCTION, DataBuffer<1>{0b00'1}); // Timing tweaks write(Command::SET_PRECHARGE_PERIOD, DataBuffer<1>{0b0010'0010}); write(Command::SET_PRECHARGE2_PERIOD, DataBuffer<1>{0b0001}); // Voltage tweaks write(Command::SET_PRECHARGE_VOLTAGE, DataBuffer<1>{0b11111}); write(Command::SET_COM_DESELECT_VOLTAGE, DataBuffer<1>{0b111}); // Seems to be useless? //write(Command::MAGIC_ENHANCE_DISPLAY, DataBuffer<3>{0xA4, 0x00, 0x00}); // Display regular pixel data write(Command::NORMAL_DISPLAY); // Contrast settings write(Command::SET_CHANNEL_CONTRAST, DataBuffer<3>{0xFF, 0xFF, 0xFF}); //set_brightness(0xA); const float gamma = 1.25; //set_brightness(0xA); const float gamma = 1.0; set_brightness(0x5); const float gamma = 0.75; //set_brightness(0x3); const float gamma = 0.7; //set_brightness(0x2); const float gamma = 0.6; // Set cryptic command from the datasheet that does fuck knows write(Command::SET_VSL, DataBuffer<3>{0xA0, 0xB5, 0x55}); DataBuffer<63> gamma_lut; for (std::size_t i = 0; i < gamma_lut.size(); ++i) { gamma_lut[i] = round(180.0f * pow(i/63.0f, gamma)); } write(Command::SET_GRAYSCALE_LUT, gamma_lut); // Start display write(Command::DISPLAY_ON); } void write(Command command, std::span<const std::uint8_t> data = {}) { gpio_put(_pinout.dc, 0); gpio_put(_pinout.cs, 0); spi_write_blocking(_spi, reinterpret_cast<std::uint8_t*>(&command), 1); if (!data.empty()) { gpio_put(_pinout.dc, 1); spi_write_blocking(_spi, data.data(), data.size()); } gpio_put(_pinout.cs, 1); } void update_frame(devices::Framebuffer view, devices::ScreenPalette screen_palette) { //const auto time_start = get_absolute_time(); // SRAM writes should cover all the framebuffer (0..127) write(Command::SET_COLUMN, DataBuffer<2>{0, 127}); write(Command::SET_ROW, DataBuffer<2>{0, 127}); // Start write write(Command::RAM_WRITE); gpio_put(_pinout.dc, 1); gpio_put(_pinout.cs, 0); /*dma_channel_configure( _dma_channel, &dma_cfg, &spi_get_hw(_spi)->dr, emu::emulator.frame_buffer().data.data(), 8192 / 4, false);*/ for (std::size_t i = 0; i < view.frame_bytes; ++i) { const auto pixel_pair = std::array{ palette[screen_palette.get_color(view.data[i] & 0x0F)], palette[screen_palette.get_color(view.data[i] >> 4)] }; spi_write_blocking( _spi, reinterpret_cast<const std::uint8_t*>(pixel_pair.data()), 2 * pixel_pair.size() ); } gpio_put(_pinout.cs, 1); //const auto time_end = get_absolute_time(); //printf("%fms\n", absolute_time_diff_us(time_start, time_end) / 1000.0f); } std::array<std::uint16_t, 32> palette; private: //unsigned _dma_channel; spi_inst_t* _spi; Pinout _pinout; }; }
28.457143
120
0.593499
yocto-8
94bc4de85927f68c910556ea6200887766e422e4
16,007
cpp
C++
source/rastertechnique/clustervisibleprefixsumtechnique.cpp
AlejandroC1983/cvrtgi
9894fc79d4036a0490dbc194b9d04654574f16d4
[ "Apache-2.0" ]
2
2022-03-25T00:37:25.000Z
2022-03-26T00:13:53.000Z
source/rastertechnique/clustervisibleprefixsumtechnique.cpp
AlejandroC1983/cvrtgi
9894fc79d4036a0490dbc194b9d04654574f16d4
[ "Apache-2.0" ]
null
null
null
source/rastertechnique/clustervisibleprefixsumtechnique.cpp
AlejandroC1983/cvrtgi
9894fc79d4036a0490dbc194b9d04654574f16d4
[ "Apache-2.0" ]
1
2022-03-02T21:11:29.000Z
2022-03-02T21:11:29.000Z
/* Copyright 2022 Alejandro Cosin & Gustavo Patow 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. */ // GLOBAL INCLUDES // PROJECT INCLUDES #include "../../include/rastertechnique/clustervisibleprefixsumtechnique.h" #include "../../include/buffer/buffer.h" #include "../../include/buffer/buffermanager.h" #include "../../include/rastertechnique/clustervisibilitytechnique.h" #include "../../include/core/gpupipeline.h" #include "../../include/core/coremanager.h" #include "../../include/material/materialprefixsum.h" #include "../../include/util/bufferverificationhelper.h" #include "../../include/rastertechnique/bufferprefixsumtechnique.h" // NAMESPACE // DEFINES // STATIC MEMBER INITIALIZATION ///////////////////////////////////////////////////////////////////////////////////////////// ClusterVisiblePrefixSumTechnique::ClusterVisiblePrefixSumTechnique(string&& name, string&& className) : RasterTechnique(move(name), move(className)) , m_clusterVisibilityBuffer(nullptr) , m_clusterVisibilityCompactedBuffer(nullptr) , m_clusterVisibilityFirstIndexBuffer(nullptr) , m_prefixSumBuffer(nullptr) , m_clusterVisibilityTechnique(nullptr) , m_prefixSumPlanarBufferSize(0) , m_numberStepsReduce(0) , m_firstSetIsSingleElement(false) , m_numberStepsDownSweep(0) , m_currentStep(0) , m_currentPhase(0) , m_compactionStepDone(false) , m_firstIndexOccupiedElement(0) , m_currentStepEnum(PrefixSumStep_::PS_REDUCTION) , m_numElementAnalyzedPerThread(0) { m_active = false; m_needsToRecord = false; m_rasterTechniqueType = RasterTechniqueType::RTT_COMPUTE; m_computeHostSynchronize = true; } ///////////////////////////////////////////////////////////////////////////////////////////// void ClusterVisiblePrefixSumTechnique::init() { // Shader storage buffer used to store the whole prefix sum steps (reduction and sweepdown) // The buffer will be resized once slotClusterVisibility is called m_prefixSumBuffer = bufferM->buildBuffer( move(string("prefixSumBuffer")), nullptr, 256, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); // TODO: Rename to more generic, prefix sum values // TODO: Delete prefixSumBuffer once the prefix sum part is done m_clusterVisibilityBuffer = bufferM->getElement(move(string("clusterVisibilityBuffer"))); m_clusterVisibilityCompactedBuffer = bufferM->getElement(move(string("clusterVisibilityCompactedBuffer"))); m_clusterVisibilityFirstIndexBuffer = bufferM->getElement(move(string("clusterVisibilityFirstIndexBuffer"))); m_vectorMaterialName.resize(1); m_vectorMaterial.resize(1); m_vectorMaterialName[0] = string("MaterialPrefixSum"); m_vectorMaterial[0] = materialM->buildMaterial(move(string("MaterialPrefixSum")), move(string("MaterialPrefixSum")), nullptr); m_clusterVisibilityTechnique = static_cast<ClusterVisibilityTechnique*>(gpuPipelineM->getRasterTechniqueByName(move(string("ClusterVisibilityTechnique")))); m_clusterVisibilityTechnique->refSignalClusterVisibilityCompletion().connect<ClusterVisiblePrefixSumTechnique, &ClusterVisiblePrefixSumTechnique::slotClusterVisibility>(this); m_numElementAnalyzedPerThread = m_clusterVisibilityTechnique->getNumThreadPerLocalWorkgroup(); } ///////////////////////////////////////////////////////////////////////////////////////////// VkCommandBuffer* ClusterVisiblePrefixSumTechnique::record(int currentImage, uint& commandBufferID, CommandBufferType& commandBufferType) { MaterialPrefixSum* material = static_cast<MaterialPrefixSum*>(m_vectorMaterial[0]); commandBufferType = CommandBufferType::CBT_COMPUTE_QUEUE; VkCommandBuffer* commandBuffer; commandBuffer = addRecordedCommandBuffer(commandBufferID); addCommandBufferQueueType(commandBufferID, commandBufferType); coreM->allocCommandBuffer(&coreM->getLogicalDevice(), coreM->getComputeCommandPool(), commandBuffer); coreM->beginCommandBuffer(*commandBuffer); #ifdef USE_TIMESTAMP vkCmdWriteTimestamp(*commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, coreM->getComputeQueueQueryPool(), m_queryIndex0); #endif // Dispatch the compute shader to build the prefix sum, the buffer m_prefixSumPlanarBuffer // has all the required prefix sum level number of elements // Several dispatchs can be needed to complete the algorithm (depending on the number of elements // in the buffer), the method postQueueSubmit is used to coordinate the dispatchs vkCmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, material->getPipeline()->getPipeline()); uint dynamicAllignment = materialM->getMaterialUBDynamicAllignment(); uint32_t offsetData = static_cast<uint32_t>(material->getMaterialUniformBufferIndex() * dynamicAllignment); vkCmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, material->getPipelineLayout(), 0, 1, &material->refDescriptorSet(), 1, &offsetData); uint finalWorkgroupSize; // 0 means reduction step, 1 sweep down, 2 write final compacted buffer if (m_currentPhase == 0) { finalWorkgroupSize = m_vectorPrefixSumNumElement[m_currentStep]; } else if (m_currentPhase == 1) { finalWorkgroupSize = uint(ceilf(float(m_vectorPrefixSumNumElement[m_currentStep]) / float(m_numElementAnalyzedPerThread))); } else if (m_currentPhase == 2) { finalWorkgroupSize = m_vectorPrefixSumNumElement[0]; } vkCmdDispatch(*commandBuffer, finalWorkgroupSize, 1, 1); // Compute shader global workgroup https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html #ifdef USE_TIMESTAMP vkCmdWriteTimestamp(*commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, coreM->getComputeQueueQueryPool(), m_queryIndex1); #endif coreM->endCommandBuffer(*commandBuffer); // NOTE: Clear command buffer if re-recorded m_vectorCommand.push_back(commandBuffer); return commandBuffer; } ///////////////////////////////////////////////////////////////////////////////////////////// void ClusterVisiblePrefixSumTechnique::postCommandSubmit() { switch (m_currentStepEnum) { case PrefixSumStep_::PS_REDUCTION: { MaterialPrefixSum* material = static_cast<MaterialPrefixSum*>(m_vectorMaterial[0]); if ((m_currentStep + 1) < m_numberStepsReduce) { m_currentStep++; material->setCurrentStep(m_currentStep); } else { //BufferVerificationHelper::verifyPrefixSumData(); m_currentPhase++; material->setCurrentPhase(m_currentPhase); if (m_firstSetIsSingleElement) { m_currentStep--; material->setCurrentStep(m_currentStep); } m_firstIndexOccupiedElement = retrieveAccumulatedNumValues(); // Since the indices to the clusters are encoded using 16 bits, half of the amount of indices is needed uint bufferSize = uint(round(float(m_firstIndexOccupiedElement) / 2.0f)); //bufferM->resize(m_clusterVisibilityCompactedBuffer, nullptr, m_firstIndexOccupiedElement * sizeof(uint)); bufferM->resize(m_clusterVisibilityCompactedBuffer, nullptr, bufferSize * sizeof(uint)); m_currentStepEnum = PrefixSumStep_::PS_SWEEPDOWN; cout << "Total number of visible cluster from all voxel faces is " << m_firstIndexOccupiedElement << endl; cout << "Size m_clusterVisibilityCompactedBuffer=" << ((m_clusterVisibilityCompactedBuffer->getDataSize()) / 1024.0f) / 1024.0f << "MB" << endl; } break; } case PrefixSumStep_::PS_SWEEPDOWN: { MaterialPrefixSum* material = static_cast<MaterialPrefixSum*>(m_vectorMaterial[0]); if (m_currentStep > 0) { m_currentStep--; material->setCurrentStep(m_currentStep); } else { m_currentPhase++; m_currentStepEnum = PrefixSumStep_::PS_LAST_STEP; material->setCurrentPhase(m_currentPhase); } break; } case PrefixSumStep_::PS_LAST_STEP: { // Copy the data in prefixSumBuffer that contains, for each element in voxelHashedPositionCompactedBuffer // the indices where to get in clusterVisibilityCompactedBuffer the clusters visible for that voxel, // for each one of the six voxel faces. This is stored at the beginning of prefixSumBuffer // after the algorithm ends Buffer* prefixSumBuffer = bufferM->getElement(move(string("prefixSumBuffer"))); BufferPrefixSumTechnique* techniquePrefixSum = static_cast<BufferPrefixSumTechnique*>(gpuPipelineM->getRasterTechniqueByName(move(string("BufferPrefixSumTechnique")))); uint numOccupiedVoxel = techniquePrefixSum->getFirstIndexOccupiedElement(); uint numElementToCopy = numOccupiedVoxel * 6; // Resize the cluster visibility first index buffer, which is used in combination with clusterVisibilityNumberBuffer // and clusterVisibilityCompactedBuffer to know, for each voxel face of each generated voxel, where in // clusterVisibilityCompactedBuffer start the amount of visible clusters from that voxel bufferM->resize(m_clusterVisibilityFirstIndexBuffer, nullptr, numElementToCopy * sizeof(uint)); cout << "The size of the clusterVisibilityFirstIndexBuffer buffer is" << numElementToCopy * sizeof(uint) << endl; // Copy the content to clusterVisibilityFirstIndexBuffer, which is generated at the end of the prefix sum process // and is present in the prefixSumBuffer buffer bufferM->copyBuffer(prefixSumBuffer, m_clusterVisibilityFirstIndexBuffer, 0, 0, int(m_clusterVisibilityFirstIndexBuffer->getDataSize())); //BufferVerificationHelper::verifyClusterVisibilityFirstIndexBuffer(); //BufferVerificationHelper::verifyClusterVisibilityCompactedData(); m_compactionStepDone = true; m_active = false; m_executeCommand = false; m_needsToRecord = false; m_currentStepEnum = PrefixSumStep_::PS_FINISHED; m_signalClusterVisiblePrefixSumTechnique.emit(); // notify the prefix sum step has been completed /**/ //m_prefixSumBuffer vectorUint8 m_prefixSumBufferNumberBuffer; Buffer* clusterVisibilityNumberBuffer = bufferM->getElement(move(string("clusterVisibilityCompactedBuffer"))); clusterVisibilityNumberBuffer->getContentCopy(m_prefixSumBufferNumberBuffer); uint numClusterVisibilityNumberBuffer = uint(clusterVisibilityNumberBuffer->getDataSize()) / sizeof(uint); uint* pClusterVisibilityNumberBuffer = (uint*)(m_prefixSumBufferNumberBuffer.data()); // Now do a verification of clusterVisibilityFirstIndexBuffer //for (uint i = 0; i < numClusterVisibilityNumberBuffer; ++i) for (uint i = 0; i < 100; ++i) { uint temp = 0; uint decoded0 = pClusterVisibilityNumberBuffer[i]; decoded0 &= (0x0000FFFF << (temp * 16)); decoded0 >>= (temp * 16); temp = 1; uint decoded1 = pClusterVisibilityNumberBuffer[i]; decoded1 &= (0x0000FFFF << (temp * 16)); decoded1 >>= (temp * 16); cout << "i = " << i << ", decoded0=" << decoded0 << ", decoded1=" << decoded1 << endl; } /**/ break; } default: { cout << "ERROR: no enum value in ClusterVisiblePrefixSumTechnique::postCommandSubmit" << endl; break; } } } ///////////////////////////////////////////////////////////////////////////////////////////// void ClusterVisiblePrefixSumTechnique::slotClusterVisibility() { m_needsToRecord = true; m_active = true; // TODO: Put the code below in a utility method and refactor with BufferPrefixSumTechnique m_vectorPrefixSumNumElement.resize(5); // Up to four levels needed to the prefix parallel sum memset(m_vectorPrefixSumNumElement.data(), 0, m_vectorPrefixSumNumElement.size() * size_t(sizeof(uint))); // The amount of elements to process is the value of ClusterVisibilityTechnique::m_bufferNumElement // which is the amount of occupied voxels multiplied by the number of faces of each voxel (6) m_vectorPrefixSumNumElement[0] = m_clusterVisibilityTechnique->getBufferNumElement() / m_numElementAnalyzedPerThread; MaterialPrefixSum* material = static_cast<MaterialPrefixSum*>(m_vectorMaterial[0]); material->setNumElementBase(m_vectorPrefixSumNumElement[0]); material->setCurrentStep(m_currentStep); // The maximum number of elements in bufferHistogramBuffer is 536862720, // given that each thread processes 128 elements of bufferHistogramBuffer in the initial pass, up to // four levels are needed to complete the algorithm. float numElementPerThread = float(m_numElementAnalyzedPerThread); m_prefixSumPlanarBufferSize += uint(m_vectorPrefixSumNumElement[0]); float prefixSumNumElemenCurrentStep = float(m_vectorPrefixSumNumElement[0]); bool stop = ((prefixSumNumElemenCurrentStep / numElementPerThread) <= 1.0f); m_numberStepsReduce++; while (!stop) { prefixSumNumElemenCurrentStep = ceilf(prefixSumNumElemenCurrentStep / numElementPerThread); m_prefixSumPlanarBufferSize += uint(prefixSumNumElemenCurrentStep); m_vectorPrefixSumNumElement[m_numberStepsReduce] = uint(prefixSumNumElemenCurrentStep); stop = (prefixSumNumElemenCurrentStep <= 1.0f); m_numberStepsReduce++; } m_currentPhase = 0; m_compactionStepDone = false; m_firstIndexOccupiedElement = 0; material->setNumElementLevel0(m_vectorPrefixSumNumElement[1]); material->setNumElementLevel1(m_vectorPrefixSumNumElement[2]); material->setNumElementLevel2(m_vectorPrefixSumNumElement[3]); material->setNumElementLevel3(m_vectorPrefixSumNumElement[4]); material->setNumberStepsReduce(m_numberStepsReduce); material->setCurrentPhase(m_currentPhase); m_numberStepsDownSweep = m_numberStepsReduce; uint numElement = uint(m_vectorPrefixSumNumElement.size()); forI(numElement) { if (m_vectorPrefixSumNumElement[numElement - 1 - i] > 1) { if ((i > 0) && (m_vectorPrefixSumNumElement[numElement - i] == 1)) { m_firstSetIsSingleElement = true; m_numberStepsDownSweep--; } break; } } m_usedCommandBufferNumber = m_numberStepsReduce + m_numberStepsDownSweep + 2; material->setNumberStepsDownSweep(m_numberStepsDownSweep); bufferM->resize(m_prefixSumBuffer, nullptr, m_prefixSumPlanarBufferSize * sizeof(uint)); } ///////////////////////////////////////////////////////////////////////////////////////////// uint ClusterVisiblePrefixSumTechnique::retrieveAccumulatedNumValues() { // TODO: Set as utility function and reuse it in BufferPrefixSumTechnique, right now duplicated uint offsetIndex; uint numElementLastStep; uint maxIndex = uint(m_vectorPrefixSumNumElement.size()); forI(maxIndex) { if (m_vectorPrefixSumNumElement[maxIndex - i - 1] > 0) { numElementLastStep = m_vectorPrefixSumNumElement[maxIndex - i - 1]; offsetIndex = maxIndex - i - 1; break; } } uint offset = 0; forI(offsetIndex) { offset += m_vectorPrefixSumNumElement[i]; } vector<uint8_t> vectorReductionLastStep; vectorReductionLastStep.resize(numElementLastStep * sizeof(uint)); void* mappedMemory; VkResult result = vkMapMemory(coreM->getLogicalDevice(), m_prefixSumBuffer->getMemory(), offset * sizeof(uint), numElementLastStep * sizeof(uint), 0, &mappedMemory); assert(result == VK_SUCCESS); memcpy((void*)vectorReductionLastStep.data(), mappedMemory, numElementLastStep * sizeof(uint)); vkUnmapMemory(coreM->getLogicalDevice(), m_prefixSumBuffer->getMemory()); uint accumulated = 0; uint* pData = (uint*)(vectorReductionLastStep.data()); forI(numElementLastStep) { accumulated += pData[i]; } return accumulated; } /////////////////////////////////////////////////////////////////////////////////////////////
41.1491
176
0.736928
AlejandroC1983
94bf0b992b8a6ac778e64cd8ecba77d2f76f9d48
2,781
cpp
C++
aws-cpp-sdk-config/source/model/AggregateConformancePackCompliance.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-config/source/model/AggregateConformancePackCompliance.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-config/source/model/AggregateConformancePackCompliance.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/config/model/AggregateConformancePackCompliance.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace ConfigService { namespace Model { AggregateConformancePackCompliance::AggregateConformancePackCompliance() : m_complianceType(ConformancePackComplianceType::NOT_SET), m_complianceTypeHasBeenSet(false), m_compliantRuleCount(0), m_compliantRuleCountHasBeenSet(false), m_nonCompliantRuleCount(0), m_nonCompliantRuleCountHasBeenSet(false), m_totalRuleCount(0), m_totalRuleCountHasBeenSet(false) { } AggregateConformancePackCompliance::AggregateConformancePackCompliance(JsonView jsonValue) : m_complianceType(ConformancePackComplianceType::NOT_SET), m_complianceTypeHasBeenSet(false), m_compliantRuleCount(0), m_compliantRuleCountHasBeenSet(false), m_nonCompliantRuleCount(0), m_nonCompliantRuleCountHasBeenSet(false), m_totalRuleCount(0), m_totalRuleCountHasBeenSet(false) { *this = jsonValue; } AggregateConformancePackCompliance& AggregateConformancePackCompliance::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("ComplianceType")) { m_complianceType = ConformancePackComplianceTypeMapper::GetConformancePackComplianceTypeForName(jsonValue.GetString("ComplianceType")); m_complianceTypeHasBeenSet = true; } if(jsonValue.ValueExists("CompliantRuleCount")) { m_compliantRuleCount = jsonValue.GetInteger("CompliantRuleCount"); m_compliantRuleCountHasBeenSet = true; } if(jsonValue.ValueExists("NonCompliantRuleCount")) { m_nonCompliantRuleCount = jsonValue.GetInteger("NonCompliantRuleCount"); m_nonCompliantRuleCountHasBeenSet = true; } if(jsonValue.ValueExists("TotalRuleCount")) { m_totalRuleCount = jsonValue.GetInteger("TotalRuleCount"); m_totalRuleCountHasBeenSet = true; } return *this; } JsonValue AggregateConformancePackCompliance::Jsonize() const { JsonValue payload; if(m_complianceTypeHasBeenSet) { payload.WithString("ComplianceType", ConformancePackComplianceTypeMapper::GetNameForConformancePackComplianceType(m_complianceType)); } if(m_compliantRuleCountHasBeenSet) { payload.WithInteger("CompliantRuleCount", m_compliantRuleCount); } if(m_nonCompliantRuleCountHasBeenSet) { payload.WithInteger("NonCompliantRuleCount", m_nonCompliantRuleCount); } if(m_totalRuleCountHasBeenSet) { payload.WithInteger("TotalRuleCount", m_totalRuleCount); } return payload; } } // namespace Model } // namespace ConfigService } // namespace Aws
24.830357
139
0.781014
perfectrecall
94bfdbab5f07f61ff7b9b16d9a59b462641acf97
20,188
cpp
C++
source/magma/vulkan/render-engine-impl.cpp
Breush/lava
1b1b1f0785300b93b4a9f35fca4490502fea6552
[ "MIT" ]
15
2018-02-26T08:20:03.000Z
2022-03-06T03:25:46.000Z
source/magma/vulkan/render-engine-impl.cpp
Breush/lava
1b1b1f0785300b93b4a9f35fca4490502fea6552
[ "MIT" ]
32
2018-02-26T08:26:38.000Z
2020-09-12T17:09:38.000Z
source/magma/vulkan/render-engine-impl.cpp
Breush/lava
1b1b1f0785300b93b4a9f35fca4490502fea6552
[ "MIT" ]
null
null
null
#include "./render-engine-impl.hpp" #include "../aft-vulkan/scene-aft.hpp" #include "../shmag-reader.hpp" #include "./helpers/queue.hpp" #include "./holders/swapchain-holder.hpp" #include "./render-image-impl.hpp" #include "./render-targets/i-render-target-impl.hpp" #include "./stages/present.hpp" using namespace lava::magma; using namespace lava::chamber; RenderEngine::Impl::Impl(RenderEngine& engine) : m_engine(engine) , m_dummyImageHolder{*this, "magma.vulkan.render-engine.dummy-image"} , m_dummyNormalImageHolder{*this, "magma.vulkan.render-engine.dummy-normal-image"} , m_dummyInvisibleImageHolder{*this, "magma.vulkan.render-engine.dummy-invisible-image"} , m_dummyCubeImageHolder{*this, "magma.vulkan.render-engine.dummy-cube-image"} { // @note This VR initialisation has to be done before initVulkan, because we need // to get the extensions list to be enable. initVr(); initVulkan(); } RenderEngine::Impl::~Impl() { vr::VR_Shutdown(); device().waitIdle(); for (auto scene : m_scenes) { m_engine.sceneAllocator().deallocate(scene); } } void RenderEngine::Impl::update() { PROFILE_FUNCTION(PROFILER_COLOR_UPDATE); updateVr(); updateShaders(); for (auto scene : m_scenes) { scene->aft().update(); } // @note The difference between RenderTarget::Impl::update and RenderTarget::Impl::prepare // is that the latter should not update any UBOs. // For instance, VrRenderTarget update is updating the VrCameraController for the eyes, // and that should not be in prepare otherwise there might be concurrency issues with scene recording. for (auto renderTargetId = 0u; renderTargetId < m_renderTargetBundles.size(); ++renderTargetId) { auto& renderTargetBundle = m_renderTargetBundles[renderTargetId]; auto& renderTargetImpl = renderTargetBundle.renderTarget->interfaceImpl(); renderTargetImpl.update(); } } void RenderEngine::Impl::draw() { // @note This function does both render and draw, so no color. PROFILE_FUNCTION(); // We record all render scenes cameras once for (auto scene : m_scenes) { scene->aft().record(); } // Prepare all render targets for (auto renderTargetId = 0u; renderTargetId < m_renderTargetBundles.size(); ++renderTargetId) { auto& renderTargetBundle = m_renderTargetBundles[renderTargetId]; auto& renderTargetImpl = renderTargetBundle.renderTarget->interfaceImpl(); renderTargetBundle.prepareOk = renderTargetImpl.prepare(); } // Wait for all scenes to be done with recording for (auto sceneId = 0u; sceneId < m_scenes.size(); ++sceneId) { auto scene = m_scenes[sceneId]; scene->aft().waitRecord(); // Tracking if (m_logTracking) { logger.info("magma.render-engine") << "Render scene " << sceneId << "." << std::endl; logger.log().tab(1); logger.log() << "draw-calls.flat-renderer: " << tracker.counter("draw-calls.flat-renderer") << std::endl; logger.log() << "draw-calls.renderer: " << tracker.counter("draw-calls.renderer") << std::endl; logger.log() << "draw-calls.shadows: " << tracker.counter("draw-calls.shadows") << std::endl; logger.log().tab(-1); m_logTracking = false; } } // Submit all the command buffers and present to the render targets for (auto renderTargetId = 0u; renderTargetId < m_renderTargetBundles.size(); ++renderTargetId) { auto& renderTargetBundle = m_renderTargetBundles[renderTargetId]; if (!renderTargetBundle.prepareOk) continue; // Record command buffer each frame auto& renderTargetImpl = renderTargetBundle.renderTarget->interfaceImpl(); auto currentIndex = renderTargetImpl.currentBufferIndex(); const auto& commandBuffers = recordCommandBuffer(renderTargetId, currentIndex); renderTargetImpl.draw(commandBuffers); } } uint32_t RenderEngine::Impl::registerMaterialFromFile(const std::string& hrid, const fs::Path& shaderPath) { PROFILE_FUNCTION(PROFILER_COLOR_REGISTER); if (m_materialInfos.find(hrid) != m_materialInfos.end()) { logger.warning("magma.vulkan.render-engine").tab(1) << "Material " << hrid << " has already been registered." << std::endl; return m_materialInfos[hrid].id; } auto materialId = m_materialInfos.size(); logger.info("magma.vulkan.render-engine").tab(1) << "Registering material " << hrid << " as " << materialId << "." << std::endl; logger.log().tab(-1); // @note ShaderManager cannot handle shmag directly, it uses @magma:impl thingy // to be able to switch-case them or so in other renderer shaders. ShmagReader shmagReader(shaderPath); auto globalUniformDefinitions = shmagReader.globalUniformDefinitions(); auto uniformDefinitions = shmagReader.uniformDefinitions(); auto shaderImplementation = shmagReader.processedString(); if (shmagReader.errored()) { logger.warning("magma.vulkan.render-engine") << "Cannot register material " << hrid << ", shmag reading failed." << std::endl; return -1u; } // Start watching the file const auto watchId = m_shadersWatcher.watch(shaderPath); auto& materialInfo = m_materialInfos[hrid]; materialInfo.id = materialId; materialInfo.globalUniformDefinitions = globalUniformDefinitions; materialInfo.uniformDefinitions = uniformDefinitions; materialInfo.sourcePath = shaderPath; materialInfo.watchId = watchId; m_shadersManager.registerImplGroup(hrid, shaderImplementation, materialId); return materialId; } uint32_t RenderEngine::Impl::addView(RenderImage renderImage, IRenderTarget& renderTarget, const Viewport& viewport) { const auto& renderImageImpl = renderImage.impl(); if (renderImageImpl.uuid() == 0u) { logger.warning("magma.vulkan.render-engine") << "Trying to add a RenderImage with no uuid." << std::endl; return -1u; } if (!renderImageImpl.view()) { logger.warning("magma.vulkan.render-engine") << "Trying to add an empty RenderImage as a view." << std::endl; return -1u; } PROFILE_FUNCTION(PROFILER_COLOR_REGISTER); // Find the render target bundle uint32_t renderTargetId = renderTarget.interfaceImpl().id(); auto& renderTargetBundle = m_renderTargetBundles[renderTargetId]; // Create the new render view m_renderViews.emplace_back(); auto& renderView = m_renderViews.back(); renderView.renderImage = renderImage; renderView.renderTargetId = renderTargetId; // Add a new image to the present stage // @fixme We should be able to forward the RenderImage directly auto imageView = renderImageImpl.view(); auto imageLayout = renderImageImpl.layout(); auto channelCount = renderImageImpl.channelCount(); // @fixme Should be "compositorViewId"... renderView.presentViewId = renderTargetBundle.renderTarget->interfaceImpl().addView(imageView, imageLayout, m_dummySampler.get(), viewport, channelCount); return m_renderViews.size() - 1u; } void RenderEngine::Impl::removeView(uint32_t viewId) { // @todo Handle views individually, generating a really unique id // that has nothing to do with internal storage. if (viewId != m_renderViews.size() - 1u) { logger.warning("magma.vulkan.render-engine") << "Currently unable to remove a view that is not the last one added." << std::endl; return; } PROFILE_FUNCTION(PROFILER_COLOR_REGISTER); auto& renderView = m_renderViews[viewId]; auto& renderTargetBundle = m_renderTargetBundles[renderView.renderTargetId]; renderTargetBundle.renderTarget->interfaceImpl().removeView(renderView.presentViewId); m_renderViews.erase(std::begin(m_renderViews) + viewId); } //----- Adders void RenderEngine::Impl::add(Scene& scene) { const uint32_t sceneId = m_scenes.size(); logger.info("magma.vulkan.render-engine") << "Adding render scene " << sceneId << "." << std::endl; logger.log().tab(1); // If no device yet, the scene initialization will be postponed // until it is created. if (m_deviceHolder.device()) { scene.aft().init(); } m_scenes.emplace_back(&scene); logger.log().tab(-1); } void RenderEngine::Impl::add(std::unique_ptr<IRenderTarget>&& renderTarget) { logger.info("magma.vulkan.render-engine") << "Adding render target " << m_renderTargetBundles.size() << "." << std::endl; logger.log().tab(1); auto& renderTargetImpl = renderTarget->interfaceImpl(); // @todo This is probably not the right thing to do. // However - what can be the solution? // Device creation requires a surface, which requires a handle. // Thus, no window => unable to init the device. // So we init what's left of the engine right here, when adding a renderTarget. if (!m_deviceHolder.device()) { // @fixme We never call it with a surface, so all that thingy thing might not be useful... // But we *should* use it... Otherwise the selected queueFamily might not be adapted. // To do so, we need a flag on RenderEngine creation (usage: Vr, Window, Offscreen). // We would then init with surface only when a WindowRenderTarget is created, // if the Window flag is on. initVulkanDevice(nullptr); // initVulkanDevice(&renderTargetImpl.surface()); } uint32_t renderTargetId = m_renderTargetBundles.size(); renderTargetImpl.init(renderTargetId); m_renderTargetBundles.emplace_back(); auto& renderTargetBundle = m_renderTargetBundles.back(); renderTargetBundle.renderTarget = std::move(renderTarget); createCommandBuffers(renderTargetId); logger.log().tab(-1); } void RenderEngine::Impl::updateRenderViews(RenderImage renderImage) { auto& renderImageImpl = renderImage.impl(); if (!renderImageImpl.image()) return; if (renderImageImpl.uuid() == 0u) { logger.warning("magma.vulkan.render-engine") << "Updating render views for an unset RenderImage uuid." << std::endl; return; } // The renderImage has changed, we update all image views we were using from it for (auto& renderView : m_renderViews) { if (renderView.renderImage.impl().uuid() != renderImageImpl.uuid()) continue; auto& renderTargetBundle = m_renderTargetBundles[renderView.renderTargetId]; auto imageView = renderImageImpl.view(); auto imageLayout = renderImageImpl.layout(); renderTargetBundle.renderTarget->interfaceImpl().updateView(renderView.presentViewId, imageView, imageLayout, m_dummySampler.get()); } } const MaterialInfo& RenderEngine::Impl::materialInfo(const std::string& hrid) const { const auto iMaterialInfo = m_materialInfos.find(hrid); if (iMaterialInfo == m_materialInfos.end()) { logger.error("magma.vulkan.render-engine") << "Material '" << hrid << "' has not been registered." << std::endl; } return iMaterialInfo->second; } const MaterialInfo* RenderEngine::Impl::materialInfoIfExists(const std::string& hrid) const { const auto iMaterialInfo = m_materialInfos.find(hrid); if (iMaterialInfo == m_materialInfos.end()) { return nullptr; } return &iMaterialInfo->second; } void RenderEngine::Impl::createCommandPools(vk::SurfaceKHR* pSurface) { PROFILE_FUNCTION(PROFILER_COLOR_ALLOCATION); logger.info("magma.vulkan.render-engine") << "Creating command pool." << std::endl; auto queueFamilyIndices = vulkan::findQueueFamilies(physicalDevice(), pSurface); vk::CommandPoolCreateInfo createInfo; createInfo.queueFamilyIndex = queueFamilyIndices.graphics; createInfo.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer; auto result = device().createCommandPoolUnique(createInfo); m_commandPool = vulkan::checkMove(result, "render-engine", "Unable to create command pool."); createInfo.queueFamilyIndex = queueFamilyIndices.transfer; createInfo.flags = vk::CommandPoolCreateFlagBits(0x0); result = device().createCommandPoolUnique(createInfo); m_transferCommandPool = vulkan::checkMove(result, "render-engine", "Unable to create transfer command pool."); } void RenderEngine::Impl::createDummyTextures() { PROFILE_FUNCTION(PROFILER_COLOR_ALLOCATION); logger.info("magma.vulkan.render-engine") << "Creating dummy textures." << std::endl; // Plain white std::vector<uint8_t> dummyData = {0xFF, 0xFF, 0xFF, 0xFF}; m_dummyImageHolder.setup(dummyData, 1, 1, 4); // Flat blue dummyData = {0x80, 0x80, 0xFF, 0xFF}; // 0.5, 0.5, 1.0 m_dummyNormalImageHolder.setup(dummyData, 1, 1, 4); // Full zeros dummyData = {0x00, 0x00, 0x00, 0x00}; m_dummyInvisibleImageHolder.setup(dummyData, 1, 1, 4); // Plain transparent for cube maps std::vector<uint8_t> dummyCubeData = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; m_dummyCubeImageHolder.setup(dummyCubeData, 1, 1, 4, 6); // Sampler vk::SamplerCreateInfo createInfo; createInfo.magFilter = vk::Filter::eLinear; createInfo.minFilter = vk::Filter::eLinear; createInfo.addressModeU = vk::SamplerAddressMode::eRepeat; createInfo.addressModeV = vk::SamplerAddressMode::eRepeat; createInfo.addressModeW = vk::SamplerAddressMode::eRepeat; createInfo.anisotropyEnable = true; createInfo.maxAnisotropy = 16; // Over 16 is useless, but lower that for better performances createInfo.unnormalizedCoordinates = false; createInfo.compareEnable = false; createInfo.mipmapMode = vk::SamplerMipmapMode::eLinear; createInfo.maxLod = 10; auto result = device().createSamplerUnique(createInfo); m_dummySampler = vulkan::checkMove(result, "render-engine", "Unable to create dummy sampler."); // Shadows sampler createInfo.magFilter = vk::Filter::eLinear; createInfo.minFilter = vk::Filter::eLinear; createInfo.addressModeU = vk::SamplerAddressMode::eClampToBorder; createInfo.addressModeV = vk::SamplerAddressMode::eClampToBorder; createInfo.addressModeW = vk::SamplerAddressMode::eClampToBorder; createInfo.anisotropyEnable = false; createInfo.unnormalizedCoordinates = false; createInfo.compareEnable = false; createInfo.mipmapMode = vk::SamplerMipmapMode::eNearest; result = device().createSamplerUnique(createInfo); m_shadowsSampler = vulkan::checkMove(result, "render-engine", "Unable to create shadows sampler."); } std::vector<vk::CommandBuffer> RenderEngine::Impl::recordCommandBuffer(uint32_t renderTargetId, uint32_t bufferIndex) { PROFILE_FUNCTION(PROFILER_COLOR_RENDER); auto& renderTargetBundle = m_renderTargetBundles[renderTargetId]; if (bufferIndex >= renderTargetBundle.commandBuffers.size()) { logger.error("magma.vulkan.render-engine") << "Invalid bufferIndex during command buffers recording (" << bufferIndex << ") that should have been between 0 and " << renderTargetBundle.commandBuffers.size() - 1u << "." << std::endl; } //----- Render all scenes // @fixme Feels like we should be able to generate all render scenes images, // and use these directly without having to re-render everything. std::vector<vk::CommandBuffer> commandBuffers; for (auto scene : m_scenes) { const auto& sceneCommandBuffers = scene->aft().commandBuffers(); commandBuffers.insert(commandBuffers.end(), sceneCommandBuffers.begin(), sceneCommandBuffers.end()); } //----- Render targets' specific rendering auto commandBuffer = renderTargetBundle.commandBuffers[bufferIndex].get(); vk::CommandBufferBeginInfo beginInfo{vk::CommandBufferUsageFlagBits::eSimultaneousUse}; commandBuffer.begin(&beginInfo); // @todo The names are unclear, what's the difference between render and draw? // @fixme We probably don't need handle a render target command buffer by ourself // because this line is the only thing we do with it. renderTargetBundle.renderTarget->interfaceImpl().render(commandBuffer); commandBuffer.end(); commandBuffers.emplace_back(commandBuffer); return commandBuffers; } void RenderEngine::Impl::createCommandBuffers(uint32_t renderTargetId) { PROFILE_FUNCTION(PROFILER_COLOR_ALLOCATION); logger.log() << "Creating command buffers for render target " << renderTargetId << "." << std::endl; auto& renderTargetBundle = m_renderTargetBundles[renderTargetId]; auto& commandBuffers = renderTargetBundle.commandBuffers; // (Re-)allocate them all commandBuffers.resize(renderTargetBundle.renderTarget->interfaceImpl().buffersCount()); vk::CommandBufferAllocateInfo allocInfo; allocInfo.commandPool = m_commandPool.get(); allocInfo.level = vk::CommandBufferLevel::ePrimary; allocInfo.commandBufferCount = commandBuffers.size(); auto result = device().allocateCommandBuffersUnique(allocInfo); commandBuffers = vulkan::checkMove(result, "render-engine", "Unable to create command buffers."); } void RenderEngine::Impl::initScenes() { if (m_scenes.size() == 0u) return; PROFILE_FUNCTION(PROFILER_COLOR_INIT); logger.info("magma.vulkan.render-engine") << "Initializing render scenes." << std::endl; logger.log().tab(1); for (const auto& scene : m_scenes) { scene->aft().init(); } logger.log().tab(-1); } void RenderEngine::Impl::initVr() { PROFILE_FUNCTION(PROFILER_COLOR_INIT); logger.info("magma.vulkan.render-engine") << "Initializing VR." << std::endl; logger.log().tab(1); // @todo vr().init() / vr().update() should probably be called by RenderEngine itself (not Impl) // as this is not vulkan dependent m_engine.vr().init(); logger.log().tab(-1); } void RenderEngine::Impl::initVulkan() { PROFILE_FUNCTION(PROFILER_COLOR_INIT); logger.info("magma.vulkan.render-engine") << "Initializing vulkan." << std::endl; logger.log().tab(1); m_instanceHolder.init(true, m_engine.vr()); logger.log().tab(-1); } void RenderEngine::Impl::initVulkanDevice(vk::SurfaceKHR* pSurface) { PROFILE_FUNCTION(PROFILER_COLOR_INIT); logger.info("magma.vulkan.render-engine") << "Initializing vulkan device." << std::endl; logger.log().tab(1); m_deviceHolder.init(instance(), pSurface, m_instanceHolder.debugEnabled(), m_engine.vr()); createCommandPools(pSurface); createDummyTextures(); initScenes(); logger.log().tab(-1); } void RenderEngine::Impl::updateVr() { if (m_engine.vr().enabled()) { m_engine.vr().update(); } } void RenderEngine::Impl::updateShaders() { PROFILE_FUNCTION(PROFILER_COLOR_UPDATE); while (auto event = m_shadersWatcher.pollEvent()) { if (event->type == chamber::FileWatchEvent::Type::Modified) { auto materialPath = event->path; auto watchId = event->watchId; logger.info("magma.vulkan.render-engine") << "Material source file " << event->path << " has changed." << std::endl; logger.log().tab(1); auto materialInfo = std::find_if(m_materialInfos.begin(), m_materialInfos.end(), [&watchId](const auto& materialInfo) { return materialInfo.second.watchId == watchId; }); ShmagReader shmagReader(materialPath); auto shaderImplementation = shmagReader.processedString(); if (shmagReader.errored()) { logger.warning("magma.vulkan.render-engine") << "Cannot update watched material " << materialInfo->first << ", shmag reading failed." << std::endl; return; } m_shadersManager.updateImplGroup(materialInfo->first, shaderImplementation); logger.log().tab(-1); } } m_shadersManager.update(); }
37.594041
135
0.68932
Breush
94c0c556d4b31c5f87ff85882a08a0bbfa16e2c4
7,354
cc
C++
tests/test.cc
CS126SP20/final-project-ckesan2
419d4b5ecc21ba7d1f3412c05f0098e7130d3703
[ "MIT" ]
null
null
null
tests/test.cc
CS126SP20/final-project-ckesan2
419d4b5ecc21ba7d1f3412c05f0098e7130d3703
[ "MIT" ]
null
null
null
tests/test.cc
CS126SP20/final-project-ckesan2
419d4b5ecc21ba7d1f3412c05f0098e7130d3703
[ "MIT" ]
null
null
null
// Copyright (c) 2020 CS126SP20. All rights reserved. #define CATCH_CONFIG_MAIN #include <mylibrary/gameengine.h> #include <mylibrary/circle.h> #include <catch2/catch.hpp> TEST_CASE("Getting the correct score", "[game score]") { //makes sure the score is 0 at the start of the game mylibrary::GameEngine engine; REQUIRE(engine.GetScore() == 0); //makes sure score updated after increasing it SECTION("Add to the score") { engine.IncreaseScore(); REQUIRE(engine.GetScore() == 1); } //checks that score goes back to 0 after resetting the game SECTION("Reset score") { engine.IncreaseScore(); engine.IncreaseScore(); REQUIRE(engine.GetScore() == 2); engine.ResetGame(); REQUIRE(engine.GetScore() == 0); } } TEST_CASE("Accuracy of X Coordinates", "[coordinates]") { //checks that x coordinate changes after every call of getX mylibrary::Circle circle; int x = circle.getX(); int x2 = circle.getX(); REQUIRE(x != x2); } TEST_CASE("Accuracy of Y Coordinates", "[coordinates]") { //checks that y coordinate changes after every call of getY mylibrary::Circle circle; int y = circle.getY(); int y2 = circle.getY(); REQUIRE(y != y2); } TEST_CASE("X of Circle center is on screen", "[coordinates]") { //checks that the x coordinate is not off screen mylibrary::Circle circle; int x = circle.getX(); REQUIRE(!circle.XIsInWindow(1000)); REQUIRE(!circle.XIsInWindow(-1)); REQUIRE(x >= 0); REQUIRE(x <= 800); REQUIRE(circle.XIsInWindow(x)); } TEST_CASE("Y of Circle center is on screen", "[coordinates]") { //checks that the y coordinate is not off screen mylibrary::Circle circle; int y = circle.getY(); REQUIRE(!circle.YIsInWindow(800)); REQUIRE(!circle.YIsInWindow(-1)); REQUIRE(y >= 0); REQUIRE(y <= 680); REQUIRE(circle.YIsInWindow(y)); } TEST_CASE("Circle Not Clicked", "[location]") { //checks that the circle is not clicked if click is outside the radius mylibrary::GameEngine engine; int radius = 20; REQUIRE(!engine.ClickedCircle(20,20,200,200, radius)); SECTION("Off by 21 in x and y") { REQUIRE(!engine.ClickedCircle(20,20,41,41, radius)); } SECTION("Off by 21 in x") { REQUIRE(!engine.ClickedCircle(20,20,41,40, radius)); } SECTION("Off by 21 in y") { REQUIRE(!engine.ClickedCircle(20,20,40,41, radius)); } } TEST_CASE("Circle Is Clicked", "[location]") { //checks that the circle is clicked if click is inside the radius mylibrary::GameEngine engine; int radius = 20; REQUIRE(engine.ClickedCircle(20,20,20,20, radius)); SECTION("Click In range") { REQUIRE(engine.ClickedCircle(20,20,40,40, radius)); REQUIRE(engine.ClickedCircle(20,20,0,0, radius)); REQUIRE(engine.ClickedCircle(10,20,9,19, radius)); REQUIRE(engine.ClickedCircle(0,0,0,0, radius)); } SECTION("Circle partially off screen") { REQUIRE(engine.ClickedCircle(10,10,-1,-1, radius)); } } TEST_CASE("Picked Easy Game Mode", "[easy]") { //checks that inputted coordinates means that user clicked the easy mode mylibrary::GameEngine engine; //assigned variables for numbers to just it have be more intuitive with the //coordinates going into the function int mouse_x = 400; int mouse_y = 400; int center_x = 400; int center_y = 350; REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y) == "easy"); SECTION("Different x coordinates but in range of easy button") { mouse_x = 360; REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y) == "easy"); } } TEST_CASE("Picked Medium Game Mode", "[medium]") { //checks that inputted coordinates means that user clicked the medium mode mylibrary::GameEngine engine; int mouse_x = 200; int mouse_y = 400; int center_x = 200; int center_y = 300; REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y) == "medium"); SECTION("Different x coordinate but in range of medium button") { mouse_x = 145; REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y) == "medium"); } } TEST_CASE("Picked Hard Game Mode", "[hard]") { //checks that inputted coordinates means that user clicked the hard mode mylibrary::GameEngine engine; int mouse_x = 400; int mouse_y = 400; int center_x = 400; int center_y = 250; REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y) == "hard"); SECTION("Different x coordinates but in range of hard button") { mouse_x = 448; REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y) == "hard"); } } TEST_CASE("No Game Mode Picked", "[no game mode]") { //checks that these coordinates mean that the user has not clicked on a game //mode's coordinates mylibrary::GameEngine engine; int mouse_x = 0; int mouse_y = 0; int center_x = 0; int center_y = 0; REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y).empty()); SECTION("Different x coordinates and no game mode picked") { mouse_x = 400; REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y).empty()); } SECTION("Different y coordinates and no game mode picked") { mouse_y = 200; REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y).empty()); } SECTION("All same coordinates other than 0") { mouse_x = 100; mouse_y = 100; center_x = 100; center_y = 100; REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y).empty()); } SECTION("All different coordinates") { mouse_x = 100; mouse_y = 200; center_x = 300; center_y = 400; REQUIRE(engine.GetGameMode(mouse_x, mouse_y, center_x, center_y).empty()); } } TEST_CASE("Clicked on Item", "[picked item]") { //makes sure it returns true when the click is on the center of the image mylibrary::GameEngine engine; int mouse_x = 400; int mouse_y = 360; int item_centerx = 400; int item_centery = 360; int width = 100; int height = 100; REQUIRE(engine.ClickedItem(mouse_x, mouse_y, item_centerx, item_centery, width, height)); //make sure it returns true when the click is on the image but just not its //center SECTION("Not same coordinates") { REQUIRE(engine.ClickedItem(401, 361, 400, 360, 100, 100)); } //makes sure method returns true when the click is on the edge of the image SECTION("Edge of the item") { REQUIRE(engine.ClickedItem(200, 200, 250, 250, 100, 100)); REQUIRE(engine.ClickedItem(200, 200, 250, 200, 100, 100)); REQUIRE(engine.ClickedItem(200, 200, 300, 250, 200, 100)); REQUIRE(engine.ClickedItem(250, 350, 275, 375, 50, 50)); REQUIRE(engine.ClickedItem(0, 0, 0, 0, 0, 0)); } } TEST_CASE("Item Is Not Clicked", "[normal click]") { //checks that the method return false when the mouse does not click in the //image range mylibrary::GameEngine engine; int mouse_x = 400; int mouse_y = 360; int item_centerx = 1000; int item_centery = 1000; int width = 100; int height = 100; REQUIRE(!engine.ClickedItem(mouse_x, mouse_y, item_centerx, item_centery, width, height)); //checks that the method returns false when the click x and y coordinates //are both one off the edges of the image SECTION("Off By One") { REQUIRE(!engine.ClickedItem(100, 250, 201, 351, 200, 200)); REQUIRE(!engine.ClickedItem(400, 400, 299, 299, 200, 200)); } }
28.393822
80
0.684389
CS126SP20
94c556dd34cd648160958e09cea3be093ebe2b20
825
cpp
C++
Game/Scene/EnemyGuide/RollBackGround.cpp
IndistinQuest/Game
3c8363026388a452a1e1b5a46ff34bb8fa8baff4
[ "MIT" ]
2
2016-12-09T02:21:23.000Z
2017-08-31T13:49:13.000Z
Game/Scene/EnemyGuide/RollBackGround.cpp
IndistinQuest/Game
3c8363026388a452a1e1b5a46ff34bb8fa8baff4
[ "MIT" ]
null
null
null
Game/Scene/EnemyGuide/RollBackGround.cpp
IndistinQuest/Game
3c8363026388a452a1e1b5a46ff34bb8fa8baff4
[ "MIT" ]
null
null
null
#include "RollBackGround.h" const double RollBackGround::W = 1280; const double RollBackGround::H = 720; const int RollBackGround::ROLL_SPEED = 5; RollBackGround::RollBackGround(String firstAssetName, String secondAssetName) { firstAssetName_m = firstAssetName; secondAssetName_m = secondAssetName; fPoint_m = Point(0.5*W, 0.5*H); sPoint_m = Point(1.5*W, 0.5*H); } RollBackGround::~RollBackGround() { } void RollBackGround::update() { fPoint_m.x -= ROLL_SPEED; sPoint_m.x -= ROLL_SPEED; if (fPoint_m.x <= static_cast<int>(-0.5*W)) { fPoint_m.x = static_cast<int>(1.5*W); } if (sPoint_m.x <= static_cast<int>(-0.5*W)) { sPoint_m.x = static_cast<int>(1.5*W); } } void RollBackGround::draw() const { TextureAsset(firstAssetName_m).drawAt(fPoint_m); TextureAsset(secondAssetName_m).drawAt(sPoint_m); }
19.642857
77
0.718788
IndistinQuest
94d2717921df8f08be83a2babe28c834bda1d911
3,176
hpp
C++
cocos2d/cocos/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp
weiDDD/particleSystem
32652b09da35e025956999227f08be83b5d79cb1
[ "Apache-2.0" ]
34
2017-08-16T13:58:24.000Z
2022-03-31T11:50:25.000Z
cocos2d/cocos/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp
weiDDD/particleSystem
32652b09da35e025956999227f08be83b5d79cb1
[ "Apache-2.0" ]
null
null
null
cocos2d/cocos/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_manual.hpp
weiDDD/particleSystem
32652b09da35e025956999227f08be83b5d79cb1
[ "Apache-2.0" ]
17
2017-08-18T07:42:44.000Z
2022-01-02T02:43:06.000Z
/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_GENERATED_LUA_COCOS2DX_MANUAL_H #define COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_GENERATED_LUA_COCOS2DX_MANUAL_H #ifdef __cplusplus extern "C" { #endif #include "tolua++.h" #ifdef __cplusplus } #endif #include "cocos2d.h" #include "LuaScriptHandlerMgr.h" NS_CC_BEGIN class LuaEventListenerCustom { public: static EventListenerCustom* create(const std::string& eventName); }; class LuaEventListenerAcceleration { public: static EventListenerAcceleration* create(); }; NS_CC_END USING_NS_CC; TOLUA_API int register_all_cocos2dx_manual(lua_State* tolua_S); TOLUA_API int register_cocos2dx_event_releated(lua_State* tolua_S); TOLUA_API int register_all_cocos2dx_module_manual(lua_State* tolua_S); TOLUA_API int register_all_cocos2dx_math_manual(lua_State* tolua_S); struct LuaEventAccelerationData { void* acc; Event* event; LuaEventAccelerationData(void* inAcc,Event* inEvent) :acc(inAcc),event(inEvent) { } }; struct LuaEventKeyboarData { int keyCode; Event* event; LuaEventKeyboarData(int inKeyCode,Event* inEvent) :keyCode(inKeyCode),event(inEvent) { } }; struct LuaEventTouchData { Touch* touch; Event* event; LuaEventTouchData(Touch* inTouch, Event* inEvent) :touch(inTouch), event(inEvent) { } }; struct LuaEventTouchesData { std::vector<Touch*> touches; Event* event; LuaEventTouchesData(std::vector<Touch*> inTouches, Event* inEvent) :touches(inTouches), event(inEvent) { } }; struct LuaEventMouseData { Event* event; LuaEventMouseData(Event* inEvent) :event(inEvent) { } }; #endif // #ifndef COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_GENERATED_LUA_COCOS2DX_MANUAL_H
26.689076
87
0.691751
weiDDD
94dab9a0cd96ec7ac344ae472ca764b0a84a3d26
192
cpp
C++
Primero/Cuatrimestre1/FS/Practicas/Parciales/Parcial2/makefile-gdb/division.cpp
diegxsantiago/
7e9bc298d1cd1f20a2177178400bbf7e6e0bab3d
[ "MIT" ]
1
2021-02-08T18:22:50.000Z
2021-02-08T18:22:50.000Z
Primero/Cuatrimestre1/FS/Practicas/Parciales/Parcial2/makefile-gdb/division.cpp
diegxsantiago/gii
7e9bc298d1cd1f20a2177178400bbf7e6e0bab3d
[ "MIT" ]
null
null
null
Primero/Cuatrimestre1/FS/Practicas/Parciales/Parcial2/makefile-gdb/division.cpp
diegxsantiago/gii
7e9bc298d1cd1f20a2177178400bbf7e6e0bab3d
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <stdio.h> #include "funciones.h" /* producto de dos numeros */ int division (int x, int y) { int tmp; tmp = x / y; return tmp; }
10.666667
28
0.536458
diegxsantiago
94db874be36602fd7af0139f01c400625acb088a
925
cpp
C++
src/backend/generic/runtime/sycl/api.cpp
alexbatashev/athena
eafbb1e16ed0b273a63a20128ebd4882829aa2db
[ "MIT" ]
2
2020-07-16T06:42:27.000Z
2020-07-16T06:42:28.000Z
src/backend/generic/runtime/sycl/api.cpp
PolarAI/polarai-framework
c5fd886732afe787a06ebf6fb05fc38069257457
[ "MIT" ]
null
null
null
src/backend/generic/runtime/sycl/api.cpp
PolarAI/polarai-framework
c5fd886732afe787a06ebf6fb05fc38069257457
[ "MIT" ]
null
null
null
//===----------------------------------------------------------------------===// // Copyright (c) 2020 Athena. All rights reserved. // https://getathena.ml // // Licensed under MIT license. // // 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 "SYCLContext.h" #include <athena/backend/llvm/runtime/api.h> #include <athena/backend/llvm/runtime/runtime_export.h> using namespace athena::backend::llvm; extern "C" { ATH_RT_LLVM_EXPORT Context* initContext() { return new SYCLContext(); } ATH_RT_LLVM_EXPORT void closeContext(Context* ctx) { delete ctx; } }
28.90625
80
0.621622
alexbatashev
94e3575f63a486b5c93822233a7c3fa80e2e1de1
95,049
hh
C++
extern/glow/src/glow/detail/xxHash/xxh3.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
11
2019-10-23T19:15:42.000Z
2021-12-07T07:37:39.000Z
extern/glow/src/glow/detail/xxHash/xxh3.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
6
2019-10-29T04:11:17.000Z
2020-10-30T16:27:23.000Z
extern/glow/src/glow/detail/xxHash/xxh3.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
2
2020-01-22T17:53:55.000Z
2020-10-01T09:18:00.000Z
/* * xxHash - Extremely Fast Hash algorithm * Development source file for `xxh3` * Copyright (C) 2019-2020 Yann Collet * * BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php) * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * You can contact the author at: * - xxHash homepage: https://www.xxhash.com * - xxHash source repository: https://github.com/Cyan4973/xxHash */ /* * Note: This file is separated for development purposes. * It will be integrated into `xxhash.h` when development stage is completed. * * Credit: most of the work on vectorial and asm variants comes from @easyaspi314 */ #ifndef XXH3_H_1397135465 #define XXH3_H_1397135465 /* === Dependencies === */ #ifndef XXHASH_H_5627135585666179 /* special: when including `xxh3.h` directly, turn on XXH_INLINE_ALL */ #undef XXH_INLINE_ALL /* avoid redefinition */ #define XXH_INLINE_ALL #endif #include "xxhash.hh" /* === Compiler specifics === */ #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* >= C99 */ #define XXH_RESTRICT restrict #else /* Note: it might be useful to define __restrict or __restrict__ for some C++ compilers */ #define XXH_RESTRICT /* disable */ #endif #if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__) #define XXH_likely(x) __builtin_expect(x, 1) #define XXH_unlikely(x) __builtin_expect(x, 0) #else #define XXH_likely(x) (x) #define XXH_unlikely(x) (x) #endif #if defined(__GNUC__) #if defined(__AVX2__) #include <immintrin.h> #elif defined(__SSE2__) #include <emmintrin.h> #elif defined(__ARM_NEON__) || defined(__ARM_NEON) #define inline __inline__ /* clang bug */ #include <arm_neon.h> #undef inline #endif #elif defined(_MSC_VER) #include <intrin.h> #endif /* * One goal of XXH3 is to make it fast on both 32-bit and 64-bit, while * remaining a true 64-bit/128-bit hash function. * * This is done by prioritizing a subset of 64-bit operations that can be * emulated without too many steps on the average 32-bit machine. * * For example, these two lines seem similar, and run equally fast on 64-bit: * * xxh_u64 x; * x ^= (x >> 47); // good * x ^= (x >> 13); // bad * * However, to a 32-bit machine, there is a major difference. * * x ^= (x >> 47) looks like this: * * x.lo ^= (x.hi >> (47 - 32)); * * while x ^= (x >> 13) looks like this: * * // note: funnel shifts are not usually cheap. * x.lo ^= (x.lo >> 13) | (x.hi << (32 - 13)); * x.hi ^= (x.hi >> 13); * * The first one is significantly faster than the second, simply because the * shift is larger than 32. This means: * - All the bits we need are in the upper 32 bits, so we can ignore the lower * 32 bits in the shift. * - The shift result will always fit in the lower 32 bits, and therefore, * we can ignore the upper 32 bits in the xor. * * Thanks to this optimization, XXH3 only requires these features to be efficient: * * - Usable unaligned access * - A 32-bit or 64-bit ALU * - If 32-bit, a decent ADC instruction * - A 32 or 64-bit multiply with a 64-bit result * - For the 128-bit variant, a decent byteswap helps short inputs. * * The first two are already required by XXH32, and almost all 32-bit and 64-bit * platforms which can run XXH32 can run XXH3 efficiently. * * Thumb-1, the classic 16-bit only subset of ARM's instruction set, is one * notable exception. * * First of all, Thumb-1 lacks support for the UMULL instruction which * performs the important long multiply. This means numerous __aeabi_lmul * calls. * * Second of all, the 8 functional registers are just not enough. * Setup for __aeabi_lmul, byteshift loads, pointers, and all arithmetic need * Lo registers, and this shuffling results in thousands more MOVs than A32. * * A32 and T32 don't have this limitation. They can access all 14 registers, * do a 32->64 multiply with UMULL, and the flexible operand allowing free * shifts is helpful, too. * * Therefore, we do a quick sanity check. * * If compiling Thumb-1 for a target which supports ARM instructions, we will * emit a warning, as it is not a "sane" platform to compile for. * * Usually, if this happens, it is because of an accident and you probably need * to specify -march, as you likely meant to compile for a newer architecture. */ #if defined(__thumb__) && !defined(__thumb2__) && defined(__ARM_ARCH_ISA_ARM) #warning "XXH3 is highly inefficient without ARM or Thumb-2." #endif /* ========================================== * Vectorization detection * ========================================== */ #define XXH_SCALAR 0 /* Portable scalar version */ #define XXH_SSE2 1 /* SSE2 for Pentium 4 and all x86_64 */ #define XXH_AVX2 2 /* AVX2 for Haswell and Bulldozer */ #define XXH_NEON 3 /* NEON for most ARMv7-A and all AArch64 */ #define XXH_VSX 4 /* VSX and ZVector for POWER8/z13 */ #define XXH_AVX512 5 /* AVX512 for Skylake and Icelake */ #ifndef XXH_VECTOR /* can be defined on command line */ #if defined(__AVX512F__) #define XXH_VECTOR XXH_AVX512 #elif defined(__AVX2__) #define XXH_VECTOR XXH_AVX2 #elif defined(__SSE2__) || defined(_M_AMD64) || defined(_M_X64) || (defined(_M_IX86_FP) && (_M_IX86_FP == 2)) #define XXH_VECTOR XXH_SSE2 #elif defined(__GNUC__) /* msvc support maybe later */ \ && (defined(__ARM_NEON__) || defined(__ARM_NEON)) \ && (defined(__LITTLE_ENDIAN__) /* We only support little endian NEON */ \ || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) #define XXH_VECTOR XXH_NEON #elif (defined(__PPC64__) && defined(__POWER8_VECTOR__)) || (defined(__s390x__) && defined(__VEC__)) && defined(__GNUC__) /* TODO: IBM XL */ #define XXH_VECTOR XXH_VSX #else #define XXH_VECTOR XXH_SCALAR #endif #endif /* * Controls the alignment of the accumulator. * This is for compatibility with aligned vector loads, which are usually faster. */ #ifndef XXH_ACC_ALIGN #if XXH_VECTOR == XXH_SCALAR /* scalar */ #define XXH_ACC_ALIGN 8 #elif XXH_VECTOR == XXH_SSE2 /* sse2 */ #define XXH_ACC_ALIGN 16 #elif XXH_VECTOR == XXH_AVX2 /* avx2 */ #define XXH_ACC_ALIGN 32 #elif XXH_VECTOR == XXH_NEON /* neon */ #define XXH_ACC_ALIGN 16 #elif XXH_VECTOR == XXH_VSX /* vsx */ #define XXH_ACC_ALIGN 16 #elif XXH_VECTOR == XXH_AVX512 /* avx512 */ #define XXH_ACC_ALIGN 64 #endif #endif /* * UGLY HACK: * GCC usually generates the best code with -O3 for xxHash. * * However, when targeting AVX2, it is overzealous in its unrolling resulting * in code roughly 3/4 the speed of Clang. * * There are other issues, such as GCC splitting _mm256_loadu_si256 into * _mm_loadu_si128 + _mm256_inserti128_si256. This is an optimization which * only applies to Sandy and Ivy Bridge... which don't even support AVX2. * * That is why when compiling the AVX2 version, it is recommended to use either * -O2 -mavx2 -march=haswell * or * -O2 -mavx2 -mno-avx256-split-unaligned-load * for decent performance, or to use Clang instead. * * Fortunately, we can control the first one with a pragma that forces GCC into * -O2, but the other one we can't control without "failed to inline always * inline function due to target mismatch" warnings. */ #if XXH_VECTOR == XXH_AVX2 /* AVX2 */ \ && defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \ && defined(__OPTIMIZE__) && !defined(__OPTIMIZE_SIZE__) /* respect -O0 and -Os */ #pragma GCC push_options #pragma GCC optimize("-O2") #endif #if XXH_VECTOR == XXH_NEON /* * NEON's setup for vmlal_u32 is a little more complicated than it is on * SSE2, AVX2, and VSX. * * While PMULUDQ and VMULEUW both perform a mask, VMLAL.U32 performs an upcast. * * To do the same operation, the 128-bit 'Q' register needs to be split into * two 64-bit 'D' registers, performing this operation:: * * [ a | b ] * | '---------. .--------' | * | x | * | .---------' '--------. | * [ a & 0xFFFFFFFF | b & 0xFFFFFFFF ],[ a >> 32 | b >> 32 ] * * Due to significant changes in aarch64, the fastest method for aarch64 is * completely different than the fastest method for ARMv7-A. * * ARMv7-A treats D registers as unions overlaying Q registers, so modifying * D11 will modify the high half of Q5. This is similar to how modifying AH * will only affect bits 8-15 of AX on x86. * * VZIP takes two registers, and puts even lanes in one register and odd lanes * in the other. * * On ARMv7-A, this strangely modifies both parameters in place instead of * taking the usual 3-operand form. * * Therefore, if we want to do this, we can simply use a D-form VZIP.32 on the * lower and upper halves of the Q register to end up with the high and low * halves where we want - all in one instruction. * * vzip.32 d10, d11 @ d10 = { d10[0], d11[0] }; d11 = { d10[1], d11[1] } * * Unfortunately we need inline assembly for this: Instructions modifying two * registers at once is not possible in GCC or Clang's IR, and they have to * create a copy. * * aarch64 requires a different approach. * * In order to make it easier to write a decent compiler for aarch64, many * quirks were removed, such as conditional execution. * * NEON was also affected by this. * * aarch64 cannot access the high bits of a Q-form register, and writes to a * D-form register zero the high bits, similar to how writes to W-form scalar * registers (or DWORD registers on x86_64) work. * * The formerly free vget_high intrinsics now require a vext (with a few * exceptions) * * Additionally, VZIP was replaced by ZIP1 and ZIP2, which are the equivalent * of PUNPCKL* and PUNPCKH* in SSE, respectively, in order to only modify one * operand. * * The equivalent of the VZIP.32 on the lower and upper halves would be this * mess: * * ext v2.4s, v0.4s, v0.4s, #2 // v2 = { v0[2], v0[3], v0[0], v0[1] } * zip1 v1.2s, v0.2s, v2.2s // v1 = { v0[0], v2[0] } * zip2 v0.2s, v0.2s, v1.2s // v0 = { v0[1], v2[1] } * * Instead, we use a literal downcast, vmovn_u64 (XTN), and vshrn_n_u64 (SHRN): * * shrn v1.2s, v0.2d, #32 // v1 = (uint32x2_t)(v0 >> 32); * xtn v0.2s, v0.2d // v0 = (uint32x2_t)(v0 & 0xFFFFFFFF); * * This is available on ARMv7-A, but is less efficient than a single VZIP.32. */ /* * Function-like macro: * void XXH_SPLIT_IN_PLACE(uint64x2_t &in, uint32x2_t &outLo, uint32x2_t &outHi) * { * outLo = (uint32x2_t)(in & 0xFFFFFFFF); * outHi = (uint32x2_t)(in >> 32); * in = UNDEFINED; * } */ #if !defined(XXH_NO_VZIP_HACK) /* define to disable */ \ && defined(__GNUC__) && !defined(__aarch64__) && !defined(__arm64__) #define XXH_SPLIT_IN_PLACE(in, outLo, outHi) \ do \ { \ /* Undocumented GCC/Clang operand modifier: %e0 = lower D half, %f0 = upper D half */ \ /* https://github.com/gcc-mirror/gcc/blob/38cf91e5/gcc/config/arm/arm.c#L22486 */ \ /* https://github.com/llvm-mirror/llvm/blob/2c4ca683/lib/Target/ARM/ARMAsmPrinter.cpp#L399 */ \ __asm__("vzip.32 %e0, %f0" : "+w"(in)); \ (outLo) = vget_low_u32(vreinterpretq_u32_u64(in)); \ (outHi) = vget_high_u32(vreinterpretq_u32_u64(in)); \ } while (0) #else #define XXH_SPLIT_IN_PLACE(in, outLo, outHi) \ do \ { \ (outLo) = vmovn_u64(in); \ (outHi) = vshrn_n_u64((in), 32); \ } while (0) #endif #endif /* XXH_VECTOR == XXH_NEON */ /* * VSX and Z Vector helpers. * * This is very messy, and any pull requests to clean this up are welcome. * * There are a lot of problems with supporting VSX and s390x, due to * inconsistent intrinsics, spotty coverage, and multiple endiannesses. */ #if XXH_VECTOR == XXH_VSX #if defined(__s390x__) #include <s390intrin.h> #else #include <altivec.h> #endif #undef vector /* Undo the pollution */ typedef __vector unsigned long long xxh_u64x2; typedef __vector unsigned char xxh_u8x16; typedef __vector unsigned xxh_u32x4; #ifndef XXH_VSX_BE #if defined(__BIG_ENDIAN__) || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) #define XXH_VSX_BE 1 #elif defined(__VEC_ELEMENT_REG_ORDER__) && __VEC_ELEMENT_REG_ORDER__ == __ORDER_BIG_ENDIAN__ #warning "-maltivec=be is not recommended. Please use native endianness." #define XXH_VSX_BE 1 #else #define XXH_VSX_BE 0 #endif #endif /* !defined(XXH_VSX_BE) */ #if XXH_VSX_BE /* A wrapper for POWER9's vec_revb. */ #if defined(__POWER9_VECTOR__) || (defined(__clang__) && defined(__s390x__)) #define XXH_vec_revb vec_revb #else XXH_FORCE_INLINE xxh_u64x2 XXH_vec_revb(xxh_u64x2 val) { xxh_u8x16 const vByteSwap = {0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08}; return vec_perm(val, val, vByteSwap); } #endif #endif /* XXH_VSX_BE */ /* * Performs an unaligned load and byte swaps it on big endian. */ XXH_FORCE_INLINE xxh_u64x2 XXH_vec_loadu(const void* ptr) { xxh_u64x2 ret; memcpy(&ret, ptr, sizeof(xxh_u64x2)); #if XXH_VSX_BE ret = XXH_vec_revb(ret); #endif return ret; } /* * vec_mulo and vec_mule are very problematic intrinsics on PowerPC * * These intrinsics weren't added until GCC 8, despite existing for a while, * and they are endian dependent. Also, their meaning swap depending on version. * */ #if defined(__s390x__) /* s390x is always big endian, no issue on this platform */ #define XXH_vec_mulo vec_mulo #define XXH_vec_mule vec_mule #elif defined(__clang__) && __has_builtin(__builtin_altivec_vmuleuw) /* Clang has a better way to control this, we can just use the builtin which doesn't swap. */ #define XXH_vec_mulo __builtin_altivec_vmulouw #define XXH_vec_mule __builtin_altivec_vmuleuw #else /* gcc needs inline assembly */ /* Adapted from https://github.com/google/highwayhash/blob/master/highwayhash/hh_vsx.h. */ XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mulo(xxh_u32x4 a, xxh_u32x4 b) { xxh_u64x2 result; __asm__("vmulouw %0, %1, %2" : "=v"(result) : "v"(a), "v"(b)); return result; } XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mule(xxh_u32x4 a, xxh_u32x4 b) { xxh_u64x2 result; __asm__("vmuleuw %0, %1, %2" : "=v"(result) : "v"(a), "v"(b)); return result; } #endif /* XXH_vec_mulo, XXH_vec_mule */ #endif /* XXH_VECTOR == XXH_VSX */ /* prefetch * can be disabled, by declaring XXH_NO_PREFETCH build macro */ #if defined(XXH_NO_PREFETCH) #define XXH_PREFETCH(ptr) (void)(ptr) /* disabled */ #else #if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_I86)) /* _mm_prefetch() is not defined outside of x86/x64 */ #include <mmintrin.h> /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */ #define XXH_PREFETCH(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T0) #elif defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))) #define XXH_PREFETCH(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 3 /* locality */) #else #define XXH_PREFETCH(ptr) (void)(ptr) /* disabled */ #endif #endif /* XXH_NO_PREFETCH */ /* ========================================== * XXH3 default settings * ========================================== */ #define XXH_SECRET_DEFAULT_SIZE 192 /* minimum XXH3_SECRET_SIZE_MIN */ #if (XXH_SECRET_DEFAULT_SIZE < XXH3_SECRET_SIZE_MIN) #error "default keyset is not large enough" #endif /* Pseudorandom secret taken directly from FARSH */ XXH_ALIGN(64) static const xxh_u8 kSecret[XXH_SECRET_DEFAULT_SIZE] = { 0xb8, 0xfe, 0x6c, 0x39, 0x23, 0xa4, 0x4b, 0xbe, 0x7c, 0x01, 0x81, 0x2c, 0xf7, 0x21, 0xad, 0x1c, 0xde, 0xd4, 0x6d, 0xe9, 0x83, 0x90, 0x97, 0xdb, 0x72, 0x40, 0xa4, 0xa4, 0xb7, 0xb3, 0x67, 0x1f, 0xcb, 0x79, 0xe6, 0x4e, 0xcc, 0xc0, 0xe5, 0x78, 0x82, 0x5a, 0xd0, 0x7d, 0xcc, 0xff, 0x72, 0x21, 0xb8, 0x08, 0x46, 0x74, 0xf7, 0x43, 0x24, 0x8e, 0xe0, 0x35, 0x90, 0xe6, 0x81, 0x3a, 0x26, 0x4c, 0x3c, 0x28, 0x52, 0xbb, 0x91, 0xc3, 0x00, 0xcb, 0x88, 0xd0, 0x65, 0x8b, 0x1b, 0x53, 0x2e, 0xa3, 0x71, 0x64, 0x48, 0x97, 0xa2, 0x0d, 0xf9, 0x4e, 0x38, 0x19, 0xef, 0x46, 0xa9, 0xde, 0xac, 0xd8, 0xa8, 0xfa, 0x76, 0x3f, 0xe3, 0x9c, 0x34, 0x3f, 0xf9, 0xdc, 0xbb, 0xc7, 0xc7, 0x0b, 0x4f, 0x1d, 0x8a, 0x51, 0xe0, 0x4b, 0xcd, 0xb4, 0x59, 0x31, 0xc8, 0x9f, 0x7e, 0xc9, 0xd9, 0x78, 0x73, 0x64, 0xea, 0xc5, 0xac, 0x83, 0x34, 0xd3, 0xeb, 0xc3, 0xc5, 0x81, 0xa0, 0xff, 0xfa, 0x13, 0x63, 0xeb, 0x17, 0x0d, 0xdd, 0x51, 0xb7, 0xf0, 0xda, 0x49, 0xd3, 0x16, 0x55, 0x26, 0x29, 0xd4, 0x68, 0x9e, 0x2b, 0x16, 0xbe, 0x58, 0x7d, 0x47, 0xa1, 0xfc, 0x8f, 0xf8, 0xb8, 0xd1, 0x7a, 0xd0, 0x31, 0xce, 0x45, 0xcb, 0x3a, 0x8f, 0x95, 0x16, 0x04, 0x28, 0xaf, 0xd7, 0xfb, 0xca, 0xbb, 0x4b, 0x40, 0x7e, }; /* * Calculates a 32-bit to 64-bit long multiply. * * Wraps __emulu on MSVC x86 because it tends to call __allmul when it doesn't * need to (but it shouldn't need to anyways, it is about 7 instructions to do * a 64x64 multiply...). Since we know that this will _always_ emit MULL, we * use that instead of the normal method. * * If you are compiling for platforms like Thumb-1 and don't have a better option, * you may also want to write your own long multiply routine here. * * XXH_FORCE_INLINE xxh_u64 XXH_mult32to64(xxh_u64 x, xxh_u64 y) * { * return (x & 0xFFFFFFFF) * (y & 0xFFFFFFFF); * } */ #if defined(_MSC_VER) && defined(_M_IX86) #include <intrin.h> #define XXH_mult32to64(x, y) __emulu((unsigned)(x), (unsigned)(y)) #else /* * Downcast + upcast is usually better than masking on older compilers like * GCC 4.2 (especially 32-bit ones), all without affecting newer compilers. * * The other method, (x & 0xFFFFFFFF) * (y & 0xFFFFFFFF), will AND both operands * and perform a full 64x64 multiply -- entirely redundant on 32-bit. */ #define XXH_mult32to64(x, y) ((xxh_u64)(xxh_u32)(x) * (xxh_u64)(xxh_u32)(y)) #endif /* * Calculates a 64->128-bit long multiply. * * Uses __uint128_t and _umul128 if available, otherwise uses a scalar version. */ static XXH128_hash_t XXH_mult64to128(xxh_u64 lhs, xxh_u64 rhs) { /* * GCC/Clang __uint128_t method. * * On most 64-bit targets, GCC and Clang define a __uint128_t type. * This is usually the best way as it usually uses a native long 64-bit * multiply, such as MULQ on x86_64 or MUL + UMULH on aarch64. * * Usually. * * Despite being a 32-bit platform, Clang (and emscripten) define this type * despite not having the arithmetic for it. This results in a laggy * compiler builtin call which calculates a full 128-bit multiply. * In that case it is best to use the portable one. * https://github.com/Cyan4973/xxHash/issues/211#issuecomment-515575677 */ #if defined(__GNUC__) && !defined(__wasm__) && defined(__SIZEOF_INT128__) || (defined(_INTEGRAL_MAX_BITS) && _INTEGRAL_MAX_BITS >= 128) __uint128_t const product = (__uint128_t)lhs * (__uint128_t)rhs; XXH128_hash_t r128; r128.low64 = (xxh_u64)(product); r128.high64 = (xxh_u64)(product >> 64); return r128; /* * MSVC for x64's _umul128 method. * * xxh_u64 _umul128(xxh_u64 Multiplier, xxh_u64 Multiplicand, xxh_u64 *HighProduct); * * This compiles to single operand MUL on x64. */ #elif defined(_M_X64) || defined(_M_IA64) #ifndef _MSC_VER #pragma intrinsic(_umul128) #endif xxh_u64 product_high; xxh_u64 const product_low = _umul128(lhs, rhs, &product_high); XXH128_hash_t r128; r128.low64 = product_low; r128.high64 = product_high; return r128; #else /* * Portable scalar method. Optimized for 32-bit and 64-bit ALUs. * * This is a fast and simple grade school multiply, which is shown below * with base 10 arithmetic instead of base 0x100000000. * * 9 3 // D2 lhs = 93 * x 7 5 // D2 rhs = 75 * ---------- * 1 5 // D2 lo_lo = (93 % 10) * (75 % 10) = 15 * 4 5 | // D2 hi_lo = (93 / 10) * (75 % 10) = 45 * 2 1 | // D2 lo_hi = (93 % 10) * (75 / 10) = 21 * + 6 3 | | // D2 hi_hi = (93 / 10) * (75 / 10) = 63 * --------- * 2 7 | // D2 cross = (15 / 10) + (45 % 10) + 21 = 27 * + 6 7 | | // D2 upper = (27 / 10) + (45 / 10) + 63 = 67 * --------- * 6 9 7 5 // D4 res = (27 * 10) + (15 % 10) + (67 * 100) = 6975 * * The reasons for adding the products like this are: * 1. It avoids manual carry tracking. Just like how * (9 * 9) + 9 + 9 = 99, the same applies with this for UINT64_MAX. * This avoids a lot of complexity. * * 2. It hints for, and on Clang, compiles to, the powerful UMAAL * instruction available in ARM's Digital Signal Processing extension * in 32-bit ARMv6 and later, which is shown below: * * void UMAAL(xxh_u32 *RdLo, xxh_u32 *RdHi, xxh_u32 Rn, xxh_u32 Rm) * { * xxh_u64 product = (xxh_u64)*RdLo * (xxh_u64)*RdHi + Rn + Rm; * *RdLo = (xxh_u32)(product & 0xFFFFFFFF); * *RdHi = (xxh_u32)(product >> 32); * } * * This instruction was designed for efficient long multiplication, and * allows this to be calculated in only 4 instructions at speeds * comparable to some 64-bit ALUs. * * 3. It isn't terrible on other platforms. Usually this will be a couple * of 32-bit ADD/ADCs. */ /* First calculate all of the cross products. */ xxh_u64 const lo_lo = XXH_mult32to64(lhs & 0xFFFFFFFF, rhs & 0xFFFFFFFF); xxh_u64 const hi_lo = XXH_mult32to64(lhs >> 32, rhs & 0xFFFFFFFF); xxh_u64 const lo_hi = XXH_mult32to64(lhs & 0xFFFFFFFF, rhs >> 32); xxh_u64 const hi_hi = XXH_mult32to64(lhs >> 32, rhs >> 32); /* Now add the products together. These will never overflow. */ xxh_u64 const cross = (lo_lo >> 32) + (hi_lo & 0xFFFFFFFF) + lo_hi; xxh_u64 const upper = (hi_lo >> 32) + (cross >> 32) + hi_hi; xxh_u64 const lower = (cross << 32) | (lo_lo & 0xFFFFFFFF); XXH128_hash_t r128; r128.low64 = lower; r128.high64 = upper; return r128; #endif } /* * Does a 64-bit to 128-bit multiply, then XOR folds it. * * The reason for the separate function is to prevent passing too many structs * around by value. This will hopefully inline the multiply, but we don't force it. */ static xxh_u64 XXH3_mul128_fold64(xxh_u64 lhs, xxh_u64 rhs) { XXH128_hash_t product = XXH_mult64to128(lhs, rhs); return product.low64 ^ product.high64; } /* Seems to produce slightly better code on GCC for some reason. */ XXH_FORCE_INLINE xxh_u64 XXH_xorshift64(xxh_u64 v64, int shift) { XXH_ASSERT(0 <= shift && shift < 64); return v64 ^ (v64 >> shift); } /* * We don't need to (or want to) mix as much as XXH64. * * Short hashes are more evenly distributed, so it isn't necessary. */ static XXH64_hash_t XXH3_avalanche(xxh_u64 h64) { h64 = XXH_xorshift64(h64, 37); h64 *= 0x165667919E3779F9ULL; h64 = XXH_xorshift64(h64, 32); return h64; } /* ========================================== * Short keys * ========================================== * One of the shortcomings of XXH32 and XXH64 was that their performance was * sub-optimal on short lengths. It used an iterative algorithm which strongly * favored lengths that were a multiple of 4 or 8. * * Instead of iterating over individual inputs, we use a set of single shot * functions which piece together a range of lengths and operate in constant time. * * Additionally, the number of multiplies has been significantly reduced. This * reduces latency, especially when emulating 64-bit multiplies on 32-bit. * * Depending on the platform, this may or may not be faster than XXH32, but it * is almost guaranteed to be faster than XXH64. */ /* * At very short lengths, there isn't enough input to fully hide secrets, or use * the entire secret. * * There is also only a limited amount of mixing we can do before significantly * impacting performance. * * Therefore, we use different sections of the secret and always mix two secret * samples with an XOR. This should have no effect on performance on the * seedless or withSeed variants because everything _should_ be constant folded * by modern compilers. * * The XOR mixing hides individual parts of the secret and increases entropy. * * This adds an extra layer of strength for custom secrets. */ XXH_FORCE_INLINE XXH64_hash_t XXH3_len_1to3_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) { XXH_ASSERT(input != NULL); XXH_ASSERT(1 <= len && len <= 3); XXH_ASSERT(secret != NULL); /* * len = 1: combined = { input[0], 0x01, input[0], input[0] } * len = 2: combined = { input[1], 0x02, input[0], input[1] } * len = 3: combined = { input[2], 0x03, input[0], input[1] } */ { xxh_u8 const c1 = input[0]; xxh_u8 const c2 = input[len >> 1]; xxh_u8 const c3 = input[len - 1]; xxh_u32 const combined = ((xxh_u32)c1 << 16) | ((xxh_u32)c2 << 24) | ((xxh_u32)c3 << 0) | ((xxh_u32)len << 8); xxh_u64 const bitflip = (XXH_readLE32(secret) ^ XXH_readLE32(secret + 4)) + seed; xxh_u64 const keyed = (xxh_u64)combined ^ bitflip; xxh_u64 const mixed = keyed * PRIME64_1; return XXH3_avalanche(mixed); } } XXH_FORCE_INLINE XXH64_hash_t XXH3_len_4to8_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) { XXH_ASSERT(input != NULL); XXH_ASSERT(secret != NULL); XXH_ASSERT(4 <= len && len < 8); seed ^= (xxh_u64)XXH_swap32((xxh_u32)seed) << 32; { xxh_u32 const input1 = XXH_readLE32(input); xxh_u32 const input2 = XXH_readLE32(input + len - 4); xxh_u64 const bitflip = (XXH_readLE64(secret + 8) ^ XXH_readLE64(secret + 16)) - seed; xxh_u64 const input64 = input2 + (((xxh_u64)input1) << 32); xxh_u64 x = input64 ^ bitflip; /* this mix is inspired by Pelle Evensen's rrmxmx */ x ^= XXH_rotl64(x, 49) ^ XXH_rotl64(x, 24); x *= 0x9FB21C651E98DF25ULL; x ^= (x >> 35) + len; x *= 0x9FB21C651E98DF25ULL; return XXH_xorshift64(x, 28); } } XXH_FORCE_INLINE XXH64_hash_t XXH3_len_9to16_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) { XXH_ASSERT(input != NULL); XXH_ASSERT(secret != NULL); XXH_ASSERT(8 <= len && len <= 16); { xxh_u64 const bitflip1 = (XXH_readLE64(secret + 24) ^ XXH_readLE64(secret + 32)) + seed; xxh_u64 const bitflip2 = (XXH_readLE64(secret + 40) ^ XXH_readLE64(secret + 48)) - seed; xxh_u64 const input_lo = XXH_readLE64(input) ^ bitflip1; xxh_u64 const input_hi = XXH_readLE64(input + len - 8) ^ bitflip2; xxh_u64 const acc = len + XXH_swap64(input_lo) + input_hi + XXH3_mul128_fold64(input_lo, input_hi); return XXH3_avalanche(acc); } } XXH_FORCE_INLINE XXH64_hash_t XXH3_len_0to16_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) { XXH_ASSERT(len <= 16); { if (XXH_likely(len > 8)) return XXH3_len_9to16_64b(input, len, secret, seed); if (XXH_likely(len >= 4)) return XXH3_len_4to8_64b(input, len, secret, seed); if (len) return XXH3_len_1to3_64b(input, len, secret, seed); return XXH3_avalanche((PRIME64_1 + seed) ^ (XXH_readLE64(secret + 56) ^ XXH_readLE64(secret + 64))); } } /* * DISCLAIMER: There are known *seed-dependent* multicollisions here due to * multiplication by zero, affecting hashes of lengths 17 to 240. * * However, they are very unlikely. * * Keep this in mind when using the unseeded XXH3_64bits() variant: As with all * unseeded non-cryptographic hashes, it does not attempt to defend itself * against specially crafted inputs, only random inputs. * * Compared to classic UMAC where a 1 in 2^31 chance of 4 consecutive bytes * cancelling out the secret is taken an arbitrary number of times (addressed * in XXH3_accumulate_512), this collision is very unlikely with random inputs * and/or proper seeding: * * This only has a 1 in 2^63 chance of 8 consecutive bytes cancelling out, in a * function that is only called up to 16 times per hash with up to 240 bytes of * input. * * This is not too bad for a non-cryptographic hash function, especially with * only 64 bit outputs. * * The 128-bit variant (which trades some speed for strength) is NOT affected * by this, although it is always a good idea to use a proper seed if you care * about strength. */ XXH_FORCE_INLINE xxh_u64 XXH3_mix16B(const xxh_u8* XXH_RESTRICT input, const xxh_u8* XXH_RESTRICT secret, xxh_u64 seed64) { #if defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \ && defined(__i386__) && defined(__SSE2__) /* x86 + SSE2 */ \ && !defined(XXH_ENABLE_AUTOVECTORIZE) /* Define to disable like XXH32 hack */ /* * UGLY HACK: * GCC for x86 tends to autovectorize the 128-bit multiply, resulting in * slower code. * * By forcing seed64 into a register, we disrupt the cost model and * cause it to scalarize. See `XXH32_round()` * * FIXME: Clang's output is still _much_ faster -- On an AMD Ryzen 3600, * XXH3_64bits @ len=240 runs at 4.6 GB/s with Clang 9, but 3.3 GB/s on * GCC 9.2, despite both emitting scalar code. * * GCC generates much better scalar code than Clang for the rest of XXH3, * which is why finding a more optimal codepath is an interest. */ __asm__("" : "+r"(seed64)); #endif { xxh_u64 const input_lo = XXH_readLE64(input); xxh_u64 const input_hi = XXH_readLE64(input + 8); return XXH3_mul128_fold64(input_lo ^ (XXH_readLE64(secret) + seed64), input_hi ^ (XXH_readLE64(secret + 8) - seed64)); } } /* For mid range keys, XXH3 uses a Mum-hash variant. */ XXH_FORCE_INLINE XXH64_hash_t XXH3_len_17to128_64b(const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize, XXH64_hash_t seed) { XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize; XXH_ASSERT(16 < len && len <= 128); { xxh_u64 acc = len * PRIME64_1; if (len > 32) { if (len > 64) { if (len > 96) { acc += XXH3_mix16B(input + 48, secret + 96, seed); acc += XXH3_mix16B(input + len - 64, secret + 112, seed); } acc += XXH3_mix16B(input + 32, secret + 64, seed); acc += XXH3_mix16B(input + len - 48, secret + 80, seed); } acc += XXH3_mix16B(input + 16, secret + 32, seed); acc += XXH3_mix16B(input + len - 32, secret + 48, seed); } acc += XXH3_mix16B(input + 0, secret + 0, seed); acc += XXH3_mix16B(input + len - 16, secret + 16, seed); return XXH3_avalanche(acc); } } #define XXH3_MIDSIZE_MAX 240 XXH_NO_INLINE XXH64_hash_t XXH3_len_129to240_64b(const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize, XXH64_hash_t seed) { XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize; XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX); #define XXH3_MIDSIZE_STARTOFFSET 3 #define XXH3_MIDSIZE_LASTOFFSET 17 { xxh_u64 acc = len * PRIME64_1; int const nbRounds = (int)len / 16; int i; for (i = 0; i < 8; i++) { acc += XXH3_mix16B(input + (16 * i), secret + (16 * i), seed); } acc = XXH3_avalanche(acc); XXH_ASSERT(nbRounds >= 8); #if defined(__clang__) /* Clang */ \ && (defined(__ARM_NEON) || defined(__ARM_NEON__)) /* NEON */ \ && !defined(XXH_ENABLE_AUTOVECTORIZE) /* Define to disable */ /* * UGLY HACK: * Clang for ARMv7-A tries to vectorize this loop, similar to GCC x86. * In everywhere else, it uses scalar code. * * For 64->128-bit multiplies, even if the NEON was 100% optimal, it * would still be slower than UMAAL (see XXH_mult64to128). * * Unfortunately, Clang doesn't handle the long multiplies properly and * converts them to the nonexistent "vmulq_u64" intrinsic, which is then * scalarized into an ugly mess of VMOV.32 instructions. * * This mess is difficult to avoid without turning autovectorization * off completely, but they are usually relatively minor and/or not * worth it to fix. * * This loop is the easiest to fix, as unlike XXH32, this pragma * _actually works_ because it is a loop vectorization instead of an * SLP vectorization. */ #pragma clang loop vectorize(disable) #endif for (i = 8; i < nbRounds; i++) { acc += XXH3_mix16B(input + (16 * i), secret + (16 * (i - 8)) + XXH3_MIDSIZE_STARTOFFSET, seed); } /* last bytes */ acc += XXH3_mix16B(input + len - 16, secret + XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET, seed); return XXH3_avalanche(acc); } } /* === Long Keys === */ #define STRIPE_LEN 64 #define XXH_SECRET_CONSUME_RATE 8 /* nb of secret bytes consumed at each accumulation */ #define ACC_NB (STRIPE_LEN / sizeof(xxh_u64)) typedef enum { XXH3_acc_64bits, XXH3_acc_128bits } XXH3_accWidth_e; /* * XXH3_accumulate_512 is the tightest loop for long inputs, and it is the most optimized. * * It is a hardened version of UMAC, based off of FARSH's implementation. * * This was chosen because it adapts quite well to 32-bit, 64-bit, and SIMD * implementations, and it is ridiculously fast. * * We harden it by mixing the original input to the accumulators as well as the product. * * This means that in the (relatively likely) case of a multiply by zero, the * original input is preserved. * * On 128-bit inputs, we swap 64-bit pairs when we add the input to improve * cross-pollination, as otherwise the upper and lower halves would be * essentially independent. * * This doesn't matter on 64-bit hashes since they all get merged together in * the end, so we skip the extra step. * * Both XXH3_64bits and XXH3_128bits use this subroutine. */ XXH_FORCE_INLINE void XXH3_accumulate_512(void* XXH_RESTRICT acc, const void* XXH_RESTRICT input, const void* XXH_RESTRICT secret, XXH3_accWidth_e accWidth) { #if (XXH_VECTOR == XXH_AVX512) XXH_ASSERT((((size_t)acc) & 63) == 0); XXH_STATIC_ASSERT(STRIPE_LEN == sizeof(__m512i)); { XXH_ALIGN(64) __m512i* const xacc = (__m512i*)acc; /* data_vec = input[0]; */ __m512i const data_vec = _mm512_loadu_si512(input); /* key_vec = secret[0]; */ __m512i const key_vec = _mm512_loadu_si512(secret); /* data_key = data_vec ^ key_vec; */ __m512i const data_key = _mm512_xor_si512(data_vec, key_vec); /* data_key_lo = data_key >> 32; */ __m512i const data_key_lo = _mm512_shuffle_epi32(data_key, _MM_SHUFFLE(0, 3, 0, 1)); /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */ __m512i const product = _mm512_mul_epu32(data_key, data_key_lo); if (accWidth == XXH3_acc_128bits) { /* xacc[0] += swap(data_vec); */ __m512i const data_swap = _mm512_shuffle_epi32(data_vec, _MM_SHUFFLE(1, 0, 3, 2)); __m512i const sum = _mm512_add_epi64(*xacc, data_swap); /* xacc[0] += product; */ *xacc = _mm512_add_epi64(product, sum); } else { /* XXH3_acc_64bits */ /* xacc[0] += data_vec; */ __m512i const sum = _mm512_add_epi64(*xacc, data_vec); /* xacc[0] += product; */ *xacc = _mm512_add_epi64(product, sum); } } #elif (XXH_VECTOR == XXH_AVX2) XXH_ASSERT((((size_t)acc) & 31) == 0); { XXH_ALIGN(32) __m256i* const xacc = (__m256i*)acc; /* Unaligned. This is mainly for pointer arithmetic, and because * _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */ const __m256i* const xinput = (const __m256i*)input; /* Unaligned. This is mainly for pointer arithmetic, and because * _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */ const __m256i* const xsecret = (const __m256i*)secret; size_t i; for (i = 0; i < STRIPE_LEN / sizeof(__m256i); i++) { /* data_vec = xinput[i]; */ __m256i const data_vec = _mm256_loadu_si256(xinput + i); /* key_vec = xsecret[i]; */ __m256i const key_vec = _mm256_loadu_si256(xsecret + i); /* data_key = data_vec ^ key_vec; */ __m256i const data_key = _mm256_xor_si256(data_vec, key_vec); /* data_key_lo = data_key >> 32; */ __m256i const data_key_lo = _mm256_shuffle_epi32(data_key, _MM_SHUFFLE(0, 3, 0, 1)); /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */ __m256i const product = _mm256_mul_epu32(data_key, data_key_lo); if (accWidth == XXH3_acc_128bits) { /* xacc[i] += swap(data_vec); */ __m256i const data_swap = _mm256_shuffle_epi32(data_vec, _MM_SHUFFLE(1, 0, 3, 2)); __m256i const sum = _mm256_add_epi64(xacc[i], data_swap); /* xacc[i] += product; */ xacc[i] = _mm256_add_epi64(product, sum); } else { /* XXH3_acc_64bits */ /* xacc[i] += data_vec; */ __m256i const sum = _mm256_add_epi64(xacc[i], data_vec); /* xacc[i] += product; */ xacc[i] = _mm256_add_epi64(product, sum); } } } #elif (XXH_VECTOR == XXH_SSE2) /* SSE2 is just a half-scale version of the AVX2 version. */ XXH_ASSERT((((size_t)acc) & 15) == 0); { XXH_ALIGN(16) __m128i* const xacc = (__m128i*)acc; /* Unaligned. This is mainly for pointer arithmetic, and because * _mm_loadu_si128 requires a const __m128i * pointer for some reason. */ const __m128i* const xinput = (const __m128i*)input; /* Unaligned. This is mainly for pointer arithmetic, and because * _mm_loadu_si128 requires a const __m128i * pointer for some reason. */ const __m128i* const xsecret = (const __m128i*)secret; size_t i; for (i = 0; i < STRIPE_LEN / sizeof(__m128i); i++) { /* data_vec = xinput[i]; */ __m128i const data_vec = _mm_loadu_si128(xinput + i); /* key_vec = xsecret[i]; */ __m128i const key_vec = _mm_loadu_si128(xsecret + i); /* data_key = data_vec ^ key_vec; */ __m128i const data_key = _mm_xor_si128(data_vec, key_vec); /* data_key_lo = data_key >> 32; */ __m128i const data_key_lo = _mm_shuffle_epi32(data_key, _MM_SHUFFLE(0, 3, 0, 1)); /* product = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */ __m128i const product = _mm_mul_epu32(data_key, data_key_lo); if (accWidth == XXH3_acc_128bits) { /* xacc[i] += swap(data_vec); */ __m128i const data_swap = _mm_shuffle_epi32(data_vec, _MM_SHUFFLE(1, 0, 3, 2)); __m128i const sum = _mm_add_epi64(xacc[i], data_swap); /* xacc[i] += product; */ xacc[i] = _mm_add_epi64(product, sum); } else { /* XXH3_acc_64bits */ /* xacc[i] += data_vec; */ __m128i const sum = _mm_add_epi64(xacc[i], data_vec); /* xacc[i] += product; */ xacc[i] = _mm_add_epi64(product, sum); } } } #elif (XXH_VECTOR == XXH_NEON) XXH_ASSERT((((size_t)acc) & 15) == 0); { XXH_ALIGN(16) uint64x2_t* const xacc = (uint64x2_t*)acc; /* We don't use a uint32x4_t pointer because it causes bus errors on ARMv7. */ uint8_t const* const xinput = (const uint8_t*)input; uint8_t const* const xsecret = (const uint8_t*)secret; size_t i; for (i = 0; i < STRIPE_LEN / sizeof(uint64x2_t); i++) { /* data_vec = xinput[i]; */ uint8x16_t data_vec = vld1q_u8(xinput + (i * 16)); /* key_vec = xsecret[i]; */ uint8x16_t key_vec = vld1q_u8(xsecret + (i * 16)); uint64x2_t data_key; uint32x2_t data_key_lo, data_key_hi; if (accWidth == XXH3_acc_64bits) { /* xacc[i] += data_vec; */ xacc[i] = vaddq_u64(xacc[i], vreinterpretq_u64_u8(data_vec)); } else { /* XXH3_acc_128bits */ /* xacc[i] += swap(data_vec); */ uint64x2_t const data64 = vreinterpretq_u64_u8(data_vec); uint64x2_t const swapped = vextq_u64(data64, data64, 1); xacc[i] = vaddq_u64(xacc[i], swapped); } /* data_key = data_vec ^ key_vec; */ data_key = vreinterpretq_u64_u8(veorq_u8(data_vec, key_vec)); /* data_key_lo = (uint32x2_t) (data_key & 0xFFFFFFFF); * data_key_hi = (uint32x2_t) (data_key >> 32); * data_key = UNDEFINED; */ XXH_SPLIT_IN_PLACE(data_key, data_key_lo, data_key_hi); /* xacc[i] += (uint64x2_t) data_key_lo * (uint64x2_t) data_key_hi; */ xacc[i] = vmlal_u32(xacc[i], data_key_lo, data_key_hi); } } #elif (XXH_VECTOR == XXH_VSX) xxh_u64x2* const xacc = (xxh_u64x2*)acc; /* presumed aligned */ xxh_u64x2 const* const xinput = (xxh_u64x2 const*)input; /* no alignment restriction */ xxh_u64x2 const* const xsecret = (xxh_u64x2 const*)secret; /* no alignment restriction */ xxh_u64x2 const v32 = {32, 32}; size_t i; for (i = 0; i < STRIPE_LEN / sizeof(xxh_u64x2); i++) { /* data_vec = xinput[i]; */ xxh_u64x2 const data_vec = XXH_vec_loadu(xinput + i); /* key_vec = xsecret[i]; */ xxh_u64x2 const key_vec = XXH_vec_loadu(xsecret + i); xxh_u64x2 const data_key = data_vec ^ key_vec; /* shuffled = (data_key << 32) | (data_key >> 32); */ xxh_u32x4 const shuffled = (xxh_u32x4)vec_rl(data_key, v32); /* product = ((xxh_u64x2)data_key & 0xFFFFFFFF) * ((xxh_u64x2)shuffled & 0xFFFFFFFF); */ xxh_u64x2 const product = XXH_vec_mulo((xxh_u32x4)data_key, shuffled); xacc[i] += product; if (accWidth == XXH3_acc_64bits) { xacc[i] += data_vec; } else { /* XXH3_acc_128bits */ /* swap high and low halves */ #ifdef __s390x__ xxh_u64x2 const data_swapped = vec_permi(data_vec, data_vec, 2); #else xxh_u64x2 const data_swapped = vec_xxpermdi(data_vec, data_vec, 2); #endif xacc[i] += data_swapped; } } #else /* scalar variant of Accumulator - universal */ XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64* const xacc = (xxh_u64*)acc; /* presumed aligned */ const xxh_u8* const xinput = (const xxh_u8*)input; /* no alignment restriction */ const xxh_u8* const xsecret = (const xxh_u8*)secret; /* no alignment restriction */ size_t i; XXH_ASSERT(((size_t)acc & (XXH_ACC_ALIGN - 1)) == 0); for (i = 0; i < ACC_NB; i++) { xxh_u64 const data_val = XXH_readLE64(xinput + 8 * i); xxh_u64 const data_key = data_val ^ XXH_readLE64(xsecret + i * 8); if (accWidth == XXH3_acc_64bits) { xacc[i] += data_val; } else { xacc[i ^ 1] += data_val; /* swap adjacent lanes */ } xacc[i] += XXH_mult32to64(data_key & 0xFFFFFFFF, data_key >> 32); } #endif } /* * XXH3_scrambleAcc: Scrambles the accumulators to improve mixing. * * Multiplication isn't perfect, as explained by Google in HighwayHash: * * // Multiplication mixes/scrambles bytes 0-7 of the 64-bit result to * // varying degrees. In descending order of goodness, bytes * // 3 4 2 5 1 6 0 7 have quality 228 224 164 160 100 96 36 32. * // As expected, the upper and lower bytes are much worse. * * Source: https://github.com/google/highwayhash/blob/0aaf66b/highwayhash/hh_avx2.h#L291 * * Since our algorithm uses a pseudorandom secret to add some variance into the * mix, we don't need to (or want to) mix as often or as much as HighwayHash does. * * This isn't as tight as XXH3_accumulate, but still written in SIMD to avoid * extraction. * * Both XXH3_64bits and XXH3_128bits use this subroutine. */ XXH_FORCE_INLINE void XXH3_scrambleAcc(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret) { #if (XXH_VECTOR == XXH_AVX512) XXH_ASSERT((((size_t)acc) & 63) == 0); XXH_STATIC_ASSERT(STRIPE_LEN == sizeof(__m512i)); { XXH_ALIGN(64) __m512i* const xacc = (__m512i*)acc; const __m512i prime32 = _mm512_set1_epi32((int)PRIME32_1); /* xacc[0] ^= (xacc[0] >> 47) */ __m512i const acc_vec = *xacc; __m512i const shifted = _mm512_srli_epi64(acc_vec, 47); __m512i const data_vec = _mm512_xor_si512(acc_vec, shifted); /* xacc[0] ^= secret; */ __m512i const key_vec = _mm512_loadu_si512(secret); __m512i const data_key = _mm512_xor_si512(data_vec, key_vec); /* xacc[0] *= PRIME32_1; */ __m512i const data_key_hi = _mm512_shuffle_epi32(data_key, _MM_SHUFFLE(0, 3, 0, 1)); __m512i const prod_lo = _mm512_mul_epu32(data_key, prime32); __m512i const prod_hi = _mm512_mul_epu32(data_key_hi, prime32); *xacc = _mm512_add_epi64(prod_lo, _mm512_slli_epi64(prod_hi, 32)); } #elif (XXH_VECTOR == XXH_AVX2) XXH_ASSERT((((size_t)acc) & 31) == 0); { XXH_ALIGN(32) __m256i* const xacc = (__m256i*)acc; /* Unaligned. This is mainly for pointer arithmetic, and because * _mm256_loadu_si256 requires a const __m256i * pointer for some reason. */ const __m256i* const xsecret = (const __m256i*)secret; const __m256i prime32 = _mm256_set1_epi32((int)PRIME32_1); size_t i; for (i = 0; i < STRIPE_LEN / sizeof(__m256i); i++) { /* xacc[i] ^= (xacc[i] >> 47) */ __m256i const acc_vec = xacc[i]; __m256i const shifted = _mm256_srli_epi64(acc_vec, 47); __m256i const data_vec = _mm256_xor_si256(acc_vec, shifted); /* xacc[i] ^= xsecret; */ __m256i const key_vec = _mm256_loadu_si256(xsecret + i); __m256i const data_key = _mm256_xor_si256(data_vec, key_vec); /* xacc[i] *= PRIME32_1; */ __m256i const data_key_hi = _mm256_shuffle_epi32(data_key, _MM_SHUFFLE(0, 3, 0, 1)); __m256i const prod_lo = _mm256_mul_epu32(data_key, prime32); __m256i const prod_hi = _mm256_mul_epu32(data_key_hi, prime32); xacc[i] = _mm256_add_epi64(prod_lo, _mm256_slli_epi64(prod_hi, 32)); } } #elif (XXH_VECTOR == XXH_SSE2) XXH_ASSERT((((size_t)acc) & 15) == 0); { XXH_ALIGN(16) __m128i* const xacc = (__m128i*)acc; /* Unaligned. This is mainly for pointer arithmetic, and because * _mm_loadu_si128 requires a const __m128i * pointer for some reason. */ const __m128i* const xsecret = (const __m128i*)secret; const __m128i prime32 = _mm_set1_epi32((int)PRIME32_1); size_t i; for (i = 0; i < STRIPE_LEN / sizeof(__m128i); i++) { /* xacc[i] ^= (xacc[i] >> 47) */ __m128i const acc_vec = xacc[i]; __m128i const shifted = _mm_srli_epi64(acc_vec, 47); __m128i const data_vec = _mm_xor_si128(acc_vec, shifted); /* xacc[i] ^= xsecret[i]; */ __m128i const key_vec = _mm_loadu_si128(xsecret + i); __m128i const data_key = _mm_xor_si128(data_vec, key_vec); /* xacc[i] *= PRIME32_1; */ __m128i const data_key_hi = _mm_shuffle_epi32(data_key, _MM_SHUFFLE(0, 3, 0, 1)); __m128i const prod_lo = _mm_mul_epu32(data_key, prime32); __m128i const prod_hi = _mm_mul_epu32(data_key_hi, prime32); xacc[i] = _mm_add_epi64(prod_lo, _mm_slli_epi64(prod_hi, 32)); } } #elif (XXH_VECTOR == XXH_NEON) XXH_ASSERT((((size_t)acc) & 15) == 0); { uint64x2_t* xacc = (uint64x2_t*)acc; uint8_t const* xsecret = (uint8_t const*)secret; uint32x2_t prime = vdup_n_u32(PRIME32_1); size_t i; for (i = 0; i < STRIPE_LEN / sizeof(uint64x2_t); i++) { /* xacc[i] ^= (xacc[i] >> 47); */ uint64x2_t acc_vec = xacc[i]; uint64x2_t shifted = vshrq_n_u64(acc_vec, 47); uint64x2_t data_vec = veorq_u64(acc_vec, shifted); /* xacc[i] ^= xsecret[i]; */ uint8x16_t key_vec = vld1q_u8(xsecret + (i * 16)); uint64x2_t data_key = veorq_u64(data_vec, vreinterpretq_u64_u8(key_vec)); /* xacc[i] *= PRIME32_1 */ uint32x2_t data_key_lo, data_key_hi; /* data_key_lo = (uint32x2_t) (xacc[i] & 0xFFFFFFFF); * data_key_hi = (uint32x2_t) (xacc[i] >> 32); * xacc[i] = UNDEFINED; */ XXH_SPLIT_IN_PLACE(data_key, data_key_lo, data_key_hi); { /* * prod_hi = (data_key >> 32) * PRIME32_1; * * Avoid vmul_u32 + vshll_n_u32 since Clang 6 and 7 will * incorrectly "optimize" this: * tmp = vmul_u32(vmovn_u64(a), vmovn_u64(b)); * shifted = vshll_n_u32(tmp, 32); * to this: * tmp = "vmulq_u64"(a, b); // no such thing! * shifted = vshlq_n_u64(tmp, 32); * * However, unlike SSE, Clang lacks a 64-bit multiply routine * for NEON, and it scalarizes two 64-bit multiplies instead. * * vmull_u32 has the same timing as vmul_u32, and it avoids * this bug completely. * See https://bugs.llvm.org/show_bug.cgi?id=39967 */ uint64x2_t prod_hi = vmull_u32(data_key_hi, prime); /* xacc[i] = prod_hi << 32; */ xacc[i] = vshlq_n_u64(prod_hi, 32); /* xacc[i] += (prod_hi & 0xFFFFFFFF) * PRIME32_1; */ xacc[i] = vmlal_u32(xacc[i], data_key_lo, prime); } } } #elif (XXH_VECTOR == XXH_VSX) XXH_ASSERT((((size_t)acc) & 15) == 0); { xxh_u64x2* const xacc = (xxh_u64x2*)acc; const xxh_u64x2* const xsecret = (const xxh_u64x2*)secret; /* constants */ xxh_u64x2 const v32 = {32, 32}; xxh_u64x2 const v47 = {47, 47}; xxh_u32x4 const prime = {PRIME32_1, PRIME32_1, PRIME32_1, PRIME32_1}; size_t i; for (i = 0; i < STRIPE_LEN / sizeof(xxh_u64x2); i++) { /* xacc[i] ^= (xacc[i] >> 47); */ xxh_u64x2 const acc_vec = xacc[i]; xxh_u64x2 const data_vec = acc_vec ^ (acc_vec >> v47); /* xacc[i] ^= xsecret[i]; */ xxh_u64x2 const key_vec = XXH_vec_loadu(xsecret + i); xxh_u64x2 const data_key = data_vec ^ key_vec; /* xacc[i] *= PRIME32_1 */ /* prod_lo = ((xxh_u64x2)data_key & 0xFFFFFFFF) * ((xxh_u64x2)prime & 0xFFFFFFFF); */ xxh_u64x2 const prod_even = XXH_vec_mule((xxh_u32x4)data_key, prime); /* prod_hi = ((xxh_u64x2)data_key >> 32) * ((xxh_u64x2)prime >> 32); */ xxh_u64x2 const prod_odd = XXH_vec_mulo((xxh_u32x4)data_key, prime); xacc[i] = prod_odd + (prod_even << v32); } } #else /* scalar variant of Scrambler - universal */ XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64* const xacc = (xxh_u64*)acc; /* presumed aligned */ const xxh_u8* const xsecret = (const xxh_u8*)secret; /* no alignment restriction */ size_t i; XXH_ASSERT((((size_t)acc) & (XXH_ACC_ALIGN - 1)) == 0); for (i = 0; i < ACC_NB; i++) { xxh_u64 const key64 = XXH_readLE64(xsecret + 8 * i); xxh_u64 acc64 = xacc[i]; acc64 = XXH_xorshift64(acc64, 47); acc64 ^= key64; acc64 *= PRIME32_1; xacc[i] = acc64; } #endif } #define XXH_PREFETCH_DIST 384 #ifdef __clang__ // for clang #define XXH_PREFETCH_DIST_AVX512_64 320 #define XXH_PREFETCH_DIST_AVX512_128 320 #else // for gcc #define XXH_PREFETCH_DIST_AVX512_64 640 #define XXH_PREFETCH_DIST_AVX512_128 512 #endif /* * XXH3_accumulate() * Loops over XXH3_accumulate_512(). * Assumption: nbStripes will not overflow the secret size */ XXH_FORCE_INLINE void XXH3_accumulate(xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT input, const xxh_u8* XXH_RESTRICT secret, size_t nbStripes, XXH3_accWidth_e accWidth) { size_t n; for (n = 0; n < nbStripes; n++) { const xxh_u8* const in = input + n * STRIPE_LEN; #if (XXH_VECTOR == XXH_AVX512) if (accWidth == XXH3_acc_64bits) XXH_PREFETCH(in + XXH_PREFETCH_DIST_AVX512_64); else XXH_PREFETCH(in + XXH_PREFETCH_DIST_AVX512_128); #else XXH_PREFETCH(in + XXH_PREFETCH_DIST); #endif XXH3_accumulate_512(acc, in, secret + n * XXH_SECRET_CONSUME_RATE, accWidth); } } XXH_FORCE_INLINE void XXH3_hashLong_internal_loop( xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize, XXH3_accWidth_e accWidth) { size_t const nb_rounds = (secretSize - STRIPE_LEN) / XXH_SECRET_CONSUME_RATE; size_t const block_len = STRIPE_LEN * nb_rounds; size_t const nb_blocks = len / block_len; size_t n; XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); for (n = 0; n < nb_blocks; n++) { XXH3_accumulate(acc, input + n * block_len, secret, nb_rounds, accWidth); XXH3_scrambleAcc(acc, secret + secretSize - STRIPE_LEN); } /* last partial block */ XXH_ASSERT(len > STRIPE_LEN); { size_t const nbStripes = (len - (block_len * nb_blocks)) / STRIPE_LEN; XXH_ASSERT(nbStripes <= (secretSize / XXH_SECRET_CONSUME_RATE)); XXH3_accumulate(acc, input + nb_blocks * block_len, secret, nbStripes, accWidth); /* last stripe */ if (len & (STRIPE_LEN - 1)) { const xxh_u8* const p = input + len - STRIPE_LEN; /* Do not align on 8, so that the secret is different from the scrambler */ #define XXH_SECRET_LASTACC_START 7 XXH3_accumulate_512(acc, p, secret + secretSize - STRIPE_LEN - XXH_SECRET_LASTACC_START, accWidth); } } } XXH_FORCE_INLINE xxh_u64 XXH3_mix2Accs(const xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT secret) { return XXH3_mul128_fold64(acc[0] ^ XXH_readLE64(secret), acc[1] ^ XXH_readLE64(secret + 8)); } static XXH64_hash_t XXH3_mergeAccs(const xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT secret, xxh_u64 start) { xxh_u64 result64 = start; size_t i = 0; for (i = 0; i < 4; i++) { result64 += XXH3_mix2Accs(acc + 2 * i, secret + 16 * i); #if defined(__clang__) /* Clang */ \ && (defined(__arm__) || defined(__thumb__)) /* ARMv7 */ \ && (defined(__ARM_NEON) || defined(__ARM_NEON__)) /* NEON */ \ && !defined(XXH_ENABLE_AUTOVECTORIZE) /* Define to disable */ /* * UGLY HACK: * Prevent autovectorization on Clang ARMv7-a. Exact same problem as * the one in XXH3_len_129to240_64b. Speeds up shorter keys > 240b. * XXH3_64bits, len == 256, Snapdragon 835: * without hack: 2063.7 MB/s * with hack: 2560.7 MB/s */ __asm__("" : "+r"(result64)); #endif } return XXH3_avalanche(result64); } #define XXH3_INIT_ACC \ { \ PRIME32_3, PRIME64_1, PRIME64_2, PRIME64_3, PRIME64_4, PRIME32_2, PRIME64_5, PRIME32_1 \ } XXH_FORCE_INLINE XXH64_hash_t XXH3_hashLong_64b_internal(const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize) { XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[ACC_NB] = XXH3_INIT_ACC; XXH3_hashLong_internal_loop(acc, input, len, secret, secretSize, XXH3_acc_64bits); /* converge into final hash */ XXH_STATIC_ASSERT(sizeof(acc) == 64); /* do not align on 8, so that the secret is different from the accumulator */ #define XXH_SECRET_MERGEACCS_START 11 XXH_ASSERT(secretSize >= sizeof(acc) + XXH_SECRET_MERGEACCS_START); return XXH3_mergeAccs(acc, secret + XXH_SECRET_MERGEACCS_START, (xxh_u64)len * PRIME64_1); } XXH_FORCE_INLINE void XXH_writeLE64(void* dst, xxh_u64 v64) { if (!XXH_CPU_LITTLE_ENDIAN) v64 = XXH_swap64(v64); memcpy(dst, &v64, sizeof(v64)); } /* XXH3_initCustomSecret() : * destination `customSecret` is presumed allocated and same size as `kSecret`. */ XXH_FORCE_INLINE void XXH3_initCustomSecret(xxh_u8* XXH_RESTRICT customSecret, xxh_u64 seed64) { int const nbRounds = XXH_SECRET_DEFAULT_SIZE / 16; int i; /* * We need a separate pointer for the hack below. * Any decent compiler will optimize this out otherwise. */ const xxh_u8* kSecretPtr = kSecret; XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 15) == 0); #if defined(__clang__) && defined(__aarch64__) /* * UGLY HACK: * Clang generates a bunch of MOV/MOVK pairs for aarch64, and they are * placed sequentially, in order, at the top of the unrolled loop. * * While MOVK is great for generating constants (2 cycles for a 64-bit * constant compared to 4 cycles for LDR), long MOVK chains stall the * integer pipelines: * I L S * MOVK * MOVK * MOVK * MOVK * ADD * SUB STR * STR * By forcing loads from memory (as the asm line causes Clang to assume * that kSecretPtr has been changed), the pipelines are used more efficiently: * I L S * LDR * ADD LDR * SUB STR * STR * XXH3_64bits_withSeed, len == 256, Snapdragon 835 * without hack: 2654.4 MB/s * with hack: 3202.9 MB/s */ __asm__("" : "+r"(kSecretPtr)); #endif /* * Note: in debug mode, this overrides the asm optimization * and Clang will emit MOVK chains again. */ XXH_ASSERT(kSecretPtr == kSecret); for (i = 0; i < nbRounds; i++) { /* * The asm hack causes Clang to assume that kSecretPtr aliases with * customSecret, and on aarch64, this prevented LDP from merging two * loads together for free. Putting the loads together before the stores * properly generates LDP. */ xxh_u64 lo = XXH_readLE64(kSecretPtr + 16 * i) + seed64; xxh_u64 hi = XXH_readLE64(kSecretPtr + 16 * i + 8) - seed64; XXH_writeLE64(customSecret + 16 * i, lo); XXH_writeLE64(customSecret + 16 * i + 8, hi); } } /* * It's important for performance that XXH3_hashLong is not inlined. Not sure * why (uop cache maybe?), but the difference is large and easily measurable. */ XXH_NO_INLINE XXH64_hash_t XXH3_hashLong_64b_defaultSecret(const xxh_u8* XXH_RESTRICT input, size_t len) { return XXH3_hashLong_64b_internal(input, len, kSecret, sizeof(kSecret)); } /* * It's important for performance that XXH3_hashLong is not inlined. Not sure * why (uop cache maybe?), but the difference is large and easily measurable. */ XXH_NO_INLINE XXH64_hash_t XXH3_hashLong_64b_withSecret(const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize) { return XXH3_hashLong_64b_internal(input, len, secret, secretSize); } /* * XXH3_hashLong_64b_withSeed(): * Generate a custom key based on alteration of default kSecret with the seed, * and then use this key for long mode hashing. * * This operation is decently fast but nonetheless costs a little bit of time. * Try to avoid it whenever possible (typically when seed==0). * * It's important for performance that XXH3_hashLong is not inlined. Not sure * why (uop cache maybe?), but the difference is large and easily measurable. */ XXH_NO_INLINE XXH64_hash_t XXH3_hashLong_64b_withSeed(const xxh_u8* input, size_t len, XXH64_hash_t seed) { XXH_ALIGN(8) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE]; if (seed == 0) return XXH3_hashLong_64b_defaultSecret(input, len); XXH3_initCustomSecret(secret, seed); return XXH3_hashLong_64b_internal(input, len, secret, sizeof(secret)); } /* === Public entry point === */ XXH_PUBLIC_API XXH64_hash_t XXH3_64bits(const void* input, size_t len) { if (len <= 16) return XXH3_len_0to16_64b((const xxh_u8*)input, len, kSecret, 0); if (len <= 128) return XXH3_len_17to128_64b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), 0); if (len <= XXH3_MIDSIZE_MAX) return XXH3_len_129to240_64b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), 0); return XXH3_hashLong_64b_defaultSecret((const xxh_u8*)input, len); } XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_withSecret(const void* input, size_t len, const void* secret, size_t secretSize) { XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); /* * If an action is to be taken if `secret` conditions are not respected, * it should be done here. * For now, it's a contract pre-condition. * Adding a check and a branch here would cost performance at every hash. */ if (len <= 16) return XXH3_len_0to16_64b((const xxh_u8*)input, len, (const xxh_u8*)secret, 0); if (len <= 128) return XXH3_len_17to128_64b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize, 0); if (len <= XXH3_MIDSIZE_MAX) return XXH3_len_129to240_64b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize, 0); return XXH3_hashLong_64b_withSecret((const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize); } XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_withSeed(const void* input, size_t len, XXH64_hash_t seed) { if (len <= 16) return XXH3_len_0to16_64b((const xxh_u8*)input, len, kSecret, seed); if (len <= 128) return XXH3_len_17to128_64b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), seed); if (len <= XXH3_MIDSIZE_MAX) return XXH3_len_129to240_64b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), seed); return XXH3_hashLong_64b_withSeed((const xxh_u8*)input, len, seed); } /* === XXH3 streaming === */ /* * Malloc's a pointer that is always aligned to align. * * This must be freed with `XXH_alignedFree()`. * * malloc typically guarantees 16 byte alignment on 64-bit systems and 8 byte * alignment on 32-bit. This isn't enough for the 32 byte aligned loads in AVX2 * or on 32-bit, the 16 byte aligned loads in SSE2 and NEON. * * This underalignment previously caused a rather obvious crash which went * completely unnoticed due to XXH3_createState() not actually being tested. * Credit to RedSpah for noticing this bug. * * The alignment is done manually: Functions like posix_memalign or _mm_malloc * are avoided: To maintain portability, we would have to write a fallback * like this anyways, and besides, testing for the existence of library * functions without relying on external build tools is impossible. * * The method is simple: Overallocate, manually align, and store the offset * to the original behind the returned pointer. * * Align must be a power of 2 and 8 <= align <= 128. */ static void* XXH_alignedMalloc(size_t s, size_t align) { XXH_ASSERT(align <= 128 && align >= 8); /* range check */ XXH_ASSERT((align & (align - 1)) == 0); /* power of 2 */ XXH_ASSERT(s != 0 && s < (s + align)); /* empty/overflow */ { /* Overallocate to make room for manual realignment and an offset byte */ xxh_u8* base = (xxh_u8*)XXH_malloc(s + align); if (base != NULL) { /* * Get the offset needed to align this pointer. * * Even if the returned pointer is aligned, there will always be * at least one byte to store the offset to the original pointer. */ size_t offset = align - ((size_t)base & (align - 1)); /* base % align */ /* Add the offset for the now-aligned pointer */ xxh_u8* ptr = base + offset; XXH_ASSERT((size_t)ptr % align == 0); /* Store the offset immediately before the returned pointer. */ ptr[-1] = (xxh_u8)offset; return ptr; } return NULL; } } /* * Frees an aligned pointer allocated by XXH_alignedMalloc(). Don't pass * normal malloc'd pointers, XXH_alignedMalloc has a specific data layout. */ static void XXH_alignedFree(void* p) { if (p != NULL) { xxh_u8* ptr = (xxh_u8*)p; /* Get the offset byte we added in XXH_malloc. */ xxh_u8 offset = ptr[-1]; /* Free the original malloc'd pointer */ xxh_u8* base = ptr - offset; XXH_free(base); } } XXH_PUBLIC_API XXH3_state_t* XXH3_createState(void) { return (XXH3_state_t*)XXH_alignedMalloc(sizeof(XXH3_state_t), 64); } XXH_PUBLIC_API XXH_errorcode XXH3_freeState(XXH3_state_t* statePtr) { XXH_alignedFree(statePtr); return XXH_OK; } XXH_PUBLIC_API void XXH3_copyState(XXH3_state_t* dst_state, const XXH3_state_t* src_state) { memcpy(dst_state, src_state, sizeof(*dst_state)); } static void XXH3_64bits_reset_internal(XXH3_state_t* statePtr, XXH64_hash_t seed, const xxh_u8* secret, size_t secretSize) { XXH_ASSERT(statePtr != NULL); memset(statePtr, 0, sizeof(*statePtr)); statePtr->acc[0] = PRIME32_3; statePtr->acc[1] = PRIME64_1; statePtr->acc[2] = PRIME64_2; statePtr->acc[3] = PRIME64_3; statePtr->acc[4] = PRIME64_4; statePtr->acc[5] = PRIME32_2; statePtr->acc[6] = PRIME64_5; statePtr->acc[7] = PRIME32_1; statePtr->seed = seed; XXH_ASSERT(secret != NULL); statePtr->secret = secret; XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); statePtr->secretLimit = (XXH32_hash_t)(secretSize - STRIPE_LEN); statePtr->nbStripesPerBlock = statePtr->secretLimit / XXH_SECRET_CONSUME_RATE; } XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset(XXH3_state_t* statePtr) { if (statePtr == NULL) return XXH_ERROR; XXH3_64bits_reset_internal(statePtr, 0, kSecret, XXH_SECRET_DEFAULT_SIZE); return XXH_OK; } XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSecret(XXH3_state_t* statePtr, const void* secret, size_t secretSize) { if (statePtr == NULL) return XXH_ERROR; XXH3_64bits_reset_internal(statePtr, 0, (const xxh_u8*)secret, secretSize); if (secret == NULL) return XXH_ERROR; if (secretSize < XXH3_SECRET_SIZE_MIN) return XXH_ERROR; return XXH_OK; } XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSeed(XXH3_state_t* statePtr, XXH64_hash_t seed) { if (statePtr == NULL) return XXH_ERROR; XXH3_64bits_reset_internal(statePtr, seed, kSecret, XXH_SECRET_DEFAULT_SIZE); XXH3_initCustomSecret(statePtr->customSecret, seed); statePtr->secret = statePtr->customSecret; return XXH_OK; } XXH_FORCE_INLINE void XXH3_consumeStripes(xxh_u64* acc, XXH32_hash_t* nbStripesSoFarPtr, XXH32_hash_t nbStripesPerBlock, const xxh_u8* input, size_t totalStripes, const xxh_u8* secret, size_t secretLimit, XXH3_accWidth_e accWidth) { XXH_ASSERT(*nbStripesSoFarPtr < nbStripesPerBlock); if (nbStripesPerBlock - *nbStripesSoFarPtr <= totalStripes) { /* need a scrambling operation */ size_t const nbStripes = nbStripesPerBlock - *nbStripesSoFarPtr; XXH3_accumulate(acc, input, secret + nbStripesSoFarPtr[0] * XXH_SECRET_CONSUME_RATE, nbStripes, accWidth); XXH3_scrambleAcc(acc, secret + secretLimit); XXH3_accumulate(acc, input + nbStripes * STRIPE_LEN, secret, totalStripes - nbStripes, accWidth); *nbStripesSoFarPtr = (XXH32_hash_t)(totalStripes - nbStripes); } else { XXH3_accumulate(acc, input, secret + nbStripesSoFarPtr[0] * XXH_SECRET_CONSUME_RATE, totalStripes, accWidth); *nbStripesSoFarPtr += (XXH32_hash_t)totalStripes; } } /* * Both XXH3_64bits_update and XXH3_128bits_update use this routine. */ XXH_FORCE_INLINE XXH_errorcode XXH3_update(XXH3_state_t* state, const xxh_u8* input, size_t len, XXH3_accWidth_e accWidth) { if (input == NULL) #if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER >= 1) return XXH_OK; #else return XXH_ERROR; #endif { const xxh_u8* const bEnd = input + len; state->totalLen += len; if (state->bufferedSize + len <= XXH3_INTERNALBUFFER_SIZE) { /* fill in tmp buffer */ XXH_memcpy(state->buffer + state->bufferedSize, input, len); state->bufferedSize += (XXH32_hash_t)len; return XXH_OK; } /* input is now > XXH3_INTERNALBUFFER_SIZE */ #define XXH3_INTERNALBUFFER_STRIPES (XXH3_INTERNALBUFFER_SIZE / STRIPE_LEN) XXH_STATIC_ASSERT(XXH3_INTERNALBUFFER_SIZE % STRIPE_LEN == 0); /* clean multiple */ /* * There is some input left inside the internal buffer. * Fill it, then consume it. */ if (state->bufferedSize) { size_t const loadSize = XXH3_INTERNALBUFFER_SIZE - state->bufferedSize; XXH_memcpy(state->buffer + state->bufferedSize, input, loadSize); input += loadSize; XXH3_consumeStripes(state->acc, &state->nbStripesSoFar, state->nbStripesPerBlock, state->buffer, XXH3_INTERNALBUFFER_STRIPES, state->secret, state->secretLimit, accWidth); state->bufferedSize = 0; } /* Consume input by full buffer quantities */ if (input + XXH3_INTERNALBUFFER_SIZE <= bEnd) { const xxh_u8* const limit = bEnd - XXH3_INTERNALBUFFER_SIZE; do { XXH3_consumeStripes(state->acc, &state->nbStripesSoFar, state->nbStripesPerBlock, input, XXH3_INTERNALBUFFER_STRIPES, state->secret, state->secretLimit, accWidth); input += XXH3_INTERNALBUFFER_SIZE; } while (input <= limit); } if (input < bEnd) { /* Some remaining input: buffer it */ XXH_memcpy(state->buffer, input, (size_t)(bEnd - input)); state->bufferedSize = (XXH32_hash_t)(bEnd - input); } } return XXH_OK; } XXH_PUBLIC_API XXH_errorcode XXH3_64bits_update(XXH3_state_t* state, const void* input, size_t len) { return XXH3_update(state, (const xxh_u8*)input, len, XXH3_acc_64bits); } XXH_FORCE_INLINE void XXH3_digest_long(XXH64_hash_t* acc, const XXH3_state_t* state, XXH3_accWidth_e accWidth) { /* * Digest on a local copy. This way, the state remains unaltered, and it can * continue ingesting more input afterwards. */ memcpy(acc, state->acc, sizeof(state->acc)); if (state->bufferedSize >= STRIPE_LEN) { size_t const totalNbStripes = state->bufferedSize / STRIPE_LEN; XXH32_hash_t nbStripesSoFar = state->nbStripesSoFar; XXH3_consumeStripes(acc, &nbStripesSoFar, state->nbStripesPerBlock, state->buffer, totalNbStripes, state->secret, state->secretLimit, accWidth); if (state->bufferedSize % STRIPE_LEN) { /* one last partial stripe */ XXH3_accumulate_512(acc, state->buffer + state->bufferedSize - STRIPE_LEN, state->secret + state->secretLimit - XXH_SECRET_LASTACC_START, accWidth); } } else { /* bufferedSize < STRIPE_LEN */ if (state->bufferedSize) { /* one last stripe */ xxh_u8 lastStripe[STRIPE_LEN]; size_t const catchupSize = STRIPE_LEN - state->bufferedSize; memcpy(lastStripe, state->buffer + sizeof(state->buffer) - catchupSize, catchupSize); memcpy(lastStripe + catchupSize, state->buffer, state->bufferedSize); XXH3_accumulate_512(acc, lastStripe, state->secret + state->secretLimit - XXH_SECRET_LASTACC_START, accWidth); } } } XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_digest(const XXH3_state_t* state) { if (state->totalLen > XXH3_MIDSIZE_MAX) { XXH_ALIGN(XXH_ACC_ALIGN) XXH64_hash_t acc[ACC_NB]; XXH3_digest_long(acc, state, XXH3_acc_64bits); return XXH3_mergeAccs(acc, state->secret + XXH_SECRET_MERGEACCS_START, (xxh_u64)state->totalLen * PRIME64_1); } /* len <= XXH3_MIDSIZE_MAX: short code */ if (state->seed) return XXH3_64bits_withSeed(state->buffer, (size_t)state->totalLen, state->seed); return XXH3_64bits_withSecret(state->buffer, (size_t)(state->totalLen), state->secret, state->secretLimit + STRIPE_LEN); } /* ========================================== * XXH3 128 bits (a.k.a XXH128) * ========================================== * XXH3's 128-bit variant has better mixing and strength than the 64-bit variant, * even without counting the significantly larger output size. * * For example, extra steps are taken to avoid the seed-dependent collisions * in 17-240 byte inputs (See XXH3_mix16B and XXH128_mix32B). * * This strength naturally comes at the cost of some speed, especially on short * lengths. Note that longer hashes are about as fast as the 64-bit version * due to it using only a slight modification of the 64-bit loop. * * XXH128 is also more oriented towards 64-bit machines. It is still extremely * fast for a _128-bit_ hash on 32-bit (it usually clears XXH64). */ XXH_FORCE_INLINE XXH128_hash_t XXH3_len_1to3_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) { /* A doubled version of 1to3_64b with different constants. */ XXH_ASSERT(input != NULL); XXH_ASSERT(1 <= len && len <= 3); XXH_ASSERT(secret != NULL); /* * len = 1: combinedl = { input[0], 0x01, input[0], input[0] } * len = 2: combinedl = { input[1], 0x02, input[0], input[1] } * len = 3: combinedl = { input[2], 0x03, input[0], input[1] } */ { xxh_u8 const c1 = input[0]; xxh_u8 const c2 = input[len >> 1]; xxh_u8 const c3 = input[len - 1]; xxh_u32 const combinedl = ((xxh_u32)c1 << 16) | ((xxh_u32)c2 << 24) | ((xxh_u32)c3 << 0) | ((xxh_u32)len << 8); xxh_u32 const combinedh = XXH_rotl32(XXH_swap32(combinedl), 13); xxh_u64 const bitflipl = (XXH_readLE32(secret) ^ XXH_readLE32(secret + 4)) + seed; xxh_u64 const bitfliph = (XXH_readLE32(secret + 8) ^ XXH_readLE32(secret + 12)) - seed; xxh_u64 const keyed_lo = (xxh_u64)combinedl ^ bitflipl; xxh_u64 const keyed_hi = (xxh_u64)combinedh ^ bitfliph; xxh_u64 const mixedl = keyed_lo * PRIME64_1; xxh_u64 const mixedh = keyed_hi * PRIME64_5; XXH128_hash_t h128; h128.low64 = XXH3_avalanche(mixedl); h128.high64 = XXH3_avalanche(mixedh); return h128; } } XXH_FORCE_INLINE XXH128_hash_t XXH3_len_4to8_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) { XXH_ASSERT(input != NULL); XXH_ASSERT(secret != NULL); XXH_ASSERT(4 <= len && len <= 8); seed ^= (xxh_u64)XXH_swap32((xxh_u32)seed) << 32; { xxh_u32 const input_lo = XXH_readLE32(input); xxh_u32 const input_hi = XXH_readLE32(input + len - 4); xxh_u64 const input_64 = input_lo + ((xxh_u64)input_hi << 32); xxh_u64 const bitflip = (XXH_readLE64(secret + 16) ^ XXH_readLE64(secret + 24)) + seed; xxh_u64 const keyed = input_64 ^ bitflip; /* Shift len to the left to ensure it is even, this avoids even multiplies. */ XXH128_hash_t m128 = XXH_mult64to128(keyed, PRIME64_1 + (len << 2)); m128.high64 += (m128.low64 << 1); m128.low64 ^= (m128.high64 >> 3); m128.low64 = XXH_xorshift64(m128.low64, 35); m128.low64 *= 0x9FB21C651E98DF25ULL; m128.low64 = XXH_xorshift64(m128.low64, 28); m128.high64 = XXH3_avalanche(m128.high64); return m128; } } XXH_FORCE_INLINE XXH128_hash_t XXH3_len_9to16_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) { XXH_ASSERT(input != NULL); XXH_ASSERT(secret != NULL); XXH_ASSERT(9 <= len && len <= 16); { xxh_u64 const bitflipl = (XXH_readLE64(secret + 32) ^ XXH_readLE64(secret + 40)) - seed; xxh_u64 const bitfliph = (XXH_readLE64(secret + 48) ^ XXH_readLE64(secret + 56)) + seed; xxh_u64 const input_lo = XXH_readLE64(input); xxh_u64 input_hi = XXH_readLE64(input + len - 8); XXH128_hash_t m128 = XXH_mult64to128(input_lo ^ input_hi ^ bitflipl, PRIME64_1); /* * Put len in the middle of m128 to ensure that the length gets mixed to * both the low and high bits in the 128x64 multiply below. */ m128.low64 += (xxh_u64)(len - 1) << 54; input_hi ^= bitfliph; /* * Add the high 32 bits of input_hi to the high 32 bits of m128, then * add the long product of the low 32 bits of input_hi and PRIME32_2 to * the high 64 bits of m128. * * The best approach to this operation is different on 32-bit and 64-bit. */ if (sizeof(void*) < sizeof(xxh_u64)) { /* 32-bit */ /* * 32-bit optimized version, which is more readable. * * On 32-bit, it removes an ADC and delays a dependency between the two * halves of m128.high64, but it generates an extra mask on 64-bit. */ m128.high64 += (input_hi & 0xFFFFFFFF00000000) + XXH_mult32to64((xxh_u32)input_hi, PRIME32_2); } else { /* * 64-bit optimized (albeit more confusing) version. * * Uses some properties of addition and multiplication to remove the mask: * * Let: * a = input_hi.lo = (input_hi & 0x00000000FFFFFFFF) * b = input_hi.hi = (input_hi & 0xFFFFFFFF00000000) * c = PRIME32_2 * * a + (b * c) * Inverse Property: x + y - x == y * a + (b * (1 + c - 1)) * Distributive Property: x * (y + z) == (x * y) + (x * z) * a + (b * 1) + (b * (c - 1)) * Identity Property: x * 1 == x * a + b + (b * (c - 1)) * * Substitute a, b, and c: * input_hi.hi + input_hi.lo + ((xxh_u64)input_hi.lo * (PRIME32_2 - 1)) * * Since input_hi.hi + input_hi.lo == input_hi, we get this: * input_hi + ((xxh_u64)input_hi.lo * (PRIME32_2 - 1)) */ m128.high64 += input_hi + XXH_mult32to64((xxh_u32)input_hi, PRIME32_2 - 1); } /* m128 ^= XXH_swap64(m128 >> 64); */ m128.low64 ^= XXH_swap64(m128.high64); { /* 128x64 multiply: h128 = m128 * PRIME64_2; */ XXH128_hash_t h128 = XXH_mult64to128(m128.low64, PRIME64_2); h128.high64 += m128.high64 * PRIME64_2; h128.low64 = XXH3_avalanche(h128.low64); h128.high64 = XXH3_avalanche(h128.high64); return h128; } } } /* * Assumption: `secret` size is >= XXH3_SECRET_SIZE_MIN */ XXH_FORCE_INLINE XXH128_hash_t XXH3_len_0to16_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed) { XXH_ASSERT(len <= 16); { if (len > 8) return XXH3_len_9to16_128b(input, len, secret, seed); if (len >= 4) return XXH3_len_4to8_128b(input, len, secret, seed); if (len) return XXH3_len_1to3_128b(input, len, secret, seed); { XXH128_hash_t h128; xxh_u64 const bitflipl = XXH_readLE64(secret + 64) ^ XXH_readLE64(secret + 72); xxh_u64 const bitfliph = XXH_readLE64(secret + 80) ^ XXH_readLE64(secret + 88); h128.low64 = XXH3_avalanche((PRIME64_1 + seed) ^ bitflipl); h128.high64 = XXH3_avalanche((PRIME64_2 - seed) ^ bitfliph); return h128; } } } /* * A bit slower than XXH3_mix16B, but handles multiply by zero better. */ XXH_FORCE_INLINE XXH128_hash_t XXH128_mix32B(XXH128_hash_t acc, const xxh_u8* input_1, const xxh_u8* input_2, const xxh_u8* secret, XXH64_hash_t seed) { acc.low64 += XXH3_mix16B(input_1, secret + 0, seed); acc.low64 ^= XXH_readLE64(input_2) + XXH_readLE64(input_2 + 8); acc.high64 += XXH3_mix16B(input_2, secret + 16, seed); acc.high64 ^= XXH_readLE64(input_1) + XXH_readLE64(input_1 + 8); return acc; } XXH_FORCE_INLINE XXH128_hash_t XXH3_len_17to128_128b(const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize, XXH64_hash_t seed) { XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize; XXH_ASSERT(16 < len && len <= 128); { XXH128_hash_t acc; acc.low64 = len * PRIME64_1; acc.high64 = 0; if (len > 32) { if (len > 64) { if (len > 96) { acc = XXH128_mix32B(acc, input + 48, input + len - 64, secret + 96, seed); } acc = XXH128_mix32B(acc, input + 32, input + len - 48, secret + 64, seed); } acc = XXH128_mix32B(acc, input + 16, input + len - 32, secret + 32, seed); } acc = XXH128_mix32B(acc, input, input + len - 16, secret, seed); { XXH128_hash_t h128; h128.low64 = acc.low64 + acc.high64; h128.high64 = (acc.low64 * PRIME64_1) + (acc.high64 * PRIME64_4) + ((len - seed) * PRIME64_2); h128.low64 = XXH3_avalanche(h128.low64); h128.high64 = (XXH64_hash_t)0 - XXH3_avalanche(h128.high64); return h128; } } } XXH_NO_INLINE XXH128_hash_t XXH3_len_129to240_128b(const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize, XXH64_hash_t seed) { XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); (void)secretSize; XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX); { XXH128_hash_t acc; int const nbRounds = (int)len / 32; int i; acc.low64 = len * PRIME64_1; acc.high64 = 0; for (i = 0; i < 4; i++) { acc = XXH128_mix32B(acc, input + (32 * i), input + (32 * i) + 16, secret + (32 * i), seed); } acc.low64 = XXH3_avalanche(acc.low64); acc.high64 = XXH3_avalanche(acc.high64); XXH_ASSERT(nbRounds >= 4); for (i = 4; i < nbRounds; i++) { acc = XXH128_mix32B(acc, input + (32 * i), input + (32 * i) + 16, secret + XXH3_MIDSIZE_STARTOFFSET + (32 * (i - 4)), seed); } /* last bytes */ acc = XXH128_mix32B(acc, input + len - 16, input + len - 32, secret + XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET - 16, 0ULL - seed); { XXH128_hash_t h128; h128.low64 = acc.low64 + acc.high64; h128.high64 = (acc.low64 * PRIME64_1) + (acc.high64 * PRIME64_4) + ((len - seed) * PRIME64_2); h128.low64 = XXH3_avalanche(h128.low64); h128.high64 = (XXH64_hash_t)0 - XXH3_avalanche(h128.high64); return h128; } } } XXH_FORCE_INLINE XXH128_hash_t XXH3_hashLong_128b_internal(const xxh_u8* XXH_RESTRICT input, size_t len, const xxh_u8* XXH_RESTRICT secret, size_t secretSize) { XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[ACC_NB] = XXH3_INIT_ACC; XXH3_hashLong_internal_loop(acc, input, len, secret, secretSize, XXH3_acc_128bits); /* converge into final hash */ XXH_STATIC_ASSERT(sizeof(acc) == 64); XXH_ASSERT(secretSize >= sizeof(acc) + XXH_SECRET_MERGEACCS_START); { XXH128_hash_t h128; h128.low64 = XXH3_mergeAccs(acc, secret + XXH_SECRET_MERGEACCS_START, (xxh_u64)len * PRIME64_1); h128.high64 = XXH3_mergeAccs(acc, secret + secretSize - sizeof(acc) - XXH_SECRET_MERGEACCS_START, ~((xxh_u64)len * PRIME64_2)); return h128; } } /* * It's important for performance that XXH3_hashLong is not inlined. Not sure * why (uop cache maybe?), but the difference is large and easily measurable. */ XXH_NO_INLINE XXH128_hash_t XXH3_hashLong_128b_defaultSecret(const xxh_u8* input, size_t len) { return XXH3_hashLong_128b_internal(input, len, kSecret, sizeof(kSecret)); } /* * It's important for performance that XXH3_hashLong is not inlined. Not sure * why (uop cache maybe?), but the difference is large and easily measurable. */ XXH_NO_INLINE XXH128_hash_t XXH3_hashLong_128b_withSecret(const xxh_u8* input, size_t len, const xxh_u8* secret, size_t secretSize) { return XXH3_hashLong_128b_internal(input, len, secret, secretSize); } /* * It's important for performance that XXH3_hashLong is not inlined. Not sure * why (uop cache maybe?), but the difference is large and easily measurable. */ XXH_NO_INLINE XXH128_hash_t XXH3_hashLong_128b_withSeed(const xxh_u8* input, size_t len, XXH64_hash_t seed) { XXH_ALIGN(8) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE]; if (seed == 0) return XXH3_hashLong_128b_defaultSecret(input, len); XXH3_initCustomSecret(secret, seed); return XXH3_hashLong_128b_internal(input, len, secret, sizeof(secret)); } XXH_PUBLIC_API XXH128_hash_t XXH3_128bits(const void* input, size_t len) { if (len <= 16) return XXH3_len_0to16_128b((const xxh_u8*)input, len, kSecret, 0); if (len <= 128) return XXH3_len_17to128_128b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), 0); if (len <= XXH3_MIDSIZE_MAX) return XXH3_len_129to240_128b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), 0); return XXH3_hashLong_128b_defaultSecret((const xxh_u8*)input, len); } XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_withSecret(const void* input, size_t len, const void* secret, size_t secretSize) { XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN); /* * If an action is to be taken if `secret` conditions are not respected, * it should be done here. * For now, it's a contract pre-condition. * Adding a check and a branch here would cost performance at every hash. */ if (len <= 16) return XXH3_len_0to16_128b((const xxh_u8*)input, len, (const xxh_u8*)secret, 0); if (len <= 128) return XXH3_len_17to128_128b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize, 0); if (len <= XXH3_MIDSIZE_MAX) return XXH3_len_129to240_128b((const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize, 0); return XXH3_hashLong_128b_withSecret((const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize); } XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_withSeed(const void* input, size_t len, XXH64_hash_t seed) { if (len <= 16) return XXH3_len_0to16_128b((const xxh_u8*)input, len, kSecret, seed); if (len <= 128) return XXH3_len_17to128_128b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), seed); if (len <= XXH3_MIDSIZE_MAX) return XXH3_len_129to240_128b((const xxh_u8*)input, len, kSecret, sizeof(kSecret), seed); return XXH3_hashLong_128b_withSeed((const xxh_u8*)input, len, seed); } XXH_PUBLIC_API XXH128_hash_t XXH128(const void* input, size_t len, XXH64_hash_t seed) { return XXH3_128bits_withSeed(input, len, seed); } /* === XXH3 128-bit streaming === */ /* * All the functions are actually the same as for 64-bit streaming variant. * The only difference is the finalizatiom routine. */ static void XXH3_128bits_reset_internal(XXH3_state_t* statePtr, XXH64_hash_t seed, const xxh_u8* secret, size_t secretSize) { XXH3_64bits_reset_internal(statePtr, seed, secret, secretSize); } XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset(XXH3_state_t* statePtr) { if (statePtr == NULL) return XXH_ERROR; XXH3_128bits_reset_internal(statePtr, 0, kSecret, XXH_SECRET_DEFAULT_SIZE); return XXH_OK; } XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSecret(XXH3_state_t* statePtr, const void* secret, size_t secretSize) { if (statePtr == NULL) return XXH_ERROR; XXH3_128bits_reset_internal(statePtr, 0, (const xxh_u8*)secret, secretSize); if (secret == NULL) return XXH_ERROR; if (secretSize < XXH3_SECRET_SIZE_MIN) return XXH_ERROR; return XXH_OK; } XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSeed(XXH3_state_t* statePtr, XXH64_hash_t seed) { if (statePtr == NULL) return XXH_ERROR; XXH3_128bits_reset_internal(statePtr, seed, kSecret, XXH_SECRET_DEFAULT_SIZE); XXH3_initCustomSecret(statePtr->customSecret, seed); statePtr->secret = statePtr->customSecret; return XXH_OK; } XXH_PUBLIC_API XXH_errorcode XXH3_128bits_update(XXH3_state_t* state, const void* input, size_t len) { return XXH3_update(state, (const xxh_u8*)input, len, XXH3_acc_128bits); } XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_digest(const XXH3_state_t* state) { if (state->totalLen > XXH3_MIDSIZE_MAX) { XXH_ALIGN(XXH_ACC_ALIGN) XXH64_hash_t acc[ACC_NB]; XXH3_digest_long(acc, state, XXH3_acc_128bits); XXH_ASSERT(state->secretLimit + STRIPE_LEN >= sizeof(acc) + XXH_SECRET_MERGEACCS_START); { XXH128_hash_t h128; h128.low64 = XXH3_mergeAccs(acc, state->secret + XXH_SECRET_MERGEACCS_START, (xxh_u64)state->totalLen * PRIME64_1); h128.high64 = XXH3_mergeAccs(acc, state->secret + state->secretLimit + STRIPE_LEN - sizeof(acc) - XXH_SECRET_MERGEACCS_START, ~((xxh_u64)state->totalLen * PRIME64_2)); return h128; } } /* len <= XXH3_MIDSIZE_MAX : short code */ if (state->seed) return XXH3_128bits_withSeed(state->buffer, (size_t)state->totalLen, state->seed); return XXH3_128bits_withSecret(state->buffer, (size_t)(state->totalLen), state->secret, state->secretLimit + STRIPE_LEN); } /* 128-bit utility functions */ #include <string.h> /* memcmp, memcpy */ /* return : 1 is equal, 0 if different */ XXH_PUBLIC_API int XXH128_isEqual(XXH128_hash_t h1, XXH128_hash_t h2) { /* note : XXH128_hash_t is compact, it has no padding byte */ return !(memcmp(&h1, &h2, sizeof(h1))); } /* This prototype is compatible with stdlib's qsort(). * return : >0 if *h128_1 > *h128_2 * <0 if *h128_1 < *h128_2 * =0 if *h128_1 == *h128_2 */ XXH_PUBLIC_API int XXH128_cmp(const void* h128_1, const void* h128_2) { XXH128_hash_t const h1 = *(const XXH128_hash_t*)h128_1; XXH128_hash_t const h2 = *(const XXH128_hash_t*)h128_2; int const hcmp = (h1.high64 > h2.high64) - (h2.high64 > h1.high64); /* note : bets that, in most cases, hash values are different */ if (hcmp) return hcmp; return (h1.low64 > h2.low64) - (h2.low64 > h1.low64); } /*====== Canonical representation ======*/ XXH_PUBLIC_API void XXH128_canonicalFromHash(XXH128_canonical_t* dst, XXH128_hash_t hash) { XXH_STATIC_ASSERT(sizeof(XXH128_canonical_t) == sizeof(XXH128_hash_t)); if (XXH_CPU_LITTLE_ENDIAN) { hash.high64 = XXH_swap64(hash.high64); hash.low64 = XXH_swap64(hash.low64); } memcpy(dst, &hash.high64, sizeof(hash.high64)); memcpy((char*)dst + sizeof(hash.high64), &hash.low64, sizeof(hash.low64)); } XXH_PUBLIC_API XXH128_hash_t XXH128_hashFromCanonical(const XXH128_canonical_t* src) { XXH128_hash_t h; h.high64 = XXH_readBE64(src); h.low64 = XXH_readBE64(src->digest + 8); return h; } /* Pop our optimization override from above */ #if XXH_VECTOR == XXH_AVX2 /* AVX2 */ \ && defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \ && defined(__OPTIMIZE__) && !defined(__OPTIMIZE_SIZE__) /* respect -O0 and -Os */ #pragma GCC pop_options #endif #endif /* XXH3_H_1397135465 */
40.071248
177
0.636367
rovedit
94efd0d68247f41cfe2aca7fc2265f8b590afac7
3,063
cpp
C++
GrowtopiaServer/resource/server/GamePacket.cpp
LinkProfitSG/GTPS
fa654fb20b62d8ff3e35c3784f5d0fa7a3368135
[ "Apache-2.0" ]
2
2021-06-08T08:17:56.000Z
2021-12-02T20:41:28.000Z
GrowtopiaServer/resource/server/GamePacket.cpp
LinkProfitSG/GTPS
fa654fb20b62d8ff3e35c3784f5d0fa7a3368135
[ "Apache-2.0" ]
1
2021-12-02T20:46:47.000Z
2021-12-02T20:52:40.000Z
GrowtopiaServer/resource/server/GamePacket.cpp
LinkProfitSG/GTPS
fa654fb20b62d8ff3e35c3784f5d0fa7a3368135
[ "Apache-2.0" ]
3
2021-07-27T21:30:35.000Z
2021-10-07T07:52:27.000Z
#pragma warning (disable : 4244) #include "../../Server.hpp" using namespace std; GamePacket::~GamePacket() { delete[] data_; } GamePacket::GamePacket(int delay, int netId) { len_ = 61; int messageType = 0x4, packetType = 0x1, charState = 0x8; memset(data_, 0, 61); memcpy(data_, &messageType, 4); memcpy(data_ + 4, &packetType, 4); memcpy(data_ + 8, &netId, 4); memcpy(data_ + 16, &charState, 4); memcpy(data_ + 24, &delay, 4); } GamePacket& GamePacket::extend(string str) { unsigned char* data = new unsigned char[len_ + 2 + str.length() + 4]; memcpy(data, this->data_, len_); delete[] this->data_; this->data_ = data; data[len_] = index_; data[len_ + 1] = 0x2; unsigned long long len = str.length(); memcpy(data + len_ + 2, &len, 4); memcpy(data + len_ + 6, str.data(), len); len_ += 2 + len + 4; index_++; data_[60] = static_cast<unsigned char>(index_); return *this; } GamePacket& GamePacket::extend(int i) { unsigned char* data = new unsigned char[len_ + 2 + 4]; memcpy(data, this->data_, len_); delete[] this->data_; this->data_ = data; data[len_] = index_; data[len_ + 1] = 0x9; memcpy(data + len_ + 2, &i, 4); len_ += 2 + 4; index_++; data_[60] = static_cast<unsigned char>(index_); return *this; } GamePacket& GamePacket::extend(unsigned u) { unsigned char* data = new unsigned char[len_ + 2 + 4]; memcpy(data, this->data_, len_); delete[] this->data_; this->data_ = data; data[len_] = index_; data[len_ + 1] = 0x5; memcpy(data + len_ + 2, &u, 4); len_ += 2 + 4; index_++; data_[60] = static_cast<unsigned char>(index_); return *this; } GamePacket& GamePacket::extend(float f) { unsigned char* data = new unsigned char[len_ + 2 + 4]; memcpy(data, this->data_, len_); delete[] this->data_; this->data_ = data; data[len_] = index_; data[len_ + 1] = 0x1; memcpy(data + len_ + 2, &f, 4); len_ += 2 + 4; index_++; data_[60] = static_cast<unsigned char>(index_); return *this; } GamePacket& GamePacket::extend(float f, float f2) { unsigned char* data = new unsigned char[len_ + 2 + 8]; memcpy(data, this->data_, len_); delete[] this->data_; this->data_ = data; data[len_] = index_; data[len_ + 1] = 0x3; memcpy(data + len_ + 2, &f, 4); memcpy(data + len_ + 6, &f2, 4); len_ += 2 + 8; index_++; data_[60] = static_cast<unsigned char>(index_); return *this; } GamePacket& GamePacket::extend(float f, float f2, float f3) { unsigned char* data = new unsigned char[len_ + 2 + 12]; memcpy(data, this->data_, len_); delete[] this->data_; this->data_ = data; data[len_] = index_; data[len_ + 1] = 0x4; memcpy(data + len_ + 2, &f, 4); memcpy(data + len_ + 6, &f2, 4); memcpy(data + len_ + 10, &f3, 4); len_ += 2 + 12; index_++; data_[60] = static_cast<unsigned char>(index_); return *this; } GamePacket& GamePacket::sendData(ENetPeer* peer) { ENetPacket* packet = enet_packet_create(data_, len_, 1); enet_peer_send(peer, 0, packet); return *this; }
25.525
71
0.615736
LinkProfitSG
94f541c491108f4eaf9f02fa2ed97656cd9c91a5
4,997
hpp
C++
src/MultiLayerOptics/src/MultiPaneSpecular.hpp
bakonyidani/Windows-CalcEngine
afa4c4a9f88199c6206af8bc994a073931fc8b91
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/MultiLayerOptics/src/MultiPaneSpecular.hpp
bakonyidani/Windows-CalcEngine
afa4c4a9f88199c6206af8bc994a073931fc8b91
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/MultiLayerOptics/src/MultiPaneSpecular.hpp
bakonyidani/Windows-CalcEngine
afa4c4a9f88199c6206af8bc994a073931fc8b91
[ "BSD-3-Clause-LBNL" ]
null
null
null
#ifndef MultiPaneSpecular_H #define MultiPaneSpecular_H #include <memory> #include <vector> #include "WCECommon.hpp" namespace FenestrationCommon { enum class Side; enum class Property; class CSeries; } // namespace FenestrationCommon namespace SingleLayerOptics { class CSpecularCell; class SpecularLayer; } // namespace SingleLayerOptics namespace MultiLayerOptics { class CEquivalentLayerSingleComponentMW; class CAbsorptancesMultiPane; class CEquivalentLayerSingleComponentMWAngle { public: CEquivalentLayerSingleComponentMWAngle( const std::shared_ptr<CEquivalentLayerSingleComponentMW> & t_Layer, const std::shared_ptr<CAbsorptancesMultiPane> & t_Abs, double t_Angle); double angle() const; std::shared_ptr<CEquivalentLayerSingleComponentMW> layer() const; std::shared_ptr<FenestrationCommon::CSeries> getProperties(FenestrationCommon::Side t_Side, FenestrationCommon::Property t_Property); std::shared_ptr<FenestrationCommon::CSeries> Abs(size_t Index); private: std::shared_ptr<CEquivalentLayerSingleComponentMW> m_Layer; std::shared_ptr<CAbsorptancesMultiPane> m_Abs; double m_Angle; }; // Handles equivalent properties of MultiLayerOptics glass consists only of specular layers class CMultiPaneSpecular { public: CMultiPaneSpecular( std::vector< double > const & t_CommonWavelength, const std::shared_ptr< FenestrationCommon::CSeries > & t_SolarRadiation, SingleLayerOptics::SpecularLayer & t_Layer ); void addLayer( SingleLayerOptics::SpecularLayer & t_Layer ); double getProperty(FenestrationCommon::Side t_Side, FenestrationCommon::Property t_Property, double t_Angle, double minLambda, double maxLambda, FenestrationCommon::IntegrationType t_IntegrationType = FenestrationCommon::IntegrationType::Trapezoidal, double normalizationCoefficient = 1); double getHemisphericalProperty(FenestrationCommon::Side t_Side, FenestrationCommon::Property t_Property, const std::shared_ptr<const std::vector<double>> & t_Angles, double minLambda, double maxLambda, FenestrationCommon::IntegrationType t_IntegrationType = FenestrationCommon::IntegrationType::Trapezoidal, double normalizationCoefficient = 1); // Absorptances of each layer based on angle of incidence double Abs(size_t Index, double t_Angle, double minLambda, double maxLambda, FenestrationCommon::IntegrationType t_IntegrationType = FenestrationCommon::IntegrationType::Trapezoidal, double normalizationCoefficient = 1); // Hemispherical absorptances of each layer. Integration is performed over t_Angles. double AbsHemispherical(size_t Index, const std::shared_ptr<const std::vector<double>> & t_Angles, double minLambda, double maxLambda, FenestrationCommon::IntegrationType t_IntegrationType = FenestrationCommon::IntegrationType::Trapezoidal, double normalizationCoefficient = 1); private: // Get correct angular object out of array and if object does not exists, then it just // creates new one and stores it into array std::shared_ptr<CEquivalentLayerSingleComponentMWAngle> getAngular(double t_Angle); // creates equivalent layer properties for certain angle std::shared_ptr<CEquivalentLayerSingleComponentMWAngle> createNewAngular(double t_Angle); // Contains all specular layers (cells) that are added to the model. This way program will // be able to recalculate equivalent properties for any angle std::vector<SingleLayerOptics::SpecularLayer> m_Layers; std::vector<double> m_CommonWavelengths; std::shared_ptr<FenestrationCommon::CSeries> m_SolarRadiation; // Results for angle-properties std::pair. If same angle is required twice, then model will // not calculate it twice. First it will search for results here and if results are not // available, then it will perform calculation for given angle std::vector<std::shared_ptr<CEquivalentLayerSingleComponentMWAngle>> m_EquivalentAngle; }; } // namespace MultiLayerOptics #endif
40.626016
99
0.634981
bakonyidani
94fa986787378cf10f900dae5321385b0539cb3d
1,041
cpp
C++
sources/Dwarf/AST/AstVariableReference.cpp
KonstantinTomashevich/dwarf-scripting-language
1cb7e2719ee66c77172d647f33052358dfe36be3
[ "MIT" ]
null
null
null
sources/Dwarf/AST/AstVariableReference.cpp
KonstantinTomashevich/dwarf-scripting-language
1cb7e2719ee66c77172d647f33052358dfe36be3
[ "MIT" ]
null
null
null
sources/Dwarf/AST/AstVariableReference.cpp
KonstantinTomashevich/dwarf-scripting-language
1cb7e2719ee66c77172d647f33052358dfe36be3
[ "MIT" ]
null
null
null
#include "AstVariableReference.hpp" #include <assert.h> namespace Dwarf { AstVariableReference::AstVariableReference (std::string name, AstValue *provider) : name_ (name), provider_ (provider) { assert (!name_.empty ()); } AstVariableReference::~AstVariableReference () { delete provider_; } std::string AstVariableReference::GetName () { return name_; } AstValue *AstVariableReference::GetProvider () { return provider_; } std::string AstVariableReference::ToString (int addSpacesIndentation) { std::string result; std::string indent = ""; if (addSpacesIndentation > 0) for (int index = 0; index < addSpacesIndentation; index++) indent += " "; result += indent + "[variable reference "; result += name_; if (provider_) { result += "\n" + indent + "provider:\n"; result += provider_->ToString (addSpacesIndentation + 4) + "\n"; result += indent + "end of variable reference]"; } else result += "]"; return result; } }
20.82
83
0.634006
KonstantinTomashevich
a20200110301e45c9d28f9183090dd41f4768738
119
cpp
C++
Source/DreamPlace/DreamPlaceGameStateBase.cpp
YuanweiZHANG/DreamPlace
b005c22e2353e674a0596c078083b82efe9ae733
[ "MIT" ]
null
null
null
Source/DreamPlace/DreamPlaceGameStateBase.cpp
YuanweiZHANG/DreamPlace
b005c22e2353e674a0596c078083b82efe9ae733
[ "MIT" ]
null
null
null
Source/DreamPlace/DreamPlaceGameStateBase.cpp
YuanweiZHANG/DreamPlace
b005c22e2353e674a0596c078083b82efe9ae733
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "DreamPlaceGameStateBase.h"
19.833333
78
0.789916
YuanweiZHANG
a20a1bae04eb55f7b54548c42c85340c822f7f2c
2,157
cpp
C++
Algorithm/0401 (Easy)Binary Watch/Brute-Force.cpp
ZexinLi0w0/LeetCode
cf3988620ccdcc3d54b9beafd04c517c96f01bb9
[ "MIT" ]
1
2020-12-03T10:10:15.000Z
2020-12-03T10:10:15.000Z
Algorithm/0401 (Easy)Binary Watch/Brute-Force.cpp
ZexinLi0w0/LeetCode
cf3988620ccdcc3d54b9beafd04c517c96f01bb9
[ "MIT" ]
null
null
null
Algorithm/0401 (Easy)Binary Watch/Brute-Force.cpp
ZexinLi0w0/LeetCode
cf3988620ccdcc3d54b9beafd04c517c96f01bb9
[ "MIT" ]
null
null
null
class Solution { void generateNumbers(int bits, long temp_num, set<long>& numbers){ if (bits == 0){ numbers.insert(temp_num); return; } // If we have bits available, out of all 10 available bits, we need to do the follwoing: // For all bits (from 0 to 1 << 9) // Check if the bit is already set in the temporary number. // If the bit is set, do nothing, move to the other bit. // If the bit is not set, mark it as set in the temporary number, decrease the number of available bits // And call the method recursively. for (int i = 0; i < 10; ++ i){ int temp_mask = (1 << i); if (temp_num & temp_mask){ continue; // The bit is set. } int tmp = temp_num; temp_num |= temp_mask; generateNumbers(bits - 1, temp_num, numbers); temp_num = tmp; } } // Bitmask for minutes: 0000111111b = 15 + 16 + 32 = 59 = 0x3F // Bitmask for hours: 1111000000 = 0x3C0 vector<string> extractHoursAndMinutes(set<long>& numbers){ vector<string> res; // We know that the hours are the first 4 bits and the minutes are the last 6 bits. for (const auto& elem : numbers){ int minutes = elem & 0x003F; int hours = (elem & 0x03C0) >> 6; if (minutes > 59 || hours > 11){ continue; } string string_hour = to_string(hours); string string_minute = to_string(minutes); if (string_minute.size() == 1){ string_minute = "0" + string_minute; } res.push_back(string_hour + ":" + string_minute); } return res; } public: vector<string> readBinaryWatch(int num) { set<long> all_numbers; generateNumbers(num, 0, all_numbers); vector<string> result; result = extractHoursAndMinutes(all_numbers); // After we have all numbers, map them to the mask for extracting hours and minutes. return result; } };
36.559322
111
0.545665
ZexinLi0w0
a2125800640f6d634c28e3d9de4de896424ba2d5
22,165
cpp
C++
src/Plugins/RenX/RenX.Core/RenX_LadderDatabase.cpp
Constructive-Tyranny/Jupiter-Bot
2f1261b55b0b420ad2a2cc7aa30118296e0a87d1
[ "0BSD" ]
9
2016-02-04T09:54:24.000Z
2021-11-25T18:56:44.000Z
src/Plugins/RenX/RenX.Core/RenX_LadderDatabase.cpp
Constructive-Tyranny/Jupiter-Bot
2f1261b55b0b420ad2a2cc7aa30118296e0a87d1
[ "0BSD" ]
8
2015-08-04T15:19:53.000Z
2021-11-18T19:39:05.000Z
src/Plugins/RenX/RenX.Core/RenX_LadderDatabase.cpp
JustinAJ/Jupiter-Bot
2f1261b55b0b420ad2a2cc7aa30118296e0a87d1
[ "0BSD" ]
15
2016-08-22T13:04:25.000Z
2022-02-18T16:19:00.000Z
/** * Copyright (C) 2015-2021 Jessica James. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Written by Jessica James <[email protected]> */ #include <iostream> #include "jessilib/unicode.hpp" #include "Jupiter/DataBuffer.h" #include "RenX_LadderDatabase.h" #include "RenX_Server.h" #include "RenX_PlayerInfo.h" #include "RenX_BanDatabase.h" RenX::LadderDatabase *RenX::default_ladder_database = nullptr; std::vector<RenX::LadderDatabase*> g_ladder_databases; std::vector<RenX::LadderDatabase*>& RenX::ladder_databases = g_ladder_databases; RenX::LadderDatabase::LadderDatabase() { g_ladder_databases.push_back(this); if (RenX::default_ladder_database == nullptr) { RenX::default_ladder_database = this; } } RenX::LadderDatabase::LadderDatabase(std::string_view in_name) : LadderDatabase() { RenX::LadderDatabase::setName(in_name); } RenX::LadderDatabase::~LadderDatabase() { while (m_head != nullptr) { m_end = m_head; m_head = m_head->next; delete m_end; } for (auto itr = g_ladder_databases.begin(); itr != g_ladder_databases.end(); ++itr) { if (*itr == this) { g_ladder_databases.erase(itr); break; } } if (RenX::default_ladder_database == this) { if (g_ladder_databases.empty()) { RenX::default_ladder_database = nullptr; } else { RenX::default_ladder_database = g_ladder_databases[0]; } } } void RenX::LadderDatabase::process_data(Jupiter::DataBuffer &buffer, FILE *file, fpos_t pos) { Entry *entry = new Entry(); // read data from buffer to entry entry->steam_id = buffer.pop<uint64_t>(); entry->total_score = buffer.pop<uint64_t>(); entry->total_kills = buffer.pop<uint32_t>(); entry->total_deaths = buffer.pop<uint32_t>(); entry->total_headshot_kills = buffer.pop<uint32_t>(); entry->total_vehicle_kills = buffer.pop<uint32_t>(); entry->total_building_kills = buffer.pop<uint32_t>(); entry->total_defence_kills = buffer.pop<uint32_t>(); entry->total_captures = buffer.pop<uint32_t>(); entry->total_game_time = buffer.pop<uint32_t>(); entry->total_games = buffer.pop<uint32_t>(); if (m_read_version == 0) { entry->total_gdi_games = buffer.pop<uint32_t>(); entry->total_nod_games = buffer.pop<uint32_t>(); } entry->total_wins = buffer.pop<uint32_t>(); if (m_read_version == 0) { entry->total_gdi_wins = buffer.pop<uint32_t>(); entry->total_nod_wins = buffer.pop<uint32_t>(); } entry->total_beacon_placements = buffer.pop<uint32_t>(); entry->total_beacon_disarms = buffer.pop<uint32_t>(); entry->total_proxy_placements = buffer.pop<uint32_t>(); entry->total_proxy_disarms = buffer.pop<uint32_t>(); if (m_read_version > 0) { entry->total_gdi_games = buffer.pop<uint32_t>(); entry->total_gdi_wins = buffer.pop<uint32_t>(); entry->total_gdi_ties = buffer.pop<uint32_t>(); entry->total_gdi_game_time = buffer.pop<uint32_t>(); entry->total_gdi_score = buffer.pop<uint64_t>(); entry->total_gdi_beacon_placements = buffer.pop<uint32_t>(); entry->total_gdi_beacon_disarms = buffer.pop<uint32_t>(); entry->total_gdi_proxy_placements = buffer.pop<uint32_t>(); entry->total_gdi_proxy_disarms = buffer.pop<uint32_t>(); entry->total_gdi_kills = buffer.pop<uint32_t>(); entry->total_gdi_deaths = buffer.pop<uint32_t>(); entry->total_gdi_vehicle_kills = buffer.pop<uint32_t>(); entry->total_gdi_defence_kills = buffer.pop<uint32_t>(); entry->total_gdi_building_kills = buffer.pop<uint32_t>(); entry->total_gdi_headshots = buffer.pop<uint32_t>(); entry->total_nod_games = buffer.pop<uint32_t>(); entry->total_nod_wins = buffer.pop<uint32_t>(); entry->total_nod_game_time = buffer.pop<uint32_t>(); entry->total_nod_score = buffer.pop<uint64_t>(); entry->total_nod_beacon_placements = buffer.pop<uint32_t>(); entry->total_nod_beacon_disarms = buffer.pop<uint32_t>(); entry->total_nod_proxy_placements = buffer.pop<uint32_t>(); entry->total_nod_proxy_disarms = buffer.pop<uint32_t>(); entry->total_nod_kills = buffer.pop<uint32_t>(); entry->total_nod_deaths = buffer.pop<uint32_t>(); entry->total_nod_vehicle_kills = buffer.pop<uint32_t>(); entry->total_nod_defence_kills = buffer.pop<uint32_t>(); entry->total_nod_building_kills = buffer.pop<uint32_t>(); entry->total_nod_headshots = buffer.pop<uint32_t>(); } entry->top_score = buffer.pop<uint32_t>(); entry->top_kills = buffer.pop<uint32_t>(); entry->most_deaths = buffer.pop<uint32_t>(); entry->top_headshot_kills = buffer.pop<uint32_t>(); entry->top_vehicle_kills = buffer.pop<uint32_t>(); entry->top_building_kills = buffer.pop<uint32_t>(); entry->top_defence_kills = buffer.pop<uint32_t>(); entry->top_captures = buffer.pop<uint32_t>(); entry->top_game_time = buffer.pop<uint32_t>(); entry->top_beacon_placements = buffer.pop<uint32_t>(); entry->top_beacon_disarms = buffer.pop<uint32_t>(); entry->top_proxy_placements = buffer.pop<uint32_t>(); entry->top_proxy_disarms = buffer.pop<uint32_t>(); entry->most_recent_ip = buffer.pop<uint32_t>(); entry->last_game = buffer.pop<time_t>(); entry->most_recent_name = buffer.pop<std::string>(); // push data to list if (m_head == nullptr) { m_head = entry; m_end = m_head; } else { m_end->next = entry; entry->prev = m_end; m_end = entry; } entry->rank = ++m_entries; } void RenX::LadderDatabase::process_header(FILE *file) { int chr = fgetc(file); if (chr != EOF) { m_read_version = chr; } } void RenX::LadderDatabase::create_header(FILE *file) { fputc(m_write_version, file); } void RenX::LadderDatabase::process_file_finish(FILE *file) { if (m_read_version != m_write_version) { std::cout << "Notice: Ladder database is out of date; upgrading..." << std::endl; std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now(); write(this->getFilename()); std::chrono::steady_clock::duration write_duration = std::chrono::steady_clock::now() - start_time; // This does not seem anything close to correct... double time_taken = static_cast<double>(write_duration.count()) * (static_cast<double>(std::chrono::steady_clock::duration::period::num) / static_cast<double>(std::chrono::steady_clock::duration::period::den) * static_cast<double>(std::chrono::seconds::duration::period::den / std::chrono::seconds::duration::period::num)); std::cout << "Ladder database upgrade completed in " << time_taken << " seconds" << std::endl; m_read_version = m_write_version; } } RenX::LadderDatabase::Entry *RenX::LadderDatabase::getHead() const { return m_head; } RenX::LadderDatabase::Entry *RenX::LadderDatabase::getPlayerEntry(uint64_t steamid) const { for (Entry *itr = m_head; itr != nullptr; itr = itr->next) { if (itr->steam_id == steamid) { return itr; } } return nullptr; } std::pair<RenX::LadderDatabase::Entry *, size_t> RenX::LadderDatabase::getPlayerEntryAndIndex(uint64_t steamid) const { size_t index = 0; for (Entry *itr = m_head; itr != nullptr; itr = itr->next, ++index) { if (itr->steam_id == steamid) { return std::pair<Entry*, size_t>(itr, index); } } return std::pair<Entry*, size_t>(nullptr, SIZE_MAX); } RenX::LadderDatabase::Entry *RenX::LadderDatabase::getPlayerEntryByName(std::string_view name) const { for (Entry *itr = m_head; itr != nullptr; itr = itr->next) { if (jessilib::equalsi(itr->most_recent_name, name)) { return itr; } } return nullptr; } std::pair<RenX::LadderDatabase::Entry *, size_t> RenX::LadderDatabase::getPlayerEntryAndIndexByName(std::string_view name) const { size_t index = 0; for (Entry *itr = m_head; itr != nullptr; itr = itr->next, ++index) { if (jessilib::equalsi(itr->most_recent_name, name)) { return std::pair<Entry*, size_t>(itr, index); } } return std::pair<Entry*, size_t>(nullptr, SIZE_MAX); } RenX::LadderDatabase::Entry *RenX::LadderDatabase::getPlayerEntryByPartName(std::string_view name) const { for (Entry *itr = m_head; itr != nullptr; itr = itr->next) { if (jessilib::findi(itr->most_recent_name, name) != std::string::npos) { return itr; } } return nullptr; } std::pair<RenX::LadderDatabase::Entry *, size_t> RenX::LadderDatabase::getPlayerEntryAndIndexByPartName(std::string_view name) const { size_t index = 0; for (Entry *itr = m_head; itr != nullptr; itr = itr->next, ++index) { if (jessilib::findi(itr->most_recent_name, name) != std::string::npos) { return std::pair<RenX::LadderDatabase::Entry*, size_t>(itr, index); } } return std::pair<Entry *, size_t>(nullptr, SIZE_MAX); } std::forward_list<RenX::LadderDatabase::Entry> RenX::LadderDatabase::getPlayerEntriesByPartName(std::string_view name, size_t max) const { std::forward_list<Entry> list; if (max == 0) { for (Entry *itr = m_head; itr != nullptr; itr = itr->next) { if (jessilib::findi(itr->most_recent_name, name) != std::string::npos) { list.emplace_front(*itr); } } } else { for (Entry* itr = m_head; itr != nullptr; itr = itr->next) { if (jessilib::findi(itr->most_recent_name, name) != std::string::npos) { list.emplace_front(*itr); if (--max == 0) { return list; } } } } return list; } std::forward_list<std::pair<RenX::LadderDatabase::Entry, size_t>> RenX::LadderDatabase::getPlayerEntriesAndIndexByPartName(std::string_view name, size_t max) const { std::forward_list<std::pair<Entry, size_t>> list; size_t index = 0; if (max == 0) { for (Entry *itr = m_head; itr != nullptr; itr = itr->next, ++index) { if (jessilib::findi(itr->most_recent_name, name) != std::string::npos) { list.emplace_front(*itr, index); } } } else { for (Entry* itr = m_head; itr != nullptr; itr = itr->next, ++index) { if (jessilib::findi(itr->most_recent_name, name) != std::string::npos) { list.emplace_front(*itr, index); if (--max) { return list; } } } } return list; } RenX::LadderDatabase::Entry *RenX::LadderDatabase::getPlayerEntryByIndex(size_t index) const { for (Entry *itr = m_head; itr != nullptr; itr = itr->next, --index) { if (index == 0) { return itr; } } return nullptr; } size_t RenX::LadderDatabase::getEntries() const { return m_entries; } std::chrono::steady_clock::time_point RenX::LadderDatabase::getLastSortTime() const { return m_last_sort; } void RenX::LadderDatabase::append(Entry *entry) { ++m_entries; if (m_head == nullptr) { m_head = entry; m_end = m_head; return; } m_end->next = entry; entry->prev = m_end; m_end = entry; } void RenX::LadderDatabase::write(const std::string &filename) { return write(filename.c_str()); } void RenX::LadderDatabase::write(const char *filename) { if (m_entries != 0) { FILE *file = fopen(filename, "wb"); if (file != nullptr) { size_t rank = 0; Jupiter::DataBuffer buffer; create_header(file); Entry *entry = m_head; while (entry != nullptr) { // update rank entry->rank = ++rank; // push data from entry to buffer buffer.push(entry->steam_id); buffer.push(entry->total_score); buffer.push(entry->total_kills); buffer.push(entry->total_deaths); buffer.push(entry->total_headshot_kills); buffer.push(entry->total_vehicle_kills); buffer.push(entry->total_building_kills); buffer.push(entry->total_defence_kills); buffer.push(entry->total_captures); buffer.push(entry->total_game_time); buffer.push(entry->total_games); buffer.push(entry->total_wins); buffer.push(entry->total_beacon_placements); buffer.push(entry->total_beacon_disarms); buffer.push(entry->total_proxy_placements); buffer.push(entry->total_proxy_disarms); buffer.push(entry->total_gdi_games); buffer.push(entry->total_gdi_wins); buffer.push(entry->total_gdi_ties); buffer.push(entry->total_gdi_game_time); buffer.push(entry->total_gdi_score); buffer.push(entry->total_gdi_beacon_placements); buffer.push(entry->total_gdi_beacon_disarms); buffer.push(entry->total_gdi_proxy_placements); buffer.push(entry->total_gdi_proxy_disarms); buffer.push(entry->total_gdi_kills); buffer.push(entry->total_gdi_deaths); buffer.push(entry->total_gdi_vehicle_kills); buffer.push(entry->total_gdi_defence_kills); buffer.push(entry->total_gdi_building_kills); buffer.push(entry->total_gdi_headshots); buffer.push(entry->total_nod_games); buffer.push(entry->total_nod_wins); buffer.push(entry->total_nod_game_time); buffer.push(entry->total_nod_score); buffer.push(entry->total_nod_beacon_placements); buffer.push(entry->total_nod_beacon_disarms); buffer.push(entry->total_nod_proxy_placements); buffer.push(entry->total_nod_proxy_disarms); buffer.push(entry->total_nod_kills); buffer.push(entry->total_nod_deaths); buffer.push(entry->total_nod_vehicle_kills); buffer.push(entry->total_nod_defence_kills); buffer.push(entry->total_nod_building_kills); buffer.push(entry->total_nod_headshots); buffer.push(entry->top_score); buffer.push(entry->top_kills); buffer.push(entry->most_deaths); buffer.push(entry->top_headshot_kills); buffer.push(entry->top_vehicle_kills); buffer.push(entry->top_building_kills); buffer.push(entry->top_defence_kills); buffer.push(entry->top_captures); buffer.push(entry->top_game_time); buffer.push(entry->top_beacon_placements); buffer.push(entry->top_beacon_disarms); buffer.push(entry->top_proxy_placements); buffer.push(entry->top_proxy_disarms); buffer.push(entry->most_recent_ip); buffer.push(entry->last_game); buffer.push(entry->most_recent_name); // push buffer to file buffer.push_to(file); // iterate entry = entry->next; } fclose(file); } } } void RenX::LadderDatabase::sort_entries() { if (m_entries <= 1) { return; } Entry *itr = m_head; Entry *itr2, *ptr; // iterate forward (search for out-of-order content) while (itr->next != nullptr) { // out-of-order content found if (itr->next->total_score > itr->total_score) { // pull content out ptr = itr->next; itr->next = ptr->next; if (itr->next != nullptr) { itr->next->prev = itr; } // iterate backwards from our iterator, and insert itr2 = itr; while (true) { if (itr2->prev == nullptr) { // push ptr to head ptr->next = itr2; ptr->prev = nullptr; itr2->prev = ptr; m_head = ptr; break; } itr2 = itr2->prev; if (itr2->total_score > ptr->total_score) { // insert ptr after itr2 ptr->next = itr2->next; ptr->next->prev = ptr; ptr->prev = itr2; itr2->next = ptr; break; } } } else { // continue iterating itr = itr->next; } } m_end = itr; m_last_sort = std::chrono::steady_clock::now(); } void RenX::LadderDatabase::updateLadder(RenX::Server &server, const RenX::TeamType &team) { if (server.players.size() != server.getBotCount()) { // call the PreUpdateLadder event if (this->OnPreUpdateLadder != nullptr) { this->OnPreUpdateLadder(*this, server, team); } // update player stats in memory Entry *entry; for (auto player = server.players.begin(); player != server.players.end(); ++player) { if (player->steamid != 0 && (player->ban_flags & RenX::BanDatabase::Entry::FLAG_TYPE_LADDER) == 0) { entry = getPlayerEntry(player->steamid); if (entry == nullptr) { entry = new Entry(); append(entry); entry->steam_id = player->steamid; } entry->total_score += static_cast<uint64_t>(player->score); entry->total_kills += player->kills; entry->total_deaths += player->deaths; entry->total_headshot_kills += player->headshots; entry->total_vehicle_kills += player->vehicleKills; entry->total_building_kills += player->buildingKills; entry->total_defence_kills += player->defenceKills; entry->total_captures += player->captures; entry->total_game_time += static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::seconds>(server.getGameTime(*player)).count()); entry->total_beacon_placements += player->beaconPlacements; entry->total_beacon_disarms += player->beaconDisarms; entry->total_proxy_placements += player->proxy_placements; entry->total_proxy_disarms += player->proxy_disarms; ++entry->total_games; switch (player->team) { case RenX::TeamType::GDI: ++entry->total_gdi_games; if (player->team == team) ++entry->total_wins, ++entry->total_gdi_wins; else if (team == RenX::TeamType::None) ++entry->total_gdi_ties; entry->total_gdi_game_time += static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::seconds>(server.getGameTime(*player)).count()); entry->total_gdi_score += static_cast<uint64_t>(player->score); entry->total_gdi_beacon_placements += player->beaconPlacements; entry->total_gdi_beacon_disarms += player->beaconDisarms; entry->total_gdi_proxy_placements += player->proxy_placements; entry->total_gdi_proxy_disarms += player->proxy_disarms; entry->total_gdi_kills += player->kills; entry->total_gdi_deaths += player->deaths; entry->total_gdi_vehicle_kills += player->vehicleKills; entry->total_gdi_defence_kills += player->defenceKills; entry->total_gdi_building_kills += player->buildingKills; entry->total_gdi_headshots += player->headshots; break; case RenX::TeamType::Nod: ++entry->total_nod_games; if (player->team == team) ++entry->total_wins, ++entry->total_nod_wins; else if (team == RenX::TeamType::None) ++entry->total_nod_ties; entry->total_nod_game_time += static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::seconds>(server.getGameTime(*player)).count()); entry->total_nod_score += static_cast<uint64_t>(player->score); entry->total_nod_beacon_placements += player->beaconPlacements; entry->total_nod_beacon_disarms += player->beaconDisarms; entry->total_nod_proxy_placements += player->proxy_placements; entry->total_nod_proxy_disarms += player->proxy_disarms; entry->total_nod_kills += player->kills; entry->total_nod_deaths += player->deaths; entry->total_nod_vehicle_kills += player->vehicleKills; entry->total_nod_defence_kills += player->defenceKills; entry->total_nod_building_kills += player->buildingKills; entry->total_nod_headshots += player->headshots; break; default: if (player->team == team) ++entry->total_wins; break; } auto set_if_greater = [](uint32_t &src, const uint32_t &cmp) { if (cmp > src) { src = cmp; } }; set_if_greater(entry->top_score, static_cast<uint32_t>(player->score)); set_if_greater(entry->top_kills, player->kills); set_if_greater(entry->most_deaths, player->deaths); set_if_greater(entry->top_headshot_kills, player->headshots); set_if_greater(entry->top_vehicle_kills, player->vehicleKills); set_if_greater(entry->top_building_kills, player->buildingKills); set_if_greater(entry->top_defence_kills, player->defenceKills); set_if_greater(entry->top_captures, player->captures); set_if_greater(entry->top_game_time, static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::seconds>(server.getGameTime(*player)).count())); set_if_greater(entry->top_beacon_placements, player->beaconPlacements); set_if_greater(entry->top_beacon_disarms, player->beaconDisarms); set_if_greater(entry->top_proxy_placements, player->proxy_placements); set_if_greater(entry->top_proxy_disarms, player->proxy_disarms); entry->most_recent_ip = player->ip32; entry->last_game = time(nullptr); entry->most_recent_name = player->name; } } // sort new stats std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now(); sort_entries(); std::chrono::steady_clock::duration sort_duration = std::chrono::steady_clock::now() - start_time; // write new stats start_time = std::chrono::steady_clock::now(); write(this->getFilename()); std::chrono::steady_clock::duration write_duration = std::chrono::steady_clock::now() - start_time; if (m_output_times) { std::string str = string_printf("Ladder: %zu entries sorted in %f seconds; Database written in %f seconds." ENDL, getEntries(), static_cast<double>(sort_duration.count()) * (static_cast<double>(std::chrono::steady_clock::duration::period::num) / static_cast<double>(std::chrono::steady_clock::duration::period::den) * static_cast<double>(std::chrono::seconds::duration::period::den / std::chrono::seconds::duration::period::num)), static_cast<double>(write_duration.count()) * (static_cast<double>(std::chrono::steady_clock::duration::period::num) / static_cast<double>(std::chrono::steady_clock::duration::period::den) * static_cast<double>(std::chrono::seconds::duration::period::den / std::chrono::seconds::duration::period::num))); std::cout << str << std::endl; server.sendLogChan(str); } } } void RenX::LadderDatabase::erase() { if (m_head != nullptr) { m_entries = 0; while (m_head->next != nullptr) { m_head = m_head->next; delete m_head->prev; } delete m_head; m_head = nullptr; m_end = nullptr; } } std::string_view RenX::LadderDatabase::getName() const { return m_name; } void RenX::LadderDatabase::setName(std::string_view in_name) { m_name = in_name; } bool RenX::LadderDatabase::getOutputTimes() const { return m_output_times; } void RenX::LadderDatabase::setOutputTimes(bool in_output_times) { m_output_times = in_output_times; }
34.741379
325
0.70467
Constructive-Tyranny
a219274fdbaeb5d5349d0e396011930fd1ae8130
10,875
hpp
C++
include/System/Net/HttpWebResponse.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Net/HttpWebResponse.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Net/HttpWebResponse.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Net.WebResponse #include "System/Net/WebResponse.hpp" // Including type: System.Net.HttpStatusCode #include "System/Net/HttpStatusCode.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Uri class Uri; // Forward declaring type: Version class Version; } // Forward declaring namespace: System::Net namespace System::Net { // Forward declaring type: WebHeaderCollection class WebHeaderCollection; // Forward declaring type: CookieCollection class CookieCollection; // Forward declaring type: CookieContainer class CookieContainer; // Forward declaring type: WebConnectionData class WebConnectionData; } // Forward declaring namespace: System::IO namespace System::IO { // Forward declaring type: Stream class Stream; } // Forward declaring namespace: System::Runtime::Serialization namespace System::Runtime::Serialization { // Forward declaring type: SerializationInfo class SerializationInfo; } // Completed forward declares // Type namespace: System.Net namespace System::Net { // Size: 0x78 #pragma pack(push, 1) // Autogenerated type: System.Net.HttpWebResponse class HttpWebResponse : public System::Net::WebResponse { public: // private System.Uri uri // Size: 0x8 // Offset: 0x18 System::Uri* uri; // Field size check static_assert(sizeof(System::Uri*) == 0x8); // private System.Net.WebHeaderCollection webHeaders // Size: 0x8 // Offset: 0x20 System::Net::WebHeaderCollection* webHeaders; // Field size check static_assert(sizeof(System::Net::WebHeaderCollection*) == 0x8); // private System.Net.CookieCollection cookieCollection // Size: 0x8 // Offset: 0x28 System::Net::CookieCollection* cookieCollection; // Field size check static_assert(sizeof(System::Net::CookieCollection*) == 0x8); // private System.String method // Size: 0x8 // Offset: 0x30 ::Il2CppString* method; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // private System.Version version // Size: 0x8 // Offset: 0x38 System::Version* version; // Field size check static_assert(sizeof(System::Version*) == 0x8); // private System.Net.HttpStatusCode statusCode // Size: 0x4 // Offset: 0x40 System::Net::HttpStatusCode statusCode; // Field size check static_assert(sizeof(System::Net::HttpStatusCode) == 0x4); // Padding between fields: statusCode and: statusDescription char __padding5[0x4] = {}; // private System.String statusDescription // Size: 0x8 // Offset: 0x48 ::Il2CppString* statusDescription; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // private System.Int64 contentLength // Size: 0x8 // Offset: 0x50 int64_t contentLength; // Field size check static_assert(sizeof(int64_t) == 0x8); // private System.String contentType // Size: 0x8 // Offset: 0x58 ::Il2CppString* contentType; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // private System.Net.CookieContainer cookie_container // Size: 0x8 // Offset: 0x60 System::Net::CookieContainer* cookie_container; // Field size check static_assert(sizeof(System::Net::CookieContainer*) == 0x8); // private System.Boolean disposed // Size: 0x1 // Offset: 0x68 bool disposed; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: disposed and: stream char __padding10[0x7] = {}; // private System.IO.Stream stream // Size: 0x8 // Offset: 0x70 System::IO::Stream* stream; // Field size check static_assert(sizeof(System::IO::Stream*) == 0x8); // Creating value type constructor for type: HttpWebResponse HttpWebResponse(System::Uri* uri_ = {}, System::Net::WebHeaderCollection* webHeaders_ = {}, System::Net::CookieCollection* cookieCollection_ = {}, ::Il2CppString* method_ = {}, System::Version* version_ = {}, System::Net::HttpStatusCode statusCode_ = {}, ::Il2CppString* statusDescription_ = {}, int64_t contentLength_ = {}, ::Il2CppString* contentType_ = {}, System::Net::CookieContainer* cookie_container_ = {}, bool disposed_ = {}, System::IO::Stream* stream_ = {}) noexcept : uri{uri_}, webHeaders{webHeaders_}, cookieCollection{cookieCollection_}, method{method_}, version{version_}, statusCode{statusCode_}, statusDescription{statusDescription_}, contentLength{contentLength_}, contentType{contentType_}, cookie_container{cookie_container_}, disposed{disposed_}, stream{stream_} {} // Deleting conversion operator: operator ::Il2CppObject* constexpr operator ::Il2CppObject*() const noexcept = delete; // System.Void .ctor(System.Uri uri, System.String method, System.Net.WebConnectionData data, System.Net.CookieContainer container) // Offset: 0x163F94C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static HttpWebResponse* New_ctor(System::Uri* uri, ::Il2CppString* method, System::Net::WebConnectionData* data, System::Net::CookieContainer* container) { static auto ___internal__logger = ::Logger::get().WithContext("System::Net::HttpWebResponse::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<HttpWebResponse*, creationType>(uri, method, data, container))); } // public System.Net.HttpStatusCode get_StatusCode() // Offset: 0x1641068 System::Net::HttpStatusCode get_StatusCode(); // public System.String get_StatusDescription() // Offset: 0x1641070 ::Il2CppString* get_StatusDescription(); // System.Void ReadAll() // Offset: 0x163EE54 void ReadAll(); // private System.Void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) // Offset: 0x1641134 void System_Runtime_Serialization_ISerializable_GetObjectData(System::Runtime::Serialization::SerializationInfo* serializationInfo, System::Runtime::Serialization::StreamingContext streamingContext); // private System.Void System.IDisposable.Dispose() // Offset: 0x16412B4 void System_IDisposable_Dispose(); // private System.Void CheckDisposed() // Offset: 0x1640FBC void CheckDisposed(); // private System.Void FillCookies() // Offset: 0x1640AF8 void FillCookies(); // protected System.Void .ctor(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) // Offset: 0x1640D10 // Implemented from: System.Net.WebResponse // Base method: System.Void WebResponse::.ctor(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static HttpWebResponse* New_ctor(System::Runtime::Serialization::SerializationInfo* serializationInfo, System::Runtime::Serialization::StreamingContext streamingContext) { static auto ___internal__logger = ::Logger::get().WithContext("System::Net::HttpWebResponse::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<HttpWebResponse*, creationType>(serializationInfo, streamingContext))); } // public override System.Net.WebHeaderCollection get_Headers() // Offset: 0x1640F90 // Implemented from: System.Net.WebResponse // Base method: System.Net.WebHeaderCollection WebResponse::get_Headers() System::Net::WebHeaderCollection* get_Headers(); // public override System.Uri get_ResponseUri() // Offset: 0x1640F98 // Implemented from: System.Net.WebResponse // Base method: System.Uri WebResponse::get_ResponseUri() System::Uri* get_ResponseUri(); // public override System.IO.Stream GetResponseStream() // Offset: 0x1641094 // Implemented from: System.Net.WebResponse // Base method: System.IO.Stream WebResponse::GetResponseStream() System::IO::Stream* GetResponseStream(); // protected override System.Void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) // Offset: 0x1641140 // Implemented from: System.Net.WebResponse // Base method: System.Void WebResponse::GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) void GetObjectData(System::Runtime::Serialization::SerializationInfo* serializationInfo, System::Runtime::Serialization::StreamingContext streamingContext); // public override System.Void Close() // Offset: 0x1641290 // Implemented from: System.Net.WebResponse // Base method: System.Void WebResponse::Close() void Close(); // protected override System.Void Dispose(System.Boolean disposing) // Offset: 0x16412C4 // Implemented from: System.Net.WebResponse // Base method: System.Void WebResponse::Dispose(System.Boolean disposing) void Dispose(bool disposing); // public System.Void .ctor() // Offset: 0x16412D8 // Implemented from: System.Net.WebResponse // Base method: System.Void WebResponse::.ctor() // Base method: System.Void MarshalByRefObject::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static HttpWebResponse* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("System::Net::HttpWebResponse::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<HttpWebResponse*, creationType>())); } }; // System.Net.HttpWebResponse #pragma pack(pop) static check_size<sizeof(HttpWebResponse), 112 + sizeof(System::IO::Stream*)> __System_Net_HttpWebResponseSizeCheck; static_assert(sizeof(HttpWebResponse) == 0x78); } DEFINE_IL2CPP_ARG_TYPE(System::Net::HttpWebResponse*, "System.Net", "HttpWebResponse");
50.115207
792
0.713379
darknight1050
b8cce46fa44b9e0520c7c6b9d38e8ec00dae1f9b
5,678
cpp
C++
coreLibrary_200/source/core/dgSPDMatrix.cpp
rastullahs-lockenpracht/newton
99b82478f3de9ee7c8d17c8ebefe62e46283d857
[ "Zlib" ]
null
null
null
coreLibrary_200/source/core/dgSPDMatrix.cpp
rastullahs-lockenpracht/newton
99b82478f3de9ee7c8d17c8ebefe62e46283d857
[ "Zlib" ]
null
null
null
coreLibrary_200/source/core/dgSPDMatrix.cpp
rastullahs-lockenpracht/newton
99b82478f3de9ee7c8d17c8ebefe62e46283d857
[ "Zlib" ]
null
null
null
/* Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #include "dgStdafx.h" #include "dgMemory.h" #include "dgSPDMatrix.h" //static bool CholeskyDecomposition (dgFloat32 **rowPointers, dgInt32 size); //static void BackAndForwardSustitition (dgFloat32 **rowPointers, dgInt32 size, dgFloat32 *rightsideVector); /* bool _CholeskyDecomposition ( void *rowPointers, dgInt32 rowStrideInBytes, dgInt32 typeSizeInBytes, dgInt32 size) { dgUnsigned8 *rowArray; rowArray = (dgUnsigned8*)rowPointers; if (typeSizeInBytes == sizeof (dgFloat32)) { dgInt32 i; dgFloat32 **rows; rows = (dgFloat32**) dgStackAlloc (size * sizeof (dgFloat32*)); for (i = 0; i < size; i ++) { rows[i] = *((dgFloat32 **)rowArray); rowArray += rowStrideInBytes; } return CholeskyDecomposition (rows, size); } else { _ASSERTE (0); _ASSERTE (typeSizeInBytes == sizeof (dgFloat64)); } return true; } */ /* void _BackAndForwardSustitition ( void *rightsideVector, void *rowPointers, dgInt32 rowStrideInBytes, dgInt32 typeSizeInBytes, dgInt32 size) { dgUnsigned8 *rowArray; rowArray = (dgUnsigned8*)rowPointers; if (typeSizeInBytes == sizeof (dgFloat32)) { dgInt32 i; dgFloat32 **rows; rows = (dgFloat32**) dgStackAlloc (size * sizeof (dgFloat32*)); for (i = 0; i < size; i ++) { rows[i] = *((dgFloat32 **)rowArray); rowArray += rowStrideInBytes; } BackAndForwardSustitition (rows, size, (dgFloat32*)rightsideVector); } else { _ASSERTE (0); _ASSERTE (typeSizeInBytes == sizeof (dgFloat64)); } } */ /* bool _SolveByCholeskyDecomposition ( void *rightsideVector, void *rowPointers, dgInt32 rowStrideInBytes, dgInt32 typeSizeInBytes, dgInt32 size) { dgUnsigned8 *rowArray; rowArray = (dgUnsigned8*)rowPointers; if (typeSizeInBytes == sizeof (dgFloat32)) { dgInt32 i; dgFloat32 **rows; rows = (dgFloat32**) dgStackAlloc (size * sizeof (dgFloat32*)); for (i = 0; i < size; i ++) { rows[i] = *((dgFloat32 **)rowArray); rowArray += rowStrideInBytes; } if (CholeskyDecomposition (rows, size)) { BackAndForwardSustitition (rows, size, (dgFloat32*)rightsideVector); return true; } } else { _ASSERTE (0); _ASSERTE (typeSizeInBytes == sizeof (dgFloat64)); } return false; } */ /* void BackAndForwardSustitition ( dgFloat32 **rows, dgInt32 size, dgFloat32 *B) { dgInt32 i; dgInt32 j; dgFloat32 acc; //dgSPDMatrix<dgFloat32> M (8); //M.CholeskyDecomposition(); #ifdef DG_COUNT_FLOAT_OPS dgInt32 memCount; dgInt32 floatCount; memCount = dgGeneralVector<dgFloat32>::GetMemWrites(); floatCount = dgGeneralVector<dgFloat32>::GetFloatOps(); #endif B[0] = B[0] / rows[0][0]; for (i = 1; i < size; i ++) { acc = 0.0f; for (j = 0; j < i; j ++) { acc = acc + rows[j][i] * B[j]; #ifdef DG_COUNT_FLOAT_OPS floatCount += 2; #endif } B[i] = (B[i] - acc) / rows[i][i]; #ifdef DG_COUNT_FLOAT_OPS floatCount += 2; memCount += 1; #endif } B[size-1] = B[size-1] / rows[size-1][size-1]; for (i = size - 2; i >= 0; i --) { acc = 0.0f; dgFloat32 *row; row = rows[i]; for (j = i + 1; j < size; j ++) { acc = acc + row[j] * B[j]; #ifdef DG_COUNT_FLOAT_OPS floatCount += 2; #endif } B[i] = (B[i] - acc) / rows[i][i]; #ifdef DG_COUNT_FLOAT_OPS floatCount += 2; memCount += 1; #endif } #ifdef DG_COUNT_FLOAT_OPS dgGeneralVector<dgFloat32>::SetMemWrites(memCount); dgGeneralVector<dgFloat32>::SetFloatOps(floatCount); #endif } */ /* bool CholeskyDecomposition (dgFloat32 **rows, dgInt32 size) { dgInt32 i; dgInt32 j; dgInt32 k; dgFloat32 factor; #ifdef DG_COUNT_FLOAT_OPS dgInt32 memCount; dgInt32 floatCount; memCount = dgGeneralVector<dgFloat32>::GetMemWrites(); floatCount = dgGeneralVector<dgFloat32>::GetFloatOps(); #endif for (j = 0; j < size; j++) { for (k = 0; k < j; k ++ ) { factor = rows[k][j]; if (dgAbsf (factor) > 1.0e-6f) { for (i = j; i < size; i ++) { rows[j][i] -= rows[k][i] * factor; #ifdef DG_COUNT_FLOAT_OPS memCount += 1; floatCount += 2; #endif } } } factor = rows[j][j]; if (factor <= 0.0f) { if (factor <= -5.0e-4f) { return false; } factor = 1.0e-12f; } factor = dgSqrt (factor); rows[j][j] = factor; factor = 1.0f / factor; #ifdef DG_COUNT_FLOAT_OPS memCount += 1; floatCount += 1; #endif for (k = j + 1; k < size; k ++) { rows[j][k] *= factor; #ifdef DG_COUNT_FLOAT_OPS memCount += 1; floatCount += 1; #endif } } #ifdef DG_COUNT_FLOAT_OPS dgGeneralVector<dgFloat32>::SetMemWrites(memCount); dgGeneralVector<dgFloat32>::SetFloatOps(floatCount); #endif return true; } */
22.621514
109
0.645826
rastullahs-lockenpracht
b8e1e9bca5c0e939259290bf44c591ad70988091
98
hpp
C++
src/lib/env.hpp
stkw0/i-hate-all-rss-readers
ac2be9f7c6b070aff3b1fe36a9efbcc8095dcafa
[ "Unlicense" ]
null
null
null
src/lib/env.hpp
stkw0/i-hate-all-rss-readers
ac2be9f7c6b070aff3b1fe36a9efbcc8095dcafa
[ "Unlicense" ]
null
null
null
src/lib/env.hpp
stkw0/i-hate-all-rss-readers
ac2be9f7c6b070aff3b1fe36a9efbcc8095dcafa
[ "Unlicense" ]
null
null
null
#pragma once namespace iharr { const std::string getenv(const char* name); } // namespace iharr
14
43
0.72449
stkw0
b8e2de30705ffd800b8f2efea1732467b4eb9ebe
97
cpp
C++
test/Heng-Core-Test/killInit.cpp
fitenne/yamc
26141cb61eff63521cd282389495c8a9b9a1604d
[ "MIT" ]
1
2022-03-27T05:01:04.000Z
2022-03-27T05:01:04.000Z
test/Heng-Core-Test/killInit.cpp
fitenne/yamc
26141cb61eff63521cd282389495c8a9b9a1604d
[ "MIT" ]
null
null
null
test/Heng-Core-Test/killInit.cpp
fitenne/yamc
26141cb61eff63521cd282389495c8a9b9a1604d
[ "MIT" ]
null
null
null
#include <signal.h> int main(void) { kill(1, SIGKILL); kill(3, SIGKILL); return 0; }
12.125
21
0.57732
fitenne
b8e58df180793b9eb2349f9808e8bc9b28e5aa4c
4,511
cpp
C++
RocketPlugin/MeshmoonUser.cpp
Adminotech/meshmoon-plugins
32043ef783bdf137860d7d01eb22de564628e572
[ "Apache-2.0" ]
4
2018-05-09T01:55:14.000Z
2021-12-19T17:46:29.000Z
RocketPlugin/MeshmoonUser.cpp
Adminotech/meshmoon-plugins
32043ef783bdf137860d7d01eb22de564628e572
[ "Apache-2.0" ]
null
null
null
RocketPlugin/MeshmoonUser.cpp
Adminotech/meshmoon-plugins
32043ef783bdf137860d7d01eb22de564628e572
[ "Apache-2.0" ]
2
2016-03-15T06:12:05.000Z
2021-06-06T00:18:38.000Z
/** @author Adminotech Ltd. Copyright Adminotech Ltd. All rights reserved. @file @brief */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "MeshmoonUser.h" #include "CoreDefines.h" #include "LoggingFunctions.h" #include <QTimer> #include "MemoryLeakCheck.h" // RocketUserAuthenticator RocketUserAuthenticator::RocketUserAuthenticator(u32 _connectionId) : connectionId(_connectionId) { } void RocketUserAuthenticator::EmitCompleted(Meshmoon::PermissionLevel permissionLevel) { emit Completed(static_cast<int>(permissionLevel), PermissionLevelToString(permissionLevel)); } // MeshmoonUser MeshmoonUser::MeshmoonUser() : connectionId_(0), levelAcquired_(false), permissionLevel_(Meshmoon::Basic) { } MeshmoonUser::~MeshmoonUser() { Clear(); } void MeshmoonUser::SetClientConnectionId(u32 connectionId) { connectionId_ = connectionId; // If we received auth requests before connection ID was set it is -1. // Set it here to the authenticators so they will emit correctly. foreach(RocketUserAuthenticator *auth, authenticators_) if (auth && auth->connectionId == 0) auth->connectionId = connectionId_; } void MeshmoonUser::Clear() { // Do not reset userData_ as it can be valid for numerous logins! connectionId_ = 0; levelAcquired_ = false; permissionLevel_ = Meshmoon::Basic; foreach(RocketUserAuthenticator *auth, authenticators_) SAFE_DELETE(auth); authenticators_.clear(); } void MeshmoonUser::Process() { if (levelAcquired_ == false) return; for(int i=0; i<authenticators_.size(); ++i) { RocketUserAuthenticator *auth = authenticators_[i]; if (auth && auth->connectionId == connectionId_) { auth->EmitCompleted(permissionLevel_); authenticators_.removeAt(i); SAFE_DELETE(auth); break; } } } void MeshmoonUser::SetPermissionLevel(Meshmoon::PermissionLevel permissionLevel, bool log) { if (log) LogInfo("[MeshmoonUser]: Received scene permission level " + PermissionLevelToString(permissionLevel)); levelAcquired_ = true; permissionLevel_ = permissionLevel; Process(); } QString MeshmoonUser::Name() const { return userData_.name; } QString MeshmoonUser::Hash() const { return QString(userData_.hash); } QString MeshmoonUser::Gender() const { return userData_.gender; } QString MeshmoonUser::ProfilePictureUrl() const { return userData_.pictureUrl.toString(); } QString MeshmoonUser::AvatarAppearanceUrl() const { return userData_.avatarAppearanceUrl.toString(); } QStringList MeshmoonUser::MEPNames() const { QStringList names; foreach(const Meshmoon::MEP &mep, userData_.meps) names << mep.name; return names; } QStringList MeshmoonUser::MEPIds() const { QStringList ids; foreach(const Meshmoon::MEP &mep, userData_.meps) ids << mep.id; return ids; } QString MeshmoonUser::MEPNameById(const QString &id) const { foreach(const Meshmoon::MEP &mep, userData_.meps) if (mep.id.compare(id, Qt::CaseSensitive) == 0) return mep.name; return ""; } u32 MeshmoonUser::ConnectionId() const { return connectionId_; } Meshmoon::PermissionLevel MeshmoonUser::PermissionLevel() const { return permissionLevel_; } QString MeshmoonUser::PermissionLevelString() const { return PermissionLevelToString(permissionLevel_); } int MeshmoonUser::PermissionLevelNumber() const { return static_cast<int>(permissionLevel_); } RocketUserAuthenticator *MeshmoonUser::RequestAuthentication() { // Return a existing authenticator for multiple requests if already initialized. RocketUserAuthenticator *auth = Authenticator(connectionId_); if (!auth) { auth = new RocketUserAuthenticator(connectionId_); authenticators_ << auth; } // If level is known, trigger authenticator after 1msec if (levelAcquired_) QTimer::singleShot(1, this, SLOT(Process())); return auth; } RocketUserAuthenticator *MeshmoonUser::Authenticator(u32 connectionId) const { foreach(RocketUserAuthenticator *auth, authenticators_) if (auth && auth->connectionId == connectionId) return auth; return 0; } void MeshmoonUser::OnAuthenticated(const Meshmoon::User &userData) { userData_ = userData; } void MeshmoonUser::OnAuthReset() { userData_.Reset(); }
22.112745
111
0.699401
Adminotech
b8f4ab9146b4e516c55092b6fd022af7f18bc838
1,482
cpp
C++
src/fsc/object/base/transformer/translate.cpp
nnoell/fsc
19c6e471fa0712c6fe4817b08d3bf8c6ae2b16fb
[ "BSD-3-Clause" ]
1
2018-11-26T19:06:52.000Z
2018-11-26T19:06:52.000Z
src/fsc/object/base/transformer/translate.cpp
nnoell/fsc
19c6e471fa0712c6fe4817b08d3bf8c6ae2b16fb
[ "BSD-3-Clause" ]
null
null
null
src/fsc/object/base/transformer/translate.cpp
nnoell/fsc
19c6e471fa0712c6fe4817b08d3bf8c6ae2b16fb
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------------------------------------------------------------------------------------------- // Copyright : (c) Julian Bouzas 2018 // License : BSD3-style (see LICENSE) // Maintainer : Julian Bouzas - nnoell3[at]gmail.com //---------------------------------------------------------------------------------------------------------------------- // FSC #include "translate.hpp" namespace fsc { namespace object { namespace base { namespace transformer { Translate::Translate(glm::vec3 position) : Transformer("translate"), position_(std::move(position)) { } Translate::~Translate() { } Translate::Translate(const Translate& other) : Transformer(other), position_(other.position_) { } Translate::Translate(Translate&& other) : Transformer(std::move(other)), position_(std::move(other.position_)) { } Translate& Translate::operator=(const Translate& other) { Transformer::operator=(other); position_ = other.position_; return *this; } Translate& Translate::operator=(Translate&& other) { Transformer::operator=(std::move(other)); position_ = std::move(other.position_); return *this; } const glm::vec3& Translate::GetPosition() const { return position_; } glm::mat4 Translate::Transform(const glm::mat4& model) const { return glm::translate(model, position_); } } // namespace transformer } // namespace base } // namespace object } // namespace fsc
26.464286
121
0.562078
nnoell
b8f6913283be1057e744c4d509444281f4870706
1,058
cpp
C++
interpreter/lox/lox/ASTPrinter.cpp
mandyedi/craftinginterpreters-cpp
fd4ec9a61d9a2640d77fd6f5fa3dc3ee23c22d34
[ "MIT" ]
null
null
null
interpreter/lox/lox/ASTPrinter.cpp
mandyedi/craftinginterpreters-cpp
fd4ec9a61d9a2640d77fd6f5fa3dc3ee23c22d34
[ "MIT" ]
null
null
null
interpreter/lox/lox/ASTPrinter.cpp
mandyedi/craftinginterpreters-cpp
fd4ec9a61d9a2640d77fd6f5fa3dc3ee23c22d34
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ASTPrinter.h" void ASTPrinter::Print( Expr *expr ) { expr->Accept( this ); } void ASTPrinter::VisitBinaryExpr( Binary *expr ) { Parenthesize( expr->Op.Lexeme, { expr->Left, expr->Right } ); } void ASTPrinter::VisitGroupingExpr( Grouping *expr ) { Parenthesize( "group", { expr->Expression } ); } void ASTPrinter::VisitLiteralExpr( Literal *expr ) { if ( auto value = std::get_if<Null>(&expr->Value) ) { std::cout << "nil"; } else if ( auto value = std::get_if<double>( &expr->Value ) ) { std::cout << *value; } else if ( auto value = std::get_if<std::string>( &expr->Value ) ) { std::cout << *value; } } void ASTPrinter::VisitUnaryExpr( Unary *expr ) { Parenthesize( expr->Op.Lexeme, { expr->Right } ); } void ASTPrinter::Parenthesize( const std::string &name, const std::vector<Expr *> exprs ) { std::cout << "(" << name; for ( auto *expr : exprs ) { std::cout << " "; expr->Accept( this ); } std::cout << ")"; }
21.591837
89
0.574669
mandyedi
b8f8f3bd897d3adccc6e03765ca7642ec4650c0c
3,862
cpp
C++
443-string-compression/string-compression.cpp
nagestx/MyLeetCode
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
[ "MIT" ]
3
2018-12-15T14:07:12.000Z
2020-07-19T23:18:09.000Z
443-string-compression/string-compression.cpp
yangyangu/MyLeetCode
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
[ "MIT" ]
null
null
null
443-string-compression/string-compression.cpp
yangyangu/MyLeetCode
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
[ "MIT" ]
null
null
null
// Given an array of characters, compress it in-place. // // The length after compression must always be smaller than or equal to the original array. // // Every element of the array should be a character (not int) of length 1. // // After you are done modifying the input array in-place, return the new length of the array. //   // // Follow up: // Could you solve it using only O(1) extra space? //   // // Example 1: // // // Input: // ["a","a","b","b","c","c","c"] // // Output: // Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] // // Explanation: // "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3". // // //   // // Example 2: // // // Input: // ["a"] // // Output: // Return 1, and the first 1 characters of the input array should be: ["a"] // // Explanation: // Nothing is replaced. // // //   // // Example 3: // // // Input: // ["a","b","b","b","b","b","b","b","b","b","b","b","b"] // // Output: // Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]. // // Explanation: // Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12". // Notice each digit has it's own entry in the array. // // //   // // Note: // // // All characters have an ASCII value in [35, 126]. // 1 <= len(chars) <= 1000. // // /* * @lc app=leetcode id=443 lang=cpp * * [443] String Compression * * https://leetcode.com/problems/string-compression/description/ * * algorithms * Easy (36.42%) * Total Accepted: 39.1K * Total Submissions: 107.5K * Testcase Example: '["a","a","b","b","c","c","c"]' * * Given an array of characters, compress it in-place. * * The length after compression must always be smaller than or equal to the * original array. * * Every element of the array should be a character (not int) of length 1. * * After you are done modifying the input array in-place, return the new length * of the array. * * * Follow up: * Could you solve it using only O(1) extra space? * * * Example 1: * * * Input: * ["a","a","b","b","c","c","c"] * * Output: * Return 6, and the first 6 characters of the input array should be: * ["a","2","b","2","c","3"] * * Explanation: * "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by * "c3". * * * * * Example 2: * * * Input: * ["a"] * * Output: * Return 1, and the first 1 characters of the input array should be: ["a"] * * Explanation: * Nothing is replaced. * * * * * Example 3: * * * Input: * ["a","b","b","b","b","b","b","b","b","b","b","b","b"] * * Output: * Return 4, and the first 4 characters of the input array should be: * ["a","b","1","2"]. * * Explanation: * Since the character "a" does not repeat, it is not compressed. * "bbbbbbbbbbbb" is replaced by "b12". * Notice each digit has it's own entry in the array. * * * * * Note: * * * All characters have an ASCII value in [35, 126]. * 1 <= len(chars) <= 1000. * * */ class Solution { public: int compress(vector<char>& chars) { int n = chars.size(); if(n < 2){ return n; } int i = 0, j = 0; while(i < n){ chars[j] = chars[i]; int cnt = 0; while(i < n && chars[i] == chars[j]){ ++ cnt; ++ i; } if(cnt == 1){ ++ j; }else{ string str = to_string(cnt); for(auto c: str){ chars[++ j] = c; } ++ j; } } return j; } };
20.875676
103
0.50492
nagestx
b8f9701d8cfcb7e5ae869cea5a5343fa1facff70
1,481
cpp
C++
shf-cpp/src/Game/Menu/MemoMenu.cpp
Upwinded/SHF
797682152234251c9a32692324904c7aa8d90683
[ "Zlib" ]
71
2018-03-21T08:04:04.000Z
2022-01-11T09:49:26.000Z
shf-cpp/src/Game/Menu/MemoMenu.cpp
Upwinded/SHF
797682152234251c9a32692324904c7aa8d90683
[ "Zlib" ]
2
2018-08-28T08:26:02.000Z
2019-04-06T14:29:39.000Z
shf-cpp/src/Game/Menu/MemoMenu.cpp
Upwinded/SHF
797682152234251c9a32692324904c7aa8d90683
[ "Zlib" ]
25
2018-03-24T03:36:28.000Z
2021-09-20T06:19:09.000Z
#include "MemoMemu.h" #include "../GameManager/GameManager.h" MemoMenu::MemoMenu() { init(); visible = false; } MemoMenu::~MemoMenu() { freeResource(); } void MemoMenu::reFresh() { if (scrollbar != NULL && memoText != NULL) { for (int i = 0; i < MEMO_LINE; i++) { if (position + i < (int)GameManager::getInstance()->memo.memo.size()) { memoText->mstr[i]->setStr(convert::GBKToUnicode(GameManager::getInstance()->memo.memo[i + position])); } else { memoText->mstr[i]->setStr(L""); } } } } void MemoMenu::reset() { scrollbar->setPosition(0); position = scrollbar->position; reFresh(); } void MemoMenu::reRange(int max) { scrollbar->max = max; scrollbar->setPosition(scrollbar->position); position = scrollbar->position; reFresh(); } void MemoMenu::init() { freeResource(); initFromIni("ini\\ui\\memo\\window.ini"); title = addImageContainer("ini\\ui\\memo\\title.ini"); image = addImageContainer("ini\\ui\\memo\\image.ini"); scrollbar = addScrollbar("ini\\ui\\memo\\scrollbar.ini"); memoText = addMemo("ini\\ui\\memo\\memo.ini"); setChildRect(); } void MemoMenu::freeResource() { if (impImage != NULL) { IMP::clearIMPImage(impImage); delete impImage; impImage = NULL; } freeCom(memoText); freeCom(title); freeCom(image); freeCom(scrollbar); } void MemoMenu::onEvent() { if (scrollbar != NULL && memoText != NULL && position != scrollbar->position) { position = scrollbar->position; reFresh(); } }
17.630952
106
0.651587
Upwinded
77013c97ae800b7c22b3e9ed56f79e5122c6bc27
1,445
cpp
C++
Maze_Lib/Color.cpp
martindubois/Maze
23026ee0d437edb7b59f39e07bc0f94c100e506f
[ "Apache-2.0" ]
null
null
null
Maze_Lib/Color.cpp
martindubois/Maze
23026ee0d437edb7b59f39e07bc0f94c100e506f
[ "Apache-2.0" ]
null
null
null
Maze_Lib/Color.cpp
martindubois/Maze
23026ee0d437edb7b59f39e07bc0f94c100e506f
[ "Apache-2.0" ]
null
null
null
// Author KMS - Martin Dubois, P. Eng. // Copyright (C) 2021 KMS // License http://www.apache.org/licenses/LICENSE-2.0 // Product Maze // File Maze_Lib/Color.cpp // CODE REVIEW 2021-12-18 KMS - Martin Dubois, P. Eng. // TEST COVERAGE 2021-12-18 KMS - Martin Dubois, P. Eng. #include "Component.h" // ===== Includes =========================================================== #include <Maze/Color.h> namespace Maze { // Public // ////////////////////////////////////////////////////////////////////// const Color Color::BLACK ( 0, 0, 0); const Color Color::BRICK ( 0, 0, 0); const Color Color::RED (255, 0, 0); const Color Color::TRAIL (255, 255, 255); const Color Color::UNKNOWN(127, 127, 127); Color::Color(uint8_t aR, uint8_t aG, uint8_t aB) { mBGRA[0] = aB; mBGRA[1] = aG; mBGRA[2] = aR; mBGRA[3] = 0; } bool Color::operator == (const Color& aB) const { return ((mBGRA[0] == aB.GetB()) && (mBGRA[1] == aB.GetG()) && (mBGRA[2] == aB.GetR()) && (mBGRA[3] == aB.GetA())); } uint8_t Color::GetA() const { return mBGRA[3]; } uint8_t Color::GetB() const { return mBGRA[0]; } uint8_t Color::GetG() const { return mBGRA[1]; } uint8_t Color::GetR() const { return mBGRA[2]; } void Color::Set(unsigned int aBGR, uint8_t aVal) { assert(3 > aBGR); mBGRA[aBGR] = aVal; } }
26.272727
122
0.504498
martindubois
770ac34cd2aa7c6f561fe07cdc40b36bf830f05a
1,654
cpp
C++
1101-9999/1801. Number of Orders in the Backlog.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
1101-9999/1801. Number of Orders in the Backlog.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
1101-9999/1801. Number of Orders in the Backlog.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
class Solution { public: int getNumberOfBacklogOrders(vector<vector<int>> &orders) { priority_queue<pair<int, int>, vector<pair<int, int>>> buy; priority_queue<pair<int, int>, vector<pair<int, int>>, std::greater<pair<int, int>>> sell; for (auto &order : orders) { // buy if (order[2] == 0) { while (!sell.empty() && sell.top().first <= order[0] && order[1] > 0) { auto top = sell.top(); sell.pop(); if (order[1] >= top.second) { order[1] -= top.second; } else { top.second -= order[1]; order[1] = 0; sell.push(top); } } if (order[1] > 0) { buy.push(make_pair(order[0], order[1])); } // sell } else { while (!buy.empty() && buy.top().first >= order[0] && order[1] > 0) { auto top = buy.top(); buy.pop(); if (order[1] >= top.second) { order[1] -= top.second; } else { top.second -= order[1]; order[1] = 0; buy.push(top); } } if (order[1] > 0) { sell.push(make_pair(order[0], order[1])); } } } long ret = 0; const int mod = 1e9 + 7; while (!sell.empty()) { auto p = sell.top(); sell.pop(); ret += p.second; ret %= mod; } while (!buy.empty()) { auto p = buy.top(); buy.pop(); ret += p.second; ret %= mod; } return ret; } };
21.763158
94
0.403265
erichuang1994
770b566e5a7eeed4d94fbdfd17e7af336c1f12bb
825
cpp
C++
Chroma/src/Chroma/Core/EntryPoint.cpp
ttalexander2/chroma
0e9946e66158938ebd6497d5bf3acfba8fbe9fee
[ "MIT" ]
1
2022-03-07T01:54:59.000Z
2022-03-07T01:54:59.000Z
Chroma/src/Chroma/Core/EntryPoint.cpp
ttalexander2/chroma
0e9946e66158938ebd6497d5bf3acfba8fbe9fee
[ "MIT" ]
20
2021-08-16T16:52:43.000Z
2022-03-26T02:47:09.000Z
Chroma/src/Chroma/Core/EntryPoint.cpp
ttalexander2/chroma
0e9946e66158938ebd6497d5bf3acfba8fbe9fee
[ "MIT" ]
null
null
null
#include "chromapch.h" #include "EntryPoint.h" #include <physfs.h> extern "C" { __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001; } extern "C" { __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; } void InitFilesystem() { PHYSFS_init(NULL); } void DeinitFilesystem() { PHYSFS_deinit(); } /// @brief Application entry point. int main(int argc, char** argv) { Chroma::Log::Init(); InitFilesystem(); CHROMA_PROFILE_BEGIN_SESSION("Startup", "ChromaProfile-Startup.json"); auto app = Chroma::CreateApplication(); CHROMA_PROFILE_END_SESSION(); CHROMA_PROFILE_BEGIN_SESSION("Runtime", "ChromaProfile-Runtime.json"); app->Run(); CHROMA_PROFILE_END_SESSION(); CHROMA_PROFILE_BEGIN_SESSION("Shutdown", "ChromaProfile-Shutdown.json"); delete app; CHROMA_PROFILE_END_SESSION(); }
20.625
73
0.757576
ttalexander2
77273a4a6254e68369f07f611c75460b9ef98541
15,672
cc
C++
Source/Models/expression.cc
AryaFaramarzi/CS220-dmfb-synthesis-skeleton
6b592516025f6c2838f269dcf2ca1696d9de5ab8
[ "MIT" ]
3
2018-11-03T06:17:08.000Z
2020-08-12T05:26:47.000Z
Source/Models/expression.cc
AryaFaramarzi/CS220-dmfb-synthesis-skeleton
6b592516025f6c2838f269dcf2ca1696d9de5ab8
[ "MIT" ]
null
null
null
Source/Models/expression.cc
AryaFaramarzi/CS220-dmfb-synthesis-skeleton
6b592516025f6c2838f269dcf2ca1696d9de5ab8
[ "MIT" ]
6
2019-09-03T23:58:04.000Z
2021-07-09T02:33:47.000Z
/*------------------------------------------------------------------------------* * (c)2016, All Rights Reserved. * * ___ ___ ___ * * /__/\ / /\ / /\ * * \ \:\ / /:/ / /::\ * * \ \:\ / /:/ / /:/\:\ * * ___ \ \:\ / /:/ ___ / /:/~/:/ * * /__/\ \__\:\ /__/:/ / /\ /__/:/ /:/___ UCR DMFB Synthesis Framework * * \ \:\ / /:/ \ \:\ / /:/ \ \:\/:::::/ www.microfluidics.cs.ucr.edu * * \ \:\ /:/ \ \:\ /:/ \ \::/~~~~ * * \ \:\/:/ \ \:\/:/ \ \:\ * * \ \::/ \ \::/ \ \:\ * * \__\/ \__\/ \__\/ * *-----------------------------------------------------------------------------*/ /*---------------------------Implementation Details-----------------------------* * Source: expression.cc * * Original Code Author(s): Dan Grissom * * Original Completion/Release Date: April 1, 2014 * * * * Details: N/A * * * * Revision History: * * WHO WHEN WHAT * * --- ---- ---- * * FML MM/DD/YY One-line description * *-----------------------------------------------------------------------------*/ #include "expression.h" int Expression::next_id = 1; ///////////////////////////////////////////////////////////////////// // Constructors ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // Creating an expression that will be manually created externally. // This method should only be called by the FileIn class when reading // in a CFG from a file. ///////////////////////////////////////////////////////////////////// Expression::Expression(int expId) { // Set ID and increase next_id if necessary id = expId; if (id >= next_id) next_id = id + 1; //operationType = ot; operands = NULL; //operandType = OP_TWO_SENSORS; constant = 0; sensor1 = NULL; sensor2 = NULL; unconditionalParent = NULL; } ///////////////////////////////////////////////////////////////////// // Creating an expression that compares the readings from two sensors. ///////////////////////////////////////////////////////////////////// Expression::Expression(AssayNode *s1, ExOperationType ot, AssayNode *s2) { { // Sanity check: Must be proper operation type if (!(ot == OP_GT || ot == OP_LT || ot == OP_GoE || ot == OP_LoE || ot == OP_EQUAL) || !s1 || !s2) { stringstream msg; msg << "ERRORL. >, <, <=, >=, == operations allowed for a sensor-sensor comparison. Must be valid sensors." << ends; claim(false, &msg); } } id = next_id++; operationType = ot; operands = NULL; operandType = OP_TWO_SENSORS; constant = 0; sensor1 = s1; sensor2 = s2; unconditionalParent = NULL; } ///////////////////////////////////////////////////////////////////// // Creating an expression that compares the reading from a sensor to // a constant value ///////////////////////////////////////////////////////////////////// Expression::Expression(AssayNode *s1, ExOperationType ot, double c) { { // Sanity check: Must be proper operation type if (!(ot == OP_GT || ot == OP_LT || ot == OP_GoE || ot == OP_LoE || ot == OP_EQUAL) || !s1) { stringstream msg; msg << "ERRORL. >, <, <=, >=, == operations allowed for a sensor-sensor comparison. Must be valid sensors." << ends; claim(false, &msg); } } id = next_id++; operationType = ot; operands = NULL; operandType = OP_ONE_SENSOR; constant = c; sensor1 = s1; sensor2 = NULL; unconditionalParent = NULL; } ///////////////////////////////////////////////////////////////////// // Creating an BioExpression that compares the run count of a repeatable // assay (eventually, a DAG) to a static runcount (constant runCount) ///////////////////////////////////////////////////////////////////// Expression::Expression(DAG *repeatableDag, ExOperationType ot, double runCount) { { // Sanity check: Must be proper operation type if (!(ot == OP_GT || ot == OP_LT || ot == OP_GoE || ot == OP_LoE || ot == OP_EQUAL) || !repeatableDag) { stringstream msg; msg << "ERRORL. >, <, <=, >=, == operations allowed for a sensor-sensor comparison. Must be valid assay/dag being checked for repetition." << ends; claim(false, &msg); } } id = next_id++; operationType = ot; operands = NULL; operandType = OP_RUN_COUNT; constant = runCount; sensor1 = NULL; sensor2 = NULL; unconditionalParent = repeatableDag; } ///////////////////////////////////////////////////////////////////// // Creating an expression that performs a NOT operation ///////////////////////////////////////////////////////////////////// Expression::Expression(Expression *notExp) { id = next_id++; operationType = OP_NOT; operands = new vector<Expression*>(); operands->push_back(notExp); operandType = OP_SUB_EXP; constant = 0; sensor1 = NULL; sensor2 = NULL; unconditionalParent = NULL; } ///////////////////////////////////////////////////////////////////// // Creating an expression that performs an AND or OR operation ///////////////////////////////////////////////////////////////////// Expression::Expression(ExOperationType andOr) { { // Sanity check: Must be proper operation type stringstream msg; msg << "ERRORL. Only AND, OR operations allowed for this expression." << ends; claim(andOr == OP_AND || andOr == OP_OR, &msg); } id = next_id++; operationType = andOr; operands = new vector<Expression*>(); operandType = OP_SUB_EXP; constant = 0; sensor1 = NULL; sensor2 = NULL; unconditionalParent = NULL; } ///////////////////////////////////////////////////////////////////// // Creating an expression that is either unconditionally true or false. // Must pass the unconditional parent from which to branch from ///////////////////////////////////////////////////////////////////// Expression::Expression(DAG *unconPar, bool unconditional) { id = next_id++; if (unconditional) operandType = OP_TRUE; else operandType = OP_FALSE; //operands = new vector<Expression*>(); operands = NULL; operationType = OP_UNCOND; constant = 0; sensor1 = NULL; sensor2 = NULL; unconditionalParent = unconPar; } ///////////////////////////////////////////////////////////////////// // Destructor. ///////////////////////////////////////////////////////////////////// Expression::~Expression() { if (operands) { // TODO: Traverse and do recursive delete...MAYBE //for (int i = 0; i < operands->size(); i++) //recursiveDelete(); operands->clear(); delete operands; } if (sensor1) sensor1 = NULL; if (sensor2) sensor2 = NULL; } ///////////////////////////////////////////////////////////////////// // Methods ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // Add an operand to an AND/OR statement. ///////////////////////////////////////////////////////////////////// void Expression::addOperand(Expression *op) { { // Sanity check: Must be AND/OR to add operand stringstream msg; msg << "ERRORL. Only AND, OR operations allowed to add more operands." << ends; claim(operationType == OP_AND || operationType == OP_OR, &msg); } { // Sanity check: Expression must not be NULL stringstream msg; msg << "ERRORL. Expression is not valid." << ends; claim(op, &msg); } operands->push_back(op); } ///////////////////////////////////////////////////////////////////// // Evaluates if the expression is valid. That is, if all the leaves // actually evaluate to a true or false (the leaves all compare // sensor/constant values). ///////////////////////////////////////////////////////////////////// bool Expression::isValidExpression() { return recursiveValidate(this); } bool Expression::recursiveValidate(Expression *e) { if (!e) return false; if (e->operationType == OP_GT || e->operationType == OP_LT || e->operationType == OP_GoE || e->operationType == OP_LoE || e->operationType == OP_EQUAL || e->operationType == OP_UNCOND) return true; else if (e->operationType == OP_AND && e->operationType == OP_OR && e->operands->size() <= 1) return false; else if (e->operands->size() == 0) // e->operationType == OP_NOT return false; bool isValid = true; for (int i = 0; i < e->operands->size(); i++) { isValid = isValid && recursiveValidate(e->operands->at(i)); if (!isValid) return false; } return true; } ///////////////////////////////////////////////////////////////////// // Prints the boolean expression. If printLiveValues is set, prints // live values of the sensors, run-count, etc.; if not, then just // prints the inequality w/o live values. ///////////////////////////////////////////////////////////////////// string Expression::printExpression(bool printLiveValues) { stringstream ss; recursivePrint(this, &ss, printLiveValues); return ss.str(); } void Expression::recursivePrint(Expression *e, stringstream *ss, bool printLiveValues) { if (!e) { *ss << "(No Condition)"; return; } *ss << "("; if (e->operationType == OP_UNCOND) { if (e->operandType == OP_TRUE) *ss << "Unconditional TRUE"; else if (e->operandType == OP_FALSE) *ss << "Unconditional FALSE"; } else if (e->operationType == OP_GT || e->operationType == OP_LT || e->operationType == OP_GoE || e->operationType == OP_LoE || e->operationType == OP_EQUAL) { // Print out run-count or sensor-reading if (printLiveValues) { if (e->operandType == OP_RUN_COUNT) *ss << e->unconditionalParent->GetIdName() << "_RUN_COUNT = " << e->unconditionalParent->getRunCount(); else // 1- or 2-Sensor reading *ss << e->sensor1->GetName() << "_READ = " << e->sensor1->GetReading(); } else { if (e->operandType == OP_RUN_COUNT) *ss << e->unconditionalParent->GetIdName() << "_RUN_COUNT"; else // 1- or 2-Sensor reading *ss << e->sensor1->GetName() << "_READ"; } if (e->operationType == OP_GT) *ss << " > "; else if (e->operationType == OP_LT) *ss << " < "; else if (e->operationType == OP_GoE) *ss << " >= "; else if (e->operationType == OP_LoE) *ss << " <= "; else if (e->operationType == OP_EQUAL) *ss << " = "; else *ss << " ??? "; if (e->operandType == OP_ONE_SENSOR || e->operandType == OP_RUN_COUNT) *ss << e->constant; else if (e->operandType == OP_TWO_SENSORS) { if (printLiveValues) *ss << e->sensor2->GetName() << "_READ = " << e->sensor2->GetReading(); else *ss << e->sensor2->GetName() << "_READ"; } else claim(false, "Unsupported operand type: Expression::recursivePrint()"); } else if (e->operationType == OP_AND || e->operationType == OP_OR) { for (int i = 0; i < e->operands->size(); i++) { recursivePrint(e->operands->at(i), ss, printLiveValues); if (i < e->operands->size()-1 && e->operationType == OP_AND) *ss << " AND "; else if (i < e->operands->size()-1 && e->operationType == OP_OR) *ss << " OR "; } } else if (e->operationType == OP_NOT) { *ss << " NOT"; recursivePrint(e->operands->front(), ss, printLiveValues); } else claim(false, "Unsupported operation/operand type: Expression::recursivePrint()."); *ss << ")"; } ///////////////////////////////////////////////////////////////////// // Evaluates the expression and returns the value. ///////////////////////////////////////////////////////////////////// bool Expression::evaluateExpression() { return recursiveEvaluate(this); } bool Expression::recursiveEvaluate(Expression *e) { { // Sanity check: Expression must be valid stringstream msg; msg << "ERRORL. Expression not valid." << ends; claim(e->isValidExpression(), &msg); } if (e->operationType == OP_UNCOND) { if (e->operandType == OP_TRUE) return true; else if (e->operandType == OP_FALSE) return false; } else if (e->operationType == OP_GT || e->operationType == OP_LT || e->operationType == OP_GoE || e->operationType == OP_LoE || e->operationType == OP_EQUAL) { { // Sanity check: Detect nodes must be done if (e->sensor1) { stringstream msg; msg << "ERRORL. Detect sensor " << e->sensor1->GetName() << " status must be 'complete'." << endl; claim(e->sensor1->GetStatus() == COMPLETE , &msg); } if (e->sensor2) { stringstream msg; msg << "ERRORL. Detect sensor " << e->sensor2->GetName() << " status must be 'complete'." << endl; claim(e->sensor2->GetStatus() == COMPLETE , &msg); } } double lhs; double rhs; if (e->operandType == OP_ONE_SENSOR) { lhs = e->sensor1->GetReading(); rhs = e->constant; } else if (e->operandType == OP_TWO_SENSORS) { lhs = e->sensor1->GetReading(); rhs = e->sensor2->GetReading(); } else if (e->operandType == OP_RUN_COUNT) { lhs = e->unconditionalParent->getRunCount(); rhs = e->constant; } else claim(false, "Unsupported operand type."); if (e->operationType == OP_GT) return lhs > rhs; else if (e->operationType == OP_LT) return lhs < rhs; else if (e->operationType == OP_GoE) return lhs >= rhs; else if (e->operationType == OP_LoE) return lhs <= rhs; else if (e->operationType == OP_EQUAL) return lhs == rhs; } else if (e->operationType == OP_AND) { bool eval = true; for (int i = 0; i < e->operands->size(); i++) eval = eval && recursiveEvaluate(e->operands->at(i)); return eval; } else if (e->operationType == OP_OR) { bool eval = false; for (int i = 0; i < e->operands->size(); i++) eval = eval || recursiveEvaluate(e->operands->at(i)); return eval; } else if (e->operationType == OP_NOT) { return !(recursiveEvaluate(e->operands->front())); } else { // Sanity check: Detect nodes must be done stringstream msg; msg << "ERRORL. Unknown operation type" << ends; claim(false , &msg); } stringstream msg; msg << "ERRORL. Reached end of non-void function" << ends; cout << msg.str() << endl; exit(-1); } ///////////////////////////////////////////////////////////////////// // Gets the unique DAG parents for this expression ///////////////////////////////////////////////////////////////////// void Expression::getParentDags(list<DAG *> *parents) { //parents->clear(); recursiveGetParents(this, parents); } void Expression::recursiveGetParents(Expression *e, list<DAG *> *parents) { if (e->operationType == OP_GT || e->operationType == OP_LT || e->operationType == OP_GoE || e->operationType == OP_LoE || e->operationType == OP_EQUAL) { if (e->operandType == OP_RUN_COUNT) { parents->remove(e->unconditionalParent); parents->push_back(e->unconditionalParent); } else if (e->operandType == OP_ONE_SENSOR || e->operandType == OP_TWO_SENSORS) { parents->remove(e->sensor1->GetDAG()); parents->push_back(e->sensor1->GetDAG()); if (e->operandType == OP_TWO_SENSORS) { parents->remove(e->sensor2->GetDAG()); parents->push_back(e->sensor2->GetDAG()); } } else claim(false, "Unsupported operandType in Expression:recursiveGetParents()."); } else if (e->operationType != OP_UNCOND) { for (int i = 0; i < e->operands->size(); i++) recursiveGetParents(e->operands->at(i), parents); } else // OP_UNCOND { parents->remove(e->unconditionalParent); parents->push_back(e->unconditionalParent); } }
31.219124
150
0.515123
AryaFaramarzi
7728ebb7cef5baa7c90f4d3be4f977cc1115eb4e
13,760
hpp
C++
src/thread/compute_thread.hpp
huangqundl/af_stream
178d98feaf403b6947fb0fae3c2bbaedd91f9ab8
[ "Apache-2.0" ]
15
2017-03-28T13:15:53.000Z
2022-03-01T08:16:48.000Z
src/thread/compute_thread.hpp
huangqundl/af_stream
178d98feaf403b6947fb0fae3c2bbaedd91f9ab8
[ "Apache-2.0" ]
null
null
null
src/thread/compute_thread.hpp
huangqundl/af_stream
178d98feaf403b6947fb0fae3c2bbaedd91f9ab8
[ "Apache-2.0" ]
6
2017-10-17T14:10:23.000Z
2022-03-01T08:16:29.000Z
#ifndef __AFS_COMPUTE_THREAD_HPP_INCLUDED__ #define __AFS_COMPUTE_THREAD_HPP_INCLUDED__ #include <stdio.h> #include <stdint.h> #include <string> #include "../config.hpp" #include "thread.hpp" #include "up_thread.hpp" #include "down_thread.hpp" #include "../wrap_item.hpp" #include "router_base.hpp" #include "../queues/mpsc_channel.hpp" #include "../queues/zerocopy_ringbuffer.hpp" #include "../fault_tolerance/operator_tracker.hpp" #include "../operator/ft_interface.hpp" namespace afs { /** * Processing events * @param InT class of input event from Dispatcher * @param OutT class of output event to Collector */ //template <class InTf, class OutTf, class InTb, class OutTb> template <class InT, class OutT, class RInT, class ROutT> class ComputeThread : public ThreadBase { typedef WrapItem<InT> WInT; typedef WrapItem<OutT> WOutT; typedef WrapItem<RInT> WRInT; typedef WrapItem<ROutT> WROutT; public: ComputeThread(int num_upstream, int num_downstream); void ConnectUpThread(UpThread<InT, ROutT>* up_thread); void ConnectDownThread(DownThread<OutT, RInT>* down_thread); void ConnectComputeThread(ThreadBase* dst_thread); virtual void ComputeThreadRecovery() {}; protected: /** * Send data to next-hop worker via output_thread */ /* void EmitData(OutT& msg) { int dest = router_->GetDestination(&msg, sizeof(OutT)); WOutT* slot = (WOutT*)writer_->GetSlot(); slot->set_type(ITEM_NORMAL); slot->set_worker_source(get_wid()); slot->set_thr_source(get_tid()); slot->data() = msg; down_writer_->Write(dest, slot); } */ uint64_t GetNumDownstream() { return num_downstream_; } void EmitData(int dest, OutT& msg) { //LOG_MSG("To emit %d\n", dest); WOutT* slot = (WOutT*)down_writer_->GetSlot(); slot->set_type(ITEM_NORMAL); slot->set_worker_source(get_wid()); slot->set_thr_source(get_tid()); slot->data() = msg; down_writer_->Write(dest, slot); //LOG_MSG(" end emit\n"); } /* WOutT* GetSlot() { return (WOutT*)writer_->GetSlot(); } */ /* void CompleteWriteSlot(int dest, WOutT* slot) { slot->set_type(ITEM_NORMAL); slot->set_worker_source(get_wid()); slot->set_thr_source(get_tid()); down_writer_->Write(dest, slot); } */ /* int GetDest(OutT& msg) { return router_->GetDestination(&msg, sizeof(OutT)); } */ /** * Send data to next-hop worker via output_thread */ void EmitReverseData(int dest, ROutT& msg) { //LOG_MSG("To emit reverse\n"); afs_assert(up_writer_, " reverse writer null\n"); //int dest = r_router_->GetDestination(&msg, sizeof(ROutT)); WROutT* slot = (WROutT*)up_writer_->GetSlot(); slot->set_type(ITEM_REVERSE); slot->set_worker_source(get_wid()); slot->set_thr_source(get_tid()); slot->data() = msg; up_writer_->Write(dest, slot); //LOG_MSG(" end emit reverse\n"); } void FlushReverseWriter() { up_writer_->Flush(); up_writer_->Clean(); up_writer_->Init(); } void EmitReverseTimeout(int dest) { WROutT r_wrap_msg; r_wrap_msg.set_type(ITEM_REVERSE); r_wrap_msg.set_worker_source(get_wid()); r_wrap_msg.set_thr_source(get_tid()); EmitReverseWrapData(dest, r_wrap_msg); } private: // Unique id of the compute_thread in the worker //int id_; // monitor number of process events uint64_t event_; uint64_t r_event_; int num_downstream_; int num_upstream_; // forward queues ZeroRingBuffer<WInT>* in_queue_; MPSCWriter<WOutT>* down_writer_; // backward queue ZeroRingBuffer<WRInT>* r_in_queue_; MPSCWriter<WROutT>* up_writer_; //RouterBase* router_; //RouterBase* r_router_; // fault-tolerant operators std::vector<FTInterface*> operators; // derived from ThreadBase void ThreadInitHandler(); void ThreadFinishHandler(); void ThreadMainHandler(); // user-define interface to initialize and cleaning-up // called by ThreadInitHandler and ThreadFinishHander respectively virtual void ComputeThreadInit() = 0; virtual void ComputeThreadFinish() = 0; // user-define interface to process events of various types //virtual void DoProcessRecord(InT& tuple) = 0; virtual void ProcessData(uint32_t src_worker, uint32_t src_thread, uint64_t seq, InT& tuple) = 0; virtual void ProcessPunc() = 0; virtual void ProcessFeedback(int src_worker, int src_thread, RInT& tuple) { LOG_MSG("Function ProcessFeedback does not be implemented\n"); } void EmitWrapData(int dest, WOutT& msg) { WOutT* slot = (WOutT*)down_writer_->GetSlot(); *slot = msg; down_writer_->Write(dest, slot); } void EmitReverseWrapData(int dest, WROutT& msg) { WROutT* slot = (WROutT*)up_writer_->GetSlot(); *slot = msg; up_writer_->Write(dest, slot); } void EmitFinish() { WOutT wrap_msg; if (down_writer_ != NULL) { wrap_msg.set_type(ITEM_FINISH); wrap_msg.set_worker_source(get_wid()); wrap_msg.set_thr_source(get_tid()); for (int i = 0; i < num_downstream_; i++) { EmitWrapData(i, wrap_msg); } down_writer_->Flush(); LOG_MSG("ComputeThread: emit finish\n"); } } void EmitReverseFinish() { WROutT r_wrap_msg; if (up_writer_ != NULL) { r_wrap_msg.set_type(ITEM_FINISH); r_wrap_msg.set_worker_source(get_wid()); r_wrap_msg.set_thr_source(get_tid()); for (int i=0; i < num_upstream_; i++) { EmitReverseWrapData(i, r_wrap_msg); } up_writer_->Flush(); } } }; template <class InT, class OutT, class RInT, class ROutT> ComputeThread<InT, OutT, RInT, ROutT>::ComputeThread( int num_upstream, //RouterBase* r, int num_downstream //, RouterBase* rr ) : ThreadBase(t_compute_thread), event_(0), r_event_(0), num_downstream_(num_downstream), num_upstream_(num_upstream), in_queue_(NULL), down_writer_(NULL), r_in_queue_(NULL), up_writer_(NULL) //router_(r), //r_router_(rr) { LOG_MSG("compute_thread downstream %d, upstream %d\n", num_downstream, num_upstream); if (num_downstream > 0) { down_writer_ = new MPSCWriter<WOutT>(); } if (num_upstream > 0) { LOG_MSG("create reverse write_\n"); up_writer_ = new MPSCWriter<WROutT>(); } } template <class InT, class OutT, class RInT, class ROutT> void ComputeThread<InT, OutT, RInT, ROutT>::ThreadInitHandler() { LOG_MSG(INDENT "initializing\n"); if (down_writer_ != NULL) { down_writer_->Init(); } if (up_writer_ != NULL) { up_writer_->Init(); } ComputeThreadInit(); operators = *(OperatorTracker::GetInstance()->GetThreadOps(thr_id())); } template <class InT, class OutT, class RInT, class ROutT> void ComputeThread<InT, OutT, RInT, ROutT>::ThreadMainHandler() { WInT* tuple = NULL; WRInT* r_tuple = NULL; int up_stop = 0; int down_stop = 0; // no upstream implies external source if (num_upstream_ == 0) { num_upstream_++; } unsigned int num_operator = operators.size(); afs_zmq::command_t cmd; /* if (!r_in_queue_) { r_stop = true; } */ //LOG_MSG("%s start to run\n", get_thread_str()); //LOG_MSG(" %s operator number %u\n", get_thread_str(), num_operator); while (up_stop<num_upstream_ || down_stop<num_downstream_) { //LOG_MSG("while\n"); while (down_stop<num_downstream_ && (r_tuple=r_in_queue_->Extract()) != NULL) { ITEM_TYPE t = r_tuple->get_type(); switch (t) { case ITEM_FINISH: down_stop++; break; case ITEM_REVERSE: r_event_++; ProcessFeedback(r_tuple->get_worker_source(), r_tuple->get_thr_source(), r_tuple->data()); break; default: LOG_ERR("Unidentified event type %d\n", (int)t); break; } r_in_queue_->Ack(); } // end of while reverse //LOG_MSG("read forward queue\n"); if (afs_unlikely(up_stop==num_upstream_)) { //LOG_MSG("Attempt to clean\n"); down_writer_->AttemptClean(); } else { if ((tuple=in_queue_->Extract()) != NULL) { ITEM_TYPE t = tuple->get_type(); uint32_t worker = tuple->get_worker_source(); uint32_t thread = tuple->get_thr_source(); uint64_t seq = tuple->get_seq(); InT data = tuple->data(); in_queue_->Ack(); switch (t) { case ITEM_FINISH: up_stop++; LOG_MSG("compute thread: up_stop %d\n", up_stop); // send finish first // but continue to wait for finish from downstream workers if (up_stop == num_upstream_) { EmitFinish(); } break; case ITEM_TIMEOUT: ProcessPunc(); break; case ITEM_NORMAL: event_++; ProcessData(worker, thread, seq, data); break; default: LOG_ERR("Unidentified event type %d\n", (int)t); break; } } // end of if } for (unsigned int i=0; i<num_operator; i++) { double d = operators[i]->CalculateDivergence(); //LOG_MSG("thread %d, operator %d, divergence %lf, divergence thresh %lf\n", thr_id(), i, d, operators[i]->GetDivergenceThresh()); if (d > operators[i]->GetDivergenceThresh()) { BackupItem& backup_item = cmd.args.backup_item; operators[i]->SerializeState(backup_item.data); if (backup_item.data.meta.len) { cmd.type = afs_zmq::command_t::backup; backup_item.info.backup_op = 0; backup_item.info.worker_id = get_wid(); backup_item.info.thread_id = thr_id(); backup_item.info.op_index = i; backup_item.info.seq = tuple->get_seq(); NotifyWorker(cmd); WaitWorker(afs_zmq::command_t::backup, true); backup_item.data.meta.len = 0; } } } } // end of while LOG_MSG(" compute thread (out-of-while): up_stop %d, upstream %d, down_stop %d, downstream %d\n", up_stop, num_upstream_, down_stop, num_downstream_); if (down_writer_) { down_writer_->AttemptClean(); } LOG_MSG(" compute thread send reverse end\n"); EmitReverseFinish(); if (up_writer_ != NULL) { up_writer_->Clean(); } LOG_MSG(" compute thread end\n"); } template <class InT, class OutT, class RInT, class ROutT> void ComputeThread<InT, OutT, RInT, ROutT>::ThreadFinishHandler() { LOG_MSG(INDENT "process %lu tuples, %lu tuples\n", event_, r_event_); ComputeThreadFinish(); } template <class InT, class OutT, class RInT, class ROutT> void ComputeThread<InT, OutT, RInT, ROutT>::ConnectUpThread(UpThread<InT, ROutT>* up_thread) { in_queue_ = new ZeroRingBuffer<WInT>(); up_thread->AddOutQueue(in_queue_); if (up_thread->IsReverse()) { // each upstream worker corresponds to an output buffer in up_thread // add this compute_thread as a writer for all the output buffers int num_upstream = up_thread->GetNumUpstream(); int writer_id = get_tid(); for (int i=0; i<num_upstream; i++) { MPSCReader<WROutT>* r_reader = (MPSCReader<WROutT>*)up_thread->GetReverseOutBufferReader(i); afs_assert(up_writer_, "reverse writer %d is not available\n", writer_id); afs_assert(r_reader, "reverse reader %d is not available\n", i); up_writer_->SetWriterId(writer_id); up_writer_->ConnectPeer(i, r_reader); r_reader->SetReaderId(i); r_reader->ConnectPeer(writer_id, up_writer_); } } } template <class InT, class OutT, class RInT, class ROutT> void ComputeThread<InT, OutT, RInT, ROutT>::ConnectDownThread(DownThread<OutT, RInT>* down_thread) { int writer_id = get_tid(); int num_down_thread_reader = down_thread->GetDownstream(); for (int i=0; i<num_down_thread_reader; i++) { MPSCReader<WOutT>* reader = (MPSCReader<WOutT>*)down_thread->GetOutBufferReader(i); afs_assert(down_writer_, "writer %d is not available\n", writer_id); afs_assert(reader, "reader %d is not available\n", i); down_writer_->SetWriterId(writer_id); down_writer_->ConnectPeer(i, reader); reader->SetReaderId(i); reader->ConnectPeer(writer_id, down_writer_); } if (down_thread->IsReverse()) { r_in_queue_ = new ZeroRingBuffer<WRInT>(); down_thread->AddReverseInBuffer(r_in_queue_); } } } // namespace #endif // SAND_SUBANALYZER_SUBANALYZER_HPP_
32.45283
157
0.59077
huangqundl
77290de4a942a5c405d09fd0daeade9d837e0acd
568
cc
C++
source/global/pyglobals.cc
yu22mal/geant4_pybind
ff7efc322fe53f39c7ae7ed140861052a92479fd
[ "Unlicense" ]
6
2021-08-08T08:40:13.000Z
2022-03-23T03:05:15.000Z
source/global/pyglobals.cc
yu22mal/geant4_pybind
ff7efc322fe53f39c7ae7ed140861052a92479fd
[ "Unlicense" ]
3
2021-12-01T14:38:06.000Z
2022-02-10T11:28:28.000Z
source/global/pyglobals.cc
yu22mal/geant4_pybind
ff7efc322fe53f39c7ae7ed140861052a92479fd
[ "Unlicense" ]
3
2021-07-16T13:57:34.000Z
2022-02-07T11:17:19.000Z
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/stl_bind.h> #include <G4ThreeVector.hh> #include <G4TwoVector.hh> #include <vector> #include "typecast.hh" #include "opaques.hh" namespace py = pybind11; void export_globals(py::module &m) { py::bind_vector<G4intVector>(m, "G4intVector"); py::bind_vector<G4doubleVector>(m, "G4doubleVector"); py::bind_vector<G4StringVector>(m, "G4StringVector"); py::bind_vector<G4ThreeVectorVector>(m, "G4ThreeVectorVector"); py::bind_vector<G4TwoVectorVector>(m, "G4TwoVectorVector"); }
25.818182
66
0.741197
yu22mal
772e1bbd622c67b57b57052831cfa9d862de4f8c
448
cpp
C++
algorithms/warmup/lcm.cpp
weirdname404/courses
611443422cc6acc1af563d9d7d07181e9984ddab
[ "MIT" ]
3
2019-05-28T16:53:54.000Z
2019-08-03T02:45:08.000Z
algorithms/warmup/lcm.cpp
weirdname404/courses
611443422cc6acc1af563d9d7d07181e9984ddab
[ "MIT" ]
null
null
null
algorithms/warmup/lcm.cpp
weirdname404/courses
611443422cc6acc1af563d9d7d07181e9984ddab
[ "MIT" ]
null
null
null
// Given two integers a and b, find their least common multiple. #include <iostream> using namespace std; int gcd_euclid(long a, long b) { if (a % b == 0) { return b; } int gcd = gcd_euclid(b, a % b); return gcd; } long long lcm(long a, long b) { long long mult = a * b; return (long long) mult / gcd_euclid(a, b); } int main() { long a, b; cin >> a >> b; cout << lcm(a, b) << endl; return 0; }
17.230769
64
0.551339
weirdname404
77345f5c3a4a4b61424f48c4c98802d3d63faf62
18,745
cpp
C++
smacc2_client_library/nav2z_client/custom_planners/undo_path_global_planner/src/undo_path_global_planner/undo_path_global_planner.cpp
reelrbtx/SMACC2
ac61cb1599f215fd9f0927247596796fc53f82bf
[ "Apache-2.0" ]
48
2021-05-28T01:33:20.000Z
2022-03-24T03:16:03.000Z
smacc2_client_library/nav2z_client/custom_planners/undo_path_global_planner/src/undo_path_global_planner/undo_path_global_planner.cpp
reelrbtx/SMACC2
ac61cb1599f215fd9f0927247596796fc53f82bf
[ "Apache-2.0" ]
75
2021-06-25T22:11:21.000Z
2022-03-30T13:05:38.000Z
smacc2_client_library/nav2z_client/custom_planners/undo_path_global_planner/src/undo_path_global_planner/undo_path_global_planner.cpp
reelrbtx/SMACC2
ac61cb1599f215fd9f0927247596796fc53f82bf
[ "Apache-2.0" ]
14
2021-06-16T12:10:57.000Z
2022-03-01T18:23:27.000Z
// Copyright 2021 RobosoftAI 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. /***************************************************************************************************************** * * Authors: Pablo Inigo Blasco, Brett Aldrich * ******************************************************************************************************************/ #include <angles/angles.h> #include <tf2/transform_datatypes.h> #include <boost/assign.hpp> #include <boost/range/adaptor/reversed.hpp> #include <boost/range/algorithm/copy.hpp> #include <geometry_msgs/msg/quaternion.hpp> #include <nav2z_planners_common/common.hpp> #include <nav_2d_utils/tf_help.hpp> #include <pluginlib/class_list_macros.hpp> #include <tf2_geometry_msgs/tf2_geometry_msgs.hpp> #include <undo_path_global_planner/undo_path_global_planner.hpp> // register this planner as a BaseGlobalPlanner plugin namespace cl_nav2z { namespace undo_path_global_planner { using namespace std::chrono_literals; /** ****************************************************************************************************************** * Constructor() ****************************************************************************************************************** */ UndoPathGlobalPlanner::UndoPathGlobalPlanner() { skip_straight_motion_distance_ = 0.2; transform_tolerance_ = 0.1; } UndoPathGlobalPlanner::~UndoPathGlobalPlanner() { // clear "rviz"- publish empty path nav_msgs::msg::Path planMsg; planMsg.header.stamp = this->nh_->now(); planPub_->publish(planMsg); } void UndoPathGlobalPlanner::cleanup() { this->clearGoalMarker(); } void UndoPathGlobalPlanner::activate() { RCLCPP_INFO_STREAM(nh_->get_logger(), "activating planner UndoPathGlobalPlanner"); planPub_->on_activate(); markersPub_->on_activate(); } void UndoPathGlobalPlanner::deactivate() { RCLCPP_INFO_STREAM(nh_->get_logger(), "deactivating planner UndoPathGlobalPlanner"); this->clearGoalMarker(); planPub_->on_deactivate(); markersPub_->on_deactivate(); } /** ****************************************************************************************************************** * initialize() ****************************************************************************************************************** */ void UndoPathGlobalPlanner::configure( const rclcpp_lifecycle::LifecycleNode::WeakPtr & parent, std::string name, std::shared_ptr<tf2_ros::Buffer> tf, std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros) { nh_ = parent.lock(); costmap_ros_ = costmap_ros; tf_ = tf; name_ = name; // RCLCPP_WARN_NAMED(nh_->get_logger(), "Backwards", "initializating global planner, costmap address: %ld", // (long)costmap_ros); rclcpp::SensorDataQoS qos; qos.keep_last(2); forwardPathSub_ = nh_->create_subscription<nav_msgs::msg::Path>( "odom_tracker_path", qos, std::bind(&UndoPathGlobalPlanner::onForwardTrailMsg, this, std::placeholders::_1)); planPub_ = nh_->create_publisher<nav_msgs::msg::Path>("undo_path_planner/global_plan", 1); markersPub_ = nh_->create_publisher<visualization_msgs::msg::MarkerArray>("undo_path_planner/markers", 1); declareOrSet(nh_, name_ + ".transform_tolerance", transform_tolerance_); } /** ****************************************************************************************************************** * onForwardTrailMsg() ****************************************************************************************************************** */ void UndoPathGlobalPlanner::onForwardTrailMsg(const nav_msgs::msg::Path::SharedPtr forwardPath) { lastForwardPathMsg_ = *forwardPath; RCLCPP_DEBUG_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] received backward path msg poses [" << lastForwardPathMsg_.poses.size() << "]"); } /** ****************************************************************************************************************** * clearGoalMarker() ****************************************************************************************************************** */ void UndoPathGlobalPlanner::clearGoalMarker() { visualization_msgs::msg::Marker marker; marker.header.frame_id = this->costmap_ros_->getGlobalFrameID(); marker.header.stamp = nh_->now(); marker.ns = "my_namespace2"; marker.id = 0; marker.action = visualization_msgs::msg::Marker::DELETEALL; visualization_msgs::msg::MarkerArray ma; ma.markers.push_back(marker); markersPub_->publish(ma); } /** ****************************************************************************************************************** * publishGoalMarker() ****************************************************************************************************************** */ void UndoPathGlobalPlanner::publishGoalMarker( const geometry_msgs::msg::Pose & pose, double r, double g, double b) { double phi = tf2::getYaw(pose.orientation); visualization_msgs::msg::Marker marker; marker.header.frame_id = this->costmap_ros_->getGlobalFrameID(); marker.header.stamp = nh_->now(); marker.ns = "my_namespace2"; marker.id = 0; marker.type = visualization_msgs::msg::Marker::ARROW; marker.action = visualization_msgs::msg::Marker::ADD; marker.scale.x = 0.1; marker.scale.y = 0.3; marker.scale.z = 0.1; marker.color.a = 1.0; marker.color.r = r; marker.color.g = g; marker.color.b = b; marker.lifetime = rclcpp::Duration(0s); geometry_msgs::msg::Point start, end; start.x = pose.position.x; start.y = pose.position.y; end.x = pose.position.x + 0.5 * cos(phi); end.y = pose.position.y + 0.5 * sin(phi); marker.points.push_back(start); marker.points.push_back(end); visualization_msgs::msg::MarkerArray ma; ma.markers.push_back(marker); markersPub_->publish(ma); } /** ****************************************************************************************************************** * defaultBackwardPath() ****************************************************************************************************************** */ void UndoPathGlobalPlanner::createDefaultUndoPathPlan( const geometry_msgs::msg::PoseStamped & start, const geometry_msgs::msg::PoseStamped & /*goal*/, std::vector<geometry_msgs::msg::PoseStamped> & plan) { //------------- TRANSFORM TO GLOBAL FRAME PATH --------------------------- // the forward plan might be recoreded in a different frame of the global (costmap) frame. Transform it. // transform global plan to the navigation reference frame RCLCPP_INFO_STREAM(nh_->get_logger(), "[UndoPathGlobalPlanner] Transforming forward path"); nav_msgs::msg::Path transformedPlan; rclcpp::Duration ttol = rclcpp::Duration::from_seconds(transform_tolerance_); for (auto p : lastForwardPathMsg_.poses) { geometry_msgs::msg::PoseStamped transformedPose; p.header.stamp = nh_->now(); // otherwise we can get some time tolerance error transformedPose.header.stamp = nh_->now(); transformedPose.header.frame_id = costmap_ros_->getGlobalFrameID(); nav_2d_utils::transformPose(tf_, costmap_ros_->getGlobalFrameID(), p, transformedPose, ttol); transformedPlan.poses.push_back(transformedPose); } lastForwardPathMsg_ = transformedPlan; //--------------------------------------------------------------------------- RCLCPP_INFO_STREAM(nh_->get_logger(), "[UndoPathGlobalPlanner] finding goal closest point"); int i = lastForwardPathMsg_.poses.size() - 1; double linear_mindist = std::numeric_limits<double>::max(); int mindistindex = -1; double startPoseAngle = tf2::getYaw(start.pose.orientation); geometry_msgs::msg::Pose startPositionProjected; // The goal of this code is finding the most convenient initial path pose. // first, find closest linear point to the current robot position // we start from the final goal, that is, the beginning of the trajectory // (since this was the forward motion from the odom tracker) for (auto & p : transformedPlan.poses /*| boost::adaptors::reversed*/) { geometry_msgs::msg::PoseStamped pose = p; pose.header.frame_id = costmap_ros_->getGlobalFrameID(); double dx = pose.pose.position.x - start.pose.position.x; double dy = pose.pose.position.y - start.pose.position.y; double dist = sqrt(dx * dx + dy * dy); double angleOrientation = tf2::getYaw(pose.pose.orientation); double angleError = fabs(angles::shortest_angular_distance(angleOrientation, startPoseAngle)); if (dist <= linear_mindist) { mindistindex = i; linear_mindist = dist; startPositionProjected = pose.pose; RCLCPP_DEBUG_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] initial start point search, NEWBEST_LINEAR= " << i << ". error, linear: " << linear_mindist << ", angular: " << angleError); } else { RCLCPP_DEBUG_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] initial start point search, skipped= " << i << ". best linear error: " << linear_mindist << ". current error, linear: " << dist << " angular: " << angleError); } i--; } double const ERROR_DISTANCE_PURE_SPINNING_FACTOR = 1.5; // Concept of second pass: now we only consider a pure spinning motion in this point. We want to consume some very // close angular targets, (accepting a larger linear minerror of 1.5 besterror. That is, more or less in the same // point). RCLCPP_DEBUG(nh_->get_logger(), "[UndoPathGlobalPlanner] second angular pass"); double angularMinDist = std::numeric_limits<double>::max(); if (mindistindex >= (int)transformedPlan.poses.size()) mindistindex = transformedPlan.poses.size() - 1; // workaround, something is making a out of bound exception in poses array access { if (transformedPlan.poses.size() == 0) { RCLCPP_WARN_STREAM(nh_->get_logger(), "[UndoPathGlobalPlanner] Warning possible bug"); } // ------- FULL FORWARD PASS TO FIND THE STARTING POIINT OF THE FORWARD MOTION ------ RCLCPP_DEBUG_STREAM(nh_->get_logger(), "[UndoPathGlobalPlanner] second pass loop"); for (int i = mindistindex; i >= 0; i--) { // warning this index, i refers to some inverse interpretation from the previous loop, // (last indexes in this path corresponds to the poses closer to our current position) RCLCPP_DEBUG_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] " << i << "/" << transformedPlan.poses.size()); auto index = (int)transformedPlan.poses.size() - i - 1; if (index < 0 || (size_t)index >= transformedPlan.poses.size()) { RCLCPP_WARN_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] this should not happen. Check implementation."); break; } geometry_msgs::msg::PoseStamped pose = transformedPlan.poses[transformedPlan.poses.size() - i - 1]; RCLCPP_DEBUG_STREAM(nh_->get_logger(), "[UndoPathGlobalPlanner] global frame"); pose.header.frame_id = costmap_ros_->getGlobalFrameID(); double dx = pose.pose.position.x - start.pose.position.x; double dy = pose.pose.position.y - start.pose.position.y; double dist = sqrt(dx * dx + dy * dy); if (dist <= linear_mindist * ERROR_DISTANCE_PURE_SPINNING_FACTOR) { double angleOrientation = tf2::getYaw(pose.pose.orientation); double angleError = fabs(angles::shortest_angular_distance(angleOrientation, startPoseAngle)); if (angleError < angularMinDist) { angularMinDist = angleError; mindistindex = i; RCLCPP_DEBUG_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] initial start point search (angular update), NEWBEST_ANGULAR= " << i << ". error, linear: " << dist << "(" << linear_mindist << ")" << ", angular: " << angleError << "(" << angularMinDist << ")"); } else { RCLCPP_DEBUG_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] initial start point search (angular update), skipped= " << i << ". error, linear: " << dist << "(" << linear_mindist << ")" << ", angular: " << angleError << "(" << angularMinDist << ")"); } } else { RCLCPP_DEBUG_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] initial start point search (angular update) not in linear " "range, skipped= " << i << " linear error: " << dist << "(" << linear_mindist << ")"); } } } // REVERSE FORWARD PASS if (mindistindex != -1) { // plan.push_back(start); RCLCPP_WARN_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] Creating the backwards plan from odom tracker path (, " << transformedPlan.poses.size() << ") poses"); RCLCPP_WARN_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] closer point to goal i=" << mindistindex << " (linear min dist " << linear_mindist << ")"); // copy the path at the inverse direction, but only up to the closest point to the goal in the path (for partial undoing) for (int i = transformedPlan.poses.size() - 1; i >= mindistindex; i--) { auto & pose = transformedPlan.poses[i]; rclcpp::Time t(pose.header.stamp); RCLCPP_INFO_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] adding to plan i = " << i << " stamp:" << t.seconds()); plan.push_back(pose); } RCLCPP_WARN_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] refined plan has " << plan.size() << " points"); } else { RCLCPP_ERROR_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner ] undo global plan size: " << plan.size()); } } /** ****************************************************************************************************************** * makePlan() ****************************************************************************************************************** */ nav_msgs::msg::Path UndoPathGlobalPlanner::createPlan( const geometry_msgs::msg::PoseStamped & start, const geometry_msgs::msg::PoseStamped & goal) { // -------------- BASIC CHECKS --------------------- RCLCPP_INFO_STREAM(nh_->get_logger(), "[UndoPathGlobalPlanner] Undo global plan start "); nav_msgs::msg::Path planMsg; std::vector<geometry_msgs::msg::PoseStamped> & plan = planMsg.poses; RCLCPP_INFO_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] last forward path msg size: " << lastForwardPathMsg_.poses.size()); RCLCPP_INFO_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] last forward path frame id: " << lastForwardPathMsg_.poses.front().header.frame_id); RCLCPP_INFO_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] start pose frame id: " << start.header.frame_id); RCLCPP_INFO_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] goal pose frame id: " << goal.header.frame_id); if (lastForwardPathMsg_.poses.size() == 0) { return planMsg; } // ---------- INPUTS ACCOMMODATION ------------------- RCLCPP_INFO_STREAM(nh_->get_logger(), "[UndoPathGlobalPlanner] Inputs accommodation"); geometry_msgs::msg::PoseStamped transformedStart, transformedGoal; { rclcpp::Duration ttol = rclcpp::Duration::from_seconds(transform_tolerance_); geometry_msgs::msg::PoseStamped pstart = start; pstart.header.stamp = nh_->now(); nav_2d_utils::transformPose( tf_, costmap_ros_->getGlobalFrameID(), pstart, transformedStart, ttol); transformedStart.header.frame_id = costmap_ros_->getGlobalFrameID(); // geometry_msgs::msg::PoseStamped pgoal = goal; // pgoal.header.stamp = nh_->now(); // nav_2d_utils::transformPose(tf_, costmap_ros_->getGlobalFrameID(), pgoal, transformedGoal, ttol); // transformedGoal.header.frame_id = costmap_ros_->getGlobalFrameID(); //--------------- FORCE GOAL POSE---------------------------- RCLCPP_INFO_STREAM(nh_->get_logger(), "[UndoPathGlobalPlanner] Forced goal"); auto forcedGoal = lastForwardPathMsg_.poses[lastForwardPathMsg_.poses.size() - 1]; // FORCE LAST POSE forcedGoal.header.stamp = nh_->now(); nav_2d_utils::transformPose( tf_, costmap_ros_->getGlobalFrameID(), forcedGoal, transformedGoal, ttol); transformedGoal.header.frame_id = costmap_ros_->getGlobalFrameID(); } //------------- CREATING GLOBAL PLAN ----------------------------------------------- RCLCPP_INFO_STREAM(nh_->get_logger(), "[UndoPathGlobalPlanner] Creating undo plan"); this->createDefaultUndoPathPlan(transformedStart, transformedGoal, plan); planMsg.header.frame_id = this->costmap_ros_->getGlobalFrameID(); RCLCPP_INFO_STREAM(nh_->get_logger(), "[UndoPathGlobalPlanner] publishing goal markers"); publishGoalMarker(plan.back().pose, 1.0, 0, 1.0 /*purple color*/); //-------- CHECKING VALID PLAN ------------------------------------ bool acceptedGlobalPlan = true; RCLCPP_INFO_STREAM(nh_->get_logger(), "[UndoPathGlobalPlanner] valid plan checking"); auto costmap2d = this->costmap_ros_->getCostmap(); for (auto & p : plan) { unsigned int mx, my; costmap2d->worldToMap(p.pose.position.x, p.pose.position.y, mx, my); auto cost = costmap2d->getCost(mx, my); if (cost >= nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE) { acceptedGlobalPlan = false; break; } } //-------- PUBLISHING RESULTS --------------------------------------- RCLCPP_INFO_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] plan publishing. size: " << plan.size()); planPub_->publish(planMsg); if (!acceptedGlobalPlan) { RCLCPP_INFO( nh_->get_logger(), "[UndoPathGlobalPlanner] not accepted global plan because of possible collision"); } RCLCPP_INFO_STREAM( nh_->get_logger(), "[UndoPathGlobalPlanner] plan publishing. size: " << planMsg.poses.size()); return planMsg; } } // namespace undo_path_global_planner } // namespace cl_nav2z PLUGINLIB_EXPORT_CLASS( cl_nav2z::undo_path_global_planner::UndoPathGlobalPlanner, nav2_core::GlobalPlanner)
39.630021
126
0.604961
reelrbtx
7737132c2c1eab3f31285311dcca89857655145a
10,534
hh
C++
dune/gdt/operators/oswald-interpolation.hh
pymor/dune-gdt
fabc279a79e7362181701866ce26133ec40a05e0
[ "BSD-2-Clause" ]
4
2018-10-12T21:46:08.000Z
2020-08-01T18:54:02.000Z
dune/gdt/operators/oswald-interpolation.hh
dune-community/dune-gdt
fabc279a79e7362181701866ce26133ec40a05e0
[ "BSD-2-Clause" ]
154
2016-02-16T13:50:54.000Z
2021-12-13T11:04:29.000Z
dune/gdt/operators/oswald-interpolation.hh
dune-community/dune-gdt
fabc279a79e7362181701866ce26133ec40a05e0
[ "BSD-2-Clause" ]
5
2016-03-02T10:11:20.000Z
2020-02-08T03:56:24.000Z
// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2019) #ifndef DUNE_GDT_OPERATORS_OSWALD_INTERPOLATION_HH #define DUNE_GDT_OPERATORS_OSWALD_INTERPOLATION_HH #include <map> #include <set> #include <vector> #include <dune/grid/common/rangegenerators.hh> #include <dune/xt/common/memory.hh> #include <dune/xt/grid/boundaryinfo/allneumann.hh> #include <dune/xt/grid/boundaryinfo/interfaces.hh> #include <dune/xt/grid/walker.hh> #include <dune/xt/grid/type_traits.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/exceptions.hh> #include <dune/gdt/spaces/h1/continuous-lagrange.hh> #include <dune/gdt/tools/dirichlet-constraints.hh> #include "interfaces.hh" namespace Dune { namespace GDT { template <class M, class AssemblyGridView, size_t dim = 1, size_t dim_cols = 1, class SGV = AssemblyGridView, class RGV = AssemblyGridView> class OswaldInterpolationOperator : public OperatorInterface<M, SGV, dim, dim_cols, dim, dim_cols, RGV> { static_assert(XT::Grid::is_view<AssemblyGridView>::value, ""); static_assert(dim == 1, "I did not think about this yet, feel free to implement!"); static_assert(dim_cols == 1, "I did not think about this yet, feel free to implement!"); using BaseType = OperatorInterface<M, SGV, dim, dim_cols, dim, dim_cols, RGV>; using ThisType = OswaldInterpolationOperator; public: using typename BaseType::RangeSpaceType; using typename BaseType::SourceSpaceType; using typename BaseType::VectorType; using AGV = AssemblyGridView; using AssemblyGridViewType = AGV; using I = XT::Grid::extract_intersection_t<AssemblyGridViewType>; /** * \param boundary_info To determine the Dirichlet boundary DoFs on which to set the range to zero. */ OswaldInterpolationOperator(AssemblyGridViewType assembly_grid_view, const SourceSpaceType& src_spc, const RangeSpaceType& rng_spc, const XT::Grid::BoundaryInfo<I>& boundary_info) : assembly_grid_view_(assembly_grid_view) , source_space_(src_spc) , range_space_(rng_spc) , boundary_info_(boundary_info) , assembled_(false) , global_DoF_id_to_global_LP_id_map_() { DUNE_THROW_IF(!range_space_.is_lagrangian(), Exceptions::operator_error, "This does not make any sense!"); DUNE_THROW_IF(range_space_.continuous(0), Exceptions::operator_error, "This does not make any sense!"); DUNE_THROW_IF( range_space_.min_polorder() != range_space_.max_polorder(), Exceptions::operator_error, "Not implemented yet!"); } /** * Does not set any boundary DoFs to zero. */ OswaldInterpolationOperator(const AssemblyGridViewType& assembly_grid_view, const SourceSpaceType& src_spc, const RangeSpaceType& rng_spc) : assembly_grid_view_(assembly_grid_view) , source_space_(src_spc) , range_space_(rng_spc) , boundary_info_(new XT::Grid::AllNeumannBoundaryInfo<I>()) // Anything without Dirichlet , assembled_(false) { DUNE_THROW_IF(!range_space_.is_lagrangian(), Exceptions::operator_error, "This does not make any sense!"); DUNE_THROW_IF(range_space_.continuous(0), Exceptions::operator_error, "This does not make any sense!"); DUNE_THROW_IF( range_space_.min_polorder() != range_space_.max_polorder(), Exceptions::operator_error, "Not implemented yet!"); } bool linear() const override final { return true; } const SourceSpaceType& source_space() const override final { return source_space_; } const RangeSpaceType& range_space() const override final { return range_space_; } ThisType& assemble(const bool use_tbb = false) override final { if (assembled_) return *this; // create conforming space of same order to be used as mapper for the global Lagrange points const auto order = range_space_.min_polorder(); DUNE_THROW_IF( range_space_.max_polorder() != order, Exceptions::operator_error, "Not implemented yet for variable orders!"); auto cg_space = make_continuous_lagrange_space(assembly_grid_view_, order); // determine Dirichlet DoFs DirichletConstraints<I, decltype(cg_space)> dirichlet_constraints(boundary_info_.access(), cg_space); auto walker = XT::Grid::make_walker(assembly_grid_view_); walker.append(dirichlet_constraints); walker.walk(use_tbb); boundary_LPs_ = std::move(dirichlet_constraints.dirichlet_DoFs()); global_LP_id_to_global_DoF_id_map_.resize(cg_space.mapper().size()); global_DoF_id_to_global_LP_id_map_.resize(range_space_.mapper().size(), std::numeric_limits<size_t>::max()); DynamicVector<size_t> global_lagrange_point_indices(cg_space.mapper().max_local_size()); DynamicVector<size_t> global_DoF_indices(range_space_.mapper().max_local_size()); // walk the grid for (auto&& element : elements(assembly_grid_view_)) { const auto& lagrange_points = cg_space.finite_elements().get(element.type(), order).lagrange_points(); DUNE_THROW_IF(range_space_.finite_elements().get(element.type(), order).lagrange_points().size() != lagrange_points.size(), Exceptions::operator_error, "This should not happen, the Lagrange points should coincide for Lagrange spaces of same order!\n" << "range_space_.finite_element(element.type(), order).lagrange_points().size() = " << range_space_.finite_elements().get(element.type(), order).lagrange_points().size() << "\nlagrange_points.size() = " << lagrange_points.size()); cg_space.mapper().global_indices(element, global_lagrange_point_indices); range_space_.mapper().global_indices(element, global_DoF_indices); for (size_t ii = 0; ii < lagrange_points.size(); ++ii) { const auto global_LP_id = global_lagrange_point_indices[ii]; const auto global_DoF_id = global_DoF_indices[ii]; global_LP_id_to_global_DoF_id_map_[global_LP_id].insert(global_DoF_id); global_DoF_id_to_global_LP_id_map_[global_DoF_id] = global_LP_id; } } assembled_ = true; return *this; } // ... assemble(...) using BaseType::apply; void apply(const VectorType& source, VectorType& range, const XT::Common::Parameter& /*param*/ = {}) const override final { // some checks DUNE_THROW_IF(!assembled_, Exceptions::operator_error, "You need to call assemble() first!"); DUNE_THROW_IF(!source.valid(), Exceptions::operator_error, "source contains inf or nan!"); DUNE_THROW_IF(!source_space_.contains(source), Exceptions::operator_error, ""); DUNE_THROW_IF(!range_space_.contains(range), Exceptions::operator_error, ""); const auto source_function = make_discrete_function(source_space_, source); auto local_source = source_function.local_function(); DynamicVector<size_t> global_DoF_indices(range_space_.mapper().max_local_size()); // clear range on those DoFs associated with assembly_grid_view_ individually // (might only be a subset, range *= 0 would clear too much) for (const auto& DoF_id : global_DoF_id_to_global_LP_id_map_) if (DoF_id != std::numeric_limits<size_t>::max()) range[DoF_id] = 0; // walk the grid to average on all inner Lagrange points auto range_basis = range_space_.basis().localize(); for (auto&& element : elements(assembly_grid_view_)) { local_source->bind(element); range_basis->bind(element); const auto& lagrange_points = range_basis->finite_element().lagrange_points(); range_space_.mapper().global_indices(element, global_DoF_indices); DUNE_THROW_IF(global_DoF_indices.size() < lagrange_points.size(), Exceptions::operator_error, "This should not happen, the range_space is broken:\n" << "global_DoF_indices.size() = " << global_DoF_indices.size() << "\n" << "lagrange_points.size() = " << lagrange_points.size()); for (size_t ii = 0; ii < lagrange_points.size(); ++ii) { const auto& lagrange_point = lagrange_points[ii]; const auto global_DoF_id = global_DoF_indices[ii]; const auto global_LP_id = global_DoF_id_to_global_LP_id_map_.at(global_DoF_id); const auto& DoFs_per_global_LP = global_LP_id_to_global_DoF_id_map_.at(global_LP_id); const auto source_value = local_source->evaluate(lagrange_point)[0] / DoFs_per_global_LP.size(); for (const auto& DoF_id : DoFs_per_global_LP) { range[DoF_id] += source_value; } } } // set Dirichlet DoFs to zero for (const auto& global_LP_id : boundary_LPs_) for (const auto& global_DoF_id : global_LP_id_to_global_DoF_id_map_.at(global_LP_id)) range[global_DoF_id] = 0; } // ... apply(...) private: const AssemblyGridViewType assembly_grid_view_; const SourceSpaceType& source_space_; const RangeSpaceType& range_space_; const XT::Common::ConstStorageProvider<XT::Grid::BoundaryInfo<I>> boundary_info_; bool assembled_; std::vector<size_t> global_DoF_id_to_global_LP_id_map_; std::vector<std::set<size_t>> global_LP_id_to_global_DoF_id_map_; std::set<size_t> boundary_LPs_; }; // class OswaldInterpolationOperator template <class MatrixType, class AssemblyGridView, class SGV, size_t dim, size_t dim_cols, class RGV> OswaldInterpolationOperator<MatrixType, AssemblyGridView, dim, dim_cols, SGV, RGV> make_oswald_interpolation_operator( const AssemblyGridView& assembly_grid_view, const SpaceInterface<SGV, dim, dim_cols>& source_space, const SpaceInterface<RGV, dim, dim_cols>& range_space, const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<AssemblyGridView>>& boundary_info) { return OswaldInterpolationOperator<MatrixType, AssemblyGridView, dim, dim_cols, SGV, RGV>( assembly_grid_view, source_space, range_space, boundary_info); } } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_OSWALD_INTERPOLATION_HH
46
120
0.713499
pymor
773c7908f97f90cedecdc644de87012e01b10b46
2,081
cpp
C++
MMOCoreORB/src/server/zone/objects/tangible/components/droid/DroidContainerComponent.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/src/server/zone/objects/tangible/components/droid/DroidContainerComponent.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/src/server/zone/objects/tangible/components/droid/DroidContainerComponent.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
/* * DroidContainerComponent.cpp */ #include "DroidContainerComponent.h" #include "server/zone/objects/scene/SceneObject.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/creature/ai/DroidObject.h" #include "server/zone/objects/player/PlayerObject.h" bool DroidContainerComponent::checkContainerPermission(SceneObject* sceneObject, CreatureObject* creature, uint16 permission) const { ManagedReference<SceneObject*> p = sceneObject->getParent().get(); if (p == nullptr || !p->isDroidObject()) { return false; } DroidObject* droid = p.castTo<DroidObject*>(); if(droid == nullptr){ return false; } if (!creature->getPlayerObject()->isPrivileged() && droid->getLinkedCreature() != creature){ return false; } if(permission == ContainerPermissions::MOVEIN){ return true; }else if (permission == ContainerPermissions::MOVEOUT ){ return true; } else if ( permission == ContainerPermissions::OPEN ) { return true; } return false; } int DroidContainerComponent::canAddObject(SceneObject* sceneObject, SceneObject* object, int containmentType, String& errorDescription) const { if (object->isContainerObject() && !object->isResourceContainer()) { errorDescription = "@container_error_message:container12"; return TransferErrorCode::INVALIDTYPE; } if (object->isControlDevice() || object->isInstallationObject() || object->isBuildingObject() || object->isCraftingStation()) { errorDescription = "@container_error_message:container12"; return TransferErrorCode::INVALIDTYPE; } if (object->isNoTrade() || object->containsNoTradeObjectRecursive()) { errorDescription = "@container_error_message:container28"; return TransferErrorCode::CANTADD; } ManagedReference<SceneObject*> p = sceneObject->getParent().get(); if (p) { DroidObject* droid = p.castTo<DroidObject*>(); if (droid) { if(!object->isASubChildOf(droid->getLinkedCreature().get())) { errorDescription = "@container_error_message:container14"; return TransferErrorCode::MUSTBEINPLAYERINVENTORY; } } } return 0; }
31.059701
143
0.742912
V-Fib
773f8f74951d2c6263fc0bf35317c8c35db15f4c
345
cpp
C++
ShaderGLLib/Image.cpp
anirul/ShaderGL-Classroom-2
f91a354588b09f34f6814e714cad015db2fa51e6
[ "MIT" ]
null
null
null
ShaderGLLib/Image.cpp
anirul/ShaderGL-Classroom-2
f91a354588b09f34f6814e714cad015db2fa51e6
[ "MIT" ]
null
null
null
ShaderGLLib/Image.cpp
anirul/ShaderGL-Classroom-2
f91a354588b09f34f6814e714cad015db2fa51e6
[ "MIT" ]
null
null
null
#include "Image.h" #include <algorithm> #include <fstream> #include <vector> #include <tuple> #include <assert.h> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> namespace sgl { Image::Image(const std::string& file) { #pragma message("Fill me up!") } Image::~Image() { #pragma message("Fill me up!") } } // End namespace sgl.
14.375
38
0.684058
anirul
774a459c11c5b4c69570340ea964d268e3db13b4
42,725
cpp
C++
src/caffe/test/test_gauss_convolution_layer.cpp
skokec/caffe
f6fd2961b9aa63d818212ee2490620fe0e703cc6
[ "BSD-2-Clause" ]
1
2021-05-16T08:35:43.000Z
2021-05-16T08:35:43.000Z
src/caffe/test/test_gauss_convolution_layer.cpp
skokec/caffe
f6fd2961b9aa63d818212ee2490620fe0e703cc6
[ "BSD-2-Clause" ]
null
null
null
src/caffe/test/test_gauss_convolution_layer.cpp
skokec/caffe
f6fd2961b9aa63d818212ee2490620fe0e703cc6
[ "BSD-2-Clause" ]
null
null
null
#include <boost/smart_ptr/shared_ptr.hpp> #include <caffe/blob.hpp> #include <caffe/common.hpp> #include <caffe/filler.hpp> #include <caffe/layers/gauss_conv_layer.hpp> #include <caffe/proto/caffe.pb.h> #include <caffe/test/test_caffe_main.hpp> #include <glog/logging.h> #include <gtest/gtest.h> #include <vector> namespace caffe { template <typename Dtype> void compare_blobs(Blob<Dtype>& a, Blob<Dtype>& b, bool compare_diff, Dtype eps) { Dtype* data_a = compare_diff ? a.mutable_cpu_diff() : a.mutable_cpu_data(); Dtype* data_b = compare_diff ? b.mutable_cpu_diff() : b.mutable_cpu_data(); for (int i = 0; i < a.count(); ++i) { EXPECT_NEAR(data_a[i], data_b[i], eps); } } // Reference convolution for checking results: // accumulate through explicit loops over input, output, and filters. template <typename Dtype> void caffe_conv(const Blob<Dtype>* in, ConvolutionParameter* conv_param, const vector<shared_ptr<Blob<Dtype> > >& weights, Blob<Dtype>* out) { const bool has_depth = (out->num_axes() == 5); if (!has_depth) { CHECK_EQ(4, out->num_axes()); } // Kernel size, stride, and pad int kernel_h, kernel_w; if (conv_param->has_kernel_h() || conv_param->has_kernel_w()) { kernel_h = conv_param->kernel_h(); kernel_w = conv_param->kernel_w(); } else { kernel_h = kernel_w = conv_param->kernel_size(0); } int pad_h, pad_w; if (conv_param->has_pad_h() || conv_param->has_pad_w()) { pad_h = conv_param->pad_h(); pad_w = conv_param->pad_w(); } else { pad_h = pad_w = conv_param->pad_size() ? conv_param->pad(0) : 0; } int stride_h, stride_w; if (conv_param->has_stride_h() || conv_param->has_stride_w()) { stride_h = conv_param->stride_h(); stride_w = conv_param->stride_w(); } else { stride_h = stride_w = conv_param->stride_size() ? conv_param->stride(0) : 1; } int kernel_d, pad_d, stride_d; if (has_depth) { kernel_d = kernel_h; stride_d = stride_h; pad_d = pad_h; } else { kernel_d = stride_d = 1; pad_d = 0; } // Groups int groups = conv_param->group(); int o_g = out->shape(1) / groups; int k_g = in->shape(1) / groups; int o_head, k_head; // Convolution vector<int> weight_offset(4 + has_depth); vector<int> in_offset(4 + has_depth); vector<int> out_offset(4 + has_depth); Dtype* out_data = out->mutable_cpu_data(); for (int n = 0; n < out->shape(0); n++) { for (int g = 0; g < groups; g++) { o_head = o_g * g; k_head = k_g * g; for (int o = 0; o < o_g; o++) { for (int k = 0; k < k_g; k++) { for (int z = 0; z < (has_depth ? out->shape(2) : 1); z++) { for (int y = 0; y < out->shape(2 + has_depth); y++) { for (int x = 0; x < out->shape(3 + has_depth); x++) { for (int r = 0; r < kernel_d; r++) { for (int p = 0; p < kernel_h; p++) { for (int q = 0; q < kernel_w; q++) { int in_z = z * stride_d - pad_d + r; int in_y = y * stride_h - pad_h + p; int in_x = x * stride_w - pad_w + q; if (in_z >= 0 && in_z < (has_depth ? in->shape(2) : 1) && in_y >= 0 && in_y < in->shape(2 + has_depth) && in_x >= 0 && in_x < in->shape(3 + has_depth)) { weight_offset[0] = o + o_head; weight_offset[1] = k; if (has_depth) { weight_offset[2] = r; } weight_offset[2 + has_depth] = p; weight_offset[3 + has_depth] = q; in_offset[0] = n; in_offset[1] = k + k_head; if (has_depth) { in_offset[2] = in_z; } in_offset[2 + has_depth] = in_y; in_offset[3 + has_depth] = in_x; out_offset[0] = n; out_offset[1] = o + o_head; if (has_depth) { out_offset[2] = z; } out_offset[2 + has_depth] = y; out_offset[3 + has_depth] = x; out_data[out->offset(out_offset)] += in->data_at(in_offset) * weights[0]->data_at(weight_offset); } } } } } } } } } } } // Bias if (conv_param->bias_term()) { const Dtype* bias_data = weights[1]->cpu_data(); for (int n = 0; n < out->shape(0); n++) { for (int o = 0; o < out->shape(1); o++) { for (int z = 0; z < (has_depth ? out->shape(2) : 1); z++) { for (int y = 0; y < out->shape(2 + has_depth); y++) { for (int x = 0; x < out->shape(3 + has_depth); x++) { out_offset[0] = n; out_offset[1] = o; if (has_depth) { out_offset[2] = z; } out_offset[2 + has_depth] = y; out_offset[3 + has_depth] = x; out_data[out->offset(out_offset)] += bias_data[o]; } } } } } } } template void caffe_conv(const Blob<float>* in, ConvolutionParameter* conv_param, const vector<shared_ptr<Blob<float> > >& weights, Blob<float>* out); template void caffe_conv(const Blob<double>* in, ConvolutionParameter* conv_param, const vector<shared_ptr<Blob<double> > >& weights, Blob<double>* out); template <typename TypeParam> class GaussConvolutionLayerTest : public MultiDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: GaussConvolutionLayerTest() : blob_bottom_(new Blob<Dtype>(2, 3, 6, 4)), blob_bottom_2_(new Blob<Dtype>(2, 3, 6, 4)), blob_bottom_3_(new Blob<Dtype>(1, 1, 4, 4)), //blob_bottom_3_(new Blob<Dtype>(2, 3, 32, 48)), blob_top_(new Blob<Dtype>()), blob_top_2_(new Blob<Dtype>()), blob_top_3_(new Blob<Dtype>()) {} virtual void SetUp() { // fill the values FillerParameter filler_param; filler_param.set_value(1.); GaussianFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); filler.Fill(this->blob_bottom_2_); filler.Fill(this->blob_bottom_3_); blob_bottom_vec_.push_back(blob_bottom_); blob_top_vec_.push_back(blob_top_); } virtual ~GaussConvolutionLayerTest() { delete blob_bottom_; delete blob_bottom_2_; delete blob_bottom_3_; delete blob_top_; delete blob_top_2_; delete blob_top_3_; } virtual Blob<Dtype>* MakeReferenceTop(Blob<Dtype>* top) { this->ref_blob_top_.reset(new Blob<Dtype>()); this->ref_blob_top_->ReshapeLike(*top); return this->ref_blob_top_.get(); } Blob<Dtype>* const blob_bottom_; Blob<Dtype>* const blob_bottom_2_; Blob<Dtype>* const blob_bottom_3_; Blob<Dtype>* const blob_top_; Blob<Dtype>* const blob_top_2_; Blob<Dtype>* const blob_top_3_; shared_ptr<Blob<Dtype> > ref_blob_top_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; }; TYPED_TEST_CASE(GaussConvolutionLayerTest, TestDtypesAndDevices); TYPED_TEST(GaussConvolutionLayerTest, TestSetup) { /*typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(4); this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); shared_ptr<Layer<Dtype> > layer( new GaussianConvLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); EXPECT_EQ(this->blob_top_->num(), 2); EXPECT_EQ(this->blob_top_->channels(), 4); EXPECT_EQ(this->blob_top_->height(), 2); EXPECT_EQ(this->blob_top_->width(), 1); EXPECT_EQ(this->blob_top_2_->num(), 2); EXPECT_EQ(this->blob_top_2_->channels(), 4); EXPECT_EQ(this->blob_top_2_->height(), 2); EXPECT_EQ(this->blob_top_2_->width(), 1); // setting group should not change the shape convolution_param->set_num_output(3); convolution_param->set_group(3); layer.reset(new ConvolutionLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); EXPECT_EQ(this->blob_top_->num(), 2); EXPECT_EQ(this->blob_top_->channels(), 3); EXPECT_EQ(this->blob_top_->height(), 2); EXPECT_EQ(this->blob_top_->width(), 1); EXPECT_EQ(this->blob_top_2_->num(), 2); EXPECT_EQ(this->blob_top_2_->channels(), 3); EXPECT_EQ(this->blob_top_2_->height(), 2); EXPECT_EQ(this->blob_top_2_->width(), 1);*/ } /* TYPED_TEST(GaussConvolutionLayerTest, TestSimpleConvolution) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); LayerParameter layer_param; ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(7); convolution_param->add_stride(1); convolution_param->add_pad(3); convolution_param->set_number_gauss(2); convolution_param->set_num_output(16); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_weight_filler()->set_std(0.01); convolution_param->mutable_bias_filler()->set_type("constant"); convolution_param->mutable_bias_filler()->set_value(0.1); convolution_param->mutable_sigma_filler()->set_type("constant"); convolution_param->mutable_sigma_filler()->set_value(0.8); convolution_param->set_gmm_component_border_bound(1.5); convolution_param->set_gmm_sigma_lower_bound(0.5); convolution_param->set_gmm_weight_normalization(false); convolution_param->set_gmm_gauss_normalization(true); convolution_param->set_gmm_square_gauss_normalization(true); shared_ptr<Layer<Dtype> > layer( new GaussianConvLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Check against reference convolution. const Dtype* top_data; const Dtype* ref_top_data; caffe_conv(this->blob_bottom_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_)); top_data = this->blob_top_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], 1e-4); } caffe_conv(this->blob_bottom_2_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_2_)); top_data = this->blob_top_2_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], 1e-4); } } */ TYPED_TEST(GaussConvolutionLayerTest, TestKernelPrecompute) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); LayerParameter layer_param; ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(7); convolution_param->add_stride(1); convolution_param->add_pad(3); convolution_param->set_number_gauss(2); convolution_param->set_num_output(32); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_weight_filler()->set_std(0.01); convolution_param->mutable_bias_filler()->set_type("constant"); convolution_param->mutable_bias_filler()->set_value(0.1); convolution_param->mutable_sigma_filler()->set_type("constant"); convolution_param->mutable_sigma_filler()->set_value(0.8); convolution_param->set_gmm_component_border_bound(1.5); convolution_param->set_gmm_sigma_lower_bound(0.5); convolution_param->set_gmm_weight_normalization(false); convolution_param->set_gmm_gauss_normalization(true); for (int gmm_sqrt_norm = 0; gmm_sqrt_norm <= 1; gmm_sqrt_norm++) { convolution_param->set_gmm_square_gauss_normalization((bool)gmm_sqrt_norm); shared_ptr<GaussianConvLayer<Dtype> > layer(new GaussianConvLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); // RUN CPU version layer->precompute_guassian_weights(true); // run CPU first since it will force buffers to cpu and would cause errors if gpu would be allocated first // store output Blob<Dtype> weight_cpu, deriv_error_cpu, deriv_weight_cpu, deriv_mu1_cpu, deriv_mu2_cpu, deriv_sigma_cpu; weight_cpu.CopyFrom(*layer->weight_buffer_, false, true); deriv_error_cpu.CopyFrom(*layer->deriv_error_buffer_, false, true); deriv_weight_cpu.CopyFrom(*layer->deriv_weight_buffer_, false, true); deriv_mu1_cpu.CopyFrom(*layer->deriv_mu1_buffer_, false, true); deriv_mu2_cpu.CopyFrom(*layer->deriv_mu2_buffer_, false, true); deriv_sigma_cpu.CopyFrom(*layer->deriv_sigma_buffer_, false, true); // RUN CPU version layer->precompute_guassian_weights_gpu(true); // Check both versions Dtype* data_gpu; Dtype* data_cpu; data_cpu = weight_cpu.mutable_cpu_data(); data_gpu = layer->weight_buffer_->mutable_cpu_data(); for (int i = 0; i < weight_cpu.count(); ++i) { EXPECT_NEAR(data_gpu[i], data_cpu[i], 1e-4); } data_cpu = deriv_error_cpu.mutable_cpu_data(); data_gpu = layer->deriv_error_buffer_->mutable_cpu_data(); for (int i = 0; i < deriv_error_cpu.count(); ++i) { EXPECT_NEAR(data_gpu[i], data_cpu[i], 1e-4); } data_cpu = deriv_weight_cpu.mutable_cpu_data(); data_gpu = layer->deriv_weight_buffer_->mutable_cpu_data(); for (int i = 0; i < deriv_weight_cpu.count(); ++i) { EXPECT_NEAR(data_gpu[i], data_cpu[i], 1e-4); } data_cpu = deriv_mu1_cpu.mutable_cpu_data(); data_gpu = layer->deriv_mu1_buffer_->mutable_cpu_data(); for (int i = 0; i < deriv_mu1_cpu.count(); ++i) { EXPECT_NEAR(data_gpu[i], data_cpu[i], 1e-4); } data_cpu = deriv_mu2_cpu.mutable_cpu_data(); data_gpu = layer->deriv_mu2_buffer_->mutable_cpu_data(); for (int i = 0; i < deriv_mu2_cpu.count(); ++i) { EXPECT_NEAR(data_gpu[i], data_cpu[i], 1e-4); } data_cpu = deriv_sigma_cpu.mutable_cpu_data(); data_gpu = layer->deriv_sigma_buffer_->mutable_cpu_data(); for (int i = 0; i < deriv_sigma_cpu.count(); ++i) { EXPECT_NEAR(data_gpu[i], data_cpu[i], 1e-4); } } } TYPED_TEST(GaussConvolutionLayerTest, TestSeperableConvolution) { if (Caffe::mode() == Caffe::GPU) return; typedef typename TypeParam::Dtype Dtype; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; blob_bottom_vec_.push_back(this->blob_bottom_3_); blob_top_vec_.push_back(this->blob_top_3_); LayerParameter layer_param; ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(7); convolution_param->add_stride(1); convolution_param->add_pad(3); convolution_param->set_number_gauss(2); convolution_param->set_num_output(16); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_weight_filler()->set_std(0.01); convolution_param->mutable_bias_filler()->set_type("constant"); convolution_param->mutable_bias_filler()->set_value(0.1); convolution_param->mutable_sigma_filler()->set_type("constant"); convolution_param->mutable_sigma_filler()->set_value(0.8); convolution_param->set_gmm_component_border_bound(1.5); convolution_param->set_gmm_sigma_lower_bound(0.5); convolution_param->set_gmm_weight_normalization(false); convolution_param->set_gmm_gauss_normalization(true); for (int gmm_sqrt_norm = 0; gmm_sqrt_norm < 1; gmm_sqrt_norm++) { convolution_param->set_gmm_square_gauss_normalization((bool)gmm_sqrt_norm); convolution_param->set_gmm_seperable_forward_pass(false); shared_ptr<GaussianConvLayer<Dtype> > layer(new GaussianConvLayer<Dtype>(layer_param)); layer->SetUp(blob_bottom_vec_, blob_top_vec_); // RUN non-seperable layer->Forward(blob_bottom_vec_, blob_top_vec_); // store output Blob<Dtype> top_org; top_org.CopyFrom(*blob_top_vec_[0], false, true); layer->use_gmm_seperable_kernels = true; // RUN seperable version layer->Forward(blob_bottom_vec_, blob_top_vec_); // Check both versions Dtype* data_non_sep = top_org.mutable_cpu_data(); Dtype* data_sep = blob_top_vec_[0]->mutable_cpu_data(); for (int i = 0; i < top_org.count(); ++i) { EXPECT_NEAR(data_non_sep[i], data_sep[i], 1e-4); } Dtype* data_diff = top_org.mutable_cpu_diff(); caffe_sub(top_org.count(), data_non_sep, data_sep, data_diff); Dtype mean_error = caffe_cpu_asum(top_org.count(), data_diff) /top_org.count(); EXPECT_NEAR(mean_error, 0, 1e-4); } } TYPED_TEST(GaussConvolutionLayerTest, TestCuDNNConvolution) { if (Caffe::mode() == Caffe::CPU) return; typedef typename TypeParam::Dtype Dtype; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; vector<Blob<Dtype>*> blob_bottom_vec_org_; vector<Blob<Dtype>*> blob_top_vec_org_; vector<bool> propagate_down; if (sizeof(Dtype) > 4) return; propagate_down.push_back(true); blob_bottom_vec_.push_back(this->blob_bottom_3_); blob_top_vec_.push_back(this->blob_top_3_); FillerParameter filler_param; filler_param.set_value(0.1); Blob<Dtype>* blob_top_diff = new Blob<Dtype>(); Blob<Dtype>* blob_bottom_3_org_ = new Blob<Dtype>(); Blob<Dtype>* blob_top_3_org_ = new Blob<Dtype>(); blob_bottom_3_org_->CopyFrom(*this->blob_bottom_3_, false, true); blob_bottom_vec_org_.push_back(blob_bottom_3_org_); blob_top_vec_org_.push_back(blob_top_3_org_); LayerParameter layer_param; ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(1); convolution_param->add_pad(1); convolution_param->set_number_gauss(2); convolution_param->set_num_output(8); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_weight_filler()->set_std(0.01); convolution_param->mutable_bias_filler()->set_type("constant"); convolution_param->mutable_bias_filler()->set_value(0.1); convolution_param->mutable_sigma_filler()->set_type("constant"); convolution_param->mutable_sigma_filler()->set_value(0.8); convolution_param->set_gmm_component_border_bound(1.5); convolution_param->set_gmm_sigma_lower_bound(0.5); convolution_param->set_gmm_weight_normalization(false); convolution_param->set_gmm_gauss_normalization(true); for (int gmm_sqrt_norm = 0; gmm_sqrt_norm < 1; gmm_sqrt_norm++) { convolution_param->set_gmm_square_gauss_normalization((bool)gmm_sqrt_norm); shared_ptr<BaseGaussianConvLayer<Dtype> > layer(new CuDNNGaussianConvLayer<Dtype>(layer_param)); shared_ptr<BaseGaussianConvLayer<Dtype> > layer_org(new GaussianConvLayer<Dtype>(layer_param)); layer->SetUp(blob_bottom_vec_, blob_top_vec_); layer_org->SetUp(blob_bottom_vec_org_, blob_top_vec_org_); layer_org->param_buffer_w_->CopyFrom(*layer->param_buffer_w_, false, false); layer_org->param_buffer_mu1_->CopyFrom(*layer->param_buffer_mu1_, false, false); layer_org->param_buffer_mu2_->CopyFrom(*layer->param_buffer_mu2_, false, false); layer_org->param_buffer_sigma_->CopyFrom(*layer->param_buffer_sigma_, false, false); layer_org->param_buffer_bias_->CopyFrom(*layer->param_buffer_bias_, false, false); // RUN forward layer->Forward(blob_bottom_vec_, blob_top_vec_); layer_org->Forward(blob_bottom_vec_org_, blob_top_vec_org_); blob_top_diff->ReshapeLike(*blob_top_vec_[0]); GaussianFiller<Dtype> filler(filler_param); filler.Fill(blob_top_diff); caffe_copy( blob_top_vec_[0]->count(), blob_top_diff->cpu_data(), blob_top_vec_[0]->mutable_cpu_diff()); blob_top_vec_[0]->cpu_data(); blob_top_vec_[0]->gpu_diff(); blob_top_vec_org_[0]->CopyFrom(*blob_top_vec_[0], true, true); // blob_top_vec_org_[0]->cpu_diff(); const Dtype* gpu_data = blob_top_vec_[0]->cpu_data(); const Dtype* cpu_data = blob_top_vec_org_[0]->cpu_data(); for (int i = 0; i < blob_top_vec_[0]->count(); ++i) { EXPECT_NEAR(gpu_data[i], cpu_data[i], 1e-4); } // set all back-propagated error values to 1 to ease debugging // caffe_gpu_set(blob_top_vec_org_[0]->count(), (Dtype)3.0, blob_top_vec_org_[0]->mutable_gpu_diff()); // caffe_gpu_set(blob_top_vec_[0]->count(), (Dtype)3.0, blob_top_vec_[0]->mutable_gpu_diff()); // caffe_gpu_set(blob_bottom_vec_org_[0]->count(), (Dtype)2.0, blob_bottom_vec_org_[0]->mutable_gpu_data()); // caffe_gpu_set(blob_bottom_vec_[0]->count(), (Dtype)2.0, blob_bottom_vec_[0]->mutable_gpu_data()); // RUN backward layer->Backward(blob_top_vec_, propagate_down, blob_bottom_vec_); layer_org->Backward(blob_top_vec_org_, propagate_down, blob_bottom_vec_org_); const Dtype* gpu_diff = blob_bottom_vec_[0]->cpu_diff(); const Dtype* cpu_diff = blob_bottom_vec_org_[0]->cpu_diff(); for (int i = 0; i < blob_bottom_vec_[0]->count(); ++i) { EXPECT_NEAR(gpu_diff[i], cpu_diff[i], 1e-4); } // layer->param_buffer_w_->cpu_data(); // layer_org->param_buffer_w_->cpu_data(); compare_blobs(*layer->param_buffer_w_, *layer_org->param_buffer_w_, true, (Dtype)1e-4); compare_blobs(*layer->param_buffer_mu1_, *layer_org->param_buffer_mu1_, true, (Dtype)1e-4); compare_blobs(*layer->param_buffer_mu2_, *layer_org->param_buffer_mu2_, true, (Dtype)1e-4); compare_blobs(*layer->param_buffer_sigma_, *layer_org->param_buffer_sigma_, true, (Dtype)1e-4); } delete blob_bottom_3_org_; delete blob_top_3_org_; delete blob_top_diff; } TYPED_TEST(GaussConvolutionLayerTest, TestCuDNNConvolutionExtensive) { if (Caffe::mode() == Caffe::CPU) return; typedef typename TypeParam::Dtype Dtype; if (sizeof(Dtype) > 4) return; // run with different combinations of settings // num images: 1, 2, 3, 5, 8, 11 // num subfeatures: 1, 2, 3, 5, 8, 11 // width: 4, 9, 16, 32, 33, // height: 4, 9, 16, 32, 33, // num features: 4, 6, 8, 16 // num gauss: 2,3,4 vector<int> num_imgs_args = {1, 11}; vector<int> num_subfeat_args = {1, 2, 3, 8, 11}; vector<int> width_args = {4, 9, 32, 33}; vector<int> height_args = {4, 9, 32, 33,}; vector<int> num_feat_args = {4, 16}; vector<int> num_gauss_args = {2,3,4}; // do not forget, this is squared, so in effect with 4,9 and 16 gauss per filter for (int img_i = 0; img_i < num_imgs_args.size(); ++img_i) { for (int subfeat_i = 0; subfeat_i < num_subfeat_args.size(); ++subfeat_i) { for (int width_i = 0; width_i < width_args.size(); ++width_i) { for (int height_i = 0; height_i < height_args.size(); ++height_i) { for (int feat_i = 0; feat_i < num_feat_args.size(); ++feat_i) { for (int gauss_i = 0; gauss_i < num_gauss_args.size(); ++gauss_i) { int num_imgs = num_imgs_args[img_i]; int num_subfeat = num_subfeat_args[subfeat_i]; int width = width_args[width_i]; int height = height_args[height_i]; int num_feat = num_feat_args[feat_i]; int num_gauss = num_gauss_args[gauss_i]; std::cout << "testing num_imgs " << num_imgs << ", num_subfeat " << num_subfeat << ", width " << width << ", height " << height << ", num_feat " << num_feat << ",num_gauss " << num_gauss << std::endl; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; vector<Blob<Dtype>*> blob_bottom_vec_org_; vector<Blob<Dtype>*> blob_top_vec_org_; vector<bool> propagate_down; Blob<Dtype>* blob_bottom_3_ = new Blob<Dtype>(num_imgs, num_subfeat, height, width); Blob<Dtype>* blob_top_3_ = new Blob<Dtype>(); { FillerParameter filler_param; filler_param.set_value(1.); GaussianFiller<Dtype> filler(filler_param); filler.Fill(blob_bottom_3_); } propagate_down.push_back(true); blob_bottom_vec_.push_back(blob_bottom_3_); blob_top_vec_.push_back(blob_top_3_); FillerParameter filler_param; filler_param.set_value(0.1); Blob<Dtype>* blob_top_diff = new Blob<Dtype>(); Blob<Dtype>* blob_bottom_3_org_ = new Blob<Dtype>(); Blob<Dtype>* blob_top_3_org_ = new Blob<Dtype>(); blob_bottom_3_org_->CopyFrom(*blob_bottom_3_, false, true); blob_bottom_vec_org_.push_back(blob_bottom_3_org_); blob_top_vec_org_.push_back(blob_top_3_org_); LayerParameter layer_param; ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(1); convolution_param->add_pad(1); convolution_param->set_number_gauss(num_gauss); convolution_param->set_num_output(num_feat); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_weight_filler()->set_std(0.01); convolution_param->mutable_bias_filler()->set_type("constant"); convolution_param->mutable_bias_filler()->set_value(0.1); convolution_param->mutable_sigma_filler()->set_type("constant"); convolution_param->mutable_sigma_filler()->set_value(0.8); convolution_param->set_gmm_component_border_bound(1.5); convolution_param->set_gmm_sigma_lower_bound(0.5); convolution_param->set_gmm_weight_normalization(false); convolution_param->set_gmm_gauss_normalization(true); for (int gmm_sqrt_norm = 0; gmm_sqrt_norm < 1; gmm_sqrt_norm++) { convolution_param->set_gmm_square_gauss_normalization((bool)gmm_sqrt_norm); shared_ptr<BaseGaussianConvLayer<Dtype> > layer(new CuDNNGaussianConvLayer<Dtype>(layer_param)); shared_ptr<BaseGaussianConvLayer<Dtype> > layer_org(new GaussianConvLayer<Dtype>(layer_param)); layer->SetUp(blob_bottom_vec_, blob_top_vec_); layer_org->SetUp(blob_bottom_vec_org_, blob_top_vec_org_); layer_org->param_buffer_w_->CopyFrom(*layer->param_buffer_w_, false, false); layer_org->param_buffer_mu1_->CopyFrom(*layer->param_buffer_mu1_, false, false); layer_org->param_buffer_mu2_->CopyFrom(*layer->param_buffer_mu2_, false, false); layer_org->param_buffer_sigma_->CopyFrom(*layer->param_buffer_sigma_, false, false); layer_org->param_buffer_bias_->CopyFrom(*layer->param_buffer_bias_, false, false); // RUN forward layer->Forward(blob_bottom_vec_, blob_top_vec_); layer_org->Forward(blob_bottom_vec_org_, blob_top_vec_org_); blob_top_diff->ReshapeLike(*blob_top_vec_[0]); GaussianFiller<Dtype> filler(filler_param); filler.Fill(blob_top_diff); caffe_copy( blob_top_vec_[0]->count(), blob_top_diff->cpu_data(), blob_top_vec_[0]->mutable_cpu_diff()); blob_top_vec_[0]->cpu_data(); blob_top_vec_[0]->gpu_diff(); blob_top_vec_org_[0]->CopyFrom(*blob_top_vec_[0], true, true); // blob_top_vec_org_[0]->cpu_diff(); const Dtype* gpu_data = blob_top_vec_[0]->cpu_data(); const Dtype* cpu_data = blob_top_vec_org_[0]->cpu_data(); for (int i = 0; i < blob_top_vec_[0]->count(); ++i) { EXPECT_NEAR(gpu_data[i], cpu_data[i], 1e-4); } // set all back-propagated error values to 1 to ease debugging //caffe_gpu_set(blob_top_vec_org_[0]->count(), (Dtype)1.0, blob_top_vec_org_[0]->mutable_gpu_diff()); //caffe_gpu_set(blob_top_vec_[0]->count(), (Dtype)1.0, blob_top_vec_[0]->mutable_gpu_diff()); // RUN backward layer->Backward(blob_top_vec_, propagate_down, blob_bottom_vec_); layer_org->Backward(blob_top_vec_org_, propagate_down, blob_bottom_vec_org_); const Dtype* gpu_diff = blob_bottom_vec_[0]->cpu_diff(); const Dtype* cpu_diff = blob_bottom_vec_org_[0]->cpu_diff(); for (int i = 0; i < blob_bottom_vec_[0]->count(); ++i) { EXPECT_NEAR(gpu_diff[i], cpu_diff[i], 1e-4); } // layer->param_buffer_w_->cpu_data(); // layer_org->param_buffer_w_->cpu_data(); compare_blobs(*layer->param_buffer_w_, *layer_org->param_buffer_w_, true, (Dtype)1e-4); compare_blobs(*layer->param_buffer_mu1_, *layer_org->param_buffer_mu1_, true, (Dtype)1e-4); compare_blobs(*layer->param_buffer_mu2_, *layer_org->param_buffer_mu2_, true, (Dtype)1e-4); compare_blobs(*layer->param_buffer_sigma_, *layer_org->param_buffer_sigma_, true, (Dtype)1e-4); } delete blob_top_3_; delete blob_bottom_3_; delete blob_bottom_3_org_; delete blob_top_3_org_; delete blob_top_diff; } } } } } } } /* TYPED_TEST(GaussConvolutionLayerTest, Test0DConvolution) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); const int kNumOutput = 3; convolution_param->set_num_output(kNumOutput); convolution_param->set_axis(3); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); shared_ptr<Layer<Dtype> > layer( new ConvolutionLayer<Dtype>(layer_param)); vector<int> top_shape = this->blob_bottom_->shape(); top_shape[3] = kNumOutput; layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); EXPECT_EQ(top_shape, this->blob_top_->shape()); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Check against reference convolution. vector<int> weight_offset(2); const Blob<Dtype>* weight = layer->blobs()[0].get(); const Blob<Dtype>* bias = layer->blobs()[1].get(); const int num = this->blob_top_->count(3); const int dim = this->blob_top_->shape(3); const int bottom_dim = this->blob_bottom_->shape(3); for (int n = 0; n < num; ++n) { for (int d = 0; d < dim; ++d) { weight_offset[0] = d; Dtype value = bias->cpu_data()[d]; for (int bottom_d = 0; bottom_d < bottom_dim; ++bottom_d) { weight_offset[1] = bottom_d; value += weight->data_at(weight_offset) * this->blob_bottom_->cpu_data()[n * bottom_dim + bottom_d]; } EXPECT_NEAR(value, this->blob_top_->cpu_data()[n * dim + d], 1e-4); } } } TYPED_TEST(GaussConvolutionLayerTest, TestSimple3DConvolution) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); vector<int> bottom_shape(5); bottom_shape[0] = this->blob_bottom_vec_[0]->shape(0); bottom_shape[1] = this->blob_bottom_vec_[0]->shape(1); bottom_shape[2] = 5; bottom_shape[3] = this->blob_bottom_vec_[0]->shape(2); bottom_shape[4] = this->blob_bottom_vec_[0]->shape(3); FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); for (int i = 0; i < this->blob_bottom_vec_.size(); ++i) { this->blob_bottom_vec_[i]->Reshape(bottom_shape); filler.Fill(this->blob_bottom_vec_[i]); } LayerParameter layer_param; ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(4); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); shared_ptr<Layer<Dtype> > layer( new ConvolutionLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Check against reference convolution. const Dtype* top_data; const Dtype* ref_top_data; caffe_conv(this->blob_bottom_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_)); top_data = this->blob_top_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], 1e-4); } caffe_conv(this->blob_bottom_2_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_2_)); top_data = this->blob_top_2_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], 1e-4); } } TYPED_TEST(GaussConvolutionLayerTest, Test1x1Convolution) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(1); convolution_param->add_stride(1); convolution_param->set_num_output(4); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("constant"); convolution_param->mutable_bias_filler()->set_value(0.1); shared_ptr<Layer<Dtype> > layer( new ConvolutionLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Check against reference convolution. const Dtype* top_data; const Dtype* ref_top_data; caffe_conv(this->blob_bottom_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_)); top_data = this->blob_top_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], 1e-4); } } TYPED_TEST(GaussConvolutionLayerTest, TestSimpleConvolutionGroup) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(3); convolution_param->set_group(3); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("constant"); convolution_param->mutable_bias_filler()->set_value(0.1); shared_ptr<Layer<Dtype> > layer( new ConvolutionLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Check against reference convolution. const Dtype* top_data; const Dtype* ref_top_data; caffe_conv(this->blob_bottom_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_)); top_data = this->blob_top_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], 1e-4); } } TYPED_TEST(GaussConvolutionLayerTest, TestNDAgainst2D) { typedef typename TypeParam::Dtype Dtype; const int kernel_h = 11; const int kernel_w = 13; vector<int> bottom_shape(4); bottom_shape[0] = 15; bottom_shape[1] = 18; bottom_shape[2] = kernel_h * 2; bottom_shape[3] = kernel_w * 2; FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); for (int i = 0; i < this->blob_bottom_vec_.size(); ++i) { this->blob_bottom_vec_[i]->Reshape(bottom_shape); filler.Fill(this->blob_bottom_vec_[i]); } LayerParameter layer_param; ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->set_num_output(12); convolution_param->set_bias_term(false); convolution_param->set_group(6); convolution_param->set_kernel_h(kernel_h); convolution_param->set_kernel_w(kernel_w); convolution_param->mutable_weight_filler()->set_type("gaussian"); Blob<Dtype> weights; Blob<Dtype> top_diff; // Shape and fill weights and top_diff. bool copy_diff; bool reshape; { ConvolutionLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); top_diff.ReshapeLike(*this->blob_top_); filler.Fill(&top_diff); ASSERT_EQ(1, layer.blobs().size()); copy_diff = false; reshape = true; weights.CopyFrom(*layer.blobs()[0], copy_diff, reshape); } vector<bool> propagate_down(1, true); Blob<Dtype> result_2d; Blob<Dtype> backward_result_2d; Blob<Dtype> backward_weight_result_2d; // Test with 2D im2col { caffe_set(this->blob_top_->count(), Dtype(0), this->blob_top_->mutable_cpu_data()); caffe_set(this->blob_bottom_->count(), Dtype(0), this->blob_bottom_->mutable_cpu_diff()); caffe_set(weights.count(), Dtype(0), weights.mutable_cpu_diff()); // Do SetUp and Forward; save Forward result in result_2d. convolution_param->set_force_nd_im2col(false); ConvolutionLayer<Dtype> layer_2d(layer_param); layer_2d.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); ASSERT_EQ(1, layer_2d.blobs().size()); copy_diff = false; reshape = false; layer_2d.blobs()[0]->CopyFrom(weights, copy_diff, reshape); layer_2d.Forward(this->blob_bottom_vec_, this->blob_top_vec_); copy_diff = false; reshape = true; result_2d.CopyFrom(*this->blob_top_, copy_diff, reshape); // Copy pre-generated top diff into actual top diff; // do Backward and save result in backward_result_2d. ASSERT_EQ(this->blob_top_->shape(), top_diff.shape()); caffe_copy(top_diff.count(), top_diff.cpu_data(), this->blob_top_->mutable_cpu_diff()); layer_2d.Backward(this->blob_top_vec_, propagate_down, this->blob_bottom_vec_); copy_diff = true; reshape = true; backward_result_2d.CopyFrom(*this->blob_bottom_, copy_diff, reshape); backward_weight_result_2d.CopyFrom(weights, copy_diff, reshape); } Blob<Dtype> result_nd; Blob<Dtype> backward_result_nd; Blob<Dtype> backward_weight_result_nd; // Test with ND im2col { caffe_set(this->blob_top_->count(), Dtype(0), this->blob_top_->mutable_cpu_data()); caffe_set(this->blob_bottom_->count(), Dtype(0), this->blob_bottom_->mutable_cpu_diff()); caffe_set(weights.count(), Dtype(0), weights.mutable_cpu_diff()); // Do SetUp and Forward; save Forward result in result_nd. convolution_param->set_force_nd_im2col(true); ConvolutionLayer<Dtype> layer_nd(layer_param); layer_nd.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); ASSERT_EQ(1, layer_nd.blobs().size()); copy_diff = false; reshape = false; layer_nd.blobs()[0]->CopyFrom(weights, copy_diff, reshape); layer_nd.Forward(this->blob_bottom_vec_, this->blob_top_vec_); copy_diff = false; reshape = true; result_nd.CopyFrom(*this->blob_top_, copy_diff, reshape); // Copy pre-generated top diff into actual top diff; // do Backward and save result in backward_result_nd. ASSERT_EQ(this->blob_top_->shape(), top_diff.shape()); caffe_copy(top_diff.count(), top_diff.cpu_data(), this->blob_top_->mutable_cpu_diff()); layer_nd.Backward(this->blob_top_vec_, propagate_down, this->blob_bottom_vec_); copy_diff = true; reshape = true; backward_result_nd.CopyFrom(*this->blob_bottom_, copy_diff, reshape); backward_weight_result_nd.CopyFrom(weights, copy_diff, reshape); } ASSERT_EQ(result_nd.count(), result_2d.count()); for (int i = 0; i < result_2d.count(); ++i) { EXPECT_EQ(result_2d.cpu_data()[i], result_nd.cpu_data()[i]); } ASSERT_EQ(backward_result_nd.count(), backward_result_2d.count()); for (int i = 0; i < backward_result_2d.count(); ++i) { EXPECT_EQ(backward_result_2d.cpu_diff()[i], backward_result_nd.cpu_diff()[i]); } ASSERT_EQ(backward_weight_result_nd.count(), backward_weight_result_2d.count()); for (int i = 0; i < backward_weight_result_2d.count(); ++i) { EXPECT_EQ(backward_weight_result_2d.cpu_diff()[i], backward_weight_result_nd.cpu_diff()[i]); } } TYPED_TEST(GaussConvolutionLayerTest, TestGradient) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(2); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); ConvolutionLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-3); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(GaussConvolutionLayerTest, TestGradient3D) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); vector<int> bottom_shape(5); bottom_shape[0] = this->blob_bottom_vec_[0]->shape(0); bottom_shape[1] = this->blob_bottom_vec_[0]->shape(1); bottom_shape[2] = 5; bottom_shape[3] = this->blob_bottom_vec_[0]->shape(2); bottom_shape[4] = this->blob_bottom_vec_[0]->shape(3); FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); for (int i = 0; i < this->blob_bottom_vec_.size(); ++i) { this->blob_bottom_vec_[i]->Reshape(bottom_shape); filler.Fill(this->blob_bottom_vec_[i]); } convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(2); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); ConvolutionLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-3); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(GaussConvolutionLayerTest, Test1x1Gradient) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); convolution_param->add_kernel_size(1); convolution_param->add_stride(1); convolution_param->set_num_output(2); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); ConvolutionLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-3); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(GaussConvolutionLayerTest, TestGradientGroup) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(3); convolution_param->set_group(3); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); ConvolutionLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-3); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } */ #ifdef USE_CUDNN #endif } // namespace caffe
38.770417
202
0.71464
skokec
774abe8746e18e9a0ffd205c8e03c8667447129b
339
hpp
C++
include/esc/detail/is_any_of.hpp
a-n-t-h-o-n-y/Escape
45ca047bacffbbde768768c6631df6336dd4e03c
[ "MIT" ]
10
2021-06-30T15:10:55.000Z
2022-03-20T18:34:06.000Z
include/esc/detail/is_any_of.hpp
a-n-t-h-o-n-y/Escape
45ca047bacffbbde768768c6631df6336dd4e03c
[ "MIT" ]
null
null
null
include/esc/detail/is_any_of.hpp
a-n-t-h-o-n-y/Escape
45ca047bacffbbde768768c6631df6336dd4e03c
[ "MIT" ]
null
null
null
#ifndef ESC_DETAIL_IS_ANY_OF_HPP #define ESC_DETAIL_IS_ANY_OF_HPP #include <type_traits> namespace esc::detail { /// Type Trait defined as true if T is_same as any of Us. template <typename T, typename... Args> bool constexpr is_any_of = (std::is_same_v<Args, T> || ...); } // namespace esc::detail #endif // ESC_DETAIL_IS_ANY_OF_HPP
26.076923
60
0.743363
a-n-t-h-o-n-y
775aca3902f0883abd4b97d5055444eb899365ae
107
cpp
C++
docs/assets/playground/choice.cpp
IohannRabeson/lexy
881beb56f030e8f4761514e70cb50d809ac4ad17
[ "BSL-1.0" ]
527
2020-12-01T14:23:50.000Z
2022-03-31T11:30:24.000Z
docs/assets/playground/choice.cpp
ExternalRepositories/lexy
edc6bd4aabd6f0ecbddba6f2bbf9bd2c6e4fa61d
[ "BSL-1.0" ]
44
2020-12-01T18:39:38.000Z
2022-03-08T00:22:39.000Z
docs/assets/playground/choice.cpp
ExternalRepositories/lexy
edc6bd4aabd6f0ecbddba6f2bbf9bd2c6e4fa61d
[ "BSL-1.0" ]
24
2020-12-02T01:45:53.000Z
2022-03-22T21:31:31.000Z
// INPUT:Hello struct production { static constexpr auto rule = LEXY_LIT("Hello") | LEXY_LIT("Hi"); };
17.833333
68
0.672897
IohannRabeson
775c953f1c9d1412519e0d7bddf4c1763db0bccc
16,384
cpp
C++
simpleshell/westeros-simpleshell.cpp
moorthy-bs/westeros
d026756a91333b376d167d9e248e18309a177c95
[ "MIT" ]
null
null
null
simpleshell/westeros-simpleshell.cpp
moorthy-bs/westeros
d026756a91333b376d167d9e248e18309a177c95
[ "MIT" ]
null
null
null
simpleshell/westeros-simpleshell.cpp
moorthy-bs/westeros
d026756a91333b376d167d9e248e18309a177c95
[ "MIT" ]
null
null
null
/* * If not stated otherwise in this file or this component's Licenses.txt file the * following copyright and licenses apply: * * Copyright 2016 RDK Management * * 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 <stdlib.h> #include <stdio.h> #include <memory.h> #include <sys/time.h> #include <vector> #include "westeros-simpleshell.h" #include "wayland-server.h" #include "simpleshell-server-protocol.h" #define WST_UNUSED( n ) ((void)n) #define MIN(x,y) (((x) < (y)) ? (x) : (y)) #define DEFAULT_NAME "noname" #define BROADCAST_DELAY (2000) static void destroy_shell(struct wl_resource *resource); static void wstSimpleShellBroadcastCreation( struct wl_simple_shell *shell, uint32_t surfaceId ); typedef struct _ShellInfo { struct wl_client *client; struct wl_resource *resource; } ShellInfo; typedef struct _PendingBroadcastInfo { uint32_t surfaceId; long long creationTime; } PendingBroadcastInfo; struct wl_simple_shell { struct wl_display *display; struct wl_global *wl_simple_shell_global; struct wayland_simple_shell_callbacks *callbacks; WstRenderer *renderer; void *userData; struct wl_event_source *delayTimer; std::vector<ShellInfo> shells; std::vector<uint32_t> surfaces; std::vector<PendingBroadcastInfo> pendingCreateBroadcast; }; static long long getCurrentTimeMillis() { struct timeval tv; long long utcCurrentTimeMillis; gettimeofday(&tv,0); utcCurrentTimeMillis= tv.tv_sec*1000LL+(tv.tv_usec/1000LL); return utcCurrentTimeMillis; } static void wstISimpleShellSetName(struct wl_client *client, struct wl_resource *resource, uint32_t surfaceId, const char *name); static void wstISimpleShellSetVisible(struct wl_client *client, struct wl_resource *resource, uint32_t surfaceId, uint32_t visible); static void wstISimpleShellSetGeometry(struct wl_client *client, struct wl_resource *resource, uint32_t surfaceId, int32_t x, int32_t y, int32_t width, int32_t height); static void wstISimpleShellSetOpacity(struct wl_client *client, struct wl_resource *resource, uint32_t surfaceId, wl_fixed_t opacity); static void wstISimpleShellSetZOrder(struct wl_client *client, struct wl_resource *resource, uint32_t surfaceId, wl_fixed_t zorder); static void wstISimpleShellGetStatus(struct wl_client *client, struct wl_resource *resource, uint32_t surface); static void wstISimpleShellGetSurfaces(struct wl_client *client, struct wl_resource *resource); static void wstISimpleShellSetFocus(struct wl_client *client, struct wl_resource *resource, uint32_t surfaceId); const static struct wl_simple_shell_interface simple_shell_interface = { wstISimpleShellSetName, wstISimpleShellSetVisible, wstISimpleShellSetGeometry, wstISimpleShellSetOpacity, wstISimpleShellSetZOrder, wstISimpleShellGetStatus, wstISimpleShellGetSurfaces, wstISimpleShellSetFocus }; static void wstSimpleShellBroadcastSurfaceUpdate(struct wl_client *client, struct wl_simple_shell *shell, uint32_t surfaceId ) { const char *name= 0; bool visible; int x, y, width, height; float opacity, zorder; wl_fixed_t fixedOpacity, fixedZOrder; shell->callbacks->get_name( shell->userData, surfaceId, &name ); if ( !name ) { name= (const char *)DEFAULT_NAME; } shell->callbacks->get_status( shell->userData, surfaceId, &visible, &x, &y, &width, &height, &opacity, &zorder ); fixedOpacity= wl_fixed_from_double( (double)opacity ); fixedZOrder= wl_fixed_from_double( (double)zorder ); // Broadcast the surface update announcement to all other clients. for( std::vector<ShellInfo>::iterator it= shell->shells.begin(); it != shell->shells.end(); ++it ) { if ((*it).client != client) { struct wl_resource *shell_resource = (*it).resource; wl_simple_shell_send_surface_status(shell_resource, surfaceId, name, (visible ? 1 : 0), x, y, width, height, fixedOpacity, fixedZOrder); } } } static void wstISimpleShellSetName(struct wl_client *client, struct wl_resource *resource, uint32_t surfaceId, const char *name) { struct wl_simple_shell *shell= (struct wl_simple_shell*)wl_resource_get_user_data(resource); shell->callbacks->set_name( shell->userData, surfaceId, name ); for( std::vector<PendingBroadcastInfo>::iterator it= shell->pendingCreateBroadcast.begin(); it != shell->pendingCreateBroadcast.end(); ++it ) { if ( (*it).surfaceId == surfaceId ) { shell->pendingCreateBroadcast.erase( it ); wstSimpleShellBroadcastCreation( shell, surfaceId ); break; } } wstSimpleShellBroadcastSurfaceUpdate(client, shell, surfaceId ); } static void wstISimpleShellSetVisible(struct wl_client *client, struct wl_resource *resource, uint32_t surfaceId, uint32_t visible) { struct wl_simple_shell *shell= (struct wl_simple_shell*)wl_resource_get_user_data(resource); shell->callbacks->set_visible( shell->userData, surfaceId, (visible != 0) ); wstSimpleShellBroadcastSurfaceUpdate(client, shell, surfaceId ); } static void wstISimpleShellSetGeometry(struct wl_client *client, struct wl_resource *resource, uint32_t surfaceId, int32_t x, int32_t y, int32_t width, int32_t height) { struct wl_simple_shell *shell= (struct wl_simple_shell*)wl_resource_get_user_data(resource); shell->callbacks->set_geometry( shell->userData, surfaceId, x, y, width, height ); wstSimpleShellBroadcastSurfaceUpdate(client, shell, surfaceId ); } static void wstISimpleShellSetOpacity(struct wl_client *client, struct wl_resource *resource, uint32_t surfaceId, wl_fixed_t opacity) { struct wl_simple_shell *shell= (struct wl_simple_shell*)wl_resource_get_user_data(resource); float opacityLevel= wl_fixed_to_double( opacity ); if ( opacityLevel < 0.0 ) opacityLevel= 0.0; if ( opacityLevel > 1.0 ) opacityLevel= 1.0; shell->callbacks->set_opacity( shell->userData, surfaceId, opacityLevel ); wstSimpleShellBroadcastSurfaceUpdate(client, shell, surfaceId ); } static void wstISimpleShellSetZOrder(struct wl_client *client, struct wl_resource *resource, uint32_t surfaceId, wl_fixed_t zorder) { struct wl_simple_shell *shell= (struct wl_simple_shell*)wl_resource_get_user_data(resource); float zOrderLevel= wl_fixed_to_double( zorder ); if ( zOrderLevel < 0.0 ) zOrderLevel= 0.0; if ( zOrderLevel > 1.0 ) zOrderLevel= 1.0; shell->callbacks->set_zorder( shell->userData, surfaceId, zOrderLevel ); wstSimpleShellBroadcastSurfaceUpdate(client, shell, surfaceId ); } static void wstISimpleShellGetStatus(struct wl_client *client, struct wl_resource *resource, uint32_t surfaceId ) { struct wl_simple_shell *shell= (struct wl_simple_shell*)wl_resource_get_user_data(resource); const char *name= 0; bool visible; int x, y, width, height; float opacity, zorder; wl_fixed_t fixedOpacity, fixedZOrder; shell->callbacks->get_name( shell->userData, surfaceId, &name ); if ( !name ) { name= (const char *)DEFAULT_NAME; } shell->callbacks->get_status( shell->userData, surfaceId, &visible, &x, &y, &width, &height, &opacity, &zorder ); fixedOpacity= wl_fixed_from_double( (double)opacity ); fixedZOrder= wl_fixed_from_double( (double)zorder ); wl_simple_shell_send_surface_status( resource, surfaceId, name, (visible ? 1 : 0), x, y, width, height, fixedOpacity, fixedZOrder ); } static void wstISimpleShellGetSurfaces(struct wl_client *client, struct wl_resource *resource) { struct wl_simple_shell *shell= (struct wl_simple_shell*)wl_resource_get_user_data(resource); for( std::vector<uint32_t>::iterator it= shell->surfaces.begin(); it != shell->surfaces.end(); ++it ) { uint32_t surfaceId= (*it); wstISimpleShellGetStatus(client, resource, surfaceId ); } wl_simple_shell_send_get_surfaces_done( resource ); } static void wstISimpleShellSetFocus(struct wl_client *client, struct wl_resource *resource, uint32_t surfaceId) { struct wl_simple_shell *shell= (struct wl_simple_shell*)wl_resource_get_user_data(resource); shell->callbacks->set_focus(shell->userData, surfaceId); } static void destroy_shell(struct wl_resource *resource) { struct wl_simple_shell *shell= (struct wl_simple_shell*)wl_resource_get_user_data(resource); for ( std::vector<ShellInfo>::iterator it= shell->shells.begin(); it != shell->shells.end(); ++it ) { if ( (*it).resource == resource ) { shell->shells.erase(it); break; } } } static void wstSimpleShellBind(struct wl_client *client, void *data, uint32_t version, uint32_t id) { struct wl_simple_shell *shell= (struct wl_simple_shell*)data; struct wl_resource *resource; ShellInfo info; printf("westeros-simpleshell: wstSimpleShellBind: enter: client %p data %p version %d id %d\n", client, data, version, id); resource= wl_resource_create(client, &wl_simple_shell_interface, MIN(version, 1), id); if (!resource) { wl_client_post_no_memory(client); return; } wl_resource_set_implementation(resource, &simple_shell_interface, shell, destroy_shell); info.client= client; info.resource= resource; shell->shells.push_back( info ); } static void wstSimpleShellBroadcastCreation( struct wl_simple_shell *shell, uint32_t surfaceId ) { const char *name= 0; // Get any name the creator may have assigned the surface shell->callbacks->get_name( shell->userData, surfaceId, &name ); if ( !name ) { name= (const char *)DEFAULT_NAME; } printf("broadcast for surfaceId %x name %s\n", surfaceId, name); // Broadcast the surface creation announcement for( std::vector<ShellInfo>::iterator it= shell->shells.begin(); it != shell->shells.end(); ++it ) { struct wl_resource *shell_resource= (*it).resource; wl_simple_shell_send_surface_created( shell_resource, surfaceId, name ); } } static int wstSimpleShellTimeOut( void *data ) { bool more= true; long long now; long long delay; PendingBroadcastInfo pendingInfo; struct wl_simple_shell *shell= (struct wl_simple_shell*)data; while( more ) { if ( shell->pendingCreateBroadcast.size() > 0 ) { pendingInfo= shell->pendingCreateBroadcast.front(); shell->pendingCreateBroadcast.erase( shell->pendingCreateBroadcast.begin() ); wstSimpleShellBroadcastCreation( shell, pendingInfo.surfaceId ); if ( shell->pendingCreateBroadcast.size() > 0 ) { pendingInfo= shell->pendingCreateBroadcast.front(); now= getCurrentTimeMillis(); delay= now-pendingInfo.creationTime; if ( delay >= BROADCAST_DELAY ) { continue; } else { delay= BROADCAST_DELAY-delay; wl_event_source_timer_update( shell->delayTimer, delay ); more= false; } } } else { break; } } return 0; } wl_simple_shell* WstSimpleShellInit( struct wl_display *display, wayland_simple_shell_callbacks *callbacks, void *userData ) { struct wl_simple_shell *shell= 0; struct wl_event_loop *loop= 0; printf("westeros-simpleshell: WstSimpleShellInit: enter: display %p\n", display ); shell= (struct wl_simple_shell*)calloc( 1, sizeof(struct wl_simple_shell) ); if ( !shell ) { goto exit; } shell->display= display; shell->callbacks= callbacks; shell->userData= userData; loop= wl_display_get_event_loop(shell->display); if ( !loop ) { free( shell ); shell= 0; goto exit; } shell->delayTimer= wl_event_loop_add_timer( loop, wstSimpleShellTimeOut, shell ); if ( !shell->delayTimer ) { free( shell ); shell= 0; goto exit; } shell->wl_simple_shell_global= wl_global_create(display, &wl_simple_shell_interface, 1, shell, wstSimpleShellBind ); exit: printf("westeros-simpleshell: WstSimpleShellInit: exit: display %p shell %p\n", display, shell); return shell; } void WstSimpleShellUninit( wl_simple_shell *shell ) { if ( shell ) { if ( shell->delayTimer ) { wl_event_source_remove( shell->delayTimer ); shell->delayTimer= 0; } wl_global_destroy( shell->wl_simple_shell_global ); shell->pendingCreateBroadcast.clear(); shell->surfaces.clear(); shell->shells.clear(); free( shell ); } } void WstSimpleShellNotifySurfaceCreated( wl_simple_shell *shell, struct wl_client *client, struct wl_resource *surface_resource, uint32_t surfaceId ) { bool creatorNotified= false; // Add surface to list shell->surfaces.push_back(surfaceId); // Provide surface creator with surfaceId for( std::vector<ShellInfo>::iterator it= shell->shells.begin(); it != shell->shells.end(); ++it ) { if ( (*it).client == client ) { long long now; PendingBroadcastInfo pendingInfo; struct wl_resource *shell_resource= (*it).resource; wl_simple_shell_send_surface_id( shell_resource, surface_resource, surfaceId ); creatorNotified= true; // Perform the surface creation broadcast after an asynchronous // delay to give the surface creator time to assign a name now= getCurrentTimeMillis(); pendingInfo.creationTime= now; pendingInfo.surfaceId= surfaceId; shell->pendingCreateBroadcast.push_back(pendingInfo); if ( shell->pendingCreateBroadcast.size() == 1 ) { wl_event_source_timer_update( shell->delayTimer, BROADCAST_DELAY ); } break; } } if ( !creatorNotified ) { wstSimpleShellBroadcastCreation( shell, surfaceId ); } } void WstSimpleShellNotifySurfaceDestroyed( wl_simple_shell *shell, struct wl_client *client, uint32_t surfaceId ) { const char *name; WST_UNUSED(client); // Get any name the creator may have assigned the surface shell->callbacks->get_name( shell->userData, surfaceId, &name ); if ( !name ) { name= (const char *)DEFAULT_NAME; } // Broadcast the surface destruction announcement for( std::vector<ShellInfo>::iterator it= shell->shells.begin(); it != shell->shells.end(); ++it ) { struct wl_resource *shell_resource= (*it).resource; wl_simple_shell_send_surface_destroyed( shell_resource, surfaceId, name ); } // Remove surface from list for( std::vector<uint32_t>::iterator it= shell->surfaces.begin(); it != shell->surfaces.end(); ++it ) { if ( (*it) == surfaceId ) { shell->surfaces.erase(it); break; } } }
32.251969
126
0.659424
moorthy-bs
776337ab0c60c5cb11d2528f22f50a174e7683fd
2,147
hpp
C++
MainGame/settings/Settings.hpp
JoaoBaptMG/ReboundTheGame
48c3d8b81de1f7fa7c622c3f815860257ccdba8e
[ "MIT" ]
63
2017-05-18T16:10:19.000Z
2022-03-26T18:05:59.000Z
MainGame/settings/Settings.hpp
JoaoBaptMG/ReboundTheGame
48c3d8b81de1f7fa7c622c3f815860257ccdba8e
[ "MIT" ]
1
2018-02-10T12:40:33.000Z
2019-01-11T07:33:13.000Z
MainGame/settings/Settings.hpp
JoaoBaptMG/ReboundTheGame
48c3d8b81de1f7fa7c622c3f815860257ccdba8e
[ "MIT" ]
4
2017-12-31T21:38:14.000Z
2019-11-20T15:13:00.000Z
// // Copyright (c) 2016-2018 João Baptista de Paula e Silva. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #pragma once #include <string> #include <vector> #include <utility> #include <SFML/System.hpp> #include <OutputStream.hpp> #include "InputSettings.hpp" #include "VideoSettings.hpp" #include "AudioSettings.hpp" #include "gameplay/SavedGame.hpp" constexpr size_t SettingsVersion = 0; struct KeyPair { std::string name; SavedGame::Key key; KeyPair(std::string name, SavedGame::Key key) : name(name), key(key) {} KeyPair() {} }; struct Settings { InputSettings inputSettings; VideoSettings videoSettings; AudioSettings audioSettings; std::string languageFile; std::vector<KeyPair> savedKeys; }; bool readFromStream(sf::InputStream &stream, KeyPair& keyPair); bool writeToStream(OutputStream& stream, const KeyPair& keyPair); bool readFromStream(sf::InputStream &stream, Settings& settings); bool writeToStream(OutputStream& stream, const Settings& settings); Settings loadSettingsFile(bool *success = nullptr); bool storeSettingsFile(const Settings& settings);
33.546875
81
0.755007
JoaoBaptMG
776722a74f9267edf4bc43db31704a8270db44d0
11,618
cxx
C++
Src/Projects/device_faceCap/device_facecap_device.cxx
Mikkelbf/OpenMoBu
c57c41a0908ad7734d48642549758271d11263b8
[ "BSD-3-Clause" ]
53
2018-04-21T14:16:46.000Z
2022-03-19T11:27:37.000Z
Src/Projects/device_faceCap/device_facecap_device.cxx
Mikkelbf/OpenMoBu
c57c41a0908ad7734d48642549758271d11263b8
[ "BSD-3-Clause" ]
6
2019-06-05T16:37:29.000Z
2021-09-20T07:17:03.000Z
Src/Projects/device_faceCap/device_facecap_device.cxx
Mikkelbf/OpenMoBu
c57c41a0908ad7734d48642549758271d11263b8
[ "BSD-3-Clause" ]
10
2019-02-22T18:43:59.000Z
2021-09-02T18:53:37.000Z
/** \file device_facecap_device.cxx * Developed by Sergei <Neill3d> Solokhin 2019 * e-mail to: [email protected] * twitter: @Neill3d * * OpenMoBu github - https://github.com/Neill3d/OpenMoBu */ //--- Class declaration #include "device_facecap_device.h" //--- Registration defines #define CDEVICEFACECAP__CLASS CDEVICEFACECAP__CLASSNAME #define CDEVICEFACECAP__NAME CDEVICEFACECAP__CLASSSTR #define CDEVICEFACECAP__LABEL "FaceCap OSC Device" #define CDEVICEFACECAP__DESC "FaceCap OSC Device" #define CDEVICEFACECAP__PREFIX "FaceCap" //--- FiLMBOX implementation and registration FBDeviceImplementation ( CDEVICEFACECAP__CLASS ); FBRegisterDevice ( CDEVICEFACECAP__NAME, CDEVICEFACECAP__CLASS, CDEVICEFACECAP__LABEL, CDEVICEFACECAP__DESC, "character_actor.png"); // Icon filename (default=Open Reality icon) /************************************************ * FiLMBOX Constructor. ************************************************/ bool CDevice_FaceCap::FBCreate() { mHardware.SetParent( this ); FBPropertyPublish(this, SpaceScale, "Space Scale", nullptr, nullptr); FBPropertyPublish(this, ShapeValueMult, "Shape Value Mult", nullptr, nullptr); SpaceScale = 100.0; ShapeValueMult = 100.0; // Create animation nodes mNodeHead_InT = AnimationNodeOutCreate( 0, "Translation", ANIMATIONNODE_TYPE_LOCAL_TRANSLATION ); mNodeHead_InR = AnimationNodeOutCreate( 1, "Rotation", ANIMATIONNODE_TYPE_LOCAL_ROTATION ); mNodeLeftEye_InR = AnimationNodeOutCreate(2, "LeftEye Rotation", ANIMATIONNODE_TYPE_LOCAL_ROTATION); mNodeRightEye_InR = AnimationNodeOutCreate(3, "RightEye Rotation", ANIMATIONNODE_TYPE_LOCAL_ROTATION); for (uint32_t i = 0; i < static_cast<uint32_t>(EHardwareBlendshapes::count); ++i) { mNodeHead_Blendshapes[i] = AnimationNodeOutCreate(i+4, blendshape_names[i], ANIMATIONNODE_TYPE_NUMBER); } // default values mNodeHead_InT->SetCandidate(FBVector3d(0.0, 5.0, 0.0)); // Create model templates mTemplateRoot = new FBModelTemplate( CDEVICEFACECAP__PREFIX, "Reference", kFBModelTemplateRoot ); mTemplateHead = new FBModelTemplate( CDEVICEFACECAP__PREFIX, "Head", kFBModelTemplateMarker ); mTemplateLeftEye = new FBModelTemplate(CDEVICEFACECAP__PREFIX, "LeftEye", kFBModelTemplateMarker); mTemplateRightEye = new FBModelTemplate(CDEVICEFACECAP__PREFIX, "RightEye", kFBModelTemplateMarker); // Build model template hierarchy ModelTemplate.Children.Add(mTemplateRoot); mTemplateRoot->Children.Add(mTemplateHead); mTemplateHead->Children.Add(mTemplateLeftEye); mTemplateHead->Children.Add(mTemplateRightEye); // Bind the model templates (if applicable) to device's animation nodes mTemplateHead->Bindings.Add( mNodeHead_InR ); mTemplateHead->Bindings.Add( mNodeHead_InT ); mTemplateLeftEye->Bindings.Add(mNodeLeftEye_InR); mTemplateRightEye->Bindings.Add(mNodeRightEye_InR); mTemplateHead->DefaultTranslation = FBVector3d(0.0, 5.0, 0.0); mTemplateLeftEye->DefaultTranslation = FBVector3d(-5.0, 5.0, 0.0); mTemplateRightEye->DefaultTranslation = FBVector3d(5.0, 5.0, 0.0); // Set sampling rate to 60 Hz FBTime lPeriod; lPeriod.SetSecondDouble(1.0/60.0); SamplingPeriod = lPeriod; CommType = kFBCommTypeNetworkUDP; mSetCandidate = false; return true; } /************************************************ * FiLMBOX Destructor. ************************************************/ void CDevice_FaceCap::FBDestroy() { } /************************************************ * Device operation. ************************************************/ bool CDevice_FaceCap::DeviceOperation( kDeviceOperations pOperation ) { switch (pOperation) { case kOpInit: return Init(); case kOpStart: return Start(); case kOpStop: return Stop(); case kOpReset: return Reset(); case kOpDone: return Done(); } return FBDevice::DeviceOperation( pOperation ); } /************************************************ * Initialization of device. ************************************************/ bool CDevice_FaceCap::Init() { FBProgress lProgress; lProgress.Caption = "Device Template"; lProgress.Text = "Initializing device..."; return true; } /************************************************ * Device is put online. ************************************************/ bool CDevice_FaceCap::Start() { FBProgress lProgress; lProgress.Caption = "Starting up device"; // Step 1: Open device communications lProgress.Text = "Opening device communications"; Status = "Opening device communications"; if(!mHardware.Open()) { Status = "Could not open device"; return false; } // Step 2: Ask hardware to get channel information lProgress.Text = "Device found, getting setup information"; Status = "Getting setup information"; if(!mHardware.GetSetupInfo()) { Status = "Could not get setup information from device."; return false; } else { HardwareVersionInfo = "Device Template, v1.0"; Information = ""; } if( mHardware.GetStreaming() ) { // Step 3: Start streaming data from device lProgress.Text = "Sending START STREAM command"; Status = "Starting device streaming"; if(!mHardware.StartStream()) { Status = "Could not start stream mode"; return false; } } Status = "Ok"; return true; } /************************************************ * Device is stopped (offline). ************************************************/ bool CDevice_FaceCap::Stop() { FBProgress lProgress; lProgress.Caption = "Shutting down device"; if( mHardware.GetStreaming() ) { // Step 1: Stop streaming data lProgress.Text = "Sending STOP STREAM command"; Status = "Stopping device streaming"; if(!mHardware.StopStream()) { Status = "Could not stop streaming"; return false; } } // Step 1: Stop streaming data lProgress.Text = "Stopping device communications"; Status = "Stopping device communications"; if(!mHardware.Close()) { Status = "Could not close device"; return false; } Status = "?"; return false; } /************************************************ * Removal of device. ************************************************/ bool CDevice_FaceCap::Done() { return false; } /************************************************ * Reset of device. ************************************************/ bool CDevice_FaceCap::Reset() { Stop(); return Start(); } /************************************************ * Real-Time Engine Evaluation. ************************************************/ bool CDevice_FaceCap::AnimationNodeNotify(FBAnimationNode* pAnimationNode ,FBEvaluateInfo* pEvaluateInfo) { double lPos[3]; double lRot[3]; const double space_scale = 0.01 * SpaceScale; // head position and rotation mHardware.GetPosition( lPos ); mHardware.GetRotation( lRot ); for (int i = 0; i < 3; ++i) { lPos[i] *= space_scale; } mNodeHead_InT->WriteData( lPos, pEvaluateInfo ); mNodeHead_InR->WriteData( lRot, pEvaluateInfo ); // left eye mHardware.GetLeftEyeRotation(lRot); lRot[2] = 0.0; mNodeLeftEye_InR->WriteData(lRot, pEvaluateInfo); // right eye mHardware.GetRightEyeRotation(lRot); lRot[2] = 0.0; mNodeRightEye_InR->WriteData(lRot, pEvaluateInfo); // blendshapes for (int i = 0; i < mHardware.GetNumberOfBlendshapes(); ++i) { double value = ShapeValueMult * mHardware.GetBlendshapeValue(i); mNodeHead_Blendshapes[i]->WriteData(&value, pEvaluateInfo); } return true; } /************************************************ * Device Evaluation Notify. ************************************************/ bool CDevice_FaceCap::DeviceEvaluationNotify( kTransportMode pMode, FBEvaluateInfo* pEvaluateInfo ) { return true; } /************************************************ * Real-Time Synchronous Device IO. ************************************************/ void CDevice_FaceCap::DeviceIONotify( kDeviceIOs pAction,FBDeviceNotifyInfo &pDeviceNotifyInfo) { int i; int lNumberOfPackets; FBTime lPacketTimeCode; switch (pAction) { // Output devices case kIOPlayModeWrite: case kIOStopModeWrite: { } break; // Input devices case kIOStopModeRead: case kIOPlayModeRead: { lNumberOfPackets = mHardware.FetchData(); for( i=0; i<lNumberOfPackets; i++ ) { DeviceRecordFrame ( pDeviceNotifyInfo ); AckOneSampleReceived( ); } if( !mHardware.GetStreaming() ) { mHardware.PollData(); } break; } } } /************************************************ * Record a frame of the device (recording). ************************************************/ void CDevice_FaceCap::DeviceRecordFrame( FBDeviceNotifyInfo &pDeviceNotifyInfo ) { double lPos[3]; double lRot[3]; FBTime lTime; const double space_scale = 0.01 * SpaceScale; lTime = pDeviceNotifyInfo.GetLocalTime(); // if( mPlayerControl.GetTransportMode() == kFBTransportPlay ) { mHardware.GetPosition(lPos); mHardware.GetRotation(lRot); for (int i = 0; i < 3; ++i) { lPos[i] *= space_scale; } switch( SamplingMode ) { case kFBHardwareTimestamp: case kFBSoftwareTimestamp: { if (FBAnimationNode* data = mNodeHead_InT->GetAnimationToRecord()) { data->KeyAdd(lTime, lPos); } if (FBAnimationNode* data = mNodeHead_InR->GetAnimationToRecord()) { data->KeyAdd(lTime, lRot); } if (FBAnimationNode* data = mNodeLeftEye_InR->GetAnimationToRecord()) { mHardware.GetLeftEyeRotation(lRot); lRot[2] = 0.0; data->KeyAdd(lTime, lRot); } if (FBAnimationNode* data = mNodeRightEye_InR->GetAnimationToRecord()) { mHardware.GetRightEyeRotation(lRot); lRot[2] = 0.0; data->KeyAdd(lTime, lRot); } for (int i = 0; i < mHardware.GetNumberOfBlendshapes(); ++i) { if (FBAnimationNode* data = mNodeHead_Blendshapes[i]->GetAnimationToRecord()) { double value = ShapeValueMult * mHardware.GetBlendshapeValue(i); data->KeyAdd(lTime, &value); } } } break; case kFBHardwareFrequency: case kFBAutoFrequency: { if (FBAnimationNode* data = mNodeHead_InT->GetAnimationToRecord()) { data->KeyAdd(lPos); } if (FBAnimationNode* data = mNodeHead_InR->GetAnimationToRecord()) { data->KeyAdd(lRot); } if (FBAnimationNode* data = mNodeLeftEye_InR->GetAnimationToRecord()) { mHardware.GetLeftEyeRotation(lRot); lRot[2] = 0.0; data->KeyAdd(lRot); } if (FBAnimationNode* data = mNodeRightEye_InR->GetAnimationToRecord()) { mHardware.GetRightEyeRotation(lRot); lRot[2] = 0.0; data->KeyAdd(lRot); } for (int i = 0; i < mHardware.GetNumberOfBlendshapes(); ++i) { if (FBAnimationNode* data = mNodeHead_Blendshapes[i]->GetAnimationToRecord()) { double value = ShapeValueMult * mHardware.GetBlendshapeValue(i); data->KeyAdd(&value); } } } break; } } } void CDevice_FaceCap::SetCandidates() { double lPos[3]; double lRot[3]; mHardware.GetPosition( lPos ); mHardware.GetRotation( lRot ); const double space_scale = 0.01 * SpaceScale; for (int i = 0; i < 3; ++i) { lPos[i] *= space_scale; } mNodeHead_InT->SetCandidate( lPos ); mNodeHead_InR->SetCandidate( lRot ); // left / right eyes mHardware.GetLeftEyeRotation(lRot); lRot[2] = 0.0; mNodeLeftEye_InR->SetCandidate(lRot); mHardware.GetRightEyeRotation(lRot); lRot[2] = 0.0; mNodeRightEye_InR->SetCandidate(lRot); // blendshapes for (int i = 0; i < mHardware.GetNumberOfBlendshapes(); ++i) { double value = ShapeValueMult * mHardware.GetBlendshapeValue(i); mNodeHead_Blendshapes[i]->SetCandidate(&value); } }
24.771855
105
0.637545
Mikkelbf
777305d41cb6005d0343a95e544d96e23a2161e2
5,301
hpp
C++
libcore/include/sirikata/core/options/CommonOptions.hpp
pathorn/sirikata
5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa
[ "BSD-3-Clause" ]
1
2016-05-09T03:34:51.000Z
2016-05-09T03:34:51.000Z
libcore/include/sirikata/core/options/CommonOptions.hpp
pathorn/sirikata
5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa
[ "BSD-3-Clause" ]
null
null
null
libcore/include/sirikata/core/options/CommonOptions.hpp
pathorn/sirikata
5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa
[ "BSD-3-Clause" ]
null
null
null
/* Sirikata * CommonOptions.hpp * * Copyright (c) 2009, Ewen Cheslack-Postava * 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 Sirikata nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _SIRIKATA_COMMON_OPTIONS_HPP_ #define _SIRIKATA_COMMON_OPTIONS_HPP_ #include <sirikata/core/util/Platform.hpp> #define OPT_CRASHREPORT_URL "crashreport" #define OPT_PLUGINS "plugins" #define OPT_LOG_FILE "log-file" #define STATS_TRACE_FILE "stats.trace-filename" #define PROFILE "profile" #define OPT_REGION_WEIGHT "region-weight" #define OPT_REGION_WEIGHT_ARGS "region-weight-args" #define OPT_CDN_HOST "cdn.host" #define OPT_CDN_SERVICE "cdn.service" #define OPT_CDN_DNS_URI_PREFIX "cdn.dns.prefix" #define OPT_CDN_DOWNLOAD_URI_PREFIX "cdn.download.prefix" #define OPT_TRACE_TIMESERIES "trace.timeseries" #define OPT_TRACE_TIMESERIES_OPTIONS "trace.timeseries-options" namespace Sirikata { /// Report version information to the log SIRIKATA_FUNCTION_EXPORT void ReportVersion(); SIRIKATA_FUNCTION_EXPORT void InitOptions(); SIRIKATA_FUNCTION_EXPORT void ParseOptions(int argc, char** argv); SIRIKATA_FUNCTION_EXPORT void ParseOptionsFile(const String& fname, bool required=true); /** Parse command line options and config files, ensuring the command line * arguments take priority but reading the config file from an option rather * than hard coding it. */ SIRIKATA_FUNCTION_EXPORT void ParseOptions(int argc, char** argv, const String& config_file_option); // Parses empty options to get options properly initialized SIRIKATA_FUNCTION_EXPORT void FakeParseOptions(); /// Fills in SIRIKATA_FUNCTION_EXPORT void FillMissingOptionDefaults(); // Be careful with GetOption. Using it and ->as() directly can be dangerous // because some types are defined per-library and won't dynamic_cast properly. // It is suggested that you use GetOptionValue where possible. SIRIKATA_FUNCTION_EXPORT OptionValue* GetOption(const char* name); SIRIKATA_FUNCTION_EXPORT OptionValue* GetOption(const char* klass, const char* name); template<typename T> T GetOptionValue(const char* name) { OptionValue* opt = GetOption(name); return opt->as<T>(); } template<typename T> T GetOptionValue(const char* klass, const char* name) { OptionValue* opt = GetOption(klass, name); return opt->unsafeAs<T>(); // FIXME should be ->as<T>(); } template<> SIRIKATA_FUNCTION_EXPORT String GetOptionValue<String>(const char* name); template<> SIRIKATA_FUNCTION_EXPORT Vector3f GetOptionValue<Vector3f>(const char* name); template<> SIRIKATA_FUNCTION_EXPORT Vector3ui32 GetOptionValue<Vector3ui32>(const char* name); template<> SIRIKATA_FUNCTION_EXPORT BoundingBox3f GetOptionValue<BoundingBox3f>(const char* name); template<> SIRIKATA_FUNCTION_EXPORT ObjectHostID GetOptionValue<ObjectHostID>(const char* name); template<> SIRIKATA_FUNCTION_EXPORT Task::DeltaTime GetOptionValue<Task::DeltaTime>(const char* name); template<> SIRIKATA_FUNCTION_EXPORT uint32 GetOptionValue<uint32>(const char* name); template<> SIRIKATA_FUNCTION_EXPORT int32 GetOptionValue<int32>(const char* name); template<> SIRIKATA_FUNCTION_EXPORT uint64 GetOptionValue<uint64>(const char* name); template<> SIRIKATA_FUNCTION_EXPORT int64 GetOptionValue<int64>(const char* name); template<> SIRIKATA_FUNCTION_EXPORT bool GetOptionValue<bool>(const char* name); SIRIKATA_FUNCTION_EXPORT String GetPerServerString(const String& orig, const ServerID& sid); /** Get an option which is a filename and modify it to be server specific. */ SIRIKATA_FUNCTION_EXPORT String GetPerServerFile(const char* opt_name, const ServerID& sid); SIRIKATA_FUNCTION_EXPORT String GetPerServerFile(const char* opt_name, const ObjectHostID& ohid); } // namespace Sirikata #endif //_SIRIKATA_COMMON_OPTIONS_HPP_
40.776923
100
0.776646
pathorn
a55cdb5b46324a3125bcb3c81828b3cb4522773e
3,730
hpp
C++
ysu/node/bootstrap/bootstrap_attempt.hpp
lik2129/ysu_coin
47e40ed5d4000fc59566099929bd08a9ae16a4c1
[ "BSD-3-Clause" ]
null
null
null
ysu/node/bootstrap/bootstrap_attempt.hpp
lik2129/ysu_coin
47e40ed5d4000fc59566099929bd08a9ae16a4c1
[ "BSD-3-Clause" ]
null
null
null
ysu/node/bootstrap/bootstrap_attempt.hpp
lik2129/ysu_coin
47e40ed5d4000fc59566099929bd08a9ae16a4c1
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <ysu/node/bootstrap/bootstrap.hpp> #include <atomic> #include <future> namespace ysu { class node; class frontier_req_client; class bulk_push_client; class bootstrap_attempt : public std::enable_shared_from_this<bootstrap_attempt> { public: explicit bootstrap_attempt (std::shared_ptr<ysu::node> node_a, ysu::bootstrap_mode mode_a, uint64_t incremental_id_a, std::string id_a); virtual ~bootstrap_attempt (); virtual void run () = 0; virtual void stop (); bool still_pulling (); void pull_started (); void pull_finished (); bool should_log (); std::string mode_text (); virtual void restart_condition (); virtual void add_frontier (ysu::pull_info const &); virtual void add_bulk_push_target (ysu::block_hash const &, ysu::block_hash const &); virtual bool request_bulk_push_target (std::pair<ysu::block_hash, ysu::block_hash> &); virtual void add_recent_pull (ysu::block_hash const &); virtual void lazy_start (ysu::hash_or_account const &, bool confirmed = true); virtual void lazy_add (ysu::pull_info const &); virtual void lazy_requeue (ysu::block_hash const &, ysu::block_hash const &, bool); virtual uint32_t lazy_batch_size (); virtual bool lazy_has_expired () const; virtual bool lazy_processed_or_exists (ysu::block_hash const &); virtual bool process_block (std::shared_ptr<ysu::block>, ysu::account const &, uint64_t, ysu::bulk_pull::count_t, bool, unsigned); virtual void requeue_pending (ysu::account const &); virtual void wallet_start (std::deque<ysu::account> &); virtual size_t wallet_size (); virtual void get_information (boost::property_tree::ptree &) = 0; std::mutex next_log_mutex; std::chrono::steady_clock::time_point next_log{ std::chrono::steady_clock::now () }; std::atomic<unsigned> pulling{ 0 }; std::shared_ptr<ysu::node> node; std::atomic<uint64_t> total_blocks{ 0 }; std::atomic<unsigned> requeued_pulls{ 0 }; std::atomic<bool> started{ false }; std::atomic<bool> stopped{ false }; uint64_t incremental_id{ 0 }; std::string id; std::chrono::steady_clock::time_point attempt_start{ std::chrono::steady_clock::now () }; std::atomic<bool> frontiers_received{ false }; std::atomic<bool> frontiers_confirmed{ false }; ysu::bootstrap_mode mode; std::mutex mutex; ysu::condition_variable condition; }; class bootstrap_attempt_legacy : public bootstrap_attempt { public: explicit bootstrap_attempt_legacy (std::shared_ptr<ysu::node> node_a, uint64_t incremental_id_a, std::string id_a = ""); void run () override; bool consume_future (std::future<bool> &); void stop () override; bool request_frontier (ysu::unique_lock<std::mutex> &, bool = false); void request_pull (ysu::unique_lock<std::mutex> &); void request_push (ysu::unique_lock<std::mutex> &); void add_frontier (ysu::pull_info const &) override; void add_bulk_push_target (ysu::block_hash const &, ysu::block_hash const &) override; bool request_bulk_push_target (std::pair<ysu::block_hash, ysu::block_hash> &) override; void add_recent_pull (ysu::block_hash const &) override; void run_start (ysu::unique_lock<std::mutex> &); void restart_condition () override; void attempt_restart_check (ysu::unique_lock<std::mutex> &); bool confirm_frontiers (ysu::unique_lock<std::mutex> &); void get_information (boost::property_tree::ptree &) override; ysu::tcp_endpoint endpoint_frontier_request; std::weak_ptr<ysu::frontier_req_client> frontiers; std::weak_ptr<ysu::bulk_push_client> push; std::deque<ysu::pull_info> frontier_pulls; std::deque<ysu::block_hash> recent_pulls_head; std::vector<std::pair<ysu::block_hash, ysu::block_hash>> bulk_push_targets; std::atomic<unsigned> account_count{ 0 }; std::atomic<bool> frontiers_confirmation_pending{ false }; }; }
42.386364
137
0.755496
lik2129
a56003e1f0d6423a7ed96b89bac370a374f70cbc
74,166
cpp
C++
Market/Market.cpp
MichaelXanth/RPG_Game
4ce98fb2b03719dbd026afea7e270b623b09b2a0
[ "MIT" ]
3
2020-06-22T16:21:03.000Z
2020-07-05T12:10:29.000Z
Market/Market.cpp
MichaelXanth/RPG_Game
4ce98fb2b03719dbd026afea7e270b623b09b2a0
[ "MIT" ]
null
null
null
Market/Market.cpp
MichaelXanth/RPG_Game
4ce98fb2b03719dbd026afea7e270b623b09b2a0
[ "MIT" ]
null
null
null
/* File: Market.cpp */ #include <cstdlib> #include <cstring> #include <iostream> #include <limits> #include <unistd.h> #include "../Input_Validation/Input_Validation.hpp" #include "../Items/Armor.hpp" #include "../Items/Potion.hpp" #include "../Items/Weapon.hpp" #include "../Living/Heroes/Hero.hpp" #include "../Spells/FireSpell.hpp" #include "../Spells/IceSpell.hpp" #include "../Spells/LightingSpell.hpp" #include "../Spells/Spell.hpp" #include "Market.hpp" using namespace std; void Market::RecalcMostItems(void) { mostItems = 0; if (mostItems < lightingSpellsArray.size()) mostItems = lightingSpellsArray.size(); if (mostItems < fireSpellsArray.size()) mostItems = fireSpellsArray.size(); if (mostItems < iceSpellsArray.size()) mostItems = iceSpellsArray.size(); if (mostItems < weaponsArray.size()) mostItems = weaponsArray.size(); if (mostItems < potionsArray.size()) mostItems = potionsArray.size(); if (mostItems < armorsArray.size()) mostItems = armorsArray.size(); } void Market::ResetForSaleProds(void) { lightingSpellsForSale = 0; fireSpellsForSale = 0; iceSpellsForSale = 0; weaponsForSale = 0; potionsForSale = 0; armorsForSale = 0; } bool Market::isValidForPurchase(string testSelections[], int& column, int& row, const int& buyState) { if (!isValid(testSelections[0].c_str(),column,0,6)) return false; if (!isNumeric(testSelections[1].c_str(),row)) return false; if (buyState == 0 && column > 3) { if (weaponsForSale || potionsForSale || armorsForSale) cerr << endl << "\033[35mWarning:\033[0m There are no more available Item slots." << endl; else cerr << endl << "\033[35mWarning:\033[0m Sorry, there are no available Items for sale." << endl; return false; } if (buyState == 1 && column < 4) { if (lightingSpellsForSale || fireSpellsForSale || iceSpellsForSale) cerr << endl << "\033[35mWarning:\033[0m There are no more available Spell slots." << endl; else cerr << endl << "\033[35mWarning:\033[0m Sorry, there are no available Spells for sale." << endl; return false; } switch(column) { case 1: if (row == 0 || row > iceSpellsForSale) { cerr << "\n\033[31mError:\033[0m The input is invalid." << endl; cerr << "Please, try again!" << endl << endl; return false; } break; case 2: if (row == 0 || row > fireSpellsForSale) { cerr << "\n\033[31mError:\033[0m The input is invalid." << endl; cerr << "Please, try again!" << endl << endl; return false; } break; case 3: if (row == 0 || row > lightingSpellsForSale) { cerr << "\n\033[31mError:\033[0m The input is invalid." << endl; cerr << "Please, try again!" << endl << endl; return false; } break; case 4: if (row == 0 || row > weaponsForSale){ cerr << "\n\033[31mError:\033[0m The input is invalid." << endl; cerr << "Please, try again!" << endl << endl; return false; } break; case 5: if (row == 0 || row > armorsForSale) { cerr << "\n\033[31mError:\033[0m The input is invalid." << endl; cerr << "Please, try again!" << endl << endl; return false; } break; case 6: if (row == 0 || row > potionsForSale) { cerr << "\n\033[31mError:\033[0m The input is invalid." << endl; cerr << "Please, try again!" << endl << endl; return false; } break; } return true; } Market::Market() : lightingSpellsForSale(0), fireSpellsForSale(0) , iceSpellsForSale(0), weaponsForSale(0) , potionsForSale(0) , armorsForSale(0) , minSpellPrice(INT32_MAX), minItemPrice(INT32_MAX), minPrice(INT32_MAX), mostItems(0) , prevLevel(0) { AddLightingSpells(10); AddFireSpells(10); AddIceSpells(10); AddWeapons(10); AddPotions(10); AddArmors(10); } Market::~Market() { for (int i = iceSpellsArray.size(); !iceSpellsArray.empty(); i--) { delete iceSpellsArray[i-1]; iceSpellsArray.erase(iceSpellsArray.begin() + i-1); } for (int i = fireSpellsArray.size(); !fireSpellsArray.empty(); i--) { delete fireSpellsArray[i-1]; fireSpellsArray.erase(fireSpellsArray.begin() + i-1); } for (int i = lightingSpellsArray.size(); !lightingSpellsArray.empty(); i--) { delete lightingSpellsArray[i-1]; lightingSpellsArray.erase(lightingSpellsArray.begin() + i-1); } for (int i = weaponsArray.size(); !weaponsArray.empty(); i--) { delete weaponsArray[i-1]; weaponsArray.erase(weaponsArray.begin() + i-1); } for (int i = armorsArray.size(); !armorsArray.empty(); i--) { delete armorsArray[i-1]; armorsArray.erase(armorsArray.begin() + i-1); } for (int i = potionsArray.size(); !potionsArray.empty(); i--) { delete potionsArray[i-1]; potionsArray.erase(potionsArray.begin() + i-1); } } void Market::AddLightingSpells(const int& num) { string spellName; LightingSpell* tmpLightingSpell; for (int i = 0; i < num; i++) { unsigned int level; int tmpMinDamage; int tmpMaxDamage; if ( ((double)rand() / RAND_MAX) < 0.7 ) level = rand() % 30 + 1; else level = rand() % 70 + 31; spellName = name.lightingSpellsNames[rand() % name.lightingSpellsNames.size()]; do { tmpMinDamage = ((rand() % 2) + 2) * level; tmpMaxDamage = ((rand() % 4) + 2) * level; } while(tmpMinDamage == tmpMaxDamage); if (tmpMaxDamage < tmpMinDamage) { int temp = tmpMinDamage; tmpMinDamage = tmpMaxDamage; tmpMaxDamage = temp; } tmpLightingSpell = new LightingSpell(spellName , ((rand() % 2) + 3) * level, (rand() % 4) + 1 , level, tmpMinDamage , tmpMaxDamage, ((rand() % 4) + 1) * level , (unsigned int)((rand() % 6) + 1) * ((level / 25) + 1)); lightingSpellsArray.push_back(tmpLightingSpell); if (minSpellPrice > tmpLightingSpell->GetPrice()) minSpellPrice = tmpLightingSpell->GetPrice(); } if (mostItems < lightingSpellsArray.size()) mostItems = lightingSpellsArray.size(); if (minPrice > minSpellPrice) minPrice = minSpellPrice; } void Market::AddFireSpells(const int& num) { string spellName; FireSpell* tmpFireSpell; for (int i = 0; i < num; i++) { unsigned int level; int tmpMinDamage; int tmpMaxDamage; if ( ((double)rand() / RAND_MAX) < 0.7 ) level = rand() % 30 + 1; else level = rand() % 70 + 31; spellName = name.fireSpellsNames[rand() % name.fireSpellsNames.size()]; do { tmpMinDamage = ((rand() % 2) + 2) * level; tmpMaxDamage = ((rand() % 4) + 2) * level; } while(tmpMinDamage == tmpMaxDamage); if (tmpMaxDamage < tmpMinDamage) { int temp = tmpMinDamage; tmpMinDamage = tmpMaxDamage; tmpMaxDamage = temp; } tmpFireSpell = new FireSpell(spellName , ((rand() % 2) + 3) * level, (rand() % 4) + 1 , level, tmpMinDamage , tmpMaxDamage, ((rand() % 4) + 1) * level , (unsigned int)((3.0 / 2.0) * level)); fireSpellsArray.push_back(tmpFireSpell); if (minSpellPrice > tmpFireSpell->GetPrice()) minSpellPrice = tmpFireSpell->GetPrice(); } if (mostItems < fireSpellsArray.size()) mostItems = fireSpellsArray.size(); if (minPrice > minSpellPrice) minPrice = minSpellPrice; } void Market::AddIceSpells(const int& num) { string spellName; IceSpell* tmpIceSpell; for (int i = 0; i < num; i++) { unsigned int level; int tmpMinDamage; int tmpMaxDamage; if ( ((double)rand() / RAND_MAX) < 0.7 ) level = rand() % 30 + 1; else level = rand() % 70 + 31; spellName = name.iceSpellsNames[rand() % name.iceSpellsNames.size()]; do { tmpMinDamage = ((rand() % 2) + 2) * level; tmpMaxDamage = ((rand() % 4) + 2) * level; } while(tmpMinDamage == tmpMaxDamage); if (tmpMaxDamage < tmpMinDamage) { int temp = tmpMinDamage; tmpMinDamage = tmpMaxDamage; tmpMaxDamage = temp; } tmpIceSpell = new IceSpell(spellName , ((rand() % 2) + 3) * level, (rand() % 4) + 1 , level, tmpMinDamage , tmpMaxDamage, ((rand() % 4) + 1) * level , ((rand() % 2) + 1) * level); iceSpellsArray.push_back(tmpIceSpell); if (minSpellPrice > tmpIceSpell->GetPrice()) minSpellPrice = tmpIceSpell->GetPrice(); } if (mostItems < iceSpellsArray.size()) mostItems = iceSpellsArray.size(); if (minPrice > minSpellPrice) minPrice = minSpellPrice; } void Market::AddWeapons(const int& num) { string weaponName; Weapon* tmpWeapon; for (int i = 0; i < num; i++) { unsigned int level; bool hand = rand() % 2; int wdamage; if ( ((double)rand() / RAND_MAX) < 0.7 ) level = rand() % 30 + 1; else level = rand() % 70 + 31; weaponName = name.weaponsNames[rand() % name.weaponsNames.size()]; wdamage = (unsigned int)((hand + 1.0) * level * ((double)(rand() % 2) + 1) / 2.0); tmpWeapon = new Weapon(weaponName , ((rand() % 2) + 3) * level , level , wdamage , hand); weaponsArray.push_back(tmpWeapon); if (minItemPrice > tmpWeapon->GetPrice()) minItemPrice = tmpWeapon->GetPrice(); } if (mostItems < weaponsArray.size()) mostItems = weaponsArray.size(); if (minPrice > minItemPrice) minPrice = minItemPrice; } void Market::AddPotions(const int& num) { string potionName; Potion* tmpPotion; for (int i = 0; i < num; i++) { unsigned int level; float posibility; if ( ((double)rand() / RAND_MAX) < 0.7 ) level = rand() % 30 + 1; else level = rand() % 70 + 31; potionName = name.potionsNames[rand() % name.potionsNames.size()]; if ((double)(posibility = rand() % 100) < 100.0 / 3) tmpPotion = new Potion(potionName , ((rand() % 2) + 2) * level , level , (unsigned int)(((rand() % 6) + 1.0) * (level / 10.0) + 1) , 0 , 0); else if ((double)posibility < 200.0 / 3) tmpPotion = new Potion(potionName , ((rand() % 2) + 2) * level , level , 0 , (unsigned int)(((rand() % 6) + 1.0) * (level / 10.0) + 1) , 0); else tmpPotion = new Potion(potionName , ((rand() % 2) + 2) * level , level , 0 , 0 , (float)(3.0 * ((level / 25.0) + 1)) / 100.0); potionsArray.push_back(tmpPotion); if (minItemPrice > tmpPotion->GetPrice()) minItemPrice = tmpPotion->GetPrice(); } if (mostItems < potionsArray.size()) mostItems = potionsArray.size(); if (minPrice > minItemPrice) minPrice = minItemPrice; } void Market::AddArmors(const int& num) { string armorName; Armor* tmpArmor; for (int i = 0; i < num; i++) { unsigned int level; if ( ((double)rand() / RAND_MAX) < 0.7 ) level = rand() % 30 + 1; else level = rand() % 70 + 31; armorName = name.armorsNames[rand() % name.armorsNames.size()]; tmpArmor = new Armor(armorName , ((rand() % 2) + 3) * level , level , (unsigned int)(level * (4.0 / 2.0))); armorsArray.push_back(tmpArmor); if (minItemPrice > tmpArmor->GetPrice()) minItemPrice = tmpArmor->GetPrice(); } if (mostItems < armorsArray.size()) mostItems = armorsArray.size(); if (minPrice > minItemPrice) minPrice = minItemPrice; } void Market::NewStuff(vector<Hero *>& heroes) { if (heroes.size() == 1) { if (heroes[0]->Living::GetLevel() < prevLevel + 2) return; prevLevel = heroes[0]->Living::GetLevel(); } else { unsigned int averageLevel = 0; for (unsigned int i = 0; i < heroes.size(); i++) averageLevel += heroes[i]->Living::GetLevel(); averageLevel /= heroes.size(); if (averageLevel < prevLevel + 2) return; prevLevel = averageLevel; } if (rand() % prevLevel < prevLevel / 6) AddLightingSpells(rand() % 10); if (rand() % prevLevel < prevLevel / 6) AddFireSpells(rand() % 10); if (rand() % prevLevel < prevLevel / 6) AddIceSpells(rand() % 10); if (rand() % prevLevel < prevLevel / 6) AddWeapons(rand() % 10); if (rand() % prevLevel < prevLevel / 6) AddPotions(rand() % 10); if (rand() % prevLevel < prevLevel / 6) AddArmors(rand() % 10); } int Market::isAbleToBuy(const Hero* hero, const bool& info = true) { int buyState = 2; bool found = false; if (hero->GetMoney() == 0) { if (info) { if (lightingSpellsForSale || fireSpellsForSale || iceSpellsForSale || weaponsForSale || potionsForSale || armorsForSale) { DisplayMarket(false, hero, 3); cerr << endl; cerr << "-------------------------------" << endl << endl; cerr << "\033[35mWarning:\033[0m Hero \033[38;5;220m" << hero->Living::GetName() << "\033[0m has no money. The minimum required amount is: " << minPrice << endl; usleep(2500000); } else cerr << endl << "\033[31mError:\033[0m Hero \033[38;5;220m" << hero->Living::GetName() << "\033[0m has no money. The minimum required amount is: " << minPrice << endl; } return -1; } if (hero->GetMoney() < minPrice) { if (info) { if (lightingSpellsForSale || fireSpellsForSale || iceSpellsForSale || weaponsForSale || potionsForSale || armorsForSale) { DisplayMarket(false,hero,3); cerr << endl; cerr << "-------------------------------" << endl << endl; cerr << "\033[35mWarning:\033[0m Hero \033[38;5;220m" << hero->Living::GetName() << "\033[0m doesn't have enough money. The minimum required amount is: " << minPrice << endl; usleep(2500000); } else cerr << endl << "\033[31mError:\033[0m Hero \033[38;5;220m" << hero->Living::GetName() << "\033[0m doesn't have enough money. The minimum required amount is: " << minPrice << endl; } return -1; } if (hero->GetAvailableItemSlots() == 0 || hero->GetMoney() < minItemPrice) { if (hero->GetAvailableSpellSlots() == 0 || hero->GetMoney() < minSpellPrice) { if (info) { if (lightingSpellsForSale || fireSpellsForSale || iceSpellsForSale || weaponsForSale || potionsForSale || armorsForSale) { DisplayMarket(false,hero,3); cerr << endl; cerr << "-------------------------------" << endl << endl; cerr << "\033[35mWarning:\033[0m Hero \033[38;5;220m" << hero->Living::GetName() << "\033[0m doesn't have any other available Item and Spell slots." << endl; usleep(2500000); } else cerr << endl << "\033[31mError:\033[0m Hero \033[38;5;220m" << hero->Living::GetName() << "\033[0m doesn't have enough money. The minimum required amount is: " << minPrice << endl; } return -1; } buyState = 0; //Means that he can buy Spells only } else if (hero->GetAvailableSpellSlots() == 0 || hero->GetMoney() < minSpellPrice) { buyState = 1; //Means that he can buy Items only } if (buyState != 1) { unsigned int i; for (i = 0; i < iceSpellsArray.size() && !canBeBought(iceSpellsArray[i],hero); i++) ; if (i < iceSpellsArray.size()) found = true; for (i = 0; i < fireSpellsArray.size() && !canBeBought(fireSpellsArray[i],hero); i++) ; if (i < fireSpellsArray.size()) found = true; for (i = 0; i < lightingSpellsArray.size() && !canBeBought(lightingSpellsArray[i],hero); i++) ; if (i < lightingSpellsArray.size()) found = true; } if (buyState != 0) { unsigned int i; for (i = 0; i < weaponsArray.size() && !canBeBought(weaponsArray[i],hero); i++) ; if (i < weaponsArray.size()) found = true; for (i = 0; i < armorsArray.size() && !canBeBought(armorsArray[i],hero); i++) ; if (i < armorsArray.size()) found = true; for (i = 0; i < potionsArray.size() && !canBeBought(potionsArray[i],hero); i++) ; if (i < potionsArray.size()) found = true; } if (!found) { if (info) { cerr << endl << "\033[31mError:\033[0m There are no available Items or Spells for Hero \033[38;5;220m" << hero->Living::GetName() << "\033[0m to buy." << endl; usleep(3000000); } return -1; } return buyState; } void Market::Purchase(Hero& hero, const int& buyState) { int column, row; char confirmation; bool errFlag = false; string testSelections[2]; cout << endl; cout << "-------------------------------" << endl << endl; cout << "(Type 0 to cancel)" << endl; if (buyState == 0) { cout << "Choose a Spell by selecting its position in the table(e.g.: \033[1;34m<\033[1;33mcolumn\033[1;34m> <\033[1;33mrow\033[1;34m>\033[0m): "; cout << "\n\n\n\n\n\n\n\n"; cout << "\033[8A\033[77C"; } else if (buyState == 1) { cout << "Choose an Item by selecting its position in the table(e.g.: \033[1;34m<\033[1;33mcolumn\033[1;34m> <\033[1;33mrow\033[1;34m>\033[0m): "; cout << "\n\n\n\n\n\n\n\n"; cout << "\033[8A\033[77C"; } else { cout << "Choose an Item or a Spell by selecting its position in the table(e.g.: \033[1;34m<\033[1;33mcolumn\033[1;34m> <\033[1;33mrow\033[1;34m>\033[0m): "; cout << "\n\n\n\n\n\n\n\n"; cout << "\033[8A\033[88C"; } cout << "\033[s"; do { if (errFlag) usleep(1800000); cout << "\033[u"; cout << "\033[J"; cout << "\033[s"; errFlag = true; cin >> testSelections[0]; if (testSelections[0] == "0") { column = 0; break; } cin >> testSelections[1]; } while(!isValidForPurchase(testSelections,column,row,buyState)); if (column == 0) { cout << endl << "\033[1;32mInfo:\033[0m The purchase was canceled." << endl << endl; return; } switch(column) { case 1: cout << endl << "Are you sure you want to buy \"\033[1m\033[38;5;32m" << iceSpellsArray[iceSpellsIndexes[row - 1]]->GetName() << "\033[0m\" Ice Spell? [y/n]: "; do { cin >> confirmation; } while(confirmation != 'y' && confirmation != 'Y' && confirmation != 'n' && confirmation != 'N'); if (confirmation == 'n' || confirmation == 'N') break; hero.ChangeMoney(-iceSpellsArray[iceSpellsIndexes[row - 1]]->GetPrice()); hero.AddNewSpell(iceSpellsArray[iceSpellsIndexes[row - 1]]); iceSpellsArray.erase(iceSpellsArray.begin() + iceSpellsIndexes[row - 1]); RecalcMostItems(); break; case 2: cout << endl << "Are you sure you want to buy \"\033[1m\033[1;31m" << fireSpellsArray[fireSpellsIndexes[row - 1]]->GetName() << "\033[0m\" Fire Spell? [y/n]: "; do { cin >> confirmation; } while(confirmation != 'y' && confirmation != 'Y' && confirmation != 'n' && confirmation != 'N'); if (confirmation == 'n' || confirmation == 'N') break; hero.ChangeMoney(-fireSpellsArray[fireSpellsIndexes[row - 1]]->GetPrice()); hero.AddNewSpell(fireSpellsArray[fireSpellsIndexes[row - 1]]); fireSpellsArray.erase(fireSpellsArray.begin() + fireSpellsIndexes[row - 1]); RecalcMostItems(); break; case 3: cout << endl << "Are you sure you want to buy \"\033[1m\033[38;5;15m" << lightingSpellsArray[lightingSpellsIndexes[row - 1]]->GetName() << "\033[0m\" Lighting Spell? [y/n]: "; do { cin >> confirmation; } while(confirmation != 'y' && confirmation != 'Y' && confirmation != 'n' && confirmation != 'N'); if (confirmation == 'n' || confirmation == 'N') break; hero.ChangeMoney(-lightingSpellsArray[lightingSpellsIndexes[row - 1]]->GetPrice()); hero.AddNewSpell(lightingSpellsArray[lightingSpellsIndexes[row - 1]]); lightingSpellsArray.erase(lightingSpellsArray.begin() + lightingSpellsIndexes[row - 1]); RecalcMostItems(); break; case 4: cout << endl << "Are you sure you want to buy \"\033[1m\033[38;5;166m" << weaponsArray[weaponsIndexes[row - 1]]->GetName() << "\033[0m\" Weapon? [y/n]: "; do { cin >> confirmation; } while(confirmation != 'y' && confirmation != 'Y' && confirmation != 'n' && confirmation != 'N'); if (confirmation == 'n' || confirmation == 'N') break; hero.ChangeMoney(-weaponsArray[weaponsIndexes[row - 1]]->GetPrice()); hero.AddNewItem(weaponsArray[weaponsIndexes[row - 1]]); weaponsArray.erase(weaponsArray.begin() + weaponsIndexes[row - 1]); RecalcMostItems(); break; case 5: cout << endl << "Are you sure you want to buy \"\033[1m\033[38;5;28m" << armorsArray[armorsIndexes[row - 1]]->GetName() << "\033[0m\" Armor? [y/n]: "; do { cin >> confirmation; } while(confirmation != 'y' && confirmation != 'Y' && confirmation != 'n' && confirmation != 'N'); if (confirmation == 'n' || confirmation == 'N') break; hero.ChangeMoney(-(armorsArray[armorsIndexes[row - 1]]->GetPrice())); hero.AddNewItem(armorsArray[armorsIndexes[row - 1]]); armorsArray.erase(armorsArray.begin() + armorsIndexes[row - 1]); RecalcMostItems(); break; case 6: cout << endl << "Are you sure you want to buy \"\033[1m\033[38;5;90m" << potionsArray[potionsIndexes[row - 1]]->GetName() << "\033[0m\" Potion? [y/n]: "; do { cin >> confirmation; } while(confirmation != 'y' && confirmation != 'Y' && confirmation != 'n' && confirmation != 'N'); if (confirmation == 'n' || confirmation == 'N') break; hero.ChangeMoney(-potionsArray[potionsIndexes[row - 1]]->GetPrice()); hero.AddNewItem(potionsArray[potionsIndexes[row - 1]]); potionsArray.erase(potionsArray.begin() + potionsIndexes[row - 1]); RecalcMostItems(); break; } } void Market::Buy(vector<Hero *>& heroes) { unsigned int i; int action; string testAction; bool infoState = false; Hero* selectedHero = NULL; if (heroes.size() == 1 && isAbleToBuy(heroes[0]) == -1) { usleep(2500000); DisplayMarket(); return; } else { for (i = 0; i < heroes.size() && isAbleToBuy(heroes[i],false) == -1; i++) ; if (i == heroes.size()) { cerr << endl << "\033[31mError:\033[0m No one of the heroes are able to buy any Items or Spells from the Market."; usleep(2500000); DisplayMarket(); return; } } while(true) { int buyState; if (heroes.size() == 1) { selectedHero = heroes[0]; } else { for (i = 0; i < heroes.size() && isAbleToBuy(heroes[i],false) == -1; i++) ; if (i == heroes.size()) { cerr << endl << "-------------------------------" << endl << endl; cerr << "\033[35mWarning:\033[0m There are no other heroes able to buy any Items or Spells from the Market."; usleep(3000000); DisplayMarket(); return; } while(selectedHero == NULL) { //bool errorFlag = false; cout << endl; cout << "-------------------------------" << endl << endl; cout << "(Type 0 to cancel)" << endl; cout << "Choose a Hero (1 - " << heroes.size() << "): "; cout << "\n\n\n\n\n"; cout << "\033[5A\033[23C"; while(true) { bool errFlag = false; cout << "\033[s"; do { if (errFlag) usleep(1800000); cout << "\033[u"; cout << "\033[J"; cout << "\033[s"; cin >> testAction; errFlag = true; } while(!isNumeric(testAction.c_str(),action)); if (action < 0 || action > heroes.size()) { cerr << endl << "\033[31mError:\033[0m Please choose a number in the given range." << endl; usleep(1800000); cout << "\033[u"; cout << "\033[J"; //cout << "\033[K"; //cout << "\033[1A\033[K"; //cout << "\033[1A\033[K"; //if (errorFlag) // cout << "\033[1A\033[K"; //errorFlag = true; } else { if (!action) { DisplayMarket(); return; } selectedHero = heroes[action - 1]; break; } } } } if ((buyState = isAbleToBuy(selectedHero)) != -1) { bool errFlag = false; DisplayMarket(infoState,selectedHero,buyState); cout << endl; cout << "-------------------------------" << endl << endl; cout << "Choose an action: "; cout << "\n\n\n\n\n"; cout << "\033[5A\033[18C"; cout << "\033[s"; do { if (errFlag) usleep(1800000); cout << "\033[u"; cout << "\033[J"; cout << "\033[s"; cin >> testAction; errFlag = true; } while(!isValid(testAction.c_str(),action,1,3)); switch(action) { case 1: Purchase(*selectedHero,buyState); break; case 2: infoState = !infoState; // DisplayMarket(infoState,selectedHero,buyState); break; case 3: DisplayMarket(); return; } } else if (heroes.size() == 1) { usleep(2500000); DisplayMarket(); return; } if (buyState == -1) { DisplayMarket(); return; } // selectedHero = NULL; } } int Market::isAbleToSell(const Hero* hero, const bool& info = true) { int sellState = 2; if (hero->GetAvailableItemSlots() == hero->GetMaxItemsSlots()) { if (hero->GetAvailableSpellSlots() == hero->GetMaxSpellsSlots()) { if (info) { cerr << endl << "\033[31mError:\033[0m Hero \033[38;5;220m" << hero->Living::GetName() << "\033[0m doesn't have any Items or Spells for sale." << endl; usleep(2500000); } return -1; } sellState = 0; //Means that he can sell Spells only } else if (hero->GetAvailableSpellSlots() == hero->GetMaxSpellsSlots()) { sellState = 1; //Means that he can buy Items only } return sellState; } void Market::Sale(Hero& hero, const int& sellState) { int column, row; char confirmation; bool errFlag = false; string testSelections[2]; cout << endl; cout << "-------------------------------" << endl << endl; cout << "(Type 0 to cancel)" << endl; if (sellState == 0) { cout << "Choose a Spell by selecting its position in the table(e.g.: \033[1;34m<\033[1;33mcolumn\033[1;34m> <\033[1;33mrow\033[1;34m>\033[0m): "; cout << "\n\n\n\n\n\n\n\n"; cout << "\033[8A\033[77C"; } else if (sellState == 1) { cout << "Choose an Item by selecting its position in the table(e.g.: \033[1;34m<\033[1;33mcolumn\033[1;34m> <\033[1;33mrow\033[1;34m>\033[0m): "; cout << "\n\n\n\n\n\n\n\n"; cout << "\033[8A\033[77C"; } else { cout << "Choose an Item or a Spell by selecting its position in the table(e.g.: \033[1;34m<\033[1;33mcolumn\033[1;34m> <\033[1;33mrow\033[1;34m>\033[0m): "; cout << "\n\n\n\n\n\n\n\n"; cout << "\033[8A\033[88C"; } cout << "\033[s"; do { if (errFlag) usleep(1800000); cout << "\033[u"; cout << "\033[J"; cout << "\033[s"; errFlag = true; cin >> testSelections[0]; if (testSelections[0] == "0") { column = 0; break; } cin >> testSelections[1]; } while(!hero.isValidForSale(testSelections,column,row,sellState)); if (column == 0) { cout << endl << "\033[1;32mInfo:\033[0m The sale operation was canceled." << endl << endl; return; } switch(column) { case 1: if (sellState == 1) { cout << endl << "Are you sure you want to sell \"\033[1m\033[38;5;166m" << hero.GetWeaponFromSlot(row - 1)->GetName() << "\033[0m\" Weapon? [y/n]: "; do { cin >> confirmation; } while(confirmation != 'y' && confirmation != 'Y' && confirmation != 'n' && confirmation != 'N'); if (confirmation == 'n' || confirmation == 'N') break; hero.RemoveWeapon(row - 1); } else { cout << endl << "Are you sure you want to sell \"\033[1m\033[38;5;32m" << hero.GetSpellFromSlot(row - 1, 2)->GetName() << "\033[0m\" Ice Spell? [y/n]: "; do { cin >> confirmation; } while(confirmation != 'y' && confirmation != 'Y' && confirmation != 'n' && confirmation != 'N'); if (confirmation == 'n' || confirmation == 'N') break; hero.RemoveIceSpell(row - 1); } break; case 2: if (sellState == 1) { cout << endl << "Are you sure you want to sell \"\033[1m\033[38;5;28m" << hero.GetArmorFromSlot(row - 1)->GetName() << "\033[0m\" Armor? [y/n]: "; do { cin >> confirmation; } while(confirmation != 'y' && confirmation != 'Y' && confirmation != 'n' && confirmation != 'N'); if (confirmation == 'n' || confirmation == 'N') break; hero.RemoveArmor(row - 1); } else { cout << endl << "Are you sure you want to sell \"\033[1m\033[1;31m" << hero.GetSpellFromSlot(row - 1, 3)->GetName() << "\033[0m\" Fire Spell? [y/n]: "; do { cin >> confirmation; } while(confirmation != 'y' && confirmation != 'Y' && confirmation != 'n' && confirmation != 'N'); if (confirmation == 'n' || confirmation == 'N') break; hero.RemoveFireSpell(row - 1); } break; case 3: if (sellState == 1) { cout << endl << "Are you sure you want to sell \"\033[1m\033[38;5;90m" << hero.GetPotionFromSlot(row - 1)->GetName() << "\033[0m\" Potion? [y/n]: "; do { cin >> confirmation; } while(confirmation != 'y' && confirmation != 'Y' && confirmation != 'n' && confirmation != 'N'); if (confirmation == 'n' || confirmation == 'N') break; hero.RemovePotion(row - 1); } else { cout << endl << "Are you sure you want to sell \"\033[1m\033[38;5;15m" << hero.GetSpellFromSlot(row - 1, 1)->GetName() << "\033[0m\" Lighting Spell? [y/n]: "; do { cin >> confirmation; } while(confirmation != 'y' && confirmation != 'Y' && confirmation != 'n' && confirmation != 'N'); if (confirmation == 'n' || confirmation == 'N') break; hero.RemoveLightingSpell(row - 1); } break; case 4: cout << endl << "Are you sure you want to sell \"\033[1m\033[38;5;166m" << hero.GetWeaponFromSlot(row - 1)->GetName() << "\033[0m\" Weapon? [y/n]: "; do { cin >> confirmation; } while(confirmation != 'y' && confirmation != 'Y' && confirmation != 'n' && confirmation != 'N'); if (confirmation == 'n' || confirmation == 'N') break; hero.RemoveWeapon(row - 1); break; case 5: cout << endl << "Are you sure you want to sell \"\033[1m\033[38;5;28m" << hero.GetArmorFromSlot(row - 1)->GetName() << "\033[0m\" Armor? [y/n]: "; do { cin >> confirmation; } while(confirmation != 'y' && confirmation != 'Y' && confirmation != 'n' && confirmation != 'N'); if (confirmation == 'n' || confirmation == 'N') break; hero.RemoveArmor(row - 1); break; case 6: cout << endl << "Are you sure you want to sell \"\033[1m\033[38;5;90m" << hero.GetPotionFromSlot(row - 1)->GetName() << "\033[0m\" Potion? [y/n]: "; do { cin >> confirmation; } while(confirmation != 'y' && confirmation != 'Y' && confirmation != 'n' && confirmation != 'N'); if (confirmation == 'n' || confirmation == 'N') break; hero.RemovePotion(row - 1); break; } } void Market::Sell(vector<Hero *>& heroes) { unsigned int i; int action; string testAction; bool infoState = false; Hero* selectedHero = NULL; if (heroes.size() == 1 && isAbleToSell(heroes[0]) == -1) { usleep(2500000); DisplayMarket(); return; } else { for (i = 0; i < heroes.size() && isAbleToSell(heroes[i],false) == -1; i++) ; if (i == heroes.size()) { cerr << endl << "\033[31mError:\033[0m No one of the heroes have any Items or Spells for sale."; usleep(2500000); DisplayMarket(); return; } } while(true) { int sellState; if (heroes.size() == 1) { selectedHero = heroes[0]; } else { for (i = 0; i < heroes.size() && isAbleToSell(heroes[i],false) == -1; i++) ; if (i == heroes.size()) { cerr << endl << "-------------------------------" << endl << endl; cerr << "\033[35mWarning:\033[0m No one of the heroes have any Items or Spells left for sale."; usleep(2500000); DisplayMarket(); return; } while(selectedHero == NULL) { //bool errorFlag = false; cout << endl; cout << "-------------------------------" << endl << endl; cout << "(Type 0 to cancel)" << endl; cout << "Choose a Hero (1 - " << heroes.size() << "): "; cout << "\n\n\n\n\n"; cout << "\033[5A\033[23C"; while(true) { bool errFlag = false; cout << "\033[s"; do { if (errFlag) usleep(1800000); cout << "\033[u"; cout << "\033[J"; cout << "\033[s"; cin >> testAction; errFlag = true; } while(!isNumeric(testAction.c_str(),action)); if (action < 0 || action > heroes.size()) { cerr << endl << "\033[31mError:\033[0m Please choose a number in the given range." << endl; usleep(1800000); cout << "\033[u"; cout << "\033[J"; //cout << "\033[K"; //cout << "\033[1A\033[K"; //cout << "\033[1A\033[K"; //if (errorFlag) // cout << "\033[1A\033[K"; //errorFlag = true; } else { if (!action) { DisplayMarket(); return; } selectedHero = heroes[action - 1]; break; } } } } if ((sellState = isAbleToSell(selectedHero)) != -1) { bool errFlag = false; selectedHero->DisplayProdsForSale(infoState,sellState); cout << endl; /*if (sellState == 0 || sellState == 1) { cout << "\033[44C-------------------------------" << endl << endl; cout << "\033[44CChoose an action: "; } else {*/ cout << "-------------------------------" << endl << endl; cout << "Choose an action: "; //} cout << "\n\n\n\n\n"; cout << "\033[5A\033[18C"; cout << "\033[s"; do { if (errFlag) usleep(1800000); cout << "\033[u"; cout << "\033[J"; cout << "\033[s"; cin >> testAction; errFlag = true; } while(!isValid(testAction.c_str(),action,1,3)); switch(action) { case 1: Sale(*selectedHero,sellState); break; case 2: infoState = !infoState; //selectedHero->DisplayProdsForSale(infoState,sellState); break; case 3: DisplayMarket(); return; } } else if (heroes.size() == 1) { usleep(2500000); DisplayMarket(); return; } if (sellState == -1) { DisplayMarket(); return; } } } bool Market::EnterMarket(vector<Hero *>& heroes) { int action; //int buyState; string testAction; bool infoState = false; NewStuff(heroes); DisplayMarket(); while(true){ bool errFlag = false; cout << endl; cout << "-------------------------------" << endl << endl; cout << "Choose an action: "; cout << "\n\n\n\n\n"; cout << "\033[5A\033[18C"; cout << "\033[s"; do { if (errFlag) usleep(1800000); cout << "\033[u"; cout << "\033[J"; cout << "\033[s"; cin >> testAction; errFlag = true; } while(!isValid(testAction.c_str(),action,1,4)); switch(action) { case 1: Buy(heroes); break; case 2: Sell(heroes); break; case 3: infoState = !infoState; DisplayMarket(infoState); break; case 4: return false; } } } bool Market::canBeBought(const Item* item, const Hero* hero) { if (hero->GetMoney() < item->GetPrice()) return false; if (hero->Living::GetLevel() < item->GetMinReqLevel()) return false; return true; } bool Market::canBeBought(const Spell* spell, const Hero* hero) { if (hero->GetMoney() < spell->GetPrice()) return false; if (hero->Living::GetLevel() < spell->GetMinReqLevel()) return false; return true; } void Market::DisplayMarket(const bool& showInfo, const Hero* hero, const int buyState) { cout << "\033[2J\033[1;1H"; cout << "\033[1;33m+\033[0;34m=========================================================================================================================================================================================\033[1;33m+\033[0m" << endl; cout << "\033[34m|\033[0m Welcome to the Market \033[34m|\033[0m" << endl; cout << "\033[1;33m+\033[0;34m=========================================================================================================================================================================================\033[1;33m+\033[0m" << endl; if (buyState != -1) { if (showInfo) cout << "\033[34m|\033[0m \033[4mAvailable Actions\033[0m: 1. Purchase, 2. Disable Info, 3. Cancel \033[34m|\033[0m" << endl; else cout << "\033[34m|\033[0m \033[4mAvailable Actions\033[0m: 1. Purchase, 2. Info, 3. Cancel \033[34m|\033[0m" << endl; } else { if (showInfo) cout << "\033[34m|\033[0m \033[4mAvailable Actions\033[0m: 1. Buy, 2. Sell, 3. Disable Info, 4. Exit \033[34m|\033[0m" << endl; else cout << "\033[34m|\033[0m \033[4mAvailable Actions\033[0m: 1. Buy, 2. Sell, 3. Info, 4. Exit \033[34m|\033[0m" << endl; } cout << "\033[1;33m+\033[0;34m=========================================================================================================================================================================================\033[1;33m+\033[0m" << endl; cout << "\033[34m|\033[0m Spells \033[34m|\033[0m Items \033[34m|\033[0m" << endl; if (showInfo) { cout << "\033[34m|--------------------------------------------------------------------------------------------\033[1;33m+\033[0;34m--------------------------------------------------------------------------------------------|\033[0m" << endl; cout << "\033[34m|\033[0m --> Spells are representing a magic attack that a hero can perform \033[34m|\033[0m --> There are items that a hero can use for attacking enemies, avoiding their attacks \033[34m|\033[0m" << endl; cout << "\033[34m|\033[0m --> They cause an amount of damage according to the hero's dexterity \033[34m|\033[0m and items that increase some of his features \033[34m|\033[0m" << endl; cout << "\033[34m|\033[0m --> They require a specific Magic Power that the hero must have in order to use them \033[34m|\033[0m --> Some of them can be used one time only \033[34m|\033[0m" << endl; cout << "\033[34m|\033[0m --> After the use of a spell the Hero's Magic Power will be reduced \033[34m|\033[0m \033[34m|\033[0m" << endl; } cout << "\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0m" << endl; cout << "\033[34m|\033[0m # \033[34m|\033[0m \033[38;5;32mIce Spells\033[0m \033[34m|\033[0m # \033[34m|\033[0m \033[1;31mFire Spells\033[0m \033[34m|\033[0m # \033[34m|\033[0m \033[38;5;15mLighting Spells\033[0m \033[34m|\033[0m # \033[34m|\033[0m \033[38;5;166mWeapons\033[0m \033[34m|\033[0m # \033[34m|\033[0m \033[38;5;28mArmors\033[0m \033[34m|\033[0m # \033[34m|\033[0m \033[38;5;90mPotions\033[0m \033[34m|\033[0m" << endl; if (showInfo) { cout << "\033[1;33m+\033[0;34m---\033[1;33m+\033[0;34m--------------------------\033[1;33m+\033[0;34m---\033[1;33m+\033[0;34m--------------------------\033[1;33m+\033[0;34m---\033[1;33m+\033[0;34m--------------------------\033[1;33m+\033[0;34m---\033[1;33m+\033[0;34m--------------------------\033[1;33m+\033[0;34m---\033[1;33m+\033[0;34m--------------------------\033[1;33m+\033[0;34m---\033[1;33m+\033[0;34m--------------------------|\033[0m" << endl; cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m Ice Spells reduce \033[34m|\033[1;33m(i)\033[0;34m|\033[0m Fire Spells reduce \033[34m|\033[1;33m(i)\033[0;34m|\033[0m Lighting Spells reduce \033[34m|\033[1;33m(i)\033[0;34m|\033[0m Weapons cause damage \033[34m|\033[1;33m(i)\033[0;34m|\033[0m Armors reduce the \033[34m|\033[1;33m(i)\033[0;34m|\033[0m Potions increase \033[34m|\033[0m" << endl; cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m enemy's damage range \033[34m|\033[1;33m(i)\033[0;34m|\033[0m enemy's defence \033[34m|\033[1;33m(i)\033[0;34m|\033[0m enemy's chance to \033[34m|\033[1;33m(i)\033[0;34m|\033[0m to the enemies and \033[34m|\033[1;33m(i)\033[0;34m|\033[0m received damage \033[34m|\033[1;33m(i)\033[0;34m|\033[0m a hero's specific \033[34m|\033[0m" << endl; cout << "\033[34m| | | | |\033[1;33m(i)\033[0;34m|\033[0m avoid an attack \033[34m|\033[1;33m(i)\033[0;34m|\033[0m they require one \033[34m| | |\033[1;33m(i)\033[0;34m|\033[0m feature and can \033[34m|\033[0m" << endl; cout << "\033[34m| | | | | | |\033[1;33m(i)\033[0;34m|\033[0m or two hands \033[34m| | |\033[1;33m(i)\033[0;34m|\033[0m be used only once \033[34m|\033[0m" << endl; } cout << "\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0m" << endl; if (buyState != -1) ResetForSaleProds(); for (unsigned int i = 0, ice_i = 0, fire_i = 0, light_i = 0, wpn_i = 0, arm_i = 0, ptn_i = 0; i < mostItems; i++, ice_i++, fire_i++, light_i++, wpn_i++, arm_i++, ptn_i++) { short terminationState = 0; if (buyState != -1) { while(ice_i < iceSpellsArray.size() && !canBeBought(iceSpellsArray[ice_i],hero)) ice_i++; } if (ice_i < iceSpellsArray.size()) { if (i < 9) cout << "\033[34m|\033[0m " << i+1 << " "; else if (i < 99) cout << "\033[34m|\033[0m " << i+1; else if (i < 999) cout << "\033[34m|\033[0m" << i+1; iceSpellsIndexes.insert(iceSpellsIndexes.begin() + i , ice_i); cout << "\033[34m| \033[0m\u2022 "; if (showInfo) cout << "\033[1;33m"; if (buyState == 1 || buyState == 3) cout << "\033[1;31m"; cout.width(23); iceSpellsForSale++; cout << left << iceSpellsArray[ice_i]->GetName() << "\033[0m"; } else { if (terminationState == 0) terminationState++; cout << "\033[34m| |\033[0m\033[26C"; } if (buyState != -1) { while(fire_i < fireSpellsArray.size() && !canBeBought(fireSpellsArray[fire_i],hero)) fire_i++; } if (fire_i < fireSpellsArray.size()) { if (i < 9) cout << "\033[34m|\033[0m " << i+1 << " "; else if (i < 99) cout << "\033[34m|\033[0m " << i+1; else if (i < 999) cout << "\033[34m|\033[0m" << i+1; fireSpellsIndexes.insert(fireSpellsIndexes.begin() + i , fire_i); cout << "\033[34m| \033[0m\u2022 "; if (showInfo) cout << "\033[1;33m"; if (buyState == 1 || buyState == 3) cout << "\033[1;31m"; cout.width(23); fireSpellsForSale++; cout << left << fireSpellsArray[fire_i]->GetName() << "\033[0m"; } else { if (terminationState == 1) terminationState++; cout << "\033[34m| |\033[0m\033[26C"; } if (buyState != -1) { while(light_i < lightingSpellsArray.size() && !canBeBought(lightingSpellsArray[light_i],hero)) light_i++; } if (light_i < lightingSpellsArray.size()) { if (i < 9) cout << "\033[34m|\033[0m " << i+1 << " "; else if (i < 99) cout << "\033[34m|\033[0m " << i+1; else if (i < 999) cout << "\033[34m|\033[0m" << i+1; lightingSpellsIndexes.insert(lightingSpellsIndexes.begin() + i , light_i); cout << "\033[34m| \033[0m\u2022 "; if (showInfo) cout << "\033[1;33m"; if (buyState == 1 || buyState == 3) cout << "\033[1;31m"; cout.width(23); lightingSpellsForSale++; cout << left << lightingSpellsArray[light_i]->GetName() << "\033[0m"; } else { if (terminationState == 2) terminationState++; cout << "\033[34m| |\033[0m\033[26C"; } if (buyState != -1) { while(wpn_i < weaponsArray.size() && !canBeBought(weaponsArray[wpn_i],hero)) wpn_i++; } if (wpn_i < weaponsArray.size()) { if (i < 9) cout << "\033[34m|\033[0m " << i+1 << " "; else if (i < 99) cout << "\033[34m|\033[0m " << i+1; else if (i < 999) cout << "\033[34m|\033[0m" << i+1; weaponsIndexes.insert(weaponsIndexes.begin() + i , wpn_i); cout << "\033[34m| \033[0m\u2022 "; if (showInfo) cout << "\033[1;33m"; if (buyState == 0 || buyState == 3) cout << "\033[1;31m"; cout.width(23); weaponsForSale++; cout << left << weaponsArray[wpn_i]->GetName() << "\033[0m"; } else { if (terminationState == 3) terminationState++; cout << "\033[34m| |\033[0m\033[26C"; // \033[23C } if (buyState != -1) { while(arm_i < armorsArray.size() && !canBeBought(armorsArray[arm_i],hero)) arm_i++; } if (arm_i < armorsArray.size()) { if (i < 9) cout << "\033[34m|\033[0m " << i+1 << " "; else if (i < 99) cout << "\033[34m|\033[0m " << i+1; else if (i < 999) cout << "\033[34m|\033[0m" << i+1; armorsIndexes.insert(armorsIndexes.begin() + i , arm_i); cout << "\033[34m| \033[0m\u2022 "; if (showInfo) cout << "\033[1;33m"; if (buyState == 0 || buyState == 3) cout << "\033[1;31m"; cout.width(23); armorsForSale++; cout << left << armorsArray[arm_i]->GetName() << "\033[0m"; } else { if (terminationState == 4) terminationState++; cout << "\033[34m| |\033[0m\033[26C"; //\033[22C } if (buyState != -1) { while(ptn_i < potionsArray.size() && !canBeBought(potionsArray[ptn_i],hero)) ptn_i++; } if (ptn_i < potionsArray.size()) { if (i < 9) cout << "\033[34m|\033[0m " << i+1 << " "; else if (i < 99) cout << "\033[34m|\033[0m " << i+1; else if (i < 999) cout << "\033[34m|\033[0m" << i+1; potionsIndexes.insert(potionsIndexes.begin() + i , ptn_i); cout << "\033[34m| \033[0m\u2022 "; if (showInfo) cout << "\033[1;33m"; if (buyState == 0 || buyState == 3) cout << "\033[1;31m"; cout.width(23); potionsForSale++; cout << left << potionsArray[ptn_i]->GetName() << "\033[0;34m|\033[0m" << endl; } else { if (terminationState == 5) terminationState++; cout << "\033[34m| |\033[26C|\033[0m" << endl; //\033[21C } if (terminationState == 6) { cout << "\033[1A"; break; } /* if (ice_i >= iceSpellsArray.size() && fire_i >= fireSpellsArray.size() && light_i >= lightingSpellsArray.size() && wpn_i >= weaponsArray.size() && arm_i >= armorsArray.size() && ptn_i >= potionsArray.size()) { if (showInfo) cout << "\033[2A"; else cout << "\033[1A"; cout << "\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0m" << endl; if (showInfo) { cout << " " << endl; cout << "\033[1A"; } if (buyState != -1) { cout << endl << "\033[38;5;220m Hero: \033[0m" << hero->GetName() << endl; cout << "\033[38;5;220mLevel: \033[0m" << hero->GetLevel() << endl; cout << "\033[38;5;220mMoney: \033[0m" << hero->GetMoney() << endl; } cout << endl << "\t\t\t\t MOST ITEMS 1 = " << mostItems << endl; return; }*/ if (showInfo) { /* ------------------------------- Start of 1st Line ------------------------------- */ if (ice_i < iceSpellsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Price: "; cout.width(15); cout << left << iceSpellsArray[ice_i]->GetPrice(); } else cout << "\033[34m| |\033[0m\033[26C"; if (fire_i < fireSpellsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Price: "; cout.width(15); cout << left << fireSpellsArray[fire_i]->GetPrice(); } else cout << "\033[34m| |\033[0m\033[26C"; if (light_i < lightingSpellsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Price: "; cout.width(15); cout << left << lightingSpellsArray[light_i]->GetPrice(); } else cout << "\033[34m| |\033[0m\033[26C"; if (wpn_i < weaponsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Price: "; cout.width(15); cout << left << weaponsArray[wpn_i]->GetPrice(); } else cout << "\033[34m| |\033[0m\033[26C"; if (arm_i < armorsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Price: "; cout.width(15); cout << left << armorsArray[arm_i]->GetPrice(); } else cout << "\033[34m| |\033[0m\033[26C"; if (ptn_i < potionsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Price: "; cout.width(15); cout << left << potionsArray[ptn_i]->GetPrice() << "\033[34m|\033[0m" << endl; } else cout << "\033[34m| |\033[26C|\033[0m" << endl; /* -------------------------------- End of 1st Line -------------------------------- */ /* ------------------------------- Start of 2nd Line ------------------------------- */ if (ice_i < iceSpellsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Required Level: "; cout.width(6); cout << left << iceSpellsArray[ice_i]->GetMinReqLevel(); } else cout << "\033[34m| |\033[0m\033[26C"; if (fire_i < fireSpellsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Required Level: "; cout.width(6); cout << left << fireSpellsArray[fire_i]->GetMinReqLevel(); } else cout << "\033[34m| |\033[0m\033[26C"; if (light_i < lightingSpellsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Required Level: "; cout.width(6); cout << left << lightingSpellsArray[light_i]->GetMinReqLevel(); } else cout << "\033[34m| |\033[0m\033[26C"; if (wpn_i < weaponsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Required Level: "; cout.width(6); cout << left << weaponsArray[wpn_i]->GetMinReqLevel(); } else cout << "\033[34m| |\033[0m\033[26C"; if (arm_i < armorsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Required Level: "; cout.width(6); cout << left << armorsArray[arm_i]->GetMinReqLevel(); } else cout << "\033[34m| |\033[0m\033[26C"; if (ptn_i < potionsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Required Level: "; cout.width(6); cout << left << potionsArray[ptn_i]->GetMinReqLevel() << "\033[34m|\033[0m" << endl; } else cout << "\033[34m| |\033[26C|\033[0m" << endl; /* -------------------------------- End of 2nd Line -------------------------------- */ /* ------------------------------- Start of 3rd Line ------------------------------- */ if (ice_i < iceSpellsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Required MP: "; cout.width(9); cout << left << iceSpellsArray[ice_i]->GetReqEnergy(); } else cout << "\033[34m| |\033[0m\033[26C"; if (fire_i < fireSpellsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Required MP: "; cout.width(9); cout << left << fireSpellsArray[fire_i]->GetReqEnergy(); } else cout << "\033[34m| |\033[0m\033[26C"; if (light_i < lightingSpellsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Required MP: "; cout.width(9); cout << left << lightingSpellsArray[light_i]->GetReqEnergy(); } else cout << "\033[34m| |\033[0m\033[26C"; if (wpn_i < weaponsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Damage: "; cout.width(14); cout << left << weaponsArray[wpn_i]->GetDamage(); } else cout << "\033[34m| |\033[0m\033[26C"; if (arm_i < armorsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Damage Reduction: "; cout.width(4); cout << left << armorsArray[arm_i]->GetDamageReduction(); } else cout << "\033[34m| |\033[0m\033[26C"; if (ptn_i < potionsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Power-Up: "; cout.width(12); if (potionsArray[ptn_i]->PotionIncreaseStrength()) { string str = "+" + to_string(potionsArray[ptn_i]->PotionIncreaseStrength()) + " str/th"; cout << str << "\033[34m|\033[0m" << endl; } else if (potionsArray[ptn_i]->PotionIncreaseDexterity()) { string str = "+" + to_string(potionsArray[ptn_i]->PotionIncreaseDexterity()) + " dext/ty"; cout << str << "\033[34m|\033[0m" << endl; } else { string str = "+" + to_string((int)(potionsArray[ptn_i]->PotionIncreaseAgility() * 100)) + "\% agility"; cout << str << "\033[34m|\033[0m" << endl; } } else cout << "\033[34m| |\033[26C|\033[0m" << endl; /* -------------------------------- End of 3rd Line -------------------------------- */ /* ------------------------------- Start of 4th Line ------------------------------- */ if (ice_i < iceSpellsArray.size()) { string str = to_string(iceSpellsArray[ice_i]->GetMinDamage()) + "-" + to_string(iceSpellsArray[ice_i]->GetMaxDamage()); cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Damage Range: "; cout.width(8); cout << left << str; } else cout << "\033[34m| |\033[0m\033[26C"; if (fire_i < fireSpellsArray.size()) { string str = to_string(fireSpellsArray[fire_i]->GetMinDamage()) + "-" + to_string(fireSpellsArray[fire_i]->GetMaxDamage()); cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Damage Range: "; cout.width(8); cout << left << str; } else cout << "\033[34m| |\033[0m\033[26C"; if (light_i < lightingSpellsArray.size()) { string str = to_string(lightingSpellsArray[light_i]->GetMinDamage()) + "-" + to_string(lightingSpellsArray[light_i]->GetMaxDamage()); cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Damage Range: "; cout.width(8); cout << left << str; } else cout << "\033[34m| |\033[0m\033[26C"; if (wpn_i < weaponsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Required Hands: "; cout.width(6); if (weaponsArray[wpn_i]->TwoHanded()) cout << left << "2"; else cout << left << "1"; } else cout << "\033[34m| |\033[0m\033[26C"; cout << "\033[34m| |\033[26C"; cout << "| |\033[26C|\033[0m" << endl; /* -------------------------------- End of 4th Line -------------------------------- */ /* ------------------------------- Start of 5th Line ------------------------------- */ if (ice_i < iceSpellsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Enemy Damage . "; cout.width(7); cout << left << (to_string(iceSpellsArray[ice_i]->GetDamageReduction()) + " HP"); } else cout << "\033[34m| |\033[0m\033[26C"; if (fire_i < fireSpellsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Enemy Defence . "; cout.width(6); cout << left << fireSpellsArray[fire_i]->GetDefenceReduction(); } else cout << "\033[34m| |\033[0m\033[26C"; if (light_i < lightingSpellsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Enemy Avoidance . "; cout.width(4); cout << left << (to_string(lightingSpellsArray[light_i]->GetAvoidanceReduction()) + "%"); } else cout << "\033[34m| |\033[0m\033[26C"; cout << "\033[34m| |\033[26C"; cout << "| |\033[26C"; cout << "| |\033[26C|\033[0m" << endl; /* -------------------------------- End of 5th Line -------------------------------- */ /* ------------------------------- Start of 6th Line ------------------------------- */ if (ice_i < iceSpellsArray.size()) cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m Reduction · "; else cout << "\033[34m| |\033[0m\033[26C"; if (fire_i < fireSpellsArray.size()) cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m Reduction · "; else cout << "\033[34m| |\033[0m\033[26C"; if (light_i < lightingSpellsArray.size()) cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m Reduction · "; else cout << "\033[34m| |\033[0m\033[26C"; cout << "\033[34m| |\033[26C"; cout << "| |\033[26C"; cout << "| |\033[26C|\033[0m" << endl; /* -------------------------------- End of 6th Line -------------------------------- */ /* ------------------------------- Start of 7th Line ------------------------------- */ if (ice_i < iceSpellsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Applies to: "; cout.width(10); if (iceSpellsArray[ice_i]->GetRounds() == 1) cout << left << (to_string(iceSpellsArray[ice_i]->GetRounds()) + " round"); else cout << left << (to_string(iceSpellsArray[ice_i]->GetRounds()) + " rounds"); } else cout << "\033[34m| |\033[0m\033[26C"; if (fire_i < fireSpellsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Applies to: "; cout.width(10); if (fireSpellsArray[fire_i]->GetRounds() == 1) cout << left << (to_string(fireSpellsArray[fire_i]->GetRounds()) + " round"); else cout << left << (to_string(fireSpellsArray[fire_i]->GetRounds()) + " rounds"); } else cout << "\033[34m| |\033[0m\033[26C"; if (light_i < lightingSpellsArray.size()) { cout << "\033[34m|\033[1;33m(i)\033[0;34m|\033[0m ~> Applies to: "; cout.width(10); if (lightingSpellsArray[light_i]->GetRounds() == 1) cout << left << (to_string(lightingSpellsArray[light_i]->GetRounds()) + " round"); else cout << left << (to_string(lightingSpellsArray[light_i]->GetRounds()) + " rounds"); } else cout << "\033[34m| |\033[0m\033[26C"; cout << "\033[34m| |\033[26C"; cout << "| |\033[26C"; cout << "| |\033[26C|\033[0m" << endl; /* -------------------------------- End of 7th Line -------------------------------- */ cout << "\033[34m| |\033[26C| |\033[26C| |\033[26C| |\033[26C| |\033[26C| |\033[26C|\033[0m" << endl; } if (hero == NULL) usleep(40000); } if (showInfo) cout << "\033[K\033[1A\033[K"; cout << "\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0;34m===\033[1;33m+\033[0;34m==========================\033[1;33m+\033[0m" << endl; if (hero != NULL) { cout << endl; cout << "\033[38;5;220m Hero: \033[0m" << hero->GetName() << endl; cout << "\033[38;5;220m Level: \033[0m" << hero->GetLevel() << endl; cout << "\033[38;5;220m Money: \033[0m" << hero->GetMoney() << endl; cout << "\033[38;5;220m Items: \033[0m(" << hero->GetMaxItemsSlots() - hero->GetAvailableItemSlots() << "/" << hero->GetMaxItemsSlots() << ")" << endl; cout << "\033[38;5;220mSpells: \033[0m(" << hero->GetMaxSpellsSlots() - hero->GetAvailableSpellSlots() << "/" << hero->GetMaxSpellsSlots() << ")" << endl; } }
38.09245
524
0.436912
MichaelXanth
a5639343acaa9d179e3370c34b5aa55147d01427
14,059
cpp
C++
HTWK_SD_FILTER/SD_FreestyleSchnapsSaufen/Freestyle.cpp
HTWKSmartDriving/aadc-2015
95ee77aa0f9ebbb541bbb1e3b99d3f044347d103
[ "BSD-2-Clause" ]
2
2017-11-29T00:15:26.000Z
2017-11-29T01:45:54.000Z
HTWK_SD_FILTER/SD_FreestyleSchnapsSaufen/Freestyle.cpp
HTWKSmartDriving/aadc-2015
95ee77aa0f9ebbb541bbb1e3b99d3f044347d103
[ "BSD-2-Clause" ]
null
null
null
HTWK_SD_FILTER/SD_FreestyleSchnapsSaufen/Freestyle.cpp
HTWKSmartDriving/aadc-2015
95ee77aa0f9ebbb541bbb1e3b99d3f044347d103
[ "BSD-2-Clause" ]
2
2017-11-28T23:47:27.000Z
2019-07-19T08:04:50.000Z
/** * Copyright (c) 2014-2015, HTWK SmartDriving * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * AUTHORS: Silvio Feig, Denny Hecht, Andreas Kluge, Lars Kollmann, Eike Florian Petersen, Artem Pokas * */ #include "stdafx.h" ADTF_FILTER_PLUGIN(FILTER_NAME, OID_NEW_LANE_DETECTION, Test); Test::Test(const char *__info) : cFilter(__info) { this->isFirstFrame = true; this->isStopLineFound = false; this->isConnectedToServer = false; this->crossroadDetector.reset(new CrossRoadDetector()); this->driveAlgorithm.reset(new DriveAlgorithm()); this->tcpClient.reset(new Client()); this->stopOnStopLine = false; this->tcpServer.reset(new Server(60000)); this->ip = "192.168.1.253"; SetPropertyStr(PROP_NAME_IP, this->ip.c_str()); SetPropertyBool(PROP_NAME_IP NSSUBPROP_REQUIRED, tTrue); SetPropertyBool(PROP_NAME_IP NSSUBPROP_ISCHANGEABLE, tTrue); this->numberOfStopLines = 20; SetPropertyInt(PROP_NAME_STOP_LINES, this->numberOfStopLines); SetPropertyInt(PROP_NAME_STOP_LINES NSSUBPROP_MIN, 1); SetPropertyInt(PROP_NAME_STOP_LINES NSSUBPROP_MAX, 1000); SetPropertyBool(PROP_NAME_STOP_LINES NSSUBPROP_REQUIRED, tTrue); SetPropertyBool(PROP_NAME_STOP_LINES NSSUBPROP_ISCHANGEABLE, tTrue); this->delay = 100000; SetPropertyInt(PROP_NAME_DELAY, this->delay); SetPropertyInt(PROP_NAME_DELAY NSSUBPROP_MIN, 1); SetPropertyInt(PROP_NAME_DELAY NSSUBPROP_MAX, 1000); SetPropertyBool(PROP_NAME_DELAY NSSUBPROP_REQUIRED, tTrue); SetPropertyBool(PROP_NAME_DELAY NSSUBPROP_ISCHANGEABLE, tTrue); this->driveSpeed = 30; SetPropertyInt(PROP_NAME_DRIVE_SPEED, this->driveSpeed); SetPropertyInt(PROP_NAME_DRIVE_SPEED NSSUBPROP_MIN, 1); SetPropertyInt(PROP_NAME_DRIVE_SPEED NSSUBPROP_MAX, 1000); SetPropertyBool(PROP_NAME_DRIVE_SPEED NSSUBPROP_REQUIRED, tTrue); SetPropertyBool(PROP_NAME_DRIVE_SPEED NSSUBPROP_ISCHANGEABLE, tTrue); this->smoothCurveValue = 7; SetPropertyInt(PROP_NAME_SMOOTH_CURVE_VALUE, this->smoothCurveValue); SetPropertyInt(PROP_NAME_SMOOTH_CURVE_VALUE NSSUBPROP_MIN, 1); SetPropertyInt(PROP_NAME_SMOOTH_CURVE_VALUE NSSUBPROP_MAX, 1000); SetPropertyBool(PROP_NAME_SMOOTH_CURVE_VALUE NSSUBPROP_REQUIRED, tTrue); SetPropertyBool(PROP_NAME_SMOOTH_CURVE_VALUE NSSUBPROP_ISCHANGEABLE, tTrue); this->ticksToStopLine = 10; SetPropertyInt(PROP_NAME_TICKS_TO_STOP_LINE, this->ticksToStopLine); SetPropertyInt(PROP_NAME_TICKS_TO_STOP_LINE NSSUBPROP_MIN, 1); SetPropertyInt(PROP_NAME_TICKS_TO_STOP_LINE NSSUBPROP_MAX, 1000); SetPropertyBool(PROP_NAME_TICKS_TO_STOP_LINE NSSUBPROP_REQUIRED, tTrue); SetPropertyBool(PROP_NAME_TICKS_TO_STOP_LINE NSSUBPROP_ISCHANGEABLE, tTrue); } Test::~Test() { } tResult Test::Init(tInitStage eStage, __exception) { RETURN_IF_FAILED(cFilter::Init(eStage, __exception_ptr)); if (eStage == StageFirst) { RETURN_IF_FAILED(_runtime->GetObject(OID_ADTF_MEDIA_DESCRIPTION_MANAGER, IID_ADTF_MEDIA_DESCRIPTION_MANAGER, (tVoid**) &this->descriptionManager, __exception_ptr)); cObjectPtr<IMediaType> typeSignalManeuver; cObjectPtr<IMediaType> typeSignalSteeringAngle; cObjectPtr<IMediaType> typeSignalAcceleration; cObjectPtr<IMediaType> typeSignalWheelTicks; RETURN_IF_FAILED(initMediaType("tSteeringAngleData", typeSignalManeuver, this->coderDescriptionManeuver)); RETURN_IF_FAILED(initMediaType("tSignalValue", typeSignalSteeringAngle, this->coderDescriptionSteeringAngle)); RETURN_IF_FAILED(initMediaType("tSignalValue", typeSignalAcceleration, this->coderDescriptionAcceleration)); RETURN_IF_FAILED(initMediaType("tSignalValue", typeSignalWheelTicks, this->coderDescriptionWheelTicks)); // input pins RETURN_IF_FAILED(createVideoInputPin("rgbVideo", this->xtionPin)); RETURN_IF_FAILED(createInputPin("maneuver", this->maneuverPin, typeSignalManeuver)); RETURN_IF_FAILED(createInputPin("wheelTicks", this->wheelTicksPin, typeSignalWheelTicks)); // output pins RETURN_IF_FAILED(createOutputPin("steeringAngle", this->steeringAnglePin, typeSignalSteeringAngle)); RETURN_IF_FAILED(createOutputPin("acceleration", this->accelerationPin, typeSignalAcceleration)); } else if (eStage == StageGraphReady) { cObjectPtr<IMediaSerializer> serializer; RETURN_IF_FAILED(this->coderDescriptionAcceleration->GetMediaSampleSerializer(&serializer)); this->ddlSizeUI16 = serializer->GetDeserializedSize(); std::thread test(&Test::accept, this); } RETURN_NOERROR; } tResult Test::initMediaType(const char *mediaTypeDescriptionName, cObjectPtr<IMediaType> &mediaType, cObjectPtr<IMediaTypeDescription> &coderDescription) { tChar const *descriptionSignalValue = this->descriptionManager->GetMediaDescription(mediaTypeDescriptionName); RETURN_IF_POINTER_NULL(descriptionSignalValue); mediaType = new cMediaType(0, 0, 0, mediaTypeDescriptionName, descriptionSignalValue, IMediaDescription::MDF_DDL_DEFAULT_VERSION); RETURN_IF_FAILED(mediaType->GetInterface(IID_ADTF_MEDIA_TYPE_DESCRIPTION, (tVoid**) &coderDescription)); RETURN_NOERROR; } tResult Test::createVideoInputPin(const tChar *pinName, cVideoPin &pin) { pin.Create(pinName, IPin::PD_Input, static_cast<IPinEventSink*>(this)); RETURN_IF_FAILED(RegisterPin(&pin)); RETURN_NOERROR; } tResult Test::createInputPin(const char *pinName, cInputPin &pin, cObjectPtr<IMediaType> &typeSignal) { RETURN_IF_FAILED(pin.Create(pinName, typeSignal, static_cast<IPinEventSink*> (this))); RETURN_IF_FAILED(RegisterPin(&pin)); RETURN_NOERROR; } tResult Test::createOutputPin(const char *pinName, cOutputPin &pin, cObjectPtr<IMediaType> &typeSignal) { RETURN_IF_FAILED(pin.Create(pinName, typeSignal)); RETURN_IF_FAILED(RegisterPin(&pin)); RETURN_NOERROR; } tResult Test::Start(__exception) { RETURN_IF_FAILED(cFilter::Start(__exception_ptr)); RETURN_NOERROR; } tResult Test::Stop(__exception) { RETURN_IF_FAILED(cFilter::Stop(__exception_ptr)); RETURN_NOERROR; } tResult Test::Shutdown(tInitStage eStage, __exception) { RETURN_IF_FAILED(cFilter::Shutdown(eStage, __exception_ptr)); RETURN_NOERROR; } tResult Test::OnPinEvent(IPin *source, tInt eventCore, tInt param1, tInt param2, IMediaSample *mediaSample) { RETURN_IF_POINTER_NULL(source); RETURN_IF_POINTER_NULL(mediaSample); if (eventCore == IPinEventSink::PE_MediaSampleReceived) { if (source == &this->maneuverPin) { static tUInt16 tmpManeuver; getManeuver(mediaSample, maneuverPin, this->coderDescriptionManeuver, tmpManeuver); if (tmpManeuver == MANEUVER_STRAIGHT) { this->isDriveActive = true; RETURN_IF_FAILED_AND_LOG_ERROR_STR(transmitAcceleration(this->driveSpeed), "Cant transmit drive"); } } else if (source == &this->wheelTicksPin) { if (!this->isConnectedToServer) { if (!tcpClient->connectToServer(this->ip, 5555)) { LOG_INFO(cString::Format("Cant connect to server with ip: %s:5555", this->ip.c_str())); RETURN_NOERROR; } else { this->isConnectedToServer = true; LOG_INFO("Could connect to server :)"); } } static tFloat32 tmpWheelTicks; RETURN_IF_FAILED_AND_LOG_ERROR_STR(getWheelTicks(mediaSample, tmpWheelTicks), "cant get wheel ticks"); this->currentWheelTicks = static_cast<int>(tmpWheelTicks); if (this->isStopLineFound) { driveToStopLine(); } } else if(source == &this->xtionPin) { if (this->isFirstFrame) { RETURN_IF_FAILED_AND_LOG_ERROR_STR(initVideoStream(), "Cant init video stream"); this->isFirstFrame = false; } else { const tVoid *buffer; if (this->isDriveActive && IS_OK(mediaSample->Lock(&buffer))) { //Receive the image Mat image(Size(this->videoInputInfo.nWidth, this->videoInputInfo.nHeight), CV_8UC3, (char*) buffer); Mat result = image.clone(); RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaSample->Unlock(buffer), "Cant unlock image"); this->driveAlgorithm->prepareImage(result); if (!this->isStopLineFound) { this->isStopLineFound = this->crossroadDetector-> searchStopLine(result); this->ticksToDrive = this->ticksToStopLine + this->currentWheelTicks; } } } } } RETURN_NOERROR; } void Test::accept(void) { tcpServer->startServer(); } tResult Test::initVideoStream(void) { //Read media type cObjectPtr<IMediaType> type; RETURN_IF_FAILED(this->xtionPin.GetMediaType(&type)); cObjectPtr<IMediaTypeVideo> typeVideo; RETURN_IF_FAILED(type->GetInterface(IID_ADTF_MEDIA_TYPE_VIDEO, (tVoid**)(&typeVideo))); const tBitmapFormat *format = typeVideo->GetFormat(); RETURN_IF_POINTER_NULL(format); //Set media type setBitmapFormat(format); RETURN_NOERROR; } tVoid Test::setBitmapFormat(const tBitmapFormat *format) { this->videoInputInfo.nBitsPerPixel = format->nBitsPerPixel; this->videoInputInfo.nBytesPerLine = format->nBytesPerLine; this->videoInputInfo.nPaletteSize = format->nPaletteSize; this->videoInputInfo.nPixelFormat = format->nPixelFormat; this->videoInputInfo.nHeight = format->nHeight; this->videoInputInfo.nWidth = format->nWidth; this->videoInputInfo.nSize = format->nSize; } tResult Test::driveToStopLine(void) { static tInt tmpDistance; tmpDistance = this->ticksToDrive - this->currentWheelTicks; if (tmpDistance <= 0) { if (this->stopOnStopLine) { RETURN_IF_FAILED(transmitAcceleration(-5.0f)); // sende zum anderen Auto, dass ich warte } else { // sende zum anderen Auto this->numberOfStopLines--; // sende... LOG_INFO(cString::Format("StopLines: %d", this->numberOfStopLines)); this->isStopLineFound = false; } } RETURN_NOERROR; } tResult Test::transmitSteeringAngle(const tFloat32 value) { RETURN_IF_FAILED(transmitF32Value(this->steeringAnglePin, this->coderDescriptionSteeringAngle, value)); RETURN_NOERROR; } tResult Test::transmitAcceleration(const tFloat32 value) { RETURN_IF_FAILED(transmitF32Value(this->accelerationPin, this->coderDescriptionAcceleration, value)); RETURN_NOERROR; } tResult Test::transmitStop(const tFloat32 value) { RETURN_IF_FAILED(transmitF32Value(this->accelerationPin, this->coderDescriptionAcceleration, value)); RETURN_NOERROR; } tResult Test::transmitF32Value(cOutputPin &pin, cObjectPtr<IMediaTypeDescription> &mediaType, const tFloat32 value) { cObjectPtr<IMediaSample> mediaSample; RETURN_IF_FAILED(AllocMediaSample((tVoid**) &mediaSample)); RETURN_IF_FAILED(mediaSample->AllocBuffer(this->ddlSizeUI16)); // write date to the media sample with the coder of the descriptor cObjectPtr<IMediaCoder> coder; RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaType->WriteLock(mediaSample, &coder), "Set F32 Failed to lock f32"); static tTimeStamp now; now = _clock ? _clock->GetStreamTime() : cHighResTimer::GetTime(); coder->Set("f32Value", (tVoid*) &value); coder->Set("ui32ArduinoTimestamp", (tVoid*) &now); RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaType->Unlock(coder), "Set F32 Failed to lock f32"); // transmit media sample over output pin RETURN_IF_FAILED(mediaSample->SetTime(now)); RETURN_IF_FAILED(pin.Transmit(mediaSample)); RETURN_NOERROR; } tResult Test::getWheelTicks(IMediaSample *mediaSample, tFloat32 &value) { RETURN_IF_FAILED(getF32Value(mediaSample, this->coderDescriptionWheelTicks, value)); RETURN_NOERROR; } tResult Test::getF32Value(IMediaSample *mediaSample, cObjectPtr<IMediaTypeDescription> &mediaType, tFloat32 &value) { static tFloat32 tmpValue; static tTimeStamp timeStamp; cObjectPtr<IMediaCoder> coder; RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaType->Lock(mediaSample, &coder), "Get32 Failed to lock f32"); coder->Get("f32Value", (tVoid*) &tmpValue); coder->Get("ui32ArduinoTimestamp", (tVoid*) &timeStamp); value = tmpValue; RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaType->Unlock(coder), "Get32 Failed to unlock f32"); RETURN_NOERROR; } tResult Test::getManeuver(IMediaSample *mediaSample, cInputPin &pin, cObjectPtr<IMediaTypeDescription> &mediaType, tUInt16 &value) { static tUInt16 tmpValue; static tUInt32 timeStamp; cObjectPtr<IMediaCoder> coder; RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaType->Lock(mediaSample, &coder), "Get UI16 failed to unlock"); coder->Get("ui16Angle", (tVoid*) &tmpValue); coder->Get("ui32ArduinoTimestamp", (tVoid*) &timeStamp); value = tmpValue; RETURN_IF_FAILED_AND_LOG_ERROR_STR(mediaType->Unlock(coder), "Get UI16 failed to unlock"); RETURN_NOERROR; } tResult Test::PropertyChanged(const char *name) { this->ip = GetPropertyStr(PROP_NAME_IP); this->numberOfStopLines = GetPropertyInt(PROP_NAME_STOP_LINES); this->delay = GetPropertyInt(PROP_NAME_DELAY); this->driveSpeed = GetPropertyInt(PROP_NAME_DRIVE_SPEED); this->smoothCurveValue = GetPropertyInt(PROP_NAME_SMOOTH_CURVE_VALUE); this->ticksToStopLine = GetPropertyInt(PROP_NAME_TICKS_TO_STOP_LINE); RETURN_NOERROR; }
33.47381
166
0.775375
HTWKSmartDriving
a565e2c43ad945daf61e2949305b14d18a01a3ed
2,599
cpp
C++
src/boss/blob.cpp
Lab-RoCoCo/fps_mapper
376e557c8f5012e05187fe85ee3f4044f99f944a
[ "BSD-3-Clause" ]
1
2017-12-01T14:57:16.000Z
2017-12-01T14:57:16.000Z
src/boss/blob.cpp
Lab-RoCoCo/fps_mapper
376e557c8f5012e05187fe85ee3f4044f99f944a
[ "BSD-3-Clause" ]
null
null
null
src/boss/blob.cpp
Lab-RoCoCo/fps_mapper
376e557c8f5012e05187fe85ee3f4044f99f944a
[ "BSD-3-Clause" ]
null
null
null
/* <one line to give the program's name and a brief idea of what it does.> Copyright (C) 2013 <copyright holder> <email> 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 3 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, see <http://www.gnu.org/licenses/>. */ //#include <fstream> #include <memory> #include "blob.h" #include "object_data.h" #include "serialization_context.h" #include "id_context.h" using namespace boss; using namespace std; BLOB::~BLOB() { if (_ref) { _ref->dataDestroyed(); } } static string DEFAULT_EXTENSION("dat"); const string& BLOB::extension() { return DEFAULT_EXTENSION; } const string& BaseBLOBReference::extension() { if (_instance) { return _instance->extension(); } return DEFAULT_EXTENSION; } void BaseBLOBReference::dataDestroyed() { _instance=0; } BaseBLOBReference::~BaseBLOBReference() { if (_instance) { delete _instance; } } void BaseBLOBReference::serialize(ObjectData& data, IdContext& context) { Identifiable::serialize(data,context); if (_instance) { //Check if binary file serialization is supported SerializationContext* fileContext=context.serializationContext(); if (fileContext) { _fileName=fileContext->createBinaryFilePath(*this); auto_ptr<ostream> os(fileContext->getBinaryOutputStream(_fileName)); if (os.get()) { _instance->write(*os); } } } data << field("pathName",_fileName); } void BaseBLOBReference::deserialize(ObjectData& data, IdContext& context) { Identifiable::deserialize(data, context); data >> field("pathName",_fileName); _instance=0; } bool BaseBLOBReference::load(BLOB& instance) { //Check if binary file serialization is supported SerializationContext* fileContext=getContext()->serializationContext(); if (fileContext) { auto_ptr<istream> is(fileContext->getBinaryInputStream(_fileName)); if (is.get()) { return instance.read(*is); } } return false; } void BaseBLOBReference::set(BLOB* instance) { if (_instance) { delete _instance; } _instance=instance; }
26.252525
75
0.710273
Lab-RoCoCo
a569e99c0c0abfab7cdaa89a8d125cf39b96d901
786
cpp
C++
C++/Playlist Maker/Song.cpp
Andrustn/Andrustn.github.io
8cc1cf815a20be06373ca61c57bb29ec41ef79f2
[ "MIT" ]
null
null
null
C++/Playlist Maker/Song.cpp
Andrustn/Andrustn.github.io
8cc1cf815a20be06373ca61c57bb29ec41ef79f2
[ "MIT" ]
null
null
null
C++/Playlist Maker/Song.cpp
Andrustn/Andrustn.github.io
8cc1cf815a20be06373ca61c57bb29ec41ef79f2
[ "MIT" ]
null
null
null
#include<iostream> #include<string> #include "Song.h" void Song::SetSongName(string userSongName) { songName = userSongName; } void Song::SetSongFirstLine(string userSongFirstLine) { songFirstLine = userSongFirstLine; } void Song::SetTimesPlayed(int userTimesPlayed) { timesPlayed = userTimesPlayed; } Song::Song() { songName = "No Name"; songFirstLine = "No first line"; timesPlayed = 0; } Song::Song(string userSongName, string userSongFirstLine) { songName = userSongName; songFirstLine = userSongFirstLine; } string Song::GetSongName() { return songName; } string Song::GetSongFirstLine() { return songFirstLine; } int Song::GetTimesPlayed() { return timesPlayed; } void Song::IncrementTimesPlayed() { timesPlayed = timesPlayed + 1; }
22.457143
60
0.720102
Andrustn
a573cd65a101e523428e648128c51c79e2092a58
1,127
cpp
C++
vulcan_test/debug_stream.cpp
WarlockD/Vulkan2D-Engine
c7808e7d29cd52ba096b03e26839efa781691de7
[ "MIT" ]
1
2021-07-02T20:35:05.000Z
2021-07-02T20:35:05.000Z
vulcan_test/debug_stream.cpp
WarlockD/Vulkan2D-Engine
c7808e7d29cd52ba096b03e26839efa781691de7
[ "MIT" ]
null
null
null
vulcan_test/debug_stream.cpp
WarlockD/Vulkan2D-Engine
c7808e7d29cd52ba096b03e26839efa781691de7
[ "MIT" ]
null
null
null
#include "dbgstream.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <fstream> #ifdef DBG_TIMESTAMP extern "C" { #include <time.h> }; #endif /* DBG_TIMESTAMP */ using namespace std; dbgstream dbg; dbgbuf::~dbgbuf() { flushMsg(); } void dbgbuf::flushMsg() { if (msg.length() > 0) { #if DBG_TIMESTAMP char tbuf[64]; time_t t = time(0); struct tm tm; tm = *localtime(&t); strftime(tbuf, sizeof(tbuf), "%b %d %R:%S", &tm); OutputDebugStringA(tbuf); OutputDebugStringA(":"); if (tee) { (*tee) << tbuf << ": "; } #endif /* DBG_TIMESTAMP */ OutputDebugStringA(msg.c_str()); OutputDebugStringA("\n"); if (tee) { (*tee) << msg << endl << flush; } msg.erase(); // erase message buffer } } std::ostream *dbgbuf::setTee(std::ostream *_tee) { std::ostream *otee = tee; tee = _tee; return otee; } int dbgbuf::overflow(int c) { if (c == '\n') { flushMsg(); } else { msg += c; } return c == -1 ? -1 : ' '; } #ifdef TEST_MAIN INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR, INT) { dbgstream dbg; dbg << "Hello, World." << endl; return 0; } #endif /* TEST_MAIN */
15.22973
58
0.606921
WarlockD
a573d91bf5f42ade2faa44b67835c31c0bec6bb2
290
hpp
C++
font.hpp
5cript/cairo-wrap
d436eea920496830647a86488c2878a76c1e7479
[ "MIT" ]
1
2020-11-11T17:19:14.000Z
2020-11-11T17:19:14.000Z
font.hpp
5cript/cairo-wrap
d436eea920496830647a86488c2878a76c1e7479
[ "MIT" ]
null
null
null
font.hpp
5cript/cairo-wrap
d436eea920496830647a86488c2878a76c1e7479
[ "MIT" ]
1
2021-03-01T08:53:46.000Z
2021-03-01T08:53:46.000Z
#pragma once #include "core.hpp" #include <string> namespace Cairo { struct Font { std::string family = "Arial"; double size = 12; cairo_font_weight_t weight = CAIRO_FONT_WEIGHT_NORMAL; cairo_font_slant_t slant = CAIRO_FONT_SLANT_NORMAL; }; }
17.058824
62
0.648276
5cript
a57dca26601e33459ea64de3041af5be99acb32a
880
hh
C++
simlucid/include/SimLucidSteppingVerbose.hh
CERNatschool/SimLUCID-lite
ccc6000bfbcd70538e60a0d46fe3f2f2ef43653a
[ "MIT" ]
null
null
null
simlucid/include/SimLucidSteppingVerbose.hh
CERNatschool/SimLUCID-lite
ccc6000bfbcd70538e60a0d46fe3f2f2ef43653a
[ "MIT" ]
null
null
null
simlucid/include/SimLucidSteppingVerbose.hh
CERNatschool/SimLUCID-lite
ccc6000bfbcd70538e60a0d46fe3f2f2ef43653a
[ "MIT" ]
null
null
null
/*! \file SimLucidSteppingVerbose.hh * \brief The header file for the SimLucidSteppingVerbose class. */ class SimLucidSteppingVerbose; #ifndef SimLucidSteppingVerbose_h #define SimLucidSteppingVerbose_h 1 // GEANT4 includes #include "G4SteppingVerbose.hh" /*! \brief Class handling user-defined verbose actions. @author T. Whyntie @date Autumn 2013 Based on work on the Allpix simulation package by J. Idarraga et al. This class provides methods for outputting information about the step and tracking processes that take place in the simulations. */ class SimLucidSteppingVerbose : public G4SteppingVerbose { public: SimLucidSteppingVerbose(); //!< Constructor. ~SimLucidSteppingVerbose(); //!< Destructor. void StepInfo(); //!< Information printed at every step. void TrackingStarted(); //!< Information printed when the tracking starts. }; #endif
23.783784
77
0.765909
CERNatschool
a57fd356c2bfe0dcabd2affd17d0daae6cb3b0c2
829
cpp
C++
CFPExercise2.21.2019/CFPExercise2.21.2019/CFPExercise2.21.2019.cpp
cperez604/ITSE-1307-Spring-2019
c5137d7e6b2785c0eb37df0964ba6d61c7cc7555
[ "MIT" ]
null
null
null
CFPExercise2.21.2019/CFPExercise2.21.2019/CFPExercise2.21.2019.cpp
cperez604/ITSE-1307-Spring-2019
c5137d7e6b2785c0eb37df0964ba6d61c7cc7555
[ "MIT" ]
null
null
null
CFPExercise2.21.2019/CFPExercise2.21.2019/CFPExercise2.21.2019.cpp
cperez604/ITSE-1307-Spring-2019
c5137d7e6b2785c0eb37df0964ba6d61c7cc7555
[ "MIT" ]
null
null
null
// CFPExercise2.21.2019.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include <iostream> using namespace std; int main() { //establish variables double dblfirstvariable = .0; double dblsecondvariable = .0; double dblvariablec = .0; cout << "Calculator for equation C = A*B/A-B" << endl; //input output for first variable/A cout << "Please Enter Decimal Value for A variable" << endl; cin >> dblfirstvariable; //input output for second variable/B cout << "Please Enter Decimal Value for B variable" << endl; cin >> dblsecondvariable; //calculate for C = A*B/A-C float fltvariablec = (float)(dblfirstvariable * dblsecondvariable) / (dblfirstvariable - dblsecondvariable); cout << "C equals: " << fltvariablec << endl; }
29.607143
111
0.685163
cperez604
a5818f8c8078d29e54b073bb18211c39f0ed474d
552
cpp
C++
PTA_L1/L1_062.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
PTA_L1/L1_062.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
PTA_L1/L1_062.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { int N; cin >> N; while (N--) { string s; cin >> s; int sum1 = 0, sum2 = 0; sum1 = (s[0] - '0') + (s[1] - '0') + (s[2] - '0'); sum2 = (s[3] - '0') + (s[4] - '0') + (s[5] - '0'); if (sum1 == sum2) { cout << "You are lucky!" << endl; } else { cout << "Wish you good luck." << endl; } sum1 = sum2 = 0; } return 0; }
21.230769
59
0.34058
codehuanglei
a582f06ceeaa1b13c8acfc0ed0d6b92790f214ff
5,237
cpp
C++
Main.cpp
d0lev/messageboard
8db6c72bb973981e6078b087f4e2e69e6998ac0d
[ "MIT" ]
null
null
null
Main.cpp
d0lev/messageboard
8db6c72bb973981e6078b087f4e2e69e6998ac0d
[ "MIT" ]
null
null
null
Main.cpp
d0lev/messageboard
8db6c72bb973981e6078b087f4e2e69e6998ac0d
[ "MIT" ]
null
null
null
#include <iostream> #include "Direction.hpp" #include "Board.hpp" using namespace std; using namespace ariel; int main() { ariel::Board board; // declaration of all variables uint row , column , length; int func; int dir; string message; Direction direction; // wellcome line cout << "Wellcome to Assignment number two : " << "\033[1;31mmessageboard part B\033[0m\n"; cout << "You can choose one of the option : " << "\033[1;32mPost (Press 1)\033[0m " << "\033[1;33mRead (Press 2)\033[0m " << "\033[1;34mShow (Press 3)\033[0m " << "\033[1;35mExit (Press 4)\033[0m " << endl; cin >> func; while (func != 4) { switch(func) { //post function case 1: cout << "\033[1;32mYou choose : Post\033[0m \n"; cout << "\033[1;32m1)\033[0m " << "for inserting a message horizontally please press 1 \n"; cout << "\033[1;32m2)\033[0m " << "for inserting a message vertically please press 2\n"; cin >> dir; if(dir == 1 || dir == 2) { if (dir == 1) {direction = Horizontal;} else if (dir == 2) {direction = Vertical;} cout << "Please enter the position of the message by two indexes [i][j]\n"; cin >> row >> column; cout << "\033[1;33mPlease enter the message \033[0m\n"; cin >> message; board.post(row,column,direction,message); cout << "\033[1;32mThe message was published successfully!\033[0m\n"; cout << "\nWellcome to Assignment number two : " << "\033[1;31mmessageboard part B\033[0m\n"; cout << "You can choose one of the option : " << "\033[1;32mPost (Press 1)\033[0m " << "\033[1;33mRead (Press 2)\033[0m " << "\033[1;34mShow (Press 3)\033[0m " << "\033[1;35mExit (Press 4)\033[0m " << endl; cin >> func; } else cout << "Wrong input , please try again. \n"; break; //read function case 2: cout << "\033[1;33mYou choose : Read\033[0m \n"; cout << "Please enter the position by two indexes [i][j]\n"; cin >> row >> column; cout << "\033[1;32m1)\033[0m " << "for read the message horizontally please press 1 \n"; cout << "\033[1;32m2)\033[0m " << "for read the message vertically please press 2\n"; cin >> dir; if(dir == 1 || dir == 2) { if (dir == 1) {direction = Horizontal;} else if (dir == 2) {direction = Vertical;} cout << "\033[1;32m2)\033[0m " << "Please enter the length of the reading\n"; cin >> length; message = board.read(row,column,direction,length); cout << "The message are : " << message << endl; cout << "\nWellcome to Assignment number two : " << "\033[1;31mmessageboard part B\033[0m\n"; cout << "You can choose one of the option : " << "\033[1;32mPost (Press 1)\033[0m " << "\033[1;33mRead (Press 2)\033[0m " << "\033[1;34mShow (Press 3)\033[0m " << "\033[1;35mExit (Press 4)\033[0m " << endl; cin >> func; } else cout << "Wrong input , please try again. \n"; break; //show function case 3: cout << "\033[1;34mYou choose : Show\033[0m \n"; cout << "The message board is :\n"; board.show(); cout << "\nWellcome to Assignment number two : " << "\033[1;31mmessageboard part B\033[0m\n"; cout << "You can choose one of the option : " << "\033[1;32mPost (Press 1)\033[0m " << "\033[1;33mRead (Press 2)\033[0m " << "\033[1;34mShow (Press 3)\033[0m " << "\033[1;35mExit (Press 4)\033[0m " << endl; cin >> func; break; default: exit(1); } } }
56.923913
121
0.384762
d0lev
a584c0e21e636636f4c9c8814415f22a23672567
376
hpp
C++
mr.Sadman/Classes/GameAct/Objects/Physical/PushPlate/PushPlate.hpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
mr.Sadman/Classes/GameAct/Objects/Physical/PushPlate/PushPlate.hpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
3
2020-12-11T10:01:27.000Z
2022-02-13T22:12:05.000Z
mr.Sadman/Classes/GameAct/Objects/Physical/PushPlate/PushPlate.hpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
#ifndef __GAME_ACT_PHYSICAL_PUSH_PLATE_HPP__ #define __GAME_ACT_PHYSICAL_PUSH_PLATE_HPP__ #include "GameAct/Objects/Physical/Button/Button.hpp" namespace GameAct { namespace Physical { class PushPlate : public Button { public: void setRotation( float angle ) override; void runAction( const std::string & action ) override; }; } } #endif
13.925926
56
0.723404
1pkg
a585088f28f2a6aca4ec849621838d21bdc7e58f
1,193
hpp
C++
src/CmdNodeDisconnect.hpp
Bwar/NebulaBeacon
4fbb53cd0c56811d25a08c47aaf67a8398e9ecc4
[ "Apache-2.0" ]
3
2019-01-24T02:49:57.000Z
2021-06-06T08:40:34.000Z
src/CmdNodeDisconnect.hpp
Bwar/NebulaBeacon
4fbb53cd0c56811d25a08c47aaf67a8398e9ecc4
[ "Apache-2.0" ]
3
2021-06-01T03:21:13.000Z
2021-09-02T04:46:27.000Z
src/CmdNodeDisconnect.hpp
Bwar/NebulaBeacon
4fbb53cd0c56811d25a08c47aaf67a8398e9ecc4
[ "Apache-2.0" ]
3
2019-10-05T12:13:03.000Z
2021-06-06T08:40:20.000Z
/******************************************************************************* * Project: Beacon * @file CmdNodeDisconnect.hpp * @brief * @author bwar * @date: Feb 14, 2017 * @note * Modify history: ******************************************************************************/ #ifndef SRC_CMDNODEDISCONNECT_CMDNODEDISCONNECT_HPP_ #define SRC_CMDNODEDISCONNECT_CMDNODEDISCONNECT_HPP_ #include <actor/cmd/Cmd.hpp> #include <Error.hpp> #include <SessionOnlineNodes.hpp> #include <util/json/CJsonObject.hpp> namespace beacon { class CmdNodeDisconnect: public neb::Cmd, public neb::DynamicCreator<CmdNodeDisconnect, int32> { public: CmdNodeDisconnect(int32 iCmd); virtual ~CmdNodeDisconnect(); virtual bool Init(); virtual bool AnyMessage( std::shared_ptr<neb::SocketChannel> pChannel, const MsgHead& oMsgHead, const MsgBody& oMsgBody); virtual std::string ObjectName() const { return("beacon::CmdNodeReport"); } private: std::shared_ptr<SessionOnlineNodes> m_pSessionOnlineNodes; }; } /* namespace beacon */ #endif /* SRC_CMDNODEDISCONNECT_CMDNODEDISCONNECT_HPP_ */
26.511111
94
0.601006
Bwar
a58b86ffcbbbc0f9e0057421f95ee69f03cc24a4
507
cpp
C++
lab3(assignment 3 date).cpp
ahmedtarek26/oop_assignments
a6f334e013dfaef5ca59658f0b2fd8d365902492
[ "MIT" ]
null
null
null
lab3(assignment 3 date).cpp
ahmedtarek26/oop_assignments
a6f334e013dfaef5ca59658f0b2fd8d365902492
[ "MIT" ]
null
null
null
lab3(assignment 3 date).cpp
ahmedtarek26/oop_assignments
a6f334e013dfaef5ca59658f0b2fd8d365902492
[ "MIT" ]
null
null
null
#include <iostream> #include<string> using namespace std; struct Date { int day=18 , month=11, year=2020; }; void Date_next(){ Date current; for (int i = 1; i < 45; i++) { if(current.day==31){ current.day=1; current.day+=1; current.month+=1; } else current.day+=1; } cout << current.day << endl; cout << current.month <<endl; cout << current.year << endl; } int main() { Date_next(); system("pause"); return 0; }
16.354839
39
0.530572
ahmedtarek26
a58c1e5e82b200b494cf624346a6313435d8266a
3,006
cpp
C++
src/udpbridge_ui.cpp
GFOE/udp_bridge
e845a587b300af802ca310f1df253e03baf32bc4
[ "BSD-2-Clause" ]
6
2018-12-22T15:32:29.000Z
2022-03-07T14:56:44.000Z
src/udpbridge_ui.cpp
GFOE/udp_bridge
e845a587b300af802ca310f1df253e03baf32bc4
[ "BSD-2-Clause" ]
null
null
null
src/udpbridge_ui.cpp
GFOE/udp_bridge
e845a587b300af802ca310f1df253e03baf32bc4
[ "BSD-2-Clause" ]
8
2018-04-05T19:57:36.000Z
2022-02-07T15:49:41.000Z
#include <ros/ros.h> #include <ros/master.h> #include "udp_bridge/ChannelStatisticsArray.h" void statisticsCallback(udp_bridge::ChannelStatisticsArray const &stats) { std::vector<std::string> headers {"source topic", "remote host", " messages", "message data", " packet data", " compressed", " ratio", "send error"}; std::vector<int> column_widths; for(auto h: headers) column_widths.push_back(h.size()); for(auto c: stats.channels) { column_widths[0] = std::max(column_widths[0], int(c.source_topic.size())); column_widths[1] = std::max(column_widths[1], int(c.destination_host.size())); } std::cout << std::left; for(int i = 0; i < headers.size(); i++) std::cout << std::setw(column_widths[i]+1) << headers[i]; std::cout << std::endl; std::vector<float> totals {0.0, 0.0, 0.0, 0.0}; for(auto c: stats.channels) { std::cout << std::left; std::cout << std::setw(column_widths[0]+1) << c.source_topic; std::cout << std::setw(column_widths[1]+1) << c.destination_host; std::cout << std::fixed; std::cout << std::setprecision(1); std::cout << std::right; std::cout << std::setw(5) << c.messages_per_second << " msg/sec "; // bytes to kilobits, *8/100 -> /125 std::cout << std::setw(7) << c.message_bytes_per_second/125.0 << " kbps "; std::cout << std::setw(7) << c.packet_bytes_per_second/125.0 << " kbps "; std::cout << std::setw(7) << c.compressed_bytes_per_second/125.0 << " kbps"; std::cout << std::setw(7) << 100*c.compressed_bytes_per_second/c.message_bytes_per_second << "%"; std::cout << std::setw(7) << 100*(1.0-c.send_success_rate) << "%"; std::cout << std::endl; totals[0] += c.messages_per_second; totals[1] += c.message_bytes_per_second; totals[2] += c.packet_bytes_per_second; totals[3] += c.compressed_bytes_per_second; } std::cout << std::left; std::cout << std::setw(column_widths[0]+column_widths[1]+2) << "totals:"; std::cout << std::right; std::cout << std::setw(5) << totals[0] << " msg/sec "; std::cout << std::setw(7) << totals[1]/125.0 << " kbps "; std::cout << std::setw(7) << totals[2]/125.0 << " kbps "; std::cout << std::setw(7) << totals[3]/125.0 << " kbps"; std::cout << std::setw(7) << 100*totals[3]/totals[1] << "%"; std::cout << std::endl; std::cout << std::endl; } int main(int argc, char **argv) { ros::init(argc, argv, "udp_bridge_ui"); ros::NodeHandle nh; std::vector<ros::Subscriber> statsSubs; ros::master::V_TopicInfo topic_infos; ros::master::getTopics(topic_infos); for(auto ti:topic_infos) if(ti.datatype == "udp_bridge/ChannelStatisticsArray") statsSubs.push_back(nh.subscribe(ti.name, 10, &statisticsCallback)); ros::spin(); return 0; }
34.953488
159
0.574185
GFOE
a591d7ef8bc0fb27ae8c0b8fe4e82791f5fbb499
1,497
cpp
C++
src/CMessageHeader.cpp
gasteve/bitcoin
b5e79be9e7612c31403a2231ba03850f495ea9c1
[ "MIT" ]
1
2017-05-18T17:12:00.000Z
2017-05-18T17:12:00.000Z
src/CMessageHeader.cpp
gasteve/bitcoin
b5e79be9e7612c31403a2231ba03850f495ea9c1
[ "MIT" ]
null
null
null
src/CMessageHeader.cpp
gasteve/bitcoin
b5e79be9e7612c31403a2231ba03850f495ea9c1
[ "MIT" ]
null
null
null
#include "CMessageHeader.h" // // Message header // (4) message start // (12) command // (4) size // (4) checksum extern char pchMessageStart[4]; CMessageHeader::CMessageHeader() { memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)); memset(pchCommand, 0, sizeof(pchCommand)); pchCommand[1] = 1; nMessageSize = -1; nChecksum = 0; } CMessageHeader::CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn) { memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)); strncpy(pchCommand, pszCommand, COMMAND_SIZE); nMessageSize = nMessageSizeIn; nChecksum = 0; } string CMessageHeader::GetCommand() { if (pchCommand[COMMAND_SIZE-1] == 0) return string(pchCommand, pchCommand + strlen(pchCommand)); else return string(pchCommand, pchCommand + COMMAND_SIZE); } bool CMessageHeader::IsValid() { // Check start string if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0) return false; // Check the command string for errors for (char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++) { if (*p1 == 0) { // Must be all zeros after the first zero for (; p1 < pchCommand + COMMAND_SIZE; p1++) if (*p1 != 0) return false; } else if (*p1 < ' ' || *p1 > 0x7E) return false; } // Message size if (nMessageSize > MAX_SIZE) { printf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand().c_str(), nMessageSize); return false; } return true; }
22.343284
117
0.691383
gasteve
a5998ad829b04b45d1ad23645e65ab2abde31d6c
1,834
cpp
C++
VME/GBO.cpp
KIKU-O/VME
e87d5d9543d30e5b15f7cf5a04878a32290326df
[ "MIT" ]
null
null
null
VME/GBO.cpp
KIKU-O/VME
e87d5d9543d30e5b15f7cf5a04878a32290326df
[ "MIT" ]
null
null
null
VME/GBO.cpp
KIKU-O/VME
e87d5d9543d30e5b15f7cf5a04878a32290326df
[ "MIT" ]
null
null
null
#include "GBO.h" void GBO::Load() { Shader.Load("Shaders\\Geometry-Buffer.vert", "Shaders\\Geometry-Buffer.frag"); } void GBO::Initialize() { glGenFramebuffers(1, &FBO); glBindFramebuffer(GL_FRAMEBUFFER, FBO); // POSITION glGenTextures(1, &Position); glBindTexture(GL_TEXTURE_2D, Position); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, 624, 480, 0, GL_RGB, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, Position, 0); // NORMAL glGenTextures(1, &Normal); glBindTexture(GL_TEXTURE_2D, Normal); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, 624, 480, 0, GL_RGB, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, Normal, 0); unsigned int attachments[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; glDrawBuffers(2, attachments); glGenRenderbuffers(1, &RBO); glBindRenderbuffer(GL_RENDERBUFFER, RBO); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, 624, 480); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, RBO); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { OutputDebugStringA("Geometry-Pass buffer could not be completed!\n"); } } void GBO::Bind(Camera camera) { glBindFramebuffer(GL_FRAMEBUFFER, FBO); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Shader.Process(); Shader.SetMatrix4("projection", camera.Projection); Shader.SetMatrix4("view", camera.View()); }
36.68
93
0.749182
KIKU-O
a59a6eb8901e97195d2f268082101a331396881b
3,559
hpp
C++
retrace.hpp
prahal/apitrace
e9426dd61586757d23d7dddc85b3076f477e7f07
[ "MIT" ]
1
2020-06-19T12:34:44.000Z
2020-06-19T12:34:44.000Z
retrace.hpp
prahal/apitrace
e9426dd61586757d23d7dddc85b3076f477e7f07
[ "MIT" ]
null
null
null
retrace.hpp
prahal/apitrace
e9426dd61586757d23d7dddc85b3076f477e7f07
[ "MIT" ]
null
null
null
/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #ifndef _RETRACE_HPP_ #define _RETRACE_HPP_ #include <string.h> #include <list> #include <map> #include <ostream> #include "trace_model.hpp" namespace retrace { /** * Handle map. * * It is just like a regular std::map<T, T> container, but lookups of missing * keys return the key instead of default constructor. * * This is necessary for several GL named objects, where one can either request * the implementation to generate an unique name, or pick a value never used * before. * * XXX: In some cases, instead of returning the key, it would make more sense * to return an unused data value (e.g., container count). */ template <class T> class map { private: typedef std::map<T, T> base_type; base_type base; public: T & operator[] (const T &key) { typename base_type::iterator it; it = base.find(key); if (it == base.end()) { return (base[key] = key); } return it->second; } const T & operator[] (const T &key) const { typename base_type::const_iterator it; it = base.find(key); if (it == base.end()) { return (base[key] = key); } return it->second; } }; void addRegion(unsigned long long address, void *buffer, unsigned long long size); void delRegionByPointer(void *ptr); void * toPointer(trace::Value &value, bool bind = false); /** * Output verbosity when retracing files. */ extern int verbosity; std::ostream &warning(trace::Call &call); void ignore(trace::Call &call); void unsupported(trace::Call &call); typedef void (*Callback)(trace::Call &call); struct Entry { const char *name; Callback callback; }; struct stringComparer { bool operator() (const char *a, const char *b) const { return strcmp(a, b) < 0; } }; extern const Entry stdc_callbacks[]; class Retracer { typedef std::map<const char *, Callback, stringComparer> Map; Map map; std::vector<Callback> callbacks; public: Retracer() { addCallbacks(stdc_callbacks); } virtual ~Retracer() {} void addCallback(const Entry *entry); void addCallbacks(const Entry *entries); void retrace(trace::Call &call); }; } /* namespace retrace */ #endif /* _RETRACE_HPP_ */
24.047297
80
0.652711
prahal
a59c53b2e48a5327e9f15e69a2fb30db04b85584
3,279
cpp
C++
firmware-latest/wiring/src/spark_wiring_servo.cpp
adeeshag/particle_project
0c2ab278cf902f97d2422c44c008978be58fe6b7
[ "Unlicense" ]
1
2019-02-24T07:13:51.000Z
2019-02-24T07:13:51.000Z
firmware-latest/wiring/src/spark_wiring_servo.cpp
adeeshag/particle_project
0c2ab278cf902f97d2422c44c008978be58fe6b7
[ "Unlicense" ]
1
2018-05-29T19:27:53.000Z
2018-05-29T19:27:53.000Z
firmware-latest/wiring/src/spark_wiring_servo.cpp
adeeshag/particle_project
0c2ab278cf902f97d2422c44c008978be58fe6b7
[ "Unlicense" ]
null
null
null
/** ****************************************************************************** * @file spark_wiring_spi.h * @author Zach Supalla * @version V1.0.0 * @date 06-December-2013 * @brief Header for spark_wiring_servo.cpp module ****************************************************************************** Copyright (c) 2013-2015 Particle Industries, Inc. All rights reserved. Copyright (c) 2010 LeafLabs, LLC. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, see <http://www.gnu.org/licenses/>. ****************************************************************************** */ #include "spark_wiring_servo.h" #include "servo_hal.h" #define ANGLE_TO_US(a) ((uint16_t)(map((a), this->minAngle, this->maxAngle, \ this->minPW, this->maxPW))) #define US_TO_ANGLE(us) ((int16_t)(map((us), this->minPW, this->maxPW, \ this->minAngle, this->maxAngle))) Servo::Servo() { this->resetFields(); } bool Servo::attach(uint16_t pin, uint16_t minPW, uint16_t maxPW, int16_t minAngle, int16_t maxAngle) { if (HAL_Validate_Pin_Function(pin, PF_TIMER)!=PF_TIMER) { return false; } // Safety check if (!pinAvailable(pin)) { return false; } if (this->attached()) { this->detach(); } this->pin = pin; this->minPW = minPW; this->maxPW = maxPW; this->minAngle = minAngle; this->maxAngle = maxAngle; HAL_Servo_Attach(this->pin); return true; } bool Servo::detach() { if (!this->attached()) { return false; } HAL_Servo_Detach(this->pin); this->resetFields(); return true; } void Servo::write(int degrees) { degrees = constrain(degrees, this->minAngle, this->maxAngle); this->writeMicroseconds(ANGLE_TO_US(degrees)+trim); } int Servo::read() const { int a = US_TO_ANGLE(this->readMicroseconds()-trim); // map() round-trips in a weird way we mostly correct for here; // the round-trip is still sometimes off-by-one for write(1) and // write(179). return a == this->minAngle || a == this->maxAngle ? a : a + 1; } void Servo::writeMicroseconds(uint16_t pulseWidth) { if (!this->attached()) { return; } pulseWidth = constrain(pulseWidth, this->minPW, this->maxPW); HAL_Servo_Write_Pulse_Width(this->pin, pulseWidth); } uint16_t Servo::readMicroseconds() const { if (!this->attached()) { return 0; } return HAL_Servo_Read_Pulse_Width(this->pin); } void Servo::resetFields(void) { this->pin = NOT_ATTACHED; this->minAngle = SERVO_DEFAULT_MIN_ANGLE; this->maxAngle = SERVO_DEFAULT_MAX_ANGLE; this->minPW = SERVO_DEFAULT_MIN_PW; this->maxPW = SERVO_DEFAULT_MAX_PW; this->trim = 0; }
24.288889
80
0.623056
adeeshag
a5a6d839502a01a11f2720b80fdd3f29eb0587c6
2,330
cpp
C++
main.cpp
ennis/autograph-shaders-2
7b7b91400206409c2fc422b04ab8732093e8b082
[ "MIT" ]
null
null
null
main.cpp
ennis/autograph-shaders-2
7b7b91400206409c2fc422b04ab8732093e8b082
[ "MIT" ]
null
null
null
main.cpp
ennis/autograph-shaders-2
7b7b91400206409c2fc422b04ab8732093e8b082
[ "MIT" ]
null
null
null
#include "clang/Frontend/FrontendActions.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" #include "clang/Tooling/ArgumentsAdjusters.h" #include "llvm/Support/CommandLine.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/CodeGen/ModuleBuilder.h" #include "clang/CodeGen/CodeGenAction.h" #include "clang/Serialization/ASTReader.h" #include <fstream> #include <iostream> #include "Driver.hpp" #include "Module.hpp" using namespace clang; using namespace clang::ast_matchers; using namespace clang::tooling; // Apply a custom category to all command-line options so that they are the // only ones displayed. static llvm::cl::OptionCategory MyToolCategory("agfxc options"); // CommonOptionsParser declares HelpMessage with a description of the common // command-line options related to the compilation database and input files. // It's nice to have this help message in all tools. static llvm::cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); // A help message for this specific tool can be added afterwards. static llvm::cl::extrahelp MoreHelp("\nMore help text..."); /* enum class ShaderStage { VertexShader, FragmentShader, GeometryShader, TessEvalShader, TessControlShader, ComputeShader }; */ //////////////////// Main frontend action class FXCDriverFrontendAction : public clang::ASTFrontendAction { public: virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer( clang::CompilerInstance &Compiler, llvm::StringRef InFile) { return std::unique_ptr<clang::ASTConsumer>(new fxc::Driver(Compiler.getASTContext(), Compiler.getDiagnostics())); } }; //////////////////// Main int main(int argc, const char **argv) { CommonOptionsParser OptionsParser(argc, argv, MyToolCategory); ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList()); Tool.appendArgumentsAdjuster(clang::tooling::getInsertArgumentAdjuster("-fmodules")); return Tool.run(newFrontendActionFactory<FXCDriverFrontendAction>().get()); }
31.917808
116
0.745923
ennis
a5af59e56fb3473c35d2877a58fc811bbac716b9
49,201
hh
C++
Dimensions.hh
pirl-lpl/pirlplusplus
d3211b05fc18f11fc66d97d5bcaeabcbd0b8b6e0
[ "Apache-2.0" ]
null
null
null
Dimensions.hh
pirl-lpl/pirlplusplus
d3211b05fc18f11fc66d97d5bcaeabcbd0b8b6e0
[ "Apache-2.0" ]
null
null
null
Dimensions.hh
pirl-lpl/pirlplusplus
d3211b05fc18f11fc66d97d5bcaeabcbd0b8b6e0
[ "Apache-2.0" ]
null
null
null
/* Dimensions PIRL CVS ID: $Id: Dimensions.hh,v 1.27 2011/02/18 02:29:28 castalia Exp $ Copyright (C) 2010 Arizona Board of Regents on behalf of the Planetary Image Research Laboratory, Lunar and Planetary Laboratory at the University of Arizona. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License, version 2.1, as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #ifndef _Dimensions_ #define _Dimensions_ #include <iosfwd> namespace PIRL { /*============================================================================== Types */ #ifndef COORDINATE_TYPE #define COORDINATE_TYPE int #endif #ifndef DIMENSIONS_TYPE #define DIMENSIONS_TYPE unsigned COORDINATE_TYPE #endif //! The integer data type of a coordinate value. typedef COORDINATE_TYPE Coordinate_Type; //! The integer data type of a dimension value. typedef DIMENSIONS_TYPE Dimensions_Type; /** Rounds a floating point number to the nearest integer value. The nearest integer value is found by adding 0.5 to the floating point number and truncating the result to the Coordinate_Type integer value. For negative numbers 0.5 is subtracted. Thus a floating point number exactly halfway beteen two integer values is rounded to the absolute larger integer with the sign preserved. @param number The floating point (double) number to be rounded. @return The integer value of the rounded number. */ inline Coordinate_Type Round (double number) {return (Coordinate_Type)(number > 0 ? (number + 0.5) : (number - 0.5));} //****************************************************************************** /** A <i>Point_2D</i> holds 2-dimensional position information. @author Bradford Castalia, UA/PIRL @version $Revision: 1.27 $ */ struct Point_2D { //! Class identification name with source code version and date. static const char* const ID; //! The horizontal (x-axis) position of the Point_2D. Coordinate_Type X; //! The vertical (y-axis) position of the Point_2D. Coordinate_Type Y; /*============================================================================== Constructors: */ //! Constructs a Point_2D at position 0,0. Point_2D (); /** Constructs a Point_2D at position x,y. @param x The horizontal (x-axis) position of the Point_2D. @param y The vertical (y-axis) position of the Point_2D. */ Point_2D (const Coordinate_Type& x,const Coordinate_Type& y); /** Constructs a Point_2D from another Point_2D. @param point A Point_2D to be copied. */ Point_2D (const Point_2D& point); /*============================================================================== Accessors: */ /** Set the position of this Point_2D. @param x The horizontal (x-axis) position of the Point_2D. @param y The vertical (y-axis) position of the Point_2D. @return This Point_2D. */ inline Point_2D& position (const Coordinate_Type& x,const Coordinate_Type& y) { X = x; Y = y; return *this; } /** Set the position of this Point_2D. @param point A Point_2D whose coordinates are to be assigned to this Point_2D. @return This Point_2D. */ inline Point_2D& position (const Point_2D& point) { X = point.X; Y = point.Y; return *this; } /** Assign the position of another Point_2D to this Point_2D. @param point A Point_2D whose coordinates are to be assigned to this Point_2D. */ inline Point_2D& operator= (const Point_2D& point) { if (this != &point) { X = point.X; Y = point.Y; } return *this; } /** Set the horizontal (x-axis) position. @param x_position The horizontal (x-axis) position of the Point_2D. @return This Point_2D. */ inline Point_2D& x (const Coordinate_Type& x_position) {X = x_position; return *this;} /** Get the horizontal (x-axis) position. @return The horizontal (x-axis) position of the Point_2D. */ inline Coordinate_Type x () const {return X;} /** Set the vertical (y-axis) position. @param y_position The vertical (y-axis) position of the Point_2D. @return This Point_2D. */ inline Point_2D& y (const Coordinate_Type& y_position) {Y = y_position; return *this;} /** Get the vertical (y-axis) position. @return The vertical (y-axis) position of the Point_2D. */ inline Coordinate_Type y () const {return Y;} /** Test if this Point_2D is equal to another Point_2D. The two Point_2Ds are equal if both their X and Y coordinates are equal. @param point The Point_2D to which this Point_2D is to be compared. @return true if the two Point_2Ds are equal; false otherwise. */ inline bool operator== (const Point_2D& point) const {return X == point.X && Y == point.Y;} /** Test if this Point_2D is not equal to another Point_2D. The two Point_2Ds are not equal if either their X or Y coordinates are not equal. @param point The Point_2D to which this Point_2D is to be compared. @return true if the two Point_2Ds are not equal; false otherwise. */ inline bool operator!= (const Point_2D& point) const {return X != point.X || Y != point.Y;} /** Test for all zero coordinate values. @return true if any coordinate value is non-zero; false otherwise. @see is_null() */ inline operator bool () {return X != 0 || Y != 0;} /** Test for all zero coordinate values. @return true if both coordinates are zero; false otherwise. @see operator bool() */ inline bool is_null () {return X == 0 && Y == 0;} /*============================================================================== Manipulators: */ /** Add an offset. @param offset A Point_2D that provides the offset values. @return This Point_2D with its values offset. */ inline Point_2D& operator+= (const Point_2D& offset) {X += offset.X; Y += offset.Y; return *this;} /** Subtract an offset. @param offset A Point_2D that provides the offset values. @return This Point_2D with its values offset. */ inline Point_2D& operator-= (const Point_2D& offset) {X -= offset.X; Y -= offset.Y; return *this;} /** Multiply by a factor. The new coordinate values will be rounded to the nearest Coordinate_Type values. @param factor A factor by which to multiply the Point_2D coordinates. @return This Point_2D with its values changed. */ inline Point_2D& operator*= (double factor) {X = Round (X * factor); Y = Round (Y * factor); return *this;} /** Divide by a factor. The new coordinate values will be rounded to the nearest Coordinate_Type values. <b>N.B.</b>: Divide by zero is handled as a special case. If the coordinate value was zero it will remain zero. If the Coordinate_Type has an infinity value (determined by numeric_types) that is used, or its negative if the coordinate value is negative. Otherwise, if the Coordinate_Type is signed the type's max value is used, or the min value if the coordinate value is negative; for an unsigned value the max value is used. @param factor A factor by which to divide the Point_2D dimensions. @return This Point_2D with its values changed. */ Point_2D& operator/= (double factor); }; // End of Point_2D class. /** Add two points. @param point_1 A Point_2D. @param point_2 A Point_2D. @return A Point_2D in which the dimensions are the sum of the dimensions of the specified points. */ inline Point_2D operator+ (const Point_2D& point_1, const Point_2D& point_2) {return Point_2D (point_1) += point_2;} /** Subtract one point from another. @param point_1 A Point_2D. @param point_2 A Point_2D. @return A Point_2D in which the dimensions are the difference of the dimensions of the specified points. */ inline Point_2D operator- (const Point_2D& point_1, const Point_2D& point_2) {return Point_2D (point_1) -= point_2;} /** Get the negation of a point. @param point A Point_2D. @return A Point_2D in which the dimensions are the negation of the dimensions of the specified points. */ inline Point_2D operator- (const Point_2D& point) {return Point_2D (-point.X, -point.Y);} /** Multiply a point by a factor. @param point A Point_2D. @param factor A floating point (double) number. @return A Point_2D in which the dimensions are the dimensions of the specified point multiplied by the factor and {@link Round(double) rounded}. */ inline Point_2D operator* (const Point_2D& point, double factor) {return Point_2D (point) *= factor;} /** Multiply a point by a factor. @param factor A floating point (double) number. @param point A Point_2D. @return A Point_2D in which the dimensions are the dimensions of the specified point multiplied by the factor and {@link Round(double) rounded}. */ inline Point_2D operator* (double factor, const Point_2D& point) {return Point_2D (point) *= factor;} /** Divide a point by a factor. @param point A Point_2D. @param factor A floating point (double) number. @return A Point_2D in which the dimensions are the dimensions of the specified point divided by the factor and {@link Round(double) rounded}. */ inline Point_2D operator/ (const Point_2D& point, double factor) {return Point_2D (point) /= factor;} /** Print a Point_2D description to an output stream. @param stream The ostream where the Point_2D will be printed. @param point The Print_2D to be printed. @return The stream that was written. */ std::ostream& operator<< (std::ostream& stream, const Point_2D& point); //****************************************************************************** /** A <i>Size_2D</i> holds 2-dimensional size information. @author Bradford Castalia, UA/PIRL @version $Revision: 1.27 $ */ struct Size_2D { //! The Width of the Size_2D. Dimensions_Type Width; //! The Height of the Size_2D. Dimensions_Type Height; /*============================================================================== Constructors: */ /** Constructs an empty Size_2D. Both Width and Height are zero. */ Size_2D (); /** Constructs a Size_2D with width,height size. @param width The Width of the Size_2D. @param height The Height of the Size_2D. */ Size_2D (const Dimensions_Type& width, const Dimensions_Type& height); /** Constructs a Size_2D of equal Width and Height. @param side The length of each side. Both Width and Height will be set to this value. */ Size_2D (const Dimensions_Type& side); /** Constructs a Size_2D from another Size_2D. @param size A Size_2D to be copied. */ Size_2D (const Size_2D& size); /*============================================================================== Accessors: */ /** Set the size of this Size_2D. @param width The Width of the Size_2D. @param height The Height of the Size_2D. @return This Size_2D. */ inline Size_2D& size (const Dimensions_Type& width, const Dimensions_Type& height) { Width = width; Height = height; return *this; } /** Set the size of this Size_2D. @param size A Size_2D to have its dimensions assigned to this Size_2D. @return This Size_2D. */ inline Size_2D& size (const Size_2D& size) { Width = size.Width; Height = size.Height; return *this; } /** Assign the dimensions of another Size_2D to this Size_2D. @param size A Size_2D to have its dimensions assigned to this Size_2D. */ inline Size_2D& operator= (const Size_2D& size) { if (this != &size) { Width = size.Width; Height = size.Height; } return *this; } /** Set the Width of the Size_2D. @param width The Width of the Size_2D. @return This Size_2D. */ inline Size_2D& width (const Dimensions_Type& width) {Width = width; return *this;} /** Get the Width of the Size_2D. @return The Width of the Size_2D. */ inline Dimensions_Type width () const {return Width;} /** Set the Height of the Size_2D. @param height The Height of the Size_2D. @return This Size_2D. */ inline Size_2D& height (const Dimensions_Type& height) {Height = height; return *this;} /** Get the Height of the Size_2D. @return The Height of the Size_2D. */ inline Dimensions_Type height () const {return Height;} /** Get the area of this Size_2D. @return The area (Width * Height) of the Size_2D. */ inline unsigned long long area () const {return (long long)Width * Height;} /** Test if this Size_2D is equal to another Size_2D. The two Size_2Ds are equal if both their Width and Height dimensions are equal. @param size The Size_2D to which this Size_2D is to be compared. @return true if the two Size_2Ds are equal; false otherwise. */ inline bool operator== (const Size_2D& size) const {return Width == size.Width && Height == size.Height;} /** Test if this Size_2D is not equal to another Size_2D. The two Size_2Ds are not equal if either their Width or Height dimensions are not equal. @param size The Size_2D to which this Size_2D is to be compared. @return true if the two Size_2Ds are not equal; false otherwise. */ inline bool operator!= (const Size_2D& size) const {return Width != size.Width || Height != size.Height;} /** Test for all zero dimension values. @return true if any dimension value is non-zero; false otherwise. */ inline operator bool () {return Width != 0 || Height != 0;} /** Test for any zero dimension values. @return true if any dimension is zero; false otherwise. */ inline bool is_empty () {return Width == 0 || Height == 0;} /*============================================================================== Manipulators: */ /** Add a size amount. @param size A Size_2D that provides the amount values. @return This Size_2D with the amount added to its values. */ inline Size_2D& operator+= (const Size_2D& size) {Width += size.Width; Height += size.Height; return *this;} /** Subtract a size amount. <b>N.B.</b>: If the size Dimensions_Type values are an unsigned type (as they are by default) and a size amount to be subtracted is greater than the corresponding dimension value, the result will be zero. @param size A Size_2D that provides the amount values. @return This Size_2D with the amount subtracted to its values. */ Size_2D& operator-= (const Size_2D& size); /** Multiply by a factor. The new size values will be rounded to the nearest Dimensions_Types. @param factor A factor by which to multiply the Size_2D dimensions. @return This Size_2D with its values changed. @throws invalid_argument If the factor is negative and the size values Dimensions_Type are an unsigned type (as they are by default). */ Size_2D& operator*= (double factor); /** Divide by a factor. The new dimension values will be rounded to the nearest Dimensions_Type values. <b>N.B.</b>: Divide by zero is handled as a special case. If the coordinate value was zero it will remain zero. If the Dimensions_Type has an infinity value (determined by numeric_types) that is used, or its negative if the coordinate value is negative. Otherwise, if the Dimensions_Type is signed the type's max value is used, or the min value if the coordinate value is negative; for an unsigned value the max value is used. @param factor A factor by which to divide the Size_2D dimensions. @return This Size_2D with its values changed. @throws invalid_argument If the factor is negative and the size values Dimensions_Type are an unsigned type (as they are by default). */ Size_2D& operator/= (double factor); }; // End of Size_2D class. /** Add two sizes. @param size_1 A Size_2D. @param size_2 A Size_2D. @return A Size_2D in which the dimensions are the sum of the dimensions of the specified sizes. */ inline Size_2D operator+ (const Size_2D& size_1, const Size_2D& size_2) {return Size_2D (size_1) += size_2;} /** Subtract one size from another. <b>N.B.</b>: If the size Dimensions_Type values are an unsigned type (as they are by default) and a size amount to be subtracted is greater than the corresponding dimension value, the result will be zero. @param size_1 A Size_2D. @param size_2 A Size_2D. @return A Size_2D in which the dimensions are the difference of the dimensions of the specified sizes. */ inline Size_2D operator- (const Size_2D& size_1, const Size_2D& size_2) {return Size_2D (size_1) -= size_2;} /** Multiply a size by a factor. @param size A Size_2D. @param factor A floating point (double) number. @return A Size_2D in which the dimensions are the dimensions of the specified size multiplied by the factor and {@link Round(double) rounded}. @throws invalid_argument If the factor is negative and the size values Dimensions_Type are an unsigned type (as they are by default). */ inline Size_2D operator* (const Size_2D& size, double factor) {return Size_2D (size) *= factor;} /** Multiply a size by a factor. @param factor A floating point (double) number. @param size A Size_2D. @return A Size_2D in which the dimensions are the dimensions of the specified size multiplied by the factor and {@link Round(double) rounded}. @throws invalid_argument If the factor is negative and the size values Dimensions_Type are an unsigned type (as they are by default). */ inline Size_2D operator* (double factor, const Size_2D& size) {return Size_2D (size) *= factor;} /** Divide a size by a factor. @param size A Size_2D. @param factor A floating point (double) number. @return A Size_2D in which the dimensions are the dimensions of the specified size divided by the factor and {@link Round(double) rounded}. @throws invalid_argument If the factor is negative and the size values Dimensions_Type are an unsigned type (as they are by default). */ inline Size_2D operator/ (const Size_2D& size, double factor) {return Size_2D (size) /= factor;} /** Print a Size_2D description to an output stream. @param stream The ostream where the Size_2D will be printed. @param size The Size_2D to be printed. @return The stream that was written. */ std::ostream& operator<< (std::ostream& stream, const Size_2D& size); //****************************************************************************** /** A <i>Rectangle</i> is a position with a size. The Rectangle's position is based in a Point_2D being at the upper left corner of the Rectangle, and its size is based in a Size_2D with the X-axis Width increasing to the right and the Y-axis Height increasing downward (raster order). @author Bradford Castalia, UA/PIRL @version $Revision: 1.27 $ @see Point_2D @see Size_2D */ struct Rectangle : public Point_2D, public Size_2D { /*============================================================================== Constructors: */ /** Constructs an empty Rectangle. The position is 0,0 and the size is 0,0. */ Rectangle (); /** Constructs a Rectangle from an x,y position and width,height size. @param x The horizontal (x-axis) position. @param y The vertical (y-axis) position. @param width The Width of the Rectangle. @param height The Height of the Rectangle. */ Rectangle ( const Coordinate_Type x, const Coordinate_Type y, const Dimensions_Type width = 0, const Dimensions_Type height = 0 ); /** Constructs a Rectangle from a position and a size. @param position A Point_2D. @param size A Size_2D. */ Rectangle (const Point_2D& position, const Size_2D& size); /** Constructs a Rectangle from a size at position 0,0. @param size A Size_2D. */ Rectangle (const Size_2D& size); /** Constructs a Rectangle as a copy of another Rectangle. @param rectangle A Rectangle to be copied. */ Rectangle (const Rectangle& rectangle); /*============================================================================== Accessors: */ /** Set the position of this Rectangle. @param x The horizontal (x-axis) position of the Rectangle. @param y The vertical (y-axis) position of the Rectangle. @return This Rectangle. */ inline Rectangle& position (const Coordinate_Type& x,const Coordinate_Type& y) {Point_2D::position (x, y); return *this;} /** Set the position of this Rectangle. @param point A Point_2D whose dimensions are to be assigned to this Rectangle. @return This Rectangle. */ inline Rectangle& position (const Point_2D& point) {Point_2D::position (point); return *this;} /** Assign the position of the Rectangle from a Point_2D. @param point A Point_2D for the position of the Rectangle. @return This Rectangle. */ inline Rectangle& operator= (const Point_2D& point) {Point_2D::operator= (point); return *this;} /** Get the Rectangle position. @return A Point_2D with the Rectangle position. <b>N.B.</b>: Changing this Point_2D will not change the position of the Rectangle. */ inline Point_2D position () const {return Point_2D (X, Y);} /** Convert the Rectangle to its corresponding Point_2D. @return A Point_2D with the Rectangle position. */ inline operator Point_2D () const {return position ();} /** Set the size of this Rectangle. @param width The Width of the Rectangle. @param height The Height of the Rectangle. @return This Rectangle. */ inline Rectangle& size (const Dimensions_Type& width, const Dimensions_Type& height) {Size_2D::size (width, height); return *this;} /** Set the size of this Rectangle. @param size A Size_2D to have its dimensions assigned to this Rectangle. @return This Rectangle. */ inline Rectangle& size (const Size_2D& size) {Size_2D::size (size); return *this;} /** Assign the size of the Rectangle from a Size_2D. @param size A Size_2D for the size of the Rectangle. @return This Rectangle. */ inline Rectangle& operator= (const Size_2D& size) {Size_2D::operator= (size); return *this;} /** Get the Rectangle size. @return A Size_2D with the Rectangle size. <b>N.B.</b>: Changing this size will not change the size of the Rectangle. */ inline Size_2D size () const {return Size_2D (Width, Height);} /** Convert the Rectangle to its corresponding Size_2D. @return A Size_2D with the Rectangle size. */ inline operator Size_2D () const {return size ();} /** Assign the position and size of another Rectangle to this Rectangle. @param rectangle A Rectangle whose position and size are to be assigned to this Rectangle. @return This Rectangle. */ inline Rectangle& operator= (const Rectangle& rectangle) { if (this != &rectangle) { X = rectangle.X; Y = rectangle.Y; Width = rectangle.Width; Height = rectangle.Height; } return *this; } /** Test if this Rectangle is equal to another Rectangle. The two Rectangles are equal if both their position and size dimensions are equal. @param rectangle The Rectangle to which this Rectangle is to be compared. @return true if the two Rectangles are equal; false otherwise. */ inline bool operator== (const Rectangle& rectangle) const {return Point_2D::operator== ((const Point_2D)rectangle) && Size_2D::operator== ((const Size_2D)rectangle);} /** Test if this Rectangle is not equal to another Rectangle. The two Rectangles are not equal if either their position or size dimensions are not equal. @param rectangle The Rectangle to which this Rectangle is to be compared. @return true if the two Rectangles are not equal; false otherwise. */ inline bool operator!= (const Rectangle& rectangle) const {return Point_2D::operator!= ((const Point_2D)rectangle) || Size_2D::operator!= ((const Size_2D)rectangle);} /** Test for all zero dimension values. @return true if any dimension value is non-zero; false otherwise. */ inline operator bool () {return Point_2D::operator bool () || Size_2D::operator bool ();} /*============================================================================== Manipulators: */ /** Add an offset. @param offset A Point_2D that provides the offset values. @return This Rectangle with its values offset. */ inline Rectangle& operator+= (const Point_2D& offset) {Point_2D::operator+= (offset); return *this;} /** Add a size amount. @param size A Size_2D that provides the amount values. @return This Rectangle with the amount added to its size values. */ inline Rectangle& operator+= (const Size_2D& size) {Size_2D::operator+= (size); return *this;} /** Add another Rectangle's point coordinate offset and size amount. @param rectangle A Rectangle. @return This Rectangle with its point coordinate offset by the other Rectangle's point coordinate values, and the other Rectangle's size amount added to its size dimensions. */ inline Rectangle& operator+= (const Rectangle& rectangle) { Point_2D::operator+= (static_cast<Point_2D>(rectangle)); Size_2D::operator+= (static_cast<Size_2D>(rectangle)); return *this; } /** Subtract an offset. @param offset A Point_2D that provides the offset values. @return This Rectangle with its values offset. */ inline Rectangle& operator-= (const Point_2D& offset) {Point_2D::operator-= (offset); return *this;} /** Subtract a size amount. <b>N.B.</b>: If the size Dimensions_Type values are an unsigned type (as they are by default) and a size amount to be subtracted is greater than the corresponding dimension value, the result will be zero. @param size A Size_2D that provides the amount values. @return This Rectangle with the amount subtracted to its values. */ inline Rectangle& operator-= (const Size_2D& size) {Size_2D::operator-= (size); return *this;} /** Subtract another Rectangle's point coordinate offset and size amount. @param rectangle A Rectangle. @return This Rectangle with its point coordinate offset by the other Rectangle's point coordinate values, and the other Rectangle's size amount subtracted from its size dimensions. */ inline Rectangle& operator-= (const Rectangle& rectangle) { Point_2D::operator-= (static_cast<Point_2D>(rectangle)); Size_2D::operator-= (static_cast<Size_2D>(rectangle)); return *this; } /** Multiply by a factor. The new size values will be rounded to the nearest Dimensions_Types. @param factor A factor by which to multiply the Size_2D dimensions. @return This Rectangle with its values changed. @throws invalid_argument If the factor is negative and the size values Dimensions_Type are an unsigned type (as they are by default). */ inline Rectangle& operator*= (double factor) {Size_2D::operator*= (factor); return *this;} /** Divide by a factor. The new size dimensions will be rounded to the nearest Dimensions_Type values. <b>N.B.</b>: Divide by zero is handled as a special case. If the coordinate value was zero it will remain zero. If the Dimensions_Type has an infinity value (determined by numeric_types) that is used, or its negative if the coordinate value is negative. Otherwise, if the Dimensions_Type is signed the type's max value is used, or the min value if the coordinate value is negative; for an unsigned value the max value is used. @param factor A factor by which to divide the Size_2D dimensions. @return This Rectangle with its values changed. @throws invalid_argument If the factor is negative and the size values Dimensions_Type are an unsigned type (as they are by default). */ inline Rectangle& operator/= (double factor) {Size_2D::operator/= (factor); return *this;} /** Take the intersection with another Rectangle. The intersection of two Rectangles is the overlapping area of both. @param rectangle The Rectangle to intersect with this Rectangle. @return This Rectangle with its position and size set to the intersection with the other Rectangle. If the Rectangles do not intersect this will result in a Rectangle with no area (Width and Height both zero) but the position will be unchanged. */ Rectangle& operator&= (const Rectangle& rectangle); /** Take the union with another Rectangle. The union of two Rectangles is the bounding area of both. @param rectangle The Rectangle to unite with this Rectangle. @return This Rectangle with its position and size set to the union - i.e. the bounding box - with the other Rectangle. */ Rectangle& operator|= (const Rectangle& rectangle); }; // End of Rectangle class. /** Add a Point_2D offset to a Rectangle. @param rectangle A Rectangle. @param point A Point_2D. @return A Rectangle in which the coordinate point dimensions are the Point_2D have been added to the coordinate point of the Rectangle. */ inline Rectangle operator+ (const Rectangle& rectangle, const Point_2D& point) {return Rectangle (rectangle) += point;} /** Add a Point_2D offset to a Rectangle. @param point A Point_2D. @param rectangle A Rectangle. @return A Rectangle in which the coordinate point dimensions of the Point_2D have been added to the coordinate point of the Rectangle. */ inline Rectangle operator+ (const Point_2D& point, const Rectangle& rectangle) {return Rectangle (rectangle) += point;} /** Add two Rectangles. @param rectangle_1 A Rectangle. @param rectangle_2 A Rectangle. @return A Rectangle in which the coordinate point dimensions and the size amounts of the two Rectangles have been added. */ inline Rectangle operator+ (const Rectangle& rectangle_1, const Rectangle& rectangle_2) {return Rectangle (rectangle_1) += rectangle_2;} /** Subtract a Point_2D offset from a Rectangle. @param rectangle A Rectangle. @param point A Point_2D. @return A Rectangle in which the coordinate point dimensions of the Point_2D have been subtracted from the coordinate point of the Rectangle. */ inline Rectangle operator- (const Rectangle& rectangle, const Point_2D& point) {return Rectangle (rectangle) -= point;} /** Subtract two Rectangles. @param rectangle_1 A Rectangle. @param rectangle_2 A Rectangle. @return A Rectangle in which the coordinate point dimensions and the size amounts of the two Rectangles have been added. */ inline Rectangle operator- (const Rectangle& rectangle_1, const Rectangle& rectangle_2) {return Rectangle (rectangle_1) -= rectangle_2;} /** Get the negation of a Rectangle. @param rectangle A Rectangle. @return A Rectangle in which the coordinate point dimensions are the negation of the Rectangle's coordinate point; the size is the same. */ inline Rectangle operator- (const Rectangle& rectangle) {return Rectangle (-rectangle.X, -rectangle.Y, rectangle.Width, rectangle.Height);} /** Add a size amount to a Rectangle. @param rectangle A Rectangle. @param size A Size_2D. @return A Rectangle in which the size amount has been added to the Rectangle size dimensions; the coordinate point is the same. */ inline Rectangle operator+ (const Rectangle& rectangle, const Size_2D& size) {return Rectangle (rectangle) += size;} /** Add a size amount to a Rectangle. @param size A Size_2D. @param rectangle A Rectangle. @return A Rectangle in which the size amount has been added to the negation of the Rectangle size dimensions; the coordinate point is the same. */ inline Rectangle operator+ (const Size_2D& size, const Rectangle& rectangle) {return Rectangle (rectangle) += size;} /** Subtract a size amount from a Rectangle. <b>N.B.</b>: If the size Dimensions_Type values are an unsigned type (as they are by default) and a size amount to be subtracted is greater than the corresponding dimension value, the result will be zero. @param size A Size_2D. @param rectangle A Rectangle. @return A Rectangle in which the size amount has been subtracted from the Rectangle size dimensions; the coordinate point is the same. */ inline Rectangle operator- (const Rectangle& rectangle, const Size_2D& size) {return Rectangle (rectangle) -= size;} /** Multiply a Rectangle by a factor. @param rectangle A Rectangle. @param factor A floating point (double) number. @return A Size_2D in which the dimensions are the dimensions of the specified size multiplied by the factor and {@link Round(double) rounded}. @throws invalid_argument If the factor is negative and the size values Dimensions_Type are an unsigned type (as they are by default). */ inline Rectangle operator* (const Rectangle& rectangle, double factor) {return Rectangle (rectangle) *= factor;} /** Multiply a Rectangle by a factor. @param factor A floating point (double) number. @param rectangle A Rectangle. @return A Rectangle in which the size dimensions are the dimensions of the specified Rectangle multiplied by the factor and {@link Round(double) rounded}. @throws invalid_argument If the factor is negative and the size values Dimensions_Type are an unsigned type (as they are by default). */ inline Rectangle operator* (double factor, const Rectangle& rectangle) {return Rectangle (rectangle) *= factor;} /** Divide a Rectangle by a factor. The new size dimensions will be rounded to the nearest Dimensions_Type values. <b>N.B.</b>: Divide by zero is handled as a special case. If the coordinate value was zero it will remain zero. If the Dimensions_Type has an infinity value (determined by numeric_types) that is used, or its negative if the coordinate value is negative. Otherwise, if the Dimensions_Type is signed the type's max value is used, or the min value if the coordinate value is negative; for an unsigned value the max value is used. @param rectangle A Rectangle. @param factor A floating point (double) number. @return A Rectangle in which the dimensions are the dimensions of the specified Rectangle divided by the factor and {@link Round(double) rounded}. @throws invalid_argument If the factor is negative and the size values Dimensions_Type are an unsigned type (as they are by default). */ inline Rectangle operator/ (const Rectangle& rectangle, double factor) {return Rectangle (rectangle) /= factor;} /** Get the intersection of two Rectangles. @param rectangle_1 A Rectangle. @param rectangle_2 A Rectangle. @return A Rectangle with its position and size set to the intersection of the two Rectangles. If the Rectangles do not intersect this will result in a Rectangle with no area (Width and Height both zero) but the position of the first Rectangle. */ inline Rectangle operator& (const Rectangle& rectangle_1, const Rectangle& rectangle_2) {return Rectangle (rectangle_1) &= rectangle_2;} /** Get the union of two Rectangles. @param rectangle_1 A Rectangle. @param rectangle_2 A Rectangle. @return A Rectangle with its position and size set to the union - i.e. the bounding box - of the two Rectangles. */ inline Rectangle& operator| (const Rectangle& rectangle_1, const Rectangle& rectangle_2) {return Rectangle (rectangle_1) |= rectangle_2;} /** Print a Rectangle description to an output stream. @param stream The ostream where the Rectangle will be printed. @param rectangle The Rectangle to be printed. @return The stream that was written. */ std::ostream& operator<< (std::ostream& stream, const Rectangle& rectangle); //****************************************************************************** /** A <i>Cube</i> is a Rectangle with depth. A Cube does not have a Z-dimension position. Instead it has a Depth with the position of the Cube having an implicit Z-coordinate of zero; i.e. the facing surface of the Cube defined by its Rectangle is at the Z-coordinate origin with the Z-axis Depth increasing away from the observer (right handed coordinate system). @author Bradford Castalia, UA/PIRL @version $Revision: 1.27 $ @see Rectangle */ struct Cube : public Rectangle { //! The Depth of the Cube. Dimensions_Type Depth; /*============================================================================== Constructors: */ /** Constructs an empty Cube. The position is 0,0; the size is 0,0; the Depth is 0. */ Cube (); /** Constructs a Cube from an x,y position, width,height size, and depth. @param x The horizontal (x-axis) position. @param y The vertical (y-axis) position. @param width The Width of the Cube. @param height The Height of the Cube. @param depth The Depth of the Cube. */ Cube ( const Coordinate_Type x, const Coordinate_Type y, const Dimensions_Type width = 0, const Dimensions_Type height = 0, const Dimensions_Type depth = 0 ); /** Constructs a Cube from a position and a size. The Cube will have a Depth of 1. @param position A Point_2D. @param size A Size_2D. */ Cube (const Point_2D& position, const Size_2D& size); /** Constructs a Cube from a size. The Cube will have a position of 0,0 and a Depth of 1. @param size A Size_2D. */ Cube (const Size_2D& size); /** Constructs a Cube from a Rectangle. The Cube will have a Depth of 1. @param rectangle A Rectangle. */ Cube (const Rectangle& rectangle); /** Constructs a Cube as a copy of another Cube. @param cube A Cube to be copied. */ Cube (const Cube& cube); /*============================================================================== Accessors: */ /** Set the position of this Cube. @param x The horizontal (x-axis) position of the Cube. @param y The vertical (y-axis) position of the Cube. @return This Cube. */ inline Cube& position (const Coordinate_Type& x,const Coordinate_Type& y) {Point_2D::position (x, y); return *this;} /** Set the position of this Cube. @param point A Point_2D whose dimensions are to be assigned as the position of this Cube. @return This Cube. */ inline Cube& position (const Point_2D& point) {Point_2D::position (point); return *this;} /** Assign the position of the Cube from a Point_2D. @param point A Point_2D for the position of the Cube. @return This Cube. */ inline Cube& operator= (const Point_2D& point) {Point_2D::operator= (point); return *this;} /** Set the size of this Cube. @param width The Width of the Cube. @param height The Height of the Cube. @return This Cube. */ inline Cube& size (const Dimensions_Type& width, const Dimensions_Type& height) {Size_2D::size (width, height); return *this;} /** Set the size of this Cube. @param size A Size_2D to have its dimensions assigned to this Cube. @return This Cube. */ inline Cube& size (const Size_2D& size) {Size_2D::size (size); return *this;} /** Set the Depth of this Cube. @param depth The Depth of this Cube. @return This Cube. */ inline Cube& depth (Dimensions_Type depth) {Depth = depth; return *this;} /** Get the Depth of this Cube. @return The Depth of this Cube. */ inline Dimensions_Type depth () const {return Depth;} /** Assign the size of the Cube from a Size_2D. @param size A Size_2D for the size of the Cube. @return This Cube. */ inline Cube& operator= (const Size_2D& size) {Size_2D::operator= (size); return *this;} /** Set the dimensions of this Cube from a Rectangle. @param rectangle A Rectangle to have its dimensions assigned to this Cube. @return This Cube. */ inline Cube& dimensions (const Rectangle& rectangle) {Rectangle::operator= (rectangle); return *this;} /** Set the dimensions of this Cube from a Rectangle. @param rectangle A Rectangle to have its dimensions assigned to this Cube. @return This Cube. */ inline Cube& operator= (const Rectangle& rectangle) {Rectangle::operator= (rectangle); return *this;} /** Assign the dimensions of another Cube to this Cube. @param cube A Cube whose dimensions are be assigned to this Cube. @return This Cube. */ inline Cube& operator= (const Cube& cube) { if (this != &cube) { X = cube.X; Y = cube.Y; Width = cube.Width; Height = cube.Height; Depth = cube.Depth; } return *this; } /** Get the volume of this Cube. @return The volume (Width * Height * Depth) of the Cube. */ inline unsigned long long volume () const {return area () * Depth;} /** Test if this Cube is equal to another Cube. The two Cubes are equal if both their Depth and Rectangle dimensions are equal. @param cube The Cube to which this Cube is to be compared. @return true if the two Cubes are equal; false otherwise. */ inline bool operator== (const Cube& cube) const {return Depth == cube.Depth && Rectangle::operator== ((const Rectangle)cube);} /** Test if this Cube is not equal to another Cube. The two Cubes are not equal if either their Depth or Rectangle dimensions are not equal. @param cube The Cube to which this Cube is to be compared. @return true if the two Cubes are not equal; false otherwise. */ inline bool operator!= (const Cube& cube) const {return Depth != cube.Depth || Rectangle::operator!= ((const Rectangle)cube);} /** Test for all zero dimension values. @return true if any dimension value is non-zero; false otherwise. */ inline operator bool () {return Depth != 0 || Rectangle::operator bool ();} /** Test for any zero dimension values. @return true if any dimension is zero; false otherwise. */ inline bool is_empty () {return Depth == 0 || Size_2D::is_empty ();} /*============================================================================== Manipulators: */ /** Add an amount to the Cube Depth. <B>N.B.</B>: If the Depth Dimensions_Type is unsigned (the default) and the amount is negative, the resulting Depth will not be less than zero. @param amount An integer amount to add to the Depth. @return This Cube with the amount applied. */ Cube& operator+= (int amount); /** Add another Cube's point coordinate offset, and depth and size amount. @param cube A Cube. @return This Cube with its point coordinate offset by the other Cube's point coordinate values, its Depth increased the other Cube's Depth, and the other Cube's size amount added to its size dimensions. */ inline Cube& operator+= (const Cube& cube) { Rectangle::operator+= (static_cast<Rectangle>(cube)); operator+= (cube.Depth); return *this; } /** Subtract an amount from the Cube Depth. <B>N.B.</B>: If the Depth Dimensions_Type is unsigned (the default) and the amount is positive, the resulting Depth will not be less than zero. @param amount An integer amount to subtract from the Depth. @return This Cube with the amount applied. */ inline Cube& operator-= (int amount) {operator+= (-amount); return *this;} /** Subtract another Cube's point coordinate and depth offset and size amount. @param cube A Cube. @return This Cube with its point coordinate offset negatively by the other Cube's point coordinate values, its Depth offset negatively by the other Cube's Depth, and the other Cube's size amount subtracted from its size dimensions. */ inline Cube& operator-= (const Cube& cube) { Rectangle::operator-= (static_cast<Rectangle>(cube)); operator-= (cube.Depth); return *this; } /** Multiply by a factor. The new size values will be rounded to the nearest Dimensions_Types. @param factor A factor by which to multiply the dimensions. @return This Cube with its dimension values changed. @throws invalid_argument If the factor is negative and the size values Dimensions_Type are an unsigned type (as they are by default). */ inline Cube& operator*= (double factor) { Rectangle::operator*= (factor); Depth = Round (Depth * factor); return *this; } /** Divide by a factor. The new size dimensions will be rounded to the nearest Dimensions_Type values. <b>N.B.</b>: Divide by zero is handled as a special case. If the coordinate value was zero it will remain zero. If the Dimensions_Type has an infinity value (determined by numeric_types) that is used, or its negative if the coordinate value is negative. Otherwise, if the Dimensions_Type is signed the type's max value is used, or the min value if the coordinate value is negative; for an unsigned value the max value is used. @param factor A factor by which to divide the dimensions. @return This Cube with its dimension values changed. @throws invalid_argument If the factor is negative and the size values Dimensions_Type are an unsigned type (as they are by default). */ Cube& operator/= (double factor); /** Take the intersection with another Cube. The intersection of the Depths of two Cubes is the minimum Depth; i.e. the two Cubes are assumed to be aligned at the zero X-Y plane. @param cube The Cube to intersect with this Cube. @return This Cube with its position, size and depth set to the intersection with the other Cube. If the Cubes do not intersect this will result in an {@link is_empty() emtpy} Cube (Width, Height and Depth zero) but the position will be unchanged. */ Cube& operator&= (const Cube& cube); /** Take the union with another Cube. The union of the Depths of two Cubes is the maximum Depth; i.e. the two Cubes are assumed to be aligned at the zero X-Y plane. @param cube The Cube to unite with this Cube. @return This Cube with its position, size and depth set to the union - i.e. the bounding volume - with the other Cube. */ Cube& operator|= (const Cube& cube); }; // End of Cube class. /** Add an amount to a Cube Depth. @param cube A Cube. @param amount An integer amount to add to the Depth. @return A Cube in which the amount has been added to the Depth of the other cube. @see Cube::operator+=(int) */ inline Cube operator+ (const Cube& cube, int amount) {return Cube (cube) += amount;} /** Subtract an amount from a Cube Depth. @param cube A Cube. @param amount An integer amount to substract from the Depth of the other cube. @return A Cube in which the amount has been subtracted from the Depth of the other cube. @see Cube::operator-=(int) */ inline Cube operator- (const Cube& cube, int amount) {return Cube (cube) -= amount;} /** Add two Cubes. @param cube_1 A Cube. @param cube_2 A Cube. @return A Cube in which the coordinate point dimensions and the size and depth amounts of the two Cubes have been added. @see Cube::operator+=(const Cube&) */ inline Cube operator+ (const Cube& cube_1, const Cube& cube_2) {return Cube (cube_1) += cube_2;} /** Subtract two Cubes. @param cube_1 A Cube. @param cube_2 A Cube. @return A Cube in which the coordinate point dimensions and the size and depth amounts of the two Cubes have been subtracted. @see Cube::operator-=(const Cube&) */ inline Cube operator- (const Cube& cube_1, const Cube& cube_2) {return Cube (cube_1) -= cube_2;} /** Multiply a Cube by a factor. @param cube A Cube. @param factor A floating point (double) number. @return A Cube in which the dimensions are the dimensions of the specified cube multiplied by the factor and {@link Round(double) rounded}. @throws invalid_argument If the factor is negative and the size values Dimensions_Type are an unsigned type (as they are by default). */ inline Cube operator* (const Cube& cube, double factor) {return Cube (cube) *= factor;} /** Multiply a Cube by a factor. @param factor A floating point (double) number. @param cube A Cube. @return A Cube in which the dimensions are the dimensions of the specified cube multiplied by the factor and {@link Round(double) rounded}. @throws invalid_argument If the factor is negative and the size values Dimensions_Type are an unsigned type (as they are by default). */ inline Cube operator* (double factor, const Cube& cube) {return Cube (cube) *= factor;} /** Divide a Cube by a factor. The new size dimensions will be rounded to the nearest Dimensions_Type values. <b>N.B.</b>: Divide by zero is handled as a special case. If the coordinate value was zero it will remain zero. If the Dimensions_Type has an infinity value (determined by numeric_types) that is used, or its negative if the coordinate value is negative. Otherwise, if the Dimensions_Type is signed the type's max value is used, or the min value if the coordinate value is negative; for an unsigned value the max value is used. @param cube A Cube. @param factor A floating point (double) number. @return A Cube in which the dimensions are the dimensions of the specified Cube divided by the factor and {@link Round(double) rounded}. @throws invalid_argument If the factor is negative and the size values Dimensions_Type are an unsigned type (as they are by default). */ inline Cube operator/ (const Cube& cube, double factor) {return Cube (cube) /= factor;} /** Get the intersection of two Cubes. The intersection the Depths of two Cubes is the minimum Depth; i.e. the two Cubes are assumed to be aligned at the zero X-Y plane. @param cube_1 A Cube. @param cube_2 A Cube. @return A Cube with its position, size and depth set to the intersection with the other Cube. If the Cubes do not intersect this will result in an emtpy Cube (Width, Height and Depth zero) but the position of the first Cube. */ inline Cube operator& (const Cube& cube_1, const Cube& cube_2) {return Cube (cube_1) &= cube_2;} /** Get the union of two Cubes. The union of the Depths of two Cubes is the maximum Depth; i.e. the two Cubes are assumed to be aligned at the zero X-Y plane. @param cube_1 A Cube. @param cube_2 A Cube. @return A Cube with its position, size and depth set to the union - i.e. the bounding volume - of the two Cubes. */ inline Cube& operator| (const Cube& cube_1, const Cube& cube_2) {return Cube (cube_1) |= cube_2;} /** Print a Cube description to an output stream. @param stream The ostream where the Cube will be printed. @param cube The Cube to be printed. @return The stream that was written. */ std::ostream& operator<< (std::ostream& stream, const Cube& cube); } // namespace PIRL #endif
30.635741
80
0.717242
pirl-lpl
a5b1aba678b7bd2cf1fedd5310d6b14c6c0247e4
1,116
hpp
C++
include/dca/phys/dca_step/cluster_solver/ctaux/walker/ct_aux_walker_tools_kernels.hpp
frobnitzem/DCA
9f5d16cbfe1a4c4df1d4c8353654dd2882671dca
[ "BSD-3-Clause" ]
27
2018-08-02T04:28:23.000Z
2021-07-08T02:14:20.000Z
include/dca/phys/dca_step/cluster_solver/ctaux/walker/ct_aux_walker_tools_kernels.hpp
frobnitzem/DCA
9f5d16cbfe1a4c4df1d4c8353654dd2882671dca
[ "BSD-3-Clause" ]
200
2018-08-02T18:19:03.000Z
2022-03-16T21:28:41.000Z
include/dca/phys/dca_step/cluster_solver/ctaux/walker/ct_aux_walker_tools_kernels.hpp
PDoakORNL/DCA-2
5a373f6af5a7d4b5be69199f60ec75a16e58c626
[ "BSD-3-Clause" ]
22
2018-08-15T15:50:00.000Z
2021-09-30T13:41:46.000Z
// Copyright (C) 2018 ETH Zurich // Copyright (C) 2018 UT-Battelle, LLC // All rights reserved. // // See LICENSE for terms of usage. // See CITATION.md for citation guidelines, if DCA++ is used for scientific publications. // // Author: Peter Staar ([email protected]) // // GPU kernels for walker tools. #ifndef DCA_PHYS_DCA_STEP_CLUSTER_SOLVER_CTAUX_WALKER_CT_AUX_WALKER_TOOLS_KERNELS_HPP #define DCA_PHYS_DCA_STEP_CLUSTER_SOLVER_CTAUX_WALKER_CT_AUX_WALKER_TOOLS_KERNELS_HPP namespace dca { namespace phys { namespace solver { namespace ctaux { namespace walkerkernels { // dca::phys::solver::ctaux::walkerkernels:: template <typename Real> void compute_Gamma(Real* Gamma, int Gamma_n, int Gamma_ld, Real* N, int N_r, int N_c, int N_ld, Real* G, int G_r, int G_c, int G_ld, int* random_vertex_vector, Real* exp_V, Real* exp_delta_V, int thread_id, int stream_id); } // namespace walkerkernels } // namespace ctaux } // namespace solver } // namespace phys } // namespace dca #endif // DCA_PHYS_DCA_STEP_CLUSTER_SOLVER_CTAUX_WALKER_CT_AUX_WALKER_TOOLS_KERNELS_HPP
32.823529
95
0.747312
frobnitzem
a5b232cf0e41043f2151ecd73a85066b68d773c1
78
cpp
C++
Source/L2NextCrypto/Private/Utils/Streams/InputStream.cpp
L2Next/L2NextCrypto
005a893b5d04e8fc522cb0e08f92b39d5411b98c
[ "MIT" ]
4
2020-09-04T21:33:35.000Z
2021-05-30T14:25:27.000Z
Source/L2NextCrypto/Private/Utils/Streams/InputStream.cpp
L2Next/L2NextCrypto
005a893b5d04e8fc522cb0e08f92b39d5411b98c
[ "MIT" ]
9
2020-08-15T14:07:12.000Z
2021-06-25T05:48:58.000Z
Source/L2NextCrypto/Private/Utils/Streams/InputStream.cpp
L2Next/L2NextCrypto
005a893b5d04e8fc522cb0e08f92b39d5411b98c
[ "MIT" ]
2
2020-11-20T04:03:42.000Z
2021-03-04T21:46:50.000Z
#include "Utils/Streams/InputStream.h" using namespace L2NextCryptoStreams;
15.6
38
0.820513
L2Next