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
f5a51726a003fa488e59a45a76bf0ea17909b6a2
2,934
cpp
C++
unit-test/exceptions_unittests.cpp
sparlane/buildsyspp
2a5a520ef4b636063b18cf783a60366d50174c16
[ "BSD-2-Clause" ]
null
null
null
unit-test/exceptions_unittests.cpp
sparlane/buildsyspp
2a5a520ef4b636063b18cf783a60366d50174c16
[ "BSD-2-Clause" ]
null
null
null
unit-test/exceptions_unittests.cpp
sparlane/buildsyspp
2a5a520ef4b636063b18cf783a60366d50174c16
[ "BSD-2-Clause" ]
2
2019-07-14T19:48:22.000Z
2019-09-27T08:32:57.000Z
#define CATCH_CONFIG_MAIN #include "exceptions.hpp" #include <catch2/catch.hpp> using namespace buildsys; TEST_CASE("Test CustomException", "") { bool exception_caught = false; std::string exception_message(""); std::string test_message("Test exception message"); try { throw CustomException(test_message); } catch(CustomException &e) { exception_caught = true; exception_message = e.what(); } REQUIRE(exception_caught); REQUIRE(exception_message == test_message); exception_caught = false; exception_message = ""; try { throw CustomException(test_message); } catch(std::runtime_error &e) { exception_caught = true; exception_message = e.what(); } REQUIRE(exception_caught); REQUIRE(exception_message == test_message); exception_caught = false; exception_message = ""; try { throw CustomException(test_message); } catch(std::exception &e) { exception_caught = true; exception_message = e.what(); } REQUIRE(exception_caught); REQUIRE(exception_message == test_message); } TEST_CASE("Test NoKeyException", "") { bool exception_caught = false; std::string exception_message(""); std::string expected_message("Key does not exist"); try { throw NoKeyException(); } catch(NoKeyException &e) { exception_caught = true; exception_message = e.what(); } REQUIRE(exception_caught); REQUIRE(exception_message == expected_message); exception_caught = false; exception_message = ""; try { throw NoKeyException(); } catch(std::runtime_error &e) { exception_caught = true; exception_message = e.what(); } REQUIRE(exception_caught); REQUIRE(exception_message == expected_message); exception_caught = false; exception_message = ""; try { throw NoKeyException(); } catch(std::exception &e) { exception_caught = true; exception_message = e.what(); } REQUIRE(exception_caught); REQUIRE(exception_message == expected_message); } TEST_CASE("Test FileNotFoundException", "") { bool exception_caught = false; std::string exception_message(""); std::string expected_message("test_location: File not found 'test_file'"); try { throw FileNotFoundException("test_file", "test_location"); } catch(FileNotFoundException &e) { exception_caught = true; exception_message = e.what(); } REQUIRE(exception_caught); REQUIRE(exception_message == expected_message); exception_caught = false; exception_message = ""; try { throw FileNotFoundException("test_file", "test_location"); } catch(std::runtime_error &e) { exception_caught = true; exception_message = e.what(); } REQUIRE(exception_caught); REQUIRE(exception_message == expected_message); exception_caught = false; exception_message = ""; try { throw FileNotFoundException("test_file", "test_location"); } catch(std::exception &e) { exception_caught = true; exception_message = e.what(); } REQUIRE(exception_caught); REQUIRE(exception_message == expected_message); }
21.573529
75
0.729721
sparlane
f5a65bcd5141fcaa19c8e4a4480980785dc2ae99
1,875
cpp
C++
libs/smart_ptr/test/weak_ptr_timing_test.cpp
zyiacas/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
198
2015-01-13T05:47:18.000Z
2022-03-09T04:46:46.000Z
libs/smart_ptr/test/weak_ptr_timing_test.cpp
sdfict/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
9
2015-01-28T16:33:19.000Z
2020-04-12T23:03:28.000Z
libs/smart_ptr/test/weak_ptr_timing_test.cpp
sdfict/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
139
2015-01-15T20:09:31.000Z
2022-01-31T15:21:16.000Z
#include <boost/config.hpp> #if defined(BOOST_MSVC) #pragma warning(disable: 4786) // identifier truncated in debug info #pragma warning(disable: 4710) // function not inlined #pragma warning(disable: 4711) // function selected for automatic inline expansion #pragma warning(disable: 4514) // unreferenced inline removed #endif // // weak_ptr_timing_test.cpp // // Copyright (c) 2002 Peter Dimov and Multi Media Ltd. // Copyright 2005 Peter Dimov // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> #include <vector> #include <cstdio> #include <ctime> #include <cstdlib> // int const n = 29000; int const k = 2048; void test( std::vector< boost::shared_ptr<int> > & v ) { using namespace std; // printf, rand std::vector< boost::weak_ptr<int> > w( v.begin(), v.end() ); int s = 0, r = 0; for( int i = 0; i < n; ++i ) { // randomly kill a pointer v[ rand() % k ].reset(); for( int j = 0; j < k; ++j ) { if( boost::shared_ptr<int> px = w[ j ].lock() ) { ++s; } else { ++r; w[ j ] = v[ rand() % k ]; } } } printf( "\n%d locks, %d rebinds.", s, r ); } int main() { using namespace std; // printf, clock_t, clock std::vector< boost::shared_ptr<int> > v( k ); for( int i = 0; i < k; ++i ) { v[ i ].reset( new int( 0 ) ); } clock_t t = clock(); test( v ); t = clock() - t; printf( "\n\n%.3f seconds.\n", static_cast<double>( t ) / CLOCKS_PER_SEC ); return 0; }
21.802326
84
0.528
zyiacas
f5aeec8bee262271d88691fafbf88ecd6a543093
7,410
hpp
C++
src/mlpack/core/optimizers/bigbatch_sgd/bigbatch_sgd.hpp
chigur/mlpack
aff1eda03b7c279acb6d3e660d5c5a6f697d3735
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
675
2019-02-07T01:23:19.000Z
2022-03-28T05:45:10.000Z
src/mlpack/core/optimizers/bigbatch_sgd/bigbatch_sgd.hpp
chigur/mlpack
aff1eda03b7c279acb6d3e660d5c5a6f697d3735
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
843
2019-01-25T01:06:46.000Z
2022-03-16T11:15:53.000Z
src/mlpack/core/optimizers/bigbatch_sgd/bigbatch_sgd.hpp
chigur/mlpack
aff1eda03b7c279acb6d3e660d5c5a6f697d3735
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
83
2019-02-20T06:18:46.000Z
2022-03-20T09:36:09.000Z
/** * @file bigbatch_sgd.hpp * @author Marcus Edel * * Definition of Big-batch Stochastic Gradient Descent (BBSGD) as described in: * "Big Batch SGD: Automated Inference using Adaptive Batch Sizes" * by Soham De et al. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_CORE_OPTIMIZERS_BIGBATCH_SGD_BIGBATCH_SGD_HPP #define MLPACK_CORE_OPTIMIZERS_BIGBATCH_SGD_BIGBATCH_SGD_HPP #include <mlpack/prereqs.hpp> #include "adaptive_stepsize.hpp" #include "backtracking_line_search.hpp" namespace mlpack { namespace optimization { /** * Big-batch Stochastic Gradient Descent is a technique for minimizing a * function which can be expressed as a sum of other functions. That is, * suppose we have * * \f[ * f(A) = \sum_{i = 0}^{n} f_i(A) * \f] * * and our task is to minimize \f$ A \f$. Big-batch SGD iterates over batches * of functions \f$ \{ f_{i0}(A), f_{i1}(A), \ldots, f_{i(m - 1)}(A) \f$ for * some batch size \f$ m \f$, producing the following update scheme: * * \f[ * A_{j + 1} = A_j + \alpha \left(\sum_{k = 0}^{m - 1} \nabla f_{ik}(A) \right) * \f] * * where \f$ \alpha \f$ is a parameter which specifies the step size. Each * big-batch is passed through either sequentially or randomly. The algorithm * continues until \f$ j \f$ reaches the maximum number of iterations---or when * a full sequence of updates through each of the big-batches produces an * improvement within a certain tolerance \f$ \epsilon \f$. * * The parameter \f$ \epsilon \f$ is specified by the tolerance parameter tot he * constructor, as is the maximum number of iterations specified by the * maxIterations parameter. * * This class is useful for data-dependent functions whose objective function * can be expressed as a sum of objective functions operating on an individual * point. Then, big-batch SGD considers the gradient of the objective function * operation on an individual big-batch of points in its update of \f$ A \f$. * * For more information, please refer to: * * @code * @article{De2017, * title = {Big Batch {SGD:} Automated Inference using Adaptive Batch * Sizes}, * author = {Soham De and Abhay Kumar Yadav and David W. Jacobs and Tom Goldstein}, * journal = {CoRR}, * year = {2017}, * url = {http://arxiv.org/abs/1610.05792}, * } * @endcode * * For big-batch SGD to work, a DecomposableFunctionType template parameter is * required. * This class must implement the following function: * * size_t NumFunctions(); * double Evaluate(const arma::mat& coordinates, const size_t i); * void Gradient(const arma::mat& coordinates, * const size_t i, * arma::mat& gradient); * * NumFunctions() should return the number of functions, and in the other two * functions, the parameter i refers to which individual function (or gradient) * is being evaluated. So, for the case of a data-dependent function, such as * NCA (see mlpack::nca::NCA), NumFunctions() should return the number of points * in the dataset, and Evaluate(coordinates, 0) will evaluate the objective * function on the first point in the dataset (presumably, the dataset is held * internally in the DecomposableFunctionType). * * @tparam UpdatePolicyType Update policy used during the iterative update * process. By default the AdaptiveStepsize update policy is used. */ template<typename UpdatePolicyType = AdaptiveStepsize> class BigBatchSGD { public: /** * Construct the BigBatchSGD optimizer with the given function and * parameters. The defaults here are not necessarily good for the given * problem, so it is suggested that the values used be tailored for the task * at hand. The maximum number of iterations refers to the maximum number of * batches that are processed. * * @param batchSize Initial batch size. * @param stepSize Step size for each iteration. * @param batchDelta Factor for the batch update step. * @param maxIterations Maximum number of iterations allowed (0 means no * limit). * @param tolerance Maximum absolute tolerance to terminate algorithm. * @param shuffle If true, the batch order is shuffled; otherwise, each * batch is visited in linear order. */ BigBatchSGD(const size_t batchSize = 1000, const double stepSize = 0.01, const double batchDelta = 0.1, const size_t maxIterations = 100000, const double tolerance = 1e-5, const bool shuffle = true); /** * Optimize the given function using big-batch SGD. The given starting point * will be modified to store the finishing point of the algorithm, and the * final objective value is returned. * * @tparam DecomposableFunctionType Type of the function to be optimized. * @param function Function to optimize. * @param iterate Starting point (will be modified). * @return Objective value of the final point. */ template<typename DecomposableFunctionType> double Optimize(DecomposableFunctionType& function, arma::mat& iterate); //! Get the batch size. size_t BatchSize() const { return batchSize; } //! Modify the batch size. size_t& BatchSize() { return batchSize; } //! Get the step size. double StepSize() const { return stepSize; } //! Modify the step size. double& StepSize() { return stepSize; } //! Get the batch delta. double BatchDelta() const { return batchDelta; } //! Modify the batch delta. double& BatchDelta() { return batchDelta; } //! Get the maximum number of iterations (0 indicates no limit). size_t MaxIterations() const { return maxIterations; } //! Modify the maximum number of iterations (0 indicates no limit). size_t& MaxIterations() { return maxIterations; } //! Get the tolerance for termination. double Tolerance() const { return tolerance; } //! Modify the tolerance for termination. double& Tolerance() { return tolerance; } //! Get whether or not the individual functions are shuffled. bool Shuffle() const { return shuffle; } //! Modify whether or not the individual functions are shuffled. bool& Shuffle() { return shuffle; } //! Get the update policy. UpdatePolicyType UpdatePolicy() const { return updatePolicy; } //! Modify the update policy. UpdatePolicyType& UpdatePolicy() { return updatePolicy; } private: //! The size of the current batch. size_t batchSize; //! The step size for each example. double stepSize; //! The factor for the batch update step. double batchDelta; //! The maximum number of allowed iterations. size_t maxIterations; //! The tolerance for termination. double tolerance; //! Controls whether or not the individual functions are shuffled when //! iterating. bool shuffle; //! The update policy used to update the parameters in each iteration. UpdatePolicyType updatePolicy; }; using BBS_Armijo = BigBatchSGD<BacktrackingLineSearch>; using BBS_BB = BigBatchSGD<AdaptiveStepsize>; } // namespace optimization } // namespace mlpack // Include implementation. #include "bigbatch_sgd_impl.hpp" #endif
36.865672
80
0.704723
chigur
f5afc318edecf04ee4ab00efcb17737adaf605f6
11,398
cpp
C++
core/block_rw.cpp
0xb100d/wink-c-
361677a68861ea65a58351dd6aa208c1977385e5
[ "Apache-2.0" ]
1
2019-05-31T07:43:51.000Z
2019-05-31T07:43:51.000Z
core/block_rw.cpp
0xb100d/wink-c-
361677a68861ea65a58351dd6aa208c1977385e5
[ "Apache-2.0" ]
null
null
null
core/block_rw.cpp
0xb100d/wink-c-
361677a68861ea65a58351dd6aa208c1977385e5
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 The Beam Team // // 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 <ctime> #include "block_crypt.h" #include "../utility/serialize.h" #include "../pow/impl/utilstrencodings.h" #include "../core/serialization_adapters.h" #include "aes.h" namespace beam { ///////////// // RW const char* const Block::BodyBase::RW::s_pszSufix[Type::count] = { #define THE_MACRO(x) #x, MBLOCK_DATA_Types(THE_MACRO) #undef THE_MACRO }; void Block::BodyBase::RW::GetPath(std::string& s, int iData) const { assert(iData < Type::count); s = m_sPath + s_pszSufix[iData]; } void Block::BodyBase::RW::ROpen() { Open(true); } void Block::BodyBase::RW::WCreate() { Open(false); } void Block::BodyBase::RW::Open(bool bRead) { using namespace std; m_bRead = bRead; if (bRead) { static_assert(Type::hd == 0, ""); // must be the 1st to open for (int i = 0; i < Type::count; i++) OpenInternal(i); } else Delete(); } bool Block::BodyBase::RW::OpenInternal(int iData) { std::string s; GetPath(s, iData); if (!m_pS[iData].Open(s.c_str(), m_bRead)) return false; PostOpen(iData); return true; } void Block::BodyBase::RW::PostOpen(int iData) { if (m_bRead) { yas::binary_iarchive<std::FStream, SERIALIZE_OPTIONS> arc(m_pS[iData]); ECC::Hash::Value hv; arc & hv; if (Type::hd == iData) { if (hv != Rules::get().Checksum) throw std::runtime_error("Block rules mismatch"); arc & m_hvContentTag; } else { if (hv != m_hvContentTag) throw std::runtime_error("MB tags mismatch"); } } else { yas::binary_oarchive<std::FStream, SERIALIZE_OPTIONS> arc(m_pS[iData]); if (Type::hd == iData) arc & Rules::get().Checksum; arc & m_hvContentTag; } } void Block::BodyBase::RW::Delete() { for (int i = 0; i < Type::count; i++) { std::string s; GetPath(s, i); DeleteFile(s.c_str()); } } void Block::BodyBase::RW::Close() { for (int i = 0; i < Type::count; i++) m_pS[i].Close(); } Block::BodyBase::RW::~RW() { if (m_bAutoDelete) { Close(); Delete(); } } void Block::BodyBase::RW::Reset() { for (int i = 0; i < Type::count; i++) if (m_pS[i].IsOpen()) { m_pS[i].Restart(); PostOpen(i); } // preload LoadInternal(m_pUtxoIn, Type::ui, m_pGuardUtxoIn); LoadInternal(m_pUtxoOut, Type::uo, m_pGuardUtxoOut); LoadInternal(m_pKernelIn, Type::ki, m_pGuardKernelIn); LoadInternal(m_pKernelOut, Type::ko, m_pGuardKernelOut); } void Block::BodyBase::RW::Flush() { for (int i = 0; i < Type::count; i++) if (m_pS[i].IsOpen()) m_pS[i].Flush(); } void Block::BodyBase::RW::Clone(Ptr& pOut) { RW* pRet = new RW; pOut.reset(pRet); pRet->m_sPath = m_sPath; pRet->Open(m_bRead); } void Block::BodyBase::RW::NextUtxoIn() { LoadInternal(m_pUtxoIn, Type::ui, m_pGuardUtxoIn); } void Block::BodyBase::RW::NextUtxoOut() { LoadInternal(m_pUtxoOut, Type::uo, m_pGuardUtxoOut); } void Block::BodyBase::RW::NextKernelIn() { LoadInternal(m_pKernelIn, Type::ki, m_pGuardKernelIn); } void Block::BodyBase::RW::NextKernelOut() { LoadInternal(m_pKernelOut, Type::ko, m_pGuardKernelOut); } void Block::BodyBase::RW::get_Start(BodyBase& body, SystemState::Sequence::Prefix& prefix) { if (!m_pS[Type::hd].IsOpen()) std::ThrowIoError(); yas::binary_iarchive<std::FStream, SERIALIZE_OPTIONS> arc(m_pS[Type::hd]); arc & body; arc & prefix; } bool Block::BodyBase::RW::get_NextHdr(SystemState::Sequence::Element& elem) { std::FStream& s = m_pS[Type::hd]; if (!s.get_Remaining()) return false; yas::binary_iarchive<std::FStream, SERIALIZE_OPTIONS> arc(s); arc & elem; return true; } void Block::BodyBase::RW::WriteIn(const Input& v) { WriteInternal(v, Type::ui); } void Block::BodyBase::RW::WriteIn(const TxKernel& v) { WriteInternal(v, Type::ki); } void Block::BodyBase::RW::WriteOut(const Output& v) { WriteInternal(v, Type::uo); } void Block::BodyBase::RW::WriteOut(const TxKernel& v) { WriteInternal(v, Type::ko); } void Block::BodyBase::RW::put_Start(const BodyBase& body, const SystemState::Sequence::Prefix& prefix) { WriteInternal(body, Type::hd); WriteInternal(prefix, Type::hd); } void Block::BodyBase::RW::put_NextHdr(const SystemState::Sequence::Element& elem) { WriteInternal(elem, Type::hd); } template <typename T> void Block::BodyBase::RW::LoadInternal(const T*& pPtr, int iData, typename T::Ptr* ppGuard) { std::FStream& s = m_pS[iData]; if (s.IsOpen() && s.get_Remaining()) { ppGuard[0].swap(ppGuard[1]); //if (!ppGuard[0]) ppGuard[0].reset(new T); CommitmentAndMaturity::SerializeMaturity scope(true); yas::binary_iarchive<std::FStream, SERIALIZE_OPTIONS> arc(s); arc & *ppGuard[0]; pPtr = ppGuard[0].get(); } else pPtr = NULL; } template <typename T> void Block::BodyBase::RW::WriteInternal(const T& v, int iData) { std::FStream& s = m_pS[iData]; if (!s.IsOpen() && !OpenInternal(iData)) std::ThrowIoError(); CommitmentAndMaturity::SerializeMaturity scope(true); yas::binary_oarchive<std::FStream, SERIALIZE_OPTIONS> arc(s); arc & v; } void TxBase::IWriter::Dump(IReader&& r) { r.Reset(); for (; r.m_pUtxoIn; r.NextUtxoIn()) WriteIn(*r.m_pUtxoIn); for (; r.m_pUtxoOut; r.NextUtxoOut()) WriteOut(*r.m_pUtxoOut); for (; r.m_pKernelIn; r.NextKernelIn()) WriteIn(*r.m_pKernelIn); for (; r.m_pKernelOut; r.NextKernelOut()) WriteOut(*r.m_pKernelOut); } bool TxBase::IWriter::Combine(IReader&& r0, IReader&& r1, const volatile bool& bStop) { IReader* ppR[] = { &r0, &r1 }; return Combine(ppR, _countof(ppR), bStop); } bool TxBase::IWriter::Combine(IReader** ppR, int nR, const volatile bool& bStop) { for (int i = 0; i < nR; i++) ppR[i]->Reset(); // Utxo while (true) { if (bStop) return false; const Input* pInp = NULL; const Output* pOut = NULL; int iInp = 0, iOut = 0; // initialized just to suppress the warning, not really needed for (int i = 0; i < nR; i++) { const Input* pi = ppR[i]->m_pUtxoIn; if (pi && (!pInp || (*pInp > *pi))) { pInp = pi; iInp = i; } const Output* po = ppR[i]->m_pUtxoOut; if (po && (!pOut || (*pOut > *po))) { pOut = po; iOut = i; } } if (pInp) { if (pOut) { int n = CmpInOut(*pInp, *pOut); if (n > 0) pInp = NULL; else if (!n) { // skip both ppR[iInp]->NextUtxoIn(); ppR[iOut]->NextUtxoOut(); continue; } } } else if (!pOut) break; if (pInp) { WriteIn(*pInp); ppR[iInp]->NextUtxoIn(); } else { WriteOut(*pOut); ppR[iOut]->NextUtxoOut(); } } // Kernels while (true) { if (bStop) return false; const TxKernel* pInp = NULL; const TxKernel* pOut = NULL; int iInp = 0, iOut = 0; // initialized just to suppress the warning, not really needed for (int i = 0; i < nR; i++) { const TxKernel* pi = ppR[i]->m_pKernelIn; if (pi && (!pInp || (*pInp > *pi))) { pInp = pi; iInp = i; } const TxKernel* po = ppR[i]->m_pKernelOut; if (po && (!pOut || (*pOut > *po))) { pOut = po; iOut = i; } } if (pInp) { if (pOut) { int n = pInp->cmp(*pOut); if (n > 0) pInp = NULL; else if (!n) { // skip both ppR[iInp]->NextUtxoIn(); ppR[iOut]->NextUtxoOut(); continue; } } } else if (!pOut) break; if (pInp) { WriteIn(*pInp); ppR[iInp]->NextKernelIn(); } else { WriteOut(*pOut); ppR[iOut]->NextKernelOut(); } } return true; } bool Block::BodyBase::IMacroWriter::CombineHdr(IMacroReader&& r0, IMacroReader&& r1, const volatile bool& bStop) { Block::BodyBase body0, body1; Block::SystemState::Sequence::Prefix prefix0, prefix1; Block::SystemState::Sequence::Element elem; r0.Reset(); r0.get_Start(body0, prefix0); r1.Reset(); r1.get_Start(body1, prefix1); body0.Merge(body1); put_Start(body0, prefix0); while (r0.get_NextHdr(elem)) { if (bStop) return false; put_NextHdr(elem); } while (r1.get_NextHdr(elem)) { if (bStop) return false; put_NextHdr(elem); } return true; } ///////////// // KeyString void KeyString::Export(const ECC::HKdf& v) { ECC::NoLeak<ECC::HKdf::Packed> p; v.Export(p.V); Export(&p.V, sizeof(p.V), 's'); } void KeyString::Export(const ECC::HKdfPub& v) { ECC::NoLeak<ECC::HKdfPub::Packed> p; v.Export(p.V); Export(&p.V, sizeof(p.V), 'P'); } void KeyString::Export(void* p, uint32_t nData, uint8_t nCode) { ByteBuffer bb; bb.resize(sizeof(MacValue) + nData + 1 + m_sMeta.size()); MacValue& mv = reinterpret_cast<MacValue&>(bb.at(0)); bb[sizeof(MacValue)] = nCode; memcpy(&bb.at(1) + sizeof(MacValue), p, nData); memcpy(&bb.at(1) + sizeof(MacValue) + nData, m_sMeta.c_str(), m_sMeta.size()); XCrypt(mv, static_cast<uint32_t>(nData + 1 + m_sMeta.size()), true); m_sRes = EncodeBase64(&bb.at(0), bb.size()); } bool KeyString::Import(ECC::HKdf& v) { ECC::NoLeak<ECC::HKdf::Packed> p; return Import(&p.V, sizeof(p.V), 's') && v.Import(p.V); } bool KeyString::Import(ECC::HKdfPub& v) { ECC::NoLeak<ECC::HKdfPub::Packed> p; return Import(&p.V, sizeof(p.V), 'P') && v.Import(p.V); } bool KeyString::Import(void* p, uint32_t nData, uint8_t nCode) { bool bInvalid = false; ByteBuffer bb = DecodeBase64(m_sRes.c_str(), &bInvalid); if (bInvalid || (bb.size() < sizeof(MacValue) + 1 + nData)) return false; MacValue& mv = reinterpret_cast<MacValue&>(bb.at(0)); MacValue mvOrg = mv; XCrypt(mv, static_cast<uint32_t>(bb.size()) - sizeof(mv), false); if ((mv != mvOrg) || (bb[sizeof(MacValue)] != nCode)) return false; memcpy(p, &bb.at(1) + sizeof(MacValue), nData); m_sMeta.resize(bb.size() - (sizeof(MacValue) + 1 + nData)); if (!m_sMeta.empty()) memcpy(&m_sMeta.front(), &bb.at(1) + sizeof(MacValue) + nData, m_sMeta.size()); return true; } void KeyString::XCrypt(MacValue& mv, uint32_t nSize, bool bEnc) const { static_assert(AES::s_KeyBytes == sizeof(m_hvSecret.V), ""); AES::Encoder enc; enc.Init(m_hvSecret.V.m_pData); AES::StreamCipher c; ECC::NoLeak<ECC::Hash::Value> hvIV; ECC::Hash::Processor() << m_hvSecret.V >> hvIV.V; c.m_Counter = hvIV.V; // truncated c.m_nBuf = 0; ECC::Hash::Mac hmac; hmac.Reset(m_hvSecret.V.m_pData, m_hvSecret.V.nBytes); if (bEnc) hmac.Write(reinterpret_cast<uint8_t*>(&mv + 1), nSize); c.XCrypt(enc, reinterpret_cast<uint8_t*>(&mv + 1), nSize); if (!bEnc) hmac.Write(reinterpret_cast<uint8_t*>(&mv + 1), nSize); hmac >> hvIV.V; mv = hvIV.V; } } // namespace beam
20.536937
113
0.614318
0xb100d
f5b19e402b916b62d86c457feb63a0bc6169329a
1,094
cpp
C++
models/utils/rw/csv_qoi_writer.cpp
CancerModeling/Angiogenesis3D1D
77527d3facd127e225ccb9e53874ddbba2096744
[ "BSL-1.0" ]
2
2021-11-02T07:49:33.000Z
2021-11-16T15:47:40.000Z
models/utils/rw/csv_qoi_writer.cpp
CancerModeling/Angiogenesis3D1D
77527d3facd127e225ccb9e53874ddbba2096744
[ "BSL-1.0" ]
null
null
null
models/utils/rw/csv_qoi_writer.cpp
CancerModeling/Angiogenesis3D1D
77527d3facd127e225ccb9e53874ddbba2096744
[ "BSL-1.0" ]
null
null
null
#include "csv_qoi_writer.hpp" #include "qoi.hpp" namespace util { CSVQoIWriter::CSVQoIWriter(libMesh::Parallel::Communicator *comm, std::string filename) : d_comm(comm), d_filename(std::move(filename)) {} void CSVQoIWriter::write(const util::QoIVec &qoi) const { // only rank zero is allowed to write if (d_comm->rank() != 0) return; std::fstream filecsv; filecsv.open(d_filename, std::ios::out); const auto names = qoi.get_names(); const auto data = qoi.get_all(); const auto num_timesteps = data.size(); const auto num_quantities = names.size(); // write header of csv file for (int qidx = 0; qidx < num_quantities; qidx += 1) { filecsv << names[qidx]; if (qidx < num_quantities - 1) filecsv << ","; else filecsv << "\n"; } for (int tidx = 0; tidx < num_timesteps; tidx += 1) { for (int qidx = 0; qidx < num_quantities; qidx += 1) { filecsv << std::scientific << data[tidx][qidx]; if (qidx < num_quantities - 1) filecsv << ","; else filecsv << "\n"; } } } } // namespace util
23.782609
87
0.610603
CancerModeling
f5bb03f1ee45dca4e4945ce6c753619435c0e3ef
1,390
cpp
C++
FlavoEngine/src/Framework/FWindow.cpp
Thirrash/FlavoEngine
fc3e867dc726d1a37ddd81bb6a1691833014703a
[ "MIT" ]
null
null
null
FlavoEngine/src/Framework/FWindow.cpp
Thirrash/FlavoEngine
fc3e867dc726d1a37ddd81bb6a1691833014703a
[ "MIT" ]
null
null
null
FlavoEngine/src/Framework/FWindow.cpp
Thirrash/FlavoEngine
fc3e867dc726d1a37ddd81bb6a1691833014703a
[ "MIT" ]
null
null
null
#include "FWindow.h" #include <glad/glad.h> #include <GLFW/glfw3.h> #include "Debug.h" Framework::FWindow::FWindow() {} Framework::FWindow::~FWindow() { delete GlfwWindow; } Framework::EWindowInitErrorCode Framework::FWindow::Initi() { if (!glfwInit()) { LogR("Failed to init GLFW"); return GlfwInitError; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GlfwWindow = glfwCreateWindow(DEFAULT_WIDTH, DEFAULT_HEIGHT, "PAG Ex2", NULL, NULL); if (!GlfwWindow) { LogR("Failed to create GLFW window"); glfwTerminate(); return GlfwWindowNull; } glfwMakeContextCurrent(GlfwWindow); //glfw uses C-style pointers and we need to somehow assign method pointer to it glfwSetWindowUserPointer(GlfwWindow, this); glfwSetFramebufferSizeCallback(GlfwWindow, [](GLFWwindow* Window, int Width, int Height) {static_cast<FWindow*>(glfwGetWindowUserPointer(Window))->OnFramebufferSizeChange(Window, Width, Height); }); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { LogR("Failed to load GLAD"); return GladInitError; } return Success; } void Framework::FWindow::Close() { glfwSetWindowShouldClose(GlfwWindow, true); } void Framework::FWindow::OnFramebufferSizeChange(GLFWwindow* Window, int Width, int Height) { glViewport(0, 0, Width, Height); }
28.367347
199
0.760432
Thirrash
f5be9a047a3d553604dee59c15b00a3214d38797
454
cpp
C++
C++-practice/排队2.cpp
GengchenXU/Star-gazer
19a119390d3f1bfa56c4dda1b04f6c673e49be24
[ "MIT" ]
4
2019-11-08T11:04:02.000Z
2021-09-08T08:24:50.000Z
C++-practice/排队2.cpp
GengchenXU/Star-gazer
19a119390d3f1bfa56c4dda1b04f6c673e49be24
[ "MIT" ]
1
2019-11-08T11:07:35.000Z
2019-11-22T06:33:24.000Z
C++-practice/排队2.cpp
GengchenXU/Star-gazer
19a119390d3f1bfa56c4dda1b04f6c673e49be24
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; char boy; int reline(char str[], int s) { int n; if (str[s] != boy) { return s; } else { n = reline(str, s+1); cout << s << ' ' << n << endl; return reline(str, n+1); } } int main() { char str[101] = {0}; cin >> str; boy = str[0]; int n = reline(str, 1); cout << "0 " << n << endl; return 0; }
15.133333
39
0.405286
GengchenXU
f5beb5a85d55df8b66dbc3c57e9fcf1e8f999d0d
6,773
cpp
C++
JUCE/modules/juce_audio_utils/gui/juce_AudioVisualiserComponent.cpp
jukea/HISE
9e867c746d48f24c7fe6fdedad801ecafa3481e6
[ "Intel" ]
1
2021-03-04T19:37:06.000Z
2021-03-04T19:37:06.000Z
JUCE/modules/juce_audio_utils/gui/juce_AudioVisualiserComponent.cpp
psobot/HISE
cb97378039bae22c8eade3d4b699931bfd65c7d1
[ "Intel", "MIT" ]
null
null
null
JUCE/modules/juce_audio_utils/gui/juce_AudioVisualiserComponent.cpp
psobot/HISE
cb97378039bae22c8eade3d4b699931bfd65c7d1
[ "Intel", "MIT" ]
null
null
null
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 5 End-User License Agreement and JUCE 5 Privacy Policy (both updated and effective as of the 27th April 2017). End User License Agreement: www.juce.com/juce-5-licence Privacy Policy: www.juce.com/juce-5-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { struct AudioVisualiserComponent::ChannelInfo { ChannelInfo (AudioVisualiserComponent& o, int bufferSize) : owner (o), nextSample (0), subSample (0) { setBufferSize (bufferSize); clear(); } void clear() noexcept { for (int i = 0; i < levels.size(); ++i) levels.getReference(i) = Range<float>(); value = Range<float>(); subSample = 0; } void pushSamples (const float* inputSamples, const int num) noexcept { for (int i = 0; i < num; ++i) pushSample (inputSamples[i]); } void pushSample (const float newSample) noexcept { if (--subSample <= 0) { nextSample %= levels.size(); levels.getReference (nextSample++) = value; subSample = owner.getSamplesPerBlock(); value = Range<float> (newSample, newSample); } else { value = value.getUnionWith (newSample); } } void setBufferSize (int newSize) { levels.removeRange (newSize, levels.size()); levels.insertMultiple (-1, Range<float>(), newSize - levels.size()); if (nextSample >= newSize) nextSample = 0; } AudioVisualiserComponent& owner; Array<Range<float>> levels; Range<float> value; int nextSample, subSample; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelInfo) }; //============================================================================== AudioVisualiserComponent::AudioVisualiserComponent (const int initialNumChannels) : numSamples (1024), inputSamplesPerBlock (256), backgroundColour (Colours::black), waveformColour (Colours::white) { setOpaque (true); setNumChannels (initialNumChannels); setRepaintRate (60); } AudioVisualiserComponent::~AudioVisualiserComponent() { } void AudioVisualiserComponent::setNumChannels (const int numChannels) { channels.clear(); for (int i = 0; i < numChannels; ++i) channels.add (new ChannelInfo (*this, numSamples)); } void AudioVisualiserComponent::setBufferSize (int newNumSamples) { numSamples = newNumSamples; for (int i = 0; i < channels.size(); ++i) channels.getUnchecked(i)->setBufferSize (newNumSamples); } void AudioVisualiserComponent::clear() { for (int i = 0; i < channels.size(); ++i) channels.getUnchecked(i)->clear(); } void AudioVisualiserComponent::pushBuffer (const float** d, int numChannels, int num) { numChannels = jmin (numChannels, channels.size()); for (int i = 0; i < numChannels; ++i) channels.getUnchecked(i)->pushSamples (d[i], num); } void AudioVisualiserComponent::pushBuffer (const AudioSampleBuffer& buffer) { pushBuffer (buffer.getArrayOfReadPointers(), buffer.getNumChannels(), buffer.getNumSamples()); } void AudioVisualiserComponent::pushBuffer (const AudioSourceChannelInfo& buffer) { const int numChannels = jmin (buffer.buffer->getNumChannels(), channels.size()); for (int i = 0; i < numChannels; ++i) channels.getUnchecked(i)->pushSamples (buffer.buffer->getReadPointer (i, buffer.startSample), buffer.numSamples); } void AudioVisualiserComponent::pushSample (const float* d, int numChannels) { numChannels = jmin (numChannels, channels.size()); for (int i = 0; i < numChannels; ++i) channels.getUnchecked(i)->pushSample (d[i]); } void AudioVisualiserComponent::setSamplesPerBlock (int newSamplesPerPixel) noexcept { inputSamplesPerBlock = newSamplesPerPixel; } void AudioVisualiserComponent::setRepaintRate (int frequencyInHz) { startTimerHz (frequencyInHz); } void AudioVisualiserComponent::timerCallback() { repaint(); } void AudioVisualiserComponent::setColours (Colour bk, Colour fg) noexcept { backgroundColour = bk; waveformColour = fg; repaint(); } void AudioVisualiserComponent::paint (Graphics& g) { g.fillAll (backgroundColour); Rectangle<float> r (getLocalBounds().toFloat()); const float channelHeight = r.getHeight() / channels.size(); g.setColour (waveformColour); for (int i = 0; i < channels.size(); ++i) { const ChannelInfo& c = *channels.getUnchecked(i); paintChannel (g, r.removeFromTop (channelHeight), c.levels.begin(), c.levels.size(), c.nextSample); } } void AudioVisualiserComponent::getChannelAsPath (Path& path, const Range<float>* levels, int numLevels, int nextSample) { path.preallocateSpace (4 * numLevels + 8); for (int i = 0; i < numLevels; ++i) { const float level = -(levels[(nextSample + i) % numLevels].getEnd()); if (i == 0) path.startNewSubPath (0.0f, level); else path.lineTo ((float) i, level); } for (int i = numLevels; --i >= 0;) path.lineTo ((float) i, -(levels[(nextSample + i) % numLevels].getStart())); path.closeSubPath(); } void AudioVisualiserComponent::paintChannel (Graphics& g, Rectangle<float> area, const Range<float>* levels, int numLevels, int nextSample) { Path p; getChannelAsPath (p, levels, numLevels, nextSample); g.fillPath (p, AffineTransform::fromTargetPoints (0.0f, -1.0f, area.getX(), area.getY(), 0.0f, 1.0f, area.getX(), area.getBottom(), (float) numLevels, -1.0f, area.getRight(), area.getY())); } } // namespace juce
29.70614
120
0.589547
jukea
f5bf32c491569ad8ed8cccc470cf43fe63c7a85e
17,940
cpp
C++
osrm-backend/src/gen-cpp/map_service_types.cpp
shiyuan/osrm
ce730ce5e471870b86b460c09051cd301476ef07
[ "MIT" ]
null
null
null
osrm-backend/src/gen-cpp/map_service_types.cpp
shiyuan/osrm
ce730ce5e471870b86b460c09051cd301476ef07
[ "MIT" ]
null
null
null
osrm-backend/src/gen-cpp/map_service_types.cpp
shiyuan/osrm
ce730ce5e471870b86b460c09051cd301476ef07
[ "MIT" ]
null
null
null
/** * Autogenerated by Thrift Compiler (0.10.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "map_service_types.h" #include <algorithm> #include <ostream> #include <thrift/TToString.h> namespace map_service { int _kRetCodeValues[] = { RetCode::fail, RetCode::success, RetCode::degrade }; const char* _kRetCodeNames[] = { "fail", "success", "degrade" }; const std::map<int, const char*> _RetCode_VALUES_TO_NAMES(::apache::thrift::TEnumIterator(3, _kRetCodeValues, _kRetCodeNames), ::apache::thrift::TEnumIterator(-1, NULL, NULL)); Point::~Point() throw() { } void Point::__set_lat(const double val) { this->lat = val; } void Point::__set_lng(const double val) { this->lng = val; } uint32_t Point::read(::apache::thrift::protocol::TProtocol* iprot) { apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_lat = false; bool isset_lng = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_DOUBLE) { xfer += iprot->readDouble(this->lat); isset_lat = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_DOUBLE) { xfer += iprot->readDouble(this->lng); isset_lng = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_lat) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_lng) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t Point::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("Point"); xfer += oprot->writeFieldBegin("lat", ::apache::thrift::protocol::T_DOUBLE, 1); xfer += oprot->writeDouble(this->lat); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("lng", ::apache::thrift::protocol::T_DOUBLE, 2); xfer += oprot->writeDouble(this->lng); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(Point &a, Point &b) { using ::std::swap; swap(a.lat, b.lat); swap(a.lng, b.lng); } Point::Point(const Point& other0) { lat = other0.lat; lng = other0.lng; } Point& Point::operator=(const Point& other1) { lat = other1.lat; lng = other1.lng; return *this; } void Point::printTo(std::ostream& out) const { using ::apache::thrift::to_string; out << "Point("; out << "lat=" << to_string(lat); out << ", " << "lng=" << to_string(lng); out << ")"; } Step::~Step() throw() { } void Step::__set_source(const int64_t val) { this->source = val; } void Step::__set_target(const int64_t val) { this->target = val; } void Step::__set_distance(const double val) { this->distance = val; } void Step::__set_duration(const double val) { this->duration = val; } uint32_t Step::read(::apache::thrift::protocol::TProtocol* iprot) { apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_source = false; bool isset_target = false; bool isset_distance = false; bool isset_duration = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->source); isset_source = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->target); isset_target = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_DOUBLE) { xfer += iprot->readDouble(this->distance); isset_distance = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_DOUBLE) { xfer += iprot->readDouble(this->duration); isset_duration = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_source) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_target) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_distance) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_duration) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t Step::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("Step"); xfer += oprot->writeFieldBegin("source", ::apache::thrift::protocol::T_I64, 1); xfer += oprot->writeI64(this->source); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("target", ::apache::thrift::protocol::T_I64, 2); xfer += oprot->writeI64(this->target); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("distance", ::apache::thrift::protocol::T_DOUBLE, 3); xfer += oprot->writeDouble(this->distance); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("duration", ::apache::thrift::protocol::T_DOUBLE, 4); xfer += oprot->writeDouble(this->duration); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(Step &a, Step &b) { using ::std::swap; swap(a.source, b.source); swap(a.target, b.target); swap(a.distance, b.distance); swap(a.duration, b.duration); } Step::Step(const Step& other2) { source = other2.source; target = other2.target; distance = other2.distance; duration = other2.duration; } Step& Step::operator=(const Step& other3) { source = other3.source; target = other3.target; distance = other3.distance; duration = other3.duration; return *this; } void Step::printTo(std::ostream& out) const { using ::apache::thrift::to_string; out << "Step("; out << "source=" << to_string(source); out << ", " << "target=" << to_string(target); out << ", " << "distance=" << to_string(distance); out << ", " << "duration=" << to_string(duration); out << ")"; } PointToPointRequest::~PointToPointRequest() throw() { } void PointToPointRequest::__set_source(const Point& val) { this->source = val; } void PointToPointRequest::__set_target(const Point& val) { this->target = val; } void PointToPointRequest::__set_step(const bool val) { this->step = val; __isset.step = true; } uint32_t PointToPointRequest::read(::apache::thrift::protocol::TProtocol* iprot) { apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_source = false; bool isset_target = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->source.read(iprot); isset_source = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->target.read(iprot); isset_target = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_BOOL) { xfer += iprot->readBool(this->step); this->__isset.step = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_source) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_target) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t PointToPointRequest::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("PointToPointRequest"); xfer += oprot->writeFieldBegin("source", ::apache::thrift::protocol::T_STRUCT, 1); xfer += this->source.write(oprot); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("target", ::apache::thrift::protocol::T_STRUCT, 2); xfer += this->target.write(oprot); xfer += oprot->writeFieldEnd(); if (this->__isset.step) { xfer += oprot->writeFieldBegin("step", ::apache::thrift::protocol::T_BOOL, 3); xfer += oprot->writeBool(this->step); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(PointToPointRequest &a, PointToPointRequest &b) { using ::std::swap; swap(a.source, b.source); swap(a.target, b.target); swap(a.step, b.step); swap(a.__isset, b.__isset); } PointToPointRequest::PointToPointRequest(const PointToPointRequest& other4) { source = other4.source; target = other4.target; step = other4.step; __isset = other4.__isset; } PointToPointRequest& PointToPointRequest::operator=(const PointToPointRequest& other5) { source = other5.source; target = other5.target; step = other5.step; __isset = other5.__isset; return *this; } void PointToPointRequest::printTo(std::ostream& out) const { using ::apache::thrift::to_string; out << "PointToPointRequest("; out << "source=" << to_string(source); out << ", " << "target=" << to_string(target); out << ", " << "step="; (__isset.step ? (out << to_string(step)) : (out << "<null>")); out << ")"; } PointToPointResponse::~PointToPointResponse() throw() { } void PointToPointResponse::__set_code(const RetCode::type val) { this->code = val; } void PointToPointResponse::__set_distance(const double val) { this->distance = val; } void PointToPointResponse::__set_duration(const double val) { this->duration = val; } void PointToPointResponse::__set_steps(const std::vector<Step> & val) { this->steps = val; __isset.steps = true; } void PointToPointResponse::__set_projections(const std::vector<Point> & val) { this->projections = val; __isset.projections = true; } uint32_t PointToPointResponse::read(::apache::thrift::protocol::TProtocol* iprot) { apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_code = false; bool isset_distance = false; bool isset_duration = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_I32) { int32_t ecast6; xfer += iprot->readI32(ecast6); this->code = (RetCode::type)ecast6; isset_code = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_DOUBLE) { xfer += iprot->readDouble(this->distance); isset_distance = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_DOUBLE) { xfer += iprot->readDouble(this->duration); isset_duration = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->steps.clear(); uint32_t _size7; ::apache::thrift::protocol::TType _etype10; xfer += iprot->readListBegin(_etype10, _size7); this->steps.resize(_size7); uint32_t _i11; for (_i11 = 0; _i11 < _size7; ++_i11) { xfer += this->steps[_i11].read(iprot); } xfer += iprot->readListEnd(); } this->__isset.steps = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->projections.clear(); uint32_t _size12; ::apache::thrift::protocol::TType _etype15; xfer += iprot->readListBegin(_etype15, _size12); this->projections.resize(_size12); uint32_t _i16; for (_i16 = 0; _i16 < _size12; ++_i16) { xfer += this->projections[_i16].read(iprot); } xfer += iprot->readListEnd(); } this->__isset.projections = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_code) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_distance) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_duration) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t PointToPointResponse::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("PointToPointResponse"); xfer += oprot->writeFieldBegin("code", ::apache::thrift::protocol::T_I32, 1); xfer += oprot->writeI32((int32_t)this->code); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("distance", ::apache::thrift::protocol::T_DOUBLE, 2); xfer += oprot->writeDouble(this->distance); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("duration", ::apache::thrift::protocol::T_DOUBLE, 3); xfer += oprot->writeDouble(this->duration); xfer += oprot->writeFieldEnd(); if (this->__isset.steps) { xfer += oprot->writeFieldBegin("steps", ::apache::thrift::protocol::T_LIST, 4); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->steps.size())); std::vector<Step> ::const_iterator _iter17; for (_iter17 = this->steps.begin(); _iter17 != this->steps.end(); ++_iter17) { xfer += (*_iter17).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); } if (this->__isset.projections) { xfer += oprot->writeFieldBegin("projections", ::apache::thrift::protocol::T_LIST, 5); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->projections.size())); std::vector<Point> ::const_iterator _iter18; for (_iter18 = this->projections.begin(); _iter18 != this->projections.end(); ++_iter18) { xfer += (*_iter18).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(PointToPointResponse &a, PointToPointResponse &b) { using ::std::swap; swap(a.code, b.code); swap(a.distance, b.distance); swap(a.duration, b.duration); swap(a.steps, b.steps); swap(a.projections, b.projections); swap(a.__isset, b.__isset); } PointToPointResponse::PointToPointResponse(const PointToPointResponse& other19) { code = other19.code; distance = other19.distance; duration = other19.duration; steps = other19.steps; projections = other19.projections; __isset = other19.__isset; } PointToPointResponse& PointToPointResponse::operator=(const PointToPointResponse& other20) { code = other20.code; distance = other20.distance; duration = other20.duration; steps = other20.steps; projections = other20.projections; __isset = other20.__isset; return *this; } void PointToPointResponse::printTo(std::ostream& out) const { using ::apache::thrift::to_string; out << "PointToPointResponse("; out << "code=" << to_string(code); out << ", " << "distance=" << to_string(distance); out << ", " << "duration=" << to_string(duration); out << ", " << "steps="; (__isset.steps ? (out << to_string(steps)) : (out << "<null>")); out << ", " << "projections="; (__isset.projections ? (out << to_string(projections)) : (out << "<null>")); out << ")"; } } // namespace
27.685185
176
0.622464
shiyuan
f5c56e27284c956497f36758fed378f618e8b1c1
3,410
cpp
C++
TraceControl/TraceControlJsonRpc.cpp
Khan3033/ThunderNanoServices
82ce924edba046489cd02654843acd31ad8fbfe2
[ "Apache-2.0" ]
null
null
null
TraceControl/TraceControlJsonRpc.cpp
Khan3033/ThunderNanoServices
82ce924edba046489cd02654843acd31ad8fbfe2
[ "Apache-2.0" ]
null
null
null
TraceControl/TraceControlJsonRpc.cpp
Khan3033/ThunderNanoServices
82ce924edba046489cd02654843acd31ad8fbfe2
[ "Apache-2.0" ]
null
null
null
#include "Module.h" #include "TraceControl.h" #include <interfaces/json/JsonData_TraceControl.h> namespace WPEFramework { namespace Plugin { using namespace JsonData::TraceControl; // Registration // void TraceControl::RegisterAll() { Register<StatusParamsData,StatusResultData>(_T("status"), &TraceControl::endpoint_status, this); Register<TraceInfo,void>(_T("set"), &TraceControl::endpoint_set, this); } void TraceControl::UnregisterAll() { Unregister(_T("set")); Unregister(_T("status")); } JsonData::TraceControl::StateType TraceControl::TranslateState(TraceControl::state state) { JsonData::TraceControl::StateType newState; switch (state) { case TraceControl::state::ENABLED: newState = JsonData::TraceControl::StateType::ENABLED; break; case TraceControl::state::DISABLED: newState = JsonData::TraceControl::StateType::DISABLED; break; case TraceControl::state::TRISTATED: newState = JsonData::TraceControl::StateType::TRISTATED; break; default: break; } return newState; } // API implementation // // Method: status - Retrieves general information // Return codes: // - ERROR_NONE: Success uint32_t TraceControl::endpoint_status(const StatusParamsData& params, StatusResultData& response) { uint32_t result = Core::ERROR_NONE; response.Console = _config.Console; response.Remote.Port = _config.Remote.Port; response.Remote.Binding = _config.Remote.Binding; Observer::ModuleIterator index(_observer.Modules()); while (index.Next() == true) { string moduleName(Core::ToString(index.Module())); Observer::ModuleIterator::CategoryIterator categories(index.Categories()); if ((params.Module.IsSet() == false) || ((params.Module.IsSet() == true) && (moduleName == params.Module.Value()))) { while (categories.Next()) { string categoryName(Core::ToString(categories.Category())); if ((params.Category.IsSet() == false) || ((params.Category.IsSet() == true) && (categoryName == params.Category.Value()))) { Data::Trace trace = Data::Trace(moduleName, categoryName, categories.State()); JsonData::TraceControl::TraceInfo traceResponse; traceResponse.Module = trace.Module; traceResponse.Category = trace.Category; traceResponse.State = TranslateState(trace.State); response.Settings.Add(traceResponse); } } } } return result; } // Method: set - Sets traces // Return codes: // - ERROR_NONE: Success uint32_t TraceControl::endpoint_set(const TraceInfo& params) { uint32_t result = Core::ERROR_NONE; _observer.Set((params.State.Value() == JsonData::TraceControl::StateType::ENABLED), (params.Module.IsSet() == true ? params.Module.Value() : std::string(EMPTY_STRING)), (params.Category.IsSet() == true ? params.Category.Value() : std::string(EMPTY_STRING))); return result; } } // namespace Plugin }
32.47619
145
0.6
Khan3033
f5c86d8275b4a15fd2a9ddeefb3469f0904997fb
1,172
cpp
C++
Source/Prefab.cpp
Project-3-UPC-DDV-BCN/Project3
3fb345ce49485ccbc7d03fb320623df6114b210c
[ "MIT" ]
10
2018-01-16T16:18:42.000Z
2019-02-19T19:51:45.000Z
Source/Prefab.cpp
Project-3-UPC-DDV-BCN/Project3
3fb345ce49485ccbc7d03fb320623df6114b210c
[ "MIT" ]
136
2018-05-10T08:47:58.000Z
2018-06-15T09:38:10.000Z
Source/Prefab.cpp
Project-3-UPC-DDV-BCN/Project3
3fb345ce49485ccbc7d03fb320623df6114b210c
[ "MIT" ]
1
2018-06-04T17:18:40.000Z
2018-06-04T17:18:40.000Z
#include "Prefab.h" #include "Data.h" #include <ctime> #include <vector> #include "GameObject.h" #include "ModuleResources.h" #include "Application.h" #include "ModuleScene.h" #include "ModuleFileSystem.h" Prefab::Prefab() { SetType(Resource::PrefabResource); } Prefab::~Prefab() { } void Prefab::Save(Data & data) const { data.AddInt("GameObjectsCount", App->scene->saving_index); data.AddString("library_path", GetLibraryPath()); data.AddString("assets_path", GetAssetsPath()); data.AddString("prefab_name", GetName()); data.AddUInt("UUID", GetUID()); App->scene->saving_index = 0; } bool Prefab::Load(Data & data) { SetUID(data.GetUInt("UUID")); SetAssetsPath(data.GetString("assets_path")); SetLibraryPath(data.GetString("library_path")); SetName(data.GetString("prefab_name")); return true; } void Prefab::CreateMeta() const { time_t now = time(0); char* dt = ctime(&now); Data data; data.AddInt("Type", GetType()); data.AddUInt("UUID", GetUID()); data.AddString("Time_Created", dt); data.AddString("Library_path", GetLibraryPath()); data.SaveAsMeta(GetAssetsPath()); } void Prefab::LoadToMemory() { } void Prefab::UnloadFromMemory() { }
19.533333
59
0.710751
Project-3-UPC-DDV-BCN
f5ca9023d96b8b39adeee017979ca1b0ed9b0caf
2,448
cpp
C++
libcxx/test/std/input.output/filesystems/fs.op.funcs/fs.op.current_path/current_path.pass.cpp
nawrinsu/llvm
e9153f0e50d45fb4a760463ae711aa45ce2bd450
[ "Apache-2.0" ]
null
null
null
libcxx/test/std/input.output/filesystems/fs.op.funcs/fs.op.current_path/current_path.pass.cpp
nawrinsu/llvm
e9153f0e50d45fb4a760463ae711aa45ce2bd450
[ "Apache-2.0" ]
null
null
null
libcxx/test/std/input.output/filesystems/fs.op.funcs/fs.op.current_path/current_path.pass.cpp
nawrinsu/llvm
e9153f0e50d45fb4a760463ae711aa45ce2bd450
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <filesystem> // path current_path(); // path current_path(error_code& ec); // void current_path(path const&); // void current_path(path const&, std::error_code& ec) noexcept; #include "filesystem_include.h" #include <type_traits> #include <cassert> #include "test_macros.h" #include "rapid-cxx-test.h" #include "filesystem_test_helper.h" using namespace fs; TEST_SUITE(filesystem_current_path_path_test_suite) TEST_CASE(current_path_signature_test) { const path p; ((void)p); std::error_code ec; ((void)ec); ASSERT_NOT_NOEXCEPT(current_path()); ASSERT_NOT_NOEXCEPT(current_path(ec)); ASSERT_NOT_NOEXCEPT(current_path(p)); ASSERT_NOEXCEPT(current_path(p, ec)); } TEST_CASE(current_path_test) { std::error_code ec; const path p = current_path(ec); TEST_REQUIRE(!ec); TEST_CHECK(p.is_absolute()); TEST_CHECK(is_directory(p)); const path p2 = current_path(); TEST_CHECK(p2 == p); } TEST_CASE(current_path_after_change_test) { CWDGuard guard; static_test_env static_env; const path new_path = static_env.Dir; current_path(new_path); TEST_CHECK(current_path() == new_path); } TEST_CASE(current_path_is_file_test) { CWDGuard guard; static_test_env static_env; const path p = static_env.File; std::error_code ec; const path old_p = current_path(); current_path(p, ec); TEST_CHECK(ec); TEST_CHECK(old_p == current_path()); } TEST_CASE(set_to_non_absolute_path) { CWDGuard guard; static_test_env static_env; const path base = static_env.Dir; current_path(base); const path p = static_env.Dir2.filename(); std::error_code ec; current_path(p, ec); TEST_CHECK(!ec); const path new_cwd = current_path(); TEST_CHECK(new_cwd == static_env.Dir2); TEST_CHECK(new_cwd.is_absolute()); } TEST_CASE(set_to_empty) { const path p = ""; std::error_code ec; const path old_p = current_path(); current_path(p, ec); TEST_CHECK(ec); TEST_CHECK(old_p == current_path()); } TEST_SUITE_END()
24.727273
80
0.65768
nawrinsu
f5cd687dbc09e270689f0289037e3de1cc24fdbd
4,158
hpp
C++
src/gpu/nvidia/cudnn_binary.hpp
ImproveMyPhone/mkl-dnn
aa13406e8a284495faaddf5396d9090a1d46f1ca
[ "Apache-2.0" ]
11
2020-05-02T12:05:59.000Z
2022-01-17T02:26:44.000Z
src/gpu/nvidia/cudnn_binary.hpp
ImproveMyPhone/mkl-dnn
aa13406e8a284495faaddf5396d9090a1d46f1ca
[ "Apache-2.0" ]
22
2020-06-17T08:27:48.000Z
2022-02-13T23:33:27.000Z
src/gpu/nvidia/cudnn_binary.hpp
ImproveMyPhone/mkl-dnn
aa13406e8a284495faaddf5396d9090a1d46f1ca
[ "Apache-2.0" ]
15
2020-05-20T09:25:04.000Z
2022-03-29T22:16:46.000Z
/******************************************************************************* * Copyright 2020-2021 Intel Corporation * Copyright 2020 Codeplay Software Limited * * 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. *******************************************************************************/ #ifndef GPU_NVIDIA_CUDNN_BINARY_HPP #define GPU_NVIDIA_CUDNN_BINARY_HPP #include "cudnn.h" #include <CL/sycl.hpp> #include "common/binary_pd.hpp" #include "common/c_types_map.hpp" #include "common/primitive.hpp" #include "gpu/nvidia/cudnn_binary_impl.hpp" #include "gpu/nvidia/sycl_cuda_engine.hpp" #include "gpu/nvidia/sycl_cuda_utils.hpp" namespace dnnl { namespace impl { namespace gpu { namespace nvidia { struct cudnn_binary_t : public primitive_t { using primitive_t::primitive_t; struct pd_t : public binary_pd_t { using binary_pd_t::binary_pd_t; DECLARE_COMMON_PD_T("cuda:cudnn:any", cudnn_binary_t); status_t init(engine_t *) { using namespace data_type; bool ok = (set_default_params() == status::success) && check_data_types() && check_no_blocking() && attr()->has_default_values( primitive_attr_t::skip_mask_t::scales) && IMPLICATION(!attr()->scales_.has_default_values(), check_scales_mask()); if (!ok) return status::unimplemented; if (check_for_zero_dims()) return status::success; binary_impl_.reset(new cudnn_binary_impl_t()); return binary_impl_->init(this); } bool check_for_zero_dims() const { return has_zero_dims(src_md(0)->dims, src_md(0)->ndims) || has_zero_dims(src_md(1)->dims, src_md(1)->ndims) || has_zero_dims(dst_md()->dims, dst_md()->ndims); } bool check_scales_mask() const { for (const auto &s : attr()->scales_.scales_) { if (s.second.mask_ != 0) return false; } return true; } bool check_no_blocking() const { // Blocking is not supported by cudnnOpTensor, return false if any // blocks are present return src_md(0)->format_desc.blocking.inner_nblks + src_md(1)->format_desc.blocking.inner_nblks + dst_md()->format_desc.blocking.inner_nblks == 0; } bool check_data_types() const { using namespace data_type; bool inputs_same = src_md(0)->data_type == src_md(1)->data_type; dnnl_data_type_t input_type = src_md(0)->data_type; dnnl_data_type_t output_type = dst_md()->data_type; switch (output_type) { case f32: return inputs_same && (input_type == f32 || input_type == s8 || input_type == f16); case f16: return inputs_same && (input_type == f32 || input_type == f16); case s8: return inputs_same && (input_type == f32 || input_type == s8); default: return false; } return false; } std::shared_ptr<cudnn_binary_impl_base_t> binary_impl_; }; status_t execute(const exec_ctx_t &ctx) const override; private: const pd_t *pd() const { return (const pd_t *)primitive_t::pd().get(); } }; } // namespace nvidia } // namespace gpu } // namespace impl } // namespace dnnl #endif
34.081967
80
0.570948
ImproveMyPhone
f5cdb6e16ae34f8a6beb9cbcd0e528f391b31c2e
3,646
cpp
C++
src/w11/w11ImageText.cpp
qiadev/MacroUniformityRuler
54f155c9374c7d6f3afab7f4594a91189d1a9a46
[ "MIT" ]
null
null
null
src/w11/w11ImageText.cpp
qiadev/MacroUniformityRuler
54f155c9374c7d6f3afab7f4594a91189d1a9a46
[ "MIT" ]
null
null
null
src/w11/w11ImageText.cpp
qiadev/MacroUniformityRuler
54f155c9374c7d6f3afab7f4594a91189d1a9a46
[ "MIT" ]
null
null
null
/* * w11TpText.cpp * w11macro * * Created by Rene Rasmussen on 6/24/08. * */ #include "w11ImageText.h" #include "w11Utilities.h" #if _SUPPORT_FREETYPE_ #include <ft2build.h> #include FT_FREETYPE_H #endif using namespace std; w11ImageText::w11ImageText(std::string fontDirectory, std::string fontName) { fFontDirectory= fontDirectory; fFontName= fontName; fPointSize= 10; } w11ImageText::~w11ImageText() { } void w11ImageText::setFontSize(double ptsize) { fPointSize= ptsize; } void w11ImageText::setFontName(std::string fontName) { fFontName= fontName; } void w11ImageText::setText(std::string t) { fText= t; } void w11ImageText::addTextAt(w11ImageChannelT<w11T8Bits>& image, double xmm, double ymm) { #if _SUPPORT_FREETYPE_ FT_Library library; FT_Face face; FT_GlyphSlot slot; FT_Matrix matrix; /* transformation matrix */ FT_Vector pen; /* untransformed origin */ FT_Error error; string fontFileName= w11Utility::appendPathSegment(fFontDirectory, fFontName); double angle; double degrees= 0.0; int n, num_chars; num_chars= fText.length(); angle= ( degrees / 360 ) * 3.14159 * 2; /* use 25 degrees */ error= FT_Init_FreeType( &library ); /* initialize library */ if (error) { throw "FT_Init_FreeType failed"; } error= FT_New_Face( library, fontFileName.c_str(), 0, &face ); /* create face object */ if (error) { throw "FT_New_Face failed"; } long xdpi= (long) (25.4 / image.dx()); long ydpi= (long) (25.4 / image.dy()); long psize266= (long) (fPointSize * 72); error= FT_Set_Char_Size( face, psize266, 0, xdpi, ydpi ); /* set character size */ if (error) { throw "FT_Set_Char_Size failed"; } slot= face->glyph; /* set up matrix */ matrix.xx = (FT_Fixed)( cos( angle ) * 0x10000L ); matrix.xy = (FT_Fixed)(-sin( angle ) * 0x10000L ); matrix.yx = (FT_Fixed)( sin( angle ) * 0x10000L ); matrix.yy = (FT_Fixed)( cos( angle ) * 0x10000L ); pen.x = 0; pen.y = 0; long xoffset= (long) (xmm / image.dx()); long yoffset= (long) (ymm / image.dy()); // baseline position for ( n = 0; n < num_chars; n++ ) { FT_Set_Transform( face, &matrix, &pen ); //set transformation error= FT_Load_Char( face, fText[n], FT_LOAD_RENDER ); // load glyph image into the slot (erase previous one) if (error) { continue; /* ignore errors */ } /* now, draw to our target surface (convert position) */ draw_bitmap(image, &slot->bitmap, xoffset + slot->bitmap_left, yoffset - slot->bitmap_top); /* increment pen position */ pen.x += slot->advance.x; pen.y += slot->advance.y; } FT_Done_Face(face); FT_Done_FreeType(library); #endif } void w11ImageText::draw_bitmap(w11ImageChannelT<w11T8Bits>& image, FT_Bitmap* bitmap, long x,long y) { #if _SUPPORT_FREETYPE_ FT_Int i, j, p, q; FT_Int x_max = x + bitmap->width; FT_Int y_max = y + bitmap->rows; for ( i = x, p = 0; i < x_max; i++, p++ ) { for ( j = y, q = 0; j < y_max; j++, q++ ) { if ( i < 0 || j < 0 || i >= image.nx() || j >= image.ny() ) { continue; } //image(j, i) |= bitmap->buffer[q * bitmap->width + p]; //image(j, i)= 0; //image(j, i) = 255 - bitmap->buffer[q * bitmap->width + p]; // black text on white //image(j, i) = bitmap->buffer[q * bitmap->width + p]; // white text on black { // here we just paint the text that is pure 255 // if some pixels are anti-aliased (gray) then they will be erased (not rendered) if (bitmap->buffer[q * bitmap->width + p] == 255) { image(j, i) = 0; } } } } #endif }
23.22293
111
0.623697
qiadev
f5cfae8d503123822ef05859dac10f65db05d74b
29,046
cc
C++
lite/tests/math/conv_int8_compute_test.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
1,799
2019-08-19T03:29:38.000Z
2022-03-31T14:30:50.000Z
lite/tests/math/conv_int8_compute_test.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
3,767
2019-08-19T03:36:04.000Z
2022-03-31T14:37:26.000Z
lite/tests/math/conv_int8_compute_test.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
798
2019-08-19T02:28:23.000Z
2022-03-31T08:31:54.000Z
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gflags/gflags.h> #include <gtest/gtest.h> #include "lite/core/context.h" #include "lite/core/profile/timer.h" #include "lite/operators/op_params.h" #include "lite/tests/utils/naive_math_impl.h" #include "lite/tests/utils/tensor_utils.h" #ifdef LITE_WITH_ARM #include "lite/kernels/arm/conv_compute.h" #endif // LITE_WITH_ARM DEFINE_int32(power_mode, 3, "power mode: " "0 for POWER_HIGH;" "1 for POWER_LOW;" "2 for POWER_FULL;" "3 for NO_BIND"); DEFINE_int32(threads, 1, "threads num"); DEFINE_int32(warmup, 0, "warmup times"); DEFINE_int32(repeats, 1, "repeats times"); DEFINE_bool(basic_test, false, "do all tests"); DEFINE_bool(check_result, true, "check the result"); DEFINE_int32(batch, 1, "batch size"); DEFINE_int32(in_channel, 32, "input channel"); DEFINE_int32(in_height, 112, "input height"); DEFINE_int32(in_width, 112, "input width"); DEFINE_int32(out_channel, 32, "output channel"); DEFINE_int32(group, 32, "group"); DEFINE_int32(kernel_h, 3, "kernel height"); DEFINE_int32(kernel_w, 3, "kernel width"); DEFINE_int32(pad_h, 1, "pad height"); DEFINE_int32(pad_w, 1, "pad width"); DEFINE_int32(stride_h, 1, "stride height"); DEFINE_int32(stride_w, 1, "stride width"); DEFINE_int32(dila_h, 1, "dilation height"); DEFINE_int32(dila_w, 1, "dilation width"); DEFINE_int32(flag_act, 1, "do act"); DEFINE_bool(flag_bias, true, "with bias"); DEFINE_double(clipped_coef, 1.0, "clipped relu coef"); DEFINE_double(leakey_relu_alpha, 2.22, "leakey relu alpha"); typedef paddle::lite::DDim DDim; typedef paddle::lite::Tensor Tensor; typedef paddle::lite::operators::ConvParam ConvParam; typedef paddle::lite::operators::ActivationParam ActivationParam; using paddle::lite::profile::Timer; DDim compute_out_dim(const DDim& dim_in, const paddle::lite::operators::ConvParam& param) { auto paddings = *param.paddings; auto dilations = *param.dilations; DDim dim_out = dim_in; dim_out[1] = param.filter->dims()[0]; auto kernel_h = param.filter->dims()[2]; auto kernel_w = param.filter->dims()[3]; auto h = dim_in[2]; auto w = dim_in[3]; int dila_h = dilations[0]; int dila_w = dilations[1]; int stride_h = param.strides[0]; int stride_w = param.strides[1]; auto kernel_exten = dila_h * (kernel_h - 1) + 1; auto hout = (h + paddings[0] + paddings[1] - kernel_exten) / stride_h + 1; kernel_exten = dila_w * (kernel_w - 1) + 1; auto wout = (w + paddings[2] + paddings[3] - kernel_exten) / stride_w + 1; dim_out[2] = hout; dim_out[3] = wout; return dim_out; } template <paddle::lite::PrecisionType ptype> void get_conv_param(const DDim& dim_w, int g, const std::vector<int>& strides, const std::vector<int>& pads, const std::vector<int>& dila, bool flag_bias, bool flag_relu, ConvParam* param) { param->x = new Tensor; param->x->set_precision(PRECISION(kInt8)); param->filter = new Tensor; param->filter->Resize(dim_w); param->filter->set_precision(PRECISION(kInt8)); if (flag_bias) { param->bias = new Tensor; param->bias->Resize({dim_w[0]}); param->bias->set_precision(PRECISION(kFloat)); } param->strides = strides; param->paddings = std::make_shared<std::vector<int>>(pads); param->dilations = std::make_shared<std::vector<int>>(dila); param->fuse_relu = flag_relu; param->groups = g; param->output = new Tensor; param->output->set_precision(ptype); } void release_param(ConvParam* param) { delete param->x; delete param->filter; delete param->output; delete param->bias; } #ifdef LITE_WITH_ARM #include "lite/backends/arm/math/funcs.h" void test_conv_int8(const DDim& dim_in, const DDim& weight_dim, int group, const std::vector<int>& strides, const std::vector<int>& pads, const std::vector<int>& dilas, bool flag_bias, int flag_act, const std::vector<int>& thread_num, const std::vector<int>& power_mode, const float six = 6.f, const float alpha = 1.f) { paddle::lite::DeviceInfo::Init(); ConvParam param_int8_out; ConvParam param_fp32_out; get_conv_param<PRECISION(kInt8)>(weight_dim, group, strides, pads, dilas, flag_bias, flag_act > 0, &param_int8_out); get_conv_param<PRECISION(kFloat)>(weight_dim, group, strides, pads, dilas, flag_bias, flag_act > 0, &param_fp32_out); Tensor weight_fp32; Tensor bias_fp32; weight_fp32.Resize(weight_dim); paddle::lite::fill_tensor_rand(*param_int8_out.filter, -127, 127); param_fp32_out.filter->CopyDataFrom(*param_int8_out.filter); if (flag_bias) { auto dim_b = param_int8_out.bias->dims(); bias_fp32.Resize(dim_b); paddle::lite::fill_tensor_rand(*param_int8_out.bias, -1.f, 1.f); param_fp32_out.bias->CopyDataFrom(*param_int8_out.bias); bias_fp32.CopyDataFrom(*param_int8_out.bias); } if (flag_act > 0) { ActivationParam act_param; act_param.has_active = true; act_param.active_type = (paddle::lite_api::ActivationType) flag_act; // 1-relu, 2-relu6, 4-leakyrelu if (flag_act == 1) { param_fp32_out.fuse_relu = true; param_int8_out.fuse_relu = true; } else if (flag_act == 2) { act_param.Relu_clipped_coef = six; } else if (flag_act == 4) { act_param.Leaky_relu_alpha = alpha; } param_fp32_out.activation_param = act_param; param_int8_out.activation_param = act_param; } std::vector<float> scale_in{1.f / 127}; std::vector<float> scale_out(1, weight_dim.count(1, 4) / 127.f); if (flag_act == 2) { scale_out[0] = six / 127.f; } else if (flag_act == 4) { if (std::abs(alpha) > 1) { scale_out[0] *= std::abs(alpha); } } std::vector<float> scale_w(weight_dim[0], 1.f / 127); param_int8_out.input_scale = scale_in[0]; param_int8_out.output_scale = scale_out[0]; param_int8_out.weight_scale = scale_w; param_fp32_out.input_scale = scale_in[0]; param_fp32_out.output_scale = scale_out[0]; param_fp32_out.weight_scale = scale_w; auto wptr_fp32 = weight_fp32.mutable_data<float>(); auto bptr_fp32 = flag_bias ? bias_fp32.data<float>() : nullptr; paddle::lite::arm::math::int8_to_fp32(param_int8_out.filter->data<int8_t>(), wptr_fp32, scale_w.data(), weight_dim[0], 1, weight_dim.count(1, 4)); for (auto& cls : power_mode) { for (auto& th : thread_num) { std::unique_ptr<paddle::lite::KernelContext> ctx1( new paddle::lite::KernelContext); std::unique_ptr<paddle::lite::KernelContext> ctx2( new paddle::lite::KernelContext); auto& ctx_tmp1 = ctx1->As<paddle::lite::ARMContext>(); ctx_tmp1.SetRunMode(static_cast<paddle::lite_api::PowerMode>(cls), th); auto& ctx_tmp2 = ctx2->As<paddle::lite::ARMContext>(); ctx_tmp2.SetRunMode(static_cast<paddle::lite_api::PowerMode>(cls), th); paddle::lite::kernels::arm::ConvCompute<PRECISION(kInt8), PRECISION(kInt8)> conv_int8_int8; paddle::lite::kernels::arm::ConvCompute<PRECISION(kInt8), PRECISION(kFloat)> conv_int8_fp32; conv_int8_int8.SetContext(std::move(ctx1)); conv_int8_fp32.SetContext(std::move(ctx2)); /// set param and context param_int8_out.x->Resize(dim_in); DDim out_tmp_dims = compute_out_dim(dim_in, param_int8_out); if (out_tmp_dims[2] < 1 || out_tmp_dims[3] < 1) { return; } param_fp32_out.x->Resize(dim_in); param_int8_out.output->Resize(out_tmp_dims); param_fp32_out.output->Resize(out_tmp_dims); conv_int8_int8.SetParam(param_int8_out); conv_int8_fp32.SetParam(param_fp32_out); /// prepare for run conv_int8_int8.PrepareForRun(); conv_int8_fp32.PrepareForRun(); CHECK_EQ(weight_dim[1] * group, dim_in[1]) << "input channel must equal to weights channel"; DDim dim_out = compute_out_dim(dim_in, param_int8_out); if (dim_out[2] < 1 || dim_out[3] < 1) { continue; } delete param_fp32_out.output; param_fp32_out.output = new Tensor; param_fp32_out.output->set_precision(PRECISION(kFloat)); delete param_int8_out.output; param_int8_out.output = new Tensor; param_int8_out.output->set_precision(PRECISION(kInt8)); param_int8_out.x->Resize(dim_in); param_int8_out.output->Resize(dim_out); param_fp32_out.x->Resize(dim_in); param_fp32_out.output->Resize(dim_out); Tensor tin_fp32; tin_fp32.Resize(dim_in); tin_fp32.set_precision(PRECISION(kFloat)); Tensor tout_basic_fp32; Tensor tout_basic_int8; paddle::lite::fill_tensor_rand(*param_int8_out.x, -127, 127); param_fp32_out.x->CopyDataFrom(*param_int8_out.x); auto din_fp32 = tin_fp32.mutable_data<float>(); paddle::lite::arm::math::int8_to_fp32(param_int8_out.x->data<int8_t>(), din_fp32, scale_in.data(), 1, 1, dim_in.production()); if (FLAGS_check_result) { tout_basic_fp32.set_precision(PRECISION(kFloat)); tout_basic_fp32.Resize(dim_out); tout_basic_int8.set_precision(PRECISION(kInt8)); tout_basic_int8.Resize(dim_out); fill_tensor_const(tout_basic_fp32, 0.f); auto dout_basic_fp32 = tout_basic_fp32.mutable_data<float>(); auto dout_basic_int8 = tout_basic_int8.mutable_data<int8_t>(); conv_basic<float, float>(din_fp32, dout_basic_fp32, dim_in[0], dim_out[1], dim_out[2], dim_out[3], dim_in[1], dim_in[2], dim_in[3], wptr_fp32, bptr_fp32, group, weight_dim[3], weight_dim[2], strides[1], strides[0], dilas[1], dilas[0], pads[2], pads[0], flag_bias, flag_act, six, alpha); paddle::lite::arm::math::fp32_to_int8(dout_basic_fp32, dout_basic_int8, scale_out.data(), 1, 1, dim_out.production()); } double gops = 2.0 * dim_out.production() * dim_in[1] * weight_dim[2] * weight_dim[3] / group; /// warm up for (int i = 0; i < FLAGS_warmup; ++i) { conv_int8_fp32.Launch(); } /// compute fp32 output Timer t0; for (int i = 0; i < FLAGS_repeats; ++i) { t0.Start(); conv_int8_fp32.Launch(); t0.Stop(); } LOG(INFO) << "int8 conv, fp32 output: output shape" << dim_out << ",running time, avg: " << t0.LapTimes().Avg() << " ms" << ", min time: " << t0.LapTimes().Min() << " ms" << ", total GOPS: " << 1e-9 * gops << " GOPS, avg GOPs: " << 1e-6 * gops / t0.LapTimes().Avg() << " GOPs, max GOPs: " << 1e-6 * gops / t0.LapTimes().Min(); // compute int8 output t0.Reset(); for (int i = 0; i < FLAGS_repeats; ++i) { t0.Start(); conv_int8_int8.Launch(); t0.Stop(); } LOG(INFO) << "int8 conv, int8 output: output shape" << dim_out << ",running time, avg: " << t0.LapTimes().Avg() << ", min time: " << t0.LapTimes().Min() << ", total GOPS: " << 1e-9 * gops << " GOPS, avg GOPs: " << 1e-6 * gops / t0.LapTimes().Avg() << " GOPs, max GOPs: " << 1e-6 * gops / t0.LapTimes().Min(); /// compare result fp32 output if (FLAGS_check_result) { double max_ratio = 0; double max_diff = 0; tensor_cmp_host( tout_basic_fp32, *param_fp32_out.output, max_ratio, max_diff); LOG(INFO) << "FP32 compare result, max diff: " << max_diff << ", max ratio: " << max_ratio; if (std::abs(max_ratio) > 1e-5f) { if (max_diff > 5e-5f) { LOG(WARNING) << "basic result"; print_tensor(tout_basic_fp32); LOG(WARNING) << "lite result"; print_tensor(*param_fp32_out.output); Tensor tdiff; tdiff.Resize(tout_basic_fp32.dims()); tdiff.set_precision(PRECISION(kFloat)); tensor_diff(tout_basic_fp32, *param_fp32_out.output, tdiff); print_tensor(tdiff); release_param(&param_int8_out); release_param(&param_fp32_out); LOG(FATAL) << "test int8 conv, fp32 out: input: " << dim_in << ", output: " << dim_out << ", weight dim: " << weight_dim << ", pad: " << pads[0] << ", " << pads[1] << ", " << pads[2] << ", " << pads[3] << ", stride: " << strides[0] << ", " << strides[1] << ", dila_: " << dilas[0] << ", " << dilas[1] << ", group: " << group << ", bias: " << (flag_bias ? "true" : "false") << ", act: " << flag_act << ", threads: " << th << ", power_mode: " << cls << " failed!!\n"; } } } // compare result int8 output if (FLAGS_check_result) { double max_ratio = 0; double max_diff = 0; // ! int8 tensor_cmp_host( tout_basic_int8, *param_int8_out.output, max_ratio, max_diff); LOG(INFO) << "int8 compare result, max diff: " << max_diff << ", max ratio: " << max_ratio; if (fabs(max_diff) > 0) { Tensor tdiff; tdiff.Resize(tout_basic_int8.dims()); tdiff.set_precision(PRECISION(kInt8)); tensor_diff(tout_basic_int8, *param_int8_out.output, tdiff); auto ptr = tdiff.data<int8_t>(); auto ptr_basic_fp32 = tout_basic_fp32.data<float>(); float count = 0; bool check = true; for (int i = 0; i < tdiff.numel(); ++i) { if (abs(ptr[i]) > 1) { check = false; LOG(ERROR) << "basic float data: " << ptr_basic_fp32[i] << ", after scale: " << ptr_basic_fp32[i] / scale_out[0]; break; } if (ptr[i] != 0) { LOG(ERROR) << "basic float data: " << ptr_basic_fp32[i] << ", after scale: " << ptr_basic_fp32[i] / scale_out[0]; count += 1; } } check = check && count < std::max(10, static_cast<int>(0.01 * tdiff.numel())); if (!check) { LOG(WARNING) << "int8 basic result"; print_tensor(tout_basic_int8); LOG(WARNING) << "int8 lite result"; print_tensor(*param_int8_out.output); LOG(WARNING) << "int8 diff tensor"; print_tensor(tdiff); release_param(&param_int8_out); release_param(&param_fp32_out); LOG(FATAL) << "test int8 conv, int8 out: input: " << dim_in << ", output: " << dim_out << ", weight dim: " << weight_dim << ", pad: " << pads[0] << ", " << pads[1] << ", " << pads[2] << ", " << pads[3] << ", stride: " << strides[0] << ", " << strides[1] << ", dila_: " << dilas[0] << ", " << dilas[1] << ", bias: " << (flag_bias ? "true" : "false") << ", act: " << flag_act << ", threads: " << th << ", power_mode: " << cls << " failed!!\n"; } } } LOG(INFO) << "test int8 conv: input: " << dim_in << ", output: " << dim_out << ", weight dim: " << weight_dim << ", pad: " << pads[0] << ", " << pads[1] << ", " << pads[2] << ", " << pads[3] << ", stride: " << strides[0] << ", " << strides[1] << ", dila_: " << dilas[0] << ", " << dilas[1] << ", bias: " << (flag_bias ? "true" : "false") << ", act: " << flag_act << ", threads: " << th << ", power_mode: " << cls << " successed!!\n"; } } release_param(&param_int8_out); release_param(&param_fp32_out); } #else void test_conv_int8(const DDim& dims_in, const DDim& weight_dim, int group, const std::vector<int>& strides, const std::vector<int>& pads, const std::vector<int>& dilas, bool flag_bias, int flag_act, const std::vector<int>& thread_num, const std::vector<int>& power_mode, float six = 6.f, float alpha = 1.f) {} #endif // LITE_WITH_ARM #if 1 /// 3x3dw TEST(TestConv3x3DWInt8, test_conv3x3_depthwise) { if (FLAGS_basic_test) { for (auto& stride : {1, 2}) { for (auto& pad : {0, 1}) { for (auto& flag_bias : {false, true}) { for (auto& flag_act : {0, 1, 2, 4}) { for (auto& c : {1, 3, 5, 8, 16, 32}) { DDim weights_dim({c, 1, 3, 3}); for (auto& batch : {1, 2}) { for (auto& h : {1, 3, 15, 33}) { DDim dims({batch, c, h, h}); test_conv_int8(dims, weights_dim, c, {stride, stride}, {pad, pad, pad, pad}, {1, 1}, flag_bias, flag_act, {FLAGS_threads}, {FLAGS_power_mode}, FLAGS_clipped_coef, FLAGS_leakey_relu_alpha); } } } } } } } } } #endif /// 3x3dw #if 1 /// 5x5dw TEST(TestConv5x5DWInt8, test_conv5x5_depthwise) { if (FLAGS_basic_test) { for (auto& stride : {1, 2}) { for (auto& pad : {0, 1, 2, 3, 4}) { for (auto& flag_bias : {false, true}) { for (auto& flag_act : {0, 1, 2, 4}) { for (auto& c : {1, 5, 15, 33}) { DDim weights_dim({c, 1, 5, 5}); for (auto& batch : {1, 2}) { for (auto& h : {1, 3, 15, 33, 112, 224}) { DDim dims({batch, c, h, h}); test_conv_int8(dims, weights_dim, c, {stride, stride}, {pad, pad, pad, pad}, {1, 1}, flag_bias, flag_act, {1, 4}, {FLAGS_power_mode}, FLAGS_clipped_coef, FLAGS_leakey_relu_alpha); } } } } } } } } } #endif /// 5x5dw #if 1 /// conv1x1s1 TEST(TestConv1x1s1Int8, test_conv1x1s1) { if (FLAGS_basic_test) { for (auto& cin : {1, 3, 8, 33}) { for (auto& cout : {1, 5, 17}) { for (auto& g : {1, 2}) { for (auto& flag_bias : {false, true}) { for (auto& flag_act : {0, 1, 2, 4}) { if (cin % g != 0 || cout % g != 0) { continue; } DDim weights_dim({cout, cin / g, 1, 1}); for (auto& batch : {1, 2}) { for (auto& h : {1, 9, 16, 33}) { DDim dims({batch, cin, h, h}); test_conv_int8(dims, weights_dim, g, {1, 1}, {0, 0, 0, 0}, {1, 1}, flag_bias, flag_act, {4}, {FLAGS_power_mode}, FLAGS_clipped_coef, FLAGS_leakey_relu_alpha); } } } } } } } } } #endif /// conv1x1s1 #if 1 /// conv3x3s1 TEST(TestConv3x3s1Int8, test_conv_3x3s1) { if (FLAGS_basic_test) { for (auto& cin : {1, 3, 8, 33}) { for (auto& cout : {1, 5, 33}) { for (auto& pad_top : {1, 2}) { for (auto& pad_bottom : {1, 2}) { for (auto& pad_left : {1, 2}) { for (auto& pad_right : {1, 2}) { for (auto& flag_bias : {false, true}) { for (auto& flag_act : {0, 1}) { DDim weights_dim({cout, cin, 3, 3}); for (auto& batch : {1, 2}) { for (auto& h : {1, 7, 17, 33}) { DDim dims({batch, cin, h, h}); if (cin == 1 && cout == 1) { continue; } test_conv_int8( dims, weights_dim, 1, {1, 1}, {pad_top, pad_bottom, pad_left, pad_right}, {1, 1}, flag_bias, flag_act, {4}, {FLAGS_power_mode}, FLAGS_clipped_coef, FLAGS_leakey_relu_alpha); } } } } } } } } } } } } #endif /// conv3x3s1 #if 1 /// conv3x3s2 TEST(TestConv3x3s2Int8, test_conv_3x3s2) { if (FLAGS_basic_test) { for (auto& cin : {1, 3, 31}) { for (auto& cout : {1, 5, 33}) { for (auto& pad_top : {1, 2}) { for (auto& pad_bottom : {1, 2}) { for (auto& pad_left : {1, 2}) { for (auto& pad_right : {1, 2}) { for (auto& flag_bias : {false, true}) { for (auto& flag_act : {0, 1, 2, 4}) { DDim weights_dim({cout, cin, 3, 3}); for (auto& batch : {1, 2}) { for (auto& h : {1, 7, 19, 33}) { DDim dims({batch, cin, h, h}); test_conv_int8( dims, weights_dim, 1, {2, 2}, {pad_top, pad_bottom, pad_left, pad_right}, {1, 1}, flag_bias, flag_act, {4}, {FLAGS_power_mode}, FLAGS_clipped_coef, FLAGS_leakey_relu_alpha); } } } } } } } } } } } } #endif /// conv3x3s2 #if 1 /// random param conv TEST(TestConvRandInt8, test_conv_rand) { if (FLAGS_basic_test) { for (auto& cin : {1, 17}) { for (auto& cout : {1, 8, 17}) { for (auto& g : {1, 2}) { for (auto& kw : {1, 2, 3}) { for (auto& kh : {1, 2, 3}) { for (auto& stride : {1, 2}) { for (auto& pad_top : {0, 1, 2}) { for (auto& pad_bottom : {0, 1, 2}) { for (auto& pad_left : {0, 1, 2}) { for (auto& pad_right : {0, 1, 2}) { for (auto& dila : {1, 2}) { for (auto& flag_bias : {false, true}) { for (auto& flag_act : {0, 1, 2, 4}) { if (cin % g != 0 || cout % g != 0) { break; } DDim weights_dim({cout, cin / g, kh, kw}); for (auto& batch : {1, 2}) { for (auto& h : {1, 3, 5, 19}) { DDim dims({batch, cin, h, h}); test_conv_int8(dims, weights_dim, g, {stride, stride}, {pad_top, pad_bottom, pad_left, pad_right}, {dila, dila}, flag_bias, flag_act, {4}, {FLAGS_power_mode}, FLAGS_clipped_coef, FLAGS_leakey_relu_alpha); } } } } } } } } } } } } } } } } } #endif /// random param conv #if 1 /// custom TEST(TestConvCustomInt8, test_conv_custom_size) { CHECK_EQ(FLAGS_in_channel % FLAGS_group, 0) << "input channel must be divided by group"; CHECK_EQ(FLAGS_out_channel % FLAGS_group, 0) << "num_output must be divided by group"; test_conv_int8( {DDim({FLAGS_batch, FLAGS_in_channel, FLAGS_in_height, FLAGS_in_width})}, DDim({FLAGS_out_channel, FLAGS_in_channel / FLAGS_group, FLAGS_kernel_h, FLAGS_kernel_w}), FLAGS_group, {FLAGS_stride_h, FLAGS_stride_w}, {FLAGS_pad_h, FLAGS_pad_h, FLAGS_pad_w, FLAGS_pad_w}, {FLAGS_dila_h, FLAGS_dila_w}, FLAGS_flag_bias, FLAGS_flag_act, {FLAGS_threads}, {FLAGS_power_mode}, FLAGS_clipped_coef, FLAGS_leakey_relu_alpha); } #endif // custom
38.369881
80
0.453212
wanglei91
f5d27241219fc6ee16ed5745830be9cf171243e0
2,948
cpp
C++
src/logging.cpp
ROCm-Developer-Tools/rocr_debug_agent
4b0589c215c0e8d70a9a4921d0ac6919dd295550
[ "Linux-OpenIB" ]
8
2019-04-21T14:04:26.000Z
2021-08-31T02:51:41.000Z
src/logging.cpp
ROCm-Developer-Tools/rocr_debug_agent
4b0589c215c0e8d70a9a4921d0ac6919dd295550
[ "Linux-OpenIB" ]
5
2019-02-10T09:13:08.000Z
2021-02-18T23:21:45.000Z
src/logging.cpp
ROCm-Developer-Tools/rocr_debug_agent
4b0589c215c0e8d70a9a4921d0ac6919dd295550
[ "Linux-OpenIB" ]
6
2019-08-26T02:47:33.000Z
2021-02-26T20:41:03.000Z
/* The University of Illinois/NCSA Open Source License (NCSA) Copyright (c) 2020, Advanced Micro Devices, Inc. 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 with 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: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimers. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimers in the documentation and/or other materials provided with the distribution. - Neither the names of Advanced Micro Devices, Inc, nor the names of its contributors may be used to endorse or promote products derived from this Software without specific prior written permission. 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 CONTRIBUTORS 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 WITH THE SOFTWARE. */ #include "logging.h" #include <amd-dbgapi.h> #include <cstdio> #include <stdarg.h> #include <string> namespace amd::debug_agent { log_level_t log_level = log_level_t::warning; std::ofstream agent_out; namespace detail { void log (log_level_t level, const char *format, ...) { va_list va; agent_out << "rocm-debug-agent: "; if (level == log_level_t::error) agent_out << "error: "; else if (level == log_level_t::warning) agent_out << "warning: "; va_start (va, format); size_t size = vsnprintf (NULL, 0, format, va); va_end (va); va_start (va, format); std::string str (size, '\0'); vsprintf (&str[0], format, va); va_end (va); agent_out << str << std::endl; } } /* namespace detail */ void set_log_level (log_level_t level) { log_level = level; switch (level) { case log_level_t::none: amd_dbgapi_set_log_level (AMD_DBGAPI_LOG_LEVEL_NONE); break; case log_level_t::info: amd_dbgapi_set_log_level (AMD_DBGAPI_LOG_LEVEL_INFO); break; case log_level_t::warning: amd_dbgapi_set_log_level (AMD_DBGAPI_LOG_LEVEL_WARNING); break; case log_level_t::error: amd_dbgapi_set_log_level (AMD_DBGAPI_LOG_LEVEL_FATAL_ERROR); break; } } } /* namespace amd::debug_agent */
30.391753
79
0.722863
ROCm-Developer-Tools
f5d2c5cfbe7d7aac8fd3e113e012ba3fe6da3508
1,685
hpp
C++
include/motherboard.hpp
Stellaris-code/SpaceInvadersEmu
e8cd69ed3c594ffb83cf4471db9f1c44e8f640e4
[ "MIT" ]
7
2016-02-16T13:24:00.000Z
2018-09-24T09:02:38.000Z
include/motherboard.hpp
Stellaris-code/SpaceInvadersEmu
e8cd69ed3c594ffb83cf4471db9f1c44e8f640e4
[ "MIT" ]
null
null
null
include/motherboard.hpp
Stellaris-code/SpaceInvadersEmu
e8cd69ed3c594ffb83cf4471db9f1c44e8f640e4
[ "MIT" ]
2
2016-02-16T13:06:23.000Z
2018-10-15T04:27:42.000Z
/* include/motherboard.hpp Motherboard - Yann BOUCHER (yann) 11/02/2016 ** ** ** DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE ** Version 2, December 2004 ** ** Copyright (C) 2004 Sam Hocevar <sam@hocevar.net> ** ** Everyone is permitted to copy and distribute verbatim or modified ** copies of this license document, and changing it is allowed as long ** as the name is changed. ** ** DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE ** TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION ** ** 0. You just DO WHAT THE FUCK YOU WANT TO. */ #ifndef MOTHERBOARD_HPP #define MOTHERBOARD_HPP #include "common.hpp" #include "cpu.hpp" #include "cpustate.hpp" #include "utility.hpp" #include "noncopyable.hpp" class Motherboard : private NonCopyable { public: Motherboard(); virtual ~Motherboard() = default; protected: virtual void registerIOPorts() {} public: virtual void start() {} virtual void reset() {} public: void pause() { m_cpu.pause(); } void resume() { m_cpu.resume(); } void setPaused(bool val) { if (val) { pause(); } else { resume(); } } bool paused() const { return m_cpu.paused(); } i8080::State& cpuState() { return m_cpu.m_state; } double ips() const { return m_cpu.ips(); } virtual unsigned long clockSpeed() const { return 2000000; } protected: i8080::CPU m_cpu; }; #endif // MOTHERBOARD_HPP
21.883117
72
0.559644
Stellaris-code
f5d2d4f2093309fce603cb2f0ae472075f5a0be4
7,066
cpp
C++
test/cali-flush-perftest.cpp
rblake-llnl/Caliper
f958f45f5cf2dccc4529f2b27d8628981a60b012
[ "BSD-3-Clause" ]
null
null
null
test/cali-flush-perftest.cpp
rblake-llnl/Caliper
f958f45f5cf2dccc4529f2b27d8628981a60b012
[ "BSD-3-Clause" ]
null
null
null
test/cali-flush-perftest.cpp
rblake-llnl/Caliper
f958f45f5cf2dccc4529f2b27d8628981a60b012
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2018, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // // This file is part of Caliper. // Written by David Boehme, boehme3@llnl.gov. // LLNL-CODE-678900 // All rights reserved. // // For details, see https://github.com/scalability-llnl/Caliper. // Please also see the LICENSE file for our additional BSD notice. // // 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 disclaimer below. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the disclaimer (as // noted below) in the documentation and/or other materials // provided with the distribution. // // * Neither the name of the LLNS/LLNL 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 LAWRENCE // LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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. // -- cali-flush-perftest // // Runs a performance test for caliper flush operations. // // The benchmark runs an annotated loop to fill up trace buffers or // aggregation buffers, then triggers a flush. // // The benchmark is multi-threaded: the loop is statically divided // between threads using OpenMP. #include <caliper/common/Attribute.h> #include <caliper/common/RuntimeConfig.h> #include <caliper/Caliper.h> #include <caliper/cali.h> #include <caliper/tools-util/Args.h> #include <chrono> #include <iostream> #ifdef _OPENMP #include <omp.h> #endif struct Config { int iter; int nxtra; bool write; std::vector<cali::Attribute> xtra_attrs; int channels; }; void run(const Config& cfg) { #pragma omp parallel { CALI_CXX_MARK_LOOP_BEGIN(testloop, "testloop"); #pragma omp for schedule(static) for (int i = 0; i < cfg.iter; ++i) { CALI_CXX_MARK_LOOP_ITERATION(testloop, i); cali::Caliper c; for (int x = 0, div = 10; x < cfg.nxtra; ++x, div *= 10) c.begin(cfg.xtra_attrs[x], cali::Variant(i/div)); for (int x = 0; x < cfg.nxtra; ++x) c.end(cfg.xtra_attrs[cfg.nxtra-(1+x)]); } CALI_CXX_MARK_LOOP_END(testloop); } } int main(int argc, char* argv[]) { cali_config_preset("CALI_CALIPER_ATTRIBUTE_PROPERTIES", "annotation=nested:process_scope"); cali_config_set("CALI_CHANNEL_FLUSH_ON_EXIT", "false"); const util::Args::Table option_table[] = { { "iterations", "iterations", 'i', true, "Number of loop iterations", "ITERATIONS" }, { "xtra", "xtra", 'x', true, "Number of extra attributes", "XTRA" }, { "channels", "channels", 'c', true, "Number of replicated channels", "CHANNELS" }, { "write", "write", 'w', false, "Write to output service in addition to flush", nullptr }, { "help", "help", 'h', false, "Print help", nullptr }, util::Args::Table::Terminator }; // --- Initialization util::Args args(option_table); int lastarg = args.parse(argc, argv); if (lastarg < argc) { std::cerr << "cali-flush-perftest: unknown option: " << argv[lastarg] << '\n' << "Available options: "; args.print_available_options(std::cerr); return 1; } if (args.is_set("help")) { args.print_available_options(std::cerr); return 2; } int threads = 1; #ifdef _OPENMP threads = omp_get_max_threads(); #endif Config cfg; cfg.iter = std::stoi(args.get("iterations", "100000")); cfg.nxtra = std::stoi(args.get("xtra", "2")); cfg.channels = std::stoi(args.get("channels", "1")); cfg.write = args.is_set("write"); cali_set_global_int_byname("flush-perftest.iterations", cfg.iter); cali_set_global_int_byname("flush-perftest.nxtra", cfg.nxtra); cali_set_global_int_byname("flush-perftest.channels", cfg.channels); cali_set_global_int_byname("flush-perftest.threads", threads); // --- print info std::cout << "cali-flush-perftest:" << "\n Channels: " << cfg.channels << "\n Iterations: " << cfg.iter << "\n Xtra: " << cfg.nxtra #ifdef _OPENMP << "\n Threads: " << threads #endif << std::endl; // --- set up the xtra attributes cali::Caliper c; for (int i = 0, div = 10; i < cfg.nxtra; ++i, div *= 10) cfg.xtra_attrs.push_back(c.create_attribute(std::string("x.")+std::to_string(div), CALI_TYPE_INT, CALI_ATTR_SCOPE_THREAD | CALI_ATTR_ASVALUE)); // --- set up channels std::vector<cali::Channel*> channels; channels.push_back(c.get_channel(0)); for (int i = 1; i < cfg.channels; ++i) { std::string s("chn."); s.append(std::to_string(i)); channels.push_back(c.create_channel(s.c_str(), cali::RuntimeConfig::get_default_config())); } // --- Run the loop to fill buffers CALI_MARK_BEGIN("fill"); run(cfg); CALI_MARK_END("fill"); // --- Timed flush int snapshots = 3 + cfg.channels * (2*threads + (cfg.iter * (2 + 2*cfg.nxtra))); CALI_MARK_BEGIN("flush"); auto stime = std::chrono::system_clock::now(); for (cali::Channel* chn : channels) if (cfg.write) c.flush_and_write(chn, nullptr); else c.flush(chn, nullptr, [](cali::CaliperMetadataAccessInterface&, const std::vector<cali::Entry>&) { }); auto etime = std::chrono::system_clock::now(); CALI_MARK_END("flush"); auto msec = std::chrono::duration_cast<std::chrono::milliseconds>(etime-stime).count(); std::cout << " " << snapshots << " snapshots flushed in " << msec/1000.0 << " sec, " << 1000.0*msec/snapshots << " usec/snapshot" << std::endl; }
31.404444
114
0.62171
rblake-llnl
f5d884561e3bdc244ba6792a2cb8a704d1ad2a98
424
cpp
C++
main.cpp
MOC99/riot-launcher
84e3935912e2115c2541eab4e70ca1ae7fe32724
[ "MIT" ]
null
null
null
main.cpp
MOC99/riot-launcher
84e3935912e2115c2541eab4e70ca1ae7fe32724
[ "MIT" ]
null
null
null
main.cpp
MOC99/riot-launcher
84e3935912e2115c2541eab4e70ca1ae7fe32724
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include <QApplication> #include <QFontDatabase> int main(int argc, char *argv[]) { QApplication a(argc, argv); int fontId = QFontDatabase::addApplicationFont(":/font/resource/font.otf"); if (fontId >= 0) { auto f = QFontDatabase::applicationFontFamilies(fontId).at(0); QFont font(f); a.setFont(font); } MainWindow w; w.show(); return a.exec(); }
24.941176
79
0.629717
MOC99
f5d98ecf736418959550346542b44a1caa132ca8
3,390
cpp
C++
Test/MasterPubKeyTest.cpp
hejianhui/Elastos.ELA.SPV.Cpp
6c3337d091e4cfa9f6dbabaa18526565ccee4e0b
[ "MIT" ]
null
null
null
Test/MasterPubKeyTest.cpp
hejianhui/Elastos.ELA.SPV.Cpp
6c3337d091e4cfa9f6dbabaa18526565ccee4e0b
[ "MIT" ]
null
null
null
Test/MasterPubKeyTest.cpp
hejianhui/Elastos.ELA.SPV.Cpp
6c3337d091e4cfa9f6dbabaa18526565ccee4e0b
[ "MIT" ]
1
2018-08-02T07:58:30.000Z
2018-08-02T07:58:30.000Z
// Copyright (c) 2012-2018 The Elastos Open Source Project // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #define CATCH_CONFIG_MAIN #include <BRBIP32Sequence.h> #include "BRBIP39WordsEn.h" #include "catch.hpp" #include "MasterPubKey.h" using namespace Elastos::ElaWallet; TEST_CASE("MasterPubKey test", "[MasterPubKey]") { SECTION("Default constructor") { MasterPubKey masterPubKey; REQUIRE(masterPubKey.getRaw() != nullptr); } SECTION("Create width phrase") { std::string phrase = "a test seed ha"; MasterPubKey masterPubKey(phrase); REQUIRE(masterPubKey.getRaw() != nullptr); } } TEST_CASE("MasterPubKey method test", "[MasterPubKey]") { SECTION("getPubKey method test") { std::string phrase = "a test seed ha"; MasterPubKey masterPubKey(phrase); CMBlock pubkeyBytes = masterPubKey.getPubKey(); REQUIRE(pubkeyBytes.GetSize() > 0); } SECTION("serialize method test") { std::string phrase = "a test seed ha"; MasterPubKey masterPubKey(phrase); const CMBlock bytes = masterPubKey.serialize(); REQUIRE(bytes.GetSize() > 0); MasterPubKey masterPubKey1; masterPubKey1.deserialize(bytes); BRMasterPubKey *key1 = masterPubKey.getRaw(); BRMasterPubKey *key2 = masterPubKey1.getRaw(); REQUIRE(key1->fingerPrint == key2->fingerPrint); int r = UInt256Eq(&key1->chainCode, &key1->chainCode); REQUIRE(r == 1); for (int i = 0; i < sizeof(key1->pubKey); i++) { REQUIRE(key1->pubKey[i] == key2->pubKey[i]); } } SECTION("getPubKeyAsKey method test") { std::string phrase = "a test seed ha"; MasterPubKey masterPubKey(phrase); BRKey *brkey = new BRKey(); brkey->compressed = 0; brkey->secret = UINT256_ZERO; boost::shared_ptr<Key> key = boost::shared_ptr<Key>(new Key(brkey)); memset(key->getRaw()->pubKey, 0, sizeof(key->getRaw()->pubKey)); char *pubkey1 = (char *) key->getRaw()->pubKey; key = masterPubKey.getPubKeyAsKey(); REQUIRE(key.get() != nullptr); REQUIRE(key->getRaw()->compressed != 0); for (int i = 0; i < sizeof(key->getRaw()->secret); i++) { REQUIRE(key->getRaw()->secret.u8[i] == 0); } char *pubkey2 = (char *) key->getRaw()->pubKey; REQUIRE(std::string(pubkey1) != std::string(pubkey2)); } } TEST_CASE("MasterPubKey static method test", "[MasterPubKey]") { SECTION("bip32BitIDKey method test") { UInt128 seed = *(UInt128 *) "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"; CMBlock seedByte; seedByte.SetMemFixed(seed.u8, sizeof(seed)); CMBlock byteData; byteData = MasterPubKey::bip32BitIDKey(seedByte, 0, "https://www.elastos.org"); REQUIRE(byteData != false); REQUIRE(byteData.GetSize() > 0); } } TEST_CASE("Mnemonic test", "[MasterPubKey]") { std::vector<std::string> words; for (std::string str : BRBIP39WordsEn) { words.push_back(str); } SECTION("Invalid mnemonic test") { std::string s = "bless bird birth blind blossom boil bonus entry equal error fence fetch"; REQUIRE(!MasterPubKey::validateRecoveryPhrase(words, s)); } SECTION("phrase validate method test") { UInt128 seed = *(UInt128 *) "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"; std::string paperKey = MasterPubKey::generatePaperKey(seed, words); REQUIRE(paperKey.size() > 0 ); REQUIRE(MasterPubKey::validateRecoveryPhrase(words, paperKey)); } }
31.100917
97
0.697935
hejianhui
f5da1e98a3534f97cc8ef8f9cf7667b4c9848772
2,419
cc
C++
extras/calcav2.cc
dch0ph/pNMRsim
2420e618c7bff9b38b43e7c2ac684c5c28b61787
[ "MIT" ]
null
null
null
extras/calcav2.cc
dch0ph/pNMRsim
2420e618c7bff9b38b43e7c2ac684c5c28b61787
[ "MIT" ]
null
null
null
extras/calcav2.cc
dch0ph/pNMRsim
2420e618c7bff9b38b43e7c2ac684c5c28b61787
[ "MIT" ]
null
null
null
// calculate averaged tensor over 2 fast wobbles #include "space_T.h" #include "NMR.h" #include "ttyio.h" using namespace libcmatrix; using namespace std; void wobble_average(double& retaniso, double& retasym, double aniso1, double asym1, double aniso2, double asym2, double wobble, const char* label, double frac1 =0.5) { const space_T A_PAS1(spatial_tensor(aniso1,asym1)); cout << "Site 1 tensor at start of step " << label << ": " << A_PAS1 << '\n'; space_T A_PAS2; const bool arediff=(aniso1!=aniso2) || (asym1!=asym2); if (arediff) { A_PAS2=spatial_tensor(aniso2,asym2); cout << "Initial site 2 tensor: " << A_PAS2 << '\n'; } Matrix<double> Am_MF,A_tmp; for (size_t step=0;step<2;step++) { const double beta=(step==0) ? -wobble/2.0 : wobble/2.0; const Euler PAS_to_MF(0.0,beta,0.0); const space_T& A_PAS_use( (arediff && (step==1)) ? A_PAS2 : A_PAS1); const space_T A_MF(rotate(A_PAS_use,PAS_to_MF)); tensor_to_matrix(A_tmp,A_MF); const double scalefac=(step==0) ? frac1 : 1.0-frac1; A_tmp*=scalefac; Am_MF+=A_tmp; } cout << "Averaged tensor\n" << Am_MF << '\n'; double iso; Euler PAS; cartesian_to_PAS_symmetric(iso,retaniso,retasym,PAS,Am_MF); const double fudge=std::sqrt(1.5); retaniso*=fudge; cout << "After step " << label << " averaging: aniso=" << retaniso << " asym=" << retasym << " orientation: " << PAS << '\n'; } int main(int argc, const char* argv[]) { int count=1; const double deg_to_rad=M_PI/180.0; const double aniso=getfloat(argc,argv,count,"Anisotropy (kHz)? ",225.0); const double asym=getfloat(argc,argv,count,"Asymmetry? ",0.16); const double wobble1=getfloat(argc,argv,count,"Wobble (full) angle 1 (degrees)? ",112.0)*deg_to_rad; const double wobble2=getfloat(argc,argv,count,"Wobble (full) angle 2 (degrees) [0 if none]? ",0.0)*deg_to_rad; double aniso2=aniso; double asym2=asym; double frac1=0.5; if (wobble2==0.0) { frac1=getfloat(argc,argv,count,"Site 1 population fraction? ",0.0,1.0,0.5); aniso2=getfloat(argc,argv,count,"Anisotropy of site 2 (kHz)? ",aniso2); asym2=getfloat(argc,argv,count,"Anisotropy of site 2 (kHz)? ",asym2); } double newaniso,newasym; wobble_average(newaniso,newasym,aniso,asym,aniso2,asym2,wobble1,"1",frac1); if (wobble2!=0.0) wobble_average(newaniso,newasym,newaniso,newasym,newaniso,newasym,wobble2,"2"); return 0; }
35.057971
165
0.675486
dch0ph
f5da3c857982a4e826892486a19e1e5da8680cd6
1,697
cpp
C++
source/canvas/scene/rigidbody/RigidBody.cpp
RobertDamerius/GroundControlStation
7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f
[ "MIT" ]
1
2021-12-26T12:48:18.000Z
2021-12-26T12:48:18.000Z
source/canvas/scene/rigidbody/RigidBody.cpp
RobertDamerius/GroundControlStation
7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f
[ "MIT" ]
null
null
null
source/canvas/scene/rigidbody/RigidBody.cpp
RobertDamerius/GroundControlStation
7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f
[ "MIT" ]
1
2021-12-26T12:48:25.000Z
2021-12-26T12:48:25.000Z
#include <RigidBody.hpp> RigidBody::RigidBody(){ UpdateModelMatrix(); } RigidBody::~RigidBody(){} void RigidBody::UpdateModelMatrix(void){ double q0q0 = this->quaternion.w * this->quaternion.w; double q1q1 = this->quaternion.x * this->quaternion.x; double q2q2 = -this->quaternion.z * -this->quaternion.z; double q3q3 = this->quaternion.y * this->quaternion.y; double q1q2 = this->quaternion.x * -this->quaternion.z; double q0q3 = this->quaternion.w * this->quaternion.y; double q1q3 = this->quaternion.x * this->quaternion.y; double q0q2 = this->quaternion.w * -this->quaternion.z; double q2q3 = -this->quaternion.z * this->quaternion.y; double q0q1 = this->quaternion.w * this->quaternion.x; GLfloat m[16]; m[0] = (GLfloat)(q0q0+q1q1-q2q2-q3q3); m[4] = (GLfloat)(q1q2+q1q2-q0q3-q0q3); m[8] = (GLfloat)(q1q3+q1q3+q0q2+q0q2); m[12] = (GLfloat)(this->position.x); m[1] = (GLfloat)(q1q2+q1q2+q0q3+q0q3); m[5] = (GLfloat)(q0q0-q1q1+q2q2-q3q3); m[9] = (GLfloat)(q2q3+q2q3-q0q1-q0q1); m[13] = (GLfloat)(-this->position.z); m[2] = (GLfloat)(q1q3+q1q3-q0q2-q0q2); m[6] = (GLfloat)(q2q3+q2q3+q0q1+q0q1); m[10] = (GLfloat)(q0q0-q1q1-q2q2+q3q3); m[14] = (GLfloat)(this->position.y); m[3] = 0.0f; m[7] = 0.0f; m[11] = 0.0f; m[15] = 1.0f; this->modelMatrix = glm::make_mat4(m); } RigidBody& RigidBody::operator=(const RigidBody& rhs){ RigidBodyState::operator=(rhs); modelMatrix = rhs.modelMatrix; return *this; } RigidBody& RigidBody::operator=(const RigidBodyState& rhs){ RigidBodyState::operator=(rhs); return *this; }
42.425
162
0.616971
RobertDamerius
f5daa8e57f8782fc9374a5f6a3ce9c11808063b3
22,762
cpp
C++
src/ImageProcessing.cpp
jbendig/Sudoku-Solver-AR
efec5522d5047b86da0c984935645b27a41c4bb0
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
8
2017-09-20T21:20:44.000Z
2020-05-19T21:09:53.000Z
src/ImageProcessing.cpp
jbendig/Sudoku-Solver-AR
efec5522d5047b86da0c984935645b27a41c4bb0
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
src/ImageProcessing.cpp
jbendig/Sudoku-Solver-AR
efec5522d5047b86da0c984935645b27a41c4bb0
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
5
2017-05-19T07:25:25.000Z
2021-03-02T13:05:32.000Z
// Copyright 2017 James Bendig. See the COPYRIGHT file at the top-level // directory of this distribution. // // Licensed under: // the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT> // or the Apache License, Version 2.0 // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, // at your option. This file may not be copied, modified, or distributed // except according to those terms. #include "ImageProcessing.h" #include <algorithm> #include <numeric> #include <stack> #include <cmath> #include <cstring> template <class T> static T Clamp(const T value,const T minimum,const T maximum) { return std::min(std::max(value,minimum),maximum); } template <class T> static unsigned char ClampToU8(const T value) { return static_cast<unsigned char>(Clamp(value,static_cast<T>(0),static_cast<T>(255))); } static void Histogram(const Image& image,std::vector<float>& normalizedHistogram) { //Note: Assumes image is greyscale. normalizedHistogram.resize(256); std::fill(normalizedHistogram.begin(),normalizedHistogram.end(),0.0f); const unsigned int pixelCount = image.width * image.height; if(pixelCount == 0) return; //Count the pixels. for(unsigned int x = 0;x < pixelCount;x++) { const unsigned int index = x * 3; normalizedHistogram[image.data[index]] += 1.0f; } //Normalize the histogram so the sum of all of the steps equal 1.0. const float divisor = 1.0f / static_cast<float>(pixelCount); for(float& value : normalizedHistogram) { value *= divisor; } } static unsigned char OtsusMethod(const std::vector<float>& normalizedHistogram) { //Based on Digital Image Processing Third Edition. Chapter 10.3.3. Page 742. assert(normalizedHistogram.size() == 256); //Calculate P_1(k). std::vector<float> cumulativeSums(256,normalizedHistogram[0]); for(unsigned int x = 1;x < cumulativeSums.size();x++) { cumulativeSums[x] = cumulativeSums[x - 1] + normalizedHistogram[x]; } //Calculate m(k). std::vector<float> cumulativeMeans(256,0.0f); for(unsigned int x = 1;x < cumulativeMeans.size();x++) { cumulativeMeans[x] = cumulativeMeans[x - 1] + normalizedHistogram[x] * static_cast<float>(x); } //Calculate m_G. const float globalIntensityMean = cumulativeMeans.back(); //Calculate O^2_B(k) and find the index(s) of the maximum. std::vector<unsigned int> betweenClassVarianceIndexes; float betweenClassVarianceMax = 0.0f; for(unsigned int x = 0;x < 256;x++) { const float numerator = globalIntensityMean * cumulativeSums[x] - cumulativeMeans[x]; const float numerator2 = numerator * numerator; const float denominator = cumulativeSums[x] * (1.0f - cumulativeSums[x]); const float betweenClassVariance = denominator == 0.0f ? 0.0f : numerator2 / denominator; if(betweenClassVariance > betweenClassVarianceMax) { betweenClassVarianceIndexes.clear(); betweenClassVarianceIndexes.push_back(x); betweenClassVarianceMax = betweenClassVariance; } else if(betweenClassVariance == betweenClassVarianceMax) betweenClassVarianceIndexes.push_back(x); } return std::accumulate(betweenClassVarianceIndexes.begin(),betweenClassVarianceIndexes.end(),0) / betweenClassVarianceIndexes.size(); } static void NonMaximumSuppression(const std::vector<float>& gradient,const unsigned int width,const unsigned int height,std::vector<unsigned char>& nonMaximumSuppression,const unsigned char lowThreshold,const unsigned char highThreshold) { //Based on Digital Image Processing Third Edition. Chapter 10.2. Page 721. assert(gradient.size() == width * height * 2); //Perform Non-Maximum Suppression and Hysterasis Thresholding. nonMaximumSuppression.resize(width * height * 3); std::fill(nonMaximumSuppression.begin(),nonMaximumSuppression.end(),0); for(unsigned int y = 1;y < height - 1;y++) { for(unsigned int x = 1;x < width - 1;x++) { const unsigned int inputIndex = (y * width + x) * 2; const unsigned int outputIndex = (y * width + x) * 3; const float magnitude = gradient[inputIndex + 0]; //Discretize angle into one of four fixed steps to indicate which direction the edge is //running along: horizontal, vertical, left-to-right diagonal, or right-to-left //diagonal. The edge direction is 90 degrees from the gradient angle. float angle = gradient[inputIndex + 1]; //The input angle is in the range of [-pi,pi] but negative angles represent the same //edge direction as angles 180 degrees apart. angle = angle >= 0.0f ? angle : angle + M_PI; //Scale from [0,pi] to [0,4] and round to an integer representing a direction. Each //direction is made up of 45 degree blocks. The rounding and modulus handle the //situation where the first and final 45/2 degrees are both part of the same direction. angle = angle * 4.0f / M_PI; const unsigned char direction = lroundf(angle) % 4; //Only mark pixels as edges when the gradients of the pixels immediately on either side //of the edge have smaller magnitudes. This keeps the edges thin. bool suppress = false; if(direction == 0) //Vertical edge. suppress = magnitude < gradient[inputIndex - 2] || magnitude < gradient[inputIndex + 2]; else if(direction == 1) //Right-to-left diagonal edge. suppress = magnitude < gradient[inputIndex - width * 2 - 2] || magnitude < gradient[inputIndex + width * 2 + 2]; else if(direction == 2) //Horizontal edge. suppress = magnitude < gradient[inputIndex - width * 2] || magnitude < gradient[inputIndex + width * 2]; else if(direction == 3) //Left-to-right diagonal edge. suppress = magnitude < gradient[inputIndex - width * 2 + 2] || magnitude < gradient[inputIndex + width * 2 - 2]; if(suppress || magnitude < lowThreshold) { nonMaximumSuppression[outputIndex + 0] = 0; nonMaximumSuppression[outputIndex + 1] = 0; nonMaximumSuppression[outputIndex + 2] = 0; } else { //Use thresholding to indicate strong and weak edges. Strong edges are assumed to be //valid edges. Connectivity analysis is used to check if a weak edge is connected to //a strong edge indiciating that the weak edge is also a valid edge. nonMaximumSuppression[outputIndex + 0] = magnitude >= highThreshold ? 255 : 0; //Strong nonMaximumSuppression[outputIndex + 1] = magnitude < highThreshold ? 255 : 0; //Weak nonMaximumSuppression[outputIndex + 2] = 0; } } } } static void ConnectivityAnalysis(Image& image) { assert(image.width >= 1 && image.height >= 1); //Input image should be output of NonMaximumSuppression(). //Channel 0: Strong edge pixels. //Channel 1: Weak edge pixels. //Channel 2: Should be set to 0. Will be used to indicate an edge that has been previously // visited. //Output image will have all weak edges connected to strong edges set to strong edges //themselves. Meaning only the first channel will have useful data and the other remaining //channels should be ignored. //Keep track of coordinates that should be searched in case they are connected. std::stack<std::pair<unsigned int,unsigned int>> searchStack; //Add all 8 coordinates around (x,y) to be searched. auto PushSearchConnected = [&searchStack](const unsigned int x,const unsigned int y) { searchStack.push(std::make_pair(x - 1,y - 1)); searchStack.push(std::make_pair(x ,y - 1)); searchStack.push(std::make_pair(x + 1,y - 1)); searchStack.push(std::make_pair(x - 1,y)); searchStack.push(std::make_pair(x ,y)); searchStack.push(std::make_pair(x + 1,y)); searchStack.push(std::make_pair(x - 1,y + 1)); searchStack.push(std::make_pair(x ,y + 1)); searchStack.push(std::make_pair(x + 1,y + 1)); }; //Search for strong edges and flood fill surrounding weak edges, promoting the weak to strong. for(unsigned int y = 1;y < image.height - 1;y++) { for(unsigned int x = 1;x < image.width - 1;x++) { const unsigned int index = (y * image.width + x) * 3; //Skip pixels that are not strong edges or have been previously visited. if(image.data[index + 0] == 0 || image.data[index + 2] == 255) continue; //Mark pixel as visited to save time flood filling later. image.data[index + 2] = 255; //Flood fill all connected weak edges. PushSearchConnected(x,y); while(!searchStack.empty()) { const std::pair<unsigned int,unsigned int> coordinates = searchStack.top(); searchStack.pop(); //Skip pixels that are not weak edges. const unsigned int x = coordinates.first; const unsigned int y = coordinates.second; const unsigned int index = (y * image.width + x) * 3; if(image.data[index + 1] == 0) continue; //Promote to strong edge and mark visited to save time flood filling later. image.data[index + 0] = 255; image.data[index + 1] = 0; image.data[index + 2] = 255; //Search around this coordinate as well. This will waste time checking the previous //coordinate again but it's fast enough. PushSearchConnected(x,y); } } } } void YUYVToRGB(const unsigned char* yuyvData,Image& frame) { for(unsigned int x = 0;x < frame.width * frame.height;x+=2) { const unsigned int inputIndex = x * 2; const unsigned int outputIndex = x * 3; const unsigned char y0 = yuyvData[inputIndex + 0]; const unsigned char cb = yuyvData[inputIndex + 1]; const unsigned char y1 = yuyvData[inputIndex + 2]; const unsigned char cr = yuyvData[inputIndex + 3]; //TODO: LOTS of optimization possibilities here. frame.data[outputIndex + 0] = Clamp(static_cast<int>(y0 + 1.402 * (cr - 128)),0,255); frame.data[outputIndex + 1] = Clamp(static_cast<int>(y0 - 0.344 * (cb - 128) - 0.714 * (cr - 128)),0,255); frame.data[outputIndex + 2] = Clamp(static_cast<int>(y0 + 1.772 * (cb - 128)),0,255); frame.data[outputIndex + 3] = Clamp(static_cast<int>(y1 + 1.402 * (cr - 128)),0,255); frame.data[outputIndex + 4] = Clamp(static_cast<int>(y1 - 0.344 * (cb - 128) - 0.714 * (cr - 128)),0,255); frame.data[outputIndex + 5] = Clamp(static_cast<int>(y1 + 1.772 * (cb - 128)),0,255); } } void YUYVToGreyscale(const unsigned char* yuyvData,Image& frame) { for(unsigned int x = 0;x < frame.width * frame.height;x+=2) { const unsigned int inputIndex = x * 2; const unsigned int outputIndex = x * 3; const unsigned char y0 = yuyvData[inputIndex + 0]; const unsigned char y1 = yuyvData[inputIndex + 2]; frame.data[outputIndex + 0] = y0; frame.data[outputIndex + 1] = y0; frame.data[outputIndex + 2] = y0; frame.data[outputIndex + 3] = y1; frame.data[outputIndex + 4] = y1; frame.data[outputIndex + 5] = y1; } } void NV12ToRGB(const unsigned char* nv12Data,Image& frame) { const unsigned int widthHalf = frame.width / 2; for(unsigned int y = 0;y < frame.height;y++) { const unsigned int yEven = y & 0xFFFFFFFE; for(unsigned int x = 0;x < frame.width;x++) { const unsigned int xEven = x & 0xFFFFFFFE; const unsigned int yIndex = y * frame.width + x; const unsigned int cIndex = frame.width * frame.height + yEven * widthHalf + xEven; const unsigned int outputIndex = (y * frame.width + x) * 3; const unsigned char y = nv12Data[yIndex]; const unsigned char cb = nv12Data[cIndex + 0]; const unsigned char cr = nv12Data[cIndex + 1]; //TODO: LOTS of optimization possibilities here. frame.data[outputIndex + 0] = Clamp(static_cast<int>(y + 1.402 * (cr - 128)),0,255); frame.data[outputIndex + 1] = Clamp(static_cast<int>(y - 0.344 * (cb - 128) - 0.714 * (cr - 128)),0,255); frame.data[outputIndex + 2] = Clamp(static_cast<int>(y + 1.772 * (cb - 128)),0,255); } } } void NV12ToGreyscale(const unsigned char* nv12Data,Image& frame) { for(unsigned int x = 0;x < frame.width * frame.height;x++) { const unsigned int outputIndex = x * 3; const unsigned char y = nv12Data[x]; frame.data[outputIndex + 0] = y; frame.data[outputIndex + 1] = y; frame.data[outputIndex + 2] = y; } } void RGBToRGB(const unsigned char* rgbData,Image& frame) { memcpy(&frame.data[0],rgbData,frame.width * frame.height * 3); } void RGBToGreyscale(const unsigned char* rgbData,Image& frame) { for(unsigned int x = 0;x < frame.width * frame.height;x++) { const unsigned int index = x * 3; //RGB to luma (BT.601 Y'UV). const float lumaf = 0.299f * rgbData[index + 0] + 0.587f * rgbData[index + 1] + 0.114f * rgbData[index + 2]; const unsigned char luma = ClampToU8(lumaf); frame.data[index + 0] = luma; frame.data[index + 1] = luma; frame.data[index + 2] = luma; } } void BGRVerticalMirroredToRGB(const unsigned char* bgrData,Image& frame) { for(unsigned int y = 0;y < frame.height;y++) { for(unsigned int x = 0;x < frame.width;x++) { const unsigned int inputIndex = ((frame.height - y - 1) * frame.width + x) * 3; const unsigned int outputIndex = (y * frame.width + x) * 3; frame.data[outputIndex + 0] = bgrData[inputIndex + 2]; frame.data[outputIndex + 1] = bgrData[inputIndex + 1]; frame.data[outputIndex + 2] = bgrData[inputIndex + 0]; } } } void BlendAdd(const Image& image1,const Image& image2,Image& outputImage) { assert(image1.width == image2.width && image1.height == image2.height); outputImage.MatchSize(image1); for(unsigned int x = 0;x < image1.width * image1.height * 3;x++) { outputImage.data[x] = ClampToU8(static_cast<unsigned int>(image1.data[x]) + static_cast<unsigned int>(image2.data[x])); } } void AutoLevels(const Image& inputImage,Image& outputImage,const unsigned int ignorePadding) { if(inputImage.width < ignorePadding * 2 || inputImage.height < ignorePadding * 2) return; outputImage.MatchSize(inputImage); //Find the lows and highs of the histogram. unsigned char minValue = 255; unsigned char maxValue = 0; for(unsigned int y = ignorePadding;y < inputImage.height - ignorePadding;y++) { for(unsigned int x = ignorePadding;x < inputImage.width - ignorePadding;x++) { const unsigned int index = (y * inputImage.width + x) * 3; const unsigned char value = inputImage.data[index]; minValue = std::min(minValue,value); maxValue = std::max(maxValue,value); } } //Rescale so the brightest and darkest parts are clipped by CLIPPING percent. constexpr float CLIPPING = 0.1; const float delta = static_cast<float>(maxValue - minValue) / 255.0f - (CLIPPING * 2.0f); if(delta <= 0.0f) return; for(unsigned int x = 0;x < inputImage.width * inputImage.height;x++) { const unsigned int index = x * 3; const float valuef = (static_cast<float>(inputImage.data[index]) - static_cast<float>(minValue)) / delta; const unsigned char value = ClampToU8(valuef); outputImage.data[index + 0] = value; outputImage.data[index + 1] = value; outputImage.data[index + 2] = value; } } void Gaussian(const Image& inputImage,Image& outputImage,const float radius) { outputImage.MatchSize(inputImage); auto GaussianKernel = [](const float radius,unsigned int& weightRadius,unsigned int& weightCount) { auto Gaussian = [](const float x,const float sigma) { const float x2 = x * x; const float sigma2 = sigma * sigma; return expf(-x2 / (2.0f * sigma2)); }; const float sigma = radius / 3.0f; //Somewhat arbitrary but dependent on radius. weightRadius = static_cast<unsigned int>(radius) + 1; weightCount = weightRadius * 2 + 1; std::vector<float> weights(weightCount,0.0f); float sum = 0.0f; for(unsigned int x = 0;x < weightCount;x++) { const float weight = Gaussian(static_cast<float>(x) - static_cast<float>(weightRadius),sigma); weights[x] = weight; sum += weight; } const float oneOverSum = 1.0f / sum; for(float& weight : weights) { weight *= oneOverSum; } return weights; }; unsigned int weightRadius = 0; unsigned int weightCount = 0; const std::vector<float> weights = GaussianKernel(radius,weightRadius,weightCount); //TODO: Make caller provide a temporary buffer to reduce large allocations. std::vector<unsigned char> tempBuffer; tempBuffer.resize(outputImage.data.size()); //Blur horizontally. //TODO: Support edges or document the current behavior. for(unsigned int y = 0;y < inputImage.height;y++) { for(unsigned int x = weightRadius;x < inputImage.width - weightRadius;x++) { float sum[3] = {0.0f,0.0f,0.0f}; for(unsigned int w = 0;w < weightCount;w++) { const unsigned int inputIndex = (y * inputImage.width + x + w - weightRadius) * 3; sum[0] += static_cast<float>(inputImage.data[inputIndex + 0]) * weights[w]; sum[1] += static_cast<float>(inputImage.data[inputIndex + 1]) * weights[w]; sum[2] += static_cast<float>(inputImage.data[inputIndex + 2]) * weights[w]; } const unsigned int outputIndex = (y * outputImage.width + x) * 3; tempBuffer[outputIndex + 0] = ClampToU8(sum[0]); tempBuffer[outputIndex + 1] = ClampToU8(sum[1]); tempBuffer[outputIndex + 2] = ClampToU8(sum[2]); } } //Blur vertically. //TODO: Might be faster to rotate 90 degrees, blur horizontally, and then rotate 90 degrees back. for(unsigned int y = weightRadius;y < inputImage.height - weightRadius;y++) { for(unsigned int x = weightRadius;x < inputImage.width - weightRadius;x++) { float sum[3] = {0.0f,0.0f,0.0f}; for(unsigned int w = 0;w < weightCount;w++) { const unsigned int inputIndex = ((y + w - weightRadius) * inputImage.width + x) * 3; sum[0] += static_cast<float>(tempBuffer[inputIndex + 0]) * weights[w]; sum[1] += static_cast<float>(tempBuffer[inputIndex + 1]) * weights[w]; sum[2] += static_cast<float>(tempBuffer[inputIndex + 2]) * weights[w]; } const unsigned int outputIndex = (y * outputImage.width + x) * 3; outputImage.data[outputIndex + 0] = ClampToU8(sum[0]); outputImage.data[outputIndex + 1] = ClampToU8(sum[1]); outputImage.data[outputIndex + 2] = ClampToU8(sum[2]); } } } void Sobel(const Image& image,std::vector<float>& gradient) { gradient.resize(image.width * image.height * 2); if(image.width == 0 || image.height == 0) return; const unsigned int rowSpan = image.width * 3; for(unsigned int y = 1;y < image.height - 1;y++) { for(unsigned int x = 1;x < image.width - 1;x++) { const unsigned int inputIndex = (y * image.width + x) * 3; const float horizontalSum = static_cast<float>(image.data[inputIndex - rowSpan - 3]) * -1.0f + static_cast<float>(image.data[inputIndex - rowSpan + 3]) + static_cast<float>(image.data[inputIndex - 3]) * -2.0f + static_cast<float>(image.data[inputIndex + 3]) * 2.0f + static_cast<float>(image.data[inputIndex + rowSpan - 3]) * -1.0f + static_cast<float>(image.data[inputIndex + rowSpan + 3]); const float verticalSum = static_cast<float>(image.data[inputIndex - rowSpan - 3]) * -1.0f + static_cast<float>(image.data[inputIndex - rowSpan]) * -2.0f + static_cast<float>(image.data[inputIndex - rowSpan + 3]) * -1.0f + static_cast<float>(image.data[inputIndex + rowSpan - 3]) + static_cast<float>(image.data[inputIndex + rowSpan]) * 2.0f + static_cast<float>(image.data[inputIndex + rowSpan + 3]); const float magnitude = hypotf(horizontalSum,verticalSum); const float angle = atan2f(verticalSum,horizontalSum); const unsigned int outputIndex = (y * image.width + x) * 2; gradient[outputIndex + 0] = magnitude; gradient[outputIndex + 1] = angle; } } } void HoughTransform(const Image& inputImage,Image& accumulationImage) { //Based on Digital Image Processing Third Edition. Chapter 10.2.7. Page 733. //AccumulationImage is where the buckets for the hough transform are written to. //X Axis: Angle evenly split up across [-pi/2,pi). //Y Axis: Distance from origin split up across [0,diagonal length). //Each pixel is the accumulation of the related input pixel's chance of being part of the line. //The red channel and green channel are a machine native 16-bit unsigned integer total. The //blue channel is unused. //The X axis interval was chosen so that rho can represent all lines with a positive value and //so we don't have to worry about angles being wrapped. if(accumulationImage.width == 0 || accumulationImage.height == 0) { //Sane defaults based off of Image Processing: The Fundamentals Chapter 5. Page 520. accumulationImage.width = 360 * 2; accumulationImage.height = std::min(inputImage.width,inputImage.height) * 2; } accumulationImage.data.resize(accumulationImage.width * accumulationImage.height * 3); std::fill(accumulationImage.data.begin(),accumulationImage.data.end(),0); //Pre-calculate as much as possible to improve performance. const float maxR = hypotf(inputImage.width,inputImage.height); const float angleFMultiplier = (3.0f * M_PI / 2.0f) / static_cast<float>(accumulationImage.width); const float rMultiplier = static_cast<float>(accumulationImage.height) / maxR; std::vector<float> cosAngles(accumulationImage.width); std::vector<float> sinAngles(accumulationImage.width); for(unsigned int x = 0;x < accumulationImage.width;x++) { const float angleF = static_cast<float>(x) * angleFMultiplier - M_PI / 2.0f; cosAngles[x] = cosf(angleF); sinAngles[x] = sinf(angleF); } constexpr unsigned int IGNORE_PADDING = 10; //How much of edges to ignore so blurred edges are not counted as an edge. for(unsigned int y = IGNORE_PADDING;y < inputImage.height - IGNORE_PADDING;y++) { for(unsigned int x = IGNORE_PADDING;x < inputImage.width - IGNORE_PADDING;x++) { const unsigned int inputIndex = (y * inputImage.width + x) * 3; if(inputImage.data[inputIndex + 0] == 0) continue; for(unsigned int z = 0;z < accumulationImage.width;z++) { float rf = static_cast<float>(x) * cosAngles[z] + static_cast<float>(y) * sinAngles[z]; if(rf < 0.0f) continue; rf *= rMultiplier; const unsigned int r = Clamp(static_cast<unsigned int>(rf),0u,accumulationImage.height - 1); const unsigned int outputIndex = (r * accumulationImage.width + z) * 3; unsigned short* value = reinterpret_cast<unsigned short*>(&accumulationImage.data[outputIndex]); if(*value < 0xFFFF) *value += 1; } } } } Canny Canny::WithRadius(const float gaussianBlurRadius) { return Canny(gaussianBlurRadius); } void Canny::Process(const Image& inputImage,Image& outputImage) { Gaussian(inputImage,gaussianImage,gaussianBlurRadius); Sobel(gaussianImage,gradient); Histogram(gaussianImage,normalizedHistogram); const float highThreshold = OtsusMethod(normalizedHistogram); const float lowThreshold = highThreshold / 2; outputImage.MatchSize(inputImage); NonMaximumSuppression(gradient,inputImage.width,inputImage.height,outputImage.data,lowThreshold,highThreshold); ConnectivityAnalysis(outputImage); } Canny::Canny(const float gaussianBlurRadius) : gaussianBlurRadius(gaussianBlurRadius) { }
36.89141
237
0.695194
jbendig
f5dd4d6c673c0c541bcf6ea8f5a1dca11051193d
436
cpp
C++
tests/concepts/is_class.cpp
SamuelAlonsoDev/lux
268a9fabddb60a06e226d8bad27a5d5d7a29dcb2
[ "MIT" ]
2
2020-11-05T07:39:05.000Z
2021-01-07T18:29:56.000Z
tests/concepts/is_class.cpp
SamuelAlonsoDev/lux
268a9fabddb60a06e226d8bad27a5d5d7a29dcb2
[ "MIT" ]
null
null
null
tests/concepts/is_class.cpp
SamuelAlonsoDev/lux
268a9fabddb60a06e226d8bad27a5d5d7a29dcb2
[ "MIT" ]
null
null
null
#include <iostream> #include <core/types.hpp> #include <concepts/is_class.hpp> class ic; class c{}; struct s{}; int main() { std::cout << std::boolalpha << "Is 'ic' a class type? " << lux::concepts::is_class<ic> << "\nIs 'c' a class type? " << lux::concepts::is_class<c> << "\nIs 's' a class type? " << lux::concepts::is_class<s> << "\nIs 'u8' a class type? " << lux::concepts::is_class<lux::u8>; return 0; }
22.947368
67
0.584862
SamuelAlonsoDev
f5e0c824e8db234013aa12bc34a4b8dcbade2b4c
169,715
cxx
C++
bst.cxx
abk-openroad/BST-DME
157616ef1305a4270abf3d17b8e4c9acba716fa9
[ "BSD-3-Clause" ]
5
2018-08-05T06:41:38.000Z
2019-06-03T17:54:12.000Z
bst.cxx
abk-openroad/BST-DME
157616ef1305a4270abf3d17b8e4c9acba716fa9
[ "BSD-3-Clause" ]
null
null
null
bst.cxx
abk-openroad/BST-DME
157616ef1305a4270abf3d17b8e4c9acba716fa9
[ "BSD-3-Clause" ]
3
2019-04-25T11:47:07.000Z
2021-08-30T13:49:52.000Z
/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (c) 2018, The Regents of the University of California // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. /////////////////////////////////////////////////////////////////////////////// /* #************************************************************************** #** Please read README to see how to run this program *** Created by Chung-Wen Albert Tsao on May 2, 2000* #** #** #************************************************************************** */ #include <cmath> #include "bst_header.h" #include "bst.h" #include "bst_sub1.h" #include "bst_sub3.h" #include "IME_code.h" #include "facility.h" #include "stdio.h" #include "stdlib.h" /* Curr_Npoints is the current number of nodes (leaves + internal nodes + 1). The leaves are numbered from 0 to nterms -1, and the internal nodes from nterms to 2*nterms-1.` The node indexed by "nterms" is preserved for the clock source, which may not be used yet. Initially, Curr_Npoints = nterms+1 , which means that that are nterms leaves and one clock source. Then Curr_Npoints is increased by one whenever a new tree root is produced during bottom-up merging. */ static int Curr_Npoints ; BstTree *gBoundedSkewTree ; vector <NodeType > Node, CandiRoot, TempNode; //AreaType *TempArea; //int N_TempArea; AreaType *TempArea = (AreaType*)calloc(1000, sizeof(AreaType)); //Modified int N_TempArea=1000; //jianchao : value assigned for IME //Modified TrrType *L_sampling, *R_sampling; int N_Sampling = 7, n_L_sampling, n_R_sampling; char *Marked; int *UnMarkedNodes; int CHECK = NO; int Max_n_regions = 0; int Max_irredundant_regions = 0; int N_Area_Per_Node = 1; int k_Parameter = -1; int N_Neighbor = 1; double Cost_Function = 1; BucketType **Bucket; int Local_Opt = NO; int BST_Mode = BME_MODE; int Dynamic_Selection = NO; /* no dynamic topology change */ int N_Index, MAX_N_Index; double Start_Tcost = 0, Start_Skew_B = -2, Skew_B = 0, Skew_B_CLS[MAX_N_SINKS]; double Last_Time, Gamma=1; double PURES[2], PUCAP[2]; /*per unit resistance and capacitance */ double PURES_V_SCALE = 1; double PUCAP_V_SCALE = 1; double K[2]; /* K[i] = 0.5*PURES[i]*PUCAP[i], quardratic terms in Elmore delay */ PairType *Best_Pair; int Read_Delay_Skew_File = NO; PointType Fms_Pt[2][2]; /* feasible merging section on JR */ int n_Fms_Pt[2]; PointType JR_corner[2]; int N_Bal_Pt[2]; PointType Bal_Pt[2][2]; int n_JR[2]; PointType JR[2][MAX_TURN_PTS]; int n_JS[2]; PointType JS[2][MAX_TURN_PTS]; TrrType L_MS, R_MS; vector<double> EdgeLength, StubLength; int *N_neighbors; int **The_NEIghors; double **Neighbor_Cost; ClusterType *Cluster; /* ============================= */ double MAX_x, MAX_y, MIN_x, MIN_y; double Split_Factor = 10.0; int *NearestCenter; int *TmpClusterId; TmpClusterType *TmpCluster, Tmp_x_Cluster, Tmp_y_Cluster; /* =============================*/ int N_Buffer_Level = 1, N_Clusters[MAX_BUFFER_LEVEL], Total_CL =0; int TreeRoots[MAX_N_SINKS]; /* nodes which are the roots */ int Cluster_id[MAX_N_NODES], *Buffered; int R_buffer= 100; double C_buffer= 50.0e-15*PUCAP_SCALE; double Delay_buffer = 100e-12*PUCAP_SCALE; int R_buffer_size[N_BUFFER_SIZE]; int All_Top = NO; int Expand_Size = 3; double Weight = 0.0; int Cmode = 0; PointType *Points; int *TmpMarked; double *Capac; int Hierachy_Cluster_id[MAX_N_NODES]; int N_Obstacle = 0; /* Number of obstacles */ double MaxClusterDelay, *ClusterDelay; int TmpCondition = NO, N_Top_Embed = 0; double calc_merging_cost(int , int ); extern double calc_buffered_node_delay(int v); extern int JR_corner_exist(int i); extern void set_K(); extern void assign_NodeType(NodeType *node1, NodeType *node2); extern int detour_Node(int v); extern void sort_pts_on_line(PointType JR[], int n); extern double Point_dist(PointType p1, PointType p2); extern double pt2linedist(PointType , PointType , PointType , PointType *ans); extern double ms_distance(TrrType *ms1,TrrType *ms2); extern double min4(double x1, double x2, double x3,double x4); extern double max4(double x1, double x2, double x3,double x4); extern void kohck_Irredundant(AreaType *areas, int *n_areas); extern void tsao_Irredundant(AreaType *areas, int *n_areas); extern void Irredundant(AreaSetType *stair); extern int equal(double x,double y); extern int equivalent(double x,double y, double fuzz); extern int pt_on_line_segment(PointType pt,PointType pt1,PointType pt2); extern int PT_on_line_segment(PointType *pt,PointType pt1,PointType pt2); extern int same_Point(PointType p1, PointType p2); extern int Same_Point_delay(PointType *p, PointType *q); extern int JS_line_type(NodeType *node); extern int Manhattan_arc_JS(NodeType *node); extern int area_Manhattan_arc_JS(AreaType *area); extern double pt_skew(PointType pt); extern double merge_cost(NodeType *node); extern double area_merge_cost(AreaType *area); extern int Manhattan_arc(PointType p1,PointType p2); extern int merging_segment_area(AreaType *area); extern int TRR_area(AreaType *area); extern int case_Manhattan_arc(); extern void ms_to_line(TrrType *ms,double *x1,double *y1,double *x2,double *y2); extern void ms2line(TrrType *ms, PointType *p1, PointType *p2); extern void line_to_ms(TrrType *ms,double x1,double y1,double x2,double y2); extern void line2ms(TrrType *ms, PointType p1, PointType p2); extern void pts2TRR(PointType pts[], int n, TrrType *trr); extern int trrContain(TrrType *t1,TrrType *t2); extern int in_bbox(double x,double y,double x1,double y1,double x2,double y2); extern void core_mid_point(TrrType *trr, PointType *p); extern void make_intersect( TrrType *trr1, TrrType *trr2, TrrType *t ); extern void make_intersect_sub( TrrType *trr1, TrrType *trr2, TrrType *t ); extern void make_core(TrrType *trr,TrrType *core); extern void make_1D_TRR(TrrType *trr,TrrType *core); extern double radius(TrrType *trr); extern void build_trr(TrrType *ms,double d,TrrType *trr); extern double pt2ms_distance(PointType *pt, TrrType *ms); extern double pt2TRR_distance_sub(PointType *pt, TrrType *trr); extern double pt2TRR_distance(PointType *pt, PointType pts[], int n); extern int bbox_overlap(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4); extern int L_intersect(double *x, double *y, double x1, double y1,double x2, double y2, double x3, double y3, double x4, double y4); extern int lineIntersect(PointType *p, PointType p1, PointType p2, PointType p3, PointType p4); extern double linedist(PointType lpt0,PointType lpt1, PointType lpt2, PointType lpt3, PointType ans[2]); extern int parallel_line(PointType p1,PointType p2,PointType p3,PointType p4); extern void check_Point_delay(PointType *pt); extern void check_Point(PointType *pt); extern void check_JS_line(NodeType *node,NodeType *node_L, NodeType *node_R); extern void check_mss(AreaType *area,AreaType *area_L, AreaType *area_R); extern void check_x(AreaType *, AreaType *, AreaType *, double *x); extern void check_fms(AreaType *area_L, AreaType *area_R, int side); extern void check_ZST_detour(NodeType *node,NodeType *node_L,NodeType *node_R); extern void check_trr(TrrType *t) ; extern void check_ms(TrrType *ms); extern void check_a_sampling_segment(AreaType *area, TrrType *ms); extern void check_tmparea(AreaType *tmparea, int n); extern void check_const_delays(PointType *p1,PointType *p2); extern void get_all_areas(int v, int i); extern void store_n_areas(AreaType tmparea[], int n, NodeType *node); extern void store_n_areas_IME(NodeType *node,AreaSetType *result); extern void store_last_n_areas_IME(NodeType *node,AreaSetType *result); extern void store_area_for_sink(int i); extern void build_NodeTRR(NodeType *node); extern double minskew(NodeType *node, int mode); extern double maxskew(NodeType *node, int mode); extern void print_IME_areas(NodeType *node,NodeType *node_L, NodeType *node_R,int ,int ); extern void print_double_array(double *a, int n); extern void print_JR_sub(FILE *f, NodeType *node); extern void print_JS_sub(FILE *f, NodeType *node); extern void print_merging_region(FILE *f, NodeType *node); extern void print_node(NodeType *node) ; extern void print_MR(NodeType *node); extern void print_child_region(NodeType *node); extern void print_max_npts(); extern void print_overlapped_regions(); extern void print_max_n_mr(); extern void print_n_region_type(); extern void print_tree_of_merging_segments(char fn[]); extern void print_Bal_Pt(NodeType *node); extern void print_Fms_Pt(NodeType *node); extern void print_node_info(NodeType *node); extern void print_node_informatio(NodeType *node,NodeType *node_L, NodeType *node_R); extern void JS_processing(AreaType *area); extern void JS_processing_sub(AreaType *area); extern void JS_processing_sub2(AreaType *area); extern void recalculate_JS(); extern void remove_epsilon_err(PointType *q) ; extern int same_line(PointType p0,PointType p1,PointType q0,PointType q1); extern void construct_TRR_mr(AreaType *area); extern int any_fms_on_JR(); extern void trace(); extern double calc_JR_area_sub(PointType p0,PointType p1,PointType p2,PointType p3); extern int calc_line_type(PointType pt1,PointType pt2); extern int calc_side_loc(int side); extern void calc_merge_distance(double r, double c, double cap1,double delay1, double cap2, double delay2, double d,double *d1,double *d2); extern void new_calc_merge_distance(PointType pt1, PointType pt2, int delay_id, double *d1,double *d2); extern double calc_delay_increase(double p, double cap, double x, double y); extern double pt_delay_increase(double p,double cap,PointType *q0,PointType *q1); extern double _pt_delay_increase(double pat, double leng,double cap, PointType *q0,PointType *q1); extern void calc_pt_coor_on_a_line(PointType q0,PointType q1, double d0,double d1, PointType *pts); extern void calc_Bal_of_2pt(PointType *pt0, PointType *pt1, int delay_id, int bal_pt_id, double *d0, double *d1, PointType *ans); extern void check_calc_Bal_of_2pt(PointType *pt0, PointType *pt1, int delay_id, PointType *ans, double d0, double d1); extern void calc_vertices(AreaType *area); extern void calc_pt_delays(AreaType *area, PointType *q1,PointType q0,PointType q2); extern void calc_BS_located(PointType *pt,AreaType *area, PointType *p1, PointType *p2); extern void calc_JS_delay(AreaType *area, AreaType *area_L,AreaType *area_R); extern int calc_TreeCost(int v, double *Tcost, double *Tdist); extern void print_cluster_cost(double cost); extern void calc_BST_delay(int v); extern void set_SuperRoot(); extern void alloca_NodeType(NodeType *node); extern void free_NodeType(NodeType *node); extern void ExG_DME_memory_allocation(); extern void Ex_DME_memory_allocation(); extern void read_clustering_info(char ClusterFile[]); extern void init_marked(int v); extern void init_turn_pt_on_JS(int side,PointType *pt); extern void calc_merging_cost_sub(NodeType *node, int L, int R); extern double path_between_JSline(AreaType *area, PointType line[2][2], PointType path[],int *n); extern int unblocked_segment(PointType *p0, PointType *p1); extern double path_finder(PointType p1, PointType p2, PointType path[], int *n); extern double calc_pathlength(PointType path[], int n, int mode); extern void modify_blocked_areas(AreaType area[], int *n, int b1, int b2); extern int calc_all_cluster_neighbors(PairType pair[], int n_clusters,int size); extern void init_re_embed_top(int v); extern void init_re_embed_top_sub(int v); extern void draw_a_TRR(TrrType *trr); void check_JR_linear_delay_skew(int side) ; /********************************************************************/ /* find solution of equation: Ax*x+Bx+c=0 */ /********************************************************************/ static double sol_equation(double A, double B, double C) { double x, y; y = B*B-4.0*A*C; assert(y>=0); x = (-B + sqrt(y))/(2.0*A); assert(x > -FUZZ); x = tMAX(0,x); return(x); } /***********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /***********************************************************************/ static double calc_x(AreaType *area) { double x; double r,c; r = PURES[H_]; c = PUCAP[H_]; x = r*(area->unbuf_capac) + area->R_buffer*c; return(x); } /***********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /***********************************************************************/ void calc_B0_B1(AreaType *area, double *B0, double *B1) { double r,c; r = PURES[H_]; c = PUCAP[H_]; *B0= r*(area->area_L->unbuf_capac) + area->area_L->R_buffer*c; *B1= r*(area->area_R->unbuf_capac) + area->area_R->R_buffer*c; } /****************************************************************************/ /* */ /****************************************************************************/ double calc_merge_pt_delay_sub(AreaType *area, double d0, double d1) { double B0, B1, x, t0, t1, r, c, cap0, cap1; r = PURES[H_]; c = PUCAP[H_]; cap0 = area->area_L->capac; cap1 = area->area_R->capac; calc_B0_B1(area, &B0, &B1); x = area->L_StubLen; t0 = r*d0*(c*d0/2+cap0) + JS[0][0].max + K[H_]*x*x+B0*x; x = area->R_StubLen; t1 = r*d1*(c*d1/2+cap1) + JS[1][0].max + K[H_]*x*x+B1*x; assert(equal(t0, t1)); return(t0); } /****************************************************************************/ /* */ /****************************************************************************/ void calc_merge_pt_delay(AreaType *area, double d0, double d1) { area->mr[0].max = calc_merge_pt_delay_sub(area, d0, d1); area->mr[0].min = area->mr[0].max - Skew_B; check_Point_delay(&(area->mr[0])); } /***********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /***********************************************************************/ double set_StubLen_by_ClusterDelay(AreaType *area,double delay) { double ans, x; double origB = gBoundedSkewTree->Orig_Skew_B() ; if (area->R_buffer>0) { if (origB==0) { assert(area->ClusterDelay >= delay - FUZZ); } area->ClusterDelay = tMAX(area->ClusterDelay, delay); x = calc_x(area); ans = sol_equation(K[H_], x, delay - area->ClusterDelay); } else { ans = 0; } return(ans); } /***********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /***********************************************************************/ void set_area_StubLen2(AreaType *area, double *d0, double *d1) { double x,y,z,len0,len1, d, B0, B1; double Lmax, Rmax; Lmax = JS[0][0].max; Rmax = JS[1][0].max; calc_B0_B1(area, &B0, &B1); d = area->dist; x = B1*d + Rmax - Lmax + K[H_]*d*d; y = B0 + B1 + 2*d*K[H_]; z = x/y; if (z <0) { len1 = sol_equation(K[H_], B1, Rmax - Lmax); len0 = 0 ; } else if (z > d) { len0 = sol_equation(K[H_], B0, Lmax - Rmax); len1 = 0; } else { len0 = z; len1 = d - z ; } if (area->area_L->R_buffer > 0) { area->L_StubLen = len0; *d0 = 0; } else { area->L_StubLen = 0 ; *d0 = len0; } if (area->area_R->R_buffer > 0) { area->R_StubLen = len1; *d1 = 0; } else { area->R_StubLen = 0 ; *d1 = len1; } area->L_EdgeLen = len0; area->R_EdgeLen = len1; } /***********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /***********************************************************************/ void calc_area_EdgeLen(AreaType *area, double *d0, double *d1) { double cap0, cap1, tL, tR, diff; double B0, B1, x; cap0 = area->area_L->capac; cap1 = area->area_R->capac; calc_B0_B1(area, &B0, &B1); x = area->L_StubLen; tL = JS[0][0].max + K[H_]*x*x+B0*x; x = area->R_StubLen; tR = JS[1][0].max + K[H_]*x*x+B1*x; diff = tMAX(0, area->dist - (area->L_StubLen+area->R_StubLen)); calc_merge_distance(PURES[H_], PUCAP[H_],cap0,tL, cap1,tR,diff,d0,d1); /* just for check */ calc_merge_pt_delay_sub(area, *d0, *d1); area->L_EdgeLen = *d0 + area->L_StubLen; area->R_EdgeLen = *d1 + area->R_StubLen; } /****************************************************************************/ /* */ /****************************************************************************/ void set_ClusterDelay_CASE1(AreaType *area0, AreaType *area1, double L, double delay) { double r,c,A,B,C,x, t; r = PURES[H_]; c = PUCAP[H_]; A = r*c; B = area0->R_buffer*c+r*area0->unbuf_capac-r*c*L-r*C_buffer; C = K[H_]*L*L+r*C_buffer*L+ delay - area1->ClusterDelay; x = sol_equation(A,B,C); if (x>= L) { area0->ClusterDelay = area1->ClusterDelay; } else { t = delay + area0->R_buffer*c*x+ r*x*(c*x/2+area0->unbuf_capac); assert( t >= area0->ClusterDelay - FUZZ); area0->ClusterDelay = t; } } /****************************************************************************/ /* area_L is unbuffered, area_R is buffered. */ /****************************************************************************/ void set_ClusterDelay_CASE2(AreaType *area_L,AreaType *area_R, double x, double t0, double t1) { double t, r, c; assert(area_L->R_buffer == 0); assert(area_R->R_buffer > 0); r = PURES[H_]; c = PUCAP[H_]; t = t0 + r*x*(c*x/2+area_L->capac); double origB = gBoundedSkewTree->Orig_Skew_B() ; if (1 || origB == 0) assert(t<=area_R->ClusterDelay + FUZZ); area_R->ClusterDelay = tMAX(t1, t); assert(area_L->ClusterDelay == 0); assert(area_L->capac == area_L->unbuf_capac); assert(area_R->ClusterDelay > 0); } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ void print_current_time() { long current_time; time(&current_time); printf("\nCurrent Time: %s \n",ctime(&current_time)); fflush(stdout); } /******************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /******************************************************************/ void rm_same_JR_turn_pts(int side) { unsigned n = n_JR[side]; unsigned j=1; for (unsigned i=1;i<n;++i) { PointType pt1 = JR[side][j-1]; PointType pt2 = JR[side][i]; if (!same_Point(pt1,pt2)) { JR[side][j++] = pt2; } } n_JR[side] = j; } /***********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /***********************************************************************/ void rm_same_pts_on_mr(AreaType *area) { int i,j,n; PointType pt, pre_pt; n = area->n_mr; for (i=1, j = 1;i<n;++i) { /* remove same turn points on mr */ pt = area->mr[i]; pre_pt = area->mr[j-1]; if (!same_Point(pt,pre_pt) ) { area->mr[j++] = pt ; } } if (j>1 && same_Point(area->mr[0],area->mr[j-1]) ) j--; area->n_mr = j; } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ int rm_same_pts_on_sorted_array(PointType q[], int n) { int i,j; PointType pt, pre_pt; for (i=1, j = 1;i<n;++i) { /* remove same turn points on mr */ pt = q[i]; pre_pt = q[j-1]; if (!same_Point(pt,pre_pt) ) { q[j++] = pt ; } } /* */ if (j>1 && same_Point(q[0],q[j-1]) ) j--; return(j); } /****************************************************************************/ /* */ /****************************************************************************/ static int point_compare_dec(const void *p, const void *q) { PointType *pp, *qq; /* if (p->t < q->t) { return(1); } else if (p->t > q->t ) { return(-1); } else { return(0); } */ pp = (PointType *) p; qq = (PointType *) q; return( (pp->t < qq->t) ? YES: NO); } /******************************************************************/ /* */ /******************************************************************/ void check_JR_turn_pts_coor(AreaType *area, int side) { int i,n, type; PointType p,p0,p1,q0,q1; n = n_JR[side]; assert(n>=2); p0 = JR[side][0]; p1 = JR[side][n-1]; q0 = area->line[side][0]; q1 = area->line[side][1]; assert(same_Point(p0,q0) && same_Point(p1,q1)); type = areaJS_line_type(area); for (i=1;i<n;++i) { p = JR[side][i]; if (type == VERTICAL ) { assert(equal(p.x, p0.x)); JR[side][i].x = p0.x; } else if (type == HORIZONTAL ) { assert(equal(p.y, p0.y)); JR[side][i].y = p0.y; } else if (type == TILT || type == FLAT) { assert(i==n-1 || pt_on_line_segment(p,p0,p1)); } else { assert(0); } } } /******************************************************************/ /* initialize JR[side][i] with turning pt child->mr[j] */ /* for the case when area->line{0] and area->line{1] are */ /* parallel hori./vert. lines */ /******************************************************************/ void add_JS_pts(AreaType *area,int side, AreaType *child) { int i, n; assert(!same_Point(JS[side][0],JS[side][1])); n=2; for (i=0;i<child->n_mr;++i) { if ( pt_on_line_segment(child->mr[i],JS[side][0],JS[side][1]) && !same_Point(child->mr[i],JS[side][0]) && !same_Point(child->mr[i],JS[side][1]) ) { JS[side][n] = child->mr[i]; n++; } } n_JS[side] = n; assert( n <= MAX_TURN_PTS); sort_pts_on_line(JS[side], n_JS[side]); } /******************************************************************/ /* check if pt = any point in q[] */ /******************************************************************/ int repeated_pts(PointType q[], int n, PointType pt) { int i; for (i=0;i<n;++i) { if (same_Point(pt,q[i])) { return(i); } } return(NIL); } /***********************************************************************/ /* */ /***********************************************************************/ void add_LINEAR_turn_point_sub(int side,double d0,double d1, PointType p0,PointType p1) { int n; double d; PointType pt, q; if (d0<=0 || d1<=0 ) return; d = d0+d1; n = n_JR[side]; pt.x = (p0.x*d1 + p1.x*d0)/d; pt.y = (p0.y*d1 + p1.y*d0)/d; if (n==3) { q = JR[side][2]; if (same_Point(pt,q)) { return; } } pt.max = tMAX(p0.max - d0, p1.max-d1); pt.min = tMIN(p0.min + d0, p1.min+d1); JR[side][n] = pt; n_JR[side] = n+1; } /***********************************************************************/ /* */ /***********************************************************************/ void add_LINEAR_turn_point(AreaType *area) { int side; PointType p0,p1; double d,t ; for (side=0;side < 2; ++side) { p0 = JR[side][0]; p1 = JR[side][1]; d = Point_dist(p0,p1); t = p0.max-p1.max; add_LINEAR_turn_point_sub(side,(d+t)/2, (d-t)/2,p0,p1); t = p0.min-p1.min; add_LINEAR_turn_point_sub(side,(d-t)/2, (d+t)/2,p0,p1); sort_pts_on_line(JR[side], n_JR[side]); /* rm_same_JR_turn_pts(side); */ n_JR[side] = rm_same_pts_on_sorted_array( JR[side], n_JR[side]); if (CHECK==1) { check_JR_turn_pts_coor(area, side); } } } /******************************************************************/ /* */ /******************************************************************/ double delay_pt_JS(int JS_side, int x, int side, int i, double t_from[]) { double ans; if (i==0) { /* max-delay */ ans = JS[side][x].max; } else { /* min_delay */ ans = JS[side][x].min; } if (JS_side != side) { ans += t_from[side]; } return(ans); } /***********************************************************************/ /* */ /***********************************************************************/ double calc_A(PointType *p0, PointType *p1) { double A; if (equal(p0->x, p1->x)) { /* JS is vertical */ assert( !equal(p0->y, p1->y) ); A = K[V_]; } else { /* JS is horizontal */ assert( equal(p0->y, p1->y) ); A = K[H_]; } return(A); } /***********************************************************************/ /* add one turn point on JR due to the changing slopes of max- or min- */ /* delay (depending on the value of y) between JR[side][x] and */ /* JR[side][x+1] */ /***********************************************************************/ void add_turn_point(int side,int x,int y, double t_from[]) { PointType pt1, pt2, new_pt; int i,j; double d,d1,d2, B[2][2], t2,t1, tmp[2][2]; double A; pt1 = JR[side][x]; pt2 = JR[side][x+1]; A = calc_A(&pt1, &pt2); d = Point_dist(JR[side][x],JR[side][x+1]); assert(!equal(d,0)); for (i=0;i<2;++i) { for (j=0;j<2;++j) { t1 = delay_pt_JS(side,x, i,j, t_from); t2 = delay_pt_JS(side,x+1,i,j, t_from); B[i][j] = (t2-t1)/d-A*d; } } d1 = (delay_pt_JS(side,x,0,y, t_from) - delay_pt_JS(side,x,1,y, t_from) ) /(B[1][y]-B[0][y]); assert(d1 > 0 && d1 < d); d2 = d - d1; /* calc coordinate of new_pt */ new_pt = pt2; new_pt.x = (pt1.x*d2 + pt2.x*d1)/d; new_pt.y = (pt1.y*d2 + pt2.y*d1)/d; /* calc delays of new_pt */ for (i=0;i<2;++i) { for (j=0;j<2;++j) { tmp[i][j] = delay_pt_JS(side,x, i,j, t_from) + A*d1*d1+B[i][j]*d1; } } new_pt.max = tMAX(tmp[0][0],tmp[1][0]); new_pt.min = tMIN(tmp[0][1],tmp[1][1]); assert(equal(tmp[0][y],tmp[1][y])); JR[side][(n_JR[side])++] = new_pt; assert(n_JR[side] <= MAX_TURN_PTS); } /******************************************************************/ /* add turn points on JR[side] due to changing slopes of delays */ /******************************************************************/ void add_more_JR_pts(AreaType *area, int side, double t_from[]) { int i, n; double t; n = n_JR[side]; for (i=0;i<n-1;++i) { /* for each point */ t = (JS[side][i].max - JS[1-side][i].max - t_from[1-side])* (JS[side][i+1].max - JS[1-side][i+1].max - t_from[1-side]); if ( t < - FUZZ ) { add_turn_point(side,i,0, t_from); } t = (JS[side][i].min - JS[1-side][i].min - t_from[1-side])* (JS[side][i+1].min - JS[1-side][i+1].min - t_from[1-side]); if ( t < - FUZZ ) { add_turn_point(side,i,1, t_from); } } sort_pts_on_line(JR[side], n_JR[side]); /* rm_same_JR_turn_pts(side); */ n_JR[side] = rm_same_pts_on_sorted_array( JR[side], n_JR[side]); if (CHECK==1) { check_JR_turn_pts_coor(area, side); } } /******************************************************************/ /* */ /******************************************************************/ void print_JR_slopes(int n, double *skew_rate, double *maxD_slope, double *minD_slope) { printf("maxD_slope: "); print_double_array(maxD_slope, n-1); printf("minD_slope: "); print_double_array(minD_slope, n-1); printf("skew_rate: "); print_double_array(skew_rate, n-1); assert(0); } /******************************************************************/ /* check turn_pts on JR[side] */ /******************************************************************/ void check_Elmore_delay_skew(PointType q[], int n, double delta) { int i; double d1,d2, t, t1,t2, skew_rate[MAX_TURN_PTS-1]; double maxD_slope[MAX_TURN_PTS-1], minD_slope[MAX_TURN_PTS-1]; double A; PointType p0,p1,p2; assert(n>=2); p0 = q[0]; A = calc_A(&(q[0]), &(q[1])); for (i=0;i<n-1;++i) { p1 = q[i]; p2 = q[i+1]; d1 = Point_dist(p1,p0); d2 = Point_dist(p2,p0); t1 = d2 - d1; t2 = d2 + d1; assert(t1 > FUZZ); skew_rate[i] = (pt_skew(p2) - pt_skew(p1) ) / t1; maxD_slope[i] = (p2.max-p1.max)/t1 -A*t2; minD_slope[i] = (p2.min-p1.min)/t1 -A*t2; } /* slopes of max-delays must be monotone increasing */ for (i=0;i<n-2;++i) { t1 = maxD_slope[i]; t2 = maxD_slope[i+1]; if ( t1 > t2+100.0*FUZZ) { print_JR_slopes(n, skew_rate, maxD_slope, minD_slope); } } /* slopes of min-delays must be monotone decreasing */ for (i=0;i<n-2;++i) { t1 = minD_slope[i]; t2 = minD_slope[i+1]; if ( t1 < t2-100.0*FUZZ) { print_JR_slopes(n, skew_rate, maxD_slope, minD_slope); } } /* slopes of skew must be strictly monotone increasing */ for (i=0;i<n-2;++i) { t = skew_rate[i+1] - skew_rate[i]; if ( t < -100.0*delta ) { print_JR_slopes(n, skew_rate, maxD_slope, minD_slope); } } } /***********************************************************************/ /* */ /***********************************************************************/ void set_pt_coord_case2(int side_loc, PointType *pt, double d) { if (side_loc==LEFT) { pt->x += d; } else if (side_loc==RIGHT) { pt->x -= d; } else if (side_loc==BOTTOM) { pt->y += d; } else { pt->y -= d; } } /******************************************************************/ /* */ /******************************************************************/ void calc_JS_pt_delays(int side, PointType *pt) { int i; for (i=0;i<n_JS[side] -1 ;++i) { if ( pt_on_line_segment(*pt,JS[side][i], JS[side][i+1]) ) { break; } } assert( i < n_JS[side] -1 ); calc_pt_delays(NULL, pt, JS[side][i], JS[side][i+1]); } /******************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /* add turn points on JS[o_side] to JR[side] */ /******************************************************************/ void add_more_JS_pts(int side, double dist, int n) { int i, j, k, o_side; o_side = 1- side; k = n_JS[side]; for (i=0;i<n ;++i) { JS[side][k] = JS[o_side][i]; j = calc_side_loc(o_side); set_pt_coord_case2(j, &(JS[side][k]),dist); j = repeated_pts(JS[side], n_JS[side], JS[side][k]); if (j <0) { assert( k < MAX_TURN_PTS); calc_JS_pt_delays(side, &(JS[side][k])); k++; } } n_JS[side] = k; } /******************************************************************/ /* */ /******************************************************************/ void calc_new_delay(AreaType *area, int side, PointType *pt) { double tL, tR; tL = pt_delay_increase(Gamma, area->area_L->capac,&(area->line[0][side]), pt); tR = pt_delay_increase(Gamma, area->area_R->capac,&(area->line[1][side]), pt); pt->max = tMAX(area->line[0][side].max + tL, area->line[1][side].max + tR); pt->min = tMIN(area->line[0][side].min + tL, area->line[1][side].min + tR); } /******************************************************************/ /* find the corner points of Joining Box. */ /******************************************************************/ void calc_JR_corner_sub2(int i, double x0,double y0,double x1,double y1) { if ( (x0-x1)*(y0-y1) < 0 ) { if (i==0) { JR_corner[i].x = tMAX(x0,x1); JR_corner[i].y = tMAX(y0,y1); } else { JR_corner[i].x = tMIN(x0,x1); JR_corner[i].y = tMIN(y0,y1); } } else { if (i==0) { JR_corner[i].x = tMIN(x0,x1); JR_corner[i].y = tMAX(y0,y1); } else { JR_corner[i].x = tMAX(x0,x1); JR_corner[i].y = tMIN(y0,y1); } } } /******************************************************************/ /* find the corner points of Joining Box. */ /******************************************************************/ void calc_JR_corner_sub1(AreaType *area, int i) { double x0,y0, x1,y1; x0 = JS[0][i].x; y0 = JS[0][i].y; x1 = JS[1][i].x; y1 = JS[1][i].y; if (JR_corner_exist(i)==YES) { calc_JR_corner_sub2(i,x0, y0, x1,y1); calc_new_delay(area, i, &(JR_corner[i])); assert(equal(JR_corner[i].x, tMAX(x0,x1)) || equal(JR_corner[i].x, tMIN(x0,x1)) ); assert(equal(JR_corner[i].y, tMAX(y0,y1)) || equal(JR_corner[i].y, tMIN(y0,y1)) ); } } /******************************************************************/ /* find the corner points of Joining Box. */ /******************************************************************/ void calc_JR_corner(AreaType *area) { int i; if (!equal(JS[0][0].y,JS[0][1].y)) { assert(JS[0][0].y > JS[0][1].y); } if (!equal(JS[1][0].y,JS[1][1].y)) { assert(JS[1][0].y > JS[1][1].y); } if (area_Manhattan_arc_JS(area) && !equal(area->dist,0)) { for (i=0;i<2;++i) { calc_JR_corner_sub1(area, i); } } } /******************************************************************/ /* calc all the turn_pts JR[side][i], side=0,1, i =0,...,n when JS are PARA_MANHATTAN_ARC; */ /******************************************************************/ void calc_JR_endpoints(AreaType *area) { assert(Same_Point_delay(&(JS[0][0]), &(area->line[0][0]))); assert(Same_Point_delay(&(JS[0][1]), &(area->line[0][1]))); assert(Same_Point_delay(&(JS[1][0]), &(area->line[1][0]))); assert(Same_Point_delay(&(JS[1][1]), &(area->line[1][1]))); JR[0][0].x = JS[0][0].x; JR[0][1].x = JS[0][1].x; JR[1][0].x = JS[1][0].x; JR[1][1].x = JS[1][1].x; JR[0][0].y = JS[0][0].y; JR[0][1].y = JS[0][1].y; JR[1][0].y = JS[1][0].y; JR[1][1].y = JS[1][1].y; calc_new_delay(area, 0, &(JR[0][0])); calc_new_delay(area, 0, &(JR[1][0])); calc_new_delay(area, 1, &(JR[0][1])); calc_new_delay(area, 1, &(JR[1][1])); } /***********************************************************************/ /* remove redundant turn points : JR[side][i] */ /***********************************************************************/ void rm_redundant_JR_pt(int side) { int i,k,n; PointType p1,p2, pt[MAX_TURN_PTS]; double d; n = n_JR[side]; assert(n>=2); for (i=0;i<n-1;++i) { p1 = JR[side][i]; p2 = JR[side][i+1]; d = Point_dist(p1,p2); assert(d >= FUZZ); JR[side][i].t= (pt_skew(p2)- pt_skew(p1) )/d; } pt[0]=JR[side][0]; k=1; for (i=1;i<n-1;++i) { p1 = pt[k-1]; p2 = JR[side][i]; if (equal(p1.t,p2.t) ) { /* p2 is a redundant turn point. */ } else if (p1.t > p2.t) { /* skew slope must be strictly monotone increasing, */ /* i.e., skew curve must be convex */ check_Elmore_delay_skew(JR[side], n_JR[side], FUZZ); assert(0); } else { pt[k++] = p2; } } pt[k++] = JR[side][n-1]; for (i=0;i<k;++i) { JR[side][i] = pt[i]; assert(pt[i].max > -FUZZ); assert(pt[i].min > -FUZZ); } n_JR[side] = k; } /******************************************************************/ /* */ /******************************************************************/ void calc_new_rect_JS_sub(AreaType *area,int side, double dist, double delay) { int i, n, loc; n = n_JS[side]; loc = calc_side_loc(side); for (i=0;i<n ;++i) { set_pt_coord_case2(loc, &(JS[side][i]),dist); JS[side][i].max += delay; JS[side][i].min += delay; } for (i=0;i<2;++i) { set_pt_coord_case2(loc, &(area->line[side][i]),dist); area->line[side][i].max += delay; area->line[side][i].min += delay; } } /******************************************************************/ /* */ /******************************************************************/ double calc_t_inc(AreaType *area, double d0) { double t0, r, c; r = PURES[H_]; c = PUCAP[H_]; t0 = d0*r*(d0*c/2+area->unbuf_capac) + area->R_buffer*c*d0; return(t0); } /******************************************************************/ /* */ /******************************************************************/ void calc_new_rect_JS(AreaType *area, AreaType *area_L, AreaType *area_R) { double d, d0, d1, t0, t1; t0 = calc_t_inc(area_L, area->L_StubLen); t1 = calc_t_inc(area_R, area->R_StubLen); d0 = area->L_StubLen; d1 = area->R_StubLen; d = area->dist ; area->dist = tMAX(0,d-d0-d1); if (d0+d1 >= d ) { if (d0>=d/2 && d1 >= d/2) { d0 = d1 = d/2; } else if (d0 <= d1 ) { d1 = d - d0; } else { d0 = d - d1; } area->L_EdgeLen = area->L_StubLen; area->R_EdgeLen = area->R_StubLen; } else { area->L_EdgeLen = area->R_EdgeLen = NIL; } calc_new_rect_JS_sub(area, 0, d0, t0); calc_new_rect_JS_sub(area, 1, d1, t1); } /******************************************************************/ /* calc all the turn_pts JR[side][i], side=0,1, i =0,...,n */ /* when JS are parallel vertical / horizontal lines */ /******************************************************************/ void calc_JR_case2(AreaType *area, AreaType *area_L,AreaType *area_R) { double t_from[2] ; int i, j; add_JS_pts(area, 0, area_L); add_JS_pts(area, 1, area_R); i = n_JS[0]; j = n_JS[1]; add_more_JS_pts(0, area->dist, j); add_more_JS_pts(1, area->dist, i); sort_pts_on_line(JS[0], n_JS[0]); sort_pts_on_line(JS[1], n_JS[1]); assert(n_JS[0]==n_JS[1]); if (CHECK) check_Elmore_delay_skew(JS[0], n_JS[0], FUZZ); if (CHECK) check_Elmore_delay_skew(JS[1], n_JS[1], FUZZ); t_from[0]=pt_delay_increase(Gamma, area_L->capac, &(JS[0][0]), &(JS[1][0]) ); t_from[1]=pt_delay_increase(Gamma, area_R->capac, &(JS[1][0]), &(JS[0][0]) ); for (i=0;i<2;++i) { n_JR[i] = n_JS[i]; for (j=0;j<n_JR[i];++j) { JR[i][j].x = JS[i][j].x; JR[i][j].y = JS[i][j].y; JR[i][j].max = tMAX(JS[i][j].max, JS[1-i][j].max+t_from[1-i]); JR[i][j].min = tMIN(JS[i][j].min, JS[1-i][j].min+t_from[1-i]); } } if (CHECK) check_Elmore_delay_skew(JR[0], n_JR[0], FUZZ); if (CHECK) check_Elmore_delay_skew(JR[1], n_JR[1], FUZZ); /* rm_same_JR_turn_pts(0); rm_same_JR_turn_pts(1); */ n_JR[0] = rm_same_pts_on_sorted_array( JR[0], n_JR[0]); n_JR[1] = rm_same_pts_on_sorted_array( JR[1], n_JR[1]); if (CHECK==1) { check_JR_turn_pts_coor(area, 0); check_JR_turn_pts_coor(area, 1); } add_more_JR_pts(area, 0, t_from); add_more_JR_pts(area, 1, t_from); rm_redundant_JR_pt(0); rm_redundant_JR_pt(1); } /******************************************************************/ /* */ /******************************************************************/ void check_calc_JR_case2(AreaType *area) { check_JR_turn_pts_coor(area,0); check_JR_turn_pts_coor(area,1); bool linear = gBoundedSkewTree->LinearDelayModel () ; if ( linear ) { check_JR_linear_delay_skew(0); check_JR_linear_delay_skew(1); } else { check_Elmore_delay_skew(JR[0], n_JR[0], 0); check_Elmore_delay_skew(JR[1], n_JR[1], 0); } } /******************************************************************/ /* add the endpoints of fms of JR[side][i] */ /******************************************************************/ void add_fms_of_JR_sub(PointType pt0,PointType pt1, PointType *pt) { double d0,d1,d; d = Point_dist(pt0,pt1); assert(d > FUZZ); d0 = (Skew_B-pt_skew(pt0))*d/(pt_skew(pt1)-pt_skew(pt0) ); d1 = d-d0; *pt = pt0; pt->x = (pt0.x*d1+pt1.x*d0)/d; pt->y = (pt0.y*d1+pt1.y*d0)/d; calc_pt_delays(NULL, pt, pt0,pt1); assert(equal( pt_skew(*pt), Skew_B)); } /******************************************************************/ /* add the endpoints of fms of JR[side][i] */ /******************************************************************/ void add_fms_of_JR(int side) { PointType pt, pt0, pt1, new_JR[MAX_TURN_PTS]; int i, j, n; double t1, t2; j = 0; n = n_JR[side]; for (i=0;i<n-1;++i) { new_JR[j++] = pt0 = JR[side][i]; pt1 = JR[side][i+1]; t1 = pt_skew(pt0) - Skew_B; t2 = pt_skew(pt1) - Skew_B; if ( t1*t2 < 0 && !equal(t1,0) && !equal(t2, 0) ) { /* add one point with skew==Skew_B */ add_fms_of_JR_sub(pt0,pt1,&pt); new_JR[j++] = pt; } } new_JR[j++] = pt1; if (j>n) { /* If there are any points with skew == Skew_B*/ n_JR[side] = j; if (j>MAX_TURN_PTS) { printf("%d JR turn points \n",j); } assert(j<=MAX_TURN_PTS); for (i=0;i<j;++i) JR[side][i] = new_JR[i]; } } /******************************************************************/ /* */ /******************************************************************/ void check_new_JS(AreaType *area) { double origB = gBoundedSkewTree->Orig_Skew_B() ; if (area->area_L->R_buffer>0 ) { if ( origB == 0) { assert(equal(JS[0][0].max, area->area_L->ClusterDelay)); } } else { assert(area->L_StubLen==0); } if (area->area_R->R_buffer>0 ) { if ( origB == 0) { assert(equal(JS[1][0].max, area->area_R->ClusterDelay)); } } else { assert(area->R_StubLen==0); } } /******************************************************************/ /* calculate new JS due to StubLength of non-zero length */ /******************************************************************/ void calc_new_JS(AreaType *area) { int i; double b[2], t, x[2]; TrrType trrL, trrR, trr, msL, msR; /* first, calculate new L_MS and R_MS */ if (area->L_StubLen+area->R_StubLen >= area->dist) { /* Case I: detour wiring happens; */ build_trr(&L_MS, area->L_StubLen, &trrL); build_trr(&R_MS, area->R_StubLen, &trrR); make_intersect(&trrL, &trrR, &trr); make_1D_TRR(&trr, &msL); msR = msL; area->L_EdgeLen = area->L_StubLen; area->R_EdgeLen = area->R_StubLen; } else { build_trr(&L_MS, area->L_StubLen, &trrL); build_trr(&R_MS, area->dist - area->L_StubLen, &trrR); make_intersect(&trrL, &trrR, &msL); build_trr(&L_MS, area->dist - area->R_StubLen, &trrL); build_trr(&R_MS, area->R_StubLen, &trrR); make_intersect(&trrL, &trrR, &msR); area->L_EdgeLen = area->R_EdgeLen = NIL; } ms2line(&msL, &(JS[0][1]), &(JS[0][0])); ms2line(&msR, &(JS[1][1]), &(JS[1][0])); area->dist = ms_distance(&msL, &msR); b[0] = calc_x(area->area_L); b[1] = calc_x(area->area_R); x[0] = area->L_StubLen; x[1] = area->R_StubLen; for (i=0;i<2;++i) { t = b[i]*x[i] + K[H_]*x[i]*x[i]; JS[i][1].max = JS[i][0].max = t + JS[i][0].max; JS[i][1].min = JS[i][0].min = t + JS[i][0].min; } JS_processing(area); check_new_JS(area); } /******************************************************************/ /* calc all the turn_pts JR[side][i], side=0,1, i =0,...,n */ /******************************************************************/ void calc_JR(AreaType *area, AreaType *area_L,AreaType *area_R) { if (area_Manhattan_arc_JS(area)) { /* JS's are para Manhattan arcs */ calc_JR_endpoints(area); } else { /* JS's are para rectilinear lines */ bool linear = gBoundedSkewTree->LinearDelayModel () ; if ( linear ) { calc_JR_endpoints(area); add_LINEAR_turn_point(area); } else { calc_JR_case2(area, area_L,area_R ); } if (CHECK==1) check_calc_JR_case2(area); add_fms_of_JR(0); add_fms_of_JR(1); } } /******************************************************************/ /* */ /******************************************************************/ double calc_JR_minskew(int i) { int j; double min_skew = DBL_MAX; for (j=0;j<n_JR[i] ;++j) { min_skew = tMIN(pt_skew(JR[i][j]),min_skew); } return(min_skew); } /********************************************************************/ /* set node->area[node->ca].mr[x] = minimum skew section of JR[side][x] */ /********************************************************************/ static int calc_mss ( AreaType *area ) { int i,j,n_pt,n ; double min_skew; min_skew = DBL_MAX; area->n_mr = 0; /* fix for bug reported by Nate on 8-02-02 */ /* The test case is in BENCHMARKS/bug_nate_8_02_02 */ /* The bug happens only when area->dist==0, or equivalently calc_JR_minskew(0 == calc_JR_minskew(1) Because of this bug, I added the detour at the incorrect child nodes. */ /* if (equal(area->dist,0)) { n_sides = 1; } else { n_sides = 2; } if (calc_JR_minskew(0) < calc_JR_minskew(1)) { i = 0; } else { i = 1; } */ if (equal(area->dist,0)) { /* break tie */ i = (area->line[0][0].max > area->line[1][0].max)?0:1 ; } else { i = (calc_JR_minskew(0) < calc_JR_minskew(1))? 0: 1; } min_skew = calc_JR_minskew(i); n = n_JR[i]; n_pt =0; for (j=0;j<n;++j) { /* for each monotone section of each side */ PointType pt = JR[i][j]; if ( equal(pt_skew(pt),min_skew) ) { area->mr[n_pt++] =pt; } } area->n_mr = n_pt; return i ; } /******************************************************************/ /* */ /******************************************************************/ void check_set_detour_EdgeLen(AreaType *area, PointType pt0, PointType pt1) { int line0type; double tL, tR, skew; line0type = calc_line_type(pt0,pt1); if (line0type != MANHATTAN_ARC) return; if (area->L_EdgeLen == 0 ) { tL = 0; tR = _pt_delay_increase(Gamma, area->R_EdgeLen, pt1.t, &pt1, &pt0); } else { tL = _pt_delay_increase(Gamma, area->L_EdgeLen, pt0.t, &pt0, &pt1); tR = 0; } skew = tMAX(pt0.max+tL, pt1.max+tR) - tMIN(pt0.min+tL, pt1.min+tR); assert(equal(skew, Skew_B)); } /********************************************************************/ /* set edgelengths for node's children when detour wireing needed */ /********************************************************************/ void set_detour_EdgeLen(AreaType *area, const int side ) { PointType pt0, pt1, tmpPT; double d0, d1, t, h, v ; pt0 = area->line[0][0]; pt1 = area->line[1][0]; pt0.t = area->area_L->capac; pt1.t = area->area_R->capac; t = pt_skew(area->mr[0]) - Skew_B; assert(t > 0); h = ABS(pt0.x-pt1.x); v = ABS(pt0.y-pt1.y); /* fix for bug reported by nate on 7-27-02 */ /* if (area->line[0][0].max > area->line[1][0].max) { */ if ( side ==0 ) { /* detour at R-sided child */ pt1.max = pt0.max - t - calc_delay_increase(Gamma, pt1.t,h,v); calc_Bal_of_2pt(&pt0,&pt1,0,0, &d0, &d1, &tmpPT); /* fix the bug reported by Nate on 8-14-02 */ /* d0 may not be identical to 0 on SUN/Solairs platform */ assert( equal(d0,0) ); area->L_EdgeLen = 0; area->R_EdgeLen = tMAX(area->dist, d1); } else { /* detour at L-sided child */ pt0.max = pt1.max - t - calc_delay_increase(Gamma, pt0.t,h,v); calc_Bal_of_2pt(&pt0,&pt1,0,0, &d0, &d1, &tmpPT); /* fix the bug reported by Nate on 8-14-02 */ /* d1 may not be identical to 0 on SUN/Solairs platform */ assert( equal(d1,0) ); area->L_EdgeLen = tMAX(area->dist, d0); area->R_EdgeLen = 0; } if (0) check_set_detour_EdgeLen(area, pt0, pt1); } /********************************************************************/ /* set min-delay of node->area[node->ca].mr(i) */ /********************************************************************/ void set_delay_for_mss(AreaType *area) { int i; for (i=0;i<area->n_mr;++i) { area->mr[i].min = area->mr[i].max - Skew_B; } } /******************************************************************/ /* */ /******************************************************************/ void add_Bal_Pt(int side,PointType p) { int n; n = N_Bal_Pt[side]; if (n==0 || !same_Point(p,Bal_Pt[side][0])) { Bal_Pt[side][n++] = p; } N_Bal_Pt[side] = n; } /********************************************************************/ /* calculate the points with d0 to area->line[0] and d1 to line[1] */ /********************************************************************/ void calc_coordinate(AreaType *area,int side, double d0,double d1,PointType *pts) { PointType tmp, q0,q1; double d; q0 = area->line[0][side]; q1 = area->line[1][side]; if (equal(q0.x,q1.x) || equal(q0.y,q1.y) ) { assert(JR_corner_exist(side)==NO); calc_pt_coor_on_a_line(q0,q1,d0,d1,pts); } else { assert(JR_corner_exist(side)==YES); tmp = JR_corner[side]; d = Point_dist(tmp,q0); if (d >= d0) { calc_pt_coor_on_a_line(q0,tmp,d0,d-d0,pts); } else { calc_pt_coor_on_a_line(tmp,q1,d0-d,d1,pts); } } } /******************************************************************/ /* */ /******************************************************************/ void new_add_Bal_Pt(int side,PointType *pt, double d0, double d1) { int n; if ( equal(d0,0) || equal(d1,0) ) { return; } n = N_Bal_Pt[side]; if (n==0 || !same_Point(*pt,Bal_Pt[side][0])) { Bal_Pt[side][n++] = *pt; } N_Bal_Pt[side] = n; } /******************************************************************/ /* */ /******************************************************************/ void check_cal_Bal_Pt_sub(AreaType *area, PointType *q,int side) { PointType q0, q1 ; double max_x, max_y, min_x, min_y; q0 = area->line[0][side]; q1 = area->line[1][side]; max_x = max4(area->line[0][0].x,area->line[0][1].x, area->line[1][0].x,area->line[1][1].x); max_y = max4(area->line[0][0].y,area->line[0][1].y, area->line[1][0].y,area->line[1][1].y); min_x = min4(area->line[0][0].x,area->line[0][1].x, area->line[1][0].x,area->line[1][1].x); min_y = min4(area->line[0][0].y,area->line[0][1].y, area->line[1][0].y,area->line[1][1].y); if (equal(q0.x, q1.x)) { assert(equal(q->x, q0.x)); } else if (equal(q0.y, q1.y)) { assert(equal(q->y, q0.y)); } else if ((q0.x-q1.x)*(q0.y-q1.y) < 0 ) { if (side==0) { assert(equal(q->x,max_x) || equal(q->y, max_y)); } else { assert(equal(q->x,min_x) || equal(q->y, min_y)); } } else { if (side==0) { assert(equal(q->x,min_x) || equal(q->y, max_y)); } else { assert(equal(q->x,max_x) || equal(q->y, min_y)); } } assert(pt_skew(*q) < Skew_B + FUZZ); } /******************************************************************/ /* */ /******************************************************************/ void cal_Bal_Pt_sub(AreaType *area, int side) { PointType q0, q1, pt0, pt1; double d0, d1; int bal_delay_id, i; q0 = area->line[0][side]; q1 = area->line[1][side]; q0.t = area->area_L->capac; q1.t = area->area_R->capac; if ((q0.x-q1.x)*(q0.y-q1.y) < 0 ) { bal_delay_id = 1 - side; } else { bal_delay_id = side; } calc_Bal_of_2pt(&q0, &q1, 0, bal_delay_id,&d0,&d1,&pt0); new_add_Bal_Pt(side, &pt0, d0, d1); calc_Bal_of_2pt(&q0, &q1, 1, bal_delay_id,&d0,&d1,&pt1); new_add_Bal_Pt(side, &pt1, d0, d1); for (i=0;i<N_Bal_Pt[side];++i) { calc_new_delay(area, side, &(Bal_Pt[side][i])); check_Point(&(Bal_Pt[side][i])); check_cal_Bal_Pt_sub(area, &(Bal_Pt[side][i]), side); } } /******************************************************************/ /* */ /******************************************************************/ void cal_Bal_Pt(AreaType *area) { N_Bal_Pt[0] = 0; N_Bal_Pt[1] = 0; if (!equal(area->dist, 0)) { cal_Bal_Pt_sub(area, 0); cal_Bal_Pt_sub(area, 1); } } /******************************************************************/ /* */ /******************************************************************/ void add_fms_of_line(int side,PointType q[5], int *n) { int i, m; m = n_Fms_Pt[side]; for (i=0;i<m;++i) { q[(*n)++] = Fms_Pt[side][i]; } } /******************************************************************/ /* */ /******************************************************************/ void add_Fms_Pt(int side,PointType *p) { int n; n = n_Fms_Pt[side]; assert(n<2); if (n==0 || !same_Point(*p,Fms_Pt[side][0])) { Fms_Pt[side][n++] = *p; } n_Fms_Pt[side] = n; } /********************************************************************/ /* */ /********************************************************************/ void calc_Fms_of_line_sub(PointType *pt,PointType *q, PointType *ans) { double d, d1, sk0, sk1; sk0 = pt_skew(*pt); sk1 = pt_skew(*q); d = Point_dist(*pt, *q); d1 = d*(Skew_B-sk1)/(sk0-sk1); assert( d > FUZZ); assert( Skew_B-sk1 >= 0); assert( sk0-sk1 > FUZZ); calc_pt_coor_on_a_line(*pt,*q,d-d1,d1,ans); } /********************************************************************/ /* */ /********************************************************************/ int calc_Fms_of_line(AreaType *area, PointType pt, PointType q, int side) { PointType tmpPt, p1, p2; double sk; int i, ans = NO; sk = pt_skew(pt); if ( equal(sk, Skew_B) || sk <=Skew_B) { add_Fms_Pt(side, &pt); ans = YES; } else { for (i=0;i<N_Bal_Pt[side];++i) { if (Point_dist(pt, (Bal_Pt[side][i])) < Point_dist(pt,q) ) { check_Point(&(Bal_Pt[side][i])); q = Bal_Pt[side][i]; } } sk = pt_skew(q); if ( equal(sk,Skew_B) ) { add_Fms_Pt(side, &q); ans = YES; } else if ( sk < Skew_B) { calc_Fms_of_line_sub(&pt,&q, &tmpPt); calc_new_delay(area, side, &tmpPt); if (!equal(pt_skew(tmpPt), Skew_B)) { p1 = pt; p2 = q; calc_new_delay(area, side, &p1); calc_new_delay(area, side, &p2); assert(equal(pt_skew(tmpPt), Skew_B)); } add_Fms_Pt(side, &tmpPt); ans = YES; } } return(ans); } /********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /********************************************************************/ void cal_Fms_Pt_sub(AreaType *area,int side){ int n0, n1, ans; PointType tmp[2]; n_Fms_Pt[side] = 0; if (side==0) { tmp[0]=JR[0][0]; tmp[1]=JR[1][0]; } else { n0 = n_JR[0]; n1 = n_JR[1]; tmp[0]=JR[0][n0-1]; tmp[1]=JR[1][n1-1]; } if (JR_corner_exist(side)) { ans = calc_Fms_of_line(area, tmp[0], JR_corner[side], side); if (ans==YES) { ans = calc_Fms_of_line(area, tmp[1], JR_corner[side], side); if (ans==NO) { ans = calc_Fms_of_line(area, JR_corner[side], tmp[0], side); assert(ans == YES); } } else { ans = calc_Fms_of_line(area, JR_corner[side], tmp[1], side); if (ans==YES) { ans = calc_Fms_of_line(area, tmp[1], JR_corner[side], side); assert(ans==YES); } } } else { ans = calc_Fms_of_line(area, tmp[0], tmp[1], side); if (ans) calc_Fms_of_line(area, tmp[1], tmp[0], side); } } /********************************************************************/ /* */ /********************************************************************/ void cal_Fms_Pt(AreaType *area, AreaType *area_L, AreaType *area_R) { int i; for (i=0;i<2;++i) { cal_Fms_Pt_sub(area, i); assert(N_Bal_Pt[i]==0 || n_Fms_Pt[i] > 0); } } /******************************************************************/ /* find the max- min-delay balance points on the line */ /******************************************************************/ void add_balance_pt(int side, PointType q[5], int *n) { int i, m; m = N_Bal_Pt[side]; for (i=0;i<m;++i) { q[(*n)++] = Bal_Pt[side][i]; } } /********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /********************************************************************/ void check_pts(AreaType *area, PointType q[], int n) { int i, type; for (i=0;i<n-1;++i) { type = calc_line_type(q[i],q[i+1]); if (type!=VERTICAL && type != HORIZONTAL){ for (i=0;i<n;++i) { print_Point(stdout, q[i]); } printf("\"corners\n"); if (JR_corner_exist(0)) { print_Point(stdout, JR_corner[0]); } if (JR_corner_exist(1)) { print_Point(stdout, JR_corner[1]); } exit(0); } } } /********************************************************************/ /* determine turn pts on the first or last line connecting JS[0]/JS[1] */ /********************************************************************/ void mr_between_JS(AreaType *area,int side, double cap[2]) { int i,j, n=0; PointType q[2], pt[5]; q[0]=area->line[0][side]; q[1]=area->line[1][side]; n=0; add_balance_pt(side, pt, &n); add_fms_of_line(side, pt, &n); if (JR_corner_exist(side)) { if (pt_skew((JR_corner[side])) <= Skew_B + FUZZ) { pt[n++] = JR_corner[side]; } } if (n==0) return; for (i=0;i<n;++i) { /* calculate the distance to JS[side] */ pt[i].t=Point_dist(pt[i],q[side]); } qsort(pt, n, sizeof(PointType), point_compare_dec); /* in decreasing order of distance to area->line[side] */ j = 1; for (i=1;i<n;++i) { if (equal(pt[j-1].t, pt[i].t)) { /* redundant points */ } else if (pt[j-1].t > pt[i].t) { pt[j++] = pt[i]; } else { assert(0); } } if (CHECK==1 && area_Manhattan_arc_JS(area)) check_pts(area, pt, j); n = area->n_mr; for (i=0;i<j;++i) { area->mr[i+n] = pt[i]; } area->n_mr += j; } /********************************************************************/ /* determine the necessary turn pts JR[side][i] */ /********************************************************************/ void mr_on_JS_sub(int side,int m[2]) { int n,o_n, o_side,m0,m1; PointType p0,q0; n = n_JR[side]; m0 = 1; o_side=(side+1)%2; p0 = JR[side][0]; q0 = JR[o_side][0]; if ( n_Fms_Pt[0] ==0 && pt_skew(p0) < pt_skew(q0) ) { for (m0=1;m0<n-1;++m0) { if ( equal(pt_skew(JR[side][m0]) ,Skew_B) ) { break; } } } p0 = JR[side][n-1]; o_n = n_JR[o_side]; q0 = JR[o_side][o_n-1]; m1 = n-2; if ( n_Fms_Pt[1] ==0 && pt_skew(p0) < pt_skew(q0) ) { for (m1=n-2;m1>=m0;--m1) { if ( equal(pt_skew(JR[side][m1]) ,Skew_B) ) { break; } } } m[0] = m0; m[1] = m1; } /*****************************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /*****************************************************************************/ void check_JR_linear_delay_skew(int side) { double maxD_slope[MAX_TURN_PTS-1], minD_slope[MAX_TURN_PTS-1]; double t1,t2, d, t, skew_rate[MAX_TURN_PTS-1]; PointType pt1,pt2; int i,n; n = n_JR[side]; for (i=0;i<n-1;++i) { pt1 = JR[side][i]; pt2 = JR[side][i+1]; d = Point_dist(pt1,pt2); maxD_slope[i] = (pt2.max - pt1.max ) / d; minD_slope[i] = (pt2.min - pt1.min ) / d; skew_rate[i] = (pt_skew(pt2)- pt_skew(pt1) ) / d; } for (i=0;i<n-1;++i) { t = ABS(skew_rate[i]); t1 = ABS(maxD_slope[i]); t2 = ABS(minD_slope[i]); if ( (!equal(t,2.0) && !equal(t,0.0)) || !equal(t1,1.0) || !equal(t2,1.0)){ print_JR_slopes(n_JR[side],skew_rate, maxD_slope, minD_slope); } } /* slopes of max-delays must be monotone increasing */ for (i=0;i<n-2;++i) { t1 = maxD_slope[i+1] - maxD_slope[i]; if ( !equal(t1,0.0) && !equal(t1,2.0) ) { print_JR_slopes(n_JR[side],skew_rate, maxD_slope, minD_slope); } } /* slopes of min-delays must be monotone decreasing */ for (i=0;i<n-2;++i) { t1 = minD_slope[i+1] - minD_slope[i]; if ( !equal(t1,0.0) && !equal(t1,-2.0) ) { print_JR_slopes(n_JR[side],skew_rate, maxD_slope, minD_slope); } } /* slopes of skew must be strictly monotone increasing */ for (i=0;i<n-2;++i) { t1 = skew_rate[i+1] - skew_rate[i]; if ( !equal(t1,2.0) && !equal(t1,4.0) ) { print_JR_slopes(n_JR[side],skew_rate, maxD_slope, minD_slope); } } } /***********************************************************************/ /* */ /***********************************************************************/ double set_Fms_Pt_min_delay(AreaType *area,int side, PointType *p0, PointType *p1) { double x,y, t; x = ABS(p0->x - p1->x); y = ABS(p0->y - p1->y); assert(equal(x,0) || equal(y,0) ); if (side==0) { t = calc_delay_increase(Gamma, area->area_L->capac, x,y); } else { t = calc_delay_increase(Gamma, area->area_R->capac, x,y); } return(t); } /***********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /***********************************************************************/ double calc_skew_slope(AreaType *area) { double x0,y0,x1,y1,cap0, cap1, t; bool linear = gBoundedSkewTree->LinearDelayModel () ; if ( linear ) { return(2.0); } else { /* Elmore delay model */ x0 = area->line[0][0].x; y0 = area->line[0][0].y; x1 = area->line[1][0].x; y1 = area->line[1][0].y; cap0 = area->area_L->capac; cap1 = area->area_R->capac; if (equal(x0,x1)) { t = PURES[V_]*(cap0+ cap1+area->dist*PUCAP[V_]); } else if (equal(y0, y1)) { t = PURES[H_]*(cap0+ cap1+area->dist*PUCAP[H_]); } else { assert(0); } return(t); } } /********************************************************************/ /* determine if feasible merging section of a line connecting JR(L) */ /* and JR(R) is empty */ /********************************************************************/ void fms_of_line_exist(AreaType *area, AreaType *area_L, AreaType *area_R, int side, int x) { double d, t; PointType pt; int nn, side_loc; nn = area->n_mr; pt = JR[side][x]; t = calc_skew_slope(area); d = (pt_skew(pt) -Skew_B)/t; if (d <= 0 ) { area->mr[nn] = pt; area->n_mr = nn + 1; } else if (d <= area->dist) { side_loc = calc_side_loc(side); set_pt_coord_case2(side_loc, &pt,d); pt.min += set_Fms_Pt_min_delay(area, side, &(JR[side][x]), &pt); pt.max = Skew_B + pt.min; area->mr[nn] = pt; area->n_mr = nn + 1; } assert(nn <= MAX_mr_PTS); } /******************************************************************/ /* construct left part or right part of merging region node->area[node->ca].mr */ /******************************************************************/ void mr_on_JS(AreaType *area,int side, AreaType *area_L,AreaType *area_R) { int i, m[2]; assert(n_JR[side] >=2); mr_on_JS_sub(side, m); if (side==0) { for (i=m[0];i<=m[1];++i) { fms_of_line_exist(area, area_L, area_R, side, i); } } else { for (i=m[1];i>=m[0];--i) { fms_of_line_exist(area, area_L, area_R, side, i); } } } /******************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /******************************************************************/ int JR_a_line() { PointType p0,q0,p1,q1; double min_x, max_x, min_y, max_y; p0 = JS[0][0]; p1 = JS[0][1]; q0 = JS[1][0]; q1 = JS[1][1]; min_x = min4(p0.x,p1.x,q0.x,q1.x); max_x = max4(p0.x,p1.x,q0.x,q1.x); min_y = min4(p0.y,p1.y,q0.y,q1.y); max_y = max4(p0.y,p1.y,q0.y,q1.y); if (equal(max_x,min_x) || equal(max_y,min_y)) { return(YES); } else { return(NO); } } /******************************************************************/ /* construct merging region node */ /******************************************************************/ void construct_mr_sub1(AreaType *area, AreaType *area_L,AreaType *area_R) { double cap[2]; cap[0] = area_L->capac; cap[1] = area_R->capac; if (area_Manhattan_arc_JS(area) ) { /*para Manhattan Arc*/ mr_between_JS(area,0, cap); if (area->mr >0 && !JR_a_line()) mr_between_JS(area,1, cap); } else { /* parallel hori. or vert. lines */ mr_between_JS(area,0, cap); mr_on_JS(area,0, area_L,area_R); mr_between_JS(area,1, cap); if (area->dist > FUZZ) { /* non-overlapping hori. or vert. lines */ mr_on_JS(area,1, area_L,area_R); } } } /******************************************************************/ /* calculate the detoru wiring */ /******************************************************************/ void construct_mr_sub2(AreaType *area, AreaType *area_L,AreaType *area_R) { /* fix a bug reported by Nate on testcase test7_3 with topology topo_out*/ /* fix for bug reported by nate on 7-27-02 */ int side = calc_mss(area); check_mss(area,area_L,area_R); set_detour_EdgeLen(area, side ); set_delay_for_mss(area); if (area_L->R_buffer == 0) assert(area->L_StubLen==0); if (area_R->R_buffer == 0) assert(area->R_StubLen==0); area->L_EdgeLen += area->L_StubLen; area->R_EdgeLen += area->R_StubLen; } /***********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /***********************************************************************/ void check_LINEAR_mr_sub(PointType p1,PointType p2) { int i,j,n; PointType p; print_Point(stdout,p1); print_Point(stdout,p2); printf("Fms_Pt \n"); for (i=0;i<2;++i) { n = n_Fms_Pt[i]; for (j=0;j<n;++j) { p = Fms_Pt[i][j]; print_Point(stdout,p); if (same_Point(p1,p)) { printf("p1 is fms \n"); } if (same_Point(p2,p)) { printf("p2 is fms \n"); } } } printf("Bal_Pt \n"); for (i=0;i<2;++i) { n = N_Bal_Pt[i]; for (j=0;j<n;++j) { p = Bal_Pt[i][j]; print_Point(stdout,p); if (same_Point(p1,p)) { printf("p1 is bal \n"); } if (same_Point(p2,p)) { printf("p2 is bal \n"); } } } } /***********************************************************************/ /* check if mr is an octilinear octagon in the linear delay model. */ /***********************************************************************/ void check_LINEAR_mr(AreaType *area) { PointType p1,p2; double a,b; int i,n; n = area->n_mr; for (i=0; i<n; i++) { p1 = area->mr[i]; p2 = area->mr[(i+1)%n]; a = ABS(p2.y-p1.y); b = ABS(p2.x-p1.x); if (!equal(a,0) && !equal(b,0) && !equal(a,b)) { printf("a=%f, b= %f \n", a,b); print_area(area); check_LINEAR_mr_sub(p1,p2); } assert(equal(a,0) || equal(b,0) || equal(a,b)); } } /***********************************************************************/ /* */ /***********************************************************************/ void check_mr_Point(AreaType *area) { PointType pt; int i; for (i=0;i<area->n_mr;++i) { pt = area->mr[i]; if (pt.min <0 || pt.min > pt.max || pt_skew(pt) >= Skew_B + FUZZ) { print_Point(stdout, pt); print_area(area); assert(0); } } } /***********************************************************************/ /* */ /***********************************************************************/ void check_mr(AreaType *area) { int i,j,n; n = area->n_mr; check_mr_Point(area); for (i=0;i<n;++i) { j = (i+1)%n; if (Manhattan_arc(area->mr[i],area->mr[j])) { check_const_delays(&(area->mr[i]),&(area->mr[j])); } } if (area_Manhattan_arc_JS(area) ) { for (i=0;i<n;++i) { j = calc_line_type(area->mr[i], area->mr[(i+1)%n]); assert(j==MANHATTAN_ARC || j==VERTICAL || j==HORIZONTAL); } } if (Skew_B == 0) assert(area->n_mr <=2); assert( n_JR[0] <= MAX_TURN_PTS); assert( n_JR[1] <= MAX_TURN_PTS); bool linear = gBoundedSkewTree->LinearDelayModel () ; if ( linear ) { if (area->n_mr > 16) { print_area(area); assert( area->n_mr <= 16); } check_LINEAR_mr(area); } else { assert( area->n_mr <= MAX_mr_PTS); } } /***********************************************************************/ /* */ /***********************************************************************/ void check_mr_array(AreaType area[], int n) { int i; for (i=0;i<n;++i) { check_mr(&(area[i])); } } /***********************************************************************/ /* */ /***********************************************************************/ void check_mr2(AreaType *area) { if (area->npts > area->n_mr) { printf("area->npts = %d, area->n_mr = %d \n",area->npts,area->n_mr); assert(0); } bool linear = gBoundedSkewTree->LinearDelayModel () ; if ( linear ) { assert(area->npts <= 8); } else { assert(area->npts <= MAXPTS); } } /***********************************************************************/ /* */ /***********************************************************************/ void check_mr3_sub(AreaType *area) { int i,j; print_area(area); for (i=0;i<2;++i) { printf("\"Fms_Pt[%d]:\n", i); for (j=0;j<n_Fms_Pt[i];++j) { print_Point(stdout, Fms_Pt[i][j]); } } for (i=0;i<2;++i) { printf("\"Bal_Pt[%d]:\n", i); for (j=0;j<N_Bal_Pt[i];++j) { print_Point(stdout, Bal_Pt[i][j]); } } for (i=0;i<2;++i) { printf("\"JR[%d]:\n", i); for (j=0;j<n_JR[i];++j) { print_Point(stdout, JR[i][j]); } } } /***********************************************************************/ /* */ /***********************************************************************/ void check_mr3(AreaType *area) { int i,j,n; PointType p1, p2; n = area->n_mr; for (i=0;i<n;++i) { j = (i+1)%n; p1 = area->mr[i]; p2 = area->mr[j]; if (!equal(p1.x, p2.x) && !equal(p1.y, p2.y) ) { /* not rectilinear boundary segment */ /* if (!equal(pt_skew(p1),Skew_B) || !equal(pt_skew(p2),Skew_B)) { printf("warning: 1792\n"); print_area(area); check_mr3_sub(area); print_Point(stdout, p1); print_Point(stdout, p2); } */ assert(equal(pt_skew(p1),pt_skew(p2))); } } } /******************************************************************/ /* construct merging region mr for node . */ /******************************************************************/ void construct_mr(AreaType *area, AreaType *area_L,AreaType *area_R, int mode){ area->n_mr = 0; calc_JR(area, area_L,area_R); calc_JR_corner(area); cal_Bal_Pt(area); cal_Fms_Pt(area, area_L, area_R); if (any_fms_on_JR()) { /* non-empty feasible merging region */ if (mode==FAST) return; construct_mr_sub1(area, area_L,area_R); } else { /* empty feasible merging region: need detour wire */ construct_mr_sub2(area, area_L,area_R); if (mode==FAST) return; } if (area_Manhattan_arc_JS(area) && area->L_EdgeLen >=0 ) { assert(area->R_EdgeLen >=0 ); construct_TRR_mr(area); } assert(area->n_mr <= MAX_mr_PTS); if (CHECK==1) check_mr(area); area->n_mr = rm_same_pts_on_sorted_array(area->mr, area->n_mr); calc_vertices(area); if (CHECK==1) check_mr(area); check_mr2(area); if (BST_Mode == BME_MODE) check_mr3(area); } /****************************************************************************/ /* update root_id of all nodes in tree rooted at v. */ /****************************************************************************/ void updateRootId(int root_id,int v) { if (v<0) return; NodeType *node = gBoundedSkewTree->TreeNode(v ) ; node->root_id = root_id; Neighbor_Cost[v][0] = DBL_MAX; updateRootId(root_id, node->L); updateRootId(root_id, node->R); } /****************************************************************************/ /* calculate the other child of node q which have one child p */ /****************************************************************************/ int sibling(int p,int q) { if (p==Node[q].L) return(Node[q].R); if (p==Node[q].R) return(Node[q].L); assert(0); } /****************************************************************************/ /* set node q = the other child of node p which have one child o */ /****************************************************************************/ void set_sibling(int o,int p,int q) { if (Node[p].L==o) { Node[p].L = q; } else if (Node[p].R==o) { Node[p].R = q; } else { assert(0); } } /****************************************************************************/ /* count_tree_nodes(); */ /****************************************************************************/ void count_tree_nodes(int root, int v, int *n) { if (v<0) return; (*n)++; assert(Node[v].root_id == root); count_tree_nodes(root, Node[v].L,n); count_tree_nodes(root, Node[v].R,n); } /****************************************************************************/ /* check the the root_id */ /****************************************************************************/ void check_root_id(int root) { int n = 0; count_tree_nodes(root, root, &n); } /****************************************************************************/ /* Print the first message. */ /****************************************************************************/ void print_BST_Mode() { if (BST_Mode == IME_MODE) { printf("IME_MODE: (N_Area_Per_Node = %d, N_Sampling = %d) \n", N_Area_Per_Node, N_Sampling); } else if (BST_Mode == HYBRID_MODE) { printf("HYBRID_MODE: (N_Area_Per_Node = %d, N_Sampling = %d) \n", N_Area_Per_Node, N_Sampling); } else { printf("BME_MODE"); } } /****************************************************************************/ /* Print the first message. */ /****************************************************************************/ void print_header( bool fixed_top) { printf("\n--------------------------------------------------------\n"); unsigned nterms = gBoundedSkewTree->Nterms() ; unsigned npoints = gBoundedSkewTree->Npoints() ; string fn = gBoundedSkewTree->SinksFileName() ; printf("bst %s (nterms=%d, Npoints=%d) ", fn.c_str() , nterms, npoints); printf("N_Obstalces = %d", N_Obstacle); printf("\n"); bool linear = gBoundedSkewTree->LinearDelayModel () ; if ( linear ) { printf("Linear delay model "); } else { printf("Elmore delay model "); } if (Skew_B == DBL_MAX) { printf("Skew_B=DBL_MAX "); } else { printf(" Skew_B = %.2f ", Skew_B); } if (!fixed_top) { printf("k_Parameter: %d CostFx=%.1f", k_Parameter, Cost_Function); } printf("\n"); print_BST_Mode(); print_current_time(); printf("--------------------------------------------------------\n"); printf("\n"); fflush(stdout); } /****************************************************************************/ /* check compare neighbor */ /****************************************************************************/ void check_compare_neighbors(int i,int j) { int k1,k2; /* printf("i=%d, j=%d \n", i,j); */ assert(j>=0); k1 = Node[i].root_id; k2 = Node[j].root_id; // unsigned npoints = gBoundedSkewTree->Npoints() ; int npoints = (int) gBoundedSkewTree->Npoints() ; assert(k1>=0 && k2 >= 0 && k1 <= npoints && k2 <= npoints); assert(k1 != k2 && !Marked[i] && !Marked[j]); } /****************************************************************************/ /* */ /****************************************************************************/ void update_neighbors_sub(int x,int y, double cost) { int i,j,n; n = N_neighbors[x]; for (j=0;j<n;++j) { if ( Neighbor_Cost[x][j] > cost) { break; } } if (j>=N_Neighbor) return; N_neighbors[x]= n = tMIN(n+1, N_Neighbor); for (i=n-2;i>=j;--i) { The_NEIghors[x][i+1] = The_NEIghors[x][i]; Neighbor_Cost[x][i+1] = Neighbor_Cost[x][i]; } The_NEIghors[x][j] = y; Neighbor_Cost[x][j] = cost; } /****************************************************************************/ /* update the nearest neighbors of mr(i) with newly added neighbor mr(j) */ /****************************************************************************/ void update_neighbors(int x,int y, double cost1) { int cluster1, cluster2, i,j,n; double cost2; n = N_neighbors[x]; cluster1 = Node[x].root_id; for (i=0;i<n;++i) { j = The_NEIghors[x][i]; cluster2 = Node[j].root_id; if (cluster1==cluster2) { cost2 = Neighbor_Cost[x][i]; if (cost1 < cost2) { The_NEIghors[x][i] = y; Neighbor_Cost[x][i] = cost1; } return; } } update_neighbors_sub(x,y,cost1); } /****************************************************************************/ /* check if areas of a node are sorted by the decreasing order of capac. */ /****************************************************************************/ int calc_best_area(int v) { int min_i, i; double x,y; min_i = 0; y = Node[v].area[min_i].capac; for (i=0;i<Node[v].n_area-1;++i) { x = Node[v].area[i].capac; if ( !equal(x,y) && x < y ) { min_i = i; } } return(min_i); assert(min_i == 0); } /****************************************************************************/ /* compute the merging cost of mr(i) with its possible neighbor mr(j), and */ /* update the neighborhood of mr(i) if mr(j) is indeed a neighbor of mr(i) */ /****************************************************************************/ void compare_neighbors(int i,int j) { int k1,k2, n1, n2 ; double cost_inc, old_cost, cost; if (CHECK==1) check_compare_neighbors(i,j); PointType &pt = Node[i].m_stnPt ; pt.t += 1.0; /* number of comparisons for mr[i]; */ cost = calc_merging_cost(i, j); /* cost = calc_merging_cost_sub(&tmpnode,i,j); */ k1 = Node[i].root_id; k2 = Node[j].root_id; if (BST_Mode == BME_MODE) { assert(Node[k1].ca==0); assert(Node[k2].ca==0); old_cost = Node[k1].area[0].subtree_cost + Node[k2].area[0].subtree_cost; } else { n1 = calc_best_area(k1); n2 = calc_best_area(k2); old_cost = Node[k1].area[n1].subtree_cost + Node[k2].area[n2].subtree_cost; } cost_inc = cost - old_cost; update_neighbors(i,j,cost_inc); } /****************************************************************************/ /* */ /****************************************************************************/ void BstTree::BuildTrr ( unsigned n ) { m_ctrr.Initialize() ; unsigned j=0; for (unsigned i=0;i<n;++i) { if (!Marked[i] ) { m_ctrr.Enclose ( *CandiRoot[i].ms ); j++; } } double t = sqrt((double) j) ; N_Index = tMAX(1,(int) t); assert(N_Index <= MAX_N_Index); } /****************************************************************************/ /* */ /****************************************************************************/ int xlow_index(NodeType *node) { int i; double t; const TrrType & ctrr = gBoundedSkewTree->Ctrr() ; t = (node->ms->xlow-ctrr.xlow)*N_Index/ctrr.Width(X); i = tMIN( (int) t, N_Index -1); assert (i>=0 && i < N_Index); return(i); } /****************************************************************************/ /* */ /****************************************************************************/ int xhi_index(NodeType *node) { int i; double t; const TrrType & ctrr = gBoundedSkewTree->Ctrr() ; t = (node->ms->xhi -ctrr.xlow)*N_Index/ctrr.Width(X); i = tMIN( (int) t, N_Index -1); assert (i>=0 && i < N_Index); return(i); } /****************************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /****************************************************************************/ int ylow_index(NodeType *node) { int i; double t; const TrrType & ctrr = gBoundedSkewTree->Ctrr() ; t = (node->ms->ylow-ctrr.ylow)*N_Index/ctrr.Width(Y) ; i = tMIN( (int) t, N_Index-1); assert (i>=0 && i < N_Index); return(i); } /****************************************************************************/ /* */ /****************************************************************************/ int yhi_index(NodeType *node) { int i; double t; const TrrType & ctrr = gBoundedSkewTree->Ctrr() ; t = (node->ms->yhi -ctrr.ylow)*N_Index/ctrr.Width(Y) ; i = tMIN( (int) t, N_Index -1); assert (i>=0 && i < N_Index); return(i); } /****************************************************************************/ /* */ /****************************************************************************/ void bucket_partitioning_sub(int v) { int j,j1,j2,k,k1,k2,n; j1 = xlow_index(&(CandiRoot[v])); j2 = xhi_index(&(CandiRoot[v])); k1 = ylow_index(&(CandiRoot[v])); k2 = yhi_index(&(CandiRoot[v])); for (j=j1;j<=j2;++j) { for (k=k1;k<=k2;++k) { n = Bucket[j][k].num; Bucket[j][k].element[n] = v; Bucket[j][k].num = n + 1; if (Bucket[j][k].num > BUCKET_CAPACITY) { printf("Bucket[%d][%d].num = %d > %d \n", j,k, Bucket[j][k].num, BUCKET_CAPACITY); } assert(Bucket[j][k].num <= BUCKET_CAPACITY); } } } /****************************************************************************/ /* */ /****************************************************************************/ void check_Bucket() { int i,j,k,s1,s2,n_bucket,max_size,min_size; double t1,t2; s1=s2=0; max_size = min_size = Bucket[0][0].num; for (i=0;i<N_Index;++i) { for (j=0;j<N_Index;++j) { k = Bucket[i][j].num; s1 += k; max_size = tMAX(max_size, k); min_size = tMIN(min_size, k); } } unsigned npoints = gBoundedSkewTree->Npoints() ; for (unsigned i=0;i<npoints;++i) { if (!Marked[i] ) s2++; } n_bucket = N_Index*N_Index; t1 = (double) n_bucket; t2 = (double) s1/ (double) s2; printf("Nodes/Bucket:ave:%f(max:%d,min:%d) --> Redundancy:%f \n", s1/t1, max_size, min_size, t2); printf("n_Bucket:%d n_unmarked_CandiRoot:%d \n", n_bucket, s2); if (s1 < s2) { printf("Buckets contains %d elements \n", s1); printf("There are %d elements \n", s2); assert(s1>=s2); } } /****************************************************************************/ /* partition n merging Nodes in buckets */ /****************************************************************************/ void bucket_partitioning(int n) { int i, j; gBoundedSkewTree->BuildTrr(n); for (i=0;i<N_Index;++i) { for (j=0;j<N_Index;++j) { Bucket[i][j].num = 0; } } for (i=0;i<n;++i) { if (!Marked[i] ) { bucket_partitioning_sub(i); } } if (CHECK==1) check_Bucket(); } /****************************************************************************/ /* */ /****************************************************************************/ void do_compare_neighbors(int i,int j) { int k1, k2; k1 = Node[i].root_id; k2 = Node[j].root_id; if (k1 != k2) { compare_neighbors(i,j); } } /****************************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /****************************************************************************/ void compare_neighbors_in_bucket(int v,int x,int y) { int j; assert(v!=NIL); assert(x>=0 && y>=0 && x < N_Index && y < N_Index); for (j=0;j<Bucket[x][y].num;++j) { do_compare_neighbors(v,Bucket[x][y].element[j]); } } /****************************************************************************/ /* */ /****************************************************************************/ void calc_nearest_neighbor_sub(int v,int out_xlow,int out_xhi,int out_ylow, int out_yhi) { int n1, n2,j; n1 = tMAX(0,out_ylow); n2 = tMIN(N_Index-1,out_yhi); for (j=n1;j<=n2;++j) { if (out_xlow>=0) compare_neighbors_in_bucket(v,out_xlow,j); if (out_xhi < N_Index) compare_neighbors_in_bucket(v,out_xhi,j); } n1 = tMAX(0,out_xlow+1); n2 = tMIN(N_Index-1,out_xhi-1); for (j=n1;j<=n2;++j) { if (out_ylow>=0) {compare_neighbors_in_bucket(v,j, out_ylow); } if (out_yhi < N_Index) compare_neighbors_in_bucket(v,j, out_yhi); } } /****************************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /* calculate the nearest neighbor of merging region mr(v). */ /****************************************************************************/ int calc_nearest_neighbor(int v,int inc) { int x1,x2,y1,y2; x1 = xlow_index(&(CandiRoot[v])) - inc; x2 = xhi_index(&(CandiRoot[v])) + inc; y1 = ylow_index(&(CandiRoot[v])) - inc; y2 = yhi_index(&(CandiRoot[v])) + inc; if (x1>=0 || y1>=0 || x2 <N_Index || y2 < N_Index) { calc_nearest_neighbor_sub(v,x1,x2,y1,y2); return(YES); } else { return(NO); } /* assert(x1>=0 || y1>=0 || x2 <N_Index || y2 < N_Index); */ } /****************************************************************************/ /* */ /****************************************************************************/ void init_nearest_neighbor(int v) { int x1,x2,y1,y2,i,j; PointType &pt = Node[v].m_stnPt ; pt.t=0.0; /* number of comparisons */ N_neighbors[v]= 0; x1 = xlow_index(&(CandiRoot[v])); x2 = xhi_index(&(CandiRoot[v])); y1 = ylow_index(&(CandiRoot[v])); y2 = yhi_index(&(CandiRoot[v])); for (i=x1;i<=x2;++i) { for (j=y1;j<=y2;++j) { compare_neighbors_in_bucket(v, i,j); } } } /****************************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /****************************************************************************/ int construct_NNG(int n) { int i,j, inc, k1; int graphSize = 0; // control search range for nearest neighbors assert(n>1); inc=0; do { ++inc; for (i=k1=0;i<n;++i) { j = UnMarkedNodes[i]; calc_nearest_neighbor(j, inc); if (N_neighbors[j]>0) { k1++;} } if (CHECK) assert(inc <= N_Index); } while (k1 == 0 || inc < graphSize); assert(k1>0); return(k1); } /****************************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /****************************************************************************/ void show_NNG_infomation(int n, int k1 ) { int i, j,k2,k3; double t; for (i=0,t=0,k2=k3=0;i<n;++i) { j = UnMarkedNodes[i]; if (N_neighbors[j]>0) { k2 += N_neighbors[j]; k3 = tMAX(k3, N_neighbors[j]); } PointType &pt = Node[j].m_stnPt ; t += pt.t; } assert(t > 0); printf("comparisons/nodes = %d/%d = %.1f \n", (int) t,n, t/n); printf("nodes_with_neighbor/nodes = %d/%d = %.2f\n", k1,n,(double)k1/n); printf("neighbors/nodes = %d/%d = %.2f\n", k2,n,(double)k2/n); printf("max_neighbors = %d \n", k3); iShowTime(); printf("\n\n"); fflush(stdout); } /****************************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /****************************************************************************/ void build_nearest_neighbor_graph(int n, int show_info) { int i, j,k1; bucket_partitioning(n); for (i=0;i<n;++i) { if (!Marked[i] ) { init_nearest_neighbor(i); } } for (i=j=0;i<n;++i) { if (!Marked[i] ) { UnMarkedNodes[j++] = i; } } k1 = construct_NNG(j); if (show_info) { show_NNG_infomation(j, k1); } } /****************************************************************************/ /* select the cloest pair of merging ares. */ /****************************************************************************/ int pair_compare_inc_sub1(PairType *p, PairType *q) { return( (p->cost > q->cost) ? YES: NO); } /****************************************************************************/ /* merging cost increase of cluster i == Cluster[i].y - Cluster[i].x */ /****************************************************************************/ double cls_merging_cost_inc(int cid) { return(Cluster[cid].y - Cluster[cid].x); } /****************************************************************************/ /* select the cloest pair of merging ares. */ /****************************************************************************/ int pair_compare_inc_sub2(PairType *p, PairType *q) { int i,j; double c1, c2; i = Node[p->x].root_id; j = Node[p->y].root_id; c1 = cls_merging_cost_inc(i) + cls_merging_cost_inc(j); i = Node[q->x].root_id; j = Node[q->y].root_id; c2 = cls_merging_cost_inc(i) + cls_merging_cost_inc(j); if ( equal(c1,c2) ) { return( (p->cost > q->cost) ? YES: NO); } else { return( (c1 < c2) ? YES: NO); } } /****************************************************************************/ /* select the cloest pair of merging ares. */ /****************************************************************************/ int pair_compare_inc(const void *p1, const void *q1) { PairType *p, *q; int ans; p = (PairType *)p1; q = (PairType *)q1; if (Cost_Function==0) { ans = pair_compare_inc_sub1(p,q); } else { ans = pair_compare_inc_sub2(p,q); } return(ans); } /****************************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /****************************************************************************/ int Area_compare_inc(const void *p1, const void *q1) { AreaType *p, *q; double a1, a2; p = (AreaType *) p1; q = (AreaType *) q1; a1 = calc_boundary_length(p); a2 = calc_boundary_length(q); if (equal(p->subtree_cost, q->subtree_cost)) { return( (a1 < a2) ? YES: NO); } else { return( (p->subtree_cost > q->subtree_cost) ? YES: NO); } /* if (equal(p->dist, q->dist)) { return( (a1 < a2) ? YES: NO); } else { return( (p->dist > q->dist) ? YES: NO); } */ } /****************************************************************************/ /* initialize the merging pairs */ /****************************************************************************/ int count_merge_pairs(int n_nodes) { int i, j, k, n; for (i=0, n=0; i<n_nodes; i++) { k = N_neighbors[i]; if (!Marked[i] && k >0 ) { for (j=0;j<k;++j) { Best_Pair[n].x = i; Best_Pair[n].y=The_NEIghors[i][j]; Best_Pair[n].cost=Neighbor_Cost[i][j]; n++; } } } assert(n>1); return(n); } /****************************************************************************/ /* initialize the merging pairs */ /****************************************************************************/ static void update_Cluster(int n_nodes) { int i,j; /* init min merging cost in current Nearest Neighbor Graph */ for (i=0;i<n_nodes;++i) { j = Node[i].root_id; if ( j >= 0 ) { Cluster[j].y = DBL_MAX; } else { /* root_id can be -1 */ // printf ("error: j=%d\n", j ) ; } } for (i=0;i<n_nodes;++i) { if (N_neighbors[i]>0) { j = Node[i].root_id; Cluster[j].x = tMIN(Cluster[j].x, Neighbor_Cost[i][0]); Cluster[j].y = tMIN(Cluster[j].y, Neighbor_Cost[i][0]); assert(Cluster[i].y >= Cluster[i].x); } } for (i=0;i<n_nodes;++i) { j = Node[i].root_id; } } /****************************************************************************/ /* initialize the merging pairs */ /****************************************************************************/ int init_pairs_to_merge(int n_nodes) { int i, n; n = count_merge_pairs(n_nodes); if (Cost_Function ==1) update_Cluster(n_nodes); qsort(Best_Pair, n, sizeof(PairType), pair_compare_inc); if (k_Parameter < 0) { i = n/ABS(k_Parameter); } else { i = k_Parameter; } n = tMIN(n, tMAX(1,i) ); return(n); } /****************************************************************************/ /* select merging pairs from Nearest-Neighbor graph */ /****************************************************************************/ int pairs_to_merge(int n_nodes) { int i, j, n, besta1, besta2, i1, i2; char *Flag; n = init_pairs_to_merge(n_nodes); unsigned npoints = gBoundedSkewTree->Npoints() ; Flag = (char *) calloc(npoints, sizeof(char)); assert(Flag != NULL); for (i=0; i<n_nodes; i++) { Flag[i] = NO; } for (i=0, j=0; i<n; i++) { besta1 = Best_Pair[i].x; besta2 = Best_Pair[i].y; assert(besta1 >=0 && besta2>=0); i1 = Node[besta1].root_id; i2 = Node[besta2].root_id; if (!Flag[i1] && !Flag[i2]) { Flag[i1] = Flag[i2] = YES; Best_Pair[j].x=besta1; Best_Pair[j].y=besta2; j++; /* Best_Pair[j++]=Best_Pair[i]; */ } } assert(j>0); assert(n_nodes+j <= (int) npoints); free(Flag); return(j); } /***********************************************************************/ /***********************************************************************/ double BstTree::TotalLength ( void ) const { double Tcost = 0; double Tdist=0 ; int root = gBoundedSkewTree->RootNodeIndex () ; calc_TreeCost( root, &Tcost, &Tdist); return Tcost ; } /***********************************************************************/ /***********************************************************************/ double BST_DME::TotalLength ( void ) const { return m_bstdme->TotalLength() ; } /***********************************************************************/ /* print the TreeCost and cost reduction over MST. */ /***********************************************************************/ static double print_answer(const char fn[],int v, bool fixedTopology ) { PointType p; double Tcost = 0, Tdist=0, t, cap; int n_detour_nodes = calc_TreeCost(v, &Tcost, &Tdist); double sCost = Node[v].area[Node[v].ca].subtree_cost ; print_cluster_cost(Tcost); assert( equivalent(Tcost, sCost, 1.0)); printf("\n%s:WL=%10.0f B=", fn, Tcost); if (Skew_B == DBL_MAX) { printf("inf ");} else {printf("%.0f", Skew_B);} bool linear = gBoundedSkewTree->LinearDelayModel () ; if ( !linear ) { printf("ps "); } t = calc_buffered_node_delay(v); cap = Node[v].area[Node[v].ca].unbuf_capac; PointType &pt = Node[v].m_stnPt ; printf("t:%.1f (%.1f)(%.3f)", t, pt.max, cap); iShowTime(); if (Start_Skew_B == DBL_MAX) {printf("(infty)"); } else {printf("(%.0f)", Start_Skew_B);} t = 1E15/PUCAP_SCALE; printf("\n\n\n"); printf("Total wirelength: %f\n", Tcost); printf("Total Delay: %f ps\n",calc_buffered_node_delay(v)); if (R_buffer>0) { printf("R_buffer = %f Oh\n", (double) R_buffer); } else { printf("%d types of Buffers with R = [%d,%d]\n",N_BUFFER_SIZE, R_buffer_size[0], R_buffer_size[N_BUFFER_SIZE-1]); } printf("C_buffer = %f FF\n", C_buffer*t); printf("Delay_buffer = %f ns\n", Delay_buffer*1E9/PUCAP_SCALE); printf("R[H], R[V]: %f Oh %f Oh\n", PURES[H_], PURES[V_]); printf("C[H], C[V]: %f FF %f FF \n", PUCAP[H_]*t, PUCAP[V_]*t); printf("Routing pattern: %.1f (1:HV, 0:VH) \n", Gamma); printf("\n"); printf("k=%d, Cost_fx=%.1f,N_Neighbor=%d \n", k_Parameter, Cost_Function, N_Neighbor); unsigned nterms = gBoundedSkewTree->Nterms() ; if (Tdist != Tcost) { t = (Tcost- Tdist)*100.0/Tdist; printf("Treewire = %.1f (detour:%.1f%%) ***", Tdist,t); t = (double) (n_detour_nodes)*100.0/nterms; printf("n_detour_nodes = %d (%f%%) ***\n", n_detour_nodes,t); } fflush(stdout); p = pt; printf("skew(%d)=%f=(%f-%f) \n", v,pt_skew(p),p.max,p.min); assert(pt_skew(p) <= Skew_B + FUZZ); print_BST_Mode(); printf("\n\n"); printf("Max_n_regions (irredundant) = %d (%d)\n", Max_n_regions, Max_irredundant_regions); print_overlapped_regions(); print_max_n_mr(); print_max_npts(); print_n_region_type(); if (BST_Mode==IME_MODE) { unsigned npoints = gBoundedSkewTree->Npoints() ; for (unsigned i=nterms+1;i<npoints;++i) { assert(JS_line_type(&(Node[i])) == MANHATTAN_ARC); } } if (!fixedTopology) { print_topology(fn, v, Tcost, Tdist); } print_bst (fn, v, Tcost, Tdist); print_merging_tree(fn, v); return(Tcost); } /******************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /******************************************************************/ void check_update_JS(AreaType *area, PointType pt[4], int line0type) { int parallel; double d; PointType tmp_pt[2],q0,q1,q2,q3; parallel = parallel_line(pt[0],pt[1],pt[2],pt[3]); if (parallel) { if (line0type == FLAT) { /* not consider non-rectilinear parallel lines */ assert(0); } else if (line0type == TILT) { assert(0); } } q0 = JS[0][0]; q1 = JS[0][1]; q2 = JS[1][0]; q3 = JS[1][1]; d=linedist(q0,q1,q2,q3,tmp_pt); if (CHECK==1) { assert(same_Point(q0,q1) || same_Point(q2,q3) || parallel_line(q0,q1,q2,q3)); assert(equal(d,area->dist)) ; assert(pt_on_line_segment(q0,pt[0],pt[1])); assert(pt_on_line_segment(q1,pt[0],pt[1])); assert(pt_on_line_segment(q2,pt[2],pt[3])); assert(pt_on_line_segment(q3,pt[2],pt[3])); } } /*****************************************************************/ /* */ /******************************************************************/ void calc_coor(PointType *pt,PointType p0,PointType p1,double z, int linetype) { double d0,d1; if (linetype==HORIZONTAL || linetype==FLAT) { d0 = ABS(p0.x - z); d1 = ABS(p1.x - z); } else { d0 = ABS(p0.y - z); d1 = ABS(p1.y - z); } pt->x = (p0.x*d1+p1.x*d0)/(d0+d1); pt->y = (p0.y*d1+p1.y*d0)/(d0+d1); } /***********************************************************************/ /* */ /***********************************************************************/ void update_JS_case1(AreaType *area, PointType pt[4], PointType pts[2], int line0type, int line1type) { TrrType ms0,ms1,trr0,trr1,t0,t1; if (line0type==MANHATTAN_ARC ) { line2ms(&ms0,pt[0],pt[1]); } else { ms0.MakeDiamond (pts[0],0 ); } if (line1type==MANHATTAN_ARC ) { line2ms(&ms1,pt[2],pt[3]); } else { ms1.MakeDiamond (pts[1],0 ); } assert(equal(ms_distance(&ms0,&ms1), area->dist)); L_MS = ms0; R_MS = ms1; build_trr(&ms0, area->dist, &trr0); build_trr(&ms1, area->dist, &trr1); make_intersect(&trr1,&ms0,&t0); make_intersect(&trr0,&ms1,&t1); ms2line(&t0, &(JS[0][0]), &(JS[0][1]) ); ms2line(&t1, &(JS[1][0]), &(JS[1][1]) ); } /***************************************************************************/ /* return the Joining Segments of node_L and node_R for node */ /* when the closest portion of Node[L] and Node[R] are parallel segments */ /***************************************************************************/ void update_JS(AreaType *area, PointType pt[4], PointType pts[2]) { int line0type, line1type; double max_x,max_y,min_x,min_y, t; TrrType ms0,ms1,trr0,trr1,t0,t1; line0type = calc_line_type(pt[0],pt[1]); line1type = calc_line_type(pt[2],pt[3]); if (line0type==MANHATTAN_ARC ) { line2ms(&ms0,pt[0],pt[1]); } if (line1type==MANHATTAN_ARC ) { line2ms(&ms1,pt[2],pt[3]); } if (line0type!=MANHATTAN_ARC && line1type==MANHATTAN_ARC ) { ms0.MakeDiamond (pts[0],0 ); } if (line0type==MANHATTAN_ARC && line1type!=MANHATTAN_ARC ) { ms1.MakeDiamond (pts[1],0 ); } JS[0][0] = JS[0][1] = pts[0]; JS[1][0] = JS[1][1] = pts[1]; if ( (line0type==MANHATTAN_ARC || line1type==MANHATTAN_ARC) ) { t = ms_distance(&ms0,&ms1); assert(equivalent(t, area->dist, 1E-6)); area->dist = t; L_MS = ms0; R_MS = ms1; build_trr(&ms0, area->dist, &trr0); build_trr(&ms1, area->dist, &trr1); make_intersect(&trr1,&ms0,&t0); make_intersect(&trr0,&ms1,&t1); ms2line(&t0, &(JS[0][0]), &(JS[0][1]) ); ms2line(&t1, &(JS[1][0]), &(JS[1][1]) ); } else if ( parallel_line(pt[0],pt[1],pt[2],pt[3])) { /* parallel lines */ min_y = tMAX( tMIN(pt[0].y,pt[1].y), tMIN(pt[2].y,pt[3].y) ); max_y = tMIN( tMAX(pt[0].y,pt[1].y), tMAX(pt[2].y,pt[3].y) ); min_x = tMAX( tMIN(pt[0].x,pt[1].x), tMIN(pt[2].x,pt[3].x) ); max_x = tMIN( tMAX(pt[0].x,pt[1].x), tMAX(pt[2].x,pt[3].x) ); if ( (line0type==VERTICAL || line0type==TILT) && max_y >= min_y) { calc_coor(&(JS[0][0]),pt[0],pt[1],min_y,line0type); calc_coor(&(JS[0][1]),pt[0],pt[1],max_y,line0type); calc_coor(&(JS[1][0]),pt[2],pt[3],min_y,line0type); calc_coor(&(JS[1][1]),pt[2],pt[3],max_y,line0type); } else if ( (line0type==HORIZONTAL || line0type==FLAT) && max_x >=min_x) { calc_coor(&(JS[0][0]),pt[0],pt[1],min_x,line0type); calc_coor(&(JS[0][1]),pt[0],pt[1],max_x,line0type); calc_coor(&(JS[1][0]),pt[2],pt[3],min_x,line0type); calc_coor(&(JS[1][1]),pt[2],pt[3],max_x,line0type); } } else { } if (calc_line_type(JS[0][0],JS[0][1]) == MANHATTAN_ARC && line0type != MANHATTAN_ARC && line1type != MANHATTAN_ARC) { L_MS.MakeDiamond (pts[0], 0 ); R_MS.MakeDiamond (pts[1], 0 ); } if (CHECK==1) check_update_JS(area,pt,line0type); } /****************************************************************************/ /* calculate the joining segment for node's children */ /****************************************************************************/ void calc_JS_sub2(AreaType *area, PointType pt[4]) { double ldist, old_dist, old_area, new_area; PointType pts[2], old_JS[2][2]; TrrType old_L_MS, old_R_MS; ldist = linedist(pt[0],pt[1],pt[2],pt[3], pts); if (equal(ldist,area->dist)) { old_JS[0][0] = JS[0][0]; old_JS[0][1] = JS[0][1]; old_JS[1][0] = JS[1][0]; old_JS[1][1] = JS[1][1]; old_dist = area->dist; if (calc_line_type(JS[0][0],JS[0][1]) == MANHATTAN_ARC) { old_L_MS = L_MS; old_R_MS = R_MS; } area->dist = ldist; update_JS(area, pt, pts); old_area = calc_JR_area_sub(old_JS[0][0],old_JS[0][1], old_JS[1][0],old_JS[1][1]); new_area = calc_JR_area_sub(JS[0][0], JS[0][1], JS[1][0], JS[1][1]); if (old_area >= new_area ) { /* original JS is better */ JS[0][0] = old_JS[0][0]; JS[0][1] = old_JS[0][1]; JS[1][0] = old_JS[1][0]; JS[1][1] = old_JS[1][1]; if (calc_line_type(JS[0][0],JS[0][1]) == MANHATTAN_ARC) { L_MS = old_L_MS; R_MS = old_R_MS; } area->dist = old_dist; } } else if (ldist < area->dist ) { area->dist = ldist; update_JS(area, pt, pts); } if (calc_line_type(JS[0][0],JS[0][1]) == MANHATTAN_ARC ) { check_JS_MS(); } } /****************************************************************************/ /* calculate the joining segment for node's children */ /****************************************************************************/ void calc_JS_sub1(AreaType *area, AreaType *area_L,AreaType *area_R) { int n1, n2; int i,j,mn1,mn2, k0, k1, k2, k3; PointType pt[4], q[2]; mn1 = n1 = area_L->npts; mn2 = n2 = area_R->npts; if (n1==2) n1 =1; if (n2==2) n2 =1; for (i=0; i<n1; i++) { k0 = area_L->vertex[i]; k1 = area_L->vertex[(i+1)%mn1]; pt[0] = area_L->mr[k0]; pt[1] = area_L->mr[k1]; for (j=0; j<n2; j++) { k2 = area_R->vertex[j]; k3 = area_R->vertex[(j+1)%mn2]; pt[2] = area_R->mr[k2]; pt[3] = area_R->mr[k3]; linedist(pt[0],pt[1],pt[2],pt[3], q); calc_JS_sub2(area, pt); } } calc_JS_delay(area, area_L,area_R); } /****************************************************************************/ /* calculate the joining segment for node's children */ /****************************************************************************/ void do_calc_JS(AreaType *area, AreaType *area_L,AreaType *area_R, int v1, int v2) { int n1,n2; int j0,j1,j2,j3; PointType pt[4]; area->dist = DBL_MAX; n1 = area_L->npts; n2 = area_R->npts; if (n1 ==1 && n2 == 1) { JS[0][0] = JS[0][1] = area_L->mr[0]; JS[1][0] = JS[1][1] = area_R->mr[0]; L_MS.MakeDiamond (area_L->mr[0], 0 ); R_MS.MakeDiamond (area_R->mr[0], 0 ); area->dist = Point_dist(area_L->mr[0], area_R->mr[0]) ; } else { if (v1<0 && v2 <0) { calc_JS_sub1(area, area_L,area_R); } else { j0 = area_L->vertex[v1]; j1 = area_L->vertex[(v1+1)%n1]; j2 = area_R->vertex[v2]; j3 = area_R->vertex[(v2+1)%n2]; pt[0] = area_L->mr[j0]; pt[1] = area_L->mr[j1]; pt[2] = area_R->mr[j2]; pt[3] = area_R->mr[j3]; calc_JS_sub2(area, pt); } calc_JS_delay(area, area_L,area_R); } if (calc_line_type(JS[0][0],JS[0][1]) == MANHATTAN_ARC) { check_JS_MS(); } } /********************************************************************/ /* */ /********************************************************************/ void recalculate_MS(AreaType *area, TrrType *trr) { if (area->n_mr ==4 && TRR_area(area)) { pts2TRR(area->mr,area->n_mr, trr); } } /********************************************************************/ /* */ /********************************************************************/ void debug_calc_JS(AreaType *area) { TrrType t; make_intersect_sub( &L_MS, &R_MS, &t); if (t.xlow <= t.xhi && t.ylow <= t.yhi) { draw_a_TRR(&L_MS); draw_a_TRR(&R_MS); print_area(area->area_L); print_area(area->area_R); printf("here for debug \n"); area->dist = 0; } } /****************************************************************************/ /* calculate the joining segment for node's children */ /****************************************************************************/ void calc_JS(AreaType *area,AreaType *area_L,AreaType *area_R,int v1,int v2) { do_calc_JS(area,area_L,area_R,v1,v2); if (Skew_B ==0 && TmpCondition) { recalculate_MS(area_L, &L_MS); recalculate_MS(area_R, &R_MS); if (0) debug_calc_JS(area); } } /********************************************************************/ /* */ /********************************************************************/ void check_sampling_segment(AreaType *area,PointType *p0, PointType *p1) { PointType v0, v1; calc_BS_located(p1,area,&v0,&v1); calc_pt_delays(area, p1, v0,v1); check_Point(p0); check_Point(p1); check_const_delays(p0,p1); } /********************************************************************/ /* calculate the max-delay/min-delay of the sampleing segemnt */ /********************************************************************/ void calc_delay_of_ms(AreaType *area, PointType *p0, PointType *p1) { PointType v0, v1; calc_BS_located(p0,area,&v0,&v1); calc_pt_delays(area, p0, v0,v1); p1->max = p0->max; p1->min = p0->min; if (CHECK==1) check_sampling_segment(area,p0, p1); } /********************************************************************/ /* get the vertex of mr which is closest to a given point. */ /********************************************************************/ int nearest_vertex(AreaType *area, PointType lpt) { int i, min_i; double d, min_d; min_d = DBL_MAX; for (i=0;i<area->n_mr;++i) { d = Point_dist(lpt,area->mr[i]); if (d < min_d) { min_i = i; min_d = d; } } return(min_i); } /********************************************************************/ /* get the Boundary Segments which are Manhattan Arcs. */ /********************************************************************/ void get_Manhattan_BS(AreaType *area, int side, TrrType *ms) { int v1, v2, k1, k2, n; int linetype1, linetype2; v1 = v2 = nearest_vertex(area, area->line[side][0]); n = area->n_mr; k1 = (v1+1)%n; k2 = (v1+n-1)%n; if (Manhattan_arc(area->mr[v1], area->mr[k1])) { v2 = k1; } else if (Manhattan_arc(area->mr[v1], area->mr[k2])) { v2 = k2; } if (v1==v2 && area->n_mr >= 2 ) { linetype1 = calc_line_type(area->mr[v1], area->mr[k1]); linetype2 = calc_line_type(area->mr[v1], area->mr[k2]); assert(linetype1==VERTICAL || linetype1==HORIZONTAL); assert(linetype2==VERTICAL || linetype2==HORIZONTAL); } line2ms(ms,area->mr[v1], area->mr[v2]); } /********************************************************************/ /* calculate the i_th sampling Manhattan arc of node */ /********************************************************************/ void get_a_sampling_segment(int i, TrrType ms[], double d) { double d0,d1; TrrType trr0, trr1; assert(i<N_Sampling-1 ); assert(i > 0 ); d0 = i*d/(N_Sampling-1); d1 = d - d0; build_trr(&(ms[0]),d0,&trr0); build_trr(&(ms[N_Sampling-1]),d1,&trr1); make_intersect(&trr0,&trr1, &(ms[i])); } /********************************************************************/ /* calculate the i_th sampling Manhattan arc of node */ /********************************************************************/ int calc_sampling_set(AreaType *area, TrrType *sampling_set) { int i, n; double d; if (!area_Manhattan_arc_JS(area)) { n=0; } else if (area->n_mr == 1) { n = 1; line2ms(&(sampling_set[0]),area->mr[0], area->mr[0]); } else if (area->n_mr == 2 && Manhattan_arc(area->mr[0], area->mr[1]) ) { n = 1; line2ms(&(sampling_set[0]),area->mr[0], area->mr[1]); } else { n = N_Sampling; get_Manhattan_BS(area, 0, &(sampling_set[0])); get_Manhattan_BS(area, 1, &(sampling_set[n-1])); d = ms_distance( &(sampling_set[0]), &(sampling_set[n-1])); assert( d > FUZZ && area->dist >= d - FUZZ); for (i=1;i<N_Sampling-1;++i) { get_a_sampling_segment(i, sampling_set, d); check_a_sampling_segment(area, &(sampling_set[i])); } } return(n); } /********************************************************************/ /* */ /********************************************************************/ void ms2line_delays(AreaType *area, TrrType *ms, PointType *p0, PointType *p1) { if (area->n_mr==1) { *p0=*p1 = area->mr[0]; } else if (area->n_mr == 2 && Manhattan_arc(area->mr[0], area->mr[1]) ) { *p0 = area->mr[0]; *p1 = area->mr[1]; } else { ms2line(ms, p0, p1); calc_delay_of_ms(area, p0, p1); } } /****************************************************************************/ /* */ /****************************************************************************/ void MergeArea_sub(AreaType *area) { double merge_cost, x, t ; merge_cost = area_merge_cost(area); area->subtree_cost = merge_cost + area->area_L->subtree_cost + area->area_R->subtree_cost; bool linear = gBoundedSkewTree->LinearDelayModel () ; if ( linear ) { area->capac = area->subtree_cost; } else { x = merge_cost - area->L_StubLen - area->R_StubLen; area->capac = area->area_L->capac + area->area_R->capac + x*PUCAP[H_]; /* h = ABS(JS[0][0].x - JS[1][0].x); v = x - h; area->capac = area_L->capac + area_R->capac+h*PUCAP[H_] + v*PUCAP[V_]; */ } t = area->L_EdgeLen + area->R_EdgeLen; assert(t >= area->dist - FUZZ || t==-2.0); area->R_buffer = 0; area->unbuf_capac = area->capac; } /****************************************************************************/ /* return the merging area of Node1 and Node2 */ /* Case I: Construction of merging area = Construction of merging segments */ /****************************************************************************/ void MergeManhattanArc(AreaType *area, AreaType *area_L, AreaType *area_R, int mode) { double d0,d1; area->dist = ms_distance(&L_MS, &R_MS); assert(area->L_StubLen == 0); assert(area->R_StubLen == 0); calc_area_EdgeLen(area, &d0, &d1); assert(d0>=0); assert(d1>=0); calc_merge_pt_delay(area, d0, d1); if (area_L->R_buffer > 0 && area_R->R_buffer > 0 && area->L_EdgeLen + area->R_EdgeLen > area->dist + FUZZ && area->L_StubLen + area->R_StubLen < area->dist) { assert(equal(d0,0) || equal(d1,0)); } if (mode==FAST) return; construct_TRR_mr(area); } /****************************************************************************/ /* */ /****************************************************************************/ void update_JS_case_ms(double dist) { TrrType ms0,ms1,t0,t1, trr0,trr1; assert(calc_line_type(JS[0][0],JS[0][1]) == MANHATTAN_ARC); line2ms(&ms0,JS[0][0],JS[0][1]); line2ms(&ms1,JS[1][0],JS[1][1]); assert(equal(ms_distance(&ms0,&ms1), dist)); build_trr(&ms0, dist, &trr0); build_trr(&ms1, dist, &trr1); make_intersect(&trr1,&ms0,&t0); make_intersect(&trr0,&ms1,&t1); ms2line(&t0, &(JS[0][0]), &(JS[0][1]) ); ms2line(&t1, &(JS[1][0]), &(JS[1][1]) ); check_JS_MS(); } /********************************************************************/ /* */ /********************************************************************/ int redundant_area(AreaType tmparea[], int n, double newcap, double newskew ) { int i; double cap, skew; for (i=0;i<n;++i) { cap = tmparea[i].capac; skew = area_minskew(&(tmparea[i])); if (equal(newcap, cap) && equal(newskew, skew)) { return(YES); } else if (newcap >= cap - FUZZ && newskew >= skew - FUZZ ) { return(YES); } } return(NO); } /*****************************************************************************/ /* uses the closest pair of boundary segments of children's regions */ /* for constructing new merging regions. */ /****************************************************************************/ void IME_mergeNode_BS2(AreaType *area_L, AreaType *area_R,int *n,int i,int j, int b1, int b2) { TempArea[*n].L_area = i; TempArea[*n].R_area = j; if (b1) {assert(area_L->R_buffer > 0);} else {area_L->R_buffer = 0;} if (b2) {assert(area_R->R_buffer > 0);} else {area_R->R_buffer = 0;} calc_JS(&(TempArea[*n]), area_L, area_R, -1,-1); MergeArea(&(TempArea[*n]), area_L, area_R, NORMAL); (*n)++; /* if (*n>1) tsao_Irredundant(TempArea, n); if (*n >10) kohck_Irredundant(TempArea, n); */ } /*****************************************************************************/ /* */ /****************************************************************************/ void IME_mergeNode_sub4(AreaType *a1, AreaType *area_R, int *n_tmparea, int k1, int k2, int b1, int b2) { int i; AreaType a2; a2 = *area_R; a2.vertex[0] = 0; a2.vertex[1] = 1; for (i=0;i<n_R_sampling;++i) { R_MS = R_sampling[i]; ms2line_delays(area_R,&R_MS,&(a2.mr[0]),&(a2.mr[1])); if (same_Point(a2.mr[0],a2.mr[1])) { a2.n_mr=1; } else { a2.n_mr=2; } a2.npts = a2.n_mr; IME_mergeNode_BS2(a1, &a2,n_tmparea, k1, k2, b1, b2); } if (n_R_sampling!=1 && BST_Mode == HYBRID_MODE) { IME_mergeNode_BS2(a1, area_R,n_tmparea, k1, k2, b1, b2); } } /*****************************************************************************/ /* */ /****************************************************************************/ void IME_mergeNode_sub3(AreaType *area_L, AreaType *area_R, int *n_tmparea, int k1, int k2, int b1, int b2) { int i; AreaType a1; a1 = *area_L; a1.vertex[0] = 0; a1.vertex[1] = 1; for (i=0;i<n_L_sampling;++i) { L_MS = L_sampling[i]; ms2line_delays(area_L,&L_MS,&(a1.mr[0]),&(a1.mr[1])); if (same_Point(a1.mr[0],a1.mr[1])) { a1.n_mr=1; } else { a1.n_mr=2; } a1.npts = a1.n_mr; IME_mergeNode_sub4(&a1, area_R, n_tmparea, k1, k2, b1, b2); } if (n_L_sampling!=1 && BST_Mode == HYBRID_MODE) { IME_mergeNode_sub4(area_L, area_R, n_tmparea, k1, k2, b1, b2); } assert(*n_tmparea>0); } /*****************************************************************************/ /* IME & HYBRID MODE uses both Boundary Segments(BS) & Internal Sampling */ /* Segments(IS)*/ /*****************************************************************************/ int IME_mergeNode_sub1(NodeType *node_L, NodeType *node_R, int b1, int b2) { int i,j,n_tmparea=0; n_tmparea = 0; assert(node_L->n_area > 0); assert(node_R->n_area > 0); for (i=0;i<node_L->n_area;++i) { for (j=0;j<node_R->n_area;++j) { IME_mergeNode_BS2(&(node_L->area[i]), &(node_R->area[j]), &n_tmparea, i, j, b1, b2); assert(n_tmparea>0); } } /* kohck_Irredundant(TempArea, &n_tmparea); */ return(n_tmparea); } /****************************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /****************************************************************************/ void check_sorted_areas(AreaType TempArea[], int n_tmparea) { int i; for (i=0;i<n_tmparea-1;++i) { assert(TempArea[i].subtree_cost <= TempArea[i+1].subtree_cost + FUZZ ); assert(TempArea[i].n_mr <= MAX_mr_PTS); } } /****************************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /****************************************************************************/ void new_IME_mergeNode(NodeType *node, NodeType *node_L, NodeType *node_R, int b1, int b2) { int i, n_tmparea=0; n_tmparea= IME_mergeNode_sub1(node_L, node_R, b1, b2); assert(n_tmparea <= N_TempArea); Max_irredundant_regions = tMAX(Max_irredundant_regions, n_tmparea); qsort(TempArea, n_tmparea, sizeof(AreaType), Area_compare_inc); n_tmparea = tMIN(n_tmparea, N_Area_Per_Node); modify_blocked_areas(TempArea,&n_tmparea, b1, b2); assert(n_tmparea <= N_TempArea); Max_n_regions = tMAX(Max_n_regions, n_tmparea); qsort(TempArea, n_tmparea, sizeof(AreaType), Area_compare_inc); check_sorted_areas(TempArea,n_tmparea); node->n_area = tMIN(n_tmparea, N_Area_Per_Node); for (i=0;i<node->n_area; ++i) { node->area[i] = TempArea[i]; } node->ca = 0; } /****************************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /****************************************************************************/ void IME_mergeNode(NodeType *node, NodeType *node_L, NodeType *node_R, int b1, int b2) { AreaSetType stair, result; int i, n_areas; stair.npoly = n_areas = IME_mergeNode_sub1(node_L, node_R, b1, b2); assert(stair.npoly<= N_TempArea && stair.npoly> 0); assert(Skew_B > 0 || stair.npoly==1); /* select n best merging regions */ result.npoly = tMIN(stair.npoly, N_Area_Per_Node); stair.freg = (AreaType *) calloc(stair.npoly, sizeof(AreaType)); result.freg = (AreaType *) calloc(N_Area_Per_Node, sizeof(AreaType)); assert( stair.freg != NULL ); assert( result.freg != NULL ); for (i=0;i<stair.npoly;++i) { stair.freg[i] = TempArea[i]; } Max_n_regions = tMAX(Max_n_regions, stair.npoly); Irredundant(&stair); Max_irredundant_regions = tMAX(Max_irredundant_regions, stair.npoly); if (Dynamic_Selection) { KStepStair(&stair, N_Area_Per_Node, &result); store_n_areas_IME(node, &result); } else { /* greedy selection */ /* store_last_n_areas_IME(node, &stair); */ for (i=0;i<stair.npoly;++i) { TempArea[i] = stair.freg[i]; } qsort(TempArea, stair.npoly, sizeof(AreaType), Area_compare_inc); if (CHECK==1) check_tmparea(TempArea, stair.npoly); store_n_areas(TempArea, result.npoly, node); } if (CHECK) print_IME_areas(node, node_L, node_R, stair.npoly, n_areas); node->ca = node->n_area-1; free(stair.freg); free(result.freg); } /****************************************************************************/ /* mr(v) = the merging region between merging region mr(L) and mr(R) */ /****************************************************************************/ void NodeType::Merge2Nodes( NodeType *node_L,NodeType *node_R) { ca = 0; AreaType *area = &(this->area[0]); AreaType *area_L = &(node_L->area[node_L->ca]); AreaType *area_R = &(node_R->area[node_R->ca]); if (BST_Mode == BME_MODE) { calc_JS(area, area_L, area_R, -1,-1); MergeArea(area, area_L, area_R, NORMAL); } else { /* IME_Mode || HYBRID_MODE */ new_IME_mergeNode(this, node_L, node_R, area_L->R_buffer, area_R->R_buffer); } } /****************************************************************************/ /* */ /****************************************************************************/ double BME_merging_cost(NodeType *node_L, NodeType *node_R) { AreaType area, *area_L, *area_R; area.n_mr = 0; /* XXXnate */ area_L = &(node_L->area[node_L->ca]); area_R = &(node_R->area[node_R->ca]); calc_JS(&area, area_L,area_R, -1,-1); MergeArea(&area, area_L, area_R, FAST); return(area.subtree_cost); } /****************************************************************************/ /* */ /****************************************************************************/ double IME_merging_cost(NodeType *node_L, NodeType *node_R) { int i,j, n1,n2; double min_cost, cost; n1 = node_L->n_area; n2 = node_R->n_area; min_cost = DBL_MAX; for (i=0;i<n1;++i) { node_L->ca = i; for (j=0;j<n2;++j) { node_R->ca = j; cost = BME_merging_cost(node_L, node_R); min_cost = tMIN(min_cost, cost); } } return(min_cost); } /****************************************************************************/ /* mr(v) = the merging region between merging region mr(L) and mr(R) */ /****************************************************************************/ double calc_merging_cost(int i, int j) { double cost; if (BST_Mode == BME_MODE) { cost = BME_merging_cost(&(CandiRoot[i]), &(CandiRoot[j])); } else { /* IME_Mode */ cost = IME_merging_cost(&(CandiRoot[i]), &(CandiRoot[j])); } return(cost); } /****************************************************************************/ /* mr(v) = the merging region between merging region mr(L) and mr(R) */ /****************************************************************************/ void Merge2Trees_sub3(int v, int L, int R) { Node[L].parent = v; Node[R].parent = v; Node[v].L = L; Node[v].R = R; Node[v].Merge2Nodes ( &(Node[L]), &(Node[R])); build_NodeTRR(&(Node[v])); } /****************************************************************************/ /* mr(v) = the merging region between merging region mr(L) and mr(R) */ /****************************************************************************/ void opt_Merge3Trees_sub1(int v, int L, int R) { int i, min_i, u[3], id[3]; double min_cost, cost, old_cost; NodeType tmpnode; alloca_NodeType(&tmpnode); tmpnode.ca=0; tmpnode.n_area = 1; id[0] = Node[L].L; id[1] = Node[L].R; id[2] = R; for (i=0;i<3;++i) { assert(id[i] != L); if (id[i]<0) return; } min_i = 0; min_cost = old_cost = Node[v].area[Node[v].ca].subtree_cost; for (i=1;i<3;++i) { u[0] = id[i%3]; u[1] = id[(i+1)%3]; u[2] = id[(i+2)%3]; tmpnode.Merge2Nodes (&(Node[u[0]]), &(Node[u[1]])); cost = BME_merging_cost(&tmpnode, &(Node[u[2]])); if (cost < min_cost) { min_cost = cost; min_i = i; } } if (min_i > 0) { u[0] = id[min_i%3]; u[1] = id[(min_i+1)%3]; u[2] = id[(min_i+2)%3]; Merge2Trees_sub3(L, u[0],u[1]); Merge2Trees_sub3(v,L, u[2]); printf(" *** opt_Merge3Trees (V=%d, L=%d, R=%d) (%d,%d,%d)\n", v,L,R, u[0],u[1],u[2]); printf(" cost : %f -> %f (impr: %.0f%%) \n", old_cost, min_cost, (old_cost - min_cost)*100.0/old_cost ); assert(equal(min_cost, Node[v].area[Node[v].ca].subtree_cost)); } free_NodeType(&tmpnode); } /****************************************************************************/ /* */ /****************************************************************************/ void opt_Merge4Trees(int v, int L, int R) { int i, min_i, u[4], id[4]; double min_cost, cost, old_cost; NodeType tmpnode1, tmpnode2; alloca_NodeType(&tmpnode1); alloca_NodeType(&tmpnode2); tmpnode1.ca=0; tmpnode1.n_area = 1; tmpnode2.ca=0; tmpnode2.n_area = 1; id[0] = Node[L].L; id[1] = Node[L].R; id[2] = Node[R].L; id[3] = Node[R].R; for (i=0;i<4;++i) { assert(id[i] != L); assert(id[i] != R); if (id[i]<0) return; } min_i = 0; min_cost = old_cost = Node[v].area[Node[v].ca].subtree_cost; u[3] = id[3]; for (i=1;i<3;++i) { u[0] = id[i%3]; u[1] = id[(i+1)%3]; u[2] = id[(i+2)%3]; tmpnode1.Merge2Nodes (&(Node[u[0]]), &(Node[u[1]])); tmpnode2.Merge2Nodes (&(Node[u[2]]), &(Node[u[3]])); cost = BME_merging_cost(&tmpnode1, &tmpnode2); if (cost < min_cost) { min_cost = cost; min_i = i; } } if (min_i > 0) { u[0] = id[min_i%3]; u[1] = id[(min_i+1)%3]; u[2] = id[(min_i+2)%3]; Merge2Trees_sub3(L, u[0],u[1]); Merge2Trees_sub3(R, u[2],u[3]); Merge2Trees_sub3(v, L, R); printf(" *** opt_Merge4Trees (V=%d, L=%d, R=%d) (%d,%d,%d,%d)\n", v,L,R, u[0],u[1],u[2],u[3]); printf(" cost : %f -> %f (impr: %.0f%%) \n", old_cost, min_cost, (old_cost - min_cost)*100.0/old_cost ); assert(equal(min_cost, Node[v].area[Node[v].ca].subtree_cost)); } free_NodeType(&tmpnode1); free_NodeType(&tmpnode2); } /****************************************************************************/ /* */ /****************************************************************************/ void opt_Merge3Trees(int v, int L, int R) { if (Node[L].area[Node[R].ca].capac > Node[R].area[Node[R].ca].capac) { opt_Merge3Trees_sub1(v,L,R); } else { opt_Merge3Trees_sub1(v,R,L); } } /****************************************************************************/ /* mr(v) = the merging region between merging region mr(L) and mr(R) */ /****************************************************************************/ void Merge2Trees(int v, int L, int R) { double old_cost; Merge2Trees_sub3(v,L,R); /* if (BST_Mode == BME_MODE && detour_Node(v)) { */ if (BST_Mode == BME_MODE && Local_Opt) { do { old_cost = Node[v].area[Node[v].ca].subtree_cost; opt_Merge3Trees(v,Node[v].L,Node[v].R); opt_Merge4Trees(v,Node[v].L,Node[v].R); } while (Node[v].area[Node[v].ca].subtree_cost < old_cost - FUZZ); } /* */ } /******************************************************************/ /* */ /******************************************************************/ void MergeSegment(AreaType *area, int mode){ double d0, d1, h, v; double t0, t1; h = ABS(JS[0][0].x - JS[1][0].x); v = ABS(JS[0][0].y - JS[1][0].y); area->dist = h + v; calc_Bal_of_2pt(&(JS[0][0]), &(JS[1][0]), 0, 0, &d0, &d1, &(area->mr[0])); assert(equal(area->mr[0].max, area->mr[0].min)); check_calc_Bal_of_2pt(&(JS[0][0]), &(JS[1][0]), 0, &(area->mr[0]), d0, d1); if ( d0==0 || d1==0 ) { /* detour happens */ area->n_mr = 1; area->L_EdgeLen = d0; area->R_EdgeLen = d1; } else { area->L_EdgeLen = NIL; area->R_EdgeLen = NIL; if (!equal(v,0) && !equal(h,0)) { area->n_mr = 2; calc_Bal_of_2pt(&(JS[0][0]), &(JS[1][0]), 0, 1, &d0, &d1, &(area->mr[1])); assert(equal(area->mr[1].max, area->mr[1].min)); t0 = pt_delay_increase(Gamma, JS[0][0].t, &(JS[0][0]), &(area->mr[1])); t1 = pt_delay_increase(Gamma, JS[1][0].t, &(JS[1][0]), &(area->mr[1])); assert(equal(JS[0][0].max + t0, JS[1][0].max + t1)); } else { area->n_mr = 1; } } area->vertex[0] = 0; area->vertex[1] = 1; area->npts = area->n_mr; } /****************************************************************************/ /* return the merging area of Node1 and Node2 */ /* Case II: general case where merging areas not equal to merging segments. */ /****************************************************************************/ void MergeNonManhattanArc(AreaType *area,AreaType *area_L,AreaType *area_R, int mode){ assert(area->area_L == area_L); assert(area->area_R == area_R); if (Skew_B == 0 ) { JS[0][0].t = area_L->capac; JS[1][0].t = area_R->capac; MergeSegment(area, mode); } else { construct_mr(area, area_L,area_R,mode); } double origB = gBoundedSkewTree->Orig_Skew_B() ; if (area->n_mr==4 && origB >0 ) assert(!TRR_area(area)); } /****************************************************************************/ /* */ /****************************************************************************/ void cal_ms_merging_cost(AreaType *area,AreaType *area_L,AreaType *area_R) { PointType path[100]; double cost; int n; cost = path_between_JSline(NULL, area->line, path, &n); assert(n<100); area->subtree_cost = cost + area_L->subtree_cost + area_R->subtree_cost; } /***********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /***********************************************************************/ void check_MergeArea1_sub(AreaType *area, PointType *pt) { if (area->R_buffer > 0) { assert(equal(area->capac,C_buffer)); assert(MaxClusterDelay >= pt->max); } else { assert(equal(area->capac,area->unbuf_capac)); } assert(area->npts > 0); assert(area->n_mr > 0); assert(area->npts <= MAXPTS); assert(area->n_mr <= MAX_mr_PTS); } /***********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /***********************************************************************/ void check_MergeArea1(AreaType *area) { check_MergeArea1_sub(area->area_L, &(JS[0][0])); check_MergeArea1_sub(area->area_R, &(JS[1][0])); } /****************************************************************************/ /* */ /****************************************************************************/ void check_MergeArea2(AreaType *area,AreaType *area_L,AreaType *area_R, int mode) { if (mode == NORMAL) { if ( (BST_Mode==BME_MODE && Skew_B == DBL_MAX && area->npts >4) || (BST_Mode==IME_MODE && area->npts >6)) { print_area_info(area); print_area(area_L); print_area(area_R); assert(0); } } } /****************************************************************************/ /* */ /****************************************************************************/ void MergeArea(AreaType *area,AreaType *area_L,AreaType *area_R,int mode) { double ori_dist; PointType orig_line[2][2]; area->area_L = area_L; area->area_R = area_R; area->L_EdgeLen = area->R_EdgeLen = NIL; area->L_StubLen = area->R_StubLen = 0; area->R_buffer = 0; area->ClusterDelay = 0; ori_dist = area->dist; JS_processing(area); orig_line[0][0] = area->line[0][0]; orig_line[0][1] = area->line[0][1]; orig_line[1][0] = area->line[1][0]; orig_line[1][1] = area->line[1][1]; check_MergeArea1(area); if ( 0 && mode==FAST) { cal_ms_merging_cost(area,area_L, area_R); } else { if (case_Manhattan_arc() && PURES[H_]==PURES[V_] && PUCAP[H_]==PUCAP[V_]) { MergeManhattanArc(area,area_L, area_R, mode); double origB = gBoundedSkewTree->Orig_Skew_B() ; if (area->n_mr==4 && origB >0 ) assert(!TRR_area(area)); } else { MergeNonManhattanArc(area,area_L,area_R, mode); } check_MergeArea2(area, area_L, area_R, mode); } if (Manhattan_arc(JS[0][0], JS[0][1]) ) { assert(Manhattan_arc(JS[1][0], JS[1][1])); JS_processing_sub2(area); } else { area->line[0][0] = orig_line[0][0]; area->line[0][1] = orig_line[0][1]; area->line[1][0] = orig_line[1][0]; area->line[1][1] = orig_line[1][1]; } area->dist = ori_dist; MergeArea_sub(area); } /****************************************************************************/ /* */ /****************************************************************************/ void embedding_sub2(int p, int v, PointType pt1, PointType pt2) { TrrType trr1, trr2,ms; PointType &pt = Node[p].m_stnPt ; trr1.MakeDiamond(pt,EdgeLength[v] ); line2ms(&ms, pt1, pt2); make_intersect(&ms, &trr1,&trr2); PointType &qt = Node[v].m_stnPt ; core_mid_point(&trr2, &qt); } /****************************************************************************/ /* */ /****************************************************************************/ double find_new_embedding_pt_sub2(int p,int v,PointType pt1,PointType pt2) { int n; PointType path[100], line[2][2]; double dist; line[0][0] = pt1; line[0][1] = pt2; PointType &pt = Node[p].m_stnPt ; line[1][0] = line[1][1] = pt ; dist = path_between_JSline(NULL, line, path, &n); Node[v].m_stnPt = path[0]; assert(pt_on_line_segment(path[0], pt1,pt2)); return(dist); } /****************************************************************************/ /* */ /****************************************************************************/ double find_new_embedding_pt_sub1(int p,int v,PointType pt1,PointType pt2) { int n1, n2; PointType path1[100], path2[100]; double cost1, cost2; PointType &pt = Node[p].m_stnPt ; cost1 = path_finder(pt1, pt, path1, &n1); assert(n1<=100); cost2 = path_finder(pt2, pt, path2, &n2); assert(n2<=100); if (cost1<=cost2) { Node[v].m_stnPt = path1[0]; } else { Node[v].m_stnPt = path2[0]; } return( tMIN(cost1, cost2)); } /****************************************************************************/ /* */ /****************************************************************************/ double find_new_embedding_pt(int p,int v,PointType pt1,PointType pt2) { double cost; if (p==221 && v==219) { cost = find_new_embedding_pt_sub1(p,v,pt1, pt2); } else { cost = find_new_embedding_pt_sub2(p,v,pt1, pt2); } return(cost); } /****************************************************************************/ /* */ /****************************************************************************/ void embedding_sub(int p, int v, PointType pt1, PointType pt2, double edgelen, AreaType *area) { double dist,a,b, old_dist; int unblocked; TrrType trr1, trr2,ms; assert(p>=0 ); PointType &pt = Node[p].m_stnPt ; PointType &qt = Node[v].m_stnPt ; if (area->n_mr == 4 && TRR_area(area)) { pts2TRR(area->mr, area->n_mr, &trr2); dist = pt2TRR_distance_sub(&pt, &trr2); trr1.MakeDiamond (pt,dist); make_intersect(&trr1, &trr2, &ms); core_mid_point(&ms, &qt ); } else { a = ABS(pt1.x-pt2.x); b = ABS(pt1.y-pt2.y); if ( equal(a,0) && equal(b,0) ) { /* pt1 and pt2 are smae points */ qt = pt1; } else if (equal(a,0)) { /* vertical line */ qt .x = pt1.x; qt .y = pt .y; } else if (equal(b,0)) { /* horizontal line */ qt .x = pt .x; qt .y = pt1.y; } else { /* other types of line segment */ pt2linedist(pt ,pt1, pt2, &(qt )); } assert(pt_on_line_segment(qt , pt1,pt2)); } old_dist = dist = Point_dist(pt, qt ); unblocked = unblocked_segment(&pt, &qt ); if (equal(dist,0) || unblocked ) { /* o.k. */ } else { dist = find_new_embedding_pt(p, v, pt1, pt2); } if ( edgelen == NIL ) { assert(Skew_B != 0 ); EdgeLength[v] = dist; } else { /* detour wiring required */ if (edgelen < dist - FUZZ) { printf("warning: p=%d:v= %d, edgelen = %.9f, dist = %.9f\n", p,v, edgelen,dist); } assert(edgelen >= dist - 100*FUZZ); EdgeLength[v] = tMAX(edgelen,dist); } } /****************************************************************************/ /* */ /****************************************************************************/ void check_embedding(PointType *p0, PointType *p1, AreaType *area) { PointType tmp_pt0, tmp_pt1; if (BST_Mode == BME_MODE) { /* check embedded in MR */ calc_BS_located(p0, area, &tmp_pt0, &tmp_pt1); calc_BS_located(p1, area, &tmp_pt0, &tmp_pt1); } } /*************************************************************************/ /* top-down embedding the tree of merging regions */ /*************************************************************************/ void embedding(int p, int child) { PointType p0, p1; AreaType *area; double t, edgelen; int v; if (child==0) { v = Node[p].L; } else { v = Node[p].R; } area = &(Node[p].area[Node[p].ca]); if (child==0) { edgelen = area->L_EdgeLen; StubLength[v] = area->L_StubLen; p0 = area->line[0][0]; p1 = area->line[0][1]; } else { edgelen = area->R_EdgeLen; StubLength[v] = area->R_StubLen; p0 = area->line[1][0]; p1 = area->line[1][1]; } area = &(Node[v].area[Node[v].ca]); check_embedding(&p0, &p1, area); t = drand48(); if ( t < Gamma) { Node[v].pattern = 1; } else { Node[v].pattern = 0; } embedding_sub(p, v, p0, p1, edgelen, area); assert(StubLength[v] < EdgeLength[v] + FUZZ); int nterms = (int) gBoundedSkewTree->Nterms() ; if (v>=nterms) embedding(v,0); if (v>=nterms) embedding(v,1); } /****************************************************************************/ /* */ /****************************************************************************/ void calc_area_center(AreaType *area, PointType *pt) { double x,y; int i, j, n; x=y=0.0; n = area->npts; for (i=0;i<n;++i) { j = area->vertex[i]; x += area->mr[j].x; y += area->mr[j].y; } pt->x = x/n; pt->y = y/n; } /****************************************************************************/ /* */ /****************************************************************************/ void TopDown_Embedding(int v) { if ( BST_Mode != BME_MODE ) { int i = calc_best_area(v); get_all_areas(v,i); } /* assert(Node[v].ca == Node[v].n_area-1); */ PointType &pt = Node[v].m_stnPt ; NodeType *from = gBoundedSkewTree->SuperRootNode () ; int superRoot = gBoundedSkewTree->SuperRootNodeIndex () ; PointType &qt = from->m_stnPt ; AreaType * area = &(Node[v].area[Node[v].ca]); calc_area_center(area, &(pt )); qt .x = pt .x; qt .y = pt .y; StubLength[superRoot] = EdgeLength[superRoot] = 0; int nterms = (int) gBoundedSkewTree->Nterms() ; if (v>=nterms) embedding(v,0); if (v>=nterms) embedding(v,1); } /****************************************************************************/ /* */ /****************************************************************************/ double skewchecking(int v) { double t, cost, cost2; TopDown_Embedding(v); calc_BST_delay(v); int root = gBoundedSkewTree->RootNodeIndex () ; if (v==root) set_SuperRoot(); calc_TreeCost(v, &cost, &t); cost2 = Node[v].area[Node[v].ca].subtree_cost; if (!equal(cost, cost2)) { assert(equivalent(cost, cost2, 1E-5)); } PointType &pt = Node[v].m_stnPt ; t = pt_skew( pt )-Skew_B; if (t > tMAX(Skew_B/10.0,FUZZ*10) ) { printf("skew[%d] - Skew_Bound = %f ", v, t); bool linear = gBoundedSkewTree->LinearDelayModel () ; if ( !linear ) { printf(" (time unit: ps)"); } printf("\n\n"); print_Point(stdout, pt ); print_node(&(Node[v])); assert(0); } return(cost); } /****************************************************************************/ /* reconstruct tree of merging Node rooted at v */ /****************************************************************************/ void embed_topology(int v) { int L,R; assert(v>=0); unsigned nterms = gBoundedSkewTree->Nterms() ; assert( (unsigned) v>=nterms || Node[v].area[Node[v].ca].npts == 1); assert(Node[v].area[Node[v].ca].npts <=0); L=Node[v].L; R=Node[v].R; unsigned npoints = gBoundedSkewTree->Npoints() ; assert( L>=0 && R>=0 && L <= (int) npoints && R <= (int) npoints); if (Node[L].area[Node[L].ca].npts<=0) { embed_topology(L); } if (Node[R].area[Node[R].ca].npts<=0) { embed_topology(R); } Node[v].Merge2Nodes ( &(Node[L]), &(Node[R])); skewchecking(v); } /****************************************************************************/ /* change the topology of the subtree to be rooted at p. */ /* return the node id of root and the associated merging Node. */ /****************************************************************************/ int change_topology(int p) { int root,o,q,s, old_p = p, old_q; int tree_size1 = 0, tree_size2 = 0; assert( p>=0 && !Marked[p]) ; /* defualt root id and its merging Node */ root = Node[p].root_id; assert(Node[root].parent == NIL); count_tree_nodes(root, root, &tree_size1); old_q = q = Node[p].parent; if (q<0) return(root); s = Node[q].parent; if (s<0) return(root); o=p; p = q; q = s; s = Node[q].parent; while (s > 0) { set_sibling(o,p,q); Node[p].area[Node[p].ca].npts = 0; Node[q].parent = p; o=p; p = q; q = s; s = Node[q].parent; } /* q == root */ q = sibling(p,q); set_sibling(o,p,q); Node[p].area[Node[p].ca].npts = 0; Node[q].parent = p; Node[root].area[Node[root].ca].npts = 0; Node[root].L = old_p; Node[root].R = old_q; Node[old_p].parent = Node[old_q].parent = root; embed_topology(root); count_tree_nodes(root, root, &tree_size2); assert(tree_size1 == tree_size2); assert(root == Node[old_p].root_id); assert(Node[root].parent < 0 ); return(root); } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ static int Ex_DME () { int root = gBoundedSkewTree->RootNodeIndex () ; string fn = gBoundedSkewTree->TopologyFileName () ; read_input_topology( fn ); embed_topology( root ); return root ; } /****************************************************************************/ /* */ /****************************************************************************/ void calloc_TempArea() { int n; n = N_Area_Per_Node*(N_Sampling+1); N_TempArea = 1000; printf("\n\nN_TempArea = %d \n\n", N_TempArea); TempArea = (AreaType *) calloc(N_TempArea, sizeof(AreaType)); assert( TempArea != NULL ); } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ void set_R_buffer_size( int t) { int i; for (i=0;i<N_BUFFER_SIZE;++i) { R_buffer_size[i] = 100 + t*i; } } /****************************************************************************/ /* parse arguments */ /****************************************************************************/ void parse_argument(int argc, char *argv[], BstTree &tree ) { int i, j; char fn[20]; int BRESinc = 20; N_Clusters[1] = 1; N_Clusters[2] = 0; Hierachy_Cluster_id[0] = 0; for (i=1;i<argc;i++) { if (strcmp("-G",argv[i]) == 0) { i++; tree.SetTopologyFileName ( argv[i] ) ; } else if (strcmp("-s",argv[i]) == 0) { i++; sscanf(argv[i],"%d",&N_Sampling); } else if (strcmp("-O",argv[i]) == 0) { // not complete yet i++; sscanf(argv[i],"%s",fn); tree.SetObstructionFileName ( fn ) ; } else if (strcmp("-n",argv[i]) == 0) { // for IME method i++; sscanf(argv[i],"%d",&N_Area_Per_Node); assert(N_Area_Per_Node>1); BST_Mode = IME_MODE; calloc_TempArea(); } else if (strcmp("-DS",argv[i]) == 0) { // for IME method Dynamic_Selection = YES; } else if (strcmp("-H",argv[i]) == 0) { // for IME method BST_Mode = HYBRID_MODE; } else if (strcmp("-D",argv[i]) == 0) { // for delay model i++; unsigned k ; sscanf(argv[i],"%d",&k ); tree.SetDelayModel ( (BST_DME::DelayModelType) k ) ; } else if (strcmp("-BRES",argv[i]) == 0) { // for buffer linear model i++; sscanf(argv[i],"%d",&R_buffer); } else if (strcmp("-BRESinc",argv[i]) == 0) { // for buffer linear model i++; sscanf(argv[i],"%d",&BRESinc); } else if (strcmp("-BCAP",argv[i]) == 0) { // for buffer linear model i++; sscanf(argv[i],"%lf",&C_buffer); C_buffer *= PUCAP_SCALE; } else if (strcmp("-RES",argv[i]) == 0) { // for non-uniform RC model i++; sscanf(argv[i],"%lf",&PURES_V_SCALE); } else if (strcmp("-CAP",argv[i]) == 0) { // for non-uniform RC model i++; sscanf(argv[i],"%lf",&PUCAP_V_SCALE); } else if (strcmp("-B",argv[i]) == 0) { // for skew bound i++; double skew =0 ; sscanf(argv[i],"%lf",&skew); if (skew < 0) { skew = DBL_MAX; } tree.SetSkewBound ( skew ) ; } else if (strcmp("-NCL",argv[i]) == 0) { j = 0; do { i++; j++; sscanf(argv[i],"%d",&(N_Clusters[j])); } while (N_Clusters[j]!=1); N_Buffer_Level = j; } else { printf("Argument %d incorrect\n",i); exit(0); } } set_R_buffer_size(BRESinc); if ( tree.SinksFileName().empty() ) { printf ("usage: bst -i inputFileName -B number (pico-seconds)\n" ) ; exit (0 ) ; } } /****************************************************************************/ /* update v's merging Node as if v were the root of tree root_id. */ /* i.e., update the variable CandiRoot[v] */ /****************************************************************************/ void update_CandiRoot(int v, int root_id, NodeType *node_R) { int par, sib; if (v<0 ) return; par = Node[v].parent; if (v==root_id) { assign_NodeType(&(CandiRoot[v]), &(Node[root_id])); Marked[v] = NO; } else if (par == root_id) { assign_NodeType(&(CandiRoot[v]), &(Node[root_id])); sib = sibling(v, par); assign_NodeType(&(TempNode[v]), &(Node[sib])); Marked[v] = YES; } else { sib = sibling(v, par); TempNode[v].Merge2Nodes ( &(Node[sib]),node_R); CandiRoot[v].Merge2Nodes (&(Node[v]), &(TempNode[v])); if (All_Top == YES || minskew(&(CandiRoot[v]), BST_Mode) <= Skew_B - 0.001 ) { Marked[v]=NO; } else { Marked[v]=YES; } /* Marked[v]=(minskew(&(CandiRoot[v]),BST_Mode) > Skew_B-0.001 ) ? YES: NO; */ } build_NodeTRR(&(CandiRoot[v])); /* if ( minskew(&(CandiRoot[v]), BST_Mode) <= Skew_B - 0.001 ) { */ if ( (Buffered[v]==NO) && (All_Top == YES || minskew(&(CandiRoot[v]), BST_Mode) <= Skew_B - 0.001) ) { update_CandiRoot(Node[v].L, root_id, &(TempNode[v])); update_CandiRoot(Node[v].R, root_id, &(TempNode[v])); } else { init_marked(Node[v].L); init_marked(Node[v].R); } } /******************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /******************************************************************/ int ExG_DME (int n_trees, int v, int show_info) { int i, j, k, n; while (n_trees > 1) { build_nearest_neighbor_graph(v, show_info); n = pairs_to_merge(v); if (show_info) { printf("\n#_trees=%d, #_nodes=%d, #_mering_pairs=%d\n",n_trees, v, n); } n_trees -= n; for (k=0;k<n;k++,v++) { i = Best_Pair[k].x; j = Best_Pair[k].y; /* printf("node %d == merge-pair (%d,%d)\n", v, i, j); */ i = change_topology(i); // change top. of subtree rooted at i j = change_topology(j); // change top. of subtree rooted at j Merge2Trees(v, i, j); updateRootId(v,v); assert(Cluster_id[i] == Cluster_id[j]); Cluster_id[v] = Cluster_id[i]; if (CHECK) skewchecking(v); update_CandiRoot(v,v, NULL); } } return(v); } /****************************************************************************/ /* Initialization */ /****************************************************************************/ void init_a_Node(int i) { Node[i].id = i; Node[i].ca = 0; Node[i].n_area = 1; Node[i].L=Node[i].R=Node[i].parent=-1; Node[i].area[0].L_EdgeLen = Node[i].area[0].R_EdgeLen = EdgeLength[i]=0; Node[i].area[0].R_buffer = 0; StubLength[i] = Node[i].area[0].L_StubLen = Node[i].area[0].R_StubLen = 0; N_neighbors[i]= 0; Cluster[i].x = DBL_MAX; /* min merging cost since this cluster exists */ Buffered[i] = NO; Marked[i] = YES; int nterms = (int) gBoundedSkewTree->Nterms() ; if (i<nterms) { Node[i].root_id = i; Node[i].area[0].n_mr = Node[i].area[0].npts = 1; PointType &pt = Node[i].m_stnPt ; pt = Node[i].area[0].mr[0]; Node[i].area[0].subtree_cost = 0; build_NodeTRR(&(Node[i])); Node[i].area[0].unbuf_capac = Node[i].area[0].capac; } else { Node[i].area[0].n_mr = Node[i].area[0].npts = Node[i].root_id = NIL; Node[i].area[0].mr[0].min = Node[i].area[0].mr[0].max = NIL; Node[i].area[0].unbuf_capac = Node[i].area[0].capac = NIL; } } /********************************************************************/ /* */ /********************************************************************/ void init_all_Nodes() { unsigned npoints = gBoundedSkewTree->Npoints() ; for (unsigned i=0;i<npoints;++i) { init_a_Node(i); } } /****************************************************************************/ /* Initialization */ /* to be used in skew_allocation() in bst_sub2.c */ /****************************************************************************/ void init_skew_allocation() { unsigned nterms = gBoundedSkewTree->Nterms() ; Points = (PointType *) calloc(nterms, sizeof(PointType)); TmpMarked = (int *) calloc(nterms, sizeof(int)); Capac = (double *) calloc(nterms, sizeof(double)); } /****************************************************************************/ /* Initialization */ /****************************************************************************/ void init() { int nterms = (int) gBoundedSkewTree->Nterms() ; N_Clusters[0] = nterms; if (N_Clusters[1]<=0) { unsigned i = ABS(N_Clusters[1]); N_Clusters[1] = (int) sqrt( (double) nterms); N_Clusters[1] = N_Clusters[1]*2/i; } if (Hierachy_Cluster_id[0] == 0) { unsigned npoints = gBoundedSkewTree->Npoints() ; for (unsigned i=0; i<npoints; i++) { Cluster_id[i] = NIL; } } assert(N_Clusters[1] <= MAX_N_SINKS); init_skew_allocation(); } /******************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /******************************************************************/ double calc_max_capac(int L) { double cap; int i, j; cap = 0; for (i=0;i<N_Clusters[L];++i) { j = TreeRoots[i]; cap = tMAX(cap, Node[j].area[0].capac); } return(cap); } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ void set_MaxClusterDelay_sub(int v) { int i, j; for (i=0;i<Node[v].n_area;++i) { for (j=0;j<Node[v].area[i].n_mr; ++j) { MaxClusterDelay = tMAX(MaxClusterDelay, Node[v].area[i].mr[j].max); } } } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ void set_MaxClusterDelay(int cid) { int i; MaxClusterDelay = 0; for (i=0; i<Curr_Npoints; i++) { if (Cluster_id[i] == cid) { set_MaxClusterDelay_sub(i); } } } /******************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /******************************************************************/ static void add_buffer_sub (int v) { int i, j; for (i=0;i<Node[v].n_area;++i) { double t = Delay_buffer+Buffered[v]*(Node[v].area[i].capac); for (j=0;j<Node[v].area[i].n_mr; ++j) { Node[v].area[i].mr[j].max += t; Node[v].area[i].mr[j].min += t; } Node[v].area[i].capac = C_buffer; Node[v].area[i].R_buffer = Buffered[v]; } } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ void set_ClusterDelay_sub(int v) { int i; for (i=0;i<Node[v].n_area;++i) { Node[v].area[i].ClusterDelay = MaxClusterDelay; } } /******************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /******************************************************************/ static void add_buffer (int L, int n_buffer, int buffered_Node[]) { MaxClusterDelay = 0; for (int i=0;i<n_buffer;++i) { int j = buffered_Node[i]; add_buffer_sub (j); set_MaxClusterDelay_sub(j); } for (int i=0;i<n_buffer;++i) { set_ClusterDelay_sub(buffered_Node[i]); } } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ void set_R_buffer_at_Node(double target_delay, int x) { int i ; double min_diff, t, diff; min_diff = DBL_MAX; for (i=0;i<N_BUFFER_SIZE;++i) { t = Node[x].area[0].capac * R_buffer_size[i]; diff = ABS(t - target_delay); if ( diff < min_diff) { min_diff = diff; Buffered[x] = R_buffer_size[i]; } } } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ double calc_Buffered_sub(int L, int n_buffer, int buffered_Node[]) { int x = buffered_Node[0]; double target_delay = Node[x].area[0].capac *Buffered[x] ; for (int i=1;i< n_buffer;++i) { set_R_buffer_at_Node(target_delay, buffered_Node[i]); } double max_t = -DBL_MAX; double min_t = DBL_MAX; for (int i=0;i<N_Clusters[L];++i) { int x = buffered_Node[i]; double t = Node[x].area[0].capac * Buffered[x]; max_t = tMAX( max_t, t); min_t = tMIN( min_t, t); } return(max_t - min_t); } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ static void selct_buffer_size_sub (int L, int n_buffer, int buffered_Node[]) { int i, min_i, x; double diff, min_diff; min_diff = DBL_MAX; for (i=0;i<N_BUFFER_SIZE;++i) { Buffered[buffered_Node[0]] = R_buffer_size[i]; diff = calc_Buffered_sub(L, n_buffer, buffered_Node); if (diff < min_diff) { min_diff = tMIN(diff, min_diff); min_i = i; } } x = buffered_Node[0]; Buffered[x] = R_buffer_size[min_i]; calc_Buffered_sub(L, n_buffer, buffered_Node); } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ static void selct_buffer_size (int L, int n_buffer, int buffered_Node[]) { int i; if (R_buffer > 0) { for (i=0;i<n_buffer;++i) { Buffered[buffered_Node[i]] = R_buffer; } } else { selct_buffer_size_sub (L, n_buffer, buffered_Node); } } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ void print_run(int L, int i, int n_trees) { printf("============================================================\n"); printf("= run ExG_DME on cluster (L=%d:i=%d/%d) cid=%d \n", L, i, N_Clusters[L], Total_CL); printf("= n_trees = %d \n", n_trees); printf("============================================================\n"); } /****************************************************************************/ /* Initialization for ExG-DME */ /****************************************************************************/ static int init_ExG_DME(int cid, int *u) { int i, n; for (i=n=0; i<Curr_Npoints; i++) { if (Cluster_id[i] == cid) { *u = i; Marked[i] = NO; assign_NodeType(&(CandiRoot[i]), &(Node[i])); assign_NodeType(&(TempNode[i]), &(Node[i])); check_root_id(i); n++; } else { Marked[i] = YES; } } assert(n>0); return(n); } /****************************************************************************/ /* Initialization */ /****************************************************************************/ static void init_calc_whole_BST() { unsigned npoints = gBoundedSkewTree->Npoints() ; int nterms = (int) gBoundedSkewTree->Nterms() ; for (unsigned i=nterms; i<npoints; i++) { Cluster_id[i] = NIL; } init_all_Nodes(); } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ void init_BSTs_at_level() { int i; int nterms = (int) gBoundedSkewTree->Nterms() ; for (i=0;i<nterms;++i) { TreeRoots[i] = i; } Curr_Npoints = nterms+1; Total_CL = 0; } /**********************************************************************/ /* construct BSTs at level L of buffer hierachy */ /* build a BST for each clusters of nodes at level L. */ /**********************************************************************/ static void BSTs_at_level(int show_info, int L) { int i, u, n_trees; int buffered_Node[MAX_N_NODES]; int n_buffer = 0; for (i=0;i<N_Clusters[L];++i) { n_trees = init_ExG_DME(Total_CL, &u); if (show_info ) print_run(L,i,n_trees); if (n_trees >1 ) { /* there is a forest */ Curr_Npoints = ExG_DME (n_trees, Curr_Npoints, show_info); buffered_Node[n_buffer++] = TreeRoots[i] = Curr_Npoints-1; } else { /* there is only a single tree */ TreeRoots[i] = u; } Total_CL++; } selct_buffer_size (L, n_buffer, buffered_Node); add_buffer (L, n_buffer, buffered_Node); } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ static void calc_whole_BST(int show_info, int PostOpt, bool fixedTopology ) { int L (0) ; assert ( PostOpt == NO ) ; init_calc_whole_BST(); if (fixedTopology) { int root = Ex_DME(); int buffered_Node[] = { root} ; int n_buffer (1) ; selct_buffer_size (L, n_buffer, buffered_Node); add_buffer (L, n_buffer, buffered_Node); } else { init_BSTs_at_level(); L = 0; do { L++; init_clusters(L, PostOpt); BSTs_at_level(show_info,L); } while (N_Clusters[L]>1); } int root = gBoundedSkewTree->RootNodeIndex () ; skewchecking( root ); if (show_info) print_answer( gBoundedSkewTree->SinksFileName().c_str(), root, fixedTopology ); } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ BST_DME::BST_DME ( const string &inputSinksFileName, const string &inputTopologyFileName, const string &inputObstructionFileName, double skewBound, DelayModelType delayModel ) { m_bstdme = new BstTree (inputSinksFileName,inputTopologyFileName, inputObstructionFileName,skewBound,delayModel ); } ; /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ BST_DME::~BST_DME ( ) { delete m_bstdme ; } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ BstTree::BstTree ( const string &inputSinksFileName, const string &inputTopologyFileName, const string &inputObstructionFileName, double skewBound, BST_DME::DelayModelType delayModel ): m_inputSinksFileName( inputSinksFileName ) , m_inputTopologyFileName( inputTopologyFileName ), m_inputObstructionFileName ( inputObstructionFileName ), m_skewBound ( skewBound ), m_delayModel ( delayModel ) , m_nterms ( 0 ) { } ; /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ BstTree::~BstTree ( ) { } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ void BST_DME::ConstructTree( ) { m_bstdme->ConstructTree() ; } /**********************************************************************/ /* Copyright (C) 1994-2000 by Andrew B. Kahng, C.-W. Albert Tsao */ /**********************************************************************/ void BstTree::ConstructTree( ) { N_Clusters[1] = 1; N_Clusters[2] = 0; gBoundedSkewTree = this ; clock(); string obsFile = ObstructionFileName() ; if ( !obsFile.empty() ) { read_obstacle_file ( obsFile ); print_obstacles( obsFile ); } bool fixTop = FixedTopology(); Skew_B = SkewBound () ; read_input_file( SinksFileName() ) ; init(); print_header( fixTop ); calc_whole_BST(YES, NO, fixTop ); iRunTime(); print_current_time(); }
33.018482
88
0.461963
abk-openroad
f5e14989f48af3b264d68e275c5ed025812e8abb
2,175
cpp
C++
Kernel/Graphics/Intel/NativeGraphicsAdapter.cpp
Anon1428/serenity
0daf5cc434e7a998da15330bd8b4d46ae1759485
[ "BSD-2-Clause" ]
2
2022-02-16T02:12:38.000Z
2022-02-20T18:40:41.000Z
Kernel/Graphics/Intel/NativeGraphicsAdapter.cpp
Anon1428/serenity
0daf5cc434e7a998da15330bd8b4d46ae1759485
[ "BSD-2-Clause" ]
null
null
null
Kernel/Graphics/Intel/NativeGraphicsAdapter.cpp
Anon1428/serenity
0daf5cc434e7a998da15330bd8b4d46ae1759485
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2021, Liav A. <liavalb@hotmail.co.il> * * SPDX-License-Identifier: BSD-2-Clause */ #include <Kernel/Arch/x86/IO.h> #include <Kernel/Bus/PCI/API.h> #include <Kernel/Graphics/Console/ContiguousFramebufferConsole.h> #include <Kernel/Graphics/Definitions.h> #include <Kernel/Graphics/GraphicsManagement.h> #include <Kernel/Graphics/Intel/NativeGraphicsAdapter.h> #include <Kernel/PhysicalAddress.h> namespace Kernel { static constexpr u16 supported_models[] { 0x29c2, // Intel G35 Adapter }; static bool is_supported_model(u16 device_id) { for (auto& id : supported_models) { if (id == device_id) return true; } return false; } RefPtr<IntelNativeGraphicsAdapter> IntelNativeGraphicsAdapter::initialize(PCI::DeviceIdentifier const& pci_device_identifier) { VERIFY(pci_device_identifier.hardware_id().vendor_id == 0x8086); if (!is_supported_model(pci_device_identifier.hardware_id().device_id)) return {}; auto adapter = adopt_ref(*new IntelNativeGraphicsAdapter(pci_device_identifier.address())); MUST(adapter->initialize_adapter()); return adapter; } ErrorOr<void> IntelNativeGraphicsAdapter::initialize_adapter() { auto address = pci_address(); dbgln_if(INTEL_GRAPHICS_DEBUG, "Intel Native Graphics Adapter @ {}", address); auto bar0_space_size = PCI::get_BAR_space_size(address, 0); VERIFY(bar0_space_size == 0x80000); auto bar2_space_size = PCI::get_BAR_space_size(address, 2); dmesgln("Intel Native Graphics Adapter @ {}, MMIO @ {}, space size is {:x} bytes", address, PhysicalAddress(PCI::get_BAR0(address)), bar0_space_size); dmesgln("Intel Native Graphics Adapter @ {}, framebuffer @ {}", address, PhysicalAddress(PCI::get_BAR2(address))); PCI::enable_bus_mastering(address); m_display_connector = IntelNativeDisplayConnector::must_create(PhysicalAddress(PCI::get_BAR2(address) & 0xfffffff0), bar2_space_size, PhysicalAddress(PCI::get_BAR0(address) & 0xfffffff0), bar0_space_size); return {}; } IntelNativeGraphicsAdapter::IntelNativeGraphicsAdapter(PCI::Address address) : GenericGraphicsAdapter() , PCI::Device(address) { } }
35.080645
209
0.741609
Anon1428
f5e1ce0e38e7decbe276e78be8c1f447321de518
8,050
cpp
C++
osquery/tables/utility/osquery.cpp
trizt/osquery
9256819b8161ab1e02ea0d7eb55da132f197723d
[ "BSD-3-Clause" ]
1
2018-10-30T03:58:24.000Z
2018-10-30T03:58:24.000Z
osquery/tables/utility/osquery.cpp
trizt/osquery
9256819b8161ab1e02ea0d7eb55da132f197723d
[ "BSD-3-Clause" ]
null
null
null
osquery/tables/utility/osquery.cpp
trizt/osquery
9256819b8161ab1e02ea0d7eb55da132f197723d
[ "BSD-3-Clause" ]
1
2020-11-04T03:18:37.000Z
2020-11-04T03:18:37.000Z
/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <osquery/config.h> #include <osquery/core.h> #include <osquery/events.h> #include <osquery/extensions.h> #include <osquery/filesystem.h> #include <osquery/flags.h> #include <osquery/logger.h> #include <osquery/packs.h> #include <osquery/registry.h> #include <osquery/sql.h> #include <osquery/system.h> #include <osquery/tables.h> #include "osquery/core/process.h" namespace osquery { DECLARE_bool(disable_logging); DECLARE_bool(disable_events); namespace tables { QueryData genOsqueryEvents(QueryContext& context) { QueryData results; auto publishers = EventFactory::publisherTypes(); for (const auto& publisher : publishers) { Row r; r["name"] = publisher; r["publisher"] = publisher; r["type"] = "publisher"; auto pubref = EventFactory::getEventPublisher(publisher); if (pubref != nullptr) { r["subscriptions"] = INTEGER(pubref->numSubscriptions()); r["events"] = INTEGER(pubref->numEvents()); r["refreshes"] = INTEGER(pubref->restartCount()); r["active"] = (pubref->hasStarted() && !pubref->isEnding()) ? "1" : "0"; } else { r["subscriptions"] = "0"; r["events"] = "0"; r["refreshes"] = "0"; r["active"] = "-1"; } results.push_back(r); } auto subscribers = EventFactory::subscriberNames(); for (const auto& subscriber : subscribers) { Row r; r["name"] = subscriber; r["type"] = "subscriber"; // Subscribers will never 'restart'. r["refreshes"] = "0"; auto subref = EventFactory::getEventSubscriber(subscriber); if (subref != nullptr) { r["publisher"] = subref->getType(); r["subscriptions"] = INTEGER(subref->numSubscriptions()); r["events"] = INTEGER(subref->numEvents()); // Subscribers are always active, even if their publisher is not. r["active"] = (subref->state() == EventState::EVENT_RUNNING) ? "1" : "0"; } else { r["subscriptions"] = "0"; r["events"] = "0"; r["active"] = "-1"; } results.push_back(r); } return results; } QueryData genOsqueryPacks(QueryContext& context) { QueryData results; Config::getInstance().packs([&results](std::shared_ptr<Pack>& pack) { Row r; r["name"] = pack->getName(); r["version"] = pack->getVersion(); r["platform"] = pack->getPlatform(); r["shard"] = INTEGER(pack->getShard()); r["active"] = INTEGER(pack->isActive() ? 1 : 0); auto stats = pack->getStats(); r["discovery_cache_hits"] = INTEGER(stats.hits); r["discovery_executions"] = INTEGER(stats.misses); results.push_back(r); }); return results; } void genFlag(const std::string& name, const FlagInfo& flag, QueryData& results) { Row r; r["name"] = name; r["type"] = flag.type; r["description"] = flag.description; r["default_value"] = flag.default_value; r["value"] = flag.value; r["shell_only"] = (flag.detail.shell) ? "1" : "0"; results.push_back(r); } QueryData genOsqueryFlags(QueryContext& context) { QueryData results; auto flags = Flag::flags(); for (const auto& flag : flags) { if (flag.first.size() > 2) { // Skip single-character flags. genFlag(flag.first, flag.second, results); } } return results; } QueryData genOsqueryRegistry(QueryContext& context) { QueryData results; auto isActive = [](const std::string& plugin, const std::shared_ptr<RegistryHelperCore>& registry) { if (FLAGS_disable_logging && registry->getName() == "logger") { return false; } else if (FLAGS_disable_events && registry->getName().find("event") != std::string::npos) { return false; } const auto& active = registry->getActive(); bool none_active = (active.empty()); return (none_active || plugin == active); }; const auto& registries = RegistryFactory::all(); for (const auto& registry : registries) { const auto& plugins = registry.second->all(); for (const auto& plugin : plugins) { Row r; r["registry"] = registry.first; r["name"] = plugin.first; r["owner_uuid"] = "0"; r["internal"] = (registry.second->isInternal(plugin.first)) ? "1" : "0"; r["active"] = (isActive(plugin.first, registry.second)) ? "1" : "0"; results.push_back(r); } for (const auto& route : registry.second->getExternal()) { Row r; r["registry"] = registry.first; r["name"] = route.first; r["owner_uuid"] = INTEGER(route.second); r["internal"] = "0"; r["active"] = (isActive(route.first, registry.second)) ? "1" : "0"; results.push_back(r); } } return results; } QueryData genOsqueryExtensions(QueryContext& context) { QueryData results; ExtensionList extensions; if (getExtensions(extensions).ok()) { for (const auto& extension : extensions) { Row r; r["uuid"] = SQL_TEXT(extension.first); r["name"] = extension.second.name; r["version"] = extension.second.version; r["sdk_version"] = extension.second.sdk_version; r["path"] = getExtensionSocket(extension.first); r["type"] = (extension.first == 0) ? "core" : "extension"; results.push_back(r); } } const auto& modules = RegistryFactory::getModules(); for (const auto& module : modules) { Row r; r["uuid"] = SQL_TEXT(module.first); r["name"] = module.second.name; r["version"] = module.second.version; r["sdk_version"] = module.second.sdk_version; r["path"] = module.second.path; r["type"] = "module"; results.push_back(r); } return results; } QueryData genOsqueryInfo(QueryContext& context) { QueryData results; Row r; r["pid"] = INTEGER(PlatformProcess::getCurrentProcess()->pid()); r["version"] = kVersion; std::string hash_string; auto s = Config::getInstance().getMD5(hash_string); r["config_hash"] = (s.ok()) ? hash_string : ""; r["config_valid"] = Config::getInstance().isValid() ? INTEGER(1) : INTEGER(0); r["extensions"] = (pingExtension(FLAGS_extensions_socket).ok()) ? "active" : "inactive"; r["build_platform"] = STR(OSQUERY_BUILD_PLATFORM); r["build_distro"] = STR(OSQUERY_BUILD_DISTRO); r["start_time"] = INTEGER(Config::getInstance().getStartTime()); if (Initializer::isWorker()) { r["watcher"] = INTEGER(PlatformProcess::getLauncherProcess()->pid()); } else { r["watcher"] = "-1"; } results.push_back(r); return results; } QueryData genOsquerySchedule(QueryContext& context) { QueryData results; Config::getInstance().scheduledQueries( [&results](const std::string& name, const ScheduledQuery& query) { Row r; r["name"] = SQL_TEXT(name); r["query"] = SQL_TEXT(query.query); r["interval"] = INTEGER(query.interval); // Set default (0) values for each query if it has not yet executed. r["executions"] = "0"; r["output_size"] = "0"; r["wall_time"] = "0"; r["user_time"] = "0"; r["system_time"] = "0"; r["average_memory"] = "0"; r["last_executed"] = "0"; // Report optional performance information. Config::getInstance().getPerformanceStats( name, [&r](const QueryPerformance& perf) { r["executions"] = BIGINT(perf.executions); r["last_executed"] = BIGINT(perf.last_executed); r["output_size"] = BIGINT(perf.output_size); r["wall_time"] = BIGINT(perf.wall_time); r["user_time"] = BIGINT(perf.user_time); r["system_time"] = BIGINT(perf.system_time); r["average_memory"] = BIGINT(perf.average_memory); }); results.push_back(r); }); return results; } } }
29.814815
80
0.616894
trizt
f5e35e246f820c6f0669458b0224d67b42783d4c
763
cpp
C++
HDOJ/5477.cpp
yanMa1995/OnlineJudge
03d8ba2858e6524ff790fcb1112b97894bb8dcfb
[ "Apache-2.0" ]
1
2022-03-03T00:16:20.000Z
2022-03-03T00:16:20.000Z
HDOJ/5477.cpp
yanMa1995/OnlineJudge
03d8ba2858e6524ff790fcb1112b97894bb8dcfb
[ "Apache-2.0" ]
null
null
null
HDOJ/5477.cpp
yanMa1995/OnlineJudge
03d8ba2858e6524ff790fcb1112b97894bb8dcfb
[ "Apache-2.0" ]
null
null
null
//HDOJ #5477 //A Sweet Journey #include <iostream> #include <cstring> #include <cstdio> #include <vector> #include <algorithm> #include <map> #include <set> #include <string> #include <sstream> #include <cmath> #include <stdio.h> using namespace std; int main() { int T; scanf("%d",&T); int n,A,B,L; for(int i=0; i<T; i++) { scanf("%d %d %d %d",&n, &A, &B, &L); int min=100000000; int temp=0; int li, ri; int begin=0; for(int j=0; j<n; j++) { scanf("%d %d", &li, &ri); temp += ((li-begin)*B - (ri-li)*A); begin=ri; if(min>temp) min=temp; } if(min>0) temp=0; else temp=(-1)*min; printf("Case #%d: %d\n", i+1, temp); } return 0; }
14.960784
41
0.498034
yanMa1995
f5e3754ba5e97662acc66dc24e0dd100d94c8c68
2,695
cpp
C++
multiprecision/MPContext.cpp
fionser/MDLHElib
3c686ab35d7b26a893213a6e9d4249cd46c2969d
[ "MIT" ]
5
2017-01-16T06:20:07.000Z
2018-05-17T12:36:34.000Z
multiprecision/MPContext.cpp
fionser/MDLHElib
3c686ab35d7b26a893213a6e9d4249cd46c2969d
[ "MIT" ]
null
null
null
multiprecision/MPContext.cpp
fionser/MDLHElib
3c686ab35d7b26a893213a6e9d4249cd46c2969d
[ "MIT" ]
2
2017-08-26T13:16:35.000Z
2019-03-15T02:08:20.000Z
#include "MPContext.hpp" #include "fhe/NumbTh.h" #include <set> #include <NTL/ZZ.h> #include <cmath> #include <vector> #include <thread> #ifdef FHE_THREADS const long WORKER_NR = 8; #else const long WORKER_NR = 1; #endif static long getSlots(long m, long p) { return phi_N(m) / multOrd(p, m); } static long gcd(long a, long b) { if (a > b) std::swap(a, b); auto r = b % a; while (r > 0) { a = r; b = a; r = b % a; } return a; } bool checkSlots(long required, long check) { if (check < required) return false; return gcd(required, check) == required; } static std::set<long> FindPrimes(long m, long p, long parts) { auto slots = getSlots(m, p); auto bits = static_cast<long>(std::ceil(std::log2(static_cast<double>(p)))); std::set<long> primes; // { // std::vector<long> pprimes = {4139, 7321, 5381, 5783, 4231, 4937, 5279, 6679, 6323, 7459, 6791}; // auto len = pprimes.size(); // for (long pp = 0; pp < parts; pp++) primes.insert(pprimes[len - 1 - pp]); // return primes; // } primes.insert(p); long generated = 1; long trial = 0; while (generated < parts) { auto prime = NTL::RandomPrime_long(bits); auto s = getSlots(m, prime); if (checkSlots(slots, s)) { auto ok = primes.insert(prime); if (ok.second) { generated += 1; } } if (trial++ > 1000) { printf("Error: Can not find enough primes, only found %ld\n", generated); break; } } return primes; } MPContext::MPContext(long m, long p, long r, long parts) : m_r(r) { contexts.reserve(parts); auto primesSet = FindPrimes(m, p, parts); for (auto prime : primesSet) { m_plainSpace *= std::pow(prime, r); m_primes.push_back(prime); } std::vector<std::thread> worker; std::atomic<size_t> counter(0); const size_t num = m_primes.size(); auto job = [this, &counter, &m, &r, &num]() { size_t i; while ((i = counter.fetch_add(1)) < num) { contexts[i] = std::make_shared<FHEcontext>(m, m_primes[i], r); } }; contexts.resize(num); for (long wr = 0; wr < WORKER_NR; wr++) worker.push_back(std::thread(job)); for (auto &&wr : worker) wr.join(); } void MPContext::buildModChain(long L) { std::vector<std::thread> worker; std::atomic<size_t> counter(0); const size_t num = contexts.size(); auto job = [this, &counter, &num, &L]() { size_t i; while ((i = counter.fetch_add(1)) < num) { ::buildModChain(*contexts[i], L); } }; contexts.resize(num); for (long wr = 0; wr < WORKER_NR; wr++) worker.push_back(std::thread(job)); for (auto &&wr : worker) wr.join(); } double MPContext::precision() const { return NTL::log(plainSpace()) / NTL::log(NTL::to_ZZ(2)); }
22.090164
100
0.611132
fionser
f5e4d52202aef2f87fcccf29b5af38f30f655774
648
hpp
C++
core/test/tu-GridPath.hpp
iboB/word-grid
d1029323d5c51499298f3ed19390928371cb70a6
[ "MIT" ]
2
2019-07-01T00:10:43.000Z
2019-09-18T19:37:38.000Z
core/test/tu-GridPath.hpp
iboB/word-grid
d1029323d5c51499298f3ed19390928371cb70a6
[ "MIT" ]
null
null
null
core/test/tu-GridPath.hpp
iboB/word-grid
d1029323d5c51499298f3ed19390928371cb70a6
[ "MIT" ]
2
2019-07-17T17:44:16.000Z
2020-12-21T07:56:11.000Z
// word-grid // Copyright (c) 2019-2021 Borislav Stanimirov // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at // https://opensource.org/licenses/MIT // #pragma once #include <core/Grid.hpp> #include <core/GridPath.hpp> namespace test { inline bool isValidGridPath(const core::GridPath& path, const core::Grid& g) { return path.valid(g.dim()); } inline bool isEmptyGridPath(const core::GridPath& path, const core::Grid& g) { if (!isValidGridPath(path, g)) return false; for (auto& c : path) { if (!g[c].empty()) return false; } return true; } } // namespace test
19.058824
76
0.674383
iboB
f5e579a0e95870a52b8920216bd93fdc81baf317
6,236
inl
C++
include/mathos/vmvector3_sse.inl
napina/mathos
c29bf3d2b9e191d4b3644b49f1d014cbaa787706
[ "MIT" ]
1
2021-03-31T13:14:54.000Z
2021-03-31T13:14:54.000Z
include/mathos/vmvector3_sse.inl
napina/mathos
c29bf3d2b9e191d4b3644b49f1d014cbaa787706
[ "MIT" ]
null
null
null
include/mathos/vmvector3_sse.inl
napina/mathos
c29bf3d2b9e191d4b3644b49f1d014cbaa787706
[ "MIT" ]
null
null
null
/*============================================================================= Copyright (c) 2010 Ville Ruusutie Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================*/ #pragma once #ifndef mathos_vmvector3_sse_inl #define mathos_vmvector3_sse_inl namespace mathos { namespace vm { __forceinline vmvec add3(vmvecFastParam v1, vmvecFastParam v2) { return add4(v1, v2); } __forceinline vmvec sub3(vmvecFastParam v1, vmvecFastParam v2) { return sub4(v1, v2); } __forceinline vmvec cross3(vmvecFastParam v1, vmvecFastParam v2) { const __m128 a = _mm_shuffle_ps(v1, v1, _MM_SHUFFLE(3,0,2,1)); const __m128 b = _mm_shuffle_ps(v2, v2, _MM_SHUFFLE(3,1,0,2)); const __m128 c = _mm_mul_ps(a, b); const __m128 d = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3,0,2,1)); const __m128 e = _mm_shuffle_ps(b, b, _MM_SHUFFLE(3,1,0,2)); const __m128 f = _mm_mul_ps(d, e); return _mm_sub_ps(c, f); } __forceinline vmvec dot3(vmvecFastParam v1, vmvecFastParam v2) { const __m128 m = _mm_mul_ps(v1, v2); const __m128 yz = _mm_shuffle_ps(m, m, _MM_SHUFFLE(2,1,2,1)); const __m128 xy = _mm_add_ss(m, yz); const __m128 z = _mm_shuffle_ps(yz, yz, _MM_SHUFFLE(1,1,1,1)); const __m128 xyz = _mm_add_ss(xy, z); return _mm_shuffle_ps(xyz, xyz, _MM_SHUFFLE(0,0,0,0)); } __forceinline vmvec length3(vmvecFastParam v) { return sqrt4(dot3(v, v)); } __forceinline vmvec lengthEst3(vmvecFastParam v) { return sqrtEst4(dot3(v, v)); } __forceinline vmvec normalize3(vmvecFastParam v) { static const __m128 half = { 0.5f, 0.5f, 0.5f, 0.5f }; static const __m128 three = { 3.0f, 3.0f, 3.0f, 3.0f }; const __m128 lenSq = dot3(v, v); const __m128 r = _mm_rsqrt_ss(lenSq); const __m128 a = _mm_sub_ss(three, _mm_mul_ss(_mm_mul_ss(lenSq, r), r)); const __m128 b = _mm_mul_ss(half, r); const __m128 rq = _mm_mul_ss(a, b); return _mm_mul_ps(v, splatX(rq)); } __forceinline vmvec normalizeEst3(vmvecFastParam v) { return _mm_mul_ps(v, _mm_rsqrt_ps(dot3(v, v))); } __forceinline vmvec reflect3(vmvecFastParam v, vmvecFastParam normal) { __m128 r = dot3(v, normal); r = _mm_add_ps(r, r); r = _mm_mul_ps(r, normal); return _mm_sub_ps(v, r); } __forceinline vmvec refract3(vmvecFastParam v, vmvecFastParam normal, float const refraction) { const __m128 index = _mm_set_ps1(refraction); return refract3(v, normal, index); } __forceinline vmvec refract3(vmvecFastParam v, vmvecFastParam normal, vmvecFastParam refraction) { // Result = RefractionIndex * Incident - Normal * (RefractionIndex * dot(Incident, Normal) + // sqrt(1 - RefractionIndex * RefractionIndex * (1 - dot(Incident, Normal) * dot(Incident, Normal)))) const __m128 IDotN = dot3(v, normal); // R = 1.0f - RefractionIndex * RefractionIndex * (1.0f - IDotN * IDotN) __m128 R = _mm_mul_ps(IDotN, IDotN); R = _mm_sub_ps(splatOne(),R); R = _mm_mul_ps(R, refraction); R = _mm_mul_ps(R, refraction); R = _mm_sub_ps(splatOne(),R); __m128 vResult = _mm_cmple_ps(R, splatZero()); if (_mm_movemask_ps(vResult)==0x0f) { // Total internal reflection vResult = splatZero(); } else { // R = RefractionIndex * IDotN + sqrt(R) R = _mm_sqrt_ps(R); vResult = _mm_mul_ps(refraction,IDotN); R = _mm_add_ps(R,vResult); // Result = RefractionIndex * Incident - Normal * R vResult = _mm_mul_ps(refraction, v); R = _mm_mul_ps(R,normal); vResult = _mm_sub_ps(vResult,R); } return vResult; } __forceinline vmvec transform3(vmvecFastParam v, vmvecFastParam quat) { static const vmmask mask = {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000}; const __m128 a = _mm_and_ps(v, mask.v); const __m128 q = conjugateQ(quat); const __m128 r = mulQ(q, a); return mulQ(r, quat); } __forceinline vmvec transform3(vmvecFastParam v, vmmatParam m) { const __m128 x = _mm_mul_ps(m.row0, _mm_shuffle_ps(v, v, _MM_SHUFFLE(0,0,0,0))); const __m128 y = _mm_mul_ps(m.row1, _mm_shuffle_ps(v, v, _MM_SHUFFLE(1,1,1,1))); const __m128 xy = _mm_add_ps(x, y); const __m128 z = _mm_mul_ps(m.row2, _mm_shuffle_ps(v, v, _MM_SHUFFLE(2,2,2,2))); const __m128 xyz = _mm_add_ps(xy, z); return _mm_add_ps(xyz, m.row3); } __forceinline vmvec transform3(vmvecFastParam v, vmtransParam t) { const __m128 p = _mm_mul_ps(v, splatW(t.posScale)); const __m128 r = transform3(p, t.quat); return _mm_add_ps(r, t.posScale); } __forceinline vmvec transformNormal(vmvecFastParam v, vmvecFastParam quat) { return transform3(v, quat); } __forceinline vmvec transformNormal(vmvecFastParam v, vmmatParam m) { const __m128 x = _mm_mul_ps(m.row0, _mm_shuffle_ps(v, v, _MM_SHUFFLE(0,0,0,0))); const __m128 y = _mm_mul_ps(m.row1, _mm_shuffle_ps(v, v, _MM_SHUFFLE(1,1,1,1))); const __m128 xy = _mm_add_ps(x, y); const __m128 z = _mm_mul_ps(m.row2, _mm_shuffle_ps(v, v, _MM_SHUFFLE(2,2,2,2))); return _mm_add_ps(xy, z); } __forceinline vmvec transformNormal(vmvecFastParam v, vmtransParam t) { return transform3(v, t.quat); } } // end of vm } // end of mathos #endif
33.526882
105
0.683932
napina
f5e6da056b6d99ae95c5796fe8dc11994a6761e8
1,308
hpp
C++
Loyalty/DataModel/Api/ApiException.hpp
uno-labs-solana-hackathon/core-server
fdbdefd32e12fcaa19227f56154e0163c18a35cb
[ "Apache-2.0" ]
null
null
null
Loyalty/DataModel/Api/ApiException.hpp
uno-labs-solana-hackathon/core-server
fdbdefd32e12fcaa19227f56154e0163c18a35cb
[ "Apache-2.0" ]
1
2021-03-06T11:38:01.000Z
2021-03-15T21:33:16.000Z
Loyalty/DataModel/Api/ApiException.hpp
uno-labs-solana-hackathon/core-server
fdbdefd32e12fcaa19227f56154e0163c18a35cb
[ "Apache-2.0" ]
null
null
null
#pragma once #include "ResultCode.hpp" namespace Sol::Loyalty::API::RPC { class SOL_LOYALTY_DATA_MODEL_API_API ApiException final: public GpException { public: using CodeT = ResultCode; using CodeTE = CodeT::EnumT; private: ApiException (void) noexcept = delete; ApiException (const ApiException& aException) noexcept = delete; ApiException& operator= (const ApiException& aException) noexcept = delete; ApiException& operator= (ApiException&& aException) noexcept = delete; public: ApiException (ApiException&& aException) noexcept; ApiException (CodeTE aCode, std::string_view aMsg, const SourceLocationT& aSourceLocation = SourceLocationT::current()) noexcept; virtual ~ApiException (void) noexcept override final; CodeTE Code (void) const noexcept {return iCode;} private: const CodeTE iCode = ResultCode::OK; }; #define THROW_API(CODE, MSG) throw ::Sol::Loyalty::API::RPC::ApiException((CODE), (MSG)) #define THROW_API_COND_CHECK(COND, CODE) if (!(COND)) throw ::Sol::Loyalty::API::RPC::ApiException((CODE), ("Condition not met: "#COND)) #define THROW_API_COND_CHECK_M(COND, CODE, MSG) if (!(COND)) throw ::Sol::Loyalty::API::RPC::ApiException((CODE), (MSG)) }//namespace Sol::Loyalty::API::RPC
34.421053
137
0.70107
uno-labs-solana-hackathon
f5e7c5e1eb94831907bd8da1a035240eeecd8584
797
hpp
C++
code/gui/ImageWindow.hpp
jdkuhnke/uipf
a944237e71cc61be29c641f7320e8ee3a0f0624f
[ "BSD-2-Clause" ]
4
2017-03-26T05:56:57.000Z
2020-02-04T23:14:13.000Z
code/gui/ImageWindow.hpp
jdkuhnke/uipf
a944237e71cc61be29c641f7320e8ee3a0f0624f
[ "BSD-2-Clause" ]
3
2017-05-13T21:30:39.000Z
2018-03-20T17:00:52.000Z
code/gui/ImageWindow.hpp
jdkuhnke/uipf
a944237e71cc61be29c641f7320e8ee3a0f0624f
[ "BSD-2-Clause" ]
3
2017-11-29T10:26:13.000Z
2021-06-15T13:14:04.000Z
#ifndef IMAGEWINDOW_H #define IMAGEWINDOW_H #include <QGraphicsView> #include <QWheelEvent> #include "ModuleInterface.hpp" #include "ModuleLoader.hpp" // TODO rewrite this namespace uipf { class ImageWindow : public QGraphicsView { Q_OBJECT public: ImageWindow(ModuleLoader& mm, QWidget *parent = 0) : QGraphicsView(parent), mm_(mm) {}; ImageWindow(ModuleLoader& mm, QGraphicsScene * scene, QWidget * parent = 0) : QGraphicsView(scene, parent), mm_(mm) {}; ~ImageWindow() {}; protected: void closeEvent(QCloseEvent *event); void keyReleaseEvent(QKeyEvent *event); void resizeEvent ( QResizeEvent * event ); void wheelEvent(QWheelEvent *event); private: ModuleLoader& mm_; bool zoomed_ = false; void zoom(qreal factor); }; } // namespace #endif // MAINWINDOW_H
18.97619
123
0.72522
jdkuhnke
f5ed720e3c1155fb45b008765794b5792ced1fa3
220
cpp
C++
net/test/socket_test.cpp
Leadam/CPX
ec732652b14ef458a33dbf21b2ae13c1164cc42e
[ "MIT" ]
null
null
null
net/test/socket_test.cpp
Leadam/CPX
ec732652b14ef458a33dbf21b2ae13c1164cc42e
[ "MIT" ]
null
null
null
net/test/socket_test.cpp
Leadam/CPX
ec732652b14ef458a33dbf21b2ae13c1164cc42e
[ "MIT" ]
null
null
null
// // Created by lengyel on 2018.10.13.. // #include <gtest/gtest.h> #include "../socket.hpp" TEST(Socket, Constructor){ // NOLINT cpx::net::Socket socket(AF_INET, SOCK_DGRAM, 0); EXPECT_TRUE(socket.good()); }
18.333333
52
0.654545
Leadam
f5ed7ed0b9736935b456785c106e4e0a205c6fdb
3,237
hpp
C++
ode/bla/ngstd.hpp
bschwb/numdiff
68b8ee34476b9efefed31accb378fefc620ec8ef
[ "MIT" ]
null
null
null
ode/bla/ngstd.hpp
bschwb/numdiff
68b8ee34476b9efefed31accb378fefc620ec8ef
[ "MIT" ]
null
null
null
ode/bla/ngstd.hpp
bschwb/numdiff
68b8ee34476b9efefed31accb378fefc620ec8ef
[ "MIT" ]
null
null
null
#ifndef FILE_NGSTD #define FILE_NGSTD /*********************************************************************/ /* File: ngstd.hpp */ /* Author: Joachim Schoeberl */ /* Date: 25. Mar. 2000 */ /*********************************************************************/ /* ng-standard classes */ #include "ngs_stdcpp_include.hpp" #ifdef WIN32 #ifdef NGINTERFACE_EXPORTS #define DLL_HEADER __declspec(dllexport) #else #define DLL_HEADER __declspec(dllimport) #endif #ifdef NGS_EXPORTS #define NGS_DLL_HEADER __declspec(dllexport) #else #define NGS_DLL_HEADER __declspec(dllimport) #endif #else #define DLL_HEADER // #define NGS_DLL_HEADER /* #ifdef NGINTERFACE_EXPORTS #define DLL_HEADER __declspec(dllexport) #else #define DLL_HEADER __declspec(dllimport) #endif */ #ifdef NGS_EXPORTS #define NGS_DLL_HEADER __attribute__ ((visibility ("default"))) #else #define NGS_DLL_HEADER #endif #endif /* inline void * operator new (size_t cnt) { static int cnt_new = 0; cnt_new++; std::cout << "private new called, cnt = " << cnt_new << ", bytes = " << cnt << std::endl; return operator new(cnt, std::nothrow); } inline void * operator new[] (size_t cnt) { static int cnt_new = 0; cnt_new++; std::cout << "private new[] called, cnt = " << cnt_new << ", bytes = " << cnt << std::endl; return operator new[](cnt, std::nothrow); } */ // #include "dynamicmem.hpp" namespace ngstd { NGS_DLL_HEADER extern ::std::ostream * testout; NGS_DLL_HEADER extern int printmessage_importance; } /* namespace ngstd { using netgen::DynamicMem; } */ /** namespace for standard data types and algorithms. Generic container classes: FlatArray, Array, ArrayMem, Table, DynamicTable, HashTable, SymbolTable. Specific data types Exception, BitArray, Flags, LocalHeap, BlockAllocator, NgProfiler, AutoPtr, EvalFunction, AutoDiff, AutoDiffDiff */ namespace ngstd { using namespace std; } //#include "ngs_defines.hpp" //#ifdef USE_MYCOMPLEX //#include "mycomplex.hpp" //#endif //#include "ngs_utils.hpp" #include "archive_base.hpp" //#include "ngsstream.hpp" #include "templates.hpp" #include "exception.hpp" #include "localheap.hpp" //#include "profiler.hpp" // #include "tuple.hpp" #include "array.hpp" //#include "table.hpp" //#include "symboltable.hpp" //#include "hashtable.hpp" #include "bitarray.hpp" // //#include "blockalloc.hpp" //#include "autoptr.hpp" //#include "memusage.hpp" //#include "flags.hpp" // //#include "evalfunc.hpp" //// namespace ngstd { class EvalFunction; } // #include "autodiff.hpp" //#include "autodiffdiff.hpp" //#include "polorder.hpp" //#include "stringops.hpp" //#include "statushandler.hpp" // //#include "mpiwrapper.hpp" //#ifndef WIN32 //#include "sockets.hpp" //#endif //#include "archive.hpp" // namespace ngstd { #ifdef WIN32 const char dirslash = '\\'; #else const char dirslash = '/'; #endif } inline void NOOP_Deleter(void *) { ; } #ifdef GOLD #include <ngstd_gold.hpp> #endif //#include "cuda_ngstd.hpp" #endif
19.267857
132
0.620019
bschwb
f5f04faced6e059e066682d760c4bd6c3d808935
15,228
cpp
C++
Rownd/Content/TexCoSphere.cpp
GarrettVance/Rownd
547d72dd40f75f522d431a1cfc5076166823bd5d
[ "MIT" ]
null
null
null
Rownd/Content/TexCoSphere.cpp
GarrettVance/Rownd
547d72dd40f75f522d431a1cfc5076166823bd5d
[ "MIT" ]
null
null
null
Rownd/Content/TexCoSphere.cpp
GarrettVance/Rownd
547d72dd40f75f522d431a1cfc5076166823bd5d
[ "MIT" ]
null
null
null
// // // // ghv : 2019_01_31 : Texture Coordinate Sphere // // #include "pch.h" #include "Sample3DSceneRenderer.h" #include "..\Common\DirectXHelper.h" using namespace Rownd; using namespace DirectX; using namespace Windows::Foundation; Rownd::VHG_Spherolux Sample3DSceneRenderer::ComputeTextureCoordinates( float pThetaColatitude, float pLambdaLongitude, DirectX::XMFLOAT3 const & pSCentre, float pSRadius, float uLocal, float vLocal ) { XMFLOAT3 eNml = XMFLOAT3(0.f, 0.f, 0.f); eNml.x = sin(pThetaColatitude) * cos(pLambdaLongitude); eNml.z = sin(pThetaColatitude) * sin(pLambdaLongitude); eNml.y = cos(pThetaColatitude); XMFLOAT3 posn = XMFLOAT3(0.f, 0.f, 0.f); posn.x = pSCentre.x + pSRadius * eNml.x; posn.z = pSCentre.z + pSRadius * eNml.z; posn.y = pSCentre.y + pSRadius * eNml.y; #if 3 == 4 float psi = -6.f * std::atanh(sin(pLambdaLongitude)); // experimental undo; posn.x = pSCentre.x + eNml.x * (3.f * cos(pThetaColatitude) / std::cosh(psi)) * pSRadius; posn.y = pSCentre.y - eNml.y * (sin(pThetaColatitude) / std::cosh(psi)) * pSRadius; posn.z = pSCentre.z + eNml.z * (2.f * sinh(psi) / std::cosh(psi)) * pSRadius; #endif XMFLOAT2 texGlobal = XMFLOAT2(0.f, 0.f); // Classic: texGlobal.x = 2.f * pLambdaLongitude / (float)DirectX::XM_2PI; // aka texco_u; // Classic: texGlobal.y = 1.f - pThetaColatitude / (float)DirectX::XM_PI; // aka texco_v; XMFLOAT2 texLocal = XMFLOAT2(uLocal, vLocal); // // Polar coordinates <polco_radius, polco_phi> // are used to identify points on the unit disk D: // // 0 <= polco_radius <= 1 and // -pi < polco_phi <= +pi; // float polco_phi = pLambdaLongitude - DirectX::XM_PI / 2.f; #if 1 == 2 float polco_radius = sin(pThetaColatitude / 2.f); // Equal-area Projection (Lambert Azimuthal); #else // ghv: The factor of 2.f multiplying tan() is aethstetic: float polco_radius = 2.f * tan(pThetaColatitude / 2.f); // Modified Conformal Projection (Altered Stereographic); #endif float u_diskPolar = polco_radius * cos(polco_phi); float v_diskPolar = polco_radius * sin(polco_phi); texGlobal.x = u_diskPolar; texGlobal.y = v_diskPolar; return Rownd::VHG_Spherolux(posn, eNml, texGlobal, texLocal); } void Sample3DSceneRenderer::TexCoSphereCreateVertexBuffer() { //======================================================================== // see http://cse.csusb.edu/tongyu/courses/cs520/notes/texture.php // which in turn quotes Paul Bourke. // // // // Create a sphere centered at sCentre, with radius sRadius, // and precision nPrecision. // // Use sRadius = 1.6f with nPrecision = 24; // // Note: Just draw a point for zero radius spheres... // //======================================================================== XMFLOAT3 sCentre = XMFLOAT3(0.f, 0.f, 0.f); // Locates the center of the sphere; float sRadius = 1.8f; // use 1.8f; uint32_t nPrecision = 24; // use 24; VHG_Spherolux tmpSpherolux{ }; std::vector<Rownd::VHG_Spherolux> vectorVB; std::vector<uint32_t> vectorIndexes; uint32_t idxV = 0; uint32_t idxColat = 0; // Colatitude loop index; uint32_t jdxLongit = 0; // Longitude loop index; float thetaColatitude = 0.f; // the present value of Colatitude; float lambdaLongitude = 0.f; // the present value of Longitude; for (jdxLongit = 0; jdxLongit < nPrecision; jdxLongit++) { for (idxColat = 0; idxColat < nPrecision; idxColat++) // For Colatitude ranging from zero to pi: { thetaColatitude = idxColat * DirectX::XM_PI / (float)nPrecision; // Colatitude; lambdaLongitude = jdxLongit * DirectX::XM_2PI / (float)nPrecision; // Longitude; tmpSpherolux = ComputeTextureCoordinates( thetaColatitude, lambdaLongitude, sCentre, sRadius, 0.f, 0.f ); vectorVB.push_back(tmpSpherolux); lambdaLongitude = (1 + jdxLongit) * DirectX::XM_2PI / (float)nPrecision; // Longitude; tmpSpherolux = ComputeTextureCoordinates( thetaColatitude, lambdaLongitude, sCentre, sRadius, 1.f, 0.f ); vectorVB.push_back(tmpSpherolux); thetaColatitude = (1 + idxColat) * DirectX::XM_PI / (float)nPrecision; // Colatitude; lambdaLongitude = jdxLongit * DirectX::XM_2PI / (float)nPrecision; // Longitude; tmpSpherolux = ComputeTextureCoordinates( thetaColatitude, lambdaLongitude, sCentre, sRadius, 0.f, 1.f ); vectorVB.push_back(tmpSpherolux); lambdaLongitude = (1 + jdxLongit) * DirectX::XM_2PI / (float)nPrecision; // Longitude; tmpSpherolux = ComputeTextureCoordinates( thetaColatitude, lambdaLongitude, sCentre, sRadius, 1.f, 1.f ); vectorVB.push_back(tmpSpherolux); vectorIndexes.push_back(idxV); vectorIndexes.push_back(idxV + 2); vectorIndexes.push_back(idxV + 1); vectorIndexes.push_back(idxV + 3); vectorIndexes.push_back(idxV + 1); vectorIndexes.push_back(idxV + 2); idxV += 4; } } uint32_t vertex_count = (uint32_t)vectorVB.size(); Sphere1_indexCount = (uint32_t)vectorIndexes.size(); D3D11_SUBRESOURCE_DATA vertexBufferData = {0}; vertexBufferData.pSysMem = &(vectorVB[0]); vertexBufferData.SysMemPitch = 0; vertexBufferData.SysMemSlicePitch = 0; CD3D11_BUFFER_DESC vertexBufferDesc( (UINT)vectorVB.size() * sizeof(VHG_Spherolux), D3D11_BIND_VERTEX_BUFFER ); DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateBuffer( &vertexBufferDesc, &vertexBufferData, &Sphere1_vertexBuffer ) ); D3D11_SUBRESOURCE_DATA indexBufferData = {0}; indexBufferData.pSysMem = &(vectorIndexes[0]); indexBufferData.SysMemPitch = 0; indexBufferData.SysMemSlicePitch = 0; CD3D11_BUFFER_DESC indexBufferDesc( (UINT)vectorIndexes.size() * sizeof(uint32_t), D3D11_BIND_INDEX_BUFFER ); DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateBuffer( &indexBufferDesc, &indexBufferData, &Sphere1_indexBuffer ) ); } void Sample3DSceneRenderer::TexCoSphereRender(void) { // // Render the sphere: // auto context = m_deviceResources->GetD3DDeviceContext(); UINT stride = sizeof(VHG_Spherolux); UINT offset = 0; context->IASetVertexBuffers( 0, 1, Sphere1_vertexBuffer.GetAddressOf(), &stride, &offset ); // Each entry of the Index Buffer is a uint32_t value, having size of 32 bits: context->IASetIndexBuffer( Sphere1_indexBuffer.Get(), DXGI_FORMAT_R32_UINT, 0 ); context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); context->IASetInputLayout(Sphere1_inputLayout.Get()); context->VSSetShader(Sphere1_vertexShader.Get(), nullptr, 0 ); context->VSSetConstantBuffers1( 0, 1, m_constantBuffer.GetAddressOf(), nullptr, nullptr ); // Slot zero; context->RSSetState(Sphere1_RasterizerState.Get()); //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // In this case const float gv_blend_factor[4] = { 1.f, 1.f, 1.f, 1.0f }; isn't used at all; context->OMSetBlendState(Sphere1_BlendState.Get(), NULL, 0xFFFFFFFF); // keywords: blendstate, alpha, blending; // This particular blendstate blending DOESN'T require changes in DeviceResources.cpp!!! //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% context->PSSetShader( Sphere1_pixelShader.Get(), nullptr, 0 ); #ifdef GHV_OPTION_SHOW_PRETTY_HYPERBOLIC context->PSSetShaderResources(0, 1, Sphere1_TextureSRV.GetAddressOf()); // Slot zero; #else context->PSSetShaderResources(0, 1, Sphere1_DDS_A_SRV.GetAddressOf()); // Slot zero; #endif context->PSSetSamplers(0, 1, Sphere1_TextureSamplerState.GetAddressOf()); // Slot zero; context->DrawIndexed( Sphere1_indexCount, 0, 0 ); } void Sample3DSceneRenderer::TexCoSphereCreateSamplerStateGeneric() { //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Create a SamplerState for Pixel Shader //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ D3D11_SAMPLER_DESC sampDesc; ZeroMemory(&sampDesc, sizeof(sampDesc)); sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; sampDesc.MinLOD = 0; sampDesc.MaxLOD = D3D11_FLOAT32_MAX; DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateSamplerState( &sampDesc, Sphere1_TextureSamplerState.ReleaseAndGetAddressOf()) ); } void Sample3DSceneRenderer::TexCoSphereDDSTextureFromFile(void) { // // DDS image properties: // =============================== // // File "asdf.dds" // originated as a full-color 923 x 923, 24 bpp, 96 dpi bmp. // // It was scaled down to 512 x 512 pixels, 24 bpp, 96 dpi bmp. // // Then the color depth of the image // was increased back to 24 bpp (using Increase Color Depth). // // Thus a 512 x 512 pixel full color 24 bpp 96 dpi bmp. // // The bmp bitmap was then converted to dds in gimp using // dds image properties: // Format: RGBA8, // Generate mipmaps: 10 mipmap levels. // Microsoft::WRL::ComPtr<ID3D11Resource> tmpResource; DX::ThrowIfFailed( DirectX::CreateDDSTextureFromFile( m_deviceResources->GetD3DDevice(), L"Assets\\a_square256.dds", tmpResource.ReleaseAndGetAddressOf(), Sphere1_DDS_A_SRV.ReleaseAndGetAddressOf(), 0, nullptr ) ); DX::ThrowIfFailed( tmpResource.CopyTo( Sphere1_DDS_A_Texture.ReleaseAndGetAddressOf() ) ); } void Sample3DSceneRenderer::TexCoSphereCreateRasterizerState(void) { D3D11_RASTERIZER_DESC rasterizer_description; ZeroMemory(&rasterizer_description, sizeof(rasterizer_description)); rasterizer_description.MultisampleEnable = FALSE; // rasterizer_description.FillMode = D3D11_FILL_WIREFRAME; rasterizer_description.FillMode = D3D11_FILL_SOLID; // SOLID; rasterizer_description.CullMode = D3D11_CULL_NONE; // Use CULL_NONE when BlendState makes sphere transparent; rasterizer_description.FrontCounterClockwise = true; // undo false; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Benefits of D3D11_CULL_NONE in the RASTERIZER: // ===================================================== // Suppose a 3D spinning cube is being rendered by D3D11. // And furthermore suppose the color has its alpha channel // set low enough to make the cube transparent. // Then in order to present a compelling illusion of a // view into the interior of the semi-transparent cube // it is NECESSARY to render triangles which otherwise // might be culled. // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ DX::ThrowIfFailed(m_deviceResources->GetD3DDevice()->CreateRasterizerState( &rasterizer_description, Sphere1_RasterizerState.ReleaseAndGetAddressOf() )); } void Sample3DSceneRenderer::TexCoSphereCreateBlendState(void) { // // ghv: The Sphere1_BlendState is applied to the texcosphere // while the sphere is being rendered, and this BlendState // allows one to see inside the texcosphere: the objects // inside the sphere become visible through the transparency // of the sphere. // D3D11_RENDER_TARGET_BLEND_DESC rt_blend_descr = { 0 }; rt_blend_descr.BlendEnable = TRUE; rt_blend_descr.SrcBlend = D3D11_BLEND_SRC_ALPHA; // SrcBlend = D3D11_BLEND_SRC_ALPHA; rt_blend_descr.DestBlend = D3D11_BLEND_INV_SRC_ALPHA; // DestBlend = D3D11_BLEND_INV_SRC_ALPHA; rt_blend_descr.BlendOp = D3D11_BLEND_OP_ADD; // BlendOp = D3D11_BLEND_OP_ADD; rt_blend_descr.SrcBlendAlpha = D3D11_BLEND_ONE; rt_blend_descr.DestBlendAlpha = D3D11_BLEND_ZERO; rt_blend_descr.BlendOpAlpha = D3D11_BLEND_OP_ADD; rt_blend_descr.RenderTargetWriteMask = 0x0F; D3D11_BLEND_DESC d3d11_blend_descr = { 0 }; d3d11_blend_descr.AlphaToCoverageEnable = TRUE; // Need AlphaToCoverageEnable = TRUE to make sphere transparent; // This is probably because the DDS image is of a multi-pane glass window fixture, // a matrix of glass with alpha = 0 ==> fully transparent // separated by "wooden" cross members...which are opaque as wood often is. // d3d11_blend_descr.IndependentBlendEnable = FALSE; d3d11_blend_descr.IndependentBlendEnable = TRUE; d3d11_blend_descr.RenderTarget[0] = { rt_blend_descr }; DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateBlendState( &d3d11_blend_descr, Sphere1_BlendState.GetAddressOf() ) ); }
24.760976
119
0.561663
GarrettVance
f5f42a637043d33995359db90e2f2abcc6a8edc7
4,363
cpp
C++
plugins/robots/common/ev3Kit/src/communication/bluetoothRobotCommunicationThread.cpp
ikonovalova/trik-studio
f084274a7663bb7f341169ee029e46b6079c7274
[ "Apache-2.0" ]
null
null
null
plugins/robots/common/ev3Kit/src/communication/bluetoothRobotCommunicationThread.cpp
ikonovalova/trik-studio
f084274a7663bb7f341169ee029e46b6079c7274
[ "Apache-2.0" ]
null
null
null
plugins/robots/common/ev3Kit/src/communication/bluetoothRobotCommunicationThread.cpp
ikonovalova/trik-studio
f084274a7663bb7f341169ee029e46b6079c7274
[ "Apache-2.0" ]
null
null
null
/* Copyright 2007-2015 QReal Research Group * * 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 "ev3Kit/communication/bluetoothRobotCommunicationThread.h" #include <QtCore/QMetaType> #include <QtCore/QTimer> #include <QtCore/QThread> #include <QtCore/QFileInfo> #include <qrkernel/settingsManager.h> #include <plugins/robots/thirdparty/qextserialport/src/qextserialport.h> #include "ev3Kit/communication/commandConstants.h" #include "ev3Kit/communication/ev3DirectCommand.h" const int keepAliveResponseSize = 5; using namespace ev3::communication; BluetoothRobotCommunicationThread::BluetoothRobotCommunicationThread() : mPort(nullptr) , mKeepAliveTimer(new QTimer(this)) { QObject::connect(mKeepAliveTimer, &QTimer::timeout, this, &BluetoothRobotCommunicationThread::checkForConnection); } BluetoothRobotCommunicationThread::~BluetoothRobotCommunicationThread() { disconnect(); } bool BluetoothRobotCommunicationThread::send(QObject *addressee, const QByteArray &buffer, int responseSize) { if (!mPort) { emit response(addressee, QByteArray()); return false; } const bool result = send1(buffer); if (buffer.size() >= 5 && buffer[4] == enums::commandType::CommandTypeEnum::DIRECT_COMMAND_REPLY) { QByteArray const result = receive(responseSize); emit response(addressee, result); } else { emit response(addressee, QByteArray()); } return result; } bool BluetoothRobotCommunicationThread::connect() { if (mPort && mPort->isOpen()) { emit connected(true, QString()); return true; } const QString portName = qReal::SettingsManager::value("Ev3BluetoothPortName").toString(); mPort = new QextSerialPort(portName, QextSerialPort::Polling); mPort->setBaudRate(BAUD9600); mPort->setFlowControl(FLOW_OFF); mPort->setParity(PAR_NONE); mPort->setDataBits(DATA_8); mPort->setStopBits(STOP_2); mPort->setTimeout(3000); mPort->open(QIODevice::ReadWrite | QIODevice::Unbuffered); // Sending "Keep alive" command to check connection. keepAlive(); const QByteArray response = receive(keepAliveResponseSize); emit connected(!response.isEmpty(), QString()); mKeepAliveTimer->moveToThread(this->thread()); mKeepAliveTimer->disconnect(); QObject::connect(mKeepAliveTimer, &QTimer::timeout, this, &BluetoothRobotCommunicationThread::checkForConnection); mKeepAliveTimer->start(500); return !response.isEmpty(); } void BluetoothRobotCommunicationThread::reconnect() { connect(); } void BluetoothRobotCommunicationThread::disconnect() { if (mPort) { mPort->close(); delete mPort; mPort = nullptr; mKeepAliveTimer->stop(); } emit disconnected(); } void BluetoothRobotCommunicationThread::allowLongJobs(bool allow) { Q_UNUSED(allow); } bool BluetoothRobotCommunicationThread::send(const QByteArray &buffer, int responseSize, QByteArray &outputBuffer) { const bool result = send1(buffer); outputBuffer = receive(responseSize); return result; } bool BluetoothRobotCommunicationThread::send1(const QByteArray &buffer) const { return mPort && (mPort->write(buffer) > 0); } QByteArray BluetoothRobotCommunicationThread::receive(int size) const { return mPort ? mPort->read(size) : QByteArray(); } void BluetoothRobotCommunicationThread::checkForConnection() { if (!mPort || !mPort->isOpen()) { return; } keepAlive(); const QByteArray response = receive(keepAliveResponseSize); if (response == QByteArray()) { emit disconnected(); mKeepAliveTimer->stop(); } } void BluetoothRobotCommunicationThread::keepAlive() { QByteArray command = Ev3DirectCommand::formCommand(10, 0, 0, 0 , enums::commandType::CommandTypeEnum::DIRECT_COMMAND_REPLY); int index = 7; Ev3DirectCommand::addOpcode(enums::opcode::OpcodeEnum::KEEP_ALIVE, command, index); Ev3DirectCommand::addByteParameter(10, command, index); // 10 - Number of minutes before entering sleep mode. send1(command); }
27.967949
115
0.762549
ikonovalova
f5f514340561a900546ffe7a2a756765e562519b
1,752
cpp
C++
test/msg/msg_queue_thread_test.cpp
ccup/mcl
4f9fc954de7c696539430daee06a7218517d6c0f
[ "Apache-2.0" ]
10
2020-09-07T02:39:51.000Z
2021-09-26T00:44:40.000Z
test/msg/msg_queue_thread_test.cpp
ccup/mcl
4f9fc954de7c696539430daee06a7218517d6c0f
[ "Apache-2.0" ]
null
null
null
test/msg/msg_queue_thread_test.cpp
ccup/mcl
4f9fc954de7c696539430daee06a7218517d6c0f
[ "Apache-2.0" ]
1
2020-09-11T01:21:42.000Z
2020-09-11T01:21:42.000Z
#include <cctest/cctest.h> #include "mcl/msg/msg_queue.h" #include "mcl/lock/atom.h" #include "mcl/thread/thread.h" namespace { constexpr MclSize MSG_QUEUE_CAPACITY = 10; MclMsg msgBuff[MSG_QUEUE_CAPACITY]; MclMsgQueue mq = MCL_MSG_QUEUE(msgBuff, MSG_QUEUE_CAPACITY); constexpr uint16_t TRY_COUNT = 10000; MclAtom SENT_COUNT = 0; MclAtom RECV_COUNT = 0; uint16_t value = 0xcd; uint16_t outValue = 0; void* sendMsg(void *) { for (uint16_t i = 0; i < TRY_COUNT; i++) { MclMsg msg = MCL_MSG(0, i, sizeof(value), &value); if (!MCL_FAILED(MclMsgQueue_Send(&mq, &msg))) { MclAtom_AddFetch(&SENT_COUNT, 1); } MclThread_Yield(); } return NULL; } void* recvMsg(void *) { for (uint16_t i = 0; i < TRY_COUNT; i++) { MclMsg msg = MCL_MSG(0, 0, sizeof(outValue), &outValue); if (!MCL_FAILED(MclMsgQueue_Recv(&mq, &msg))) { MclAtom_AddFetch(&RECV_COUNT, 1); } MclThread_Yield(); } return NULL; } } FIXTURE(MsgQueueThreadTest) { BEFORE { MclAtom_Clear(&SENT_COUNT); MclAtom_Clear(&RECV_COUNT); } TEST("should execute correct in multi threads") { MclThread s1, s2, r1, r2; MclThread_Create(&s1, NULL, sendMsg, NULL); MclThread_Create(&s2, NULL, sendMsg, NULL); MclThread_Create(&r1, NULL, recvMsg, NULL); MclThread_Create(&r2, NULL, recvMsg, NULL); MclThread_Join(s1, NULL); MclThread_Join(s2, NULL); MclThread_Join(r1, NULL); MclThread_Join(r2, NULL); ASSERT_EQ(SENT_COUNT, RECV_COUNT + MclMsgQueue_GetCount(&mq)); } };
27.375
70
0.5879
ccup
f5fdca3110d65da7c2d358dfd86e745bdac8c2eb
3,800
hh
C++
src/events/Event.hh
imulilla/openMSX_TSXadv_nofork
4ee003d87a44633c14c054bd59ec2bfd866e5d9f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/events/Event.hh
imulilla/openMSX_TSXadv_nofork
4ee003d87a44633c14c054bd59ec2bfd866e5d9f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/events/Event.hh
imulilla/openMSX_TSXadv_nofork
4ee003d87a44633c14c054bd59ec2bfd866e5d9f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
#ifndef EVENT_HH #define EVENT_HH #include <string> namespace openmsx { class TclObject; enum EventType { OPENMSX_KEY_UP_EVENT, OPENMSX_KEY_DOWN_EVENT, OPENMSX_KEY_GROUP_EVENT, OPENMSX_MOUSE_MOTION_EVENT, OPENMSX_MOUSE_MOTION_GROUP_EVENT, OPENMSX_MOUSE_BUTTON_UP_EVENT, OPENMSX_MOUSE_BUTTON_DOWN_EVENT, OPENMSX_MOUSE_BUTTON_GROUP_EVENT, OPENMSX_MOUSE_WHEEL_EVENT, OPENMSX_MOUSE_WHEEL_GROUP_EVENT, OPENMSX_JOY_AXIS_MOTION_EVENT, OPENMSX_JOY_AXIS_MOTION_GROUP_EVENT, OPENMSX_JOY_HAT_EVENT, OPENMSX_JOY_HAT_GROUP_EVENT, OPENMSX_JOY_BUTTON_UP_EVENT, OPENMSX_JOY_BUTTON_DOWN_EVENT, OPENMSX_JOY_BUTTON_GROUP_EVENT, OPENMSX_FOCUS_EVENT, OPENMSX_RESIZE_EVENT, OPENMSX_FILEDROP_EVENT, OPENMSX_FILEDROP_GROUP_EVENT, OPENMSX_QUIT_EVENT, OPENMSX_OSD_CONTROL_RELEASE_EVENT, OPENMSX_OSD_CONTROL_PRESS_EVENT, OPENMSX_BOOT_EVENT, // sent when the MSX resets or power ups /** Sent when VDP (V99x8 or V9990) reaches the end of a frame */ OPENMSX_FINISH_FRAME_EVENT, /** Sent when a OPENMSX_FINISH_FRAME_EVENT caused a redraw of the screen. * So in other words send when a OPENMSX_FINISH_FRAME_EVENT event was send * and the frame was not skipped and the event came from the active video * source. */ OPENMSX_FRAME_DRAWN_EVENT, OPENMSX_BREAK_EVENT, OPENMSX_SWITCH_RENDERER_EVENT, /** Used to schedule 'taking reverse snapshots' between Z80 instructions. */ OPENMSX_TAKE_REVERSE_SNAPSHOT, /** Command received on CliComm connection */ OPENMSX_CLICOMMAND_EVENT, /** Send when an after-emutime command should be executed. */ OPENMSX_AFTER_TIMED_EVENT, /** Send when a (new) machine configuration is loaded */ OPENMSX_MACHINE_LOADED_EVENT, /** Send when a machine is (de)activated. * This events is specific per machine. */ OPENMSX_MACHINE_ACTIVATED, OPENMSX_MACHINE_DEACTIVATED, /** Send when (part of) the openMSX window gets exposed, and thus * should be repainted. */ OPENMSX_EXPOSE_EVENT, /** Delete old MSXMotherboards */ OPENMSX_DELETE_BOARDS, OPENMSX_MIDI_IN_READER_EVENT, OPENMSX_MIDI_IN_WINDOWS_EVENT, OPENMSX_MIDI_IN_COREMIDI_EVENT, OPENMSX_MIDI_IN_COREMIDI_VIRTUAL_EVENT, OPENMSX_RS232_TESTER_EVENT, NUM_EVENT_TYPES // must be last }; class Event { public: Event(const Event&) = delete; Event& operator=(const Event&) = delete; EventType getType() const { return type; } /** Get a string representation of this event. */ std::string toString() const; /** Similar to toString(), but retains the structure of the event. */ virtual TclObject toTclList() const = 0; bool operator< (const Event& other) const; bool operator> (const Event& other) const; bool operator<=(const Event& other) const; bool operator>=(const Event& other) const; bool operator==(const Event& other) const; bool operator!=(const Event& other) const; /** Should 'bind -repeat' be stopped by 'other' event. * Normally all events should stop auto-repeat of the previous * event. But see OsdControlEvent for some exceptions. */ virtual bool isRepeatStopper(const Event& /*other*/) const { return true; } /** Does this event 'match' the given event. Normally an event * only matches itself (as defined by operator==). But e.g. * MouseMotionGroupEvent matches any MouseMotionEvent. */ virtual bool matches(const Event& other) const { return *this == other; } protected: explicit Event(EventType type_) : type(type_) {} ~Event() = default; private: virtual bool lessImpl(const Event& other) const = 0; const EventType type; }; // implementation for events that don't need additional data class SimpleEvent final : public Event { public: explicit SimpleEvent(EventType type_) : Event(type_) {} TclObject toTclList() const override; bool lessImpl(const Event& other) const override; }; } // namespace openmsx #endif
27.142857
77
0.773947
imulilla
f5fee3371ed29e6cae2a1c7c3cd62f0734aaa25d
2,816
cpp
C++
JContainers/src/gtest.cpp
SilverIce/JContainers
98ca31304a74e299d1f7f003602c55fb07e866ee
[ "MIT" ]
39
2015-01-16T09:17:05.000Z
2021-12-15T23:02:00.000Z
JContainers/src/gtest.cpp
SilverIce/JContainers
98ca31304a74e299d1f7f003602c55fb07e866ee
[ "MIT" ]
26
2015-01-03T20:26:27.000Z
2019-12-30T22:46:15.000Z
JContainers/src/gtest.cpp
SilverIce/JContainers
98ca31304a74e299d1f7f003602c55fb07e866ee
[ "MIT" ]
14
2015-10-23T08:46:01.000Z
2022-03-24T18:08:24.000Z
#include "gtest.h" //#include "typedefs_p.h" #include <stdio.h> #include <intrin.h> #include <string> #include <exception> namespace testing { static bool IsDisabled(const TestInfo& info) { const char * text = "DISABLED"; return strncmp(info.name2, text, strlen(text)) == 0; } struct Statistics { //int countTestsFailed; int countChecksFailed; int countDisabledTests; int countFailedTests; int countTotalTests; explicit Statistics() { memset(this, 0, sizeof(*this)); } void OnTestsComplete() { printf("\n"); printf("%d tests failed\n", countFailedTests); printf("%d tests disabled\n", countDisabledTests); printf("%d tests total amount\n", countTotalTests); } }; struct State : public Statistics { bool currentFailed; }; bool runTests(const meta<TestInfo>::list& list) { State state; for (auto& test : list) { state.currentFailed = false; ++state.countTotalTests; if (IsDisabled(test)) { printf(" %s::%s is disabled\n", test.name, test.name2); ++state.countDisabledTests; continue; } printf(" %s::%s has been invoked\n", test.name, test.name2); try { test.function(state); } catch(const std::exception& exception) { char text[1024] = {'\0'}; sprintf_s(text, "test throws exception\n" " of type '%s' message '%s'\n", typeid(exception).name(), exception.what() ); ::testing::check(state, false, __FUNCTION__, text); \ } catch(...) { ::testing::check(state, false, __FUNCTION__, "test throws exception"); \ } if (state.currentFailed) printf(" %s::%s has been failed!\n", test.name, test.name2); } state.OnTestsComplete(); return state.countFailedTests == 0; } void check(State& teststate, bool result, const char* source, const char* errorMessage) { if (result) return; printf("In '%s': %s\n", source, errorMessage); ++teststate.countChecksFailed; if (!teststate.currentFailed) { teststate.currentFailed = true; ++teststate.countFailedTests; } __debugbreak(); } TEST(gtest, test_self) { EXPECT_TRUE( true ); EXPECT_FALSE( false ); EXPECT_EQ( 1, 1); EXPECT_THROW( throw "expected_exception", char* ); EXPECT_NOTHROW( ; ); } TEST_DISABLED(gtest, disabled) { EXPECT_TRUE( false ); } }
26.819048
96
0.529119
SilverIce
eb069235c56842e3a3f65867f800e68ab32b54b9
1,166
hpp
C++
lib/STL+/strings/string_shared_ptr.hpp
knela96/Game-Engine
06659d933c4447bd8d6c8536af292825ce4c2ab1
[ "Unlicense" ]
3
2018-05-07T19:09:23.000Z
2019-05-03T14:19:38.000Z
deps/stlplus/strings/string_shared_ptr.hpp
evpo/libencryptmsg
fa1ea59c014c0a9ce339d7046642db4c80fc8701
[ "BSD-2-Clause-FreeBSD", "BSD-3-Clause" ]
null
null
null
deps/stlplus/strings/string_shared_ptr.hpp
evpo/libencryptmsg
fa1ea59c014c0a9ce339d7046642db4c80fc8701
[ "BSD-2-Clause-FreeBSD", "BSD-3-Clause" ]
null
null
null
#ifndef STLPLUS_STRING_SHARED_PTR #define STLPLUS_STRING_SHARED_PTR //////////////////////////////////////////////////////////////////////////////// // Author: Andy Rushton // Copyright: (c) Southampton University 1999-2004 // (c) Andy Rushton 2004 onwards // License: BSD License, see ../docs/license.html // Generate a string representation of a shared pointer //////////////////////////////////////////////////////////////////////////////// #include "strings_fixes.hpp" #include <memory> #include <string> //////////////////////////////////////////////////////////////////////////////// namespace stlplus { template<typename T, typename S> std::string shared_ptr_to_string(const std::shared_ptr<T>& value, S to_string_fn, const std::string& empty_string = "<empty>", const std::string& null_string = "<null>", const std::string& prefix = "(", const std::string& suffix = ")"); } // end namespace stlplus #include "string_shared_ptr.tpp" #endif
33.314286
80
0.453688
knela96
eb08a61f77475c329b551503be807e6d4a251a00
11,479
cpp
C++
src/info.cpp
Audionut/torrenttools
1d365e0629abe1b23b5be5bac16b24dd38ae56b5
[ "MIT" ]
null
null
null
src/info.cpp
Audionut/torrenttools
1d365e0629abe1b23b5be5bac16b24dd38ae56b5
[ "MIT" ]
null
null
null
src/info.cpp
Audionut/torrenttools
1d365e0629abe1b23b5be5bac16b24dd38ae56b5
[ "MIT" ]
null
null
null
#include <string_view> #include <fmt/format.h> #include <fmt/chrono.h> #include <filesystem> #include <string> #include <chrono> #include <ranges> #include <bencode/bview.hpp> #include <bencode/events/encode_json_to.hpp> #include "dottorrent/metafile.hpp" #include "dottorrent/serialization/all.hpp" #include "info.hpp" #include "argument_parsers.hpp" #include "formatters.hpp" #include "tree_view.hpp" #include "config.hpp" #ifdef __unix__ #include <unistd.h> #endif #include "escape_binary_fields.hpp" #include "cli_helpers.hpp" namespace fs = std::filesystem; namespace dt = dottorrent; namespace bc = bencode; namespace rng = std::ranges; namespace tt = torrenttools; using namespace std::string_view_literals; using namespace std::chrono_literals; using namespace bencode::literals; constexpr std::string_view program_name = PROJECT_NAME; constexpr std::string_view program_version_string = PROJECT_VERSION; void run_info_app(const main_app_options& main_options, const info_app_options& options) { verify_metafile(options.metafile); if (options.raw) { create_raw_info(std::cout, options.metafile, options.show_pieces); return; } auto m = dottorrent::load_metafile(options.metafile); auto protocol_version = m.storage().protocol(); formatting_options fmt_options {.show_padding_files = options.show_padding_files}; #ifdef __unix__ if (!isatty(STDOUT_FILENO)) { fmt_options.use_color = false; } #endif create_general_info(std::cout, m, options.metafile, protocol_version, fmt_options); } void configure_info_app(CLI::App* app, info_app_options& options) { CLI::callback_t metafile_parser = [&](const CLI::results_t& v) -> bool { options.metafile = metafile_target_transformer(v); return true; }; app->add_option("target", metafile_parser, "Target bittorrent metafile.") ->type_name("<path>") ->required(); auto* raw_option = app->add_flag("--raw", options.raw, "Print the metafile data formatted as JSON. Binary data is filtered out.") ->default_val(false); auto* show_pieces_option = app->add_flag("--show-pieces", options.show_pieces, "Print the metafile data formatted as JSON.\n" "Binary data is included as hexadecimal strings.") ->default_val(false); show_pieces_option->needs(raw_option); app->add_flag("--show-padding-files", options.show_padding_files, "Show padding files in the file tree.") ->default_val(false); } auto format_multiline(std::string_view key, std::string_view value, const formatting_options& options) -> std::string { std::vector<std::string_view> strings; std::string::size_type pos = 0; std::string::size_type prev = 0; std::string result; auto out = std::back_inserter(result); pos = value.find('\n', prev); fmt::format_to(out, fmt::runtime(options.entry_format), key, value.substr(prev, pos-prev)); prev = pos + 1; while ((pos = value.find('\n', prev)) != std::string::npos) { fmt::format_to(out, fmt::runtime(options.entry_continuation_format), value.substr(prev, pos - prev)); prev = pos + 1; } return result; } std::string format_indented_list( const std::string& key, const std::vector<std::string>& values, const formatting_options& options) { std::string result; auto out = std::back_inserter(result); if (values.empty()) { fmt::format_to(out, fmt::runtime(options.entry_format), key, ""); return result; } fmt::format_to(out, fmt::runtime(options.entry_format), key, values.at(0)); for (std::size_t i = 1; i < values.size(); ++i) { fmt::format_to(out, fmt::runtime(options.entry_continuation_format), values.at(i)); } return result; } // Pass protocol_version explicitly since not yet hashed torrent cannot query the protocol from // the file_storage. void create_general_info(std::ostream& os, const dt::metafile& metafile, const fs::path& metafile_path, dt::protocol protocol_version, const formatting_options& options) { const auto& m = metafile; auto out = std::ostreambuf_iterator<char>(os); const std::string piece_size = fmt::format( fmt::runtime(options.piece_size_format), tt::format_size(m.piece_size()), m.piece_size()); std::string creation_date; if (m.creation_date() != 0s) { std::time_t timestamp = m.creation_date().count(); std::tm* datetime = std::gmtime(&timestamp); creation_date = fmt::format( fmt::runtime(options.creation_date_format), *datetime, timestamp); } const auto& entry = options.entry_format; const std::string& source_path = metafile_path.string(); std::string protocol_version_string = tt::format_protocol_version(protocol_version); const std::string& comment = format_multiline("Comment"sv, m.comment(), options); static const auto general_template = ( "Metafile: {metafile_path}\n" "Protocol version: {protocol_version}\n" "{infohash_string}" "Piece size: {piece_size}\n" "Piece count: {piece_count}\n" "Created by: {created_by}\n" "Created on: {creation_date}\n" "Private: {private}\n" "Name: {name}\n" "Source: {source}\n" "Comment: {comment}\n" ); // Check if torrent file is hashed so we can return to infohash std::string info_hash_string {}; if (auto protocol = metafile.storage().protocol(); protocol != dt::protocol::none) { if ((protocol & dt::protocol::hybrid) == dt::protocol::hybrid ) { auto infohash_v1 = dt::info_hash_v1(metafile).hex_string(); auto infohash_v2 = dt::info_hash_v2(metafile).hex_string(); info_hash_string = fmt::format( "Infohash: v1: {}\n" " v2: {}\n", infohash_v1, infohash_v2); } // v2-only else if ((protocol & dt::protocol::v2) == dt::protocol::v2) { auto infohash_v2 = dt::info_hash_v2(metafile).hex_string(); info_hash_string = fmt::format( "Infohash: {}\n", infohash_v2); } // v1-only else if ((protocol & dt::protocol::v1) == dt::protocol::v1) { auto infohash_v1 = dt::info_hash_v1(metafile).hex_string(); info_hash_string = fmt::format( "Infohash: {}\n", infohash_v1); } } fmt::format_to(out, fmt::runtime(general_template), fmt::arg("metafile_path", metafile_path.string()), fmt::arg("protocol_version", protocol_version_string), fmt::arg("infohash_string", info_hash_string), fmt::arg("piece_size", piece_size), fmt::arg("piece_count", m.piece_count()), fmt::arg("private", m.is_private()), fmt::arg("created_by", m.created_by()), fmt::arg("creation_date", creation_date), fmt::arg("name", m.name()), fmt::arg("source", m.source()), fmt::arg("comment", m.comment()) ); std::vector<std::string> similar_torrents_infohashes{}; for (const auto& k: m.similar_torrents()) { switch (k.version()) { case dt::protocol::v1: { similar_torrents_infohashes.push_back(k.v1().hex_string()); break; } case dt::protocol::v2: { similar_torrents_infohashes.push_back(k.v2().hex_string()); break; } case dt::protocol::hybrid: { similar_torrents_infohashes.push_back(k.v1().hex_string()); similar_torrents_infohashes.push_back(k.v2().hex_string()); break; } } } format_announces(os, metafile, options); std::vector<std::string> dht_nodes_strings; rng::transform(m.dht_nodes(), std::back_inserter(dht_nodes_strings), [](auto node){ return std::string(node);}); std::vector<std::string> collections(m.collections().begin(), m.collections().end()); rng::copy(format_indented_list("DHT nodes:", dht_nodes_strings, options), out); rng::copy(format_indented_list("Web seeds:", m.web_seeds(), options), out); rng::copy(format_indented_list("HTTP seeds:", m.http_seeds(), options), out); rng::copy(format_indented_list("Similar torrents:", similar_torrents_infohashes, options), out); rng::copy(format_indented_list("Collections:", collections, options), out); tree_options tree_fmt_options { .use_color = options.use_color, .list_padding_files = options.show_padding_files }; std::string file_tree; if (m.storage().file_count() < 1000) { file_tree = format_file_tree(m, " ", tree_fmt_options); } else { file_tree = "\nMetafile contains more than 1000 files: skipping file tree ...\n"; } auto file_stats = format_file_stats(m, " ", options.show_padding_files); fmt::format_to(out, "\nFiles:\n{}\n{}\n", file_tree, file_stats); } void format_announces(std::ostream& os, const dottorrent::metafile& metafile, const formatting_options& options) { std::ostreambuf_iterator out {os}; constexpr auto tracker_tier_entry = "tier {} - {}"sv; constexpr auto tracker_entry = " - {}"sv; const auto& announce_urls = metafile.trackers(); if (announce_urls.empty()) { fmt::format_to(out, fmt::runtime(options.entry_format), "Announce-urls:", ""); return; } std::size_t tier_index = 0; auto [tier_begin, tier_end] = announce_urls.get_tier(tier_index); auto line = fmt::format(tracker_tier_entry, tier_index+1, *tier_begin++); fmt::format_to(out, fmt::runtime(options.entry_format), "Announce-urls:", line); // Finish current tier for ( ; tier_begin != tier_end; ++tier_begin) { line = fmt::format(tracker_entry, *tier_begin); fmt::format_to(out, fmt::runtime(options.entry_continuation_format), line); } // Finish other tiers for (tier_index += 1; tier_index < announce_urls.tier_count(); ++tier_index) { auto [tier_begin, tier_end] = announce_urls.get_tier(tier_index); auto line = fmt::format(tracker_tier_entry, tier_index+1, *tier_begin++); fmt::format_to(out, fmt::runtime(options.entry_continuation_format), line); for ( ; tier_begin != tier_end; ++tier_begin) { line = fmt::format(tracker_entry, *tier_begin); fmt::format_to(out, fmt::runtime(options.entry_continuation_format), line); } } } /// Format the raw structure but replace strings with raw bytes by placeholder strings. void create_raw_info(std::ostream& os, const fs::path& metafile_path, bool include_binary) { auto ifs = std::ifstream(metafile_path); auto bv = bencode::decode_value(ifs); if (!include_binary) { bv = escape_binary_metafile_fields(bv); } else { bv = escape_binary_metafile_fields_hex(bv); } auto formatter = bc::events::encode_json_to{std::cout}; bencode::connect(formatter, bv); std::cout << std::endl; }
35.103976
116
0.628713
Audionut
eb1143ee98aab485465fab34bfaca366725d3d82
30,145
cpp
C++
modules/core/src/Aquila/core/Algorithm.cpp
dtmoodie/Acquilla
b395b7d1338221369f9b0b46c7abc20f7bc5e827
[ "MIT" ]
null
null
null
modules/core/src/Aquila/core/Algorithm.cpp
dtmoodie/Acquilla
b395b7d1338221369f9b0b46c7abc20f7bc5e827
[ "MIT" ]
null
null
null
modules/core/src/Aquila/core/Algorithm.cpp
dtmoodie/Acquilla
b395b7d1338221369f9b0b46c7abc20f7bc5e827
[ "MIT" ]
null
null
null
#include <Aquila/core/Algorithm.hpp> #include <Aquila/utilities/container.hpp> #include <MetaObject/params/IParam.hpp> #include <MetaObject/params/ISubscriber.hpp> #include <MetaObject/params/buffers/IBuffer.hpp> #include <RuntimeObjectSystem/ISimpleSerializer.h> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/rolling_mean.hpp> #include <boost/accumulators/statistics/rolling_window.hpp> using namespace mo; using namespace aq; Algorithm::Algorithm() { m_logger = mo::getLogger(); } void Algorithm::setEnabled(bool value) { m_enabled = value; } bool Algorithm::getEnabled() const { return m_enabled; } mo::ConstParamVec_t Algorithm::getComponentParams(const std::string& filter) const { mo::ConstParamVec_t output; // = mo::IMetaObject::getParams(filter); for (auto& component : m_algorithm_components) { auto shared = component.lock(); if (shared) { auto output2 = shared->getParams(filter); output.insert(output.end(), output2.begin(), output2.end()); } } return output; } mo::ParamVec_t Algorithm::getComponentParams(const std::string& filter) { mo::ParamVec_t output; // = mo::IMetaObject::getParams(filter); for (auto& component : m_algorithm_components) { auto shared = component.lock(); if (shared) { auto output2 = shared->getParams(filter); output.insert(output.end(), output2.begin(), output2.end()); } } return output; } mo::ParamVec_t Algorithm::getParams(const std::string& filter) { mo::ParamVec_t output = mo::MetaObject::getParams(filter); for (auto& component : m_algorithm_components) { auto shared = component.lock(); if (shared) { auto output2 = shared->getParams(filter); output.insert(output.end(), output2.begin(), output2.end()); } } return output; } mo::ConstParamVec_t Algorithm::getParams(const std::string& filter) const { mo::ConstParamVec_t output = mo::MetaObject::getParams(filter); for (auto& component : m_algorithm_components) { auto shared = component.lock(); if (shared) { auto output2 = shared->getParams(filter); output.insert(output.end(), output2.begin(), output2.end()); } } return output; } const mo::IControlParam* Algorithm::getParam(const std::string& name) const { auto output = IAlgorithm::getParam(name); if (output) { return output; } for (auto& component : m_algorithm_components) { auto shared = component.lock(); if (shared) { output = shared->getParam(name); if (output) { return output; } } } return output; } mo::IControlParam* Algorithm::getParam(const std::string& name) { auto output = IAlgorithm::getParam(name); if (output) { return output; } for (auto& component : m_algorithm_components) { auto shared = component.lock(); if (shared) { output = shared->getParam(name); if (output) { return output; } } } return output; } bool Algorithm::process() { mo::Lock_t lock(getMutex()); if (m_enabled == false) { return false; } if (checkInputs() == InputState::kNONE_VALID) { return false; } if (processImpl()) { clearModifiedInputs(); return true; } return false; } const mo::IPublisher* Algorithm::getOutput(const std::string& name) const { auto output = mo::MetaObject::getOutput(name); if (output) { return output; } if (!output) { for (auto& component : m_algorithm_components) { auto shared = component.lock(); if (shared) { output = shared->getOutput(name); if (output) { return output; } } } } return nullptr; } mo::IPublisher* Algorithm::getOutput(const std::string& name) { auto output = mo::MetaObject::getOutput(name); if (output) { return output; } if (!output) { for (auto& component : m_algorithm_components) { auto shared = component.lock(); if (shared) { output = shared->getOutput(name); if (output) { return output; } } } } return nullptr; } IMetaObject::PublisherVec_t Algorithm::getOutputs(const std::string& name_filter) { auto outputs = mo::MetaObject::getOutputs(name_filter); for (auto& component : m_algorithm_components) { auto shared = component.lock(); if (shared) { auto comp_outputs = shared->getOutputs(name_filter); outputs.insert(outputs.end(), comp_outputs.begin(), comp_outputs.end()); } } return outputs; } IMetaObject::ConstPublisherVec_t Algorithm::getOutputs(const std::string& name_filter) const { auto outputs = mo::MetaObject::getOutputs(name_filter); for (auto& component : m_algorithm_components) { auto shared = component.lock(); if (shared) { auto comp_outputs = shared->getOutputs(name_filter); outputs.insert(outputs.end(), comp_outputs.begin(), comp_outputs.end()); } } return outputs; } IMetaObject::PublisherVec_t Algorithm::getOutputs(const mo::TypeInfo& type_filter, const std::string& name_filter) { auto outputs = mo::MetaObject::getOutputs(type_filter, name_filter); for (auto& component : m_algorithm_components) { auto shared = component.lock(); if (shared) { auto comp_outputs = shared->getOutputs(type_filter, name_filter); outputs.insert(outputs.end(), comp_outputs.begin(), comp_outputs.end()); } } return outputs; } IMetaObject::ConstPublisherVec_t Algorithm::getOutputs(const mo::TypeInfo& type_filter, const std::string& name_filter) const { auto outputs = mo::MetaObject::getOutputs(type_filter, name_filter); for (auto& component : m_algorithm_components) { auto shared = component.lock(); if (shared) { auto comp_outputs = shared->getOutputs(type_filter, name_filter); outputs.insert(outputs.end(), comp_outputs.begin(), comp_outputs.end()); } } return outputs; } bool Algorithm::checkModified(const std::vector<mo::ISubscriber*>& inputs) const { for (auto input : inputs) { if (input->hasNewData()) { LOG_ALGO(trace, "param {} has new data", input->getName()); return true; } } return false; } bool Algorithm::checkModifiedControlParams() const { auto params = this->getParams(); for (auto param : params) { if (param->checkFlags(mo::ParamFlags::kCONTROL)) { if (auto control = static_cast<const mo::IControlParam*>(param)) { if (control->getModified()) { LOG_ALGO(trace, "control param {} has been modified", param->getName()); return true; } } } } return false; } Algorithm::InputState Algorithm::syncTimestamp(const mo::Time& ts, const std::vector<mo::ISubscriber*>& inputs) { if (m_ts && (*m_ts == ts)) { // return InputState::kNOT_UPDATED; if (!checkModified(inputs) && !checkModifiedControlParams()) { LOG_ALGO(debug, "Timestamp already processed and no inputs have been modified"); return InputState::kNOT_UPDATED; } } FrameNumber fn; mo::Header header(ts); for (auto input : inputs) { auto data = input->getData(&header); if (data) { LOG_ALGO(trace, "Got data at {} when requesting data at {} from input {}", data->getHeader().timestamp, ts, input->getName()); } else { if (input->checkFlags(mo::ParamFlags::kDESYNCED)) { data = input->getData(); if (data != nullptr) { continue; } } if (input->checkFlags(mo::ParamFlags::kOPTIONAL)) { // If the input isn't set and it's optional then this is ok if (auto input_param = input->getPublisher()) { // Input is optional and set, but couldn't get the right timestamp, error if (auto buf_ptr = dynamic_cast<mo::buffer::IBuffer*>(input_param)) { mo::OptionalTime start, end; buf_ptr->getTimestampRange(start, end); LOG_ALGO(debug, "Failed to get input '{}' at timestamp {} buffer range [{}, {}]", input->getTreeName(), ts, start, end); } else { LOG_ALGO(debug, "Failed to get input '{}' at timestamp {}", input->getTreeName(), ts); } } else { LOG_ALGO(trace, "Optional input not set '{}'", input->getTreeName()); } } else { // Input is not optional if (auto param = input->getPublisher()) { if (param->checkFlags(mo::ParamFlags::kUNSTAMPED)) { continue; } if (param->checkFlags(mo::ParamFlags::kBUFFER)) { auto buffer = dynamic_cast<mo::buffer::IBuffer*>(param); mo::OptionalTime begin, end; if (buffer->getTimestampRange(begin, end)) { if (begin && end) { LOG_ALGO(trace, "Failed to get input for '{}' ({}) at timestamp {}, input buffer: {} -> {}", input->getTreeName(), param->getTreeName(), ts, *begin, *end); } else { LOG_ALGO(trace, "Failed to get input for '{}' ({}) at timestamp {}, input buffer is empty", input->getTreeName(), param->getTreeName(), ts); } } } else { auto data = param->getData(); if (data) { LOG_ALGO(trace, "Failed to get input for '{}' ({}) at timestamp {}, input contains {}", input->getTreeName(), param->getTreeName(), ts, data->getHeader()); } else { LOG_ALGO(trace, "Failed to get input for '{}' ({}) at timestamp {}, input is empty", input->getTreeName(), param->getTreeName(), ts); } } return InputState::kNONE_VALID; } LOG_ALGO(trace, "Input not set '{}'", input->getTreeName()); return InputState::kNONE_VALID; } } } m_ts = ts; m_fn = fn; LOG_ALGO(debug, "All inputs pass, ready to process"); return Algorithm::InputState::kALL_VALID; } Algorithm::InputState Algorithm::syncFrameNumber(size_t fn, const std::vector<mo::ISubscriber*>& inputs) { boost::optional<mo::Time> ts; std::vector<mo::OptionalTime> tss; mo::Header header(fn); for (auto input : inputs) { if (!input->isInputSet() && !input->checkFlags(mo::ParamFlags::kOPTIONAL)) { MO_LOG(trace, "Input not set '{}'", input->getTreeName()); return InputState::kNONE_VALID; } auto data = input->getData(&header); if (data) { tss.push_back(data->getHeader().timestamp); } else { if (input->checkFlags(mo::ParamFlags::kDESYNCED)) { continue; } if (input->checkFlags(mo::ParamFlags::kOPTIONAL)) { // If the input isn't set and it's optional then this is ok if (input->isInputSet()) { // Input is optional and set, but couldn't get the right timestamp, error MO_LOG( debug, "Input is set to \"{}\" but could not get at frame number {}", input->getTreeName(), fn); } else { MO_LOG(trace, "Optional input not set '{}'", input->getTreeName()); } } else { // Input is not optional if (auto param = input->getPublisher()) { if (param->checkFlags(mo::ParamFlags::kBUFFER)) { auto buffer = dynamic_cast<mo::buffer::IBuffer*>(param); uint64_t begin, end; if (buffer->getFrameNumberRange(begin, end)) { LOG_ALGO(trace, "Failed to get input for '{}' ({}) at framenumber {}, input buffer: {} -> {}", input->getTreeName(), param->getTreeName(), fn, begin, end); } } else { auto data = param->getData(); if (data) { LOG_ALGO(trace, "Failed to get input for '{}' ({}) at timestamp {}, input contains {}", input->getTreeName(), param->getTreeName(), fn, data->getHeader()); } else { LOG_ALGO(trace, "Failed to get input for '{}' ({}) at timestamp {}, input is empty", input->getTreeName(), param->getTreeName(), fn); } } return InputState::kNONE_VALID; } else { MO_LOG(trace, "Input not set for '{}'", input->getTreeName()); } } } } if (m_fn == fn) { if (!checkModified(inputs)) { return InputState::kNOT_UPDATED; } } if (m_ts) { if (std::count(tss.begin(), tss.end(), m_ts) == tss.size()) { return InputState::kNOT_UPDATED; } } if (ts) { m_ts = ts; } m_fn = fn; return InputState::kALL_VALID; } void Algorithm::removeTimestampFromBuffer(const mo::Time& ts) { mo::Lock_t lock(m_mtx); for (auto& itr : m_buffer_timing_data) { auto itr2 = std::find_if(itr.second.begin(), itr.second.end(), [ts](const SyncData& st) { if (st.ts) { return *st.ts == ts; } return false; }); if (itr2 != itr.second.end()) { itr.second.erase(itr2); } } } void Algorithm::removeFrameNumberFromBuffer(size_t fn) { mo::Lock_t lock(m_mtx); for (auto& itr : m_buffer_timing_data) { auto itr2 = std::find_if(itr.second.begin(), itr.second.end(), [fn](const SyncData& st) { if (st.ts) { return st.fn == fn; } return false; }); if (itr2 != itr.second.end()) { itr.second.erase(itr2); } } } mo::OptionalTime Algorithm::findBufferedTimestamp() { mo::Lock_t lock(m_mtx); if (!m_buffer_timing_data.empty()) { // Search for the smallest timestamp common to all buffers std::vector<mo::Time> tss; for (const auto& itr : m_buffer_timing_data) { if (!itr.second.empty()) { auto& ts = itr.second.front().ts; if (ts) { tss.push_back(*ts); } } } // assuming time only moves forward, pick the largest of the min timestamps if (!tss.empty()) { auto max_elem = std::max_element(tss.begin(), tss.end()); bool all_found = true; // Check if the value is in the other timing buffers for (const auto& itr : m_buffer_timing_data) { bool found = false; for (const auto& itr2 : itr.second) { if (itr2.ts && *(itr2.ts) == *max_elem) { found = true; break; } } if (!found) { all_found = false; break; } } if (all_found) { return *max_elem; } } } return {}; } mo::OptionalTime Algorithm::findDirectTimestamp(bool& buffered, const std::vector<ISubscriber*>& inputs) { mo::OptionalTime ts; for (auto input : inputs) { auto input_param = input->getPublisher(); if (input_param) { const auto buffered_flag = input_param->checkFlags(mo::ParamFlags::kBUFFER); const auto unstamped_flag = input_param->checkFlags(mo::ParamFlags::kUNSTAMPED); const auto modified_flag = input->hasNewData(); if (!buffered_flag && !unstamped_flag) { if (modified_flag) { auto headers = input_param->getAvailableHeaders(); if (!headers.empty()) { auto in_ts = headers.back().timestamp; if (in_ts) { if (!ts) { ts = in_ts; continue; } ts = std::min<mo::Time>(*ts, *in_ts); } } } } else { buffered = true; } } } return ts; } Algorithm::InputState Algorithm::checkInputs() { auto inputs = this->getInputs(); if (inputs.empty()) { return InputState::kALL_VALID; } for (auto input : inputs) { if (!input->isInputSet() && !input->checkFlags(mo::ParamFlags::kOPTIONAL)) { LOG_ALGO(trace, "Required input ({}) is not connected", input->getTreeName()); return InputState::kNONE_VALID; } } boost::optional<mo::Time> ts; FrameNumber fn; // First check to see if we have a sync input, if we do then use its synchronizatio method // TODO: Handle processing queue bool buffered = false; if (m_sync_input) { mo::Lock_t lock(m_mtx); auto input_param = m_sync_input->getPublisher(); if (input_param && input_param->checkFlags(mo::ParamFlags::kBUFFER)) { if (!m_ts_processing_queue.empty()) { if (m_sync_method == SyncMethod::kEVERY) { ts = m_ts_processing_queue.front(); } else { ts = m_ts_processing_queue.back(); } m_ts_processing_queue.pop(); } } else { auto header = m_sync_input->getNewestHeader(); if (header && !header->timestamp) { fn = header->frame_number; } } } else { // first look for any direct connections, if so use the timestamp from them ts = findDirectTimestamp(buffered, inputs); if (!ts && buffered) { ts = findBufferedTimestamp(); } if (!ts) { for (auto input : inputs) { if (input->isInputSet()) { auto header = input->getNewestHeader(); if (header) { auto in_fn = header->frame_number; fn = std::min(fn.val, in_fn.val); } } } } } // Synchronizing on timestamp if (ts) { auto ret = syncTimestamp(*ts, inputs); if (ret == InputState::kALL_VALID) { LOG_ALGO(trace, "Syncing to {}", *ts); if (buffered) { removeTimestampFromBuffer(*ts); } } else { LOG_ALGO(debug, "Unable to sync timestamp to {} due to {}", *ts, ct::toString(ret)); } return ret; } if (fn.valid()) { auto ret = syncFrameNumber(fn, inputs); if (ret == InputState::kALL_VALID) { LOG_ALGO(trace, "Syncing to {}", fn); if (buffered) { removeFrameNumberFromBuffer(fn); } } else { LOG_ALGO(debug, "Unable to sync frame number to {} due to {}", fn, ct::toString(ret)); } return ret; } LOG_ALGO(debug, "Nothing to sync to "); return InputState::kNONE_VALID; } void Algorithm::clearModifiedInputs() { auto inputs = getInputs(); // TODO what do we do now after the refactor? /*for (auto input : inputs) { input->modified(false); }*/ } void Algorithm::clearModifiedControlParams() { auto params = this->getParams(); for (auto param : params) { if (param->checkFlags(mo::ParamFlags::kCONTROL)) { param->setModified(false); } } } boost::optional<mo::Time> Algorithm::getTimestamp() { return m_ts; } void Algorithm::setSyncInput(const std::string& name) { m_sync_input = getInput(name); if (m_sync_input) { LOG_ALGO(info, "Updating sync parameter for {} to {}", this->GetTypeName(), name); } else { LOG_ALGO(warn, "Unable to set sync input for {} to {}", this->GetTypeName(), name); } } int Algorithm::setupParamServer(const std::shared_ptr<mo::IParamServer>& mgr) { int count = mo::MetaObject::setupParamServer(mgr); for (auto& child : m_algorithm_components) { auto shared = child.lock(); if (shared) { count += shared->setupParamServer(mgr); } } return count; } int Algorithm::setupSignals(const std::shared_ptr<mo::RelayManager>& mgr) { int cnt = IAlgorithm::setupSignals(mgr); for (const auto& cmp : m_algorithm_components) { auto shared = cmp.lock(); if (shared) { cnt += shared->setupSignals(mgr); } } return cnt; } void Algorithm::setSyncMethod(SyncMethod _method) { if (m_sync_method == SyncMethod::kEVERY && _method != SyncMethod::kEVERY) { // std::swap(_ts_processing_queue, std::queue<long long>()); m_ts_processing_queue = std::queue<mo::Time>(); } m_sync_method = _method; } void Algorithm::onParamUpdate(const mo::IParam& param, mo::Header hdr, mo::UpdateFlags fg, IAsyncStream& stream) { mo::MetaObject::onParamUpdate(param, hdr, fg, stream); if (param.checkFlags(mo::ParamFlags::kSOURCE)) { sig_update(); } auto ts = hdr.timestamp; auto fn = hdr.frame_number; if (m_sync_method == SyncMethod::kEVERY) { if (&param == m_sync_input) { auto input_param = m_sync_input->getPublisher(); mo::Lock_t lock(m_mtx); if (input_param && input_param->checkFlags(mo::ParamFlags::kBUFFER)) { if (ts) { if (m_ts_processing_queue.empty() || m_ts_processing_queue.back() != *ts) m_ts_processing_queue.push(*ts); } else { if (m_fn_processing_queue.empty() || m_fn_processing_queue.back() != fn) m_fn_processing_queue.push(fn); } } } } if (fg & ct::value(UpdateFlags::kBUFFER_UPDATED)) { auto in_param = dynamic_cast<const mo::ISubscriber*>(&param); auto buf = dynamic_cast<mo::buffer::IBuffer*>(in_param->getPublisher()); if (in_param) { mo::Lock_t lock(m_mtx); auto itr = m_buffer_timing_data.find(in_param); if (itr == m_buffer_timing_data.end()) { boost::circular_buffer<SyncData> data_buffer; data_buffer.set_capacity(100); if (buf) { auto capacity = buf->getFrameBufferCapacity(); if (capacity) { data_buffer.set_capacity(*capacity); } } auto result = m_buffer_timing_data.insert(std::make_pair(in_param, std::move(data_buffer))); if (result.second) { itr = result.first; } } SyncData data(ts, fn); if (itr->second.empty() || itr->second.back() != data) { itr->second.push_back(std::move(data)); } } } } void Algorithm::setStream(const mo::IAsyncStreamPtr_t& ctx) { mo::MetaObject::setStream(ctx); for (auto& child : m_algorithm_components) { auto shared = child.lock(); if (shared) { shared->setStream(ctx); } } } void Algorithm::postSerializeInit() { auto stream = getStream(); for (auto& child : m_algorithm_components) { auto shared = child.lock(); if (shared) { shared->setStream(stream); shared->postSerializeInit(); } } } void Algorithm::Init(bool first_init) { if (!first_init) { for (auto& cmp : m_algorithm_components) { auto shared = cmp.lock(); if (shared) { shared->Init(first_init); this->addComponent(cmp); } } } mo::MetaObject::Init(first_init); } void Algorithm::addComponent(const rcc::weak_ptr<IAlgorithm>& component) { auto ptr = component.lock(); if (ptr == nullptr) { return; } if (!aq::contains(m_algorithm_components, component)) { m_algorithm_components.push_back(component); } mo::ISlot* slot = this->getSlot("param_updated", mo::TypeInfo::create<void(IParam*, Header, UpdateFlags, IAsyncStream&)>()); if (slot) { auto params = ptr->getParams(); for (auto param : params) { param->registerUpdateNotifier(*slot); } } else { m_logger->warn("Unable to get param_updated slot from self"); } auto manager = getRelayManager(); if (manager) { ptr->setupSignals(manager); } sig_componentAdded(ptr); } std::vector<rcc::weak_ptr<IAlgorithm>> Algorithm::getComponents() const { return m_algorithm_components; } void Algorithm::Serialize(ISimpleSerializer* pSerializer) { mo::MetaObject::Serialize(pSerializer); SERIALIZE(m_algorithm_components); } Algorithm::SyncData::SyncData(const boost::optional<mo::Time>& ts_, mo::FrameNumber fn_) : ts(ts_) , fn(fn_) { } bool Algorithm::SyncData::operator==(const SyncData& other) { if (ts && other.ts) return *ts == *other.ts; return fn == other.fn; } bool Algorithm::SyncData::operator!=(const SyncData& other) { return !(*this == other); } void Algorithm::setLogger(const std::shared_ptr<spdlog::logger>& logger) { m_logger = logger; }
29.069431
120
0.474142
dtmoodie
eb177bb261a8bff52a5a6c7c77635960555f38f7
8,822
cpp
C++
src/Shared/Config/JSONConfig.cpp
AlexWayfer/RankCheck
cf3005a2ba6f66bd66f27e0e42ca6b0ccb907014
[ "Unlicense", "MIT" ]
10
2018-02-12T16:14:07.000Z
2022-03-19T15:08:29.000Z
src/Shared/Config/JSONConfig.cpp
AlexWayfer/RankCheck
cf3005a2ba6f66bd66f27e0e42ca6b0ccb907014
[ "Unlicense", "MIT" ]
11
2018-02-08T16:46:49.000Z
2022-02-03T20:48:12.000Z
src/Shared/Config/JSONConfig.cpp
AlexWayfer/RankCheck
cf3005a2ba6f66bd66f27e0e42ca6b0ccb907014
[ "Unlicense", "MIT" ]
3
2018-02-12T22:08:55.000Z
2021-06-24T16:29:17.000Z
#include <Shared/Config/DataTypes.hpp> #include <Shared/Config/JSONConfig.hpp> #include <rapidjson/error/en.h> #include <rapidjson/error/error.h> #include <rapidjson/prettywriter.h> #include <rapidjson/rapidjson.h> #include <rapidjson/reader.h> #include <rapidjson/stringbuffer.h> #include <rapidjson/writer.h> #include <Shared/Utils/Error.hpp> #include <Shared/Utils/MakeUnique.hpp> #include <Shared/Utils/StrNumCon.hpp> #include <Shared/Utils/Utilities.hpp> #include <cassert> #include <stdexcept> namespace cfg { const std::string JSONConfig::LENGTH_NODE = "length"; const std::string JSONConfig::LENGTH_SUFFIX = ".length"; JSONConfig::JSONConfig() { document = makeUnique<rapidjson::Document>(); document->SetObject(); } JSONConfig::~JSONConfig() { } void JSONConfig::loadFromMemory(const char* data, std::size_t size) { // TODO: Optimize this. // Need to create a string to ensure trailing '\0'. loadFromString(std::string(data, data + size)); } void JSONConfig::loadFromString(const std::string & json) { document = makeUnique<rapidjson::Document>(); document->SetObject(); rapidjson::ParseResult result = document->Parse<rapidjson::kParseTrailingCommasFlag | rapidjson::kParseCommentsFlag>(json.c_str()); if (result.IsError()) { throw std::runtime_error( std::string("Error parsing JSON: ") + rapidjson::GetParseError_En(result.Code()) + " [Error location: character " + cNtoS(result.Offset()) + "]"); } } std::string JSONConfig::saveToString(Style style) const { if (document == nullptr) { return ""; } rapidjson::StringBuffer buffer; switch (style) { case Style::Compact: default: { rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); document->Accept(writer); } break; case Style::Pretty: { rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer); document->Accept(writer); } break; } return buffer.GetString(); } Value JSONConfig::readValue(std::string key) const { std::size_t arrayLength; if (tryGetArrayLength(key, arrayLength)) { return Value(Value::Type::Int, cNtoS(arrayLength)); } const rapidjson::Value * node = findKey(key); if (node != nullptr) { return getNodeValue(*node); } else { return Value(); } } void JSONConfig::writeValue(std::string key, Value value) { if (document == nullptr) { return; } if (value.type == Value::Type::Int && trySetArrayLength(key, cStoUL(value.content))) { return; } rapidjson::Value & node = createOrFindKey(key); setNodeValue(node, std::move(value)); } std::vector<JSONConfig::PathComponent> JSONConfig::getPathComponents(const std::string& key) const { std::vector<PathComponent> components; std::vector<std::string> pathStrings; splitString(key, ".", pathStrings); for (std::string & pathString : pathStrings) { if (pathString.empty()) { throw Error("Malformed config path \"" + key + "\" (expected key name)"); } std::size_t openBracketIndex = pathString.find_first_of('['); if (openBracketIndex != std::string::npos) { std::string pathSubStr = pathString.substr(0, openBracketIndex); checkPathString(pathSubStr); components.emplace_back(std::move(pathSubStr)); while (openBracketIndex != std::string::npos) { std::size_t closedBracketIndex = pathString.find_first_of(']', openBracketIndex + 1); if (closedBracketIndex == std::string::npos) { throw Error("Malformed config path \"" + key + "\" (expected ']')"); } std::string bracketStr = pathString.substr(openBracketIndex + 1, closedBracketIndex - openBracketIndex - 1); unsigned int arrayIndex = 0; if (bracketStr.empty() || !str2Num(arrayIndex, bracketStr)) { throw Error("Malformed config path \"" + key + "\" (expected array index)"); } components.emplace_back(arrayIndex); openBracketIndex = pathString.find_first_of('[', closedBracketIndex); } } else { checkPathString(pathString); components.emplace_back(std::move(pathString)); } } return components; } void JSONConfig::checkPathString(const std::string& pathString) const { for (char ch : pathString) { if ((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z') && ch != '_') { throw Error( "Malformed config node name \"" + pathString + "\" (only A-Z, a-z and _ are allowed)"); } } } const rapidjson::Value* JSONConfig::findKey(const std::string & key) const { if (document == nullptr || !document->IsObject()) { return nullptr; } const rapidjson::Value * currentNode = document.get(); std::vector<PathComponent> pathComponents = getPathComponents(key); for (const PathComponent & component : pathComponents) { if (component.isArrayIndex()) { if (!currentNode->IsArray() || currentNode->Size() <= component.getArrayIndex()) { return nullptr; } currentNode = &((*currentNode)[component.getArrayIndex()]); } else { if (!currentNode->IsObject()) { return nullptr; } auto result = currentNode->FindMember(component.getName().c_str()); if (result == currentNode->MemberEnd()) { return nullptr; } currentNode = &result->value; } } return currentNode; } rapidjson::Value & JSONConfig::createOrFindKey(const std::string & key) { rapidjson::Value * currentNode = document.get(); std::vector<PathComponent> pathComponents = getPathComponents(key); for (const PathComponent & component : pathComponents) { if (component.isArrayIndex()) { if (!currentNode->IsArray()) { currentNode->SetArray(); } if (currentNode->Capacity() <= component.getArrayIndex()) { currentNode->Reserve(component.getArrayIndex() + 1, document->GetAllocator()); } while (currentNode->Size() <= component.getArrayIndex()) { currentNode->PushBack(rapidjson::Value(), document->GetAllocator()); } currentNode = &((*currentNode)[component.getArrayIndex()]); } else { if (!currentNode->IsObject()) { currentNode->SetObject(); } auto result = currentNode->FindMember(component.getName().c_str()); if (result == currentNode->MemberEnd()) { // Member does not exist, create it. currentNode->AddMember(rapidjson::Value(component.getName().c_str(), document->GetAllocator()), rapidjson::Value(rapidjson::kObjectType), document->GetAllocator()); result = currentNode->FindMember(component.getName().c_str()); assert(result != currentNode->MemberEnd()); } currentNode = &result->value; } } return *currentNode; } bool JSONConfig::isArrayLengthKey(const std::string& key) const { return key.size() >= LENGTH_SUFFIX.length() && key.compare(key.length() - LENGTH_SUFFIX.length(), LENGTH_SUFFIX.length(), LENGTH_SUFFIX) == 0; } bool JSONConfig::tryGetArrayLength(const std::string & key, std::size_t& arrayLength) const { if (isArrayLengthKey(key)) { std::size_t lastDot = key.find_last_of('.'); if (lastDot != std::string::npos) { const rapidjson::Value * node = findKey(key.substr(0, lastDot)); if (node != nullptr && node->IsArray()) { arrayLength = node->Size(); return true; } } } return false; } bool JSONConfig::trySetArrayLength(const std::string & key, std::size_t arrayLength) { if (isArrayLengthKey(key)) { std::size_t lastDot = key.find_last_of('.'); if (lastDot != std::string::npos) { rapidjson::Value & node = createOrFindKey(key.substr(0, lastDot)); if (node.IsArray()) { while (node.Size() > arrayLength) { node.PopBack(); } node.Reserve(arrayLength, document->GetAllocator()); while (node.Size() < arrayLength) { node.PushBack(rapidjson::Value(), document->GetAllocator()); } return true; } } } return false; } void JSONConfig::setNodeValue(rapidjson::Value& node, Value value) { switch (value.type) { case Value::Type::Bool: node.SetBool(value.content == "true"); break; case Value::Type::Int: node.SetInt64(cStoL(value.content)); break; case Value::Type::String: node.SetString(value.content.c_str(), document->GetAllocator()); break; case Value::Type::Float: node.SetDouble(cStoD(value.content)); break; case Value::Type::Missing: case Value::Type::Null: default: node.SetNull(); break; } } Value JSONConfig::getNodeValue(const rapidjson::Value& node) const { if (node.IsTrue()) { return Value(Value::Type::Bool, "true"); } else if (node.IsFalse()) { return Value(Value::Type::Bool, "false"); } else if (node.IsDouble()) { return Value(Value::Type::Float, cNtoS(node.GetDouble())); } else if (node.IsInt64()) { return Value(Value::Type::Int, cNtoS(node.GetInt64())); } else if (node.IsUint64()) { return Value(Value::Type::Int, cNtoS(node.GetUint64())); } else if (node.IsString()) { return Value(Value::Type::String, node.GetString()); } return Value(); } }
22.165829
100
0.67309
AlexWayfer
a3e4ac7cdd36073ec7db3b2c11a356750245d317
3,136
hh
C++
dune/gdt/spaces/dg.hh
ftalbrecht/dune-gdt
574bc4a3b28d2a6a6195a6b4df6727c61f0d73c9
[ "BSD-2-Clause" ]
1
2020-02-08T04:12:08.000Z
2020-02-08T04:12:08.000Z
dune/gdt/spaces/dg.hh
dune-community/dune-gdt-archive
08c0167b2761f8263514189be2dcdf0e21a055dc
[ "BSD-2-Clause" ]
null
null
null
dune/gdt/spaces/dg.hh
dune-community/dune-gdt-archive
08c0167b2761f8263514189be2dcdf0e21a055dc
[ "BSD-2-Clause" ]
1
2020-02-08T04:12:11.000Z
2020-02-08T04:12:11.000Z
// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_SPACES_DG_HH #define DUNE_GDT_SPACES_DG_HH #include <memory> #include <dune/common/deprecated.hh> #if HAVE_DUNE_GRID_MULTISCALE # include <dune/grid/multiscale/provider/interface.hh> #endif #include <dune/stuff/common/type_utils.hh> #include <dune/stuff/grid/layers.hh> #include <dune/stuff/grid/provider/interface.hh> #include "interface.hh" #include "../playground/spaces/dg/fem.hh" #include "../playground/spaces/dg/pdelab.hh" namespace Dune { namespace GDT { namespace Spaces { template< class GridType, Stuff::Grid::ChooseLayer layer_type, ChooseSpaceBackend backend_type, int polOrder, class RangeFieldType, size_t dimRange, size_t dimRangeCols = 1 > class DGProvider { static const Stuff::Grid::ChoosePartView part_view_type = ChooseGridPartView< backend_type >::type; public: typedef typename Stuff::Grid::Layer< GridType, layer_type, part_view_type >::Type GridLayerType; private: template< class G, int p, class R, size_t r, size_t rC, GDT::ChooseSpaceBackend b > struct SpaceChooser { static_assert(AlwaysFalse< G >::value, "No space available for this backend!"); }; template< class G, int p, class R, size_t r, size_t rC > struct SpaceChooser< G, p, R, r, rC, GDT::ChooseSpaceBackend::fem > { typedef GDT::Spaces::DG::FemBased< GridLayerType, p, R, r > Type; }; template< class G, int p, class R, size_t r, size_t rC > struct SpaceChooser< G, p, R, r, rC, GDT::ChooseSpaceBackend::pdelab > { typedef GDT::Spaces::DG::PdelabBased< GridLayerType, p, R, r > Type; }; typedef Stuff::Grid::ProviderInterface< GridType > GridProviderType; #if HAVE_DUNE_GRID_MULTISCALE typedef grid::Multiscale::ProviderInterface< GridType > MsGridProviderType; #endif public: typedef typename SpaceChooser< GridType, polOrder, RangeFieldType, dimRange, dimRangeCols, backend_type >::Type Type; static Type create(GridLayerType grid_layer) { return Type(grid_layer); } static Type create(GridProviderType& grid_provider, const int level = 0) { return Type(grid_provider.template layer< layer_type, part_view_type >(level)); } #if HAVE_DUNE_GRID_MULTISCALE static Type create(const MsGridProviderType& grid_provider, const int level_or_subdomain = 0) { return Type(grid_provider.template layer< layer_type, part_view_type >(level_or_subdomain)); } #endif // HAVE_DUNE_GRID_MULTISCALE }; // class DGProvider template< class GridType, Stuff::Grid::ChooseLayer layer_type, ChooseSpaceBackend backend_type, int polOrder, class RangeFieldType, size_t dimRange, size_t dimRangeCols = 1 > class DUNE_DEPRECATED_MSG("Use DGProvider instead (02.02.2015)!") DiscontinuousLagrangeProvider : public DGProvider< GridType, layer_type, backend_type, polOrder, RangeFieldType, dimRange, dimRangeCols > {}; } // namespace Spaces } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACES_DG_HH
31.676768
119
0.747449
ftalbrecht
a3e870427eec6c6433352acbe75cf5d498725864
9,152
hpp
C++
rocprim/include/rocprim/iterator/zip_iterator.hpp
stanleytsang-amd/rocPRIM
1a4135dfc43f90f465c336a551bccbe359d40f11
[ "MIT" ]
null
null
null
rocprim/include/rocprim/iterator/zip_iterator.hpp
stanleytsang-amd/rocPRIM
1a4135dfc43f90f465c336a551bccbe359d40f11
[ "MIT" ]
null
null
null
rocprim/include/rocprim/iterator/zip_iterator.hpp
stanleytsang-amd/rocPRIM
1a4135dfc43f90f465c336a551bccbe359d40f11
[ "MIT" ]
null
null
null
// Copyright (c) 2017-2019 Advanced Micro Devices, Inc. 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 ROCPRIM_ITERATOR_ZIP_ITERATOR_HPP_ #define ROCPRIM_ITERATOR_ZIP_ITERATOR_HPP_ #include <iterator> #include <cstddef> #include <type_traits> #include "../config.hpp" #include "../types/tuple.hpp" /// \addtogroup iteratormodule /// @{ BEGIN_ROCPRIM_NAMESPACE namespace detail { template<class T> struct tuple_of_references; template<class... Types> struct tuple_of_references<::rocprim::tuple<Types...>> { using type = ::rocprim::tuple<typename std::iterator_traits<Types>::reference...>; }; template<class T> struct tuple_of_values; template<class... Types> struct tuple_of_values<::rocprim::tuple<Types...>> { using type = ::rocprim::tuple<typename std::iterator_traits<Types>::value_type...>; }; template<class... Types, class Function, size_t... Indices> ROCPRIM_HOST_DEVICE inline void for_each_in_tuple_impl(::rocprim::tuple<Types...>& t, Function f, ::rocprim::index_sequence<Indices...>) { auto swallow = { (f(::rocprim::get<Indices>(t)), 0)... }; (void) swallow; } template<class... Types, class Function> ROCPRIM_HOST_DEVICE inline void for_each_in_tuple(::rocprim::tuple<Types...>& t, Function f) { for_each_in_tuple_impl(t, f, ::rocprim::index_sequence_for<Types...>()); } struct increment_iterator { template<class Iterator> ROCPRIM_HOST_DEVICE inline void operator()(Iterator& it) { ++it; } }; struct decrement_iterator { template<class Iterator> ROCPRIM_HOST_DEVICE inline void operator()(Iterator& it) { --it; } }; template<class Difference> struct advance_iterator { ROCPRIM_HOST_DEVICE inline advance_iterator(Difference distance) : distance_(distance) { } template<class Iterator> ROCPRIM_HOST_DEVICE inline void operator()(Iterator& it) { using it_distance_type = typename std::iterator_traits<Iterator>::difference_type; it += static_cast<it_distance_type>(distance_); } private: Difference distance_; }; template<class ReferenceTuple, class... Types, size_t... Indices> ROCPRIM_HOST_DEVICE inline ReferenceTuple dereference_iterator_tuple_impl(const ::rocprim::tuple<Types...>& t, ::rocprim::index_sequence<Indices...>) { ReferenceTuple rt { *::rocprim::get<Indices>(t)... }; return rt; } template<class ReferenceTuple, class... Types> ROCPRIM_HOST_DEVICE inline ReferenceTuple dereference_iterator_tuple(const ::rocprim::tuple<Types...>& t) { return dereference_iterator_tuple_impl<ReferenceTuple>( t, ::rocprim::index_sequence_for<Types...>() ); } } // end detail namespace /// \class zip_iterator /// \brief TBD /// /// \par Overview /// * TBD /// /// \tparam IteratorTuple - template<class IteratorTuple> class zip_iterator { public: /// \brief A reference type of the type iterated over. /// /// The type of the tuple made of the reference types of the iterator /// types in the IteratorTuple argument. using reference = typename detail::tuple_of_references<IteratorTuple>::type; /// The type of the value that can be obtained by dereferencing the iterator. using value_type = typename detail::tuple_of_values<IteratorTuple>::type; /// \brief A pointer type of the type iterated over (\p value_type). using pointer = value_type*; /// \brief A type used for identify distance between iterators. /// /// The difference_type member of zip_iterator is the difference_type of /// the first of the iterator types in the IteratorTuple argument. using difference_type = typename std::iterator_traits< typename ::rocprim::tuple_element<0, IteratorTuple>::type >::difference_type; /// The category of the iterator. using iterator_category = std::random_access_iterator_tag; ROCPRIM_HOST_DEVICE inline ~zip_iterator() = default; /// \brief Creates a new zip_iterator. /// /// \param iterator_tuple tuple of iterators ROCPRIM_HOST_DEVICE inline zip_iterator(IteratorTuple iterator_tuple) : iterator_tuple_(iterator_tuple) { } ROCPRIM_HOST_DEVICE inline zip_iterator& operator++() { detail::for_each_in_tuple(iterator_tuple_, detail::increment_iterator()); return *this; } ROCPRIM_HOST_DEVICE inline zip_iterator operator++(int) { zip_iterator old = *this; ++(*this); return old; } ROCPRIM_HOST_DEVICE inline zip_iterator& operator--() { detail::for_each_in_tuple(iterator_tuple_, detail::decrement_iterator()); return *this; } ROCPRIM_HOST_DEVICE inline zip_iterator operator--(int) { zip_iterator old = *this; --(*this); return old; } ROCPRIM_HOST_DEVICE inline reference operator*() const { return detail::dereference_iterator_tuple<reference>(iterator_tuple_); } ROCPRIM_HOST_DEVICE inline pointer operator->() const { return &(*(*this)); } ROCPRIM_HOST_DEVICE inline reference operator[](difference_type distance) const { zip_iterator i = (*this) + distance; return *i; } ROCPRIM_HOST_DEVICE inline zip_iterator operator+(difference_type distance) const { zip_iterator copy = *this; copy += distance; return copy; } ROCPRIM_HOST_DEVICE inline zip_iterator& operator+=(difference_type distance) { detail::for_each_in_tuple( iterator_tuple_, detail::advance_iterator<difference_type>(distance) ); return *this; } ROCPRIM_HOST_DEVICE inline zip_iterator operator-(difference_type distance) const { auto copy = *this; copy -= distance; return copy; } ROCPRIM_HOST_DEVICE inline zip_iterator& operator-=(difference_type distance) { *this += -distance; return *this; } ROCPRIM_HOST_DEVICE inline difference_type operator-(zip_iterator other) const { return ::rocprim::get<0>(iterator_tuple_) - ::rocprim::get<0>(other.iterator_tuple_); } ROCPRIM_HOST_DEVICE inline bool operator==(zip_iterator other) const { return iterator_tuple_ == other.iterator_tuple_; } ROCPRIM_HOST_DEVICE inline bool operator!=(zip_iterator other) const { return !(*this == other); } ROCPRIM_HOST_DEVICE inline bool operator<(zip_iterator other) const { return ::rocprim::get<0>(iterator_tuple_) < ::rocprim::get<0>(other.iterator_tuple_); } ROCPRIM_HOST_DEVICE inline bool operator<=(zip_iterator other) const { return !(other < *this); } ROCPRIM_HOST_DEVICE inline bool operator>(zip_iterator other) const { return other < *this; } ROCPRIM_HOST_DEVICE inline bool operator>=(zip_iterator other) const { return !(*this < other); } friend std::ostream& operator<<(std::ostream& os, const zip_iterator& /* iter */) { return os; } private: IteratorTuple iterator_tuple_; }; template<class IteratorTuple> ROCPRIM_HOST_DEVICE inline zip_iterator<IteratorTuple> operator+(typename zip_iterator<IteratorTuple>::difference_type distance, const zip_iterator<IteratorTuple>& iterator) { return iterator + distance; } /// make_zip_iterator creates a zip_iterator using \p iterator_tuple as /// the underlying tuple of iterator. /// /// \tparam IteratorTuple - iterator tuple type /// /// \param iterator_tuple - tuple of iterators to use /// \return A new zip_iterator object template<class IteratorTuple> ROCPRIM_HOST_DEVICE inline zip_iterator<IteratorTuple> make_zip_iterator(IteratorTuple iterator_tuple) { return zip_iterator<IteratorTuple>(iterator_tuple); } /// @} // end of group iteratormodule END_ROCPRIM_NAMESPACE #endif // ROCPRIM_ITERATOR_ZIP_ITERATOR_HPP_
26.917647
93
0.685642
stanleytsang-amd
a3f1a7cc921eea822a0fa1754abf9a8191044bd9
3,575
cpp
C++
src/fdm_r44/r44_Fuselage.cpp
paperoga-dev/mscsim
a5bd3b88745bf8d91e85fd001b0972662ff8e410
[ "MIT" ]
195
2019-12-01T00:21:06.000Z
2022-03-29T09:06:07.000Z
src/fdm_r44/r44_Fuselage.cpp
paperoga-dev/mscsim
a5bd3b88745bf8d91e85fd001b0972662ff8e410
[ "MIT" ]
4
2019-06-03T12:41:17.000Z
2021-01-30T21:47:00.000Z
src/fdm_r44/r44_Fuselage.cpp
paperoga-dev/mscsim
a5bd3b88745bf8d91e85fd001b0972662ff8e410
[ "MIT" ]
26
2019-12-01T02:42:26.000Z
2022-02-14T11:50:49.000Z
/****************************************************************************//* * Copyright (C) 2021 Marek M. Cel * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. ******************************************************************************/ #include <fdm_r44/r44_Fuselage.h> #include <fdm/utils/fdm_Units.h> #include <fdm/xml/fdm_XmlUtils.h> //////////////////////////////////////////////////////////////////////////////// using namespace fdm; //////////////////////////////////////////////////////////////////////////////// R44_Fuselage::R44_Fuselage() { _dcx_dbeta = Table1::oneRecordTable( 0.0 ); _dcz_dbeta = Table1::oneRecordTable( 0.0 ); _dcm_dbeta = Table1::oneRecordTable( 0.0 ); } //////////////////////////////////////////////////////////////////////////////// R44_Fuselage::~R44_Fuselage() {} //////////////////////////////////////////////////////////////////////////////// void R44_Fuselage::readData( XmlNode &dataNode ) { /////////////////////////////// Fuselage::readData( dataNode ); /////////////////////////////// if ( dataNode.isValid() ) { int result = FDM_SUCCESS; if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, &_dcx_dbeta, "dcx_dbeta" ); if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, &_dcz_dbeta, "dcz_dbeta" ); if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, &_dcm_dbeta, "dcm_dbeta" ); if ( result == FDM_SUCCESS ) { _dcx_dbeta.multiplyKeys( Units::deg2rad() ); _dcz_dbeta.multiplyKeys( Units::deg2rad() ); _dcm_dbeta.multiplyKeys( Units::deg2rad() ); } else { XmlUtils::throwError( __FILE__, __LINE__, dataNode ); } } else { XmlUtils::throwError( __FILE__, __LINE__, dataNode ); } } //////////////////////////////////////////////////////////////////////////////// double R44_Fuselage::getCx( double angleOfAttack ) const { return Fuselage::getCx( angleOfAttack ) + _dcx_dbeta.getValue( _sideslipAngle ); } //////////////////////////////////////////////////////////////////////////////// double R44_Fuselage::getCz( double angleOfAttack ) const { return Fuselage::getCz( angleOfAttack ) + _dcz_dbeta.getValue( _sideslipAngle ); } //////////////////////////////////////////////////////////////////////////////// double R44_Fuselage::getCm( double angleOfAttack ) const { return Fuselage::getCm( angleOfAttack ) + _dcm_dbeta.getValue( _sideslipAngle ); }
36.479592
99
0.538741
paperoga-dev
a3f6b1a223bdafe868413f3a9fcdd857ba9a0a94
1,251
hpp
C++
DirectProgramming/DPC++FPGA/ReferenceDesigns/decompress/src/common/simple_crc32.hpp
yafshar/oneAPI-samples
592a2036e86e7083a05c0d6a1613fb826adf9a60
[ "MIT" ]
null
null
null
DirectProgramming/DPC++FPGA/ReferenceDesigns/decompress/src/common/simple_crc32.hpp
yafshar/oneAPI-samples
592a2036e86e7083a05c0d6a1613fb826adf9a60
[ "MIT" ]
1
2022-01-21T02:29:18.000Z
2022-01-21T02:29:18.000Z
DirectProgramming/DPC++FPGA/ReferenceDesigns/decompress/src/common/simple_crc32.hpp
yafshar/oneAPI-samples
592a2036e86e7083a05c0d6a1613fb826adf9a60
[ "MIT" ]
null
null
null
#ifndef __SIMPLE_CRC32_HPP__ #define __SIMPLE_CRC32_HPP__ // // A simple CRC-32 implementation (not optimized for high performance). // Compute CRC-32 on 'len' elements in 'buf', starting with a CRC of 'init'. // // Arguments: // init: the initial CRC value. This is used to string together multiple // calls to SimpleCRC32. For the first iteration, use 0. // buf: a pointer to the data // len: the number of bytes pointer to by 'buf' // unsigned int SimpleCRC32(unsigned init, const void* buf, size_t len) { // generate the 256-element table constexpr uint32_t polynomial = 0xEDB88320; constexpr auto table = [] { std::array<uint32_t, 256> a{}; for (uint32_t i = 0; i < 256; i++) { uint32_t c = i; for (uint32_t j = 0; j < 8; j++) { if (c & 1) { c = polynomial ^ (c >> 1); } else { c >>= 1; } } a[i] = c; } return a; }(); // compute the CRC-32 for the input data unsigned c = init ^ 0xFFFFFFFF; const uint8_t* u = static_cast<const uint8_t*>(buf); for (size_t i = 0; i < len; i++) { c = table[(c ^ u[i]) & 0xFF] ^ (c >> 8); } return c ^ 0xFFFFFFFF; } #endif /* __SIMPLE_CRC32_HPP__ */
29.785714
77
0.573941
yafshar
a3f9084a64f36e7f46df7db54b363e66b8a06e25
9,262
cpp
C++
src/openms/source/METADATA/MassAnalyzer.cpp
mrurik/OpenMS
3bf48247423dc28a7df7b12b72fbc7751965c321
[ "Zlib", "Apache-2.0" ]
null
null
null
src/openms/source/METADATA/MassAnalyzer.cpp
mrurik/OpenMS
3bf48247423dc28a7df7b12b72fbc7751965c321
[ "Zlib", "Apache-2.0" ]
null
null
null
src/openms/source/METADATA/MassAnalyzer.cpp
mrurik/OpenMS
3bf48247423dc28a7df7b12b72fbc7751965c321
[ "Zlib", "Apache-2.0" ]
null
null
null
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2016. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Andreas Bertsch $ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #include <OpenMS/METADATA/MassAnalyzer.h> using namespace std; namespace OpenMS { const std::string MassAnalyzer::NamesOfAnalyzerType[] = {"Unknown", "Quadrupole", "Quadrupole ion trap", "Radial ejection linear ion trap", "Axial ejection linear ion trap", "Time-of-flight", "Magnetic sector", "Fourier transform ion cyclotron resonance mass spectrometer", "Ion storage", "Electrostatic energy analyzer", "Ion trap", "Stored waveform inverse fourier transform", "Cyclotron", "Orbitrap", "Linear ion trap"}; const std::string MassAnalyzer::NamesOfResolutionMethod[] = {"Unknown", "Full width at half max", "Ten percent valley", "Baseline"}; const std::string MassAnalyzer::NamesOfResolutionType[] = {"Unknown", "Constant", "Proportional"}; const std::string MassAnalyzer::NamesOfScanDirection[] = {"Unknown", "Up", "Down"}; const std::string MassAnalyzer::NamesOfScanLaw[] = {"Unknown", "Exponential", "Linar", "Quadratic"}; const std::string MassAnalyzer::NamesOfReflectronState[] = {"Unknown", "On", "Off", "None"}; MassAnalyzer::MassAnalyzer() : MetaInfoInterface(), type_(ANALYZERNULL), resolution_method_(RESMETHNULL), resolution_type_(RESTYPENULL), scan_direction_(SCANDIRNULL), scan_law_(SCANLAWNULL), reflectron_state_(REFLSTATENULL), resolution_(0.0), accuracy_(0.0), scan_rate_(0.0), scan_time_(0.0), TOF_total_path_length_(0.0), isolation_width_(0.0), final_MS_exponent_(0), magnetic_field_strength_(0.0), order_(0) { } MassAnalyzer::MassAnalyzer(const MassAnalyzer & source) : MetaInfoInterface(source), type_(source.type_), resolution_method_(source.resolution_method_), resolution_type_(source.resolution_type_), scan_direction_(source.scan_direction_), scan_law_(source.scan_law_), reflectron_state_(source.reflectron_state_), resolution_(source.resolution_), accuracy_(source.accuracy_), scan_rate_(source.scan_rate_), scan_time_(source.scan_time_), TOF_total_path_length_(source.TOF_total_path_length_), isolation_width_(source.isolation_width_), final_MS_exponent_(source.final_MS_exponent_), magnetic_field_strength_(source.magnetic_field_strength_), order_(source.order_) { } MassAnalyzer::~MassAnalyzer() { } MassAnalyzer & MassAnalyzer::operator=(const MassAnalyzer & source) { if (&source == this) return *this; order_ = source.order_; type_ = source.type_; resolution_method_ = source.resolution_method_; resolution_type_ = source.resolution_type_; scan_direction_ = source.scan_direction_; scan_law_ = source.scan_law_; reflectron_state_ = source.reflectron_state_; resolution_ = source.resolution_; accuracy_ = source.accuracy_; scan_rate_ = source.scan_rate_; scan_time_ = source.scan_time_; TOF_total_path_length_ = source.TOF_total_path_length_; isolation_width_ = source.isolation_width_; final_MS_exponent_ = source.final_MS_exponent_; magnetic_field_strength_ = source.magnetic_field_strength_; MetaInfoInterface::operator=(source); return *this; } bool MassAnalyzer::operator==(const MassAnalyzer & rhs) const { return order_ == rhs.order_ && type_ == rhs.type_ && resolution_method_ == rhs.resolution_method_ && resolution_type_ == rhs.resolution_type_ && scan_direction_ == rhs.scan_direction_ && scan_law_ == rhs.scan_law_ && reflectron_state_ == rhs.reflectron_state_ && resolution_ == rhs.resolution_ && accuracy_ == rhs.accuracy_ && scan_rate_ == rhs.scan_rate_ && scan_time_ == rhs.scan_time_ && TOF_total_path_length_ == rhs.TOF_total_path_length_ && isolation_width_ == rhs.isolation_width_ && final_MS_exponent_ == rhs.final_MS_exponent_ && magnetic_field_strength_ == rhs.magnetic_field_strength_ && MetaInfoInterface::operator==(rhs); } bool MassAnalyzer::operator!=(const MassAnalyzer & rhs) const { return !(operator==(rhs)); } MassAnalyzer::AnalyzerType MassAnalyzer::getType() const { return type_; } void MassAnalyzer::setType(MassAnalyzer::AnalyzerType type) { type_ = type; } MassAnalyzer::ResolutionMethod MassAnalyzer::getResolutionMethod() const { return resolution_method_; } void MassAnalyzer::setResolutionMethod(MassAnalyzer::ResolutionMethod resolution_method) { resolution_method_ = resolution_method; } MassAnalyzer::ResolutionType MassAnalyzer::getResolutionType() const { return resolution_type_; } void MassAnalyzer::setResolutionType(MassAnalyzer::ResolutionType resolution_type) { resolution_type_ = resolution_type; } MassAnalyzer::ScanDirection MassAnalyzer::getScanDirection() const { return scan_direction_; } void MassAnalyzer::setScanDirection(MassAnalyzer::ScanDirection scan_direction) { scan_direction_ = scan_direction; } MassAnalyzer::ScanLaw MassAnalyzer::getScanLaw() const { return scan_law_; } void MassAnalyzer::setScanLaw(MassAnalyzer::ScanLaw scan_law) { scan_law_ = scan_law; } MassAnalyzer::ReflectronState MassAnalyzer::getReflectronState() const { return reflectron_state_; } void MassAnalyzer::setReflectronState(MassAnalyzer::ReflectronState reflectron_state) { reflectron_state_ = reflectron_state; } double MassAnalyzer::getResolution() const { return resolution_; } void MassAnalyzer::setResolution(double resolution) { resolution_ = resolution; } double MassAnalyzer::getAccuracy() const { return accuracy_; } void MassAnalyzer::setAccuracy(double accuracy) { accuracy_ = accuracy; } double MassAnalyzer::getScanRate() const { return scan_rate_; } void MassAnalyzer::setScanRate(double scan_rate) { scan_rate_ = scan_rate; } double MassAnalyzer::getScanTime() const { return scan_time_; } void MassAnalyzer::setScanTime(double scan_time) { scan_time_ = scan_time; } double MassAnalyzer::getTOFTotalPathLength() const { return TOF_total_path_length_; } void MassAnalyzer::setTOFTotalPathLength(double TOF_total_path_length) { TOF_total_path_length_ = TOF_total_path_length; } double MassAnalyzer::getIsolationWidth() const { return isolation_width_; } void MassAnalyzer::setIsolationWidth(double isolation_width) { isolation_width_ = isolation_width; } Int MassAnalyzer::getFinalMSExponent() const { return final_MS_exponent_; } void MassAnalyzer::setFinalMSExponent(Int final_MS_exponent) { final_MS_exponent_ = final_MS_exponent; } double MassAnalyzer::getMagneticFieldStrength() const { return magnetic_field_strength_; } void MassAnalyzer::setMagneticFieldStrength(double magnetic_field_strength) { magnetic_field_strength_ = magnetic_field_strength; } Int MassAnalyzer::getOrder() const { return order_; } void MassAnalyzer::setOrder(Int order) { order_ = order; } }
30.668874
425
0.694882
mrurik
a3f97d349fdb1e7a5bea806b282dd692ea8c60c1
862
cpp
C++
ds4wizard-cpp/DeviceIdleOptions.cpp
SonicFreak94/ds4wizard
4d2ddc15b7db7cc5618c8676c91cf81614921c3c
[ "MIT" ]
7
2019-02-27T19:23:34.000Z
2021-11-13T08:35:31.000Z
ds4wizard-cpp/DeviceIdleOptions.cpp
SonicFreak94/ds4wizard
4d2ddc15b7db7cc5618c8676c91cf81614921c3c
[ "MIT" ]
1
2020-01-29T20:34:26.000Z
2020-06-30T04:00:38.000Z
ds4wizard-cpp/DeviceIdleOptions.cpp
SonicFreak94/ds4wizard
4d2ddc15b7db7cc5618c8676c91cf81614921c3c
[ "MIT" ]
null
null
null
#include "pch.h" #include "DeviceIdleOptions.h" const DeviceIdleOptions DeviceIdleOptions::defaultIdleOptions(std::chrono::minutes(5), true); DeviceIdleOptions::DeviceIdleOptions(std::chrono::seconds timeout, bool disconnect) : timeout(timeout), disconnect(disconnect) { } bool DeviceIdleOptions::operator==(const DeviceIdleOptions& other) const { return disconnect == other.disconnect && timeout == other.timeout; } bool DeviceIdleOptions::operator!=(const DeviceIdleOptions& other) const { return !(*this == other); } void DeviceIdleOptions::readJson(const nlohmann::json& json) { this->timeout = std::chrono::seconds(json["timeout"].get<int64_t>()); this->disconnect = json["disconnect"]; } void DeviceIdleOptions::writeJson(nlohmann::json& json) const { json["timeout"] = this->timeout.count(); json["disconnect"] = this->disconnect; }
26.121212
93
0.740139
SonicFreak94
a3fa2c88b3c3fe8f2b3e4395902598481e9bf381
1,766
hpp
C++
include/tao/pq/result_traits_tuple.hpp
skaae/taopq
a621cbba1f63c599819466f3da7ef7d352bdaf0d
[ "BSL-1.0" ]
142
2018-12-10T10:12:50.000Z
2022-03-26T16:01:06.000Z
include/tao/pq/result_traits_tuple.hpp
skaae/taopq
a621cbba1f63c599819466f3da7ef7d352bdaf0d
[ "BSL-1.0" ]
45
2018-11-29T13:13:59.000Z
2022-01-17T07:03:30.000Z
include/tao/pq/result_traits_tuple.hpp
skaae/taopq
a621cbba1f63c599819466f3da7ef7d352bdaf0d
[ "BSL-1.0" ]
34
2018-11-29T14:03:59.000Z
2022-03-15T13:08:13.000Z
// Copyright (c) 2016-2021 Daniel Frey and Dr. Colin Hirsch // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #ifndef TAO_PQ_RESULT_TRAITS_TUPLE_HPP #define TAO_PQ_RESULT_TRAITS_TUPLE_HPP #include <tuple> #include <type_traits> #include <utility> #include <tao/pq/internal/exclusive_scan.hpp> #include <tao/pq/result_traits.hpp> namespace tao::pq { template< typename T > struct result_traits< std::tuple< T > > { static constexpr std::size_t size = result_traits_size< T >; template< typename U = T > [[nodiscard]] static auto null() -> std::enable_if_t< std::is_same_v< T, U > && result_traits_has_null< T >, std::tuple< T > > { return std::tuple< T >( result_traits< T >::null() ); } [[nodiscard]] static auto from( const char* value ) { return std::tuple< T >( result_traits< T >::from( value ) ); } }; template< typename... Ts > struct result_traits< std::tuple< Ts... > > { static_assert( sizeof...( Ts ) != 0, "conversion to empty std::tuple<> not support" ); static constexpr std::size_t size{ (0 + ... + result_traits_size< Ts >)}; template< typename Row, std::size_t... Ns > [[nodiscard]] static auto from( const Row& row, std::index_sequence< Ns... > /*unused*/ ) { return std::tuple< Ts... >( row.template get< Ts >( Ns )... ); } template< typename Row > [[nodiscard]] static auto from( const Row& row ) { return result_traits::from( row, internal::exclusive_scan_t< std::index_sequence< result_traits_size< Ts >... > >() ); } }; } // namespace tao::pq #endif
30.448276
127
0.619479
skaae
a3fabe3204214a4e10ddf30a3da423a539b62df3
13,322
cpp
C++
third_party/opencore-audio/aac/dec/src/fft_rx4_short.cpp
asveikau/audio
4b8978d5a7855a0ee62cd15b1dd76d35fb6c8290
[ "0BSD" ]
null
null
null
third_party/opencore-audio/aac/dec/src/fft_rx4_short.cpp
asveikau/audio
4b8978d5a7855a0ee62cd15b1dd76d35fb6c8290
[ "0BSD" ]
null
null
null
third_party/opencore-audio/aac/dec/src/fft_rx4_short.cpp
asveikau/audio
4b8978d5a7855a0ee62cd15b1dd76d35fb6c8290
[ "0BSD" ]
null
null
null
/* ------------------------------------------------------------------ * Copyright (C) 2008 PacketVideo * * 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. * ------------------------------------------------------------------- */ /* Pathname: ./src/fft_rx4_short.c Funtions: fft_rx4_short Date: 9/04/2002 ------------------------------------------------------------------------------ REVISION HISTORY Description: (1) Eliminated search for max in the main loop. (2) Simplified the function by eliminating different conditions for exp. (3) Reduced precision on w_64rx4 from Q15 to Q12, so now the input can be as high as 1.0 and saturation will not occurre because the accumulation times the new Q12 format will never exceed 31 bits. Description: (1) Added comment to explain max search elimination and Q format during multiplications (2) Increased down shift from 1 to 2, to ensure that 32-bit numbers will not overflow when 2 consecutive adds are done This was found during code review. Description: ------------------------------------------------------------------------------ INPUT AND OUTPUT DEFINITIONS Inputs: Data = Input complex vector, arranged in the following order: real, imag, real, imag... This is a complex vector whose elements (real and Imag) are Int32. type Int32 * peak_value = Input, peak value of the input vector Output, peak value of the resulting vector type Int32 * Local Stores/Buffers/Pointers Needed: None Global Stores/Buffers/Pointers Needed: None Outputs: exponent returns a shift to compensate the scaling introduced by overflow protection Pointers and Buffers Modified: calculation are done in-place and returned in Data Local Stores Modified: None Global Stores Modified: None ------------------------------------------------------------------------------ FUNCTION DESCRIPTION Fast Fourier Transform, radix 4 with Decimation in Frequency and block floating point arithmetic. The radix-4 FFT simply divides the FFT into four smaller FFTs. Each of the smaller FFTs is then further divided into smaller ones and so on. It consists of log 4 N stages and each stage consists of N/4 dragonflies. An FFT is nothing but a bundle of multiplications and summations which may overflow during calculations. This routine uses a scheme to test and scale the result output from each FFT stage in order to fix the accumulation overflow. The Input Data should be in Q13 format to get the highest precision. At the end of each dragonfly calculation, a test for possible bit growth is made, if bit growth is possible the Data is scale down back to Q13. ------------------------------------------------------------------------------ REQUIREMENTS This function should provide a fixed point FFT for an input array of size 64. ------------------------------------------------------------------------------ REFERENCES [1] Advance Digital Signal Processing, J. Proakis, C. Rader, F. Ling, C. Nikias, Macmillan Pub. Co. ------------------------------------------------------------------------------ PSEUDO-CODE MODIFY( x[] ) RETURN( exponent ) ------------------------------------------------------------------------------ RESOURCES USED When the code is written for a specific target processor the the resources used should be documented below. STACK USAGE: [stack count for this module] + [variable to represent stack usage for each subroutine called] where: [stack usage variable] = stack usage for [subroutine name] (see [filename].ext) DATA MEMORY USED: x words PROGRAM MEMORY USED: x words CLOCK CYCLES: [cycle count equation for this module] + [variable used to represent cycle count for each subroutine called] where: [cycle count variable] = cycle count for [subroutine name] (see [filename].ext) ------------------------------------------------------------------------------ */ /*---------------------------------------------------------------------------- ; INCLUDES ----------------------------------------------------------------------------*/ #include "pv_audio_type_defs.h" #include "fft_rx4.h" #include "pv_normalize.h" #include "fxp_mul32.h" /*---------------------------------------------------------------------------- ; MACROS ; Define module specific macros here ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; DEFINES ; Include all pre-processor statements here. Include conditional ; compile variables also. ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL FUNCTION DEFINITIONS ; Function Prototype declaration ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL VARIABLE DEFINITIONS ; Variable declaration - defined here and used outside this module ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL FUNCTION REFERENCES ; Declare functions defined elsewhere and referenced in this module ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL VARIABLES REFERENCES ; Declare variables used in this module but defined elsewhere ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES ; Declare variables used in this module but defined elsewhere ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; FUNCTION CODE ----------------------------------------------------------------------------*/ Int fft_rx4_short( Int32 Data[], Int32 *peak_value) { Int n1; Int n2; Int n3; Int j; Int k; Int i; Int32 exp_jw1; Int32 exp_jw2; Int32 exp_jw3; Int32 t1; Int32 t2; Int32 r1; Int32 r2; Int32 r3; Int32 s1; Int32 s2; Int32 s3; Int32 *pData1; Int32 *pData2; Int32 *pData3; Int32 *pData4; const Int32 *pw; Int32 temp1; Int32 temp2; Int32 temp3; Int32 temp4; Int32 max; Int exp; Int exponent = 0; Int shift; max = *peak_value; exp = 0; if (max > 0x008000) { exp = 8 - pv_normalize(max); /* use 24 bits */ exponent = exp; /* keeps track of # of shifts */ } n2 = FFT_RX4_SHORT; pw = W_64rx4; /* shift down to avoid possible overflow in first pass of the loop */ shift = 2; for (k = FFT_RX4_SHORT; k > 4; k >>= 2) { n1 = n2; n2 >>= 2; n3 = n1 >> 1; exp -= 2; for (i = 0; i < FFT_RX4_SHORT; i += n1) { pData1 = &Data[ i<<1]; pData3 = pData1 + n3; pData2 = pData1 + n1; pData4 = pData3 + n1; temp1 = *(pData1); temp2 = *(pData2); temp1 >>= shift; temp2 >>= shift; r1 = temp1 + temp2; r2 = temp1 - temp2; temp3 = *(pData3++); temp4 = *(pData4++); temp3 >>= shift; temp4 >>= shift; t1 = temp3 + temp4; t2 = temp3 - temp4; *(pData1++) = (r1 + t1) >> exp; *(pData2++) = (r1 - t1) >> exp; temp1 = *pData1; temp2 = *pData2; temp1 >>= shift; temp2 >>= shift; s1 = temp1 + temp2; s2 = temp1 - temp2; temp3 = *pData3; temp4 = *pData4; temp3 >>= shift; temp4 >>= shift; t1 = temp3 + temp4; r1 = temp3 - temp4; *pData1 = (s1 + t1) >> exp; *pData2 = (s1 - t1) >> exp; *pData4-- = (s2 + t2) >> exp; *pData4 = (r2 - r1) >> exp; *pData3-- = (s2 - t2) >> exp; *pData3 = (r2 + r1) >> exp; } /* i */ for (j = 1; j < n2; j++) { exp_jw1 = *pw++; exp_jw2 = *pw++; exp_jw3 = *pw++; for (i = j; i < FFT_RX4_SHORT; i += n1) { pData1 = &Data[ i<<1]; pData3 = pData1 + n3; pData2 = pData1 + n1; pData4 = pData3 + n1; temp1 = *(pData1); temp2 = *(pData2++); temp1 >>= shift; temp2 >>= shift; r1 = temp1 + temp2; r2 = temp1 - temp2; temp3 = *(pData3++); temp4 = *(pData4++); temp3 >>= shift; temp4 >>= shift; t1 = temp3 + temp4; t2 = temp3 - temp4; *(pData1++) = (r1 + t1) >> exp; r1 = (r1 - t1) >> exp; temp1 = *pData1; temp2 = *pData2; temp1 >>= shift; temp2 >>= shift; s1 = temp1 + temp2; s2 = temp1 - temp2; s3 = (s2 + t2) >> exp; s2 = (s2 - t2) >> exp; temp3 = *pData3; temp4 = *pData4 ; temp3 >>= shift; temp4 >>= shift; t1 = temp3 + temp4; t2 = temp3 - temp4; *pData1 = (s1 + t1) >> exp; s1 = (s1 - t1) >> exp; *pData2-- = cmplx_mul32_by_16(s1, -r1, exp_jw2) << 1; *pData2 = cmplx_mul32_by_16(r1, s1, exp_jw2) << 1; r3 = ((r2 - t2) >> exp); r2 = ((r2 + t2) >> exp); *pData3-- = cmplx_mul32_by_16(s2, -r2, exp_jw1) << 1; *pData3 = cmplx_mul32_by_16(r2, s2, exp_jw1) << 1; *pData4-- = cmplx_mul32_by_16(s3, -r3, exp_jw3) << 1; *pData4 = cmplx_mul32_by_16(r3, s3, exp_jw3) << 1; } /* i */ } /* j */ /* * this will reset exp and shift to zero for the second pass of the * loop */ exp = 2; shift = 0; } /* k */ max = 0; pData1 = Data - 7; for (i = ONE_FOURTH_FFT_RX4_SHORT; i != 0 ; i--) { pData1 += 7; pData3 = pData1 + 2; pData2 = pData1 + 4; pData4 = pData1 + 6; temp1 = *pData1; temp2 = *pData2++; r1 = temp1 + temp2; r2 = temp1 - temp2; temp1 = *pData3++; temp2 = *pData4++; t1 = temp1 + temp2; t2 = temp1 - temp2; temp1 = (r1 + t1); r1 = (r1 - t1); *(pData1++) = temp1; max |= (temp1 >> 31) ^ temp1; temp1 = *pData1; temp2 = *pData2; s1 = temp1 + temp2; s2 = temp1 - temp2; s3 = (s2 + t2); s2 = (s2 - t2); temp1 = *pData3; temp2 = *pData4; t1 = temp1 + temp2; t2 = temp1 - temp2; temp1 = (s1 + t1); temp2 = (s1 - t1); *pData1 = temp1; *pData2-- = temp2; max |= (temp1 >> 31) ^ temp1; max |= (temp2 >> 31) ^ temp2; *pData2 = r1; *pData3-- = s2; *pData4-- = s3; max |= (r1 >> 31) ^ r1; max |= (s2 >> 31) ^ s2; max |= (s3 >> 31) ^ s3; temp1 = (r2 - t2); temp2 = (r2 + t2); *pData4 = temp1; *pData3 = temp2; max |= (temp1 >> 31) ^ temp1; max |= (temp2 >> 31) ^ temp2; } /* i */ *peak_value = max; return (exponent); }
28.344681
78
0.419982
asveikau
a3fc0e32e5ea56086a18991962e1fb5b941dab65
7,070
cpp
C++
src/to_string.cpp
robhz786/strf-benchmarks
e783700317ef1fea0d9e7217c8c42884c3c0371e
[ "BSL-1.0" ]
1
2021-07-19T11:07:24.000Z
2021-07-19T11:07:24.000Z
src/to_string.cpp
robhz786/strf-benchmarks
e783700317ef1fea0d9e7217c8c42884c3c0371e
[ "BSL-1.0" ]
null
null
null
src/to_string.cpp
robhz786/strf-benchmarks
e783700317ef1fea0d9e7217c8c42884c3c0371e
[ "BSL-1.0" ]
null
null
null
// Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt) #define _USE_MATH_DEFINES #define _CRT_SECURE_NO_WARNINGS #include <strf/to_string.hpp> #include <strf/to_cfile.hpp> #include <iostream> #include <sstream> #include <climits> #include "fmt/format.h" #include "fmt/compile.h" #include <benchmark/benchmark.h> #define STR2(X) #X #define STR(X) STR2(X) #define CAT2(X, Y) X##Y #define CAT(X,Y) CAT2(X,Y) #define BM(FIXTURE, EXPR) BM2(FIXTURE, EXPR, STR(EXPR)) #define BM2(FIXTURE, EXPR, LABEL) DO_BM(CAT(bm_, __LINE__), FIXTURE, EXPR, LABEL) #define DO_BM(ID, FIXTURE, EXPR, LABEL) \ struct ID { \ static void func(benchmark::State& state) { \ FIXTURE; \ for(auto _ : state) { \ auto s = EXPR ; \ benchmark::DoNotOptimize(s.data()); \ benchmark::ClobberMemory(); \ } \ } \ }; \ benchmark::RegisterBenchmark(LABEL, ID :: func); #define FIXTURE_STR std::string str = "blah blah blah blah blah "; #define FIXTURE_U8SAMPLE auto u8sample = std::string(500, 'A'); #define FIXTURE_U16SAMPLE auto u16sample = std::string(500, u'A'); // static void u8_to_u16_buff(benchmark::State& state) // { // char16_t u16buff [510]; // FIXTURE_U8SAMPLE; // for(auto _ : state) { // (void)strf::to(u16buff)(strf::conv(u8sample)); // auto str = strf::to_u16string.reserve_calc() (u16buff); // benchmark::DoNotOptimize(str.data()); // benchmark::ClobberMemory(); // } // } // static void u16_to_u8_buff(benchmark::State& state) // { // char buff[510]; // FIXTURE_U16SAMPLE; // for(auto _ : state) { // (void)strf::to(buff)(strf::conv(u16sample)); // auto str = strf::to_string.reserve_calc()(buff); // benchmark::DoNotOptimize(str.data()); // benchmark::ClobberMemory(); // } // } constexpr double pi = M_PI; int main(int argc, char** argv) { BM(, std::to_string(123456)); BM(, std::to_string(0.123456)); BM(,strf::to_string(123456)); BM(,strf::to_string(0.123456)); BM(FIXTURE_STR, strf::to_string("Blah ", str, "!\n")); BM(FIXTURE_STR, strf::to_string("Blah ", strf::right(str, 40, '.'), "!\n")); //BM(FIXTURE_STR, strf::to_string("Blah ", strf::right(str, 40, U'\u2026'), "!\n")); BM(, strf::to_string("blah ", 123456, " blah ", 0x123456, " blah")); BM(, strf::to_string("blah ", +strf::dec(123456), " blah ", *strf::hex(0x123456), " blah")); BM(, strf::to_string("blah ", +strf::right(123456, 20, '_'), " blah ", *strf::hex(0x123456)<20, " blah")); BM(, strf::to_string(1.123e+5, ' ', pi, ' ', 1.11e-222)); BM(, strf::to_string(*strf::fixed(1.123e+5), ' ', +strf::fixed(pi, 8), ' ', strf::sci(1.11e-222)>30)); BM(, strf::to_string.tr("{}", 123456)); BM(, strf::to_string.tr("{}", 0.123456)); BM(FIXTURE_STR, strf::to_string.tr("Blah {}!\n", str)); BM(FIXTURE_STR, strf::to_string.tr("Blah {}!\n", strf::right(str, 40, '.'))); //BM(FIXTURE_STR, strf::to_string.tr("Blah {}!\n", strf::right(str, 40, U'\u2026') )); BM(, strf::to_string.tr("blah {} blah {} blah", 123456, 0x123456)); BM(, strf::to_string.tr("blah {} blah {} blah", +strf::dec(123456), *strf::hex(0x123456))); BM(, strf::to_string.tr("blah {} blah {} blah", +strf::right(123456, 20, '_'), *strf::hex(0x123456)<20)); BM(, strf::to_string.tr("{} {} {}", 1.123e+5, pi, 1.11e-222)); BM(, strf::to_string.tr("{} {} {}", *strf::fixed(1.123e+5), +strf::fixed(pi, 8), strf::sci(1.11e-222)>30)); BM2(, fmt::format(FMT_COMPILE("{}"), 123456) , "fmt::format(FMT_COMPILE(\"{}\"), 123456)"); BM2(, fmt::format(FMT_COMPILE("{}"), 0.123456) , "fmt::format(FMT_COMPILE(\"{}\"), 0.123456)"); BM2( FIXTURE_STR , fmt::format(FMT_COMPILE("Blah {}!\n"), str) , "fmt::format(FMT_COMPILE(\"Blah {}!\\n\"), str)"); BM2(FIXTURE_STR , fmt::format(FMT_COMPILE("Blah {:.>40}!\n"), str) , "fmt::format(FMT_COMPILE(\"Blah {:.>40}!\\n\"), str)"); // BM2(FIXTURE_STR // , fmt::format(FMT_COMPILE("Blah {:\xE2\x80\xA6>40}!\n"), str) // , "fmt::format(FMT_COMPILE(\"Blah {:\\xE2\\x80\\xA6>40}!\\n\"), str)"); BM2(, fmt::format(FMT_COMPILE("blah {} blah {} blah"), 123456, 0x123456) , "fmt::format(FMT_COMPILE(\"blah {} blah {} blah\"), 123456, 0x123456)"); BM2(, fmt::format(FMT_COMPILE("blah {:+} blah {:#x} blah"), 123456, 0x123456) , "fmt::format(FMT_COMPILE(\"blah {:+} blah {:#x} blah\"), 123456, 0x123456)"); BM2(, fmt::format(FMT_COMPILE("blah {:_>+20} blah {:<#20x} blah"), 123456, 0x123456) , "fmt::format(FMT_COMPILE(\"blah {:_>+20} blah {:<#20x} blah\"), 123456, 0x123456)"); BM2(, fmt::format(FMT_COMPILE( "{} {} {}" ), 1.123e+5, pi, 1.11e-222) , "fmt::format(FMT_COMPILE(\"{} {} {}\"), 1.123e+5, pi, 1.11e-222)"); BM2(, fmt::format(FMT_COMPILE( "{:#f} {:+.8f} {:>30e}" ), 1.123e+5, pi, 1.11e-222) , "fmt::format(FMT_COMPILE(\"{:#f} {:+.8f} {:>30e}\"), 1.123e+5, pi, 1.11e-222)"); BM(, fmt::format("{}", 123456)); BM(, fmt::format("{}", 0.123456)); BM(FIXTURE_STR, fmt::format("Blah {}!\n", str)); BM(FIXTURE_STR, fmt::format("Blah {:.>40}!\n", str)); // BM(FIXTURE_STR, fmt::format("Blah {:\xE2\x80\xA6>40}!\n", str)); BM(, fmt::format("blah {} blah {} blah", 123456, 0x123456)); BM(, fmt::format("blah {:+} blah {:#x} blah", 123456, 0x123456)); BM(, fmt::format("blah {:_>+20} blah {:<#20x} blah", 123456, 0x123456)); BM(, fmt::format("{} {} {}", 1.123e+5, pi, 1.11e-222)); BM(, fmt::format("{:#f} {:+.8f} {:>30e}", 1.123e+5, pi, 1.11e-222)); BM(FIXTURE_U8SAMPLE, strf::to_u16string.reserve_calc() (strf::conv(u8sample))); BM(FIXTURE_U8SAMPLE, strf::to_u16string.no_reserve() (strf::conv(u8sample))); BM(FIXTURE_U8SAMPLE, strf::to_u16string.reserve(510) (strf::conv(u8sample))); BM(FIXTURE_U16SAMPLE, strf::to_string.reserve_calc() (strf::conv(u16sample))); BM(FIXTURE_U16SAMPLE, strf::to_string.no_reserve() (strf::conv(u16sample))); BM(FIXTURE_U16SAMPLE, strf::to_string.reserve(510) (strf::conv(u16sample))); benchmark::Initialize(&argc, argv); benchmark::RunSpecifiedBenchmarks(); strf::to(stdout) ( "\n where :" "\n constexpr double pi = M_PI;" "\n " STR(FIXTURE_STR) "\n " STR(FIXTURE_U8SAMPLE) "\n " STR(FIXTURE_U16SAMPLE) "\n" ); return 0; }
46.513158
111
0.537907
robhz786
a3fdadcf5685880e2e692e57267c4ca11b199ec4
1,569
cpp
C++
qpcol/types/setting.cpp
quntax/qpcol
290e2f0639eaee12fe6190070b3e2c38a8fd1ea7
[ "BSD-3-Clause" ]
null
null
null
qpcol/types/setting.cpp
quntax/qpcol
290e2f0639eaee12fe6190070b3e2c38a8fd1ea7
[ "BSD-3-Clause" ]
null
null
null
qpcol/types/setting.cpp
quntax/qpcol
290e2f0639eaee12fe6190070b3e2c38a8fd1ea7
[ "BSD-3-Clause" ]
null
null
null
#include "setting.h" template<typename T> Setting<T>::Setting() { valid = false; m_Value = QVariant(); } template<typename T> Setting<T>::~Setting() { ch = 0; delete ch; } template<typename T> Setting<T>::Setting(const Parameter & parameter, T defaultValue) { ch = ConfigHandler::instance(); m_Parameter = parameter; m_Name = SettingsMap[parameter]; load(defaultValue); valid = m_Value.isValid() && ! m_Value.isNull(); } template<typename T> T Setting<T>::value() { return m_Value.value<T>(); } template<typename T> void Setting<T>::setValue(T value) { valid = false; m_Value = value; if (m_Value.isValid() && ! m_Value.isNull()) { valid = true; } } template<typename T> void Setting<T>::setValue(const Parameter & parameter, T value) { m_Parameter = parameter; setValue(value); } template<typename T> void Setting<T>::load(T defaultValue) { QVariant v = ch->load(m_Parameter, defaultValue); m_Value = v.isValid() && ! v.isNull() ? v : QVariant(); valid = m_Value.isValid() && ! m_Value.isNull(); } template<typename T> void Setting<T>::save() { if (! valid) { qDebug() << "Setting not saved, validation failed"; return; } ch->save(m_Parameter, m_Value); } template<typename T> void Setting<T>::save(T value) { setValue(value); save(); } template<typename T> T Setting<T>::operator()() { return m_Value.value<T>(); } template class Setting<bool>; template class Setting<int>; template class Setting<QString>;
17.629213
63
0.630338
quntax
4301299c68404cfe0957fdf1022db622e9ccfd39
1,842
cpp
C++
src/fx/util/util.cpp
jathu/fx
2ab96b8b47da16ad980bf7422e211cc1f773bf6d
[ "Apache-2.0" ]
14
2022-02-09T02:57:54.000Z
2022-03-11T08:18:27.000Z
src/fx/util/util.cpp
jathu/fx
2ab96b8b47da16ad980bf7422e211cc1f773bf6d
[ "Apache-2.0" ]
null
null
null
src/fx/util/util.cpp
jathu/fx
2ab96b8b47da16ad980bf7422e211cc1f773bf6d
[ "Apache-2.0" ]
1
2022-02-13T16:09:18.000Z
2022-02-13T16:09:18.000Z
#include "util.hpp" #include <algorithm> #include <cstring> namespace fx::util { bool icompare(std::string const& left, std::string const& right) { if (left.size() == right.size()) { return std::equal(right.begin(), right.end(), left.begin(), left.end(), [](char l, char r) { return std::tolower(l) == std::tolower(r); }); } return false; } std::string lower(std::string const& str) { auto copy = str; std::transform(copy.begin(), copy.end(), copy.begin(), [](unsigned char c) { return std::tolower(c); }); return copy; } fx::result::Result<std::filesystem::path> workspace_descriptor_path() { std::filesystem::path workspace; auto current_directory = std::filesystem::current_path(); auto const root_directory = current_directory.root_directory(); auto const workspace_filename = std::filesystem::path("workspace.fx.yaml"); while (current_directory.parent_path() != root_directory) { auto const possible_workspace = current_directory / workspace_filename; if (std::filesystem::exists(possible_workspace)) { workspace = possible_workspace; break; } current_directory = current_directory.parent_path(); } if (workspace.empty()) { return fx::result::Error(std::string("Workspace descriptor not found.")); } return fx::result::Ok(workspace); } char** c_vector_string(const std::vector<std::string>& strings) { char** result = new char*[strings.size() + 1]; for (int i = 0; i < strings.size(); ++i) { result[i] = new char[strings[i].size() + 1]; std::memcpy(result[i], strings[i].c_str(), strings[i].size() + 1); } result[strings.size()] = nullptr; return result; } } // namespace fx::util
30.7
80
0.610206
jathu
4305f240f4a696b965c72f624dcf3b27cbbe7fc4
3,767
cpp
C++
tc 160+/MarriageProblemRevised.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/MarriageProblemRevised.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/MarriageProblemRevised.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> #include <queue> using namespace std; int M[1<<12], F[1<<12]; int bc[1<<12]; class MarriageProblemRevised { public: int neededMarriages(vector <string> pref) { int m = pref.size(); int f = pref[0].size(); for (int i=0; i<m; ++i) if (pref[i] == string(f, '0')) return -1; for (int j=0; j<f; ++j) { bool ok = false; for (int i=0; i<m; ++i) if (pref[i][j] == '1') { ok = true; break; } if (!ok) return -1; } for (int i=0; i<m; ++i) { M[1<<i] = 0; for (int j=0; j<f; ++j) if (pref[i][j] == '1') M[1<<i] |= (1<<j); } for (int j=0; j<f; ++j) { F[1<<j] = 0; for (int i=0; i<m; ++i) if (pref[i][j] == '1') F[1<<j] |= (1<<i); } bc[0] = 0; for (int i=0; i<(1<<12); ++i) bc[i] = bc[i>>1] + (i&1); for (int mask=0; mask<(1<<m); ++mask) if (bc[mask] > 1) { M[mask] = 0; for (int i=0; i<m; ++i) if (mask & (1<<i)) M[mask] |= M[1<<i]; } for (int mask=0; mask<(1<<f); ++mask) if (bc[mask] > 1) { F[mask] = 0; for (int j=0; j<f; ++j) if (mask & (1<<j)) F[mask] |= F[1<<j]; } int sol = 1234567890; for (int i=0; i<(1<<m); ++i) { if (bc[i]<sol && (i==0 || M[i]!=0)) for (int j=0; j<(1<<f); ++j) if (bc[i]+bc[j]<sol && (j==0 || F[j]!=0)) if ((M[i]|j) == ((1<<f)-1) && (F[j]|i) == ((1<<m)-1) && (bc[M[i]] >= bc[M[i] ^ (M[i]&j)]) && (bc[F[j]] >= bc[F[j] ^ (F[j]&i)])) sol = bc[i]+bc[j]; } return sol>min(m, f) ? -1 : sol; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"111"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(0, Arg1, neededMarriages(Arg0)); } void test_case_1() { string Arr0[] = {"100", "010", "001"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 3; verify_case(1, Arg1, neededMarriages(Arg0)); } void test_case_2() { string Arr0[] = {"00", "00"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = -1; verify_case(2, Arg1, neededMarriages(Arg0)); } void test_case_3() { string Arr0[] = {"0001", "0001", "0001", "1111"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; verify_case(3, Arg1, neededMarriages(Arg0)); } void test_case_4() { string Arr0[] = {"11101011","00011110","11100100","01010000","01000010","10100011","01110110","10111111"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 3; verify_case(4, Arg1, neededMarriages(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { MarriageProblemRevised ___test; ___test.run_test(-1); } // END CUT HERE
34.559633
309
0.510751
ibudiselic
43112381189a957a484eb433c34709d92ded8cea
3,872
cc
C++
runtime/lib/function.cc
annagrin/sdk
dfce72bbf9bf359ecd810964259978e24c55e237
[ "BSD-3-Clause" ]
2
2019-11-06T13:44:11.000Z
2019-11-17T06:49:40.000Z
runtime/lib/function.cc
annagrin/sdk
dfce72bbf9bf359ecd810964259978e24c55e237
[ "BSD-3-Clause" ]
1
2021-01-21T14:45:59.000Z
2021-01-21T14:45:59.000Z
runtime/lib/function.cc
annagrin/sdk
dfce72bbf9bf359ecd810964259978e24c55e237
[ "BSD-3-Clause" ]
3
2020-02-13T02:08:04.000Z
2020-08-09T07:49:55.000Z
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/bootstrap_natives.h" #include "vm/compiler/jit/compiler.h" #include "vm/dart_entry.h" #include "vm/exceptions.h" #include "vm/native_entry.h" #include "vm/object.h" #include "vm/symbols.h" namespace dart { DEFINE_NATIVE_ENTRY(Function_apply, 0, 2) { const int kTypeArgsLen = 0; // TODO(regis): Add support for generic function. const Array& fun_arguments = Array::CheckedHandle(zone, arguments->NativeArgAt(0)); const Array& fun_arg_names = Array::CheckedHandle(zone, arguments->NativeArgAt(1)); const Array& fun_args_desc = Array::Handle( zone, ArgumentsDescriptor::New(kTypeArgsLen, fun_arguments.Length(), fun_arg_names)); const Object& result = Object::Handle( zone, DartEntry::InvokeClosure(fun_arguments, fun_args_desc)); if (result.IsError()) { Exceptions::PropagateError(Error::Cast(result)); } return result.raw(); } DEFINE_NATIVE_ENTRY(Closure_equals, 0, 2) { const Closure& receiver = Closure::CheckedHandle(zone, arguments->NativeArgAt(0)); GET_NATIVE_ARGUMENT(Instance, other, arguments->NativeArgAt(1)); ASSERT(!other.IsNull()); // For implicit instance closures compare receiver instance and function's // name and owner (multiple function objects could exist for the same // function due to hot reload). // Objects of other closure kinds are unique, so use identity comparison. if (receiver.raw() == other.raw()) { return Bool::True().raw(); } if (other.IsClosure()) { const Function& func_a = Function::Handle(zone, receiver.function()); if (func_a.IsImplicitInstanceClosureFunction()) { const Closure& other_closure = Closure::Cast(other); const Function& func_b = Function::Handle(zone, other_closure.function()); if (func_b.IsImplicitInstanceClosureFunction()) { const Context& context_a = Context::Handle(zone, receiver.context()); const Context& context_b = Context::Handle(zone, other_closure.context()); RawObject* receiver_a = context_a.At(0); RawObject* receiver_b = context_b.At(0); if ((receiver_a == receiver_b) && ((func_a.raw() == func_b.raw()) || ((func_a.name() == func_b.name()) && (func_a.Owner() == func_b.Owner())))) { return Bool::True().raw(); } } } } return Bool::False().raw(); } DEFINE_NATIVE_ENTRY(Closure_computeHash, 0, 1) { const Closure& receiver = Closure::CheckedHandle(zone, arguments->NativeArgAt(0)); return Smi::New(receiver.ComputeHash()); } DEFINE_NATIVE_ENTRY(Closure_clone, 0, 1) { const Closure& receiver = Closure::CheckedHandle(zone, arguments->NativeArgAt(0)); const TypeArguments& instantiator_type_arguments = TypeArguments::Handle(zone, receiver.instantiator_type_arguments()); const TypeArguments& function_type_arguments = TypeArguments::Handle(zone, receiver.function_type_arguments()); const Function& function = Function::Handle(zone, receiver.function()); const Context& context = Context::Handle(zone, receiver.context()); Context& cloned_context = Context::Handle(zone); if (!context.IsNull()) { cloned_context = Context::New(context.num_variables()); cloned_context.set_parent(Context::Handle(zone, context.parent())); Object& instance = Object::Handle(zone); for (int i = 0; i < context.num_variables(); i++) { instance = context.At(i); cloned_context.SetAt(i, instance); } } return Closure::New(instantiator_type_arguments, function_type_arguments, function, cloned_context); } } // namespace dart
39.510204
80
0.683626
annagrin
43128856c2571e20dd32511587845a431b72cdd9
66,711
cpp
C++
src/test/test_algebra_semiring.cpp
KIwabuchi/gbtl
62c6b1e3262f3623359e793edb5ec4fa7bb471f0
[ "Unlicense" ]
112
2016-04-26T05:54:30.000Z
2022-03-27T05:56:16.000Z
src/test/test_algebra_semiring.cpp
KIwabuchi/gbtl
62c6b1e3262f3623359e793edb5ec4fa7bb471f0
[ "Unlicense" ]
21
2016-03-22T19:06:46.000Z
2021-10-07T15:40:18.000Z
src/test/test_algebra_semiring.cpp
KIwabuchi/gbtl
62c6b1e3262f3623359e793edb5ec4fa7bb471f0
[ "Unlicense" ]
22
2016-04-26T05:54:35.000Z
2021-12-21T03:33:20.000Z
/* * GraphBLAS Template Library (GBTL), Version 3.0 * * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and * Authors. * * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF * THE UNITED STATES GOVERNMENT. NEITHER THE UNITED STATES GOVERNMENT NOR THE * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED * RIGHTS. * * Released under a BSD-style license, please see LICENSE file or contact * permission@sei.cmu.edu for full terms. * * [DISTRIBUTION STATEMENT A] This material has been approved for public release * and unlimited distribution. Please see Copyright notice for non-US * Government use and distribution. * * This Software includes and/or makes use of the following Third-Party Software * subject to its own license: * * 1. Boost Unit Test Framework * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html) * Copyright 2001 Boost software license, Gennadiy Rozental. * * DM20-0442 */ #include <functional> #include <iostream> #include <vector> #include <graphblas/graphblas.hpp> using namespace grb; #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE algebra_semiring_test_suite #include <boost/test/included/unit_test.hpp> BOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE) //**************************************************************************** BOOST_AUTO_TEST_CASE(arithmetic_semiring_test) { BOOST_CHECK_EQUAL(ArithmeticSemiring<double>().zero(), 0.0); BOOST_CHECK_EQUAL(ArithmeticSemiring<double>().add(-2., 1.), -1.0); BOOST_CHECK_EQUAL(ArithmeticSemiring<double>().mult(-2., 1.), -2.0); BOOST_CHECK_EQUAL(ArithmeticSemiring<float>().zero(), 0.0f); BOOST_CHECK_EQUAL(ArithmeticSemiring<float>().add(-2.f, 1.f), -1.0f); BOOST_CHECK_EQUAL(ArithmeticSemiring<float>().mult(-2.f, 1.f), -2.0f); BOOST_CHECK_EQUAL(ArithmeticSemiring<uint64_t>().zero(), 0UL); BOOST_CHECK_EQUAL(ArithmeticSemiring<uint64_t>().add(2UL, 1UL), 3UL); BOOST_CHECK_EQUAL(ArithmeticSemiring<uint64_t>().mult(2UL, 1UL), 2UL); BOOST_CHECK_EQUAL(ArithmeticSemiring<uint32_t>().zero(), 0U); BOOST_CHECK_EQUAL(ArithmeticSemiring<uint32_t>().add(2U, 1U), 3U); BOOST_CHECK_EQUAL(ArithmeticSemiring<uint32_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(ArithmeticSemiring<uint16_t>().zero(), 0U); BOOST_CHECK_EQUAL(ArithmeticSemiring<uint16_t>().add(2U, 1U), 3U); BOOST_CHECK_EQUAL(ArithmeticSemiring<uint16_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(ArithmeticSemiring<uint8_t>().zero(), 0U); BOOST_CHECK_EQUAL(ArithmeticSemiring<uint8_t>().add(2U, 1U), 3U); BOOST_CHECK_EQUAL(ArithmeticSemiring<uint8_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(ArithmeticSemiring<int64_t>().zero(), 0L); BOOST_CHECK_EQUAL(ArithmeticSemiring<int64_t>().add(-2L, 1L), -1L); BOOST_CHECK_EQUAL(ArithmeticSemiring<int64_t>().mult(-2L, 1L), -2L); BOOST_CHECK_EQUAL(ArithmeticSemiring<int32_t>().zero(), 0); BOOST_CHECK_EQUAL(ArithmeticSemiring<int32_t>().add(-2, 1), -1); BOOST_CHECK_EQUAL(ArithmeticSemiring<int32_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(ArithmeticSemiring<int16_t>().zero(), 0); BOOST_CHECK_EQUAL(ArithmeticSemiring<int16_t>().add(-2, 1), -1); BOOST_CHECK_EQUAL(ArithmeticSemiring<int16_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(ArithmeticSemiring<int8_t>().zero(), 0); BOOST_CHECK_EQUAL(ArithmeticSemiring<int8_t>().add(-2, 1), -1); BOOST_CHECK_EQUAL(ArithmeticSemiring<int8_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(ArithmeticSemiring<bool>().zero(), false); BOOST_CHECK_EQUAL(ArithmeticSemiring<bool>().add(false, false), false); BOOST_CHECK_EQUAL(ArithmeticSemiring<bool>().add(false, true), true); BOOST_CHECK_EQUAL(ArithmeticSemiring<bool>().mult(false, true), false); BOOST_CHECK_EQUAL(ArithmeticSemiring<bool>().mult(true, true), true); } //**************************************************************************** BOOST_AUTO_TEST_CASE(min_plus_semiring_test) { BOOST_CHECK_EQUAL(MinPlusSemiring<double>().zero(), std::numeric_limits<double>::infinity()); BOOST_CHECK_EQUAL(MinPlusSemiring<double>().add(-2., 1.), -2.0); BOOST_CHECK_EQUAL(MinPlusSemiring<double>().add(2., 1.), 1.0); BOOST_CHECK_EQUAL(MinPlusSemiring<double>().mult(-2., 1.), -1.0); BOOST_CHECK_EQUAL(MinPlusSemiring<float>().zero(), std::numeric_limits<float>::infinity()); BOOST_CHECK_EQUAL(MinPlusSemiring<float>().add(-2.f, 1.f), -2.0f); BOOST_CHECK_EQUAL(MinPlusSemiring<float>().add(2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(MinPlusSemiring<float>().mult(-2.f, 1.f), -1.0f); BOOST_CHECK_EQUAL(MinPlusSemiring<uint64_t>().zero(), std::numeric_limits<uint64_t>::max()); BOOST_CHECK_EQUAL(MinPlusSemiring<uint64_t>().add(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(MinPlusSemiring<uint64_t>().add(2UL, 3UL), 2UL); BOOST_CHECK_EQUAL(MinPlusSemiring<uint64_t>().mult(2UL, 1UL), 3UL); BOOST_CHECK_EQUAL(MinPlusSemiring<uint32_t>().zero(), std::numeric_limits<uint32_t>::max()); BOOST_CHECK_EQUAL(MinPlusSemiring<uint32_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinPlusSemiring<uint32_t>().add(2U, 3U), 2U); BOOST_CHECK_EQUAL(MinPlusSemiring<uint32_t>().mult(2U, 1U), 3U); BOOST_CHECK_EQUAL(MinPlusSemiring<uint16_t>().zero(), std::numeric_limits<uint16_t>::max()); BOOST_CHECK_EQUAL(MinPlusSemiring<uint16_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinPlusSemiring<uint16_t>().add(2U, 3U), 2U); BOOST_CHECK_EQUAL(MinPlusSemiring<uint16_t>().mult(2U, 1U), 3U); BOOST_CHECK_EQUAL(MinPlusSemiring<uint8_t>().zero(), std::numeric_limits<uint8_t>::max()); BOOST_CHECK_EQUAL(MinPlusSemiring<uint8_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinPlusSemiring<uint8_t>().add(2U, 3U), 2U); BOOST_CHECK_EQUAL(MinPlusSemiring<uint8_t>().mult(2U, 1U), 3U); BOOST_CHECK_EQUAL(MinPlusSemiring<int64_t>().zero(), std::numeric_limits<int64_t>::max()); BOOST_CHECK_EQUAL(MinPlusSemiring<int64_t>().add(-2L, 1L), -2L); BOOST_CHECK_EQUAL(MinPlusSemiring<int64_t>().add(2L, -1L), -1L); BOOST_CHECK_EQUAL(MinPlusSemiring<int64_t>().mult(-2L, 1L), -1L); BOOST_CHECK_EQUAL(MinPlusSemiring<int32_t>().zero(), std::numeric_limits<int32_t>::max()); BOOST_CHECK_EQUAL(MinPlusSemiring<int32_t>().add(-2, 1), -2); BOOST_CHECK_EQUAL(MinPlusSemiring<int32_t>().add(2, -1), -1); BOOST_CHECK_EQUAL(MinPlusSemiring<int32_t>().mult(-2, 1), -1); BOOST_CHECK_EQUAL(MinPlusSemiring<int16_t>().zero(), std::numeric_limits<int16_t>::max()); BOOST_CHECK_EQUAL(MinPlusSemiring<int16_t>().add(-2, 1), -2); BOOST_CHECK_EQUAL(MinPlusSemiring<int16_t>().add(2, -1), -1); BOOST_CHECK_EQUAL(MinPlusSemiring<int16_t>().mult(-2, 1), -1); BOOST_CHECK_EQUAL(MinPlusSemiring<int8_t>().zero(), std::numeric_limits<int8_t>::max()); BOOST_CHECK_EQUAL(MinPlusSemiring<int8_t>().add(-2, 1), -2); BOOST_CHECK_EQUAL(MinPlusSemiring<int8_t>().add(2, -1), -1); BOOST_CHECK_EQUAL(MinPlusSemiring<int8_t>().mult(-2, 1), -1); BOOST_CHECK_EQUAL(MinPlusSemiring<bool>().zero(), true); BOOST_CHECK_EQUAL(MinPlusSemiring<bool>().add(false, true), false); BOOST_CHECK_EQUAL(MinPlusSemiring<bool>().add(true, true), true); BOOST_CHECK_EQUAL(MinPlusSemiring<bool>().mult(false, false), false); BOOST_CHECK_EQUAL(MinPlusSemiring<bool>().mult(true, false), true); } //**************************************************************************** BOOST_AUTO_TEST_CASE(max_plus_semiring_test) { BOOST_CHECK_EQUAL(MaxPlusSemiring<double>().zero(), -std::numeric_limits<double>::infinity()); BOOST_CHECK_EQUAL(MaxPlusSemiring<double>().add(-2., 1.), 1.0); BOOST_CHECK_EQUAL(MaxPlusSemiring<double>().add(2., 1.), 2.0); BOOST_CHECK_EQUAL(MaxPlusSemiring<double>().mult(-2., 1.), -1.0); BOOST_CHECK_EQUAL(MaxPlusSemiring<float>().zero(), -std::numeric_limits<float>::infinity()); BOOST_CHECK_EQUAL(MaxPlusSemiring<float>().add(-2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(MaxPlusSemiring<float>().add(2.f, 1.f), 2.0f); BOOST_CHECK_EQUAL(MaxPlusSemiring<float>().mult(-2.f, 1.f), -1.0f); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint64_t>().zero(), std::numeric_limits<uint64_t>::min()); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint64_t>().add(2UL, 1UL), 2UL); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint64_t>().add(2UL, 3UL), 3UL); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint64_t>().mult(2UL, 1UL), 3UL); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint32_t>().zero(), std::numeric_limits<uint32_t>::min()); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint32_t>().add(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint32_t>().add(2U, 3U), 3U); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint32_t>().mult(2U, 1U), 3U); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint16_t>().zero(), std::numeric_limits<uint16_t>::min()); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint16_t>().add(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint16_t>().add(2U, 3U), 3U); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint16_t>().mult(2U, 1U), 3U); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint8_t>().zero(), std::numeric_limits<uint8_t>::min()); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint8_t>().add(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint8_t>().add(2U, 3U), 3U); BOOST_CHECK_EQUAL(MaxPlusSemiring<uint8_t>().mult(2U, 1U), 3U); BOOST_CHECK_EQUAL(MaxPlusSemiring<int64_t>().zero(), std::numeric_limits<int64_t>::min()); BOOST_CHECK_EQUAL(MaxPlusSemiring<int64_t>().add(-2L, 1L), 1L); BOOST_CHECK_EQUAL(MaxPlusSemiring<int64_t>().add(2L, -1L), 2L); BOOST_CHECK_EQUAL(MaxPlusSemiring<int64_t>().mult(-2L, 1L), -1L); BOOST_CHECK_EQUAL(MaxPlusSemiring<int32_t>().zero(), std::numeric_limits<int32_t>::min()); BOOST_CHECK_EQUAL(MaxPlusSemiring<int32_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(MaxPlusSemiring<int32_t>().add(2, -1), 2); BOOST_CHECK_EQUAL(MaxPlusSemiring<int32_t>().mult(-2, 1), -1); BOOST_CHECK_EQUAL(MaxPlusSemiring<int16_t>().zero(), std::numeric_limits<int16_t>::min()); BOOST_CHECK_EQUAL(MaxPlusSemiring<int16_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(MaxPlusSemiring<int16_t>().add(2, -1), 2); BOOST_CHECK_EQUAL(MaxPlusSemiring<int16_t>().mult(-2, 1), -1); BOOST_CHECK_EQUAL(MaxPlusSemiring<int8_t>().zero(), std::numeric_limits<int8_t>::min()); BOOST_CHECK_EQUAL(MaxPlusSemiring<int8_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(MaxPlusSemiring<int8_t>().add(2, -1), 2); BOOST_CHECK_EQUAL(MaxPlusSemiring<int8_t>().mult(-2, 1), -1); BOOST_CHECK_EQUAL(MaxPlusSemiring<bool>().zero(), false); BOOST_CHECK_EQUAL(MaxPlusSemiring<bool>().add(false, true), true); BOOST_CHECK_EQUAL(MaxPlusSemiring<bool>().add(true, true), true); BOOST_CHECK_EQUAL(MaxPlusSemiring<bool>().mult(false, false), false); BOOST_CHECK_EQUAL(MaxPlusSemiring<bool>().mult(true, false), true); } //**************************************************************************** BOOST_AUTO_TEST_CASE(min_times_semiring_test) { BOOST_CHECK_EQUAL(MinTimesSemiring<double>().zero(), std::numeric_limits<double>::infinity()); BOOST_CHECK_EQUAL(MinTimesSemiring<double>().add(-2., 1.), -2.0); BOOST_CHECK_EQUAL(MinTimesSemiring<double>().mult(-2., 1.), -2.0); BOOST_CHECK_EQUAL(MinTimesSemiring<float>().zero(), std::numeric_limits<float>::infinity()); BOOST_CHECK_EQUAL(MinTimesSemiring<float>().add(-2.f, 1.f), -2.0f); BOOST_CHECK_EQUAL(MinTimesSemiring<float>().mult(-2.f, 1.f), -2.0f); BOOST_CHECK_EQUAL(MinTimesSemiring<uint64_t>().zero(), std::numeric_limits<uint64_t>::max()); BOOST_CHECK_EQUAL(MinTimesSemiring<uint64_t>().add(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(MinTimesSemiring<uint64_t>().mult(2UL, 1UL), 2UL); BOOST_CHECK_EQUAL(MinTimesSemiring<uint32_t>().zero(), std::numeric_limits<uint32_t>::max()); BOOST_CHECK_EQUAL(MinTimesSemiring<uint32_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinTimesSemiring<uint32_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(MinTimesSemiring<uint16_t>().zero(), std::numeric_limits<uint16_t>::max()); BOOST_CHECK_EQUAL(MinTimesSemiring<uint16_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinTimesSemiring<uint16_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(MinTimesSemiring<uint8_t>().zero(), std::numeric_limits<uint8_t>::max()); BOOST_CHECK_EQUAL(MinTimesSemiring<uint8_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinTimesSemiring<uint8_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(MinTimesSemiring<int64_t>().zero(), std::numeric_limits<int64_t>::max()); BOOST_CHECK_EQUAL(MinTimesSemiring<int64_t>().add(-2L, 1L), -2L); BOOST_CHECK_EQUAL(MinTimesSemiring<int64_t>().mult(-2L, 1L), -2L); BOOST_CHECK_EQUAL(MinTimesSemiring<int32_t>().zero(), std::numeric_limits<int32_t>::max()); BOOST_CHECK_EQUAL(MinTimesSemiring<int32_t>().add(-2, 1), -2); BOOST_CHECK_EQUAL(MinTimesSemiring<int32_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(MinTimesSemiring<int16_t>().zero(), std::numeric_limits<int16_t>::max()); BOOST_CHECK_EQUAL(MinTimesSemiring<int16_t>().add(-2, 1), -2); BOOST_CHECK_EQUAL(MinTimesSemiring<int16_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(MinTimesSemiring<int8_t>().zero(), std::numeric_limits<int8_t>::max()); BOOST_CHECK_EQUAL(MinTimesSemiring<int8_t>().add(-2, 1), -2); BOOST_CHECK_EQUAL(MinTimesSemiring<int8_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(MinTimesSemiring<bool>().zero(), true); BOOST_CHECK_EQUAL(MinTimesSemiring<bool>().add(false, false), false); BOOST_CHECK_EQUAL(MinTimesSemiring<bool>().add(false, true), false); BOOST_CHECK_EQUAL(MinTimesSemiring<bool>().mult(false, true), false); BOOST_CHECK_EQUAL(MinTimesSemiring<bool>().mult(true, true), true); } //**************************************************************************** BOOST_AUTO_TEST_CASE(max_times_semiring_test) { BOOST_CHECK_EQUAL(MaxTimesSemiring<double>().zero(), -std::numeric_limits<double>::infinity()); BOOST_CHECK_EQUAL(MaxTimesSemiring<double>().add(-2., 1.), 1.0); BOOST_CHECK_EQUAL(MaxTimesSemiring<double>().mult(-2., 1.), -2.0); BOOST_CHECK_EQUAL(MaxTimesSemiring<float>().zero(), -std::numeric_limits<float>::infinity()); BOOST_CHECK_EQUAL(MaxTimesSemiring<float>().add(-2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(MaxTimesSemiring<float>().mult(-2.f, 1.f), -2.0f); BOOST_CHECK_EQUAL(MaxTimesSemiring<uint64_t>().zero(), 0UL); BOOST_CHECK_EQUAL(MaxTimesSemiring<uint64_t>().add(2UL, 1UL), 2UL); BOOST_CHECK_EQUAL(MaxTimesSemiring<uint64_t>().mult(2UL, 1UL), 2UL); BOOST_CHECK_EQUAL(MaxTimesSemiring<uint32_t>().zero(), 0U); BOOST_CHECK_EQUAL(MaxTimesSemiring<uint32_t>().add(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxTimesSemiring<uint32_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxTimesSemiring<uint16_t>().zero(), 0U); BOOST_CHECK_EQUAL(MaxTimesSemiring<uint16_t>().add(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxTimesSemiring<uint16_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxTimesSemiring<uint8_t>().zero(), 0U); BOOST_CHECK_EQUAL(MaxTimesSemiring<uint8_t>().add(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxTimesSemiring<uint8_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxTimesSemiring<int64_t>().zero(), std::numeric_limits<int64_t>::min()); BOOST_CHECK_EQUAL(MaxTimesSemiring<int64_t>().add(-2L, 1L), 1L); BOOST_CHECK_EQUAL(MaxTimesSemiring<int64_t>().mult(-2L, 1L), -2L); BOOST_CHECK_EQUAL(MaxTimesSemiring<int32_t>().zero(), std::numeric_limits<int32_t>::min()); BOOST_CHECK_EQUAL(MaxTimesSemiring<int32_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(MaxTimesSemiring<int32_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(MaxTimesSemiring<int16_t>().zero(), std::numeric_limits<int16_t>::min()); BOOST_CHECK_EQUAL(MaxTimesSemiring<int16_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(MaxTimesSemiring<int16_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(MaxTimesSemiring<int8_t>().zero(), std::numeric_limits<int8_t>::min()); BOOST_CHECK_EQUAL(MaxTimesSemiring<int8_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(MaxTimesSemiring<int8_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(MaxTimesSemiring<bool>().zero(), false); BOOST_CHECK_EQUAL(MaxTimesSemiring<bool>().add(false, false), false); BOOST_CHECK_EQUAL(MaxTimesSemiring<bool>().add(false, true), true); BOOST_CHECK_EQUAL(MaxTimesSemiring<bool>().mult(false, true), false); BOOST_CHECK_EQUAL(MaxTimesSemiring<bool>().mult(true, true), true); } //**************************************************************************** BOOST_AUTO_TEST_CASE(min_max_semiring_test) { BOOST_CHECK_EQUAL(MinMaxSemiring<double>().zero(), std::numeric_limits<double>::infinity()); BOOST_CHECK_EQUAL(MinMaxSemiring<double>().add(-2., 1.), -2.0); BOOST_CHECK_EQUAL(MinMaxSemiring<double>().mult(-2., 1.), 1.0); BOOST_CHECK_EQUAL(MinMaxSemiring<float>().zero(), std::numeric_limits<float>::infinity()); BOOST_CHECK_EQUAL(MinMaxSemiring<float>().add(-2.f, 1.f), -2.0f); BOOST_CHECK_EQUAL(MinMaxSemiring<float>().mult(-2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(MinMaxSemiring<uint64_t>().zero(), std::numeric_limits<uint64_t>::max()); BOOST_CHECK_EQUAL(MinMaxSemiring<uint64_t>().add(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(MinMaxSemiring<uint64_t>().mult(2UL, 1UL), 2UL); BOOST_CHECK_EQUAL(MinMaxSemiring<uint32_t>().zero(), std::numeric_limits<uint32_t>::max()); BOOST_CHECK_EQUAL(MinMaxSemiring<uint32_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinMaxSemiring<uint32_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(MinMaxSemiring<uint16_t>().zero(), std::numeric_limits<uint16_t>::max()); BOOST_CHECK_EQUAL(MinMaxSemiring<uint16_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinMaxSemiring<uint16_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(MinMaxSemiring<uint8_t>().zero(), std::numeric_limits<uint8_t>::max()); BOOST_CHECK_EQUAL(MinMaxSemiring<uint8_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinMaxSemiring<uint8_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(MinMaxSemiring<int64_t>().zero(), std::numeric_limits<int64_t>::max()); BOOST_CHECK_EQUAL(MinMaxSemiring<int64_t>().add(-2L, 1L),-2L); BOOST_CHECK_EQUAL(MinMaxSemiring<int64_t>().mult(-2L, 1L), 1L); BOOST_CHECK_EQUAL(MinMaxSemiring<int32_t>().zero(), std::numeric_limits<int32_t>::max()); BOOST_CHECK_EQUAL(MinMaxSemiring<int32_t>().add(-2, 1),-2); BOOST_CHECK_EQUAL(MinMaxSemiring<int32_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(MinMaxSemiring<int16_t>().zero(), std::numeric_limits<int16_t>::max()); BOOST_CHECK_EQUAL(MinMaxSemiring<int16_t>().add(-2, 1),-2); BOOST_CHECK_EQUAL(MinMaxSemiring<int16_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(MinMaxSemiring<int8_t>().zero(), std::numeric_limits<int8_t>::max()); BOOST_CHECK_EQUAL(MinMaxSemiring<int8_t>().add(-2, 1),-2); BOOST_CHECK_EQUAL(MinMaxSemiring<int8_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(MinMaxSemiring<bool>().zero(), true); BOOST_CHECK_EQUAL(MinMaxSemiring<bool>().add(false, false), false); BOOST_CHECK_EQUAL(MinMaxSemiring<bool>().add(false, true), false); BOOST_CHECK_EQUAL(MinMaxSemiring<bool>().mult(false, true), true); BOOST_CHECK_EQUAL(MinMaxSemiring<bool>().mult(true, true), true); } //**************************************************************************** BOOST_AUTO_TEST_CASE(max_min_semiring_test) { BOOST_CHECK_EQUAL(MaxMinSemiring<double>().zero(), -std::numeric_limits<double>::infinity()); BOOST_CHECK_EQUAL(MaxMinSemiring<double>().add(-2., 1.), 1.0); BOOST_CHECK_EQUAL(MaxMinSemiring<double>().mult(-2., 1.), -2.0); BOOST_CHECK_EQUAL(MaxMinSemiring<float>().zero(), -std::numeric_limits<float>::infinity()); BOOST_CHECK_EQUAL(MaxMinSemiring<float>().add(-2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(MaxMinSemiring<float>().mult(-2.f, 1.f), -2.0f); BOOST_CHECK_EQUAL(MaxMinSemiring<uint64_t>().zero(), 0UL); BOOST_CHECK_EQUAL(MaxMinSemiring<uint64_t>().add(2UL, 1UL), 2UL); BOOST_CHECK_EQUAL(MaxMinSemiring<uint64_t>().mult(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(MaxMinSemiring<uint32_t>().zero(), 0U); BOOST_CHECK_EQUAL(MaxMinSemiring<uint32_t>().add(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxMinSemiring<uint32_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(MaxMinSemiring<uint16_t>().zero(), 0U); BOOST_CHECK_EQUAL(MaxMinSemiring<uint16_t>().add(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxMinSemiring<uint16_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(MaxMinSemiring<uint8_t>().zero(), 0U); BOOST_CHECK_EQUAL(MaxMinSemiring<uint8_t>().add(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxMinSemiring<uint8_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(MaxMinSemiring<int64_t>().zero(), std::numeric_limits<int64_t>::min()); BOOST_CHECK_EQUAL(MaxMinSemiring<int64_t>().add(-2L, 1L), 1L); BOOST_CHECK_EQUAL(MaxMinSemiring<int64_t>().mult(-2L, 1L), -2L); BOOST_CHECK_EQUAL(MaxMinSemiring<int32_t>().zero(), std::numeric_limits<int32_t>::min()); BOOST_CHECK_EQUAL(MaxMinSemiring<int32_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(MaxMinSemiring<int32_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(MaxMinSemiring<int16_t>().zero(), std::numeric_limits<int16_t>::min()); BOOST_CHECK_EQUAL(MaxMinSemiring<int16_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(MaxMinSemiring<int16_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(MaxMinSemiring<int8_t>().zero(), std::numeric_limits<int8_t>::min()); BOOST_CHECK_EQUAL(MaxMinSemiring<int8_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(MaxMinSemiring<int8_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(MaxMinSemiring<bool>().zero(), false); BOOST_CHECK_EQUAL(MaxMinSemiring<bool>().add(false, false), false); BOOST_CHECK_EQUAL(MaxMinSemiring<bool>().add(false, true), true); BOOST_CHECK_EQUAL(MaxMinSemiring<bool>().mult(false, true), false); BOOST_CHECK_EQUAL(MaxMinSemiring<bool>().mult(true, true), true); } //**************************************************************************** BOOST_AUTO_TEST_CASE(plus_min_semiring_test) { BOOST_CHECK_EQUAL(PlusMinSemiring<double>().zero(), 0.); BOOST_CHECK_EQUAL(PlusMinSemiring<double>().add(-2., 1.), -1.0); BOOST_CHECK_EQUAL(PlusMinSemiring<double>().add(2., 1.), 3.0); BOOST_CHECK_EQUAL(PlusMinSemiring<double>().mult(-2., 1.), -2.0); BOOST_CHECK_EQUAL(PlusMinSemiring<float>().zero(), 0.f); BOOST_CHECK_EQUAL(PlusMinSemiring<float>().add(-2.f, 1.f), -1.0f); BOOST_CHECK_EQUAL(PlusMinSemiring<float>().add(2.f, 1.f), 3.0f); BOOST_CHECK_EQUAL(PlusMinSemiring<float>().mult(-2.f, 1.f), -2.0f); BOOST_CHECK_EQUAL(PlusMinSemiring<uint64_t>().zero(), 0UL); BOOST_CHECK_EQUAL(PlusMinSemiring<uint64_t>().add(2UL, 1UL), 3UL); BOOST_CHECK_EQUAL(PlusMinSemiring<uint64_t>().add(2UL, 3UL), 5UL); BOOST_CHECK_EQUAL(PlusMinSemiring<uint64_t>().mult(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(PlusMinSemiring<uint32_t>().zero(), 0U); BOOST_CHECK_EQUAL(PlusMinSemiring<uint32_t>().add(2U, 1U), 3U); BOOST_CHECK_EQUAL(PlusMinSemiring<uint32_t>().add(2U, 3U), 5U); BOOST_CHECK_EQUAL(PlusMinSemiring<uint32_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(PlusMinSemiring<uint16_t>().zero(), 0U); BOOST_CHECK_EQUAL(PlusMinSemiring<uint16_t>().add(2U, 1U), 3U); BOOST_CHECK_EQUAL(PlusMinSemiring<uint16_t>().add(2U, 3U), 5U); BOOST_CHECK_EQUAL(PlusMinSemiring<uint16_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(PlusMinSemiring<uint8_t>().zero(), 0U); BOOST_CHECK_EQUAL(PlusMinSemiring<uint8_t>().add(2U, 1U), 3U); BOOST_CHECK_EQUAL(PlusMinSemiring<uint8_t>().add(2U, 3U), 5U); BOOST_CHECK_EQUAL(PlusMinSemiring<uint8_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(PlusMinSemiring<int64_t>().zero(), 0L); BOOST_CHECK_EQUAL(PlusMinSemiring<int64_t>().add(-2L, 1L), -1L); BOOST_CHECK_EQUAL(PlusMinSemiring<int64_t>().add(2L, -1L), 1L); BOOST_CHECK_EQUAL(PlusMinSemiring<int64_t>().mult(-2L, 1L), -2L); BOOST_CHECK_EQUAL(PlusMinSemiring<int32_t>().zero(), 0); BOOST_CHECK_EQUAL(PlusMinSemiring<int32_t>().add(-2, 1), -1); BOOST_CHECK_EQUAL(PlusMinSemiring<int32_t>().add(2, -1), 1); BOOST_CHECK_EQUAL(PlusMinSemiring<int32_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(PlusMinSemiring<int16_t>().zero(), 0); BOOST_CHECK_EQUAL(PlusMinSemiring<int16_t>().add(-2, 1), -1); BOOST_CHECK_EQUAL(PlusMinSemiring<int16_t>().add(2, -1), 1); BOOST_CHECK_EQUAL(PlusMinSemiring<int16_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(PlusMinSemiring<int8_t>().zero(), 0); BOOST_CHECK_EQUAL(PlusMinSemiring<int8_t>().add(-2, 1), -1); BOOST_CHECK_EQUAL(PlusMinSemiring<int8_t>().add(2, -1), 1); BOOST_CHECK_EQUAL(PlusMinSemiring<int8_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(PlusMinSemiring<bool>().zero(), false); BOOST_CHECK_EQUAL(PlusMinSemiring<bool>().add(false, true), true); BOOST_CHECK_EQUAL(PlusMinSemiring<bool>().add(true, true), true); BOOST_CHECK_EQUAL(PlusMinSemiring<bool>().mult(false, false), false); BOOST_CHECK_EQUAL(PlusMinSemiring<bool>().mult(true, false), false); BOOST_CHECK_EQUAL(PlusMinSemiring<bool>().mult(true, true), true); } //**************************************************************************** BOOST_AUTO_TEST_CASE(logical_semiring_test) { BOOST_CHECK_EQUAL(LogicalSemiring<double>().zero(), 0.0); BOOST_CHECK_EQUAL(LogicalSemiring<double>().add(-2., 1.), 1.0); BOOST_CHECK_EQUAL(LogicalSemiring<double>().add(0., 1.), 1.0); BOOST_CHECK_EQUAL(LogicalSemiring<double>().add(-2., 0.), 1.0); BOOST_CHECK_EQUAL(LogicalSemiring<double>().add(0., 0.), 0.0); BOOST_CHECK_EQUAL(LogicalSemiring<double>().mult(-2., 1.), 1.0); BOOST_CHECK_EQUAL(LogicalSemiring<double>().mult(0., 1.), 0.0); BOOST_CHECK_EQUAL(LogicalSemiring<double>().mult(-2., 0.), 0.0); BOOST_CHECK_EQUAL(LogicalSemiring<double>().mult(0., 0.), 0.0); BOOST_CHECK_EQUAL(LogicalSemiring<float>().zero(), 0.0f); BOOST_CHECK_EQUAL(LogicalSemiring<float>().add(-2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(LogicalSemiring<float>().add(0.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(LogicalSemiring<float>().add(-2.f, 0.f), 1.0f); BOOST_CHECK_EQUAL(LogicalSemiring<float>().add(0.f, 0.f), 0.0f); BOOST_CHECK_EQUAL(LogicalSemiring<float>().mult(-2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(LogicalSemiring<float>().mult(0.f, 1.f), 0.0f); BOOST_CHECK_EQUAL(LogicalSemiring<float>().mult(-2.f, 0.f), 0.0f); BOOST_CHECK_EQUAL(LogicalSemiring<float>().mult(0.f, 0.f), 0.0f); BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().zero(), 0UL); BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().add(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().add(2UL, 0UL), 1UL); BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().add(0UL, 1UL), 1UL); BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().add(0UL, 0UL), 0UL); BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().mult(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().mult(2UL, 0UL), 0UL); BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().mult(0UL, 1UL), 0UL); BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().mult(0UL, 0UL), 0UL); BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().zero(), 0U); BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().add(2U, 0U), 1U); BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().add(0U, 1U), 1U); BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().add(0U, 0U), 0U); BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().mult(2U, 0U), 0U); BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().mult(0U, 1U), 0U); BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().mult(0U, 0U), 0U); BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().zero(), 0U); BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().add(2U, 0U), 1U); BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().add(0U, 1U), 1U); BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().add(0U, 0U), 0U); BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().mult(2U, 0U), 0U); BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().mult(0U, 1U), 0U); BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().mult(0U, 0U), 0U); BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().zero(), 0U); BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().add(2U, 0U), 1U); BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().add(0U, 1U), 1U); BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().add(0U, 0U), 0U); BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().mult(2U, 0U), 0U); BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().mult(0U, 1U), 0U); BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().mult(0U, 0U), 0U); BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().zero(), 0L); BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().add(-2L, 1L), 1L); BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().add(-2L, 0L), 1L); BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().add(0L, 1L), 1L); BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().add(0L, 0L), 0L); BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().mult(-2L, 1L), 1L); BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().mult(-2L, 0L), 0L); BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().mult(0L, 1L), 0L); BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().mult(0L, 0L), 0L); BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().zero(), 0); BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().add(-2, 0), 1); BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().add(0, 1), 1); BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().add(0, 0), 0); BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().mult(-2, 0), 0); BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().mult(0, 1), 0); BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().mult(0, 0), 0); BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().zero(), 0); BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().add(-2, 0), 1); BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().add(0, 1), 1); BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().add(0, 0), 0); BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().mult(-2, 0), 0); BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().mult(0, 1), 0); BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().mult(0, 0), 0); BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().zero(), 0); BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().add(-2, 0), 1); BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().add(0, 1), 1); BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().add(0, 0), 0); BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().mult(-2, 0), 0); BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().mult(0, 1), 0); BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().mult(0, 0), 0); BOOST_CHECK_EQUAL(LogicalSemiring<bool>().zero(), false); BOOST_CHECK_EQUAL(LogicalSemiring<bool>().add(false, false), false); BOOST_CHECK_EQUAL(LogicalSemiring<bool>().add(false, true), true); BOOST_CHECK_EQUAL(LogicalSemiring<bool>().add(true, false), true); BOOST_CHECK_EQUAL(LogicalSemiring<bool>().add(true, true), true); BOOST_CHECK_EQUAL(LogicalSemiring<bool>().mult(false, false), false); BOOST_CHECK_EQUAL(LogicalSemiring<bool>().mult(false, true), false); BOOST_CHECK_EQUAL(LogicalSemiring<bool>().mult(true, false), false); BOOST_CHECK_EQUAL(LogicalSemiring<bool>().mult(true, true), true); } //**************************************************************************** BOOST_AUTO_TEST_CASE(and_or_semiring_test) { BOOST_CHECK_EQUAL(AndOrSemiring<double>().zero(), 1.0); BOOST_CHECK_EQUAL(AndOrSemiring<double>().mult(-2., 1.), 1.0); BOOST_CHECK_EQUAL(AndOrSemiring<double>().mult(0., 1.), 1.0); BOOST_CHECK_EQUAL(AndOrSemiring<double>().mult(-2., 0.), 1.0); BOOST_CHECK_EQUAL(AndOrSemiring<double>().mult(0., 0.), 0.0); BOOST_CHECK_EQUAL(AndOrSemiring<double>().add(-2., 1.), 1.0); BOOST_CHECK_EQUAL(AndOrSemiring<double>().add(0., 1.), 0.0); BOOST_CHECK_EQUAL(AndOrSemiring<double>().add(-2., 0.), 0.0); BOOST_CHECK_EQUAL(AndOrSemiring<double>().add(0., 0.), 0.0); BOOST_CHECK_EQUAL(AndOrSemiring<float>().zero(), 1.0f); BOOST_CHECK_EQUAL(AndOrSemiring<float>().mult(-2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(AndOrSemiring<float>().mult(0.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(AndOrSemiring<float>().mult(-2.f, 0.f), 1.0f); BOOST_CHECK_EQUAL(AndOrSemiring<float>().mult(0.f, 0.f), 0.0f); BOOST_CHECK_EQUAL(AndOrSemiring<float>().add(-2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(AndOrSemiring<float>().add(0.f, 1.f), 0.0f); BOOST_CHECK_EQUAL(AndOrSemiring<float>().add(-2.f, 0.f), 0.0f); BOOST_CHECK_EQUAL(AndOrSemiring<float>().add(0.f, 0.f), 0.0f); BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().zero(), 1UL); BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().mult(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().mult(2UL, 0UL), 1UL); BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().mult(0UL, 1UL), 1UL); BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().mult(0UL, 0UL), 0UL); BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().add(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().add(2UL, 0UL), 0UL); BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().add(0UL, 1UL), 0UL); BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().add(0UL, 0UL), 0UL); BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().zero(), 1U); BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().mult(2U, 0U), 1U); BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().mult(0U, 1U), 1U); BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().mult(0U, 0U), 0U); BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().add(2U, 0U), 0U); BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().add(0U, 1U), 0U); BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().add(0U, 0U), 0U); BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().zero(), 1U); BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().mult(2U, 0U), 1U); BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().mult(0U, 1U), 1U); BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().mult(0U, 0U), 0U); BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().add(2U, 0U), 0U); BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().add(0U, 1U), 0U); BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().add(0U, 0U), 0U); BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().zero(), 1U); BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().mult(2U, 0U), 1U); BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().mult(0U, 1U), 1U); BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().mult(0U, 0U), 0U); BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().add(2U, 0U), 0U); BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().add(0U, 1U), 0U); BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().add(0U, 0U), 0U); BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().zero(), 1L); BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().mult(-2L, 1L), 1L); BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().mult(-2L, 0L), 1L); BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().mult(0L, 1L), 1L); BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().mult(0L, 0L), 0L); BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().add(-2L, 1L), 1L); BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().add(-2L, 0L), 0L); BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().add(0L, 1L), 0L); BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().add(0L, 0L), 0L); BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().zero(), 1); BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().mult(-2, 0), 1); BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().mult(0, 1), 1); BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().mult(0, 0), 0); BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().add(-2, 0), 0); BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().add(0, 1), 0); BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().add(0, 0), 0); BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().zero(), 1); BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().mult(-2, 0), 1); BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().mult(0, 1), 1); BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().mult(0, 0), 0); BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().add(-2, 0), 0); BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().add(0, 1), 0); BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().add(0, 0), 0); BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().zero(), 1); BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().mult(-2, 0), 1); BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().mult(0, 1), 1); BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().mult(0, 0), 0); BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().add(-2, 0), 0); BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().add(0, 1), 0); BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().add(0, 0), 0); BOOST_CHECK_EQUAL(AndOrSemiring<bool>().zero(), true); BOOST_CHECK_EQUAL(AndOrSemiring<bool>().mult(false, false), false); BOOST_CHECK_EQUAL(AndOrSemiring<bool>().mult(false, true), true); BOOST_CHECK_EQUAL(AndOrSemiring<bool>().mult(true, false), true); BOOST_CHECK_EQUAL(AndOrSemiring<bool>().mult(true, true), true); BOOST_CHECK_EQUAL(AndOrSemiring<bool>().add(false, false), false); BOOST_CHECK_EQUAL(AndOrSemiring<bool>().add(false, true), false); BOOST_CHECK_EQUAL(AndOrSemiring<bool>().add(true, false), false); BOOST_CHECK_EQUAL(AndOrSemiring<bool>().add(true, true), true); } //**************************************************************************** BOOST_AUTO_TEST_CASE(xor_and_semiring_test) { BOOST_CHECK_EQUAL(XorAndSemiring<double>().zero(), 0.0); BOOST_CHECK_EQUAL(XorAndSemiring<double>().add(-2., 1.), 0.0); BOOST_CHECK_EQUAL(XorAndSemiring<double>().add(0., 1.), 1.0); BOOST_CHECK_EQUAL(XorAndSemiring<double>().add(-2., 0.), 1.0); BOOST_CHECK_EQUAL(XorAndSemiring<double>().add(0., 0.), 0.0); BOOST_CHECK_EQUAL(XorAndSemiring<double>().mult(-2., 1.), 1.0); BOOST_CHECK_EQUAL(XorAndSemiring<double>().mult(0., 1.), 0.0); BOOST_CHECK_EQUAL(XorAndSemiring<double>().mult(-2., 0.), 0.0); BOOST_CHECK_EQUAL(XorAndSemiring<double>().mult(0., 0.), 0.0); BOOST_CHECK_EQUAL(XorAndSemiring<float>().zero(), 0.0f); BOOST_CHECK_EQUAL(XorAndSemiring<float>().add(-2.f, 1.f), 0.0f); BOOST_CHECK_EQUAL(XorAndSemiring<float>().add(0.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(XorAndSemiring<float>().add(-2.f, 0.f), 1.0f); BOOST_CHECK_EQUAL(XorAndSemiring<float>().add(0.f, 0.f), 0.0f); BOOST_CHECK_EQUAL(XorAndSemiring<float>().mult(-2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(XorAndSemiring<float>().mult(0.f, 1.f), 0.0f); BOOST_CHECK_EQUAL(XorAndSemiring<float>().mult(-2.f, 0.f), 0.0f); BOOST_CHECK_EQUAL(XorAndSemiring<float>().mult(0.f, 0.f), 0.0f); BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().zero(), 0UL); BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().add(2UL, 1UL), 0UL); BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().add(2UL, 0UL), 1UL); BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().add(0UL, 1UL), 1UL); BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().add(0UL, 0UL), 0UL); BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().mult(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().mult(2UL, 0UL), 0UL); BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().mult(0UL, 1UL), 0UL); BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().mult(0UL, 0UL), 0UL); BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().zero(), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().add(2U, 1U), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().add(2U, 0U), 1U); BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().add(0U, 1U), 1U); BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().add(0U, 0U), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().mult(2U, 0U), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().mult(0U, 1U), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().mult(0U, 0U), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().zero(), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().add(2U, 1U), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().add(2U, 0U), 1U); BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().add(0U, 1U), 1U); BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().add(0U, 0U), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().mult(2U, 0U), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().mult(0U, 1U), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().mult(0U, 0U), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().zero(), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().add(2U, 1U), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().add(2U, 0U), 1U); BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().add(0U, 1U), 1U); BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().add(0U, 0U), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().mult(2U, 0U), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().mult(0U, 1U), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().mult(0U, 0U), 0U); BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().zero(), 0L); BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().add(-2L, 1L), 0L); BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().add(-2L, 0L), 1L); BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().add(0L, 1L), 1L); BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().add(0L, 0L), 0L); BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().mult(-2L, 1L), 1L); BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().mult(-2L, 0L), 0L); BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().mult(0L, 1L), 0L); BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().mult(0L, 0L), 0L); BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().zero(), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().add(-2, 1), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().add(-2, 0), 1); BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().add(0, 1), 1); BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().add(0, 0), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().mult(-2, 0), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().mult(0, 1), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().mult(0, 0), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().zero(), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().add(-2, 1), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().add(-2, 0), 1); BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().add(0, 1), 1); BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().add(0, 0), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().mult(-2, 0), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().mult(0, 1), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().mult(0, 0), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().zero(), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().add(-2, 1), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().add(-2, 0), 1); BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().add(0, 1), 1); BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().add(0, 0), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().mult(-2, 0), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().mult(0, 1), 0); BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().mult(0, 0), 0); BOOST_CHECK_EQUAL(XorAndSemiring<bool>().zero(), false); BOOST_CHECK_EQUAL(XorAndSemiring<bool>().add(false, false), false); BOOST_CHECK_EQUAL(XorAndSemiring<bool>().add(false, true), true); BOOST_CHECK_EQUAL(XorAndSemiring<bool>().add(true, false), true); BOOST_CHECK_EQUAL(XorAndSemiring<bool>().add(true, true), false); BOOST_CHECK_EQUAL(XorAndSemiring<bool>().mult(false, false), false); BOOST_CHECK_EQUAL(XorAndSemiring<bool>().mult(false, true), false); BOOST_CHECK_EQUAL(XorAndSemiring<bool>().mult(true, false), false); BOOST_CHECK_EQUAL(XorAndSemiring<bool>().mult(true, true), true); } //**************************************************************************** BOOST_AUTO_TEST_CASE(xnor_or_semiring_test) { BOOST_CHECK_EQUAL(XnorOrSemiring<double>().zero(), 1.0); BOOST_CHECK_EQUAL(XnorOrSemiring<double>().mult(-2., 1.), 1.0); BOOST_CHECK_EQUAL(XnorOrSemiring<double>().mult(0., 1.), 1.0); BOOST_CHECK_EQUAL(XnorOrSemiring<double>().mult(-2., 0.), 1.0); BOOST_CHECK_EQUAL(XnorOrSemiring<double>().mult(0., 0.), 0.0); BOOST_CHECK_EQUAL(XnorOrSemiring<double>().add(-2., 1.), 1.0); BOOST_CHECK_EQUAL(XnorOrSemiring<double>().add(0., 1.), 0.0); BOOST_CHECK_EQUAL(XnorOrSemiring<double>().add(-2., 0.), 0.0); BOOST_CHECK_EQUAL(XnorOrSemiring<double>().add(0., 0.), 1.0); BOOST_CHECK_EQUAL(XnorOrSemiring<float>().zero(), 1.0f); BOOST_CHECK_EQUAL(XnorOrSemiring<float>().mult(-2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(XnorOrSemiring<float>().mult(0.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(XnorOrSemiring<float>().mult(-2.f, 0.f), 1.0f); BOOST_CHECK_EQUAL(XnorOrSemiring<float>().mult(0.f, 0.f), 0.0f); BOOST_CHECK_EQUAL(XnorOrSemiring<float>().add(-2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(XnorOrSemiring<float>().add(0.f, 1.f), 0.0f); BOOST_CHECK_EQUAL(XnorOrSemiring<float>().add(-2.f, 0.f), 0.0f); BOOST_CHECK_EQUAL(XnorOrSemiring<float>().add(0.f, 0.f), 1.0f); BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().zero(), 1UL); BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().mult(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().mult(2UL, 0UL), 1UL); BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().mult(0UL, 1UL), 1UL); BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().mult(0UL, 0UL), 0UL); BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().add(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().add(2UL, 0UL), 0UL); BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().add(0UL, 1UL), 0UL); BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().add(0UL, 0UL), 1UL); BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().zero(), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().mult(2U, 0U), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().mult(0U, 1U), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().mult(0U, 0U), 0U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().add(2U, 0U), 0U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().add(0U, 1U), 0U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().add(0U, 0U), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().zero(), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().mult(2U, 0U), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().mult(0U, 1U), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().mult(0U, 0U), 0U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().add(2U, 0U), 0U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().add(0U, 1U), 0U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().add(0U, 0U), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().zero(), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().mult(2U, 0U), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().mult(0U, 1U), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().mult(0U, 0U), 0U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().add(2U, 0U), 0U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().add(0U, 1U), 0U); BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().add(0U, 0U), 1U); BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().zero(), 1L); BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().mult(-2L, 1L), 1L); BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().mult(-2L, 0L), 1L); BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().mult(0L, 1L), 1L); BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().mult(0L, 0L), 0L); BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().add(-2L, 1L), 1L); BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().add(-2L, 0L), 0L); BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().add(0L, 1L), 0L); BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().add(0L, 0L), 1L); BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().zero(), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().mult(-2, 0), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().mult(0, 1), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().mult(0, 0), 0); BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().add(-2, 0), 0); BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().add(0, 1), 0); BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().add(0, 0), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().zero(), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().mult(-2, 0), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().mult(0, 1), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().mult(0, 0), 0); BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().add(-2, 0), 0); BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().add(0, 1), 0); BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().add(0, 0), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().zero(), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().mult(-2, 0), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().mult(0, 1), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().mult(0, 0), 0); BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().add(-2, 0), 0); BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().add(0, 1), 0); BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().add(0, 0), 1); BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().zero(), true); BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().mult(false, false), false); BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().mult(false, true), true); BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().mult(true, false), true); BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().mult(true, true), true); BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().add(false, false), true); BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().add(false, true), false); BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().add(true, false), false); BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().add(true, true), true); } //**************************************************************************** BOOST_AUTO_TEST_CASE(min_first_test) { BOOST_CHECK_EQUAL(MinFirstSemiring<double>().zero(), std::numeric_limits<double>::infinity()); BOOST_CHECK_EQUAL(MinFirstSemiring<double>().add(-2., 1.), -2.0); BOOST_CHECK_EQUAL(MinFirstSemiring<double>().add(2., 1.), 1.0); BOOST_CHECK_EQUAL(MinFirstSemiring<double>().mult(-2., 1.), -2.0); BOOST_CHECK_EQUAL(MinFirstSemiring<float>().zero(), std::numeric_limits<float>::infinity()); BOOST_CHECK_EQUAL(MinFirstSemiring<float>().add(-2.f, 1.f), -2.0f); BOOST_CHECK_EQUAL(MinFirstSemiring<float>().add(2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(MinFirstSemiring<float>().mult(-2.f, 1.f), -2.0f); BOOST_CHECK_EQUAL(MinFirstSemiring<uint64_t>().zero(), std::numeric_limits<uint64_t>::max()); BOOST_CHECK_EQUAL(MinFirstSemiring<uint64_t>().add(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(MinFirstSemiring<uint64_t>().add(2UL, 3UL), 2UL); BOOST_CHECK_EQUAL(MinFirstSemiring<uint64_t>().mult(2UL, 1UL), 2UL); BOOST_CHECK_EQUAL(MinFirstSemiring<uint32_t>().zero(), std::numeric_limits<uint32_t>::max()); BOOST_CHECK_EQUAL(MinFirstSemiring<uint32_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinFirstSemiring<uint32_t>().add(2U, 3U), 2U); BOOST_CHECK_EQUAL(MinFirstSemiring<uint32_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(MinFirstSemiring<uint16_t>().zero(), std::numeric_limits<uint16_t>::max()); BOOST_CHECK_EQUAL(MinFirstSemiring<uint16_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinFirstSemiring<uint16_t>().add(2U, 3U), 2U); BOOST_CHECK_EQUAL(MinFirstSemiring<uint16_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(MinFirstSemiring<uint8_t>().zero(), std::numeric_limits<uint8_t>::max()); BOOST_CHECK_EQUAL(MinFirstSemiring<uint8_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinFirstSemiring<uint8_t>().add(2U, 3U), 2U); BOOST_CHECK_EQUAL(MinFirstSemiring<uint8_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(MinFirstSemiring<int64_t>().zero(), std::numeric_limits<int64_t>::max()); BOOST_CHECK_EQUAL(MinFirstSemiring<int64_t>().add(-2L, 1L), -2L); BOOST_CHECK_EQUAL(MinFirstSemiring<int64_t>().add(2L, -1L), -1L); BOOST_CHECK_EQUAL(MinFirstSemiring<int64_t>().mult(-2L, 1L), -2L); BOOST_CHECK_EQUAL(MinFirstSemiring<int32_t>().zero(), std::numeric_limits<int32_t>::max()); BOOST_CHECK_EQUAL(MinFirstSemiring<int32_t>().add(-2, 1), -2); BOOST_CHECK_EQUAL(MinFirstSemiring<int32_t>().add(2, -1), -1); BOOST_CHECK_EQUAL(MinFirstSemiring<int32_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(MinFirstSemiring<int16_t>().zero(), std::numeric_limits<int16_t>::max()); BOOST_CHECK_EQUAL(MinFirstSemiring<int16_t>().add(-2, 1), -2); BOOST_CHECK_EQUAL(MinFirstSemiring<int16_t>().add(2, -1), -1); BOOST_CHECK_EQUAL(MinFirstSemiring<int16_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(MinFirstSemiring<int8_t>().zero(), std::numeric_limits<int8_t>::max()); BOOST_CHECK_EQUAL(MinFirstSemiring<int8_t>().add(-2, 1), -2); BOOST_CHECK_EQUAL(MinFirstSemiring<int8_t>().add(2, -1), -1); BOOST_CHECK_EQUAL(MinFirstSemiring<int8_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(MinFirstSemiring<bool>().zero(), true); BOOST_CHECK_EQUAL(MinFirstSemiring<bool>().add(false, true), false); BOOST_CHECK_EQUAL(MinFirstSemiring<bool>().add(true, true), true); BOOST_CHECK_EQUAL(MinFirstSemiring<bool>().mult(true, false), true); BOOST_CHECK_EQUAL(MinFirstSemiring<bool>().mult(false, true), false); } //**************************************************************************** BOOST_AUTO_TEST_CASE(min_second_test) { BOOST_CHECK_EQUAL(MinSecondSemiring<double>().zero(), std::numeric_limits<double>::infinity()); BOOST_CHECK_EQUAL(MinSecondSemiring<double>().add(-2., 1.), -2.0); BOOST_CHECK_EQUAL(MinSecondSemiring<double>().add(2., 1.), 1.0); BOOST_CHECK_EQUAL(MinSecondSemiring<double>().mult(-2., 1.), 1.0); BOOST_CHECK_EQUAL(MinSecondSemiring<float>().zero(), std::numeric_limits<float>::infinity()); BOOST_CHECK_EQUAL(MinSecondSemiring<float>().add(-2.f, 1.f), -2.0f); BOOST_CHECK_EQUAL(MinSecondSemiring<float>().add(2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(MinSecondSemiring<float>().mult(-2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(MinSecondSemiring<uint64_t>().zero(), std::numeric_limits<uint64_t>::max()); BOOST_CHECK_EQUAL(MinSecondSemiring<uint64_t>().add(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(MinSecondSemiring<uint64_t>().add(2UL, 3UL), 2UL); BOOST_CHECK_EQUAL(MinSecondSemiring<uint64_t>().mult(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(MinSecondSemiring<uint32_t>().zero(), std::numeric_limits<uint32_t>::max()); BOOST_CHECK_EQUAL(MinSecondSemiring<uint32_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinSecondSemiring<uint32_t>().add(2U, 3U), 2U); BOOST_CHECK_EQUAL(MinSecondSemiring<uint32_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinSecondSemiring<uint16_t>().zero(), std::numeric_limits<uint16_t>::max()); BOOST_CHECK_EQUAL(MinSecondSemiring<uint16_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinSecondSemiring<uint16_t>().add(2U, 3U), 2U); BOOST_CHECK_EQUAL(MinSecondSemiring<uint16_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinSecondSemiring<uint8_t>().zero(), std::numeric_limits<uint8_t>::max()); BOOST_CHECK_EQUAL(MinSecondSemiring<uint8_t>().add(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinSecondSemiring<uint8_t>().add(2U, 3U), 2U); BOOST_CHECK_EQUAL(MinSecondSemiring<uint8_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(MinSecondSemiring<int64_t>().zero(), std::numeric_limits<int64_t>::max()); BOOST_CHECK_EQUAL(MinSecondSemiring<int64_t>().add(-2L, 1L), -2L); BOOST_CHECK_EQUAL(MinSecondSemiring<int64_t>().add(2L, -1L), -1L); BOOST_CHECK_EQUAL(MinSecondSemiring<int64_t>().mult(-2L, 1L), 1L); BOOST_CHECK_EQUAL(MinSecondSemiring<int32_t>().zero(), std::numeric_limits<int32_t>::max()); BOOST_CHECK_EQUAL(MinSecondSemiring<int32_t>().add(-2, 1), -2); BOOST_CHECK_EQUAL(MinSecondSemiring<int32_t>().add(2, -1), -1); BOOST_CHECK_EQUAL(MinSecondSemiring<int32_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(MinSecondSemiring<int16_t>().zero(), std::numeric_limits<int16_t>::max()); BOOST_CHECK_EQUAL(MinSecondSemiring<int16_t>().add(-2, 1), -2); BOOST_CHECK_EQUAL(MinSecondSemiring<int16_t>().add(2, -1), -1); BOOST_CHECK_EQUAL(MinSecondSemiring<int16_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(MinSecondSemiring<int8_t>().zero(), std::numeric_limits<int8_t>::max()); BOOST_CHECK_EQUAL(MinSecondSemiring<int8_t>().add(-2, 1), -2); BOOST_CHECK_EQUAL(MinSecondSemiring<int8_t>().add(2, -1), -1); BOOST_CHECK_EQUAL(MinSecondSemiring<int8_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(MinSecondSemiring<bool>().zero(), true); BOOST_CHECK_EQUAL(MinSecondSemiring<bool>().add(false, true), false); BOOST_CHECK_EQUAL(MinSecondSemiring<bool>().add(true, true), true); BOOST_CHECK_EQUAL(MinSecondSemiring<bool>().mult(true, false), false); BOOST_CHECK_EQUAL(MinSecondSemiring<bool>().mult(false, true), true); } //**************************************************************************** BOOST_AUTO_TEST_CASE(max_first_test) { BOOST_CHECK_EQUAL(MaxFirstSemiring<double>().zero(), -std::numeric_limits<double>::infinity()); BOOST_CHECK_EQUAL(MaxFirstSemiring<double>().add(-2., 1.), 1.0); BOOST_CHECK_EQUAL(MaxFirstSemiring<double>().mult(-2., 1.), -2.0); BOOST_CHECK_EQUAL(MaxFirstSemiring<float>().zero(), -std::numeric_limits<float>::infinity()); BOOST_CHECK_EQUAL(MaxFirstSemiring<float>().add(-2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(MaxFirstSemiring<float>().mult(-2.f, 1.f), -2.0f); BOOST_CHECK_EQUAL(MaxFirstSemiring<uint64_t>().zero(), 0UL); BOOST_CHECK_EQUAL(MaxFirstSemiring<uint64_t>().add(2UL, 1UL), 2UL); BOOST_CHECK_EQUAL(MaxFirstSemiring<uint64_t>().mult(2UL, 1UL), 2UL); BOOST_CHECK_EQUAL(MaxFirstSemiring<uint32_t>().zero(), 0U); BOOST_CHECK_EQUAL(MaxFirstSemiring<uint32_t>().add(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxFirstSemiring<uint32_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxFirstSemiring<uint16_t>().zero(), 0U); BOOST_CHECK_EQUAL(MaxFirstSemiring<uint16_t>().add(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxFirstSemiring<uint16_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxFirstSemiring<uint8_t>().zero(), 0U); BOOST_CHECK_EQUAL(MaxFirstSemiring<uint8_t>().add(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxFirstSemiring<uint8_t>().mult(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxFirstSemiring<int64_t>().zero(), std::numeric_limits<int64_t>::min()); BOOST_CHECK_EQUAL(MaxFirstSemiring<int64_t>().add(-2L, 1L), 1L); BOOST_CHECK_EQUAL(MaxFirstSemiring<int64_t>().mult(-2L, 1L), -2L); BOOST_CHECK_EQUAL(MaxFirstSemiring<int32_t>().zero(), std::numeric_limits<int32_t>::min()); BOOST_CHECK_EQUAL(MaxFirstSemiring<int32_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(MaxFirstSemiring<int32_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(MaxFirstSemiring<int16_t>().zero(), std::numeric_limits<int16_t>::min()); BOOST_CHECK_EQUAL(MaxFirstSemiring<int16_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(MaxFirstSemiring<int16_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(MaxFirstSemiring<int8_t>().zero(), std::numeric_limits<int8_t>::min()); BOOST_CHECK_EQUAL(MaxFirstSemiring<int8_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(MaxFirstSemiring<int8_t>().mult(-2, 1), -2); BOOST_CHECK_EQUAL(MaxFirstSemiring<bool>().zero(), false); BOOST_CHECK_EQUAL(MaxFirstSemiring<bool>().add(false, false), false); BOOST_CHECK_EQUAL(MaxFirstSemiring<bool>().add(false, true), true); BOOST_CHECK_EQUAL(MaxFirstSemiring<bool>().mult(false, true), false); BOOST_CHECK_EQUAL(MaxFirstSemiring<bool>().mult(true, false), true); } //**************************************************************************** BOOST_AUTO_TEST_CASE(max_second_test) { BOOST_CHECK_EQUAL(MaxSecondSemiring<double>().zero(), -std::numeric_limits<double>::infinity()); BOOST_CHECK_EQUAL(MaxSecondSemiring<double>().add(-2., 1.), 1.0); BOOST_CHECK_EQUAL(MaxSecondSemiring<double>().mult(-2., 1.), 1.0); BOOST_CHECK_EQUAL(MaxSecondSemiring<float>().zero(), -std::numeric_limits<float>::infinity()); BOOST_CHECK_EQUAL(MaxSecondSemiring<float>().add(-2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(MaxSecondSemiring<float>().mult(-2.f, 1.f), 1.0f); BOOST_CHECK_EQUAL(MaxSecondSemiring<uint64_t>().zero(), 0UL); BOOST_CHECK_EQUAL(MaxSecondSemiring<uint64_t>().add(2UL, 1UL), 2UL); BOOST_CHECK_EQUAL(MaxSecondSemiring<uint64_t>().mult(2UL, 1UL), 1UL); BOOST_CHECK_EQUAL(MaxSecondSemiring<uint32_t>().zero(), 0U); BOOST_CHECK_EQUAL(MaxSecondSemiring<uint32_t>().add(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxSecondSemiring<uint32_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(MaxSecondSemiring<uint16_t>().zero(), 0U); BOOST_CHECK_EQUAL(MaxSecondSemiring<uint16_t>().add(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxSecondSemiring<uint16_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(MaxSecondSemiring<uint8_t>().zero(), 0U); BOOST_CHECK_EQUAL(MaxSecondSemiring<uint8_t>().add(2U, 1U), 2U); BOOST_CHECK_EQUAL(MaxSecondSemiring<uint8_t>().mult(2U, 1U), 1U); BOOST_CHECK_EQUAL(MaxSecondSemiring<int64_t>().zero(), std::numeric_limits<int64_t>::min()); BOOST_CHECK_EQUAL(MaxSecondSemiring<int64_t>().add(-2L, 1L), 1L); BOOST_CHECK_EQUAL(MaxSecondSemiring<int64_t>().mult(-2L, 1L), 1L); BOOST_CHECK_EQUAL(MaxSecondSemiring<int32_t>().zero(), std::numeric_limits<int32_t>::min()); BOOST_CHECK_EQUAL(MaxSecondSemiring<int32_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(MaxSecondSemiring<int32_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(MaxSecondSemiring<int16_t>().zero(), std::numeric_limits<int16_t>::min()); BOOST_CHECK_EQUAL(MaxSecondSemiring<int16_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(MaxSecondSemiring<int16_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(MaxSecondSemiring<int8_t>().zero(), std::numeric_limits<int8_t>::min()); BOOST_CHECK_EQUAL(MaxSecondSemiring<int8_t>().add(-2, 1), 1); BOOST_CHECK_EQUAL(MaxSecondSemiring<int8_t>().mult(-2, 1), 1); BOOST_CHECK_EQUAL(MaxSecondSemiring<bool>().zero(), false); BOOST_CHECK_EQUAL(MaxSecondSemiring<bool>().add(false, false), false); BOOST_CHECK_EQUAL(MaxSecondSemiring<bool>().add(false, true), true); BOOST_CHECK_EQUAL(MaxSecondSemiring<bool>().mult(false, true), true); BOOST_CHECK_EQUAL(MaxSecondSemiring<bool>().mult(true, false), false); } BOOST_AUTO_TEST_SUITE_END()
55.918692
80
0.680667
KIwabuchi
43146e3e831203873c8b2985ca353dd08806f500
1,037
cpp
C++
Pumpkin Knight/Motor2D/Button.cpp
RustikTie/Pumpkin-Knight
7a93689fe69adbf4b35ded6509dec40f793969ed
[ "MIT" ]
null
null
null
Pumpkin Knight/Motor2D/Button.cpp
RustikTie/Pumpkin-Knight
7a93689fe69adbf4b35ded6509dec40f793969ed
[ "MIT" ]
null
null
null
Pumpkin Knight/Motor2D/Button.cpp
RustikTie/Pumpkin-Knight
7a93689fe69adbf4b35ded6509dec40f793969ed
[ "MIT" ]
null
null
null
#include "Button.h" #include "p2Log.h" #include "j1App.h" #include "j1Render.h" #include "j1Textures.h" #include "j1Window.h" #include "j1Fonts.h" #include "j1Gui.h" Button::Button(int x, int y, ElementType types, bool show, SDL_Rect* rec, const char* text) : Element(x, y, types) { if (text != nullptr) { buttontext = text; ButtonText = App->font->Print(buttontext, { 255, 255, 255 }, App->gui->font); } texture_rect = rec; ButtonBox = App->gui->GetAtlas(); tex_width = rec->w; tex_height = rec->h; this->show = show; } Button::~Button() { } void Button::Draw() { if (show) { int rect_x = pos.x - App->render->camera.x; int rect_y = pos.y - App->render->camera.y; debug_rect = { rect_x, rect_y, (int)(tex_width*0.5f), (int)(tex_height*0.5f) }; App->render->Blit(ButtonBox, pos.x, pos.y, 0.5f, 0.5f, false, texture_rect); App->render->Blit(ButtonText, pos.x + (tex_width / 6), pos.y + (tex_height / 7), 1, 1, false); if (debug == true) { App->render->DrawQuad(debug_rect, 0, 255, 0, 50); } } }
21.163265
114
0.63163
RustikTie
431550ccaee29bed8b7f522bc78af873723504ef
1,052
cpp
C++
QSynthesis/Frontend/Base/Graphics/GraphicsPlaneHandle.cpp
SineStriker/QSynthesis-Old
7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d
[ "MIT" ]
3
2021-12-08T05:30:52.000Z
2021-12-18T10:46:49.000Z
QSynthesis/Frontend/Base/Graphics/GraphicsPlaneHandle.cpp
QSynthesis/QSynthesis-Old
7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d
[ "MIT" ]
null
null
null
QSynthesis/Frontend/Base/Graphics/GraphicsPlaneHandle.cpp
QSynthesis/QSynthesis-Old
7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d
[ "MIT" ]
null
null
null
#include "GraphicsPlaneHandle.h" GraphicsPlaneHandle::GraphicsPlaneHandle(QGraphicsItem *parent) : GraphicsHandle(parent) { } GraphicsPlaneHandle::~GraphicsPlaneHandle() { } void GraphicsPlaneHandle::init() { } void GraphicsPlaneHandle::setValue(QPointF values) { setValueX(values.x()); setValueY(values.y()); } void GraphicsPlaneHandle::setValueX(double value) { double toX = 0; toX = value * (m_region.right() - m_region.left()) + m_region.left(); setLocation(limitArea(MorePoint(toX, y()))); } void GraphicsPlaneHandle::setValueY(double value) { double toY = 0; toY = value * (m_region.bottom() - m_region.top()) + m_region.top(); setLocation(limitArea(MorePoint(x(), toY))); } QPointF GraphicsPlaneHandle::value() const { return QPointF(valueX(), valueY()); } double GraphicsPlaneHandle::valueX() const { return (x() - m_region.left()) / (m_region.right() - m_region.left()); } double GraphicsPlaneHandle::valueY() const { return (y() - m_region.top()) / (m_region.bottom() - m_region.top()); }
26.3
90
0.690114
SineStriker
4317c10a6276d0f3b708c21a11bf9a6d8a15bb74
9,239
cc
C++
RPC/MessageSocketTest.cc
Alex-II/logcabin_raft_optimzations
f6ac900f386ccfb28eae43ebef0576f48d189ab9
[ "ISC" ]
null
null
null
RPC/MessageSocketTest.cc
Alex-II/logcabin_raft_optimzations
f6ac900f386ccfb28eae43ebef0576f48d189ab9
[ "ISC" ]
null
null
null
RPC/MessageSocketTest.cc
Alex-II/logcabin_raft_optimzations
f6ac900f386ccfb28eae43ebef0576f48d189ab9
[ "ISC" ]
null
null
null
/* Copyright (c) 2012 Stanford University * Copyright (c) 2015 Diego Ongaro * * Permission to use, copy, modify, and 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(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS 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. */ #include <memory> #include <gtest/gtest.h> #include <sys/epoll.h> #include <sys/socket.h> #include <sys/types.h> #include "../Core/Debug.h" #include "../Event/Loop.h" #include "../RPC/MessageSocket.h" namespace LogCabin { namespace RPC { namespace { const char* payload = "abcdefghijklmnopqrstuvwxyz0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ+-"; using Core::Buffer; class MyMessageSocketHandler : public MessageSocket::Handler { MyMessageSocketHandler() : lastReceivedId(~0UL) , lastReceivedPayload() , disconnected(false) { } void handleReceivedMessage(MessageId messageId, Buffer message) { lastReceivedId = messageId; lastReceivedPayload = std::move(message); } void handleDisconnect() { EXPECT_FALSE(disconnected); disconnected = true; } MessageId lastReceivedId; Buffer lastReceivedPayload; bool disconnected; }; class RPCMessageSocketTest : public ::testing::Test { RPCMessageSocketTest() : loop() , handler() , msgSocket() , remote(-1) { int socketPair[2]; EXPECT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK, 0, socketPair)); remote = socketPair[1]; msgSocket.reset(new MessageSocket(handler, loop, socketPair[0], 64)); } ~RPCMessageSocketTest() { closeRemote(); } void closeRemote() { if (remote >= 0) { EXPECT_EQ(0, close(remote)); remote = -1; } } Event::Loop loop; MyMessageSocketHandler handler; std::unique_ptr<MessageSocket> msgSocket; int remote; }; TEST_F(RPCMessageSocketTest, close) { msgSocket->close(); EXPECT_TRUE(handler.disconnected); } TEST_F(RPCMessageSocketTest, sendMessage) { EXPECT_DEATH(msgSocket->sendMessage(0, Buffer(NULL, ~0U, NULL)), "too long to send"); char hi[3]; strncpy(hi, "hi", sizeof(hi)); msgSocket->sendMessage(123, Buffer(hi, 3, NULL)); ASSERT_EQ(1U, msgSocket->outboundQueue.size()); MessageSocket::Outbound& outbound = msgSocket->outboundQueue.front(); EXPECT_EQ(0U, outbound.bytesSent); outbound.header.fromBigEndian(); EXPECT_EQ(123U, outbound.header.messageId); EXPECT_EQ(3U, outbound.header.payloadLength); EXPECT_EQ(hi, outbound.message.getData()); EXPECT_EQ(3U, outbound.message.getLength()); } TEST_F(RPCMessageSocketTest, readableSpurious) { msgSocket->readable(); EXPECT_FALSE(handler.disconnected); msgSocket->readable(); EXPECT_EQ(0U, msgSocket->inbound.bytesRead); EXPECT_FALSE(handler.disconnected); } TEST_F(RPCMessageSocketTest, readableSenderDisconnectInHeader) { closeRemote(); msgSocket->readable(); EXPECT_TRUE(handler.disconnected); } TEST_F(RPCMessageSocketTest, readableMessageTooLong) { MessageSocket::Header header; header.fixed = 0xdaf4; header.version = 1; header.payloadLength = 65; header.messageId = 0; header.toBigEndian(); EXPECT_EQ(ssize_t(sizeof(header)), send(remote, &header, sizeof(header), 0)); LogCabin::Core::Debug::setLogPolicy({{"", "ERROR"}}); msgSocket->readable(); ASSERT_TRUE(handler.disconnected); } TEST_F(RPCMessageSocketTest, readableEmptyPayload) { // This test exists to prevent a regression. Before, sending a message with // a length of 0 was not handled correctly. MessageSocket::Header header; header.fixed = 0xdaf4; header.version = 1; header.payloadLength = 0; header.messageId = 12; header.toBigEndian(); EXPECT_EQ(ssize_t(sizeof(header)), send(remote, &header, sizeof(header), 0)); msgSocket->readable(); ASSERT_FALSE(handler.disconnected); EXPECT_EQ(0U, msgSocket->inbound.bytesRead); EXPECT_EQ(12U, handler.lastReceivedId); EXPECT_EQ(0U, handler.lastReceivedPayload.getLength()); } TEST_F(RPCMessageSocketTest, readableSenderDisconnectInPayload) { MessageSocket::Header header; header.fixed = 0xdaf4; header.version = 1; header.payloadLength = 1; header.messageId = 0; header.toBigEndian(); EXPECT_EQ(ssize_t(sizeof(header)), send(remote, &header, sizeof(header), 0)); msgSocket->readable(); ASSERT_FALSE(handler.disconnected); EXPECT_EQ(sizeof(header), msgSocket->inbound.bytesRead); closeRemote(); msgSocket->readable(); EXPECT_TRUE(handler.disconnected); } TEST_F(RPCMessageSocketTest, readableAllAtOnce) { MessageSocket::Header header; header.fixed = 0xdaf4; header.version = 1; header.payloadLength = 64; header.messageId = 0xdeadbeef8badf00d; header.toBigEndian(); char buf[sizeof(header) + 64]; memcpy(buf, &header, sizeof(header)); header.fromBigEndian(); strncpy(buf + sizeof(header), payload, 64); EXPECT_EQ(ssize_t(sizeof(buf)), send(remote, buf, sizeof(buf), 0)); // will do one read for the header msgSocket->readable(); ASSERT_FALSE(handler.disconnected); // and a second read for the data msgSocket->readable(); ASSERT_FALSE(handler.disconnected); EXPECT_EQ(header.messageId, handler.lastReceivedId); EXPECT_EQ(payload, std::string(static_cast<const char*>( handler.lastReceivedPayload.getData()), handler.lastReceivedPayload.getLength())); EXPECT_EQ(1, send(remote, "x", 1, 0)); msgSocket->readable(); EXPECT_FALSE(handler.disconnected); EXPECT_EQ(1U, msgSocket->inbound.bytesRead); } TEST_F(RPCMessageSocketTest, readableBytewise) { MessageSocket::Header header; header.fixed = 0xdaf4; header.version = 1; header.payloadLength = 64; header.messageId = 0xdeadbeef8badf00d; header.toBigEndian(); char buf[sizeof(header) + 64]; memcpy(buf, &header, sizeof(header)); header.fromBigEndian(); strncpy(buf + sizeof(header), payload, 64); for (uint32_t i = 0; i < sizeof(buf); ++i) { EXPECT_EQ(1, send(remote, &buf[i], 1, 0)); msgSocket->readable(); ASSERT_FALSE(handler.disconnected) << "Disconnected at byte " << i; msgSocket->readable(); // spurious ASSERT_FALSE(handler.disconnected) << "Disconnected at byte " << i; } EXPECT_EQ(header.messageId, handler.lastReceivedId); EXPECT_EQ(payload, std::string(static_cast<const char*>( handler.lastReceivedPayload.getData()), handler.lastReceivedPayload.getLength())); EXPECT_EQ(1, send(remote, "x", 1, 0)); msgSocket->readable(); EXPECT_FALSE(handler.disconnected); EXPECT_EQ(1U, msgSocket->inbound.bytesRead); } TEST_F(RPCMessageSocketTest, writableSpurious) { msgSocket->writable(); } TEST_F(RPCMessageSocketTest, writableDisconnect) { closeRemote(); msgSocket->sendMessage(123, Buffer(const_cast<char*>(payload), 64, NULL)); ASSERT_EQ(1U, msgSocket->outboundQueue.size()); ASSERT_FALSE(handler.disconnected); msgSocket->writable(); ASSERT_TRUE(handler.disconnected); } TEST_F(RPCMessageSocketTest, writableNormal) { MessageSocket::Header header; header.fixed = 0xdaf4; header.version = 1; header.payloadLength = 64; header.messageId = 123; header.toBigEndian(); char expected[sizeof(header) + 64]; memcpy(expected, &header, sizeof(header)); strncpy(expected + sizeof(header), payload, 64); for (uint32_t i = 0; i < sizeof(MessageSocket::Header) + 64; ++i) { msgSocket->sendMessage(123, Buffer(const_cast<char*>(payload), 64, NULL)); ASSERT_EQ(1U, msgSocket->outboundQueue.size()); msgSocket->outboundQueue.front().bytesSent = i; msgSocket->writable(); ASSERT_FALSE(handler.disconnected); ASSERT_EQ(0U, msgSocket->outboundQueue.size()); char buf[sizeof(MessageSocket::Header) + 64 + 1]; ASSERT_EQ(ssize_t(sizeof(buf)) - i - 1, recv(remote, buf + i, sizeof(buf) - i, 0)); ASSERT_EQ(0, memcmp(expected + i, buf + i, sizeof(buf) - i - 1)) << "suffix of packet does not match from byte " << i; } } } // namespace LogCabin::RPC::<anonymous> } // namespace LogCabin::RPC } // namespace LogCabin
32.879004
79
0.658188
Alex-II
431b16b67a576acaca228dcb5a2102f14899df6a
22,095
cpp
C++
tests/src/test_TensorMeshHierarchy.cpp
kmorel/MGARD
a7c44d57fda76a5c3e6fa38702ca8c8c12150b83
[ "Apache-2.0" ]
19
2019-03-08T15:21:36.000Z
2022-02-11T04:02:50.000Z
tests/src/test_TensorMeshHierarchy.cpp
kmorel/MGARD
a7c44d57fda76a5c3e6fa38702ca8c8c12150b83
[ "Apache-2.0" ]
100
2019-01-14T15:34:09.000Z
2022-03-29T13:39:30.000Z
tests/src/test_TensorMeshHierarchy.cpp
kmorel/MGARD
a7c44d57fda76a5c3e6fa38702ca8c8c12150b83
[ "Apache-2.0" ]
22
2018-11-16T01:13:57.000Z
2022-03-14T23:53:28.000Z
#include "catch2/catch_approx.hpp" #include "catch2/catch_test_macros.hpp" #include <algorithm> #include <array> #include <numeric> #include <stdexcept> #include <vector> #include "testing_utilities.hpp" #include "TensorMeshHierarchy.hpp" #include "TensorMeshHierarchyIteration.hpp" #include "shuffle.hpp" #include "utilities.hpp" TEST_CASE("hierarchy mesh shapes", "[TensorMeshHierarchy]") { { const std::array<std::size_t, 1> shape = {5}; const mgard::TensorMeshHierarchy<1, float> hierarchy(shape); REQUIRE(hierarchy.L == 2); REQUIRE(hierarchy.shapes.back() == shape); } { const mgard::TensorMeshHierarchy<2, float> hierarchy({11, 32}); REQUIRE(hierarchy.L == 4); const std::array<std::size_t, 2> expected = {9, 17}; REQUIRE(hierarchy.shapes.at(3) == expected); } { const std::array<std::size_t, 5> shape = {1, 257, 129, 129, 1}; const mgard::TensorMeshHierarchy<5, float> hierarchy(shape); REQUIRE(hierarchy.L == 7); REQUIRE(hierarchy.shapes.back() == shape); } { const mgard::TensorMeshHierarchy<2, float> hierarchy({6, 5}); REQUIRE(hierarchy.L == 3); const std::array<std::size_t, 2> expected = {5, 5}; REQUIRE(hierarchy.shapes.at(2) == expected); } REQUIRE_THROWS(mgard::TensorMeshHierarchy<3, float>({1, 1, 1})); REQUIRE_THROWS(mgard::TensorMeshHierarchy<2, float>({17, 0})); } TEST_CASE("TensorMeshHierarchy construction", "[TensorMeshHierarchy]") { { const mgard::TensorMeshHierarchy<1, float> hierarchy({17}); REQUIRE(hierarchy.uniform); REQUIRE(hierarchy.L == 4); std::vector<std::size_t> ndofs(hierarchy.L + 1); for (std::size_t l = 0; l <= hierarchy.L; ++l) { ndofs.at(l) = hierarchy.ndof(l); } REQUIRE(ndofs.back() == hierarchy.ndof()); const std::vector<std::size_t> expected = {2, 3, 5, 9, 17}; REQUIRE(ndofs == expected); } { const mgard::TensorMeshHierarchy<2, double> hierarchy({12, 39}); REQUIRE(hierarchy.uniform); REQUIRE(hierarchy.L == 4); std::vector<std::size_t> ndofs(hierarchy.L + 1); for (std::size_t l = 0; l <= hierarchy.L; ++l) { ndofs.at(l) = hierarchy.ndof(l); } { const std::vector<std::array<std::size_t, 2>> expected = { {2, 5}, {3, 9}, {5, 17}, {9, 33}, {12, 39}}; REQUIRE(hierarchy.shapes == expected); } { const std::vector<std::size_t> expected = {10, 27, 85, 297, 468}; REQUIRE(ndofs == expected); } const std::array<std::size_t, 2> &SHAPE = hierarchy.shapes.back(); TrialTracker tracker; for (std::size_t i = 0; i < 2; ++i) { const std::vector<double> &xs = hierarchy.coordinates.at(i); const std::size_t n = SHAPE.at(i); for (std::size_t j = 0; j < n; ++j) { tracker += xs.at(j) == Catch::Approx(static_cast<double>(j) / (n - 1)); } } REQUIRE(tracker); } { const mgard::TensorMeshHierarchy<3, double> hierarchy({15, 6, 129}); REQUIRE(hierarchy.uniform); REQUIRE(hierarchy.L == 3); // Note that the final dimension doesn't begin decreasing until every index // is of the form `2^k + 1`. const std::vector<std::array<std::size_t, 3>> expected = { {3, 2, 33}, {5, 3, 65}, {9, 5, 129}, {15, 6, 129}}; REQUIRE(hierarchy.shapes == expected); } { const mgard::TensorMeshHierarchy<3, float> hierarchy( {5, 3, 2}, {{{0.0, 0.5, 0.75, 1.0, 1.25}, {-3, -2, -1}, {10.5, 9.5}}}); REQUIRE(not hierarchy.uniform); REQUIRE_NOTHROW(hierarchy); } { bool thrown = false; try { const mgard::TensorMeshHierarchy<2, double> hierarchy( {10, 5}, {{{1, 2, 3}, {1, 2, 3, 4, 5}}}); } catch (const std::invalid_argument &exception) { thrown = true; } REQUIRE(thrown); } } namespace { //! Count the nodes in a given mesh level preceding a given node. //! //! If the node is contained in the mesh level, the count is equal to the //! position of the node in the 'physical' ordering of the nodes (`{0, 0, 0}`, //! `{0, 0, 1}`, and so on). //! //!\param hierarchy Mesh hierarchy. //!\param l Index of the mesh level whose nodes are to be counted. //!\param multiindex Multiindex of the node. template <std::size_t N, typename Real> std::size_t number_nodes_before(const mgard::TensorMeshHierarchy<N, Real> &hierarchy, const std::size_t l, const std::array<std::size_t, N> multiindex) { const std::array<std::size_t, N> &SHAPE = hierarchy.shapes.back(); const std::array<std::size_t, N> &shape = hierarchy.shapes.at(l); // Let `α` be the given node (its multiindex). A node (multiindex) `β` comes // before `α` if // * `β_{1} < α_{1}` xor // * `β_{1} = α_{1}` and `β_{2} < α_{2}` xor // * … // * `β_{1} = α_{1}`, …, `β_{N - 1} = α_{N - 1}` and `β_{N} < α_{N}`. // Consider one of these options: `β_{1} = α_{1}`, …, `β_{i - 1} = α_{i - 1}` // and `β_{i} < α_{i}`. Let `M_{k}` and `m_{k}` be the sizes of the finest and // `l`th meshes, respectively, in dimension `k`. `β` is unconstrained in // dimensions `i + 1` through `N`, so we start with a factor of `m_{i + 1} × ⋯ // × m_{N}`. The values of `β_{1}`, …, `β_{i - 1}` are prescribed. `β_{i}` is // of the form `floor((j * (M_{i} - 1)) / (m_{i} - 1))`. We want `β_{i} < // α_{i}`, so `j` will go from zero up to some maximal value, after which // `β_{i} ≥ α_{i}`. The count of possible `j` values is the least `j` such // that `β_{i} ≥ α_{i}`. A bit of algebra shows that this is // `ceil((α_{i} * (m_{i} - 1)) / (M_{i} - 1))`. So, the count of possible // `β`s for this option is (assuming the constraints on `β_{1}`, …, // `β_{i - 1}` can be met – see below) // ``` // m_{i + 1} × ⋯ × m_{N} × ceil((α_{i} * (m_{i} - 1)) / (M_{i} - 1)). // ``` // We compute the sum of these counts in the loop below, rearranging so that // we only have to multiply by each `m_{k}` once. // // One detail I missed: if `α` was introduced *after* the `l`th mesh, then it // may not be possible for `β_{k}` to equal `α_{k}`, since `β` must be present // in the `l`th mesh. Any option involving one of these 'impossible // constraints' will be knocked out and contribute nothing to the sum. // // That above assumes that `M_{i} ≠ 1`. In that case, it is impossible for // `β_{i}` to be less than `α_{i}` (both must be zero), so instead of // `ceil((α_{i} * (m_{i} - 1)) / (M_{i} - 1))` we get a factor of zero. std::size_t count = 0; bool impossible_constraint_encountered = false; for (std::size_t i = 0; i < N; ++i) { const std::size_t m = shape.at(i); const std::size_t M = SHAPE.at(i); // Notice that this has no effect in the first iteration. count *= m; if (impossible_constraint_encountered) { continue; } const std::size_t index = multiindex.at(i); const std::size_t numerator = index * (m - 1); const std::size_t denominator = M - 1; // We want to add `ceil(numerator / denominator)`. We can compute this term // using only integer divisions by adding one less than the denominator to // the numerator. // If the mesh is flat in this dimension (if `M == 1`), then `β_{i}` cannot // be less than `α_{i}` and so this case contributes nothing to the count. count += denominator ? (numerator + (denominator - 1)) / denominator : 0; // The 'impossible constraint' will be encountered in the next iteration, // when we stipulate that `β_{i} = α_{i}` (current value of `i`). impossible_constraint_encountered = impossible_constraint_encountered || hierarchy.dates_of_birth.at(i).at(index) > l; } return count; } //! Compute the index of a node in the 'shuffled' ordering. //! //!\param hierarchy Mesh hierarchy. //!\param multiindex Multiindex of the node. template <std::size_t N, typename Real> std::size_t index(const mgard::TensorMeshHierarchy<N, Real> &hierarchy, const std::array<std::size_t, N> multiindex) { const std::size_t l = hierarchy.date_of_birth(multiindex); if (!l) { return number_nodes_before(hierarchy, l, multiindex); } return hierarchy.ndof(l - 1) + number_nodes_before(hierarchy, l, multiindex) - number_nodes_before(hierarchy, l - 1, multiindex); } template <std::size_t N, typename Real> void test_entry_indexing_manual( const std::array<std::size_t, N> shape, const std::vector<std::array<std::size_t, N>> &multiindices, const std::vector<Real> &expected) { const std::size_t ntrials = multiindices.size(); if (expected.size() != ntrials) { throw std::invalid_argument("number of trials inconsistently specified"); } const mgard::TensorMeshHierarchy<N, Real> hierarchy(shape); const std::size_t ndof = hierarchy.ndof(); std::vector<Real> v_unshuffled_(ndof); std::vector<Real> v_shuffled_(ndof); std::iota(v_unshuffled_.begin(), v_unshuffled_.end(), 0); Real *const v = v_shuffled_.data(); mgard::shuffle(hierarchy, v_unshuffled_.data(), v); TrialTracker tracker; for (std::size_t i = 0; i < ntrials; ++i) { const std::array<std::size_t, N> &multiindex = multiindices.at(i); const Real expected_ = expected.at(i); tracker += hierarchy.at(v, multiindex) == expected_; // Compare with original `TensorMeshHierarchy::index` implementation. tracker += v[index(hierarchy, multiindex)] == expected_; } REQUIRE(tracker); } template <std::size_t N> void test_entry_indexing_exhaustive(const std::array<std::size_t, N> shape) { const mgard::TensorMeshHierarchy<N, float> hierarchy(shape); const std::size_t ndof = hierarchy.ndof(); float *const buffer = static_cast<float *>(std::malloc(ndof * sizeof(float))); std::iota(buffer, buffer + ndof, 0); float *const u = static_cast<float *>(std::malloc(ndof * sizeof(float))); mgard::shuffle(hierarchy, buffer, u); std::free(buffer); int expected = 0; TrialTracker tracker; for (const mgard::TensorNode<N> node : mgard::UnshuffledTensorNodeRange(hierarchy, hierarchy.L)) { const std::array<std::size_t, N> &multiindex = node.multiindex; const float expected_ = static_cast<float>(expected); tracker += hierarchy.at(u, multiindex) == expected_; // Compare with original `TensorMeshHierarchy::index` implementation. tracker += u[index(hierarchy, multiindex)] == expected_; ++expected; } REQUIRE(tracker); std::free(u); } } // namespace TEST_CASE("TensorMeshHierarchy indexing", "[TensorMeshHierarchy]") { SECTION("accessing elements") { { const std::vector<std::array<std::size_t, 1>> multiindices = { {0}, {2}, {5}}; const std::vector<float> expected = {0, 2, 5}; test_entry_indexing_manual({6}, multiindices, expected); } { const std::vector<std::array<std::size_t, 2>> multiindices = { {0, 3}, {10, 1}, {12, 3}}; const std::vector<double> expected = {3, 41, 51}; test_entry_indexing_manual({13, 4}, multiindices, expected); } { const std::vector<std::array<std::size_t, 4>> multiindices = { {1, 2, 1, 90}, {2, 0, 1, 15}, {2, 2, 1, 27}}; const std::vector<float> expected = {1190, 1315, 1727}; test_entry_indexing_manual({3, 3, 2, 100}, multiindices, expected); } { test_entry_indexing_exhaustive<1>({95}); test_entry_indexing_exhaustive<2>({20, 6}); test_entry_indexing_exhaustive<3>({7, 11, 12}); } } SECTION("accessing indices directly") { { const mgard::TensorMeshHierarchy<3, float> hierarchy({5, 3, 17}); REQUIRE(hierarchy.L == 1); // Every index is included in the finest level. for (std::size_t i = 0; i < 3; ++i) { const mgard::TensorIndexRange indices = hierarchy.indices(1, i); TrialTracker tracker; std::size_t expected = 0; for (const std::size_t index : indices) { tracker += index == expected++; } REQUIRE(tracker); } // On the coarse level, we get every other index. { const std::array<std::vector<std::size_t>, 3> expected = { {{0, 2, 4}, {0, 2}, {0, 2, 4, 6, 8, 10, 12, 14, 16}}}; std::array<std::vector<std::size_t>, 3> obtained; for (std::size_t i = 0; i < 3; ++i) { const mgard::TensorIndexRange indices = hierarchy.indices(0, i); obtained.at(i).assign(indices.begin(), indices.end()); } REQUIRE(obtained == expected); } } { const mgard::TensorMeshHierarchy<2, double> hierarchy({5, 6}); const std::array<std::vector<std::size_t>, 4> expected = { {{0, 5}, {0, 2, 5}, {0, 1, 2, 3, 5}, {0, 1, 2, 3, 4, 5}}}; std::array<std::vector<std::size_t>, 4> obtained; for (std::size_t l = 0; l < 4; ++l) { const mgard::TensorIndexRange indices = hierarchy.indices(l, 1); obtained.at(l).assign(indices.begin(), indices.end()); } REQUIRE(obtained == expected); } { const mgard::TensorMeshHierarchy<1, double> hierarchy({60}); const std::array<std::vector<std::size_t>, 4> expected = { {{0, 59}, {0, 29, 59}, {0, 14, 29, 44, 59}, {0, 7, 14, 22, 29, 36, 44, 51, 59}}}; std::array<std::vector<std::size_t>, 4> obtained; for (std::size_t l = 0; l < 4; ++l) { const mgard::TensorIndexRange indices = hierarchy.indices(l, 0); obtained.at(l).assign(indices.begin(), indices.end()); } REQUIRE(obtained == expected); } } SECTION("'flat' meshes") { test_entry_indexing_exhaustive<2>({1, 35}); test_entry_indexing_exhaustive<2>({7, 1}); test_entry_indexing_exhaustive<3>({12, 1, 13}); test_entry_indexing_exhaustive<3>({9, 1, 1}); test_entry_indexing_exhaustive<4>({1, 8, 22, 1}); } } namespace { template <std::size_t N> void test_index_iteration( const std::array<std::size_t, N> shape, const std::vector<std::array<std::vector<std::size_t>, N>> &expected) { const mgard::TensorMeshHierarchy<N, float> hierarchy(shape); std::vector<std::array<std::vector<std::size_t>, N>> encountered(hierarchy.L + 1); for (std::size_t l = 0; l <= hierarchy.L; ++l) { std::array<std::vector<std::size_t>, N> &enc = encountered.at(l); for (std::size_t i = 0; i < N; ++i) { const mgard::TensorIndexRange indices = hierarchy.indices(l, i); enc.at(i).assign(indices.begin(), indices.end()); } } REQUIRE(encountered == expected); } } // namespace TEST_CASE("index iteration", "[TensorMeshHierarchy]") { { const std::array<std::size_t, 2> shape = {9, 5}; const std::vector<std::array<std::vector<std::size_t>, 2>> expected = { {{{{0, 4, 8}, {0, 4}}}, {{{0, 2, 4, 6, 8}, {0, 2, 4}}}, {{{0, 1, 2, 3, 4, 5, 6, 7, 8}, {0, 1, 2, 3, 4}}}}}; test_index_iteration(shape, expected); } { const std::array<std::size_t, 1> shape = {8}; const std::vector<std::array<std::vector<std::size_t>, 1>> expected = { {{{{0, 7}}}, {{{0, 3, 7}}}, {{{0, 1, 3, 5, 7}}}, {{{0, 1, 2, 3, 4, 5, 6, 7}}}}}; test_index_iteration(shape, expected); } { const std::size_t singleton = 0; const mgard::TensorIndexRange indices = {.begin_ = &singleton, .end_ = &singleton + 1}; const std::vector<std::size_t> obtained(indices.begin(), indices.end()); const std::vector<std::size_t> expected = {0}; REQUIRE(obtained == expected); } } TEST_CASE("node iteration", "[TensorMeshHierarchy]") { // The largest of the mesh sizes used below. const std::size_t N = 11 * 14; float *const buffer = static_cast<float *>(std::malloc(N * sizeof(float))); std::iota(buffer, buffer + N, 1); { const mgard::TensorMeshHierarchy<1, float> hierarchy({17}); const std::size_t ndof = hierarchy.ndof(); float *const v = static_cast<float *>(std::malloc(ndof * sizeof(float))); mgard::shuffle(hierarchy, buffer, v); std::vector<float> encountered_values; std::vector<std::size_t> encountered_ls; for (const mgard::TensorNode<1> node : mgard::UnshuffledTensorNodeRange(hierarchy, 2)) { encountered_values.push_back(hierarchy.at(v, node.multiindex)); encountered_ls.push_back(hierarchy.date_of_birth(node.multiindex)); } const std::vector<float> expected_values = {1, 5, 9, 13, 17}; const std::vector<std::size_t> expected_ls = {0, 2, 1, 2, 0}; REQUIRE(encountered_values == expected_values); REQUIRE(encountered_ls == expected_ls); std::free(v); } { const mgard::TensorMeshHierarchy<2, float> hierarchy({3, 5}); const std::size_t ndof = hierarchy.ndof(); float *const v = static_cast<float *>(std::malloc(ndof * sizeof(float))); mgard::shuffle(hierarchy, buffer, v); std::vector<float> encountered; // For the indices. TrialTracker tracker; for (const mgard::TensorNode<2> node : mgard::UnshuffledTensorNodeRange(hierarchy, 0)) { encountered.push_back(hierarchy.at(v, node.multiindex)); tracker += hierarchy.date_of_birth(node.multiindex) == 0; } const std::vector<float> expected = {1, 3, 5, 11, 13, 15}; REQUIRE(encountered == expected); REQUIRE(tracker); std::free(v); } { const mgard::TensorMeshHierarchy<2, float> hierarchy({9, 3}); const std::size_t ndof = hierarchy.ndof(); float *const v = static_cast<float *>(std::malloc(ndof * sizeof(float))); mgard::shuffle(hierarchy, buffer, v); std::vector<float> encountered; // For the indices. TrialTracker tracker; for (const mgard::TensorNode<2> node : mgard::UnshuffledTensorNodeRange(hierarchy, 0)) { encountered.push_back(hierarchy.at(v, node.multiindex)); tracker += hierarchy.date_of_birth(node.multiindex) == 0; } const std::vector<float> expected = {1, 3, 7, 9, 13, 15, 19, 21, 25, 27}; REQUIRE(encountered == expected); REQUIRE(tracker); std::free(v); } { const mgard::TensorMeshHierarchy<3, float> hierarchy({3, 3, 3}); const std::size_t ndof = hierarchy.ndof(); float *const v = static_cast<float *>(std::malloc(ndof * sizeof(float))); mgard::shuffle(hierarchy, buffer, v); float expected_value = 1; TrialTracker tracker; // For the indices. std::vector<std::size_t> encountered_ls; for (const mgard::TensorNode<3> node : mgard::UnshuffledTensorNodeRange(hierarchy, hierarchy.L)) { tracker += hierarchy.at(v, node.multiindex) == expected_value; expected_value += 1; encountered_ls.push_back(hierarchy.date_of_birth(node.multiindex)); } std::vector<std::size_t> expected_ls(27, 1); for (const std::size_t index : {0, 2, 6, 8, 18, 20, 24, 26}) { expected_ls.at(index) = 0; } REQUIRE(tracker); REQUIRE(encountered_ls == expected_ls); std::free(v); } { const mgard::TensorMeshHierarchy<2, float> hierarchy({11, 14}); const std::size_t ndof = hierarchy.ndof(); float *const v = static_cast<float *>(std::malloc(ndof * sizeof(float))); mgard::shuffle(hierarchy, buffer, v); std::vector<std::array<std::size_t, 2>> encountered_multiindices; std::vector<std::size_t> encountered_ls; for (const mgard::TensorNode<2> node : mgard::UnshuffledTensorNodeRange(hierarchy, 2)) { encountered_multiindices.push_back(node.multiindex); encountered_ls.push_back(hierarchy.date_of_birth(node.multiindex)); } const std::vector<std::array<std::size_t, 2>> expected_multiindices = { {{0, 0}}, {{0, 3}}, {{0, 6}}, {{0, 9}}, {{0, 13}}, {{2, 0}}, {{2, 3}}, {{2, 6}}, {{2, 9}}, {{2, 13}}, {{5, 0}}, {{5, 3}}, {{5, 6}}, {{5, 9}}, {{5, 13}}, {{7, 0}}, {{7, 3}}, {{7, 6}}, {{7, 9}}, {{7, 13}}, {{10, 0}}, {{10, 3}}, {{10, 6}}, {{10, 9}}, {{10, 13}}}; const std::vector<std::size_t> expected_ls = {0, 2, 1, 2, 0, 2, 2, 2, 2, 2, 1, 2, 1, 2, 1, 2, 2, 2, 2, 2, 0, 2, 1, 2, 0}; REQUIRE(encountered_multiindices == expected_multiindices); REQUIRE(encountered_ls == expected_ls); std::free(v); } std::free(buffer); } TEST_CASE("dates of birth", "[TensorMeshHierarchy]") { { const mgard::TensorMeshHierarchy<1, float> hierarchy({9}); std::vector<std::size_t> encountered; for (std::size_t i = 0; i < 9; ++i) { encountered.push_back(hierarchy.date_of_birth({i})); } const std::vector<std::size_t> expected = {0, 3, 2, 3, 1, 3, 2, 3, 0}; REQUIRE(encountered == expected); } { const mgard::TensorMeshHierarchy<2, double> hierarchy({6, 3}); const mgard::UnshuffledTensorNodeRange<2, double> nodes(hierarchy, hierarchy.L); // Cheating a little here in predetermining the size. std::vector<std::size_t> encountered(hierarchy.ndof()); std::transform(nodes.begin(), nodes.end(), encountered.begin(), [&](const mgard::TensorNode<2> &node) -> std::size_t { return hierarchy.date_of_birth(node.multiindex); }); const std::vector<std::size_t> expected = {0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 2, 2, 2, 0, 1, 0}; REQUIRE(encountered == expected); } { const mgard::TensorMeshHierarchy<3, float> hierarchy({5, 17, 12}); TrialTracker tracker; { tracker += hierarchy.date_of_birth({0, 4, 5}) == 0; tracker += hierarchy.date_of_birth({4, 8, 11}) == 0; tracker += hierarchy.date_of_birth({2, 14, 2}) == 1; tracker += hierarchy.date_of_birth({2, 16, 8}) == 1; tracker += hierarchy.date_of_birth({3, 9, 1}) == 2; tracker += hierarchy.date_of_birth({4, 8, 9}) == 2; tracker += hierarchy.date_of_birth({3, 8, 10}) == 3; tracker += hierarchy.date_of_birth({1, 0, 7}) == 3; } REQUIRE(tracker); } }
38.831283
80
0.602172
kmorel
431cf12b7d6069cc43318a927baacb44023df546
1,306
hpp
C++
maylee/include/maylee/syntax/syntax_node_visitor.hpp
eidolonsystems/maylee
a0a2e94bdc8543f88e428bee53b83db7a4bca0c0
[ "MIT" ]
null
null
null
maylee/include/maylee/syntax/syntax_node_visitor.hpp
eidolonsystems/maylee
a0a2e94bdc8543f88e428bee53b83db7a4bca0c0
[ "MIT" ]
null
null
null
maylee/include/maylee/syntax/syntax_node_visitor.hpp
eidolonsystems/maylee
a0a2e94bdc8543f88e428bee53b83db7a4bca0c0
[ "MIT" ]
null
null
null
#ifndef MAYLEE_SYNTAX_NODE_VISITOR_HPP #define MAYLEE_SYNTAX_NODE_VISITOR_HPP #include "maylee/syntax/syntax.hpp" namespace maylee { //! Implements the visitor pattern for syntax nodes. class syntax_node_visitor { public: virtual ~syntax_node_visitor() = default; virtual void visit(const assignment_statement& node); virtual void visit(const block_statement& node); virtual void visit(const call_expression& node); virtual void visit(const expression& node); virtual void visit(const function_definition& node); virtual void visit(const if_statement& node); virtual void visit(const let_expression& node); virtual void visit(const literal_expression& node); virtual void visit(const return_statement& node); virtual void visit(const statement& node); virtual void visit(const syntax_node& node); virtual void visit(const terminal_node& node); virtual void visit(const type_name_expression& node); virtual void visit(const variable_expression& node); virtual void visit(const void_expression& node); protected: //! Constructs a syntax node visitor. syntax_node_visitor() = default; }; inline void syntax_node_visitor::visit(const syntax_node& node) {} } #endif
25.115385
68
0.721286
eidolonsystems
432439997a9965725b6a62eee1ad1a27a304a70c
1,593
cpp
C++
Game Theory/Alice and Bob's Silly Game.cpp
StavrosChryselis/hackerrank
42a3e393231e237a99a9e54522ce3ec954bf614f
[ "MIT" ]
null
null
null
Game Theory/Alice and Bob's Silly Game.cpp
StavrosChryselis/hackerrank
42a3e393231e237a99a9e54522ce3ec954bf614f
[ "MIT" ]
null
null
null
Game Theory/Alice and Bob's Silly Game.cpp
StavrosChryselis/hackerrank
42a3e393231e237a99a9e54522ce3ec954bf614f
[ "MIT" ]
null
null
null
/* **************************************************************** **************************************************************** -> Coded by Stavros Chryselis -> Visit my github for more solved problems over multiple sites -> https://github.com/StavrosChryselis -> Feel free to email me at stavrikios@gmail.com **************************************************************** **************************************************************** */ #include <iostream> #include <cstring> #include <vector> #include <algorithm> #define SIEVE_N 100007 using namespace std; bool is_prime[SIEVE_N]; vector< int > primes; vector< pair<int, int> > A; inline void sieve() { int i, j; memset(is_prime, 1, sizeof(is_prime)); primes.push_back(2); is_prime[0] = is_prime[1] = 0; for (i = 4; i < SIEVE_N; i += 2) is_prime[i] = 0; for (i = 3; i < SIEVE_N; i += 2) if (is_prime[i]) { primes.push_back(i); for (j = i + i; j < SIEVE_N; j += i) is_prime[j] = 0; } // for (i = 0; i < primes.size(); i++) A.push_back(make_pair(primes[i], i + 1)); } inline void solve() { vector< pair<int, int> >::iterator ii; int i; int num; cin >> num; if(num == 1) { cout << "Bob\n"; return; } ii = upper_bound(A.begin(), A.end(), make_pair(num, (int)A.size() + 1)); if (ii == A.end()) { cout << "Bob\n"; return; } ii = prev(ii); if (ii->second % 2) cout << "Alice\n"; else cout << "Bob\n"; } int main() { // freopen("input.txt", "r", stdin); ios::sync_with_stdio(0); int T; cin >> T; sieve(); while (T--) solve(); return 0; }
16.42268
73
0.483365
StavrosChryselis
432530239e6c600c525c1d8005b487cbcafeec85
490
cpp
C++
src/LowLevel/ResponseMessages/ReadyMessage.cpp
cpv-project/cpv-cql-driver
66eebfd4e9ec75dc49cd4a7073a51a830236807a
[ "MIT" ]
41
2018-01-23T09:27:32.000Z
2021-02-15T15:49:07.000Z
src/LowLevel/ResponseMessages/ReadyMessage.cpp
cpv-project/cpv-cql-driver
66eebfd4e9ec75dc49cd4a7073a51a830236807a
[ "MIT" ]
20
2018-01-25T04:25:48.000Z
2019-03-09T02:49:41.000Z
src/LowLevel/ResponseMessages/ReadyMessage.cpp
cpv-project/cpv-cql-driver
66eebfd4e9ec75dc49cd4a7073a51a830236807a
[ "MIT" ]
5
2018-04-10T12:19:13.000Z
2020-02-17T03:30:50.000Z
#include "./ReadyMessage.hpp" namespace cql { /** The storage of ReadyMessage */ template <> thread_local ReusableStorageType<ReadyMessage> ReusableStorageInstance<ReadyMessage>; /** Get description of this message */ std::string ReadyMessage::toString() const { return "ReadyMessage()"; } /** Decode message body from binary data */ void ReadyMessage::decodeBody( const ConnectionInfo&, seastar::temporary_buffer<char>&&) { // The body of a READY message is empty } }
23.333333
61
0.72449
cpv-project
4326e1bf7b89c1b0c74cfef817e272a04df248a4
4,769
hpp
C++
container.hpp
MattAszyk/containers
eb0ae05d49075c01bba3e0003422f0bddd5da031
[ "MIT" ]
null
null
null
container.hpp
MattAszyk/containers
eb0ae05d49075c01bba3e0003422f0bddd5da031
[ "MIT" ]
null
null
null
container.hpp
MattAszyk/containers
eb0ae05d49075c01bba3e0003422f0bddd5da031
[ "MIT" ]
null
null
null
#ifndef CONTAINER_HPP #define CONTAINER_HPP #include<exception> namespace matt{ template<class T> class container { protected: struct item { item(const T& _value, item* _prev, item* _next) : value(_value), prev(_prev), next(_next){} T value; item* prev = nullptr; item* next = nullptr; }; item* head = nullptr; item* tail = nullptr; size_t amount = 0; container(); container(const container<T>&); ~container(); //ELEMENT ACCESS T& front(); T& back(); //ITERATORS class iterator; iterator begin() { return iterator(head);} iterator end() { return iterator(nullptr); }; class iterator { private: const item* current; public: iterator() noexcept: current(head){} iterator(const item* _item) noexcept: current(_item){} iterator& operator=(item* _item) { this->current = _item; return *this; } iterator& operator++() { if(current == nullptr) throw "Out of range."; current = current->next; return *this; } iterator& operator++(int) { iterator iter = *this; ++*this; return iter; } const T& operator*() { if(current ==nullptr) throw "Element doesnt exist"; return current->value; } bool operator!=(const iterator& it) { return it.current != current; } }; //CAPACITY bool empty(); size_t size(); //MODIFIERS void clear(); void insert(int ind, T& value); void push_back(const T&); void pop_back(); void push_front(const T&); void pop_front(); }; } template<class T> matt::container<T>::container(/* args */) { } template<class T> matt::container<T>::container(const container<T>& item) { for(auto it = item.begin(); it != item.end(); it++) push_back(*it); } template<class T> matt::container<T>::~container() { clear(); } template<class T> size_t matt::container<T>::size() { return amount; } template<class T> bool matt::container<T>::empty() { return amount == 0; } template<class T> T& matt::container<T>::front() { if(amount == 0) { throw "Container is empty"; } return head->value; } template<class T> T& matt::container<T>::back() { if(amount == 0) { throw "Container is empty"; } return tail->value; } template<class T> void matt::container<T>::clear() { switch (amount) { case 0: break; case 1: delete head; head = nullptr; tail = nullptr; amount--; return; break; default: tail->prev->next = nullptr; item *temp = tail->prev; delete tail; tail = temp; amount--; clear(); break; } } template<class T> void matt::container<T>::push_back(const T& val) { if(amount == 0) { head = new item(val,nullptr,nullptr); tail = head; } else { item* temp = new item(val,tail,nullptr); tail->next = temp; tail = temp; } amount++; } template<class T> void matt::container<T>::push_front(const T& val) { if(amount == 0) { head = new item(val,nullptr,nullptr); tail = head; } else { item* temp = new item(val,nullptr,head); head->prev = temp; head = temp; } amount++; } template<class T> void matt::container<T>::pop_back() { switch (amount) { case 0: throw "Container is empty!"; break; case 1: delete head; head = nullptr; tail = nullptr; amount--; break; default: tail->prev->next = nullptr; item *temp = tail->prev; delete tail; tail = temp; amount--; break; } } template<class T> void matt::container<T>::pop_front() { switch (amount) { case 0: throw "Container is empty!"; break; case 1: delete head; head = nullptr; tail = nullptr; amount--; break; default: head->next->prev = nullptr; item *temp = head->next; delete head; head = temp; amount--; break; } } #endif
18.849802
103
0.479765
MattAszyk
432cb18e08afefbf72aab2f03e465390db60ce4e
5,166
cpp
C++
src/Passes/PettisAndHansen.cpp
davidmalcolm/BOLT
c5c46ca08fd846fb22e032a965fbccf2b0415861
[ "NCSA" ]
13
2019-12-22T11:52:13.000Z
2021-11-09T12:02:23.000Z
src/Passes/PettisAndHansen.cpp
angelica-moreira/BOLT
414249f74d0c422bd4286e6408ad32dd5b54bbbb
[ "NCSA" ]
null
null
null
src/Passes/PettisAndHansen.cpp
angelica-moreira/BOLT
414249f74d0c422bd4286e6408ad32dd5b54bbbb
[ "NCSA" ]
7
2020-01-01T17:21:36.000Z
2021-02-11T06:43:38.000Z
#include "HFSort.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Format.h" #include "llvm/Support/raw_ostream.h" #include <set> #include <unordered_map> #undef DEBUG_TYPE #define DEBUG_TYPE "hfsort" namespace llvm { namespace bolt { using NodeId = CallGraph::NodeId; using Arc = CallGraph::Arc; using Node = CallGraph::Node; namespace { class ClusterArc { public: ClusterArc(Cluster *Ca, Cluster *Cb, double W = 0) : C1(std::min(Ca, Cb)) , C2(std::max(Ca, Cb)) , Weight(W) {} friend bool operator==(const ClusterArc &Lhs, const ClusterArc &Rhs) { return Lhs.C1 == Rhs.C1 && Lhs.C2 == Rhs.C2; } Cluster *const C1; Cluster *const C2; mutable double Weight; }; class ClusterArcHash { public: int64_t operator()(const ClusterArc &Arc) const { std::hash<int64_t> Hasher; return hashCombine(Hasher(int64_t(Arc.C1)), int64_t(Arc.C2)); } }; using ClusterArcSet = std::unordered_set<ClusterArc, ClusterArcHash>; void orderFuncs(const CallGraph &Cg, Cluster *C1, Cluster *C2) { auto C1head = C1->targets().front(); auto C1tail = C1->targets().back(); auto C2head = C2->targets().front(); auto C2tail = C2->targets().back(); double C1headC2head = 0; double C1headC2tail = 0; double C1tailC2head = 0; double C1tailC2tail = 0; for (const auto &Arc : Cg.arcs()) { if ((Arc.src() == C1head && Arc.dst() == C2head) || (Arc.dst() == C1head && Arc.src() == C2head)) { C1headC2head += Arc.weight(); } else if ((Arc.src() == C1head && Arc.dst() == C2tail) || (Arc.dst() == C1head && Arc.src() == C2tail)) { C1headC2tail += Arc.weight(); } else if ((Arc.src() == C1tail && Arc.dst() == C2head) || (Arc.dst() == C1tail && Arc.src() == C2head)) { C1tailC2head += Arc.weight(); } else if ((Arc.src() == C1tail && Arc.dst() == C2tail) || (Arc.dst() == C1tail && Arc.src() == C2tail)) { C1tailC2tail += Arc.weight(); } } const double Max = std::max(std::max(C1headC2head, C1headC2tail), std::max(C1tailC2head, C1tailC2tail)); if (C1headC2head == Max) { // flip C1 C1->reverseTargets(); } else if (C1headC2tail == Max) { // flip C1 C2 C1->reverseTargets(); C2->reverseTargets(); } else if (C1tailC2tail == Max) { // flip C2 C2->reverseTargets(); } } } std::vector<Cluster> pettisAndHansen(const CallGraph &Cg) { // indexed by NodeId, keeps its current cluster std::vector<Cluster*> FuncCluster(Cg.numNodes(), nullptr); std::vector<Cluster> Clusters; std::vector<NodeId> Funcs; Clusters.reserve(Cg.numNodes()); for (NodeId F = 0; F < Cg.numNodes(); F++) { if (Cg.samples(F) == 0) continue; Clusters.emplace_back(F, Cg.getNode(F)); FuncCluster[F] = &Clusters.back(); Funcs.push_back(F); } ClusterArcSet Carcs; auto insertOrInc = [&](Cluster *C1, Cluster *C2, double Weight) { auto Res = Carcs.emplace(C1, C2, Weight); if (!Res.second) { Res.first->Weight += Weight; } }; // Create a std::vector of cluster arcs for (auto &Arc : Cg.arcs()) { if (Arc.weight() == 0) continue; auto const S = FuncCluster[Arc.src()]; auto const D = FuncCluster[Arc.dst()]; // ignore if s or d is nullptr if (S == nullptr || D == nullptr) continue; // ignore self-edges if (S == D) continue; insertOrInc(S, D, Arc.weight()); } // Find an arc with max weight and merge its nodes while (!Carcs.empty()) { auto Maxpos = std::max_element( Carcs.begin(), Carcs.end(), [&] (const ClusterArc &Carc1, const ClusterArc &Carc2) { return Carc1.Weight < Carc2.Weight; } ); auto Max = *Maxpos; Carcs.erase(Maxpos); auto const C1 = Max.C1; auto const C2 = Max.C2; if (C1->size() + C2->size() > MaxClusterSize) continue; if (C1->frozen() || C2->frozen()) continue; // order functions and merge cluster orderFuncs(Cg, C1, C2); DEBUG(dbgs() << format("merging %s -> %s: %.1f\n", C2->toString().c_str(), C1->toString().c_str(), Max.Weight);); // update carcs: merge C1arcs to C2arcs std::unordered_map<ClusterArc, Cluster *, ClusterArcHash> C2arcs; for (auto &Carc : Carcs) { if (Carc.C1 == C2) C2arcs.emplace(Carc, Carc.C2); if (Carc.C2 == C2) C2arcs.emplace(Carc, Carc.C1); } for (auto It : C2arcs) { auto const C = It.second; auto const C2arc = It.first; insertOrInc(C, C1, C2arc.Weight); Carcs.erase(C2arc); } // update FuncCluster for (auto F : C2->targets()) { FuncCluster[F] = C1; } C1->merge(*C2, Max.Weight); C2->clear(); } // Return the set of Clusters that are left, which are the ones that // didn't get merged. std::set<Cluster*> LiveClusters; std::vector<Cluster> OutClusters; for (auto Fid : Funcs) { LiveClusters.insert(FuncCluster[Fid]); } for (auto C : LiveClusters) { OutClusters.push_back(std::move(*C)); } std::sort(OutClusters.begin(), OutClusters.end(), compareClustersDensity); return OutClusters; } } }
24.836538
78
0.598335
davidmalcolm
4333899958398ae6e3aa74f35c66b15c5630d8a3
5,870
cpp
C++
src/AboutWindow.cpp
TruckerMP/ETS2Sync-Helper-4
2a8b9df1d4db1e59635762147725fcec84eaf211
[ "Apache-2.0" ]
1
2018-12-08T07:31:13.000Z
2018-12-08T07:31:13.000Z
src/AboutWindow.cpp
TruckerMP/ETS2Sync-Helper-4
2a8b9df1d4db1e59635762147725fcec84eaf211
[ "Apache-2.0" ]
null
null
null
src/AboutWindow.cpp
TruckerMP/ETS2Sync-Helper-4
2a8b9df1d4db1e59635762147725fcec84eaf211
[ "Apache-2.0" ]
2
2019-05-10T14:13:53.000Z
2019-11-05T20:25:12.000Z
#include "precomp.hpp" #include "AboutWindow.hpp" #include "version.hpp" #include "MainWindow.hpp" #include <wx/hyperlink.h> #include <wx/statline.h> AboutWindow::AboutWindow(MainWindow * wndParent) : wxDialog(wndParent, wxID_ANY, "About " + APP_DISPLAY_NAME) { SetIcon(GetParent()->GetIcon()); Bind(wxEVT_SHOW, &AboutWindow::onShow, this); wxPoint border = wxDLG_UNIT(this, wxPoint(7, 7)); wxPoint internalBorder = wxDLG_UNIT(this, wxPoint(4, 4)); mUpdateChecker = new UpdateChecker(this); mUpdateChecker->Bind(EVT_UPDATE_CHECKER, [this](wxCommandEvent&) { onUpdateStatus(); }); wxBoxSizer * canvas = new wxBoxSizer(wxHORIZONTAL); wxBitmap logo("app_logo", wxBITMAP_TYPE_PNG_RESOURCE); canvas->Add(new wxStaticBitmap(this, wxID_ANY, logo), wxSizerFlags().Border(wxRIGHT, border.x)); wxBoxSizer * infoSizer = new wxBoxSizer(wxVERTICAL); wxStaticText * appName = new wxStaticText(this, wxID_ANY, APP_DISPLAY_NAME); appName->SetFont(appName->GetFont().Scale(3.0).MakeBold()); infoSizer->Add(appName); wxStaticText * appVersion = new wxStaticText(this, wxID_ANY, "Version " + APP_VERSION); appVersion->SetFont(appVersion->GetFont().Scale(1.7f).MakeBold()); infoSizer->Add(appVersion, wxSizerFlags()); infoSizer->AddSpacer(internalBorder.y); mUpdateCheckSizer = new wxBoxSizer(wxHORIZONTAL); mCheckingAnimation = new wxActivityIndicator(this, wxID_ANY, wxDefaultPosition, wxDLG_UNIT(this, wxSize(10, 10))); mUpdateCheckSizer->Add(mCheckingAnimation, wxSizerFlags().CenterVertical().Proportion(0).Border(wxRIGHT, 5)); mCheckStatusText = new StatusText(this, wxID_ANY); mUpdateCheckSizer->Add(mCheckStatusText, wxSizerFlags().CenterVertical(). Proportion(1)); mUpdateCheckSizer->AddSpacer(internalBorder.x); mUpdateCheckAgain = new wxButton(this, wxID_ANY, "Stop"); mUpdateCheckAgain->Bind(wxEVT_BUTTON, [this](wxCommandEvent&) {onUpdateCheckAgain(); }); mUpdateCheckSizer->Add(mUpdateCheckAgain, wxSizerFlags().CenterVertical().Proportion(0)); infoSizer->Add(mUpdateCheckSizer, wxSizerFlags().Expand()); infoSizer->AddSpacer(internalBorder.y); wxBoxSizer * websiteSizer = new wxBoxSizer(wxHORIZONTAL); websiteSizer->Add(new wxStaticText(this, wxID_ANY, "Website: ")); websiteSizer->Add(new wxHyperlinkCtrl(this, wxID_ANY, APP_URL_WEBSITE, APP_URL_WEBSITE)); infoSizer->Add(websiteSizer); infoSizer->AddSpacer(border.y); wxBoxSizer * creatorSizer = new wxBoxSizer(wxHORIZONTAL); creatorSizer->Add(new wxStaticText(this, wxID_ANY, "Developer: ")); creatorSizer->Add(new wxHyperlinkCtrl(this, wxID_ANY, "David Santos", "https://github.com/davidsantos-br/")); infoSizer->Add(creatorSizer); /*wxBoxSizer * jobListSizer = new wxBoxSizer(wxHORIZONTAL); jobListSizer->Add(new wxStaticText(this, wxID_ANY, "Job List: ")); jobListSizer->Add(new wxHyperlinkCtrl(this, wxID_ANY, "ETS2 Job Sync", "http://www.ets2sync.com/")); infoSizer->Add(jobListSizer); wxBoxSizer * translatorSizer = new wxBoxSizer(wxHORIZONTAL); translatorSizer->Add(new wxStaticText(this, wxID_ANY, "English Translation: ")); translatorSizer->Add(new wxHyperlinkCtrl(this, wxID_ANY, "David Santos", "https://github.com/davidsantos-br/")); infoSizer->Add(translatorSizer);*/ infoSizer->AddSpacer(border.y); infoSizer->Add(new wxStaticText(this, wxID_ANY, wxGetLibraryVersionInfo().ToString().Trim())); canvas->Add(infoSizer); wxBoxSizer * windowSizer = new wxBoxSizer(wxVERTICAL); windowSizer->AddSpacer(border.y); windowSizer->Add(canvas, wxSizerFlags().Border(wxLEFT|wxRIGHT, border.x)); windowSizer->AddSpacer(border.y); windowSizer->Add(new wxStaticLine(this), wxSizerFlags().Expand()); windowSizer->AddSpacer(border.y); wxBoxSizer * closeSizer = new wxBoxSizer(wxHORIZONTAL); closeSizer->Add(new wxStaticText(this, wxID_ANY, "Built on " __DATE__ " " __TIME__ " (" #ifdef _DEBUG "Debug" #else "Release" #endif " build)"), wxSizerFlags().CenterVertical()); closeSizer->AddStretchSpacer(); wxButton * closeButton = new wxButton(this, wxID_CLOSE, "Close"); closeSizer->Add(closeButton); windowSizer->Add(closeSizer, wxSizerFlags().Expand().Border(wxLEFT|wxRIGHT, border.x)); closeButton->SetFocus(); closeButton->SetDefault(); closeButton->Bind(wxEVT_BUTTON, [this](wxCommandEvent&) { Close(); }); windowSizer->AddSpacer(border.y); SetSizerAndFit(windowSizer); } AboutWindow::~AboutWindow() { delete mUpdateChecker; } MainWindow * AboutWindow::GetParent() { return static_cast<MainWindow *>(wxDialog::GetParent()); } void AboutWindow::checkUpdates() { mUpdateChecker->start(); } void AboutWindow::onUpdateStatus() { UpdateChecker::Status status = mUpdateChecker->getStatus(); StatusText::Type statusTextType; if (status.state == UpdateChecker::STATE_RUNNING) { statusTextType = StatusText::TYPE_STATUS; } else if (status.state == UpdateChecker::STATE_FINISHED && status.result == UpdateChecker::RESULT_UP_TO_DATE) { statusTextType = StatusText::TYPE_SUCCESS; } else { statusTextType = StatusText::TYPE_ERROR; } mCheckStatusText->SetLabel(UpdateChecker::getStatusDescription(status), statusTextType); if (status.state != UpdateChecker::STATE_RUNNING) { if (mCheckingAnimation->IsShown()) { mCheckingAnimation->Stop(); mCheckingAnimation->Hide(); mUpdateCheckAgain->SetLabel("Check Again"); } } else { if (!mCheckingAnimation->IsShown()) { mCheckingAnimation->Show(); mCheckingAnimation->Start(); mUpdateCheckAgain->SetLabel("Stop"); } } mUpdateCheckSizer->Layout(); } void AboutWindow::onShow(wxShowEvent& weEvent) { if (weEvent.IsShown()) { Center(); checkUpdates(); } } void AboutWindow::onUpdateCheckAgain() { if (mUpdateChecker->getStatus().state == UpdateChecker::STATE_RUNNING) { mUpdateChecker->cancel(); } else { checkUpdates(); } } void AboutWindow::onOpenWebsite() { GetParent()->openWebsite(); } void AboutWindow::onClose() { Close(); }
34.327485
115
0.748893
TruckerMP
433658af52807237dc9011b4e3440046deec2823
2,289
cpp
C++
Application/source/ui/frame/settings/SysMP3.cpp
RoutineFree/TriPlayer
4e5ee19c992eba033b57444b7f4b312acf339163
[ "MIT" ]
106
2020-11-01T09:58:37.000Z
2022-03-26T10:44:26.000Z
Application/source/ui/frame/settings/SysMP3.cpp
RoutineFree/TriPlayer
4e5ee19c992eba033b57444b7f4b312acf339163
[ "MIT" ]
30
2020-11-01T11:21:48.000Z
2022-02-01T23:09:47.000Z
Application/source/ui/frame/settings/SysMP3.cpp
RoutineFree/TriPlayer
4e5ee19c992eba033b57444b7f4b312acf339163
[ "MIT" ]
15
2020-11-02T12:06:03.000Z
2021-08-05T14:22:39.000Z
#include "Application.hpp" #include "lang/Lang.hpp" #include "ui/frame/settings/SysMP3.hpp" namespace Frame::Settings { SysMP3::SysMP3(Main::Application * a) : Frame(a) { // Temporary variables Config * cfg = this->app->config(); // MP3::accurate_seek this->addToggle("Settings.SysMP3.AccurateSeek"_lang, [cfg]() -> bool { return cfg->sysMP3AccurateSeek(); }, [this, cfg](bool b) { cfg->setSysMP3AccurateSeek(b); this->app->sysmodule()->sendReloadConfig(); }); this->addComment("Settings.SysMP3.AccurateSeekText"_lang); // Equalizer this->addButton("Settings.SysMP3.Equalizer"_lang, [this]() { this->showEqualizer(); }); this->addComment("Settings.SysMP3.EqualizerText"_lang); // Setup overlay this->ovlEQ = new CustomOvl::Equalizer("Settings.SysMP3.Equalizer"_lang); this->ovlEQ->setApplyLabel("Common.Apply"_lang); this->ovlEQ->setBackLabel("Common.Back"_lang); this->ovlEQ->setOKLabel("Common.OK"_lang); this->ovlEQ->setResetLabel("Common.Reset"_lang); this->ovlEQ->setBackgroundColour(this->app->theme()->popupBG()); this->ovlEQ->setHeadingColour(this->app->theme()->FG()); this->ovlEQ->setLineColour(this->app->theme()->muted()); this->ovlEQ->setSliderBackgroundColour(this->app->theme()->muted2()); this->ovlEQ->setSliderForegroundColour(this->app->theme()->accent()); this->ovlEQ->setSliderKnobColour(this->app->theme()->FG()); this->ovlEQ->setApplyCallback([this]() { std::array<float, 32> arr = this->ovlEQ->getValues(); this->app->config()->setSysMP3Equalizer(arr); this->app->sysmodule()->sendReloadConfig(); }); this->ovlEQ->setResetCallback([this]() { std::array<float, 32> arr; arr.fill(1.0f); this->ovlEQ->setValues(arr); }); } void SysMP3::showEqualizer() { // Set initial values and add std::array<float, 32> arr = this->app->config()->sysMP3Equalizer(); this->ovlEQ->setValues(arr); this->app->addOverlay(this->ovlEQ); } SysMP3::~SysMP3() { delete this->ovlEQ; } };
38.79661
81
0.591525
RoutineFree
433b2ada31562b35d201d7517d4fca7971c36ae4
6,503
cpp
C++
serial_tun.cpp
ClausKlein/Serial-TUN
f2929cae5b6ab907b7b5d1e20b81b400d2ccb3e9
[ "MIT" ]
null
null
null
serial_tun.cpp
ClausKlein/Serial-TUN
f2929cae5b6ab907b7b5d1e20b81b400d2ccb3e9
[ "MIT" ]
null
null
null
serial_tun.cpp
ClausKlein/Serial-TUN
f2929cae5b6ab907b7b5d1e20b81b400d2ccb3e9
[ "MIT" ]
null
null
null
#include "slip.h" #include "tun-driver.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <libserialport.h> #include <pthread.h> struct CommDevices { int tunFileDescriptor; struct sp_port *serialPort; }; char adapterName[IF_NAMESIZE]; char serialPortName[128]; unsigned serialBaudRate = 9600; static void *serialToTun(void *ptr); static void *tunToSerial(void *ptr); /** * Handles getting packets from the serial port and writing them to the TUN * interface * @param ptr - Pointer to the CommDevices struct */ static void *serialToTun(void *ptr) { // Grab thread parameters struct CommDevices *args = static_cast<struct CommDevices *>(ptr); int tunFd = args->tunFileDescriptor; struct sp_port *serialPort = args->serialPort; // Create two buffers, one to store raw data from the serial port and // one to store SLIP frames Buffer_t inBuffer(SLIP_IN_FRAME_LENGTH); Buffer_t outBuffer(SLIP_OUT_FRAME_LENGTH); size_t outSize = 0; int inIndex = 0; // Incoming byte count size_t count; // Serial result enum sp_return serialResult; // Add 'RX ready' event to serial port struct sp_event_set *eventSet; sp_new_event_set(&eventSet); sp_add_port_events(eventSet, serialPort, SP_EVENT_RX_READY); while (true) { // Wait for the event (RX Ready) sp_wait(eventSet, 0); count = sp_input_waiting(serialPort); // Bytes ready for reading // Read bytes from serial serialResult = sp_blocking_read(serialPort, &inBuffer[inIndex], count, 0); if (serialResult < 0) { std::cerr << "Serial error! " << serialResult << std::endl; } else { // We need to check if there is an SLIP_END sequence in the new // bytes for (int i = 0; i < serialResult; i++) { if (inBuffer[inIndex] == SLIP_END) { // Decode the packet that is marked by SLIP_END slip_decode(inBuffer, inIndex, outBuffer, &outSize); // Write the packet to the virtual interface write(tunFd, outBuffer.data(), outSize); // Copy the remaining data (belonging to the next packet) // to the start of the buffer memcpy(inBuffer.data(), &inBuffer[inIndex + 1], serialResult - i - 1); inIndex = serialResult - i - 1; break; } inIndex++; } } } return ptr; } static void *tunToSerial(void *ptr) { // Grab thread parameters struct CommDevices *args = static_cast<struct CommDevices *>(ptr); int tunFd = args->tunFileDescriptor; struct sp_port *serialPort = args->serialPort; // Create TUN buffer Buffer_t inBuffer(SLIP_IN_FRAME_LENGTH); Buffer_t outBuffer(SLIP_OUT_FRAME_LENGTH); // Incoming byte count ssize_t count; // Encoded data size unsigned long encodedLength = 0; // Serial error messages enum sp_return serialResult; while (true) { count = read(tunFd, inBuffer.data(), inBuffer.size()); if (count < 0) { std::cerr << "Could not read from interface\n"; continue; } // Encode data slip_encode(inBuffer, (size_t)count, outBuffer, &encodedLength); // Write to serial port serialResult = sp_nonblocking_write(serialPort, outBuffer.data(), encodedLength); if (serialResult < 0) { std::cerr << "Could not send data to serial port: " << serialResult << std::endl; } } return ptr; } int main(int argc, char *argv[]) { // Grab parameters int param; while ((param = getopt(argc, argv, "i:p:b:")) > 0) { switch (param) { case 'i': strncpy(static_cast<char *>(adapterName), optarg, IFNAMSIZ - 1); break; case 'p': strncpy(static_cast<char *>(serialPortName), optarg, sizeof(serialPortName) - 1); break; case 'b': serialBaudRate = strtoul(optarg, NULL, 10); break; default: std::cerr << "Unknown parameter " << param << std::endl; break; } } if (adapterName[0] == '\0') { std::cerr << "Adapter name required (-i)\n"; return EXIT_FAILURE; } if (serialPortName[0] == '\0') { std::cerr << "Serial port required (-p)\n"; return EXIT_FAILURE; } int tunFd = tun_open_common(static_cast<char *>(adapterName), VTUN_P2P); if (tunFd < 0) { std::cerr << "Could not open /dev/net/tun\n"; return EXIT_FAILURE; } // Configure & open serial port struct sp_port *serialPort; sp_get_port_by_name(static_cast<char *>(serialPortName), &serialPort); enum sp_return status = sp_open(serialPort, SP_MODE_READ_WRITE); sp_set_bits(serialPort, 8); sp_set_parity(serialPort, SP_PARITY_NONE); sp_set_stopbits(serialPort, 1); sp_set_baudrate(serialPort, serialBaudRate); sp_set_xon_xoff(serialPort, SP_XONXOFF_DISABLED); sp_set_flowcontrol(serialPort, SP_FLOWCONTROL_NONE); if (status < 0) { std::cerr << "Could not open serial port: "; switch (status) { case SP_ERR_ARG: std::cerr << "Invalid argument\n"; break; case SP_ERR_FAIL: std::cerr << "System error\n"; break; case SP_ERR_MEM: std::cerr << "Memory allocation error\n"; break; case SP_ERR_SUPP: std::cerr << "Operation not supported by device\n"; break; default: std::cerr << "Unknown error\n"; break; } return EXIT_FAILURE; } // Create threads pthread_t tun2serial, serial2tun; struct CommDevices threadParams = {}; threadParams.tunFileDescriptor = tunFd; threadParams.serialPort = serialPort; puts("Starting threads"); pthread_create(&tun2serial, NULL, tunToSerial, (void *)&threadParams); pthread_create(&serial2tun, NULL, serialToTun, (void *)&threadParams); pthread_join(tun2serial, NULL); puts("Thread tun-to-network returned"); pthread_join(serial2tun, NULL); puts("Thread network-to-tun returned"); return EXIT_SUCCESS; }
28.902222
79
0.594341
ClausKlein
4343006c339dd3d8c5c5f8e16921fb3ab296b467
51,747
cpp
C++
src/main.cpp
fluffels/vulkan-experiments
77fc2a3510a22df277d49a6e9b86e52505768b91
[ "MIT" ]
null
null
null
src/main.cpp
fluffels/vulkan-experiments
77fc2a3510a22df277d49a6e9b86e52505768b91
[ "MIT" ]
null
null
null
src/main.cpp
fluffels/vulkan-experiments
77fc2a3510a22df277d49a6e9b86e52505768b91
[ "MIT" ]
null
null
null
#include <array> #include <chrono> #include <filesystem> #include <fstream> #include <iostream> #include <set> #include <unordered_map> #include <string> #include <vector> #include "lib/meshes/Terrain.h" #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/gtc/matrix_transform.hpp> #ifndef NOMINMAX # define NOMINMAX #endif #include <glm/glm.hpp> #include "easylogging++.h" #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #define TINYOBJLOADER_IMPLEMENTATION #include "tiny_obj_loader.h" #include "WangTiling.h" #include "FS.h" #include "Memory.h" #include "Buffer.h" #include "Vulkan.h" struct Coord { double x; double y; }; struct MVP { glm::mat4 model; glm::mat4 view; glm::mat4 proj; }; struct Scene { Buffer indices; Buffer uniforms; Buffer vertices; MVP mvp; Image grassTexture; Image groundTexture; Image colour; Image depth; Image noise; }; std::vector<TerrainVertex> groundVertices; std::vector<uint32_t> indices; Buffer groundBuffer; Buffer groundIndexBuffer; std::vector<uint32_t> groundIndexVector; auto eye = glm::vec3(50.0f, -2.0f, 50.0f); auto at = glm::vec3(0.0f, -2.0f, 0.0f); auto up = glm::vec3(0.0f, 1.0f, 0.0f); int keyboard[GLFW_KEY_LAST] = {GLFW_RELEASE}; const bool fullscreen = false; const std::vector<const char*> requiredDeviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; const int WINDOW_HEIGHT = 900; const int WINDOW_WIDTH = 1800; INITIALIZE_EASYLOGGINGPP static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objType, uint64_t obj, size_t location, int32_t code, const char *layerPrefix, const char *msg, void *userData ) { if (flags == VK_DEBUG_REPORT_ERROR_BIT_EXT) { LOG(ERROR) << "[" << layerPrefix << "] " << msg; } else if (flags == VK_DEBUG_REPORT_WARNING_BIT_EXT) { LOG(WARNING) << "[" << layerPrefix << "] " << msg; } else { LOG(DEBUG) << "[" << layerPrefix << "] " << msg; } return VK_FALSE; } void onKeyEvent( GLFWwindow* window, int key, int scancode, int action, int mods ) { if (key == GLFW_KEY_ESCAPE) { glfwSetWindowShouldClose(window, GLFW_TRUE); } else { if (action == GLFW_PRESS) { keyboard[key] = GLFW_PRESS; } else if (action == GLFW_RELEASE) { keyboard[key] = GLFW_RELEASE; } } } int main (int argc, char** argv, char** envp) { START_EASYLOGGINGPP(argc, argv); VK vk; Scene scene; while (*envp != 0) { char* env = *envp; if (strstr(env, "VULKAN") == env || strstr(env, "VK") == env || strstr(env, "LD_LIBRARY_PATH=") == env || strstr(env, "PATH") == env) { LOG(DEBUG) << env; } envp++; } LOG(INFO) << "Initalizing GLFW..."; if (!glfwInit()) { return 1; } else { glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); } LOG(INFO) << "Creating window..."; auto window = glfwCreateWindow( WINDOW_WIDTH, WINDOW_HEIGHT, "Vulkan Experiments", fullscreen ? glfwGetPrimaryMonitor() : nullptr, nullptr ); if (!window) { glfwTerminate(); return 2; } LOG(INFO) << "Swap to window context..."; glfwMakeContextCurrent(window); /* NOTE(jan): Vulkan application. */ VkApplicationInfo ai = {}; ai.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; ai.pApplicationName = "Vk Experiments"; ai.applicationVersion = VK_MAKE_VERSION(0, 1, 0); ai.pEngineName = "No Engine"; ai.engineVersion = VK_MAKE_VERSION(0, 1, 0); ai.apiVersion = VK_API_VERSION_1_0; /* NOTE(jan): Start creating Vulkan instance. */ VkInstanceCreateInfo ici = {}; ici.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; ici.pApplicationInfo = &ai; /* NOTE(jan): Check whether validation layers should be enabled. */ #ifdef NDEBUG bool validation_enabled = false; #else LOG(INFO) << "Enabling validation layers..."; bool validationEnabled = true; std::vector<const char *> layersRequested = { "VK_LAYER_LUNARG_standard_validation" }; { uint32_t count; vkEnumerateInstanceLayerProperties(&count, nullptr); auto layersAvailable = new VkLayerProperties[count]; vkEnumerateInstanceLayerProperties(&count, layersAvailable); for (const auto &nameRequested: layersRequested) { bool found = false; uint32_t i = 0; while ((i < count) && (!found)) { auto *nameAvailable = layersAvailable[i].layerName; if (strcmp(nameAvailable, nameRequested) == 0) { found = true; } i++; } if (!found) { LOG(ERROR) << "Could not find layer '" << nameRequested << "'."; LOG(WARNING) << "Disabling validation layers..."; validationEnabled = false; break; } } } #endif /* NOTE(jan): Conditionally enable validation layers. */ #ifndef NDEBUG if (validationEnabled) { ici.enabledLayerCount = static_cast<uint32_t>(layersRequested.size()); ici.ppEnabledLayerNames = layersRequested.data(); } else { ici.enabledLayerCount = 0; } #endif /* NOTE(jan): Extensions. */ uint32_t glfwExtensionCount = 0; const char** glfwExtensions = glfwGetRequiredInstanceExtensions( &glfwExtensionCount ); std::vector<const char*> requestedExtensions; for (uint32_t i = 0; i < glfwExtensionCount; i++) { requestedExtensions.push_back(glfwExtensions[i]); } #ifndef NDEBUG if (validationEnabled) { requestedExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); } #endif ici.enabledExtensionCount = static_cast<uint32_t> (requestedExtensions.size()); ici.ppEnabledExtensionNames = requestedExtensions.data(); /* NOTE(jan): Create Vulkan instance. */ VkResult result = vkCreateInstance(&ici, nullptr, &vk.h); if (result == VK_ERROR_LAYER_NOT_PRESENT) { throw std::runtime_error("Layer not present."); } else if (result == VK_ERROR_EXTENSION_NOT_PRESENT) { throw std::runtime_error("Extension not present."); } else if (result != VK_SUCCESS) { throw std::runtime_error("Could not instantiate Vulkan."); } /* NOTE(jan): Debug callback. */ #ifndef NDEBUG VkDebugReportCallbackEXT callback_debug; if (validationEnabled) { VkDebugReportCallbackCreateInfoEXT cf = {}; cf.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; cf.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_DEBUG_BIT_EXT; cf.pfnCallback = debugCallback; auto create = (PFN_vkCreateDebugReportCallbackEXT) vkGetInstanceProcAddr(vk.h, "vkCreateDebugReportCallbackEXT"); if (create == nullptr) { LOG(WARNING) << "Could load debug callback creation function"; } else { vkCheckSuccess( create(vk.h, &cf, nullptr, &callback_debug), "Could not create debug callback" ); } } #endif /* NOTE(jan): Create surface. */ vkCheckSuccess( glfwCreateWindowSurface(vk.h, window, nullptr, &vk.surface), "Could not create surface." ); glfwSetWindowPos(window, 10, 40); /* NOTE(jan): Physical device selection. */ { uint32_t count; vkEnumeratePhysicalDevices(vk.h, &count, nullptr); if (count == 0) { throw std::runtime_error("No Vulkan devices detected."); } std::vector<VkPhysicalDevice> devices(count); vkEnumeratePhysicalDevices(vk.h, &count, devices.data()); int max_score = -1; for (const auto& device: devices) { int score = -1; VkPhysicalDeviceProperties properties; vkGetPhysicalDeviceProperties(device, &properties); VkPhysicalDeviceFeatures features; vkGetPhysicalDeviceFeatures(device, &features); vkEnumerateDeviceExtensionProperties( device, nullptr, &count, nullptr ); std::vector<VkExtensionProperties> extensions_available(count); vkEnumerateDeviceExtensionProperties( device, nullptr, &count, extensions_available.data() ); std::set<std::string> extensions_required( requiredDeviceExtensions.begin(), requiredDeviceExtensions.end() ); for (const auto& extension: extensions_available) { extensions_required.erase(extension.extensionName); } vkGetPhysicalDeviceSurfaceCapabilitiesKHR( device, vk.surface, &vk.swap.capabilities ); vkGetPhysicalDeviceSurfaceFormatsKHR( device, vk.surface, &count, nullptr ); if (count > 0) { vk.swap.formats.resize(count); vkGetPhysicalDeviceSurfaceFormatsKHR( device, vk.surface, &count, vk.swap.formats.data() ); } vkGetPhysicalDeviceSurfacePresentModesKHR( device, vk.surface, &count, nullptr ); if (count > 0) { vk.swap.modes.resize(count); vkGetPhysicalDeviceSurfacePresentModesKHR( device, vk.surface, &count, vk.swap.modes.data() ); } /* NOTE(jan): Determine our multisampling settings. */ VkSampleCountFlags maxSampleCounts = std::min( properties.limits.framebufferColorSampleCounts, properties.limits.framebufferDepthSampleCounts ); auto vkSampleCounts = { VK_SAMPLE_COUNT_2_BIT, VK_SAMPLE_COUNT_4_BIT, VK_SAMPLE_COUNT_8_BIT, VK_SAMPLE_COUNT_16_BIT, VK_SAMPLE_COUNT_32_BIT, VK_SAMPLE_COUNT_64_BIT, }; std::vector<VkSampleCountFlagBits> availableSampleCounts; for (auto sampleCount : vkSampleCounts) { if (maxSampleCounts & sampleCount) { availableSampleCounts.push_back(sampleCount); } } vk.sampleCount = availableSampleCounts.back(); if (!extensions_required.empty()) { LOG(ERROR) << properties.deviceName << " does not support " << "all required extensions, skipping..."; } else if (!features.geometryShader) { LOG(ERROR) << properties.deviceName << " does not support " << "geometry shaders, skipping..."; } else if (!features.samplerAnisotropy) { LOG(ERROR) << properties.deviceName << " does not support " << "anisotropic samplers, skipping..."; } else if (vk.swap.formats.empty()) { LOG(ERROR) << properties.deviceName << " does not support " << "any compatible swap formats, skipping..."; } else if (vk.swap.modes.empty()) { LOG(ERROR) << properties.deviceName << " does not support " << "any compatible swap modes, skipping..."; } else { vkGetPhysicalDeviceQueueFamilyProperties( device, &count, nullptr ); std::vector<VkQueueFamilyProperties> queueFamilies(count); vkGetPhysicalDeviceQueueFamilyProperties( device, &count, queueFamilies.data() ); vk.queues.graphics.family_index = -1; vk.queues.present.family_index = -1; int i = 0; for (const auto& queueFamily: queueFamilies) { VkBool32 presentSupport = VK_FALSE; vkGetPhysicalDeviceSurfaceSupportKHR( device, i, vk.surface, &presentSupport ); if ((queueFamily.queueCount) && presentSupport) { vk.queues.present.family_index = i; } if ((queueFamily.queueCount) && (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT)) { vk.queues.graphics.family_index = i; } if ((vk.queues.present.family_index >= 0) && (vk.queues.graphics.family_index >= 0)) { score = 0; if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) { score += 100; } break; } i++; } } LOG(INFO) << "Device '" << properties.deviceName << "' scored at " << score; if (score > max_score) { vk.physical_device = device; } break; } } if (vk.physical_device == VK_NULL_HANDLE) { throw std::runtime_error("No suitable Vulkan devices detected."); } /* NOTE(jan): Logical device. */ { std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; std::set<int> uniqueQueueFamilyIndices = { vk.queues.graphics.family_index, vk.queues.present.family_index }; float queuePriority = 1.0f; for (int queueFamilyIndex: uniqueQueueFamilyIndices) { VkDeviceQueueCreateInfo cf = {}; cf.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; cf.queueFamilyIndex = queueFamilyIndex; cf.queueCount = 1; cf.pQueuePriorities = &queuePriority; queueCreateInfos.push_back(cf); } VkPhysicalDeviceFeatures features = {}; features.geometryShader = VK_TRUE; features.samplerAnisotropy = VK_TRUE; features.sampleRateShading = VK_TRUE; VkDeviceCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); createInfo.pQueueCreateInfos = queueCreateInfos.data(); createInfo.pEnabledFeatures = &features; createInfo.enabledExtensionCount = static_cast<uint32_t>(requiredDeviceExtensions.size()); createInfo.ppEnabledExtensionNames = requiredDeviceExtensions.data(); #ifndef NDEBUG if (validationEnabled) { createInfo.enabledLayerCount = static_cast<uint32_t>(layersRequested.size()); createInfo.ppEnabledLayerNames = layersRequested.data(); } else { createInfo.enabledLayerCount = 0; } #endif VkResult r = vkCreateDevice( vk.physical_device, &createInfo, nullptr, &vk.device ); if (r == VK_ERROR_OUT_OF_HOST_MEMORY) { throw std::runtime_error("Out of host memory."); } else if (r == VK_ERROR_OUT_OF_DEVICE_MEMORY) { throw std::runtime_error("Out of device memory."); } else if (r == VK_ERROR_EXTENSION_NOT_PRESENT) { throw std::runtime_error("Extension not present."); } else if (r == VK_ERROR_FEATURE_NOT_PRESENT) { throw std::runtime_error("Feature not present."); } else if (r == VK_ERROR_TOO_MANY_OBJECTS) { throw std::runtime_error("Too many logical devices."); } else if (r == VK_ERROR_DEVICE_LOST) { throw std::runtime_error("Device lost."); } vkCheckSuccess(r, "Could not create physical device."); } /* NOTE(jan): Device queues. */ { vkGetDeviceQueue( vk.device, vk.queues.graphics.family_index, 0, &vk.queues.graphics.q ); vkGetDeviceQueue( vk.device, vk.queues.present.family_index, 0, &vk.queues.present.q ); } /* NOTE(jan): Swap chain format. */ { /* NOTE(jan): Pick a surface format. */ /* NOTE(jan): Default. */ vk.swap.format = vk.swap.formats[0]; if ((vk.swap.formats.size() == 1) && (vk.swap.formats[0].format == VK_FORMAT_UNDEFINED)) { vk.swap.format = { VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR }; LOG(INFO) << "Surface has no preferred format. " << "Selecting 8 bit SRGB..."; } else { for (const auto &format: vk.swap.formats) { if ((format.format == VK_FORMAT_B8G8R8A8_UNORM) && (format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)) { vk.swap.format = format; LOG(INFO) << "Surface supports 8 bit SRGB. Selecting..."; } } } } /* NOTE(jan): Swap chain presentation mode. */ { /* NOTE(jan): Default. Guaranteed to be present. */ vk.swap.mode = VK_PRESENT_MODE_FIFO_KHR; for (const auto &mode: vk.swap.modes) { /* NOTE(jan): This allows us to implement triple buffering. */ if (mode == VK_PRESENT_MODE_MAILBOX_KHR) { vk.swap.mode = VK_PRESENT_MODE_MAILBOX_KHR; LOG(INFO) << "Surface supports mailbox presentation mode. " << "Selecting..."; } } } /* NOTE(jan): Swap chain extent. */ { if (vk.swap.capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()) { vk.swap.extent = vk.swap.capabilities.currentExtent; } else { VkExtent2D extent = {WINDOW_WIDTH, WINDOW_HEIGHT}; extent.width = std::max( vk.swap.capabilities.minImageExtent.width, std::min( vk.swap.capabilities.maxImageExtent.width, extent.width ) ); extent.height = std::max( vk.swap.capabilities.minImageExtent.height, std::min( vk.swap.capabilities.maxImageExtent.height, extent.height ) ); vk.swap.extent = extent; } LOG(INFO) << "Swap chain extent set to " << vk.swap.extent.width << "x" << vk.swap.extent.height; } /* NOTE(jan): Swap chain length. */ { vk.swap.l = vk.swap.capabilities.minImageCount + 1; /* NOTE(jan): maxImageCount == 0 means no limit. */ if ((vk.swap.capabilities.maxImageCount < vk.swap.l) && (vk.swap.capabilities.maxImageCount > 0)) { vk.swap.l = vk.swap.capabilities.maxImageCount; } vk.swap.images.resize(vk.swap.l); LOG(INFO) << "Swap chain length set to " << vk.swap.l; } /* NOTE(jan): Swap chain. */ { VkSwapchainCreateInfoKHR cf = {}; cf.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; cf.surface = vk.surface; cf.minImageCount = vk.swap.l; cf.imageFormat = vk.swap.format.format; cf.imageColorSpace = vk.swap.format.colorSpace; cf.imageExtent = vk.swap.extent; cf.imageArrayLayers = 1; cf.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; cf.preTransform = vk.swap.capabilities.currentTransform; cf.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; cf.presentMode = vk.swap.mode; cf.clipped = VK_TRUE; cf.oldSwapchain = VK_NULL_HANDLE; uint32_t queueFamilyIndices[] = { static_cast<uint32_t>(vk.queues.graphics.family_index), static_cast<uint32_t>(vk.queues.present.family_index) }; if (vk.queues.graphics.family_index != vk.queues.present.family_index) { cf.imageSharingMode = VK_SHARING_MODE_CONCURRENT; cf.queueFamilyIndexCount = 2; cf.pQueueFamilyIndices = queueFamilyIndices; } else { cf.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; cf.queueFamilyIndexCount = 0; cf.pQueueFamilyIndices = nullptr; } vkCheckSuccess( vkCreateSwapchainKHR(vk.device, &cf, nullptr, &vk.swap.h), "Could not create swap chain." ); } /* NOTE(jan): Swap chain images. */ { vkGetSwapchainImagesKHR(vk.device, vk.swap.h, &vk.swap.l, nullptr); auto images = new VkImage[vk.swap.l]; vkGetSwapchainImagesKHR(vk.device, vk.swap.h, &vk.swap.l, images); for (uint32_t i = 0; i < vk.swap.l; i++) { vk.swap.images[i].i = images[i]; } LOG(INFO) << "Retrieved " << vk.swap.l << " swap chain images."; } /* NOTE(jan): Swap chain image views. */ for (uint32_t i = 0; i < vk.swap.l; i++) { VkImageViewCreateInfo cf = {}; cf.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; cf.image = vk.swap.images[i].i; cf.viewType = VK_IMAGE_VIEW_TYPE_2D; cf.format = vk.swap.format.format; cf.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; cf.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; cf.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; cf.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; cf.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; cf.subresourceRange.baseMipLevel = 0; cf.subresourceRange.levelCount = 1; cf.subresourceRange.baseArrayLayer = 0; cf.subresourceRange.layerCount = 1; vkCheckSuccess( vkCreateImageView(vk.device, &cf, nullptr, &vk.swap.images[i].v), "Could not create image view." ); } /* NOTE(jan): The render passes and descriptor sets below start the * pipeline creation process. */ Pipeline grassPipeline = {}; Pipeline groundPipeline = {}; /* NOTE(jan): Render pass. */ VkRenderPass defaultRenderPass; { VkAttachmentDescription descriptions[3] = {}; descriptions[0].format = vk.swap.format.format; descriptions[0].samples = vk.sampleCount; descriptions[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; descriptions[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; descriptions[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; descriptions[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; descriptions[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; descriptions[0].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; descriptions[1].format = vk.findDepthFormat(); descriptions[1].samples = vk.sampleCount; descriptions[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; descriptions[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; descriptions[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; descriptions[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; descriptions[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; descriptions[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; descriptions[2].format = vk.swap.format.format; descriptions[2].samples = VK_SAMPLE_COUNT_1_BIT; descriptions[2].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; descriptions[2].storeOp = VK_ATTACHMENT_STORE_OP_STORE; descriptions[2].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; descriptions[2].stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE; descriptions[2].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; descriptions[2].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference refs[3] = {}; refs[0].attachment = 0; refs[0].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; refs[1].attachment = 1; refs[1].layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; refs[2].attachment = 2; refs[2].layout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkSubpassDescription subpass = {}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &refs[0]; subpass.pDepthStencilAttachment = &refs[1]; subpass.pResolveAttachments = &refs[2]; VkSubpassDependency dep = {}; dep.srcSubpass = VK_SUBPASS_EXTERNAL; dep.dstSubpass = 0; dep.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dep.srcAccessMask = 0; dep.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dep.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; VkRenderPassCreateInfo cf = {}; cf.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; cf.attachmentCount = 3; cf.pAttachments = descriptions; cf.subpassCount = 1; cf.pSubpasses = &subpass; cf.dependencyCount = 1; cf.pDependencies = &dep; vkCheckSuccess( vkCreateRenderPass(vk.device, &cf, nullptr, &defaultRenderPass), "Could not create render pass." ); } VkDescriptorSetLayout defaultDescriptorSetLayout; { std::vector<VkDescriptorSetLayoutBinding> bindings; { VkDescriptorSetLayoutBinding b = {}; b.binding = 0; b.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; b.descriptorCount = 1; b.stageFlags = ( VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT ); b.pImmutableSamplers = nullptr; bindings.push_back(b); } for (int i = 0; i < 2; i++) { VkDescriptorSetLayoutBinding b = {}; b.binding = 1 + i; b.descriptorCount = 1; b.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; b.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; b.pImmutableSamplers = nullptr; bindings.push_back(b); } { VkDescriptorSetLayoutBinding b = {}; b.binding = 3; b.descriptorCount = 1; b.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; b.stageFlags = ( VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT ); b.pImmutableSamplers = nullptr; bindings.push_back(b); } defaultDescriptorSetLayout = vk.createDescriptorSetLayout(bindings); } LOG(INFO) << "Creating grass pipeline..."; { grassPipeline = vk.createPipeline<GridVertex>( "shaders/triangle", defaultRenderPass, defaultDescriptorSetLayout ); } LOG(INFO) << "Creating ground pipeline..."; { groundPipeline = vk.createPipeline<TerrainVertex>( "shaders/ground", defaultRenderPass, defaultDescriptorSetLayout ); } /* NOTE(jan): Command pool creation. */ LOG(INFO) << "Create command pools..."; { VkCommandPoolCreateInfo cf = {}; cf.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; cf.queueFamilyIndex = vk.queues.graphics.family_index; cf.flags = 0; vkCheckSuccess( vkCreateCommandPool(vk.device, &cf, nullptr, &vk.commandPool), "Could not create command pool." ); } /* NOTE(jan): Vertex buffers. */ { Terrain terrain("noise.png"); LOG(INFO) << "Generating model..."; const int extent = 256; eye.x = 128; eye.y = terrain.getHeightAt(128, 128) - 1.f; eye.z = 128; std::vector<GridVertex> vertices; const float* positions = terrain.getPositions(); const float* normals = terrain.getNormals(); for (unsigned x = 0; x < terrain.getWidth(); x++) { for (unsigned z = 0; z < terrain.getDepth(); z++) { TerrainVertex v; v.pos = glm::vec3(positions[0], positions[1], positions[2]); v.normal = glm::vec3(normals[0], normals[1], normals[2]); v.tex = glm::vec2( x / terrain.getWidth(), z / terrain.getDepth() ); groundVertices.push_back(v); positions += 3; normals += 3; } } groundBuffer = vk.createVertexBuffer<TerrainVertex>(groundVertices); const unsigned* groundIndices = terrain.getIndices(); groundIndexVector.resize(terrain.getIndexCount()); groundIndexVector.assign( groundIndices, groundIndices + terrain.getIndexCount() ); groundIndexBuffer = vk.createIndexBuffer(groundIndexVector); const float density = 1.f; const int count = static_cast<int>(extent * density); WangTiling wangTiling(count, count); { for (int z = 0; z < count; z++) { for (int x = 0; x < count; x++) { GridVertex vertex = {}; vertex.pos = { x * (1/(float)density), terrain.getHeightAt(x, z) + 0.2f, z * (1/(float)density), }; vertex.type = wangTiling.getTile(z, x).getID(); indices.push_back( static_cast<uint32_t>(vertices.size()) ); vertices.push_back(vertex); } } } scene.vertices = vk.createVertexBuffer<GridVertex>(vertices); } /* NOTE(jan): Index buffer. */ { scene.indices = vk.createIndexBuffer(indices); } /* NOTE(jan): Uniform buffer. */ { VkDeviceSize size = sizeof(scene.mvp); scene.uniforms = vk.createBuffer( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, size ); } scene.grassTexture = vk.createTexture("grass.png"); scene.groundTexture = vk.createTexture("ground.png", true); scene.noise = vk.createTexture("noise.png"); /* NOTE(jan): Colour buffer. */ { scene.colour = vk.createImage( { vk.swap.extent.width, vk.swap.extent.height, 1 }, vk.sampleCount, vk.swap.format.format, VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_IMAGE_ASPECT_COLOR_BIT ); vk.transitionImage( scene.colour, vk.swap.format.format, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL ); } /* NOTE(jan): Depth buffer. */ { auto format = vk.findDepthFormat(); scene.depth = vk.createImage( {vk.swap.extent.width, vk.swap.extent.height, 1}, vk.sampleCount, format, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_IMAGE_ASPECT_DEPTH_BIT ); vk.transitionImage( scene.depth, format, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ); } /* NOTE(jan): Frame buffers. */ { vk.swap.frames.resize(vk.swap.l); for (size_t i = 0; i < vk.swap.l; i++) { VkImageView attachments[] = { scene.colour.v, scene.depth.v, vk.swap.images[i].v, }; VkFramebufferCreateInfo cf = {}; cf.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; cf.renderPass = defaultRenderPass; cf.attachmentCount = 3; cf.pAttachments = attachments; cf.width = vk.swap.extent.width; cf.height = vk.swap.extent.height; cf.layers = 1; vkCheckSuccess( vkCreateFramebuffer( vk.device, &cf, nullptr, &vk.swap.frames[i] ), "Could not create framebuffer." ); } } /* NOTE(jan): Descriptor pool. */ VkDescriptorPool defaultDescriptorPool; { std::vector<VkDescriptorPoolSize> size; { VkDescriptorPoolSize s = {}; s.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; s.descriptorCount = 1; size.push_back(s); } for (int i = 0; i < 3; i++) { VkDescriptorPoolSize s = {}; s.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; s.descriptorCount = 1; size.push_back(s); } defaultDescriptorPool = vk.createDescriptorPool(size); } /* NOTE(jan): Descriptor set. */ VkDescriptorSet defaultDescriptorSet; { std::vector<VkDescriptorSetLayout> layouts; layouts.push_back(defaultDescriptorSetLayout); defaultDescriptorSet = vk.allocateDescriptorSet( defaultDescriptorPool, layouts ); std::vector<VkWriteDescriptorSet> writes; { VkDescriptorBufferInfo i = {}; i.buffer = scene.uniforms.buffer; i.offset = 0; i.range = sizeof(scene.mvp); VkWriteDescriptorSet w = {}; w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = defaultDescriptorSet; w.dstBinding = 0; w.dstArrayElement = 0; w.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; w.descriptorCount = 1; w.pBufferInfo = &i; writes.push_back(w); } { VkDescriptorImageInfo i = {}; i.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; i.imageView = scene.grassTexture.v; i.sampler = scene.grassTexture.s; VkWriteDescriptorSet w = {}; w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = defaultDescriptorSet; w.dstBinding = 1; w.dstArrayElement = 0; w.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; w.descriptorCount = 1; w.pImageInfo = &i; writes.push_back(w); } { VkDescriptorImageInfo i = {}; i.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; i.imageView = scene.groundTexture.v; i.sampler = scene.groundTexture.s; VkWriteDescriptorSet w = {}; w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = defaultDescriptorSet; w.dstBinding = 2; w.dstArrayElement = 0; w.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; w.descriptorCount = 1; w.pImageInfo = &i; writes.push_back(w); } { VkDescriptorImageInfo i = {}; i.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; i.imageView = scene.noise.v; i.sampler = scene.noise.s; VkWriteDescriptorSet w = {}; w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = defaultDescriptorSet; w.dstBinding = 3; w.dstArrayElement = 0; w.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; w.descriptorCount = 1; w.pImageInfo = &i; writes.push_back(w); } vkUpdateDescriptorSets( vk.device, static_cast<uint32_t>(writes.size()), writes.data(), 0, nullptr ); } /* NOTE(jan): Command buffer creation. */ { vk.swap.command_buffers.resize(vk.swap.l); VkCommandBufferAllocateInfo i = {}; i.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; i.commandPool = vk.commandPool; i.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; i.commandBufferCount = (uint32_t)vk.swap.command_buffers.size(); vkCheckSuccess( vkAllocateCommandBuffers(vk.device, &i, vk.swap.command_buffers.data()), "Could not allocate command buffers." ); } /* NOTE(jan): Command buffer recording. */ for (size_t i = 0; i < vk.swap.command_buffers.size(); i++) { VkCommandBufferBeginInfo cbbi = {}; cbbi.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; cbbi.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; cbbi.pInheritanceInfo = nullptr; vkBeginCommandBuffer(vk.swap.command_buffers[i], &cbbi); /* NOTE(jan): Set up render pass. */ VkRenderPassBeginInfo rpbi = {}; rpbi.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; rpbi.renderPass = defaultRenderPass; rpbi.framebuffer = vk.swap.frames[i]; rpbi.renderArea.offset = {0, 0}; rpbi.renderArea.extent = vk.swap.extent; VkClearValue clear[3] = {}; clear[0].color = {1.0f, 1.0f, 1.0f, 0.0f}; clear[1].depthStencil = {1.0f, 0}; clear[2].color = {1.0f, 1.0f, 1.0f, 0.0f}; rpbi.clearValueCount = 3; rpbi.pClearValues = clear; vkCmdBeginRenderPass( vk.swap.command_buffers[i], &rpbi, VK_SUBPASS_CONTENTS_INLINE ); vkCmdBindDescriptorSets( vk.swap.command_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, grassPipeline.layout, 0, 1, &defaultDescriptorSet, 0, nullptr ); VkDeviceSize offsets[] = {0}; vkCmdBindPipeline( vk.swap.command_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, groundPipeline.handle ); VkBuffer ground_vertex_buffers[] = { groundBuffer.buffer }; vkCmdBindVertexBuffers( vk.swap.command_buffers[i], 0, 1, ground_vertex_buffers, offsets ); vkCmdBindIndexBuffer( vk.swap.command_buffers[i], groundIndexBuffer.buffer, 0, VK_INDEX_TYPE_UINT32 ); vkCmdDrawIndexed( vk.swap.command_buffers[i], static_cast<uint32_t>(groundIndexVector.size()), 1, 0, 0, 0 ); vkCmdBindPipeline( vk.swap.command_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, grassPipeline.handle ); VkBuffer vertex_buffers[] = {scene.vertices.buffer}; vkCmdBindVertexBuffers( vk.swap.command_buffers[i], 0, 1, vertex_buffers, offsets ); vkCmdBindIndexBuffer( vk.swap.command_buffers[i], scene.indices.buffer, 0, VK_INDEX_TYPE_UINT32 ); vkCmdDrawIndexed( vk.swap.command_buffers[i], static_cast<uint32_t>(indices.size()), 1, 0, 0, 0 ); vkCmdEndRenderPass(vk.swap.command_buffers[i]); vkCheckSuccess( vkEndCommandBuffer(vk.swap.command_buffers[i]), "Failed to record command buffer." ); } /* NOTE(jan): Create semaphores. */ { VkSemaphoreCreateInfo sci = {}; sci.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VkResult result; bool success; result = vkCreateSemaphore( vk.device, &sci, nullptr, &vk.swap.image_available ); success = result == VK_SUCCESS; result = vkCreateSemaphore( vk.device, &sci, nullptr, &vk.swap.render_finished ); success = success && (result == VK_SUCCESS); if (!success) { throw std::runtime_error("Could not create semaphores."); } } /* NOTE(jan): Initialize MVP matrices. */ scene.mvp.model = glm::mat4(1.0f); scene.mvp.proj = glm::perspective( glm::radians(45.0f), vk.swap.extent.width / (float)vk.swap.extent.height, 0.1f, 1000.0f ); /* NOTE(jan): Log frame times. */ std::ofstream frameTimeFile("frames.csv", std::ios::out); frameTimeFile << "\"frameID\", \"ms_d\"" << std::endl; /* NOTE(jan): All calculations should be scaled by the time it took * to render the last frame. */ auto start_f = std::chrono::high_resolution_clock::now(); auto last_f = std::chrono::high_resolution_clock::now(); auto this_f = std::chrono::high_resolution_clock::now(); auto frame_count = 0; float total_delta_f = 0.0f; float delta_f = 0.0f; LOG(INFO) << "Entering main loop..."; glfwSetKeyCallback(window, onKeyEvent); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); if (glfwRawMouseMotionSupported()) { LOG(INFO) << "Raw mouse motion is supported, enabling..."; glfwSetInputMode(window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE); } Coord mouse_position_last_frame; glfwGetCursorPos(window, &mouse_position_last_frame.x, &mouse_position_last_frame.y); while(!glfwWindowShouldClose(window)) { last_f = std::chrono::high_resolution_clock::now(); /* NOTE(jan): Copy MVP. */ void* mvp_dst; size_t s = sizeof(scene.mvp); vkMapMemory(vk.device, scene.uniforms.memory, 0, s, 0, &mvp_dst); memcpy(mvp_dst, &scene.mvp, s); vkUnmapMemory(vk.device, scene.uniforms.memory); uint32_t imageIndex; vkAcquireNextImageKHR( vk.device, vk.swap.h, std::numeric_limits<uint64_t>::max(), vk.swap.image_available, VK_NULL_HANDLE, &imageIndex ); VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkSemaphore waitSemaphores[] = {vk.swap.image_available}; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = waitSemaphores; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &vk.swap.command_buffers[imageIndex]; VkSemaphore signalSemaphores[] = {vk.swap.render_finished}; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = signalSemaphores; result = vkQueueSubmit(vk.queues.graphics.q, 1, &submitInfo, VK_NULL_HANDLE); if (result == VK_ERROR_OUT_OF_HOST_MEMORY) { throw std::runtime_error("Could not submit to graphics queue: out of host memory."); } else if (result == VK_ERROR_OUT_OF_DEVICE_MEMORY) { throw std::runtime_error("Could not submit to graphics queue: out of device memory."); } else if (result == VK_ERROR_DEVICE_LOST) { throw std::runtime_error("Could not submit to graphics queue: device lost."); } else if (result != VK_SUCCESS) { throw std::runtime_error("Could not submit to graphics queue for unknown reason."); }; VkPresentInfoKHR presentInfo = {}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = signalSemaphores; VkSwapchainKHR swapChains[] = {vk.swap.h}; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = swapChains; presentInfo.pImageIndices = &imageIndex; /* NOTE(jan): For returning VkResults for multiple swap chains. */ presentInfo.pResults = nullptr; vkQueuePresentKHR(vk.queues.present.q, &presentInfo); vkQueueWaitIdle(vk.queues.present.q); this_f = std::chrono::high_resolution_clock::now(); delta_f = std::chrono::duration< float, std::chrono::seconds::period>(this_f - last_f).count(); total_delta_f = std::chrono::duration< float, std::chrono::seconds::period>(this_f - start_f).count(); frame_count++; frameTimeFile << frame_count << ", " << delta_f * 1000 << std::endl; float fps = 1.0f / delta_f; char title[255]; snprintf( title, 255, "avg_ms_d: %f ms_d: %f FPS: %f", total_delta_f * 1000 / frame_count, delta_f*1000, fps ); glfwSetWindowTitle(window, title); glfwPollEvents(); /* NOTE(jan): Mouse look. */ { double delta_angle = 3.14; Coord mouse_position_this_frame, mouse_delta; glfwGetCursorPos( window, &mouse_position_this_frame.x, &mouse_position_this_frame.y ); mouse_delta = { mouse_position_this_frame.x - mouse_position_last_frame.x, mouse_position_this_frame.y - mouse_position_last_frame.y }; mouse_position_last_frame = { mouse_position_this_frame.x, mouse_position_this_frame.y }; Coord scaled = { mouse_delta.x / WINDOW_WIDTH, mouse_delta.y / WINDOW_HEIGHT }; Coord rotation = { /* NOTE(jan): Positive rotation is clockwise. */ scaled.x * delta_angle * (-1), scaled.y * delta_angle }; glm::vec3 d(glm::normalize(at - eye)); glm::vec3 right = glm::normalize(glm::cross(d, up)); glm::mat4 rot(1.0f); rot = glm::rotate(rot, (float)rotation.y, right); rot = glm::rotate(rot, (float)rotation.x, up); glm::vec4 d4(d, 0.f); d4 = rot * d4; d = glm::normalize(glm::vec3(d4)); d = glm::vec3(d4.x, d4.y, d4.z); at = eye + d; } /* NOTE(jan): Movement. */ auto delta = 2.f; if (keyboard[GLFW_KEY_W] == GLFW_PRESS) { glm::vec3 forward = at - eye; forward.y = 0.0f; forward = glm::normalize(forward); eye += forward * delta * delta_f; at += forward * delta * delta_f; } if (keyboard[GLFW_KEY_S] == GLFW_PRESS) { glm::vec3 backward = glm::normalize(eye - at); eye += backward * delta * delta_f; at += backward * delta * delta_f; } if (keyboard[GLFW_KEY_A] == GLFW_PRESS) { glm::vec3 forward = glm::normalize(at - eye); glm::vec3 right = glm::cross(forward, up); glm::vec3 left = right * -1.f; eye += left * delta * delta_f; at += left * delta * delta_f; } if (keyboard[GLFW_KEY_D] == GLFW_PRESS) { glm::vec3 forward = glm::normalize(at - eye); glm::vec3 right = glm::cross(forward, up); eye += right * delta * delta_f; at += right * delta * delta_f; } if (keyboard[GLFW_KEY_Z] == GLFW_PRESS) { eye.x = 100; eye.y = -1; eye.z = 100; at.x = 0; at.z = 0; glm::vec3 forward = glm::normalize(at - eye); glm::vec3 right = glm::cross(forward, up); eye += right * delta * delta_f; at += right * delta * delta_f; } if (keyboard[GLFW_KEY_X] == GLFW_PRESS) { eye.x = 0; eye.y = -1; eye.z = 0; at.x = 100; at.z = 100; glm::vec3 forward = glm::normalize(at - eye); glm::vec3 right = glm::cross(forward, up); eye += right * delta * delta_f; at += right * delta * delta_f; } if (keyboard[GLFW_KEY_SPACE] == GLFW_PRESS) { eye -= up * delta * delta_f; at -= up * delta * delta_f; } if (keyboard[GLFW_KEY_LEFT_SHIFT] == GLFW_PRESS) { glm::vec3 down = up * -1.f; eye -= down * delta * delta_f; at -= down * delta * delta_f; } scene.mvp.view = glm::lookAt(eye, at, up); if (keyboard[GLFW_KEY_P] == GLFW_PRESS) { LOG(INFO) << "eye(" << eye.x << " " << eye.y << " " << eye.z << ")"; LOG(INFO) << "at(" << at.x << " " << at.y << " " << at.z << ")"; } } frameTimeFile.close(); /* NOTE(jan): Wait for everything to complete before we start destroying * stuff. */ LOG(INFO) << "Received exit request. Completing in-progress frames..."; vkDeviceWaitIdle(vk.device); /* NOTE(jan): Clean up Vulkan objects. */ LOG(INFO) << "Cleaning up..."; auto vkDestroyCallback = (PFN_vkDestroyDebugReportCallbackEXT) vkGetInstanceProcAddr( vk.h, "vkDestroyDebugReportCallbackEXT" ); #ifndef NDEBUG if (vkDestroyCallback != nullptr) { vkDestroyCallback(vk.h, callback_debug, nullptr); } #endif vkDestroySemaphore(vk.device, vk.swap.render_finished, nullptr); vkDestroySemaphore(vk.device, vk.swap.image_available, nullptr); vkDestroyImageView(vk.device, scene.colour.v, nullptr); vkFreeMemory(vk.device, scene.colour.m, nullptr); vkDestroyImage(vk.device, scene.colour.i, nullptr); vkDestroyImageView(vk.device, scene.depth.v, nullptr); vkFreeMemory(vk.device, scene.depth.m, nullptr); vkDestroyImage(vk.device, scene.depth.i, nullptr); vkDestroySampler(vk.device, scene.grassTexture.s, nullptr); vkDestroyImageView(vk.device, scene.grassTexture.v, nullptr); vkDestroyImage(vk.device, scene.grassTexture.i, nullptr); vkDestroySampler(vk.device, scene.groundTexture.s, nullptr); vkDestroyImageView(vk.device, scene.groundTexture.v, nullptr); vkDestroyImage(vk.device, scene.groundTexture.i, nullptr); vkDestroySampler(vk.device, scene.noise.s, nullptr); vkDestroyImageView(vk.device, scene.noise.v, nullptr); vkDestroyImage(vk.device, scene.noise.i, nullptr); vkFreeMemory(vk.device, scene.grassTexture.m, nullptr); vkFreeMemory(vk.device, scene.groundTexture.m, nullptr); vkFreeMemory(vk.device, scene.noise.m, nullptr); vkFreeMemory(vk.device, scene.indices.memory, nullptr); vkDestroyBuffer(vk.device, scene.indices.buffer, nullptr); vkFreeMemory(vk.device, scene.vertices.memory, nullptr); vkDestroyBuffer(vk.device, scene.vertices.buffer, nullptr); vkFreeMemory(vk.device, groundBuffer.memory, nullptr); vkDestroyBuffer(vk.device, groundBuffer.buffer, nullptr); vkFreeMemory(vk.device, scene.uniforms.memory, nullptr); vkDestroyBuffer(vk.device, scene.uniforms.buffer, nullptr); vkDestroyDescriptorPool( vk.device, defaultDescriptorPool, nullptr ); vkDestroyCommandPool(vk.device, vk.commandPool, nullptr); for (const auto& f: vk.swap.frames) { vkDestroyFramebuffer(vk.device, f, nullptr); } vkDestroyPipeline(vk.device, grassPipeline.handle, nullptr); vkDestroyPipelineLayout(vk.device, grassPipeline.layout, nullptr); vkDestroyDescriptorSetLayout( vk.device, defaultDescriptorSetLayout, nullptr ); vkDestroyRenderPass(vk.device, defaultRenderPass, nullptr); vkDestroyPipeline(vk.device, groundPipeline.handle, nullptr); vkDestroyPipelineLayout(vk.device, groundPipeline.layout, nullptr); for (const auto& i: vk.swap.images) { vkDestroyImageView(vk.device, i.v, nullptr); } vkDestroySwapchainKHR(vk.device, vk.swap.h, nullptr); vkDestroyDevice(vk.device, nullptr); vkDestroySurfaceKHR(vk.h, vk.surface, nullptr); vkDestroyInstance(vk.h, nullptr); /* NOTE(jan): Clean up GLFW. */ glfwDestroyWindow(window); glfwTerminate(); LOG(INFO) << "Exiting cleanly."; return 0; }
36.390295
89
0.593348
fluffels
434339a9051a37c24f755588b6f57997b0898001
19,515
cpp
C++
3rdParty/_DKIMPORTS/librocket/Source/Core/Factory.cpp
aquawicket/DigitalKnob
9e5997a1f0314ede80cf66a9bf28dc6373cb5987
[ "MIT" ]
29
2015-05-03T06:23:22.000Z
2022-02-10T15:16:26.000Z
3rdParty/_DKIMPORTS/librocket/Source/Core/Factory.cpp
aquawicket/DigitalKnob
9e5997a1f0314ede80cf66a9bf28dc6373cb5987
[ "MIT" ]
125
2016-02-28T06:13:49.000Z
2022-01-04T11:50:08.000Z
3rdParty/_DKIMPORTS/librocket/Source/Core/Factory.cpp
aquawicket/DigitalKnob
9e5997a1f0314ede80cf66a9bf28dc6373cb5987
[ "MIT" ]
8
2016-12-04T02:29:34.000Z
2022-01-04T01:11:25.000Z
/* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include "precompiled.h" #include "../../Include/Rocket/Core.h" #include "../../Include/Rocket/Core/StreamMemory.h" #include "ContextInstancerDefault.h" #include "DecoratorNoneInstancer.h" #include "DecoratorTiledBoxInstancer.h" #include "DecoratorTiledHorizontalInstancer.h" #include "DecoratorTiledImageInstancer.h" #include "DecoratorTiledVerticalInstancer.h" #include "ElementHandle.h" #include "ElementImage.h" #include "ElementTextDefault.h" #include "EventInstancerDefault.h" #include "FontEffectNoneInstancer.h" #include "FontEffectOutlineInstancer.h" #include "FontEffectShadowInstancer.h" #include "PluginRegistry.h" #include "PropertyParserColour.h" #include "StreamFile.h" #include "StyleSheetFactory.h" #include "TemplateCache.h" #include "XMLNodeHandlerBody.h" #include "XMLNodeHandlerDefault.h" #include "XMLNodeHandlerHead.h" #include "XMLNodeHandlerHtml.h" #include "XMLNodeHandlerTemplate.h" #include "XMLParseTools.h" namespace Rocket { namespace Core { // Element instancers. typedef std::map< String, ElementInstancer* > ElementInstancerMap; static ElementInstancerMap element_instancers; // Decorator instancers. typedef std::map< String, DecoratorInstancer* > DecoratorInstancerMap; static DecoratorInstancerMap decorator_instancers; // Font effect instancers. typedef std::map< String, FontEffectInstancer* > FontEffectInstancerMap; static FontEffectInstancerMap font_effect_instancers; // The context instancer. static ContextInstancer* context_instancer = NULL; // The event instancer static EventInstancer* event_instancer = NULL; // Event listener instancer. static EventListenerInstancer* event_listener_instancer = NULL; Factory::Factory() { } Factory::~Factory() { } bool Factory::Initialise() { // Bind the default context instancer. if (context_instancer == NULL) context_instancer = new ContextInstancerDefault(); // Bind default event instancer if (event_instancer == NULL) event_instancer = new EventInstancerDefault(); // No default event listener instancer if (event_listener_instancer == NULL) event_listener_instancer = NULL; // Bind the default element instancers RegisterElementInstancer("*", new ElementInstancerGeneric< Element >())->RemoveReference(); RegisterElementInstancer("img", new ElementInstancerGeneric< ElementImage >())->RemoveReference(); RegisterElementInstancer("#text", new ElementInstancerGeneric< ElementTextDefault >())->RemoveReference(); RegisterElementInstancer("handle", new ElementInstancerGeneric< ElementHandle >())->RemoveReference(); RegisterElementInstancer("body", new ElementInstancerGeneric< Element >())->RemoveReference(); RegisterElementInstancer("html", new ElementInstancerGeneric< ElementDocument >())->RemoveReference(); // Bind the default decorator instancers RegisterDecoratorInstancer("tiled-horizontal", new DecoratorTiledHorizontalInstancer())->RemoveReference(); RegisterDecoratorInstancer("tiled-vertical", new DecoratorTiledVerticalInstancer())->RemoveReference(); RegisterDecoratorInstancer("tiled-box", new DecoratorTiledBoxInstancer())->RemoveReference(); RegisterDecoratorInstancer("image", new DecoratorTiledImageInstancer())->RemoveReference(); RegisterDecoratorInstancer("none", new DecoratorNoneInstancer())->RemoveReference(); RegisterFontEffectInstancer("shadow", new FontEffectShadowInstancer())->RemoveReference(); RegisterFontEffectInstancer("outline", new FontEffectOutlineInstancer())->RemoveReference(); RegisterFontEffectInstancer("none", new FontEffectNoneInstancer())->RemoveReference(); // Register the core XML node handlers. XMLParser::RegisterNodeHandler("", new XMLNodeHandlerDefault())->RemoveReference(); XMLParser::RegisterNodeHandler("body", new XMLNodeHandlerBody())->RemoveReference(); XMLParser::RegisterNodeHandler("html", new XMLNodeHandlerHtml())->RemoveReference(); XMLParser::RegisterNodeHandler("head", new XMLNodeHandlerHead())->RemoveReference(); XMLParser::RegisterNodeHandler("template", new XMLNodeHandlerTemplate())->RemoveReference(); return true; } void Factory::Shutdown() { for (ElementInstancerMap::iterator i = element_instancers.begin(); i != element_instancers.end(); ++i) (*i).second->RemoveReference(); element_instancers.clear(); for (DecoratorInstancerMap::iterator i = decorator_instancers.begin(); i != decorator_instancers.end(); ++i) (*i).second->RemoveReference(); decorator_instancers.clear(); for (FontEffectInstancerMap::iterator i = font_effect_instancers.begin(); i != font_effect_instancers.end(); ++i) (*i).second->RemoveReference(); font_effect_instancers.clear(); if (context_instancer) context_instancer->RemoveReference(); context_instancer = NULL; if (event_listener_instancer) event_listener_instancer->RemoveReference(); event_listener_instancer = NULL; if (event_instancer) event_instancer->RemoveReference(); event_instancer = NULL; XMLParser::ReleaseHandlers(); } // Registers the instancer to use when instancing contexts. ContextInstancer* Factory::RegisterContextInstancer(ContextInstancer* instancer) { instancer->AddReference(); if (context_instancer != NULL) context_instancer->RemoveReference(); context_instancer = instancer; return instancer; } // Instances a new context. Context* Factory::InstanceContext(const String& name) { Context* new_context = context_instancer->InstanceContext(name); if (new_context != NULL) new_context->SetInstancer(context_instancer); return new_context; } ElementInstancer* Factory::RegisterElementInstancer(const String& name, ElementInstancer* instancer) { String lower_case_name = name.ToLower(); instancer->AddReference(); // Check if an instancer for this tag is already defined, if so release it ElementInstancerMap::iterator itr = element_instancers.find(lower_case_name); if (itr != element_instancers.end()) { (*itr).second->RemoveReference(); } element_instancers[lower_case_name] = instancer; return instancer; } // Looks up the instancer for the given element ElementInstancer* Factory::GetElementInstancer(const String& tag) { ElementInstancerMap::iterator instancer_iterator = element_instancers.find(tag); if (instancer_iterator == element_instancers.end()) { instancer_iterator = element_instancers.find("*"); if (instancer_iterator == element_instancers.end()) return NULL; } return (*instancer_iterator).second; } // Instances a single element. Element* Factory::InstanceElement(Element* parent, const String& instancer_name, const String& tag, const XMLAttributes& attributes) { ElementInstancer* instancer = GetElementInstancer(instancer_name); if (instancer) { Element* element = instancer->InstanceElement(parent, tag, attributes); // Process the generic attributes and bind any events if (element) { element->SetInstancer(instancer); element->SetAttributes(&attributes); ElementUtilities::BindEventAttributes(element); PluginRegistry::NotifyElementCreate(element); } return element; } return NULL; } // Instances a single text element containing a string. bool Factory::InstanceElementText(Element* parent, const String& text) { SystemInterface* system_interface = GetSystemInterface(); // Do any necessary translation. If any substitutions were made then new XML may have been introduced, so we'll // have to run the data through the XML parser again. String translated_data; if (system_interface != NULL && (system_interface->TranslateString(translated_data, text) > 0 || translated_data.Find("<") != String::npos)) { StreamMemory* stream = new StreamMemory(translated_data.Length() + 32); stream->Write("<html>", 6); stream->Write(translated_data); stream->Write("</html>", 7); stream->Seek(0, SEEK_SET); InstanceElementStream(parent, stream); stream->RemoveReference(); } else { // Check if this text node contains only white-space; if so, we don't want to construct it. bool only_white_space = true; for (size_t i = 0; i < translated_data.Length(); ++i) { if (!StringUtilities::IsWhitespace(translated_data[i])) { only_white_space = false; break; } } if (only_white_space) return true; // Attempt to instance the element. XMLAttributes attributes; Element* element = Factory::InstanceElement(parent, "#text", "#text", attributes); if (!element) { Log::Message(Log::LT_ERROR, "Failed to instance text element '%s', instancer returned NULL.", translated_data.CString()); return false; } // Assign the element its text value. ElementText* text_element = dynamic_cast< ElementText* >(element); if (text_element == NULL) { Log::Message(Log::LT_ERROR, "Failed to instance text element '%s'. Found type '%s', was expecting a derivative of ElementText.", translated_data.CString(), typeid(element).name()); element->RemoveReference(); return false; } text_element->SetText(translated_data); // Add to active node. parent->AppendChild(element); element->RemoveReference(); } return true; } // Instances a element tree based on the stream bool Factory::InstanceElementStream(Element* parent, Stream* stream) { XMLParser parser(parent); parser.Parse(stream); return true; } // Instances a element tree based on the stream ElementDocument* Factory::InstanceDocumentStream(Rocket::Core::Context* context, Stream* stream) { Element* element = Factory::InstanceElement(NULL, "html", "html", XMLAttributes()); if (!element) { Log::Message(Log::LT_ERROR, "Failed to instance document, instancer returned NULL."); return NULL; } ElementDocument* document = dynamic_cast< ElementDocument* >(element); if (!document) { Log::Message(Log::LT_ERROR, "Failed to instance document element. Found type '%s', was expecting derivative of ElementDocument.", typeid(element).name()); return NULL; } document->lock_layout = true; document->context = context; XMLParser parser(element); parser.Parse(stream); document->lock_layout = false; return document; } // Registers an instancer that will be used to instance decorators. DecoratorInstancer* Factory::RegisterDecoratorInstancer(const String& name, DecoratorInstancer* instancer) { String lower_case_name = name.ToLower(); instancer->AddReference(); // Check if an instancer for this tag is already defined. If so, release it. DecoratorInstancerMap::iterator iterator = decorator_instancers.find(lower_case_name); if (iterator != decorator_instancers.end()) (*iterator).second->RemoveReference(); decorator_instancers[lower_case_name] = instancer; return instancer; } // Attempts to instance a decorator from an instancer registered with the factory. Decorator* Factory::InstanceDecorator(const String& name, const PropertyDictionary& properties) { float z_index = 0; int specificity = -1; DecoratorInstancerMap::iterator iterator = decorator_instancers.find(name); if (iterator == decorator_instancers.end()) return NULL; // Turn the generic, un-parsed properties we've got into a properly parsed dictionary. const PropertySpecification& property_specification = (*iterator).second->GetPropertySpecification(); PropertyDictionary parsed_properties; for (PropertyMap::const_iterator i = properties.GetProperties().begin(); i != properties.GetProperties().end(); ++i) { specificity = Math::Max(specificity, (*i).second.specificity); // Check for the 'z-index' property; we don't want to send this through. if ((*i).first == Z_INDEX) z_index = (*i).second.value.Get< float >(); else property_specification.ParsePropertyDeclaration(parsed_properties, (*i).first, (*i).second.value.Get< String >(), (*i).second.source, (*i).second.source_line_number); } // Set the property defaults for all unset properties. property_specification.SetPropertyDefaults(parsed_properties); Decorator* decorator = (*iterator).second->InstanceDecorator(name, parsed_properties); if (decorator == NULL) return NULL; decorator->SetZIndex(z_index); decorator->SetSpecificity(specificity); decorator->instancer = (*iterator).second; return decorator; } // Registers an instancer that will be used to instance font effects. FontEffectInstancer* Factory::RegisterFontEffectInstancer(const String& name, FontEffectInstancer* instancer) { String lower_case_name = name.ToLower(); instancer->AddReference(); // Check if an instancer for this tag is already defined. If so, release it. FontEffectInstancerMap::iterator iterator = font_effect_instancers.find(lower_case_name); if (iterator != font_effect_instancers.end()) (*iterator).second->RemoveReference(); font_effect_instancers[lower_case_name] = instancer; return instancer; } // Attempts to instance a font effect from an instancer registered with the factory. FontEffect* Factory::InstanceFontEffect(const String& name, const PropertyDictionary& properties) { bool set_colour = false; Colourb colour(255, 255, 255); bool set_z_index = false; float z_index = 0; int specificity = -1; FontEffectInstancerMap::iterator iterator = font_effect_instancers.find(name); if (iterator == font_effect_instancers.end()) return NULL; FontEffectInstancer* instancer = iterator->second; // Turn the generic, un-parsed properties we've got into a properly parsed dictionary. const PropertySpecification& property_specification = (*iterator).second->GetPropertySpecification(); PropertyDictionary parsed_properties; for (PropertyMap::const_iterator i = properties.GetProperties().begin(); i != properties.GetProperties().end(); ++i) { specificity = Math::Max(specificity, i->second.specificity); // Check for the 'z-index' property; we don't want to send this through. if (i->first == Z_INDEX) { set_z_index = true; z_index = i->second.value.Get< float >(); } else if (i->first == COLOR) { static PropertyParserColour colour_parser; Property colour_property; if (colour_parser.ParseValue(colour_property, i->second.value.Get< String >(), ParameterMap())) { colour = colour_property.value.Get< Colourb >(); set_colour = true; } } else { property_specification.ParsePropertyDeclaration(parsed_properties, (*i).first, (*i).second.value.Get< String >(), (*i).second.source, (*i).second.source_line_number); } } // Set the property defaults for all unset properties. property_specification.SetPropertyDefaults(parsed_properties); // Compile an ordered list of the values of the properties used to generate the effect's // textures and geometry. typedef std::list< std::pair< String, String > > GenerationPropertyList; GenerationPropertyList generation_properties; for (PropertyMap::const_iterator i = parsed_properties.GetProperties().begin(); i != parsed_properties.GetProperties().end(); ++i) { if (instancer->volatile_properties.find(i->first) != instancer->volatile_properties.end()) { GenerationPropertyList::iterator j = generation_properties.begin(); while (j != generation_properties.end() && j->first < i->first) ++j; generation_properties.insert(j, GenerationPropertyList::value_type(i->first, i->second.value.Get< String >())); } } String generation_key; for (GenerationPropertyList::iterator i = generation_properties.begin(); i != generation_properties.end(); ++i) { generation_key += i->second; generation_key += ";"; } // Now we can actually instance the effect! FontEffect* font_effect = (*iterator).second->InstanceFontEffect(name, parsed_properties); if (font_effect == NULL) return NULL; font_effect->name = name; font_effect->generation_key = generation_key; if (set_z_index) font_effect->SetZIndex(z_index); if (set_colour) font_effect->SetColour(colour); font_effect->SetSpecificity(specificity); font_effect->instancer = (*iterator).second; return font_effect; } // Creates a style sheet containing the passed in styles. StyleSheet* Factory::InstanceStyleSheetString(const String& string) { StreamMemory* memory_stream = new StreamMemory((const byte*) string.CString(), string.Length()); StyleSheet* style_sheet = InstanceStyleSheetStream(memory_stream); memory_stream->RemoveReference(); return style_sheet; } // Creates a style sheet from a file. StyleSheet* Factory::InstanceStyleSheetFile(const String& file_name) { StreamFile* file_stream = new StreamFile(); file_stream->Open(file_name); StyleSheet* style_sheet = InstanceStyleSheetStream(file_stream); file_stream->RemoveReference(); return style_sheet; } // Creates a style sheet from an Stream. StyleSheet* Factory::InstanceStyleSheetStream(Stream* stream) { StyleSheet* style_sheet = new StyleSheet(); if (style_sheet->LoadStyleSheet(stream)) { return style_sheet; } style_sheet->RemoveReference(); return NULL; } // Clears the style sheet cache. This will force style sheets to be reloaded. void Factory::ClearStyleSheetCache() { StyleSheetFactory::ClearStyleSheetCache(); } /// Clears the template cache. This will force templates to be reloaded. void Factory::ClearTemplateCache() { TemplateCache::Clear(); } // Registers an instancer for all RKTEvents EventInstancer* Factory::RegisterEventInstancer(EventInstancer* instancer) { instancer->AddReference(); if (event_instancer) event_instancer->RemoveReference(); event_instancer = instancer; return instancer; } // Instance an event object. Event* Factory::InstanceEvent(Element* target, const String& name, const Dictionary& parameters, bool interruptible) { Event* event = event_instancer->InstanceEvent(target, name, parameters, interruptible); if (event != NULL) event->instancer = event_instancer; return event; } // Register an instancer for all event listeners EventListenerInstancer* Factory::RegisterEventListenerInstancer(EventListenerInstancer* instancer) { instancer->AddReference(); if (event_listener_instancer) event_listener_instancer->RemoveReference(); event_listener_instancer = instancer; return instancer; } // Instance an event listener with the given string EventListener* Factory::InstanceEventListener(const String& value, Element* element) { // If we have an event listener instancer, use it if (event_listener_instancer) return event_listener_instancer->InstanceEventListener(value, element); return NULL; } } }
33.132428
183
0.762234
aquawicket
4344e306bbf124aee69a51773bcd881845233e18
815
cpp
C++
test/src/huffman_node.test.cpp
hhsdev/huffman-compression
5c538f54a37c5ada3117c92ec70428a01c75d113
[ "MIT" ]
null
null
null
test/src/huffman_node.test.cpp
hhsdev/huffman-compression
5c538f54a37c5ada3117c92ec70428a01c75d113
[ "MIT" ]
null
null
null
test/src/huffman_node.test.cpp
hhsdev/huffman-compression
5c538f54a37c5ada3117c92ec70428a01c75d113
[ "MIT" ]
null
null
null
#include "catch.hpp" #include "huffman_node.hpp" TEST_CASE("HuffmanNode", "[HuffmanNode]") { HuffmanNode leafNode1('a', 3); HuffmanNode leafNode2('b', 5); HuffmanNode branchNode(leafNode1, leafNode2); SECTION("Constructors") { REQUIRE(leafNode1.getChar() == 'a'); REQUIRE(leafNode1.getFrequency() == 3); REQUIRE(leafNode2.getChar() == 'b'); REQUIRE(leafNode2.getFrequency() == 5); REQUIRE(branchNode.getChar() == -1); REQUIRE(branchNode.getFrequency() == leafNode1.getFrequency() + leafNode2.getFrequency()); } SECTION("Comparisons") { REQUIRE(leafNode1 < leafNode2); REQUIRE(leafNode1 <= leafNode2); REQUIRE(leafNode2 > leafNode1); REQUIRE(leafNode2 >= leafNode1); REQUIRE(leafNode1 == leafNode1); REQUIRE(leafNode1 != leafNode2); } }
27.166667
65
0.662577
hhsdev
4346b465026ef9b02acbdb62fdada96589e4305a
7,469
cpp
C++
source/worker_url.cpp
DynasticSponge/erasmus
daaf81ee03a71cd532b744488eb164df12c4c9ec
[ "MIT" ]
null
null
null
source/worker_url.cpp
DynasticSponge/erasmus
daaf81ee03a71cd532b744488eb164df12c4c9ec
[ "MIT" ]
null
null
null
source/worker_url.cpp
DynasticSponge/erasmus
daaf81ee03a71cd532b744488eb164df12c4c9ec
[ "MIT" ]
null
null
null
// // worker_url.cpp // ~~~~~~~~~~~~~~ // // Author: Joseph Adomatis // Copyright (c) 2020 Joseph R Adomatis (joseph dot adomatis at gmail dot com) // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <cctype> #include <string> #include "../headers/erasmus_namespace.hpp" #include "../headers/erasmus_director.hpp" #include "../headers/worker_numeric.hpp" #include "../headers/worker_url.hpp" using namespace erasmus; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // global variable definitions /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // global function definitions /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // erasmus::workerURL member definitions /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Constructors /////////////////////////////////////////////////////////////////////////////// workerURL::workerURL() { this->director = nullptr; this->numericWorker = nullptr; } workerURL::workerURL(erasmus::director *newDirector) { this->director = newDirector; this->numericWorker = nullptr; } /////////////////////////////////////////////////////////////////////////////// // erasmus::workerURL::charDecode /////////////////////////////////////////////////////////////////////////////// bool workerURL::charDecode(const std::string& original, char& revised) { bool returnValue{true}; bool useNumericWorker{this->initNumericWorker()}; bool goodInput{original[0] == '%'}; if(useNumericWorker) { goodInput &= this->numericWorker->isHex(original[1]); goodInput &= this->numericWorker->isHex(original[2]); } else { goodInput &= this->director->isHex(original[1]); goodInput &= this->director->isHex(original[2]); } if(goodInput) { int numVal{std::stoi(original.substr(1, 2), 0, 16)}; char outChar{static_cast<char>(numVal)}; revised = std::move(outChar); } else { returnValue = false; } return(returnValue); } /////////////////////////////////////////////////////////////////////////////// // erasmus::workerURL::charEncode /////////////////////////////////////////////////////////////////////////////// bool workerURL::charEncode(char original, std::string& revised) { bool returnValue{true}; bool useNumericWorker{this->initNumericWorker()}; bool encodeSuccess{true}; std::string bldStr; if(useNumericWorker) { encodeSuccess = this->numericWorker->charToHex(original, bldStr); } else { encodeSuccess = this->director->charToHex(original, bldStr); } if(encodeSuccess){ bldStr.insert(0,"%"); revised = std::move(bldStr); } else { returnValue = false; } return(returnValue); } /////////////////////////////////////////////////////////////////////////////// // erasmus::workerURL::initNumericWorker /////////////////////////////////////////////////////////////////////////////// bool workerURL::initNumericWorker() { bool returnValue{true}; if(this->numericWorker == nullptr) { if(this->director == nullptr) { this->numericWorker = new workerNumeric(); } else { returnValue = false; } } return(returnValue); } /////////////////////////////////////////////////////////////////////////////// // erasmus::workerURL::urlDecode /////////////////////////////////////////////////////////////////////////////// bool workerURL::urlDecode(const std::string& original, std::string& revised) { bool returnValue{true}; size_t maxBound{original.size()}; size_t maxHexBound{(original.size() - 2)}; std::string bldStr; for(size_t index = 0; index < maxBound && returnValue; index++) { char c0{original[index]}; if (c0 == '%') { // verify % has at least 2 chars after it if(index < maxHexBound) { char decodedChar{'\0'}; if(this->charDecode(original.substr(index,3), decodedChar)) { bldStr.push_back(decodedChar); index += 2; } else { // invalid hex chars returnValue = false; } } else { // not enough chars after % returnValue = false; } } else if(c0 == '+') { // + decodes to <space> bldStr.push_back(' '); } else { // character wasnt an encoded character bldStr.push_back(c0); } } // update revised with bldStr revised = std::move(bldStr); return(returnValue); } /////////////////////////////////////////////////////////////////////////////// // erasmus::workerURL::urlEncode /////////////////////////////////////////////////////////////////////////////// bool workerURL::urlEncode(const std::string& original, std::string& revised) { bool returnValue{true}; std::string bldStr; std::string workingStr; for(size_t index = 0; index < original.size() && returnValue; index++) { char c0{original[index]}; // determine if c0 is url safe bool safeChar{static_cast<bool>(isalnum(c0))}; safeChar |= (c0 == '-'); safeChar |= (c0 == '.'); safeChar |= (c0 == '_'); safeChar |= (c0 == '~'); if(!safeChar) { // encode the unsafe char if(this->charEncode(c0, workingStr)) { // encode success, append to bldStr bldStr.append(workingStr); workingStr.clear(); } else { // encode failed returnValue = false; } } /* else if(c0 == ' ') { // char is <space> encode as '%20' and append to bldStr bldStr.append("%20"); } */ else { // safe char... append to bldStr bldStr.push_back(c0); } } if(returnValue) { // no errors, update revised revised = std::move(bldStr); } return(returnValue); } /////////////////////////////////////////////////////////////////////////////// // Deconstructor /////////////////////////////////////////////////////////////////////////////// workerURL::~workerURL() { this->director = nullptr; if(this->numericWorker != nullptr) { delete this->numericWorker; this->numericWorker = nullptr; } }
28.616858
119
0.391619
DynasticSponge
43478dfda4272168c0934f1de8c0ecfa53171891
1,587
cc
C++
src/tint/ast/vector.cc
encounter/dawn-cmake
64a23ce0ede5f232cc209b69d64164ede6810b65
[ "Apache-2.0" ]
null
null
null
src/tint/ast/vector.cc
encounter/dawn-cmake
64a23ce0ede5f232cc209b69d64164ede6810b65
[ "Apache-2.0" ]
null
null
null
src/tint/ast/vector.cc
encounter/dawn-cmake
64a23ce0ede5f232cc209b69d64164ede6810b65
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Tint Authors. // // 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 "src/tint/ast/vector.h" #include "src/tint/program_builder.h" TINT_INSTANTIATE_TYPEINFO(tint::ast::Vector); namespace tint::ast { Vector::Vector(ProgramID pid, Source const& src, const Type* subtype, uint32_t w) : Base(pid, src), type(subtype), width(w) { TINT_ASSERT_PROGRAM_IDS_EQUAL_IF_VALID(AST, subtype, program_id); TINT_ASSERT(AST, width > 1); TINT_ASSERT(AST, width < 5); } Vector::Vector(Vector&&) = default; Vector::~Vector() = default; std::string Vector::FriendlyName(const SymbolTable& symbols) const { std::ostringstream out; out << "vec" << width; if (type) { out << "<" << type->FriendlyName(symbols) << ">"; } return out.str(); } const Vector* Vector::Clone(CloneContext* ctx) const { // Clone arguments outside of create() call to have deterministic ordering auto src = ctx->Clone(source); auto* ty = ctx->Clone(type); return ctx->dst->create<Vector>(src, ty, width); } } // namespace tint::ast
31.117647
81
0.695022
encounter
4348cd3ba2a16f60e989232ad7d3dab053417f47
2,144
cpp
C++
cpp/godot-cpp/src/gen/Joint2D.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
1
2021-03-16T09:51:00.000Z
2021-03-16T09:51:00.000Z
cpp/godot-cpp/src/gen/Joint2D.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
cpp/godot-cpp/src/gen/Joint2D.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
#include "Joint2D.hpp" #include <core/GodotGlobal.hpp> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include <core/Godot.hpp> #include "__icalls.hpp" namespace godot { Joint2D::___method_bindings Joint2D::___mb = {}; void Joint2D::___init_method_bindings() { ___mb.mb_get_bias = godot::api->godot_method_bind_get_method("Joint2D", "get_bias"); ___mb.mb_get_exclude_nodes_from_collision = godot::api->godot_method_bind_get_method("Joint2D", "get_exclude_nodes_from_collision"); ___mb.mb_get_node_a = godot::api->godot_method_bind_get_method("Joint2D", "get_node_a"); ___mb.mb_get_node_b = godot::api->godot_method_bind_get_method("Joint2D", "get_node_b"); ___mb.mb_set_bias = godot::api->godot_method_bind_get_method("Joint2D", "set_bias"); ___mb.mb_set_exclude_nodes_from_collision = godot::api->godot_method_bind_get_method("Joint2D", "set_exclude_nodes_from_collision"); ___mb.mb_set_node_a = godot::api->godot_method_bind_get_method("Joint2D", "set_node_a"); ___mb.mb_set_node_b = godot::api->godot_method_bind_get_method("Joint2D", "set_node_b"); } real_t Joint2D::get_bias() const { return ___godot_icall_float(___mb.mb_get_bias, (const Object *) this); } bool Joint2D::get_exclude_nodes_from_collision() const { return ___godot_icall_bool(___mb.mb_get_exclude_nodes_from_collision, (const Object *) this); } NodePath Joint2D::get_node_a() const { return ___godot_icall_NodePath(___mb.mb_get_node_a, (const Object *) this); } NodePath Joint2D::get_node_b() const { return ___godot_icall_NodePath(___mb.mb_get_node_b, (const Object *) this); } void Joint2D::set_bias(const real_t bias) { ___godot_icall_void_float(___mb.mb_set_bias, (const Object *) this, bias); } void Joint2D::set_exclude_nodes_from_collision(const bool enable) { ___godot_icall_void_bool(___mb.mb_set_exclude_nodes_from_collision, (const Object *) this, enable); } void Joint2D::set_node_a(const NodePath node) { ___godot_icall_void_NodePath(___mb.mb_set_node_a, (const Object *) this, node); } void Joint2D::set_node_b(const NodePath node) { ___godot_icall_void_NodePath(___mb.mb_set_node_b, (const Object *) this, node); } }
34.580645
133
0.788246
GDNative-Gradle
43491864b7e19f03d3bf1929f865b3c3d9a03b96
49,954
cc
C++
src/couch_db.cc
sduvuru/couchstore
0ddb502b5b32aaa728e3323bd5d447f467f77966
[ "Apache-2.0" ]
null
null
null
src/couch_db.cc
sduvuru/couchstore
0ddb502b5b32aaa728e3323bd5d447f467f77966
[ "Apache-2.0" ]
null
null
null
src/couch_db.cc
sduvuru/couchstore
0ddb502b5b32aaa728e3323bd5d447f467f77966
[ "Apache-2.0" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "config.h" #include <fcntl.h> #include <platform/cb_malloc.h> #include <phosphor/phosphor.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <stdio.h> #include "internal.h" #include "node_types.h" #include "couch_btree.h" #include "bitfield.h" #include "reduces.h" #include "util.h" #include "couch_latency_internal.h" #define ROOT_BASE_SIZE 12 #define HEADER_BASE_SIZE 25 #if __APPLE__ /* * Apple's clang disables thread_local keyword support */ __thread char internal_error_string[MAX_ERR_STR_LEN]; #else thread_local char internal_error_string[MAX_ERR_STR_LEN]; #endif // Initializes one of the db's root node pointers from data in the file header static couchstore_error_t read_db_root(Db *db, node_pointer **root, void *root_data, int root_size) { couchstore_error_t errcode = COUCHSTORE_SUCCESS; if (root_size > 0) { error_unless(root_size >= ROOT_BASE_SIZE, COUCHSTORE_ERROR_CORRUPT); *root = read_root(root_data, root_size); error_unless(*root, COUCHSTORE_ERROR_ALLOC_FAIL); error_unless((*root)->pointer < db->header.position, COUCHSTORE_ERROR_CORRUPT); } else { *root = NULL; } cleanup: return errcode; } // Attempts to initialize the database from a header at the given file position static couchstore_error_t find_header_at_pos(Db *db, cs_off_t pos) { int seqrootsize; int idrootsize; int localrootsize; char *root_data; int header_len; couchstore_error_t errcode = COUCHSTORE_SUCCESS; union { raw_file_header *raw; char *buf; } header_buf = { NULL }; uint8_t buf[2]; ssize_t readsize; { // Speculative read looking for header, mark as Empty. ScopedFileTag tag(db->file.ops, db->file.handle, FileTag::Empty); readsize = db->file.ops->pread( &db->file.lastError, db->file.handle, buf, 2, pos); } error_unless(readsize == 2, COUCHSTORE_ERROR_READ); if (buf[0] == 0) { return COUCHSTORE_ERROR_NO_HEADER; } else if (buf[0] != 1) { return COUCHSTORE_ERROR_CORRUPT; } header_len = pread_header(&db->file, pos, &header_buf.buf, MAX_DB_HEADER_SIZE); if (header_len < 0) { error_pass(static_cast<couchstore_error_t>(header_len)); } db->header.position = pos; db->header.disk_version = decode_raw08(header_buf.raw->version); // Only 12 and 11 are valid error_unless(db->header.disk_version == COUCH_DISK_VERSION || db->header.disk_version == COUCH_DISK_VERSION_11, COUCHSTORE_ERROR_HEADER_VERSION); db->header.update_seq = decode_raw48(header_buf.raw->update_seq); db->header.purge_seq = decode_raw48(header_buf.raw->purge_seq); db->header.purge_ptr = decode_raw48(header_buf.raw->purge_ptr); error_unless(db->header.purge_ptr <= db->header.position, COUCHSTORE_ERROR_CORRUPT); seqrootsize = decode_raw16(header_buf.raw->seqrootsize); idrootsize = decode_raw16(header_buf.raw->idrootsize); localrootsize = decode_raw16(header_buf.raw->localrootsize); error_unless(header_len == HEADER_BASE_SIZE + seqrootsize + idrootsize + localrootsize, COUCHSTORE_ERROR_CORRUPT); root_data = (char*) (header_buf.raw + 1); // i.e. just past *header_buf error_pass(read_db_root(db, &db->header.by_seq_root, root_data, seqrootsize)); root_data += seqrootsize; error_pass(read_db_root(db, &db->header.by_id_root, root_data, idrootsize)); root_data += idrootsize; error_pass(read_db_root(db, &db->header.local_docs_root, root_data, localrootsize)); cleanup: cb_free(header_buf.raw); return errcode; } // Finds the database header by scanning back from the end of the file at 4k boundaries static couchstore_error_t find_header(Db *db, int64_t start_pos) { couchstore_error_t last_header_errcode = COUCHSTORE_ERROR_NO_HEADER; int64_t pos = start_pos; pos -= pos % COUCH_BLOCK_SIZE; for (; pos >= 0; pos -= COUCH_BLOCK_SIZE) { couchstore_error_t errcode = find_header_at_pos(db, pos); switch(errcode) { case COUCHSTORE_SUCCESS: // Found it! return COUCHSTORE_SUCCESS; case COUCHSTORE_ERROR_NO_HEADER: // No header here, so keep going break; case COUCHSTORE_ERROR_ALLOC_FAIL: // Fatal error return errcode; default: // Invalid header; continue, but remember the last error last_header_errcode = errcode; break; } } return last_header_errcode; } /** * Calculates how large in bytes the current header will be * when written to disk. * * The seqrootsize, idrootsize and localrootsize params are * used to return the respective sizes in this header if * needed. */ size_t calculate_header_size(Db *db, size_t& seqrootsize, size_t& idrootsize, size_t& localrootsize) { seqrootsize = idrootsize = localrootsize = 0; if (db->header.by_seq_root) { seqrootsize = ROOT_BASE_SIZE + db->header.by_seq_root->reduce_value.size; } if (db->header.by_id_root) { idrootsize = ROOT_BASE_SIZE + db->header.by_id_root->reduce_value.size; } if (db->header.local_docs_root) { localrootsize = ROOT_BASE_SIZE + db->header.local_docs_root->reduce_value.size; } return sizeof(raw_file_header) + seqrootsize + idrootsize + localrootsize; } couchstore_error_t db_write_header(Db *db) { sized_buf writebuf; size_t seqrootsize, idrootsize, localrootsize; writebuf.size = calculate_header_size(db, seqrootsize, idrootsize, localrootsize); writebuf.buf = (char *) cb_calloc(1, writebuf.size); raw_file_header* header = (raw_file_header*)writebuf.buf; header->version = encode_raw08(db->header.disk_version); encode_raw48(db->header.update_seq, &header->update_seq); encode_raw48(db->header.purge_seq, &header->purge_seq); encode_raw48(db->header.purge_ptr, &header->purge_ptr); header->seqrootsize = encode_raw16((uint16_t)seqrootsize); header->idrootsize = encode_raw16((uint16_t)idrootsize); header->localrootsize = encode_raw16((uint16_t)localrootsize); uint8_t *root = (uint8_t*)(header + 1); encode_root(root, db->header.by_seq_root); root += seqrootsize; encode_root(root, db->header.by_id_root); root += idrootsize; encode_root(root, db->header.local_docs_root); cs_off_t pos; couchstore_error_t errcode = write_header(&db->file, &writebuf, &pos); if (errcode == COUCHSTORE_SUCCESS) { db->header.position = pos; } cb_free(writebuf.buf); return errcode; } static couchstore_error_t create_header(Db *db) { // Select the version based upon selected CRC if (db->file.crc_mode == CRC32) { // user is creating down-level files db->header.disk_version = COUCH_DISK_VERSION_11; } else { // user is using latest db->header.disk_version = COUCH_DISK_VERSION; } db->header.update_seq = 0; db->header.by_id_root = NULL; db->header.by_seq_root = NULL; db->header.local_docs_root = NULL; db->header.purge_seq = 0; db->header.purge_ptr = 0; db->header.position = 0; return db_write_header(db); } LIBCOUCHSTORE_API uint64_t couchstore_get_header_position(Db *db) { return db->header.position; } /** * Precommit should occur before writing a header, it has two * purposes. Firstly it ensures data is written before we attempt * to write the header. This means it's impossible for the header * to be written before the data. This is accomplished through * a sync. * * The second purpose is to extend the file to be large enough * to include the subsequently written header. This is done so * the fdatasync performed by writing a header doesn't have to * do an additional (expensive) modified metadata flush on top * of the one we're already doing. */ couchstore_error_t precommit(Db *db) { cs_off_t curpos = db->file.pos; db->file.pos = align_to_next_block(db->file.pos); sized_buf zerobyte = { const_cast<char*>("\0"), 1}; size_t seqrootsize, idrootsize, localrootsize; db->file.pos += calculate_header_size(db, seqrootsize, idrootsize, localrootsize); //Extend file size to where end of header will land before we do first sync couchstore_error_t errcode = static_cast<couchstore_error_t>( db_write_buf(&db->file, &zerobyte, NULL, NULL)); if (errcode == COUCHSTORE_SUCCESS) { errcode = db->file.ops->sync(&db->file.lastError, db->file.handle); } // Move cursor back to where it was db->file.pos = curpos; return errcode; } LIBCOUCHSTORE_API couchstore_error_t couchstore_commit(Db *db) { COLLECT_LATENCY(); couchstore_error_t errcode = precommit(db); if (errcode == COUCHSTORE_SUCCESS) { errcode = db_write_header(db); } if (errcode == COUCHSTORE_SUCCESS) { errcode = db->file.ops->sync(&db->file.lastError, db->file.handle); } return errcode; } static tree_file_options get_tree_file_options_from_flags(couchstore_open_flags flags) { tree_file_options options; if (flags & COUCHSTORE_OPEN_FLAG_UNBUFFERED) { options.buf_io_enabled = false; } else if (flags & COUCHSTORE_OPEN_WITH_CUSTOM_BUFFER) { // Buffered IO with custom buffer settings. // * First 4 bits [15:12]: read buffer capacity // * Next 4 bits [11:08]: max read buffer count uint32_t unit_index = (flags >> 12) & 0xf; if (unit_index) { // unit_index 1 2 3 4 ... 15 // unit size 1KB 2KB 4KB 8KB ... 16MB options.buf_io_read_unit_size = 1024 * (1 << (unit_index -1)); } uint32_t count_index = (flags >> 8) & 0xf; if (count_index) { // count_index 1 2 3 4 ... 15 // # buffers 8 16 32 64 ... 128K options.buf_io_read_buffers = 8 * (1 << (count_index-1)); } } // Set default value first. options.kp_nodesize = DB_KP_CHUNK_THRESHOLD; options.kv_nodesize = DB_KV_CHUNK_THRESHOLD; if (flags & COUCHSTORE_OPEN_WITH_CUSTOM_NODESIZE) { // B+tree custom node size settings. // * First 4 bits [23:20]: KP node size // * Next 4 bits [19:16]: KV node size uint32_t kp_flag = (flags >> 20) & 0xf; if (kp_flag) { options.kp_nodesize = kp_flag * 1024; } uint32_t kv_flag = (flags >> 16) & 0xf; if (kv_flag) { options.kv_nodesize = kv_flag * 1024; } } if (flags & COUCHSTORE_OPEN_WITH_PERIODIC_SYNC) { // Automatic sync() every N bytes written. // * 5 bits [28-24]: power-of-2 * 1kB uint64_t sync_flag = (flags >> 24) & 0x1f; options.periodic_sync_bytes = uint64_t(1024) << (sync_flag - 1); } /* set the tracing and validation options */ options.tracing_enabled = false; options.write_validation_enabled = false; options.mprotect_enabled = false; if (flags & COUCHSTORE_OPEN_WITH_TRACING) { options.tracing_enabled = true; } if (flags & COUCHSTORE_OPEN_WITH_WRITE_VALIDATION) { options.write_validation_enabled = true; } if (flags & COUCHSTORE_OPEN_WITH_MPROTECT) { options.mprotect_enabled = true; } return options; } LIBCOUCHSTORE_API couchstore_open_flags couchstore_encode_periodic_sync_flags(uint64_t bytes) { // Convert to encoding supported by couchstore_open_flags - KB power-of-2 // value. // Round up to whole kilobyte units. const uint64_t kilobytes = (bytes + 1023) / 1024; // Calculate the shift amount (what is the log2 power) uint64_t shiftAmount = std::log2(kilobytes); // Saturate if the user specified more than the encodable amount. shiftAmount = std::min(shiftAmount, uint64_t(30)); // Finally, encode in couchstore_open flags return ((shiftAmount + 1)) << 24; } LIBCOUCHSTORE_API couchstore_error_t couchstore_open_db(const char *filename, couchstore_open_flags flags, Db **pDb) { return couchstore_open_db_ex(filename, flags, couchstore_get_default_file_ops(), pDb); } LIBCOUCHSTORE_API couchstore_error_t couchstore_open_db_ex(const char *filename, couchstore_open_flags flags, FileOpsInterface* ops, Db **pDb) { COLLECT_LATENCY(); couchstore_error_t errcode = COUCHSTORE_SUCCESS; Db *db; int openflags; cs_off_t pos; /* Sanity check input parameters */ if ((flags & COUCHSTORE_OPEN_FLAG_RDONLY) && (flags & COUCHSTORE_OPEN_FLAG_CREATE)) { return COUCHSTORE_ERROR_INVALID_ARGUMENTS; } if ((db = static_cast<Db*>(cb_calloc(1, sizeof(Db)))) == NULL) { return COUCHSTORE_ERROR_ALLOC_FAIL; } if (flags & COUCHSTORE_OPEN_FLAG_RDONLY) { openflags = O_RDONLY; } else { openflags = O_RDWR; } if (flags & COUCHSTORE_OPEN_FLAG_CREATE) { openflags |= O_CREAT; } // open with CRC unknown, CRC will be selected when header is read/or not found. error_pass(tree_file_open(&db->file, filename, openflags, CRC_UNKNOWN, ops, get_tree_file_options_from_flags(flags))); pos = db->file.ops->goto_eof(&db->file.lastError, db->file.handle); db->file.pos = pos; if (pos == 0) { /* This is an empty file. Create a new fileheader unless the * user wanted a read-only version of the file */ if (flags & COUCHSTORE_OPEN_FLAG_RDONLY) { error_pass(COUCHSTORE_ERROR_NO_HEADER); } else { // Select the CRC to use on this new file if (flags & COUCHSTORE_OPEN_WITH_LEGACY_CRC) { db->file.crc_mode = CRC32; } else { db->file.crc_mode = CRC32C; } error_pass(create_header(db)); } } else if (pos > 0) { error_pass(find_header(db, db->file.pos - 2)); if (db->header.disk_version <= COUCH_DISK_VERSION_11) { db->file.crc_mode = CRC32; } else { cb_assert(db->header.disk_version >= COUCH_DISK_VERSION_12); db->file.crc_mode = CRC32C; } // Not allowed. Can't request legacy_crc but be opening non legacy CRC files. if (db->file.crc_mode == CRC32C && flags & COUCHSTORE_OPEN_WITH_LEGACY_CRC) { errcode = COUCHSTORE_ERROR_INVALID_ARGUMENTS; goto cleanup; } } else { error_pass(static_cast<couchstore_error_t>(db->file.pos)); } *pDb = db; db->dropped = 0; cleanup: if ((openflags & O_RDWR) && (db->file.options.tracing_enabled)) { TRACE_INSTANT2("couchstore_write", "couchstore_open_db_ex", "filename", filename, "errcode", int(errcode)); } if (errcode != COUCHSTORE_SUCCESS) { couchstore_close_file(db); couchstore_free_db(db); } return errcode; } LIBCOUCHSTORE_API couchstore_error_t couchstore_close_file(Db* db) { COLLECT_LATENCY(); if(db->dropped) { return COUCHSTORE_SUCCESS; } couchstore_error_t error = tree_file_close(&db->file); db->dropped = 1; return error; } LIBCOUCHSTORE_API couchstore_error_t couchstore_rewind_db_header(Db *db) { COLLECT_LATENCY(); couchstore_error_t errcode; error_unless(!db->dropped, COUCHSTORE_ERROR_FILE_CLOSED); // free current header guts cb_free(db->header.by_id_root); cb_free(db->header.by_seq_root); cb_free(db->header.local_docs_root); db->header.by_id_root = NULL; db->header.by_seq_root = NULL; db->header.local_docs_root = NULL; error_unless(db->header.position != 0, COUCHSTORE_ERROR_DB_NO_LONGER_VALID); // find older header error_pass(find_header(db, db->header.position - 2)); cleanup: // if we failed, free the handle and return an error if(errcode != COUCHSTORE_SUCCESS) { couchstore_close_file(db); couchstore_free_db(db); errcode = COUCHSTORE_ERROR_DB_NO_LONGER_VALID; } return errcode; } LIBCOUCHSTORE_API couchstore_error_t couchstore_free_db(Db* db) { COLLECT_LATENCY(); if(!db) { return COUCHSTORE_SUCCESS; } if(!db->dropped) { return COUCHSTORE_ERROR_INVALID_ARGUMENTS; } cb_free(db->header.by_id_root); cb_free(db->header.by_seq_root); cb_free(db->header.local_docs_root); db->header.by_id_root = NULL; db->header.by_seq_root = NULL; db->header.local_docs_root = NULL; memset(db, 0xa5, sizeof(*db)); cb_free(db); return COUCHSTORE_SUCCESS; } LIBCOUCHSTORE_API const char* couchstore_get_db_filename(Db *db) { return db->file.path; } LIBCOUCHSTORE_API FileOpsInterface::FHStats* couchstore_get_db_filestats(Db* db) { return db->file.ops->get_stats(db->file.handle); } DocInfo* couchstore_alloc_docinfo(const sized_buf *id, const sized_buf *rev_meta) { size_t size = sizeof(DocInfo); if (id) { size += id->size; } if (rev_meta) { size += rev_meta->size; } DocInfo* docInfo = static_cast<DocInfo*>(cb_malloc(size)); if (!docInfo) { return NULL; } memset(docInfo, 0, sizeof(DocInfo)); char *extra = (char *)docInfo + sizeof(DocInfo); if (id) { memcpy(extra, id->buf, id->size); docInfo->id.buf = extra; docInfo->id.size = id->size; extra += id->size; } if (rev_meta) { memcpy(extra, rev_meta->buf, rev_meta->size); docInfo->rev_meta.buf = extra; docInfo->rev_meta.size = rev_meta->size; } return docInfo; } LIBCOUCHSTORE_API void couchstore_free_docinfo(DocInfo *docinfo) { cb_free(docinfo); } LIBCOUCHSTORE_API void couchstore_free_document(Doc *doc) { if (doc) { char *offset = (char *) (&((fatbuf *) NULL)->buf); fatbuf_free((fatbuf *) ((char *)doc - (char *)offset)); } } couchstore_error_t by_seq_read_docinfo(DocInfo **pInfo, const sized_buf *k, const sized_buf *v) { const raw_seq_index_value *raw = (const raw_seq_index_value*)v->buf; ssize_t extraSize = v->size - sizeof(*raw); if (extraSize < 0) { return COUCHSTORE_ERROR_CORRUPT; } uint32_t idsize, datasize; decode_kv_length(&raw->sizes, &idsize, &datasize); uint64_t bp = decode_raw48(raw->bp); int deleted = (bp & BP_DELETED_FLAG) != 0; bp &= ~BP_DELETED_FLAG; uint8_t content_meta = decode_raw08(raw->content_meta); uint64_t rev_seq = decode_raw48(raw->rev_seq); uint64_t db_seq = decode_sequence_key(k); sized_buf id = {v->buf + sizeof(*raw), idsize}; sized_buf rev_meta = {id.buf + idsize, extraSize - id.size}; DocInfo* docInfo = couchstore_alloc_docinfo(&id, &rev_meta); if (!docInfo) { return COUCHSTORE_ERROR_ALLOC_FAIL; } docInfo->db_seq = db_seq; docInfo->rev_seq = rev_seq; docInfo->deleted = deleted; docInfo->bp = bp; docInfo->size = datasize; docInfo->content_meta = content_meta; *pInfo = docInfo; return COUCHSTORE_SUCCESS; } static couchstore_error_t by_id_read_docinfo(DocInfo **pInfo, const sized_buf *k, const sized_buf *v) { const raw_id_index_value *raw = (const raw_id_index_value*)v->buf; ssize_t revMetaSize = v->size - sizeof(*raw); if (revMetaSize < 0) { return COUCHSTORE_ERROR_CORRUPT; } uint32_t datasize, deleted; uint8_t content_meta; uint64_t bp, seq, revnum; seq = decode_raw48(raw->db_seq); datasize = decode_raw32(raw->size); bp = decode_raw48(raw->bp); deleted = (bp & BP_DELETED_FLAG) != 0; bp &= ~BP_DELETED_FLAG; content_meta = decode_raw08(raw->content_meta); revnum = decode_raw48(raw->rev_seq); sized_buf rev_meta = {v->buf + sizeof(*raw), static_cast<size_t>(revMetaSize)}; DocInfo* docInfo = couchstore_alloc_docinfo(k, &rev_meta); if (!docInfo) { return COUCHSTORE_ERROR_ALLOC_FAIL; } docInfo->db_seq = seq; docInfo->rev_seq = revnum; docInfo->deleted = deleted; docInfo->bp = bp; docInfo->size = datasize; docInfo->content_meta = content_meta; *pInfo = docInfo; return COUCHSTORE_SUCCESS; } //Fill in doc from reading file. static couchstore_error_t bp_to_doc(Doc **pDoc, Db *db, cs_off_t bp, couchstore_open_options options) { couchstore_error_t errcode = COUCHSTORE_SUCCESS; int bodylen = 0; char *docbody = NULL; fatbuf *docbuf = NULL; error_unless(!db->dropped, COUCHSTORE_ERROR_FILE_CLOSED); if (options & DECOMPRESS_DOC_BODIES) { bodylen = pread_compressed(&db->file, bp, &docbody); } else { bodylen = pread_bin(&db->file, bp, &docbody); } error_unless(bodylen >= 0, static_cast<couchstore_error_t>(bodylen)); // if bodylen is negative it's an error code error_unless(docbody || bodylen == 0, COUCHSTORE_ERROR_READ); error_unless(docbuf = fatbuf_alloc(sizeof(Doc) + bodylen), COUCHSTORE_ERROR_ALLOC_FAIL); *pDoc = (Doc *) fatbuf_get(docbuf, sizeof(Doc)); if (bodylen == 0) { //Empty doc (*pDoc)->data.buf = NULL; (*pDoc)->data.size = 0; cb_free(docbody); return COUCHSTORE_SUCCESS; } (*pDoc)->data.buf = (char *) fatbuf_get(docbuf, bodylen); (*pDoc)->data.size = bodylen; memcpy((*pDoc)->data.buf, docbody, bodylen); cleanup: cb_free(docbody); if (errcode < 0) { fatbuf_free(docbuf); } return errcode; } static couchstore_error_t docinfo_fetch_by_id(couchfile_lookup_request *rq, const sized_buf *k, const sized_buf *v) { DocInfo **pInfo = (DocInfo **) rq->callback_ctx; if (v == NULL) { return COUCHSTORE_ERROR_DOC_NOT_FOUND; } return by_id_read_docinfo(pInfo, k, v); } static couchstore_error_t docinfo_fetch_by_seq(couchfile_lookup_request *rq, const sized_buf *k, const sized_buf *v) { DocInfo **pInfo = (DocInfo **) rq->callback_ctx; if (v == NULL) { return COUCHSTORE_ERROR_DOC_NOT_FOUND; } return by_seq_read_docinfo(pInfo, k, v); } LIBCOUCHSTORE_API couchstore_error_t couchstore_docinfo_by_id(Db *db, const void *id, size_t idlen, DocInfo **pInfo) { COLLECT_LATENCY(); sized_buf key; sized_buf *keylist = &key; couchfile_lookup_request rq; couchstore_error_t errcode; error_unless(!db->dropped, COUCHSTORE_ERROR_FILE_CLOSED); if (db->header.by_id_root == NULL) { return COUCHSTORE_ERROR_DOC_NOT_FOUND; } key.buf = (char *) id; key.size = idlen; rq.cmp.compare = ebin_cmp; rq.file = &db->file; rq.num_keys = 1; rq.keys = &keylist; rq.callback_ctx = pInfo; rq.fetch_callback = docinfo_fetch_by_id; rq.node_callback = NULL; rq.fold = 0; errcode = btree_lookup(&rq, db->header.by_id_root->pointer); if (errcode == COUCHSTORE_SUCCESS) { if (*pInfo == NULL) { errcode = COUCHSTORE_ERROR_DOC_NOT_FOUND; } } cleanup: return errcode; } LIBCOUCHSTORE_API couchstore_error_t couchstore_docinfo_by_sequence(Db *db, uint64_t sequence, DocInfo **pInfo) { COLLECT_LATENCY(); sized_buf key; sized_buf *keylist = &key; couchfile_lookup_request rq; couchstore_error_t errcode; error_unless(!db->dropped, COUCHSTORE_ERROR_FILE_CLOSED); if (db->header.by_id_root == NULL) { return COUCHSTORE_ERROR_DOC_NOT_FOUND; } sequence = htonll(sequence); key.buf = (char *)&sequence + 2; key.size = 6; rq.cmp.compare = seq_cmp; rq.file = &db->file; rq.num_keys = 1; rq.keys = &keylist; rq.callback_ctx = pInfo; rq.fetch_callback = docinfo_fetch_by_seq; rq.node_callback = NULL; rq.fold = 0; errcode = btree_lookup(&rq, db->header.by_seq_root->pointer); if (errcode == COUCHSTORE_SUCCESS) { if (*pInfo == NULL) { errcode = COUCHSTORE_ERROR_DOC_NOT_FOUND; } } cleanup: return errcode; } LIBCOUCHSTORE_API couchstore_error_t couchstore_open_doc_with_docinfo(Db *db, const DocInfo *docinfo, Doc **pDoc, couchstore_open_options options) { COLLECT_LATENCY(); couchstore_error_t errcode; *pDoc = NULL; if (docinfo->bp == 0) { return COUCHSTORE_ERROR_DOC_NOT_FOUND; } if (!(docinfo->content_meta & COUCH_DOC_IS_COMPRESSED)) { options &= ~DECOMPRESS_DOC_BODIES; } errcode = bp_to_doc(pDoc, db, docinfo->bp, options); if (errcode == COUCHSTORE_SUCCESS) { (*pDoc)->id.buf = docinfo->id.buf; (*pDoc)->id.size = docinfo->id.size; } return errcode; } LIBCOUCHSTORE_API couchstore_error_t couchstore_open_document(Db *db, const void *id, size_t idlen, Doc **pDoc, couchstore_open_options options) { COLLECT_LATENCY(); couchstore_error_t errcode; DocInfo *info; error_unless(!db->dropped, COUCHSTORE_ERROR_FILE_CLOSED); *pDoc = NULL; errcode = couchstore_docinfo_by_id(db, id, idlen, &info); if (errcode == COUCHSTORE_SUCCESS) { errcode = couchstore_open_doc_with_docinfo(db, info, pDoc, options); if (errcode == COUCHSTORE_SUCCESS) { (*pDoc)->id.buf = (char *) id; (*pDoc)->id.size = idlen; } couchstore_free_docinfo(info); } cleanup: return errcode; } // context info passed to lookup_callback via btree_lookup typedef struct { Db *db; couchstore_docinfos_options options; couchstore_changes_callback_fn callback; void* callback_context; int by_id; int depth; couchstore_walk_tree_callback_fn walk_callback; } lookup_context; // btree_lookup callback, called while iterating keys static couchstore_error_t lookup_callback(couchfile_lookup_request *rq, const sized_buf *k, const sized_buf *v) { if (v == NULL) { return COUCHSTORE_SUCCESS; } const lookup_context *context = static_cast<const lookup_context *>(rq->callback_ctx); DocInfo *docinfo = NULL; couchstore_error_t errcode; if (context->by_id) { errcode = by_id_read_docinfo(&docinfo, k, v); } else { errcode = by_seq_read_docinfo(&docinfo, k, v); } if (errcode == COUCHSTORE_ERROR_CORRUPT && (context->options & COUCHSTORE_TOLERATE_CORRUPTION)) { // Invoke callback even if doc info is corrupted/unreadable, if magic flag is set docinfo = static_cast<DocInfo*>(cb_calloc(sizeof(DocInfo), 1)); docinfo->id = *k; docinfo->rev_meta = *v; } else if (errcode) { return errcode; } if ((context->options & COUCHSTORE_DELETES_ONLY) && docinfo->deleted == 0) { couchstore_free_docinfo(docinfo); return COUCHSTORE_SUCCESS; } if ((context->options & COUCHSTORE_NO_DELETES) && docinfo->deleted == 1) { couchstore_free_docinfo(docinfo); return COUCHSTORE_SUCCESS; } if (context->walk_callback) { errcode = static_cast<couchstore_error_t>(context->walk_callback(context->db, context->depth, docinfo, 0, NULL, context->callback_context)); } else { errcode = static_cast<couchstore_error_t>(context->callback(context->db, docinfo, context->callback_context)); } if (errcode <= 0) { couchstore_free_docinfo(docinfo); } else { // User requested docinfo not be freed, don't free it, return success return COUCHSTORE_SUCCESS; } return errcode; } LIBCOUCHSTORE_API couchstore_error_t couchstore_changes_since(Db *db, uint64_t since, couchstore_docinfos_options options, couchstore_changes_callback_fn callback, void *ctx) { COLLECT_LATENCY(); char since_termbuf[6]; sized_buf since_term; sized_buf *keylist = &since_term; lookup_context cbctx = {db, options, callback, ctx, 0, 0, NULL}; couchfile_lookup_request rq; couchstore_error_t errcode; error_unless(!db->dropped, COUCHSTORE_ERROR_FILE_CLOSED); if (db->header.by_seq_root == NULL) { return COUCHSTORE_SUCCESS; } since_term.buf = since_termbuf; since_term.size = 6; encode_raw48(since, (raw_48*)since_term.buf); rq.cmp.compare = seq_cmp; rq.file = &db->file; rq.num_keys = 1; rq.keys = &keylist; rq.callback_ctx = &cbctx; rq.fetch_callback = lookup_callback; rq.node_callback = NULL; rq.fold = 1; rq.tolerate_corruption = (options & COUCHSTORE_TOLERATE_CORRUPTION) != 0; errcode = btree_lookup(&rq, db->header.by_seq_root->pointer); cleanup: return errcode; } LIBCOUCHSTORE_API couchstore_error_t couchstore_all_docs(Db *db, const sized_buf* startKeyPtr, couchstore_docinfos_options options, couchstore_changes_callback_fn callback, void *ctx) { COLLECT_LATENCY(); sized_buf startKey = {NULL, 0}; sized_buf *keylist = &startKey; lookup_context cbctx = {db, options, callback, ctx, 1, 0, NULL}; couchfile_lookup_request rq; couchstore_error_t errcode; error_unless(!db->dropped, COUCHSTORE_ERROR_FILE_CLOSED); if (db->header.by_id_root == NULL) { return COUCHSTORE_SUCCESS; } if (startKeyPtr) { startKey = *startKeyPtr; } rq.cmp.compare = ebin_cmp; rq.file = &db->file; rq.num_keys = 1; rq.keys = &keylist; rq.callback_ctx = &cbctx; rq.fetch_callback = lookup_callback; rq.node_callback = NULL; rq.fold = 1; rq.tolerate_corruption = (options & COUCHSTORE_TOLERATE_CORRUPTION) != 0; errcode = btree_lookup(&rq, db->header.by_id_root->pointer); cleanup: return errcode; } static couchstore_error_t walk_node_callback(struct couchfile_lookup_request *rq, uint64_t subtreeSize, const sized_buf *reduceValue) { lookup_context* context = static_cast<lookup_context*>(rq->callback_ctx); if (reduceValue) { int result = context->walk_callback(context->db, context->depth, NULL, subtreeSize, reduceValue, context->callback_context); context->depth++; if (result < 0) return static_cast<couchstore_error_t>(result); } else { context->depth--; } return COUCHSTORE_SUCCESS; } static couchstore_error_t couchstore_walk_tree(Db *db, int by_id, const node_pointer* root, const sized_buf* startKeyPtr, couchstore_docinfos_options options, int (*compare)(const sized_buf *k1, const sized_buf *k2), couchstore_walk_tree_callback_fn callback, void *ctx) { couchstore_error_t errcode; sized_buf startKey = {NULL, 0}; sized_buf *keylist; couchfile_lookup_request rq; error_unless(!db->dropped, COUCHSTORE_ERROR_FILE_CLOSED); if (root == NULL) { return COUCHSTORE_SUCCESS; } // Invoke the callback on the root node: errcode = static_cast<couchstore_error_t>(callback(db, 0, NULL, root->subtreesize, &root->reduce_value, ctx)); if (errcode < 0) { return errcode; } if (startKeyPtr) { startKey = *startKeyPtr; } keylist = &startKey; { // Create a new scope here just to mute the warning from the // compiler that the goto in the macro error_unless // skips the initialization of lookup_ctx.. lookup_context lookup_ctx = {db, options, NULL, ctx, by_id, 1, callback}; rq.cmp.compare = compare; rq.file = &db->file; rq.num_keys = 1; rq.keys = &keylist; rq.callback_ctx = &lookup_ctx; rq.fetch_callback = lookup_callback; rq.node_callback = walk_node_callback; rq.fold = 1; rq.tolerate_corruption = (options & COUCHSTORE_TOLERATE_CORRUPTION) != 0; error_pass(btree_lookup(&rq, root->pointer)); } cleanup: return errcode; } LIBCOUCHSTORE_API couchstore_error_t couchstore_walk_id_tree(Db *db, const sized_buf* startDocID, couchstore_docinfos_options options, couchstore_walk_tree_callback_fn callback, void *ctx) { COLLECT_LATENCY(); return couchstore_walk_tree(db, 1, db->header.by_id_root, startDocID, options, ebin_cmp, callback, ctx); } LIBCOUCHSTORE_API couchstore_error_t couchstore_walk_seq_tree(Db *db, uint64_t startSequence, couchstore_docinfos_options options, couchstore_walk_tree_callback_fn callback, void *ctx) { COLLECT_LATENCY(); raw_48 start_termbuf; encode_raw48(startSequence, &start_termbuf); sized_buf start_term = {(char*)&start_termbuf, 6}; return couchstore_walk_tree(db, 0, db->header.by_seq_root, &start_term, options, seq_cmp, callback, ctx); } static int id_ptr_cmp(const void *a, const void *b) { sized_buf **buf1 = (sized_buf**) a; sized_buf **buf2 = (sized_buf**) b; return ebin_cmp(*buf1, *buf2); } static int seq_ptr_cmp(const void *a, const void *b) { sized_buf **buf1 = (sized_buf**) a; sized_buf **buf2 = (sized_buf**) b; return seq_cmp(*buf1, *buf2); } // Common subroutine of couchstore_docinfos_by_{ids, sequence} static couchstore_error_t iterate_docinfos(Db *db, const sized_buf keys[], unsigned numDocs, node_pointer *tree, int (*key_ptr_compare)(const void *, const void *), int (*key_compare)(const sized_buf *k1, const sized_buf *k2), couchstore_changes_callback_fn callback, int fold, int tolerate_corruption, void *ctx) { couchstore_error_t errcode = COUCHSTORE_SUCCESS; const sized_buf **keyptrs = NULL; error_unless(!db->dropped, COUCHSTORE_ERROR_FILE_CLOSED); // Nothing to do if the tree is empty if (tree == NULL) { return COUCHSTORE_SUCCESS; } if(numDocs <= 0) { return COUCHSTORE_ERROR_INVALID_ARGUMENTS; } // Create an array of *pointers to* sized_bufs, which is what btree_lookup wants: keyptrs = static_cast<const sized_buf**>(cb_malloc(numDocs * sizeof(sized_buf*))); error_unless(keyptrs, COUCHSTORE_ERROR_ALLOC_FAIL); { unsigned i; for (i = 0; i< numDocs; ++i) { keyptrs[i] = &keys[i]; } if (!fold) { // Sort the key pointers: qsort(keyptrs, numDocs, sizeof(keyptrs[0]), key_ptr_compare); } // Construct the lookup request: lookup_context cbctx = {db, 0, callback, ctx, (tree == db->header.by_id_root), 0, NULL}; couchfile_lookup_request rq; rq.cmp.compare = key_compare; rq.file = &db->file; rq.num_keys = numDocs; rq.keys = (sized_buf**) keyptrs; rq.callback_ctx = &cbctx; rq.fetch_callback = lookup_callback; rq.node_callback = NULL; rq.fold = fold; rq.tolerate_corruption = tolerate_corruption; // Go! error_pass(btree_lookup(&rq, tree->pointer)); } cleanup: cb_free(keyptrs); return errcode; } LIBCOUCHSTORE_API couchstore_error_t couchstore_docinfos_by_id(Db *db, const sized_buf ids[], unsigned numDocs, couchstore_docinfos_options options, couchstore_changes_callback_fn callback, void *ctx) { COLLECT_LATENCY(); return iterate_docinfos(db, ids, numDocs, db->header.by_id_root, id_ptr_cmp, ebin_cmp, callback, (options & RANGES) != 0, (options & COUCHSTORE_TOLERATE_CORRUPTION) != 0, ctx); } LIBCOUCHSTORE_API couchstore_error_t couchstore_docinfos_by_sequence(Db *db, const uint64_t sequence[], unsigned numDocs, couchstore_docinfos_options options, couchstore_changes_callback_fn callback, void *ctx) { COLLECT_LATENCY(); // Create the array of keys: sized_buf *keylist = static_cast<sized_buf*>(cb_malloc(numDocs * sizeof(sized_buf))); raw_by_seq_key *keyvalues = static_cast<raw_by_seq_key*>(cb_malloc(numDocs * sizeof(raw_by_seq_key))); couchstore_error_t errcode; error_unless(!db->dropped, COUCHSTORE_ERROR_FILE_CLOSED); error_unless(keylist && keyvalues, COUCHSTORE_ERROR_ALLOC_FAIL); unsigned i; for (i = 0; i< numDocs; ++i) { encode_raw48(sequence[i], &keyvalues[i].sequence); keylist[i].buf = static_cast<char*>((void*) &keyvalues[i]); keylist[i].size = sizeof(keyvalues[i]); } error_pass(iterate_docinfos(db, keylist, numDocs, db->header.by_seq_root, seq_ptr_cmp, seq_cmp, callback, (options & RANGES) != 0, (options & COUCHSTORE_TOLERATE_CORRUPTION) != 0, ctx)); cleanup: cb_free(keylist); cb_free(keyvalues); return errcode; } LIBCOUCHSTORE_API couchstore_error_t couchstore_db_info(Db *db, DbInfo* dbinfo) { if (db == NULL || dbinfo == NULL) { return COUCHSTORE_ERROR_INVALID_ARGUMENTS; } const node_pointer *id_root = db->header.by_id_root; const node_pointer *seq_root = db->header.by_seq_root; const node_pointer *local_root = db->header.local_docs_root; dbinfo->filename = db->file.path; dbinfo->header_position = db->header.position; dbinfo->last_sequence = db->header.update_seq; dbinfo->purge_seq = db->header.purge_seq; dbinfo->deleted_count = dbinfo->doc_count = dbinfo->space_used = 0; dbinfo->file_size = db->file.pos; if (id_root) { raw_by_id_reduce* id_reduce = (raw_by_id_reduce*) id_root->reduce_value.buf; dbinfo->doc_count = decode_raw40(id_reduce->notdeleted); dbinfo->deleted_count = decode_raw40(id_reduce->deleted); dbinfo->space_used = decode_raw48(id_reduce->size); dbinfo->space_used += id_root->subtreesize; } if(seq_root) { dbinfo->space_used += seq_root->subtreesize; } if(local_root) { dbinfo->space_used += local_root->subtreesize; } return COUCHSTORE_SUCCESS; } static couchstore_error_t local_doc_fetch(couchfile_lookup_request *rq, const sized_buf *k, const sized_buf *v) { LocalDoc **lDoc = (LocalDoc **) rq->callback_ctx; LocalDoc *dp; if (!v) { *lDoc = NULL; return COUCHSTORE_SUCCESS; } fatbuf *ldbuf = fatbuf_alloc(sizeof(LocalDoc) + k->size + v->size); if (ldbuf == NULL) { return COUCHSTORE_ERROR_ALLOC_FAIL; } dp = *lDoc = (LocalDoc *) fatbuf_get(ldbuf, sizeof(LocalDoc)); dp->id.buf = (char *) fatbuf_get(ldbuf, k->size); dp->id.size = k->size; dp->json.buf = (char *) fatbuf_get(ldbuf, v->size); dp->json.size = v->size; dp->deleted = 0; memcpy(dp->id.buf, k->buf, k->size); memcpy(dp->json.buf, v->buf, v->size); return COUCHSTORE_SUCCESS; } LIBCOUCHSTORE_API couchstore_error_t couchstore_open_local_document(Db *db, const void *id, size_t idlen, LocalDoc **pDoc) { sized_buf key; sized_buf *keylist = &key; couchfile_lookup_request rq; couchstore_error_t errcode; error_unless(!db->dropped, COUCHSTORE_ERROR_FILE_CLOSED); if (db->header.local_docs_root == NULL) { return COUCHSTORE_ERROR_DOC_NOT_FOUND; } key.buf = (char *) id; key.size = idlen; rq.cmp.compare = ebin_cmp; rq.file = &db->file; rq.num_keys = 1; rq.keys = &keylist; rq.callback_ctx = pDoc; rq.fetch_callback = local_doc_fetch; rq.node_callback = NULL; rq.fold = 0; errcode = btree_lookup(&rq, db->header.local_docs_root->pointer); if (errcode == COUCHSTORE_SUCCESS) { if (*pDoc == NULL) { errcode = COUCHSTORE_ERROR_DOC_NOT_FOUND; } } cleanup: return errcode; } LIBCOUCHSTORE_API couchstore_error_t couchstore_save_local_document(Db *db, LocalDoc *lDoc) { couchstore_error_t errcode; couchfile_modify_action ldupdate; node_pointer *nroot = NULL; error_unless(!db->dropped, COUCHSTORE_ERROR_FILE_CLOSED); if (lDoc->deleted) { ldupdate.type = ACTION_REMOVE; } else { ldupdate.type = ACTION_INSERT; } ldupdate.key = &lDoc->id; ldupdate.value.data = &lDoc->json; couchfile_modify_request rq; rq.cmp.compare = ebin_cmp; rq.num_actions = 1; rq.actions = &ldupdate; rq.fetch_callback = NULL; rq.reduce = NULL; rq.rereduce = NULL; rq.file = &db->file; rq.enable_purging = false; rq.purge_kp = NULL; rq.purge_kv = NULL; rq.compacting = 0; rq.kv_chunk_threshold = db->file.options.kv_nodesize; rq.kp_chunk_threshold = db->file.options.kp_nodesize; nroot = modify_btree(&rq, db->header.local_docs_root, &errcode); if (errcode == COUCHSTORE_SUCCESS && nroot != db->header.local_docs_root) { cb_free(db->header.local_docs_root); db->header.local_docs_root = nroot; } cleanup: return errcode; } LIBCOUCHSTORE_API void couchstore_free_local_document(LocalDoc *lDoc) { if (lDoc) { char *offset = (char *) (&((fatbuf *) NULL)->buf); fatbuf_free((fatbuf *) ((char *)lDoc - (char *)offset)); } } LIBCOUCHSTORE_API couchstore_error_t couchstore_last_os_error(const Db *db, char* buf, size_t size) { if (db == NULL || buf == nullptr || size == 0) { return COUCHSTORE_ERROR_INVALID_ARGUMENTS; } const couchstore_error_info_t *err = &db->file.lastError; int nw; #ifdef WIN32 char* win_msg = NULL; FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err->error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &win_msg, 0, NULL); nw = _snprintf(buf, size, "WINAPI error = %d: '%s'", err->error, win_msg); LocalFree(win_msg); #else nw = snprintf(buf, size, "errno = %d: '%s'", err->error, strerror(err->error)); #endif if (nw < 0) { return COUCHSTORE_ERROR_ALLOC_FAIL; } if (size_t(nw) >= size) { /* Truncate the error message */ buf[size - 1] = '\0'; } return COUCHSTORE_SUCCESS; } LIBCOUCHSTORE_API couchstore_error_t couchstore_last_internal_error(const Db *db, char* buf, size_t size) { if (db == NULL || buf == nullptr || size == 0) { return COUCHSTORE_ERROR_INVALID_ARGUMENTS; } int nw; nw = snprintf(buf, size, "'%s'", internal_error_string); if (nw < 0) { return COUCHSTORE_ERROR_ALLOC_FAIL; } return COUCHSTORE_SUCCESS; } static couchstore_error_t btree_eval_seq_reduce(Db *db, uint64_t *accum, sized_buf *left, sized_buf *right, bool past_left_edge, uint64_t diskpos) { couchstore_error_t errcode = COUCHSTORE_SUCCESS; int bufpos = 1, nodebuflen = 0; int node_type; char *nodebuf = NULL; nodebuflen = pread_compressed(&db->file, diskpos, &nodebuf); error_unless(nodebuflen >= 0, (static_cast<couchstore_error_t>(nodebuflen))); // if negative, it's an error code node_type = nodebuf[0]; while(bufpos < nodebuflen) { sized_buf k, v; bufpos += read_kv(nodebuf + bufpos, &k, &v); int left_cmp = seq_cmp(&k, left); int right_cmp = seq_cmp(&k, right); if(left_cmp < 0) { continue; } if(node_type == KP_NODE) { // In-range Item in a KP Node const raw_node_pointer *raw = (const raw_node_pointer*)v.buf; const raw_by_seq_reduce *rawreduce = (const raw_by_seq_reduce*) (v.buf + sizeof(raw_node_pointer)); uint64_t subcount = decode_raw40(rawreduce->count); uint64_t pointer = decode_raw48(raw->pointer); if((left_cmp >= 0 && !past_left_edge) || right_cmp >= 0) { error_pass(btree_eval_seq_reduce(db, accum, left, right, past_left_edge, pointer)); if(right_cmp >= 0) { break; } else { past_left_edge = true; } } else { *accum += subcount; } } else { if(right_cmp > 0) { break; } // In-range Item in a KV Node *accum += 1; } } cleanup: if (nodebuf) { cb_free(nodebuf); } return errcode; } LIBCOUCHSTORE_API couchstore_error_t couchstore_changes_count(Db* db, uint64_t min_seq, uint64_t max_seq, uint64_t *count) { COLLECT_LATENCY(); couchstore_error_t errcode = COUCHSTORE_SUCCESS; raw_48 leftkr, rightkr; sized_buf leftk, rightk; leftk.buf = (char*) &leftkr; rightk.buf = (char*) &rightkr; leftk.size = 6; rightk.size = 6; encode_raw48(min_seq, &leftkr); encode_raw48(max_seq, &rightkr); *count = 0; if(db->header.by_seq_root) { error_pass(btree_eval_seq_reduce(db, count, &leftk, &rightk, false, db->header.by_seq_root->pointer)); } cleanup: return errcode; }
33.082119
121
0.589262
sduvuru
434990dcb181181334115c988a9e499ed02b7b82
21,628
hpp
C++
tcob/include/tcob/core/Input.hpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
2
2021-08-18T19:14:35.000Z
2021-12-01T14:14:49.000Z
tcob/include/tcob/core/Input.hpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
null
null
null
tcob/include/tcob/core/Input.hpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Tobias Bohnen // // This software is released under the MIT License. // https://opensource.org/licenses/MIT #pragma once #include <tcob/tcob_config.hpp> #include <unordered_map> #include <tcob/core/Signal.hpp> #include <tcob/core/data/Point.hpp> typedef struct _SDL_GameController SDL_GameController; typedef union SDL_Event SDL_Event; namespace tcob { //////////////////////////////////////////////////////////// //from SDL2: enum class Scancode { UNKNOWN = 0, /** * \name Usage page 0x07 * * These values are from usage page 0x07 (USB keyboard page). */ /* @{ */ A = 4, B = 5, C = 6, D = 7, E = 8, F = 9, G = 10, H = 11, I = 12, J = 13, K = 14, L = 15, M = 16, N = 17, O = 18, P = 19, Q = 20, R = 21, S = 22, T = 23, U = 24, V = 25, W = 26, X = 27, Y = 28, Z = 29, D1 = 30, D2 = 31, D3 = 32, D4 = 33, D5 = 34, D6 = 35, D7 = 36, D8 = 37, D9 = 38, D0 = 39, RETURN = 40, ESCAPE = 41, BACKSPACE = 42, TAB = 43, SPACE = 44, MINUS = 45, EQUALS = 46, LEFTBRACKET = 47, RIGHTBRACKET = 48, BACKSLASH = 49, NONUSHASH = 50, SEMICOLON = 51, APOSTROPHE = 52, GRAVE = 53, COMMA = 54, PERIOD = 55, SLASH = 56, CAPSLOCK = 57, F1 = 58, F2 = 59, F3 = 60, F4 = 61, F5 = 62, F6 = 63, F7 = 64, F8 = 65, F9 = 66, F10 = 67, F11 = 68, F12 = 69, PRINTSCREEN = 70, SCROLLLOCK = 71, PAUSE = 72, INSERT = 73, /**< insert on PC, help on some Mac keyboards (but does send code 73, not 117) */ HOME = 74, PAGEUP = 75, DEL = 76, END = 77, PAGEDOWN = 78, RIGHT = 79, LEFT = 80, DOWN = 81, UP = 82, NUMLOCKCLEAR = 83, /**< num lock on PC, clear on Mac keyboards */ KP_DIVIDE = 84, KP_MULTIPLY = 85, KP_MINUS = 86, KP_PLUS = 87, KP_ENTER = 88, KP_1 = 89, KP_2 = 90, KP_3 = 91, KP_4 = 92, KP_5 = 93, KP_6 = 94, KP_7 = 95, KP_8 = 96, KP_9 = 97, KP_0 = 98, KP_PERIOD = 99, NONUSBACKSLASH = 100, APPLICATION = 101, /**< windows contextual menu, compose */ POWER = 102, KP_EQUALS = 103, F13 = 104, F14 = 105, F15 = 106, F16 = 107, F17 = 108, F18 = 109, F19 = 110, F20 = 111, F21 = 112, F22 = 113, F23 = 114, F24 = 115, EXECUTE = 116, HELP = 117, MENU = 118, SELECT = 119, STOP = 120, AGAIN = 121, /**< redo */ UNDO = 122, CUT = 123, COPY = 124, PASTE = 125, FIND = 126, MUTE = 127, VOLUMEUP = 128, VOLUMEDOWN = 129, KP_COMMA = 133, KP_EQUALSAS400 = 134, INTERNATIONAL1 = 135, INTERNATIONAL2 = 136, INTERNATIONAL3 = 137, /**< Yen */ INTERNATIONAL4 = 138, INTERNATIONAL5 = 139, INTERNATIONAL6 = 140, INTERNATIONAL7 = 141, INTERNATIONAL8 = 142, INTERNATIONAL9 = 143, LANG1 = 144, /**< Hangul/English toggle */ LANG2 = 145, /**< Hanja conversion */ LANG3 = 146, /**< Katakana */ LANG4 = 147, /**< Hiragana */ LANG5 = 148, /**< Zenkaku/Hankaku */ LANG6 = 149, /**< reserved */ LANG7 = 150, /**< reserved */ LANG8 = 151, /**< reserved */ LANG9 = 152, /**< reserved */ ALTERASE = 153, /**< Erase-Eaze */ SYSREQ = 154, CANCEL = 155, CLEAR = 156, PRIOR = 157, RETURN2 = 158, SEPARATOR = 159, KEY_OUT = 160, OPER = 161, CLEARAGAIN = 162, CRSEL = 163, EXSEL = 164, KP_00 = 176, KP_000 = 177, THOUSANDSSEPARATOR = 178, DECIMALSEPARATOR = 179, CURRENCYUNIT = 180, CURRENCYSUBUNIT = 181, KP_LEFTPAREN = 182, KP_RIGHTPAREN = 183, KP_LEFTBRACE = 184, KP_RIGHTBRACE = 185, KP_TAB = 186, KP_BACKSPACE = 187, KP_A = 188, KP_B = 189, KP_C = 190, KP_D = 191, KP_E = 192, KP_F = 193, KP_XOR = 194, KP_POWER = 195, KP_PERCENT = 196, KP_LESS = 197, KP_GREATER = 198, KP_AMPERSAND = 199, KP_DBLAMPERSAND = 200, KP_VERTICALBAR = 201, KP_DBLVERTICALBAR = 202, KP_COLON = 203, KP_HASH = 204, KP_SPACE = 205, KP_AT = 206, KP_EXCLAM = 207, KP_MEMSTORE = 208, KP_MEMRECALL = 209, KP_MEMCLEAR = 210, KP_MEMADD = 211, KP_MEMSUBTRACT = 212, KP_MEMMULTIPLY = 213, KP_MEMDIVIDE = 214, KP_PLUSMINUS = 215, KP_CLEAR = 216, KP_CLEARENTRY = 217, KP_BINARY = 218, KP_OCTAL = 219, KP_DECIMAL = 220, KP_HEXADECIMAL = 221, LCTRL = 224, LSHIFT = 225, LALT = 226, /**< alt, option */ LGUI = 227, /**< windows, command (apple), meta */ RCTRL = 228, RSHIFT = 229, RALT = 230, /**< alt gr, option */ RGUI = 231, /**< windows, command (apple), meta */ MODE = 257, /**< I'm not sure if this is really not covered * by any of the above, but since there's a * special KMOD_MODE for it I'm adding it here */ /* @} */ /* Usage page 0x07 */ /** * \name Usage page 0x0C * * These values are mapped from usage page 0x0C (USB consumer page). */ /* @{ */ AUDIONEXT = 258, AUDIOPREV = 259, AUDIOSTOP = 260, AUDIOPLAY = 261, AUDIOMUTE = 262, MEDIASELECT = 263, WWW = 264, MAIL = 265, CALCULATOR = 266, COMPUTER = 267, AC_SEARCH = 268, AC_HOME = 269, AC_BACK = 270, AC_FORWARD = 271, AC_STOP = 272, AC_REFRESH = 273, AC_BOOKMARKS = 274, /* @} */ /* Usage page 0x0C */ /** * \name Walther keys * * These are values that Christian Walther added (for mac keyboard?). */ /* @{ */ BRIGHTNESSDOWN = 275, BRIGHTNESSUP = 276, DISPLAYSWITCH = 277, /**< display mirroring/dual display switch, video mode switch */ KBDILLUMTOGGLE = 278, KBDILLUMDOWN = 279, KBDILLUMUP = 280, EJECT = 281, SLEEP = 282, APP1 = 283, APP2 = 284, /* @} */ /* Walther keys */ /** * \name Usage page 0x0C (additional media keys) * * These values are mapped from usage page 0x0C (USB consumer page). */ /* @{ */ AUDIOREWIND = 285, AUDIOFASTFORWARD = 286, /* @} */ /* Usage page 0x0C (additional media keys) */ /* Add any other keys here. */ SDL_NUM_SCANCODES = 512 /**< not a key, just marks the number of scancodes for array bounds */ }; constexpr auto ScancodeToKeycode(Scancode x) -> i32 { return static_cast<i32>(x) | (1 << 30); } enum class KeyCode { UNKNOWN = 0, RETURN = '\r', ESCAPE = '\033', BACKSPACE = '\b', TAB = '\t', SPACE = ' ', EXCLAIM = '!', QUOTEDBL = '"', HASH = '#', PERCENT = '%', DOLLAR = '$', AMPERSAND = '&', QUOTE = '\'', LEFTPAREN = '(', RIGHTPAREN = ')', ASTERISK = '*', PLUS = '+', COMMA = ',', MINUS = '-', PERIOD = '.', SLASH = '/', D0 = '0', D1 = '1', D2 = '2', D3 = '3', D4 = '4', D5 = '5', D6 = '6', D7 = '7', D8 = '8', D9 = '9', COLON = ':', SEMICOLON = ';', LESS = '<', EQUALS = '=', GREATER = '>', QUESTION = '?', AT = '@', /* Skip uppercase letters */ LEFTBRACKET = '[', BACKSLASH = '\\', RIGHTBRACKET = ']', CARET = '^', UNDERSCORE = '_', BACKQUOTE = '`', a = 'a', b = 'b', c = 'c', d = 'd', e = 'e', f = 'f', g = 'g', h = 'h', i = 'i', j = 'j', k = 'k', l = 'l', m = 'm', n = 'n', o = 'o', p = 'p', q = 'q', r = 'r', s = 's', t = 't', u = 'u', v = 'v', w = 'w', x = 'x', y = 'y', z = 'z', CAPSLOCK = ScancodeToKeycode(Scancode::CAPSLOCK), F1 = ScancodeToKeycode(Scancode::F1), F2 = ScancodeToKeycode(Scancode::F2), F3 = ScancodeToKeycode(Scancode::F3), F4 = ScancodeToKeycode(Scancode::F4), F5 = ScancodeToKeycode(Scancode::F5), F6 = ScancodeToKeycode(Scancode::F6), F7 = ScancodeToKeycode(Scancode::F7), F8 = ScancodeToKeycode(Scancode::F8), F9 = ScancodeToKeycode(Scancode::F9), F10 = ScancodeToKeycode(Scancode::F10), F11 = ScancodeToKeycode(Scancode::F11), F12 = ScancodeToKeycode(Scancode::F12), PRINTSCREEN = ScancodeToKeycode(Scancode::PRINTSCREEN), SCROLLLOCK = ScancodeToKeycode(Scancode::SCROLLLOCK), PAUSE = ScancodeToKeycode(Scancode::PAUSE), INSERT = ScancodeToKeycode(Scancode::INSERT), HOME = ScancodeToKeycode(Scancode::HOME), PAGEUP = ScancodeToKeycode(Scancode::PAGEUP), DEL = '\177', END = ScancodeToKeycode(Scancode::END), PAGEDOWN = ScancodeToKeycode(Scancode::PAGEDOWN), RIGHT = ScancodeToKeycode(Scancode::RIGHT), LEFT = ScancodeToKeycode(Scancode::LEFT), DOWN = ScancodeToKeycode(Scancode::DOWN), UP = ScancodeToKeycode(Scancode::UP), NUMLOCKCLEAR = ScancodeToKeycode(Scancode::NUMLOCKCLEAR), KP_DIVIDE = ScancodeToKeycode(Scancode::KP_DIVIDE), KP_MULTIPLY = ScancodeToKeycode(Scancode::KP_MULTIPLY), KP_MINUS = ScancodeToKeycode(Scancode::KP_MINUS), KP_PLUS = ScancodeToKeycode(Scancode::KP_PLUS), KP_ENTER = ScancodeToKeycode(Scancode::KP_ENTER), KP_1 = ScancodeToKeycode(Scancode::KP_1), KP_2 = ScancodeToKeycode(Scancode::KP_2), KP_3 = ScancodeToKeycode(Scancode::KP_3), KP_4 = ScancodeToKeycode(Scancode::KP_4), KP_5 = ScancodeToKeycode(Scancode::KP_5), KP_6 = ScancodeToKeycode(Scancode::KP_6), KP_7 = ScancodeToKeycode(Scancode::KP_7), KP_8 = ScancodeToKeycode(Scancode::KP_8), KP_9 = ScancodeToKeycode(Scancode::KP_9), KP_0 = ScancodeToKeycode(Scancode::KP_0), KP_PERIOD = ScancodeToKeycode(Scancode::KP_PERIOD), APPLICATION = ScancodeToKeycode(Scancode::APPLICATION), POWER = ScancodeToKeycode(Scancode::POWER), KP_EQUALS = ScancodeToKeycode(Scancode::KP_EQUALS), F13 = ScancodeToKeycode(Scancode::F13), F14 = ScancodeToKeycode(Scancode::F14), F15 = ScancodeToKeycode(Scancode::F15), F16 = ScancodeToKeycode(Scancode::F16), F17 = ScancodeToKeycode(Scancode::F17), F18 = ScancodeToKeycode(Scancode::F18), F19 = ScancodeToKeycode(Scancode::F19), F20 = ScancodeToKeycode(Scancode::F20), F21 = ScancodeToKeycode(Scancode::F21), F22 = ScancodeToKeycode(Scancode::F22), F23 = ScancodeToKeycode(Scancode::F23), F24 = ScancodeToKeycode(Scancode::F24), EXECUTE = ScancodeToKeycode(Scancode::EXECUTE), HELP = ScancodeToKeycode(Scancode::HELP), MENU = ScancodeToKeycode(Scancode::MENU), SELECT = ScancodeToKeycode(Scancode::SELECT), STOP = ScancodeToKeycode(Scancode::STOP), AGAIN = ScancodeToKeycode(Scancode::AGAIN), UNDO = ScancodeToKeycode(Scancode::UNDO), CUT = ScancodeToKeycode(Scancode::CUT), COPY = ScancodeToKeycode(Scancode::COPY), PASTE = ScancodeToKeycode(Scancode::PASTE), FIND = ScancodeToKeycode(Scancode::FIND), MUTE = ScancodeToKeycode(Scancode::MUTE), VOLUMEUP = ScancodeToKeycode(Scancode::VOLUMEUP), VOLUMEDOWN = ScancodeToKeycode(Scancode::VOLUMEDOWN), KP_COMMA = ScancodeToKeycode(Scancode::KP_COMMA), KP_EQUALSAS400 = ScancodeToKeycode(Scancode::KP_EQUALSAS400), ALTERASE = ScancodeToKeycode(Scancode::ALTERASE), SYSREQ = ScancodeToKeycode(Scancode::SYSREQ), CANCEL = ScancodeToKeycode(Scancode::CANCEL), CLEAR = ScancodeToKeycode(Scancode::CLEAR), PRIOR = ScancodeToKeycode(Scancode::PRIOR), RETURN2 = ScancodeToKeycode(Scancode::RETURN2), SEPARATOR = ScancodeToKeycode(Scancode::SEPARATOR), KEY_OUT = ScancodeToKeycode(Scancode::KEY_OUT), OPER = ScancodeToKeycode(Scancode::OPER), CLEARAGAIN = ScancodeToKeycode(Scancode::CLEARAGAIN), CRSEL = ScancodeToKeycode(Scancode::CRSEL), EXSEL = ScancodeToKeycode(Scancode::EXSEL), KP_00 = ScancodeToKeycode(Scancode::KP_00), KP_000 = ScancodeToKeycode(Scancode::KP_000), THOUSANDSSEPARATOR = ScancodeToKeycode(Scancode::THOUSANDSSEPARATOR), DECIMALSEPARATOR = ScancodeToKeycode(Scancode::DECIMALSEPARATOR), CURRENCYUNIT = ScancodeToKeycode(Scancode::CURRENCYUNIT), CURRENCYSUBUNIT = ScancodeToKeycode(Scancode::CURRENCYSUBUNIT), KP_LEFTPAREN = ScancodeToKeycode(Scancode::KP_LEFTPAREN), KP_RIGHTPAREN = ScancodeToKeycode(Scancode::KP_RIGHTPAREN), KP_LEFTBRACE = ScancodeToKeycode(Scancode::KP_LEFTBRACE), KP_RIGHTBRACE = ScancodeToKeycode(Scancode::KP_RIGHTBRACE), KP_TAB = ScancodeToKeycode(Scancode::KP_TAB), KP_BACKSPACE = ScancodeToKeycode(Scancode::KP_BACKSPACE), KP_A = ScancodeToKeycode(Scancode::KP_A), KP_B = ScancodeToKeycode(Scancode::KP_B), KP_C = ScancodeToKeycode(Scancode::KP_C), KP_D = ScancodeToKeycode(Scancode::KP_D), KP_E = ScancodeToKeycode(Scancode::KP_E), KP_F = ScancodeToKeycode(Scancode::KP_F), KP_XOR = ScancodeToKeycode(Scancode::KP_XOR), KP_POWER = ScancodeToKeycode(Scancode::KP_POWER), KP_PERCENT = ScancodeToKeycode(Scancode::KP_PERCENT), KP_LESS = ScancodeToKeycode(Scancode::KP_LESS), KP_GREATER = ScancodeToKeycode(Scancode::KP_GREATER), KP_AMPERSAND = ScancodeToKeycode(Scancode::KP_AMPERSAND), KP_DBLAMPERSAND = ScancodeToKeycode(Scancode::KP_DBLAMPERSAND), KP_VERTICALBAR = ScancodeToKeycode(Scancode::KP_VERTICALBAR), KP_DBLVERTICALBAR = ScancodeToKeycode(Scancode::KP_DBLVERTICALBAR), KP_COLON = ScancodeToKeycode(Scancode::KP_COLON), KP_HASH = ScancodeToKeycode(Scancode::KP_HASH), KP_SPACE = ScancodeToKeycode(Scancode::KP_SPACE), KP_AT = ScancodeToKeycode(Scancode::KP_AT), KP_EXCLAM = ScancodeToKeycode(Scancode::KP_EXCLAM), KP_MEMSTORE = ScancodeToKeycode(Scancode::KP_MEMSTORE), KP_MEMRECALL = ScancodeToKeycode(Scancode::KP_MEMRECALL), KP_MEMCLEAR = ScancodeToKeycode(Scancode::KP_MEMCLEAR), KP_MEMADD = ScancodeToKeycode(Scancode::KP_MEMADD), KP_MEMSUBTRACT = ScancodeToKeycode(Scancode::KP_MEMSUBTRACT), KP_MEMMULTIPLY = ScancodeToKeycode(Scancode::KP_MEMMULTIPLY), KP_MEMDIVIDE = ScancodeToKeycode(Scancode::KP_MEMDIVIDE), KP_PLUSMINUS = ScancodeToKeycode(Scancode::KP_PLUSMINUS), KP_CLEAR = ScancodeToKeycode(Scancode::KP_CLEAR), KP_CLEARENTRY = ScancodeToKeycode(Scancode::KP_CLEARENTRY), KP_BINARY = ScancodeToKeycode(Scancode::KP_BINARY), KP_OCTAL = ScancodeToKeycode(Scancode::KP_OCTAL), KP_DECIMAL = ScancodeToKeycode(Scancode::KP_DECIMAL), KP_HEXADECIMAL = ScancodeToKeycode(Scancode::KP_HEXADECIMAL), LCTRL = ScancodeToKeycode(Scancode::LCTRL), LSHIFT = ScancodeToKeycode(Scancode::LSHIFT), LALT = ScancodeToKeycode(Scancode::LALT), LGUI = ScancodeToKeycode(Scancode::LGUI), RCTRL = ScancodeToKeycode(Scancode::RCTRL), RSHIFT = ScancodeToKeycode(Scancode::RSHIFT), RALT = ScancodeToKeycode(Scancode::RALT), RGUI = ScancodeToKeycode(Scancode::RGUI), MODE = ScancodeToKeycode(Scancode::MODE), AUDIONEXT = ScancodeToKeycode(Scancode::AUDIONEXT), AUDIOPREV = ScancodeToKeycode(Scancode::AUDIOPREV), AUDIOSTOP = ScancodeToKeycode(Scancode::AUDIOSTOP), AUDIOPLAY = ScancodeToKeycode(Scancode::AUDIOPLAY), AUDIOMUTE = ScancodeToKeycode(Scancode::AUDIOMUTE), MEDIASELECT = ScancodeToKeycode(Scancode::MEDIASELECT), WWW = ScancodeToKeycode(Scancode::WWW), MAIL = ScancodeToKeycode(Scancode::MAIL), CALCULATOR = ScancodeToKeycode(Scancode::CALCULATOR), COMPUTER = ScancodeToKeycode(Scancode::COMPUTER), AC_SEARCH = ScancodeToKeycode(Scancode::AC_SEARCH), AC_HOME = ScancodeToKeycode(Scancode::AC_HOME), AC_BACK = ScancodeToKeycode(Scancode::AC_BACK), AC_FORWARD = ScancodeToKeycode(Scancode::AC_FORWARD), AC_STOP = ScancodeToKeycode(Scancode::AC_STOP), AC_REFRESH = ScancodeToKeycode(Scancode::AC_REFRESH), AC_BOOKMARKS = ScancodeToKeycode(Scancode::AC_BOOKMARKS), BRIGHTNESSDOWN = ScancodeToKeycode(Scancode::BRIGHTNESSDOWN), BRIGHTNESSUP = ScancodeToKeycode(Scancode::BRIGHTNESSUP), DISPLAYSWITCH = ScancodeToKeycode(Scancode::DISPLAYSWITCH), KBDILLUMTOGGLE = ScancodeToKeycode(Scancode::KBDILLUMTOGGLE), KBDILLUMDOWN = ScancodeToKeycode(Scancode::KBDILLUMDOWN), KBDILLUMUP = ScancodeToKeycode(Scancode::KBDILLUMUP), EJECT = ScancodeToKeycode(Scancode::EJECT), SLEEP = ScancodeToKeycode(Scancode::SLEEP), APP1 = ScancodeToKeycode(Scancode::APP1), APP2 = ScancodeToKeycode(Scancode::APP2), AUDIOREWIND = ScancodeToKeycode(Scancode::AUDIOREWIND), AUDIOFASTFORWARD = ScancodeToKeycode(Scancode::AUDIOFASTFORWARD) }; //////////////////////////////////////////////////////////// enum class KeyMod { None = 0x0000, LShift = 0x0001, RShift = 0x0002, LCtrl = 0x0040, RCtrl = 0x0080, LAlt = 0x0100, RAlt = 0x0200, LGui = 0x0400, RGui = 0x0800, Num = 0x1000, Caps = 0x2000, Mode = 0x4000, Ctrl = LCtrl | RCtrl, Shift = LShift | RShift, Alt = LAlt | RAlt, Gui = LGui | RGui }; struct KeyboardEvent { bool Pressed; bool Repeat; Scancode Code; KeyCode Key; KeyMod Mod; }; //////////////////////////////////////////////////////////// struct TextInputEvent { std::string Text; }; //////////////////////////////////////////////////////////// struct TextEditingEvent { std::string Text; i32 Start; i32 Length; }; //////////////////////////////////////////////////////////// struct MouseMotionEvent { PointI Position; PointI RelativeMotion; }; //////////////////////////////////////////////////////////// enum class MouseButton { None = 0, Left = 1, Middle = 2, Right = 3, X1 = 4, X2 = 5 }; struct MouseButtonEvent { MouseButton Button; bool Pressed; u8 Clicks; PointI Position; }; //////////////////////////////////////////////////////////// struct MouseWheelEvent { PointI Scroll; bool Flipped; }; //////////////////////////////////////////////////////////// struct JoyAxisEvent { i32 JoystickID; u8 Axis; i16 Value; }; //////////////////////////////////////////////////////////// enum class JoyHat { Centered = 0x00, Up = 0x01, Right = 0x02, Down = 0x04, Left = 0x08, RightUp = Right | Up, RightDown = Right | Down, LeftUp = Left | Up, LeftDown = Left | Down, }; struct JoyHatEvent { i32 JoystickID; JoyHat Hat; u8 Value; }; //////////////////////////////////////////////////////////// struct JoyButtonEvent { i32 JoystickID; u8 Button; bool Pressed; }; //////////////////////////////////////////////////////////// enum class GameControllerAxis { Invalid = -1, LeftX, LeftY, RightX, RightY, TriggerLeft, TriggerRight, }; struct ControllerAxisEvent { i32 JoystickID; GameControllerAxis Axis; i16 Value; }; //////////////////////////////////////////////////////////// enum class GameControllerButton { Invalid = -1, A, B, X, Y, Back, Guide, Start, LeftStick, RightStick, LeftShoulder, RightShoulder, DPadUp, DPadDown, DPadLeft, DPadRight }; struct ControllerButtonEvent { i32 JoystickID; GameControllerButton Button; bool Pressed; }; //////////////////////////////////////////////////////////// class GameController final { friend class Input; public: auto get_name() const -> std::string; auto rumble(u16 lowFrequencyRumble, u16 highFrequencyRumble, MilliSeconds duration) const -> bool; auto rumble_triggers(u16 leftRumble, u16 rightRumble, MilliSeconds duration) const -> bool; auto is_button_pressed(GameControllerButton button) const -> bool; auto has_button(GameControllerButton button) const -> bool; static auto GetButtonName(GameControllerButton button) -> std::string; auto get_axis_value(GameControllerAxis axis) const -> i16; auto has_axis(GameControllerAxis axis) const -> bool; static auto GetAxisName(GameControllerAxis axis) -> std::string; auto is_valid() const -> bool; private: GameController(SDL_GameController* controller); SDL_GameController* _controller; }; //////////////////////////////////////////////////////////// enum class InputMode { KeyboardMouse, Controller }; class Input final { public: Input(); ~Input(); Signal<KeyboardEvent> KeyDown; Signal<KeyboardEvent> KeyUp; Signal<TextInputEvent> TextInput; Signal<TextEditingEvent> TextEditing; Signal<MouseMotionEvent> MouseMotion; Signal<MouseButtonEvent> MouseButtonDown; Signal<MouseButtonEvent> MouseButtonUp; Signal<MouseWheelEvent> MouseWheel; Signal<JoyAxisEvent> JoyAxisMotion; Signal<JoyHatEvent> JoyHatMotion; Signal<JoyButtonEvent> JoyButtonDown; Signal<JoyButtonEvent> JoyButtonUp; Signal<ControllerAxisEvent> ControllerAxisMotion; Signal<ControllerButtonEvent> ControllerButtonDown; Signal<ControllerButtonEvent> ControllerButtonUp; Signal<InputMode> InputModeChanged; auto get_controller_at(u32 index) -> GameController; auto get_controller_count() -> u32; auto get_mode() const -> InputMode; void process_events(SDL_Event* ev); private: std::unordered_map<i32, SDL_GameController*> _controllers; InputMode _mode { InputMode::KeyboardMouse }; }; }
26.37561
102
0.605465
TobiasBohnen
434a33d2cfa3965264dfadc1622f7f72d916b547
7,792
hpp
C++
Source/AllProjects/Drivers/iTunesRendTM/Server/iTunesRendTMS_iTrayMonPlIntfClientProxy.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/Drivers/iTunesRendTM/Server/iTunesRendTMS_iTrayMonPlIntfClientProxy.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/Drivers/iTunesRendTM/Server/iTunesRendTMS_iTrayMonPlIntfClientProxy.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// ---------------------------------------------------------------------------- // FILE: iTunesRendTMS_iTrayMonPlIntfClientProxy.hpp // DATE: Fri, Feb 12 21:14:16 2021 -0500 // ID: 016EC0A20CCA441C-F05CAF46433D51D7 // // This file was generated by the Charmed Quark CIDIDL compiler. Do not make // changes by hand, because they will be lost if the file is regenerated. // ---------------------------------------------------------------------------- #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) class TiTPlayerIntfClientProxy : public TOrbClientBase { public : // -------------------------------------------------------------------- // Public, static data // -------------------------------------------------------------------- static const TString strInterfaceId; static const TString strImplScope; static const TString strImplBinding; // ------------------------------------------------------------------------ // Transport control values used in the player command call. // // ------------------------------------------------------------------------ enum class EPlCmds { None , FF , FullScrOff , FullScrOn , Next , Pause , Play , Previous , Rewind , Stop , VisualsOff , VisualsOn , Count , Min = None , Max = VisualsOn }; [[nodiscard]] static EPlCmds eXlatEPlCmds(const TString& strToXlat, const tCIDLib::TBoolean bThrowIfNot = kCIDLib::False); [[nodiscard]] static const TString& strXlatEPlCmds(const EPlCmds eToXlat, const tCIDLib::TBoolean bThrowIfNot = kCIDLib::True); [[nodiscard]] static tCIDLib::TBoolean bIsValidEnum(const EPlCmds eVal); // ------------------------------------------------------------------------ // Transport control values used in the player command call. // // ------------------------------------------------------------------------ enum class EPlStates { None , Playing , Stopped , Unknown , Count , Min = None , Max = Unknown }; [[nodiscard]] static EPlStates eXlatEPlStates(const TString& strToXlat, const tCIDLib::TBoolean bThrowIfNot = kCIDLib::False); [[nodiscard]] static const TString& strXlatEPlStates(const EPlStates eToXlat, const tCIDLib::TBoolean bThrowIfNot = kCIDLib::True); [[nodiscard]] static tCIDLib::TBoolean bIsValidEnum(const EPlStates eVal); // -------------------------------------------------------------------- // Public Constructors and Destructor // -------------------------------------------------------------------- TiTPlayerIntfClientProxy(); TiTPlayerIntfClientProxy(const TOrbObjId& ooidSrc, const TString& strNSBinding); TiTPlayerIntfClientProxy(const TiTPlayerIntfClientProxy&) = delete; TiTPlayerIntfClientProxy(TiTPlayerIntfClientProxy&&) = delete; ~TiTPlayerIntfClientProxy(); // -------------------------------------------------------------------- // Public operators // -------------------------------------------------------------------- TiTPlayerIntfClientProxy& operator=(const TiTPlayerIntfClientProxy&) = delete; TiTPlayerIntfClientProxy& operator=(TiTPlayerIntfClientProxy&&) = delete; // -------------------------------------------------------------------- // Public, inherited methods // -------------------------------------------------------------------- tCIDLib::TVoid SetObjId ( const TOrbObjId& ooidToSet , const TString& strNSBinding , const tCIDLib::TBoolean bCheck = kCIDLib::True ) override; // -------------------------------------------------------------------- // Public, non-virtual methods // -------------------------------------------------------------------- tCIDLib::TBoolean bGetPlayerState ( CIOP tCIDLib::TCard4& c4Serial , tCIDLib::TBoolean& bConnected , tCIDLib::TCard4& c4Volume , TiTPlayerIntfClientProxy::EPlStates& ePlState , tCIDLib::TBoolean& bMute , tCIDLib::TCard8& enctTotal , tCIDLib::TCard8& enctCur , TString& strCurAlbum , TString& strCurArtist , TString& strCurTrack ); tCIDLib::TVoid DoPlayerCmd ( const TiTPlayerIntfClientProxy::EPlCmds eCmd ); tCIDLib::TVoid SelPLByCookie ( const TString& strTitleCookie ); tCIDLib::TVoid SelTrackByCookie ( const TString& strItemCookie ); tCIDLib::TVoid SetMute ( const tCIDLib::TBoolean bToSet ); tCIDLib::TVoid SetVolume ( const tCIDLib::TCard4 c4ToSet ); protected : // -------------------------------------------------------------------- // Declare our friends // -------------------------------------------------------------------- friend class TFacCIDOrb; private : // -------------------------------------------------------------------- // Magic macros // -------------------------------------------------------------------- RTTIDefs(TiTPlayerIntfClientProxy,TOrbClientBase) }; #pragma CIDLIB_POPPACK inline tCIDLib::TVoid TiTPlayerIntfClientProxy::SetObjId(const TOrbObjId& ooidToSet , const TString& strNSBinding , const tCIDLib::TBoolean bCheck) { TParent::SetObjId(ooidToSet, strNSBinding, bCheck); } tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, TiTPlayerIntfClientProxy::EPlCmds* const aeList, const tCIDLib::TCard4 c4Count); tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const TiTPlayerIntfClientProxy::EPlCmds* const aeList, const tCIDLib::TCard4 c4Count); inline TiTPlayerIntfClientProxy::EPlCmds operator++(TiTPlayerIntfClientProxy::EPlCmds& eVal, int) { TiTPlayerIntfClientProxy::EPlCmds eTmp = eVal; eVal = TiTPlayerIntfClientProxy::EPlCmds(int(eVal)+1); return eTmp; } inline TBinOutStream& operator<<(TBinOutStream& strmTar, const TiTPlayerIntfClientProxy::EPlCmds eVal) { strmTar.WriteEnum(tCIDLib::TCard4(eVal)); return strmTar; } inline TBinInStream& operator>>(TBinInStream& strmSrc, COP TiTPlayerIntfClientProxy::EPlCmds& eToFill) { eToFill = TiTPlayerIntfClientProxy::EPlCmds(strmSrc.c4ReadEnum()); return strmSrc; } tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, TiTPlayerIntfClientProxy::EPlStates* const aeList, const tCIDLib::TCard4 c4Count); tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const TiTPlayerIntfClientProxy::EPlStates* const aeList, const tCIDLib::TCard4 c4Count); inline TiTPlayerIntfClientProxy::EPlStates operator++(TiTPlayerIntfClientProxy::EPlStates& eVal, int) { TiTPlayerIntfClientProxy::EPlStates eTmp = eVal; eVal = TiTPlayerIntfClientProxy::EPlStates(int(eVal)+1); return eTmp; } inline TBinOutStream& operator<<(TBinOutStream& strmTar, const TiTPlayerIntfClientProxy::EPlStates eVal) { strmTar.WriteEnum(tCIDLib::TCard4(eVal)); return strmTar; } inline TBinInStream& operator>>(TBinInStream& strmSrc, COP TiTPlayerIntfClientProxy::EPlStates& eToFill) { eToFill = TiTPlayerIntfClientProxy::EPlStates(strmSrc.c4ReadEnum()); return strmSrc; }
38.384236
153
0.518352
MarkStega
434e3ef48db16dda3ad9f7c57a560e236bea40e8
1,586
cpp
C++
asio-utils/src/asio-main.cpp
kovdan01/cosec-examples
bf19f2e2db8962d80ee7ce237be1c8af9e901cc9
[ "MIT" ]
3
2020-12-06T13:14:27.000Z
2021-06-01T13:59:50.000Z
asio-utils/src/asio-main.cpp
kovdan01/cosec-examples
bf19f2e2db8962d80ee7ce237be1c8af9e901cc9
[ "MIT" ]
74
2020-10-25T13:10:31.000Z
2021-06-06T15:12:15.000Z
asio-utils/src/asio-main.cpp
kovdan01/cosec-examples
bf19f2e2db8962d80ee7ce237be1c8af9e901cc9
[ "MIT" ]
3
2020-12-17T20:10:56.000Z
2021-04-28T09:03:16.000Z
#include <ce/asio-main.hpp> #include <ce/socket_session.hpp> #include <boost/exception/diagnostic_information.hpp> #include <boost/log/expressions.hpp> #include <boost/log/support/date_time.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/utility/setup/console.hpp> #include <iostream> namespace ce { int asio_main(int argc,char* argv[],int (*main_impl)(std::span<const char* const>)) try{ // Setup logging and failsafe exception handlers. std::ios_base::sync_with_stdio(false); namespace bl = boost::log; bl::add_console_log(std::cerr, bl::keywords::format = ( bl::expressions::stream << bl::expressions::format_date_time<boost::posix_time::ptime>( "TimeStamp","%Y-%m-%d %H:%M:%S.%f" ) << " [" << bl::trivial::severity << "] T" << bl::expressions::attr<bl::attributes::current_thread_id::value_type>("ThreadID") << " @" << ce::remote << " : " << bl::expressions::smessage ), bl::keywords::auto_flush = true ); bl::add_common_attributes(); try{ return main_impl({argv,std::size_t(argc)}); } catch(...){ BOOST_LOG_TRIVIAL(fatal) << boost::current_exception_diagnostic_information(); return 1; } } catch(...){ std::cerr << '\n' << boost::current_exception_diagnostic_information() << '\n'; return 1; } }
34.478261
103
0.554855
kovdan01
434f2739db07dae37ba5f90c89adbfba3e815823
1,997
cpp
C++
tools/freebayes/src/Contamination.cpp
benranco/test
7cf9740108844da30dcc506e733015fd5dd76a05
[ "MIT" ]
1
2020-11-23T09:20:07.000Z
2020-11-23T09:20:07.000Z
tools/freebayes/src/Contamination.cpp
benranco/test
7cf9740108844da30dcc506e733015fd5dd76a05
[ "MIT" ]
null
null
null
tools/freebayes/src/Contamination.cpp
benranco/test
7cf9740108844da30dcc506e733015fd5dd76a05
[ "MIT" ]
1
2020-10-23T11:50:01.000Z
2020-10-23T11:50:01.000Z
#ifndef CONTAMINATION_CPP #define CONTAMINATION_CPP #include "Contamination.h" #include "convert.h" void Contamination::open(string& file) { ifstream input; input.open(file.c_str()); if (!input.is_open()) { cerr << "contamination estimates file " << file << " is not open" << endl; exit(1); } string line; int last; while (std::getline(input, line)) { vector<string> fields = split(line, " \t"); if (fields.size() != 3) { cerr << "could not parse contamination estimate:" << endl << line << endl << "should be of the form:" << endl << "sample p(read=R|genotype=AR) p(read=A|genotype=AA)" << endl; exit(1); } string sample = fields[0]; ContaminationEstimate c; convert(fields[1], c.probRefGivenHet); convert(fields[2], c.probRefGivenHomAlt); if (sample == "*") { // default defaultEstimate = c; } else { insert(make_pair(sample, c)); } } input.close(); } double Contamination::probRefGivenHet(string& sample) { Contamination::iterator s = find(sample); if (s != end()) { return s->second.probRefGivenHet; } else { return defaultEstimate.probRefGivenHet; } } double Contamination::probRefGivenHomAlt(string& sample) { Contamination::iterator s = find(sample); if (s != end()) { return s->second.probRefGivenHomAlt; } else { return defaultEstimate.probRefGivenHomAlt; } } double Contamination::refBias(string& sample) { Contamination::iterator s = find(sample); if (s != end()) { return s->second.refBias; } else { return defaultEstimate.refBias; } } ContaminationEstimate& Contamination::of(string& sample) { Contamination::iterator s = find(sample); if (s != end()) { return s->second; } else { return defaultEstimate; } } #endif
25.935065
82
0.576365
benranco
4351ec0a92db20f701a9f47d4212807f2f44f2c9
4,112
cpp
C++
igl/copyleft/cgal/submesh_aabb_tree.cpp
aviadtzemah/animation2
9a3f980fbe27672fe71f8f61f73b5713f2af5089
[ "Apache-2.0" ]
2,392
2016-12-17T14:14:12.000Z
2022-03-30T19:40:40.000Z
igl/copyleft/cgal/submesh_aabb_tree.cpp
aviadtzemah/animation2
9a3f980fbe27672fe71f8f61f73b5713f2af5089
[ "Apache-2.0" ]
106
2018-04-19T17:47:31.000Z
2022-03-01T19:44:11.000Z
igl/copyleft/cgal/submesh_aabb_tree.cpp
aviadtzemah/animation2
9a3f980fbe27672fe71f8f61f73b5713f2af5089
[ "Apache-2.0" ]
184
2017-11-15T09:55:37.000Z
2022-02-21T16:30:46.000Z
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2016 Alec Jacobson // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "submesh_aabb_tree.h" #include <stdexcept> template< typename DerivedV, typename DerivedF, typename DerivedI, typename Kernel> IGL_INLINE void igl::copyleft::cgal::submesh_aabb_tree( const Eigen::PlainObjectBase<DerivedV>& V, const Eigen::PlainObjectBase<DerivedF>& F, const Eigen::PlainObjectBase<DerivedI>& I, CGAL::AABB_tree< CGAL::AABB_traits< Kernel, CGAL::AABB_triangle_primitive< Kernel, typename std::vector< typename Kernel::Triangle_3 >::iterator > > > & tree, std::vector<typename Kernel::Triangle_3 > & triangles, std::vector<bool> & in_I) { in_I.resize(F.rows(), false); const size_t num_faces = I.rows(); for (size_t i=0; i<num_faces; i++) { const Eigen::Vector3i f = F.row(I(i, 0)); in_I[I(i,0)] = true; triangles.emplace_back( typename Kernel::Point_3(V(f[0], 0), V(f[0], 1), V(f[0], 2)), typename Kernel::Point_3(V(f[1], 0), V(f[1], 1), V(f[1], 2)), typename Kernel::Point_3(V(f[2], 0), V(f[2], 1), V(f[2], 2))); #ifndef NDEBUG if (triangles.back().is_degenerate()) { throw std::runtime_error( "Input facet components contains degenerated triangles"); } #endif } tree.insert(triangles.begin(), triangles.end()); tree.accelerate_distance_queries(); } #ifdef IGL_STATIC_LIBRARY // Explicit template instantiation // generated by autoexplicit.sh template void igl::copyleft::cgal::submesh_aabb_tree<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, CGAL::Epeck>(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, CGAL::AABB_tree<CGAL::AABB_traits<CGAL::Epeck, CGAL::AABB_triangle_primitive<CGAL::Epeck, std::vector<CGAL::Epeck::Triangle_3, std::allocator<CGAL::Epeck::Triangle_3> >::iterator, CGAL::Boolean_tag<false> > > >&, std::vector<CGAL::Epeck::Triangle_3, std::allocator<CGAL::Epeck::Triangle_3> >&, std::vector<bool, std::allocator<bool> >&); // generated by autoexplicit.sh template void igl::copyleft::cgal::submesh_aabb_tree<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, CGAL::Epeck>(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, CGAL::AABB_tree<CGAL::AABB_traits<CGAL::Epeck, CGAL::AABB_triangle_primitive<CGAL::Epeck, std::vector<CGAL::Epeck::Triangle_3, std::allocator<CGAL::Epeck::Triangle_3> >::iterator, CGAL::Boolean_tag<false> > > >&, std::vector<CGAL::Epeck::Triangle_3, std::allocator<CGAL::Epeck::Triangle_3> >&, std::vector<bool, std::allocator<bool> >&); template void igl::copyleft::cgal::submesh_aabb_tree<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, CGAL::Epeck>(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, CGAL::AABB_tree<CGAL::AABB_traits<CGAL::Epeck, CGAL::AABB_triangle_primitive<CGAL::Epeck, std::vector<CGAL::Epeck::Triangle_3, std::allocator<CGAL::Epeck::Triangle_3> >::iterator, CGAL::Boolean_tag<false> > > >&, std::vector<CGAL::Epeck::Triangle_3, std::allocator<CGAL::Epeck::Triangle_3> >&, std::vector<bool, std::allocator<bool> >&); #endif
69.694915
785
0.675584
aviadtzemah
4356f340f496462a0aa2f15e8e2fe7ad79267eb0
990
hpp
C++
include/RadonFramework/Memory/PointerID.hpp
tak2004/RadonFramework
e916627a54a80fac93778d5010c50c09b112259b
[ "Apache-2.0" ]
3
2015-09-15T06:57:50.000Z
2021-03-16T19:05:02.000Z
include/RadonFramework/Memory/PointerID.hpp
tak2004/RadonFramework
e916627a54a80fac93778d5010c50c09b112259b
[ "Apache-2.0" ]
2
2015-09-26T12:41:10.000Z
2015-12-08T08:41:37.000Z
include/RadonFramework/Memory/PointerID.hpp
tak2004/RadonFramework
e916627a54a80fac93778d5010c50c09b112259b
[ "Apache-2.0" ]
1
2015-07-09T02:56:34.000Z
2015-07-09T02:56:34.000Z
#ifndef RF_POINTERID_HPP #define RF_POINTERID_HPP #if _MSC_VER > 1000 #pragma once #endif #include <RadonFramework/Core/Types/UInt32.hpp> #include <RadonFramework/Core/Types/UInt64.hpp> namespace RadonFramework::Memory { using PtrID = RF_Type::UInt64; using PointerIDHolder = union { PtrID ID; void* Ptr; struct { RF_Type::UInt32 ID32; RF_Type::UInt32 unset1; } Identifier32Bit; struct { void* Ptr32; RF_Type::UInt32 unset2; } Pointer32Bit; }; struct PointerID { static const PointerID& Zero(); static PointerID GenerateFromPointer(void* Ptr); static PointerID GenerateFromID(PtrID ID); PtrID GetID() const; void* GetPointer() const; bool operator==(const PointerID& other) const; bool operator!=(const PointerID& other) const; private: PointerIDHolder m_PtrID; }; } // namespace RadonFramework::Memory #ifndef RF_SHORTHAND_NAMESPACE_MEM #define RF_SHORTHAND_NAMESPACE_MEM namespace RF_Mem = RadonFramework::Memory; #endif #endif
18.333333
50
0.741414
tak2004
4358ad8fccc94ca4af08bc092d0c0a0f2863e14e
2,664
cpp
C++
level_zero/tools/source/metrics/linux/os_metric_enumeration_imp_linux.cpp
troels/compute-runtime
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
[ "Intel", "MIT" ]
null
null
null
level_zero/tools/source/metrics/linux/os_metric_enumeration_imp_linux.cpp
troels/compute-runtime
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
[ "Intel", "MIT" ]
null
null
null
level_zero/tools/source/metrics/linux/os_metric_enumeration_imp_linux.cpp
troels/compute-runtime
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
[ "Intel", "MIT" ]
null
null
null
/* * Copyright (C) 2020-2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/os_interface/linux/drm_neo.h" #include "shared/source/os_interface/linux/sys_calls.h" #include "shared/source/os_interface/os_interface.h" #include "level_zero/tools/source/metrics/metric_enumeration_imp.h" #include <sys/stat.h> #include <sys/sysmacros.h> namespace L0 { const char *MetricEnumeration::getMetricsDiscoveryFilename() { return "libmd.so.1"; } bool MetricEnumeration::getAdapterId(uint32_t &adapterMajor, uint32_t &adapterMinor) { auto &device = metricContext.getDevice(); auto &osInterface = device.getOsInterface(); auto drm = osInterface.getDriverModel()->as<NEO::Drm>(); auto drmFile = drm->getFileDescriptor(); struct stat drmStat = {}; int32_t result = NEO::SysCalls::fstat(drmFile, &drmStat); adapterMajor = major(drmStat.st_rdev); adapterMinor = minor(drmStat.st_rdev); return result == 0; } MetricsDiscovery::IAdapter_1_9 *MetricEnumeration::getMetricsAdapter() { UNRECOVERABLE_IF(pAdapterGroup == nullptr); // Obtain drm minor / major version. uint32_t drmMajor = 0; uint32_t drmMinor = 0; UNRECOVERABLE_IF(getAdapterId(drmMajor, drmMinor) == false); // Driver drm major/minor version. const int32_t drmNodePrimary = 0; // From xf86drm.h const int32_t drmNodeRender = 2; // From xf86drm.h const int32_t drmMaxDevices = 64; // From drm_drv.c#110 const int32_t drmMinorRender = drmMinor - (drmNodeRender * drmMaxDevices); const int32_t drmMinorPrimary = drmMinor - (drmNodePrimary * drmMaxDevices); // Enumerate metrics discovery adapters. for (uint32_t index = 0, count = pAdapterGroup->GetParams()->AdapterCount; index < count; ++index) { UNRECOVERABLE_IF(pAdapterGroup->GetAdapter(index) == nullptr); UNRECOVERABLE_IF(pAdapterGroup->GetAdapter(index)->GetParams() == nullptr); auto adapter = pAdapterGroup->GetAdapter(index); auto adapterParams = adapter->GetParams(); const bool validAdapterType = adapterParams->SystemId.Type == MetricsDiscovery::ADAPTER_ID_TYPE_MAJOR_MINOR; const bool validAdapterMajor = adapterParams->SystemId.MajorMinor.Major == static_cast<int32_t>(drmMajor); const bool validAdapterMinor = (adapterParams->SystemId.MajorMinor.Minor == drmMinorRender) || (adapterParams->SystemId.MajorMinor.Minor == drmMinorPrimary); if (validAdapterType && validAdapterMajor && validAdapterMinor) { return adapter; } } return nullptr; } } // namespace L0
33.3
116
0.700826
troels
4359e751c877cdede09f85372d15542aa294890f
17,573
hh
C++
src/c++/include/alignment/Cigar.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
13
2018-02-09T22:59:39.000Z
2021-11-29T06:33:22.000Z
src/c++/include/alignment/Cigar.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
17
2018-01-26T11:36:07.000Z
2022-02-03T18:48:43.000Z
src/c++/include/alignment/Cigar.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
4
2018-10-19T20:00:00.000Z
2020-10-29T14:44:06.000Z
/** ** Isaac Genome Alignment Software ** Copyright (c) 2010-2017 Illumina, Inc. ** All rights reserved. ** ** This software is provided under the terms and conditions of the ** GNU GENERAL PUBLIC LICENSE Version 3 ** ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3 ** along with this program. If not, see ** <https://github.com/illumina/licenses/>. ** ** \file Cigar.hh ** ** \brief Tools for creation, handling, management of BAM CIGAR ** ** \author Come Raczy **/ #ifndef iSAAC_ALIGNMENT_CIGAR_HH #define iSAAC_ALIGNMENT_CIGAR_HH #include <string> #include <vector> #include <utility> #include <algorithm> #include <numeric> #include <stdint.h> #include <boost/bind.hpp> #include <boost/foreach.hpp> #include "common/Debug.hh" #include "common/FastIo.hh" #include "common/Numa.hh" #include "flowcell/Layout.hh" #include "flowcell/ReadMetadata.hh" #include "reference/ReferencePosition.hh" namespace isaac { namespace alignment { class Cigar: public std::vector<uint32_t, common::NumaAllocator<uint32_t, common::numa::defaultNodeLocal> > { typedef std::vector<uint32_t, common::NumaAllocator<uint32_t, common::numa::defaultNodeLocal> > BaseT; public: Cigar (const std::size_t n, const uint32_t &init) : BaseT(n, init) { } Cigar(const BaseT &that) : BaseT(that) { } Cigar(unsigned reservedSize = 0) { reserve(reservedSize); } enum OpCode { ALIGN = 0, // 'M' INSERT = 1, // 'I' DELETE = 2, // 'D' SKIP = 3, // 'N' Not being used in iSAAC. // Use DELETE whenever there is a jump in the reference between two bases of a read. SOFT_CLIP = 4, // 'S' HARD_CLIP = 5, // 'H' // only used to indicate internal clipping in inversions. PAD = 6, // 'P' MATCH = 7, // '=' MISMATCH = 8, // 'X' CONTIG = 9, // Absolute contig change. No equivalent in Bam CIGAR. // Simply changes the contig while leaving the position unchanged. // Normally followed by DELETE or BACK for position adjustment. BACK = 10, // same as DELETE, but backwards. No equivalent in Bam CIGAR. FLIP = 11, // Changes the orientation from F to R and vice versa. // The argument indicates the number of sequence bases covered by subsequent CIGAR // No equivalent in Bam CIGAR. UNKNOWN = 12 // '?' }; using BaseT::at; using BaseT::back; using BaseT::begin; using BaseT::capacity; using BaseT::clear; using BaseT::iterator; using BaseT::const_iterator; using BaseT::empty; using BaseT::end; using BaseT::erase; using BaseT::front; using BaseT::pop_back; using BaseT::reserve; using BaseT::resize; using BaseT::size; using BaseT::value_type; using BaseT::operator[]; void reserve(size_type n) { BaseT::reserve(n); } // we're in read length of hundreds. assume read length of thousands plus the operation code char static const unsigned OPERATION_CHARS_MAX = 5; template <typename IteratorT> void addOperations(IteratorT b, IteratorT e) { // reallocation of Cigar buffer can cause lots of bad memory access. Just prohibit it ISAAC_ASSERT_MSG(capacity() >= size() + std::distance(b, e), "CIGAR buffer is out of capacity:" << capacity() << " needed:" << std::distance(b, e) << " more"); insert(end(), b, e); } void addOperation(int64_t length, OpCode opCode) { uint64_t ulength = std::abs(length); if (DELETE == opCode && 0 > length) { opCode = BACK; } else { ISAAC_ASSERT_MSG(0 <= length, "Negative length is only allowed for DELETE. opCode:" << opCodeToChar(opCode) << " length:" << length); } do { // reallocation of Cigar buffer can cause lots of bad memory access. Just prohibit it ISAAC_ASSERT_MSG(capacity() >= size() + 1, "CIGAR buffer is out of capacity:" << capacity()); push_back(encode(ulength, opCode)); } while (ulength); } void updateOperation(const unsigned offset, uint64_t len, const Cigar::OpCode op) { at(offset) = Cigar::encode(len, op); ISAAC_ASSERT_MSG(!len, "Expected the length to fit in one component"); } std::string toString() const; std::string toString(unsigned offset, unsigned length) const; static std::string toString(const Cigar &cigarBuffer, unsigned offset, unsigned length); template <bool hardClipsAsS = false> static char opCodeToChar(const Cigar::OpCode opCode) { static const char opCodes[] = {'M','I','D','N','S',hardClipsAsS ? 'S':'H','P','=','X','C','B','F','?'}; ISAAC_ASSERT_MSG(sizeof(opCodes) > std::size_t(opCode), "Unexpected CIGAR op code: " << opCode); return opCodes[opCode]; } template <typename IteratorT> void fromString(IteratorT begin, IteratorT end) { static const char opCodes[] = {'M','I','D','N','S','H','P','=','X','C','B','F','?'}; clear(); uint64_t len = 0; for (IteratorT i = begin; end != i; ++i) { char c = *i; if ('0' <= c && c <= '9') { len *= 10; len += c - '0'; } else { const OpCode oc = OpCode( std::distance(opCodes, std::find(opCodes, &opCodes[0] + sizeof(opCodes) - 1, c))); addOperation(len, oc); len = 0; } } } /** * \brief Serializes cigar to a container. Does not push terminating zero * * \return const reference to result */ template <bool hardClipsAsS = false, typename IteratorT, typename ContainerT> static const ContainerT &toString(IteratorT begin, IteratorT end, ContainerT &result) { for (IteratorT v = begin; end != v; ++v) { const Component d = Cigar::decode(*v); common::appendUnsignedInteger(result, d.first); result.push_back(opCodeToChar<hardClipsAsS>(d.second)); } return result; } template <typename IteratorT> static std::string toString(IteratorT begin, IteratorT end) { std::string result; return toString(begin, end, result); } template <typename IteratorT> static std::ostream& toStream(IteratorT begin, IteratorT end, std::ostream &os) { for (IteratorT v = begin; end != v; ++v) { const Component d = Cigar::decode(*v); os << d.first << opCodeToChar(d.second); } return os; } template <typename IteratorT> static unsigned getReadLength(IteratorT begin, IteratorT end) { unsigned ret = 0; BOOST_FOREACH(const value_type v, std::make_pair(begin, end)) { const Component d = Cigar::decode(v); switch (d.second) { case ALIGN: case INSERT: case SOFT_CLIP: ret += d.first; break; default: break; } } return ret; } template <typename IteratorT> static unsigned getMappedLength(IteratorT begin, IteratorT end) { unsigned ret = 0; BOOST_FOREACH(const value_type v, std::make_pair(begin, end)) { const Component d = Cigar::decode(v); switch (d.second) { case ALIGN: ret += d.first; break; default: break; } } return ret; } typedef std::pair<uint32_t, OpCode> Component; struct Encoder { static const uint32_t LENGTH_MAX = ~(~uint32_t(0) << 28); Encoder(uint64_t length, OpCode opCode): opCode_(opCode), length_(LENGTH_MAX < length ? LENGTH_MAX : length) { ISAAC_ASSERT_MSG(ALIGN <= opCode && UNKNOWN >= opCode, "Invalid CIGAR code " << opCode); // ISAAC_ASSERT_MSG(length == length_, "Supplied length value does not fit the length_ data field: " << length << " length_:" << length_); } Encoder(uint32_t value) : value_(value) { } union { struct { OpCode opCode_: 4; uint32_t length_ : 28; }; uint32_t value_; }; uint32_t getValue() const {return value_;} uint32_t getLength() const {return length_;} Component unpack() const {return Component(Component::first_type(length_), Component::second_type(opCode_));} }; static Component decode(const uint32_t value) { return Encoder(value).unpack(); // const unsigned length = value>>4; // const unsigned code = std::min(value & 0x0F, static_cast<unsigned>(UNKNOWN)); // return std::pair<unsigned, OpCode>(length, static_cast<OpCode>(code)); } static unsigned getMaxLength(const unsigned maxGaps) { return getMaxOpeations(maxGaps) * sizeof(value_type); } static unsigned getMinLength() { return 1 * sizeof(value_type); } static unsigned getMaxOpeations(const unsigned maxGaps) { const unsigned cigarOpsPerGap = 2; //any gap requires one following match. const unsigned cigarOpsPerStructuralVariant = maxGaps ? 4 : 0; //any gap requires one following match. Inversions need up to 3 operations to describe the breakpoint const unsigned oneMatchOp = 1; const unsigned maxHardClipOps = 0; //iSAAC does not support had clips const unsigned maxSoftClipOps = 2; //one at each end const unsigned maxCigarOperations = maxSoftClipOps + maxHardClipOps + oneMatchOp + std::max(cigarOpsPerStructuralVariant, maxGaps * cigarOpsPerGap); return maxCigarOperations; } static unsigned getTotalOperationsForReads(const flowcell::ReadMetadataList &readMetadataList, const unsigned maxGaps) { return readMetadataList.size() * getMaxOpeations(maxGaps); } static unsigned getMaxOperationsForReads( const flowcell::FlowcellLayoutList &flowcellLayoutList, const unsigned maxGaps) { unsigned ret = 0; BOOST_FOREACH(const flowcell::Layout &flowcell, flowcellLayoutList) { ret = std::max(ret, getTotalOperationsForReads(flowcell.getReadMetadataList(), maxGaps)); } return ret; } /** * @return encoded SOFT_CLIP if value was a hard clip, original value otherwise */ static uint32_t softenHardClip(uint32_t value) { alignment::Cigar::Component c = alignment::Cigar::decode(value); return HARD_CLIP == c.second ? encode(c.first, SOFT_CLIP) : value; } private: static uint32_t encode(const uint32_t &length, OpCode opCode) { Encoder c(length, opCode); return c.getValue(); } static uint32_t encode(uint64_t &length, OpCode opCode) { Encoder c(length, opCode); length -= c.getLength(); return c.getValue(); // assert(ALIGN <= opCode); // assert(UNKNOWN >= opCode); // return (length<<4) | opCode; } }; inline std::ostream &operator <<(std::ostream &os, const Cigar::Component &cigarComponent) { return os << "CigarComponent(" << cigarComponent.first << "," << cigarComponent.second << ")"; } template <typename IteratorT> struct CigarPosition { CigarPosition(const IteratorT cigarIt, const IteratorT cigarEnd, const reference::ReferencePosition referencePos, const bool reverse, const unsigned readLength): referencePos_(referencePos), cigarIt_(cigarIt), cigarEnd_(cigarEnd), sequenceOffset_(0), reverse_(reverse), readLength_(readLength){} reference::ReferencePosition referencePos_; IteratorT cigarIt_; IteratorT cigarEnd_; unsigned sequenceOffset_; bool reverse_; unsigned readLength_; bool operator ==(const CigarPosition &other) const { ISAAC_ASSERT_MSG(cigarEnd_ == other.cigarEnd_, "Attempt to compare CigarPosition objects of difference CIGARs"); if (cigarIt_ == other.cigarIt_) { ISAAC_ASSERT_MSG( referencePos_ == other.referencePos_ || isaac::reference::ReferencePosition(isaac::reference::ReferencePosition::NoMatch) == referencePos_ || isaac::reference::ReferencePosition(isaac::reference::ReferencePosition::NoMatch) == other.referencePos_, "Invalid comparison of CigarPositions. When cigar iterators match, positions must match or be not set"); return true; } return false; } bool operator != (const CigarPosition &other) const { return !(other == *this); } Cigar::Component component() const {return Cigar::decode(*cigarIt_); } CigarPosition & operator ++() { ISAAC_ASSERT_MSG(cigarEnd_ != cigarIt_, "Attempt to advance past the end of the CIGAR. sequenceOffset_:" << sequenceOffset_); const Cigar::Component component = Cigar::decode(*cigarIt_++); if (Cigar::ALIGN == component.second) { referencePos_ += component.first; sequenceOffset_ += component.first; } else if (Cigar::INSERT == component.second) { sequenceOffset_ += component.first; } else if (Cigar::DELETE == component.second) { referencePos_ += component.first; } else if (Cigar::BACK == component.second) { referencePos_ -= component.first; skipToNextAlign(); } else if (Cigar::CONTIG == component.second) { referencePos_ = reference::ReferencePosition(component.first, referencePos_.getPosition()); skipToNextAlign(); } else if (Cigar::FLIP == component.second) { sequenceOffset_ = readLength_ - sequenceOffset_ - component.first; reverse_ = !reverse_; skipToNextAlign(); } else if (Cigar::SOFT_CLIP == component.second) { sequenceOffset_ += component.first; } else if (Cigar::HARD_CLIP == component.second) { sequenceOffset_ += component.first; } else { using boost::format; const format message = format("Unexpected Cigar OpCode: %d") % component.second; BOOST_THROW_EXCEPTION(common::PostConditionException(message.str())); } return *this; } bool end() const {return cigarEnd_ == cigarIt_;} private: void skipToNextAlign() { while (!end()) { const Cigar::Component nextComponent = Cigar::decode(*cigarIt_); if (Cigar::DELETE == nextComponent.second) { referencePos_ += nextComponent.first; } else if (Cigar::BACK == nextComponent.second) { referencePos_ -= nextComponent.first; } else if (Cigar::CONTIG == nextComponent.second) { referencePos_ = reference::ReferencePosition(nextComponent.first, referencePos_.getPosition()); } else { ISAAC_ASSERT_MSG( Cigar::ALIGN == nextComponent.second || Cigar::SOFT_CLIP == nextComponent.second || Cigar::HARD_CLIP == nextComponent.second, "Unexpected cigar operation " << nextComponent.second << " while looking for Cigar::ALIGN or Cigar::SOFT_CLIP in " << *this); break; } ++cigarIt_; } } friend std::ostream & operator <<(std::ostream &os, const CigarPosition& pos) { return os << "CigarPosition(" << pos.referencePos_ << "," << alignment::Cigar::toString(pos.cigarIt_, pos.cigarEnd_) << "," << pos.reverse_ << "," << pos.sequenceOffset_ << "," << pos.readLength_ << ")"; } }; template <typename IteratorT> unsigned computeObservedLength(const IteratorT cigarBegin, const IteratorT cigarEnd) { // ISAAC_THREAD_CERR << Cigar::toString(cigarBegin, cigarEnd) << std::endl; reference::ReferencePosition lastRefPos(0,0); CigarPosition<IteratorT> cp(cigarBegin, cigarEnd, lastRefPos, false, 0); while(!cp.end()) { // ISAAC_THREAD_CERR << lastRefPos << cp.referencePos_ << std::endl; ISAAC_ASSERT_MSG(lastRefPos.getContigId() == cp.referencePos_.getContigId(), "Only regular CIGARs are supported. lastRefPos:" << lastRefPos << " cp.referencePos_:" << cp.referencePos_ << Cigar::toString(cigarBegin, cigarEnd)); ISAAC_ASSERT_MSG(!cp.reverse_, "Only regular CIGARs are supported. lastRefPos:" << lastRefPos << " cp.referencePos_:" << cp.referencePos_ << Cigar::toString(cigarBegin, cigarEnd)); ISAAC_ASSERT_MSG(lastRefPos <= cp.referencePos_, "Only regular CIGARs are supported"); lastRefPos = cp.referencePos_; ++cp; } return cp.referencePos_ - reference::ReferencePosition(0,0); } } // namespace alignment } // namespace isaac #endif // #ifndef iSAAC_ALIGNMENT_CIGAR_HH
33.729367
172
0.5958
Illumina
435a3fbfef3478542363abfb13e93de86e7595c2
24,853
cpp
C++
test/tools/almath_test.cpp
UCCS-Social-Robotics/libalmath
608475eced68452eb19ef09c46e1916ac597ed88
[ "BSD-3-Clause" ]
4
2016-03-14T20:34:05.000Z
2021-02-14T05:53:00.000Z
test/tools/almath_test.cpp
UCCS-Social-Robotics/libalmath
608475eced68452eb19ef09c46e1916ac597ed88
[ "BSD-3-Clause" ]
1
2021-02-14T05:52:04.000Z
2022-03-16T11:18:20.000Z
test/tools/almath_test.cpp
UCCS-Social-Robotics/libalmath
608475eced68452eb19ef09c46e1916ac597ed88
[ "BSD-3-Clause" ]
9
2017-07-11T16:01:27.000Z
2022-02-13T20:41:05.000Z
/* * Copyright (c) 2012 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #include <almath/tools/almath.h> #include <almath/tools/altrigonometry.h> #include <almath/tools/almathio.h> #include <almath/tools/altransformhelpers.h> #include <boost/math/constants/constants.hpp> #include <gtest/gtest.h> #include <stdexcept> TEST(ALMathTest, moduloPI) { float epsilon = 0.001f; float pAngle = 0.0f; // case 0 pAngle = 0.0f; AL::Math::modulo2PIInPlace(pAngle); EXPECT_NEAR(pAngle, 0.0f, epsilon); pAngle = 0.99f*AL::Math::PI; AL::Math::modulo2PIInPlace(pAngle); EXPECT_NEAR(pAngle, 0.99f*AL::Math::PI, epsilon); pAngle = -0.99f*AL::Math::PI; AL::Math::modulo2PIInPlace(pAngle); EXPECT_NEAR(pAngle, -0.99f*AL::Math::PI, epsilon); // case 1 pAngle = AL::Math::PI + 0.5f; AL::Math::modulo2PIInPlace(pAngle); EXPECT_NEAR(pAngle, 0.5f-AL::Math::PI, epsilon); pAngle = -AL::Math::PI - 0.5f; AL::Math::modulo2PIInPlace(pAngle); EXPECT_NEAR(pAngle, -0.5f+AL::Math::PI, epsilon); // case 2 pAngle = 10.0f*AL::Math::PI + 0.5f; AL::Math::modulo2PIInPlace(pAngle); EXPECT_NEAR(pAngle, 0.5f, epsilon); pAngle = -10.0f*AL::Math::PI - 0.5f; AL::Math::modulo2PIInPlace(pAngle); EXPECT_NEAR(pAngle, -0.5f, epsilon); // case 3 pAngle = 11.0f*AL::Math::PI + 0.5f; AL::Math::modulo2PIInPlace(pAngle); EXPECT_NEAR(pAngle, 0.5f-AL::Math::PI, epsilon); pAngle = -11.0f*AL::Math::PI - 0.5f; AL::Math::modulo2PIInPlace(pAngle); EXPECT_NEAR(pAngle, -0.5f+AL::Math::PI, epsilon); pAngle = 1.0f; EXPECT_NEAR(AL::Math::modulo2PI(pAngle), 1.0f, 1e-4f); pAngle = 2 * AL::Math::PI; EXPECT_NEAR(AL::Math::modulo2PI(pAngle), 0.0f, 1e-4f); pAngle = -5 * AL::Math::PI_2; EXPECT_NEAR(AL::Math::modulo2PI(pAngle), -AL::Math::PI_2, 1e-4f); pAngle = 3 * AL::Math::PI_2; EXPECT_NEAR(AL::Math::modulo2PI(pAngle), -AL::Math::PI_2, 1e-4f); pAngle = AL::Math::PI; EXPECT_NEAR(AL::Math::modulo2PI(pAngle), AL::Math::PI, 1e-4f); } TEST(ALMathTest, mean) { EXPECT_THROW(AL::Math::meanAngle(std::vector<float>()), std::runtime_error); EXPECT_THROW(AL::Math::weightedMeanAngle(std::vector<float>(), std::vector<float>()), std::runtime_error); std::vector<float> angles; std::vector<float> weights; angles.push_back(AL::Math::PI); EXPECT_NEAR(AL::Math::modulo2PI(AL::Math::meanAngle(angles) - AL::Math::PI), 0.f, 1e-3f); EXPECT_THROW(AL::Math::weightedMeanAngle(angles, weights), std::runtime_error); weights.push_back(0.5f); EXPECT_NEAR(AL::Math::modulo2PI(AL::Math::weightedMeanAngle(angles, weights) - AL::Math::PI), 0.f, 1e-3f); angles.push_back(-AL::Math::PI); weights.push_back(0.5f); EXPECT_NEAR(AL::Math::modulo2PI(AL::Math::meanAngle(angles) - AL::Math::PI), 0.f, 1e-3f); EXPECT_NEAR(AL::Math::modulo2PI(AL::Math::weightedMeanAngle(angles, weights) - AL::Math::PI), 0.f, 1e-3f); angles[0] = AL::Math::PI_2; EXPECT_NEAR(AL::Math::modulo2PI(AL::Math::meanAngle(angles) - 0.75f*AL::Math::PI), 0.f, 1e-3f); EXPECT_NEAR(AL::Math::modulo2PI(AL::Math::weightedMeanAngle(angles, weights) - 0.75f*AL::Math::PI), 0.f, 1e-3f); angles[0] = 0.f; EXPECT_THROW(AL::Math::meanAngle(angles), std::runtime_error); EXPECT_THROW(AL::Math::weightedMeanAngle(angles, weights), std::runtime_error); angles[0] = 0.f; weights[0] = 1.f; angles[1] = 0.5f*AL::Math::PI; weights[1] = 0.5f; EXPECT_NEAR(AL::Math::weightedMeanAngle(angles, weights), std::atan(0.5f), 1e-3f); weights[1] = 0.f; EXPECT_THROW(AL::Math::weightedMeanAngle(angles, weights), std::exception); weights[1] = -1.f; EXPECT_THROW(AL::Math::weightedMeanAngle(angles, weights), std::runtime_error); } TEST(ALMathTest, clipData) { float pMin = -0.2f; float pMax = 0.5f; float pData = 0.4f; EXPECT_FALSE(AL::Math::clipData(pMin, pMax, pData)); pMin = -0.2f; pMax = 0.5f; pData = 0.6f; EXPECT_TRUE(AL::Math::clipData(pMin, pMax, pData)); EXPECT_NEAR(pData, pMax, 0.0001f); pMin = -0.2f; pMax = 0.5f; pData = -0.1f; EXPECT_FALSE(AL::Math::clipData(pMin, pMax, pData)); pMin = -0.2f; pMax = 0.5f; pData = -0.3f; EXPECT_TRUE(AL::Math::clipData(pMin, pMax, pData)); EXPECT_NEAR(pData, pMin, 0.0001f); pData = 2.1f; EXPECT_TRUE(AL::Math::clipData(1, 2, pData)); EXPECT_NEAR(pData, static_cast<float>(2), 0.0001f); } TEST(ALMathTest, clipDataVector) { const float lEpsilon = 0.0001f; std::vector<float> data(5, -1.0f); bool isClipped = AL::Math::clipData(0.0f, 1.0f, data); EXPECT_TRUE(isClipped); for (unsigned int i=0; i<data.size(); ++i) { EXPECT_NEAR(data[i], 0.0f, lEpsilon); } data.clear(); data.push_back(-1.0f); data.push_back(1.0f); data.push_back(2.0f); data.push_back(-0.5f); data.push_back(3.0f); std::vector<float> expectedData; expectedData.push_back(0.0f); expectedData.push_back(1.0f); expectedData.push_back(1.0f); expectedData.push_back(0.0f); expectedData.push_back(1.0f); isClipped = AL::Math::clipData(0.0f, 1.0f, data); EXPECT_TRUE(data.size()==expectedData.size()); EXPECT_TRUE(isClipped); for (unsigned int i=0; i<data.size(); ++i) { EXPECT_NEAR(data[i], expectedData[i], lEpsilon); } data.clear(); data.push_back(0.0f); data.push_back(0.1f); data.push_back(0.2f); data.push_back(0.3f); data.push_back(0.4f); expectedData = data; isClipped = AL::Math::clipData(0.0f, 1.0f, data); EXPECT_TRUE(data.size()==expectedData.size()); EXPECT_FALSE(isClipped); for (unsigned int i=0; i<data.size(); ++i) { EXPECT_NEAR(data[i], expectedData[i], lEpsilon); } } TEST(ALMathTest, clipDataVectorVector) { const float lEpsilon = 0.0001f; std::vector<float> data(5, -1.0f); std::vector<std::vector<float> > dataList(5, data); bool isClipped = AL::Math::clipData(0.0f, 1.0f, dataList); EXPECT_TRUE(isClipped); for (unsigned int i=0; i<dataList.size(); ++i) { for (unsigned int j=0; j<dataList[i].size(); ++j) { EXPECT_NEAR(dataList[i][j], 0.0f, lEpsilon); } } } TEST(ALMathTest, changeReferencePose2D) { float pTheta = 90.0f*AL::Math::TO_RAD; AL::Math::Pose2D pPosIn; AL::Math::Pose2D pPosOut; pPosIn = AL::Math::Pose2D(10.0f, 0.0f, 0.5f); AL::Math::changeReferencePose2D(pTheta, pPosIn, pPosOut); EXPECT_TRUE(pPosOut.isNear(AL::Math::Pose2D(0.0f, 10.0f, 0.5f), 0.001f)); pPosIn = AL::Math::Pose2D(0.0f, 10.0f, 0.5f); AL::Math::changeReferencePose2D(pTheta, pPosIn, pPosOut); EXPECT_TRUE(pPosOut.isNear(AL::Math::Pose2D(-10.0f, 0.0f, 0.5f), 0.001f)); pPosIn = AL::Math::Pose2D(-10.0f, 0.0f, 0.5f); AL::Math::changeReferencePose2D(pTheta, pPosIn, pPosOut); EXPECT_TRUE(pPosOut.isNear(AL::Math::Pose2D(0.0f, -10.0f, 0.5f), 0.001f)); pPosIn = AL::Math::Pose2D(0.0f, -10.0f, 0.5f); AL::Math::changeReferencePose2D(pTheta, pPosIn, pPosOut); EXPECT_TRUE(pPosOut.isNear(AL::Math::Pose2D(10.0f, 0.0f, 0.5f), 0.001f)); } TEST(ALMathTest, changeReferencePose2DInPlace) { float pTheta = 90.0f*AL::Math::TO_RAD; AL::Math::Pose2D pPosIn; pPosIn = AL::Math::Pose2D(10.0f, 0.0f, 0.5f); AL::Math::changeReferencePose2DInPlace(pTheta, pPosIn); EXPECT_TRUE(pPosIn.isNear(AL::Math::Pose2D(0.0f, 10.0f, 0.5f), 0.001f)); pPosIn = AL::Math::Pose2D(0.0f, 10.0f, 0.5f); AL::Math::changeReferencePose2DInPlace(pTheta, pPosIn); EXPECT_TRUE(pPosIn.isNear(AL::Math::Pose2D(-10.0f, 0.0f, 0.5f), 0.001f)); pPosIn = AL::Math::Pose2D(-10.0f, 0.0f, 0.5f); AL::Math::changeReferencePose2DInPlace(pTheta, pPosIn); EXPECT_TRUE(pPosIn.isNear(AL::Math::Pose2D(0.0f, -10.0f, 0.5f), 0.001f)); pPosIn = AL::Math::Pose2D(0.0f, -10.0f, 0.5f); AL::Math::changeReferencePose2DInPlace(pTheta, pPosIn); EXPECT_TRUE(pPosIn.isNear(AL::Math::Pose2D(10.0f, 0.0f, 0.5f), 0.001f)); } TEST(ALMathTest, position3DFromPosition6D) { AL::Math::Position6D pPose6d = AL::Math::Position6D(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f); AL::Math::Position3D pPos3dExpected = AL::Math::Position3D(0.1f, 0.2f, 0.3f); AL::Math::Position3D pPose3dResult = AL::Math::position3DFromPosition6D(pPose6d); EXPECT_TRUE(pPose3dResult.isNear(pPos3dExpected, 0.0001f)); } TEST(ALMathTest, position2DFromPose2D) { const AL::Math::Pose2D pPose2d(0.1f, 0.2f, 0.3f); const AL::Math::Position2D pPos2dExpected(0.1f, 0.2f); const AL::Math::Position2D& pPose2dResult = AL::Math::position2DFromPose2D(pPose2d); EXPECT_TRUE(pPose2dResult.isNear(pPos2dExpected, 0.0001f)); } TEST(ALMathTest, pose2DFromPosition2DInPlace) { const AL::Math::Position2D pPosition2d(0.1f, 0.2f); const AL::Math::Pose2D pPos2dExpected(0.1f, 0.2f, 0.5f); AL::Math::Pose2D pPose2dResult = AL::Math::Pose2D(10.0f, 20.0f, 30.0f); AL::Math::pose2DFromPosition2DInPlace(pPosition2d, 0.5f, pPose2dResult); EXPECT_TRUE(pPose2dResult.isNear(pPos2dExpected, 0.0001f)); } TEST(ALMathTest, pose2DFromPosition2D) { const AL::Math::Position2D pPosition2d(0.1f, 0.2f); const AL::Math::Pose2D pPos2dExpected(0.1f, 0.2f, 0.0f); const AL::Math::Pose2D& pPose2dResult = AL::Math::pose2DFromPosition2D(pPosition2d); EXPECT_TRUE(pPose2dResult.isNear(pPos2dExpected, 0.0001f)); const AL::Math::Position2D pPosition2d2(0.1f, 0.2f); const AL::Math::Pose2D pPos2dExpected2(0.1f, 0.2f, 0.5f); const AL::Math::Pose2D& pPose2dResult2 = AL::Math::pose2DFromPosition2D(pPosition2d2, 0.5f); EXPECT_TRUE(pPose2dResult2.isNear(pPos2dExpected2, 0.0001f)); } TEST(ALMathTest, Position6DFromVelocity6D) { const AL::Math::Velocity6D pVIn = AL::Math::Velocity6D(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f); const AL::Math::Position6D pPosIn = AL::Math::position6DFromVelocity6D(pVIn); const AL::Math::Position6D pPosOut = AL::Math::Position6D(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f); EXPECT_TRUE(pPosIn.isNear(pPosOut, 0.0001f)); } TEST(ALMathTest, position2DFromPose2DInPlace) { const AL::Math::Pose2D pose2D = AL::Math::Pose2D(1.0f, 2.0f, 3.0f); AL::Math::Position2D position2D = AL::Math::Position2D(10.0f, 20.0f); AL::Math::position2DFromPose2DInPlace(pose2D, position2D); EXPECT_TRUE(position2D.isNear(AL::Math::Position2D(1.0f, 2.0f), 0.0001f)); } TEST(ALMathTest, variousOperator) { //inline Position3D operator*( // const Rotation& pRot, // const Position3D& pPos) AL::Math::Rotation pRot; AL::Math::Position3D pPos3D; AL::Math::Position3D pPosIn = pRot*pPos3D; AL::Math::Position3D pPosOut = AL::Math::Position3D(); EXPECT_TRUE(pPosIn.isNear(pPosOut, 0.0001f)); pRot = AL::Math::Rotation(); pPos3D = AL::Math::Position3D(1.0f, -1.0f, 0.5f); pPosIn = pRot*pPos3D; pPosOut = AL::Math::Position3D(1.0f, -1.0f, 0.5f); EXPECT_TRUE(pPosIn.isNear(pPosOut, 0.0001f)); pRot = AL::Math::Rotation::fromRotX(0.5f); pPos3D = AL::Math::Position3D(1.0f, -1.0f, 0.5f); pPosIn = pRot*pPos3D; pPosOut = AL::Math::Position3D(1.00000000000000f, -1.11729533119247f, -0.04063425765902f); EXPECT_TRUE(pPosIn.isNear(pPosOut, 0.0001f)); //inline Velocity6D operator*( // const float pK, // const Position6D& pDelta) float pK = 10.0f; AL::Math::Position6D pPos6D = AL::Math::Position6D(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f); AL::Math::Velocity6D pVel6DIn = pK*pPos6D; AL::Math::Velocity6D pVel6DOut = AL::Math::Velocity6D(10.0f, 20.0f, 30.0f, 40.0f, 50.0f, 60.0f); EXPECT_TRUE(pVel6DIn.isNear(pVel6DOut, 0.0001f)); //Velocity3D operator* (const Rotation& pRot, const Velocity3D& pVel); AL::Math::Velocity3D pVIn1 = AL::Math::Velocity3D(0.5f, 0.3f, 0.1f); AL::Math::Rotation pRot1 = AL::Math::rotationFromRotZ(AL::Math::PI_2); AL::Math::Velocity3D pVIn2 = pRot1*pVIn1; AL::Math::Velocity3D pVOut = AL::Math::Velocity3D(-0.3f, 0.5f, 0.1f); EXPECT_TRUE(pVIn2.isNear(pVOut, 0.0001f)); } TEST(ALMathTest, isLeft) { } TEST(ALMathTest, FilterPosition6D) { } TEST(ALMathTest, AxisMaskToPosition6DOn) { } TEST(ALMathTest, AxisMaskToPosition6DOff) { } TEST(ALMathTest, AxisMaskToVelocity6DOn) { } TEST(ALMathTest, RotationFromAngleDirection) { AL::Math::Rotation pRotOut; float pTheta = 0.0f; AL::Math::Position3D pPos = AL::Math::Position3D(0.0f, 0.0f, 0.0f); // ****** test 0 ****** // ASSERT_THROW(AL::Math::rotationFromAngleDirection(pTheta, pPos), std::runtime_error); // ****** test 1 ****** // pTheta = 0.0f; pPos = AL::Math::Position3D(1.0f, 0.0f, 0.0f); pRotOut = AL::Math::rotationFromAngleDirection(pTheta, pPos); EXPECT_TRUE(pRotOut.isNear(AL::Math::Rotation())); // ****** test 2 ****** // pTheta = 0.0f; pPos = AL::Math::Position3D(0.0f, 1.0f, 0.0f); pRotOut = AL::Math::rotationFromAngleDirection(pTheta, pPos); EXPECT_TRUE(pRotOut.isNear(AL::Math::Rotation())); // ****** test 3 ****** // pTheta = 0.0f; pPos = AL::Math::Position3D(0.0f, 0.0f, 1.0f); pRotOut = AL::Math::rotationFromAngleDirection(pTheta, pPos); EXPECT_TRUE(pRotOut.isNear(AL::Math::Rotation())); // ****** test 4 ****** // pTheta = 15.0f*AL::Math::TO_RAD; pPos = AL::Math::Position3D(1.0f, 0.0f, 0.0f); pRotOut = AL::Math::rotationFromAngleDirection(pTheta, pPos); EXPECT_TRUE(pRotOut.isNear(AL::Math::Rotation::fromRotX(pTheta))); EXPECT_FALSE(pRotOut.isNear(AL::Math::Rotation())); // ****** test 5 ****** // pTheta = 15.0f*AL::Math::TO_RAD; pPos = AL::Math::Position3D(0.0f, 1.0f, 0.0f); pRotOut = AL::Math::rotationFromAngleDirection(pTheta, pPos); EXPECT_TRUE(pRotOut.isNear(AL::Math::Rotation::fromRotY(pTheta))); EXPECT_FALSE(pRotOut.isNear(AL::Math::Rotation())); // ****** test 6 ****** // pTheta = 15.0f*AL::Math::TO_RAD; pPos = AL::Math::Position3D(0.0f, 0.0f, 1.0f); pRotOut = AL::Math::rotationFromAngleDirection(pTheta, pPos); EXPECT_TRUE(pRotOut.isNear(AL::Math::Rotation::fromRotZ(pTheta))); EXPECT_FALSE(pRotOut.isNear(AL::Math::Rotation())); EXPECT_TRUE(AL::Math::Rotation::fromRotXPi().isNear( AL::Math::Rotation::fromRotX( boost::math::constants::pi<float>()))); EXPECT_TRUE(AL::Math::Rotation::fromRotYPi().isNear( AL::Math::Rotation::fromRotY( boost::math::constants::pi<float>()))); EXPECT_TRUE(AL::Math::Rotation::fromRotZPi().isNear( AL::Math::Rotation::fromRotZ( boost::math::constants::pi<float>()))); EXPECT_TRUE(AL::Math::Rotation::fromRotZHalfPi().isNear( AL::Math::Rotation::fromRotZ( 0.5f * boost::math::constants::pi<float>()))); } TEST(ALMathTest, quaternionOperator) { AL::Math::Quaternion pQuat; AL::Math::Position3D pPos; AL::Math::Position3D result; result = pQuat * pPos; EXPECT_NEAR(pPos.x, 0.0f, 1e-6f); EXPECT_NEAR(pPos.y, 0.0f, 1e-6f); EXPECT_NEAR(pPos.z, 0.0f, 1e-6f); // Test 90° rotation around the x axis. pQuat = AL::Math::Quaternion(0.7071f, 0.7071f, 0.0f, 0.0f); pPos = AL::Math::Position3D(0.0f, 1.0f, 0.0f); result = pQuat * pPos; EXPECT_NEAR(result.x, 0.0f, 1e-4f); EXPECT_NEAR(result.y, 0.0f, 1e-4f); EXPECT_NEAR(result.z, 1.0f, 1e-4f); // Test 90° rotation around the y axis. pQuat = AL::Math::Quaternion(0.7071f, 0.0f, 0.7071f, 0.0f); pPos = AL::Math::Position3D(0.0f, 0.0f, 1.0f); result = pQuat * pPos; EXPECT_NEAR(result.x, 1.0f, 1e-4f); EXPECT_NEAR(result.y, 0.0f, 1e-4f); EXPECT_NEAR(result.z, 0.0f, 1e-4f); // Test 90° rotation around the z axis. pQuat = AL::Math::Quaternion(0.7071f, 0.0f, 0.0f, 0.7071f); pPos = AL::Math::Position3D(1.0f, 0.0f, 0.0f); result = pQuat * pPos; EXPECT_NEAR(result.x, 0.0f, 1e-4f); EXPECT_NEAR(result.y, 1.0f, 1e-4f); EXPECT_NEAR(result.z, 0.0f, 1e-4f); } TEST(ALMathTest, position6DFromPose2DInPlace) { const AL::Math::Pose2D pPose2d = AL::Math::Pose2D(0.1f, 0.2f, 0.3f); const AL::Math::Position6D pPose6dExpected = AL::Math::Position6D(0.1f, 0.2f, 0.0f, 0.0f, 0.0f, 0.3f); AL::Math::Position6D pPose6dComputed = AL::Math::Position6D(10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f); AL::Math::position6DFromPose2DInPlace( pPose2d, pPose6dComputed); EXPECT_TRUE(pPose6dComputed.isNear(pPose6dExpected, 0.0001f)); } TEST(ALMathTest, position6DFromPose2D) { AL::Math::Pose2D pPose2d = AL::Math::Pose2D(0.1f, 0.2f, 0.3f); AL::Math::Position6D pPose6dExpected = AL::Math::Position6D(0.1f, 0.2f, 0.0f, 0.0f, 0.0f, 0.3f); AL::Math::Position6D pPose6dComputed = AL::Math::position6DFromPose2D(pPose2d); EXPECT_TRUE(pPose6dComputed.isNear(pPose6dExpected, 0.0001f)); } TEST(ALMathTest, pose2DFromPosition6DInPlace) { AL::Math::Position6D pPose6d = AL::Math::Position6D(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f); AL::Math::Pose2D pPose2dExpected = AL::Math::Pose2D(0.1f, 0.2f, 0.6f); AL::Math::Pose2D pPose2dComputed; AL::Math::pose2DFromPosition6DInPlace(pPose6d, pPose2dComputed); EXPECT_TRUE(pPose2dComputed.isNear(pPose2dExpected, 0.0001f)); } TEST(ALMathTest, pose2DFromPosition6D) { AL::Math::Position6D pPose6d = AL::Math::Position6D(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f); AL::Math::Pose2D pPose2dExpected = AL::Math::Pose2D(0.1f, 0.2f, 0.6f); AL::Math::Pose2D pPose2dComputed = AL::Math::pose2DFromPosition6D(pPose6d); EXPECT_TRUE(pPose2dComputed.isNear(pPose2dExpected, 0.0001f)); } TEST(ALMathTest, position6DFromPosition3DInPlace) { const AL::Math::Position3D position3D = AL::Math::Position3D(0.1f, 0.2f, 0.3f); AL::Math::Position6D position6D = AL::Math::Position6D(10.1f, 10.2f, 10.0f, 10.0f, 10.0f, 10.3f); AL::Math::position6DFromPosition3DInPlace(position3D, position6D); EXPECT_TRUE(position6D.isNear( AL::Math::Position6D(0.1f, 0.2f, 0.3f, 0.0f, 0.0f, 0.0f), 0.0001f)); } TEST(ALMathTest, position6DFromPosition3D) { const AL::Math::Position3D position3D = AL::Math::Position3D(0.1f, 0.2f, 0.3f); const AL::Math::Position6D position6D = AL::Math::position6DFromPosition3D(position3D); EXPECT_TRUE(position6D.isNear( AL::Math::Position6D(0.1f, 0.2f, 0.3f, 0.0f, 0.0f, 0.0f), 0.0001f)); } TEST(ALMathTest, multiplicationPose2DPosition2D) { AL::Math::Pose2D pVal; AL::Math::Position2D pPos; AL::Math::Position2D pExpected; AL::Math::Position2D pResult; pVal = AL::Math::Pose2D(0.0f, 0.0f, AL::Math::PI_2); pPos = AL::Math::Position2D(1.0f, 0.0f); pExpected = AL::Math::Position2D(0.0f, 1.0f); pResult = pVal*pPos; EXPECT_TRUE(pResult.isNear(pExpected, 0.0001f)); pVal = AL::Math::Pose2D(0.0f, 0.0f, AL::Math::PI_2); pPos = AL::Math::Position2D(0.0f, 1.0f); pExpected = AL::Math::Position2D(-1.0f, 0.0f); pResult = pVal*pPos; EXPECT_TRUE(pResult.isNear(pExpected, 0.0001f)); pVal = AL::Math::Pose2D(1.0f, 1.0f, -AL::Math::PI_2); pPos = AL::Math::Position2D(1.0f, 0.0f); pExpected = AL::Math::Position2D(1.0f, 0.0f); pResult = pVal*pPos; EXPECT_TRUE(pResult.isNear(pExpected, 0.0001f)); } TEST(ALMathTest, quaternionFromRotation3D) { for (unsigned int i=0; i<360; ++i) { const float angleX = static_cast<float>(i)*AL::Math::TO_RAD; const AL::Math::Quaternion quatX = AL::Math::quaternionFromAngleAndAxisRotation(angleX, 1.0f, 0.0f, 0.0f); for (unsigned int j=0; j<360; ++j) { const float angleY = static_cast<float>(j)*AL::Math::TO_RAD; const AL::Math::Quaternion quatY = AL::Math::quaternionFromAngleAndAxisRotation(angleY, 0.0f, 1.0f, 0.0f); for (unsigned int k=0; k<360; ++k) { const float angleZ = static_cast<float>(k)*AL::Math::TO_RAD; const AL::Math::Quaternion quatZ = AL::Math::quaternionFromAngleAndAxisRotation(angleZ, 0.0f, 0.0f, 1.0f); const AL::Math::Quaternion quatExpected = quatZ*quatY*quatX; const AL::Math::Rotation3D rot3DZYX(angleX, angleY, angleZ); const AL::Math::Quaternion quatResult = AL::Math::quaternionFromRotation3D(rot3DZYX); EXPECT_TRUE(quatResult.isNear(quatExpected, 0.001f)); } } } } TEST(ALMathTest, rotation3DFromQuaternion1) { const float lAngleX = 0.5f; const float lAngleY = -0.3f; AL::Math::Quaternion quat = AL::Math::quaternionFromAngleAndAxisRotation(lAngleY, 0.0f, 1.0f , 0.0f)* AL::Math::quaternionFromAngleAndAxisRotation(lAngleX, 1.0f, 0.0f , 0.0f); AL::Math::Rotation3D lRotation3D; AL::Math::rotation3DFromQuaternion(quat, lRotation3D); EXPECT_NEAR(lRotation3D.wx, lAngleX, 0.0001f); EXPECT_NEAR(lRotation3D.wy, lAngleY, 0.0001f); AL::Math::Quaternion lQuat; AL::Math::quaternionFromRotation3D(lRotation3D, lQuat); EXPECT_NEAR(lQuat.w, quat.w, 0.0001f); EXPECT_NEAR(lQuat.x, quat.x, 0.0001f); EXPECT_NEAR(lQuat.y, quat.y, 0.0001f); EXPECT_NEAR(lQuat.z, quat.z, 0.0001f); // new test jory AL::Math::Rotation3D rotation3DRef(0.0213f, 0.0139f, 0.02619f); quat = AL::Math::Quaternion(0.99983f, 0.01056f, 0.00712f, 0.01302f); quat = quat.normalize(); AL::Math::Rotation3D rotation3D; AL::Math::rotation3DFromQuaternion(quat, rotation3D); EXPECT_TRUE(rotation3D.isNear(rotation3DRef, 0.0001f)); rotation3DRef = AL::Math::Rotation3D(-0.00350f, 0.0f, 0.0314f); quat = AL::Math::Quaternion(0.99988f, -0.00175f, -0.00003f, 0.01571f); AL::Math::rotation3DFromQuaternion(quat, rotation3D); EXPECT_TRUE(rotation3D.isNear(rotation3DRef, 0.0001f)); const float wx = -180.0f*AL::Math::TO_RAD; const float wy = -90.0f*AL::Math::TO_RAD; const float wz = -175.0f*AL::Math::TO_RAD; quat = AL::Math::quaternionFromAngleAndAxisRotation(wz, 0.0f, 0.0f, 1.0f)* AL::Math::quaternionFromAngleAndAxisRotation(wy, 0.0f, 1.0f, 0.0f)* AL::Math::quaternionFromAngleAndAxisRotation(wx, 1.0f, 0.0f, 0.0f); const AL::Math::Rotation3D rot3D = AL::Math::rotation3DFromQuaternion(quat); EXPECT_TRUE(rot3D.wx == rot3D.wx); EXPECT_TRUE(rot3D.wy == rot3D.wy); EXPECT_TRUE(rot3D.wz == rot3D.wz); } TEST(ALMathTest, rotation3DFromQuaternion2) { // function quaternionFromRotation3D must be check before for (int i=-180; i<180; ++i) { const float angleX = static_cast<float>(i)*AL::Math::TO_RAD; const AL::Math::Quaternion quatX = AL::Math::quaternionFromAngleAndAxisRotation(angleX, 1.0f, 0.0f, 0.0f); for (int j=-180; j<180; ++j) { const float angleY = static_cast<float>(j)*AL::Math::TO_RAD; const AL::Math::Quaternion quatY = AL::Math::quaternionFromAngleAndAxisRotation(angleY, 0.0f, 1.0f, 0.0f); for (int k=-180; k<180; ++k) { const float angleZ = static_cast<float>(k)*AL::Math::TO_RAD; const AL::Math::Quaternion quatZ = AL::Math::quaternionFromAngleAndAxisRotation(angleZ, 0.0f, 0.0f, 1.0f); const AL::Math::Quaternion quatExpected = quatZ*quatY*quatX; const AL::Math::Rotation3D rot3D = AL::Math::rotation3DFromQuaternion(quatExpected); const AL::Math::Quaternion quatResult = AL::Math::quaternionFromRotation3D(rot3D); EXPECT_TRUE(quatExpected.isNear(quatResult, 0.001f)); } } } } TEST(ALMathTest, quaternionPosition3DFromPosition6D) { // function quaternionFromRotation3D must be check before const float lEpsilon = 0.001f; const AL::Math::Position6D pos6D = AL::Math::Position6D(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f); AL::Math::Quaternion qua; AL::Math::Position3D pos3D; AL::Math::quaternionPosition3DFromPosition6D(pos6D, qua, pos3D); const AL::Math::Quaternion quaExpected = AL::Math::quaternionFromRotation3D(AL::Math::Rotation3D(0.4f, 0.5f, 0.6f)); EXPECT_TRUE(qua.isNear(quaExpected, lEpsilon)); EXPECT_TRUE(pos3D.isNear(AL::Math::Position3D(0.1f, 0.2f, 0.3f), lEpsilon)); } TEST(ALMathTest, pointMassRotationalInertia) { AL::Math::Position3D pos123(1.f, 2.f, 3.f); std::vector<float> inertia; pointMassRotationalInertia(0.f, pos123, inertia); ASSERT_EQ(9, inertia.size()); ASSERT_EQ(std::vector<float>(9, 0.f), inertia); pointMassRotationalInertia(1.f, AL::Math::Position3D(), inertia); ASSERT_EQ(std::vector<float>(9, 0.f), inertia); float m10 = 10.f; pointMassRotationalInertia(m10, pos123, inertia); // check symmetry ASSERT_TRUE(inertia[1] == inertia[3]); ASSERT_TRUE(inertia[2] == inertia[6]); ASSERT_TRUE(inertia[5] == inertia[7]); // check values ASSERT_EQ(m10*(4+9), inertia[0]); ASSERT_EQ(m10*(1+9), inertia[4]); ASSERT_EQ(m10*(1+4), inertia[8]); ASSERT_EQ(-m10*1*2, inertia[1]); ASSERT_EQ(-m10*1*3, inertia[2]); ASSERT_EQ(-m10*2*3, inertia[5]); }
33.315013
98
0.660041
UCCS-Social-Robotics
435c602d991cf6408bff6ea148b1a47b1bfbccee
60
cpp
C++
build/sharedLib/mainLoad.cpp
NoCodeProgram/ModernCPP
ac7b05a4d720678e68878d70c0a7a69f56885d00
[ "MIT" ]
5
2020-08-17T12:14:44.000Z
2022-01-21T06:57:56.000Z
build/sharedLib/mainLoad.cpp
NoCodeProgram/ModernCPP
ac7b05a4d720678e68878d70c0a7a69f56885d00
[ "MIT" ]
null
null
null
build/sharedLib/mainLoad.cpp
NoCodeProgram/ModernCPP
ac7b05a4d720678e68878d70c0a7a69f56885d00
[ "MIT" ]
2
2022-01-18T03:20:51.000Z
2022-02-11T14:50:19.000Z
void foo(); //declaration int main() { foo(); return 0; }
8.571429
25
0.583333
NoCodeProgram
435d48631cdc82fb11740cdf32032fddf60b1e4a
238
cpp
C++
day-12-7-1.cpp
duasong111/c_lang_learn
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
[ "BSD-2-Clause" ]
null
null
null
day-12-7-1.cpp
duasong111/c_lang_learn
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
[ "BSD-2-Clause" ]
null
null
null
day-12-7-1.cpp
duasong111/c_lang_learn
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
[ "BSD-2-Clause" ]
null
null
null
//对于printf,其实还有更牛逼的用法,拿那个输出举例 #include<stdio.h> int main(void) { int i; int x; printf("你想有几行呢?"); scanf_s("%d", &x); for (i = 1; i <= x; i++) printf("%*d\n", i, i % 10); //超级喜欢这个%*d,i,i%10; 直接省略了我两行代码 return 0; }
18.307692
35
0.529412
duasong111
cb1f7a7c44a2ea331c78925fa71f73d8e19b1989
16,874
cpp
C++
tesseract_ros_examples/src/car_seat_example.cpp
cbw36/tesseract_ros
a430b59ef95220232628e4e2266f0a31e82134de
[ "Apache-2.0", "BSD-2-Clause" ]
1
2020-04-02T22:15:06.000Z
2020-04-02T22:15:06.000Z
tesseract_ros_examples/src/car_seat_example.cpp
cbw36/tesseract_ros
a430b59ef95220232628e4e2266f0a31e82134de
[ "Apache-2.0", "BSD-2-Clause" ]
null
null
null
tesseract_ros_examples/src/car_seat_example.cpp
cbw36/tesseract_ros
a430b59ef95220232628e4e2266f0a31e82134de
[ "Apache-2.0", "BSD-2-Clause" ]
null
null
null
/** * @file car_seat_example.cpp * @brief Car seat example implementation * * @author Levi Armstrong * @date July 22, 2019 * @version TODO * @bug No known bugs * * @copyright Copyright (c) 2017, Southwest Research Institute * * @par License * Software License Agreement (Apache License) * @par * 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 * @par * 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 <tesseract_common/macros.h> TESSERACT_COMMON_IGNORE_WARNINGS_PUSH #include <ros/ros.h> #include <memory> TESSERACT_COMMON_IGNORE_WARNINGS_POP #include <tesseract_ros_examples/car_seat_example.h> #include <tesseract_environment/core/utils.h> #include <tesseract_environment/core/commands.h> #include <tesseract_rosutils/plotting.h> #include <tesseract_rosutils/utils.h> #include <tesseract_geometry/mesh_parser.h> #include <tesseract_command_language/command_language.h> #include <tesseract_command_language/profile_dictionary.h> #include <tesseract_command_language/utils/utils.h> #include <tesseract_process_managers/core/process_planning_server.h> #include <tesseract_process_managers/core/default_process_planners.h> #include <tesseract_motion_planners/trajopt/profile/trajopt_default_composite_profile.h> #include <tesseract_motion_planners/trajopt/profile/trajopt_default_solver_profile.h> #include <tesseract_motion_planners/core/utils.h> #include <tesseract_planning_server/tesseract_planning_server.h> #include <tesseract_visualization/markers/toolpath_marker.h> using namespace tesseract_environment; using namespace tesseract_kinematics; using namespace tesseract_scene_graph; using namespace tesseract_collision; using namespace tesseract_rosutils; using namespace tesseract_visualization; /**@ Default ROS parameter for robot description */ const std::string ROBOT_DESCRIPTION_PARAM = "robot_description"; /**@ Default ROS parameter for robot description */ const std::string ROBOT_SEMANTIC_PARAM = "robot_description_semantic"; /** @brief RViz Example Namespace */ const std::string EXAMPLE_MONITOR_NAMESPACE = "tesseract_ros_examples"; namespace tesseract_ros_examples { Commands addSeats(const ResourceLocator::Ptr& locator) { Commands cmds; for (int i = 0; i < 3; ++i) { Link link_seat("seat_" + std::to_string(i + 1)); Visual::Ptr visual = std::make_shared<Visual>(); visual->origin = Eigen::Isometry3d::Identity(); visual->geometry = tesseract_geometry::createMeshFromResource<tesseract_geometry::Mesh>(locator->locateResource("package://" "tesseract_ros_" "examples/meshes/" "car_seat/visual/" "seat.dae"), Eigen::Vector3d(1, 1, 1), true)[0]; link_seat.visual.push_back(visual); for (int m = 1; m <= 10; ++m) { std::vector<tesseract_geometry::Mesh::Ptr> meshes = tesseract_geometry::createMeshFromResource<tesseract_geometry::Mesh>( locator->locateResource("package://tesseract_ros_examples/" "meshes/car_seat/collision/seat_" + std::to_string(m) + ".stl")); for (auto& mesh : meshes) { Collision::Ptr collision = std::make_shared<Collision>(); collision->origin = visual->origin; collision->geometry = makeConvexMesh(*mesh); link_seat.collision.push_back(collision); } } Joint joint_seat("joint_seat_" + std::to_string(i + 1)); joint_seat.parent_link_name = "world"; joint_seat.child_link_name = link_seat.getName(); joint_seat.type = JointType::FIXED; joint_seat.parent_to_joint_origin_transform = Eigen::AngleAxisd(0.0, Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(0.0, Eigen::Vector3d::UnitY()) * Eigen::AngleAxisd(3.14159, Eigen::Vector3d::UnitZ()); joint_seat.parent_to_joint_origin_transform.translation() = Eigen::Vector3d(0.5 + i, 2.15, 0.45); cmds.push_back(std::make_shared<tesseract_environment::AddLinkCommand>(link_seat, joint_seat)); } return cmds; } CarSeatExample::CarSeatExample(const ros::NodeHandle& nh, bool plotting, bool rviz) : Example(plotting, rviz), nh_(nh) { } std::unordered_map<std::string, std::unordered_map<std::string, double>> CarSeatExample::getPredefinedPosition() { std::unordered_map<std::string, std::unordered_map<std::string, double>> result; std::unordered_map<std::string, double> default_pos; default_pos["carriage_rail"] = 1.0; default_pos["joint_b"] = 0.0; default_pos["joint_e"] = 0.0; default_pos["joint_l"] = 0.0; default_pos["joint_r"] = 0.0; default_pos["joint_s"] = -1.5707; default_pos["joint_t"] = 0.0; default_pos["joint_u"] = -1.5707; result["Default"] = default_pos; std::unordered_map<std::string, double> pick1; pick1["carriage_rail"] = 2.22; pick1["joint_b"] = 0.39; pick1["joint_e"] = 0.0; pick1["joint_l"] = 0.5; pick1["joint_r"] = 0.0; pick1["joint_s"] = -3.14; pick1["joint_t"] = -0.29; pick1["joint_u"] = -1.45; result["Pick1"] = pick1; std::unordered_map<std::string, double> pick2; pick2["carriage_rail"] = 1.22; pick1["joint_b"] = 0.39; pick1["joint_e"] = 0.0; pick1["joint_l"] = 0.5; pick1["joint_r"] = 0.0; pick1["joint_s"] = -3.14; pick1["joint_t"] = -0.29; pick1["joint_u"] = -1.45; result["Pick2"] = pick2; std::unordered_map<std::string, double> pick3; pick3["carriage_rail"] = 0.22; pick1["joint_b"] = 0.39; pick1["joint_e"] = 0.0; pick1["joint_l"] = 0.5; pick1["joint_r"] = 0.0; pick1["joint_s"] = -3.14; pick1["joint_t"] = -0.29; pick1["joint_u"] = -1.45; result["Pick3"] = pick3; std::unordered_map<std::string, double> place1; place1["carriage_rail"] = 4.15466; place1["joint_b"] = 0.537218; place1["joint_e"] = 0.0189056; place1["joint_l"] = 0.801223; place1["joint_r"] = 0.0580309; place1["joint_s"] = -0.0481182; place1["joint_t"] = -0.325783; place1["joint_u"] = -1.2813; result["Place1"] = place1; std::unordered_map<std::string, double> home; home["carriage_rail"] = 0.0; home["joint_b"] = 0.0; home["joint_e"] = 0.0; home["joint_l"] = 0.0; home["joint_r"] = 0.0; home["joint_s"] = 0.0; home["joint_t"] = 0.0; home["joint_u"] = 0.0; result["Home"] = home; return result; } std::vector<double> CarSeatExample::getPositionVector(const ForwardKinematics::ConstPtr& kin, const std::unordered_map<std::string, double>& pos) { std::vector<double> result; for (const auto& joint_name : kin->getJointNames()) result.push_back(pos.at(joint_name)); return result; } Eigen::VectorXd CarSeatExample::getPositionVectorXd(const ForwardKinematics::ConstPtr& kin, const std::unordered_map<std::string, double>& pos) { Eigen::VectorXd result; result.resize(kin->numJoints()); int cnt = 0; for (const auto& joint_name : kin->getJointNames()) result[cnt++] = pos.at(joint_name); return result; } bool CarSeatExample::run() { using tesseract_planning::CartesianWaypoint; using tesseract_planning::CompositeInstruction; using tesseract_planning::CompositeInstructionOrder; using tesseract_planning::Instruction; using tesseract_planning::ManipulatorInfo; using tesseract_planning::PlanInstruction; using tesseract_planning::PlanInstructionType; using tesseract_planning::ProcessPlanningFuture; using tesseract_planning::ProcessPlanningRequest; using tesseract_planning::ProcessPlanningServer; using tesseract_planning::StateWaypoint; using tesseract_planning::Waypoint; using tesseract_planning_server::ROSProcessEnvironmentCache; console_bridge::setLogLevel(console_bridge::LogLevel::CONSOLE_BRIDGE_LOG_DEBUG); // Initial setup std::string urdf_xml_string, srdf_xml_string; nh_.getParam(ROBOT_DESCRIPTION_PARAM, urdf_xml_string); nh_.getParam(ROBOT_SEMANTIC_PARAM, srdf_xml_string); ResourceLocator::Ptr locator = std::make_shared<tesseract_rosutils::ROSResourceLocator>(); if (!env_->init<OFKTStateSolver>(urdf_xml_string, srdf_xml_string, locator)) return false; // Create monitor monitor_ = std::make_shared<tesseract_monitoring::EnvironmentMonitor>(env_, EXAMPLE_MONITOR_NAMESPACE); if (rviz_) monitor_->startPublishingEnvironment(tesseract_monitoring::EnvironmentMonitor::UPDATE_ENVIRONMENT); // Get manipulator ForwardKinematics::Ptr fwd_kin; { // Need to lock monitor for read auto lock = monitor_->lockEnvironmentRead(); fwd_kin = monitor_->getEnvironment()->getManipulatorManager()->getFwdKinematicSolver("manipulator"); } // Create seats and add it to the local environment Commands cmds = addSeats(locator); if (!monitor_->applyCommands(cmds)) return false; // Create plotting tool ROSPlottingPtr plotter = std::make_shared<ROSPlotting>(monitor_->getSceneGraph()->getRoot()); if (rviz_) plotter->waitForConnection(); if (rviz_ && plotter != nullptr && plotter->isConnected()) plotter->waitForInput(); // Get predefined positions saved_positions_ = getPredefinedPosition(); // Move to home position env_->setState(saved_positions_["Home"]); // Create Process Planning Server ProcessPlanningServer planning_server(std::make_shared<ROSProcessEnvironmentCache>(monitor_), 5); planning_server.loadDefaultProcessPlanners(); // Create TrajOpt Profile auto trajopt_composite_profile = std::make_shared<tesseract_planning::TrajOptDefaultCompositeProfile>(); trajopt_composite_profile->collision_constraint_config.enabled = false; trajopt_composite_profile->collision_cost_config.safety_margin = 0.005; trajopt_composite_profile->collision_cost_config.coeff = 50; auto trajopt_solver_profile = std::make_shared<tesseract_planning::TrajOptDefaultSolverProfile>(); trajopt_solver_profile->opt_info.max_iter = 200; trajopt_solver_profile->opt_info.min_approx_improve = 1e-3; trajopt_solver_profile->opt_info.min_trust_box_size = 1e-3; // Add profile to Dictionary planning_server.getProfiles()->addProfile<tesseract_planning::TrajOptCompositeProfile>("FREESPACE", trajopt_composite_profile); planning_server.getProfiles()->addProfile<tesseract_planning::TrajOptSolverProfile>("FREESPACE", trajopt_solver_profile); // Solve Trajectory ROS_INFO("Car Seat Demo Started"); { // Create Program to pick up first seat CompositeInstruction program("FREESPACE", CompositeInstructionOrder::ORDERED, ManipulatorInfo("manipulator")); program.setDescription("Pick up the first seat!"); // Start and End Joint Position for the program Eigen::VectorXd start_pos = getPositionVectorXd(fwd_kin, saved_positions_["Home"]); Eigen::VectorXd pick_pose = getPositionVectorXd(fwd_kin, saved_positions_["Pick1"]); Waypoint wp0 = StateWaypoint(fwd_kin->getJointNames(), start_pos); Waypoint wp1 = StateWaypoint(fwd_kin->getJointNames(), pick_pose); // Start Joint Position for the program PlanInstruction start_instruction(wp0, PlanInstructionType::START); program.setStartInstruction(start_instruction); // Plan freespace from start PlanInstruction plan_f0(wp1, PlanInstructionType::FREESPACE, "FREESPACE"); plan_f0.setDescription("Freespace pick seat 1"); // Add Instructions to program program.push_back(plan_f0); ROS_INFO("Freespace plan to pick seat 1 example"); // Create Process Planning Request ProcessPlanningRequest request; request.name = tesseract_planning::process_planner_names::TRAJOPT_PLANNER_NAME; request.instructions = Instruction(program); // Print Diagnostics request.instructions.print("Program: "); // Solve process plan ProcessPlanningFuture response = planning_server.run(request); planning_server.waitForAll(); // Plot Process Trajectory if (rviz_ && plotter != nullptr && plotter->isConnected()) { const auto* ci = response.results->cast_const<tesseract_planning::CompositeInstruction>(); tesseract_common::Toolpath toolpath = tesseract_planning::toToolpath(*ci, env_); tesseract_common::JointTrajectory trajectory = tesseract_planning::toJointTrajectory(*ci); plotter->plotMarker(ToolpathMarker(toolpath)); plotter->plotTrajectory(trajectory, env_->getStateSolver()); plotter->waitForInput(); } } // Get the state at the end of pick 1 trajectory EnvState::Ptr state = env_->getState(saved_positions_["Pick1"]); // Now we to detach seat_1 and attach it to the robot end_effector Joint joint_seat_1_robot("joint_seat_1_robot"); joint_seat_1_robot.parent_link_name = "end_effector"; joint_seat_1_robot.child_link_name = "seat_1"; joint_seat_1_robot.type = JointType::FIXED; joint_seat_1_robot.parent_to_joint_origin_transform = state->link_transforms["end_effector"].inverse() * state->link_transforms["seat_1"]; cmds.clear(); cmds.push_back(std::make_shared<MoveLinkCommand>(joint_seat_1_robot)); cmds.push_back(std::make_shared<AddAllowedCollisionCommand>("seat_1", "end_effector", "Adjacent")); cmds.push_back(std::make_shared<AddAllowedCollisionCommand>("seat_1", "cell_logo", "Never")); cmds.push_back(std::make_shared<AddAllowedCollisionCommand>("seat_1", "fence", "Never")); cmds.push_back(std::make_shared<AddAllowedCollisionCommand>("seat_1", "link_b", "Never")); cmds.push_back(std::make_shared<AddAllowedCollisionCommand>("seat_1", "link_r", "Never")); cmds.push_back(std::make_shared<AddAllowedCollisionCommand>("seat_1", "link_t", "Never")); // Apply the commands to the environment if (!monitor_->applyCommands(cmds)) return false; { // Create Program to place first seat CompositeInstruction program("FREESPACE", CompositeInstructionOrder::ORDERED, ManipulatorInfo("manipulator")); program.setDescription("Place the first seat!"); // Start and End Joint Position for the program Eigen::VectorXd start_pos = getPositionVectorXd(fwd_kin, saved_positions_["Pick1"]); Eigen::VectorXd pick_pose = getPositionVectorXd(fwd_kin, saved_positions_["Place1"]); Waypoint wp0 = StateWaypoint(fwd_kin->getJointNames(), start_pos); Waypoint wp1 = StateWaypoint(fwd_kin->getJointNames(), pick_pose); // Start Joint Position for the program PlanInstruction start_instruction(wp0, PlanInstructionType::START); program.setStartInstruction(start_instruction); // Plan freespace from start PlanInstruction plan_f0(wp1, PlanInstructionType::FREESPACE, "FREESPACE"); plan_f0.setDescription("Freespace pick seat 1"); // Add Instructions to program program.push_back(plan_f0); ROS_INFO("Freespace plan to pick seat 1 example"); // Create Process Planning Request ProcessPlanningRequest request; request.name = tesseract_planning::process_planner_names::TRAJOPT_PLANNER_NAME; request.instructions = Instruction(program); // Print Diagnostics request.instructions.print("Program: "); // Solve process plan ProcessPlanningFuture response = planning_server.run(request); planning_server.waitForAll(); // Plot Process Trajectory if (rviz_ && plotter != nullptr && plotter->isConnected()) { const auto* ci = response.results->cast_const<tesseract_planning::CompositeInstruction>(); tesseract_common::Toolpath toolpath = tesseract_planning::toToolpath(*ci, env_); tesseract_common::JointTrajectory trajectory = tesseract_planning::toJointTrajectory(*ci); plotter->plotMarker(ToolpathMarker(toolpath)); plotter->plotTrajectory(trajectory, env_->getStateSolver()); plotter->waitForInput(); } } return true; } } // namespace tesseract_ros_examples
40.17619
119
0.697523
cbw36
cb233dcaf44452982b7c4027090c202c6013b585
16,107
cpp
C++
src/Magnum/GL/Test/AbstractTextureGLTest.cpp
pinojojo/magnum
aef0ee4bfba8dd0e6b23bee4e170faf66c3e0e96
[ "MIT" ]
1
2022-02-18T06:19:35.000Z
2022-02-18T06:19:35.000Z
src/Magnum/GL/Test/AbstractTextureGLTest.cpp
pinojojo/magnum
aef0ee4bfba8dd0e6b23bee4e170faf66c3e0e96
[ "MIT" ]
null
null
null
src/Magnum/GL/Test/AbstractTextureGLTest.cpp
pinojojo/magnum
aef0ee4bfba8dd0e6b23bee4e170faf66c3e0e96
[ "MIT" ]
null
null
null
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Vladimír Vondruš <mosra@centrum.cz> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <sstream> #include <Corrade/Utility/DebugStl.h> #include "Magnum/ImageView.h" #include "Magnum/GL/Context.h" #include "Magnum/GL/Extensions.h" #include "Magnum/GL/PixelFormat.h" #include "Magnum/GL/Texture.h" #include "Magnum/GL/TextureFormat.h" #include "Magnum/GL/OpenGLTester.h" #include "Magnum/Math/Range.h" namespace Magnum { namespace GL { namespace Test { namespace { struct AbstractTextureGLTest: OpenGLTester { explicit AbstractTextureGLTest(); void construct(); void constructMove(); #ifndef MAGNUM_TARGET_GLES void imageQueryViewNullptr(); void imageQueryViewBadSize(); void subImageQueryViewNullptr(); void subImageQueryViewBadSize(); void compressedImageQueryViewNullptr(); void compressedImageQueryViewBadSize(); void compressedImageQueryViewBadDataSize(); void compressedImageQueryViewBadFormat(); void compressedSubImageQueryViewNullptr(); void compressedSubImageQueryViewBadSize(); void compressedSubImageQueryViewBadDataSize(); void compressedSubImageQueryViewBadFormat(); #endif #ifndef MAGNUM_TARGET_WEBGL void label(); #endif }; AbstractTextureGLTest::AbstractTextureGLTest() { addTests({&AbstractTextureGLTest::construct, &AbstractTextureGLTest::constructMove, #ifndef MAGNUM_TARGET_GLES &AbstractTextureGLTest::imageQueryViewNullptr, &AbstractTextureGLTest::imageQueryViewBadSize, &AbstractTextureGLTest::subImageQueryViewNullptr, &AbstractTextureGLTest::subImageQueryViewBadSize, &AbstractTextureGLTest::compressedImageQueryViewNullptr, &AbstractTextureGLTest::compressedImageQueryViewBadSize, &AbstractTextureGLTest::compressedImageQueryViewBadDataSize, &AbstractTextureGLTest::compressedImageQueryViewBadFormat, &AbstractTextureGLTest::compressedSubImageQueryViewNullptr, &AbstractTextureGLTest::compressedSubImageQueryViewBadSize, &AbstractTextureGLTest::compressedSubImageQueryViewBadDataSize, &AbstractTextureGLTest::compressedSubImageQueryViewBadFormat, #endif #ifndef MAGNUM_TARGET_WEBGL &AbstractTextureGLTest::label #endif }); } void AbstractTextureGLTest::construct() { { const Texture2D texture; MAGNUM_VERIFY_NO_GL_ERROR(); CORRADE_VERIFY(texture.id() > 0); CORRADE_COMPARE(texture.target(), GL_TEXTURE_2D); } MAGNUM_VERIFY_NO_GL_ERROR(); } void AbstractTextureGLTest::constructMove() { Texture2D a; const Int id = a.id(); MAGNUM_VERIFY_NO_GL_ERROR(); CORRADE_VERIFY(id > 0); Texture2D b(std::move(a)); CORRADE_COMPARE(a.id(), 0); CORRADE_COMPARE(b.id(), id); Texture2D c; const Int cId = c.id(); c = std::move(b); MAGNUM_VERIFY_NO_GL_ERROR(); CORRADE_VERIFY(cId > 0); CORRADE_COMPARE(b.id(), cId); CORRADE_COMPARE(c.id(), id); } #ifndef MAGNUM_TARGET_GLES void AbstractTextureGLTest::imageQueryViewNullptr() { #ifdef CORRADE_NO_ASSERT CORRADE_SKIP("CORRADE_NO_ASSERT defined, can't test assertions"); #endif Texture2D texture; texture.setStorage(1, TextureFormat::RGBA8, Vector2i{2}); MAGNUM_VERIFY_NO_GL_ERROR(); MutableImageView2D image{PixelFormat::RGBA, PixelType::UnsignedByte, Vector2i{2}, {nullptr, 2*2*4}}; std::ostringstream out; Error redirectError{&out}; texture.image(0, image); CORRADE_COMPARE(out.str(), "GL::AbstractTexture::image(): image view is nullptr\n"); } void AbstractTextureGLTest::imageQueryViewBadSize() { #ifdef CORRADE_NO_ASSERT CORRADE_SKIP("CORRADE_NO_ASSERT defined, can't test assertions"); #endif Texture2D texture; texture.setStorage(1, TextureFormat::RGBA8, Vector2i{2}); MAGNUM_VERIFY_NO_GL_ERROR(); char data[2*4]; MutableImageView2D image{PixelFormat::RGBA, PixelType::UnsignedByte, Vector2i{2, 1}, data}; std::ostringstream out; Error redirectError{&out}; texture.image(0, image); CORRADE_COMPARE(out.str(), "GL::AbstractTexture::image(): expected image view size Vector(2, 2) but got Vector(2, 1)\n"); } void AbstractTextureGLTest::subImageQueryViewNullptr() { #ifdef CORRADE_NO_ASSERT CORRADE_SKIP("CORRADE_NO_ASSERT defined, can't test assertions"); #endif Texture2D texture; texture.setStorage(1, TextureFormat::RGBA8, Vector2i{2}); MAGNUM_VERIFY_NO_GL_ERROR(); MutableImageView2D image{PixelFormat::RGBA, PixelType::UnsignedByte, Vector2i{2}, {nullptr, 2*2*4}}; std::ostringstream out; Error redirectError{&out}; texture.subImage(0, {{}, Vector2i{2}}, image); CORRADE_COMPARE(out.str(), "GL::AbstractTexture::subImage(): image view is nullptr\n"); } void AbstractTextureGLTest::subImageQueryViewBadSize() { #ifdef CORRADE_NO_ASSERT CORRADE_SKIP("CORRADE_NO_ASSERT defined, can't test assertions"); #endif if(!Context::current().isExtensionSupported<Extensions::ARB::get_texture_sub_image>()) CORRADE_SKIP(Extensions::ARB::get_texture_sub_image::string() << "is not supported."); Texture2D texture; texture.setStorage(1, TextureFormat::RGBA8, Vector2i{2}); MAGNUM_VERIFY_NO_GL_ERROR(); char data[2*4]; MutableImageView2D image{PixelFormat::RGBA, PixelType::UnsignedByte, Vector2i{2, 1}, data}; std::ostringstream out; Error redirectError{&out}; texture.subImage(0, {{}, Vector2i{2}}, image); CORRADE_COMPARE(out.str(), "GL::AbstractTexture::subImage(): expected image view size Vector(2, 2) but got Vector(2, 1)\n"); } void AbstractTextureGLTest::compressedImageQueryViewNullptr() { #ifdef CORRADE_NO_ASSERT CORRADE_SKIP("CORRADE_NO_ASSERT defined, can't test assertions"); #endif if(!Context::current().isExtensionSupported<Extensions::EXT::texture_compression_s3tc>()) CORRADE_SKIP(Extensions::EXT::texture_compression_s3tc::string() << "is not supported."); Texture2D texture; texture.setStorage(1, TextureFormat::CompressedRGBAS3tcDxt3, Vector2i{4}); MAGNUM_VERIFY_NO_GL_ERROR(); MutableCompressedImageView2D image{CompressedPixelFormat::RGBAS3tcDxt3, Vector2i{4}, {nullptr, 16}}; std::ostringstream out; Error redirectError{&out}; texture.compressedImage(0, image); CORRADE_COMPARE(out.str(), "GL::AbstractTexture::compressedImage(): image view is nullptr\n"); } void AbstractTextureGLTest::compressedImageQueryViewBadSize() { #ifdef CORRADE_NO_ASSERT CORRADE_SKIP("CORRADE_NO_ASSERT defined, can't test assertions"); #endif if(!Context::current().isExtensionSupported<Extensions::EXT::texture_compression_s3tc>()) CORRADE_SKIP(Extensions::EXT::texture_compression_s3tc::string() << "is not supported."); Texture2D texture; texture.setStorage(1, TextureFormat::CompressedRGBAS3tcDxt3, Vector2i{4}); MAGNUM_VERIFY_NO_GL_ERROR(); char data[2*16]; MutableCompressedImageView2D image{CompressedPixelFormat::RGBAS3tcDxt3, Vector2i{4, 8}, data}; std::ostringstream out; Error redirectError{&out}; texture.compressedImage(0, image); CORRADE_COMPARE(out.str(), "GL::AbstractTexture::compressedImage(): expected image view size Vector(4, 4) but got Vector(4, 8)\n"); } void AbstractTextureGLTest::compressedImageQueryViewBadDataSize() { #ifdef CORRADE_NO_ASSERT CORRADE_SKIP("CORRADE_NO_ASSERT defined, can't test assertions"); #endif if(!Context::current().isExtensionSupported<Extensions::EXT::texture_compression_s3tc>()) CORRADE_SKIP(Extensions::EXT::texture_compression_s3tc::string() << "is not supported."); Texture2D texture; texture.setStorage(1, TextureFormat::CompressedRGBAS3tcDxt3, Vector2i{4}); MAGNUM_VERIFY_NO_GL_ERROR(); char data[16 - 1]; MutableCompressedImageView2D image{CompressedPixelFormat::RGBAS3tcDxt3, Vector2i{4}, data}; std::ostringstream out; Error redirectError{&out}; texture.compressedImage(0, image); CORRADE_COMPARE(out.str(), "GL::AbstractTexture::compressedImage(): expected image view data size 16 bytes but got 15\n"); } void AbstractTextureGLTest::compressedImageQueryViewBadFormat() { #ifdef CORRADE_NO_ASSERT CORRADE_SKIP("CORRADE_NO_ASSERT defined, can't test assertions"); #endif if(!Context::current().isExtensionSupported<Extensions::EXT::texture_compression_s3tc>()) CORRADE_SKIP(Extensions::EXT::texture_compression_s3tc::string() << "is not supported."); Texture2D texture; texture.setStorage(1, TextureFormat::CompressedRGBAS3tcDxt3, Vector2i{4}); MAGNUM_VERIFY_NO_GL_ERROR(); char data[16]; MutableCompressedImageView2D image{CompressedPixelFormat::RGBAS3tcDxt1, Vector2i{4}, data}; std::ostringstream out; Error redirectError{&out}; texture.compressedImage(0, image); CORRADE_COMPARE(out.str(), "GL::AbstractTexture::compressedImage(): expected image view format GL::CompressedPixelFormat::RGBAS3tcDxt3 but got GL::CompressedPixelFormat::RGBAS3tcDxt1\n"); } void AbstractTextureGLTest::compressedSubImageQueryViewNullptr() { #ifdef CORRADE_NO_ASSERT CORRADE_SKIP("CORRADE_NO_ASSERT defined, can't test assertions"); #endif if(!Context::current().isExtensionSupported<Extensions::ARB::get_texture_sub_image>()) CORRADE_SKIP(Extensions::ARB::get_texture_sub_image::string() << "is not supported."); if(!Context::current().isExtensionSupported<Extensions::EXT::texture_compression_s3tc>()) CORRADE_SKIP(Extensions::EXT::texture_compression_s3tc::string() << "is not supported."); if(!Context::current().isExtensionSupported<Extensions::ARB::internalformat_query2>()) CORRADE_SKIP(Extensions::ARB::internalformat_query2::string() << "is not supported."); Texture2D texture; texture.setStorage(1, TextureFormat::CompressedRGBAS3tcDxt3, Vector2i{4}); MAGNUM_VERIFY_NO_GL_ERROR(); MutableCompressedImageView2D image{CompressedPixelFormat::RGBAS3tcDxt3, Vector2i{4}, {nullptr, 16}}; std::ostringstream out; Error redirectError{&out}; texture.compressedSubImage(0, {{}, Vector2i{4}}, image); CORRADE_COMPARE(out.str(), "GL::AbstractTexture::compressedSubImage(): image view is nullptr\n"); } void AbstractTextureGLTest::compressedSubImageQueryViewBadSize() { #ifdef CORRADE_NO_ASSERT CORRADE_SKIP("CORRADE_NO_ASSERT defined, can't test assertions"); #endif if(!Context::current().isExtensionSupported<Extensions::ARB::get_texture_sub_image>()) CORRADE_SKIP(Extensions::ARB::get_texture_sub_image::string() << "is not supported."); if(!Context::current().isExtensionSupported<Extensions::EXT::texture_compression_s3tc>()) CORRADE_SKIP(Extensions::EXT::texture_compression_s3tc::string() << "is not supported."); if(!Context::current().isExtensionSupported<Extensions::ARB::internalformat_query2>()) CORRADE_SKIP(Extensions::ARB::internalformat_query2::string() << "is not supported."); Texture2D texture; texture.setStorage(1, TextureFormat::CompressedRGBAS3tcDxt3, Vector2i{4}); MAGNUM_VERIFY_NO_GL_ERROR(); char data[2*16]; MutableCompressedImageView2D image{CompressedPixelFormat::RGBAS3tcDxt3, Vector2i{4, 8}, data}; std::ostringstream out; Error redirectError{&out}; texture.compressedSubImage(0, {{}, Vector2i{4}}, image); CORRADE_COMPARE(out.str(), "GL::AbstractTexture::compressedSubImage(): expected image view size Vector(4, 4) but got Vector(4, 8)\n"); } void AbstractTextureGLTest::compressedSubImageQueryViewBadDataSize() { #ifdef CORRADE_NO_ASSERT CORRADE_SKIP("CORRADE_NO_ASSERT defined, can't test assertions"); #endif if(!Context::current().isExtensionSupported<Extensions::ARB::get_texture_sub_image>()) CORRADE_SKIP(Extensions::ARB::get_texture_sub_image::string() << "is not supported."); if(!Context::current().isExtensionSupported<Extensions::EXT::texture_compression_s3tc>()) CORRADE_SKIP(Extensions::EXT::texture_compression_s3tc::string() << "is not supported."); if(!Context::current().isExtensionSupported<Extensions::ARB::internalformat_query2>()) CORRADE_SKIP(Extensions::ARB::internalformat_query2::string() << "is not supported."); Texture2D texture; texture.setStorage(1, TextureFormat::CompressedRGBAS3tcDxt3, Vector2i{4}); MAGNUM_VERIFY_NO_GL_ERROR(); char data[16 - 1]; MutableCompressedImageView2D image{CompressedPixelFormat::RGBAS3tcDxt3, Vector2i{4}, data}; std::ostringstream out; Error redirectError{&out}; texture.compressedSubImage(0, {{}, Vector2i{4}}, image); CORRADE_COMPARE(out.str(), "GL::AbstractTexture::compressedSubImage(): expected image view data size 16 bytes but got 15\n"); } void AbstractTextureGLTest::compressedSubImageQueryViewBadFormat() { #ifdef CORRADE_NO_ASSERT CORRADE_SKIP("CORRADE_NO_ASSERT defined, can't test assertions"); #endif if(!Context::current().isExtensionSupported<Extensions::ARB::get_texture_sub_image>()) CORRADE_SKIP(Extensions::ARB::get_texture_sub_image::string() << "is not supported."); if(!Context::current().isExtensionSupported<Extensions::EXT::texture_compression_s3tc>()) CORRADE_SKIP(Extensions::EXT::texture_compression_s3tc::string() << "is not supported."); if(!Context::current().isExtensionSupported<Extensions::ARB::internalformat_query2>()) CORRADE_SKIP(Extensions::ARB::internalformat_query2::string() << "is not supported."); Texture2D texture; texture.setStorage(1, TextureFormat::CompressedRGBAS3tcDxt3, Vector2i{4}); MAGNUM_VERIFY_NO_GL_ERROR(); char data[16]; MutableCompressedImageView2D image{CompressedPixelFormat::RGBAS3tcDxt1, Vector2i{4}, data}; std::ostringstream out; Error redirectError{&out}; texture.compressedSubImage(0, {{}, Vector2i{4}}, image); CORRADE_COMPARE(out.str(), "GL::AbstractTexture::compressedSubImage(): expected image view format GL::CompressedPixelFormat::RGBAS3tcDxt3 but got GL::CompressedPixelFormat::RGBAS3tcDxt1\n"); } #endif #ifndef MAGNUM_TARGET_WEBGL void AbstractTextureGLTest::label() { /* No-Op version is tested in AbstractObjectGLTest */ if(!Context::current().isExtensionSupported<Extensions::KHR::debug>() && !Context::current().isExtensionSupported<Extensions::EXT::debug_label>()) CORRADE_SKIP("Required extension is not available"); Texture2D texture; CORRADE_COMPARE(texture.label(), ""); MAGNUM_VERIFY_NO_GL_ERROR(); texture.setLabel("MyTexture"); MAGNUM_VERIFY_NO_GL_ERROR(); CORRADE_COMPARE(texture.label(), "MyTexture"); } #endif }}}} CORRADE_TEST_MAIN(Magnum::GL::Test::AbstractTextureGLTest)
38.533493
194
0.729124
pinojojo
cb23c86660a5e07a0590c6395424b3346265745b
9,404
cpp
C++
src/ssa/ssa_dereference.cpp
KentrilDespair/2ls
29b5de1abe0abee3ea07109deb9430c45756831d
[ "BSD-4-Clause" ]
null
null
null
src/ssa/ssa_dereference.cpp
KentrilDespair/2ls
29b5de1abe0abee3ea07109deb9430c45756831d
[ "BSD-4-Clause" ]
null
null
null
src/ssa/ssa_dereference.cpp
KentrilDespair/2ls
29b5de1abe0abee3ea07109deb9430c45756831d
[ "BSD-4-Clause" ]
null
null
null
/*******************************************************************\ Module: Aliasing Decision Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ /// \file /// Aliasing Decision // #define DEBUG #ifdef DEBUG #include <iostream> #include <langapi/language_util.h> #endif #include <util/prefix.h> #include <util/suffix.h> #include <util/cprover_prefix.h> #include <util/std_expr.h> #include <util/pointer_predicates.h> #include <util/pointer_offset_size.h> #include <util/arith_tools.h> #include <util/byte_operators.h> #include <util/base_type.h> #include <util/expr_util.h> #include <util/simplify_expr.h> #include <ansi-c/c_types.h> #include "ssa_dereference.h" #include "address_canonizer.h" exprt lift_if(const exprt &src) { if(src.operands().size()==1 && src.op0().id()==ID_if) { // push operator into ?: if_exprt if_expr=to_if_expr(src.op0()); if_expr.type()=src.type(); if(if_expr.true_case().is_not_nil()) { exprt previous=if_expr.true_case(); if_expr.true_case()=src; if_expr.true_case().op0()=previous; } if(if_expr.false_case().is_not_nil()) { exprt previous=if_expr.false_case(); if_expr.false_case()=src; if_expr.false_case().op0()=previous; } return if_expr; } else return src; } bool ssa_may_alias( const exprt &e1, const exprt &e2, const namespacet &ns) { #ifdef DEBUG std::cout << "MAY ALIAS1 " << from_expr(ns, "", e1) << " " << from_expr(ns, "", e2) << "\n"; #endif // The same? if(e1==e2) return true; // Both symbol? if(e1.id()==ID_symbol && e2.id()==ID_symbol) { return to_symbol_expr(e1).get_identifier()== to_symbol_expr(e2).get_identifier(); } // __CPROVER symbols if(e1.id()==ID_symbol && has_prefix( id2string(to_symbol_expr(e1).get_identifier()), CPROVER_PREFIX)) return false; if(e2.id()==ID_symbol && has_prefix( id2string(to_symbol_expr(e2).get_identifier()), CPROVER_PREFIX)) return false; if(e1.id()==ID_symbol && has_suffix( id2string(to_symbol_expr(e1).get_identifier()), "#return_value")) return false; if(e2.id()==ID_symbol && has_suffix( id2string(to_symbol_expr(e2).get_identifier()), "#return_value")) return false; // Both member? if(e1.id()==ID_member && e2.id()==ID_member) { const member_exprt &m1=to_member_expr(e1); const member_exprt &m2=to_member_expr(e2); // same component? if(m1.get_component_name()!=m2.get_component_name()) return false; return ssa_may_alias(m1.struct_op(), m2.struct_op(), ns); } // Both index? if(e1.id()==ID_index && e2.id()==ID_index) { const index_exprt &i1=to_index_expr(e1); const index_exprt &i2=to_index_expr(e2); return ssa_may_alias(i1.array(), i2.array(), ns); } const typet &t1=ns.follow(e1.type()); const typet &t2=ns.follow(e2.type()); // If one is an array and the other not, consider the elements if(t1.id()==ID_array && t2.id()!=ID_array) if(ssa_may_alias( index_exprt(e1, gen_zero(index_type()), t1.subtype()), e2, ns)) return true; if(t2.id()==ID_array && t2.id()!=ID_array) if(ssa_may_alias( e1, index_exprt(e2, gen_zero(index_type()), t2.subtype()), ns)) return true; // Pointers only alias with other pointers, // which is a restriction. if(t1.id()==ID_pointer) return t2.id()==ID_pointer; if(t2.id()==ID_pointer) return t1.id()==ID_pointer; // Is one a scalar pointer? if(e1.id()==ID_dereference && (t1.id()==ID_signedbv || t1.id()==ID_unsignedbv || t1.id()==ID_floatbv)) return true; if(e2.id()==ID_dereference && (t2.id()==ID_signedbv || t2.id()==ID_unsignedbv || t1.id()==ID_floatbv)) return true; // Is one a pointer? if(e1.id()==ID_dereference || e2.id()==ID_dereference) { // look at the types // same type? if(base_type_eq(t1, t2, ns)) { return true; } // should consider further options, e.g., struct prefixes return false; } return false; // both different objects } exprt ssa_alias_guard( const exprt &e1, const exprt &e2, const namespacet &ns) { exprt a1=address_canonizer(address_of_exprt(e1), ns); // TODO: We should compare 'base' pointers here because // we have a higher chance that there was no pointer arithmetic // on the base pointer than that the result of the pointer // arithmetic points to a base pointer. // The following hack does that: if(a1.id()==ID_plus) a1=a1.op0(); exprt a2=address_canonizer(address_of_exprt(e2), ns); // in some cases, we can use plain address equality, // as we assume well-aligned-ness mp_integer size1=pointer_offset_size(e1.type(), ns); mp_integer size2=pointer_offset_size(e2.type(), ns); if(size1>=size2) { exprt lhs=a1; exprt rhs=a2; if(ns.follow(rhs.type())!=ns.follow(lhs.type())) rhs=typecast_exprt(rhs, lhs.type()); return equal_exprt(lhs, rhs); } return same_object(a1, a2); } exprt ssa_alias_value( const exprt &e1, const exprt &e2, const namespacet &ns) { const typet &e1_type=ns.follow(e1.type()); const typet &e2_type=ns.follow(e2.type()); // type matches? if(e1_type==e2_type) return e2; exprt a1=address_canonizer(address_of_exprt(e1), ns); exprt a2=address_canonizer(address_of_exprt(e2), ns); exprt offset1=pointer_offset(a1); // array index possible? if(e2_type.id()==ID_array && e1_type==ns.follow(e2_type.subtype())) { // this assumes well-alignedness mp_integer element_size=pointer_offset_size(e2_type.subtype(), ns); if(element_size==1) return index_exprt(e2, offset1, e1.type()); else if(element_size>1) { exprt index= div_exprt(offset1, from_integer(element_size, offset1.type())); return index_exprt(e2, index, e1.type()); } } byte_extract_exprt byte_extract(byte_extract_id(), e1.type()); byte_extract.op()=e2; byte_extract.offset()=offset1; return byte_extract; } exprt dereference_rec( const exprt &src, const ssa_value_domaint &ssa_value_domain, const std::string &nondet_prefix, const namespacet &ns) { if(src.id()==ID_dereference) { const exprt &pointer=dereference_rec( to_dereference_expr(src).pointer(), ssa_value_domain, nondet_prefix, ns); const typet &pointed_type=ns.follow(pointer.type().subtype()); const ssa_value_domaint::valuest values=ssa_value_domain(pointer, ns); exprt result; if(values.value_set.empty()) { result=pointed_object(pointer, ns); } else { auto it=values.value_set.begin(); if(values.null || values.unknown || (values.value_set.size()>1 && it->type().get_bool("#dynamic"))) { std::string dyn_type_name=pointed_type.id_string(); if(pointed_type.id()==ID_struct) dyn_type_name+="_"+id2string(to_struct_type(pointed_type).get_tag()); irep_idt identifier="ssa::"+dyn_type_name+"_obj$unknown"; result=symbol_exprt(identifier, src.type()); result.set("#unknown_obj", true); } else { result=ssa_alias_value(src, (it++)->get_expr(), ns); result.set("#heap_access", result.type().get_bool("#dynamic")); } for(; it!=values.value_set.end(); ++it) { exprt guard=ssa_alias_guard(src, it->get_expr(), ns); exprt value=ssa_alias_value(src, it->get_expr(), ns); result=if_exprt(guard, value, result); result.set( "#heap_access", result.get_bool("#heap_access") || value.type().get_bool("#dynamic")); } } return result; } else if(src.id()==ID_member) { member_exprt tmp=to_member_expr(src); tmp.struct_op()= dereference_rec(tmp.struct_op(), ssa_value_domain, nondet_prefix, ns); tmp.set("#heap_access", tmp.struct_op().get_bool("#heap_access")); #ifdef DEBUG std::cout << "dereference_rec tmp: " << from_expr(ns, "", tmp) << '\n'; #endif if(tmp.struct_op().is_nil()) return nil_exprt(); return lift_if(tmp); } else if(src.id()==ID_address_of) { address_of_exprt tmp=to_address_of_expr(src); tmp.object()= dereference_rec(tmp.object(), ssa_value_domain, nondet_prefix, ns); tmp.set("#heap_access", tmp.object().get_bool("#heap_access")); if(tmp.object().is_nil()) return nil_exprt(); return lift_if(tmp); } else { exprt tmp=src; Forall_operands(it, tmp) { *it=dereference_rec(*it, ssa_value_domain, nondet_prefix, ns); if(it->get_bool("#heap_access")) tmp.set("#heap_access", true); } return tmp; } } exprt dereference( const exprt &src, const ssa_value_domaint &ssa_value_domain, const std::string &nondet_prefix, const namespacet &ns) { #ifdef DEBUG std::cout << "dereference src: " << from_expr(ns, "", src) << '\n'; #endif exprt tmp1=dereference_rec(src, ssa_value_domain, nondet_prefix, ns); #ifdef DEBUG std::cout << "dereference tmp1: " << from_expr(ns, "", tmp1) << '\n'; #endif exprt tmp2=simplify_expr(tmp1, ns); #ifdef DEBUG std::cout << "dereference tmp2: " << from_expr(ns, "", tmp2) << '\n'; #endif return tmp2; }
24.747368
79
0.630264
KentrilDespair
cb2457a04ff22828416c82770410e168de6c61ba
477
cpp
C++
artifact/storm/src/storm-dft/storage/dft/elements/BEConst.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm-dft/storage/dft/elements/BEConst.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm-dft/storage/dft/elements/BEConst.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
1
2022-02-05T12:39:53.000Z
2022-02-05T12:39:53.000Z
#include "BEConst.h" namespace storm { namespace storage { template <typename ValueType> ValueType BEConst<ValueType>::getUnreliability(ValueType time) const { return failed() ? storm::utility::one<ValueType>() : storm::utility::zero<ValueType>(); } // Explicitly instantiate the class. template class BEConst<double>; template class BEConst<RationalFunction>; } // namespace storage } // namespace storm
28.058824
99
0.651992
glatteis
cb24890ee7eeea3fa935678ae2c809cc47e72f42
7,259
cpp
C++
TimeSync/TimeSync.cpp
rjpdasilva/ThunderNanoServices
23a5bf2fdab09135a7da080c1a5195f4257e5b98
[ "BSD-2-Clause" ]
null
null
null
TimeSync/TimeSync.cpp
rjpdasilva/ThunderNanoServices
23a5bf2fdab09135a7da080c1a5195f4257e5b98
[ "BSD-2-Clause" ]
null
null
null
TimeSync/TimeSync.cpp
rjpdasilva/ThunderNanoServices
23a5bf2fdab09135a7da080c1a5195f4257e5b98
[ "BSD-2-Clause" ]
null
null
null
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2020 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 "TimeSync.h" #include "NTPClient.h" namespace WPEFramework { namespace Plugin { SERVICE_REGISTRATION(TimeSync, 1, 0); static Core::ProxyPoolType<Web::Response> responseFactory(4); static Core::ProxyPoolType<Web::JSONBodyType<TimeSync::Data<>>> jsonResponseFactory(4); static Core::ProxyPoolType<Web::JSONBodyType<TimeSync::SetData<>>> jsonBodyDataFactory(2); static const uint16_t NTPPort = 123; #ifdef __WINDOWS__ #pragma warning(disable : 4355) #endif TimeSync::TimeSync() : _skipURL(0) , _periodicity(0) , _client(Core::Service<NTPClient>::Create<Exchange::ITimeSync>()) , _activity(Core::ProxyType<PeriodicSync>::Create(_client)) , _sink(this) , _service(nullptr) { RegisterAll(); } #ifdef __WINDOWS__ #pragma warning(default : 4355) #endif /* virtual */ TimeSync::~TimeSync() { UnregisterAll(); _client->Release(); } /* virtual */ const string TimeSync::Initialize(PluginHost::IShell* service) { Config config; config.FromString(service->ConfigLine()); string version = service->Version(); _skipURL = static_cast<uint16_t>(service->WebPrefix().length()); _periodicity = config.Periodicity.Value() * 60 /* minutes */ * 60 /* seconds */ * 1000 /* milliSeconds */; bool start = (((config.Deferred.IsSet() == true) && (config.Deferred.Value() == true)) == false); NTPClient::SourceIterator index(config.Sources.Elements()); static_cast<NTPClient*>(_client)->Initialize(index, config.Retries.Value(), config.Interval.Value()); ASSERT(service != nullptr); ASSERT(_service == nullptr); _service = service; _service->AddRef(); _sink.Initialize(_client, start); // On success return empty, to indicate there is no error text. return _T(""); } /* virtual */ void TimeSync::Deinitialize(PluginHost::IShell* service) { Core::IWorkerPool::Instance().Revoke(_activity); _sink.Deinitialize(); ASSERT(_service != nullptr); _service->Release(); _service = nullptr; } /* virtual */ string TimeSync::Information() const { // No additional info to report. return (string()); } /* virtual */ void TimeSync::Inbound(Web::Request& request) { if (request.Verb == Web::Request::HTTP_PUT) { request.Body(jsonBodyDataFactory.Element()); } } /* virtual */ Core::ProxyType<Web::Response> TimeSync::Process(const Web::Request& request) { Core::ProxyType<Web::Response> result(PluginHost::IFactories::Instance().Response()); Core::TextSegmentIterator index( Core::TextFragment(request.Path, _skipURL, static_cast<uint16_t>(request.Path.length()) - _skipURL), false, '/'); result->ErrorCode = Web::STATUS_BAD_REQUEST; result->Message = "Unsupported request for the TimeSync service"; index.Next(); if (request.Verb == Web::Request::HTTP_GET) { Core::ProxyType<Web::JSONBodyType<Data<>>> response(jsonResponseFactory.Element()); uint64_t syncTime(_client->SyncTime()); response->TimeSource = _client->Source(); response->SyncTime = (syncTime == 0 ? _T("invalid time") : Core::Time(syncTime).ToRFC1123(true)); result->ContentType = Web::MIMETypes::MIME_JSON; result->Body(Core::proxy_cast<Web::IBody>(response)); result->ErrorCode = Web::STATUS_OK; result->Message = "OK"; } else if (request.Verb == Web::Request::HTTP_POST) { if (index.IsValid() && index.Next()) { if (index.Current() == "Sync") { _client->Synchronize(); result->ErrorCode = Web::STATUS_OK; result->Message = "OK"; } } } else if (request.Verb == Web::Request::HTTP_PUT) { if (index.IsValid() && index.Next()) { if (index.Current() == "Set") { result->ErrorCode = Web::STATUS_OK; result->Message = "OK"; Core::Time newTime(0); if (request.HasBody()) { Core::JSON::String time = request.Body<const TimeSync::SetData<>>()->Time; if (time.IsSet()) { newTime.FromISO8601(time.Value()); if (!newTime.IsValid()) { result->ErrorCode = Web::STATUS_BAD_REQUEST; result->Message = "Invalid time given."; } } } if (result->ErrorCode == Web::STATUS_OK) { // Stop automatic synchronisation _client->Cancel(); Core::IWorkerPool::Instance().Revoke(_activity); if (newTime.IsValid()) { Core::SystemInfo::Instance().SetTime(newTime); } EnsureSubsystemIsActive(); } } } } return result; } void TimeSync::SyncedTime(const uint64_t time) { Core::Time newTime(time); TRACE(Trace::Information, (_T("Syncing time to %s."), newTime.ToRFC1123(false).c_str())); Core::SystemInfo::Instance().SetTime(newTime); if (_periodicity != 0) { Core::Time newSyncTime(Core::Time::Now()); newSyncTime.Add(_periodicity); // Seems we are synchronised with the time. Schedule the next timesync. TRACE(Trace::Information, (_T("Waking up again at %s."), newSyncTime.ToRFC1123(false).c_str())); Core::IWorkerPool::Instance().Schedule(newSyncTime, _activity); event_timechange(); } } void TimeSync::EnsureSubsystemIsActive() { ASSERT(_service != nullptr); PluginHost::ISubSystem* subSystem = _service->SubSystems(); ASSERT(subSystem != nullptr); if (subSystem != nullptr) { if (subSystem->IsActive(PluginHost::ISubSystem::TIME) == false) { subSystem->Set(PluginHost::ISubSystem::TIME, _client); } subSystem->Release(); } } } // namespace Plugin } // namespace WPEFramework
34.402844
114
0.571429
rjpdasilva
cb276b14a7363da0a429669b43f547ba839a74b9
3,269
cpp
C++
AssortedWidgets/MenuBar.cpp
Bot-Labs/AssortedWidgets
298567b8f069580205e309979bc35ec063d09f51
[ "MIT" ]
107
2016-03-13T23:45:48.000Z
2022-02-13T21:17:44.000Z
AssortedWidgets/MenuBar.cpp
Bot-Labs/AssortedWidgets
298567b8f069580205e309979bc35ec063d09f51
[ "MIT" ]
2
2019-10-12T12:19:21.000Z
2022-01-04T10:42:18.000Z
AssortedWidgets/MenuBar.cpp
Bot-Labs/AssortedWidgets
298567b8f069580205e309979bc35ec063d09f51
[ "MIT" ]
29
2017-06-04T15:04:30.000Z
2021-11-25T14:36:48.000Z
#include "MenuBar.h" #include "Menu.h" #include "ThemeEngine.h" namespace AssortedWidgets { namespace Widgets { MenuBar::~MenuBar(void) { } void MenuBar::setExpand(Menu *_expandMenu) { if(m_expandMenu) { m_expandMenu->shrink(); } m_expandMenu=_expandMenu; m_expand=true; } void MenuBar::setShrink() { if(m_expandMenu) { m_expandMenu->shrink(); } m_expandMenu=0; m_expand=false; } void MenuBar::addMenu(Menu *menu) { m_menuList.push_back(menu); menu->setMenuBar(this); updateLayout(); } void MenuBar::paint() { Theme::ThemeEngine::getSingleton().getTheme().paintMenuBar(this); std::vector<Menu*>::iterator iter; for(iter=m_menuList.begin();iter<m_menuList.end();++iter) { (*iter)->paint(); } } void MenuBar::onMouseEnter(const Event::MouseEvent &e) { m_isHover=true; onMouseMove(e); } void MenuBar::onMouseExit(const Event::MouseEvent &e) { m_isHover=false; onMouseMove(e); } void MenuBar::onMousePressed(const Event::MouseEvent &e) { std::vector<Menu*>::iterator iter; for(iter=m_menuList.begin();iter<m_menuList.end();++iter) { if((*iter)->isIn(e.getX(),e.getY())) { Event::MouseEvent event((*iter),Event::MouseEvent::MOUSE_PRESSED,e.getX(),e.getY(),0); (*iter)->processMousePressed(event); } } if(isExpand() && m_expandMenu) { m_expandMenu->listMousePressed(e); } } void MenuBar::onMouseReleased(const Event::MouseEvent &e) { std::vector<Menu*>::iterator iter; for(iter=m_menuList.begin();iter<m_menuList.end();++iter) { if((*iter)->isIn(e.getX(),e.getY())) { Event::MouseEvent event((*iter),Event::MouseEvent::MOUSE_RELEASED,e.getX(),e.getY(),0); (*iter)->processMouseReleased(event); } } if(isExpand() && m_expandMenu) { m_expandMenu->listMouseReleased(e); } } void MenuBar::onMouseMove(const Event::MouseEvent &e) { std::vector<Menu*>::iterator iter; for(iter=m_menuList.begin();iter<m_menuList.end();++iter) { if((*iter)->isIn(e.getX(),e.getY())) { if(!(*iter)->m_isHover) { Event::MouseEvent event((*iter),Event::MouseEvent::MOUSE_ENTERED,e.getX(),e.getY(),0); (*iter)->processMouseEntered(event); } } else { if((*iter)->m_isHover) { Event::MouseEvent event((*iter),Event::MouseEvent::MOUSE_EXITED,e.getX(),e.getY(),0); (*iter)->processMouseExited(event); } } } if(isExpand() && m_expandMenu) { m_expandMenu->listMouseMotion(e); } } void MenuBar::updateLayout() { std::vector<Menu*>::iterator iter; int tempBegin=m_rightSpacer; for(iter=m_menuList.begin();iter<m_menuList.end();++iter) { (*iter)->m_position.x=tempBegin; (*iter)->m_position.y=m_topSpacer; tempBegin+=m_spacer+(*iter)->getPreferedSize().m_width; } } } }
23.35
92
0.552463
Bot-Labs
cb2a7726700111d0e24f206a1e624a9f65bd780f
2,537
cpp
C++
source/Structure/custom_plugins/plugins/pertubation/pertubation.cpp
Guiraffo/ProVANT-Simulator
568c6f1688525fa64ac0193a6734563a5b95c997
[ "MIT" ]
7
2020-05-17T21:49:00.000Z
2022-03-25T12:32:24.000Z
source/Structure/custom_plugins/plugins/pertubation/pertubation.cpp
Guiraffo/ProVANT-Simulator
568c6f1688525fa64ac0193a6734563a5b95c997
[ "MIT" ]
null
null
null
source/Structure/custom_plugins/plugins/pertubation/pertubation.cpp
Guiraffo/ProVANT-Simulator
568c6f1688525fa64ac0193a6734563a5b95c997
[ "MIT" ]
2
2020-12-20T02:10:37.000Z
2021-01-24T10:11:49.000Z
/* * File: pertubation.cpp * Author: Arthur Viana Lara * Project: ProVANT * Company: Federal University of Minas Gerais * Version: 1.0 * Date: 29/01/18 * Description: This library is responsable to implement a plugin to simulate a force pertubation. */ #include <pertubation.h> namespace gazebo { // constructor pertubation::pertubation() { } // destructor pertubation::~pertubation() { } // initial setup void pertubation::Load(physics::ModelPtr _model, sdf::ElementPtr _sdf) { try { if (!ros::isInitialized()) { std::cout << "Aerodinamica nao inicializado!" << std::endl; return; } // get ROS topics name topicX = XMLRead::ReadXMLString("topicX",_sdf); topicY = XMLRead::ReadXMLString("topicY",_sdf); topicZ = XMLRead::ReadXMLString("topicZ",_sdf); // get link name NameOfLink = XMLRead::ReadXMLString("Link",_sdf); // get simulation link link = _model->GetLink(NameOfLink); // update timer Reset(); // subscribers pertubation_subscriberX = node_handle_.subscribe(topicX, 1, &gazebo::pertubation::CallbackX, this); pertubation_subscriberY = node_handle_.subscribe(topicY, 1, &gazebo::pertubation::CallbackY, this); pertubation_subscriberZ = node_handle_.subscribe(topicZ, 1, &gazebo::pertubation::CallbackZ, this); } catch(std::exception& e) { std::cout << e.what() << std::endl; } } // reset void pertubation::Reset() { try { } catch(std::exception& e) { std::cout << e.what() << std::endl; } } // Callback to provide a pertubation in x direction void pertubation::CallbackX(std_msgs::Float64 msg) { try { Fx = msg.data; ignition::math::Vector3d force(Fx,0,0); // applying link->AddRelativeForce(force); } catch(std::exception& e) { std::cout << e.what() << std::endl; } } // Callback to provide a pertubation in y direction void pertubation::CallbackY(std_msgs::Float64 msg) { try { Fy = msg.data; ignition::math::Vector3d force(0,Fy,0); // applying link->AddRelativeForce(force); } catch(std::exception& e) { std::cout << e.what() << std::endl; } } // Callback to provide a pertubation in z direction void pertubation::CallbackZ(std_msgs::Float64 msg) { try { Fz = msg.data; ignition::math::Vector3d force(0,0,Fz); // applying link->AddRelativeForce(force); } catch(std::exception& e) { std::cout << e.what() << std::endl; } } GZ_REGISTER_MODEL_PLUGIN(pertubation) }
20.296
102
0.642885
Guiraffo
cb2ae40322d5bd895b23a3e8780fe1ad9bb1094a
402
cpp
C++
Jerboa/src/Jerboa/Core/EventObserver.cpp
GilbertNordhammar/Newt
5e3c04cc8e11dfc64b43458d060d037c2ecff062
[ "Apache-2.0" ]
null
null
null
Jerboa/src/Jerboa/Core/EventObserver.cpp
GilbertNordhammar/Newt
5e3c04cc8e11dfc64b43458d060d037c2ecff062
[ "Apache-2.0" ]
null
null
null
Jerboa/src/Jerboa/Core/EventObserver.cpp
GilbertNordhammar/Newt
5e3c04cc8e11dfc64b43458d060d037c2ecff062
[ "Apache-2.0" ]
null
null
null
#include "jerboa-pch.h" #include "EventObserver.h" namespace Jerboa { EventObserver::EventObserver(EventBus* eventBus, EventCallback callback, std::type_index eventIndex) : EventObserverBase(eventBus), mCallback(callback), mEventIndex(eventIndex) { Subscribe(mCallback, mEventIndex); } EventObserver::~EventObserver() { Unsubscribe(mCallback, mEventIndex); } }
30.923077
104
0.716418
GilbertNordhammar
cb2b2e1fb776bdcb2f9af7661fd4cd7e4bc4e35e
4,460
cpp
C++
aws-cpp-sdk-s3-crt/source/model/RestoreRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-s3-crt/source/model/RestoreRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-s3-crt/source/model/RestoreRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/s3-crt/model/RestoreRequest.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace S3Crt { namespace Model { RestoreRequest::RestoreRequest() : m_days(0), m_daysHasBeenSet(false), m_glacierJobParametersHasBeenSet(false), m_type(RestoreRequestType::NOT_SET), m_typeHasBeenSet(false), m_tier(Tier::NOT_SET), m_tierHasBeenSet(false), m_descriptionHasBeenSet(false), m_selectParametersHasBeenSet(false), m_outputLocationHasBeenSet(false) { } RestoreRequest::RestoreRequest(const XmlNode& xmlNode) : m_days(0), m_daysHasBeenSet(false), m_glacierJobParametersHasBeenSet(false), m_type(RestoreRequestType::NOT_SET), m_typeHasBeenSet(false), m_tier(Tier::NOT_SET), m_tierHasBeenSet(false), m_descriptionHasBeenSet(false), m_selectParametersHasBeenSet(false), m_outputLocationHasBeenSet(false) { *this = xmlNode; } RestoreRequest& RestoreRequest::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode daysNode = resultNode.FirstChild("Days"); if(!daysNode.IsNull()) { m_days = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(daysNode.GetText()).c_str()).c_str()); m_daysHasBeenSet = true; } XmlNode glacierJobParametersNode = resultNode.FirstChild("GlacierJobParameters"); if(!glacierJobParametersNode.IsNull()) { m_glacierJobParameters = glacierJobParametersNode; m_glacierJobParametersHasBeenSet = true; } XmlNode typeNode = resultNode.FirstChild("Type"); if(!typeNode.IsNull()) { m_type = RestoreRequestTypeMapper::GetRestoreRequestTypeForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(typeNode.GetText()).c_str()).c_str()); m_typeHasBeenSet = true; } XmlNode tierNode = resultNode.FirstChild("Tier"); if(!tierNode.IsNull()) { m_tier = TierMapper::GetTierForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(tierNode.GetText()).c_str()).c_str()); m_tierHasBeenSet = true; } XmlNode descriptionNode = resultNode.FirstChild("Description"); if(!descriptionNode.IsNull()) { m_description = Aws::Utils::Xml::DecodeEscapedXmlText(descriptionNode.GetText()); m_descriptionHasBeenSet = true; } XmlNode selectParametersNode = resultNode.FirstChild("SelectParameters"); if(!selectParametersNode.IsNull()) { m_selectParameters = selectParametersNode; m_selectParametersHasBeenSet = true; } XmlNode outputLocationNode = resultNode.FirstChild("OutputLocation"); if(!outputLocationNode.IsNull()) { m_outputLocation = outputLocationNode; m_outputLocationHasBeenSet = true; } } return *this; } void RestoreRequest::AddToNode(XmlNode& parentNode) const { Aws::StringStream ss; if(m_daysHasBeenSet) { XmlNode daysNode = parentNode.CreateChildElement("Days"); ss << m_days; daysNode.SetText(ss.str()); ss.str(""); } if(m_glacierJobParametersHasBeenSet) { XmlNode glacierJobParametersNode = parentNode.CreateChildElement("GlacierJobParameters"); m_glacierJobParameters.AddToNode(glacierJobParametersNode); } if(m_typeHasBeenSet) { XmlNode typeNode = parentNode.CreateChildElement("Type"); typeNode.SetText(RestoreRequestTypeMapper::GetNameForRestoreRequestType(m_type)); } if(m_tierHasBeenSet) { XmlNode tierNode = parentNode.CreateChildElement("Tier"); tierNode.SetText(TierMapper::GetNameForTier(m_tier)); } if(m_descriptionHasBeenSet) { XmlNode descriptionNode = parentNode.CreateChildElement("Description"); descriptionNode.SetText(m_description); } if(m_selectParametersHasBeenSet) { XmlNode selectParametersNode = parentNode.CreateChildElement("SelectParameters"); m_selectParameters.AddToNode(selectParametersNode); } if(m_outputLocationHasBeenSet) { XmlNode outputLocationNode = parentNode.CreateChildElement("OutputLocation"); m_outputLocation.AddToNode(outputLocationNode); } } } // namespace Model } // namespace S3Crt } // namespace Aws
28.407643
164
0.731839
perfectrecall
cb2c0501cef23216487726082b85ef75957f41d3
1,364
hpp
C++
libs/move/example/copymovable.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
11
2016-04-12T16:29:29.000Z
2021-06-28T11:01:57.000Z
libs/move/example/copymovable.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
3
2018-10-31T19:35:14.000Z
2019-06-04T17:11:27.000Z
libs/move/example/copymovable.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
9
2015-09-09T02:38:32.000Z
2021-01-30T00:24:24.000Z
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2009. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/move for documentation. // ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_MOVE_TEST_COPYMOVABLE_HPP #define BOOST_MOVE_TEST_COPYMOVABLE_HPP #include <boost/move/detail/config_begin.hpp> //[movable_definition //header file "copy_movable.hpp" #include <boost/move/core.hpp> //A copy_movable class class copy_movable { BOOST_COPYABLE_AND_MOVABLE(copy_movable) int value_; public: copy_movable() : value_(1){} //Move constructor and assignment copy_movable(BOOST_RV_REF(copy_movable) m) { value_ = m.value_; m.value_ = 0; } copy_movable(const copy_movable &m) { value_ = m.value_; } copy_movable & operator=(BOOST_RV_REF(copy_movable) m) { value_ = m.value_; m.value_ = 0; return *this; } copy_movable & operator=(BOOST_COPY_ASSIGN_REF(copy_movable) m) { value_ = m.value_; return *this; } bool moved() const //Observer { return value_ == 0; } }; //] #include <boost/move/detail/config_end.hpp> #endif //BOOST_MOVE_TEST_COPYMOVABLE_HPP
26.745098
78
0.629032
ballisticwhisper
cb2fe6fcb75350618eef157089e49f7ddabea2ff
1,835
cpp
C++
src/solutions/490.cpp
bshankar/euler
c866a661a94d15d3744c74d85149534efac2ca23
[ "MIT" ]
null
null
null
src/solutions/490.cpp
bshankar/euler
c866a661a94d15d3744c74d85149534efac2ca23
[ "MIT" ]
null
null
null
src/solutions/490.cpp
bshankar/euler
c866a661a94d15d3744c74d85149534efac2ca23
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cstdlib> using namespace std; template <class T> class F { public: F(T n, T r) { // initialize some values v.resize(n); perm.resize(n); v[0] = true; perm[0] = 1; v[n-1] = true; perm[n-1] = n; count1 = count2 = count3 = index = 0; this->r = r; } void bt(T d) { if (d == perm.size()-1) { bool nV = false; for (T i = 0; i < v.size(); ++i) { if (v[i] == false) { nV = true; break; } } if (!nV) { T l1 = perm.size() - 2; if (perm[l1] == l1+1) ++count1; else if (perm[l1] == l1) ++count2; else if (perm[l1] == l1-1) ++count3; } return; } for (T i = perm[d-1]-r; i <= perm[d-1]+r; ++i) { if (i <= 0 || v[i-1] || i > perm.size()) continue; if (d == perm.size()-2 && i+r < perm[perm.size()-1]) continue; perm[d] = i; v[i-1] = true; bt(d+1); // reset values v[i-1] = false; perm[d] = 0; } } void print() { for (T i = 0; i < perm.size(); ++i) cout << perm[i] << " "; cout << endl; } T count1, count2, count3; private: vector<bool> v; // placed or not vector<T> perm; T index, r; }; int main(int argc, char** argv) { F<long> f_(atoi(argv[1]), 3); f_.bt(1); cout << f_.count1 << " " << f_.count2 << " " << f_.count3 << endl; }
22.654321
64
0.346049
bshankar
cb31012ac2fe8d0796f522ac41df7a6dd5d6a6ef
3,307
cpp
C++
folly/futures/Barrier.cpp
foreverhy/folly
8d141fc119bbb2f703d145c1a7cb70e7f6ce282f
[ "Apache-2.0" ]
2
2021-06-29T13:42:22.000Z
2021-09-06T10:57:34.000Z
folly/futures/Barrier.cpp
foreverhy/folly
8d141fc119bbb2f703d145c1a7cb70e7f6ce282f
[ "Apache-2.0" ]
null
null
null
folly/futures/Barrier.cpp
foreverhy/folly
8d141fc119bbb2f703d145c1a7cb70e7f6ce282f
[ "Apache-2.0" ]
5
2021-06-29T13:42:26.000Z
2022-02-08T02:41:34.000Z
/* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/futures/Barrier.h> #include <folly/lang/Exception.h> namespace folly { namespace futures { Barrier::Barrier(uint32_t n) : size_(n), controlBlock_(allocateControlBlock()) { } Barrier::~Barrier() { auto block = controlBlock_.load(std::memory_order_relaxed); auto prev = block->valueAndReaderCount.load(std::memory_order_relaxed); DCHECK_EQ(prev >> kReaderShift, 0u); auto val = prev & kValueMask; auto p = promises(block); for (uint32_t i = 0; i < val; ++i) { p[i].setException( folly::make_exception_wrapper<std::runtime_error>("Barrier destroyed")); } freeControlBlock(controlBlock_); } auto Barrier::allocateControlBlock() -> ControlBlock* { auto storage = malloc(controlBlockSize(size_)); if (!storage) { throw_exception<std::bad_alloc>(); } auto block = ::new (storage) ControlBlock(); auto p = promises(block); uint32_t i = 0; try { for (i = 0; i < size_; ++i) { new (p + i) BoolPromise(); } } catch (...) { for (; i != 0; --i) { p[i - 1].~BoolPromise(); } throw; } return block; } void Barrier::freeControlBlock(ControlBlock* block) { auto p = promises(block); for (uint32_t i = size_; i != 0; --i) { p[i - 1].~BoolPromise(); } free(block); } folly::Future<bool> Barrier::wait() { // Load the current control block first. As we know there is at least // one thread in the current epoch (us), this means that the value is // < size_, so controlBlock_ can't change until we bump the value below. auto block = controlBlock_.load(std::memory_order_acquire); auto p = promises(block); // Bump the value and record ourselves as reader. // This ensures that block stays allocated, as the reader count is > 0. auto prev = block->valueAndReaderCount.fetch_add(kReader + 1, std::memory_order_acquire); auto prevValue = static_cast<uint32_t>(prev & kValueMask); DCHECK_LT(prevValue, size_); auto future = p[prevValue].getFuture(); if (prevValue + 1 == size_) { // Need to reset the barrier before fulfilling any futures. This is // when the epoch is flipped to the next. controlBlock_.store(allocateControlBlock(), std::memory_order_release); p[0].setValue(true); for (uint32_t i = 1; i < size_; ++i) { p[i].setValue(false); } } // Free the control block if we're the last reader at max value. prev = block->valueAndReaderCount.fetch_sub(kReader, std::memory_order_acq_rel); if (prev == (kReader | uint64_t(size_))) { freeControlBlock(block); } return future; } } // namespace futures } // namespace folly
29.792793
80
0.658905
foreverhy