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
b867c2059a12d5c2a450dee520e7e61a6c1ccecd
1,846
cpp
C++
LibCarla/source/carla/rpc/WeatherParameters.cpp
xiaobaibai521/auto
f0585716a8afc4e327dcc57944cb44fc39184b57
[ "MIT" ]
8
2019-11-27T18:43:09.000Z
2022-01-16T06:08:36.000Z
LibCarla/source/carla/rpc/WeatherParameters.cpp
tiev-tongji/carla-ex
1cd2ecc43a9ac1b039842b8c46b3de368b70afc4
[ "MIT" ]
2
2019-09-18T16:06:58.000Z
2019-09-24T16:48:07.000Z
LibCarla/source/carla/rpc/WeatherParameters.cpp
tiev-tongji/carla-ex
1cd2ecc43a9ac1b039842b8c46b3de368b70afc4
[ "MIT" ]
5
2020-05-12T20:03:10.000Z
2022-02-25T14:40:07.000Z
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "carla/rpc/WeatherParameters.h" namespace carla { namespace rpc { using WP = WeatherParameters; // cloudyness precip. prec.dep. wind azimuth altitude WP WP::Default = { -1.0f, -1.0f, -1.0f, -1.00f, -1.0f, -1.0f}; WP WP::ClearNoon = { 15.0f, 0.0f, 0.0f, 0.35f, 0.0f, 75.0f}; WP WP::CloudyNoon = { 80.0f, 0.0f, 0.0f, 0.35f, 0.0f, 75.0f}; WP WP::WetNoon = { 20.0f, 0.0f, 50.0f, 0.35f, 0.0f, 75.0f}; WP WP::WetCloudyNoon = { 80.0f, 0.0f, 50.0f, 0.35f, 0.0f, 75.0f}; WP WP::MidRainyNoon = { 80.0f, 30.0f, 50.0f, 0.40f, 0.0f, 75.0f}; WP WP::HardRainNoon = { 90.0f, 60.0f, 100.0f, 1.00f, 0.0f, 75.0f}; WP WP::SoftRainNoon = { 70.0f, 15.0f, 50.0f, 0.35f, 0.0f, 75.0f}; WP WP::ClearSunset = { 15.0f, 0.0f, 0.0f, 0.35f, 0.0f, 15.0f}; WP WP::CloudySunset = { 80.0f, 0.0f, 0.0f, 0.35f, 0.0f, 15.0f}; WP WP::WetSunset = { 20.0f, 0.0f, 50.0f, 0.35f, 0.0f, 15.0f}; WP WP::WetCloudySunset = { 90.0f, 0.0f, 50.0f, 0.35f, 0.0f, 15.0f}; WP WP::MidRainSunset = { 80.0f, 30.0f, 50.0f, 0.40f, 0.0f, 15.0f}; WP WP::HardRainSunset = { 80.0f, 60.0f, 100.0f, 1.00f, 0.0f, 15.0f}; WP WP::SoftRainSunset = { 90.0f, 15.0f, 50.0f, 0.35f, 0.0f, 15.0f}; } // namespace rpc } // namespace carla
55.939394
91
0.472914
xiaobaibai521
b86cba27311b9ffe770a16aace7db8bfbb9bb40a
909
hpp
C++
include/NP-Engine/Memory/Memory.hpp
naphipps/NP-Engine
0cac8b2d5e76c839b96f2061bf57434bdc37915e
[ "MIT" ]
null
null
null
include/NP-Engine/Memory/Memory.hpp
naphipps/NP-Engine
0cac8b2d5e76c839b96f2061bf57434bdc37915e
[ "MIT" ]
null
null
null
include/NP-Engine/Memory/Memory.hpp
naphipps/NP-Engine
0cac8b2d5e76c839b96f2061bf57434bdc37915e
[ "MIT" ]
null
null
null
// // Memory.hpp // Project Space // // Created by Nathan Phipps on 2/7/21. // Copyright © 2021 Nathan Phipps. All rights reserved. // #ifndef NP_ENGINE_MEMORY_HPP #define NP_ENGINE_MEMORY_HPP #include "NP-Engine/Foundation/Foundation.hpp" #include "Allocator.hpp" #include "Block.hpp" #include "CAllocator.hpp" #include "SizedAllocator.hpp" #include "LinearAllocator.hpp" #include "PoolAllocator.hpp" #include "ObjectPool.hpp" #include "Margin.hpp" #include "ImplicitListAllocator.hpp" #include "ExplicitListAllocator.hpp" #include "ExplicitSegListAllocator.hpp" #include "RedBlackTreeAllocator.hpp" #include "LockingPoolAllocator.hpp" #include "FallbackAllocator.hpp" #include "SegregatedAllocator.hpp" #include "MemoryFunctions.hpp" #include "TraitAllocator.hpp" #include "StdAllocator.hpp" #include "PadObject.hpp" #include "Delegate.hpp" #include "SmartPtr.hpp" #endif /* NP_ENGINE_MEMORY_HPP */
24.567568
56
0.776678
naphipps
b86ed7331b7911705c6841460a642603dbf3414e
50,497
cpp
C++
groups/bsl/bslalg/bslalg_nothrowmovableutil.t.cpp
eddiepierce/bde
45953ece9dd1cd8732f01a1cd24bbe838791d298
[ "Apache-2.0" ]
1
2021-11-10T16:53:42.000Z
2021-11-10T16:53:42.000Z
groups/bsl/bslalg/bslalg_nothrowmovableutil.t.cpp
eddiepierce/bde
45953ece9dd1cd8732f01a1cd24bbe838791d298
[ "Apache-2.0" ]
2
2020-11-05T15:20:55.000Z
2021-01-05T19:38:43.000Z
groups/bsl/bslalg/bslalg_nothrowmovableutil.t.cpp
eddiepierce/bde
45953ece9dd1cd8732f01a1cd24bbe838791d298
[ "Apache-2.0" ]
2
2020-01-16T17:58:12.000Z
2020-08-11T20:59:30.000Z
// bslalg_nothrowmovableutil.t.cpp -*-C++-*- #include <bslalg_nothrowmovableutil.h> #include <bslalg_constructorproxy.h> #include <bslma_defaultallocatorguard.h> #include <bsla_maybeunused.h> #include <bslma_testallocator.h> #include <bslma_usesbslmaallocator.h> #include <bsls_asserttest.h> #include <bsls_bsltestutil.h> #include <bsltf_templatetestfacility.h> #include <stdio.h> // 'printf' #include <stdlib.h> // 'atoi' using namespace BloombergLP; // ============================================================================ // TEST PLAN // ---------------------------------------------------------------------------- // Overview // -------- // The component under test provides a utility struct, // 'bslalg::NothrowMovableUtil', that provides a namespace for static functions // 'wrap' and 'unwrap' with a uniform interface such that unwrapping an object // that is not wrapped or wrapping an object that is already wrapped are // no-ops. This utility struct also provides type traits for determining // whether a type is wrapped and for deducing the type of the wrapped and // unwrapped object. The tests will verify that the 'wrap' and 'unwrap' // utility behave as expected and that they preserve the constness and the // value type category of the wrapped object. Additionally, the tests will // verify that traits correctly determine whether the type is a wrapped or // unwrapped type, and that the deduced wrapped and unwrapped type are correct. //----------------------------------------------------------------------------- // // TRAITS // [ 2] IsWrapped // [ 2] WrappedType // [ 2] UnwrappedType // // STATIC METHODS // [ 3] wrap(TYPE&) // [ 3] wrap(TYPE const&) // [ 3] wrap(BSLALG_NOTHROWMOVABLEUTIL_DEDUCE_RVREF(TYPE)) // [ 3] wrap(BSLALG_NOTHROWMOVABLEUTIL_DEDUCE_RVREF(const TYPE) // [ 4] unwrap(TYPE&) // [ 4] unwrap(TYPE const&) // [ 4] unwrap(BSLALG_NOTHROWMOVABLEUTIL_DEDUCE_RVREF(TYPE)) // [ 4] unwrap(BSLALG_NOTHROWMOVABLEUTIL_DEDUCE_RVREF(const TYPE)) // // ---------------------------------------------------------------------------- // [ 5] USAGE EXAMPLE // [ 1] BREATHING TEST // ============================================================================ // STANDARD BSL ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { printf("Error " __FILE__ "(%d): %s (failed)\n", line, message); if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace // ============================================================================ // STANDARD BSL TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLS_BSLTESTUTIL_ASSERT #define ASSERTV BSLS_BSLTESTUTIL_ASSERTV #define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT #define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally. #define P BSLS_BSLTESTUTIL_P // Print identifier and value. #define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'. #define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLS_BSLTESTUTIL_L_ // current Line number #define RUN_EACH_TYPE BSLTF_TEMPLATETESTFACILITY_RUN_EACH_TYPE //============================================================================= // SEMI-STANDARD NEGATIVE-TESTING MACROS //----------------------------------------------------------------------------- #define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR) #define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR) #define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR) #define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR) #define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR) #define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR) //============================================================================= // VERBOSITY //----------------------------------------------------------------------------- static int verbose = 0; static int veryVerbose = 0; static int veryVeryVerbose = 0; static int veryVeryVeryVerbose = 0; // For test allocators //============================================================================= // GLOBAL TYPEDEFS/CONSTANTS FOR TESTING //----------------------------------------------------------------------------- typedef bslmf::MovableRefUtil MoveUtil; typedef void (*FunctionPtrType)(); typedef void(FunctionType)(); typedef bslalg::NothrowMovableWrapper<int> WrappedInt; typedef bslalg::NothrowMovableWrapper<const int> WrappedConstInt; typedef bslalg::NothrowMovableWrapper<FunctionPtrType> WrappedFunctionPtrType; #define BSLALG_NOTHROWMOVABLEUTIL_TEST_TYPES \ int, const int, FunctionPtrType, FunctionType, WrappedInt, \ WrappedConstInt, WrappedFunctionPtrType class TrackableValue { // This class tracks a value through a series of move and copy operations // and has an easily-testable moved-from state. An instance stores an // unsigned integer value and a pair of bits, one indicating if the value // was copied, another if it was moved (or neither or both). When assigned // a value at construction, via assignment, or via a mutating operation // (such as +=), the move and copy bits are cleared, indicating that the // new value has been neither moved nor copied. When assigned a new value // via copy construction or copy assignment, the copy bit is set and the // move bit is cleared. When assigned a new value via move construction, // move assignment, or swap, the copy bit is transferred from the original // value and the move bit is set. Thus a value that is copied then moved // will have both bits set but a value that is moved then copy has only the // copy bit set. The copy and move bits are not salient attributes of the // value and are thus not used for testing equality. // PRIVATE CONSTANTS enum { e_NUM_FLAGS = 2, // Value is multiplied by the following value to make room for the // flag bits. Multiply and divide are used to scale the value because // shift operations are not guaranteed to preserve sign. The compiler // will almost certainly replace these multiplication and divisions // with more efficient arithmetic shift operations. e_VALUE_MULTIPLIER = 1 << e_NUM_FLAGS, e_FLAGS_MASK = e_VALUE_MULTIPLIER - 1, e_VALUE_MASK = ~e_FLAGS_MASK, e_COPIED_FLAG = 0x01, e_MOVED_FLAG = 0x02, e_MOVED_FROM_VAL = 0x11111111, // Value assigned to moved-from object // The moved from state has a value of e_MOVED_FROM_VAL, with neither // flag set. e_MOVED_FROM_STATE = e_MOVED_FROM_VAL * e_VALUE_MULTIPLIER }; // PRIVATE DATA mutable int d_valueAndFlags; TrackableValue& setValue(int v, bool movedFlag = false, bool copiedFlag = false); // Set the value to the specified 'v'. Set the 'isMoved()' flag to the // optionally-specified 'movedFlag' bit and the 'isCopied()' flag to // the optionally-specified 'copiedFlag' bit. public: // TRAITS BSLMF_NESTED_TRAIT_DECLARATION(TrackableValue, bslmf::IsBitwiseMoveable); // Constants enum { e_MIN = INT_MIN / e_VALUE_MULTIPLIER, e_MAX = INT_MAX / e_VALUE_MULTIPLIER }; // CREATORS TrackableValue(int v = 0) // IMPLICIT // Set value to the optionally-specified 'v' and set 'isMoved()' and // 'isCopied()' to false. { setValue(v); } TrackableValue(const TrackableValue& original) // Copy value from the specified 'original', set 'isMoved()' to false // and // 'isCopied()' to 'true'. { setValue(original.value(), false, true); } TrackableValue(bslmf::MovableRef<TrackableValue> original) // Move value from the specified 'original', set 'isMoved()' to true, // and set 'isCopied()' to 'original.isCopied()', then set 'original' // to the moved-from state. { *this = bslmf::MovableRefUtil::move(original); } //! ~TrackableValue() = default; // MANIPULATORS TrackableValue& operator=(int v) // Set value to the specified 'v' and set 'isMoved()' and 'isCopied()' // to false; then return '*this'. { return setValue(v); } TrackableValue& operator=(const TrackableValue& rhs) // Set value to the specified 'rhs.value()' and set 'isMoved()' to // false and 'isCopied()' to true; then return '*this'. { return setValue(rhs.value(), false, true); } TrackableValue& operator=(bslmf::MovableRef<TrackableValue> rhs); // Move value from the specified 'rhs', set 'isMoved()' to true, and // set 'isCopied()' to 'rhs.isCopied()', then assign 'rhs' the value // 'e_MOVED_FROM_VAL' and return '*this'. void setIsCopiedRaw(bool); void setIsMovedRaw(bool); void setValueRaw(int); // Set the constituent parts of this object without modifying the other // parts. It is up to the caller to ensure that the flags are set // consistently. void swap(TrackableValue& other); // Exchange the values AND 'isCopied()' flags of '*this' and specified // 'other', then set the 'isMoved()' flag of both to true. // ACCESSORS bool isCopied() const { return d_valueAndFlags & e_COPIED_FLAG; } bool isMoved() const { return d_valueAndFlags & e_MOVED_FLAG; } bool isMovedFrom() const { return d_valueAndFlags == e_MOVED_FROM_STATE; } // Return the state of this object void resetMoveCopiedFlags() const // Set 'isMoved()' and 'isCopied() to false. { d_valueAndFlags &= e_VALUE_MASK; } int value() const { return d_valueAndFlags / e_VALUE_MULTIPLIER; } // Return the state of this object }; // IMPLEMENTATION OF TrackableValue // MANIPULATORS inline TrackableValue& TrackableValue::setValue(int v, bool movedFlag, bool copiedFlag) { ASSERT(e_MIN <= v && v <= e_MAX); d_valueAndFlags = v * e_VALUE_MULTIPLIER; if (movedFlag) d_valueAndFlags |= e_MOVED_FLAG; if (copiedFlag) d_valueAndFlags |= e_COPIED_FLAG; return *this; } inline TrackableValue& TrackableValue::operator=( bslmf::MovableRef<TrackableValue> rhs) { TrackableValue& otherRef = bslmf::MovableRefUtil::access(rhs); d_valueAndFlags = otherRef.d_valueAndFlags | e_MOVED_FLAG; otherRef.d_valueAndFlags = e_MOVED_FROM_STATE; return *this; } void TrackableValue::swap(TrackableValue& other) { // Don't use std::swap<int> because don't want to #include <algorithm> int tmp = d_valueAndFlags; d_valueAndFlags = other.d_valueAndFlags; other.d_valueAndFlags = tmp; d_valueAndFlags |= e_MOVED_FLAG; other.d_valueAndFlags |= e_MOVED_FLAG; } // ACCESSORS void TrackableValue::setIsCopiedRaw(bool copiedFlag) { d_valueAndFlags &= (e_VALUE_MASK | e_MOVED_FLAG); if (copiedFlag) d_valueAndFlags |= e_COPIED_FLAG; } void TrackableValue::setIsMovedRaw(bool movedFlag) { d_valueAndFlags &= (e_VALUE_MASK | e_COPIED_FLAG); if (movedFlag) d_valueAndFlags |= e_MOVED_FLAG; } void TrackableValue::setValueRaw(int v) { d_valueAndFlags &= e_FLAGS_MASK; d_valueAndFlags |= v * e_VALUE_MULTIPLIER; } // TrackableValue FREE FUNCTIONS BSLA_MAYBE_UNUSED inline bool operator==(const TrackableValue& a, const TrackableValue& b) { return a.value() == b.value(); } BSLA_MAYBE_UNUSED inline bool operator!=(const TrackableValue& a, const TrackableValue& b) { return a.value() != b.value(); } BSLA_MAYBE_UNUSED inline void swap(TrackableValue& a, TrackableValue& b) { a.swap(b); } // End implementation of TrackableValue class TrackableValueWithAlloc { // Trackable value with allocator. // - Uses allocator // - Not bitwise moveable // - potentially-throwing move constructor TrackableValue d_trackable; bsl::allocator<char> d_alloc; public: BSLMF_NESTED_TRAIT_DECLARATION(TrackableValueWithAlloc, bslma::UsesBslmaAllocator); typedef bsl::allocator<char> allocator_type; explicit TrackableValueWithAlloc(int v = 0) : d_trackable(v) , d_alloc() { } explicit TrackableValueWithAlloc(const allocator_type& alloc) : d_trackable(0) , d_alloc(alloc) { } TrackableValueWithAlloc(int v, const allocator_type& alloc) : d_trackable(v) , d_alloc(alloc) { } TrackableValueWithAlloc( const TrackableValueWithAlloc& original, const allocator_type& alloc = allocator_type()) : d_trackable(original.d_trackable) , d_alloc(alloc) { } // Move constructor propagates allocator TrackableValueWithAlloc( bslmf::MovableRef<TrackableValueWithAlloc> original) : d_trackable(bslmf::MovableRefUtil::move( bslmf::MovableRefUtil::access(original).d_trackable)) , d_alloc(bslmf::MovableRefUtil::access(original).d_alloc) { } TrackableValueWithAlloc( bslmf::MovableRef<TrackableValueWithAlloc> original, const allocator_type& alloc) : d_trackable(bslmf::MovableRefUtil::move( bslmf::MovableRefUtil::access(original).d_trackable)) , d_alloc(alloc) { } ~TrackableValueWithAlloc() { memset((void *)this, 0xbb, sizeof(*this)); } TrackableValueWithAlloc& operator=(const TrackableValueWithAlloc& rhs) { d_trackable = rhs.d_trackable; return *this; } TrackableValueWithAlloc& operator=( bslmf::MovableRef<TrackableValueWithAlloc> rhs) { TrackableValueWithAlloc& rhsRef = rhs; d_trackable = bslmf::MovableRefUtil::move(rhsRef.d_trackable); return *this; } void setValue(int v) { d_trackable = v; } void resetMoveCopiedFlags() const // Set 'isMoved()' and 'isCopied() to false. { d_trackable.resetMoveCopiedFlags(); } // ACCESSORS bslma::Allocator *allocator() const { return d_alloc.mechanism(); } allocator_type get_allocator() const { return d_alloc; } bool isCopied() const { return d_trackable.isCopied(); } bool isMoved() const { return d_trackable.isMoved(); } bool isMovedFrom() const { return d_trackable.isMovedFrom(); } int value() const { return d_trackable.value(); } }; BSLA_MAYBE_UNUSED inline bool operator==(const TrackableValueWithAlloc& a, const TrackableValueWithAlloc& b) { return a.value() == b.value(); } BSLA_MAYBE_UNUSED inline bool operator!=(const TrackableValueWithAlloc& a, const TrackableValueWithAlloc& b) { return a.value() != b.value(); } TrackableValue VTV(6); int VI(6); //============================================================================= // USAGE EXAMPLES //----------------------------------------------------------------------------- namespace { ///Example 1 ///- - - - - // In this example, we define a class template, 'CountedType<TYPE>', a wrapper // around 'TYPE' that counts the count member along with the single value // member: //.. template <class TYPE> class CountedType { // PUBLIC CLASS DATA static int s_count; // PUBLIC DATA TYPE d_value; //.. // Because of externally-imposed requirements, the move constructor for // 'CountedType' must provide the strong guarantee; i.e., if the move // constructor of 'TYPE' throws an exception, then the moved-from // 'CountedType' object must be left unchanged. To support this // requirement, we next define a private static function, // 'MoveIfNoexcept', similar to the standard 'std::move_if_noexcept', // that returns a movable reference if its argument is no-throw move // constructible and a const lvalue reference otherwise: //.. // PRIVATE CLASS FUNCTIONS template <class TP> static typename bsl::conditional< bsl::is_nothrow_move_constructible<TP>::value, bslmf::MovableRef<TP>, const TP&>::type MoveIfNoexcept(TP&); //.. // We next finish out the class definition with a constructor, copy // constructor, move constructor, destructor, and member functions to // retrieve the count and value: //.. public: // CLASS FUNCTIONS static int count() { return s_count; } // CREATORS CountedType(const TYPE& val); // IMPLICIT // Construct 'CountedType' from the specified 'val'. CountedType(const CountedType& original); // IMPLICIT // Copy construct '*this' from the specified 'original' object. CountedType(bslmf::MovableRef<CountedType> original); // IMPLICIT // Move construct '*this' from 'original'. If an exception is thrown, // by the constructor for 'TYPE' 'original' is unchanged. ~CountedType() { --s_count; } // Destroy this object. // MANIPULATORS TYPE& value() { return d_value; } // ACCESSORS const TYPE& value() const { return d_value; } }; //.. // Next, we implement 'MoveIfNoexcept', which calls 'move' on its argument, // allowing it to convert back to an lvalue if the return type is an lvalue // reference: //.. template <class TYPE> template <class TP> inline typename bsl::conditional<bsl::is_nothrow_move_constructible<TP>::value, bslmf::MovableRef<TP>, const TP&>::type CountedType<TYPE>::MoveIfNoexcept(TP& x) { return bslmf::MovableRefUtil::move(x); } //.. // Next, we implement the value constructor and copy constructor, which simply // copy their argument into the 'd_value' data members and increment the count: //.. template <class TYPE> CountedType<TYPE>::CountedType(const TYPE& val) : d_value(val) { ++s_count; } template <class TYPE> CountedType<TYPE>::CountedType(const CountedType& original) : d_value(original.d_value) { ++s_count; } //.. // We're now ready implement the move constructor. Logically, we would simply // move the value from 'original' into the 'd_value' member of '*this', but an // exception thrown by 'TYPE''s move constructor would leave 'original' in a // (valid but) unspecified state, violating the strong guarantee. Instead, we // move the value only if we know that the move will succeed; otherwise, we // copy it. This behavior is facilitated by the 'MoveIfNoexcept' function // defined above: //.. template <class TYPE> CountedType<TYPE>::CountedType(bslmf::MovableRef<CountedType> original) : d_value(MoveIfNoexcept(bslmf::MovableRefUtil::access(original).d_value)) { ++s_count; } //.. // Finally, we define the 's_count' member to complete the class // implementation: //.. template <class TYPE> int CountedType<TYPE>::s_count = 0; //.. // To test the 'CountedType' class template, assume a simple client type, // 'SomeType' that makes it easy to detect if it was move constructed. // 'SomeType' holds an 'int' value which is set to -1 when it is moved from, as // shown here: //.. class SomeType { int d_value; public: SomeType(int v = 0) : d_value(v) { } // IMPLICIT SomeType(const SomeType& original) : d_value(original.d_value) { } SomeType(bslmf::MovableRef<SomeType> original) : d_value(bslmf::MovableRefUtil::access(original).d_value) { bslmf::MovableRefUtil::access(original).d_value = -1; } int value() const { return d_value; } }; //.. // Notice that 'SomeType' neglected to declare its move constructor as // 'noexcept'. This might be an oversight or it could be an old class that // predates both 'noexcept' and the 'bsl::is_nothrow_move_constructible' trait. // It is even be possible that the move constructor might throw (though, of // course, it doesn't in this simplified example). Regardless, the effect is // that move-constructing a 'CountedType<SomeType>' will result in the move // constructor actually performing a copy: //.. // void main() // { // CountedType<SomeType> obj1(1); // CountedType<SomeType> obj2(bslmf::MovableRefUtil::move(obj1)); // assert(1 == obj1.value().value()); // Copied, not moved from // assert(1 == obj2.value().value()); //.. // For the purpose of this example, we can be sure that 'SomeThing' will not // throw on move, at least not in our application. In order to obtain the // expected move optimization, we next wrap our 'SomeType in a // 'bslalg::NothrowMovableWrapper': //.. // CountedType<bslalg::NothrowMovableWrapper<SomeType> > // obj3(SomeType(3)); // CountedType<bslalg::NothrowMovableWrapper<SomeType> > // obj4(bslmf::MovableRefUtil::move(obj3)); // assert(-1 == obj3.value().unwrap().value()); // moved from // assert(3 == obj4.value().unwrap().value()); // } //.. // Note that, in the last two lines of 'main', we must call 'unwrap' in order // to access the 'SomeType' object inside of the 'NothrowMovableWrapper'. This // is one situation where it would be attractive to have an overloadable // "operator dot" so that both 'CountedThing' and 'NothrowMovableWrapper' could // be transparent proxy types. C++ does not have overloadable operator dot, // but we can create a 'CountedType' that is more intelligent about the // existance of 'NothrowMovableWrapper' and automatically unwraps values for // the user's convenience. // // Rather than starting from scratch, we'll build our new counted type, // 'CountedType2' on 'CountedType'. We start be defining a single data member // of type 'CountedType': //.. template <class TYPE> class CountedType2 { CountedType<TYPE> d_data; //.. // Next, for convenience, we add a public data type, 'ValueType' for // the value stored within 'CountedType2'. However, rather than // defining 'ValueType' as simply 'TYPE', we want to know if it is an // instantiation of 'NothrowMovableWrapper<TP>'. If it is, we want a // type that represents the unwrapped 'TP' rather than the full 'TYPE'. // For this type transformation, we turn to the type traits defined in // 'bslalg::NothrowMovableUtil':" //.. public: // TYPES typedef typename bslalg::NothrowMovableUtil::UnwrappedType<TYPE>::type ValueType; //.. // Note that the 'UnwrappedType' metafunction has no affect of 'TYPE' // is not wrapped. // // Next, we declare (and define) the class functions, constructors, and // destructor, simply forwarding to the corresponding 'CountedType' // function, constructor, or destructor: //.. // CLASS FUNCTIONS static int count() { return CountedType<TYPE>::count(); } // CREATORS CountedType2(const TYPE& val) // IMPLICIT : d_data(val) { } CountedType2(const CountedType2& original) : d_data(original.d_data) { } CountedType2(bslmf::MovableRef<CountedType2> original) // IMPLICIT : d_data(bslmf::MovableRefUtil::move( bslmf::MovableRefUtil::access(original).d_data)) { } //.. // Finally, we implement the 'value()' members such that the returned // values do not need to be unwrapped. As in the case of the // 'UnwrappedType' metafunction, the 'unwrap()' function in // 'NothrowMovableUtil' handles both wrapped and unwrapped arguments, // unwrapping the latter and returning an unmodified reference to the // former: //.. // MANIPULATORS ValueType& value() { return bslalg::NothrowMovableUtil::unwrap(d_data.value()); // Alternatively: 'return d_data.value();' } // ACCESSORS const ValueType& value() const { return bslalg::NothrowMovableUtil::unwrap(d_data.value()); // Alternatively: 'return d_data.value();' } }; //.. // Note the alternative code for these members: A 'NothrowMovableWrapper<TP>' // object is implicitly convertible to 'TP&', so if 'TYPE' is a // 'NothrowMovableWrapper', the simple return statement will implicitly unwrap // it. // // Using a similar example for 'CountedType2' as we used for 'CountedType', we // see that the usage of 'CountedType2' with and without // 'NothrowMovableWrapper' is the same: //.. void usageExample() { CountedType2<SomeType> obj1(1); CountedType2<SomeType> obj2(bslmf::MovableRefUtil::move(obj1)); ASSERT(1 == obj1.value().value()); // Copied, not moved from ASSERT(1 == obj2.value().value()); CountedType2<bslalg::NothrowMovableWrapper<SomeType> > obj3(SomeType(3)); CountedType2<bslalg::NothrowMovableWrapper<SomeType> > obj4( bslmf::MovableRefUtil::move(obj3)); ASSERT(-1 == obj3.value().value()); // moved from ASSERT(3 == obj4.value().value()); // No need to call 'unwrap' } } // close unnamed namespace #define TEST_IS_WRAPPED(TYPE, isWrapped) \ ASSERT((bslalg::NothrowMovableUtil::IsWrapped<TYPE>::value) == \ isWrapped); #define TEST_UNWRAPPED_TYPE(TYPE, Expected) \ ASSERT( \ (bsl::is_same<bslalg::NothrowMovableUtil::UnwrappedType<TYPE>::type, \ Expected>::value)); #define TEST_WRAPPED_TYPE(TYPE, Expected) \ ASSERT( \ (bsl::is_same<bslalg::NothrowMovableUtil::WrappedType<TYPE>::type, \ Expected>::value)); template <class TYPE, bool USES_BSLMA_ALLOC = BloombergLP::bslma::UsesBslmaAllocator<TYPE>::value> class AllocatorTestUtil { // This class provided test utilities that have different behaviour // depending on whether 'TYPE is allocator-aware or not. The primary // template is for allocator-aware types. public: static bool checkAllocator(const TYPE& obj, const bsl::allocator<char>& expected); // Check if, for the specified 'obj', 'obj.get_allocator()' returns the // specified 'expected' allocator. static bool hasSameAllocator(const TYPE& obj, const TYPE& other); // Check if, for the specified 'obj' and specified 'other', // 'obj.allocator() == other.allocator()'; }; template <class TYPE> class AllocatorTestUtil<TYPE, false> { // This class provided test utilities that have different behaviour // depending on whether 'TYPE is allocator-aware or not. This // specialization is for non allocator-aware types. public: static bool checkAllocator(const TYPE&, const bsl::allocator<char>&); // return 'true'. static bool hasSameAllocator(const TYPE&, const TYPE&); // return 'true'. }; template <class TYPE, bool USES_BSLMA_ALLOC> inline bool AllocatorTestUtil<TYPE, USES_BSLMA_ALLOC>::checkAllocator( const TYPE& obj, const bsl::allocator<char>& expected) { return (expected == obj.get_allocator()); } template <class TYPE, bool USES_BSLMA_ALLOC> inline bool AllocatorTestUtil<TYPE, USES_BSLMA_ALLOC>::hasSameAllocator( const TYPE& obj, const TYPE& other) { return (obj.allocator() == other.allocator()); } template <class TYPE> inline bool AllocatorTestUtil<TYPE, false>::checkAllocator(const TYPE&, const bsl::allocator<char>&) { return true; } template <class TYPE> inline bool AllocatorTestUtil<TYPE, false>::hasSameAllocator(const TYPE&, const TYPE&) { return true; } template <class TYPE> bool checkAllocator(const TYPE& obj, const bsl::allocator<char>& allocator) // If 'TYPE' is allocator-aware, return whether the allocator of the // specified 'obj' is the specified 'allocator'; otherwise return 'true'. { return AllocatorTestUtil<TYPE>::checkAllocator(obj, allocator); } template <class TYPE> bool hasSameAllocator(const TYPE& obj1, const TYPE& obj2) // If 'TYPE' is allocator-aware, return whether the allocator of the // specified 'obj1' matches that of specified 'obj2'; otherwise return // 'true'. { return AllocatorTestUtil<TYPE>::hasSameAllocator(obj1, obj2); } // ============================================================================ // TEST DRIVER TEMPLATE // ---------------------------------------------------------------------------- template <class TEST_TYPE> class TestDriver { // This class template provides a namespace for testing the // 'bslalg::NothrowMovableUtil' when used with 'TEST_TYPE'. public: // TYPES enum ValueCategory { e_LVALUE_REF, e_CONST_LVALUE_REF, e_MOVABLE_REF, e_CONST_MOVABLE_REF }; private: // PRIVATE TYPES typedef BloombergLP::bslalg::NothrowMovableUtil Util; // abbreviation for utility struct typedef typename Util::UnwrappedType<TEST_TYPE>::type ValueType; // Unwrapped type typedef typename bsl::remove_cv<ValueType>::type NonConstValueType; // non const version of ValueType. This is needed for // checkValueCategory overloads. typedef typename Util::WrappedType<TEST_TYPE>::type WrappedType; // Wrapped type public: static ValueCategory checkValueCategory(NonConstValueType&); static ValueCategory checkValueCategory(const NonConstValueType&); static ValueCategory checkValueCategory( BloombergLP::bslmf::MovableRef<NonConstValueType>); static ValueCategory checkValueCategory( BloombergLP::bslmf::MovableRef<const NonConstValueType>); // Helper functions to determine the value category of an expression. // Returns the 'ValueCategory' value corresponding to the value // category and the constness of the argument. static void testCase3(); // TESTING 'wrap' METHOD static void testCase4(); // TESTING 'unwrap' METHOD }; template <class TYPE> typename TestDriver<TYPE>::ValueCategory TestDriver<TYPE>::checkValueCategory( NonConstValueType&) { return e_LVALUE_REF; } template <class TYPE> typename TestDriver<TYPE>::ValueCategory TestDriver<TYPE>::checkValueCategory( const NonConstValueType&) { return e_CONST_LVALUE_REF; } template <class TYPE> typename TestDriver<TYPE>::ValueCategory TestDriver<TYPE>::checkValueCategory( BloombergLP::bslmf::MovableRef<NonConstValueType>) { return e_MOVABLE_REF; } template <class TYPE> typename TestDriver<TYPE>::ValueCategory TestDriver<TYPE>::checkValueCategory( BloombergLP::bslmf::MovableRef<const NonConstValueType>) { return e_CONST_MOVABLE_REF; } template <class TYPE> void TestDriver<TYPE>::testCase4() { // -------------------------------------------------------------------- // TESTING 'unwrap' METHOD // // Concerns: //: 1 Invoking 'unwrap' method with an argument of an unwrapped type //: returns a reference to the argument. //: //: 2 Invoking 'unwrap' method with an argument of a wrapped type returns //: a reference to the wrapped object. //: //: 3 That the value category of the returned reference matches the value //: category of the argument. //: //: 4 That the returned reference is a const reference if the argument is //: a reference to a const unwrapped object or a reference to a wrapper //: of const type. Otherwise, the returned reference is a reference to //: a modifiable object. // // Plan: //: 1 Using a matrix of all value categories, invoke unwrap and //: verify the returned reference has the correct value category and //: constness using 'checkValueCategory' helper function. [C-3][C-4] //: //: 2 In step 1, check the address of the returned object matches the //: address of the unwrap argument if the argument is of an unwrapped //: type, or the address of the argument's wrapped 'ValueType' object //: otherwise. [C-1], [C-2] // // Testing: // unwrap(TYPE&); // unwrap(TYPE const&); // unwrap(BSLALG_NOTHROWMOVABLEUTIL_DEDUCE_RVREF(TYPE)); // unwrap(BSLALG_NOTHROWMOVABLEUTIL_DEDUCE_RVREF(const TYPE)); // -------------------------------------------------------------------- typedef bslalg::ConstructorProxy<TYPE> TypeWithAllocator; bslma::TestAllocator da("default", veryVeryVeryVerbose); bslma::TestAllocator oa("other", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); if (veryVerbose) printf("\tCalling unwrap with a non const lvalue ref.\n"); { TypeWithAllocator xBuffer(ValueType(3), &oa); TYPE& x = xBuffer.object(); const ValueType& val = x; ValueType& unwrappedX = Util::unwrap(x); ASSERT(checkValueCategory(Util::unwrap(x)) == (bsl::is_const<ValueType>::value ? e_CONST_LVALUE_REF : e_LVALUE_REF)); ASSERT(BSLS_UTIL_ADDRESSOF(unwrappedX) == BSLS_UTIL_ADDRESSOF(val)); } if (veryVerbose) printf("\tCalling unwrap with a const lvalue ref.\n"); { TypeWithAllocator xBuffer(ValueType(3), &oa); const TYPE& x = xBuffer.object(); const ValueType& val = x; const ValueType& unwrappedX = Util::unwrap(x); ASSERT(checkValueCategory(Util::unwrap(x)) == e_CONST_LVALUE_REF); ASSERT(BSLS_UTIL_ADDRESSOF(unwrappedX) == BSLS_UTIL_ADDRESSOF(val)); } if (veryVerbose) printf("\tCalling unwrap with a non const movable ref.\n"); { TypeWithAllocator xBuffer(ValueType(3), &oa); TYPE& x = xBuffer.object(); const ValueType& val = x; BloombergLP::bslmf::MovableRef<ValueType> unwrappedX = Util::unwrap(MoveUtil::move(x)); ASSERT(checkValueCategory(Util::unwrap(MoveUtil::move(x))) == (bsl::is_const<ValueType>::value ? e_CONST_MOVABLE_REF : e_MOVABLE_REF)); ASSERT(BSLS_UTIL_ADDRESSOF(MoveUtil::access(unwrappedX)) == BSLS_UTIL_ADDRESSOF(val)); } if (veryVerbose) printf("\tCalling unwrap with a const movable ref.\n"); { TypeWithAllocator xBuffer(ValueType(3), &oa); const TYPE& x = xBuffer.object(); const ValueType& val = x; BloombergLP::bslmf::MovableRef<const ValueType> unwrappedX = Util::unwrap(MoveUtil::move(x)); ASSERT(checkValueCategory(Util::unwrap(MoveUtil::move(x))) == e_CONST_MOVABLE_REF); ASSERT(BSLS_UTIL_ADDRESSOF(MoveUtil::access(unwrappedX)) == BSLS_UTIL_ADDRESSOF(val)); } } template <class TYPE> void TestDriver<TYPE>::testCase3() { // -------------------------------------------------------------------- // TESTING 'wrap' METHOD // // Concerns: //: 1 Invoking 'wrap' method with an argument of an unwrapped type returns //: a wrapper object containing a copy of the argument. //: //: 2 Invoking 'wrap' method with an argument of a wrapped type returns a //: copy of the same object. //: //: 3 Wrapping an object of 'const TYPE' yields a //: 'NothrowMovableWrapper<const TYPE>'. //: //: 4 The argument is moved from if it is a movable ref to a non-const //: object having a move constructor // // Plan: //: 1 Create an object of 'TYPE' from a 'ValueType' object. Using the //: 'wrap' method, created a Wrapper object. Verify that the Wrapper //: object contains a copy of the original ValueType object. [C-1][C-2] //: //: 2 Repeat step 1 using a const object of 'TYPE'. [C-3] //: //: 3 Repeat step 1 invoking wrap by moving from the original object. //: Verify the object inside the returned wrapper has been created by //: move construction if the original object is a non const object //: of a type with a move constructor. [C-4] // // Testing: // wrap(TYPE& ); // wrap(TYPE const&); // wrap(BSLALG_NOTHROWMOVABLEUTIL_DEDUCE_RVREF(TYPE)); // wrap(BSLALG_NOTHROWMOVABLEUTIL_DEDUCE_RVREF(const TYPE)); // -------------------------------------------------------------------- typedef bslalg::ConstructorProxy<TYPE> TypeWithAllocator; bslma::TestAllocator da("default", veryVeryVeryVerbose); bslma::TestAllocator oa("other", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); if (veryVerbose) printf("\tWrapping a non const object.\n"); { TypeWithAllocator xBuffer(ValueType(3), &oa); TYPE& x = xBuffer.object(); ValueType exp(3); const WrappedType& wrappedX = Util::wrap(x); // using const reference to get lifetime extension. ASSERT(wrappedX.unwrap() == exp); ASSERT(wrappedX.unwrap().isCopied()); ASSERT(!wrappedX.unwrap().isMoved()); ASSERT(checkAllocator(wrappedX.unwrap(), &da)); } if (veryVerbose) printf("\tWrapping a const object.\n"); { TypeWithAllocator xBuffer(ValueType(3), &oa); const TYPE& x = xBuffer.object(); ValueType exp(3); const WrappedType& wrappedX = Util::wrap(x); // using const reference to get lifetime extension. ASSERT(wrappedX.unwrap() == exp); ASSERT(wrappedX.unwrap().isCopied()); ASSERT(!wrappedX.unwrap().isMoved()); ASSERT(checkAllocator(wrappedX.unwrap(), &da)); } if (veryVerbose) printf("\tWrapping a non const movable ref .\n"); { TypeWithAllocator xBuffer(ValueType(3), &oa); TYPE& x = xBuffer.object(); ValueType exp(3); ValueType& val = x; val.resetMoveCopiedFlags(); const WrappedType& wrappedX = Util::wrap(MoveUtil::move(x)); // using const reference to get lifetime extension. // If TYPE is const, wrap will perform a copy. Otherwise, it will do a // move ASSERT(wrappedX.unwrap() == exp); ASSERT(wrappedX.unwrap().isCopied() == bsl::is_const<ValueType>::value); ASSERT(wrappedX.unwrap().isMoved() != bsl::is_const<ValueType>::value); ASSERT(checkAllocator(wrappedX.unwrap(), (bsl::is_const<ValueType>::value ? &da : &oa))); } if (veryVerbose) printf("\tWrapping a const movable ref .\n"); { const TYPE x(ValueType(3)); ValueType exp(3); const ValueType& val = x; val.resetMoveCopiedFlags(); const WrappedType& wrappedX = Util::wrap(MoveUtil::move(x)); // using const reference to get lifetime extension. ASSERT(wrappedX.unwrap() == exp); ASSERT(wrappedX.unwrap().isCopied()); ASSERT(!wrappedX.unwrap().isMoved()); } } //============================================================================= // MAIN PROGRAM //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; verbose = argc > 2; veryVerbose = argc > 3; veryVeryVerbose = argc > 4; veryVeryVeryVerbose = argc > 5; printf("TEST " __FILE__ " CASE %d\n", test); switch (test) { case 0: // Zero is always the leading case. case 5: { // -------------------------------------------------------------------- // USAGE EXAMPLE // // Concerns: //: 1 That the usage example in the component documentation compiles //: and runs correctly. // // Plan: //: 1 Copy the usage example directly into the test driver. // // Testing: // USAGE EXAMPLE // -------------------------------------------------------------------- if (verbose) printf("\nUSAGE EXAMPLE" "\n=============\n"); usageExample(); } break; case 4: { // -------------------------------------------------------------------- // TESTING 'unwrap' METHOD // -------------------------------------------------------------------- if (verbose) printf("\nTESTING 'unwrap' METHOD" "\n=======================\n"); RUN_EACH_TYPE( TestDriver, testCase4, TrackableValue, TrackableValueWithAlloc, BloombergLP::bslalg::NothrowMovableWrapper<TrackableValue>, BloombergLP::bslalg::NothrowMovableWrapper< TrackableValueWithAlloc>, BloombergLP::bslalg::NothrowMovableWrapper<const TrackableValue>, BloombergLP::bslalg::NothrowMovableWrapper< const TrackableValueWithAlloc>); } break; case 3: { // -------------------------------------------------------------------- // TESTING 'wrap' METHOD // -------------------------------------------------------------------- if (verbose) printf("\nTESTING 'wrap' METHOD" "\n=====================\n"); RUN_EACH_TYPE( TestDriver, testCase3, TrackableValue, TrackableValueWithAlloc, BloombergLP::bslalg::NothrowMovableWrapper<TrackableValue>, BloombergLP::bslalg::NothrowMovableWrapper< TrackableValueWithAlloc>, BloombergLP::bslalg::NothrowMovableWrapper<const TrackableValue>, BloombergLP::bslalg::NothrowMovableWrapper< const TrackableValueWithAlloc>); } break; case 2: { // -------------------------------------------------------------------- // TESTING 'NothrowMovableUtil' TRAITS // // This test checks the correct behaviour of 'NothrowMovableUtil' // traits. // // Concerns: //: 1 'IsWrapped<TYPE>' trait is derived from 'bsl::true_type' if and //: only if 'TYPE' is a specialization of 'NothrowMovableWrapper'. //: //: 2 'WrappedType<TYPE>::type' is 'NothrowMovableWrapper<TYPE>' if //: 'TYPE' is not a specialization of 'NothrowMovableWrapper', and //: 'TYPE' otherwise. //: //: 3 'UnWrappedType<TYPE>::type' is 'TYPE' if 'TYPE' is not a //: specialization of 'NothrowMovableWrapper' and 'TYPE is not a //: function, 'TYPE*' if TYPE is a function, and 'TYPE::ValueType' //: otherwise. // // Plan: //: 1 Using a 'TYPE' which is not a specialization of //: 'NothrowMovableWrapper' check that 'IsWrapped<TYPE>' trait is //: derived from 'bsl::false_type'. [C-1] //: //: 2 In step 1, check that 'WrappedType<TYPE>::type' is //: 'NothrowMovableWrapper<TYPE>'. [C-2] //: //: 3 In step 1, check that 'UnwrappedType<TYPE>::type' is 'TYPE'. //: [C-3] //: //: 4 In step 3, using a function type 'TYPE', verify that //: 'UnwrappedType<TYPE>::type' is 'TYPE*' //: //: 5 Using a 'NothrowMovableWrapper<TYPE> as test type, check that //: 'IsWrapped<TYPE>' trait is derived from 'bsl::true_type'. [C-1] //: //: 6 In step 5, check that 'WrappedType<TYPE>::type' is 'TYPE'. //: [C-2] //: //: 7 In step 6, check that 'UnwrappedType<TYPE>::type' is //: 'TYPE::ValueType'. [C-3] // // Testing: // IsWrapped // UnwrappedType // WrappedType // -------------------------------------------------------------------- if (verbose) printf("\nTESTING 'NothrowMovableUtil' TRAITS" "\n===================================\n"); if (veryVerbose) printf("\tTesting isWrapped.\n"); { TEST_IS_WRAPPED( int, false ); TEST_IS_WRAPPED( const int, false ); TEST_IS_WRAPPED( FunctionPtrType, false ); TEST_IS_WRAPPED( FunctionType, false ); TEST_IS_WRAPPED( WrappedInt, true ); TEST_IS_WRAPPED( WrappedConstInt, true ); TEST_IS_WRAPPED( WrappedFunctionPtrType, true ); } if (veryVerbose) printf("\tTesting UnwrappedType.\n"); { TEST_UNWRAPPED_TYPE( int, int ); TEST_UNWRAPPED_TYPE( const int, const int ); TEST_UNWRAPPED_TYPE( FunctionPtrType, FunctionPtrType ); TEST_UNWRAPPED_TYPE( FunctionType, FunctionPtrType ); TEST_UNWRAPPED_TYPE( WrappedInt, int ); TEST_UNWRAPPED_TYPE( WrappedConstInt, const int ); TEST_UNWRAPPED_TYPE( WrappedFunctionPtrType, FunctionPtrType ); } if (veryVerbose) printf("\tTesting WrappedType.\n"); { TEST_WRAPPED_TYPE( int, WrappedInt ); TEST_WRAPPED_TYPE( const int, WrappedConstInt ); TEST_WRAPPED_TYPE( FunctionPtrType, WrappedFunctionPtrType ); TEST_WRAPPED_TYPE( FunctionType, WrappedFunctionPtrType ); TEST_WRAPPED_TYPE( WrappedInt, WrappedInt ); TEST_WRAPPED_TYPE( WrappedConstInt, WrappedConstInt ); TEST_WRAPPED_TYPE( WrappedFunctionPtrType,WrappedFunctionPtrType ); } } break; case 1: { // -------------------------------------------------------------------- // BREATHING TEST // // Concerns: //: 1 That the basic 'NothrowMovableUtil' functionality works as // intended. // // Plan: //: 1 Wrap and unwrap an object. //: //: 2 Apply each of the traits. // // Testing: // BREATHING TEST // -------------------------------------------------------------------- if (verbose) printf("\nBREATHING TEST" "\n==============\n"); bslalg::NothrowMovableUtil::WrappedType<int>::type intWrap = bslalg::NothrowMovableUtil::wrap(VI); ASSERT(intWrap.unwrap() == VI); bslalg::NothrowMovableUtil::WrappedType<TrackableValue>::type trackableValueWrap = bslalg::NothrowMovableUtil::wrap(VTV); ASSERT(trackableValueWrap.unwrap() == VTV); ASSERT(!(bslalg::NothrowMovableUtil_Traits<int>::IsWrapped::value)); ASSERT(( bsl::is_same<bslalg::NothrowMovableUtil_Traits<int>::UnwrappedType, int>::value)); ASSERT( (bsl::is_same<bslalg::NothrowMovableUtil_Traits<int>::WrappedType, WrappedInt>::value)); ASSERT( (bslalg::NothrowMovableUtil_Traits<WrappedInt>::IsWrapped::value)); ASSERT((bsl::is_same< bslalg::NothrowMovableUtil_Traits<WrappedInt>::UnwrappedType, int>::value)); ASSERT((bsl::is_same< bslalg::NothrowMovableUtil_Traits<WrappedInt>::WrappedType, WrappedInt>::value)); } break; default: { fprintf(stderr, "WARNING: CASE '%d' NOT FOUND.\n", test); testStatus = -1; } } if (testStatus > 0) { fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus); } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2020 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
36.967057
80
0.588669
eddiepierce
b87653a3554e9111f5840f45dd932de5a1e33c09
6,066
cpp
C++
src/acid.cpp
Celissa/Legacy-Base
027553da16342c4e31cebf5eaad6925fbaa5d5a5
[ "CC-BY-3.0" ]
1
2018-09-16T03:17:50.000Z
2018-09-16T03:17:50.000Z
src/acid.cpp
Celissa/Legacy-Base
027553da16342c4e31cebf5eaad6925fbaa5d5a5
[ "CC-BY-3.0" ]
null
null
null
src/acid.cpp
Celissa/Legacy-Base
027553da16342c4e31cebf5eaad6925fbaa5d5a5
[ "CC-BY-3.0" ]
null
null
null
#include "system.h" /* * ACID DAMAGE ROUTINES */ int obj_data :: vs_acid( ) { int save = 100; int i; for( i = 0; i < MAX_MATERIAL; i++ ) if( is_set( &pIndexData->materials, i ) ) save = min( save, material_table[i].save_acid ); if( pIndexData->item_type != ITEM_ARMOR || pIndexData->item_type != ITEM_WEAPON || pIndexData->item_type != ITEM_SHIELD ) return save; return save+value[0]*(100-save)/(value[0]+2); } bool affected_shock( char_data* ch ) { if( !is_set( ch->affected_by, AFF_ION_SHIELD ) && !is_set( ch->affected_by, AFF_SPARK_SHIELD ) && !is_set( ch->affected_by, AFF_SHOCK_SHIELD ) && !is_set( ch->affected_by, AFF_LIGHTNING_SHIELD ) ) return FALSE; return TRUE; } /* * ACID BASED SPELLS */ bool spell_resist_acid( char_data* ch, char_data* victim, void*, int level, int duration ) { spell_affect( ch, victim, level, duration, SPELL_RESIST_ACID, AFF_RESIST_ACID ); return TRUE; } bool spell_acid_blast( char_data* ch, char_data* victim, void* vo, int level, int duration ) { obj_data* obj = (obj_data*) vo; int save; /* Quaff */ if( ch == NULL && obj == NULL ) { fsend( victim, "You feel incredible pain as the acid eats away at your stomach and throat. Luckily you don't feel it for long." ); fsend_seen( victim, "%s grasps %s throat and spasms in pain - %s does not survive long.", victim, victim->His_Her( ), victim->He_She( ) ); death_message( victim ); death( victim, NULL, "drinking acid" ); return TRUE; } /* Fill */ if( ch == NULL ) { if( obj->metal( ) || is_set( &obj->materials, MAT_STONE ) || is_set( &obj->materials, MAT_GLASS ) ) return FALSE; fsend( victim, "The acid bubbles and boils, eating its way through %s, which you quickly drop and watch disappear into nothing.\r\n", obj ); fsend( *victim->array, "%s quickly drops %s as %s dissolved by the liquid.", victim, obj, obj->selected > 1 ? "they are" : "it is" ); obj->Extract( obj->selected ); return TRUE; } /* Dip */ if( duration == -3 ) { save = obj->vs_acid( ); if( number_range( 0,99 ) > save ) { if( number_range( 0,99 ) > save ) { send( *ch->array, "%s is devoured.\r\n", obj ); obj->Extract( 1 ); return TRUE; } send( ch, "%s is partially destroyed.\r\n", obj ); } if( obj->rust > 0 ) { send( ch, "%sthe %s on %s is removed.\r\n", obj->rust-- > 1 ? "Some of " : "", "rust", obj ); } return TRUE; } /* Throw-Cast */ damage_acid( victim, ch, spell_damage( SPELL_ACID_BLAST, level ), "*the splatter of acid" ); return TRUE; } bool spell_acid_storm( char_data* ch, char_data* victim, void*, int level, int ) { damage_acid( victim, ch, spell_damage( SPELL_ACID_STORM, level ), "*the blast of acid" ); return TRUE; } bool spell_acid_arrow( char_data* ch, char_data* victim, void*, int level, int ) { damage_acid( victim, ch, spell_damage( SPELL_ACID_ARROW, level ), "*the acidic arrow" ); return TRUE; } bool spell_horrid_wilting( char_data* ch, char_data* victim, void*, int level, int ) { damage_acid( victim, ch, spell_damage( SPELL_HORRID_WILTING, level ), "*the horrific acid" ); return TRUE; } bool spell_withering_blast( char_data* ch, char_data* victim, void*, int level, int duration ) { damage_element( victim, ch, spell_damage( SPELL_WITHERING_BLAST, level ), "*the acidic blast", ATT_ACID ); if( victim->hit >= 0 ) spell_affect( ch, victim, level, duration, SPELL_WITHERING_BLAST, AFF_ACID_DEATH ); return TRUE; } bool spell_erosion_shield( char_data* ch, char_data* victim, void*, int level, int duration ) { if( !consenting( victim, ch, "shield of erosion" ) ) return TRUE; if( affected_shock( victim ) ) { send( victim, "The roaring electricity prevents the acid from surrounding you.\r\n" ); send_seen( victim, "The roaring electricity protecting %s stops the acid.\r\n", victim ); return TRUE; } spell_affect( ch, victim, level, duration, SPELL_EROSION_SHIELD, AFF_EROSION_SHIELD ); return TRUE; } bool spell_corrosive_shield( char_data* ch, char_data* victim, void*, int level, int duration ) { if( !consenting( victim, ch, "shield of corrosion" ) ) return TRUE; if( affected_shock( victim ) ) { send( victim, "The roaring electricity prevents the acid from surrounding you.\r\n" ); send_seen( victim, "The roaring electricity protecting %s stops the acid.\r\n", victim ); return TRUE; } spell_affect( ch, victim, level, duration, SPELL_CORROSIVE_SHIELD, AFF_CORROSIVE_SHIELD ); return TRUE; } bool spell_caustic_shield( char_data* ch, char_data* victim, void*, int level, int duration ) { if( !consenting( victim, ch, "caustic shield" ) ) return TRUE; if( affected_shock( victim ) ) { send( victim, "The roaring electricity prevents the acid from surrounding you.\r\n" ); send_seen( victim, "The roaring electricity protecting %s stops the acid.\r\n", victim ); return TRUE; } spell_affect( ch, victim, level, duration, SPELL_CAUSTIC_SHIELD, AFF_CAUSTIC_SHIELD ); return TRUE; } /* * Druid Acid Spells */ bool spell_autumn_touch( char_data* ch, char_data* victim, void*, int level, int ) { damage_element( victim, ch, spell_damage( SPELL_AUTUMN_TOUCH, level ), "*The erosion of autumn", ATT_ACID ); return TRUE; } bool spell_frog_tongue( char_data* ch, char_data* victim, void*, int level, int ) { damage_element( victim, ch, spell_damage( SPELL_FROG_TONGUE, level ), "*The frog's acidic tongue", ATT_ACID ); return TRUE; } bool spell_acidic_water( char_data* ch, char_data* victim, void*, int level, int ) { damage_element( victim, ch, spell_damage( SPELL_ACIDIC_WATER, level ), "*The bubbling acidic water", ATT_ACID ); return TRUE; } bool spell_acid_rain( char_data* ch, char_data* victim, void*, int level, int ) { damage_element( victim, ch, spell_damage( SPELL_ACID_RAIN, level ), "*The stinging acid rain", ATT_ACID ); return TRUE; }
27.953917
144
0.661556
Celissa
b877a8ebf250532bd1f23deedb2ef1f8fed418c1
2,802
cpp
C++
solutions/src/map_groupAnagrams.cpp
imvasu/algorithms
6013bc4c0d3b1f233adc83b2f6fa9d51d482a441
[ "Apache-2.0" ]
null
null
null
solutions/src/map_groupAnagrams.cpp
imvasu/algorithms
6013bc4c0d3b1f233adc83b2f6fa9d51d482a441
[ "Apache-2.0" ]
3
2018-03-27T23:43:30.000Z
2018-03-27T23:48:58.000Z
solutions/src/map_groupAnagrams.cpp
imvasu/algorithms
6013bc4c0d3b1f233adc83b2f6fa9d51d482a441
[ "Apache-2.0" ]
null
null
null
// // map_groupAnagrams.cpp // algorithms // // Created by Vasu Pasupuleti on 3/28/18. // Copyright © 2018 Vasu Pasupuleti. All rights reserved. // /* INPUT anagrams(['xxy', 'cab', 'bca', 'cab', 'bac', 'dash', 'shad']) OUTPUT [ ['xxy'], ['cab', 'bca’, 'bac'], ['dash', 'shad'] ] Group strings that are anagram of each other into a list without duplicate. ‘cab’ is an example duplicates removed. There are 2 ‘cab’ in the input and only 1 ‘cab’ in the output. You can think of anagram as two words that have the same count per letter. You should treat upper and lower case differently. 'xxy’ is by itself because it doesn’t have any other strings that are anagram with ’xxy’ Abc and abc are NOT anagrams abcc and abc are NOT anagrams abc and cab are anagrams because each of them has 1 a, 1 b, and 1 c You can assume it’s 256 ASCII You don’t need to compile the code, let me know when you’re done implementing the code. If you’re unsure about the syntax, just make it up. */ #include "map_groupAnagrams.hpp" #include <vector> #include <map> #include <string> #include <algorithm> #include <iostream> #include <set> using namespace std; vector<set<string> > groupAnagrams(vector<string> input) { map<string, set<string> > groups; for(int i=0; i < input.size(); i++) { string key = input[i]; sort(key.begin(),key.end()); if(groups.find(key) == groups.end()) { set<string> s; s.insert(input[i]); groups[key] = s; } else { (groups[key]).insert(input[i]); } } vector<set<string> > output; map<string, set<string> > :: iterator it = groups.begin(); for(;it!=groups.end();it++) { set<string> values = it->second; output.push_back(values); } return output; } int main() { const char* str[] = {"xxy", "cab", "bca", "cab", "bac", "dash", "shad", "shad"}; vector<string> input(str,str+sizeof(str)/sizeof(str[0])); vector<set<string> > output = groupAnagrams(input); for(int i=0;i<output.size();i++) { set<string> :: iterator it = output[i].begin(); for(;it!=output[i].end();it++) { cout<<*it<<" "; } cout<<endl; } } /* ['xxy', 'yxx'] algorithm: { ['xxy'] : {'xxy'} ['cab'] : {'cab', 'bca’, 'bac'} cost of checking for anagram - len(key) cost of checking all keys - o(nkeys) o(n2) keep keys in sorted order sort the new key and check in hash whether the key exist or not? check and insert anagram - O(klogk) } input: vector<string> input output: vector<vector<string>> output 1. iterate through the input strings 2. sort the string 3. check if it exists in the map 4. if yes, insert Unit tests: Test1: 1 string Test2: general case Test3: all strings are same anagram Test4: all unique strings Test5: no strings */
20.602941
140
0.637759
imvasu
b87b8beef92029ae1f4a625461703b424c687e50
1,079
hpp
C++
include/mtl/memory.hpp
scaryrawr/mtl
eea8e9c6662b613dc5098a2cb442a7b1522bf8f0
[ "MIT" ]
null
null
null
include/mtl/memory.hpp
scaryrawr/mtl
eea8e9c6662b613dc5098a2cb442a7b1522bf8f0
[ "MIT" ]
null
null
null
include/mtl/memory.hpp
scaryrawr/mtl
eea8e9c6662b613dc5098a2cb442a7b1522bf8f0
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <type_traits> #include "type_traits.hpp" namespace mtl { template <class FuncPtr, FuncPtr func> struct custom_delete { using value_type = unary_argument_type_t<FuncPtr>; auto operator()(value_type arg) const { return func(arg); } }; template <class FuncPtr, FuncPtr func> using unique_ptr = std::unique_ptr<std::remove_pointer_t<unary_argument_type_t<FuncPtr>>, custom_delete<FuncPtr, func>>; template <class PtrType, class FuncPtr, FuncPtr func> using typed_unique_ptr = std::unique_ptr<PtrType, custom_delete<FuncPtr, func>>; template <class SmartPtr> struct out_ptr { using pointer = typename SmartPtr::pointer; out_ptr(SmartPtr &smartpointer) : wrapper(smartpointer) { } ~out_ptr() { wrapper.reset(ptr); } operator pointer *() { return &ptr; } private: pointer ptr{}; SmartPtr &wrapper; }; } // namespace mtl
21.58
124
0.60519
scaryrawr
b87bf58908deca82c70532bdeab9663f6056fb00
2,595
cpp
C++
weekly-challenges/week154.cpp
guicaiWXY/HIHO-problems
e4334e3a13eb18d16c5902064ea02c38ab3c2cc2
[ "MIT" ]
null
null
null
weekly-challenges/week154.cpp
guicaiWXY/HIHO-problems
e4334e3a13eb18d16c5902064ea02c38ab3c2cc2
[ "MIT" ]
null
null
null
weekly-challenges/week154.cpp
guicaiWXY/HIHO-problems
e4334e3a13eb18d16c5902064ea02c38ab3c2cc2
[ "MIT" ]
null
null
null
// // Created by wxy on 17.6.15. // #include <vector> #include <cstring> #include "week154.h" #include <cstdio> //#define SQR(__x) ((__x) * (__x)) //#define INTERSECTED(i, j) ((long long)SQR(x[(i)] - x[(j)]) + SQR(y[(i)] - y[(j)])) <= (long long)SQR(r[(i)] + r[(j)]) int x[1000]; int y[1000]; int r[1000]; int indices[1002]; int H; int week154::run() { int n; scanf("%d", &n); getchar(); int i; int width; int height; int N; for (i=0; i < n; i++) { scanf("%d %d %d", &width, &height, &N); getchar(); H = height; int j; for (j=0; j < N; j++) { scanf("%d %d %d", x+j, y+j, r+j); getchar(); } judge(N); } return 0; } void dump(int N) { for (int i = 0; i < N; i++) { printf("%d ", indices[i]); } printf("\n"); } long long SQR(int x) { return ((long long)x) * x; } // get N as number of radar zones // judge if any component(of the connection graph)'s upper/lower bounds cover H int week154::judge(int N) { int i = 0; // define a structure to store already identified intersected circles for (i = 0; i < N+2; i++) { indices[i] = i; } // construct connection graph for (i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if ((long long)(r[i] + r[j]) * (r[i] + r[j]) >= (long long)(x[i] - x[j]) * (x[i] - x[j]) + (long long)(y[i] - y[j]) * (y[i] - y[j])) { // merge quick_union(i, j); } } } // dump(N+2); // judge any set's height > H for (i = 0; i < N; ++i) { if (y[i] <= r[i]) { // lower bound class quick_union(i, N); } // bug here!!! // can not use else if because r can be large enough if (y[i] >= H - r[i]) quick_union(i, N+1); } // dump(N+2); if (find(N) == find(N+1)) printf("NO\n"); else printf("YES\n"); return 0; } void week154::quick_union(int i, int j) { // int root_i = find(i); // int root_j = find(j); // if (root_i == root_j) return; // if (size[root_i] < size[root_j]) { // indices[root_i] = root_j; // size[root_j] += size[root_i]; // } else { // indices[root_j] = root_i; // size[root_i] += size[root_j]; // } // count--; indices[find(i)] = find(j); } int week154::find(int q) { while (q != indices[q]) { // compass the path indices[q] = indices[indices[q]]; q = indices[q]; } return q; }
21.991525
144
0.454721
guicaiWXY
b87c7f286679548d87c51b76c9d9274b273aaea3
3,228
cpp
C++
Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeComponentAction.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeComponentAction.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeComponentAction.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include <QmitkDataNodeComponentAction.h> // mitk core #include <mitkDataNode.h> #include <mitkImage.h> #include <mitkRenderingManager.h> // mitk gui common plugin #include <mitkDataNodeSelection.h> // qt #include <QHBoxLayout> #include <QLabel> QmitkDataNodeComponentAction::QmitkDataNodeComponentAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchpartSite) : QWidgetAction(parent) , QmitkAbstractDataNodeAction(workbenchpartSite) { InitializeAction(); } QmitkDataNodeComponentAction::QmitkDataNodeComponentAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchpartSite) : QWidgetAction(parent) , QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchpartSite)) { InitializeAction(); } void QmitkDataNodeComponentAction::InitializeAction() { setCheckable(true); m_ComponentSlider = new QmitkNumberPropertySlider; m_ComponentSlider->setOrientation(Qt::Horizontal); QLabel* componentLabel = new QLabel(tr("Component: ")); QHBoxLayout* componentWidgetLayout = new QHBoxLayout; componentWidgetLayout->setContentsMargins(4, 4, 4, 4); componentWidgetLayout->addWidget(componentLabel); componentWidgetLayout->addWidget(m_ComponentSlider); QLabel* componentValueLabel = new QLabel(); componentWidgetLayout->addWidget(componentValueLabel); connect(m_ComponentSlider, &QmitkNumberPropertySlider::valueChanged, componentValueLabel, static_cast<void (QLabel::*)(int)>(&QLabel::setNum)); QWidget* componentWidget = new QWidget; componentWidget->setLayout(componentWidgetLayout); setDefaultWidget(componentWidget); connect(this, &QmitkDataNodeComponentAction::changed, this, &QmitkDataNodeComponentAction::OnActionChanged); } void QmitkDataNodeComponentAction::InitializeWithDataNode(const mitk::DataNode* dataNode) { if (nullptr == dataNode) { m_ComponentSlider->SetProperty(static_cast<mitk::IntProperty*>(nullptr)); return; } mitk::Image* img = dynamic_cast<mitk::Image*>(dataNode->GetData()); if (nullptr == img) { m_ComponentSlider->SetProperty(static_cast<mitk::IntProperty*>(nullptr)); return; } mitk::BaseRenderer::Pointer baseRenderer = GetBaseRenderer(); int numComponents = 0; numComponents = img->GetPixelType().GetNumberOfComponents(); mitk::IntProperty* componentProperty = dynamic_cast<mitk::IntProperty*>(dataNode->GetProperty("Image.Displayed Component", baseRenderer)); if (numComponents <= 1 || nullptr == componentProperty) { m_ComponentSlider->SetProperty(static_cast<mitk::IntProperty*>(nullptr)); return; } m_ComponentSlider->SetProperty(componentProperty); m_ComponentSlider->setMinValue(0); m_ComponentSlider->setMaxValue(numComponents - 1); } void QmitkDataNodeComponentAction::OnActionChanged() { auto dataNode = GetSelectedNode(); InitializeWithDataNode(dataNode); }
31.647059
145
0.742255
zhaomengxiao
b87d1d79bf33cccff70f3a0cbfac707753bfbd76
16,038
cpp
C++
NULL Engine/Source/GameObject.cpp
xsiro/NULL_Engine
bb8da3de7f507b27d895cf8066a03faa115ff3c6
[ "MIT" ]
null
null
null
NULL Engine/Source/GameObject.cpp
xsiro/NULL_Engine
bb8da3de7f507b27d895cf8066a03faa115ff3c6
[ "MIT" ]
null
null
null
NULL Engine/Source/GameObject.cpp
xsiro/NULL_Engine
bb8da3de7f507b27d895cf8066a03faa115ff3c6
[ "MIT" ]
null
null
null
#include "VariableTypedefs.h" #include "Macros.h" #include "Log.h" #include "JSONParser.h" #include "Random.h" #include "Application.h" #include "M_Renderer3D.h" // TMP. Move the Renderers generation elsewhere. #include "R_Mesh.h" #include "Component.h" #include "C_Transform.h" #include "C_Mesh.h" #include "C_Material.h" #include "C_Light.h" #include "C_Camera.h" #include "GameObject.h" GameObject::GameObject() : uid (Random::LCG::GetRandomUint()), parent_uid (0), name ("GameObject"), is_active (true), is_static (false), parent (nullptr), is_master_root (false), is_scene_root (false), to_delete (false), show_bounding_boxes (false) { transform = (C_Transform*)CreateComponent(COMPONENT_TYPE::TRANSFORM); obb.SetNegativeInfinity(); aabb.SetNegativeInfinity(); obb_vertices = new float3[8]; // Bounding boxes will always have 8 vertices as they are Cuboids. aabb_vertices = new float3[8]; // Bounding boxes will always have 8 vertices as they are Cuboids. } GameObject::GameObject(std::string name, bool is_active, bool is_static) : uid (Random::LCG::GetRandomUint()), parent_uid (0), name (name), is_active (is_active), is_static (is_static), parent (nullptr), is_master_root (false), is_scene_root (false), to_delete (false), show_bounding_boxes (false) { uid = Random::LCG::GetRandomUint(); if (name.empty()) { name = "GameObject"; } transform = (C_Transform*)CreateComponent(COMPONENT_TYPE::TRANSFORM); obb.SetNegativeInfinity(); aabb.SetNegativeInfinity(); obb_vertices = new float3[8]; // Bounding boxes will always have 8 vertices as they are Cuboids. aabb_vertices = new float3[8]; // Bounding boxes will always have 8 vertices as they are Cuboids. } GameObject::~GameObject() { RELEASE_ARRAY(obb_vertices); RELEASE_ARRAY(aabb_vertices); } bool GameObject::Update() { bool ret = true; for (uint i = 0; i < components.size(); ++i) { if (components[i]->IsActive()) { components[i]->Update(); } } UpdateBoundingBoxes(); // Make the call in C_Transform after receiving a dirty flag? return ret; } bool GameObject::CleanUp() { bool ret = true; FreeComponents(); FreeChilds(); return ret; } bool GameObject::SaveState(ParsonNode& root) const { bool ret = true; root.SetNumber("UID", uid); uint parent_UID = (parent != nullptr) ? parent->uid : 0; root.SetNumber("ParentUID", parent_UID); root.SetString("Name", name.c_str()); root.SetBool("IsActive", is_active); root.SetBool("IsStatic", is_static); root.SetBool("IsSceneRoot", is_scene_root); root.SetBool("ShowBoundingBoxes", show_bounding_boxes); // --- OBB --- /*ParsonArray obb_array = root.SetArray("OBB"); math::vec* obb_points = new math::vec[8]; obb.GetCornerPoints(obb_points); for (uint i = 0; i < 8; ++i) { obb_array.SetNumber(obb_points[i].x); obb_array.SetNumber(obb_points[i].y); obb_array.SetNumber(obb_points[i].z); } delete[] obb_points; // --- AABB --- ParsonArray aabb_array = root.SetArray("AABB"); math::vec* aabb_points = new math::vec[8]; aabb.GetCornerPoints(aabb_points); for (uint i = 0; i < 8; ++i) { aabb_array.SetNumber(aabb_points[i].x); aabb_array.SetNumber(aabb_points[i].y); aabb_array.SetNumber(aabb_points[i].z); } delete[] aabb_points;*/ ParsonArray component_array = root.SetArray("Components"); for (uint i = 0; i < components.size(); ++i) { ParsonNode component_node = component_array.SetNode(components[i]->GetNameFromType()); components[i]->SaveState(component_node); } return ret; } bool GameObject::LoadState(ParsonNode& root) { bool ret = true; ForceUID((uint)root.GetNumber("UID")); parent_uid = (uint)root.GetNumber("ParentUID"); name = root.GetString("Name"); is_active = root.GetBool("IsActive"); is_static = root.GetBool("IsStatic"); is_scene_root = root.GetBool("IsSceneRoot"); show_bounding_boxes = root.GetBool("ShowBoundingBoxes"); // Recalculate AABB and OBB ParsonArray components_array = root.GetArray("Components"); for (uint i = 0; i < components_array.size; ++i) { ParsonNode component_node = components_array.GetNode(i); if (!component_node.NodeIsValid()) { continue; } COMPONENT_TYPE type = (COMPONENT_TYPE)component_node.GetNumber("Type"); if (type == COMPONENT_TYPE::TRANSFORM) { GetTransformComponent()->LoadState(component_node); continue; } else { Component* component = nullptr; switch (type) { //case COMPONENT_TYPE::TRANSFORM: { component = new C_Transform(this); } break; case COMPONENT_TYPE::MESH: { component = new C_Mesh(this); } break; case COMPONENT_TYPE::MATERIAL: { component = new C_Material(this); } break; case COMPONENT_TYPE::LIGHT: { component = new C_Light(this); } break; case COMPONENT_TYPE::CAMERA: { component = new C_Camera(this); } break; } if (component != nullptr) { component->LoadState(component_node); components.push_back(component); } } } return ret; } // --- GAMEOBJECT METHODS --- void GameObject::FreeComponents() { transform = nullptr; for (uint i = 0; i < components.size(); ++i) { components[i]->CleanUp(); RELEASE(components[i]); } components.clear(); } void GameObject::FreeChilds() { if (parent != nullptr) { parent->DeleteChild(this); // Deleting this GameObject from the childs list of its parent. } for (uint i = 0; i < childs.size(); ++i) { if (childs[i] != nullptr) { childs[i]->to_delete = true; // Will set the children of the GameObject being deleted to be deleted too in M_Scene's game_objects vector. //childs[i]->CleanUp(); // Recursively cleaning up the the childs. } } childs.clear(); } void GameObject::UpdateBoundingBoxes() { std::vector<C_Mesh*> c_meshes; GetAllMeshComponents(c_meshes); for (uint i = 0; i < c_meshes.size(); ++i) { if (c_meshes[i] == nullptr || c_meshes[i]->GetMesh() == nullptr) { continue; } obb = c_meshes[i]->GetMesh()->GetAABB(); obb.Transform(GetTransformComponent()->GetWorldTransform()); aabb.SetNegativeInfinity(); aabb.Enclose(obb); } c_meshes.clear(); } AABB GameObject::GetAABB() const { return aabb; } float3* GameObject::GetAABBVertices() const { return aabb_vertices; } void GameObject::GetRenderers(std::vector<MeshRenderer>& mesh_renderers, std::vector<CuboidRenderer>& cuboid_renderers) { std::vector<C_Mesh*> c_meshes; GetAllMeshComponents(c_meshes); C_Material* c_material = GetMaterialComponent(); C_Camera* c_camera = GetCameraComponent(); for (uint i = 0; i < c_meshes.size(); ++i) { if (c_meshes[i] != nullptr) { if (c_meshes[i]->IsActive() && c_meshes[i]->GetMesh() != nullptr) { mesh_renderers.push_back(MeshRenderer(GetTransformComponent()->GetWorldTransform(), c_meshes[i], c_material)); } } } c_meshes.clear(); if (c_camera != nullptr) { if (!c_camera->FrustumIsHidden()) { Color frustum_color = Color(1.0f, 0.0f, 0.0f, 1.0f); cuboid_renderers.push_back(CuboidRenderer(c_camera->GetFrustumVertices(), frustum_color)); } } if (show_bounding_boxes) { obb.GetCornerPoints(obb_vertices); aabb.GetCornerPoints(aabb_vertices); Color obb_color = Color(1.0f, 1.0f, 0.0f, 1.0f); Color aabb_color = Color(0.0f, 1.0f, 0.0f, 1.0f); cuboid_renderers.push_back(CuboidRenderer(obb_vertices, obb_color)); cuboid_renderers.push_back(CuboidRenderer(aabb_vertices, aabb_color)); } } bool GameObject::SetParent(GameObject* new_parent) { bool success = true; if (new_parent == nullptr) { LOG("[ERROR] Game Objects: SetParent() operation failed! Error: New parent was nullptr."); return false; } if (new_parent->NewChildIsOwnParent(this)) { LOG("[ERROR] Game Objects: Cannot re-parent parents into their own children!"); return false; } if (parent != nullptr) { success = parent->DeleteChild(this); if (success) { GetTransformComponent()->SyncLocalToWorld(); //GetTransformComponent()->sync_local_to_global = true; } else { LOG("[ERROR] Game Objects: DeleteChild() operation failed! Error: Child could not be found in Parent."); return false; } } success = new_parent->AddChild(this); if (success) { parent = new_parent; } else { LOG("[ERROR] GameObjects: AddChild() operation failed! Error: Check for AddChild() errors in the Console Log"); if (parent != nullptr) { parent->AddChild(this); // Safety check to not lose the game object to the void. } // The GameObject will be reassigned as a child of the prev parent. } return success; } bool GameObject::AddChild(GameObject* child) { bool ret = true; if (child->is_master_root) { LOG("[ERROR] Game Objects: AddChild() operation failed! Error: %s is the master root object!", child->name.c_str()); return false; } if (!is_master_root && child->is_scene_root) { LOG("[ERROR] Game Objects: AddChild() operation failed! Error: %s is current scene root object!", child->name.c_str()); return false; } if (!is_master_root && !is_scene_root) { if (NewChildIsOwnParent(child)) { LOG("[ERROR] GameObjects: AddChild() operation failed! Error: Cannot re-parent parents into their own children!"); return false; } } /*if (child->parent != nullptr) { child->parent->DeleteChild(child); child->GetTransformComponent()->sync_local_to_global = true; } child->parent = this;*/ childs.push_back(child); return ret; } bool GameObject::NewChildIsOwnParent(GameObject* child) { bool ret = false; if (!child->HasChilds()) // If the child does not have any children, then it cannot be the parent of this object. { return false; } GameObject* parent_item = this->parent; // Will set the parent of this object as the starting point of the search. while (parent_item != nullptr && !parent_item->is_scene_root) // Iterate back up to the root object, as it is the parent of everything in the scene. (First check is TMP) { if (parent_item == child) // Child is the parent of one of the parent objects of this object (the one which called AddChild()) { ret = true; // A parent of this object that had the passed child as the parent has been found. break; } parent_item = parent_item->parent; // Setting the next parent GameObject to iterate. } // --- Adding a parent into a child /*for (uint i = 0; i < child->childs.size(); ++i) // Iterating all the childs of the child. { child->parent->AddChild(child->childs[i]); // Re-setting the parent of the childs to the parent of the passed child (root->GO->childs => root->childs->GO) } child->childs.clear();*/ return ret; } bool GameObject::DeleteChild(GameObject* child) { bool ret = false; for (uint i = 0; i < childs.size(); ++i) { if (childs[i] == child) { childs.erase(childs.begin() + i); ret = true; break; } } return ret; } bool GameObject::HasChilds() const { return !childs.empty(); } Component* GameObject::CreateComponent(COMPONENT_TYPE type) { Component* component = nullptr; bool check_for_duplicates = false; switch(type) { case COMPONENT_TYPE::TRANSFORM: component = new C_Transform(this); check_for_duplicates = true; break; case COMPONENT_TYPE::MESH: component = new C_Mesh(this); break; case COMPONENT_TYPE::MATERIAL: component = new C_Material(this); check_for_duplicates = true; break; case COMPONENT_TYPE::LIGHT: component = new C_Light(this); break; case COMPONENT_TYPE::CAMERA: component = new C_Camera(this); break; } if (component != nullptr) { if (check_for_duplicates) { for (uint i = 0; i < components.size(); ++i) { if (type == components[i]->GetType()) { LOG("[ERROR] %s Component could not be added to %s: No duplicates allowed!", component->GetNameFromType(), name.c_str()); RELEASE(component); return nullptr; } } } components.push_back(component); } return component; } bool GameObject::DeleteComponent(Component* component_to_delete) { switch (component_to_delete->GetType()) { case COMPONENT_TYPE::MESH: App->renderer->DeleteFromMeshRenderers((C_Mesh*)component_to_delete); show_bounding_boxes = false; break; } std::string component_name = component_to_delete->GetNameFromType(); if (component_to_delete != nullptr) { for (uint i = 0; i < components.size(); ++i) { if (components[i] == component_to_delete) { components[i]->CleanUp(); RELEASE(components[i]); components.erase(components.begin() + i); return true; } } } LOG("[STATUS] Deleted Component %s of Game Object %s", component_name.c_str(), name.c_str()); component_name.clear(); return false; } Component* GameObject::GetComponent(COMPONENT_TYPE type) { for (uint i = 0; i < components.size(); ++i) { if (components[i]->GetType() == type) { return components[i]; } } //LOG("[WARNING] Could not find %s Component in %s", GetComponentNameFromType(type), name.c_str()); return nullptr; } const char* GameObject::GetComponentNameFromType(COMPONENT_TYPE type) { switch (type) { case COMPONENT_TYPE::NONE: { return "None"; } break; case COMPONENT_TYPE::TRANSFORM: { return "Transform"; } break; case COMPONENT_TYPE::MESH: { return "Mesh"; } break; case COMPONENT_TYPE::MATERIAL: { return "Material"; } break; case COMPONENT_TYPE::LIGHT: { return "Light"; } break; } LOG("[ERROR] Could Not Get Component Name From Type"); return "Invalid Component Type"; } void GameObject::GetAllComponentsWithType(std::vector<Component*>& components_with_type, COMPONENT_TYPE type) { for (uint i = 0; i < components.size(); ++i) { if (components[i]->GetType() == type) { components_with_type.push_back(components[i]); } } } C_Transform* GameObject::GetTransformComponent() { return (C_Transform*)GetComponent(COMPONENT_TYPE::TRANSFORM); // The component is returned directly without any checks as the checks will be done in GetComponent(). } C_Mesh* GameObject::GetMeshComponent() { return (C_Mesh*)GetComponent(COMPONENT_TYPE::MESH); } C_Material* GameObject::GetMaterialComponent() { return (C_Material*)GetComponent(COMPONENT_TYPE::MATERIAL); } C_Light* GameObject::GetLightComponent() { return (C_Light*)GetComponent(COMPONENT_TYPE::LIGHT); } C_Camera* GameObject::GetCameraComponent() { return (C_Camera*)GetComponent(COMPONENT_TYPE::CAMERA); } void GameObject::GetAllMeshComponents(std::vector<C_Mesh*>& c_meshes) { for (uint i = 0; i < components.size(); ++i) { if (components[i]->GetType() == COMPONENT_TYPE::MESH) { c_meshes.push_back((C_Mesh*)components[i]); } } } uint32 GameObject::GetUID() const { return uid; } // --- GAME OBJECT GETTERS AND SETTERS --- const char* GameObject::GetName() const { return name.c_str(); } bool GameObject::IsActive() const { return is_active; } bool GameObject::IsStatic() const { return is_static; } void GameObject::ForceUID(const uint32& UID) { uid = UID; } void GameObject::SetName(const char* new_name) { name = new_name; } void GameObject::SetIsActive(const bool& set_to) { is_active = set_to; SetChildsIsActive(set_to, this); } void GameObject::SetIsStatic(const bool& set_to) { is_static = set_to; SetChildsIsStatic(set_to, this); } void GameObject::SetChildsIsActive(const bool& set_to, GameObject* parent) { if (parent != nullptr) { for (uint i = 0; i < parent->childs.size(); ++i) { parent->childs[i]->is_active = set_to; SetChildsIsActive(set_to, parent->childs[i]); } } } void GameObject::SetChildsIsStatic(const bool& set_to, GameObject* parent) { if (parent != nullptr) { for (uint i = 0; i < parent->childs.size(); ++i) { parent->childs[i]->is_static = set_to; SetChildsIsStatic(set_to, parent->childs[i]); } } } uint32 GameObject::GetParentUID() const { return parent_uid; }
22.556962
172
0.679885
xsiro
b87fa743a184093b4c1a360caae9643a5315827e
684
cpp
C++
src/noj_am/BOJ_5639.cpp
ginami0129g/my-problem-solving
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
1
2020-06-01T12:19:31.000Z
2020-06-01T12:19:31.000Z
src/noj_am/BOJ_5639.cpp
ginami0129g/my-study-history
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
23
2020-11-08T07:14:02.000Z
2021-02-11T11:16:00.000Z
src/noj_am/BOJ_5639.cpp
ginami0129g/my-problem-solving
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
null
null
null
#include <iostream> using namespace std; typedef struct Node { int data; Node *left = nullptr, *right = nullptr; } Node; int num; Node *root = nullptr; void insert(Node *&node, int data) { if (node == nullptr) { node = new Node; node->data = data; } else if (node->data < data) { insert(node->right, data); } else if (node->data > data) { insert(node->left, data); } } void postorder(Node *node) { if (node == nullptr) return; postorder(node->left); postorder(node->right); cout << node->data << '\n'; } int main(void) { cin.tie(NULL); ios_base::sync_with_stdio(false); while (cin >> num) { insert(root, num); } postorder(root); }
19
41
0.608187
ginami0129g
b8818760146488af0756d048cdc8e7bd7f6568ce
7,851
cpp
C++
Atomic/AtSmtpSender.cpp
denisbider/Atomic
8e8e979a6ef24d217a77f17fa81a4129f3506952
[ "MIT" ]
4
2019-11-10T21:56:40.000Z
2021-12-11T20:10:55.000Z
Atomic/AtSmtpSender.cpp
denisbider/Atomic
8e8e979a6ef24d217a77f17fa81a4129f3506952
[ "MIT" ]
null
null
null
Atomic/AtSmtpSender.cpp
denisbider/Atomic
8e8e979a6ef24d217a77f17fa81a4129f3506952
[ "MIT" ]
1
2019-11-11T08:38:59.000Z
2019-11-11T08:38:59.000Z
#include "AtIncludes.h" #include "AtSmtpSender.h" #include "AtInitOnFirstUse.h" #include "AtNumCvt.h" #include "AtSmtpSenderThread.h" #include "AtTime.h" #include "AtWait.h" namespace At { // SmtpSenderWorkItem SmtpSenderWorkItem::~SmtpSenderWorkItem() noexcept { if (m_memUsage.Any()) InterlockedExchangeAdd_PtrDiff(&m_memUsage->m_nrBytes, -(NumCast<ptrdiff>(m_content.n))); } ptrdiff SmtpSenderWorkItem::RegisterMemUsage(Rp<SmtpSenderMemUsage> const& memUsage) { EnsureThrow(!m_memUsage.Any()); m_memUsage = memUsage; ptrdiff const contentLen = NumCast<ptrdiff>(m_content.n); ptrdiff const v = InterlockedExchangeAdd_PtrDiff(&m_memUsage->m_nrBytes, contentLen); EnsureThrow(v >= 0); return v + contentLen; } // SmtpSender Rp<SmtpMsgToSend> SmtpSender::CreateMsg() { Rp<SmtpMsgToSend> msg = new SmtpMsgToSend(Entity::ChildOf, SmtpSender_GetStorageParent()); // This retry schedule is intended to cause messages sent toward the end of a business day to fail // (if they fail) by a time earlier in the next business day, giving time to look into the issue msg->f_futureRetryDelayMinutes.Add( 10U); // attempt 2 after 10 minutes msg->f_futureRetryDelayMinutes.Add( 15U); // attempt 3 after 25 minutes msg->f_futureRetryDelayMinutes.Add( 25U); // attempt 4 after 50 minutes msg->f_futureRetryDelayMinutes.Add( 35U); // attempt 5 after 85 minutes msg->f_futureRetryDelayMinutes.Add( 50U); // attempt 6 after 135 minutes msg->f_futureRetryDelayMinutes.Add( 75U); // attempt 7 after 210 minutes msg->f_futureRetryDelayMinutes.Add(115U); // attempt 8 after 325 minutes msg->f_futureRetryDelayMinutes.Add(170U); // attempt 9 after 495 minutes msg->f_futureRetryDelayMinutes.Add(215U); // attempt 10 after 710 minutes msg->f_futureRetryDelayMinutes.Add(215U); // attempt 11 after 925 minutes msg->f_futureRetryDelayMinutes.Add(215U); // attempt 12 after 1140 minutes = 19 hours total // totals assuming each attempt is short - it may not be // Common maximum email sizes range from 10 MB, most commonly 20 - 30 MB, up to 150 MB: // https://blog.mailtrap.io/email-size/#Limits_for_popular_email_sending_providers_and_clients_like_Gmail_Outlook_Sendgrid_etc // // The below allows up to 330 seconds to send a 30 MB message, with a minimum provisioned time of 90 seconds per message. msg->f_baseSendSecondsMax = 90; msg->f_nrBytesToAddOneSec = 128 * 1024; return msg; } bool SmtpSender::SendNextQueuedMessageNow() { Time nowPlusOne = Time::StrictNow(); ++nowPlusOne; Rp<SmtpMsgToSend> msgToSend; SmtpSender_GetStorageParent().FindChildren<SmtpMsgToSend>(nowPlusOne, nullptr, [&] (Rp<SmtpMsgToSend> const& msg) -> bool { if (msg->f_status == SmtpMsgStatus::NonFinal_Idle) { msgToSend = msg; return false; } return true; } ); if (!msgToSend.Any()) return false; msgToSend->f_nextAttemptTime = Time(); msgToSend->Update(); SignalTrigger(); return true; } void SmtpSender::SmtpSender_InTx_LoadMoreContent(SmtpMsgToSend const&, Enc&) { throw NotImplemented(); } void SmtpSender::WorkPool_Run() { m_memUsage = new SmtpSenderMemUsage; // Reset status on any messages that might be stuck in sending state from a previous run { RpVec<SmtpMsgToSend> msgsToReset; GetStore().RunTxExclusive( [&] () { SmtpSender_GetStorageParent().EnumAllChildrenOfKind<SmtpMsgToSend>( [&] (Rp<SmtpMsgToSend> const& msg) -> bool { if (msg->f_status == SmtpMsgStatus::NonFinal_Sending) msgsToReset.Add(msg); return true; } ); if (msgsToReset.Any()) { // Delay when we start resending messages from last run so that the admin has opportunity to take any emergency actions. // Don't start resending the messages all at once, but instead spread them out over a reasonable period of time. Time perMsgDelay = Time::FromMilliseconds(InitResumeSend_DefaultPerMsgDelayMs); sizet const nrDelays = msgsToReset.Len() - 1; Time const lastMsgDelay = perMsgDelay * nrDelays; Time const maxLastMsgDelay = Time::FromMinutes(InitResumeSend_MaxLastMsgDelayMins); if (nrDelays && lastMsgDelay > maxLastMsgDelay) perMsgDelay = maxLastMsgDelay / nrDelays; Time const now = Time::StrictNow(); Time nextMsgTime = now + Time::FromMinutes(InitResumeSend_DelayMins); for (Rp<SmtpMsgToSend> const& msg : msgsToReset) { msg->f_nextAttemptTime = nextMsgTime; msg->f_status = SmtpMsgStatus::NonFinal_Idle; msg->Update(); nextMsgTime += perMsgDelay; } } } ); SmtpSender_GetSendLog().SmtpSendLog_OnReset(msgsToReset); } // Pump messages while (true) { // Check for messages to send SmtpSenderCfg cfg { Entity::Contained }; SmtpSender_GetCfg(cfg); bool atMemUsageLimit {}; Time nextPumpTime; if (0 != cfg.f_memUsageLimitKb) { ptrdiff const curUsageBytes = InterlockedExchangeAdd_PtrDiff(&m_memUsage->m_nrBytes, 0); if (curUsageBytes >= SatMulConst<ptrdiff, 1024>(SatCast<ptrdiff>(cfg.f_memUsageLimitKb))) atMemUsageLimit = true; } if (!atMemUsageLimit) { AutoFreeVec<SmtpSenderWorkItem> workItems; GetStore().RunTx(GetStopCtl(), typeid(*this), [&] () { workItems.Clear(); nextPumpTime = Time::Max(); Time timeMin = Time::Min(); Time timeNow = Time::StrictNow(); Time timeNowPlusOne = timeNow; ++timeNowPlusOne; SmtpSender_GetStorageParent().FindChildren<SmtpMsgToSend>(timeMin, &timeNowPlusOne, [&] (Rp<SmtpMsgToSend> const& m) -> bool { if (m->f_status == SmtpMsgStatus::NonFinal_Idle) { SmtpSenderWorkItem* wi = new SmtpSenderWorkItem; AutoFree<SmtpSenderWorkItem> autoFreeWorkItem { wi }; workItems.Add(autoFreeWorkItem); wi->m_msg = m; wi->m_msg->f_status = SmtpMsgStatus::NonFinal_Sending; wi->m_msg->Update(); if (!wi->m_msg->f_moreContentContext.Any()) wi->m_content = wi->m_msg->f_contentPart1; else { wi->m_contentStorage = wi->m_msg->f_contentPart1; SmtpSender_InTx_LoadMoreContent(wi->m_msg.Ref(), wi->m_contentStorage); wi->m_content = wi->m_contentStorage; } LONG64 const curUsageBytes = wi->RegisterMemUsage(m_memUsage); if (0 != cfg.f_memUsageLimitKb) if (curUsageBytes >= SatMulConst<LONG64, 1024>(SatCast<LONG64>(cfg.f_memUsageLimitKb))) { atMemUsageLimit = true; return false; } } return true; } ); SmtpSender_GetStorageParent().FindChildren<SmtpMsgToSend>(timeNowPlusOne, nullptr, [&] (Rp<SmtpMsgToSend> const& m) -> bool { nextPumpTime = m->f_nextAttemptTime; return false; } ); } ); // Enqueue messages for (sizet i=0; i!=workItems.Len(); ++i) { AutoFree<SmtpSenderWorkItem> afwi; workItems.Extract(i, afwi); EnqueueWorkItem(afwi); } } // Wait for a trigger, stop signal, or next pump time DWORD waitMs = INFINITE; if (atMemUsageLimit) waitMs = AtMemUsageLimit_PumpDelayMs; else if (nextPumpTime != Time::Max()) waitMs = SatCast<DWORD>((nextPumpTime - Time::StrictNow()).ToMilliseconds()); if (Wait2(StopEvent().Handle(), m_pumpTrigger.Handle(), waitMs) == 0) break; } } BCrypt::Provider const& SmtpSender::GetMd5Provider() { InitOnFirstUse(&m_md5ProviderInitFlag, [this] { m_md5Provider.OpenMd5(); } ); return m_md5Provider; } }
32.17623
129
0.6631
denisbider
b881a48eb4f61d5017c5660c7fa55f42ae308d81
17,467
hpp
C++
Libraries/Mathter/Matrix/MatrixArithmetic.hpp
petiaccja/MathterBench
e47ad69447a3031c24ed06c51435c60593719b26
[ "Unlicense" ]
1
2020-05-26T22:08:29.000Z
2020-05-26T22:08:29.000Z
Libraries/Mathter/Matrix/MatrixArithmetic.hpp
petiaccja/MathterBench
e47ad69447a3031c24ed06c51435c60593719b26
[ "Unlicense" ]
null
null
null
Libraries/Mathter/Matrix/MatrixArithmetic.hpp
petiaccja/MathterBench
e47ad69447a3031c24ed06c51435c60593719b26
[ "Unlicense" ]
null
null
null
#pragma once #include "MatrixImpl.hpp" #include <utility> namespace mathter { //------------------------------------------------------------------------------ // Matrix-matrix multiplication //------------------------------------------------------------------------------ namespace impl { template <class T, class U, int Rows1, int Match, int Columns2, eMatrixOrder Order, bool Packed, int... MatchIndices> inline auto SmallProductRowRR(const Matrix<T, Rows1, Match, Order, eMatrixLayout::ROW_MAJOR, Packed>& lhs, const Matrix<U, Match, Columns2, Order, eMatrixLayout::ROW_MAJOR, Packed>& rhs, int row, std::integer_sequence<int, MatchIndices...>) { return (... + (rhs.stripes[MatchIndices] * lhs(row, MatchIndices))); } template <class T, class U, int Rows1, int Match, int Columns2, eMatrixOrder Order, bool Packed, int... RowIndices> inline auto SmallProductRR(const Matrix<T, Rows1, Match, Order, eMatrixLayout::ROW_MAJOR, Packed>& lhs, const Matrix<U, Match, Columns2, Order, eMatrixLayout::ROW_MAJOR, Packed>& rhs, std::integer_sequence<int, RowIndices...>) { using V = traits::MatMulElemT<T, U>; using ResultT = Matrix<V, Rows1, Columns2, Order, eMatrixLayout::ROW_MAJOR, Packed>; return ResultT{ ResultT::FromStripes, SmallProductRowRR(lhs, rhs, RowIndices, std::make_integer_sequence<int, Match>{})... }; } template <class T, class U, int Rows1, int Match, int Columns2, eMatrixOrder Order, eMatrixLayout Layout2, bool Packed, int... MatchIndices> inline auto SmallProductRowCC(const Matrix<T, Rows1, Match, Order, eMatrixLayout::COLUMN_MAJOR, Packed>& lhs, const Matrix<U, Match, Columns2, Order, Layout2, Packed>& rhs, int col, std::integer_sequence<int, MatchIndices...>) { return (... + (lhs.stripes[MatchIndices] * rhs(MatchIndices, col))); } template <class T, class U, int Rows1, int Match, int Columns2, eMatrixOrder Order, eMatrixLayout Layout2, bool Packed, int... ColIndices> inline auto SmallProductCC(const Matrix<T, Rows1, Match, Order, eMatrixLayout::COLUMN_MAJOR, Packed>& lhs, const Matrix<U, Match, Columns2, Order, Layout2, Packed>& rhs, std::integer_sequence<int, ColIndices...>) { using V = traits::MatMulElemT<T, U>; using ResultT = Matrix<V, Rows1, Columns2, Order, eMatrixLayout::COLUMN_MAJOR, Packed>; return ResultT{ ResultT::FromStripes, SmallProductRowCC(lhs, rhs, ColIndices, std::make_integer_sequence<int, Match>{})... }; } } // namespace impl template <class T, class U, int Rows1, int Match, int Columns2, eMatrixOrder Order, bool Packed> inline auto operator*(const Matrix<T, Rows1, Match, Order, eMatrixLayout::ROW_MAJOR, Packed>& lhs, const Matrix<U, Match, Columns2, Order, eMatrixLayout::ROW_MAJOR, Packed>& rhs) { #ifdef MATHTER_SSE2_HACK if constexpr (Rows1 == 2 && Match == 2 && Columns2 == 2 && std::is_same_v<T, float> && std::is_same_v<U, float>) { using V = traits::MatMulElemT<T, U>; using Vec4T = Vector<V, 4>; Vec4T lhsv; Vec4T rhsv; lhsv.simd.reg = _mm_loadu_ps(reinterpret_cast<const float*>(&lhs)); rhsv.simd.reg = _mm_loadu_ps(reinterpret_cast<const float*>(&rhs)); Vec4T resultv = Vec4T(lhsv.xxzz) * Vec4T(rhsv.xyxy) + Vec4T(lhsv.yyww) * Vec4T(rhsv.zwzw); Matrix<V, 2, 2, Order, eMatrixLayout::ROW_MAJOR, Packed> result; _mm_storeu_ps(reinterpret_cast<float*>(&result), resultv.simd.reg); return result; } #endif if constexpr (Rows1 <= 4 && Match <= 4 && Columns2 <= 4) { return impl::SmallProductRR(lhs, rhs, std::make_integer_sequence<int, Rows1>{}); } else { using V = traits::MatMulElemT<T, U>; Matrix<V, Rows1, Columns2, Order, eMatrixLayout::ROW_MAJOR, Packed> result; for (int i = 0; i < Rows1; ++i) { result.stripes[i] = rhs.stripes[0] * lhs(i, 0); } for (int i = 0; i < Rows1; ++i) { for (int j = 1; j < Match; ++j) { result.stripes[i] += rhs.stripes[j] * lhs(i, j); } } return result; } } template <class T, class U, int Rows1, int Match, int Columns2, eMatrixOrder Order1, eMatrixOrder Order2, bool Packed, class V> inline auto operator*(const Matrix<T, Rows1, Match, Order1, eMatrixLayout::ROW_MAJOR, Packed>& lhs, const Matrix<U, Match, Columns2, Order2, eMatrixLayout::COLUMN_MAJOR, Packed>& rhs) -> Matrix<V, Rows1, Columns2, Order1, eMatrixLayout::ROW_MAJOR, Packed> { Matrix<V, Rows1, Columns2, Order1, eMatrixLayout::ROW_MAJOR, Packed> result; for (int j = 0; j < Columns2; ++j) { for (int i = 0; i < Rows1; ++i) { result(i, j) = Dot(lhs.stripes[i], rhs.stripes[j]); } } return result; } template <class T, class U, int Rows1, int Match, int Columns2, eMatrixOrder Order, bool Packed> inline auto operator*(const Matrix<T, Rows1, Match, Order, eMatrixLayout::COLUMN_MAJOR, Packed>& lhs, const Matrix<U, Match, Columns2, Order, eMatrixLayout::COLUMN_MAJOR, Packed>& rhs) { if constexpr (Rows1 <= 4 && Match <= 4 && Columns2 <= 4) { return impl::SmallProductCC(lhs, rhs, std::make_integer_sequence<int, Columns2>{}); } else { using V = traits::MatMulElemT<T, U>; Matrix<V, Rows1, Columns2, Order, eMatrixLayout::COLUMN_MAJOR, Packed> result; for (int j = 0; j < Columns2; ++j) { result.stripes[j] = lhs.stripes[0] * rhs(0, j); } for (int i = 1; i < Match; ++i) { for (int j = 0; j < Columns2; ++j) { result.stripes[j] += lhs.stripes[i] * rhs(i, j); } } return result; } } template <class T, class U, int Rows1, int Match, int Columns2, eMatrixOrder Order, bool Packed> inline auto operator*(const Matrix<T, Rows1, Match, Order, eMatrixLayout::COLUMN_MAJOR, Packed>& lhs, const Matrix<U, Match, Columns2, Order, eMatrixLayout::ROW_MAJOR, Packed>& rhs) { // CC algorithm is completely fine for COL_MAJOR x ROW_MAJOR. // See that rhs is only indexed per-element, so its layout does not matter. if constexpr (Rows1 <= 4 && Match <= 4 && Columns2 <= 4) { return impl::SmallProductCC(lhs, rhs, std::make_integer_sequence<int, Columns2>{}); } else { using V = traits::MatMulElemT<T, U>; Matrix<V, Rows1, Columns2, Order, eMatrixLayout::COLUMN_MAJOR, Packed> result; for (int j = 0; j < Columns2; ++j) { result.stripes[j] = lhs.stripes[0] * rhs(0, j); } for (int i = 1; i < Match; ++i) { for (int j = 0; j < Columns2; ++j) { result.stripes[j] += lhs.stripes[i] * rhs(i, j); } } return result; } } // Assign-multiply template <class T1, class T2, int Dim, eMatrixOrder Order, eMatrixLayout Layout1, eMatrixLayout Layout2, bool Packed> inline Matrix<T1, Dim, Dim, Order, Layout1, Packed>& operator*=(Matrix<T1, Dim, Dim, Order, Layout1, Packed>& lhs, const Matrix<T2, Dim, Dim, Order, Layout2, Packed>& rhs) { lhs = lhs * rhs; return lhs; } //------------------------------------------------------------------------------ // Matrix-matrix addition & subtraction //------------------------------------------------------------------------------ namespace impl { template <class T, class U, int Rows, int Columns, eMatrixOrder Order, eMatrixLayout SameLayout, bool Packed, int... StripeIndices> inline auto SmallAdd(const Matrix<T, Rows, Columns, Order, SameLayout, Packed>& lhs, const Matrix<U, Rows, Columns, Order, SameLayout, Packed>& rhs, std::integer_sequence<int, StripeIndices...>) { using V = traits::MatMulElemT<T, U>; using ResultT = Matrix<V, Rows, Columns, Order, SameLayout, Packed>; return ResultT{ ResultT::FromStripes, (lhs.stripes[StripeIndices] + rhs.stripes[StripeIndices])... }; } template <class T, class U, int Rows, int Columns, eMatrixOrder Order, eMatrixLayout SameLayout, bool Packed, int... StripeIndices> inline auto SmallSub(const Matrix<T, Rows, Columns, Order, SameLayout, Packed>& lhs, const Matrix<U, Rows, Columns, Order, SameLayout, Packed>& rhs, std::integer_sequence<int, StripeIndices...>) { using V = traits::MatMulElemT<T, U>; using ResultT = Matrix<V, Rows, Columns, Order, SameLayout, Packed>; return ResultT{ ResultT::FromStripes, (lhs.stripes[StripeIndices] - rhs.stripes[StripeIndices])... }; } } // namespace impl // Same layout template <class T, class U, int Rows, int Columns, eMatrixOrder Order, eMatrixLayout SameLayout, bool Packed> inline auto operator+(const Matrix<T, Rows, Columns, Order, SameLayout, Packed>& lhs, const Matrix<U, Rows, Columns, Order, SameLayout, Packed>& rhs) { using V = traits::MatMulElemT<T, U>; if constexpr (Rows * Columns == 4) { Matrix<V, Rows, Columns, Order, SameLayout, Packed> result; for (int i = 0; i < result.RowCount(); ++i) { for (int j = 0; j < result.ColumnCount(); ++j) { result(i, j) = lhs(i, j) + rhs(i, j); } } return result; } else if constexpr (Rows <= 4 && Columns <= 4) { return impl::SmallAdd(lhs, rhs, std::make_integer_sequence<int, lhs.StripeCount>{}); } else { Matrix<V, Rows, Columns, Order, SameLayout, Packed> result; for (int i = 0; i < result.StripeCount; ++i) { result.stripes[i] = lhs.stripes[i] + rhs.stripes[i]; } return result; } } template <class T, class U, int Rows, int Columns, eMatrixOrder Order, eMatrixLayout SameLayout, bool Packed> inline auto operator-(const Matrix<T, Rows, Columns, Order, SameLayout, Packed>& lhs, const Matrix<U, Rows, Columns, Order, SameLayout, Packed>& rhs) { using VectorAccelerator = Vector<T, 4, false>; using V = traits::MatMulElemT<T, U>; if constexpr (Rows * Columns == 4) { Matrix<V, Rows, Columns, Order, SameLayout, Packed> result; for (int i = 0; i < result.RowCount(); ++i) { for (int j = 0; j < result.ColumnCount(); ++j) { result(i, j) = lhs(i, j) - rhs(i, j); } } return result; } else if constexpr (Rows <= 4 && Columns <= 4) { return impl::SmallSub(lhs, rhs, std::make_integer_sequence<int, lhs.StripeCount>{}); } else { Matrix<V, Rows, Columns, Order, SameLayout, Packed> result; for (int i = 0; i < result.StripeCount; ++i) { result.stripes[i] = lhs.stripes[i] - rhs.stripes[i]; } return result; } } // Add & sub opposite layout template <class T, class U, int Rows, int Columns, eMatrixOrder Order1, eMatrixOrder Order2, eMatrixLayout Layout1, eMatrixLayout Layout2, bool Packed, class V, class = typename std::enable_if<Layout1 != Layout2>::type> inline auto operator+(const Matrix<T, Rows, Columns, Order1, Layout1, Packed>& lhs, const Matrix<U, Rows, Columns, Order2, Layout2, Packed>& rhs) { using V = traits::MatMulElemT<T, U>; Matrix<V, Rows, Columns, Order1, Layout1, Packed> result; for (int i = 0; i < result.RowCount(); ++i) { for (int j = 0; j < result.ColumnCount(); ++j) { result(i, j) = lhs(i, j) + rhs(i, j); } } return result; } template <class T, class U, int Rows, int Columns, eMatrixOrder Order1, eMatrixOrder Order2, eMatrixLayout Layout1, eMatrixLayout Layout2, bool Packed, class V, class = typename std::enable_if<Layout1 != Layout2>::type> inline auto operator-(const Matrix<T, Rows, Columns, Order1, Layout1, Packed>& lhs, const Matrix<U, Rows, Columns, Order2, Layout2, Packed>& rhs) { using V = traits::MatMulElemT<T, U>; Matrix<V, Rows, Columns, Order1, Layout1, Packed> result; for (int i = 0; i < result.RowCount(); ++i) { for (int j = 0; j < result.ColumnCount(); ++j) { result(i, j) = lhs(i, j) - rhs(i, j); } } return result; } /// <summary> Performs matrix addition and stores result in this. </summary> template <class T, class U, int Rows, int Columns, eMatrixOrder Order1, eMatrixOrder Order2, eMatrixLayout Layout1, eMatrixLayout Layout2, bool Packed> inline Matrix<U, Rows, Columns, Order1, Layout1, Packed>& operator+=( Matrix<T, Rows, Columns, Order1, Layout1, Packed>& lhs, const Matrix<U, Rows, Columns, Order2, Layout2, Packed>& rhs) { lhs = lhs + rhs; return lhs; } /// <summary> Performs matrix subtraction and stores result in this. </summary> template <class T, class U, int Rows, int Columns, eMatrixOrder Order1, eMatrixOrder Order2, eMatrixLayout Layout1, eMatrixLayout Layout2, bool Packed> inline Matrix<U, Rows, Columns, Order1, Layout1, Packed>& operator-=( Matrix<T, Rows, Columns, Order1, Layout1, Packed>& lhs, const Matrix<U, Rows, Columns, Order2, Layout2, Packed>& rhs) { lhs = lhs - rhs; return lhs; } //------------------------------------------------------------------------------ // Matrix-Scalar arithmetic //------------------------------------------------------------------------------ // Scalar multiplication /// <summary> Multiplies all elements of the matrix by scalar. </summary> template <class T, int Rows, int Columns, eMatrixOrder Order, eMatrixLayout Layout, bool Packed, class U> inline Matrix<T, Rows, Columns, Order, Layout, Packed>& operator*=(Matrix<T, Rows, Columns, Order, Layout, Packed>& mat, U s) { for (auto& stripe : mat.stripes) { stripe *= s; } return mat; } /// <summary> Divides all elements of the matrix by scalar. </summary> template <class T, int Rows, int Columns, eMatrixOrder Order, eMatrixLayout Layout, bool Packed, class U> inline Matrix<T, Rows, Columns, Order, Layout, Packed>& operator/=(Matrix<T, Rows, Columns, Order, Layout, Packed>& mat, U s) { mat *= U(1) / s; return mat; } template <class T, int Rows, int Columns, eMatrixOrder Order, eMatrixLayout Layout, bool Packed, class U> Matrix<T, Rows, Columns, Order, Layout, Packed> operator*(const Matrix<T, Rows, Columns, Order, Layout, Packed>& mat, U s) { Matrix<T, Rows, Columns, Order, Layout, Packed> copy(mat); copy *= s; return copy; } template <class T, int Rows, int Columns, eMatrixOrder Order, eMatrixLayout Layout, bool Packed, class U> Matrix<T, Rows, Columns, Order, Layout, Packed> operator/(const Matrix<T, Rows, Columns, Order, Layout, Packed>& mat, U s) { Matrix<T, Rows, Columns, Order, Layout, Packed> copy(mat); copy /= s; return copy; } template <class T, int Rows, int Columns, eMatrixOrder Order, eMatrixLayout Layout, bool Packed, class U> Matrix<T, Rows, Columns, Order, Layout, Packed> operator*(U s, const Matrix<T, Rows, Columns, Order, Layout, Packed>& mat) { return mat * s; } template <class T, int Rows, int Columns, eMatrixOrder Order, eMatrixLayout Layout, bool Packed, class U> Matrix<T, Rows, Columns, Order, Layout, Packed> operator/(U s, const Matrix<T, Rows, Columns, Order, Layout, Packed>& mat) { return mat / s; } //------------------------------------------------------------------------------ // Elementwise multiply and divide //------------------------------------------------------------------------------ template <class T, class T2, int Rows, int Columns, eMatrixOrder Order, eMatrixOrder Order2, eMatrixLayout Layout, bool Packed> auto MulElementwise(const Matrix<T, Rows, Columns, Order, Layout, Packed>& lhs, const Matrix<T2, Rows, Columns, Order2, Layout, Packed>& rhs) { Matrix<T, Rows, Columns, Order, Layout, Packed> result; for (int i = 0; i < result.StripeCount; ++i) { result.stripes[i] = lhs.stripes[i] * rhs.stripes[i]; } return result; } template <class T, class T2, int Rows, int Columns, eMatrixOrder Order, eMatrixOrder Order2, eMatrixLayout Layout, bool Packed> auto MulElementwise(const Matrix<T, Rows, Columns, Order, Layout, Packed>& lhs, const Matrix<T2, Rows, Columns, Order2, traits::OppositeLayout<Layout>::value, Packed>& rhs) { Matrix<T, Rows, Columns, Order, Layout, Packed> result; for (int i = 0; i < Rows; ++i) { for (int j = 0; j < Columns; ++j) { result(i, j) = lhs(i, j) * rhs(i, j); } } return result; } template <class T, class T2, int Rows, int Columns, eMatrixOrder Order, eMatrixOrder Order2, eMatrixLayout Layout, bool Packed> auto DivElementwise(const Matrix<T, Rows, Columns, Order, Layout, Packed>& lhs, const Matrix<T2, Rows, Columns, Order2, Layout, Packed>& rhs) { Matrix<T, Rows, Columns, Order, Layout, Packed> result; for (int i = 0; i < result.StripeCount; ++i) { result.stripes[i] = lhs.stripes[i] / rhs.stripes[i]; } return result; } template <class T, class T2, int Rows, int Columns, eMatrixOrder Order, eMatrixOrder Order2, eMatrixLayout Layout, bool Packed> auto DivElementwise(const Matrix<T, Rows, Columns, Order, Layout, Packed>& lhs, const Matrix<T2, Rows, Columns, Order2, traits::OppositeLayout<Layout>::value, Packed>& rhs) { Matrix<T, Rows, Columns, Order, Layout, Packed> result; for (int i = 0; i < Rows; ++i) { for (int j = 0; j < Columns; ++j) { result(i, j) = lhs(i, j) / rhs(i, j); } } return result; } //------------------------------------------------------------------------------ // Unary signs //------------------------------------------------------------------------------ template <class T, int Rows, int Columns, eMatrixOrder Order, eMatrixLayout Layout, bool Packed> auto operator+(const Matrix<T, Rows, Columns, Order, Layout, Packed>& mat) { return Matrix<T, Rows, Columns, Order, Layout, Packed>(mat); } template <class T, int Rows, int Columns, eMatrixOrder Order, eMatrixLayout Layout, bool Packed> auto operator-(const Matrix<T, Rows, Columns, Order, Layout, Packed>& mat) { return Matrix<T, Rows, Columns, Order, Layout, Packed>(mat) * T(-1); } } // namespace mathter
45.018041
220
0.640236
petiaccja
b8849bc28ba843753b3453fce59ab2d978be1486
4,044
hpp
C++
external/boost_1_60_0/qsboost/fusion/container/generation/detail/pp_make_vector.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
1
2019-06-27T17:54:13.000Z
2019-06-27T17:54:13.000Z
external/boost_1_60_0/qsboost/fusion/container/generation/detail/pp_make_vector.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
external/boost_1_60_0/qsboost/fusion/container/generation/detail/pp_make_vector.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef QSBOOST_PP_IS_ITERATING #if !defined(FUSION_MAKE_VECTOR_07162005_0243) #define FUSION_MAKE_VECTOR_07162005_0243 #include <qsboost/preprocessor/iterate.hpp> #include <qsboost/preprocessor/repetition/enum_params.hpp> #include <qsboost/preprocessor/repetition/enum_binary_params.hpp> #include <qsboost/preprocessor/repetition/enum_params_with_a_default.hpp> #include <qsboost/preprocessor/repetition/repeat_from_to.hpp> #include <qsboost/fusion/container/vector/vector.hpp> #include <qsboost/fusion/support/detail/as_fusion_element.hpp> #if !defined(QSBOOST_FUSION_DONT_USE_PREPROCESSED_FILES) #include <qsboost/fusion/container/generation/detail/preprocessed/make_vector.hpp> #else #if defined(__WAVE__) && defined(QSBOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 2, line: 0, output: "preprocessed/make_vector" FUSION_MAX_VECTOR_SIZE_STR".hpp") #endif /*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) This is an auto-generated file. Do not edit! ==============================================================================*/ #if defined(__WAVE__) && defined(QSBOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 1) #endif namespace qsboost { namespace fusion { struct void_; namespace result_of { template < QSBOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT( FUSION_MAX_VECTOR_SIZE, typename T, void_) , typename Extra = void_ > struct make_vector; template <> struct make_vector<> { typedef vector0<> type; }; } QSBOOST_CONSTEXPR QSBOOST_FUSION_GPU_ENABLED inline vector0<> make_vector() { return vector0<>(); } #define QSBOOST_FUSION_AS_FUSION_ELEMENT(z, n, data) \ typename detail::as_fusion_element<QSBOOST_PP_CAT(T, n)>::type #define QSBOOST_PP_FILENAME_1 <qsboost/fusion/container/generation/detail/pp_make_vector.hpp> #define QSBOOST_PP_ITERATION_LIMITS (1, FUSION_MAX_VECTOR_SIZE) #include QSBOOST_PP_ITERATE() #undef QSBOOST_FUSION_AS_FUSION_ELEMENT }} #if defined(__WAVE__) && defined(QSBOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(output: null) #endif #endif // BOOST_FUSION_DONT_USE_PREPROCESSED_FILES #endif #else // defined(BOOST_PP_IS_ITERATING) /////////////////////////////////////////////////////////////////////////////// // // Preprocessor vertical repetition code // /////////////////////////////////////////////////////////////////////////////// #define N QSBOOST_PP_ITERATION() namespace result_of { template <QSBOOST_PP_ENUM_PARAMS(N, typename T)> #define TEXT(z, n, text) , text struct make_vector< QSBOOST_PP_ENUM_PARAMS(N, T) QSBOOST_PP_REPEAT_FROM_TO(QSBOOST_PP_DEC(N), FUSION_MAX_VECTOR_SIZE, TEXT, void_) > #undef TEXT { typedef QSBOOST_PP_CAT(vector, N)<QSBOOST_PP_ENUM(N, QSBOOST_FUSION_AS_FUSION_ELEMENT, _)> type; }; } template <QSBOOST_PP_ENUM_PARAMS(N, typename T)> QSBOOST_CONSTEXPR QSBOOST_FUSION_GPU_ENABLED inline QSBOOST_PP_CAT(vector, N)<QSBOOST_PP_ENUM(N, QSBOOST_FUSION_AS_FUSION_ELEMENT, _)> make_vector(QSBOOST_PP_ENUM_BINARY_PARAMS(N, T, const& arg)) { return QSBOOST_PP_CAT(vector, N)<QSBOOST_PP_ENUM(N, QSBOOST_FUSION_AS_FUSION_ELEMENT, _)>( QSBOOST_PP_ENUM_PARAMS(N, arg)); } #undef N #endif // defined(BOOST_PP_IS_ITERATING)
34.862069
140
0.651583
wouterboomsma
b8854804dd7da7c7ba0eeecca6c439213a016c57
489
hpp
C++
libs/font/include/sge/font/object_unique_ptr.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/font/include/sge/font/object_unique_ptr.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/font/include/sge/font/object_unique_ptr.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_FONT_OBJECT_UNIQUE_PTR_HPP_INCLUDED #define SGE_FONT_OBJECT_UNIQUE_PTR_HPP_INCLUDED #include <sge/font/object_fwd.hpp> #include <fcppt/unique_ptr_impl.hpp> namespace sge::font { using object_unique_ptr = fcppt::unique_ptr<sge::font::object>; } #endif
24.45
63
0.750511
cpreh
b886af39809c5eff327b66dccde51a9943335b9c
513
cpp
C++
chapter-01/sumI.cpp
zyzisyz/DataStructure
0856f1f1eccad90aadbb8e0c205bdc932d367d72
[ "Apache-2.0" ]
null
null
null
chapter-01/sumI.cpp
zyzisyz/DataStructure
0856f1f1eccad90aadbb8e0c205bdc932d367d72
[ "Apache-2.0" ]
null
null
null
chapter-01/sumI.cpp
zyzisyz/DataStructure
0856f1f1eccad90aadbb8e0c205bdc932d367d72
[ "Apache-2.0" ]
null
null
null
/********************************** * filename: sumI * author: Yang Zhang * e-mail: zyziszy@foxmail.com * time: 2018-10-15 ***********************************/ #include <iostream> using namespace std; //计算给定n个整数的总和 //时间复杂度为O(n) int sumI(int A[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += A[i]; return sum; } //test function int main(void) { int A[] = {1, 2, 3, 4, 5}; cout << "Sum:" << sumI(A, 5) << endl; //for windows test system("pause"); return 0; }
16.548387
41
0.467836
zyzisyz
b889e6e8d801bc587942fc5623ddd86b9b34c971
84
cpp
C++
Engine/src/EnginePCH.cpp
jpvanoosten/VolumeTiledForwardShading
daf27632cb173c05faace6db0b72a74ae0fe216c
[ "MIT" ]
70
2017-11-12T08:25:47.000Z
2022-03-10T03:16:06.000Z
Engine/src/EnginePCH.cpp
jpvanoosten/VolumeTiledForwardShading
daf27632cb173c05faace6db0b72a74ae0fe216c
[ "MIT" ]
null
null
null
Engine/src/EnginePCH.cpp
jpvanoosten/VolumeTiledForwardShading
daf27632cb173c05faace6db0b72a74ae0fe216c
[ "MIT" ]
11
2017-12-18T12:42:32.000Z
2022-02-04T08:19:53.000Z
#include <EnginePCH.h> // Reference any static headers in EnginePCH.h and not here.
28
60
0.761905
jpvanoosten
b88a78cadaa1ab34d1402c0b0b430a81ff6b0c02
52
hpp
C++
src/boost_thread_pthread_recursive_mutex.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_thread_pthread_recursive_mutex.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_thread_pthread_recursive_mutex.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/thread/pthread/recursive_mutex.hpp>
26
51
0.826923
miathedev
b88cf523dcbbfe994d064afeac09aac9a6ab97d0
2,537
cpp
C++
src/caffe/layers/cudnn_relu_layer.cpp
superxuang/caffe_3d_faster_rcnn
5a18ab92997885f4b6033ed1f1b9ba907b1e2609
[ "BSD-2-Clause" ]
38
2018-07-30T07:53:56.000Z
2022-02-23T13:57:49.000Z
src/caffe/layers/cudnn_relu_layer.cpp
superxuang/caffe_triple-branch_FCN
e6b3ce2969dc95c55c25921194b93b05513f09ef
[ "MIT" ]
22
2018-07-12T03:33:35.000Z
2021-09-07T16:29:41.000Z
src/caffe/layers/cudnn_relu_layer.cpp
Wangdali-jpg/caffe_3d_faster_rcnn
5a18ab92997885f4b6033ed1f1b9ba907b1e2609
[ "BSD-2-Clause" ]
20
2019-01-01T07:33:56.000Z
2021-09-17T12:50:17.000Z
#ifdef USE_CUDNN #include <vector> #include "caffe/layers/cudnn_relu_layer.hpp" namespace caffe { template <typename Dtype> void CuDNNReLULayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { ReLULayer<Dtype>::LayerSetUp(bottom, top); // initialize cuDNN CUDNN_CHECK(cudnnCreate(&handle_)); cudnn::createTensor4dDesc<Dtype>(&bottom_desc_); cudnn::createTensor4dDesc<Dtype>(&top_desc_); cudnn::createActivationDescriptor<Dtype>(&activ_desc_, CUDNN_ACTIVATION_RELU); handles_setup_ = true; } template <typename Dtype> void CuDNNReLULayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { ReLULayer<Dtype>::Reshape(bottom, top); const int bottom_dim = bottom[0]->num_axes() < 4 ? 4 : bottom[0]->num_axes(); int* bottom_shape = new int[bottom_dim]; for (int i = 0; i < bottom_dim; ++i) { bottom_shape[i] = 1; } for (int i = 0; i < bottom[0]->num_axes(); ++i) { bottom_shape[i] = bottom[0]->shape(i); } int* bottom_stride = new int[bottom_dim]; bottom_stride[bottom_dim - 1] = 1; for (int i = bottom_dim - 2; i >= 0; --i) { bottom_stride[i] = bottom_shape[i + 1] * bottom_stride[i + 1]; } if (bottom_dim > 4) { cudnn::setTensorNdDesc<Dtype>(&bottom_desc_, bottom_dim, bottom_shape, bottom_stride); } else { cudnn::setTensor4dDesc<Dtype>(&bottom_desc_, bottom_shape[0], bottom_shape[1], bottom_shape[2], bottom_shape[3]); } delete[]bottom_shape; delete[]bottom_stride; const int top_dim = top[0]->num_axes() < 4 ? 4 : top[0]->num_axes(); int* top_shape = new int[top_dim]; for (int i = 0; i < top_dim; ++i) { top_shape[i] = 1; } for (int i = 0; i < top[0]->num_axes(); ++i) { top_shape[i] = top[0]->shape(i); } int* top_stride = new int[top_dim]; top_stride[top_dim - 1] = 1; for (int i = top_dim - 2; i >= 0; --i) { top_stride[i] = top_shape[i + 1] * top_stride[i + 1]; } if (top_dim > 4) { cudnn::setTensorNdDesc<Dtype>(&top_desc_, top_dim, top_shape, top_stride); } else { cudnn::setTensor4dDesc<Dtype>(&top_desc_, top_shape[0], top_shape[1], top_shape[2], top_shape[3]); } delete[]top_shape; delete[]top_stride; } template <typename Dtype> CuDNNReLULayer<Dtype>::~CuDNNReLULayer() { // Check that handles have been setup before destroying. if (!handles_setup_) { return; } cudnnDestroyTensorDescriptor(this->bottom_desc_); cudnnDestroyTensorDescriptor(this->top_desc_); cudnnDestroy(this->handle_); } INSTANTIATE_CLASS(CuDNNReLULayer); } // namespace caffe #endif
27.576087
115
0.687426
superxuang
b88cfb16af59bd62fe67211318f1d7b45f444767
10,437
cpp
C++
code/components/citizen-server-impl/src/state/ServerRPC.cpp
R0JEA/fivem
a61a3d501d4c06e5f3f9d65b0ef33e52d4ccd50e
[ "MIT" ]
null
null
null
code/components/citizen-server-impl/src/state/ServerRPC.cpp
R0JEA/fivem
a61a3d501d4c06e5f3f9d65b0ef33e52d4ccd50e
[ "MIT" ]
null
null
null
code/components/citizen-server-impl/src/state/ServerRPC.cpp
R0JEA/fivem
a61a3d501d4c06e5f3f9d65b0ef33e52d4ccd50e
[ "MIT" ]
null
null
null
#include "StdInc.h" #include <ScriptEngine.h> #include <ServerInstanceBase.h> #include <NetBuffer.h> #include <ClientRegistry.h> #include <GameServer.h> #include <state/ServerGameState.h> #include <Resource.h> #include <ResourceManager.h> #include <fxScripting.h> #include <RpcConfiguration.h> #include <CoreConsole.h> #define GLM_ENABLE_EXPERIMENTAL // TODO: clang style defines/checking #if defined(_M_IX86) || defined(_M_AMD64) #define GLM_FORCE_DEFAULT_ALIGNED_GENTYPES #define GLM_FORCE_SSE2 #define GLM_FORCE_SSE3 #endif #include <glm/vec3.hpp> #include <glm/gtx/norm.hpp> struct EntityCreationState { // TODO: allow resending in case the target client disappears uint16_t creationToken; uint32_t clientIdx; fx::ScriptGuid* scriptGuid; }; static tbb::concurrent_unordered_map<uint16_t, EntityCreationState> g_entityCreationList; static std::atomic<uint16_t> g_creationToken; inline uint32_t MakeEntityHandle(uint8_t playerId, uint16_t objectId) { return ((playerId + 1) << 16) | objectId; } namespace fx { glm::vec3 GetPlayerFocusPos(const std::shared_ptr<sync::SyncEntityState>& entity); } static InitFunction initFunction([]() { fx::ServerInstanceBase::OnServerCreate.Connect([](fx::ServerInstanceBase* ref) { auto rpcConfiguration = RpcConfiguration::Load("citizen:/scripting/rpc_natives.json"); if (!rpcConfiguration) { console::PrintWarning("server", "Could not load rpc_natives.json. Is the server running from the correct directory, and is citizen_dir set?\n"); return; } auto clientRegistry = ref->GetComponent<fx::ClientRegistry>(); auto gameState = ref->GetComponent<fx::ServerGameState>(); auto gameServer = ref->GetComponent<fx::GameServer>(); gameServer->GetComponent<fx::HandlerMapComponent>()->Add(HashRageString("msgEntityCreate"), [=](const std::shared_ptr<fx::Client>& client, net::Buffer& buffer) { auto creationToken = buffer.Read<uint16_t>(); auto objectId = buffer.Read<uint16_t>(); auto it = g_entityCreationList.find(creationToken); if (it != g_entityCreationList.end()) { auto guid = it->second.scriptGuid; if (guid->type == fx::ScriptGuid::Type::TempEntity) { guid->type = fx::ScriptGuid::Type::Entity; guid->entity.handle = MakeEntityHandle(0, objectId); // broadcast entity creation net::Buffer outBuffer; outBuffer.Write<uint32_t>(HashRageString("msgRpcEntityCreation")); outBuffer.Write<uint16_t>(creationToken); outBuffer.Write<uint16_t>(objectId); clientRegistry->ForAllClients([&](const std::shared_ptr<fx::Client>& cl) { cl->SendPacket(0, outBuffer, NetPacketType_ReliableReplayed); }); } g_entityCreationList[creationToken] = {}; } }); for (auto& native : rpcConfiguration->GetNatives()) { fx::ScriptEngine::RegisterNativeHandler(native->GetName(), [=](fx::ScriptContext& ctx) { int clientIdx = -1; if (native->GetRpcType() == RpcConfiguration::RpcType::EntityContext) { // ascertain the client that is the context int ctxIdx = native->GetContextIndex(); switch (native->GetContextType()) { case RpcConfiguration::ArgumentType::Player: { clientIdx = ctx.GetArgument<int>(ctxIdx); break; } case RpcConfiguration::ArgumentType::Entity: { int cxtEntity = ctx.GetArgument<int>(ctxIdx); if (cxtEntity < 0x20000) { auto client = clientRegistry->GetClientByNetID(cxtEntity); if (client) { cxtEntity = std::any_cast<uint32_t>(client->GetData("playerEntity")); } } fx::ScriptGuid* scriptGuid = g_scriptHandlePool->AtHandle(cxtEntity - 0x20000); if (scriptGuid) { if (scriptGuid->type == fx::ScriptGuid::Type::Entity) { // look up the entity owner auto entity = gameState->GetEntity(cxtEntity); if (entity) { clientIdx = entity->client.lock()->GetNetId(); } } else if (scriptGuid->type == fx::ScriptGuid::Type::TempEntity) { auto it = g_entityCreationList.find(scriptGuid->tempEntity.creationToken); if (it != g_entityCreationList.end()) { clientIdx = it->second.clientIdx; } } } break; } } } else if (native->GetRpcType() == RpcConfiguration::RpcType::EntityCreate) { // 3 floats next to one another = pos int flts = 0; int startIdx = 0; int idx = 0; bool found = false; for (auto& argument : native->GetArguments()) { if (argument.GetType() == RpcConfiguration::ArgumentType::Float) { flts++; if (flts == 1) { startIdx = idx; } else if (flts == 3) { found = true; break; } } else { flts = 0; } idx++; } // if no pos-style argument, route to first client we find if (!found) { clientRegistry->ForAllClients([&](const std::shared_ptr<fx::Client>& client) { if (clientIdx != -1) { return; } if (client->GetData("playerEntity").has_value()) { clientIdx = client->GetNetId(); } }); } else { // route to a nearby candidate std::vector<std::tuple<float, std::shared_ptr<fx::Client>>> candidates; glm::vec3 pos{ ctx.GetArgument<float>(startIdx), ctx.GetArgument<float>(startIdx + 1), ctx.GetArgument<float>(startIdx + 2) }; clientRegistry->ForAllClients([&candidates, gameState, pos](const std::shared_ptr<fx::Client>& tgtClient) { if (tgtClient->GetSlotId() == 0xFFFFFFFF) { return; } float distance = std::numeric_limits<float>::max(); try { std::weak_ptr<fx::sync::SyncEntityState> entityRef; { auto [data, lock] = gameState->ExternalGetClientData(tgtClient); entityRef = data->playerEntity; } auto playerEntity = entityRef.lock(); if (playerEntity) { auto tgt = fx::GetPlayerFocusPos(playerEntity); distance = glm::distance2(tgt, pos); } } catch (std::bad_any_cast&) { } candidates.emplace_back(distance, tgtClient); }); std::sort(candidates.begin(), candidates.end()); if (candidates.size() == 0) { return; } clientIdx = std::get<1>(candidates[0])->GetNetId(); } } uint32_t resourceHash = -1; fx::OMPtr<IScriptRuntime> runtime; if (FX_SUCCEEDED(fx::GetCurrentScriptRuntime(&runtime))) { fx::Resource* resource = reinterpret_cast<fx::Resource*>(runtime->GetParentObject()); if (resource) { resourceHash = HashString(resource->GetName().c_str()); } } // build an RPC packet net::Buffer buffer; buffer.Write<uint32_t>(HashRageString("msgRpcNative")); buffer.Write<uint64_t>(native->GetGameHash()); buffer.Write<uint32_t>(resourceHash); uint16_t creationToken = 0; if (native->GetRpcType() == RpcConfiguration::RpcType::EntityCreate) { creationToken = ++g_creationToken; buffer.Write<uint16_t>(creationToken); } int i = 0; for (auto& argument : native->GetArguments()) { switch (argument.GetType()) { case RpcConfiguration::ArgumentType::Entity: { int cxtEntity = ctx.GetArgument<int>(i); int entityHandle; if (cxtEntity < 0x20000) { auto client = clientRegistry->GetClientByNetID(cxtEntity); if (client) { cxtEntity = std::any_cast<uint32_t>(client->GetData("playerEntity")); } } fx::ScriptGuid* scriptGuid = g_scriptHandlePool->AtHandle(cxtEntity - 0x20000); if (scriptGuid) { if (scriptGuid->type == fx::ScriptGuid::Type::Entity) { auto entity = gameState->GetEntity(cxtEntity); if (entity) { entityHandle = entity->handle; buffer.Write<int>(entityHandle); } else { return; } } else if (scriptGuid->type == fx::ScriptGuid::Type::TempEntity) { auto it = g_entityCreationList.find(scriptGuid->tempEntity.creationToken); if (it != g_entityCreationList.end()) { buffer.Write<uint32_t>(scriptGuid->tempEntity.creationToken | 0x80000000); } else { return; } } } else { return; } break; } case RpcConfiguration::ArgumentType::Player: { int player = ctx.GetArgument<int>(i); auto client = clientRegistry->GetClientByNetID(player); if (!client) { return; } buffer.Write<uint8_t>(client->GetSlotId()); break; } case RpcConfiguration::ArgumentType::Int: case RpcConfiguration::ArgumentType::Hash: buffer.Write<int>(ctx.GetArgument<int>(i)); break; case RpcConfiguration::ArgumentType::Float: buffer.Write<float>(ctx.GetArgument<float>(i)); break; case RpcConfiguration::ArgumentType::Bool: buffer.Write<uint8_t>(ctx.GetArgument<bool>(i)); break; case RpcConfiguration::ArgumentType::String: { const char* str = ctx.GetArgument<const char*>(i); buffer.Write<uint16_t>(strlen(str)); buffer.Write(str, strlen(str)); break; } } ++i; } auto sendToClient = [&](const std::shared_ptr<fx::Client>& cl) { cl->SendPacket(0, buffer, NetPacketType_ReliableReplayed); }; if (clientIdx == -1) { clientRegistry->ForAllClients(sendToClient); } else { sendToClient(clientRegistry->GetClientByNetID(clientIdx)); } if (native->GetRpcType() == RpcConfiguration::RpcType::EntityCreate) { EntityCreationState state; state.creationToken = creationToken; auto guid = new fx::ScriptGuid; guid->type = fx::ScriptGuid::Type::TempEntity; guid->tempEntity.creationToken = creationToken; guid->reference = nullptr; state.clientIdx = clientIdx; state.scriptGuid = guid; auto scrHdl = g_scriptHandlePool->GetIndex(guid) + 0x20000; g_entityCreationList.insert({ creationToken, state }); ctx.SetResult(scrHdl); } }); } }, 99999999); });
24.442623
161
0.615694
R0JEA
b892b25a6877470239cdbc4423601f96733a5007
10,063
cpp
C++
Jackal/Source/Core/Private/Math/Matrix4.cpp
CheezBoiger/Jackal
6c87bf19f6c1cd63f53c815820b32fc71b48bf77
[ "MIT" ]
null
null
null
Jackal/Source/Core/Private/Math/Matrix4.cpp
CheezBoiger/Jackal
6c87bf19f6c1cd63f53c815820b32fc71b48bf77
[ "MIT" ]
null
null
null
Jackal/Source/Core/Private/Math/Matrix4.cpp
CheezBoiger/Jackal
6c87bf19f6c1cd63f53c815820b32fc71b48bf77
[ "MIT" ]
null
null
null
// Copyright (c) 2017 Jackal Engine, MIT License. #include "Core/Math/Matrix4.hpp" namespace jackal { Matrix4 Matrix4::operator+(const Matrix4 &m) const { return Matrix4( data[0][0] + m.data[0][0], data[0][1] + m.data[0][1], data[0][2] + m.data[0][2], data[0][3] + m.data[0][3], data[1][0] + m.data[1][0], data[1][1] + m.data[1][1], data[1][2] + m.data[1][2], data[1][3] + m.data[1][3], data[2][0] + m.data[2][0], data[2][1] + m.data[2][1], data[2][2] + m.data[2][2], data[2][3] + m.data[2][3], data[3][0] + m.data[3][0], data[3][1] + m.data[3][1], data[3][2] + m.data[3][2], data[3][3] + m.data[3][3] ); } Matrix4 Matrix4::operator-(const Matrix4 &m) const { return Matrix4( data[0][0] - m.data[0][0], data[0][1] - m.data[0][1], data[0][2] - m.data[0][2], data[0][3] - m.data[0][3], data[1][0] - m.data[1][0], data[1][1] - m.data[1][1], data[1][2] - m.data[1][2], data[1][3] - m.data[1][3], data[2][0] - m.data[2][0], data[2][1] - m.data[2][1], data[2][2] - m.data[2][2], data[2][3] - m.data[2][3], data[3][0] - m.data[3][0], data[3][1] - m.data[3][1], data[3][2] - m.data[3][2], data[3][3] - m.data[3][3] ); } Matrix4 Matrix4::operator*(const Matrix4 &m) const { return Matrix4( data[0][0] * m.data[0][0] + data[0][1] * m.data[1][0] + data[0][2] * m.data[2][0] + data[0][3] * m.data[3][0], data[0][0] * m.data[0][1] + data[0][1] * m.data[1][1] + data[0][2] * m.data[2][1] + data[0][3] * m.data[3][1], data[0][0] * m.data[0][2] + data[0][1] * m.data[1][2] + data[0][2] * m.data[2][2] + data[0][3] * m.data[3][2], data[0][0] * m.data[0][3] + data[0][1] * m.data[1][3] + data[0][2] * m.data[2][3] + data[0][3] * m.data[3][3], data[1][0] * m.data[0][0] + data[1][1] * m.data[1][0] + data[1][2] * m.data[2][0] + data[1][3] * m.data[3][0], data[1][0] * m.data[0][1] + data[1][1] * m.data[1][1] + data[1][2] * m.data[2][1] + data[1][3] * m.data[3][1], data[1][0] * m.data[0][2] + data[1][1] * m.data[1][2] + data[1][2] * m.data[2][2] + data[1][3] * m.data[3][2], data[1][0] * m.data[0][3] + data[1][1] * m.data[1][3] + data[1][2] * m.data[2][3] + data[1][3] * m.data[3][3], data[2][0] * m.data[0][0] + data[2][1] * m.data[1][0] + data[2][2] * m.data[2][0] + data[2][3] * m.data[3][0], data[2][0] * m.data[0][1] + data[2][1] * m.data[1][1] + data[2][2] * m.data[2][1] + data[2][3] * m.data[3][1], data[2][0] * m.data[0][2] + data[2][1] * m.data[1][2] + data[2][2] * m.data[2][2] + data[2][3] * m.data[3][2], data[2][0] * m.data[0][3] + data[2][1] * m.data[1][3] + data[2][2] * m.data[2][3] + data[2][3] * m.data[3][3], data[3][0] * m.data[0][0] + data[3][1] * m.data[1][0] + data[3][2] * m.data[2][0] + data[3][3] * m.data[3][0], data[3][0] * m.data[0][1] + data[3][1] * m.data[1][1] + data[3][2] * m.data[2][1] + data[3][3] * m.data[3][1], data[3][0] * m.data[0][2] + data[3][1] * m.data[1][2] + data[3][2] * m.data[2][2] + data[3][3] * m.data[3][2], data[3][0] * m.data[0][3] + data[3][1] * m.data[1][3] + data[3][2] * m.data[2][3] + data[3][3] * m.data[3][3] ); } Matrix4 Matrix4::operator*(const real32 scale) const { return Matrix4( data[0][0] * scale, data[0][1] * scale, data[0][2] * scale, data[0][3] * scale, data[1][0] * scale, data[1][1] * scale, data[1][2] * scale, data[1][3] * scale, data[2][0] * scale, data[2][1] * scale, data[2][2] * scale, data[2][3] * scale, data[3][0] * scale, data[3][1] * scale, data[3][2] * scale, data[3][3] * scale ); } void Matrix4::operator*=(const real32 scale) { data[0][0] *= scale; data[0][1] *= scale; data[0][2] *= scale; data[0][3] *= scale; data[1][0] *= scale; data[1][1] *= scale; data[1][2] *= scale; data[1][3] *= scale; data[2][0] *= scale; data[2][1] *= scale; data[2][2] *= scale; data[2][3] *= scale; data[3][0] *= scale; data[3][1] *= scale; data[3][2] *= scale; data[3][3] *= scale; } void Matrix4::operator+=(const Matrix4 &m) { data[0][0] += m.data[0][0]; data[0][1] += m.data[0][1]; data[0][2] += m.data[0][2]; data[0][3] += m.data[0][3]; data[1][0] += m.data[1][0]; data[1][1] += m.data[1][1]; data[1][2] += m.data[1][2]; data[1][3] += m.data[1][3]; data[2][0] += m.data[2][0]; data[2][1] += m.data[2][1]; data[2][2] += m.data[2][2]; data[2][3] += m.data[2][3]; data[3][0] += m.data[3][0]; data[3][1] += m.data[3][1]; data[3][2] += m.data[3][2]; data[3][3] += m.data[3][3]; } void Matrix4::operator-=(const Matrix4 &m) { data[0][0] -= m.data[0][0]; data[0][1] -= m.data[0][1]; data[0][2] -= m.data[0][2]; data[0][3] -= m.data[0][3]; data[1][0] -= m.data[1][0]; data[1][1] -= m.data[1][1]; data[1][2] -= m.data[1][2]; data[1][3] -= m.data[1][3]; data[2][0] -= m.data[2][0]; data[2][1] -= m.data[2][1]; data[2][2] -= m.data[2][2]; data[2][3] -= m.data[2][3]; data[3][0] -= m.data[3][0]; data[3][1] -= m.data[3][1]; data[3][2] -= m.data[3][2]; data[3][3] -= m.data[3][3]; } void Matrix4::operator*=(const Matrix4 &m) { Matrix4 ori = *this; data[0][0] = ori[0][0] * m.data[0][0] + ori[0][1] * m.data[1][0] + ori[0][2] * m.data[2][0] + ori[0][3] * m.data[3][0]; data[0][1] = ori[0][0] * m.data[0][1] + ori[0][1] * m.data[1][1] + ori[0][2] * m.data[2][1] + ori[0][3] * m.data[3][1]; data[0][2] = ori[0][0] * m.data[0][2] + ori[0][1] * m.data[1][2] + ori[0][2] * m.data[2][2] + ori[0][3] * m.data[3][2]; data[0][3] = ori[0][0] * m.data[0][3] + ori[0][1] * m.data[1][3] + ori[0][2] * m.data[2][3] + ori[0][3] * m.data[3][3]; data[1][0] = ori[1][0] * m.data[0][0] + ori[1][1] * m.data[1][0] + ori[1][2] * m.data[2][0] + ori[1][3] * m.data[3][0]; data[1][1] = ori[1][0] * m.data[0][1] + ori[1][1] * m.data[1][1] + ori[1][2] * m.data[2][1] + ori[1][3] * m.data[3][1]; data[1][2] = ori[1][0] * m.data[0][2] + ori[1][1] * m.data[1][2] + ori[1][2] * m.data[2][2] + ori[1][3] * m.data[3][2]; data[1][3] = ori[1][0] * m.data[0][3] + ori[1][1] * m.data[1][3] + ori[1][2] * m.data[2][3] + ori[1][3] * m.data[3][3]; data[2][0] = ori[2][0] * m.data[0][0] + ori[2][1] * m.data[1][0] + ori[2][2] * m.data[2][0] + ori[2][3] * m.data[3][0]; data[2][1] = ori[2][0] * m.data[0][1] + ori[2][1] * m.data[1][1] + ori[2][2] * m.data[2][1] + ori[2][3] * m.data[3][1]; data[2][2] = ori[2][0] * m.data[0][2] + ori[2][1] * m.data[1][2] + ori[2][2] * m.data[2][2] + ori[2][3] * m.data[3][2]; data[2][3] = ori[2][0] * m.data[0][3] + ori[2][1] * m.data[1][3] + ori[2][2] * m.data[2][3] + ori[2][3] * m.data[3][3]; data[3][0] = ori[3][0] * m.data[0][0] + ori[3][1] * m.data[1][0] + ori[3][2] * m.data[2][0] + ori[3][3] * m.data[3][0]; data[3][1] = ori[3][0] * m.data[0][1] + ori[3][1] * m.data[1][1] + ori[3][2] * m.data[2][1] + ori[3][3] * m.data[3][1]; data[3][2] = ori[3][0] * m.data[0][2] + ori[3][1] * m.data[1][2] + ori[3][2] * m.data[2][2] + ori[3][3] * m.data[3][2]; data[3][3] = ori[3][0] * m.data[0][3] + ori[3][1] * m.data[1][3] + ori[3][2] * m.data[2][3] + ori[3][3] * m.data[3][3]; } real32 Matrix4::Determinant() const { return data[0][0] * ( data[1][1] * (data[2][2] * data[3][3] - data[2][3] * data[3][2]) - data[1][2] * (data[2][1] * data[3][3] - data[2][3] * data[3][1]) + data[1][3] * (data[2][1] * data[3][2] - data[2][2] * data[3][1]) ) - data[0][1] * ( data[1][0] * (data[2][2] * data[3][3] - data[2][3] * data[3][2]) - data[1][2] * (data[2][0] * data[3][3] - data[2][3] * data[3][0]) + data[1][3] * (data[2][0] * data[3][2] - data[2][2] * data[3][0]) ) + data[0][2] * ( data[1][0] * (data[2][1] * data[3][3] - data[2][3] * data[3][1]) - data[1][1] * (data[2][0] * data[3][3] - data[2][3] * data[3][0]) + data[1][3] * (data[2][0] * data[3][1] - data[2][1] * data[3][0]) ) - data[0][3] * ( data[1][0] * (data[2][1] * data[3][2] - data[2][2] * data[3][1]) - data[1][1] * (data[2][0] * data[3][2] - data[2][2] * data[3][0]) + data[1][2] * (data[2][0] * data[3][1] - data[2][1] * data[3][0]) ); } Matrix4 Matrix4::Transpose() const { return Matrix4( data[0][0], data[1][0], data[2][0], data[3][0], data[0][1], data[1][1], data[2][1], data[3][1], data[0][2], data[1][2], data[2][2], data[3][2], data[0][3], data[1][3], data[2][3], data[3][3] ); } // We calculate the inverse of a 4x4 matrix using the standard method // of finding the adjugate and multiplying it with one over // the determinant. The formula: // // inv(A) = (1/detA) * adj(A) Matrix4 Matrix4::Inverse() const { real32 detA = Determinant(); if (detA == 0.0f) { return Matrix4::Identity(); } Matrix4 inverse = Adjugate() * (1.0f / detA); return inverse; } Matrix4 Matrix4::Adjugate() const { // Calculating our adjugate using the transpose of the cofactor of our // matrix. Matrix4 CofactorMatrix; real32 sign = 1.0f; for (uint32 row = 0; row < 4; ++row) { sign = -sign; for (uint32 col = 0; col < 4; ++col) { sign = -sign; CofactorMatrix[row][col] = Minor(row, col).Determinant() * sign; } } // Transpose this CofactorMatrix to get the adjugate. return CofactorMatrix.Transpose(); } Matrix3 Matrix4::Minor(uint32 row, uint32 col) const { Matrix3 minor; uint32 r = 0, c; for (uint32 i = 0; i < 4; ++i) { if (i == row) continue; c = 0; for (uint32 j = 0; j < 4; ++j) { if (j == col) continue; minor[r][c] = data[i][j]; c++; } r++; } return minor; } bool Matrix4::ContainsNaN() const { for (uint32 i = 0; i < 4; ++i) { for (uint32 j = 0; j < 4; ++j) { if (IsNaN(data[i][j])) { return true; } } } return false; } bool Matrix4::operator==(const Matrix4 &m) const { for (uint32 i = 0; i < 4; ++i) { for (uint32 j = 0; j < 4; ++j) { if (data[i][j] != m.data[i][j]) { return false; } } } return true; } } // jackal
44.330396
121
0.474113
CheezBoiger
b89780ff17deb6f22188194e4f6f657f496d9609
6,181
cpp
C++
src/graphics/render/pipeline.cpp
guillaume-haerinck/learn-vulkan
30acd5b477866f7454a3c89bf10a7bfffc11c9a1
[ "MIT" ]
null
null
null
src/graphics/render/pipeline.cpp
guillaume-haerinck/learn-vulkan
30acd5b477866f7454a3c89bf10a7bfffc11c9a1
[ "MIT" ]
null
null
null
src/graphics/render/pipeline.cpp
guillaume-haerinck/learn-vulkan
30acd5b477866f7454a3c89bf10a7bfffc11c9a1
[ "MIT" ]
null
null
null
#include "pipeline.h" #include <fstream> #include <iostream> #include <debug_break/debug_break.h> Pipeline::Pipeline(LogicalDevice& device, SwapChain& swapChain, DescriptorPool& descriptorPool, MemoryAllocator& memoryAllocator, Sampler& sampler, TextureImageView& texture ) : m_device(device), m_pipelineLayout(device), m_uniformBuffer(device, memoryAllocator, swapChain.getImageViews().size()), m_descriptorSets(device, descriptorPool, m_pipelineLayout.getDescriptorSetLayout(), swapChain.getImageViews().size(), m_uniformBuffer, sampler, texture ), m_framebuffer(device, swapChain, memoryAllocator) { // Shader stages vk::PipelineShaderStageCreateInfo shaderStages[2]; { std::vector<char> vertShaderCode = readBinaryFile("res/shaders/test_vs.spv"); vk::PipelineShaderStageCreateInfo vertShaderStageInfo( vk::PipelineShaderStageCreateFlags(), vk::ShaderStageFlagBits::eVertex, createShaderModule(vertShaderCode, device), "main" ); shaderStages[0] = vertShaderStageInfo; std::vector<char> fragShaderCode = readBinaryFile("res/shaders/test_ps.spv"); vk::PipelineShaderStageCreateInfo fragShaderStageInfo( vk::PipelineShaderStageCreateFlags(), vk::ShaderStageFlagBits::eFragment, createShaderModule(fragShaderCode, device), "main" ); shaderStages[1] = fragShaderStageInfo; } // Vertex input vk::PipelineVertexInputStateCreateInfo vertexInputInfo( vk::PipelineVertexInputStateCreateFlags(), 1, // bindingDescriptionCount &m_vbDescription.getBindingDescription(), m_vbDescription.getAttributeDescriptions().size(), m_vbDescription.getAttributeDescriptions().data() ); // Input assembly vk::PipelineInputAssemblyStateCreateInfo inputAssembly(vk::PipelineInputAssemblyStateCreateFlags(), vk::PrimitiveTopology::eTriangleList, false); // Viewport auto viewport = vk::Viewport(0.0f, 0.0f, (float) swapChain.getExtent().width, (float) swapChain.getExtent().height, 0.0f, 1.0f); auto scisor = vk::Rect2D(vk::Offset2D(0.0f, 0.0f), swapChain.getExtent()); vk::PipelineViewportStateCreateInfo viewportState(vk::PipelineViewportStateCreateFlags(), 1, &viewport, 1, &scisor); // Rasterizer vk::PipelineRasterizationStateCreateInfo rasterizer( vk::PipelineRasterizationStateCreateFlags(), false, // depthClamp false, // rasterizerDiscard vk::PolygonMode::eFill, vk::CullModeFlagBits::eBack, vk::FrontFace::eCounterClockwise, false, // depthBias 0.0f, // depthBiasConstantFactor 0.0f, // depthBiasClamp 0.0f, // depthBiasSlopeFactor 1.0f // lineWidth ); // Multisampling vk::PipelineMultisampleStateCreateInfo multisampling( vk::PipelineMultisampleStateCreateFlags(), vk::SampleCountFlagBits::e1, false, 1.0f, nullptr, false, false ); // Color blending auto attachement = vk::PipelineColorBlendAttachmentState( false, // blend vk::BlendFactor::eOne, // srcColorBlendFactor vk::BlendFactor::eZero, // dstColorBlendFactor vk::BlendOp::eAdd, // colorBlendOp vk::BlendFactor::eOne, // srcAlphaBlendFactor vk::BlendFactor::eZero, // dstAlphaBlendFactor vk::BlendOp::eAdd, // alphaBlendOp vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA // colorWriteMask ); vk::PipelineColorBlendStateCreateInfo colorBlending( vk::PipelineColorBlendStateCreateFlags(), false, // logicOp vk::LogicOp::eCopy, 1, // attachementCount &attachement, { 0.0f, 0.0f, 0.0f, 0.0f } // BlendConstants ); // Z-Test vk::PipelineDepthStencilStateCreateInfo depthStencil( vk::PipelineDepthStencilStateCreateFlags(), true, // depthTest true, // depthWrite vk::CompareOp::eLess, false, // depthBound false, // stencilTest vk::StencilOpState(), // front vk::StencilOpState(), // back 0, // minDepthBound 1 // maxDepthBound ); // Create pipeline vk::GraphicsPipelineCreateInfo pipelineInfo( vk::PipelineCreateFlags(), 2, shaderStages, &vertexInputInfo, &inputAssembly, nullptr, // pTessellationState &viewportState, &rasterizer, &multisampling, &depthStencil, &colorBlending, nullptr, // pDynamicState m_pipelineLayout.get(), m_framebuffer.getRenderPass(), 0, // subpass nullptr, // basePipelineHandle -1 // basePipelineIndex ); m_graphicsPipeline = m_device.get().createGraphicsPipeline(nullptr, pipelineInfo); // Cleanup m_device.get().destroyShaderModule(shaderStages[0].module); m_device.get().destroyShaderModule(shaderStages[1].module); } Pipeline::~Pipeline() { m_device.get().destroyPipeline(m_graphicsPipeline); } void Pipeline::updateUniformBuffer(unsigned int imageIndex, const glm::mat4x4& viewProj) { m_uniformBuffer.updateBuffer(imageIndex, viewProj); } std::vector<char> Pipeline::readBinaryFile(const std::string& filename) { std::ifstream file(filename, std::ios::ate | std::ios::binary); if (!file.is_open()) { std::cerr << "[Pipeline] Failed to open SPIR-V file : " << filename << std::endl; debug_break(); } size_t fileSize = (size_t) file.tellg(); std::vector<char> buffer(fileSize); file.seekg(0); file.read(buffer.data(), fileSize); file.close(); return buffer; } vk::ShaderModule Pipeline::createShaderModule(const std::vector<char>& code, LogicalDevice& device) { vk::ShaderModuleCreateInfo createInfo( vk::ShaderModuleCreateFlags(), code.size(), reinterpret_cast<const uint32_t*>(code.data()) ); return device.get().createShaderModule(createInfo); }
34.920904
155
0.661705
guillaume-haerinck
b8987efcfc200daf40273c3590d42086e18e762b
2,066
cpp
C++
riscv-sim/src/FlashMemoryDevice.cpp
XiaoxingChen/riscv-console
8f671e13a374e7a350d202cde3fe98e3235aa9d3
[ "BSD-3-Clause" ]
null
null
null
riscv-sim/src/FlashMemoryDevice.cpp
XiaoxingChen/riscv-console
8f671e13a374e7a350d202cde3fe98e3235aa9d3
[ "BSD-3-Clause" ]
null
null
null
riscv-sim/src/FlashMemoryDevice.cpp
XiaoxingChen/riscv-console
8f671e13a374e7a350d202cde3fe98e3235aa9d3
[ "BSD-3-Clause" ]
null
null
null
#include "FlashMemoryDevice.h" #include <stdexcept> #include <cstring> #include <string> CFlashMemoryDevice::CFlashMemoryDevice(uint32_t size){ DBaseAddress = 0; DData.resize(size); DWriteEnabled = false; } uint8_t *CFlashMemoryDevice::AccessAddress(uint32_t addr, uint32_t size){ uint32_t Index = addr - DBaseAddress; if((Index < DData.size())&&(Index + size <= DData.size())){ return DData.data() + Index; } throw std::out_of_range("CFlashMemoryDevice addr out of range!"); } bool CFlashMemoryDevice::EraseAll() noexcept{ if(DWriteEnabled){ memset(DData.data(), 0,DData.size()); } return true; } uint8_t CFlashMemoryDevice::LoadUINT8(uint32_t addr){ return *AccessAddress(addr, sizeof(uint8_t)); } uint16_t CFlashMemoryDevice::LoadUINT16(uint32_t addr){ return *(uint16_t *)AccessAddress(addr, sizeof(uint16_t)); } uint32_t CFlashMemoryDevice::LoadUINT32(uint32_t addr){ return *(uint32_t *)AccessAddress(addr, sizeof(uint32_t)); } uint64_t CFlashMemoryDevice::LoadUINT64(uint32_t addr){ return *(uint64_t *)AccessAddress(addr, sizeof(uint64_t)); } void CFlashMemoryDevice::StoreUINT8(uint32_t addr, uint8_t val){ if(DWriteEnabled){ *AccessAddress(addr, sizeof(uint8_t)) = val; } } void CFlashMemoryDevice::StoreUINT16(uint32_t addr, uint16_t val){ if(DWriteEnabled){ *(uint16_t *)AccessAddress(addr, sizeof(uint16_t)) = val; } } void CFlashMemoryDevice::StoreUINT32(uint32_t addr, uint32_t val){ if(DWriteEnabled){ *(uint32_t *)AccessAddress(addr, sizeof(uint32_t)) = val; } } void CFlashMemoryDevice::StoreUINT64(uint32_t addr, uint64_t val){ if(DWriteEnabled){ *(uint64_t *)AccessAddress(addr, sizeof(uint64_t)) = val; } } const uint8_t *CFlashMemoryDevice::LoadData(uint32_t addr, uint32_t size){ return AccessAddress(addr,size); } void CFlashMemoryDevice::StoreData(uint32_t addr, const uint8_t *src, uint32_t size){ if(DWriteEnabled){ std::memcpy(AccessAddress(addr,size),src,size); } }
26.487179
85
0.70668
XiaoxingChen
b89ba9878b3486320fb2b3699cb8cca839151113
6,579
cpp
C++
panda_softhand_control/src/PoseControl.cpp
CentroEPiaggio/panda-softhand
817e78cdd7343bf62897897dcbe06c32e5ae8b88
[ "BSD-3-Clause" ]
3
2019-04-06T01:43:33.000Z
2021-04-23T13:03:16.000Z
panda_softhand_control/src/PoseControl.cpp
CentroEPiaggio/panda-softhand
817e78cdd7343bf62897897dcbe06c32e5ae8b88
[ "BSD-3-Clause" ]
null
null
null
panda_softhand_control/src/PoseControl.cpp
CentroEPiaggio/panda-softhand
817e78cdd7343bf62897897dcbe06c32e5ae8b88
[ "BSD-3-Clause" ]
2
2020-02-12T19:20:34.000Z
2022-03-18T11:29:08.000Z
/* POSE CONTROL - Uses moveit movegroupinterface to plan towards a pose Authors: George Jose Pollayil - Mathew Jose Pollayil Email: gpollayil@gmail.com, mathewjosepollayil@gmail.com */ #include "ros/ros.h" #include <cstdlib> #include <sstream> #include <string> #include "panda_softhand_control/PoseControl.h" #include <moveit_visual_tools/moveit_visual_tools.h> PoseControl::PoseControl(ros::NodeHandle& nh_, std::string group_name_, std::string end_effector_name_, boost::shared_ptr<actionlib::SimpleActionClient<control_msgs::FollowJointTrajectoryAction>> arm_client_ptr_){ ROS_INFO("Starting to create PoseControl object"); // Initializing node handle this->nh = nh_; // Initializing names this->end_effector_name = end_effector_name_; this->group_name = group_name_; // Initializing the arm client this->arm_client_ptr = arm_client_ptr_; ROS_INFO("Finished creating PoseControl object"); } PoseControl::~PoseControl(){ // Nothing to do here yet } // This is the callback function of the pose control service bool PoseControl::call_pose_control(panda_softhand_control::pose_control::Request &req, panda_softhand_control::pose_control::Response &res){ // Setting up things if(!this->initialize(req.goal_pose, req.is_goal_relative)){ ROS_ERROR("Could not initialize PoseControl object. Returning..."); res.answer = false; return false; } // Perform motion plan towards the goal pose if(!this->performMotionPlan()){ ROS_ERROR("Could not perform motion planning in PoseControl object. Returning..."); res.answer = false; return false; } // Send computed joint motion if(!this->sendJointTrajectory(this->computed_trajectory)){ ROS_ERROR("Could not send computed trajectory from PoseControl object. Returning..."); res.answer = false; return false; } // At this point everything is completed, return true res.answer = true; return true; } // Initialize the things for motion planning. Is called by the callback bool PoseControl::initialize(geometry_msgs::Pose goal_pose, bool is_goal_relative){ // Getting the current ee transform try { this->tf_listener.waitForTransform("/world", this->end_effector_name, ros::Time(0), ros::Duration(10.0) ); this->tf_listener.lookupTransform("/world", this->end_effector_name, ros::Time(0), this->stamp_ee_transform); } catch (tf::TransformException ex){ ROS_ERROR("%s", ex.what()); ros::Duration(1.0).sleep(); return false; } tf::Transform ee_transform(this->stamp_ee_transform.getRotation(), this->stamp_ee_transform.getOrigin()); tf::transformTFToEigen(ee_transform, this->end_effector_state); // Print the current end-effector pose if(DEBUG) ROS_INFO_STREAM("Endeffector current Translation: \n" << this->end_effector_state.translation()); if(DEBUG) ROS_INFO_STREAM("Endeffector current Rotation: \n" << this->end_effector_state.rotation()); // Setting the goal pose tf::poseMsgToEigen(goal_pose, this->goalPoseAff); // If the goal is relative, get the global goal pose by multiplying it with ee pose (end_effector_state) if(is_goal_relative){ this->goalPoseAff = this->end_effector_state * this->goalPoseAff; } // Reconvert to geometry_msgs Pose tf::poseEigenToMsg(this->goalPoseAff, this->goalPose); // Print the goal end-effector pose if(DEBUG) ROS_INFO_STREAM("Endeffector goal Translation: \n" << this->goalPoseAff.translation()); if(DEBUG) ROS_INFO_STREAM("Endeffector goal Rotation: \n" << this->goalPoseAff.linear()); return true; } // Performs motion planning for the end-effector towards goal bool PoseControl::performMotionPlan(){ // Move group interface moveit::planning_interface::MoveGroupInterface group(this->group_name); // Getting the robot joint model ros::spinOnce(); // May not be necessary const robot_state::JointModelGroup* joint_model_group = group.getCurrentState()->getJointModelGroup(this->group_name); /* If VISUAL is enabled */ #ifdef VISUAL // Visual tools moveit_visual_tools::MoveItVisualTools visual_tools("world"); visual_tools.deleteAllMarkers(); // Loading the remote control for visual tools and promting a message visual_tools.loadRemoteControl(); visual_tools.trigger(); #endif // Printing the planning group frame and the group ee frame if(DEBUG) ROS_INFO("MoveIt Group Reference frame: %s", group.getPlanningFrame().c_str()); if(DEBUG) ROS_INFO("MoveIt Group End-effector frame: %s", group.getEndEffectorLink().c_str()); // Setting the pose target of the move group group.setPoseTarget(this->goalPose); if(DEBUG) ROS_INFO("Done setting the target pose in MoveIt Group."); // Planning to Pose moveit::planning_interface::MoveGroupInterface::Plan my_plan; bool success = (group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS); ROS_INFO("Motion Plan towards goal pose %s.", success ? "SUCCEDED" : "FAILED"); // If complete path is not achieved return false, true otherwise if(!success) return false; /* If VISUAL is enabled */ #ifdef VISUAL ROS_INFO("Visualizing the computed plan as trajectory line."); visual_tools.publishAxisLabeled(this->goalPose, "goal pose"); visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group); visual_tools.trigger(); #ifdef PROMPT visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to execute the motion on the robot."); #endif #endif // Saving the computed trajectory and returning true this->computed_trajectory = my_plan.trajectory_.joint_trajectory; return true; } // Sends trajectory to the joint_traj controller bool PoseControl::sendJointTrajectory(trajectory_msgs::JointTrajectory trajectory){ // Waiting for the arm server to be ready if(!this->arm_client_ptr->waitForServer(ros::Duration(1,0))){ ROS_ERROR("The arm client is taking too much to get ready. Returning..."); return false; } // Send the message and wait for the result control_msgs::FollowJointTrajectoryGoal goalmsg; goalmsg.trajectory = trajectory; this->arm_client_ptr->sendGoal(goalmsg); if(!this->arm_client_ptr->waitForResult(ros::Duration(60, 0))){ ROS_WARN("The arm client is taking too to complete goal execution. Is it a really long motion???"); } return true; }
35.562162
141
0.715458
CentroEPiaggio
b8a1e2b14b69ed8b918bc425f3419e34e4c55839
3,590
cpp
C++
Source/CSharp/CSharp/Urho3D/Native/HashMap.cpp
TrevorCash/Urho3D_old
d24b1467ab2932e9f2bf7881cf116f841a20a6a7
[ "MIT" ]
3
2018-06-26T05:53:51.000Z
2018-10-24T20:52:38.000Z
Source/CSharp/CSharp/Urho3D/Native/HashMap.cpp
TrevorCash/Urho3D_old
d24b1467ab2932e9f2bf7881cf116f841a20a6a7
[ "MIT" ]
1
2018-02-17T17:32:37.000Z
2018-03-03T03:51:11.000Z
Source/CSharp/CSharp/Urho3D/Native/HashMap.cpp
TrevorCash/Urho3D_old
d24b1467ab2932e9f2bf7881cf116f841a20a6a7
[ "MIT" ]
2
2018-08-04T21:12:11.000Z
2019-02-09T05:04:29.000Z
// // Copyright (c) 2018 Rokas Kupstys // // 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 "CSharp.h" extern "C" { ////////////////////////////////////////////////////// VariantMap ////////////////////////////////////////////////////// URHO3D_EXPORT_API unsigned Urho3D_HashMap_StringHash_Variant_GetKey(Urho3D::VariantMap::Iterator it) { return it->first_.Value(); } URHO3D_EXPORT_API void* Urho3D_HashMap_StringHash_Variant_GetValue(Urho3D::VariantMap::Iterator it) { return (void*) &it->second_; } URHO3D_EXPORT_API void Urho3D_HashMap_StringHash_Variant_Add(Urho3D::VariantMap* map, unsigned key, Urho3D::Variant* value) { map->Insert(Urho3D::Pair<StringHash, Variant>(StringHash(key), *value)); } URHO3D_EXPORT_API bool Urho3D_HashMap_StringHash_Variant_Remove(Urho3D::VariantMap* map, unsigned key) { return map->Erase(StringHash(key)); } URHO3D_EXPORT_API bool Urho3D_HashMap_StringHash_Variant_First(Urho3D::VariantMap* map, Urho3D::VariantMap::Iterator& it) { it = map->Begin(); return it != map->End(); } URHO3D_EXPORT_API bool Urho3D_HashMap_StringHash_Variant_Next(Urho3D::VariantMap* map, Urho3D::VariantMap::Iterator& it) { it++; return it != map->End(); } URHO3D_EXPORT_API bool Urho3D_HashMap_StringHash_Variant_Contains(Urho3D::VariantMap* map, unsigned key) { return map->Contains(StringHash(key)); } URHO3D_EXPORT_API Variant* Urho3D_HashMap_StringHash_Variant_TryGet(Urho3D::VariantMap* map, unsigned key) { Variant result; if (map->TryGetValue(StringHash(key), result)) return new Variant(result); return nullptr; } URHO3D_EXPORT_API void Urho3D_HashMap_StringHash_Variant_destructor(Urho3D::VariantMap* map) { delete map; } void RegisterVariantMapInternalCalls(Context* context) { MONO_INTERNAL_CALL(Urho3D.VariantMap, Urho3D_HashMap_StringHash_Variant_GetKey); MONO_INTERNAL_CALL(Urho3D.VariantMap, Urho3D_HashMap_StringHash_Variant_GetValue); MONO_INTERNAL_CALL(Urho3D.VariantMap, Urho3D_HashMap_StringHash_Variant_Add); MONO_INTERNAL_CALL(Urho3D.VariantMap, Urho3D_HashMap_StringHash_Variant_Remove); MONO_INTERNAL_CALL(Urho3D.VariantMap, Urho3D_HashMap_StringHash_Variant_First); MONO_INTERNAL_CALL(Urho3D.VariantMap, Urho3D_HashMap_StringHash_Variant_Next); MONO_INTERNAL_CALL(Urho3D.VariantMap, Urho3D_HashMap_StringHash_Variant_Contains); MONO_INTERNAL_CALL(Urho3D.VariantMap, Urho3D_HashMap_StringHash_Variant_TryGet); MONO_INTERNAL_CALL(Urho3D.VariantMap, Urho3D_HashMap_StringHash_Variant_destructor); } }
37.789474
120
0.762674
TrevorCash
b8a4443cfee7e77cfbb9f0b178e25c965b81c6a8
3,485
cpp
C++
loom/script/native/core/system/lmJSON.cpp
RichardRanft/LoomSDK
7f12b9d572f2ca409b9070ba92a284a82263ae97
[ "ECL-2.0", "Apache-2.0", "BSD-2-Clause" ]
1
2018-08-10T01:24:52.000Z
2018-08-10T01:24:52.000Z
loom/script/native/core/system/lmJSON.cpp
RichardRanft/LoomSDK
7f12b9d572f2ca409b9070ba92a284a82263ae97
[ "ECL-2.0", "Apache-2.0", "BSD-2-Clause" ]
null
null
null
loom/script/native/core/system/lmJSON.cpp
RichardRanft/LoomSDK
7f12b9d572f2ca409b9070ba92a284a82263ae97
[ "ECL-2.0", "Apache-2.0", "BSD-2-Clause" ]
null
null
null
/* * =========================================================================== * Loom SDK * Copyright 2011, 2012, 2013 * The Game Engine Company, LLC * * 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 "loom/common/utils/json.h" #include "loom/script/loomscript.h" static int registerSystemJSON(lua_State *L) { beginPackage(L, "system") .beginClass<JSON> ("JSON") .addConstructor<void (*)(void)>() .addMethod("initObject", &JSON::initObject) .addMethod("initArray", &JSON::initArray) .addMethod("loadString", &JSON::loadString) .addMethod("serialize", &JSON::serialize) .addMethod("getError", &JSON::getError) .addMethod("getJSONType", &JSON::getJSONType) .addMethod("getObjectJSONType", &JSON::getObjectJSONType) .addMethod("getArrayJSONType", &JSON::getArrayJSONType) .addMethod("getLongLongAsString", &JSON::getLongLongAsString) .addMethod("getInteger", &JSON::getInteger) .addMethod("setInteger", &JSON::setInteger) .addMethod("getFloat", &JSON::getFloat) .addMethod("setFloat", &JSON::setFloat) .addMethod("getNumber", &JSON::getNumber) .addMethod("setNumber", &JSON::setNumber) .addMethod("getString", &JSON::getString) .addMethod("setString", &JSON::setString) .addMethod("getBoolean", &JSON::getBoolean) .addMethod("setBoolean", &JSON::setBoolean) .addMethod("getObject", &JSON::getObject) .addMethod("setObject", &JSON::setObject) .addMethod("getArray", &JSON::getArray) .addMethod("setArray", &JSON::setArray) .addMethod("isObject", &JSON::isObject) .addMethod("getObjectFirstKey", &JSON::getObjectFirstKey) .addMethod("getObjectNextKey", &JSON::getObjectNextKey) .addMethod("isArray", &JSON::isArray) .addMethod("getArrayCount", &JSON::getArrayCount) .addMethod("getArrayBoolean", &JSON::getArrayBoolean) .addMethod("setArrayBoolean", &JSON::setArrayBoolean) .addMethod("getArrayInteger", &JSON::getArrayInteger) .addMethod("setArrayInteger", &JSON::setArrayInteger) .addMethod("getArrayFloat", &JSON::getArrayFloat) .addMethod("setArrayFloat", &JSON::setArrayFloat) .addMethod("getArrayNumber", &JSON::getArrayNumber) .addMethod("setArrayNumber", &JSON::setArrayNumber) .addMethod("getArrayString", &JSON::getArrayString) .addMethod("setArrayString", &JSON::setArrayString) .addMethod("getArrayObject", &JSON::getArrayObject) .addMethod("setArrayObject", &JSON::setArrayObject) .addMethod("getArrayArray", &JSON::getArrayArray) .addMethod("setArrayArray", &JSON::setArrayArray) .endClass() .endPackage(); return 0; } void installSystemJSON() { NativeInterface::registerManagedNativeType<JSON>(registerSystemJSON); }
36.302083
78
0.647346
RichardRanft
b8a79bb6df4ce8b152e463513f33f9836ee9f714
2,010
cpp
C++
Builds/JuceLibraryCode/modules/juce_audio_devices/native/juce_android_Midi.cpp
eriser/CSL
6f4646369f0c90ea90e2c113374044818ab37ded
[ "BSD-4-Clause-UC" ]
1
2019-10-16T08:54:44.000Z
2019-10-16T08:54:44.000Z
JuceLibraryCode/modules/juce_audio_devices/native/juce_android_Midi.cpp
connerlacy/quneo_demo_lab
073a81d7fa7fa462e07c7b33de3e982a03a0055c
[ "Unlicense" ]
null
null
null
JuceLibraryCode/modules/juce_audio_devices/native/juce_android_Midi.cpp
connerlacy/quneo_demo_lab
073a81d7fa7fa462e07c7b33de3e982a03a0055c
[ "Unlicense" ]
null
null
null
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ StringArray MidiOutput::getDevices() { StringArray devices; return devices; } int MidiOutput::getDefaultDeviceIndex() { return 0; } MidiOutput* MidiOutput::openDevice (int index) { return nullptr; } MidiOutput::~MidiOutput() { } void MidiOutput::sendMessageNow (const MidiMessage&) { } //============================================================================== MidiInput::MidiInput (const String& name_) : name (name_), internal (0) { } MidiInput::~MidiInput() { } void MidiInput::start() { } void MidiInput::stop() { } int MidiInput::getDefaultDeviceIndex() { return 0; } StringArray MidiInput::getDevices() { StringArray devs; return devs; } MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return nullptr; }
23.372093
81
0.548756
eriser
b8acec46bf478e522cd3bf55798c297851b8e9a3
5,956
hpp
C++
Source/AllProjects/OrbUtils/CIDCfgSrv/CIDCfgSrv_CfgServerImpl.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
216
2019-03-09T06:41:28.000Z
2022-02-25T16:27:19.000Z
Source/AllProjects/OrbUtils/CIDCfgSrv/CIDCfgSrv_CfgServerImpl.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
9
2020-09-27T08:00:52.000Z
2021-07-02T14:27:31.000Z
Source/AllProjects/OrbUtils/CIDCfgSrv/CIDCfgSrv_CfgServerImpl.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
29
2019-03-09T10:12:24.000Z
2021-03-03T22:25:29.000Z
// // FILE NAME: CIDCfgSrv_CfgServerImpl.hpp // // AUTHOR: Dean Roddey // // CREATED: 12/05/2001 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the header for the CIDCfgSrv_Impl.cpp file, which provides an // implementation of the log server IDL interface. That interface is from // the CIDOrbUC facility, so others can implement it and provide their own // log server if required. We just provide a canned implementation that will // serve most folks. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // #pragma once // --------------------------------------------------------------------------- // CLASS: TCIDNameServerImpl // PREFIX: orbs // --------------------------------------------------------------------------- class TCIDCfgServerImpl : public TCIDCfgSrvServerBase { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TCIDCfgServerImpl(); TCIDCfgServerImpl(const TCIDCfgServerImpl&) = delete; TCIDCfgServerImpl(TCIDCfgServerImpl&&) = delete; ~TCIDCfgServerImpl(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TCIDCfgServerImpl& operator=(const TCIDCfgServerImpl&) = delete; TCIDCfgServerImpl& operator=(TCIDCfgServerImpl&&) = delete; // ------------------------------------------------------------------- // Public, inherited methods // ------------------------------------------------------------------- tCIDLib::TVoid AddObject ( const TString& strKey , const tCIDLib::TCard4 c4DataBytes , const THeapBuf& mbufObjData , const tCIDLib::TCard4 c4Reserve ) final; tCIDLib::TBoolean bAddOrUpdate ( const TString& strKey , CIOP tCIDLib::TCard4& c4Version , const tCIDLib::TCard4 c4DataBytes , const THeapBuf& mbufObjData , const tCIDLib::TCard4 c4Reserve ) final; tCIDLib::TBoolean bAllObjectsUnder ( const TString& strStartPath , tCIDLib::TStrList& colToFill ) final; tCIDLib::TBoolean bDeleteObjectIfExists ( const TString& strKey ) final; tCIDLib::TBoolean bFindNameUnder ( const TString& strName , const TString& strStartPath , tCIDLib::TStrList& colToFill ) final; tCIDLib::TBoolean bKeyExists ( const TString& strKey ) final; tCIDLib::TBoolean bKeyExists2 ( const TString& strKey , CIOP tCIDLib::TCard4& c4Version ) final; tCIDLib::TBoolean bReadObject ( const TString& strKey , COP tCIDLib::TCard4& c4BytesRead , THeapBuf& mbufToFill , CIOP tCIDLib::TCard4& c4Version ) final; tCIDLib::TCard4 c4QueryObjectsInScope ( const TString& strParScope , tCIDLib::TStrList& colToFill ) final; tCIDLib::TCard4 c4QuerySubScopes ( const TString& strParScope , tCIDLib::TStrList& colToFill ) final; tCIDLib::TCard4 c4UpdateObject ( const TString& strKey , const tCIDLib::TCard4 c4DataBytes , const THeapBuf& mbufObjData ) final; tCIDLib::TVoid DeleteObject ( const TString& strKey ) final; tCIDLib::TVoid DeleteScope ( const TString& strScopeKey ) final; tCIDLib::ELoadRes eReadObject ( const TString& strKey , COP tCIDLib::TCard4& c4BytesRead , THeapBuf& mbufToFill , CIOP tCIDLib::TCard4& c4Version , const tCIDLib::TBoolean bThrowIfNot ) final; protected : // ------------------------------------------------------------------- // Protected, inherited methods // ------------------------------------------------------------------- tCIDLib::TVoid Initialize() final; tCIDLib::TVoid Terminate() final; private : // ------------------------------------------------------------------- // Private data members // // m_oseRepo // The object store that manages our repository. It has a fixed // file name, but it's path is in m_strRepoPath. Note that the // object store provides it's own synchronization, so we don't // have to provide any. // ------------------------------------------------------------------- TCIDObjStore m_oseRepo; // ------------------------------------------------------------------- // Magic Macros // ------------------------------------------------------------------- RTTIDefs(TCIDCfgServerImpl,TCIDCfgSrvServerBase) };
32.725275
78
0.428475
MarkStega
b8af52638192a42bcb58bac39c0e50a3cd3ae3e5
53,882
cpp
C++
whisper.cpp
antoniocgj/SweRV-ISS-1
bc32016a0b92d6240b5963457c4403b498200403
[ "Apache-2.0" ]
null
null
null
whisper.cpp
antoniocgj/SweRV-ISS-1
bc32016a0b92d6240b5963457c4403b498200403
[ "Apache-2.0" ]
null
null
null
whisper.cpp
antoniocgj/SweRV-ISS-1
bc32016a0b92d6240b5963457c4403b498200403
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 Western Digital Corporation or its affiliates. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <fstream> #include <sstream> #include <thread> #include <atomic> #if defined(__cpp_lib_filesystem) #include <filesystem> namespace FileSystem = std::filesystem; #else #include <experimental/filesystem> namespace FileSystem = std::experimental::filesystem; #endif #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include <boost/format.hpp> #ifdef __MINGW64__ #include <winsock2.h> typedef int socklen_t; #define close(s) closesocket((s)) #define setlinebuf(f) setvbuf((f),NULL,_IOLBF,0) #define strerror_r(a,b,c) strerror((a)) #else #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #endif #include <csignal> #include "HartConfig.hpp" #include "WhisperMessage.h" #include "Hart.hpp" #include "Core.hpp" #include "System.hpp" #include "Server.hpp" #include "Interactive.hpp" using namespace WdRiscv; /// Return format string suitable for printing an integer of type URV /// in hexadecimal form. template <typename URV> static const char* getHexForm() { if (sizeof(URV) == 4) return "0x%08x"; if (sizeof(URV) == 8) return "0x%016x"; if (sizeof(URV) == 16) return "0x%032x"; return "0x%x"; } /// Convert the command line string numberStr to a number using /// strotull and a base of zero (prefixes 0 and 0x are /// honored). Return true on success and false on failure (string does /// not represent a number). TYPE is an integer type (e.g /// uint32_t). Option is the command line option associated with the /// string and is used for diagnostic messages. template <typename TYPE> static bool parseCmdLineNumber(const std::string& option, const std::string& numberStr, TYPE& number) { std::string str = numberStr; bool good = not str.empty(); uint64_t scale = 1; if (good) { char suffix = str.back(); if (suffix == 'k') scale = 1024; else if (suffix == 'm') scale = 1024*1024; else if (suffix == 'g') scale = 1024*1024*1024; if (scale != 1) { str = str.substr(0, str.length() - 1); if (str.empty()) good = false; } } if (good) { typedef typename std::make_signed_t<TYPE> STYPE; char* end = nullptr; bool bad = false; if (std::is_same<TYPE, STYPE>::value) { int64_t val = strtoll(str.c_str(), &end, 0) * scale; number = static_cast<TYPE>(val); bad = val != number; } else { uint64_t val = strtoull(str.c_str(), &end, 0) * scale; number = static_cast<TYPE>(val); bad = val != number; } if (bad) { std::cerr << "parseCmdLineNumber: Number too large: " << numberStr << '\n'; return false; } if (end and *end) good = false; // Part of the string are non parseable. } if (not good) std::cerr << "Invalid command line " << option << " value: " << numberStr << '\n'; return good; } /// Aapter for the parseCmdLineNumber for optionals. template <typename TYPE> static bool parseCmdLineNumber(const std::string& option, const std::string& numberStr, std::optional<TYPE>& number) { TYPE n; if (not parseCmdLineNumber(option, numberStr, n)) return false; number = n; return true; } typedef std::vector<std::string> StringVec; /// Hold values provided on the command line. struct Args { StringVec hexFiles; // Hex files to be loaded into simulator memory. std::string traceFile; // Log of state change after each instruction. std::string commandLogFile; // Log of interactive or socket commands. std::string consoleOutFile; // Console io output file. std::string serverFile; // File in which to write server host and port. std::string instFreqFile; // Instruction frequency file. std::string configFile; // Configuration (JSON) file. std::string isa; std::string snapshotDir = "snapshot"; // Dir prefix for saving snapshots std::string loadFrom; // Directory for loading a snapshot std::string stdoutFile; // Redirect target program stdout to this. std::string stderrFile; // Redirect target program stderr to this. StringVec zisa; StringVec regInits; // Initial values of regs StringVec targets; // Target (ELF file) programs and associated // program options to be loaded into simulator // memory. Each target plus args is one string. std::string targetSep = " "; // Target program argument separator. std::optional<std::string> toHostSym; std::optional<std::string> consoleIoSym; // Ith item is a vector of strings representing ith target and its args. std::vector<StringVec> expandedTargets; std::optional<uint64_t> startPc; std::optional<uint64_t> endPc; std::optional<uint64_t> toHost; std::optional<uint64_t> consoleIo; std::optional<uint64_t> instCountLim; std::optional<uint64_t> memorySize; std::optional<uint64_t> snapshotPeriod; std::optional<uint64_t> alarmInterval; std::optional<uint64_t> swInterrupt; // Sotware interrupt mem mapped address std::optional<uint64_t> clint; // Clint mem mapped address unsigned regWidth = 32; unsigned harts = 1; unsigned cores = 1; unsigned pageSize = 4*1024; bool help = false; bool hasRegWidth = false; bool hasHarts = false; bool hasCores = false; bool trace = false; bool interactive = false; bool verbose = false; bool version = false; bool traceLdSt = false; // Trace ld/st data address if true. bool triggers = false; // Enable debug triggers when true. bool counters = false; // Enable performance counters when true. bool gdb = false; // Enable gdb mode when true. std::vector<unsigned> gdbTcpPort; // Enable gdb mode over TCP when port is positive. bool abiNames = false; // Use ABI register names in inst disassembly. bool newlib = false; // True if target program linked with newlib. bool linux = false; // True if target program linked with Linux C-lib. bool raw = false; // True if bare-metal program (no linux no newlib). bool elfisa = false; // Use ELF file RISCV architecture tags to set MISA if true. bool fastExt = false; // True if fast external interrupt dispatch enabled. bool unmappedElfOk = false; bool iccmRw = false; bool quitOnAnyHart = false; // True if run quits when any hart finishes. bool noConInput = false; // If true console io address is not used for input (ld). // Expand each target program string into program name and args. void expandTargets(); }; void Args::expandTargets() { this->expandedTargets.clear(); for (const auto& target : this->targets) { StringVec tokens; boost::split(tokens, target, boost::is_any_of(this->targetSep), boost::token_compress_on); this->expandedTargets.push_back(tokens); } } static void printVersion() { unsigned version = 1; unsigned subversion = 640; std::cout << "Version " << version << "." << subversion << " compiled on " << __DATE__ << " at " << __TIME__ << '\n'; } static bool collectCommandLineValues(const boost::program_options::variables_map& varMap, Args& args) { bool ok = true; if (varMap.count("startpc")) { auto numStr = varMap["startpc"].as<std::string>(); if (not parseCmdLineNumber("startpc", numStr, args.startPc)) ok = false; } if (varMap.count("endpc")) { auto numStr = varMap["endpc"].as<std::string>(); if (not parseCmdLineNumber("endpc", numStr, args.endPc)) ok = false; } if (varMap.count("tohost")) { auto numStr = varMap["tohost"].as<std::string>(); if (not parseCmdLineNumber("tohost", numStr, args.toHost)) ok = false; } if (varMap.count("consoleio")) { auto numStr = varMap["consoleio"].as<std::string>(); if (not parseCmdLineNumber("consoleio", numStr, args.consoleIo)) ok = false; } if (varMap.count("maxinst")) { auto numStr = varMap["maxinst"].as<std::string>(); if (not parseCmdLineNumber("maxinst", numStr, args.instCountLim)) ok = false; } if (varMap.count("memorysize")) { auto numStr = varMap["memorysize"].as<std::string>(); if (not parseCmdLineNumber("memorysize", numStr, args.memorySize)) ok = false; } if (varMap.count("snapshotperiod")) { auto numStr = varMap["snapshotperiod"].as<std::string>(); if (not parseCmdLineNumber("snapshotperiod", numStr, args.snapshotPeriod)) ok = false; else if (*args.snapshotPeriod == 0) std::cerr << "Warning: Zero snapshot period ignored.\n"; } if (varMap.count("tohostsym")) args.toHostSym = varMap["tohostsym"].as<std::string>(); if (varMap.count("consoleiosym")) args.consoleIoSym = varMap["consoleiosym"].as<std::string>(); if (varMap.count("xlen")) args.hasRegWidth = true; if (varMap.count("cores")) args.hasCores = true; if (varMap.count("harts")) args.hasHarts = true; if (varMap.count("alarm")) { auto numStr = varMap["alarm"].as<std::string>(); if (not parseCmdLineNumber("alarm", numStr, args.alarmInterval)) ok = false; else if (*args.alarmInterval == 0) std::cerr << "Warning: Zero alarm period ignored.\n"; } if (varMap.count("clint")) { auto numStr = varMap["clint"].as<std::string>(); if (not parseCmdLineNumber("clint", numStr, args.clint)) ok = false; else if ((*args.clint & 7) != 0) { std::cerr << "Error: clint address must be a multiple of 8\n"; ok = false; } } if (varMap.count("softinterrupt")) { auto numStr = varMap["softinterrupt"].as<std::string>(); if (not parseCmdLineNumber("softinterrupt", numStr, args.swInterrupt)) ok = false; else if ((*args.swInterrupt & 3) != 0) { std::cerr << "Error: softinterrupt address must be a multiple of 4\n"; ok = false; } } if (args.interactive) args.trace = true; // Enable instruction tracing in interactive mode. return ok; } /// Parse command line arguments. Place option values in args. /// Return true on success and false on failure. Exists program /// if --help is used. static bool parseCmdLineArgs(int argc, char* argv[], Args& args) { try { // Define command line options. namespace po = boost::program_options; po::options_description desc("options"); desc.add_options() ("help,h", po::bool_switch(&args.help), "Produce this message.") ("log,l", po::bool_switch(&args.trace), "Enable tracing to standard output of executed instructions.") ("isa", po::value(&args.isa), "Specify instruction set extensions to enable. Supported extensions " "are a, c, d, f, i, m, s and u. Default is imc.") ("zisa", po::value(&args.zisa)->multitoken(), "Specify instruction set z-extension to enable. Only z-extensions " "currently supported are zbb and zbs (Exammple --zisa zbb)") ("xlen", po::value(&args.regWidth), "Specify register width (32 or 64), defaults to 32") ("harts", po::value(&args.harts), "Specify number of hardware threads per core (default=1).") ("cores", po::value(&args.cores), "Specify number of core per system (default=1).") ("pagesize", po::value(&args.pageSize), "Specify memory page size.") ("target,t", po::value(&args.targets)->multitoken(), "Target program (ELF file) to load into simulator memory. In " "newlib/Linux emulation mode, program options may follow program name.") ("targetsep", po::value(&args.targetSep), "Target program argument separator.") ("hex,x", po::value(&args.hexFiles)->multitoken(), "HEX file to load into simulator memory.") ("logfile,f", po::value(&args.traceFile), "Enable tracing to given file of executed instructions.") ("consoleoutfile", po::value(&args.consoleOutFile), "Redirect console output to given file.") ("commandlog", po::value(&args.commandLogFile), "Enable logging of interactive/socket commands to the given file.") ("server", po::value(&args.serverFile), "Interactive server mode. Put server hostname and port in file.") ("startpc,s", po::value<std::string>(), "Set program entry point. If not specified, use entry point of the " "most recently loaded ELF file.") ("endpc,e", po::value<std::string>(), "Set stop program counter. Simulator will stop once instruction at " "the stop program counter is executed.") ("tohost", po::value<std::string>(), "Memory address to which a write stops simulator.") ("tohostsym", po::value<std::string>(), "ELF symbol to use for setting tohost from ELF file (in the case " "where tohost is not specified on the command line). Default: " "\"tohost\".") ("consoleio", po::value<std::string>(), "Memory address corresponding to console io. Reading/writing " "(lw/lh/lb sw/sh/sb) from given address reads/writes a byte from the " "console.") ("consoleiosym", po::value<std::string>(), "ELF symbol to use as console-io address (in the case where " "consoleio is not specified on the command line). Deafult: " "\"__whisper_console_io\".") ("maxinst,m", po::value<std::string>(), "Limit executed instruction count to arg.") ("memorysize", po::value<std::string>(), "Memory size (must be a multiple of 4096).") ("interactive,i", po::bool_switch(&args.interactive), "Enable interactive mode.") ("traceload", po::bool_switch(&args.traceLdSt), "Enable tracing of load/store instruction data address.") ("triggers", po::bool_switch(&args.triggers), "Enable debug triggers (triggers are on in interactive and server modes)") ("counters", po::bool_switch(&args.counters), "Enable performance counters") ("gdb", po::bool_switch(&args.gdb), "Run in gdb mode enabling remote debugging from gdb (this requires gdb version" "8.2 or higher).") ("gdb-tcp-port", po::value(&args.gdbTcpPort)->multitoken(), "TCP port number for gdb; If port num is negative," " gdb will work with stdio (default -1).") ("profileinst", po::value(&args.instFreqFile), "Report instruction frequency to file.") ("setreg", po::value(&args.regInits)->multitoken(), "Initialize registers. Apply to all harts unless specific prefix " "present (hart is 1 in 1:x3=0xabc). Example: --setreg x1=4 x2=0xff " "1:x3=0xabc") ("configfile", po::value(&args.configFile), "Configuration file (JSON file defining system features).") ("snapshotdir", po::value(&args.snapshotDir), "Directory prefix for saving snapshots.") ("snapshotperiod", po::value<std::string>(), "Snapshot period: Save snapshot using snapshotdir every so many instructions.") ("loadfrom", po::value(&args.loadFrom), "Snapshot directory from which to restore a previously saved (snapshot) state.") ("stdout", po::value(&args.stdoutFile), "Redirect standard output of newlib/Linux target program to this.") ("stderr", po::value(&args.stderrFile), "Redirect standard error of newlib/Linux target program to this.") ("abinames", po::bool_switch(&args.abiNames), "Use ABI register names (e.g. sp instead of x2) in instruction disassembly.") ("newlib", po::bool_switch(&args.newlib), "Emulate (some) newlib system calls. Done automatically if newlib " "symbols are detected in the target ELF file.") ("linux", po::bool_switch(&args.linux), "Emulate (some) Linux system calls. Done automatically if Linux " "symbols are detected in the target ELF file.") ("raw", po::bool_switch(&args.raw), "Bare metal mode: Disble emulation of Linux/newlib system call emulation " "even if Linux/newlib symbols detected in the target ELF file.") ("elfisa", po::bool_switch(&args.elfisa), "Confiure reset value of MISA according to the RISCV architecture tag(s) " "encoded into the laoded ELF file(s) if any.") ("fastext", po::bool_switch(&args.fastExt), "Enable fast external interrupt dispatch.") ("unmappedelfok", po::bool_switch(&args.unmappedElfOk), "Do not flag as error ELF file sections targeting unmapped " " memory.") ("alarm", po::value<std::string>(), "External interrupt period in micro-seconds: Convert arg to an " "instruction count, n, assuming a 1ghz clock, and force an external " " interrupt every n instructions. No-op if arg is zero.") ("softinterrupt", po::value<std::string>(), "Address of memory mapped word(s) controlling software interrupts. In " "an n-hart system, words at addresses a, a+4, ... a+(n-1)*4 " "are associated with the n harts (\"a\" being the address " "specified by this option and must be a multiple of " "4). Writing 0/1 to one of these addresses (using sw) " "clear/sets the software interrupt bit in the the MIP (machine " "interrupt pending) CSR of the corresponding hart. If a " "software interrupt is taken, it is up to interrupt handler to " "write zero to the same location to clear the corresponding " "bit in MIP. Writing values besides 0/1 will not affect the " "MIP bit and neither will writing using sb/sh/sd or writing to " "non-multiple-of-4 addresses.") ("clint", po::value<std::string>(), "Define address, a, of memory mapped area for clint (core local " "interruptor). In an n-hart system, words at addresses a, a+4, ... " "a+(n-1)*4, are associated with the n harts. Store a 0/1 to one of " "these locations clears/sets the software interrupt bit in the MIP CSR " "of the corresponding hart. Similary, addresses b, b+8, ... b+(n-1)*8, " "where b is a+0x4000, are associated with the n harts. Writing to one " "of these double words sets the timer-limit of the corresponding hart. " "A timer interrupt in such a hart becomes pending when the timer value " "equals or exceeds the timer limit.") ("iccmrw", po::bool_switch(&args.iccmRw), "Temporary switch to make ICCM region available to ld/st isntructions.") ("quitany", po::bool_switch(&args.quitOnAnyHart), "Terminate multi-threaded run when any hart finishes (default is to wait " "for all harts.)") ("noconinput", po::bool_switch(&args.noConInput), "Do not use console IO address for input. Loads from the cosole io address " "simply return last value stored there.") ("verbose,v", po::bool_switch(&args.verbose), "Be verbose.") ("version", po::bool_switch(&args.version), "Print version."); // Define positional options. po::positional_options_description pdesc; pdesc.add("target", -1); // Parse command line options. po::variables_map varMap; po::command_line_parser parser(argc, argv); auto parsed = parser.options(desc).positional(pdesc).run(); po::store(parsed, varMap); po::notify(varMap); // auto unparsed = po::collect_unrecognized(parsed.options, po::include_positional); if (args.version) printVersion(); if (args.help) { std::cout << "Simulate a RISCV system running the program specified by the given ELF\n" "and/or HEX file. With --newlib/--linux, the ELF file is a newlib/linux linked\n" "program and may be followed by corresponding command line arguments.\n" "All numeric arguments are interpreted as hexadecimal numbers when prefixed" " with 0x." "Examples:\n" " whisper --target prog --log\n" " whisper --target prog --setreg sp=0xffffff00\n" " whisper --newlib --log --target \"prog -x -y\"\n" " whisper --linux --log --targetsep ':' --target \"prog:-x:-y\"\n\n"; std::cout << desc; return true; } if (not collectCommandLineValues(varMap, args)) return false; } catch (std::exception& exp) { std::cerr << "Failed to parse command line args: " << exp.what() << '\n'; return false; } return true; } /// Apply register initializations specified on the command line. template<typename URV> static bool applyCmdLineRegInit(const Args& args, Hart<URV>& hart) { bool ok = true; URV hartId = hart.sysHartIndex(); for (const auto& regInit : args.regInits) { // Each register initialization is a string of the form reg=val // or hart:reg=val std::vector<std::string> tokens; boost::split(tokens, regInit, boost::is_any_of("="), boost::token_compress_on); if (tokens.size() != 2) { std::cerr << "Invalid command line register initialization: " << regInit << '\n'; ok = false; continue; } std::string regName = tokens.at(0); const std::string& regVal = tokens.at(1); bool specificHart = false; unsigned id = 0; size_t colonIx = regName.find(':'); if (colonIx != std::string::npos) { std::string hartStr = regName.substr(0, colonIx); regName = regName.substr(colonIx + 1); if (not parseCmdLineNumber("hart", hartStr, id)) { std::cerr << "Invalid command line register initialization: " << regInit << '\n'; ok = false; continue; } specificHart = true; } URV val = 0; if (not parseCmdLineNumber("register", regVal, val)) { ok = false; continue; } if (specificHart and id != hartId) continue; if (unsigned reg = 0; hart.findIntReg(regName, reg)) { if (args.verbose) std::cerr << "Setting register " << regName << " to command line " << "value 0x" << std::hex << val << std::dec << '\n'; hart.pokeIntReg(reg, val); continue; } if (unsigned reg = 0; hart.findFpReg(regName, reg)) { if (args.verbose) std::cerr << "Setting register " << regName << " to command line " << "value 0x" << std::hex << val << std::dec << '\n'; hart.pokeFpReg(reg, val); continue; } auto csr = hart.findCsr(regName); if (csr) { if (args.verbose) std::cerr << "Setting register " << regName << " to command line " << "value 0x" << std::hex << val << std::dec << '\n'; hart.pokeCsr(csr->getNumber(), val); continue; } std::cerr << "No such RISCV register: " << regName << '\n'; ok = false; } return ok; } template<typename URV> static bool applyZisaStrings(const std::vector<std::string>& zisa, Hart<URV>& hart) { unsigned errors = 0; for (const auto& ext : zisa) { if (ext == "zba" or ext == "ba") hart.enableRvzba(true); else if (ext == "zbb" or ext == "bb") hart.enableRvzbb(true); else if (ext == "zbc" or ext == "bc") hart.enableRvzbc(true); else if (ext == "zbe" or ext == "be") hart.enableRvzbe(true); else if (ext == "zbf" or ext == "bf") hart.enableRvzbf(true); else if (ext == "zbm" or ext == "bm") hart.enableRvzbm(true); else if (ext == "zbp" or ext == "bp") hart.enableRvzbp(true); else if (ext == "zbr" or ext == "br") hart.enableRvzbr(true); else if (ext == "zbs" or ext == "bs") hart.enableRvzbs(true); else if (ext == "zbt" or ext == "bt") hart.enableRvzbt(true); else if (ext == "zbmini" or ext == "bmini") { hart.enableRvzbb(true); hart.enableRvzbs(true); std::cerr << "ISA option zbmini is deprecated. Using zbb and zbs.\n"; } else { std::cerr << "No such Z extension: " << ext << '\n'; errors++; } } return errors == 0; } template<typename URV> static bool applyIsaString(const std::string& isaStr, Hart<URV>& hart) { URV isa = 0; unsigned errors = 0; for (auto c : isaStr) { switch(c) { case 'a': case 'c': case 'd': case 'e': case 'f': case 'i': case 'm': case 's': case 'u': case 'v': isa |= URV(1) << (c - 'a'); break; case 'g': // Enable a, d, f, and m isa |= 0x1 | 0x8 | 0x20 | 0x1000; break; default: std::cerr << "Extension \"" << c << "\" is not supported.\n"; errors++; break; } } if (not (isa & (URV(1) << ('i' - 'a')))) { std::cerr << "Extension \"i\" implicitly enabled\n"; isa |= URV(1) << ('i' - 'a'); } if (isa & (URV(1) << ('d' - 'a'))) if (not (isa & (URV(1) << ('f' - 'a')))) { std::cerr << "Extension \"d\" requires \"f\" -- Enabling \"f\"\n"; isa |= URV(1) << ('f' - 'a'); } // Set the xlen bits: 1 for 32-bits and 2 for 64. URV xlen = sizeof(URV) == 4? 1 : 2; isa |= xlen << (8*sizeof(URV) - 2); bool resetMemoryMappedRegs = false; URV mask = 0, pokeMask = 0; bool implemented = true, isDebug = false, shared = true; if (not hart.configCsr("misa", implemented, isa, mask, pokeMask, isDebug, shared)) { std::cerr << "Failed to configure MISA CSR\n"; errors++; } else hart.reset(resetMemoryMappedRegs); // Apply effects of new misa value. return errors == 0; } /// Enable linux or newlib based on the symbols in the ELF files. /// Return true if either is enabled. template<typename URV> static bool enableNewlibOrLinuxFromElf(const Args& args, Hart<URV>& hart) { bool newlib = args.newlib, linux = args.linux; if (args.raw) { if (newlib or linux) std::cerr << "Raw mode not comptible with newlib/linux. Sticking" << " with raw mode.\n"; return false; } if (linux or newlib) ; // Emulation preference already set by user. else { // At this point ELF files have not been loaded: Cannot use // hart.findElfSymbol. for (auto target : args.expandedTargets) { auto elfPath = target.at(0); if (not linux) linux = Memory::isSymbolInElfFile(elfPath, "__libc_csu_init"); if (not newlib) newlib = Memory::isSymbolInElfFile(elfPath, "__call_exitprocs"); } if (args.verbose and linux) std::cerr << "Deteced linux symbol in ELF\n"; if (args.verbose and newlib) std::cerr << "Deteced newlib symbol in ELF\n"; if (newlib and linux) { std::cerr << "Fishy: Both newlib and linux symbols present in " << "ELF file(s). Doing linux emulation.\n"; newlib = false; } } hart.enableNewlib(newlib); hart.enableLinux(linux); return newlib or linux; } /// Set stack pointer to a reasonable value for linux/newlib. template<typename URV> static void sanitizeStackPointer(Hart<URV>& hart, bool verbose) { // Set stack pointer to the 128 bytes below end of memory. size_t memSize = hart.getMemorySize(); if (memSize > 128) { size_t spValue = memSize - 128; if (verbose) std::cerr << "Setting stack pointer to 0x" << std::hex << spValue << std::dec << " for newlib/linux\n"; hart.pokeIntReg(IntRegNumber::RegSp, spValue); } } /// Load register and memory state from snapshot previously saved /// in the given directory. Return true on success and false on /// failure. template <typename URV> static bool loadSnapshot(Hart<URV>& hart, const std::string& snapDir) { using std::cerr; if (not FileSystem::is_directory(snapDir)) { cerr << "Error: Path is not a snapshot directory: " << snapDir << '\n'; return false; } FileSystem::path path(snapDir); FileSystem::path regPath = path / "registers"; if (not FileSystem::is_regular_file(regPath)) { cerr << "Error: Snapshot file does not exists: " << regPath << '\n'; return false; } FileSystem::path memPath = path / "memory"; if (not FileSystem::is_regular_file(regPath)) { cerr << "Error: Snapshot file does not exists: " << memPath << '\n'; return false; } if (not hart.loadSnapshot(path)) { cerr << "Error: Failed to load sanpshot from dir " << snapDir << '\n'; return false; } return true; } template<typename URV> static void configureClint(Hart<URV>& hart, System<URV>& system, uint64_t clintStart, uint64_t clintLimit, uint64_t timerAddr) { // Define callback to associate a memory mapped software interrupt // location to its corresponding hart so that when such a location // is written the software interrupt bit is set/cleared in the MIP // register of that hart. uint64_t swAddr = clintStart; auto swAddrToHart = [swAddr, &system](URV addr) -> Hart<URV>* { uint64_t addr2 = swAddr + system.hartCount()*4; // 1 word per hart if (addr >= swAddr and addr < addr2) { size_t ix = (addr - swAddr) / 4; return system.ithHart(ix).get(); } return nullptr; }; // Same for timer limit addresses. auto timerAddrToHart = [timerAddr, &system](URV addr) -> Hart<URV>* { uint64_t addr2 = timerAddr + system.hartCount()*8; // 1 double word per hart if (addr >= timerAddr and addr < addr2) { size_t ix = (addr - timerAddr) / 8; return system.ithHart(ix).get(); } return nullptr; }; hart.configClint(clintStart, clintLimit, swAddrToHart, timerAddrToHart); } static bool getElfFilesIsaString(const Args& args, std::string& isaString) { std::vector<std::string> archTags; unsigned errors = 0; for (const auto& target : args.expandedTargets) { const auto& elfFile = target.front(); if (not Memory::collectElfRiscvTags(elfFile, archTags)) errors++; } std::unordered_set<char> isaChars; for (const auto& tag : archTags) { if (args.verbose) std::cerr << "Collecting ISA string from ELF file tag: " << tag << '\n'; // Example tag: rv32i2p0_m2p0_a2p0_f2p0_d2p0_c2p0 std::vector<std::string> extensions; boost::split(extensions, tag, boost::is_any_of("_")); for (size_t i = 1; i < extensions.size(); ++i) { const auto& ext = extensions.at(i); if (not ext.empty()) { char cc = ext.front(); isaChars.insert(cc); } } } for (auto cc : isaChars) isaString.push_back(cc); if (args.verbose) std::cerr << "ISA string from ELF file(s): " << isaString << '\n'; return errors == 0; } /// Apply command line arguments: Load ELF and HEX files, set /// start/end/tohost. Return true on success and false on failure. template<typename URV> static bool applyCmdLineArgs(const Args& args, Hart<URV>& hart, System<URV>& system) { unsigned errors = 0; std::string isa = args.isa; // Handle linux/newlib adjusting stack if needed. bool clib = enableNewlibOrLinuxFromElf(args, hart); // TBD: Do this once. Do not do it for each hart. if (isa.empty() and args.elfisa) if (not getElfFilesIsaString(args, isa)) errors++; if (clib and isa.empty() and not args.raw) { if (args.verbose) std::cerr << "Enabling a/c/m/f/d extensions for newlib/linux\n"; isa = "icmafd"; } if (not isa.empty()) if (not applyIsaString(isa, hart)) errors++; if (not applyZisaStrings(args.zisa, hart)) errors++; if (clib) // Linux or newlib enabled. sanitizeStackPointer(hart, args.verbose); if (args.toHostSym) hart.setTohostSymbol(*args.toHostSym); if (args.consoleIoSym) hart.setConsoleIoSymbol(*args.consoleIoSym); // Load ELF files. for (const auto& target : args.expandedTargets) { const auto& elfFile = target.front(); if (args.verbose) std::cerr << "Loading ELF file " << elfFile << '\n'; size_t entryPoint = 0; if (hart.loadElfFile(elfFile, entryPoint)) hart.pokePc(URV(entryPoint)); else errors++; } // Load HEX files. for (const auto& hexFile : args.hexFiles) { if (args.verbose) std::cerr << "Loading HEX file " << hexFile << '\n'; if (not hart.loadHexFile(hexFile)) errors++; } if (not args.instFreqFile.empty()) hart.enableInstructionFrequency(true); if (not args.loadFrom.empty()) if (not loadSnapshot(hart, args.loadFrom)) errors++; if (not args.stdoutFile.empty()) if (not hart.redirectOutputDescriptor(STDOUT_FILENO, args.stdoutFile)) errors++; if (not args.stderrFile.empty()) if (not hart.redirectOutputDescriptor(STDERR_FILENO, args.stderrFile)) errors++; // Command line to-host overrides that of ELF and config file. if (args.toHost) hart.setToHostAddress(*args.toHost); // Command-line entry point overrides that of ELF. if (args.startPc) hart.pokePc(URV(*args.startPc)); // Command-line exit point overrides that of ELF. if (args.endPc) hart.setStopAddress(URV(*args.endPc)); // Command-line console io address overrides config file. if (args.consoleIo) hart.setConsoleIo(URV(*args.consoleIo)); hart.enableConsoleInput(! args.noConInput); if (args.clint and args.swInterrupt) std::cerr << "Ignoring --sontinterrupt: incompatible with --clint.\n"; if (args.clint) { uint64_t swAddr = *args.clint; uint64_t timerAddr = swAddr + 0x4000; uint64_t clintLimit = swAddr + 0x40000000 - 1; configureClint(hart, system, swAddr, clintLimit, timerAddr); } else if (args.swInterrupt) { uint64_t swAddr = *args.swInterrupt; uint64_t timerAddr = swAddr + 0x4000; uint64_t clintLimit = swAddr + system.hartCount() * 4 - 1; configureClint(hart, system, swAddr, clintLimit, timerAddr); } // Set instruction count limit. if (args.instCountLim) hart.setInstructionCountLimit(*args.instCountLim); // Print load-instruction data-address when tracing instructions. hart.setTraceLoadStore(args.traceLdSt); // Setup periodic external interrupts. if (args.alarmInterval) { // Convert from micro-seconds to processor ticks. Assume a 1 // ghz-processor. uint64_t ticks = (*args.alarmInterval)*1000; hart.setupPeriodicTimerInterrupts(ticks); } hart.enableTriggers(args.triggers); hart.enableGdb(args.gdb); if (args.gdbTcpPort.size()>hart.sysHartIndex()) hart.setGdbTcpPort(args.gdbTcpPort[hart.sysHartIndex()]); hart.enablePerformanceCounters(args.counters); hart.enableAbiNames(args.abiNames); if (args.fastExt) hart.enableFastInterrupts(args.fastExt); // Apply register initialization. if (not applyCmdLineRegInit(args, hart)) errors++; if (args.expandedTargets.empty()) return errors == 0; // Setup target program arguments. if (clib) { if (args.loadFrom.empty()) if (not hart.setTargetProgramArgs(args.expandedTargets.front())) { size_t memSize = hart.memorySize(); size_t suggestedStack = memSize - 4; std::cerr << "Failed to setup target program arguments -- stack " << "is not writable\n" << "Try using --setreg sp=<val> to set the stack pointer " << "to a\nwritable region of memory (e.g. --setreg " << "sp=0x" << std::hex << suggestedStack << '\n' << std::dec; errors++; } } else if (args.expandedTargets.front().size() > 1) { std::cerr << "Warning: Target program options present which requires\n" << " the use of --newlib/--linux. Options ignored.\n"; } return errors == 0; } /// Open a server socket and put opened socket information (hostname /// and port number) in the given server file. Wait for one /// connection. Service connection. Return true on success and false /// on failure. template <typename URV> static bool runServer(System<URV>& system, const std::string& serverFile, FILE* traceFile, FILE* commandLog) { char hostName[1024]; if (gethostname(hostName, sizeof(hostName)) != 0) { std::cerr << "Failed to obtain name of this computer\n"; return false; } int soc = socket(AF_INET, SOCK_STREAM, 0); if (soc < 0) { char buffer[512]; char* p = buffer; #if defined __APPLE__ || defined __EMSCRIPTEN__ strerror_r(errno, buffer, 512); #else p = strerror_r(errno, buffer, 512); #endif std::cerr << "Failed to create socket: " << p << '\n'; return -1; } sockaddr_in serverAddr; memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); serverAddr.sin_port = htons(0); if (bind(soc, (sockaddr*) &serverAddr, sizeof(serverAddr)) < 0) { perror("Socket bind failed"); return false; } if (listen(soc, 1) < 0) { perror("Socket listen failed"); return false; } sockaddr_in socAddr; socklen_t socAddrSize = sizeof(socAddr); socAddr.sin_family = AF_INET; socAddr.sin_port = 0; if (getsockname(soc, (sockaddr*) &socAddr, &socAddrSize) == -1) { perror("Failed to obtain socket information"); return false; } { std::ofstream out(serverFile); if (not out.good()) { std::cerr << "Failed to open file '" << serverFile << "' for output\n"; return false; } out << hostName << ' ' << ntohs(socAddr.sin_port) << std::endl; } sockaddr_in clientAddr; socklen_t clientAddrSize = sizeof(clientAddr); int newSoc = accept(soc, (sockaddr*) & clientAddr, &clientAddrSize); if (newSoc < 0) { perror("Socket accept failed"); return false; } bool ok = true; try { Server<URV> server(system); ok = server.interact(newSoc, traceFile, commandLog); } catch(...) { ok = false; } close(newSoc); close(soc); return ok; } template <typename URV> static bool reportInstructionFrequency(Hart<URV>& hart, const std::string& outPath) { FILE* outFile = fopen(outPath.c_str(), "w"); if (not outFile) { std::cerr << "Failed to open instruction frequency file '" << outPath << "' for output.\n"; return false; } hart.reportInstructionFrequency(outFile); hart.reportTrapStat(outFile); fprintf(outFile, "\n"); hart.reportPmpStat(outFile); fprintf(outFile, "\n"); hart.reportLrScStat(outFile); fclose(outFile); return true; } /// Open the trace-file, command-log and console-output files /// specified on the command line. Return true if successful or false /// if any specified file fails to open. static bool openUserFiles(const Args& args, FILE*& traceFile, FILE*& commandLog, FILE*& consoleOut) { if (not args.traceFile.empty()) { traceFile = fopen(args.traceFile.c_str(), "w"); if (not traceFile) { std::cerr << "Failed to open trace file '" << args.traceFile << "' for output\n"; return false; } } if (args.trace and traceFile == NULL) traceFile = stdout; if (traceFile) setlinebuf(traceFile); // Make line-buffered. if (not args.commandLogFile.empty()) { commandLog = fopen(args.commandLogFile.c_str(), "w"); if (not commandLog) { std::cerr << "Failed to open command log file '" << args.commandLogFile << "' for output\n"; return false; } setlinebuf(commandLog); // Make line-buffered. } if (not args.consoleOutFile.empty()) { consoleOut = fopen(args.consoleOutFile.c_str(), "w"); if (not consoleOut) { std::cerr << "Failed to open console output file '" << args.consoleOutFile << "' for output\n"; return false; } } return true; } /// Counterpart to openUserFiles: Close any open user file. static void closeUserFiles(FILE*& traceFile, FILE*& commandLog, FILE*& consoleOut) { if (consoleOut and consoleOut != stdout) fclose(consoleOut); consoleOut = nullptr; if (traceFile and traceFile != stdout) fclose(traceFile); traceFile = nullptr; if (commandLog and commandLog != stdout) fclose(commandLog); commandLog = nullptr; } // In interactive mode, keyboard interrupts (typically control-c) are // ignored. static void kbdInterruptHandler(int) { std::cerr << "keyboard interrupt\n"; } template <typename URV> static bool batchRun(System<URV>& system, FILE* traceFile, bool waitAll) { if (system.hartCount() == 0) return true; if (system.hartCount() == 1) { auto& hart = *system.ithHart(0); bool ok = hart.run(traceFile); #ifdef FAST_SLOPPY hart.reportOpenedFiles(std::cout); #endif return ok; } // Run each hart in its own thread. std::vector<std::thread> threadVec; std::atomic<bool> result = true; std::atomic<unsigned> finished = 0; // Count of finished threads. std::atomic<bool> hart0Done = false; auto threadFunc = [&traceFile, &result, &finished, &hart0Done] (Hart<URV>* hart) { // In multi-hart system, wait till hart is started by hart0. while (not hart->isStarted()) if (hart0Done) return; // We are not going to be started. bool r = hart->run(traceFile); result = result and r; finished++; if (hart->sysHartIndex() == 0) hart0Done = true; }; for (unsigned i = 0; i < system.hartCount(); ++i) { Hart<URV>* hart = system.ithHart(i).get(); threadVec.emplace_back(std::thread(threadFunc, hart)); } if (waitAll) { for (auto& t : threadVec) t.join(); } else { // First thread to finish terminates run. while (finished == 0) ; extern void forceUserStop(int); forceUserStop(0); for (auto& t : threadVec) t.join(); } return result; } /// Run producing a snapshot after each snapPeriod instructions. Each /// snapshot goes into its own directory names <dir><n> where <dir> is /// the string in snapDir and <n> is a sequential integer starting at /// 0. Return true on success and false on failure. template <typename URV> static bool snapshotRun(System<URV>& system, FILE* traceFile, const std::string& snapDir, uint64_t snapPeriod) { if (not snapPeriod) { std::cerr << "Warning: Zero snap period ignored.\n"; return batchRun(system, traceFile, true /* waitAll */); } assert(system.hartCount() == 1); Hart<URV>& hart = *(system.ithHart(0)); bool done = false; uint64_t globalLimit = hart.getInstructionCountLimit(); while (not done) { uint64_t nextLimit = hart.getInstructionCount() + snapPeriod; if (nextLimit >= globalLimit) done = true; nextLimit = std::min(nextLimit, globalLimit); hart.setInstructionCountLimit(nextLimit); hart.run(traceFile); if (hart.hasTargetProgramFinished()) done = true; if (not done) { unsigned index = hart.snapshotIndex(); FileSystem::path path(snapDir + std::to_string(index)); if (not FileSystem::is_directory(path)) if (not FileSystem::create_directories(path)) { std::cerr << "Error: Failed to create snapshot directory " << path << '\n'; return false; } hart.setSnapshotIndex(index + 1); if (not hart.saveSnapshot(path)) { std::cerr << "Error: Failed to save a snapshot\n"; return false; } } } #ifdef FAST_SLOPPY hart.reportOpenedFiles(std::cout); #endif return true; } /// Depending on command line args, start a server, run in interactive /// mode, or initiate a batch run. template <typename URV> static bool sessionRun(System<URV>& system, const Args& args, FILE* traceFile, FILE* cmdLog) { for (unsigned i = 0; i < system.hartCount(); ++i) if (not applyCmdLineArgs(args, *system.ithHart(i), system)) if (not args.interactive) return false; // In server/interactive modes: enable triggers and performance counters. bool serverMode = not args.serverFile.empty(); if (serverMode or args.interactive) { for (unsigned i = 0; i < system.hartCount(); ++i) { auto& hart = *system.ithHart(i); hart.enableTriggers(true); hart.enablePerformanceCounters(true); } } else { // Load error rollback is an annoyance if not in server/interactive mode for (unsigned i = 0; i < system.hartCount(); ++i) { auto& hart = *system.ithHart(i); hart.enableLoadErrorRollback(false); hart.enableBenchLoadExceptions(false); } } if (serverMode) return runServer(system, args.serverFile, traceFile, cmdLog); if (args.interactive) { // Ignore keyboard interrupt for most commands. Long running // commands will enable keyboard interrupts while they run. #ifdef __MINGW64__ signal(SIGINT, kbdInterruptHandler); #else struct sigaction newAction; sigemptyset(&newAction.sa_mask); newAction.sa_flags = 0; newAction.sa_handler = kbdInterruptHandler; sigaction(SIGINT, &newAction, nullptr); #endif Interactive interactive(system); return interactive.interact(traceFile, cmdLog); } if (args.snapshotPeriod and *args.snapshotPeriod) { uint64_t period = *args.snapshotPeriod; std::string dir = args.snapshotDir; if (system.hartCount() == 1) return snapshotRun(system, traceFile, dir, period); std::cerr << "Warning: Snapshots not supported for multi-thread runs\n"; } bool waitAll = not args.quitOnAnyHart; return batchRun(system, traceFile, waitAll); } /// Santize memory parameters. Page/region sizes must be greater and /// equal to 4 and must be powers of 2. /// Region size must be a multiple of page size. /// Memory size must be a multiple of region size. /// Return true if given parameters are good. False if any parameters /// is changed to meet expectation. static bool checkAndRepairMemoryParams(size_t& memSize, size_t& pageSize, size_t& regionSize) { bool ok = true; unsigned logPageSize = static_cast<unsigned>(std::log2(pageSize)); size_t p2PageSize = size_t(1) << logPageSize; if (p2PageSize != pageSize) { std::cerr << "Memory page size (0x" << std::hex << pageSize << ") " << "is not a power of 2 -- using 0x" << p2PageSize << '\n' << std::dec; pageSize = p2PageSize; ok = false; } if (pageSize < 64) { std::cerr << "Page size (" << pageSize << ") is less than 64. Using 64.\n"; pageSize = 64; ok = false; } size_t logRegionSize = static_cast<size_t>(std::log2(regionSize)); size_t p2RegionSize = size_t(1) << logRegionSize; if (p2RegionSize != regionSize) { std::cerr << "Memory region size (0x" << std::hex << regionSize << ") " << "is not a power of 2 -- using 0x" << p2RegionSize << '\n' << std::dec; regionSize = p2RegionSize; ok = false; } if (regionSize < pageSize) { std::cerr << "Memory region size (0x" << std::hex << regionSize << ") " << "smaller than page size (0x" << pageSize << ") -- " << "using page size\n" << std::dec; regionSize = pageSize; ok = false; } size_t pagesInRegion = regionSize / pageSize; size_t multiple = pagesInRegion * pageSize; if (multiple != regionSize) { std::cerr << "Memory region size (0x" << std::hex << regionSize << ") " << "is not a multiple of page size (0x" << pageSize << ") -- " << "using 0x" << multiple << " as region size\n" << std::dec; regionSize = multiple; ok = false; } if (memSize < pageSize) { std::cerr << "Memory size (0x" << std::hex << memSize << ") " << "smaller than page size (0x" << pageSize << ") -- " << "using 0x" << pageSize << " as memory size\n" << std::dec; memSize = pageSize; ok = false; } size_t pageCount = memSize / pageSize; if (pageCount * pageSize != memSize) { pageCount++; size_t newSize = pageCount * pageSize; std::cerr << "Memory size (0x" << std::hex << memSize << ") is not a " << "multiple of page size (0x" << pageSize << ") -- " << "using 0x" << newSize << '\n' << std::dec; memSize = newSize; ok = false; } return ok; } static bool getPrimaryConfigParameters(const Args& args, const HartConfig& config, unsigned& hartsPerCore, unsigned& coreCount, size_t& pageSize, size_t& memorySize) { config.getHartsPerCore(hartsPerCore); if (args.hasHarts) hartsPerCore = args.harts; if (hartsPerCore == 0 or hartsPerCore > 16) { std::cerr << "Unsupported hart count: " << hartsPerCore; std::cerr << " (1 to 16 currently suppored)\n"; return false; } config.getCoreCount(coreCount); if (args.hasCores) coreCount = args.cores; if (coreCount == 0 or coreCount > 16) { std::cerr << "Unsupported core count: " << coreCount; std::cerr << " (1 to 16 currently suppored)\n"; return false; } // Determine simulated memory size. Default to 4 gigs. // If running a 32-bit machine (pointer size = 32 bits), try 2 gigs. memorySize = size_t(1) << 27; // 2 gigs if (memorySize == 0) memorySize = size_t(1) << 31; // 2 gigs config.getMemorySize(memorySize); if (args.memorySize) memorySize = *args.memorySize; if (not config.getPageSize(pageSize)) pageSize = args.pageSize; return true; } template <typename URV> static bool session(const Args& args, const HartConfig& config) { // Collect primary configuration paramters. unsigned hartsPerCore = 1; unsigned coreCount = 1; size_t pageSize = 4*1024; size_t regionSize = 256*1024*1024; size_t memorySize = size_t(1) << 27; // 4 gigs if (not getPrimaryConfigParameters(args, config, hartsPerCore, coreCount, pageSize, memorySize)) return false; checkAndRepairMemoryParams(memorySize, pageSize, regionSize); // Create cores & harts. System<URV> system(coreCount, hartsPerCore, memorySize, pageSize); assert(system.hartCount() == coreCount*hartsPerCore); assert(system.hartCount() > 0); // Configure harts. Define callbacks for non-standard CSRs. if (not config.configHarts(system, args.isa, args.verbose)) if (not args.interactive) return false; // Configure memory. if (not config.configMemory(system, args.iccmRw, args.unmappedElfOk, args.verbose)) return false; if (args.hexFiles.empty() and args.expandedTargets.empty() and not args.interactive) { std::cerr << "No program file specified.\n"; return false; } FILE* traceFile = nullptr; FILE* commandLog = nullptr; FILE* consoleOut = stdout; if (not openUserFiles(args, traceFile, commandLog, consoleOut)) return false; for (unsigned i = 0; i < system.hartCount(); ++i) { auto& hart = *system.ithHart(i); hart.setConsoleOutput(consoleOut); hart.reset(); } bool result = sessionRun(system, args, traceFile, commandLog); auto& hart0 = *system.ithHart(0); if (not args.instFreqFile.empty()) result = reportInstructionFrequency(hart0, args.instFreqFile) and result; closeUserFiles(traceFile, commandLog, consoleOut); return result; } /// Determine regiser width (xlen) from ELF file. Return true if /// successful and false otherwise (xlen is left unmodified). static bool getXlenFromElfFile(const Args& args, unsigned& xlen) { if (args.expandedTargets.empty()) return false; // Get the length from the first target. auto& elfPath = args.expandedTargets.front().front(); bool is32 = false, is64 = false, isRiscv = false; if (not Memory::checkElfFile(elfPath, is32, is64, isRiscv)) return false; // ELF does not exist. if (not is32 and not is64) return false; if (is32 and is64) { std::cerr << "Error: ELF file '" << elfPath << "' has both" << " 32 and 64-bit calss\n"; return false; } if (is32) xlen = 32; else xlen = 64; if (args.verbose) std::cerr << "Setting xlen to " << xlen << " based on ELF file " << elfPath << '\n'; return true; } /// Obtain integer-register width (xlen). Command line has top /// priority, then config file, then ELF file. static unsigned determineRegisterWidth(const Args& args, const HartConfig& config) { unsigned width = 32; if (args.hasRegWidth) width = args.regWidth; else if (not config.getXlen(width)) getXlenFromElfFile(args, width); return width; } int main(int argc, char* argv[]) { Args args; if (not parseCmdLineArgs(argc, argv, args)) return 1; if (args.help) return 0; // Expand each target program string into program name and args. args.expandTargets(); // Load configuration file. HartConfig config; if (not args.configFile.empty()) if (not config.loadConfigFile(args.configFile)) return 1; unsigned regWidth = determineRegisterWidth(args, config); bool ok = true; try { if (regWidth == 32) ok = session<uint32_t>(args, config); else if (regWidth == 64) ok = session<uint64_t>(args, config); else { std::cerr << "Invalid register width: " << regWidth; std::cerr << " -- expecting 32 or 64\n"; ok = false; } } catch (std::exception& e) { std::cerr << e.what() << '\n'; ok = false; } return ok? 0 : 1; }
29.204336
93
0.631899
antoniocgj
b8b522d550177a88f5383968ad588a1fa93756c5
231
cpp
C++
regression/esbmc-cpp/cpp/cstring2_strcat/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
143
2015-06-22T12:30:01.000Z
2022-03-21T08:41:17.000Z
regression/esbmc-cpp/cpp/cstring2_strcat/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
542
2017-06-02T13:46:26.000Z
2022-03-31T16:35:17.000Z
regression/esbmc-cpp/cpp/cstring2_strcat/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
81
2015-10-21T22:21:59.000Z
2022-03-24T14:07:55.000Z
/* strcat example */ #include <iostream> #include <cstring> int main () { char str[80] = "these "; strcat (str,"strings "); strcat (str,"are "); strcat (str,"concatenated."); std::cout << str << std::endl; return 0; }
16.5
32
0.588745
shmarovfedor
b8b5c6461ad487696649f6c3519c58532a2cc0eb
2,403
hpp
C++
src/mixer/linear_mixer.hpp
mtaillefumier/SIRIUS
50ec1c202c019113c5660f1966b170dec9dfd4d4
[ "BSD-2-Clause" ]
77
2016-03-18T08:38:30.000Z
2022-03-11T14:06:25.000Z
src/mixer/linear_mixer.hpp
simonpintarelli/SIRIUS
f4b5c4810af2a3ea1e67992d65750535227da84b
[ "BSD-2-Clause" ]
240
2016-04-12T16:39:11.000Z
2022-03-31T08:46:12.000Z
src/mixer/linear_mixer.hpp
simonpintarelli/SIRIUS
f4b5c4810af2a3ea1e67992d65750535227da84b
[ "BSD-2-Clause" ]
43
2016-03-18T17:45:07.000Z
2022-02-28T05:27:59.000Z
// Copyright (c) 2013-2019 Simon Frasch, Anton Kozhevnikov, Thomas Schulthess // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that // the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the // following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions // and the following disclaimer in the documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** \file linear_mixer.hpp * * \brief Contains definition and implementation of sirius::Linear_mixer. */ #ifndef __LINEAR_MIXER_HPP__ #define __LINEAR_MIXER_HPP__ #include <tuple> #include <functional> #include <utility> #include <vector> #include <limits> #include <memory> #include <exception> #include <cmath> #include <numeric> #include "mixer/mixer.hpp" namespace sirius { namespace mixer { template <typename... FUNCS> class Linear : public Mixer<FUNCS...> { public: explicit Linear(double beta) : Mixer<FUNCS...>(2) , beta_(beta) { } void mix_impl() override { const auto idx = this->idx_hist(this->step_ + 1); this->copy(this->input_, this->output_history_[idx]); this->scale(beta_, this->output_history_[idx]); this->axpy(1.0 - beta_, this->output_history_[this->idx_hist(this->step_)], this->output_history_[idx]); } private: double beta_; }; } // namespace mixer } // namespace sirius #endif // __MIXER_HPP__
35.338235
116
0.734082
mtaillefumier
b8b6c1fab394ec3603dfc4497723e360eef7ed16
19,515
cpp
C++
src/dawn_native/vulkan/VulkanInfo.cpp
dcerisano/dawn-ray-tracing-linux
984b4cd0ca2886009a70c22d38cc656cbc565e67
[ "Apache-2.0" ]
null
null
null
src/dawn_native/vulkan/VulkanInfo.cpp
dcerisano/dawn-ray-tracing-linux
984b4cd0ca2886009a70c22d38cc656cbc565e67
[ "Apache-2.0" ]
null
null
null
src/dawn_native/vulkan/VulkanInfo.cpp
dcerisano/dawn-ray-tracing-linux
984b4cd0ca2886009a70c22d38cc656cbc565e67
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 The Dawn 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 "dawn_native/vulkan/VulkanInfo.h" #include "dawn_native/vulkan/AdapterVk.h" #include "dawn_native/vulkan/BackendVk.h" #include "dawn_native/vulkan/VulkanError.h" #include <cstring> namespace dawn_native { namespace vulkan { namespace { bool IsLayerName(const VkLayerProperties& layer, const char* name) { return strncmp(layer.layerName, name, VK_MAX_EXTENSION_NAME_SIZE) == 0; } bool IsExtensionName(const VkExtensionProperties& extension, const char* name) { return strncmp(extension.extensionName, name, VK_MAX_EXTENSION_NAME_SIZE) == 0; } bool EnumerateInstanceExtensions(const char* layerName, const dawn_native::vulkan::VulkanFunctions& vkFunctions, std::vector<VkExtensionProperties>* extensions) { uint32_t count = 0; VkResult result = VkResult::WrapUnsafe( vkFunctions.EnumerateInstanceExtensionProperties(layerName, &count, nullptr)); if (result != VK_SUCCESS && result != VK_INCOMPLETE) { return false; } extensions->resize(count); result = VkResult::WrapUnsafe(vkFunctions.EnumerateInstanceExtensionProperties( layerName, &count, extensions->data())); return (result == VK_SUCCESS); } } // namespace const char kLayerNameLunargStandardValidation[] = "VK_LAYER_LUNARG_standard_validation"; const char kLayerNameLunargVKTrace[] = "VK_LAYER_LUNARG_vktrace"; const char kLayerNameRenderDocCapture[] = "VK_LAYER_RENDERDOC_Capture"; const char kLayerNameFuchsiaImagePipeSwapchain[] = "VK_LAYER_FUCHSIA_imagepipe_swapchain"; const char kExtensionNameExtDebugMarker[] = "VK_EXT_debug_marker"; const char kExtensionNameExtDebugUtils[] = "VK_EXT_debug_utils"; const char kExtensionNameExtDebugReport[] = "VK_EXT_debug_report"; const char kExtensionNameMvkMacosSurface[] = "VK_MVK_macos_surface"; const char kExtensionNameKhrExternalMemory[] = "VK_KHR_external_memory"; const char kExtensionNameKhrExternalMemoryCapabilities[] = "VK_KHR_external_memory_capabilities"; const char kExtensionNameKhrExternalMemoryFD[] = "VK_KHR_external_memory_fd"; const char kExtensionNameExtExternalMemoryDmaBuf[] = "VK_EXT_external_memory_dma_buf"; const char kExtensionNameExtImageDrmFormatModifier[] = "VK_EXT_image_drm_format_modifier"; const char kExtensionNameFuchsiaExternalMemory[] = "VK_FUCHSIA_external_memory"; const char kExtensionNameKhrExternalSemaphore[] = "VK_KHR_external_semaphore"; const char kExtensionNameKhrExternalSemaphoreCapabilities[] = "VK_KHR_external_semaphore_capabilities"; const char kExtensionNameKhrExternalSemaphoreFD[] = "VK_KHR_external_semaphore_fd"; const char kExtensionNameFuchsiaExternalSemaphore[] = "VK_FUCHSIA_external_semaphore"; const char kExtensionNameKhrGetPhysicalDeviceProperties2[] = "VK_KHR_get_physical_device_properties2"; const char kExtensionNameKhrSurface[] = "VK_KHR_surface"; const char kExtensionNameKhrSwapchain[] = "VK_KHR_swapchain"; const char kExtensionNameKhrWaylandSurface[] = "VK_KHR_wayland_surface"; const char kExtensionNameKhrWin32Surface[] = "VK_KHR_win32_surface"; const char kExtensionNameKhrXcbSurface[] = "VK_KHR_xcb_surface"; const char kExtensionNameKhrXlibSurface[] = "VK_KHR_xlib_surface"; const char kExtensionNameFuchsiaImagePipeSurface[] = "VK_FUCHSIA_imagepipe_surface"; const char kExtensionNameKhrMaintenance1[] = "VK_KHR_maintenance1"; const char kExtensionNameNvRayTracing[] = "VK_NV_ray_tracing"; const char kExtensionNameKhrGetMemoryRequirements2[] = "VK_KHR_get_memory_requirements2"; ResultOrError<VulkanGlobalInfo> GatherGlobalInfo(const Backend& backend) { VulkanGlobalInfo info = {}; const VulkanFunctions& vkFunctions = backend.GetFunctions(); // Gather the info about the instance layers { uint32_t count = 0; VkResult result = VkResult::WrapUnsafe(vkFunctions.EnumerateInstanceLayerProperties(&count, nullptr)); // From the Vulkan spec result should be success if there are 0 layers, // incomplete otherwise. This means that both values represent a success. // This is the same for all Enumarte functions if (result != VK_SUCCESS && result != VK_INCOMPLETE) { return DAWN_DEVICE_LOST_ERROR("vkEnumerateInstanceLayerProperties"); } info.layers.resize(count); DAWN_TRY(CheckVkSuccess( vkFunctions.EnumerateInstanceLayerProperties(&count, info.layers.data()), "vkEnumerateInstanceLayerProperties")); for (const auto& layer : info.layers) { if (IsLayerName(layer, kLayerNameLunargStandardValidation)) { info.standardValidation = true; } if (IsLayerName(layer, kLayerNameLunargVKTrace)) { info.vktrace = true; } if (IsLayerName(layer, kLayerNameRenderDocCapture)) { info.renderDocCapture = true; } // Technical note: Fuchsia implements the swapchain through // a layer (VK_LAYER_FUCHSIA_image_pipe_swapchain), which adds // an instance extensions (VK_FUCHSIA_image_surface) to all ICDs. if (IsLayerName(layer, kLayerNameFuchsiaImagePipeSwapchain)) { info.fuchsiaImagePipeSwapchain = true; } } } // Gather the info about the instance extensions { if (!EnumerateInstanceExtensions(nullptr, vkFunctions, &info.extensions)) { return DAWN_DEVICE_LOST_ERROR("vkEnumerateInstanceExtensionProperties"); } for (const auto& extension : info.extensions) { if (IsExtensionName(extension, kExtensionNameExtDebugUtils)) { info.debugUtils = true; } if (IsExtensionName(extension, kExtensionNameExtDebugReport)) { info.debugReport = true; } if (IsExtensionName(extension, kExtensionNameMvkMacosSurface)) { info.macosSurface = true; } if (IsExtensionName(extension, kExtensionNameKhrExternalMemoryCapabilities)) { info.externalMemoryCapabilities = true; } if (IsExtensionName(extension, kExtensionNameKhrExternalSemaphoreCapabilities)) { info.externalSemaphoreCapabilities = true; } if (IsExtensionName(extension, kExtensionNameKhrGetPhysicalDeviceProperties2)) { info.getPhysicalDeviceProperties2 = true; } if (IsExtensionName(extension, kExtensionNameKhrSurface)) { info.surface = true; } if (IsExtensionName(extension, kExtensionNameKhrWaylandSurface)) { info.waylandSurface = true; } if (IsExtensionName(extension, kExtensionNameKhrWin32Surface)) { info.win32Surface = true; } if (IsExtensionName(extension, kExtensionNameKhrXcbSurface)) { info.xcbSurface = true; } if (IsExtensionName(extension, kExtensionNameKhrXlibSurface)) { info.xlibSurface = true; } if (IsExtensionName(extension, kExtensionNameFuchsiaImagePipeSurface)) { info.fuchsiaImagePipeSurface = true; } } } // Specific handling for the Fuchsia swapchain surface creation extension // which is normally part of the Fuchsia-specific swapchain layer. if (info.fuchsiaImagePipeSwapchain && !info.fuchsiaImagePipeSurface) { std::vector<VkExtensionProperties> layer_extensions; if (!EnumerateInstanceExtensions(kLayerNameFuchsiaImagePipeSwapchain, vkFunctions, &layer_extensions)) { return DAWN_DEVICE_LOST_ERROR("vkEnumerateInstanceExtensionProperties"); } for (const auto& extension : layer_extensions) { if (IsExtensionName(extension, kExtensionNameFuchsiaImagePipeSurface)) { info.fuchsiaImagePipeSurface = true; // For now, copy this to the global extension list. info.extensions.push_back(extension); } } } // Gather info on available API version { uint32_t supportedAPIVersion = VK_MAKE_VERSION(1, 0, 0); if (vkFunctions.EnumerateInstanceVersion) { vkFunctions.EnumerateInstanceVersion(&supportedAPIVersion); } // Use Vulkan 1.1 if it's available. info.apiVersion = (supportedAPIVersion >= VK_MAKE_VERSION(1, 1, 0)) ? VK_MAKE_VERSION(1, 1, 0) : VK_MAKE_VERSION(1, 0, 0); } // TODO(cwallez@chromium:org): Each layer can expose additional extensions, query them? return info; } ResultOrError<std::vector<VkPhysicalDevice>> GetPhysicalDevices(const Backend& backend) { VkInstance instance = backend.GetVkInstance(); const VulkanFunctions& vkFunctions = backend.GetFunctions(); uint32_t count = 0; VkResult result = VkResult::WrapUnsafe(vkFunctions.EnumeratePhysicalDevices(instance, &count, nullptr)); if (result != VK_SUCCESS && result != VK_INCOMPLETE) { return DAWN_DEVICE_LOST_ERROR("vkEnumeratePhysicalDevices"); } std::vector<VkPhysicalDevice> physicalDevices(count); DAWN_TRY(CheckVkSuccess( vkFunctions.EnumeratePhysicalDevices(instance, &count, physicalDevices.data()), "vkEnumeratePhysicalDevices")); return physicalDevices; } ResultOrError<VulkanDeviceInfo> GatherDeviceInfo(const Adapter& adapter) { VulkanDeviceInfo info = {}; VkPhysicalDevice physicalDevice = adapter.GetPhysicalDevice(); const VulkanFunctions& vkFunctions = adapter.GetBackend()->GetFunctions(); // Gather general info about the device vkFunctions.GetPhysicalDeviceProperties(physicalDevice, &info.properties); vkFunctions.GetPhysicalDeviceFeatures(physicalDevice, &info.features); // Gather info about device memory. { VkPhysicalDeviceMemoryProperties memory; vkFunctions.GetPhysicalDeviceMemoryProperties(physicalDevice, &memory); info.memoryTypes.assign(memory.memoryTypes, memory.memoryTypes + memory.memoryTypeCount); info.memoryHeaps.assign(memory.memoryHeaps, memory.memoryHeaps + memory.memoryHeapCount); } // Gather info about device queue families { uint32_t count = 0; vkFunctions.GetPhysicalDeviceQueueFamilyProperties(physicalDevice, &count, nullptr); info.queueFamilies.resize(count); vkFunctions.GetPhysicalDeviceQueueFamilyProperties(physicalDevice, &count, info.queueFamilies.data()); } // Gather the info about the device layers { uint32_t count = 0; VkResult result = VkResult::WrapUnsafe( vkFunctions.EnumerateDeviceLayerProperties(physicalDevice, &count, nullptr)); if (result != VK_SUCCESS && result != VK_INCOMPLETE) { return DAWN_DEVICE_LOST_ERROR("vkEnumerateDeviceLayerProperties"); } info.layers.resize(count); DAWN_TRY(CheckVkSuccess(vkFunctions.EnumerateDeviceLayerProperties( physicalDevice, &count, info.layers.data()), "vkEnumerateDeviceLayerProperties")); } // Gather the info about the device extensions { uint32_t count = 0; VkResult result = VkResult::WrapUnsafe(vkFunctions.EnumerateDeviceExtensionProperties( physicalDevice, nullptr, &count, nullptr)); if (result != VK_SUCCESS && result != VK_INCOMPLETE) { return DAWN_DEVICE_LOST_ERROR("vkEnumerateDeviceExtensionProperties"); } info.extensions.resize(count); DAWN_TRY(CheckVkSuccess(vkFunctions.EnumerateDeviceExtensionProperties( physicalDevice, nullptr, &count, info.extensions.data()), "vkEnumerateDeviceExtensionProperties")); for (const auto& extension : info.extensions) { if (IsExtensionName(extension, kExtensionNameExtDebugMarker)) { info.debugMarker = true; } if (IsExtensionName(extension, kExtensionNameKhrExternalMemory)) { info.externalMemory = true; } if (IsExtensionName(extension, kExtensionNameKhrExternalMemoryFD)) { info.externalMemoryFD = true; } if (IsExtensionName(extension, kExtensionNameExtExternalMemoryDmaBuf)) { info.externalMemoryDmaBuf = true; } if (IsExtensionName(extension, kExtensionNameExtImageDrmFormatModifier)) { info.imageDrmFormatModifier = true; } if (IsExtensionName(extension, kExtensionNameFuchsiaExternalMemory)) { info.externalMemoryZirconHandle = true; } if (IsExtensionName(extension, kExtensionNameKhrExternalSemaphore)) { info.externalSemaphore = true; } if (IsExtensionName(extension, kExtensionNameKhrExternalSemaphoreFD)) { info.externalSemaphoreFD = true; } if (IsExtensionName(extension, kExtensionNameFuchsiaExternalSemaphore)) { info.externalSemaphoreZirconHandle = true; } if (IsExtensionName(extension, kExtensionNameKhrSwapchain)) { info.swapchain = true; } if (IsExtensionName(extension, kExtensionNameKhrMaintenance1)) { info.maintenance1 = true; } if (IsExtensionName(extension, kExtensionNameNvRayTracing)) { info.rayTracingNV = true; } if (IsExtensionName(extension, kExtensionNameKhrGetMemoryRequirements2)) { info.memoryRequirements2 = true; } } } // TODO(cwallez@chromium.org): gather info about formats return info; } MaybeError GatherSurfaceInfo(const Adapter& adapter, VkSurfaceKHR surface, VulkanSurfaceInfo* info) { VkPhysicalDevice physicalDevice = adapter.GetPhysicalDevice(); const VulkanFunctions& vkFunctions = adapter.GetBackend()->GetFunctions(); // Get the surface capabilities DAWN_TRY(CheckVkSuccess(vkFunctions.GetPhysicalDeviceSurfaceCapabilitiesKHR( physicalDevice, surface, &info->capabilities), "vkGetPhysicalDeviceSurfaceCapabilitiesKHR")); // Query which queue families support presenting this surface { size_t nQueueFamilies = adapter.GetDeviceInfo().queueFamilies.size(); info->supportedQueueFamilies.resize(nQueueFamilies, false); for (uint32_t i = 0; i < nQueueFamilies; ++i) { VkBool32 supported = VK_FALSE; DAWN_TRY(CheckVkSuccess(vkFunctions.GetPhysicalDeviceSurfaceSupportKHR( physicalDevice, i, surface, &supported), "vkGetPhysicalDeviceSurfaceSupportKHR")); info->supportedQueueFamilies[i] = (supported == VK_TRUE); } } // Gather supported formats { uint32_t count = 0; VkResult result = VkResult::WrapUnsafe(vkFunctions.GetPhysicalDeviceSurfaceFormatsKHR( physicalDevice, surface, &count, nullptr)); if (result != VK_SUCCESS && result != VK_INCOMPLETE) { return DAWN_DEVICE_LOST_ERROR("vkGetPhysicalDeviceSurfaceFormatsKHR"); } info->formats.resize(count); DAWN_TRY(CheckVkSuccess(vkFunctions.GetPhysicalDeviceSurfaceFormatsKHR( physicalDevice, surface, &count, info->formats.data()), "vkGetPhysicalDeviceSurfaceFormatsKHR")); } // Gather supported presents modes { uint32_t count = 0; VkResult result = VkResult::WrapUnsafe(vkFunctions.GetPhysicalDeviceSurfacePresentModesKHR( physicalDevice, surface, &count, nullptr)); if (result != VK_SUCCESS && result != VK_INCOMPLETE) { return DAWN_DEVICE_LOST_ERROR("vkGetPhysicalDeviceSurfacePresentModesKHR"); } info->presentModes.resize(count); DAWN_TRY(CheckVkSuccess(vkFunctions.GetPhysicalDeviceSurfacePresentModesKHR( physicalDevice, surface, &count, info->presentModes.data()), "vkGetPhysicalDeviceSurfacePresentModesKHR")); } return {}; } VkPhysicalDeviceRayTracingPropertiesNV GetRayTracingProperties(const Adapter& adapter) { VkPhysicalDevice physicalDevice = adapter.GetPhysicalDevice(); const VulkanFunctions& vkFunctions = adapter.GetBackend()->GetFunctions(); VkPhysicalDeviceRayTracingPropertiesNV rayTracingProperties = {}; rayTracingProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PROPERTIES_NV; VkPhysicalDeviceProperties2 deviceProperties2 = {}; deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; deviceProperties2.pNext = &rayTracingProperties; vkFunctions.GetPhysicalDeviceProperties2KHR(physicalDevice, &deviceProperties2); return rayTracingProperties; } }} // namespace dawn_native::vulkan
47.597561
100
0.625263
dcerisano
b8b7760b8a125375bf1beacb4199e993f9724aa0
4,682
hpp
C++
include/tileson_parser.hpp
SaraSmiseth/tileson
f12dfed9bc94cd94d2eb7efe7c2f940f51813b74
[ "BSD-2-Clause" ]
null
null
null
include/tileson_parser.hpp
SaraSmiseth/tileson
f12dfed9bc94cd94d2eb7efe7c2f940f51813b74
[ "BSD-2-Clause" ]
null
null
null
include/tileson_parser.hpp
SaraSmiseth/tileson
f12dfed9bc94cd94d2eb7efe7c2f940f51813b74
[ "BSD-2-Clause" ]
null
null
null
// // Created by robin on 22.03.2020. // #ifndef TILESON_TILESON_PARSER_HPP #define TILESON_TILESON_PARSER_HPP #include "common/Tools.hpp" #include "common/Base64Decompressor.hpp" #include "common/DecompressorContainer.hpp" #include "tiled/Map.hpp" #include "tiled/Project.hpp" #include "misc/MemoryStream.hpp" #include <fstream> #include <sstream> #include <memory> namespace tson { class Tileson { public: inline explicit Tileson(bool includeBase64Decoder = true); #ifndef DISABLE_CPP17_FILESYSTEM inline std::unique_ptr<tson::Map> parse(const fs::path &path); #else inline std::unique_ptr<tson::Map> parse(const std::string &path); #endif inline std::unique_ptr<tson::Map> parse(const void * data, size_t size); inline tson::DecompressorContainer *decompressors(); private: inline std::unique_ptr<tson::Map> parseJson(const nlohmann::json &json); tson::DecompressorContainer m_decompressors; }; } /*! * * @param includeBase64Decoder Includes the base64-decoder from "Base64Decompressor.hpp" if true. * Otherwise no other decompressors/decoders than whatever the user itself have added will be used. */ tson::Tileson::Tileson(bool includeBase64Decoder) { if(includeBase64Decoder) m_decompressors.add<Base64Decompressor>(); } /*! * Parses Tiled json map data by file * @param path path to file * @return parsed data as Map */ #ifndef DISABLE_CPP17_FILESYSTEM std::unique_ptr<tson::Map> tson::Tileson::parse(const fs::path &path) { if(fs::exists(path) && fs::is_regular_file(path)) { std::ifstream i(path.u8string()); nlohmann::json json; try { i >> json; } catch(const nlohmann::json::parse_error &error) { std::string message = "Parse error: "; message += std::string(error.what()); message += std::string("\n"); return std::make_unique<tson::Map>(tson::ParseStatus::ParseError, message); } return parseJson(json); } std::string msg = "File not found: "; msg += std::string(path.u8string()); return std::make_unique<tson::Map>(tson::ParseStatus::FileNotFound, msg); } #else [[deprecated("std::filesystem will be required in future versions and DISABLE_CPP17_FILESYSTEM will be removed")]] std::unique_ptr<tson::Map> tson::Tileson::parse(const std::string &path) { std::ifstream i(path); nlohmann::json json; try { i >> json; } catch(const nlohmann::json::parse_error &error) { std::string message = "Parse error: "; message += std::string(error.what()); message += std::string("\n"); return std::make_unique<tson::Map> (tson::ParseStatus::ParseError, message); } return std::move(parseJson(json)); } #endif /*! * Parses Tiled json map data by memory * @param data The data to parse * @param size The size of the data to parse * @return parsed data as Map */ std::unique_ptr<tson::Map> tson::Tileson::parse(const void *data, size_t size) { //std::istringstream i; //i.rdbuf()->pubsetbuf((char *)data, size); tson::MemoryStream mem {(uint8_t *)data, size}; nlohmann::json json; try { mem >> json; } catch (const nlohmann::json::parse_error& error) { std::string message = "Parse error: "; message += std::string(error.what()); message += std::string("\n"); return std::make_unique<tson::Map>(tson::ParseStatus::ParseError, message); } return std::move(parseJson(json)); } /*! * Common parsing functionality for doing the json parsing * @param json Tiled json to parse * @return parsed data as Map */ std::unique_ptr<tson::Map> tson::Tileson::parseJson(const nlohmann::json &json) { std::unique_ptr<tson::Map> map = std::make_unique<tson::Map>(); if(map->parse(json, &m_decompressors)) return std::move(map); return std::make_unique<tson::Map> (tson::ParseStatus::MissingData, "Missing map data..."); } /*! * Gets the decompressor container used when something is either encoded or compressed (regardless: IDecompressor is used as base). * These are used specifically for tile layers, and are connected by checking the name of the IDecompressor. If the name of a decompressor * matches with an encoding or a compression, its decompress() function will be used. * * @return The container including all decompressors. */ tson::DecompressorContainer *tson::Tileson::decompressors() { return &m_decompressors; } #endif //TILESON_TILESON_PARSER_HPP
29.821656
138
0.655703
SaraSmiseth
b8bd9d01a6afb6d6597a43f9ab92bb46c37182e0
1,055
cpp
C++
libraries/Si7021/si7021.cpp
emptyland/arduino
278cf1189401ba2bcb2d4125e42ac338c20ee4c8
[ "BSD-3-Clause" ]
null
null
null
libraries/Si7021/si7021.cpp
emptyland/arduino
278cf1189401ba2bcb2d4125e42ac338c20ee4c8
[ "BSD-3-Clause" ]
null
null
null
libraries/Si7021/si7021.cpp
emptyland/arduino
278cf1189401ba2bcb2d4125e42ac338c20ee4c8
[ "BSD-3-Clause" ]
null
null
null
#include "si7021.h" #include <Wire.h> void Si7021::init() { Wire.begin(); Wire.beginTransmission(0x40); Wire.endTransmission(); } void Si7021::getMonitor2(double *temp, double *humidity) { int X0,X1,Y0,Y1,Y2,Y3; double X,Y,X_out,Y_out1,Y_out2; /**发送温度测量命令**/ Wire.beginTransmission(0x40); Wire.write(0xE3); //发送读温度命令 Wire.endTransmission(); /**读取温度数据**/ Wire.requestFrom(0x40,2); //回传数据 if(Wire.available()<=2); { X0 = Wire.read(); X1 = Wire.read(); X0 = X0<<8; X_out = X0+X1; } /**计算并显示温度**/ X=(175.72*X_out)/65536; *temp=X-46.85; /**发送湿度测量命令**/ Wire.beginTransmission(0x40); Wire.write(0xE5); Wire.endTransmission(); /**读取湿度数据**/ Wire.requestFrom(0x40,2); if(Wire.available()<=2); { Y0 = Wire.read(); Y2=Y0/100; Y0=Y0%100; Y1 = Wire.read(); Y_out1 = Y2*25600; Y_out2 = Y0*256+Y1; } /**计算并显示湿度**/ Y_out1 = (125*Y_out1)/65536; Y_out2 = (125*Y_out2)/65536; Y = Y_out1+Y_out2; *humidity=Y-6; }
18.508772
59
0.567773
emptyland
b8bf2e3c1b6f678b3a5a71c888f567881c0a9e3f
1,829
cpp
C++
utility/unittest/reactor_test.cpp
hadescoincom/hds-core
383a38da9a5e40de66ba2277b54fea41b7c32537
[ "Apache-2.0" ]
null
null
null
utility/unittest/reactor_test.cpp
hadescoincom/hds-core
383a38da9a5e40de66ba2277b54fea41b7c32537
[ "Apache-2.0" ]
null
null
null
utility/unittest/reactor_test.cpp
hadescoincom/hds-core
383a38da9a5e40de66ba2277b54fea41b7c32537
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Hds 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 "utility/io/reactor.h" #ifndef LOG_VERBOSE_ENABLED #define LOG_VERBOSE_ENABLED 0 #endif #include "utility/logger.h" #include <future> #include <iostream> using namespace hds; using namespace hds::io; using namespace std; void reactor_start_stop() { Reactor::Ptr reactor = Reactor::create(); auto f = std::async( std::launch::async, [reactor]() { this_thread::sleep_for(chrono::microseconds(300000)); //usleep(300000); LOG_DEBUG() << "stopping reactor from foreign thread..."; reactor->stop(); } ); LOG_DEBUG() << "starting reactor...";; reactor->run(); LOG_DEBUG() << "reactor stopped"; f.get(); } void error_codes_test() { std::string unknown_descr = error_descr(ErrorCode(1005000)); std::string str; #define XX(code, _) \ str = format_io_error("", "", 0, EC_ ## code); \ LOG_VERBOSE() << str; \ assert(str.find(unknown_descr) == string::npos); UV_ERRNO_MAP(XX) #undef XX } int main() { int logLevel = LOG_LEVEL_DEBUG; #if LOG_VERBOSE_ENABLED logLevel = LOG_LEVEL_VERBOSE; #endif auto logger = Logger::create(logLevel, logLevel); reactor_start_stop(); error_codes_test(); }
26.897059
75
0.668671
hadescoincom
b8c26f134e4eebd4896f39160a648b122dd0aa94
1,166
cpp
C++
ewk/unittest/utc_blink_ewk_settings_edge_effect_enabled_set_func.cpp
Jabawack/chromium-efl
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
[ "BSD-3-Clause" ]
9
2015-04-09T20:22:08.000Z
2021-03-17T08:34:56.000Z
ewk/unittest/utc_blink_ewk_settings_edge_effect_enabled_set_func.cpp
Jabawack/chromium-efl
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
[ "BSD-3-Clause" ]
2
2015-02-04T13:41:12.000Z
2015-05-25T14:00:40.000Z
ewk/unittest/utc_blink_ewk_settings_edge_effect_enabled_set_func.cpp
isabella232/chromium-efl
db2d09aba6498fb09bbea1f8440d071c4b0fde78
[ "BSD-3-Clause" ]
14
2015-02-12T16:20:47.000Z
2022-01-20T10:36:26.000Z
// Copyright 2014 Samsung Electronics. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "utc_blink_ewk_base.h" class utc_blink_ewk_settings_edge_effect_enabled_set : public utc_blink_ewk_base { }; /** * @brief Tests if returns TRUE when initiated with a correct webview and * edge effect enabled set to TRUE/FALSE. */ TEST_F(utc_blink_ewk_settings_edge_effect_enabled_set, Set) { Ewk_Settings* settings = ewk_view_settings_get(GetEwkWebView()); ASSERT_TRUE(NULL != settings); Eina_Bool set = !ewk_settings_edge_effect_enabled_get(settings); ASSERT_EQ(EINA_TRUE, ewk_settings_edge_effect_enabled_set(settings, set)); ASSERT_EQ(set, ewk_settings_edge_effect_enabled_get(settings)); set = !set; ASSERT_EQ(EINA_TRUE, ewk_settings_edge_effect_enabled_set(settings, set)); ASSERT_EQ(set, ewk_settings_edge_effect_enabled_get(settings)); } /** * @brief Tests if returns FALSE when initiated with NULL webview. */ TEST_F(utc_blink_ewk_settings_edge_effect_enabled_set, NullArg) { ASSERT_NE(EINA_TRUE, ewk_settings_edge_effect_enabled_set(NULL, EINA_FALSE)); }
33.314286
82
0.797599
Jabawack
b8c337deafcc20682e646059d7cd59a6f6c055f5
43
hpp
C++
src/boost_type_erasure_iterator.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_type_erasure_iterator.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_type_erasure_iterator.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/type_erasure/iterator.hpp>
21.5
42
0.813953
miathedev
b8c35fff2f924aa122a0c3ca92711bb160bb09f8
1,665
hpp
C++
src/sdk/REMath.hpp
MeatSafeMurderer/REFramework
e275d7eccccfcb70311863b3f822428bdd74ce95
[ "MIT" ]
583
2021-06-05T06:56:54.000Z
2022-03-31T19:16:09.000Z
src/sdk/REMath.hpp
drowhunter/REFramework
49ef476d13439110cc0ae565cc323cd615d9b327
[ "MIT" ]
198
2021-07-13T02:54:19.000Z
2022-03-29T20:28:53.000Z
src/sdk/REMath.hpp
drowhunter/REFramework
49ef476d13439110cc0ae565cc323cd615d9b327
[ "MIT" ]
73
2021-07-12T18:52:12.000Z
2022-03-31T17:12:56.000Z
#pragma once #include <algorithm> #define GLM_ENABLE_EXPERIMENTAL #include <glm/gtx/euler_angles.hpp> #include <glm/gtx/vector_angle.hpp> #include "ReClass.hpp" namespace utility::math { using namespace glm; static vec3 euler_angles(const glm::mat4& rot); static float fix_angle(float ang); static void fix_angles(const glm::vec3& angles); static float clamp_pitch(float ang); // RE engine's way of storing euler angles or I'm just an idiot. static vec3 euler_angles(const glm::mat4& rot) { float pitch = 0.0f; float yaw = 0.0f; float roll = 0.0f; glm::extractEulerAngleYZX(rot, yaw, roll, pitch); return { pitch, yaw, roll }; } static float fix_angle(float ang) { auto angDeg = glm::degrees(ang); while (angDeg > 180.0f) { angDeg -= 360.0f; } while (angDeg < -180.0f) { angDeg += 360.0f; } return glm::radians(angDeg); } static void fix_angles(glm::vec3& angles) { angles[0] = fix_angle(angles[0]); angles[1] = fix_angle(angles[1]); angles[2] = fix_angle(angles[2]); } float clamp_pitch(float ang) { return std::clamp(ang, glm::radians(-89.0f), glm::radians(89.0f)); } static glm::mat4 remove_y_component(const glm::mat4& mat) { // Remove y component and normalize so we have the facing direction const auto forward_dir = glm::normalize(Vector3f{ mat[2].x, 0.0f, mat[2].z }); return glm::rowMajor4(glm::lookAtLH(Vector3f{}, Vector3f{ forward_dir }, Vector3f(0.0f, 1.0f, 0.0f))); } static quat to_quat(const vec3& v) { const auto mat = glm::rowMajor4(glm::lookAtLH(Vector3f{0.0f, 0.0f, 0.0f}, v, Vector3f{0.0f, 1.0f, 0.0f})); return glm::quat{mat}; } }
25.615385
110
0.667267
MeatSafeMurderer
fef58e6ea3dd75409d77d4afd00c94b81f80bef0
1,167
cpp
C++
PC/src/GameStates/GameOver.cpp
Termimad/UWOL
f6fb3e0d04d54d6338b4c661338648c8abf448bb
[ "MIT" ]
4
2016-10-17T14:32:53.000Z
2021-06-03T23:17:56.000Z
PC/src/GameStates/GameOver.cpp
Termimad/UWOL
f6fb3e0d04d54d6338b4c661338648c8abf448bb
[ "MIT" ]
4
2017-03-02T21:07:04.000Z
2017-03-02T21:45:14.000Z
PC/src/GameStates/GameOver.cpp
Termimad/UWOL
f6fb3e0d04d54d6338b4c661338648c8abf448bb
[ "MIT" ]
3
2016-09-20T16:30:06.000Z
2020-04-17T07:05:36.000Z
#include "GameOver.h" GameOver::GameOver() { _g = Graphics::GetInstance(); this->Name = "GameOver"; this->_currentFrame = new Frame("data/game-over.png"); this->_music = new Sound("music/GameOver.ogg"); this->_disposed = false; } GameOver::~GameOver() { this->Dispose(); } void GameOver::OnEnter() { this->_music->PlayAsMusic(false); this->_totalMsecs = 0; } void GameOver::OnExit() { MusicManager::FadeOutMusic(300); Game::GetInstance()->Restart(); } string GameOver::Update(Uint32 milliSec, Event & inputEvent) { this->_totalMsecs += milliSec; if (inputEvent.Name == "KEY_UP" || inputEvent.Name == "JOY_UP") { return "Presentacion"; } if (this->_totalMsecs > 10000) { return "Presentacion"; } return this->Name; } void GameOver::Draw(void) { int width = this->_currentFrame->Texture->width * 2; int height = this->_currentFrame->Texture->height * 2; _g->BlitCenteredFrameAlpha(this->_currentFrame, width, height, 1.0f, false, false); } void GameOver::Dispose(void) { if (!this->_disposed) { this->_disposed = true; delete this->_currentFrame; delete this->_music; } } Program * GameOver::GetProgram(void) { return nullptr; }
20.473684
84
0.686375
Termimad
fef74adcdc8e21327ba57495ee38aebb02e43dad
5,072
hpp
C++
roxie/ccd/ccdsnmp.hpp
davidarcher/HPCC-Platform
fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3
[ "Apache-2.0" ]
null
null
null
roxie/ccd/ccdsnmp.hpp
davidarcher/HPCC-Platform
fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3
[ "Apache-2.0" ]
null
null
null
roxie/ccd/ccdsnmp.hpp
davidarcher/HPCC-Platform
fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3
[ "Apache-2.0" ]
3
2021-05-02T17:01:57.000Z
2021-05-02T17:02:28.000Z
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ############################################################################## */ #ifndef CCDSNMP_HPP #define CCDSNMP_HPP #include "ccd.hpp" class CRoxieMetricsManager; class RoxieQueryStats { public: RelaxedAtomic<unsigned> count; RelaxedAtomic<unsigned> failedCount; RelaxedAtomic<unsigned> active; RelaxedAtomic<unsigned __int64> totalTime; RelaxedAtomic<unsigned> maxTime; RelaxedAtomic<unsigned> minTime; public: RoxieQueryStats() { count = 0; failedCount = 0; active = 0; totalTime = 0; maxTime = 0; minTime = (unsigned) -1; } inline void noteActive() { active++; } inline void noteComplete() { active--; } void noteQuery(bool failed, unsigned elapsedms) { totalTime += elapsedms; maxTime.store_max(elapsedms); minTime.store_min(elapsedms); count++; if (failed) failedCount++; active--; } void addMetrics(CRoxieMetricsManager *mgr, const char *prefix, unsigned interval); }; interface IQueryStatsAggregator : public IInterface { virtual void noteQuery(time_t startTime, bool failed, unsigned elapsedTimeMs, unsigned memUsed, unsigned slavesReplyLen, unsigned bytesOut) = 0; virtual IPropertyTree *getStats(time_t from, time_t to) = 0; }; extern IQueryStatsAggregator *queryGlobalQueryStatsAggregator(); extern IQueryStatsAggregator *createQueryStatsAggregator(const char *queryName, unsigned expirySeconds); extern IPropertyTree *getAllQueryStats(bool includeQueries, time_t from, time_t to); extern RelaxedAtomic<unsigned> queryCount; extern RoxieQueryStats unknownQueryStats; extern RoxieQueryStats loQueryStats; extern RoxieQueryStats hiQueryStats; extern RoxieQueryStats slaQueryStats; extern RoxieQueryStats combinedQueryStats; extern RelaxedAtomic<unsigned> retriesIgnoredPrm; extern RelaxedAtomic<unsigned> retriesIgnoredSec; extern RelaxedAtomic<unsigned> retriesNeeded; extern RelaxedAtomic<unsigned> retriesReceivedPrm; extern RelaxedAtomic<unsigned> retriesReceivedSec; extern RelaxedAtomic<unsigned> retriesSent; extern RelaxedAtomic<unsigned> rowsIn; extern RelaxedAtomic<unsigned> ibytiPacketsFromSelf; extern RelaxedAtomic<unsigned> ibytiPacketsSent; extern RelaxedAtomic<unsigned> ibytiPacketsWorked; extern RelaxedAtomic<unsigned> ibytiPacketsHalfWorked; extern RelaxedAtomic<unsigned> ibytiPacketsReceived; extern RelaxedAtomic<unsigned> ibytiPacketsTooLate; extern RelaxedAtomic<unsigned> ibytiNoDelaysPrm; extern RelaxedAtomic<unsigned> ibytiNoDelaysSec; extern RelaxedAtomic<unsigned> packetsReceived; extern RelaxedAtomic<unsigned> packetsSent; extern RelaxedAtomic<unsigned> resultsReceived; extern RelaxedAtomic<unsigned> indexRecordsRead; extern RelaxedAtomic<unsigned> postFiltered; extern RelaxedAtomic<unsigned> abortsSent; extern RelaxedAtomic<unsigned> activitiesStarted; extern RelaxedAtomic<unsigned> activitiesCompleted; extern RelaxedAtomic<unsigned> diskReadStarted; extern RelaxedAtomic<unsigned> diskReadCompleted; extern RelaxedAtomic<unsigned> globalSignals; extern RelaxedAtomic<unsigned> globalLocks; extern RelaxedAtomic<unsigned> maxSlavesActive; extern RelaxedAtomic<unsigned> slavesActive; extern RelaxedAtomic<unsigned> rowsOut; extern RelaxedAtomic<unsigned> queueLength; extern RelaxedAtomic<unsigned> maxQueueLength; extern RelaxedAtomic<unsigned> maxScanLength; extern RelaxedAtomic<unsigned> totScanLength; extern RelaxedAtomic<unsigned> totScans; extern RelaxedAtomic<unsigned> numFilesToProcess; #ifdef TIME_PACKETS extern RelaxedAtomic<unsigned __int64> packetWaitElapsed; extern RelaxedAtomic<unsigned> packetWaitMax; extern RelaxedAtomic<unsigned> packetWaitCount; extern RelaxedAtomic<unsigned __int64> packetRunElapsed; extern RelaxedAtomic<unsigned> packetRunMax; extern RelaxedAtomic<unsigned> packetRunCount; #endif extern RelaxedAtomic<unsigned> lastQueryDate; extern RelaxedAtomic<unsigned> lastQueryTime; interface IRoxieMetricsManager : extends IInterface { virtual void dumpMetrics() = 0; virtual void addUserMetric(const char *name, const char *regex) = 0; virtual StringBuffer &getMetrics(StringBuffer &) = 0; virtual void resetMetrics() = 0; }; IRoxieMetricsManager *createRoxieMetricsManager(); extern Owned<IRoxieMetricsManager> roxieMetrics; #endif
34.27027
148
0.762815
davidarcher
fef9f797be8f6045e854e9fa2c6b56ab1410bd2d
2,721
cpp
C++
src/Ray3D.cpp
nsilvestri/cpp-raytracer
79336657784f5bd76bb3d15985488bd61255e00b
[ "MIT" ]
1
2021-03-29T09:39:33.000Z
2021-03-29T09:39:33.000Z
src/Ray3D.cpp
nsilvestri/cpp-raytracer
79336657784f5bd76bb3d15985488bd61255e00b
[ "MIT" ]
1
2021-05-19T05:55:23.000Z
2021-09-07T14:00:01.000Z
src/Ray3D.cpp
nsilvestri/cpp-raytracer
79336657784f5bd76bb3d15985488bd61255e00b
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> #include "Ray3D.hpp" #include "Vector3D.hpp" /** * Constructor for Ray3D. Creates a new Ray3D object based on the given origin * and direction, given as Vector3D objects. * @param origin the origin of this new Ray3D * @param direction the direction of this new Ray3D. The direction will be * normalized. */ Ray3D::Ray3D(Vector3D origin, Vector3D direction) { this->setOrigin(origin); this->setDirection(direction.normalize()); } /** * Default constructor of Ray3D. Sets the origin and direction to Vector3Ds with * initial values of 0. */ Ray3D::Ray3D() { this->setOrigin(Vector3D(0, 0, 0)); this->setDirection(Vector3D(0, 0, 0)); } /** * Copy constructor for Ray3D */ Ray3D::Ray3D(const Ray3D& r) { this->setOrigin(r.getOrigin()); this->setDirection(r.getDirection().normalize()); } /** * Gets the origin of this Ray3D as a Vector3D. * @returns the origin of this Ray3D as a Vector3D. */ Vector3D Ray3D::getOrigin() const { return this->origin; } /** * Gets the direction of this Ray3D as a Vector3D. * @returns the direction of this Ray3D as a Vector3D. */ Vector3D Ray3D::getDirection() const { return this->direction; } /** * Sets the origin of this Ray3D to the given origin. * @param origin the new origin to set this Ray3D to. */ void Ray3D::setOrigin(Vector3D origin) { this->origin = origin; } /** * Sets the direction of this Ray3D to the given direction. The direction will * be normalized. * @param direction the new direction to set this Ray3D to. */ void Ray3D::setDirection(Vector3D direction) { this->direction = direction.normalize(); } /** * Determines if the given Vector3D, interpreted as a point, lies on this Ray3D. * @param point the Vector3D point to check if it lies on this Ray3D. */ bool Ray3D::isPointOn(Vector3D point) const { Vector3D pointDirection = point - this->getOrigin(); float xScale = point.getX() / this->getDirection().getX(); std::cout << xScale << std::endl; float yScale = point.getY() / this->getDirection().getY(); std::cout << yScale << std::endl; float zScale = point.getZ() / this->getDirection().getZ(); std::cout << zScale << std::endl; /* a point must be on the origin or in the direction of ray.direction * relative to the origin, and all scales must be equal */ return (xScale >= 0 && xScale == yScale && yScale == zScale); } std::ostream& operator<<(std::ostream &stream, const Ray3D& r) { return stream << "Ray3D(Origin=" << r.getOrigin() << ", direction=" << r.getDirection() << ")"; }
26.940594
81
0.646821
nsilvestri
fefba69df8d1d755cd5c5c88fa967b64d6bb84b7
50,861
cpp
C++
Source/AllProjects/CQCMedia/CQCMedia_Shared.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/CQCMedia/CQCMedia_Shared.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/CQCMedia/CQCMedia_Shared.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// ---------------------------------------------------------------------------- // FILE: CQCMedia_Shared.cpp // DATE: Fri, Feb 12 21:14:15 2021 -0500 // // 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. // ---------------------------------------------------------------------------- #include "CQCMedia_.hpp" const TString kCQCMedia::strRend_StdPLItemKeyPref(L"StdPLItemKey:"); const TString kCQCMedia::strQuery_CatList(L"QCatList"); const TString kCQCMedia::strQuery_ColItems(L"QColItems"); const TString kCQCMedia::strQuery_TitleDetails(L"QTitleDets"); const TString kCQCMedia::strQuery_OTFTitleList(L"QOTFList"); const TString kCQCMedia::strQuery_ColDetails(L"QColDets"); const TString kCQCMedia::strQuery_ItemDetails(L"QItemDets"); const TString kCQCMedia::strQuery_DefCatInfo(L"QDefCatInfo"); const TString kCQCMedia::strQuery_MediaFmt(L"QMediaFmt"); const TString kCQCMedia::strQuery_DBSerialNumber(L"QDBSerialNumber"); const TString kCQCMedia::strQuery_Artist(L"Fld_Artist"); const TString kCQCMedia::strQuery_AspectRatio(L"Fld_Aspect"); const TString kCQCMedia::strQuery_Cast(L"Fld_Cast"); const TString kCQCMedia::strQuery_Description(L"Fld_Descr"); const TString kCQCMedia::strQuery_Label(L"Fld_Label"); const TString kCQCMedia::strQuery_LeadActor(L"Fld_LeadActor"); const TString kCQCMedia::strQuery_Rating(L"Fld_Rating"); const TString kCQCMedia::strQuery_RawRunTime(L"Fld_RawRunTime"); const TString kCQCMedia::strQuery_RunTime(L"Fld_RunTime"); const TString kCQCMedia::strQuery_Title(L"Fld_Title"); const TString kCQCMedia::strQuery_Year(L"Fld_Year"); const TString kCQCMedia::strQuery_CookieLookup(L"CookieLookup"); const TString kCQCMedia::strQuery_RandomGenreItems(L"RandomGenreItems"); const TString kCQCMedia::strQuery_BitDepth(L"Fld_BitDepth"); const TString kCQCMedia::strQuery_BitRate(L"Fld_BitRate"); const TString kCQCMedia::strQuery_Channels(L"Fld_Channels"); const TString kCQCMedia::strQuery_DateAdded(L"Fld_DateAdded"); const TString kCQCMedia::strQuery_SampleRate(L"Fld_SampleRate"); const TString kCQCMedia::strQuery_SeqNum(L"Fld_SeqNum"); const TString kCQCMedia::strQuery_UserRating(L"Fld_UserRating"); const TString kCQCMedia::strQuery_QueryAudioFmt(L"QueryAudFmt"); const TString kCQCMedia::strQuery_Name(L"Fld_Name"); const TString kCQCMedia::strQuery_CurPLItem(L"QCurPLItem"); const TString kCQCMedia::strQuery_PLItems(L"QPLItems"); const TString kCQCMedia::strQuery_BinMediaDump(L"QBinMediaDump"); const TString kCQCMedia::strQuery_XMLMediaDump(L"QXMLMediaDump"); const TString kCQCMedia::strQuery_QueryCurPLItemId(L"QCurPLItemId"); const TString kCQCMedia::strQuery_ProtoVer(L"QueryProtoVer"); const TString kCQCMedia::strQuery_MediaTypes(L"QMediaTypes"); const TString kCQCMedia::strQuery_ColLoc(L"QColLoc"); const TString kCQCMedia::strQuery_QueryArt(L"QArt"); const TString kCQCMedia::strQuery_QueryTitleArt(L"QTitleArt"); const TString kCQCMedia::strQuery_QueryItemArt(L"QItemArt"); const TString kCQCMedia::strQuery_QueryThumbArt(L"QThumbArt"); const TString kCQCMedia::strQuery_QueryTitleThumbArt(L"QTitleThumbArt"); const TString kCQCMedia::strQuery_QueryItemThumbArt(L"QTitleItemArt"); const TString kCQCMedia::strQuery_QueryPosterArt(L"QPosterArt"); const TString kCQCMedia::strQuery_QueryImgById(L"QImgById"); const TString kCQCMedia::strCmd_SetUserRating(L"SetUserRating"); const TString kCQCMedia::strEvId_OnSelectCol(L"StdEvent:OnSelectCol"); const TString kCQCMedia::strEvId_OnSelectItem(L"StdEvent:OnSelectItem"); const TString kCQCMedia::strCmdId_SetCategory(L"MediaCmd:SetCategory"); const TString kCQCMedia::strCmdId_SetTitle(L"MediaCmd:SetTitle"); const TString kCQCMedia::strCmdId_SetTitleCookie(L"MediaCmd:SetTitleCookie"); const TString kCQCMedia::strCmdId_SetMediaType(L"MediaCmd:SetMediaType"); const TString kCQCMedia::strCmdId_SetSortOrder(L"MediaCmd:SetSortOrder"); const TString kCQCMedia::strCmdId_SetColCookie(L"MediaCmd:SetColCookie"); const TString kCQCMedia::strCmdId_GetColLocInfo(L"MediaCmd:GetColLocInfo"); const TString kCQCMedia::strCmdId_GetItemLocInfo(L"MediaCmd:GetColItemInfo"); const TString kCQCMedia::strCmdId_GetSortOrder(L"MediaCmd:GetSortOrder"); const TString kCQCMedia::strCmdId_SearchByArtist(L"MediaCmd:SearchByArtist"); const TString kCQCMedia::strCmdId_SetRepository(L"MediaCmd:SetRepository"); const TString kCQCMedia::strCmdId_GetCatCookie(L"MediaCmd:GetCatCookie"); const TString kCQCMedia::strCmdId_SetTextType(L"MediaCmd:SetTextType"); const TString kCQCMedia::strCmdId_SearchByTitle(L"MediaCmd:SearchByTitle"); const TString kCQCMedia::strCmdId_SearchByActor(L"MediaCmd:SearchByActor"); const TString kCQCMedia::strCmdId_GetMediaType(L"MediaCmd:GetMediaType"); const TString kCQCMedia::strCmdId_GetAudioFmt(L"MediaCmd:GetAudioFmt"); const TString kCQCMedia::strCmdId_SearchByAudioFmt(L"MediaCmd:SearchByAudioFmt"); const TString kCQCMedia::strCmdId_RandomTitleSearch(L"MediaCmd:RandomTitleSearch"); const TString kCQCMedia::strRTVId_CategoryCookie(L"MediaRTV:CategoryCookie"); const TString kCQCMedia::strRTVId_Artist(L"MediaRTV:Artist"); const TString kCQCMedia::strRTVId_CategoryName(L"MediaRTV:CategoryName"); const TString kCQCMedia::strRTVId_ColArtist(L"MediaRTV:ColArtist"); const TString kCQCMedia::strRTVId_ColCookie(L"MediaRTV:ColCookie"); const TString kCQCMedia::strRTVId_ColCount(L"MediaRTV:ColCount"); const TString kCQCMedia::strRTVId_ItemArtist(L"MediaRTV:ItemArtist"); const TString kCQCMedia::strRTVId_ItemArtistList(L"MediaRTV:ItemArtistList"); const TString kCQCMedia::strRTVId_ItemCookie(L"MediaRTV:ItemCookie"); const TString kCQCMedia::strRTVId_ItemCookieList(L"MediaRTV:ItemCookieList"); const TString kCQCMedia::strRTVId_ItemName(L"MediaRTV:ItemName"); const TString kCQCMedia::strRTVId_ItemNameList(L"MediaRTV:ItemNameList"); const TString kCQCMedia::strRTVId_LocInfo(L"MediaRTV:LocInfo"); const TString kCQCMedia::strRTVId_LocType(L"MediaRTV:LocType"); const TString kCQCMedia::strRTVId_MediaType(L"MediaRTV:MediaType"); const TString kCQCMedia::strRTVId_TitleArtist(L"MediaRTV:TitleArtist"); const TString kCQCMedia::strRTVId_TitleCookie(L"MediaRTV:TitleCookie"); const TString kCQCMedia::strRTVId_TitleCount(L"MediaRTV:TitleCount"); const TString kCQCMedia::strRTVId_TitleName(L"MediaRTV:TitleName"); const TString kCQCMedia::strRTVId_TitleNumber(L"MediaRTV:TitleNumber"); const TString kCQCMedia::strRTVId_MediaRepoMoniker(L"MediaRTV:MediaRepoMoniker"); const TString kCQCMedia::strRTVId_MediaFmt(L"MediaRTV:MediaFmt"); const TString kCQCMedia::strRTVId_Name(L"MediaRTV:Name"); const TString kCQCMedia::strRTVId_TopLevel(L"MediaRTV:TopLevel"); const TString kCQCMedia::strRTVId_ListItemId(L"MediaRTV:ListItemId"); const TString kCQCMedia::strMediaFld_DBSerialNum(L"MediaDBSerialNum"); static TEnumMap::TEnumValItem aeitemValues_ECookieTypes[4] = { { tCIDLib::TInt4(tCQCMedia::ECookieTypes::Cat), 0, 0, { L"", L"", L"", L"Cat", L"ECookieTypes::Cat", L"Category" } } , { tCIDLib::TInt4(tCQCMedia::ECookieTypes::Title), 0, 0, { L"", L"", L"", L"Title", L"ECookieTypes::Title", L"Title" } } , { tCIDLib::TInt4(tCQCMedia::ECookieTypes::Collect), 0, 0, { L"", L"", L"", L"Collect", L"ECookieTypes::Collect", L"Collect" } } , { tCIDLib::TInt4(tCQCMedia::ECookieTypes::Item), 0, 0, { L"", L"", L"", L"Item", L"ECookieTypes::Item", L"Item" } } }; static TEnumMap emapECookieTypes ( L"ECookieTypes" , 4 , kCIDLib::False , aeitemValues_ECookieTypes , nullptr , tCIDLib::TCard4(tCQCMedia::ECookieTypes::Count) ); const TString& tCQCMedia::strXlatECookieTypes(const tCQCMedia::ECookieTypes eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapECookieTypes.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::Text, bThrowIfNot); } tCQCMedia::ECookieTypes tCQCMedia::eXlatECookieTypes(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::ECookieTypes(emapECookieTypes.i4MapEnumText(strVal, TEnumMap::ETextVals::Text, bThrowIfNot)); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::ECookieTypes eVal) { return emapECookieTypes.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_ECompTypes[5] = { { tCIDLib::TInt4(tCQCMedia::ECompTypes::Eq), 0, 0, { L"", L"", L"", L"Eq", L"ECompTypes::Eq", L"=" } } , { tCIDLib::TInt4(tCQCMedia::ECompTypes::Lt), 0, 0, { L"", L"", L"", L"Lt", L"ECompTypes::Lt", L"<" } } , { tCIDLib::TInt4(tCQCMedia::ECompTypes::LtEq), 0, 0, { L"", L"", L"", L"LtEq", L"ECompTypes::LtEq", L"<=" } } , { tCIDLib::TInt4(tCQCMedia::ECompTypes::Gt), 0, 0, { L"", L"", L"", L"Gt", L"ECompTypes::Gt", L">" } } , { tCIDLib::TInt4(tCQCMedia::ECompTypes::GtEq), 0, 0, { L"", L"", L"", L"GtEq", L"ECompTypes::GtEq", L">=" } } }; static TEnumMap emapECompTypes ( L"ECompTypes" , 5 , kCIDLib::False , aeitemValues_ECompTypes , nullptr , tCIDLib::TCard4(tCQCMedia::ECompTypes::Count) ); const TString& tCQCMedia::strXlatECompTypes(const tCQCMedia::ECompTypes eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapECompTypes.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::Text, bThrowIfNot); } tCQCMedia::ECompTypes tCQCMedia::eXlatECompTypes(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::ECompTypes(emapECompTypes.i4MapEnumText(strVal, TEnumMap::ETextVals::Text, bThrowIfNot)); } tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, tCQCMedia::ECompTypes* const aeList, const tCIDLib::TCard4 c4Count) { tCIDLib::TCard4 c4Cur = 0; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmSrc >> c4Cur; aeList[c4Index] = tCQCMedia::ECompTypes(c4Cur); } } tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const tCQCMedia::ECompTypes* const aeList, const tCIDLib::TCard4 c4Count) { for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) strmTar << tCIDLib::TCard4(aeList[c4Index]); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::ECompTypes eVal) { return emapECompTypes.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_EDataTypes[5] = { { tCIDLib::TInt4(tCQCMedia::EDataTypes::Cat), 0, 0, { L"", L"", L"", L"Cat", L"EDataTypes::Cat", L"category" } } , { tCIDLib::TInt4(tCQCMedia::EDataTypes::Collect), 0, 0, { L"", L"", L"", L"Collect", L"EDataTypes::Collect", L"collect" } } , { tCIDLib::TInt4(tCQCMedia::EDataTypes::Image), 0, 0, { L"", L"", L"", L"Image", L"EDataTypes::Image", L"image" } } , { tCIDLib::TInt4(tCQCMedia::EDataTypes::Item), 0, 0, { L"", L"", L"", L"Item", L"EDataTypes::Item", L"item" } } , { tCIDLib::TInt4(tCQCMedia::EDataTypes::TitleSet), 0, 0, { L"", L"", L"", L"TitleSet", L"EDataTypes::TitleSet", L"titleset" } } }; static TEnumMap emapEDataTypes ( L"EDataTypes" , 5 , kCIDLib::False , aeitemValues_EDataTypes , nullptr , tCIDLib::TCard4(tCQCMedia::EDataTypes::Count) ); const TString& tCQCMedia::strXlatEDataTypes(const tCQCMedia::EDataTypes eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapEDataTypes.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::Text, bThrowIfNot); } tCQCMedia::EDataTypes tCQCMedia::eXlatEDataTypes(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::EDataTypes(emapEDataTypes.i4MapEnumText(strVal, TEnumMap::ETextVals::Text, bThrowIfNot)); } tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, tCQCMedia::EDataTypes* const aeList, const tCIDLib::TCard4 c4Count) { tCIDLib::TCard4 c4Cur = 0; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmSrc >> c4Cur; aeList[c4Index] = tCQCMedia::EDataTypes(c4Cur); } } tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const tCQCMedia::EDataTypes* const aeList, const tCIDLib::TCard4 c4Count) { for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) strmTar << tCIDLib::TCard4(aeList[c4Index]); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::EDataTypes eVal) { return emapEDataTypes.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_ELoadStatus[4] = { { tCIDLib::TInt4(tCQCMedia::ELoadStatus::Init), 0, 0, { L"", L"", L"", L"Init", L"ELoadStatus::Init", L"Initializing" } } , { tCIDLib::TInt4(tCQCMedia::ELoadStatus::Loading), 0, 0, { L"", L"", L"", L"Loading", L"ELoadStatus::Loading", L"Loading" } } , { tCIDLib::TInt4(tCQCMedia::ELoadStatus::Ready), 0, 0, { L"", L"", L"", L"Ready", L"ELoadStatus::Ready", L"Ready" } } , { tCIDLib::TInt4(tCQCMedia::ELoadStatus::Failed), 0, 0, { L"", L"", L"", L"Failed", L"ELoadStatus::Failed", L"Failed" } } }; static TEnumMap emapELoadStatus ( L"ELoadStatus" , 4 , kCIDLib::False , aeitemValues_ELoadStatus , nullptr , tCIDLib::TCard4(tCQCMedia::ELoadStatus::Count) ); const TString& tCQCMedia::strXlatELoadStatus(const tCQCMedia::ELoadStatus eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapELoadStatus.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::Text, bThrowIfNot); } tCQCMedia::ELoadStatus tCQCMedia::eXlatELoadStatus(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::ELoadStatus(emapELoadStatus.i4MapEnumText(strVal, TEnumMap::ETextVals::Text, bThrowIfNot)); } tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, tCQCMedia::ELoadStatus* const aeList, const tCIDLib::TCard4 c4Count) { tCIDLib::TCard4 c4Cur = 0; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmSrc >> c4Cur; aeList[c4Index] = tCQCMedia::ELoadStatus(c4Cur); } } tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const tCQCMedia::ELoadStatus* const aeList, const tCIDLib::TCard4 c4Count) { for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) strmTar << tCIDLib::TCard4(aeList[c4Index]); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::ELoadStatus eVal) { return emapELoadStatus.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_ELocTypes[3] = { { tCIDLib::TInt4(tCQCMedia::ELocTypes::FileCol), 0, kMedMsgs::midLoc_FileCol, { L"", L"", L"", L"FileCol", L"ELocTypes::FileCol", L"" } } , { tCIDLib::TInt4(tCQCMedia::ELocTypes::FileItem), 0, kMedMsgs::midLoc_FileItem, { L"", L"", L"", L"FileItem", L"ELocTypes::FileItem", L"" } } , { tCIDLib::TInt4(tCQCMedia::ELocTypes::Changer), 0, kMedMsgs::midLoc_Changer, { L"", L"", L"", L"Changer", L"ELocTypes::Changer", L"" } } }; static TEnumMap emapELocTypes ( L"ELocTypes" , 3 , kCIDLib::False , aeitemValues_ELocTypes , &facCQCMedia() , tCIDLib::TCard4(tCQCMedia::ELocTypes::Count) ); const TString& tCQCMedia::strAltXlatELocTypes(const tCQCMedia::ELocTypes eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapELocTypes.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::BaseName, bThrowIfNot); } tCQCMedia::ELocTypes tCQCMedia::eAltXlatELocTypes(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::ELocTypes(emapELocTypes.i4MapEnumText(strVal, TEnumMap::ETextVals::BaseName, bThrowIfNot)); } const TString& tCQCMedia::strXlatELocTypes(const tCQCMedia::ELocTypes eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapELocTypes.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::Text, bThrowIfNot); } tCQCMedia::ELocTypes tCQCMedia::eXlatELocTypes(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::ELocTypes(emapELocTypes.i4MapEnumText(strVal, TEnumMap::ETextVals::Text, bThrowIfNot)); } tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, tCQCMedia::ELocTypes* const aeList, const tCIDLib::TCard4 c4Count) { tCIDLib::TCard4 c4Cur = 0; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmSrc >> c4Cur; aeList[c4Index] = tCQCMedia::ELocTypes(c4Cur); } } tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const tCQCMedia::ELocTypes* const aeList, const tCIDLib::TCard4 c4Count) { for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) strmTar << tCIDLib::TCard4(aeList[c4Index]); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::ELocTypes eVal) { return emapELocTypes.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_EEndStates[3] = { { tCIDLib::TInt4(tCQCMedia::EEndStates::Running), 0, 0, { L"", L"", L"", L"Running", L"EEndStates::Running", L"" } } , { tCIDLib::TInt4(tCQCMedia::EEndStates::Ended), 0, 0, { L"", L"", L"", L"Ended", L"EEndStates::Ended", L"" } } , { tCIDLib::TInt4(tCQCMedia::EEndStates::Failed), 0, 0, { L"", L"", L"", L"Failed", L"EEndStates::Failed", L"" } } }; static TEnumMap emapEEndStates ( L"EEndStates" , 3 , kCIDLib::False , aeitemValues_EEndStates , nullptr , tCIDLib::TCard4(tCQCMedia::EEndStates::Count) ); const TString& tCQCMedia::strXlatEEndStates(const tCQCMedia::EEndStates eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapEEndStates.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::BaseName, bThrowIfNot); } tCQCMedia::EEndStates tCQCMedia::eXlatEEndStates(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::EEndStates(emapEEndStates.i4MapEnumText(strVal, TEnumMap::ETextVals::BaseName, bThrowIfNot)); } tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, tCQCMedia::EEndStates* const aeList, const tCIDLib::TCard4 c4Count) { tCIDLib::TCard4 c4Cur = 0; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmSrc >> c4Cur; aeList[c4Index] = tCQCMedia::EEndStates(c4Cur); } } tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const tCQCMedia::EEndStates* const aeList, const tCIDLib::TCard4 c4Count) { for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) strmTar << tCIDLib::TCard4(aeList[c4Index]); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::EEndStates eVal) { return emapEEndStates.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_EMediaStates[6] = { { tCIDLib::TInt4(tCQCMedia::EMediaStates::Undefined), 0, 0, { L"", L"", L"", L"Undefined", L"EMediaStates::Undefined", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMediaStates::Buffering), 0, 0, { L"", L"", L"", L"Buffering", L"EMediaStates::Buffering", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMediaStates::Loading), 0, 0, { L"", L"", L"", L"Loading", L"EMediaStates::Loading", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMediaStates::Playing), 0, 0, { L"", L"", L"", L"Playing", L"EMediaStates::Playing", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMediaStates::Paused), 0, 0, { L"", L"", L"", L"Paused", L"EMediaStates::Paused", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMediaStates::Stopped), 0, 0, { L"", L"", L"", L"Stopped", L"EMediaStates::Stopped", L"" } } }; static TEnumMap emapEMediaStates ( L"EMediaStates" , 6 , kCIDLib::False , aeitemValues_EMediaStates , nullptr , tCIDLib::TCard4(tCQCMedia::EMediaStates::Count) ); const TString& tCQCMedia::strXlatEMediaStates(const tCQCMedia::EMediaStates eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapEMediaStates.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::BaseName, bThrowIfNot); } tCQCMedia::EMediaStates tCQCMedia::eXlatEMediaStates(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::EMediaStates(emapEMediaStates.i4MapEnumText(strVal, TEnumMap::ETextVals::BaseName, bThrowIfNot)); } tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, tCQCMedia::EMediaStates* const aeList, const tCIDLib::TCard4 c4Count) { tCIDLib::TCard4 c4Cur = 0; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmSrc >> c4Cur; aeList[c4Index] = tCQCMedia::EMediaStates(c4Cur); } } tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const tCQCMedia::EMediaStates* const aeList, const tCIDLib::TCard4 c4Count) { for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) strmTar << tCIDLib::TCard4(aeList[c4Index]); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::EMediaStates eVal) { return emapEMediaStates.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_EMImgAttrs[7] = { { tCIDLib::TInt4(tCQCMedia::EMImgAttrs::CoverArtLrg), 0, kMedMsgs::midMImg_CoverArtLrg, { L"", L"", L"", L"CoverArtLrg", L"EMImgAttrs::CoverArtLrg", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMImgAttrs::CoverArtSml), 0, kMedMsgs::midMImg_CoverArtSml, { L"", L"", L"", L"CoverArtSml", L"EMImgAttrs::CoverArtSml", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMImgAttrs::RatingLg), 0, kMedMsgs::midMImg_RatingLg, { L"", L"", L"", L"RatingLg", L"EMImgAttrs::RatingLg", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMImgAttrs::RatingSm), 0, kMedMsgs::midMImg_RatingSm, { L"", L"", L"", L"RatingSm", L"EMImgAttrs::RatingSm", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMImgAttrs::RatingLgWh), 0, kMedMsgs::midMImg_RatingLgWh, { L"", L"", L"", L"RatingLgWh", L"EMImgAttrs::RatingLgWh", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMImgAttrs::RatingSmWh), 0, kMedMsgs::midMImg_RatingSmWh, { L"", L"", L"", L"RatingSmWh", L"EMImgAttrs::RatingSmWh", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMImgAttrs::PosterArt), 0, kMedMsgs::midMImg_PosterArt, { L"", L"", L"", L"PosterArt", L"EMImgAttrs::PosterArt", L"" } } }; static TEnumMap emapEMImgAttrs ( L"EMImgAttrs" , 7 , kCIDLib::False , aeitemValues_EMImgAttrs , &facCQCMedia() , tCIDLib::TCard4(tCQCMedia::EMImgAttrs::Count) ); tCIDLib::TVoid tCQCMedia::FormatEMImgAttrs(TString& strToFill, const TString& strPrefix, const tCIDLib::TCh chSepChar, const TEnumMap::ETextVals eVal) { emapEMImgAttrs.FormatValues(strToFill, strPrefix, chSepChar, eVal); } const TString& tCQCMedia::strXlatEMImgAttrs(const tCQCMedia::EMImgAttrs eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapEMImgAttrs.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::Text, bThrowIfNot); } tCQCMedia::EMImgAttrs tCQCMedia::eXlatEMImgAttrs(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::EMImgAttrs(emapEMImgAttrs.i4MapEnumText(strVal, TEnumMap::ETextVals::Text, bThrowIfNot)); } tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, tCQCMedia::EMImgAttrs* const aeList, const tCIDLib::TCard4 c4Count) { tCIDLib::TCard4 c4Cur = 0; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmSrc >> c4Cur; aeList[c4Index] = tCQCMedia::EMImgAttrs(c4Cur); } } tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const tCQCMedia::EMImgAttrs* const aeList, const tCIDLib::TCard4 c4Count) { for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) strmTar << tCIDLib::TCard4(aeList[c4Index]); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::EMImgAttrs eVal) { return emapEMImgAttrs.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_EMTextAttrs[20] = { { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::AspectRatio), 0, kMedMsgs::midMText_AspectRatio, { L"", L"", L"", L"AspectRatio", L"EMTextAttrs::AspectRatio", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::Cast), 0, kMedMsgs::midMText_Cast, { L"", L"", L"", L"Cast", L"EMTextAttrs::Cast", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::Description), 0, kMedMsgs::midMText_Descr, { L"", L"", L"", L"Description", L"EMTextAttrs::Description", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::Label), 0, kMedMsgs::midMText_Label, { L"", L"", L"", L"Label", L"EMTextAttrs::Label", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::Rating), 0, kMedMsgs::midMText_Rating, { L"", L"", L"", L"Rating", L"EMTextAttrs::Rating", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::RunTime), 0, kMedMsgs::midMText_Runtime, { L"", L"", L"", L"RunTime", L"EMTextAttrs::RunTime", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::Title), 0, kMedMsgs::midMText_Title, { L"", L"", L"", L"Title", L"EMTextAttrs::Title", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::Year), 0, kMedMsgs::midMText_Year, { L"", L"", L"", L"Year", L"EMTextAttrs::Year", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::Artist), 0, kMedMsgs::midMText_Artist, { L"", L"", L"", L"Artist", L"EMTextAttrs::Artist", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::LeadActor), 0, kMedMsgs::midMText_LeadActor, { L"", L"", L"", L"LeadActor", L"EMTextAttrs::LeadActor", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::MediaFmt), 0, kMedMsgs::midMText_MediaFmt, { L"", L"", L"", L"MediaFmt", L"EMTextAttrs::MediaFmt", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::RawRunTime), 0, kMedMsgs::midMText_RawRuntime, { L"", L"", L"", L"RawRunTime", L"EMTextAttrs::RawRunTime", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::BitDepth), 0, kMedMsgs::midMText_BitDepth, { L"", L"", L"", L"BitDepth", L"EMTextAttrs::BitDepth", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::BitRate), 0, kMedMsgs::midMText_BitRate, { L"", L"", L"", L"BitRate", L"EMTextAttrs::BitRate", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::Channels), 0, kMedMsgs::midMText_Channels, { L"", L"", L"", L"Channels", L"EMTextAttrs::Channels", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::DateAdded), 0, kMedMsgs::midMText_DateAdded, { L"", L"", L"", L"DateAdded", L"EMTextAttrs::DateAdded", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::SampleRate), 0, kMedMsgs::midMText_SampleRate, { L"", L"", L"", L"SampleRate", L"EMTextAttrs::SampleRate", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::SeqNum), 0, kMedMsgs::midMText_SeqNum, { L"", L"", L"", L"SeqNum", L"EMTextAttrs::SeqNum", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::UserRating), 0, kMedMsgs::midMText_UserRating, { L"", L"", L"", L"UserRating", L"EMTextAttrs::UserRating", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTextAttrs::Name), 0, kMedMsgs::midMText_Name, { L"", L"", L"", L"Name", L"EMTextAttrs::Name", L"" } } }; static TEnumMap emapEMTextAttrs ( L"EMTextAttrs" , 20 , kCIDLib::False , aeitemValues_EMTextAttrs , &facCQCMedia() , tCIDLib::TCard4(tCQCMedia::EMTextAttrs::Count) ); tCIDLib::TVoid tCQCMedia::FormatEMTextAttrs(TString& strToFill, const TString& strPrefix, const tCIDLib::TCh chSepChar, const TEnumMap::ETextVals eVal) { emapEMTextAttrs.FormatValues(strToFill, strPrefix, chSepChar, eVal); } const TString& tCQCMedia::strXlatEMTextAttrs(const tCQCMedia::EMTextAttrs eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapEMTextAttrs.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::Text, bThrowIfNot); } tCQCMedia::EMTextAttrs tCQCMedia::eXlatEMTextAttrs(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::EMTextAttrs(emapEMTextAttrs.i4MapEnumText(strVal, TEnumMap::ETextVals::Text, bThrowIfNot)); } tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, tCQCMedia::EMTextAttrs* const aeList, const tCIDLib::TCard4 c4Count) { tCIDLib::TCard4 c4Cur = 0; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmSrc >> c4Cur; aeList[c4Index] = tCQCMedia::EMTextAttrs(c4Cur); } } tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const tCQCMedia::EMTextAttrs* const aeList, const tCIDLib::TCard4 c4Count) { for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) strmTar << tCIDLib::TCard4(aeList[c4Index]); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::EMTextAttrs eVal) { return emapEMTextAttrs.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_EMediaTypes[3] = { { tCIDLib::TInt4(tCQCMedia::EMediaTypes::Movie), 0, 0, { L"", L"", L"", L"Movie", L"EMediaTypes::Movie", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMediaTypes::Music), 0, 0, { L"", L"", L"", L"Music", L"EMediaTypes::Music", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMediaTypes::Pic), 0, 0, { L"", L"", L"", L"Pic", L"EMediaTypes::Pic", L"" } } }; static TEnumMap emapEMediaTypes ( L"EMediaTypes" , 3 , kCIDLib::False , aeitemValues_EMediaTypes , nullptr , tCIDLib::TCard4(tCQCMedia::EMediaTypes::Count) ); tCIDLib::TVoid tCQCMedia::FormatEMediaTypes(TString& strToFill, const TString& strPrefix, const tCIDLib::TCh chSepChar, const TEnumMap::ETextVals eVal) { emapEMediaTypes.FormatValues(strToFill, strPrefix, chSepChar, eVal); } const TString& tCQCMedia::strXlatEMediaTypes(const tCQCMedia::EMediaTypes eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapEMediaTypes.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::BaseName, bThrowIfNot); } tCQCMedia::EMediaTypes tCQCMedia::eXlatEMediaTypes(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::EMediaTypes(emapEMediaTypes.i4MapEnumText(strVal, TEnumMap::ETextVals::BaseName, bThrowIfNot)); } tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, tCQCMedia::EMediaTypes* const aeList, const tCIDLib::TCard4 c4Count) { tCIDLib::TCard4 c4Cur = 0; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmSrc >> c4Cur; aeList[c4Index] = tCQCMedia::EMediaTypes(c4Cur); } } tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const tCQCMedia::EMediaTypes* const aeList, const tCIDLib::TCard4 c4Count) { for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) strmTar << tCIDLib::TCard4(aeList[c4Index]); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::EMediaTypes eVal) { return emapEMediaTypes.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_EMTFlags[4] = { { tCIDLib::TInt4(tCQCMedia::EMTFlags::Movie), 0, 0, { L"", L"", L"", L"Movie", L"EMTFlags::Movie", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTFlags::Music), 0, 0, { L"", L"", L"", L"Music", L"EMTFlags::Music", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTFlags::Pic), 0, 0, { L"", L"", L"", L"Pic", L"EMTFlags::Pic", L"" } } , { tCIDLib::TInt4(tCQCMedia::EMTFlags::MultiMedia), 0, 0, { L"", L"", L"", L"MultiMedia", L"EMTFlags::MultiMedia", L"" } } }; static TEnumMap emapEMTFlags ( L"EMTFlags" , 4 , kCIDLib::True , aeitemValues_EMTFlags , nullptr , tCIDLib::TCard4(tCQCMedia::EMTFlags::None) ); tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, tCQCMedia::EMTFlags* const aeList, const tCIDLib::TCard4 c4Count) { tCIDLib::TCard4 c4Cur = 0; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmSrc >> c4Cur; aeList[c4Index] = tCQCMedia::EMTFlags(c4Cur); } } tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const tCQCMedia::EMTFlags* const aeList, const tCIDLib::TCard4 c4Count) { for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) strmTar << tCIDLib::TCard4(aeList[c4Index]); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::EMTFlags eVal) { return emapEMTFlags.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_EPLModes[4] = { { tCIDLib::TInt4(tCQCMedia::EPLModes::Normal), 0, 0, { L"", L"", L"", L"Normal", L"EPLModes::Normal", L"Normal" } } , { tCIDLib::TInt4(tCQCMedia::EPLModes::Jukebox), 0, 0, { L"", L"", L"", L"Jukebox", L"EPLModes::Jukebox", L"Jukebox" } } , { tCIDLib::TInt4(tCQCMedia::EPLModes::Shuffle), 0, 0, { L"", L"", L"", L"Shuffle", L"EPLModes::Shuffle", L"Shuffle" } } , { tCIDLib::TInt4(tCQCMedia::EPLModes::RandomCat), 0, 0, { L"", L"", L"", L"RandomCat", L"EPLModes::RandomCat", L"Random Category" } } }; static TEnumMap emapEPLModes ( L"EPLModes" , 4 , kCIDLib::False , aeitemValues_EPLModes , nullptr , tCIDLib::TCard4(tCQCMedia::EPLModes::Count) ); const TString& tCQCMedia::strXlatEPLModes(const tCQCMedia::EPLModes eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapEPLModes.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::Text, bThrowIfNot); } tCQCMedia::EPLModes tCQCMedia::eXlatEPLModes(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::EPLModes(emapEPLModes.i4MapEnumText(strVal, TEnumMap::ETextVals::Text, bThrowIfNot)); } tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, tCQCMedia::EPLModes* const aeList, const tCIDLib::TCard4 c4Count) { tCIDLib::TCard4 c4Cur = 0; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmSrc >> c4Cur; aeList[c4Index] = tCQCMedia::EPLModes(c4Cur); } } tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const tCQCMedia::EPLModes* const aeList, const tCIDLib::TCard4 c4Count) { for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) strmTar << tCIDLib::TCard4(aeList[c4Index]); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::EPLModes eVal) { return emapEPLModes.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_EPLMgrActs[5] = { { tCIDLib::TInt4(tCQCMedia::EPLMgrActs::Rejected), 0, 0, { L"", L"", L"", L"Rejected", L"EPLMgrActs::Rejected", L"Rejected" } } , { tCIDLib::TInt4(tCQCMedia::EPLMgrActs::NoAction), 0, 0, { L"", L"", L"", L"NoAction", L"EPLMgrActs::NoAction", L"NoAction" } } , { tCIDLib::TInt4(tCQCMedia::EPLMgrActs::NewItem), 0, 0, { L"", L"", L"", L"NewItem", L"EPLMgrActs::NewItem", L"NewItem" } } , { tCIDLib::TInt4(tCQCMedia::EPLMgrActs::NewSelection), 0, 0, { L"", L"", L"", L"NewSelection", L"EPLMgrActs::NewSelection", L"NewItem" } } , { tCIDLib::TInt4(tCQCMedia::EPLMgrActs::Stop), 0, 0, { L"", L"", L"", L"Stop", L"EPLMgrActs::Stop", L"Stop" } } }; static TEnumMap emapEPLMgrActs ( L"EPLMgrActs" , 5 , kCIDLib::False , aeitemValues_EPLMgrActs , nullptr , tCIDLib::TCard4(tCQCMedia::EPLMgrActs::Count) ); const TString& tCQCMedia::strXlatEPLMgrActs(const tCQCMedia::EPLMgrActs eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapEPLMgrActs.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::Text, bThrowIfNot); } tCQCMedia::EPLMgrActs tCQCMedia::eXlatEPLMgrActs(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::EPLMgrActs(emapEPLMgrActs.i4MapEnumText(strVal, TEnumMap::ETextVals::Text, bThrowIfNot)); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::EPLMgrActs eVal) { return emapEPLMgrActs.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_EPLMgrSelRes[3] = { { tCIDLib::TInt4(tCQCMedia::EPLMgrSelRes::Empty), 0, 0, { L"", L"", L"", L"Empty", L"EPLMgrSelRes::Empty", L"" } } , { tCIDLib::TInt4(tCQCMedia::EPLMgrSelRes::NewItem), 0, 0, { L"", L"", L"", L"NewItem", L"EPLMgrSelRes::NewItem", L"" } } , { tCIDLib::TInt4(tCQCMedia::EPLMgrSelRes::NewAndChanged), 0, 0, { L"", L"", L"", L"NewAndChanged", L"EPLMgrSelRes::NewAndChanged", L"" } } }; static TEnumMap emapEPLMgrSelRes ( L"EPLMgrSelRes" , 3 , kCIDLib::False , aeitemValues_EPLMgrSelRes , nullptr , tCIDLib::TCard4(tCQCMedia::EPLMgrSelRes::Count) ); tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::EPLMgrSelRes eVal) { return emapEPLMgrSelRes.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_ERArtTypes[3] = { { tCIDLib::TInt4(tCQCMedia::ERArtTypes::SmlCover), 0, 0, { L"", L"", L"", L"SmlCover", L"ERArtTypes::SmlCover", L"Thumbnail" } } , { tCIDLib::TInt4(tCQCMedia::ERArtTypes::LrgCover), 0, 0, { L"", L"", L"", L"LrgCover", L"ERArtTypes::LrgCover", L"Large" } } , { tCIDLib::TInt4(tCQCMedia::ERArtTypes::Poster), 0, 0, { L"", L"", L"", L"Poster", L"ERArtTypes::Poster", L"Poster" } } }; static TEnumMap emapERArtTypes ( L"ERArtTypes" , 3 , kCIDLib::False , aeitemValues_ERArtTypes , nullptr , tCIDLib::TCard4(tCQCMedia::ERArtTypes::Count) ); const TString& tCQCMedia::strXlatERArtTypes(const tCQCMedia::ERArtTypes eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapERArtTypes.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::Text, bThrowIfNot); } tCQCMedia::ERArtTypes tCQCMedia::eXlatERArtTypes(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::ERArtTypes(emapERArtTypes.i4MapEnumText(strVal, TEnumMap::ETextVals::Text, bThrowIfNot)); } tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, tCQCMedia::ERArtTypes* const aeList, const tCIDLib::TCard4 c4Count) { tCIDLib::TCard4 c4Cur = 0; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmSrc >> c4Cur; aeList[c4Index] = tCQCMedia::ERArtTypes(c4Cur); } } tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const tCQCMedia::ERArtTypes* const aeList, const tCIDLib::TCard4 c4Count) { for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) strmTar << tCIDLib::TCard4(aeList[c4Index]); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::ERArtTypes eVal) { return emapERArtTypes.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_ERendFlds[39] = { { tCIDLib::TInt4(tCQCMedia::ERendFlds::ActiveRepo), 0, 0, { L"", L"MREND#ActiveRepository", L"", L"ActiveRepo", L"ERendFlds::ActiveRepo", L"ActiveRepository" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::ClearPL), 0, 0, { L"", L"MREND#ClearPlaylist", L"", L"ClearPL", L"ERendFlds::ClearPL", L"ClearPlaylist" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurAspect), 0, 0, { L"", L"MREND#CurAspectRatio", L"", L"CurAspect", L"ERendFlds::CurAspect", L"CurAspectRatio" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurCast), 0, 0, { L"", L"MREND#CurCast", L"", L"CurCast", L"ERendFlds::CurCast", L"CurCast" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurColArtist), 0, 0, { L"", L"MREND#CurColArtist", L"", L"CurColArtist", L"ERendFlds::CurColArtist", L"CurColArtist" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurColCookie), 0, 0, { L"", L"MREND#CurColCookie", L"", L"CurColCookie", L"ERendFlds::CurColCookie", L"CurColCookie" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurColName), 0, 0, { L"", L"MREND#CurColName", L"", L"CurColName", L"ERendFlds::CurColName", L"CurColName" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurDescr), 0, 0, { L"", L"MREND#CurDescr", L"", L"CurDescr", L"ERendFlds::CurDescr", L"CurDescr" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurItName), 0, 0, { L"", L"MREND#CurItemName", L"", L"CurItName", L"ERendFlds::CurItName", L"CurItemName" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurItArtist), 0, 0, { L"", L"MREND#CurItemArtist", L"", L"CurItArtist", L"ERendFlds::CurItArtist", L"CurItemArtist" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurItCookie), 0, 0, { L"", L"MREND#CurItemCookie", L"", L"CurItCookie", L"ERendFlds::CurItCookie", L"CurItemCookie" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurItTime), 0, 0, { L"", L"MREND#CurItemTime", L"", L"CurItTime", L"ERendFlds::CurItTime", L"CurItemTime" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurItTotal), 0, 0, { L"", L"MREND#CurItemTotal", L"", L"CurItTotal", L"ERendFlds::CurItTotal", L"CurItemTotal" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurLabel), 0, 0, { L"", L"MREND#CurLabel", L"", L"CurLabel", L"ERendFlds::CurLabel", L"CurLabel" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurLeadActor), 0, 0, { L"", L"MREND#CurLeadActor", L"", L"CurLeadActor", L"ERendFlds::CurLeadActor", L"CurLeadActor" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurRating), 0, 0, { L"", L"MREND#CurRating", L"", L"CurRating", L"ERendFlds::CurRating", L"CurRating" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurTiName), 0, 0, { L"", L"MREND#CurTitleName", L"", L"CurTiName", L"ERendFlds::CurTiName", L"CurTitleName" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurTiCookie), 0, 0, { L"", L"MREND#CurTitleCookie", L"", L"CurTiCookie", L"ERendFlds::CurTiCookie", L"CurTitleCookie" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::CurYear), 0, 0, { L"", L"MREND#CurYear", L"", L"CurYear", L"ERendFlds::CurYear", L"CurYear" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::DelPLItem), 0, 0, { L"", L"MREND#DelPlaylistItem", L"", L"DelPLItem", L"ERendFlds::DelPLItem", L"DelPlaylistItem" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::EnqMedia), 0, 0, { L"", L"MREND#EnqueueMedia", L"", L"EnqMedia", L"ERendFlds::EnqMedia", L"EnqueueMedia" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::PBPercent), 0, 0, { L"", L"MREND#PBPercent", L"", L"PBPercent", L"ERendFlds::PBPercent", L"PBPercent" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::PlayMedia), 0, 0, { L"", L"MREND#PlayMedia", L"", L"PlayMedia", L"ERendFlds::PlayMedia", L"PlayMedia" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::PLItemCnt), 0, 0, { L"", L"MREND#PLItemCnt", L"", L"PLItemCnt", L"ERendFlds::PLItemCnt", L"PLItemCnt" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::PLItemKey), 0, 0, { L"", L"MREND#PLItemKey", L"", L"PLItemKey", L"ERendFlds::PLItemKey", L"PLItemKey" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::PLIndex), 0, 0, { L"", L"MREND#PLIndex", L"", L"PLIndex", L"ERendFlds::PLIndex", L"PLIndex" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::PLMode), 0, 0, { L"", L"MREND#PlaylistMode", L"", L"PLMode", L"ERendFlds::PLMode", L"PlaylistMode" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::PLSerialNum), 0, 0, { L"", L"MREND#PLSerialNum", L"", L"PLSerialNum", L"ERendFlds::PLSerialNum", L"PLSerialNum" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::SelPLItem), 0, 0, { L"", L"MREND#SelPlaylistItem", L"", L"SelPLItem", L"ERendFlds::SelPLItem", L"SelPlaylistItem" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::SetRandomCat), 0, 0, { L"", L"MREND#SetRandomCat", L"", L"SetRandomCat", L"ERendFlds::SetRandomCat", L"SetRandomCat" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::SetRepo), 0, 0, { L"", L"MREND#SetRepository", L"", L"SetRepo", L"ERendFlds::SetRepo", L"SetRepository" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::ZoneNum), 0, 0, { L"", L"MREND#ZoneNum", L"", L"ZoneNum", L"ERendFlds::ZoneNum", L"ZoneNum" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::Power), 0, 0, { L"", L"PWR#Power", L"", L"Power", L"ERendFlds::Power", L"Power" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::PowerStatus), 0, 0, { L"", L"PWR#Status", L"", L"PowerStatus", L"ERendFlds::PowerStatus", L"Status" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::AdjustVolume), 0, 0, { L"", L"AUD#AdjustVolume", L"", L"AdjustVolume", L"ERendFlds::AdjustVolume", L"AdjustVolume" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::Mute), 0, 0, { L"", L"AUD#Mute", L"", L"Mute", L"ERendFlds::Mute", L"Mute" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::Volume), 0, 0, { L"", L"AUD#Volume", L"", L"Volume", L"ERendFlds::Volume", L"Volume" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::MediaState), 0, 0, { L"", L"MTRANS#MediaState", L"", L"MediaState", L"ERendFlds::MediaState", L"MediaState" } } , { tCIDLib::TInt4(tCQCMedia::ERendFlds::Transport), 0, 0, { L"", L"MTRANS#Transport", L"", L"Transport", L"ERendFlds::Transport", L"Transport" } } }; static TEnumMap emapERendFlds ( L"ERendFlds" , 39 , kCIDLib::False , aeitemValues_ERendFlds , nullptr , tCIDLib::TCard4(tCQCMedia::ERendFlds::Count) ); const TString& tCQCMedia::strAltXlatERendFlds(const tCQCMedia::ERendFlds eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapERendFlds.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::AltText, bThrowIfNot); } tCQCMedia::ERendFlds tCQCMedia::eAltXlatERendFlds(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::ERendFlds(emapERendFlds.i4MapEnumText(strVal, TEnumMap::ETextVals::AltText, bThrowIfNot)); } const TString& tCQCMedia::strXlatERendFlds(const tCQCMedia::ERendFlds eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapERendFlds.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::Text, bThrowIfNot); } tCQCMedia::ERendFlds tCQCMedia::eXlatERendFlds(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::ERendFlds(emapERendFlds.i4MapEnumText(strVal, TEnumMap::ETextVals::Text, bThrowIfNot)); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::ERendFlds eVal) { return emapERendFlds.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_ESortOrders[14] = { { tCIDLib::TInt4(tCQCMedia::ESortOrders::Artist), 0, 0, { L"", L"", L"", L"Artist", L"ESortOrders::Artist", L"By Artist" } } , { tCIDLib::TInt4(tCQCMedia::ESortOrders::BitDepth), 0, 0, { L"", L"", L"", L"BitDepth", L"ESortOrders::BitDepth", L"By Bit Depth" } } , { tCIDLib::TInt4(tCQCMedia::ESortOrders::BitRate), 0, 0, { L"", L"", L"", L"BitRate", L"ESortOrders::BitRate", L"By Bit Rate" } } , { tCIDLib::TInt4(tCQCMedia::ESortOrders::Channels), 0, 0, { L"", L"", L"", L"Channels", L"ESortOrders::Channels", L"By Channels" } } , { tCIDLib::TInt4(tCQCMedia::ESortOrders::DateAdded), 0, 0, { L"", L"", L"", L"DateAdded", L"ESortOrders::DateAdded", L"By Date Added" } } , { tCIDLib::TInt4(tCQCMedia::ESortOrders::DateAddedDesc), 0, 0, { L"", L"", L"", L"DateAddedDesc", L"ESortOrders::DateAddedDesc", L"By Date Added Desc" } } , { tCIDLib::TInt4(tCQCMedia::ESortOrders::SampleRate), 0, 0, { L"", L"", L"", L"SampleRate", L"ESortOrders::SampleRate", L"By Sample Rate" } } , { tCIDLib::TInt4(tCQCMedia::ESortOrders::SeqNum), 0, 0, { L"", L"", L"", L"SeqNum", L"ESortOrders::SeqNum", L"By Seq Number" } } , { tCIDLib::TInt4(tCQCMedia::ESortOrders::SeqNumDesc), 0, 0, { L"", L"", L"", L"SeqNumDesc", L"ESortOrders::SeqNumDesc", L"By Seq Number Desc" } } , { tCIDLib::TInt4(tCQCMedia::ESortOrders::Title), 0, 0, { L"", L"", L"", L"Title", L"ESortOrders::Title", L"By Title" } } , { tCIDLib::TInt4(tCQCMedia::ESortOrders::UserRating), 0, 0, { L"", L"", L"", L"UserRating", L"ESortOrders::UserRating", L"By User Rating" } } , { tCIDLib::TInt4(tCQCMedia::ESortOrders::UserRatingDesc), 0, 0, { L"", L"", L"", L"UserRatingDesc", L"ESortOrders::UserRatingDesc", L"By User Rating Desc" } } , { tCIDLib::TInt4(tCQCMedia::ESortOrders::Year), 0, 0, { L"", L"", L"", L"Year", L"ESortOrders::Year", L"By Year" } } , { tCIDLib::TInt4(tCQCMedia::ESortOrders::YearDesc), 0, 0, { L"", L"", L"", L"YearDesc", L"ESortOrders::YearDesc", L"By Year Desc" } } }; static TEnumMap emapESortOrders ( L"ESortOrders" , 14 , kCIDLib::False , aeitemValues_ESortOrders , nullptr , tCIDLib::TCard4(tCQCMedia::ESortOrders::Count) ); tCIDLib::TVoid tCQCMedia::FormatESortOrders(TString& strToFill, const TString& strPrefix, const tCIDLib::TCh chSepChar, const TEnumMap::ETextVals eVal) { emapESortOrders.FormatValues(strToFill, strPrefix, chSepChar, eVal); } const TString& tCQCMedia::strXlatESortOrders(const tCQCMedia::ESortOrders eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapESortOrders.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::Text, bThrowIfNot); } tCQCMedia::ESortOrders tCQCMedia::eXlatESortOrders(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::ESortOrders(emapESortOrders.i4MapEnumText(strVal, TEnumMap::ETextVals::Text, bThrowIfNot)); } tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, tCQCMedia::ESortOrders* const aeList, const tCIDLib::TCard4 c4Count) { tCIDLib::TCard4 c4Cur = 0; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmSrc >> c4Cur; aeList[c4Index] = tCQCMedia::ESortOrders(c4Cur); } } tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const tCQCMedia::ESortOrders* const aeList, const tCIDLib::TCard4 c4Count) { for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) strmTar << tCIDLib::TCard4(aeList[c4Index]); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::ESortOrders eVal) { return emapESortOrders.bIsValidEnum(tCIDLib::TCard4(eVal)); } static TEnumMap::TEnumValItem aeitemValues_ETransCmds[7] = { { tCIDLib::TInt4(tCQCMedia::ETransCmds::Pause), 0, 0, { L"", L"", L"", L"Pause", L"ETransCmds::Pause", L"" } } , { tCIDLib::TInt4(tCQCMedia::ETransCmds::Play), 0, 0, { L"", L"", L"", L"Play", L"ETransCmds::Play", L"" } } , { tCIDLib::TInt4(tCQCMedia::ETransCmds::Stop), 0, 0, { L"", L"", L"", L"Stop", L"ETransCmds::Stop", L"" } } , { tCIDLib::TInt4(tCQCMedia::ETransCmds::Next), 0, 0, { L"", L"", L"", L"Next", L"ETransCmds::Next", L"" } } , { tCIDLib::TInt4(tCQCMedia::ETransCmds::Previous), 0, 0, { L"", L"", L"", L"Previous", L"ETransCmds::Previous", L"" } } , { tCIDLib::TInt4(tCQCMedia::ETransCmds::FF), 0, 0, { L"", L"", L"", L"FF", L"ETransCmds::FF", L"" } } , { tCIDLib::TInt4(tCQCMedia::ETransCmds::Rewind), 0, 0, { L"", L"", L"", L"Rewind", L"ETransCmds::Rewind", L"" } } }; static TEnumMap emapETransCmds ( L"ETransCmds" , 7 , kCIDLib::False , aeitemValues_ETransCmds , nullptr , tCIDLib::TCard4(tCQCMedia::ETransCmds::Count) ); const TString& tCQCMedia::strXlatETransCmds(const tCQCMedia::ETransCmds eVal, const tCIDLib::TBoolean bThrowIfNot) { return emapETransCmds.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::BaseName, bThrowIfNot); } tCQCMedia::ETransCmds tCQCMedia::eXlatETransCmds(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot) { return tCQCMedia::ETransCmds(emapETransCmds.i4MapEnumText(strVal, TEnumMap::ETextVals::BaseName, bThrowIfNot)); } tCIDLib::TVoid TBinInStream_ReadArray(TBinInStream& strmSrc, tCQCMedia::ETransCmds* const aeList, const tCIDLib::TCard4 c4Count) { tCIDLib::TCard4 c4Cur = 0; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { strmSrc >> c4Cur; aeList[c4Index] = tCQCMedia::ETransCmds(c4Cur); } } tCIDLib::TVoid TBinOutStream_WriteArray(TBinOutStream& strmTar, const tCQCMedia::ETransCmds* const aeList, const tCIDLib::TCard4 c4Count) { for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) strmTar << tCIDLib::TCard4(aeList[c4Index]); } tCIDLib::TBoolean tCQCMedia::bIsValidEnum(const tCQCMedia::ETransCmds eVal) { return emapETransCmds.bIsValidEnum(tCIDLib::TCard4(eVal)); }
48.346958
167
0.703211
MarkStega
fefcd231379463fc6db0d77a20e80bb9934052b1
410
cpp
C++
src/13000/13567.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
8
2018-04-12T15:54:09.000Z
2020-06-05T07:41:15.000Z
src/13000/13567.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
src/13000/13567.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int dx[]={1, 0, -1, 0}; int dy[]={0, 1, 0, -1}; int main() { int m, n, d; string cmd; cin>>m>>n; int x=0, y=0, cd=0; while(n--) { cin>>cmd>>d; if(cmd=="MOVE") { x=x+dx[cd]*d, y=y+dy[cd]*d; if(x<0 || x>=m || y<0 || y>=m) { cout<<-1; return 0; } } else { cd=(d?(cd+3)%4:(cd+1)%4); } } cout<<x<<" "<<y; }
11.714286
33
0.436585
upple
fefedf20b297f9be28d24060d24bb34005645607
34,681
cpp
C++
src/forks.cpp
nextcashtech/bitcoin
15f62465e909ef676d1cd41515776d0db2eeefc1
[ "MIT" ]
25
2018-04-14T05:35:48.000Z
2019-04-21T00:05:38.000Z
src/forks.cpp
nextcashtech/bitcoin
15f62465e909ef676d1cd41515776d0db2eeefc1
[ "MIT" ]
1
2020-01-23T16:39:45.000Z
2020-01-23T16:39:45.000Z
src/forks.cpp
nextcashtech/bitcoin
15f62465e909ef676d1cd41515776d0db2eeefc1
[ "MIT" ]
1
2019-04-05T14:12:26.000Z
2019-04-05T14:12:26.000Z
/************************************************************************** * Copyright 2017-2018 NextCash, LLC * * Contributors : * * Curtis Ellis <curtis@nextcash.tech> * * Distributed under the MIT software license, see the accompanying * * file license.txt or http://www.opensource.org/licenses/mit-license.php * **************************************************************************/ #include "forks.hpp" #include "log.hpp" #include "file_stream.hpp" #include "base.hpp" #include "info.hpp" #include "chain.hpp" #include <algorithm> namespace BitCoin { void SoftFork::write(NextCash::OutputStream *pStream) { pStream->writeByte(name.length()); pStream->writeString(name); pStream->writeUnsignedInt(id); pStream->writeByte(bit); pStream->writeUnsignedInt(startTime); pStream->writeUnsignedInt(timeout); pStream->writeByte(state); pStream->writeUnsignedInt(lockedHeight); } bool SoftFork::read(NextCash::InputStream *pStream) { if(pStream->remaining() < 1) return false; unsigned int nameLength = pStream->readByte(); if(pStream->remaining() < nameLength + 18) return false; name = pStream->readString(nameLength); id = pStream->readUnsignedInt(); bit = pStream->readByte(); startTime = pStream->readUnsignedInt(); timeout = pStream->readUnsignedInt(); state = static_cast<SoftFork::State>(pStream->readByte()); lockedHeight = pStream->readUnsignedInt(); return true; } bool SoftFork::isActive(unsigned int pHeight) { return lockedHeight != NOT_LOCKED && pHeight >= (unsigned int)lockedHeight + RETARGET_PERIOD; } const char *SoftFork::stateName() { switch(state) { default: case UNDEFINED: return "Undefined"; case DEFINED: return "Defined"; case STARTED: return "Started"; case LOCKED_IN: return "Locked In"; case ACTIVE: return "Active"; case FAILED: return "Failed"; } } NextCash::String SoftFork::description() { NextCash::String result; switch(state) { default: case UNDEFINED: result = "Undefined"; break; case DEFINED: { NextCash::String startTimeText; startTimeText.writeFormattedTime(startTime); result.writeFormatted("Defined : start at %s", startTimeText.text()); break; } case STARTED: { NextCash::String timeoutText; timeoutText.writeFormattedTime(timeout); result.writeFormatted("Started : timeout at %s", timeoutText.text()); break; } case LOCKED_IN: result.writeFormatted("Locked in at block height %d", lockedHeight); break; case ACTIVE: result.writeFormatted("Active at block height %d", lockedHeight + RETARGET_PERIOD); break; case FAILED: NextCash::String timeoutText; timeoutText.writeFormattedTime(timeout); result.writeFormatted("Failed : timeout at %s", timeoutText.text()); break; } return result; } void SoftFork::revert(Chain *pChain, unsigned int pHeight) { switch(state) { default: case UNDEFINED: case DEFINED: break; case STARTED: if(pChain->time(pHeight - 1) < startTime) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Soft fork %s reverted from STARTED to DEFINED", name.text()); state = DEFINED; } break; case LOCKED_IN: if(pHeight <= lockedHeight) { lockedHeight = NOT_LOCKED; if(pChain->time(pHeight - 1) < startTime) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Soft fork %s reverted from LOCKED_IN to DEFINED", name.text()); state = DEFINED; } else { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Soft fork %s reverted from LOCKED_IN to STARTED", name.text()); state = STARTED; } } break; case ACTIVE: if(pHeight <= lockedHeight) { lockedHeight = NOT_LOCKED; if(pChain->time(pHeight - 1) < startTime) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Soft fork %s reverted from ACTIVE to DEFINED", name.text()); state = DEFINED; } else { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Soft fork %s reverted from ACTIVE to STARTED", name.text()); state = STARTED; } } else if(pHeight <= lockedHeight + RETARGET_PERIOD) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Soft fork %s reverted from ACTIVE to LOCKED_IN", name.text()); state = LOCKED_IN; } break; case FAILED: if(pChain->time(pHeight - 1) < startTime) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Soft fork %s reverted from FAILED to DEFINED", name.text()); state = DEFINED; } else if(pChain->time(pHeight - 1) < timeout) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Soft fork %s reverted from FAILED to STARTED", name.text()); state = STARTED; } break; } } Forks::Forks() : mMutex("Forks") { mHeight = 0; mBlockMaxSize = HARD_MAX_BLOCK_SIZE; mElementMaxSize = 520; mCashActivationBlockHeight = 0; mCashFork201711BlockHeight = 0; mCashFork201805BlockHeight = 0; mCashFork201811BlockHeight = 0; mCashForkID = 0; mModified = false; for(unsigned int i = 0; i < 3; i++) { mBlockVersionEnabledHeights[i] = 0; mBlockVersionRequiredHeights[i] = 0; } switch(network()) { case MAINNET: mThreshHold = 1916; // Add known soft forks mForks.push_back(new SoftFork("BIP-0068,BIP-0112,BIP-0113", SoftFork::BIP0068, 0, 1462060800, 1493596800)); mForks.push_back(new SoftFork("BIP-0141", SoftFork::BIP0141, 1, 1479168000, 1510704000)); mForks.push_back(new SoftFork("BIP-0091", SoftFork::BIP0091, 4, 1496275200, 1510704000)); break; default: case TESTNET: mThreshHold = 1512; // Add known soft forks mForks.push_back(new SoftFork("BIP-0068,BIP-0112,BIP-0113", SoftFork::BIP0068, 0, 1462060800, 1493596800)); mForks.push_back(new SoftFork("BIP-0141", SoftFork::BIP0141, 1, 1462060800, 1493596800)); break; } } Forks::~Forks() { mMutex.lock(); for(std::vector<SoftFork *>::const_iterator softFork = mForks.begin(); softFork != mForks.end(); ++softFork) delete *softFork; mMutex.unlock(); } bool Forks::softForkIsActive(unsigned int pHeight, unsigned int pID) { bool result = false; mMutex.lock(); for(std::vector<SoftFork *>::const_iterator softFork = mForks.begin(); softFork != mForks.end(); ++softFork) if((*softFork)->id == pID) { result = (*softFork)->isActive(pHeight); break; } mMutex.unlock(); return result; } void Forks::process(Chain *pChain, unsigned int pHeight) { mMutex.lock(); if(mBlockVersionRequiredHeights[2] == 0) { unsigned int totalCount = 1000; unsigned int activateCount = 750; unsigned int requireCount = 950; if(network() == TESTNET) { totalCount = 100; activateCount = 51; requireCount = 75; } // Update versions if(mBlockVersions.size() < totalCount && mBlockVersions.size() < pHeight) { mBlockVersions.clear(); for(unsigned int height = pHeight; mBlockVersions.size() < totalCount; --height) { mBlockVersions.push_front(pChain->version(height)); if(height == 0) break; } } mBlockVersions.push_back(pChain->version(pHeight)); while(mBlockVersions.size() > totalCount) mBlockVersions.pop_front(); unsigned int version4OrHigherCount = 0; unsigned int version3OrHigherCount = 0; unsigned int version2OrHigherCount = 0; for(std::list<int32_t>::iterator version = mBlockVersions.begin(); version != mBlockVersions.end(); ++version) switch(*version) { default: case 4: ++version4OrHigherCount; case 3: ++version3OrHigherCount; case 2: ++version2OrHigherCount; case 1: case 0: break; } // BIP-0065 if(version4OrHigherCount >= requireCount) { if(mBlockVersionRequiredHeights[2] == 0) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Version 4 blocks now required (height %d)", pHeight); mBlockVersionRequiredHeights[2] = pHeight; mModified = true; mBlockVersions.clear(); } if(mBlockVersionEnabledHeights[2] == 0) { mBlockVersionEnabledHeights[2] = pHeight; mModified = true; } } else if(mBlockVersionEnabledHeights[2] == 0 && version4OrHigherCount >= activateCount) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Version 4 blocks now enabled (height %d)", pHeight); mBlockVersionEnabledHeights[2] = pHeight; mModified = true; } // BIP-0066 if(version3OrHigherCount >= requireCount) { if(mBlockVersionRequiredHeights[1] == 0) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Version 3 blocks now required (height %d)", pHeight); mBlockVersionRequiredHeights[1] = pHeight; mModified = true; } if(mBlockVersionEnabledHeights[1] == 0) { mBlockVersionEnabledHeights[1] = pHeight; mModified = true; } } else if(mBlockVersionEnabledHeights[1] == 0 && version3OrHigherCount >= activateCount) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Version 3 blocks now enabled (height %d)", pHeight); mBlockVersionEnabledHeights[1] = pHeight; mModified = true; } // BIP-0034 if(version2OrHigherCount >= requireCount) { if(mBlockVersionRequiredHeights[0] == 0) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Version 2 blocks now required (height %d)", pHeight); mBlockVersionRequiredHeights[0] = pHeight; mModified = true; } if(mBlockVersionEnabledHeights[0] == 0) { mBlockVersionEnabledHeights[0] = pHeight; mModified = true; } } else if(mBlockVersionEnabledHeights[0] == 0 && version2OrHigherCount >= activateCount) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Version 2 blocks now enabled (height %d)", pHeight); mBlockVersionEnabledHeights[0] = pHeight; mModified = true; } } mHeight = pHeight; mModified = true; if(mBlockVersionRequiredHeights[2] != 0 && pHeight != 0 && pHeight % RETARGET_PERIOD == 0) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Updating at height %d", pHeight); uint32_t compositeValue = 0; int32_t version; Time medianTimePast = pChain->getMedianPastTime(pHeight, 11); for(std::vector<SoftFork *>::iterator softFork = mForks.begin(); softFork != mForks.end(); ++softFork) { compositeValue |= (0x01 << (*softFork)->bit); switch((*softFork)->state) { case SoftFork::DEFINED: if(medianTimePast > (*softFork)->timeout) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "(%s) failed at height %d", (*softFork)->name.text(), pHeight); (*softFork)->state = SoftFork::FAILED; mModified = true; } else if(medianTimePast > (*softFork)->startTime) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "(%s) started at height %d", (*softFork)->name.text(), pHeight); (*softFork)->state = SoftFork::STARTED; mModified = true; } break; case SoftFork::STARTED: { if(medianTimePast > (*softFork)->timeout) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "(%s) failed at height %d", (*softFork)->name.text(), pHeight); (*softFork)->state = SoftFork::FAILED; mModified = true; break; } unsigned int support = 0; int offset = 0; for(unsigned int height = pHeight; offset < RETARGET_PERIOD; --height, ++offset) { version = pChain->version(height); if((version & 0xE0000000) == 0x20000000 && (version >> (*softFork)->bit) & 0x01) ++support; if(height == 0) break; } if(support >= mThreshHold) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "(%s) locked in with support %d/%d at height %d", (*softFork)->name.text(), support, mThreshHold, pHeight); (*softFork)->lockedHeight = pHeight; (*softFork)->state = SoftFork::LOCKED_IN; mModified = true; } else { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "(%s) still started with support %d/%d at height %d", (*softFork)->name.text(), support, mThreshHold, pHeight); } break; } case SoftFork::LOCKED_IN: NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Soft fork (%s) active at height %d", (*softFork)->name.text(), pHeight); (*softFork)->state = SoftFork::ACTIVE; mModified = true; break; default: case SoftFork::ACTIVE: case SoftFork::FAILED: break; } } // Warn about unknown forks (bits set in version not corresponding to known soft forks) unsigned int i; unsigned int unknownSupport[29]; for(i = 0; i < 29; i++) unknownSupport[i] = 0; unsigned int offset = 0; for(unsigned int height = pHeight; offset < RETARGET_PERIOD; --height, ++offset) { version = pChain->version(height); if((version & 0xE0000000) != 0x20000000) { if(height == 0) break; else continue; } if((version | compositeValue) != compositeValue) { for(i = 0; i < 29; i++) if((version & (0x01 << i)) && !(compositeValue & (0x01 << i))) ++unknownSupport[i]; // Bit set in version and not in composite } if(height == 0) break; } for(i = 0; i < 29; i++) if(unknownSupport[i] > 0) { NextCash::Log::addFormatted(NextCash::Log::NOTIFICATION, BITCOIN_FORKS_LOG_NAME, "Unknown soft fork for bit %d with %d/%d support (height %d)", i, unknownSupport[i], RETARGET_PERIOD, pHeight); } } if(CASH_ACTIVATION_TIME != 0) { if(mCashActivationBlockHeight == 0) { if(pChain->time(pHeight) > CASH_ACTIVATION_TIME && pChain->getMedianPastTime(pHeight, 11) >= CASH_ACTIVATION_TIME) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Cash fork activated at block height %d", pHeight); mCashActivationBlockHeight = pHeight; mBlockMaxSize = CASH_START_MAX_BLOCK_SIZE; } } else if(mCashFork201711BlockHeight == 0) { if(pChain->time(pHeight) > CASH_FORK_201711_ACTIVATION_TIME && pChain->getMedianPastTime(pHeight, 11) >= CASH_FORK_201711_ACTIVATION_TIME) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Cash DAA activated at block height %d", pHeight); mCashFork201711BlockHeight = pHeight; } } else if(mCashFork201805BlockHeight == 0) { if(pChain->time(pHeight) > CASH_FORK_201805_ACTIVATION_TIME && pChain->getMedianPastTime(pHeight, 11) >= CASH_FORK_201805_ACTIVATION_TIME) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "2018 May fork activated at block height %d", pHeight); mCashFork201805BlockHeight = pHeight; mBlockMaxSize = FORK_201805_MAX_BLOCK_SIZE; } } else if(mCashFork201811BlockHeight == 0) { if(pChain->time(pHeight) > CASH_FORK_201811_ACTIVATION_TIME && pChain->getMedianPastTime(pHeight, 11) >= CASH_FORK_201811_ACTIVATION_TIME) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "2018 Nov fork activated at block height %d", pHeight); mCashFork201811BlockHeight = pHeight; mBlockMaxSize = FORK_201811_MAX_BLOCK_SIZE; } } } mMutex.unlock(); } void Forks::revert(Chain *pChain, unsigned int pHeight) { mMutex.lock(); mBlockVersions.clear(); // Back out any version enabled/required heights below new block height for(unsigned int i = 0; i < 3; ++i) { if(mBlockVersionRequiredHeights[i] != 0 && mBlockVersionRequiredHeights[i] >= pHeight) mBlockVersionRequiredHeights[i] = 0; if(mBlockVersionEnabledHeights[i] != 0 && mBlockVersionEnabledHeights[i] >= pHeight) mBlockVersionEnabledHeights[i] = 0; } if(mCashFork201811BlockHeight != 0 && pHeight <= mCashFork201811BlockHeight) { // Undo Nov 2018 fork mCashFork201811BlockHeight = 0; mBlockMaxSize = FORK_201805_MAX_BLOCK_SIZE; } if(mCashFork201805BlockHeight != 0 && pHeight <= mCashFork201805BlockHeight) { // Undo May 2018 fork mCashFork201805BlockHeight = 0; mBlockMaxSize = CASH_START_MAX_BLOCK_SIZE; } if(mCashFork201711BlockHeight != 0 && pHeight <= mCashFork201711BlockHeight) mCashFork201711BlockHeight = 0; // Undo Nov 2017 fork if(mCashActivationBlockHeight != 0 && pHeight <= mCashActivationBlockHeight) { // Undo cash fork mCashActivationBlockHeight = 0; mBlockMaxSize = HARD_MAX_BLOCK_SIZE; } for(std::vector<SoftFork *>::iterator softFork = mForks.begin(); softFork != mForks.end(); ++softFork) (*softFork)->revert(pChain, pHeight); mHeight = pHeight; mModified = true; mMutex.unlock(); } void Forks::reset() { mMutex.lock(); mBlockVersions.clear(); for(unsigned int i = 0; i < 3; ++i) { mBlockVersionEnabledHeights[i] = 0; mBlockVersionRequiredHeights[i] = 0; } mCashActivationBlockHeight = 0; mCashFork201711BlockHeight = 0; mCashFork201805BlockHeight = 0; mCashFork201811BlockHeight = 0; mCashForkID = 0; mBlockMaxSize = HARD_MAX_BLOCK_SIZE; for(std::vector<SoftFork *>::iterator softFork = mForks.begin(); softFork != mForks.end(); ++softFork) (*softFork)->reset(); mMutex.unlock(); } void Forks::add(SoftFork *pSoftFork, bool pLocked) { if(!pLocked) mMutex.lock(); // Overwrite if it is already in here bool found = false; for(std::vector<SoftFork *>::iterator softFork = mForks.begin(); softFork != mForks.end(); ++softFork) if((*softFork)->id == pSoftFork->id) { delete *softFork; *softFork = pSoftFork; found = true; break; } if(!found) mForks.push_back(pSoftFork); if(!pLocked) mMutex.unlock(); } bool Forks::load(Chain *pChain) { mMutex.lock(); NextCash::String filePathName = Info::instance().path(); filePathName.pathAppend("forks"); if(!NextCash::fileExists(filePathName)) { NextCash::Log::add(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "No forks file to load"); mMutex.unlock(); return true; } NextCash::FileInputStream file(filePathName); if(!file.isValid()) { NextCash::Log::add(NextCash::Log::ERROR, BITCOIN_FORKS_LOG_NAME, "Failed to open forks file"); mMutex.unlock(); return false; } // Read version unsigned int version = file.readUnsignedInt(); if(version != 1 && version != 2) { NextCash::Log::add(NextCash::Log::ERROR, BITCOIN_FORKS_LOG_NAME, "Unknown forks file version"); mMutex.unlock(); return false; } // Read height mHeight = file.readUnsignedInt(); // Read versions block heights for(unsigned int i = 0; i < 3; ++i) mBlockVersionEnabledHeights[i] = file.readUnsignedInt(); for(unsigned int i = 0; i < 3; ++i) mBlockVersionRequiredHeights[i] = file.readUnsignedInt(); unsigned int requiredBlockVersion = 1; if(mBlockVersionRequiredHeights[2] != 0) requiredBlockVersion = 4; else if(mBlockVersionRequiredHeights[1] != 0) requiredBlockVersion = 3; else if(mBlockVersionRequiredHeights[0] != 0) requiredBlockVersion = 2; unsigned int enabledBlockVersion = 1; if(mBlockVersionEnabledHeights[2] != 0) enabledBlockVersion = 4; else if(mBlockVersionEnabledHeights[1] != 0) enabledBlockVersion = 3; else if(mBlockVersionEnabledHeights[0] != 0) enabledBlockVersion = 2; NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Block versions %d/%d enabled/required", enabledBlockVersion, requiredBlockVersion); if(version == 1) { mCashActivationBlockHeight = file.readUnsignedInt(); mBlockMaxSize = file.readUnsignedInt(); mCashForkID = file.readUnsignedInt(); if(mCashActivationBlockHeight != 0) { NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Cash fork active since block height %d, max block size %d", mCashActivationBlockHeight, CASH_START_MAX_BLOCK_SIZE); // Determine Cash fork heights for(unsigned int height = mCashActivationBlockHeight; height <= mHeight; ++height) { if(mCashFork201711BlockHeight == 0) { if(pChain->time(height) > CASH_FORK_201711_ACTIVATION_TIME && pChain->getMedianPastTime(height, 11) > CASH_FORK_201711_ACTIVATION_TIME) { mCashFork201711BlockHeight = height; NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Cash DAA active since block height %d", mCashFork201711BlockHeight); } } else if(mCashFork201805BlockHeight == 0) { if(pChain->time(height) > CASH_FORK_201805_ACTIVATION_TIME && pChain->getMedianPastTime(height, 11) > CASH_FORK_201805_ACTIVATION_TIME) { mCashFork201805BlockHeight = height; NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "2018 May fork active since block height %d, max block size %d", mCashFork201805BlockHeight, FORK_201805_MAX_BLOCK_SIZE); } } else if(mCashFork201811BlockHeight == 0) { if(pChain->time(height) > CASH_FORK_201811_ACTIVATION_TIME && pChain->getMedianPastTime(height, 11) > CASH_FORK_201811_ACTIVATION_TIME) { mCashFork201811BlockHeight = height; NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "2018 Nov fork active since block height %d", mCashFork201811BlockHeight); } break; } } } } else if(version == 2) { mBlockMaxSize = file.readUnsignedInt(); mCashForkID = file.readUnsignedInt(); unsigned int cashForkCount = file.readUnsignedInt(); if(cashForkCount != 4) return false; mCashActivationBlockHeight = file.readUnsignedInt(); mCashFork201711BlockHeight = file.readUnsignedInt(); mCashFork201805BlockHeight = file.readUnsignedInt(); mCashFork201811BlockHeight = file.readUnsignedInt(); if(mCashActivationBlockHeight != 0) NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Cash fork active since block height %d", mCashActivationBlockHeight); if(mCashFork201711BlockHeight != 0) NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Cash DAA active since block height %d", mCashFork201711BlockHeight); if(mCashFork201805BlockHeight != 0) NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "2018 May fork active since block height %d", mCashFork201805BlockHeight); if(mCashFork201811BlockHeight != 0) NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "2018 Nov fork active since block height %d", mCashFork201811BlockHeight); NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Max block size %d", mBlockMaxSize); NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Cash fork ID 0x%08x", mCashForkID); } SoftFork *newSoftFork; while(file.remaining()) { newSoftFork = new SoftFork(); if(!newSoftFork->read(&file)) { delete newSoftFork; NextCash::Log::add(NextCash::Log::ERROR, BITCOIN_FORKS_LOG_NAME, "Failed to read soft fork"); mMutex.unlock(); return false; } add(newSoftFork, true); NextCash::Log::addFormatted(NextCash::Log::VERBOSE, BITCOIN_FORKS_LOG_NAME, "Loaded soft fork %s : %s", newSoftFork->name.text(), newSoftFork->description().text()); } mModified = false; NextCash::Log::addFormatted(NextCash::Log::INFO, BITCOIN_FORKS_LOG_NAME, "Loaded %d soft forks at height %d", mForks.size(), mHeight); mMutex.unlock(); return true; } bool Forks::save() { mMutex.lock(); if(!mModified) { mMutex.unlock(); return true; } NextCash::String filePathName = Info::instance().path(); filePathName.pathAppend("forks"); NextCash::FileOutputStream file(filePathName, true); if(!file.isValid()) { NextCash::Log::add(NextCash::Log::ERROR, BITCOIN_FORKS_LOG_NAME, "Failed to open soft forks file to save"); mMutex.unlock(); return false; } // Write version file.writeUnsignedInt(2); // Write height file.writeUnsignedInt(mHeight); // Write versions block heights for(unsigned int i = 0; i < 3; ++i) file.writeUnsignedInt(mBlockVersionEnabledHeights[i]); for(unsigned int i = 0; i < 3; ++i) file.writeUnsignedInt(mBlockVersionRequiredHeights[i]); // Write max size and cash fork ID file.writeUnsignedInt(mBlockMaxSize); file.writeUnsignedInt(mCashForkID); // Write cash fork block heights file.writeUnsignedInt(4); file.writeUnsignedInt(mCashActivationBlockHeight); file.writeUnsignedInt(mCashFork201711BlockHeight); file.writeUnsignedInt(mCashFork201805BlockHeight); file.writeUnsignedInt(mCashFork201811BlockHeight); for(std::vector<SoftFork *>::iterator softFork = mForks.begin(); softFork != mForks.end(); ++softFork) (*softFork)->write(&file); mModified = false; mMutex.unlock(); return true; } int32_t Forks::enabledBlockVersion(unsigned int pHeight) const { // Block version 1 is enabled by default // Height at offset 0 represents version 2 // Height at offset 1 represents version 3 // Height at offset 2 represents version 4 for(int i = 2; i >= 0; --i) if(mBlockVersionEnabledHeights[i] != 0 && mBlockVersionEnabledHeights[i] < pHeight) return i + 2; return 1; } int32_t Forks::requiredBlockVersion(unsigned int pHeight) const { // Block version 1 is enabled by default // Height at offset 0 represents version 2 // Height at offset 1 represents version 3 // Height at offset 2 represents version 4 for(int i = 2; i >= 0; --i) if(mBlockVersionRequiredHeights[i] != 0 && mBlockVersionRequiredHeights[i] < pHeight) return i + 2; return 1; } }
37.614967
103
0.509847
nextcashtech
3a0223685c4f1d1132c6952fb6507caafcd473fe
372
hpp
C++
Secp256k1/Random.hpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
108
2020-10-01T17:12:40.000Z
2022-03-30T09:18:03.000Z
Secp256k1/Random.hpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
94
2020-10-03T13:40:30.000Z
2022-03-30T09:18:00.000Z
Secp256k1/Random.hpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
17
2020-10-29T13:27:59.000Z
2022-03-18T13:05:03.000Z
#ifndef SECP256K1_RANDOM_HPP #define SECP256K1_RANDOM_HPP #include<cstdint> #include<memory> namespace Secp256k1 { /* A source of random data. */ class Random { private: class Impl; std::unique_ptr<Impl> pimpl; public: Random(); Random(Random&&) =delete; Random(Random const&) =delete; ~Random(); std::uint8_t get(); }; } #endif /* SECP256K1_RANDOM_HPP */
13.285714
33
0.704301
3nprob
3a02a9adf3067b91d36e9dcd8eaa303ab79ddd3f
2,275
cpp
C++
src/subprocessoutputview.cpp
chigraph/chigraph-gui
26e72f9cdc4c69f331601bbd485abc88e8620197
[ "Apache-2.0" ]
91
2017-04-14T20:23:39.000Z
2022-03-30T16:44:20.000Z
src/subprocessoutputview.cpp
chigraph/chigraph-gui
26e72f9cdc4c69f331601bbd485abc88e8620197
[ "Apache-2.0" ]
21
2017-04-14T23:43:15.000Z
2020-02-04T09:27:09.000Z
src/subprocessoutputview.cpp
chigraph/chigraph-gui
26e72f9cdc4c69f331601bbd485abc88e8620197
[ "Apache-2.0" ]
27
2017-05-08T07:52:35.000Z
2022-01-24T11:14:38.000Z
#include "subprocessoutputview.hpp" #include <llvm-c/BitWriter.h> #include <KLocalizedString> #include <KMessageBox> #include <QApplication> #include <QLabel> #include <QPlainTextEdit> #include <QVBoxLayout> #include <chi/Context.hpp> #include <chi/GraphModule.hpp> #include <chi/Support/Result.hpp> #include <chi/Support/TempFile.hpp> #include <filesystem> #include <iostream> namespace fs = std::filesystem; SubprocessOutputView::SubprocessOutputView(chi::GraphModule* module) : mModule(module) { // compile! chi::OwnedLLVMModule llmod; chi::Result res = module->context().compileModule(module->fullName(), chi::CompileSettings::Default, &llmod); if (!res) { KMessageBox::detailedError(this, "Failed to compile module", QString::fromStdString(res.dump())); return; } // write it to a temporary file fs::path tempBitcodeFile = chi::makeTempPath(".bc"); LLVMWriteBitcodeToFile(*llmod, tempBitcodeFile.string().c_str()); setReadOnly(true); std::filesystem::path chiPath = std::filesystem::path(QApplication::applicationFilePath().toStdString()).parent_path() / "chi"; #ifdef _WIN32 chiPath.replace_extension(".exe"); #endif Q_ASSERT(std::filesystem::is_regular_file(chiPath)); // run in lli mProcess = new QProcess(this); mProcess->setProgram(QString::fromStdString(chiPath.string())); auto args = QStringList() << QStringLiteral("interpret") << QStringLiteral("-i") << QString::fromStdString(tempBitcodeFile.string()) << QStringLiteral("-O2"); mProcess->setArguments(args); connect(mProcess, &QProcess::readyReadStandardOutput, this, [this] { appendPlainText(mProcess->readAllStandardOutput().constData()); }); connect(mProcess, &QProcess::readyReadStandardOutput, this, [this] { appendHtml("<span style='color:red'>" + QString(mProcess->readAllStandardOutput().constData()).toHtmlEscaped() + "</span>"); }); connect(mProcess, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), this, &SubprocessOutputView::processFinished); mProcess->start(); } void SubprocessOutputView::cancelProcess() { if (mProcess != nullptr) { mProcess->kill(); } }
30.333333
96
0.687912
chigraph
3a08d8c61bd6b7b2e8d356650546b3737b4ba8c3
2,059
hh
C++
src/Damage/StrainPolicy.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/Damage/StrainPolicy.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/Damage/StrainPolicy.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // StrainPolicy -- An implementation of UpdatePolicyBase specialized // for the updating the strain. // // Created by JMO, Sun Sep 26 16:15:17 PDT 2004 //----------------------------------------------------------------------------// #ifndef __Spheral_StrainPolicy_hh__ #define __Spheral_StrainPolicy_hh__ #include "DataBase/UpdatePolicyBase.hh" #include <string> namespace Spheral { // Forward declarations. template<typename Dimension> class State; template<typename Dimension> class StateDerivatives; template<typename Dimension> class FluidNodeList; template<typename Dimension, typename DataType> class Field; template<typename Dimension> class StrainModel; template<typename Dimension> class StrainPolicy: public UpdatePolicyBase<Dimension> { public: //--------------------------- Public Interface ---------------------------// // Useful typedefs typedef typename Dimension::Scalar Scalar; typedef typename Dimension::Vector Vector; typedef typename Dimension::Tensor Tensor; typedef typename Dimension::SymTensor SymTensor; typedef Field<Dimension, Scalar> FieldType; typedef typename UpdatePolicyBase<Dimension>::KeyType KeyType; // Constructors, destructor. StrainPolicy(); virtual ~StrainPolicy(); // Overload the methods describing how to update Fields. virtual void update(const KeyType& key, State<Dimension>& state, StateDerivatives<Dimension>& derivs, const double multiplier, const double t, const double dt); // Equivalence. virtual bool operator==(const UpdatePolicyBase<Dimension>& rhs) const; private: //--------------------------- Private Interface ---------------------------// StrainPolicy(const StrainPolicy& rhs); StrainPolicy& operator=(const StrainPolicy& rhs); }; } #else // Forward declaration. namespace Spheral { template<typename Dimension> class StrainPolicy; } #endif
30.731343
80
0.633803
jmikeowen
3a0bcae08a28734c3ae0467938fab0c9e3ce4e6f
2,461
cc
C++
Mu2eUtilities/src/MedianCalculator.cc
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
1
2021-06-23T22:09:28.000Z
2021-06-23T22:09:28.000Z
Mu2eUtilities/src/MedianCalculator.cc
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
125
2020-04-03T13:44:30.000Z
2021-10-15T21:29:57.000Z
Mu2eUtilities/src/MedianCalculator.cc
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <iostream> #include <memory> #include "cetlib_except/exception.h" #include "Mu2eUtilities/inc/MedianCalculator.hh" namespace mu2e { float MedianCalculator::weightedMedian(){ //now, we need to loop over it and evaluate the median size_t v_size = _vec.size(); if (v_size ==0) { throw cet::exception("MATH")<<"No entries in the vector: median undefined" << std::endl; } if (v_size == 1){ return _vec[0].val; } if (_needsSorting){ std::sort(_vec.begin(), _vec.end(), MedianDatacomp()); _needsSorting = false; }else { return _weightedMedian; } float sum(0); size_t id(0); sum = _totalWeight - _vec[0].wg; while (sum > 0.5*_totalWeight){ ++id; sum -= _vec[id].wg; } float over((sum)/_totalWeight); float interpolation(0); if (v_size %2 == 0) { interpolation = _vec[id].val * over + _vec[id+1].val * (1.-over); }else { float w2 = (sum)/_totalWeight; float w1 = (sum + _vec[id].wg )/_totalWeight; float val1 = _vec[id-1].val*w1 + _vec[id].val*(1.-w1); float val2 = _vec[id].val*w2 + _vec[id+1].val*(1.-w2); interpolation = 0.5*(val1 + val2); } //cache the result _weightedMedian = interpolation; return interpolation; } float MedianCalculator::unweightedMedian(){ //now, we need to loop over it and evaluate the median size_t v_size = _vec.size(); if (v_size ==0) { throw cet::exception("MATH")<<"No entries in the vector: median undefined" << std::endl; } if (v_size == 1){ return _vec[0].val; } if (_needsSorting){ std::sort(_vec.begin(), _vec.end(), MedianDatacomp()); _needsSorting = false; }else { return _unweightedMedian; } float totWg(_vec.size()); size_t id(0); float interpolation(0); if (v_size %2 == 0) { id = v_size/2 - 1; interpolation = _vec[id].val * 0.5 + _vec[id+1].val * 0.5; }else { id = v_size/2; float sum(id); float w2 = (sum)/totWg; float w1 = (sum + 1.)/totWg; float val1 = _vec[id-1].val*w1 + _vec[id].val *(1.-w1); float val2 = _vec[id].val *w2 + _vec[id+1].val*(1.-w2); interpolation = 0.5*(val1 + val2); } //cache the result _weightedMedian = interpolation; return interpolation; } }
25.635417
94
0.562779
lborrel
3a0de775ed00af0479eb3e1787133abbccf3e7e2
5,864
cpp
C++
framework/src/service/ServiceListenerEntry.cpp
hkgmahwa/CppMicroServices
05260dcf70e5f161da5093a5c8547b00d4d626ac
[ "Apache-2.0" ]
1
2020-12-08T16:21:45.000Z
2020-12-08T16:21:45.000Z
framework/src/service/ServiceListenerEntry.cpp
iHouLei/CppMicroServices
aa9cc47dde75ba9ead18df399ce08269c15e3aa1
[ "Apache-2.0" ]
null
null
null
framework/src/service/ServiceListenerEntry.cpp
iHouLei/CppMicroServices
aa9cc47dde75ba9ead18df399ce08269c15e3aa1
[ "Apache-2.0" ]
null
null
null
/*============================================================================= Library: CppMicroServices Copyright (c) The CppMicroServices developers. See the COPYRIGHT file at the top-level directory of this distribution and at https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT . Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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 "cppmicroservices/GlobalConfig.h" US_MSVC_PUSH_DISABLE_WARNING( 4180) // qualifier applied to function type has no meaning; ignored #include "ServiceListenerEntry.h" #include "ServiceListenerHookPrivate.h" #include <cassert> namespace cppmicroservices { struct ServiceListenerCompare : std::function<bool(ServiceListener, ServiceListener)> { bool operator()(const ServiceListener& f1, const ServiceListener& f2) const { return f1.target<void(const ServiceEvent&)>() == f2.target<void(const ServiceEvent&)>(); } }; class ServiceListenerEntryData : public ServiceListenerHook::ListenerInfoData { public: ServiceListenerEntryData(const ServiceListenerEntryData&) = delete; ServiceListenerEntryData& operator=(const ServiceListenerEntryData&) = delete; ServiceListenerEntryData(const std::shared_ptr<BundleContextPrivate>& context, const ServiceListener& l, void* data, ListenerTokenId tokenId, const std::string& filter) : ServiceListenerHook::ListenerInfoData(context, l, data, tokenId, filter) , ldap() , hashValue(0) { if (!filter.empty()) { ldap = LDAPExpr(filter); } } ~ServiceListenerEntryData() override = default; LDAPExpr ldap; /** * The elements of "simple" filters are cached, for easy lookup. * * The grammar for simple filters is as follows: * * <pre> * Simple = '(' attr '=' value ')' * | '(' '|' Simple+ ')' * </pre> * where <code>attr</code> is one of Constants#OBJECTCLASS, * Constants#SERVICE_ID or Constants#SERVICE_PID, and * <code>value</code> must not contain a wildcard character. * <p> * The index of the vector determines which key the cache is for * (see ServiceListenerState#hashedKeys). For each key, there is * a vector pointing out the values which are accepted by this * ServiceListenerEntry's filter. This cache is maintained to make * it easy to remove this service listener. */ LDAPExpr::LocalCache local_cache; std::size_t hashValue; }; ServiceListenerEntry::ServiceListenerEntry() = default; ServiceListenerEntry::ServiceListenerEntry(const ServiceListenerEntry&) = default; ServiceListenerEntry::ServiceListenerEntry( const ServiceListenerHook::ListenerInfo& info) : ServiceListenerHook::ListenerInfo(info) { assert(info.d); } ServiceListenerEntry::~ServiceListenerEntry() = default; ServiceListenerEntry& ServiceListenerEntry::operator=( const ServiceListenerEntry& other) { d = other.d; return *this; } void ServiceListenerEntry::SetRemoved(bool removed) const { d->bRemoved = removed; } ServiceListenerEntry::ServiceListenerEntry( const std::shared_ptr<BundleContextPrivate>& context, const ServiceListener& l, void* data, ListenerTokenId tokenId, const std::string& filter) : ServiceListenerHook::ListenerInfo( new ServiceListenerEntryData(context, l, data, tokenId, filter)) {} const LDAPExpr& ServiceListenerEntry::GetLDAPExpr() const { return static_cast<ServiceListenerEntryData*>(d.get())->ldap; } LDAPExpr::LocalCache& ServiceListenerEntry::GetLocalCache() const { return static_cast<ServiceListenerEntryData*>(d.get())->local_cache; } void ServiceListenerEntry::CallDelegate(const ServiceEvent& event) const { d->listener(event); } bool ServiceListenerEntry::operator==(const ServiceListenerEntry& other) const { return (d->data == other.d->data) && (d->tokenId == other.d->tokenId) && ServiceListenerCompare()(d->listener, other.d->listener) && ((d->context == nullptr || other.d->context == nullptr) || d->context == other.d->context); } bool ServiceListenerEntry::operator<(const ServiceListenerEntry& other) const { return d->tokenId < other.d->tokenId; } bool ServiceListenerEntry::Contains( const std::shared_ptr<BundleContextPrivate>& context, ListenerTokenId tokenId) const { return (d->context == context) && (d->tokenId == tokenId); } bool ServiceListenerEntry::Contains( const std::shared_ptr<BundleContextPrivate>& context, const ServiceListener& listener, void* data) const { return (d->context == context) && (d->data == data) && ServiceListenerCompare()(d->listener, listener); } ListenerTokenId ServiceListenerEntry::Id() const { return d->tokenId; } std::size_t ServiceListenerEntry::Hash() const { using std::hash; if (static_cast<ServiceListenerEntryData*>(d.get())->hashValue == 0) { static_cast<ServiceListenerEntryData*>(d.get())->hashValue = ((hash<BundleContextPrivate*>()(d->context.get()) ^ (hash<void*>()(d->data) << 1)) >> 1) ^ ((hash<ServiceListener>()(d->listener)) ^ (hash<ListenerTokenId>()(d->tokenId) << 1) << 1); } return static_cast<ServiceListenerEntryData*>(d.get())->hashValue; } } US_MSVC_POP_WARNING
29.467337
80
0.688097
hkgmahwa
3a0e5d474e7fc923b8bc9aeb862546e94743b0d1
3,365
cpp
C++
Filters/RadiusOutlier.cpp
QuMIke/PracticePCL
efe947607516d28c176721c9930be049b50ad18a
[ "MIT" ]
null
null
null
Filters/RadiusOutlier.cpp
QuMIke/PracticePCL
efe947607516d28c176721c9930be049b50ad18a
[ "MIT" ]
null
null
null
Filters/RadiusOutlier.cpp
QuMIke/PracticePCL
efe947607516d28c176721c9930be049b50ad18a
[ "MIT" ]
null
null
null
/* we will learn how to us a RadiusOutlierRemoval filter which removes all indices in it’s input cloud that don’t have at least some number of neighbors within a certain range. */ #include "stdafx.h" #include <iostream> #include <pcl/point_types.h> #include <pcl/filters/radius_outlier_removal.h> #include <pcl/visualization/cloud_viewer.h> #include "KinnectGrabber.h" int main() { pcl::io::OpenNI2Grabber grabber; KinnectGrabber<pcl::PointXYZRGBA> v(grabber); v.run(); pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr cloud = nullptr; cloud = v.getLatestCloud(); if (cloud == nullptr) { std::cout << "Get cloud failed!" << std::endl; } else { /* using PCLVisualizer will make pcl::removeNaNFromPointCloud failed beacuase of cloud_viewer->spinOnce employ cloud to renew display window */ //boost::shared_ptr<pcl::visualization::PCLVisualizer> cloud_viewer(new pcl::visualization::PCLVisualizer("captured cloud")); //cloud_viewer->setCameraFieldOfView(1.02259994f); //cloud_viewer->spinOnce(); //cloud_viewer->setPosition(0, 0); //cloud_viewer->setSize(cloud->width, cloud->height); //cloud_viewer->addPointCloud(cloud, "captured cloud"); //cloud_viewer->resetCameraViewpoint("captured cloud"); //cloud_viewer->setCameraPosition( // 0, 0, 0, // Position // 0, 0, 1, // Viewpoint // 0, -1, 0); // Up std::cerr << "PointCloud before filtering: " << cloud->width * cloud->height << " data points(" << pcl::getFieldsList(*cloud) << ")." << std::endl; // Remove nan points std::vector<int> idx; boost::shared_ptr<pcl::PointIndices> index = nullptr; pcl::PointCloud<pcl::PointXYZRGBA>::Ptr no_nan_cloud(new pcl::PointCloud<pcl::PointXYZRGBA>); pcl::removeNaNFromPointCloud(*cloud, *no_nan_cloud, idx); if (no_nan_cloud == nullptr) { std::cout << "remove NaN from point cloud failed!" << std::endl; return 0; } //index->header = no_nan_cloud->header; // if you want to set RadiusOutlierRemover.setIndices, so code this line to get an indices, this will make no_nan_cloud header change, so it makes no_nan_cloud nullptr //index->indices = idx; pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_filtered(new pcl::PointCloud<pcl::PointXYZRGBA>); // Build filter pcl::RadiusOutlierRemoval<pcl::PointXYZRGBA> outrem; outrem.setInputCloud(no_nan_cloud); outrem.setRadiusSearch(0.8); outrem.setMinNeighborsInRadius(2); //outrem.setKeepOrganized(true); // //outrem.setIndices(index); // Apply filter outrem.filter(*cloud_filtered); /* cloud_filtered is not organized, so PCLVisualizer won't work!*/ //boost::shared_ptr<pcl::visualization::PCLVisualizer> filtered_viewer(new pcl::visualization::PCLVisualizer("filtered cloud")); //filtered_viewer->setCameraFieldOfView(1.02259994f); //filtered_viewer->spinOnce(); //filtered_viewer->setPosition(400, 100); //filtered_viewer->setSize(cloud_filtered->width, cloud_filtered->height); //filtered_viewer->addPointCloud(cloud_filtered); //filtered_viewer->resetCameraViewpoint("filtered cloud"); //filtered_viewer->setCameraPosition( // 0, 0, 0, // Position // 0, 0, 1, // Viewpoint // 0, -1, 0); // Up std::cerr << "PointCloud after filtering: " << cloud_filtered->width * cloud_filtered->height << " data points(" << pcl::getFieldsList(*cloud_filtered) << ")." << std::endl; } return 0; }
39.127907
211
0.711144
QuMIke
3a14109f5812ea679b677f5c132766763e6f44eb
1,767
hpp
C++
include/gazebo_ros_articulated_steering/plugin.hpp
Kettenhoax/gazebo_ros_articulated_steering
270e0652c2711399c758eeb9ae384afa505f0a88
[ "Apache-2.0" ]
null
null
null
include/gazebo_ros_articulated_steering/plugin.hpp
Kettenhoax/gazebo_ros_articulated_steering
270e0652c2711399c758eeb9ae384afa505f0a88
[ "Apache-2.0" ]
null
null
null
include/gazebo_ros_articulated_steering/plugin.hpp
Kettenhoax/gazebo_ros_articulated_steering
270e0652c2711399c758eeb9ae384afa505f0a88
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 AIT Austrian Institute of Technology GmbH // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <gazebo/common/Plugin.hh> #include <memory> namespace gazebo_plugins { class GazeboRosArticulatedSteeringPrivate; /// A control plugin for robots with articulated steering and all wheel drive /// Subscribes to ackermann_msgs/msg/AckermannDriveStamped /** Example Usage: \code{.xml} <plugin name="gazebo_ros_articulated_steering" filename="libgazebo_ros_articulated_steering.so"> <ros> <namespace>demo</namespace> <remapping>cmd_drive:=cmd_demo</remapping> </ros> <update_rate>100.0</update_rate> ... <robot_base_frame>base_footprint</robot_base_frame> </plugin> \endcode */ class GazeboRosArticulatedSteering : public gazebo::ModelPlugin { public: /// Constructor GazeboRosArticulatedSteering(); /// Destructor ~GazeboRosArticulatedSteering(); protected: // Documentation inherited void Load(gazebo::physics::ModelPtr _model, sdf::ElementPtr _sdf) override; // Documentation inherited void Reset() override; private: /// Private data pointer std::unique_ptr<GazeboRosArticulatedSteeringPrivate> impl_; }; } // namespace gazebo_plugins
27.609375
100
0.742501
Kettenhoax
3a14da3880ba119dc261abe3541087174b786510
22,334
cpp
C++
ui/src/inputprofileeditor.cpp
markusb/qlcplus
1aae45b8d1914114b9a7ea6174e83e51e81ab8a1
[ "Apache-2.0" ]
2
2016-12-12T15:32:27.000Z
2021-05-18T17:55:30.000Z
ui/src/inputprofileeditor.cpp
markusb/qlcplus
1aae45b8d1914114b9a7ea6174e83e51e81ab8a1
[ "Apache-2.0" ]
null
null
null
ui/src/inputprofileeditor.cpp
markusb/qlcplus
1aae45b8d1914114b9a7ea6174e83e51e81ab8a1
[ "Apache-2.0" ]
null
null
null
/* Q Light Controller inputprofileeditor.cpp Copyright (C) Heikki Junnila 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.txt 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 <QTreeWidgetItem> #include <QTextBrowser> #include <QTreeWidget> #include <QToolButton> #include <QMessageBox> #include <QTabWidget> #include <QSettings> #include <QCheckBox> #include <QDialog> #include <QTimer> #include <QDebug> #include <QFile> #include <QList> #include <QDir> #include "qlcinputprofile.h" #include "qlcchannel.h" #include "inputchanneleditor.h" #include "inputprofileeditor.h" #include "inputoutputmap.h" #include "apputil.h" #define SETTINGS_GEOMETRY "inputprofileeditor/geometry" #define KColumnNumber 0 #define KColumnName 1 #define KColumnType 2 #define KColumnValues 3 /**************************************************************************** * Initialization ****************************************************************************/ InputProfileEditor::InputProfileEditor(QWidget* parent, QLCInputProfile* profile, InputOutputMap *ioMap) : QDialog(parent) , m_ioMap(ioMap) , m_wizardActive(false) , m_latestItem(NULL) { Q_ASSERT(ioMap != NULL); setupUi(this); m_midiGroupSettings->setVisible(false); connect(m_typeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(slotTypeComboChanged(int))); /* Connect the buttons to slots */ connect(m_addButton, SIGNAL(clicked()), this, SLOT(slotAddClicked())); connect(m_removeButton, SIGNAL(clicked()), this, SLOT(slotRemoveClicked())); connect(m_editButton, SIGNAL(clicked()), this, SLOT(slotEditClicked())); connect(m_wizardButton, SIGNAL(clicked(bool)), this, SLOT(slotWizardClicked(bool))); connect(m_tree, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(slotItemClicked(QTreeWidgetItem*,int))); connect(m_tree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), this, SLOT(slotEditClicked())); connect(m_movementCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(slotMovementComboChanged(int))); connect(m_sensitivitySpin, SIGNAL(valueChanged(int)), this, SLOT(slotSensitivitySpinChanged(int))); connect(m_extraPressCheck, SIGNAL(toggled(bool)), this, SLOT(slotExtraPressChecked(bool))); connect(m_lowerSpin, SIGNAL(valueChanged(int)), this, SLOT(slotLowerValueSpinChanged(int))); connect(m_upperSpin, SIGNAL(valueChanged(int)), this, SLOT(slotUpperValueSpinChanged(int))); /* Listen to input data */ connect(m_ioMap, SIGNAL(inputValueChanged(quint32, quint32, uchar, const QString&)), this, SLOT(slotInputValueChanged(quint32, quint32, uchar, const QString&))); if (profile == NULL) { m_profile = new QLCInputProfile(); } else { m_profile = new QLCInputProfile(*profile); if ((QFile::permissions(m_profile->path()) & QFile::WriteUser) == 0) { QMessageBox::warning(this, tr("File not writable"), tr("You do not have permission to write to " "the file %1. You might not be able to " "save your modifications to the profile.") .arg(QDir::toNativeSeparators( m_profile->path()))); } } QList<QLCInputProfile::Type> types = QLCInputProfile::types(); for (int i = 0; i < types.size(); ++i) { const QLCInputProfile::Type type = types.at(i); m_typeCombo->addItem(QLCInputProfile::typeToString(type), type); if (m_profile->type() == type) { m_typeCombo->setCurrentIndex(i); if (type == QLCInputProfile::Midi) { m_midiGroupSettings->setVisible(true); m_noteOffCheck->setChecked(m_profile->midiSendNoteOff()); } } } /* Profile manufacturer & model */ m_manufacturerEdit->setText(m_profile->manufacturer()); m_modelEdit->setText(m_profile->model()); m_behaviourBox->hide(); m_feedbackGroup->hide(); /* Fill up the tree with profile's channels */ fillTree(); /* Timer that clears the input data icon after a while */ m_timer = new QTimer(this); m_timer->setSingleShot(true); connect(m_timer, SIGNAL(timeout()), this, SLOT(slotTimerTimeout())); QSettings settings; QVariant var = settings.value(SETTINGS_GEOMETRY); if (var.isValid() == true) restoreGeometry(var.toByteArray()); AppUtil::ensureWidgetIsVisible(this); } InputProfileEditor::~InputProfileEditor() { QSettings settings; settings.setValue(SETTINGS_GEOMETRY, saveGeometry()); delete m_profile; } void InputProfileEditor::fillTree() { m_tree->clear(); QMapIterator <quint32,QLCInputChannel*> it(m_profile->channels()); while (it.hasNext() == true) { it.next(); updateChannelItem(new QTreeWidgetItem(m_tree), it.value()); } m_tree->header()->resizeSections(QHeaderView::ResizeToContents); } void InputProfileEditor::updateChannelItem(QTreeWidgetItem* item, QLCInputChannel* ch) { quint32 num; Q_ASSERT(item != NULL); Q_ASSERT(ch != NULL); num = m_profile->channelNumber(ch); item->setText(KColumnNumber, QString("%1").arg(num + 1, 4, 10, QChar('0'))); item->setText(KColumnName, ch->name()); item->setText(KColumnType, QLCInputChannel::typeToString(ch->type())); item->setIcon(KColumnType, ch->icon()); } void InputProfileEditor::setOptionsVisibility(QLCInputChannel::Type type) { bool showBox = true; bool showMovement = false; bool showSensitivity = false; bool showButtonOpts = false; if (type == QLCInputChannel::Slider || type == QLCInputChannel::Knob) { showMovement = true; showSensitivity = true; m_sensitivitySpin->setRange(10, 100); } else if (type == QLCInputChannel::Encoder) { showSensitivity = true; m_sensitivitySpin->setRange(1, 20); } else if (type == QLCInputChannel::Button) { showButtonOpts = true; } else showBox = false; m_movementLabel->setVisible(showMovement); m_movementCombo->setVisible(showMovement); m_sensitivityLabel->setVisible(showSensitivity); m_sensitivitySpin->setVisible(showSensitivity); m_extraPressCheck->setVisible(showButtonOpts); m_feedbackGroup->setVisible(showButtonOpts); m_behaviourBox->setVisible(showBox); } void InputProfileEditor::slotTypeComboChanged(int) { if (currentProfileType() == QLCInputProfile::Midi) m_midiGroupSettings->setVisible(true); else m_midiGroupSettings->setVisible(false); } /**************************************************************************** * OK & Cancel ****************************************************************************/ void InputProfileEditor::reject() { /* Don't allow closing the dialog in any way when the wizard is on */ if (m_buttonBox->isEnabled() == false) return; QDialog::reject(); } void InputProfileEditor::accept() { /* Don't allow closing the dialog in any way when the wizard is on */ if (m_buttonBox->isEnabled() == false) return; m_profile->setManufacturer(m_manufacturerEdit->text()); m_profile->setModel(m_modelEdit->text()); m_profile->setType(currentProfileType()); if (currentProfileType() == QLCInputProfile::Midi) m_profile->setMidiSendNoteOff(m_noteOffCheck->isChecked()); /* Check that we have at least the bare necessities to save the profile */ if (m_profile->manufacturer().isEmpty() == true || m_profile->model().isEmpty() == true) { QMessageBox::warning(this, tr("Missing information"), tr("Manufacturer and/or model name is missing.")); } else { QDialog::accept(); } } /**************************************************************************** * Editing ****************************************************************************/ QList<QLCInputChannel *> InputProfileEditor::selectedChannels() { QList<QLCInputChannel *> channels; QListIterator <QTreeWidgetItem*>it(m_tree->selectedItems()); while (it.hasNext() == true) { QTreeWidgetItem *item = it.next(); Q_ASSERT(item != NULL); quint32 chnum = item->text(KColumnNumber).toUInt() - 1; QLCInputChannel *channel = m_profile->channel(chnum); Q_ASSERT(channel != NULL); channels.append(channel); } return channels; } void InputProfileEditor::slotAddClicked() { QLCInputChannel* channel = new QLCInputChannel(); InputChannelEditor ice(this, m_profile, channel, currentProfileType()); add: if (ice.exec() == QDialog::Accepted) { channel->setType(ice.type()); channel->setName(ice.name()); if (m_profile->channel(ice.channel()) == NULL) { m_profile->insertChannel(ice.channel(), channel); updateChannelItem(new QTreeWidgetItem(m_tree), channel); } else { QMessageBox::warning(this, tr("Channel already exists"), tr("Channel %1 already exists") .arg(ice.channel() + 1)); goto add; } } else { delete channel; } } void InputProfileEditor::slotRemoveClicked() { QList <QTreeWidgetItem*> selected; QTreeWidgetItem* next = NULL; /* Ask for confirmation if we're deleting more than one channel */ selected = m_tree->selectedItems(); if (selected.count() > 1) { int r; r = QMessageBox::question(this, tr("Delete channels"), tr("Delete all %1 selected channels?") .arg(selected.count()), QMessageBox::Yes | QMessageBox::No); if (r == QMessageBox::No) return; } /* Remove all selected channels */ QMutableListIterator <QTreeWidgetItem*> it(selected); while (it.hasNext() == true) { QTreeWidgetItem *item = it.next(); Q_ASSERT(item != NULL); /* Remove & Delete the channel object */ quint32 chnum = item->text(KColumnNumber).toUInt() - 1; m_profile->removeChannel(chnum); /* Choose the closest item below or above the removed items as the one that is selected after the removal */ next = m_tree->itemBelow(item); if (next == NULL) next = m_tree->itemAbove(item); delete item; } m_tree->setCurrentItem(next); } void InputProfileEditor::slotEditClicked() { QLCInputChannel* channel; quint32 chnum; QTreeWidgetItem* item; if (m_tree->selectedItems().count() == 1) { /* Just one item selected. Edit that. */ item = m_tree->currentItem(); if (item == NULL) return; /* Find the channel object associated to the selected item */ chnum = item->text(KColumnNumber).toUInt() - 1; channel = m_profile->channel(chnum); Q_ASSERT(channel != NULL); /* Edit the channel and update its item if necessary */ InputChannelEditor ice(this, m_profile, channel, currentProfileType()); edit: if (ice.exec() == QDialog::Accepted) { QLCInputChannel* another; another = m_profile->channel(ice.channel()); if (another == NULL || another == channel) { if (ice.channel() != QLCChannel::invalid()) m_profile->remapChannel(channel, ice.channel()); if (ice.name().isEmpty() == false) channel->setName(ice.name()); if (ice.type() != QLCInputChannel::NoType) { if (ice.type() != channel->type()) setOptionsVisibility(ice.type()); channel->setType(ice.type()); if (m_sensitivitySpin->isVisible()) m_sensitivitySpin->setValue(channel->movementSensitivity()); } updateChannelItem(item, channel); } else { QMessageBox::warning(this, tr("Channel already exists"), tr("Channel %1 already exists") .arg(ice.channel() + 1)); goto edit; } } } else if (m_tree->selectedItems().count() > 1) { /* Multiple channels selected. Apply changes to all of them */ InputChannelEditor ice(this, NULL, NULL, QLCInputProfile::Dmx); if (ice.exec() == QDialog::Accepted) { QListIterator <QTreeWidgetItem*> it(m_tree->selectedItems()); while (it.hasNext() == true) { item = it.next(); Q_ASSERT(item != NULL); chnum = item->text(KColumnNumber).toUInt() - 1; channel = m_profile->channel(chnum); Q_ASSERT(channel != NULL); /* Set only name and type and only if they have been modified. */ if (ice.name().isEmpty() == false) channel->setName(ice.name()); if (ice.type() != QLCInputChannel::NoType) channel->setType(ice.type()); updateChannelItem(item, channel); } } } } void InputProfileEditor::slotWizardClicked(bool checked) { if (checked == true) { QMessageBox::information(this, tr("Channel wizard activated"), tr("You have enabled the input channel wizard. After " "clicking OK, wiggle your mapped input profile's " "controls. They should appear into the list. " "Click the wizard button again to stop channel " "auto-detection.\n\nNote that the wizard cannot " "tell the difference between a knob and a slider " "so you will have to do the change manually.")); m_wizardActive = true; } else { m_wizardActive = false; } m_buttonBox->setEnabled(!checked); m_tab->setTabEnabled(0, !checked); } void InputProfileEditor::slotItemClicked(QTreeWidgetItem *item, int col) { Q_UNUSED(col) quint32 chNum = item->text(KColumnNumber).toUInt() - 1; QLCInputChannel *ich = m_profile->channel(chNum); if (ich != NULL) { setOptionsVisibility(ich->type()); if (ich->type() == QLCInputChannel::Slider || ich->type() == QLCInputChannel::Knob) { if (ich->movementType() == QLCInputChannel::Absolute) { m_movementCombo->setCurrentIndex(0); m_sensitivitySpin->setEnabled(false); } else { m_movementCombo->setCurrentIndex(1); m_sensitivitySpin->setValue(ich->movementSensitivity()); m_sensitivitySpin->setEnabled(true); } } else if (ich->type() == QLCInputChannel::Encoder) { m_sensitivitySpin->setValue(ich->movementSensitivity()); m_sensitivitySpin->setEnabled(true); } else if (ich->type() == QLCInputChannel::Button) { m_extraPressCheck->setChecked(ich->sendExtraPress()); m_lowerSpin->blockSignals(true); m_upperSpin->blockSignals(true); m_lowerSpin->setValue(ich->lowerValue()); m_upperSpin->setValue(ich->upperValue()); m_lowerSpin->blockSignals(false); m_upperSpin->blockSignals(false); } } else setOptionsVisibility(QLCInputChannel::NoType); } void InputProfileEditor::slotMovementComboChanged(int index) { if (index == 1) m_sensitivitySpin->setEnabled(true); else m_sensitivitySpin->setEnabled(false); foreach(QLCInputChannel *channel, selectedChannels()) { if (channel->type() == QLCInputChannel::Slider || channel->type() == QLCInputChannel::Knob) { if (index == 1) channel->setMovementType(QLCInputChannel::Relative); else channel->setMovementType(QLCInputChannel::Absolute); } } } void InputProfileEditor::slotSensitivitySpinChanged(int value) { foreach(QLCInputChannel *channel, selectedChannels()) { if ((channel->type() == QLCInputChannel::Slider || channel->type() == QLCInputChannel::Knob) && channel->movementType() == QLCInputChannel::Relative) channel->setMovementSensitivity(value); else if (channel->type() == QLCInputChannel::Encoder) channel->setMovementSensitivity(value); } } void InputProfileEditor::slotExtraPressChecked(bool checked) { foreach(QLCInputChannel *channel, selectedChannels()) { if(channel->type() == QLCInputChannel::Button) channel->setSendExtraPress(checked); } } void InputProfileEditor::slotLowerValueSpinChanged(int value) { foreach(QLCInputChannel *channel, selectedChannels()) { if (channel->type() == QLCInputChannel::Button) channel->setRange(uchar(value), uchar(m_upperSpin->value())); } } void InputProfileEditor::slotUpperValueSpinChanged(int value) { foreach(QLCInputChannel *channel, selectedChannels()) { if (channel->type() == QLCInputChannel::Button) channel->setRange(uchar(m_lowerSpin->value()), uchar(value)); } } void InputProfileEditor::slotInputValueChanged(quint32 universe, quint32 channel, uchar value, const QString& key) { QTreeWidgetItem* latestItem = NULL; Q_UNUSED(universe); /* Get a list of items that represent the given channel. Basically the list should always contain just one item. */ QList <QTreeWidgetItem*> list; if (channel == UINT_MAX && key.isEmpty() == false) list = m_tree->findItems(key, Qt::MatchExactly, KColumnName); else list = m_tree->findItems(QString("%1").arg(channel + 1, 4, 10, QChar('0')), Qt::MatchExactly, KColumnNumber); if (list.size() != 0) latestItem = list.first(); if (list.size() == 0 && m_wizardActive == true) { /* No channel items found. Create a new channel to the profile and display it also in the tree widget */ QLCInputChannel* ch = new QLCInputChannel(); if(key.isEmpty()) ch->setName(tr("Button %1").arg(channel + 1)); else ch->setName(key); ch->setType(QLCInputChannel::Button); m_profile->insertChannel(channel, ch); latestItem = new QTreeWidgetItem(m_tree); updateChannelItem(latestItem, ch); } else if (m_wizardActive == true) { /* Existing channel & item found. Modify their contents. */ latestItem = list.first(); QVariant var = latestItem->data(KColumnValues, Qt::UserRole); QStringList values(var.toStringList()); if (values.size() > 3) { /* No need to collect any more values, since this channel has been judged to be a slider when count == 3 (see below). */ } else if (values.contains(QString("%1").arg(value)) == false) { values << QString("%1").arg(value); values.sort(); latestItem->setData(KColumnValues, Qt::UserRole, values); } /* Change the channel type only the one time when its value count goes over 2. I.e. when a channel can have more than two distinct values, it can no longer be a button. */ if (values.size() == 3) { QLCInputChannel* ch = m_profile->channel(channel); Q_ASSERT(ch != NULL); if (ch->type() == QLCInputChannel::Button) { ch->setType(QLCInputChannel::Slider); if(key.isEmpty()) ch->setName(tr("Slider %1").arg(channel + 1)); else ch->setName(key); updateChannelItem(latestItem, ch); } } } if (latestItem != NULL) { if (m_latestItem != NULL) m_latestItem->setIcon(KColumnNumber, QIcon()); m_latestItem = latestItem; m_latestItem->setIcon(KColumnNumber, QIcon(":/input.png")); m_tree->scrollToItem(m_latestItem); m_timer->start(250); } } void InputProfileEditor::slotTimerTimeout() { if (m_latestItem != NULL) m_latestItem->setIcon(KColumnNumber, QIcon()); m_latestItem = NULL; } /**************************************************************************** * Profile ****************************************************************************/ const QLCInputProfile* InputProfileEditor::profile() const { return m_profile; } QLCInputProfile::Type InputProfileEditor::currentProfileType() const { return static_cast<QLCInputProfile::Type>(m_typeCombo->itemData(m_typeCombo->currentIndex()).toInt()); }
32.892489
106
0.573655
markusb
3a16e14eea9f85cc7a6ae96dc026d1f680b64e22
668
hpp
C++
include/Game/gameobject.hpp
Lucrecious/DungeonGame
9e427c4eba18cdc0aa93a6e28e505a8ecb1357e5
[ "MIT" ]
null
null
null
include/Game/gameobject.hpp
Lucrecious/DungeonGame
9e427c4eba18cdc0aa93a6e28e505a8ecb1357e5
[ "MIT" ]
null
null
null
include/Game/gameobject.hpp
Lucrecious/DungeonGame
9e427c4eba18cdc0aa93a6e28e505a8ecb1357e5
[ "MIT" ]
null
null
null
#ifndef GAMEOBJECT_H #define GAMEOBJECT_H #include <Utils/vector.hpp> #include <Global/kind.hpp> #include <string> class Game; class Controller; class GameObject { public: const Kind topKind; const Kind subKind; bool ghost; GameObject(Kind, Kind); virtual ~GameObject() = 0; void setPosition(Vector); void setPosition(int, int); Vector getPosition() const; void setController(Controller*); void setGame(Game*); static bool less_than(const GameObject* gobj1, const GameObject* gobj2); void setName(std::string); std::string getName() const; protected: Controller* controller; Game* game; private: Vector position; std::string name; }; #endif
16.292683
73
0.739521
Lucrecious
3a1881eacdacf9b61a925b62487573ba0f7af78a
2,306
cpp
C++
YorozuyaGSLib/source/_inven_download_result_zoclDetail.cpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
YorozuyaGSLib/source/_inven_download_result_zoclDetail.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
YorozuyaGSLib/source/_inven_download_result_zoclDetail.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
#include <_inven_download_result_zoclDetail.hpp> #include <common/ATFCore.hpp> START_ATF_NAMESPACE namespace Detail { Info::_inven_download_result_zoclctor__inven_download_result_zocl2_ptr _inven_download_result_zoclctor__inven_download_result_zocl2_next(nullptr); Info::_inven_download_result_zoclctor__inven_download_result_zocl2_clbk _inven_download_result_zoclctor__inven_download_result_zocl2_user(nullptr); Info::_inven_download_result_zoclsize4_ptr _inven_download_result_zoclsize4_next(nullptr); Info::_inven_download_result_zoclsize4_clbk _inven_download_result_zoclsize4_user(nullptr); void _inven_download_result_zoclctor__inven_download_result_zocl2_wrapper(struct _inven_download_result_zocl* _this) { _inven_download_result_zoclctor__inven_download_result_zocl2_user(_this, _inven_download_result_zoclctor__inven_download_result_zocl2_next); }; int _inven_download_result_zoclsize4_wrapper(struct _inven_download_result_zocl* _this) { return _inven_download_result_zoclsize4_user(_this, _inven_download_result_zoclsize4_next); }; ::std::array<hook_record, 2> _inven_download_result_zocl_functions = { _hook_record { (LPVOID)0x1400ef330L, (LPVOID *)&_inven_download_result_zoclctor__inven_download_result_zocl2_user, (LPVOID *)&_inven_download_result_zoclctor__inven_download_result_zocl2_next, (LPVOID)cast_pointer_function(_inven_download_result_zoclctor__inven_download_result_zocl2_wrapper), (LPVOID)cast_pointer_function((void(_inven_download_result_zocl::*)())&_inven_download_result_zocl::ctor__inven_download_result_zocl) }, _hook_record { (LPVOID)0x1400ef350L, (LPVOID *)&_inven_download_result_zoclsize4_user, (LPVOID *)&_inven_download_result_zoclsize4_next, (LPVOID)cast_pointer_function(_inven_download_result_zoclsize4_wrapper), (LPVOID)cast_pointer_function((int(_inven_download_result_zocl::*)())&_inven_download_result_zocl::size) }, }; }; // end namespace Detail END_ATF_NAMESPACE
52.409091
155
0.740676
lemkova
3a19f9b3df2713b329d30fd9a86d5239800181c6
2,483
cpp
C++
IA20-CommonLib/src/ia20/commonlib/net/conn/udp/Base.cpp
InvenireAude/IA20-BuilderTools
7ef0116bd2d1db83e3d3583c9059d5b2ee5462d6
[ "Apache-2.0" ]
null
null
null
IA20-CommonLib/src/ia20/commonlib/net/conn/udp/Base.cpp
InvenireAude/IA20-BuilderTools
7ef0116bd2d1db83e3d3583c9059d5b2ee5462d6
[ "Apache-2.0" ]
null
null
null
IA20-CommonLib/src/ia20/commonlib/net/conn/udp/Base.cpp
InvenireAude/IA20-BuilderTools
7ef0116bd2d1db83e3d3583c9059d5b2ee5462d6
[ "Apache-2.0" ]
null
null
null
/* * File: IA20-CommonLib/src/commonlib/net/mcast/Base.cpp * * Copyright (C) 2020, Albert Krzymowski * * 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 "Base.h" #include <ia20/commonlib/commonlib.h> #include <unistd.h> namespace IA20 { namespace Net { namespace Conn { namespace UDP { /*************************************************************************/ Base::Base(unsigned int iPort): iPort(iPort), iTimeout(C_UnLimited){ IA20_TRACER; if((iSocket=socket(AF_INET, SOCK_DGRAM, 0)) < 0) IA20_THROW(SystemException("UDP mulitcast socket, port: ")<<(int)iPort); IA20_LOG(LogLevel::INSTANCE.isInfo(),"iSocket:"<<iSocket); } /*************************************************************************/ Base::~Base() throw(){ IA20_TRACER; if(iSocket > 0) ::close(iSocket); } /*************************************************************************/ void Base::setTimeout(int iTimeout){ IA20_TRACER; if(iTimeout != C_UnLimited && iTimeout < 0) IA20_THROW(BadUsageException("timeout: ")<<iTimeout); this->iTimeout=iTimeout; IA20_LOG(LogLevel::INSTANCE.isInfo(),"fd("<<iSocket<<"), timeout: "<<this->iTimeout); } /*************************************************************************/ bool Base::waitForData(WaitMode iMode){ IA20_TRACER; fd_set set; struct timeval timeout; FD_ZERO(&set); FD_SET(iSocket, &set); timeout.tv_sec = 0; timeout.tv_usec = 1000*iTimeout; IA20_LOG(LogLevel::INSTANCE.isInfo(),"fd("<<iSocket<<"), timeout: "<<iTimeout); int iRC = ::select(iSocket + 1, (iMode == WM_Read ? &set : NULL), (iMode == WM_Write ? &set : NULL), &set, iTimeout == C_UnLimited ? NULL : &timeout); IA20_LOG(LogLevel::INSTANCE.isInfo(),"rc="<<iRC); switch(iRC){ case -1: IA20_THROW(SystemException("select: ")<<iSocket) break; case 0: return false; break; } return true; } /*************************************************************************/ } } } }
25.864583
86
0.578333
InvenireAude
3a1f9a4ba1584963acc7dc87db2d2a9c137c8d72
62,553
cpp
C++
arangod/IResearch/IResearchFilterFactory.cpp
pavelsevcik/arangodb
647a29d1aeab0909147961f5868dfd0618717e96
[ "Apache-2.0" ]
1
2018-12-08T01:58:16.000Z
2018-12-08T01:58:16.000Z
arangod/IResearch/IResearchFilterFactory.cpp
lipper/arangodb
66ea1fd4946668192e3f0d1060f0844f324ad7b8
[ "Apache-2.0" ]
null
null
null
arangod/IResearch/IResearchFilterFactory.cpp
lipper/arangodb
66ea1fd4946668192e3f0d1060f0844f324ad7b8
[ "Apache-2.0" ]
1
2018-12-05T04:56:16.000Z
2018-12-05T04:56:16.000Z
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2017 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov /// @author Vasiliy Nabatchikov //////////////////////////////////////////////////////////////////////////////// // otherwise define conflict between 3rdParty\date\include\date\date.h and 3rdParty\iresearch\core\shared.hpp #if defined(_MSC_VER) #include "date/date.h" #undef NOEXCEPT #endif #include <cctype> #include <type_traits> #include "search/all_filter.hpp" #include "search/boolean_filter.hpp" #include "search/term_filter.hpp" #include "search/prefix_filter.hpp" #include "search/range_filter.hpp" #include "search/granular_range_filter.hpp" #include "search/column_existence_filter.hpp" #include "search/phrase_filter.hpp" #include "AqlHelper.h" #include "ExpressionFilter.h" #include "IResearchFeature.h" #include "IResearchAnalyzerFeature.h" #include "IResearchCommon.h" #include "IResearchFilterFactory.h" #include "IResearchDocument.h" #include "IResearchKludge.h" #include "IResearchPrimaryKeyFilter.h" #include "Aql/Function.h" #include "Aql/Ast.h" #include "Logger/LogMacros.h" using namespace arangodb::iresearch; namespace { struct FilterContext { FilterContext( IResearchAnalyzerFeature::AnalyzerPool::ptr const& analyzer, irs::boost::boost_t boost ) noexcept : analyzer(analyzer), boost(boost) { TRI_ASSERT(analyzer); } FilterContext(FilterContext const&) = default; FilterContext& operator=(FilterContext const&) = delete; // need shared_ptr since pool could be deleted from the feature IResearchAnalyzerFeature::AnalyzerPool::ptr const analyzer; irs::boost::boost_t boost; }; // FilterContext typedef std::function<bool( irs::boolean_filter*, QueryContext const&, FilterContext const&, arangodb::aql::AstNode const& )> ConvertionHandler; // forward declaration bool filter( irs::boolean_filter* filter, QueryContext const& queryCtx, FilterContext const& filterCtx, arangodb::aql::AstNode const& node ); //////////////////////////////////////////////////////////////////////////////// /// @brief logs message about malformed AstNode with the specified type //////////////////////////////////////////////////////////////////////////////// void logMalformedNode(arangodb::aql::AstNodeType type) { auto const* typeName = arangodb::iresearch::getNodeTypeName(type); if (typeName) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "Can't process malformed AstNode of type '" << *typeName << "'"; } else { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "Can't process malformed AstNode of type '" << type << "'"; } } //////////////////////////////////////////////////////////////////////////////// /// @brief appends value tokens to a phrase filter //////////////////////////////////////////////////////////////////////////////// void appendTerms( irs::by_phrase& filter, irs::string_ref const& value, irs::analysis::analyzer& stream, size_t firstOffset) { // reset stream stream.reset(value); // get token attribute irs::term_attribute const& token = *stream.attributes().get<irs::term_attribute>(); // add tokens while (stream.next()) { filter.push_back(token.value(), firstOffset); firstOffset = 0; } } FORCE_INLINE void appendExpression( irs::boolean_filter& filter, arangodb::aql::AstNode const& node, QueryContext const& ctx, FilterContext const& filterCtx ) { auto& exprFilter = filter.add<arangodb::iresearch::ByExpression>(); exprFilter.init(*ctx.plan, *ctx.ast, const_cast<arangodb::aql::AstNode&>(node)); exprFilter.boost(filterCtx.boost); } FORCE_INLINE void appendExpression( irs::boolean_filter& filter, std::shared_ptr<arangodb::aql::AstNode>&& node, QueryContext const& ctx, FilterContext const& filterCtx ) { auto& exprFilter = filter.add<arangodb::iresearch::ByExpression>(); exprFilter.init(*ctx.plan, *ctx.ast, std::move(node)); exprFilter.boost(filterCtx.boost); } IResearchAnalyzerFeature::AnalyzerPool::ptr extractAnalyzerFromArg( irs::boolean_filter const* filter, arangodb::aql::AstNode const* analyzerArg, QueryContext const& ctx, size_t argIdx, irs::string_ref const& functionName ) { if (!analyzerArg) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'" << functionName << "' AQL function: " << argIdx << " argument is invalid analyzer"; return nullptr; } auto* analyzerFeature = arangodb::application_features::ApplicationServer::lookupFeature< IResearchAnalyzerFeature >(); if (!analyzerFeature) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'" << IResearchAnalyzerFeature::name() << "' feature is not registered, unable to evaluate '" << functionName << "' function"; return nullptr; } ScopedAqlValue analyzerValue(*analyzerArg); IResearchAnalyzerFeature::AnalyzerPool::ptr analyzer = IResearchAnalyzerFeature::identity(); if (filter || analyzerValue.isConstant()) { if (!analyzerValue.execute(ctx)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'" << functionName << "' AQL function: Failed to evaluate " << argIdx << " argument"; return nullptr; } if (arangodb::iresearch::SCOPED_VALUE_TYPE_STRING != analyzerValue.type()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'" << functionName << "' AQL function: " << argIdx << " argument has invalid type '" << analyzerValue.type() << "' (string expected)"; return nullptr; } irs::string_ref analyzerId; if (!analyzerValue.getString(analyzerId)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'" << functionName << "' AQL function: Unable to parse " << argIdx << " argument as a string"; return nullptr; } analyzer = analyzerFeature->get(analyzerId); if (!analyzer) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'" << functionName << "' AQL function: Unable to load requested analyzer '" << analyzerId << "'"; } } return analyzer; } bool byTerm( irs::by_term* filter, arangodb::aql::AstNode const& attribute, ScopedAqlValue const& value, QueryContext const& ctx, FilterContext const& filterCtx ) { std::string name; if (filter && !arangodb::iresearch::nameFromAttributeAccess(name, attribute, ctx)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "Failed to generate field name from node " << arangodb::aql::AstNode::toString(&attribute); return false; } switch (value.type()) { case arangodb::iresearch::SCOPED_VALUE_TYPE_NULL: if (filter) { kludge::mangleNull(name); filter->field(std::move(name)); filter->boost(filterCtx.boost); filter->term(irs::null_token_stream::value_null()); } return true; case arangodb::iresearch::SCOPED_VALUE_TYPE_BOOL: if (filter) { kludge::mangleBool(name); filter->field(std::move(name)); filter->boost(filterCtx.boost); filter->term(irs::boolean_token_stream::value(value.getBoolean())); } return true; case arangodb::iresearch::SCOPED_VALUE_TYPE_DOUBLE: if (filter) { double_t dblValue; if (!value.getDouble(dblValue)) { // something went wrong return false; } kludge::mangleNumeric(name); irs::numeric_token_stream stream; irs::term_attribute const* term = stream.attributes().get<irs::term_attribute>().get(); TRI_ASSERT(term); stream.reset(dblValue); stream.next(); filter->field(std::move(name)); filter->boost(filterCtx.boost); filter->term(term->value()); } return true; case arangodb::iresearch::SCOPED_VALUE_TYPE_STRING: if (filter) { irs::string_ref strValue; if (!value.getString(strValue)) { // something went wrong return false; } TRI_ASSERT(filterCtx.analyzer); kludge::mangleStringField(name, *filterCtx.analyzer); filter->field(std::move(name)); filter->boost(filterCtx.boost); filter->term(strValue); } return true; default: // unsupported value type return false; } } bool byTerm( irs::by_term* filter, arangodb::iresearch::NormalizedCmpNode const& node, QueryContext const& ctx, FilterContext const& filterCtx ) { TRI_ASSERT(node.attribute && node.attribute->isDeterministic()); TRI_ASSERT(node.value && node.value->isDeterministic()); ScopedAqlValue value(*node.value); if (!value.isConstant()) { if (!filter) { // can't evaluate non constant filter before the execution return true; } if (!value.execute(ctx)) { // failed to execute expression return false; } } return byTerm(filter, *node.attribute, value, ctx, filterCtx); } bool byRange( irs::boolean_filter* filter, arangodb::aql::AstNode const& attribute, arangodb::aql::Range const& rangeData, QueryContext const& ctx, FilterContext const& filterCtx ) { TRI_ASSERT(attribute.isDeterministic()); std::string name; if (filter && !nameFromAttributeAccess(name, attribute, ctx)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "Failed to generate field name from node " << arangodb::aql::AstNode::toString(&attribute); return false; } TRI_ASSERT(filter); auto& range = filter->add<irs::by_granular_range>(); kludge::mangleNumeric(name); range.field(std::move(name)); range.boost(filterCtx.boost); irs::numeric_token_stream stream; // setup min bound stream.reset(static_cast<double_t>(rangeData._low)); range.insert<irs::Bound::MIN>(stream); range.include<irs::Bound::MIN>(true); // setup max bound stream.reset(static_cast<double_t>(rangeData._high)); range.insert<irs::Bound::MAX>(stream); range.include<irs::Bound::MAX>(true); return true; } bool byRange( irs::boolean_filter* filter, arangodb::aql::AstNode const& attributeNode, arangodb::aql::AstNode const& minValueNode, bool const minInclude, arangodb::aql::AstNode const& maxValueNode, bool const maxInclude, QueryContext const& ctx, FilterContext const& filterCtx ) { TRI_ASSERT(attributeNode.isDeterministic()); TRI_ASSERT(minValueNode.isDeterministic()); TRI_ASSERT(maxValueNode.isDeterministic()); ScopedAqlValue min(minValueNode); if (!min.isConstant()) { if (!filter) { // can't evaluate non constant filter before the execution return true; } if (!min.execute(ctx)) { // failed to execute expression return false; } } ScopedAqlValue max(maxValueNode); if (!max.isConstant()) { if (!filter) { // can't evaluate non constant filter before the execution return true; } if (!max.execute(ctx)) { // failed to execute expression return false; } } if (min.type() != max.type()) { // type mismatch return false; } std::string name; if (filter && !nameFromAttributeAccess(name, attributeNode, ctx)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "Failed to generate field name from node " << arangodb::aql::AstNode::toString(&attributeNode); return false; } switch (min.type()) { case arangodb::iresearch::SCOPED_VALUE_TYPE_NULL: { if (filter) { kludge::mangleNull(name); auto& range = filter->add<irs::by_range>(); range.field(std::move(name)); range.boost(filterCtx.boost); range.term<irs::Bound::MIN>(irs::null_token_stream::value_null()); range.include<irs::Bound::MIN>(minInclude);; range.term<irs::Bound::MAX>(irs::null_token_stream::value_null()); range.include<irs::Bound::MAX>(maxInclude);; } return true; } case arangodb::iresearch::SCOPED_VALUE_TYPE_BOOL: { if (filter) { kludge::mangleBool(name); auto& range = filter->add<irs::by_range>(); range.field(std::move(name)); range.boost(filterCtx.boost); range.term<irs::Bound::MIN>( irs::boolean_token_stream::value(min.getBoolean()) ); range.include<irs::Bound::MIN>(minInclude); range.term<irs::Bound::MAX>( irs::boolean_token_stream::value(max.getBoolean()) ); range.include<irs::Bound::MAX>(maxInclude); } return true; } case arangodb::iresearch::SCOPED_VALUE_TYPE_DOUBLE: { if (filter) { double_t minDblValue, maxDblValue; if (!min.getDouble(minDblValue) || !max.getDouble(maxDblValue)) { // can't parse value as double return false; } auto& range = filter->add<irs::by_granular_range>(); kludge::mangleNumeric(name); range.field(std::move(name)); range.boost(filterCtx.boost); irs::numeric_token_stream stream; // setup min bound stream.reset(minDblValue); range.insert<irs::Bound::MIN>(stream); range.include<irs::Bound::MIN>(minInclude); // setup max bound stream.reset(maxDblValue); range.insert<irs::Bound::MAX>(stream); range.include<irs::Bound::MAX>(maxInclude); } return true; } case arangodb::iresearch::SCOPED_VALUE_TYPE_STRING: { if (filter) { irs::string_ref minStrValue, maxStrValue; if (!min.getString(minStrValue) || !max.getString(maxStrValue)) { // failed to get string value return false; } auto& range = filter->add<irs::by_range>(); TRI_ASSERT(filterCtx.analyzer); kludge::mangleStringField(name, *filterCtx.analyzer); range.field(std::move(name)); range.boost(filterCtx.boost); range.term<irs::Bound::MIN>(minStrValue); range.include<irs::Bound::MIN>(minInclude); range.term<irs::Bound::MAX>(maxStrValue); range.include<irs::Bound::MAX>(maxInclude); } return true; } default: // wrong value type return false; } } template<irs::Bound Bound> bool byRange( irs::boolean_filter* filter, arangodb::iresearch::NormalizedCmpNode const& node, bool const incl, QueryContext const& ctx, FilterContext const& filterCtx ) { TRI_ASSERT(node.attribute && node.attribute->isDeterministic()); TRI_ASSERT(node.value && node.value->isDeterministic()); ScopedAqlValue value(*node.value); if (!value.isConstant()) { if (!filter) { // can't evaluate non constant filter before the execution return true; } if (!value.execute(ctx)) { // con't execute expression return false; } } std::string name; if (filter && !nameFromAttributeAccess(name, *node.attribute, ctx)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "Failed to generate field name from node " << arangodb::aql::AstNode::toString(node.attribute); return false; } switch (value.type()) { case arangodb::iresearch::SCOPED_VALUE_TYPE_NULL: { if (filter) { auto& range = filter->add<irs::by_range>(); kludge::mangleNull(name); range.field(std::move(name)); range.boost(filterCtx.boost); range.term<Bound>(irs::null_token_stream::value_null()); range.include<Bound>(incl); } return true; } case arangodb::iresearch::SCOPED_VALUE_TYPE_BOOL: { if (filter) { auto& range = filter->add<irs::by_range>(); kludge::mangleBool(name); range.field(std::move(name)); range.boost(filterCtx.boost); range.term<Bound>( irs::boolean_token_stream::value(value.getBoolean()) ); range.include<Bound>(incl); } return true; } case arangodb::iresearch::SCOPED_VALUE_TYPE_DOUBLE: { if (filter) { double_t dblValue; if (!value.getDouble(dblValue)) { // can't parse as double return false; } auto& range = filter->add<irs::by_granular_range>(); irs::numeric_token_stream stream; kludge::mangleNumeric(name); range.field(std::move(name)); range.boost(filterCtx.boost); stream.reset(dblValue); range.insert<Bound>(stream); range.include<Bound>(incl); } return true; } case arangodb::iresearch::SCOPED_VALUE_TYPE_STRING: { if (filter) { irs::string_ref strValue; if (!value.getString(strValue)) { // can't parse as string return false; } auto& range = filter->add<irs::by_range>(); TRI_ASSERT(filterCtx.analyzer); kludge::mangleStringField(name, *filterCtx.analyzer); range.field(std::move(name)); range.boost(filterCtx.boost); range.term<Bound>(strValue); range.include<Bound>(incl); } return true; } default: // wrong value type return false; } } bool fromExpression( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, std::shared_ptr<arangodb::aql::AstNode> && node ) { if (!filter) { return true; } // non-deterministic condition or self-referenced variable if (!node->isDeterministic() || arangodb::iresearch::findReference(*node, *ctx.ref)) { // not supported by IResearch, but could be handled by ArangoDB appendExpression(*filter, std::move(node), ctx, filterCtx); return true; } bool result; if (node->isConstant()) { result = node->isTrue(); } else { // deterministic expression ScopedAqlValue value(*node); if (!value.execute(ctx)) { // can't execute expression return false; } result = value.getBoolean(); } if (result) { filter->add<irs::all>().boost(filterCtx.boost); } else { filter->add<irs::empty>(); } return true; } bool fromExpression( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& node ) { if (!filter) { return true; } // non-deterministic condition or self-referenced variable if (!node.isDeterministic() || arangodb::iresearch::findReference(node, *ctx.ref)) { // not supported by IResearch, but could be handled by ArangoDB appendExpression(*filter, node, ctx, filterCtx); return true; } bool result; if (node.isConstant()) { result = node.isTrue(); } else { // deterministic expression ScopedAqlValue value(node); if (!value.execute(ctx)) { // can't execute expression return false; } result = value.getBoolean(); } if (result) { filter->add<irs::all>().boost(filterCtx.boost); } else { filter->add<irs::empty>(); } return true; } bool fromInterval( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& node ) { TRI_ASSERT( arangodb::aql::NODE_TYPE_OPERATOR_BINARY_LT == node.type || arangodb::aql::NODE_TYPE_OPERATOR_BINARY_LE == node.type || arangodb::aql::NODE_TYPE_OPERATOR_BINARY_GT == node.type || arangodb::aql::NODE_TYPE_OPERATOR_BINARY_GE == node.type ); arangodb::iresearch::NormalizedCmpNode normNode; if (!arangodb::iresearch::normalizeCmpNode(node, *ctx.ref, normNode)) { return fromExpression(filter, ctx, filterCtx, node); } bool const incl = arangodb::aql::NODE_TYPE_OPERATOR_BINARY_GE == normNode.cmp || arangodb::aql::NODE_TYPE_OPERATOR_BINARY_LE == normNode.cmp; bool const min = arangodb::aql::NODE_TYPE_OPERATOR_BINARY_GT == normNode.cmp || arangodb::aql::NODE_TYPE_OPERATOR_BINARY_GE == normNode.cmp; return min ? byRange<irs::Bound::MIN>(filter, normNode, incl, ctx, filterCtx) : byRange<irs::Bound::MAX>(filter, normNode, incl, ctx, filterCtx); } bool fromBinaryEq( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& node ) { TRI_ASSERT( arangodb::aql::NODE_TYPE_OPERATOR_BINARY_EQ == node.type || arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NE == node.type ); arangodb::iresearch::NormalizedCmpNode normalized; if (!arangodb::iresearch::normalizeCmpNode(node, *ctx.ref, normalized)) { return fromExpression(filter, ctx, filterCtx, node); } irs::by_term* termFilter = nullptr; if (filter) { termFilter = &(arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NE == node.type ? filter->add<irs::Not>().filter<irs::by_term>() : filter->add<irs::by_term>()); } return byTerm(termFilter, normalized, ctx, filterCtx); } bool fromRange( irs::boolean_filter* filter, QueryContext const& /*ctx*/, FilterContext const& filterCtx, arangodb::aql::AstNode const& node ) { TRI_ASSERT(arangodb::aql::NODE_TYPE_RANGE == node.type); if (node.numMembers() != 2) { logMalformedNode(node.type); return false; // wrong number of members } // ranges are always true if (filter) { filter->add<irs::all>().boost(filterCtx.boost); } return true; } bool fromInArray( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& node ) { TRI_ASSERT( arangodb::aql::NODE_TYPE_OPERATOR_BINARY_IN == node.type || arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NIN == node.type ); // `attributeNode` IN `valueNode` auto const* attributeNode = node.getMemberUnchecked(0); TRI_ASSERT(attributeNode); auto const* valueNode = node.getMemberUnchecked(1); TRI_ASSERT(valueNode && arangodb::aql::NODE_TYPE_ARRAY == valueNode->type); if (!attributeNode->isDeterministic()) { // not supported by IResearch, but could be handled by ArangoDB return fromExpression(filter, ctx, filterCtx, node); } size_t const n = valueNode->numMembers(); if (!arangodb::iresearch::checkAttributeAccess(attributeNode, *ctx.ref)) { // no attribute access specified in attribute node, try to // find it in value node bool attributeAccessFound = false; for (size_t i = 0; i < n; ++i) { attributeAccessFound |= (nullptr != arangodb::iresearch::checkAttributeAccess( valueNode->getMemberUnchecked(i), *ctx.ref )); } if (!attributeAccessFound) { return fromExpression(filter, ctx, filterCtx, node); } } if (!n) { if (filter) { if (arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NIN == node.type) { filter->add<irs::all>().boost(filterCtx.boost); // not in [] means 'all' } else { filter->add<irs::empty>(); } } // nothing to do more return true; } if (filter) { filter = arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NIN == node.type ? &static_cast<irs::boolean_filter&>(filter->add<irs::Not>().filter<irs::And>()) : &static_cast<irs::boolean_filter&>(filter->add<irs::Or>()); filter->boost(filterCtx.boost); } FilterContext const subFilterCtx{ filterCtx.analyzer, irs::boost::no_boost() // reset boost }; arangodb::iresearch::NormalizedCmpNode normalized; arangodb::aql::AstNode toNormalize(arangodb::aql::NODE_TYPE_OPERATOR_BINARY_EQ); toNormalize.reserve(2); // FIXME better to rewrite expression the following way but there is no place to // store created `AstNode` // d.a IN [1,RAND(),'3'+RAND()] -> (d.a == 1) OR d.a IN [RAND(),'3'+RAND()] for (size_t i = 0; i < n; ++i) { auto const* member = valueNode->getMemberUnchecked(i); TRI_ASSERT(member); // edit in place for now; TODO change so we can replace instead TEMPORARILY_UNLOCK_NODE(&toNormalize); toNormalize.clearMembers(); toNormalize.addMember(attributeNode); toNormalize.addMember(member); toNormalize.flags = member->flags; // attributeNode is deterministic here if (!arangodb::iresearch::normalizeCmpNode(toNormalize, *ctx.ref, normalized)) { if (!filter) { // can't evaluate non constant filter before the execution return true; } // use std::shared_ptr since AstNode is not copyable/moveable auto exprNode = std::make_shared<arangodb::aql::AstNode>( arangodb::aql::NODE_TYPE_OPERATOR_BINARY_EQ ); exprNode->reserve(2); exprNode->addMember(attributeNode); exprNode->addMember(member); // not supported by IResearch, but could be handled by ArangoDB if (!fromExpression(filter, ctx, subFilterCtx, std::move(exprNode))) { return false; } } else { auto* termFilter = filter ? &filter->add<irs::by_term>() : nullptr; if (!byTerm(termFilter, normalized, ctx, subFilterCtx)) { return false; } } } return true; } bool fromIn( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& node ) { TRI_ASSERT( arangodb::aql::NODE_TYPE_OPERATOR_BINARY_IN == node.type || arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NIN == node.type ); if (node.numMembers() != 2) { logMalformedNode(node.type); return false; // wrong number of members } auto const* valueNode = node.getMemberUnchecked(1); TRI_ASSERT(valueNode); if (arangodb::aql::NODE_TYPE_ARRAY == valueNode->type) { return fromInArray(filter, ctx, filterCtx, node); } auto* attributeNode = node.getMemberUnchecked(0); TRI_ASSERT(attributeNode); if (!node.isDeterministic() || !arangodb::iresearch::checkAttributeAccess(attributeNode, *ctx.ref) || arangodb::iresearch::findReference(*valueNode, *ctx.ref)) { return fromExpression(filter, ctx, filterCtx, node); } if (!filter) { // can't evaluate non constant filter before the execution return true; } if (arangodb::aql::NODE_TYPE_RANGE == valueNode->type) { ScopedAqlValue value(*valueNode); if (!value.execute(ctx)) { // con't execute expression LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "Unable to extract value from 'IN' operator"; return false; } // range auto const* range = value.getRange(); if (!range) { return false; } if (arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NIN == node.type) { // handle negation filter = &filter->add<irs::Not>().filter<irs::Or>(); } return byRange(filter, *attributeNode, *range, ctx, filterCtx); } ScopedAqlValue value(*valueNode); if (!value.execute(ctx)) { // con't execute expression LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "Unable to extract value from 'IN' operator"; return false; } switch (value.type()) { case arangodb::iresearch::SCOPED_VALUE_TYPE_ARRAY: { size_t const n = value.size(); if (!n) { if (arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NIN == node.type) { filter->add<irs::all>().boost(filterCtx.boost); // not in [] means 'all' } else { filter->add<irs::empty>(); } // nothing to do more return true; } filter = arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NIN == node.type ? &static_cast<irs::boolean_filter&>(filter->add<irs::Not>().filter<irs::And>()) : &static_cast<irs::boolean_filter&>(filter->add<irs::Or>()); filter->boost(filterCtx.boost); FilterContext const subFilterCtx{ filterCtx.analyzer, irs::boost::no_boost() // reset boost }; for (size_t i = 0; i < n; ++i) { if (!byTerm(&filter->add<irs::by_term>(), *attributeNode, value.at(i), ctx, subFilterCtx)) { // failed to create a filter return false; } } return true; } case arangodb::iresearch::SCOPED_VALUE_TYPE_RANGE: { // range auto const* range = value.getRange(); if (!range) { return false; } if (arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NIN == node.type) { // handle negation filter = &filter->add<irs::Not>().filter<irs::Or>(); } return byRange(filter, *attributeNode, *range, ctx, filterCtx); } default: break; } // wrong value node type return false; } bool fromNegation( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& node ) { TRI_ASSERT(arangodb::aql::NODE_TYPE_OPERATOR_UNARY_NOT == node.type); if (node.numMembers() != 1) { logMalformedNode(node.type); return false; // wrong number of members } auto const* member = node.getMemberUnchecked(0); TRI_ASSERT(member); if (filter) { auto& notFilter = filter->add<irs::Not>(); notFilter.boost(filterCtx.boost); filter = &notFilter.filter<irs::And>(); } FilterContext const subFilterCtx{ filterCtx.analyzer, irs::boost::no_boost() // reset boost }; return ::filter(filter, ctx, subFilterCtx, *member); } bool rangeFromBinaryAnd( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& node ) { TRI_ASSERT( arangodb::aql::NODE_TYPE_OPERATOR_BINARY_AND == node.type || arangodb::aql::NODE_TYPE_OPERATOR_NARY_AND == node.type ); if (node.numMembers() != 2) { logMalformedNode(node.type); return false; // wrong number of members } auto const* lhsNode = node.getMemberUnchecked(0); TRI_ASSERT(lhsNode); auto const* rhsNode = node.getMemberUnchecked(1); TRI_ASSERT(rhsNode); arangodb::iresearch::NormalizedCmpNode lhsNormNode, rhsNormNode; if (arangodb::iresearch::normalizeCmpNode(*lhsNode, *ctx.ref, lhsNormNode) && arangodb::iresearch::normalizeCmpNode(*rhsNode, *ctx.ref, rhsNormNode)) { bool const lhsInclude = arangodb::aql::NODE_TYPE_OPERATOR_BINARY_GE == lhsNormNode.cmp; bool const rhsInclude = arangodb::aql::NODE_TYPE_OPERATOR_BINARY_LE == rhsNormNode.cmp; if ((lhsInclude || arangodb::aql::NODE_TYPE_OPERATOR_BINARY_GT == lhsNormNode.cmp) && (rhsInclude || arangodb::aql::NODE_TYPE_OPERATOR_BINARY_LT == rhsNormNode.cmp)) { auto const* lhsAttr = lhsNormNode.attribute; auto const* rhsAttr = rhsNormNode.attribute; if (arangodb::iresearch::attributeAccessEqual(lhsAttr, rhsAttr, filter ? &ctx : nullptr)) { auto const* lhsValue = lhsNormNode.value; auto const* rhsValue = rhsNormNode.value; if (byRange(filter, *lhsAttr, *lhsValue, lhsInclude, *rhsValue, rhsInclude, ctx, filterCtx)) { // successsfully parsed as range return true; } } } } // unable to create range return false; } template<typename Filter> bool fromGroup( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& node ) { TRI_ASSERT(arangodb::aql::NODE_TYPE_OPERATOR_BINARY_AND == node.type || arangodb::aql::NODE_TYPE_OPERATOR_BINARY_OR == node.type || arangodb::aql::NODE_TYPE_OPERATOR_NARY_AND == node.type || arangodb::aql::NODE_TYPE_OPERATOR_NARY_OR == node.type); size_t const n = node.numMembers(); if (!n) { // nothing to do return true; } // Note: cannot optimize for single member in AND/OR since 'a OR NOT b' translates to 'a OR (OR NOT b)' if (std::is_same<Filter, irs::And>::value && 2 == n && rangeFromBinaryAnd(filter, ctx, filterCtx, node)) { // range case return true; } if (filter) { filter = &filter->add<Filter>(); filter->boost(filterCtx.boost); } FilterContext const subFilterCtx{ filterCtx.analyzer, irs::boost::no_boost() // reset boost }; for (size_t i = 0; i < n; ++i) { auto const* valueNode = node.getMemberUnchecked(i); TRI_ASSERT(valueNode); if (!::filter(filter, ctx, subFilterCtx, *valueNode)) { return false; } } return true; } // Analyze(<filter-expression>, analyzer) bool fromFuncAnalyzer( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& args ) { auto const argc = args.numMembers(); if (argc != 2) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'ANALYZER' AQL function: Invalid number of arguments passed (must be 2)"; return false; } // 1st argument defines filter expression auto expressionArg = args.getMemberUnchecked(0); if (!expressionArg) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'ANALYZER' AQL function: 1st argument is invalid"; return false; } // 2nd argument defines a boost auto const analyzerArg = args.getMemberUnchecked(1); if (!analyzerArg) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'ANALYZER' AQL function: 2nd argument is invalid"; return false; } if (!analyzerArg->isDeterministic()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'ANALYZER' AQL function: 2nd argument is intended to be deterministic"; return false; } ScopedAqlValue analyzerId(*analyzerArg); auto analyzer = IResearchAnalyzerFeature::identity(); // default analyzer if (filter || analyzerId.isConstant()) { if (!analyzerId.execute(ctx)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'ANALYZER' AQL function: Failed to evaluate 2nd argument"; return false; } if (arangodb::iresearch::SCOPED_VALUE_TYPE_STRING != analyzerId.type()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'ANALYZER' AQL function: 'analyzer' argument has invalid type '" << analyzerId.type() << "' (string expected)"; return false; } irs::string_ref analyzerIdValue; if (!analyzerId.getString(analyzerIdValue)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'ANALYZER' AQL function: Unable to parse 2nd argument as string"; return false; } auto* analyzerFeature = arangodb::application_features::ApplicationServer::lookupFeature< IResearchAnalyzerFeature >(); if (!analyzerFeature) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'" << IResearchAnalyzerFeature::name() << "' feature is not registered, unable to evaluate 'ANALYZER' function"; return false; } analyzer = analyzerFeature->get(analyzerIdValue); if (!analyzer) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'ANALYZER' AQL function: Unable to lookup analyzer '" << analyzerIdValue << "'"; return false; } } FilterContext const subFilterContext{ analyzer, // override analyzer filterCtx.boost }; return ::filter(filter, ctx, subFilterContext, *expressionArg); } // BOOST(<filter-expression>, boost) bool fromFuncBoost( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& args ) { auto const argc = args.numMembers(); if (argc != 2) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'BOOST' AQL function: Invalid number of arguments passed (must be 2)"; return false; } // 1st argument defines filter expression auto expressionArg = args.getMemberUnchecked(0); if (!expressionArg) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'BOOST' AQL function: 1st argument is invalid"; return false; } // 2nd argument defines a boost auto const boostArg = args.getMemberUnchecked(1); if (!boostArg) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'BOOST' AQL function: 2nd argument is invalid"; return false; } if (!boostArg->isDeterministic()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'BOOST' AQL function: 2nd argument is intended to be deterministic"; return false; } ScopedAqlValue boost(*boostArg); double_t boostValue = 0; if (filter || boost.isConstant()) { if (!boost.execute(ctx)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'BOOST' AQL function: Failed to evaluate 2nd argument"; return false; } if (arangodb::iresearch::SCOPED_VALUE_TYPE_DOUBLE != boost.type()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'BOOST' AQL function: 2nd argument has invalid type '" << boost.type() << "' (double expected)"; return false; } if (!boost.getDouble(boostValue)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'BOOST' AQL function: Failed to parse 2nd argument as string"; return false; } } FilterContext const subFilterContext { filterCtx.analyzer, filterCtx.boost * static_cast<float_t>(boostValue) }; return ::filter(filter, ctx, subFilterContext, *expressionArg); } // EXISTS(<attribute>, <"analyzer">, <"analyzer-name">) // EXISTS(<attribute>, <"string"|"null"|"bool"|"numeric">) bool fromFuncExists( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& args ) { if (!args.isDeterministic()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "Unable to handle non-deterministic arguments for 'EXISTS' function"; return false; // nondeterministic } auto const argc = args.numMembers(); if (argc < 1 || argc > 3) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'EXISTS' AQL function: Invalid number of arguments passed (must be >= 1 and <= 3)"; return false; } // 1st argument defines a field auto const* fieldArg = arangodb::iresearch::checkAttributeAccess( args.getMemberUnchecked(0), *ctx.ref ); if (!fieldArg) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'EXISTS' AQL function: 1st argument is invalid"; return false; } bool prefixMatch = true; std::string fieldName; auto analyzer = filterCtx.analyzer; if (filter && !arangodb::iresearch::nameFromAttributeAccess(fieldName, *fieldArg, ctx)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'EXISTS' AQL function: Failed to generate field name from the 1st argument"; return false; } if (argc > 1) { // 2nd argument defines a type (if present) auto const typeArg = args.getMemberUnchecked(1); if (!typeArg) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'EXISTS' AQL function: 2nd argument is invalid"; return false; } irs::string_ref arg; ScopedAqlValue type(*typeArg); if (filter || type.isConstant()) { if (!type.execute(ctx)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'EXISTS' AQL function: Failed to evaluate 2nd argument"; return false; } if (arangodb::iresearch::SCOPED_VALUE_TYPE_STRING != type.type()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'EXISTS' AQL function: 2nd argument has invalid type '" << type.type() << "' (string expected)"; return false; } if (!type.getString(arg)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'EXISTS' AQL function: Failed to parse 2nd argument as string"; return false; } std::string strArg(arg); arangodb::basics::StringUtils::tolowerInPlace(&strArg); // normalize user input irs::string_ref const TypeAnalyzer("analyzer"); typedef bool(*TypeHandler)(std::string&, IResearchAnalyzerFeature::AnalyzerPool const&); static std::map<irs::string_ref, TypeHandler> const TypeHandlers { // any string { irs::string_ref("string"), [] (std::string& name, IResearchAnalyzerFeature::AnalyzerPool const&) { kludge::mangleAnalyzer(name); return true; // a prefix match } }, // any non-string type { irs::string_ref("type"), [](std::string& name, IResearchAnalyzerFeature::AnalyzerPool const&) { kludge::mangleType(name); return true; // a prefix match } }, // concrete analyzer from the context { TypeAnalyzer, [](std::string& name, IResearchAnalyzerFeature::AnalyzerPool const& analyzer) { kludge::mangleStringField(name, analyzer); return false; // not a prefix match } }, { irs::string_ref("numeric"), [] (std::string& name, IResearchAnalyzerFeature::AnalyzerPool const&) { kludge::mangleNumeric(name); return false; // not a prefix match } }, { irs::string_ref("bool"), [] (std::string& name, IResearchAnalyzerFeature::AnalyzerPool const&) { kludge::mangleBool(name); return false; // not a prefix match } }, { irs::string_ref("boolean"), [] (std::string& name, IResearchAnalyzerFeature::AnalyzerPool const&) { kludge::mangleBool(name); return false; // not a prefix match } }, { irs::string_ref("null"), [] (std::string& name, IResearchAnalyzerFeature::AnalyzerPool const&) { kludge::mangleNull(name); return false; // not a prefix match } } }; auto const typeHandler = TypeHandlers.find(strArg); if (TypeHandlers.end() == typeHandler) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'EXISTS' AQL function: 2nd argument must be equal to one of the following:" " 'string', 'type', 'analyzer', 'numeric', 'bool', 'boolean', 'null', but got '" << arg << "'"; return false; } if (argc > 2) { if (TypeAnalyzer.c_str() != typeHandler->first.c_str()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'EXISTS' AQL function: 3rd argument is intended to use with 'analyzer' type only"; return false; } analyzer = extractAnalyzerFromArg( filter, args.getMemberUnchecked(2), ctx, 2, "EXISTS" ); if (!analyzer) { return false; } } prefixMatch = typeHandler->second(fieldName, *analyzer); } } if (filter) { auto& exists = filter->add<irs::by_column_existence>(); exists.field(std::move(fieldName)); exists.boost(filterCtx.boost); exists.prefix_match(prefixMatch); } return true; } // MIN_MATCH(<filter-expression>[, <filter-expression>,...], <min-match-count>) bool fromFuncMinMatch( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& args ) { auto const argc = args.numMembers(); if (argc < 2) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'MIN_MATCH' AQL function: Invalid number of arguments passed (must be >= 2)"; return false; } // ........................................................................... // last argument defines min match count // ........................................................................... auto const lastArg = argc - 1; auto minMatchCountArg = args.getMemberUnchecked(lastArg); if (!minMatchCountArg) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'MIN_MATCH' AQL function: " << lastArg << " argument is invalid"; return false; } if (!minMatchCountArg->isDeterministic()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'MIN_MATCH' AQL function: " << lastArg << " argument is intended to be deterministic"; return false; } ScopedAqlValue minMatchCount(*minMatchCountArg); int64_t minMatchCountValue = 0; if (filter || minMatchCount.isConstant()) { if (!minMatchCount.execute(ctx)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'MIN_MATCH' AQL function: Failed to evaluate " << lastArg << " argument"; return false; } if (arangodb::iresearch::SCOPED_VALUE_TYPE_DOUBLE != minMatchCount.type()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'MIN_MATCH' AQL function: " << lastArg << " argument has invalid type '" << minMatchCount.type() << "' (numeric expected)"; return false; } minMatchCountValue = minMatchCount.getInt64(); } if (filter) { auto& minMatchFilter = filter->add<irs::Or>(); minMatchFilter.min_match_count(minMatchCountValue); minMatchFilter.boost(filterCtx.boost); // become a new root filter = &minMatchFilter; } FilterContext const subFilterCtx { filterCtx.analyzer, irs::boost::no_boost() // reset boost }; for (size_t i = 0; i < lastArg; ++i) { auto subFilterExpression = args.getMemberUnchecked(i); if (!subFilterExpression) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'MIN_MATCH' AQL function: Failed to evaluate " << i << " argument"; return false; } irs::boolean_filter* subFilter = filter ? &filter->add<irs::Or>() : nullptr; if (!::filter(subFilter, ctx, subFilterCtx, *subFilterExpression)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'MIN_MATCH' AQL function: Failed to instantiate sub-filter for " << i << " argument"; return false; } } return true; } // PHRASE(<attribute>, <value> [, <offset>, <value>, ...] [, <analyzer>]) // PHRASE(<attribute>, '[' <value> [, <offset>, <value>, ...] ']' [, <analyzer>]) bool fromFuncPhrase( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& args ) { if (!args.isDeterministic()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "Unable to handle non-deterministic arguments for 'PHRASE' function"; return false; // nondeterministic } auto argc = args.numMembers(); if (argc < 2) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'PHRASE' AQL function: Invalid number of arguments passed (must be >= 2)"; return false; } // ........................................................................... // last odd argument defines an analyzer // ........................................................................... auto analyzerPool = filterCtx.analyzer; if (0 != (argc & 1)) { // override analyzer --argc; analyzerPool = extractAnalyzerFromArg( filter, args.getMemberUnchecked(argc), ctx, argc, "PHRASE" ); if (!analyzerPool) { return false; } } // ........................................................................... // 1st argument defines a field // ........................................................................... auto const* fieldArg = arangodb::iresearch::checkAttributeAccess( args.getMemberUnchecked(0), *ctx.ref ); if (!fieldArg) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'PHRASE' AQL function: 1st argument is invalid"; return false; } // ........................................................................... // 2nd argument defines a value // ........................................................................... auto const* valueArg = args.getMemberUnchecked(1); if (!valueArg) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'PHRASE' AQL function: 2nd argument is invalid"; return false; } auto* valueArgs = &args; size_t valueArgsBegin = 1; size_t valueArgsEnd = argc; if (valueArg->isArray()) { valueArgs = valueArg; valueArgsBegin = 0; valueArgsEnd = valueArg->numMembers(); if (0 == (valueArgsEnd & 1)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'PHRASE' AQL function: 2nd argument has an invalid number of members (must be an odd number)"; return false; } valueArg = valueArgs->getMemberUnchecked(valueArgsBegin); if (!valueArg) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'PHRASE' AQL function: 2nd argument has an invalid member at offset: " << valueArg; return false; } } irs::string_ref value; ScopedAqlValue inputValue(*valueArg); if (filter || inputValue.isConstant()) { if (!inputValue.execute(ctx)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'PHRASE' AQL function: Failed to evaluate 2nd argument"; return false; } if (arangodb::iresearch::SCOPED_VALUE_TYPE_STRING != inputValue.type()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'PHRASE' AQL function: 2nd argument has invalid type '" << inputValue.type() << "' (string expected)"; return false; } if (!inputValue.getString(value)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'PHRASE' AQL function: Unable to parse 2nd argument as string"; return false; } } irs::by_phrase* phrase = nullptr; irs::analysis::analyzer::ptr analyzer; if (filter) { std::string name; if (!arangodb::iresearch::nameFromAttributeAccess(name, *fieldArg, ctx)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'PHRASE' AQL function: Failed to generate field name from the 1st argument"; return false; } TRI_ASSERT(analyzerPool); analyzer = analyzerPool->get(); // get analyzer from pool if (!analyzer) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'PHRASE' AQL function: Unable to instantiate analyzer '" << analyzerPool->name() << "'"; return false; } kludge::mangleStringField(name, *analyzerPool); phrase = &filter->add<irs::by_phrase>(); phrase->field(std::move(name)); phrase->boost(filterCtx.boost); TRI_ASSERT(analyzer); appendTerms(*phrase, value, *analyzer, 0); } decltype(fieldArg) offsetArg = nullptr; size_t offset = 0; for (size_t idx = valueArgsBegin + 1, end = valueArgsEnd; idx < end; idx += 2) { offsetArg = valueArgs->getMemberUnchecked(idx); if (!offsetArg) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'PHRASE' AQL function: Unable to parse argument on position " << idx << " as an offset"; return false; } valueArg = valueArgs->getMemberUnchecked(idx + 1); if (!valueArg) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'PHRASE' AQL function: Unable to parse argument on position " << idx + 1 << " as a value"; return false; } ScopedAqlValue offsetValue(*offsetArg); if (filter || offsetValue.isConstant()) { if (!offsetValue.execute(ctx) || arangodb::iresearch::SCOPED_VALUE_TYPE_DOUBLE != offsetValue.type()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'PHRASE' AQL function: Unable to parse argument on position " << idx << " as an offset"; return false; } offset = static_cast<uint64_t>(offsetValue.getInt64()); } ScopedAqlValue inputValue(*valueArg); if (filter || inputValue.isConstant()) { if (!inputValue.execute(ctx) || arangodb::iresearch::SCOPED_VALUE_TYPE_STRING != inputValue.type() || !inputValue.getString(value)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'PHRASE' AQL function: Unable to parse argument on position " << idx + 1 << " as a value"; return false; } } if (phrase) { TRI_ASSERT(analyzer); appendTerms(*phrase, value, *analyzer, offset); } } return true; } // STARTS_WITH(<attribute>, <prefix>, [<scoring-limit>]) bool fromFuncStartsWith( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& args ) { if (!args.isDeterministic()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "Unable to handle non-deterministic arguments for 'STARTS_WITH' function"; return false; // nondeterministic } auto const argc = args.numMembers(); if (argc < 2 || argc > 3) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'STARTS_WITH' AQL function: Invalid number of arguments passed (should be >= 2 and <= 3)"; return false; } // 1st argument defines a field auto const* field = arangodb::iresearch::checkAttributeAccess( args.getMemberUnchecked(0), *ctx.ref ); if (!field) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'STARTS_WITH' AQL function: Unable to parse 1st argument as an attribute identifier"; return false; } // 2nd argument defines a value auto const* prefixArg = args.getMemberUnchecked(1); if (!prefixArg) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'STARTS_WITH' AQL function: 2nd argument is invalid"; return false; } irs::string_ref prefix; size_t scoringLimit = 128; // FIXME make configurable ScopedAqlValue prefixValue(*prefixArg); if (filter || prefixValue.isConstant()) { if (!prefixValue.execute(ctx)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'STARTS_WITH' AQL function: Failed to evaluate 2nd argument"; return false; } if (arangodb::iresearch::SCOPED_VALUE_TYPE_STRING != prefixValue.type()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'STARTS_WITH' AQL function: 2nd argument has invalid type '" << prefixValue.type() << "' (string expected)"; return false; } if (!prefixValue.getString(prefix)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'STARTS_WITH' AQL function: Unable to parse 2nd argument as string"; return false; } } if (argc > 2) { // 3rd (optional) argument defines a number of scored terms auto const* scoringLimitArg = args.getMemberUnchecked(2); if (!scoringLimitArg) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'STARTS_WITH' AQL function: 3rd argument is invalid"; return false; } ScopedAqlValue scoringLimitValue(*scoringLimitArg); if (filter || scoringLimitValue.isConstant()) { if (!scoringLimitValue.execute(ctx)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'STARTS_WITH' AQL function: Failed to evaluate 3rd argument"; return false; } if (arangodb::iresearch::SCOPED_VALUE_TYPE_DOUBLE != scoringLimitValue.type()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'STARTS_WITH' AQL function: 3rd argument has invalid type '" << scoringLimitValue.type() << "' (numeric expected)"; return false; } scoringLimit = static_cast<size_t>(scoringLimitValue.getInt64()); } } if (filter) { std::string name; if (!nameFromAttributeAccess(name, *field, ctx)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "'STARTS_WITH' AQL function: Failed to generate field name from the 1st argument"; return false; } TRI_ASSERT(filterCtx.analyzer); kludge::mangleStringField(name, *filterCtx.analyzer); auto& prefixFilter = filter->add<irs::by_prefix>(); prefixFilter.scored_terms_limit(scoringLimit); prefixFilter.field(std::move(name)); prefixFilter.boost(filterCtx.boost); prefixFilter.term(prefix); } return true; } std::map<irs::string_ref, ConvertionHandler> const FCallUserConvertionHandlers; bool fromFCallUser( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& node ) { TRI_ASSERT(arangodb::aql::NODE_TYPE_FCALL_USER == node.type); if (node.numMembers() != 1) { logMalformedNode(node.type); return false; } auto const* args = arangodb::iresearch::getNode( node, 0, arangodb::aql::NODE_TYPE_ARRAY ); if (!args) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "Unable to parse user function arguments as an array'"; return false; // invalid args } irs::string_ref name; if (!arangodb::iresearch::parseValue(name, node)) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "Unable to parse user function name"; return false; } auto const entry = FCallUserConvertionHandlers.find(name); if (entry == FCallUserConvertionHandlers.end()) { return fromExpression(filter, ctx, filterCtx, node); } if (!args->isDeterministic()) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "Unable to handle non-deterministic function '" << name << "' arguments"; return false; // nondeterministic } return entry->second(filter, ctx, filterCtx, *args); } std::map<std::string, ConvertionHandler> const FCallSystemConvertionHandlers{ { "PHRASE", fromFuncPhrase }, { "STARTS_WITH", fromFuncStartsWith }, { "EXISTS", fromFuncExists }, { "BOOST", fromFuncBoost }, { "ANALYZER", fromFuncAnalyzer }, { "MIN_MATCH", fromFuncMinMatch } }; bool fromFCall( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& node ) { TRI_ASSERT(arangodb::aql::NODE_TYPE_FCALL == node.type); auto const* fn = static_cast<arangodb::aql::Function*>(node.getData()); if (!fn || node.numMembers() != 1) { logMalformedNode(node.type); return false; // no function } if (!arangodb::iresearch::isFilter(*fn)) { // not a filter function return fromExpression(filter, ctx, filterCtx, node); } auto const entry = FCallSystemConvertionHandlers.find(fn->name); if (entry == FCallSystemConvertionHandlers.end()) { return fromExpression(filter, ctx, filterCtx, node); } auto const* args = arangodb::iresearch::getNode(node, 0, arangodb::aql::NODE_TYPE_ARRAY); if (!args) { LOG_TOPIC(WARN, arangodb::iresearch::TOPIC) << "Unable to parse arguments of system function '" << fn->name << "' as an array'"; return false; // invalid args } return entry->second(filter, ctx, filterCtx, *args); } bool fromFilter( irs::boolean_filter* filter, QueryContext const& ctx, FilterContext const& filterCtx, arangodb::aql::AstNode const& node ) { TRI_ASSERT(arangodb::aql::NODE_TYPE_FILTER == node.type); if (node.numMembers() != 1) { logMalformedNode(node.type); return false; // wrong number of members } auto const* member = node.getMemberUnchecked(0); return member && ::filter(filter, ctx, filterCtx, *member); } bool filter( irs::boolean_filter* filter, QueryContext const& queryCtx, FilterContext const& filterCtx, arangodb::aql::AstNode const& node ) { switch (node.type) { case arangodb::aql::NODE_TYPE_FILTER: // FILTER return fromFilter(filter, queryCtx, filterCtx, node); case arangodb::aql::NODE_TYPE_VARIABLE: // variable return fromExpression(filter, queryCtx, filterCtx, node); case arangodb::aql::NODE_TYPE_OPERATOR_UNARY_NOT: // unary minus return fromNegation(filter, queryCtx, filterCtx, node); case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_AND: // logical and return fromGroup<irs::And>(filter, queryCtx, filterCtx, node); case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_OR: // logical or return fromGroup<irs::Or>(filter, queryCtx, filterCtx, node); case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_EQ: // compare == case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NE: // compare != return fromBinaryEq(filter, queryCtx, filterCtx, node); case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_LT: // compare < case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_LE: // compare <= case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_GT: // compare > case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_GE: // compare >= return fromInterval(filter, queryCtx, filterCtx, node); case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_IN: // compare in case arangodb::aql::NODE_TYPE_OPERATOR_BINARY_NIN: // compare not in return fromIn(filter, queryCtx, filterCtx, node); case arangodb::aql::NODE_TYPE_OPERATOR_TERNARY: // ternary case arangodb::aql::NODE_TYPE_ATTRIBUTE_ACCESS: // attribute access case arangodb::aql::NODE_TYPE_VALUE : // value case arangodb::aql::NODE_TYPE_ARRAY: // array case arangodb::aql::NODE_TYPE_OBJECT: // object case arangodb::aql::NODE_TYPE_REFERENCE: // reference case arangodb::aql::NODE_TYPE_PARAMETER: // bind parameter return fromExpression(filter, queryCtx, filterCtx, node); case arangodb::aql::NODE_TYPE_FCALL: // function call return fromFCall(filter, queryCtx, filterCtx, node); case arangodb::aql::NODE_TYPE_FCALL_USER: // user function call return fromFCallUser(filter, queryCtx, filterCtx, node); case arangodb::aql::NODE_TYPE_RANGE: // range return fromRange(filter, queryCtx, filterCtx, node); case arangodb::aql::NODE_TYPE_OPERATOR_NARY_AND: // n-ary and return fromGroup<irs::And>(filter, queryCtx, filterCtx, node); case arangodb::aql::NODE_TYPE_OPERATOR_NARY_OR: // n-ary or return fromGroup<irs::Or>(filter, queryCtx, filterCtx, node); default: return fromExpression(filter, queryCtx, filterCtx, node); } } } namespace arangodb { namespace iresearch { // ---------------------------------------------------------------------------- // --SECTION-- FilerFactory implementation // ---------------------------------------------------------------------------- /*static*/ bool FilterFactory::filter( irs::boolean_filter* filter, QueryContext const& ctx, arangodb::aql::AstNode const& node ) { FilterContext const filterCtx{ IResearchAnalyzerFeature::identity(), irs::boost::no_boost() }; return ::filter(filter, ctx, filterCtx, node); } } // iresearch } // arangodb // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // -----------------------------------------------------------------------------
29.958333
120
0.633799
pavelsevcik
3a2872084f9fb02bb2ad83efe1439a4de98540e3
3,760
cpp
C++
QTDialogs/QtOpenGLView/BaseGLView.cpp
msolids/musen
67d9a70d03d771ccda649c21b78d165684e31171
[ "BSD-3-Clause" ]
19
2020-09-28T07:22:50.000Z
2022-03-07T09:52:20.000Z
QTDialogs/QtOpenGLView/BaseGLView.cpp
LasCondes/musen
18961807928285ff802e050050f4c627dd7bec1e
[ "BSD-3-Clause" ]
5
2020-12-26T18:18:27.000Z
2022-02-23T22:56:43.000Z
QTDialogs/QtOpenGLView/BaseGLView.cpp
LasCondes/musen
18961807928285ff802e050050f4c627dd7bec1e
[ "BSD-3-Clause" ]
11
2020-11-02T11:32:03.000Z
2022-01-27T08:22:04.000Z
/* Copyright (c) 2013-2020, MUSEN Development Team. All rights reserved. This file is part of MUSEN framework http://msolids.net/musen. See LICENSE file for license and warranty information. */ #include "BaseGLView.h" #include <QPainter> #include <QtMath> void CBaseGLView::SetFontTime(const QFont& _font, const QColor& _color) { m_fontTime.font = _font; m_fontTime.color = _color; } void CBaseGLView::SetFontAxes(const QFont& _font, const QColor& _color) { m_fontAxes.font = _font; m_fontAxes.color = _color; } void CBaseGLView::SetFontLegend(const QFont& _font, const QColor& _color) { m_fontLegend.font = _font; m_fontLegend.color = _color; } void CBaseGLView::SetCameraStandardView(const SBox& _box, const QVector3D& _cameraDirection) { const QVector3D maxLength{ std::max(_box.maxCoord.y() - _box.minCoord.y(), _box.maxCoord.z() - _box.minCoord.z()), std::max(_box.maxCoord.x() - _box.minCoord.x(), _box.maxCoord.z() - _box.minCoord.z()), std::max(_box.maxCoord.x() - _box.minCoord.x(), _box.maxCoord.y() - _box.minCoord.y()) }; const QVector3D midCoord = (_box.maxCoord + _box.minCoord) / 2; // update viewport and projection matrix m_viewport.zNear = std::max({ maxLength.x(), maxLength.y(), maxLength.z() }) * 10e-2f; m_viewport.zFar = m_viewport.zNear * 10e+5f; UpdatePerspective(); // set camera translation m_cameraTranslation[0] = -midCoord.x(); m_cameraTranslation[1] = -midCoord.z(); m_cameraTranslation[2] = -midCoord.y(); // setup camera position according to length and height if (_cameraDirection.x() != 0) m_cameraTranslation[0] = -midCoord.y(); if (_cameraDirection.x() == -1) m_cameraTranslation[0] += 2.0f * midCoord.y(); if (_cameraDirection.y() == 1) m_cameraTranslation[0] += 2.0f * midCoord.x(); if (_cameraDirection.z() != 0) std::swap(m_cameraTranslation[1], m_cameraTranslation[2]); if (_cameraDirection.z() == -1) m_cameraTranslation[1] += 2.0f * midCoord.y(); // setup camera position according to depth if (_cameraDirection.x() != 0) m_cameraTranslation[2] = -maxLength.x() / (2 * std::tan(m_viewport.fovy / 2 * static_cast<float>(M_PI) / 180)); if (_cameraDirection.x() == 1) m_cameraTranslation[2] -= _box.maxCoord.x(); if (_cameraDirection.x() == -1) m_cameraTranslation[2] += _box.minCoord.x(); if (_cameraDirection.y() != 0) m_cameraTranslation[2] = -maxLength.y() / (2 * std::tan(m_viewport.fovy / 2 * static_cast<float>(M_PI) / 180)); if (_cameraDirection.y() == 1) m_cameraTranslation[2] -= _box.maxCoord.y(); if (_cameraDirection.y() == -1) m_cameraTranslation[2] += _box.minCoord.y(); if (_cameraDirection.z() != 0) m_cameraTranslation[2] = -maxLength.z() / (2 * std::tan(m_viewport.fovy / 2 * static_cast<float>(M_PI) / 180)); if (_cameraDirection.z() == 1) m_cameraTranslation[2] -= _box.maxCoord.z(); if (_cameraDirection.z() == -1) m_cameraTranslation[2] += _box.minCoord.z(); // set camera rotation m_cameraRotation[0] = _cameraDirection.z() * 90.0f - 90.0f; m_cameraRotation[1] = 0.0f; m_cameraRotation[2] = -_cameraDirection.x() * 90.0f + 180.0f * std::max(_cameraDirection.y(), 0.0f); } SCameraSettings CBaseGLView::GetCameraSettings() const { return { m_viewport, m_cameraTranslation, m_cameraRotation }; } void CBaseGLView::SetCameraSettings(const SCameraSettings& _settings) { m_viewport = _settings.viewport; m_cameraTranslation = _settings.translation; m_cameraRotation = _settings.rotation; UpdatePerspective(); Redraw(); } void CBaseGLView::SetupPainter(QPainter* _painter, const SFont& _font) const { QFont font(_font.font); font.setPointSize(_font.font.pointSize() * m_scaling); _painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); _painter->setPen(_font.color); _painter->setFont(font); }
39.578947
143
0.71383
msolids
3a2a326d67ca331b394193abd7cbd498822c1ddf
3,385
cpp
C++
SRC/Element/Interpolation/Utils/MultiIndex/MultiIndex.cpp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
SRC/Element/Interpolation/Utils/MultiIndex/MultiIndex.cpp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
SRC/Element/Interpolation/Utils/MultiIndex/MultiIndex.cpp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
// MultiIndex.cpp: implementation of the MultiIndex class. // Copyright (c) 2017-2018 Extreme Computation Technology and Solutions, LLC // All rights reserved // see file License.txt for license details ////////////////////////////////////////////////////////////////////// //#include <cassert> #include "./MultiIndex.h" namespace Element { namespace Interpolation { namespace Utils { ////////////////////////////////////////////////////////////////////// // Class MultiIndex ////////////////////////////////////////////////////////////////////// MultiIndex::MultiIndex() : n(0), head(0), tail(0){} MultiIndex::MultiIndex(const unsigned int &n_) : n(n_), head(new unsigned int [n]), tail(head+n) { unsigned int *p; for (p=head; p<tail; p++) *p=0; } MultiIndex::~MultiIndex(){delete [] head;} MultiIndex::MultiIndex(const MultiIndex &A) : n(A.n), head(new unsigned int [n]), tail(head+n) { unsigned int *p, *q; for (p=head, q=A.head; p<tail; p++, q++) *p = *q; } MultiIndex & MultiIndex::operator = (const MultiIndex &A) { if (this == &A) return *this; assert(n == A.n); unsigned int *p, *q; for (p=head, q=A.head; p<tail; p++, q++) *p = *q; return *this; } unsigned int * const & MultiIndex::begin() const{return head;} unsigned int * const & MultiIndex::end() const{return tail;} const unsigned int & MultiIndex::operator [] (const unsigned int &i) const { assert(i < n); return *(head+i); } unsigned int & MultiIndex::operator [] (const unsigned int &i) { assert(i < n); return *(head+i); } bool MultiIndex::operator < (const MultiIndex &A) const { assert (A.size() == n); unsigned int *p, *q; for (p=head, q=A.begin(); p!=tail; p++, q++) { if (*p < *q) return true; if (*p > *q) return false; } return false; } bool MultiIndex::operator == (const MultiIndex &A) const { assert (A.size() == n); unsigned int *p, *q; for (p=head, q=A.begin(); p!=tail; p++, q++) if (*p != *q) return false; return true; } bool MultiIndex::operator != (const MultiIndex &A) const { assert (A.size() == n); unsigned int *p, *q; for (p=head, q=A.begin(); p!=tail; p++, q++) if (*p != *q) return true; return false; } void MultiIndex::print(ostream *os) const { unsigned int *p; for (p=head; p<tail; p++) *os << *p << ", "; } unsigned int MultiIndex::size() const { return n; } unsigned int MultiIndex::degree() const { unsigned int k=0; unsigned int *p; for (p=head; p<tail; p++) k += *p; return k; } ////////////////////////////////////////////////////////////////////// // Utilities ////////////////////////////////////////////////////////////////////// MultiIndex Reduce(const MultiIndex &b) { MultiIndex a = b; unsigned int i, m=a.degree(); if (m == 0) return a; for (i=0; i<a.size(); i++) if ((a[i] != 0) && (a[i] < m)) m = a[i]; if (m == 1) return a; for (i=0; i<a.size(); i++) if (a[i]%m != 0) return a; for (i=0; i<a.size(); i++) a[i] /= m; return a; } } } } ////////////////////////////////////////////////////////////////////// // Class MultiIndex: operators ////////////////////////////////////////////////////////////////////// ostream & operator<<(ostream &os, const Element::Interpolation::Utils::MultiIndex &A) { A.print(&os); return os; }
22.269737
77
0.49483
bxl295
3a2b75c9ddfb50b8139901d55955ffb51bd5eff2
441
cpp
C++
lib/OTExtensionBristol/Networking/data.cpp
manel1874/libscapi
8cf705162af170c04c8e2299213f52888193cabe
[ "MIT" ]
160
2016-05-11T09:45:56.000Z
2022-03-06T09:32:19.000Z
Networking/data.cpp
bristolcrypto/apricot
3760dda51b0080ee0fb79c7184cbe2c00762c2b8
[ "BSD-4-Clause-UC" ]
57
2016-12-26T07:02:12.000Z
2022-03-06T16:34:31.000Z
lib/OTExtensionBristol/Networking/data.cpp
manel1874/libscapi
8cf705162af170c04c8e2299213f52888193cabe
[ "MIT" ]
67
2016-10-10T17:56:22.000Z
2022-03-15T22:56:39.000Z
// (C) 2016 University of Bristol. See LICENSE.txt #include "data.h" #include "Exceptions/Exceptions.h" void encode_length(octet *buff,int len) { if (len<0) { throw invalid_length(); } buff[0]=len&255; buff[1]=(len>>8)&255; buff[2]=(len>>16)&255; buff[3]=(len>>24)&255; } int decode_length(octet *buff) { int len=buff[0]+256*buff[1]+65536*buff[2]+16777216*buff[3]; if (len<0) { throw invalid_length(); } return len; }
18.375
61
0.643991
manel1874
3a36f400b910612543529a658e55d8127d67c61b
48,334
cxx
C++
src/usb/ft4222/ftdi_ft4222.cxx
nazeer22/mraa
0a12c5a0177f9fa8e7c4c564e70a65c4a0bb81af
[ "MIT" ]
2
2019-04-17T12:41:28.000Z
2019-06-03T12:30:12.000Z
src/usb/ft4222/ftdi_ft4222.cxx
nazeer22/mraa
0a12c5a0177f9fa8e7c4c564e70a65c4a0bb81af
[ "MIT" ]
1
2018-11-01T14:54:06.000Z
2018-11-01T14:54:06.000Z
src/usb/ft4222/ftdi_ft4222.cxx
nazeer22/mraa
0a12c5a0177f9fa8e7c4c564e70a65c4a0bb81af
[ "MIT" ]
2
2018-07-12T11:59:47.000Z
2018-12-14T14:22:14.000Z
/* * Author: Henry Bruce <henry.bruce@intel.com> * Copyright (c) 2015 Intel Corporation. * * 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 "ftdi_ft4222.hpp" #include "ftd2xx.h" #include "libft4222.h" #include "linux/i2c-dev.h" #include "types.h" #include <algorithm> #include <cerrno> #include <cstdlib> #include <cstring> #include <cstring> #include <ctime> #include <map> #include <pthread.h> #include <sstream> #include <string> #include <sys/time.h> #include <vector> namespace ft4222 { #define gpioPinsPerFt4222 4 /* These devices have configurable addresses which leave it up to makers of * development expander boards to either set these addresses or provide a means * to set them (jumpers or solder). The dev boards for both the PCA9555 and * PCA9672 have a slave address of 010 0xxx (where xxx is configurable). */ #define PCA9672_ADDR 0x20 #define PCA9555_ADDR 0x27 #define PCA9555_INPUT_REG 0 #define PCA9555_OUTPUT_REG 2 #define PCA9555_POLARITY_REG 4 #define PCA9555_DIRECTION_REG 6 #define PCA9545_ADDR 0x70 #define PCA9672_PINS 8 #define PCA9555_PINS 16 #define PCA9545_BUSSES 4 #define GPIO_PORT_IO_RESET GPIO_PORT2 #define GPIO_PORT_IO_INT GPIO_PORT3 #define MAX_IO_EXPANDER_PINS PCA9555_PINS /* GPIO expander types */ typedef enum { IO_EXP_NONE, IO_EXP_PCA9672, IO_EXP_PCA9555 } ft4222_io_exp_type; /* GPIO types */ typedef enum { GPIO_TYPE_BUILTIN, GPIO_TYPE_PCA9672, GPIO_TYPE_PCA9555, GPIO_TYPE_UNKNOWN = 99 } ft4222_gpio_type; /* GPIO expander interrupt monitor */ struct gpio_expander_intmon { pthread_t thread; pthread_mutex_t mutex; mraa_boolean_t should_stop; mraa_boolean_t is_interrupt_detected[MAX_IO_EXPANDER_PINS]; int num_active_pins; }; /* At present, no c++11 in mraa, so create a lock guard */ class lock_guard { public: lock_guard(pthread_mutex_t& mtx) : _mtx(mtx) { if (pthread_mutex_lock(&_mtx)) syslog(LOG_ERR, "FT4222 error creating lock on mutex"); } virtual ~lock_guard() { if (pthread_mutex_unlock(&_mtx)) syslog(LOG_ERR, "FT4222 error creating lock on mutex"); } private: pthread_mutex_t& _mtx; }; /* Each FT4222 device is represented by 1 Ftdi_4222_Shim instance */ class Ftdi_4222_Shim { public: Ftdi_4222_Shim(); virtual ~Ftdi_4222_Shim(); static mraa_board_t* init_and_setup_mraa_board(); bool init_next_free_ftdi4222_device(); bool setup_io(); bool init_ftdi_gpios(); int ft4222_detect_i2c_switch(); uint32_t ftdi_device_id; uint8_t pca9672DirectionMask; union { uint16_t word; uint8_t bytes[2]; } pca9555OutputValue; union { uint16_t word; uint8_t bytes[2]; } pca9555DirectionValue; gpio_expander_intmon gpio_mon; std::vector<GPIO_Dir> pinDirection; FT_HANDLE h_gpio; FT_HANDLE h_i2c; FT_HANDLE h_spi; mraa_i2c_mode_t mraa_i2c_mode; uint32_t ft4222_i2c_speed(); pthread_mutex_t mtx_ft4222; int cur_i2c_bus; ft4222_io_exp_type exp_type; private: /** * Function detects known I2C I/O expanders and returns the number of GPIO pins * on expander */ int _detect_io_expander(); /* Collection to store the board info for 1 FT4222 device */ mraa_board_t _board; /* Collection to store pin info for 1 FT4222 device */ std::vector<mraa_pininfo_t> _pins; /* Struct to store the function table info for 1 FT4222 device */ mraa_adv_func_t _adv_func_table; }; Ftdi_4222_Shim::Ftdi_4222_Shim() : ftdi_device_id(0), pca9672DirectionMask(0), gpio_mon(), pinDirection(4, GPIO_INPUT), h_gpio(NULL), h_i2c(NULL), h_spi(NULL), mraa_i2c_mode(MRAA_I2C_FAST), cur_i2c_bus(0), exp_type(IO_EXP_NONE), _board(), _adv_func_table() { pca9555OutputValue.word = 0; pca9555DirectionValue.word = 0; /* Initialize mutexes */ pthread_mutexattr_t attr_rec; pthread_mutexattr_init(&attr_rec); pthread_mutexattr_settype(&attr_rec, PTHREAD_MUTEX_RECURSIVE); if (pthread_mutex_init(&mtx_ft4222, &attr_rec) != 0) { syslog(LOG_ERR, "Failed to setup FT HW device mutex for FT4222 access"); throw std::runtime_error("Failed to setup FT HW device mutex for FT4222 access"); } } Ftdi_4222_Shim::~Ftdi_4222_Shim() { if (ftdi_device_id) syslog(LOG_NOTICE, "Closing FTDI FT4222 device id: 0x%08x", ftdi_device_id); if (h_gpio) FT4222_UnInitialize(h_gpio); if (h_i2c) FT4222_UnInitialize(h_i2c); if (h_spi) FT4222_UnInitialize(h_spi); if (h_gpio) FT_Close(h_gpio); if (h_i2c) FT_Close(h_i2c); if (h_spi) FT_Close(h_spi); } /* Global collections for handling multiple shims */ std::vector<Ftdi_4222_Shim> _ftdi_shims; /* Provide a map of i2c bus index to shim pointer */ std::map<int, Ftdi_4222_Shim*> _i2c_bus_to_shim; /* Provide a map of gpio bus index to shim pointer */ std::map<int, Ftdi_4222_Shim*> _gpio_pin_to_shim; uint32_t Ftdi_4222_Shim::ft4222_i2c_speed() { static std::map<mraa_i2c_mode_t, uint32_t> mode2kHz; mode2kHz[MRAA_I2C_STD] = 100; mode2kHz[MRAA_I2C_FAST] = 400; mode2kHz[MRAA_I2C_HIGH] = 3400; return mode2kHz[mraa_i2c_mode]; } Ftdi_4222_Shim* ShimFromI2cBus(int bus) { std::map<int, Ftdi_4222_Shim*>::iterator it = _i2c_bus_to_shim.find(bus); if (it == _i2c_bus_to_shim.end()) { std::ostringstream oss; oss << "{"; for (std::map<int, Ftdi_4222_Shim*>::const_iterator it = _i2c_bus_to_shim.begin(); it != _i2c_bus_to_shim.end();) { oss << it->first; if (++it != _i2c_bus_to_shim.end()) oss << ", "; } oss << "}"; syslog(LOG_ERR, "Ftdi_4222_Shim lookup failed for I2C bus: %d, valid busses are: %s", bus, oss.str().c_str()); return NULL; } return it->second; } Ftdi_4222_Shim* ShimFromGpioPin(int pin) { std::map<int, Ftdi_4222_Shim*>::iterator it = _gpio_pin_to_shim.find(pin); if (it == _gpio_pin_to_shim.end()) { std::ostringstream oss; oss << "{"; for (std::map<int, Ftdi_4222_Shim*>::const_iterator it = _gpio_pin_to_shim.begin(); it != _gpio_pin_to_shim.end();) { oss << it->first; if (++it != _gpio_pin_to_shim.end()) oss << ", "; } oss << "}"; syslog(LOG_ERR, "Ftdi_4222_Shim lookup failed for pin: %d, valid pins are: %s", pin, oss.str().c_str()); return NULL; } return it->second; } mraa_board_t* Ftdi_4222_Shim::init_and_setup_mraa_board() { /* The Ftdi_4222_Shim constructor can throw */ try { /* Add a shim object to the collection */ _ftdi_shims.push_back(Ftdi_4222_Shim()); } catch (...) { syslog(LOG_ERR, "Failed to create an Ftdi_4222_Shim instance..."); return NULL; } /* Attempt to initialize an FTDI4222 device and setup I/O for use by mraa */ if (_ftdi_shims.back().init_next_free_ftdi4222_device() && _ftdi_shims.back().setup_io()) { return &_ftdi_shims.back()._board; } else { _ftdi_shims.pop_back(); return NULL; } } void ft4222_sleep_ms(unsigned long mseconds) { struct timespec sleepTime = {}; // Number of seconds sleepTime.tv_sec = mseconds / 1000; // Convert fractional seconds to nanoseconds sleepTime.tv_nsec = (mseconds % 1000) * 1000000; // Iterate nanosleep in a loop until the total sleep time is the original // value of the seconds parameter while ((nanosleep(&sleepTime, &sleepTime) != 0) && (errno == EINTR)) ; } bool Ftdi_4222_Shim::init_next_free_ftdi4222_device() { DWORD numDevs = 0; if (FT_CreateDeviceInfoList(&numDevs) != FT_OK) { syslog(LOG_ERR, "FT_CreateDeviceInfoList failed"); return false; } syslog(LOG_NOTICE, "FT_GetDeviceInfoList returned %d devices", numDevs); FT_DEVICE_LIST_INFO_NODE devInfo[numDevs]; if (FT_GetDeviceInfoList(&devInfo[0], &numDevs) != FT_OK) { syslog(LOG_ERR, "FT_GetDeviceInfoList failed"); return false; } int first_4222_ndx = -1; int ftdi_mode = -1; /* Look for FT_DEVICE_4222H_0 devices. Print out all devices found. */ for (DWORD i = 0; i < numDevs; i++) { /* Log info for debugging */ syslog(LOG_NOTICE, " FTDI ndx: %02d id: 0x%08x %s description: '%s'", i, devInfo[i].ID, (devInfo[i].Flags & 0x2) ? "High-speed USB" : "Full-speed USB", &devInfo[i].Description[0]); /* If this FTDI device ID is already assigned to an Ftdi_4222_Shim, * then log and skip */ for (std::vector<Ftdi_4222_Shim>::const_iterator it = _ftdi_shims.begin(); (it != _ftdi_shims.end()) && ((*it).ftdi_device_id != 0); ++it) { if ((*it).ftdi_device_id == devInfo[i].ID) { syslog(LOG_NOTICE, " FTDI ndx: %02d id: 0x%08x already initialized, skipping...", i, devInfo[i].ID); continue; } } /* FTDI_4222 mode 3 provides 2 devices */ if ((first_4222_ndx == -1) && (devInfo[i].Type == FT_DEVICE_4222H_0) && ((i + 1 < numDevs) && (devInfo[i].ID == devInfo[i + 1].ID))) { first_4222_ndx = i; ftdi_mode = 3; } /* FTDI_4222 mode 0 provides 1 device */ else if ((first_4222_ndx == -1) && (devInfo[i].Type == FT_DEVICE_4222H_0)) { first_4222_ndx = i; ftdi_mode = 0; } } /* Was a usable 4222 found? */ if (first_4222_ndx == -1) { syslog(LOG_ERR, "No FT4222 (mode 0 or 3) devices found."); return false; } syslog(LOG_NOTICE, "FTDI 4222 device found at ndx: %02d, mode %d (%s)", first_4222_ndx, ftdi_mode, ftdi_mode == 0 ? "SPI/I2C" : ftdi_mode == 3 ? "SPI/I2C and GPIO" : "Unknown mode"); /* Both modes provide a SPI/I2C at the first ndx */ syslog(LOG_NOTICE, "FTDI ndx: %02d initializing as SPI/I2C", first_4222_ndx); /* Setup I2c */ if (devInfo[first_4222_ndx].LocId == 0) { syslog(LOG_ERR, "No I2C controller for FTDI_4222 device"); return false; } if (FT_OpenEx(reinterpret_cast<PVOID>(devInfo[first_4222_ndx].LocId), FT_OPEN_BY_LOCATION, &h_i2c) != FT_OK) { syslog(LOG_NOTICE, "FTDI ndx: %02d initializing as SPI/I2C device - FAILED to open", first_4222_ndx + 1); return false; } // Tell the FT4222 to be an I2C Master by default on init. if (FT4222_I2CMaster_Init(h_i2c, ft4222_i2c_speed()) != FT4222_OK) { syslog(LOG_NOTICE, "FTDI ndx: %02d initializing as SPI/I2C device - FAILED to " "initialize", first_4222_ndx + 1); return false; } if (FT4222_I2CMaster_Reset(h_i2c) != FT4222_OK) { syslog(LOG_NOTICE, "FTDI ndx: %02d initializing as SPI/I2C device - FAILED to reset", first_4222_ndx + 1); return false; } /* Mode 3 adds 1 GPIO device, setup GPIO */ if (ftdi_mode == 3) { syslog(LOG_NOTICE, "FTDI ndx: %02d initializing as GPIO device", first_4222_ndx + 1); DWORD locationIdGpio = devInfo[first_4222_ndx + 1].LocId; if (locationIdGpio == 0) { syslog(LOG_ERR, "No GPIO controller for FTDI_4222 device"); return false; } if (FT_OpenEx((PVOID)(uintptr_t) locationIdGpio, FT_OPEN_BY_LOCATION, &h_gpio) != FT_OK) { syslog(LOG_NOTICE, "FTDI ndx: %02d initializing as GPIO device - FAILED to open", first_4222_ndx + 1); return false; } if (!init_ftdi_gpios()) { syslog(LOG_NOTICE, "FTDI ndx: %02d initializing as GPIO device - FAILED to initialize", first_4222_ndx + 1); return false; } } /* Save off this FTDI device ID */ ftdi_device_id = devInfo[first_4222_ndx].ID; syslog(LOG_NOTICE, "FTDI FT4222 device initialization completed successfully"); return true; } int ft4222_i2c_read_internal(Ftdi_4222_Shim& shim, uint8_t addr, uint8_t* data, int length) { uint16 bytesRead = 0; uint8 controllerStatus = 0; /* If a read fails, check the I2C controller status, reset the controller. * * In some cases a master read will return FT4222_OK but leaves the bus in * an error state. * */ FT4222_STATUS sts_rd = FT4222_I2CMaster_Read(shim.h_i2c, addr, data, length, &bytesRead); if ((sts_rd != FT4222_OK) || ((FT4222_I2CMaster_GetStatus(shim.h_i2c, &controllerStatus) != FT4222_OK) || (controllerStatus & 0x2))) { FT4222_I2CMaster_GetStatus(shim.h_i2c, &controllerStatus); syslog(LOG_ERR, "FT4222_I2CMaster_Read failed for address 0x%02x with code 0x%02x I2C " "controller status: 0x%02x", addr, sts_rd, controllerStatus); FT4222_I2CMaster_Reset(shim.h_i2c); return 0; } return bytesRead; } int ft4222_i2c_write_internal(Ftdi_4222_Shim& shim, uint8_t addr, uint8_t* data, int bytesToWrite) { uint16 bytesWritten = 0; uint8 controllerStatus; /* If a write fails, check the I2C controller status, reset the controller, * return 0? */ if (FT4222_I2CMaster_Write(shim.h_i2c, addr, data, bytesToWrite, &bytesWritten) != FT4222_OK) { FT4222_I2CMaster_GetStatus(shim.h_i2c, &controllerStatus); syslog(LOG_ERR, "FT4222_I2CMaster_Write failed address %#02x. Code %d", addr, controllerStatus); FT4222_I2CMaster_Reset(shim.h_i2c); bytesWritten = 0; } if (bytesWritten != bytesToWrite) syslog(LOG_ERR, "FT4222_I2CMaster_Write wrote %u of %u bytes.", bytesWritten, bytesToWrite); return bytesWritten; } mraa_result_t ft4222_i2c_select_bus(int bus) { Ftdi_4222_Shim* shim = ShimFromI2cBus(bus); if (!shim) return MRAA_ERROR_NO_RESOURCES; if (bus > 0 && bus != shim->cur_i2c_bus) { syslog(LOG_NOTICE, "ft4222_i2c_select_bus switching to bus %d", bus); uint8_t data; if (bus == 0) data = 0; else data = 1 << (bus - 1); if (ft4222_i2c_write_internal(*shim, PCA9545_ADDR, &data, 1) == 1) shim->cur_i2c_bus = bus; else return MRAA_ERROR_UNSPECIFIED; } return MRAA_SUCCESS; } int ft4222_i2c_context_read(mraa_i2c_context dev, uint8_t* data, int length) { Ftdi_4222_Shim* shim = ShimFromI2cBus(dev->busnum); if (!shim) return -1; int bytes_read = 0; if (ft4222_i2c_select_bus(dev->busnum) == MRAA_SUCCESS) bytes_read = ft4222_i2c_read_internal(*shim, dev->addr, data, length); return bytes_read; } int ft4222_i2c_context_write(mraa_i2c_context dev, uint8_t* data, int length) { Ftdi_4222_Shim* shim = ShimFromI2cBus(dev->busnum); if (!shim) return -1; int bytes_written = 0; if (ft4222_i2c_select_bus(dev->busnum) == MRAA_SUCCESS) bytes_written = ft4222_i2c_write_internal(*shim, dev->addr, data, length); return bytes_written; } int Ftdi_4222_Shim::_detect_io_expander() { uint8_t data = 0; if (ft4222_i2c_read_internal(*this, PCA9672_ADDR, &data, 1) == 1) { syslog(LOG_ERR, "Detected I/O expander: PCA9672 with %d I/O pins", PCA9672_PINS); exp_type = IO_EXP_PCA9672; return PCA9672_PINS; } else { uint8_t reg = PCA9555_INPUT_REG; ft4222_i2c_write_internal(*this, PCA9555_ADDR, &reg, 1); if (ft4222_i2c_read_internal(*this, PCA9555_ADDR, &data, 1) == 1) { syslog(LOG_ERR, "Detected I/O expander: PCA9555 with %d I/O pins", PCA9555_PINS); exp_type = IO_EXP_PCA9555; reg = PCA9555_OUTPUT_REG; ft4222_i2c_write_internal(*this, PCA9555_ADDR, &reg, 1); ft4222_i2c_read_internal(*this, PCA9555_ADDR, &pca9555OutputValue.bytes[0], 2); reg = PCA9555_DIRECTION_REG; ft4222_i2c_write_internal(*this, PCA9555_ADDR, &reg, 1); ft4222_i2c_read_internal(*this, PCA9555_ADDR, &pca9555DirectionValue.bytes[0], 2); return PCA9555_PINS; } } exp_type = IO_EXP_NONE; return 0; } ft4222_gpio_type ft4222_get_gpio_type(int pin) { Ftdi_4222_Shim* shim = ShimFromGpioPin(pin); if (!shim) return GPIO_TYPE_UNKNOWN; if (pin < gpioPinsPerFt4222) { return GPIO_TYPE_BUILTIN; } else switch (shim->exp_type) { case IO_EXP_PCA9672: return GPIO_TYPE_PCA9672; case GPIO_TYPE_PCA9555: return GPIO_TYPE_PCA9555; default: return GPIO_TYPE_UNKNOWN; } } mraa_result_t ftdi_ft4222_set_internal_gpio_dir(Ftdi_4222_Shim& shim, int physical_pin, GPIO_Dir direction) { /* Update the direction for this pin */ shim.pinDirection[physical_pin] = direction; if (!shim.init_ftdi_gpios()) return MRAA_ERROR_UNSPECIFIED; return MRAA_SUCCESS; } mraa_result_t ft4222_gpio_set_pca9672_dir(mraa_gpio_context dev, mraa_gpio_dir_t dir) { Ftdi_4222_Shim* shim = ShimFromGpioPin(dev->phy_pin); if (!shim) return MRAA_ERROR_UNSPECIFIED; uint8_t mask = 1 << dev->phy_pin; switch (dir) { case MRAA_GPIO_IN: { shim->pca9672DirectionMask |= mask; int bytes_written = ft4222_i2c_write_internal(*shim, PCA9672_ADDR, &shim->pca9672DirectionMask, 1); return bytes_written == 1 ? MRAA_SUCCESS : MRAA_ERROR_UNSPECIFIED; } case MRAA_GPIO_OUT: { shim->pca9672DirectionMask &= (~mask); return MRAA_SUCCESS; } default: return MRAA_ERROR_UNSPECIFIED; } } mraa_result_t ft4222_gpio_set_pca9555_dir(mraa_gpio_context dev, mraa_gpio_dir_t dir) { Ftdi_4222_Shim* shim = ShimFromGpioPin(dev->phy_pin); if (!shim) return MRAA_ERROR_UNSPECIFIED; uint16_t mask = 1 << (dev->phy_pin - gpioPinsPerFt4222); switch (dir) { case MRAA_GPIO_IN: shim->pca9555DirectionValue.word |= mask; break; case MRAA_GPIO_OUT: shim->pca9555DirectionValue.word &= (~mask); break; default: { syslog(LOG_ERR, "Invalid gpio direction: 0x%08x", dir); return MRAA_ERROR_UNSPECIFIED; } } uint8_t buf[3] = { PCA9555_DIRECTION_REG, shim->pca9555DirectionValue.bytes[0], shim->pca9555DirectionValue.bytes[1] }; int bytes_written = ft4222_i2c_write_internal(*shim, PCA9555_ADDR, &buf[0], sizeof(buf)); return bytes_written == sizeof(buf) ? MRAA_SUCCESS : MRAA_ERROR_UNSPECIFIED; } mraa_result_t ftdi_ft4222_set_internal_gpio_trigger(int pin, GPIO_Trigger trigger) { Ftdi_4222_Shim* shim = ShimFromGpioPin(pin); if (!shim) return MRAA_ERROR_NO_RESOURCES; FT4222_STATUS ft4222Status = FT4222_GPIO_SetInputTrigger(shim->h_gpio, static_cast<GPIO_Port>(pin), trigger); if (ft4222Status == FT4222_OK) return MRAA_SUCCESS; else { syslog(LOG_ERR, "FT4222_GPIO_SetInputTrigger failed with FT4222_STATUS: 0x%04x", ft4222Status); return MRAA_ERROR_UNSPECIFIED; } } // Function detects known I2C switches and returns the number of busses. // On startup switch is disabled so default bus will be integrated i2c bus. int Ftdi_4222_Shim::ft4222_detect_i2c_switch() { uint8_t data = 0; if (ft4222_i2c_read_internal(*this, PCA9545_ADDR, &data, 1) == 1) { data = 0; return ft4222_i2c_write_internal(*this, PCA9545_ADDR, &data, 1) == 1 ? PCA9545_BUSSES : 0; } return 0; } /******************* I2C functions *******************/ mraa_result_t i2c_init_bus_replace(mraa_i2c_context dev) { Ftdi_4222_Shim* shim = ShimFromI2cBus(dev->busnum); if (!shim) return MRAA_ERROR_NO_RESOURCES; lock_guard lock(shim->mtx_ft4222); // Tell the FT4222 to be an I2C Master. FT4222_STATUS ft4222Status = FT4222_I2CMaster_Init(shim->h_i2c, shim->ft4222_i2c_speed()); if (FT4222_OK != ft4222Status) { syslog(LOG_ERR, "FT4222_I2CMaster_Init failed (error %d)!", ft4222Status); return MRAA_ERROR_NO_RESOURCES; } // Reset the I2CM registers to a known state. ft4222Status = FT4222_I2CMaster_Reset(shim->h_i2c); if (FT4222_OK != ft4222Status) { syslog(LOG_ERR, "FT4222_I2CMaster_Reset failed (error %d)!", ft4222Status); return MRAA_ERROR_NO_RESOURCES; } syslog(LOG_NOTICE, "I2C interface enabled GPIO0 and GPIO1 will be unavailable."); dev->handle = shim->h_i2c; // Don't use file descriptors dev->fh = -1; // Advertise minimal i2c support as per // https://www.kernel.org/doc/Documentation/i2c/functionality dev->funcs = I2C_FUNC_I2C; return MRAA_SUCCESS; } mraa_result_t i2c_set_frequency_replace(mraa_i2c_context dev, mraa_i2c_mode_t mode) { Ftdi_4222_Shim* shim = ShimFromI2cBus(dev->busnum); if (!shim) return MRAA_ERROR_NO_RESOURCES; lock_guard lock(shim->mtx_ft4222); /* Save off this speed */ shim->mraa_i2c_mode = mode; return FT4222_I2CMaster_Init(shim->h_i2c, shim->ft4222_i2c_speed()) == FT4222_OK ? MRAA_SUCCESS : MRAA_ERROR_UNSPECIFIED; } mraa_result_t i2c_address_replace(mraa_i2c_context dev, uint8_t addr) { dev->addr = (int) addr; return MRAA_SUCCESS; } int i2c_read_replace(mraa_i2c_context dev, uint8_t* data, int length) { Ftdi_4222_Shim* shim = ShimFromI2cBus(dev->busnum); if (!shim) return -1; lock_guard lock(shim->mtx_ft4222); int bytes_read = ft4222_i2c_read_internal(*shim, dev->addr, data, length); return bytes_read; } int i2c_read_byte_replace(mraa_i2c_context dev) { Ftdi_4222_Shim* shim = ShimFromI2cBus(dev->busnum); if (!shim) return -1; lock_guard lock(shim->mtx_ft4222); uint8_t data = 0; int bytes_read = ft4222_i2c_context_read(dev, &data, 1); return bytes_read == 1 ? data : -1; } int i2c_read_byte_data_replace(mraa_i2c_context dev, uint8_t command) { Ftdi_4222_Shim* shim = ShimFromI2cBus(dev->busnum); if (!shim) return -1; lock_guard lock(shim->mtx_ft4222); uint8_t data; int bytes_read = 0; uint16 bytesWritten = ft4222_i2c_context_write(dev, &command, 1); if (bytesWritten == 1) bytes_read = ft4222_i2c_context_read(dev, &data, 1); if (bytes_read == 1) { return (int) data; } return -1; } int i2c_read_word_data_replace(mraa_i2c_context dev, uint8_t command) { Ftdi_4222_Shim* shim = ShimFromI2cBus(dev->busnum); if (!shim) return -1; lock_guard lock(shim->mtx_ft4222); union { uint8_t bytes[2]; uint16_t word; } buf = {}; int bytes_read = 0; int bytes_written = ft4222_i2c_context_write(dev, &command, 1); if (bytes_written == 1) bytes_read = ft4222_i2c_context_read(dev, &buf.bytes[0], 2); if (bytes_read == 2) return (int) buf.word; return -1; } int i2c_read_bytes_data_replace(mraa_i2c_context dev, uint8_t command, uint8_t* data, int length) { Ftdi_4222_Shim* shim = ShimFromI2cBus(dev->busnum); if (!shim) return -1; lock_guard lock(shim->mtx_ft4222); int bytes_read = 0; int bytes_written = ft4222_i2c_context_write(dev, &command, 1); if (bytes_written == 1) bytes_read = ft4222_i2c_context_read(dev, data, length); return bytes_read; } mraa_result_t i2c_write_replace(mraa_i2c_context dev, const uint8_t* data, int bytesToWrite) { Ftdi_4222_Shim* shim = ShimFromI2cBus(dev->busnum); if (!shim) return MRAA_ERROR_NO_RESOURCES; lock_guard lock(shim->mtx_ft4222); uint16 bytesWritten = ft4222_i2c_context_write(dev, (uint8_t*) data, bytesToWrite); return bytesToWrite == bytesWritten ? MRAA_SUCCESS : MRAA_ERROR_INVALID_HANDLE; } /* No mutex needed */ mraa_result_t i2c_write_byte_replace(mraa_i2c_context dev, uint8_t data) { mraa_result_t status = i2c_write_replace(dev, &data, 1); return status; } /* No mutex needed */ mraa_result_t i2c_write_byte_data_replace(mraa_i2c_context dev, const uint8_t data, const uint8_t command) { uint8_t buf[2] = { command, data }; mraa_result_t status = i2c_write_replace(dev, &buf[0], 2); return status; } /* No mutex needed */ mraa_result_t i2c_write_word_data_replace(mraa_i2c_context dev, const uint16_t data, const uint8_t command) { uint8_t buf[3] = { command, (uint8_t) data, (uint8_t)(data >> 8) }; mraa_result_t status = i2c_write_replace(dev, &buf[0], 3); return status; } mraa_result_t i2c_stop_replace(mraa_i2c_context /*dev*/) { return MRAA_SUCCESS; } // /******************* GPIO functions *******************/ // mraa_result_t gpio_init_internal_replace(mraa_gpio_context dev, int pin) { Ftdi_4222_Shim* shim = ShimFromGpioPin(dev->phy_pin); if (!shim) return MRAA_ERROR_NO_RESOURCES; lock_guard lock(shim->mtx_ft4222); /* Keep the subplatform index as pin. Example: 516 */ /* And the phy_pin as the local index to pin. Example: 516 - 512 = 4 */ dev->pin = pin; dev->phy_pin = pin & (~MRAA_SUB_PLATFORM_MASK); if (pin < 2) { syslog(LOG_NOTICE, "Closing I2C interface to enable GPIO%d", pin); /* Replace with call to SPI init when SPI is fully implemented */ FT4222_STATUS ft4222Status = FT4222_SPIMaster_Init(shim->h_gpio, SPI_IO_SINGLE, CLK_DIV_4, CLK_IDLE_HIGH, CLK_LEADING, 0x01); if (FT4222_OK != ft4222Status) { syslog(LOG_ERR, "Failed to close I2C interface and start SPI (error %d)!", ft4222Status); return MRAA_ERROR_NO_RESOURCES; } } return MRAA_SUCCESS; } mraa_result_t gpio_mode_replace(mraa_gpio_context /*dev*/, mraa_gpio_mode_t /*mode*/) { return MRAA_ERROR_FEATURE_NOT_IMPLEMENTED; } mraa_result_t gpio_edge_mode_replace(mraa_gpio_context dev, mraa_gpio_edge_t mode) { Ftdi_4222_Shim* shim = ShimFromGpioPin(dev->phy_pin); if (!shim) return MRAA_ERROR_NO_RESOURCES; lock_guard lock(shim->mtx_ft4222); mraa_result_t result = MRAA_SUCCESS; switch (ft4222_get_gpio_type(dev->phy_pin)) { case GPIO_TYPE_BUILTIN: switch (mode) { case MRAA_GPIO_EDGE_NONE: case MRAA_GPIO_EDGE_BOTH: result = ftdi_ft4222_set_internal_gpio_trigger( dev->phy_pin, static_cast<GPIO_Trigger>(GPIO_TRIGGER_RISING | GPIO_TRIGGER_FALLING)); break; case MRAA_GPIO_EDGE_RISING: result = ftdi_ft4222_set_internal_gpio_trigger(dev->phy_pin, GPIO_TRIGGER_RISING); break; case MRAA_GPIO_EDGE_FALLING: result = ftdi_ft4222_set_internal_gpio_trigger(dev->phy_pin, GPIO_TRIGGER_FALLING); break; default: result = MRAA_ERROR_FEATURE_NOT_IMPLEMENTED; break; } break; case GPIO_TYPE_PCA9672: case GPIO_TYPE_PCA9555: break; default: result = MRAA_ERROR_INVALID_RESOURCE; break; } return result; } mraa_result_t ft4222_i2c_read_io_expander(Ftdi_4222_Shim& shim, uint16_t* value) { int bytes_read = 0; uint8_t reg = PCA9555_INPUT_REG; switch (shim.exp_type) { case IO_EXP_PCA9672: bytes_read = ft4222_i2c_read_internal(shim, PCA9672_ADDR, (uint8_t*) value, 1); break; case GPIO_TYPE_PCA9555: if (ft4222_i2c_write_internal(shim, PCA9555_ADDR, &reg, 1) == 1) bytes_read = ft4222_i2c_read_internal(shim, PCA9555_ADDR, (uint8_t*) value, 2); break; default:; } return bytes_read > 0 ? MRAA_SUCCESS : MRAA_ERROR_UNSPECIFIED; } int gpio_read_replace(mraa_gpio_context dev) { Ftdi_4222_Shim* shim = ShimFromGpioPin(dev->phy_pin); if (!shim) return -1; lock_guard lock(shim->mtx_ft4222); switch (ft4222_get_gpio_type(dev->phy_pin)) { case GPIO_TYPE_BUILTIN: { BOOL value; FT4222_STATUS ft4222Status = FT4222_GPIO_Read(shim->h_gpio, static_cast<GPIO_Port>(dev->phy_pin), &value); if (FT4222_OK != ft4222Status) { syslog(LOG_ERR, "FT4222_GPIO_Read failed (error %d)!", ft4222Status); return -1; } return value; } case GPIO_TYPE_PCA9672: case GPIO_TYPE_PCA9555: { uint16_t mask = 1 << (dev->phy_pin - gpioPinsPerFt4222); uint16_t value; mraa_result_t res = ft4222_i2c_read_io_expander(*shim, &value); return res == MRAA_SUCCESS ? (value & mask) == mask : -1; } default: return -1; } } mraa_result_t gpio_write_replace_wrapper(mraa_gpio_context dev, int write_value, bool require_atomic = true) { Ftdi_4222_Shim* shim = ShimFromGpioPin(dev->phy_pin); if (!shim) return MRAA_ERROR_NO_RESOURCES; if (require_atomic) pthread_mutex_lock(&shim->mtx_ft4222); mraa_result_t result = MRAA_SUCCESS; switch (ft4222_get_gpio_type(dev->phy_pin)) { case GPIO_TYPE_BUILTIN: { FT4222_STATUS ft4222Status = FT4222_GPIO_Write(shim->h_gpio, static_cast<GPIO_Port>(dev->phy_pin), write_value); if (FT4222_OK != ft4222Status) { syslog(LOG_ERR, "FT4222_GPIO_Write to pin %i failed (error %d)!", dev->phy_pin, ft4222Status); result = MRAA_ERROR_UNSPECIFIED; } } break; case GPIO_TYPE_PCA9672: { uint8_t mask = 1 << dev->phy_pin; uint8_t value; int bytes_written = 0; int bytes_read = ft4222_i2c_read_internal(*shim, PCA9672_ADDR, &value, 1); if (bytes_read == 1) { if (write_value == 1) value = value | mask | shim->pca9672DirectionMask; else value &= (~mask); bytes_written = ft4222_i2c_write_internal(*shim, PCA9672_ADDR, &value, 1); } result = bytes_written == 1 ? MRAA_SUCCESS : MRAA_ERROR_UNSPECIFIED; } break; case GPIO_TYPE_PCA9555: { uint16_t mask = 1 << (dev->phy_pin - gpioPinsPerFt4222); if (write_value) shim->pca9555OutputValue.word |= mask; else shim->pca9555OutputValue.word &= (~mask); uint8_t buf[3] = { PCA9555_OUTPUT_REG, shim->pca9555OutputValue.bytes[0], shim->pca9555OutputValue.bytes[1] }; int bytes_written = ft4222_i2c_write_internal(*shim, PCA9555_ADDR, &buf[0], sizeof(buf)); result = bytes_written == sizeof(buf) ? MRAA_SUCCESS : MRAA_ERROR_UNSPECIFIED; } break; default: result = MRAA_ERROR_INVALID_RESOURCE; break; } if (require_atomic) pthread_mutex_unlock(&shim->mtx_ft4222); return result; } mraa_result_t gpio_write_replace(mraa_gpio_context dev, int write_value) { Ftdi_4222_Shim* shim = ShimFromGpioPin(dev->phy_pin); if (!shim) return MRAA_ERROR_NO_RESOURCES; lock_guard lock(shim->mtx_ft4222); /* Default to an atomic gpio_write_replace call */ return gpio_write_replace_wrapper(dev, write_value); } mraa_result_t gpio_dir_replace(mraa_gpio_context dev, mraa_gpio_dir_t dir) { Ftdi_4222_Shim* shim = ShimFromGpioPin(dev->phy_pin); if (!shim) return MRAA_ERROR_NO_RESOURCES; lock_guard lock(shim->mtx_ft4222); switch (ft4222_get_gpio_type(dev->phy_pin)) { case GPIO_TYPE_BUILTIN: switch (dir) { case MRAA_GPIO_IN: return ftdi_ft4222_set_internal_gpio_dir(*shim, dev->phy_pin, GPIO_INPUT); case MRAA_GPIO_OUT: return ftdi_ft4222_set_internal_gpio_dir(*shim, dev->phy_pin, GPIO_OUTPUT); case MRAA_GPIO_OUT_HIGH: if (ftdi_ft4222_set_internal_gpio_dir(*shim, dev->phy_pin, GPIO_OUTPUT) != MRAA_SUCCESS) return MRAA_ERROR_UNSPECIFIED; return gpio_write_replace_wrapper(dev, 1, false); case MRAA_GPIO_OUT_LOW: if (ftdi_ft4222_set_internal_gpio_dir(*shim, dev->phy_pin, GPIO_OUTPUT) != MRAA_SUCCESS) return MRAA_ERROR_UNSPECIFIED; return gpio_write_replace_wrapper(dev, 0, false); default: return MRAA_ERROR_INVALID_PARAMETER; } case GPIO_TYPE_PCA9672: switch (dir) { case MRAA_GPIO_IN: case MRAA_GPIO_OUT: return ft4222_gpio_set_pca9672_dir(dev, dir); case MRAA_GPIO_OUT_HIGH: if (ft4222_gpio_set_pca9672_dir(dev, dir) != MRAA_SUCCESS) return MRAA_ERROR_UNSPECIFIED; return gpio_write_replace_wrapper(dev, 1, false); case MRAA_GPIO_OUT_LOW: if (ft4222_gpio_set_pca9672_dir(dev, dir) != MRAA_SUCCESS) return MRAA_ERROR_UNSPECIFIED; return gpio_write_replace_wrapper(dev, 0, false); default: return MRAA_ERROR_INVALID_PARAMETER; } case GPIO_TYPE_PCA9555: switch (dir) { case MRAA_GPIO_IN: case MRAA_GPIO_OUT: return ft4222_gpio_set_pca9555_dir(dev, dir); case MRAA_GPIO_OUT_HIGH: if (ft4222_gpio_set_pca9555_dir(dev, dir) != MRAA_SUCCESS) return MRAA_ERROR_UNSPECIFIED; return gpio_write_replace_wrapper(dev, 1, false); case MRAA_GPIO_OUT_LOW: if (ft4222_gpio_set_pca9555_dir(dev, dir) != MRAA_SUCCESS) return MRAA_ERROR_UNSPECIFIED; return gpio_write_replace_wrapper(dev, 0, false); default: return MRAA_ERROR_INVALID_PARAMETER; } default: return MRAA_ERROR_INVALID_RESOURCE; } } mraa_boolean_t ft4222_has_internal_gpio_triggered(Ftdi_4222_Shim& shim, int physical_pin) { uint16 num_events = 0; FT4222_GPIO_GetTriggerStatus(shim.h_gpio, static_cast<GPIO_Port>(physical_pin), &num_events); if (num_events > 0) { int i; uint16 num_events_read; GPIO_Trigger event; for (i = 0; i < num_events; ++i) { FT4222_GPIO_ReadTriggerQueue(shim.h_gpio, static_cast<GPIO_Port>(physical_pin), &event, 1, &num_events_read); } return TRUE; } else return FALSE; } // INT pin of i2c PCA9672 GPIO expander is connected to FT4222 GPIO #3 // We use INT to detect any expander GPIO level change void* ft4222_gpio_monitor(void* arg) { Ftdi_4222_Shim* shim = static_cast<Ftdi_4222_Shim*>(arg); uint16_t prev_value = 0; ft4222_i2c_read_io_expander(*shim, &prev_value); while (!shim->gpio_mon.should_stop) { { lock_guard lock(shim->mtx_ft4222); if (ft4222_has_internal_gpio_triggered(*shim, GPIO_PORT_IO_INT)) { uint16_t value; if (ft4222_i2c_read_io_expander(*shim, &value) == MRAA_SUCCESS) { uint16_t change_value = prev_value ^ value; int i; for (i = 0; i < MAX_IO_EXPANDER_PINS; ++i) { uint16_t mask = 1 << i; shim->gpio_mon.is_interrupt_detected[i] = (change_value & mask); } prev_value = value; } } } ft4222_sleep_ms(10); } return NULL; } void ft4222_gpio_monitor_add_pin(Ftdi_4222_Shim& shim) { if (shim.gpio_mon.num_active_pins == 0) { pthread_mutexattr_t attr_rec; pthread_mutexattr_init(&attr_rec); pthread_mutexattr_settype(&attr_rec, PTHREAD_MUTEX_RECURSIVE); if (pthread_mutex_init(&shim.gpio_mon.mutex, &attr_rec) != 0) { syslog(LOG_ERR, "Failed to setup GPIO monitor mutex for FT4222 access"); throw std::runtime_error("Failed to setup GPIO monitor mutex for FT4222 access"); } pthread_create(&shim.gpio_mon.thread, NULL, ft4222_gpio_monitor, &shim); } shim.gpio_mon.num_active_pins++; } void ft4222_gpio_monitor_remove_pin(Ftdi_4222_Shim& shim) { shim.gpio_mon.num_active_pins--; if (shim.gpio_mon.num_active_pins == 0) { shim.gpio_mon.should_stop = TRUE; pthread_join(shim.gpio_mon.thread, NULL); pthread_mutex_destroy(&shim.gpio_mon.mutex); } } mraa_boolean_t ft4222_gpio_monitor_is_interrupt_detected(Ftdi_4222_Shim& shim, int pin) { mraa_boolean_t is_interrupt_detected = FALSE; if (shim.gpio_mon.is_interrupt_detected[pin]) { shim.gpio_mon.is_interrupt_detected[pin] = FALSE; is_interrupt_detected = TRUE; } return is_interrupt_detected; } mraa_result_t gpio_interrupt_handler_init_replace(mraa_gpio_context dev) { while (dev->isr_thread_terminating) { ft4222_sleep_ms(10); } Ftdi_4222_Shim* shim = ShimFromGpioPin(dev->phy_pin); if (!shim) return MRAA_ERROR_NO_RESOURCES; lock_guard lock(shim->mtx_ft4222); std::string extra; switch (ft4222_get_gpio_type(dev->phy_pin)) { case GPIO_TYPE_BUILTIN: /* Make sure this pin is an input */ // ftdi_ft4222_set_internal_gpio_dir(*shim, dev->phy_pin, GPIO_INPUT); extra += "(FT4222 GPIO pin)"; break; case GPIO_TYPE_PCA9672: case GPIO_TYPE_PCA9555: /* Make sure pin is an input */ ftdi_ft4222_set_internal_gpio_dir(*shim, GPIO_PORT_IO_INT, GPIO_INPUT); ftdi_ft4222_set_internal_gpio_trigger(GPIO_PORT_IO_INT, GPIO_TRIGGER_FALLING); ft4222_gpio_monitor_add_pin(*shim); extra += "(FT4222 expander GPIO pin)"; break; default: return MRAA_ERROR_INVALID_RESOURCE; } syslog(LOG_NOTICE, "ISR added for pin: %d physical_pin: %d %s", dev->pin, dev->phy_pin, extra.c_str()); return MRAA_SUCCESS; } /* This method is running in a cancelable thread which can go away at any time, * likewise, the isr_thread_terminating check might never happen and the GPIO * monitor can have problems - not sure of the best fix for this... most likely * the best fix would be to NOT support the I/O expanders. */ mraa_result_t gpio_wait_interrupt_replace(mraa_gpio_context dev) { Ftdi_4222_Shim* shim = ShimFromGpioPin(dev->phy_pin); if (!shim) return MRAA_ERROR_NO_RESOURCES; mraa_boolean_t interrupt_detected = FALSE; ft4222_gpio_type gpio_type = GPIO_TYPE_BUILTIN; { lock_guard lock(shim->mtx_ft4222); gpio_type = ft4222_get_gpio_type(dev->phy_pin); } while (!dev->isr_thread_terminating && !interrupt_detected) { switch (gpio_type) { case GPIO_TYPE_BUILTIN: { lock_guard lock(shim->mtx_ft4222); interrupt_detected = ft4222_has_internal_gpio_triggered(*shim, dev->phy_pin); } break; case GPIO_TYPE_PCA9672: case GPIO_TYPE_PCA9555: { lock_guard lock(shim->mtx_ft4222); /* Expander pin indexing starts past the FT4222 GPIO pins */ interrupt_detected = ft4222_gpio_monitor_is_interrupt_detected(*shim, dev->phy_pin - gpioPinsPerFt4222); } break; default:; } ft4222_sleep_ms(10); } if (dev->isr_thread_terminating) { lock_guard lock(shim->mtx_ft4222); ft4222_gpio_monitor_remove_pin(*shim); } return MRAA_SUCCESS; } void ft4222_populate_i2c_func_table(mraa_adv_func_t* func_table) { func_table->i2c_init_bus_replace = &i2c_init_bus_replace; func_table->i2c_set_frequency_replace = &i2c_set_frequency_replace; func_table->i2c_address_replace = &i2c_address_replace; func_table->i2c_read_replace = &i2c_read_replace; func_table->i2c_read_byte_replace = &i2c_read_byte_replace; func_table->i2c_read_byte_data_replace = &i2c_read_byte_data_replace; func_table->i2c_read_word_data_replace = &i2c_read_word_data_replace; func_table->i2c_read_bytes_data_replace = &i2c_read_bytes_data_replace; func_table->i2c_write_replace = &i2c_write_replace; // Used in 3 places func_table->i2c_write_byte_replace = &i2c_write_byte_replace; // No mutex needed func_table->i2c_write_byte_data_replace = &i2c_write_byte_data_replace; func_table->i2c_write_word_data_replace = &i2c_write_word_data_replace; func_table->i2c_stop_replace = &i2c_stop_replace; } void ft4222_populate_gpio_func_table(mraa_adv_func_t* func_table) { func_table->gpio_init_internal_replace = &gpio_init_internal_replace; func_table->gpio_mode_replace = &gpio_mode_replace; func_table->gpio_edge_mode_replace = &gpio_edge_mode_replace; func_table->gpio_dir_replace = &gpio_dir_replace; func_table->gpio_read_replace = &gpio_read_replace; func_table->gpio_write_replace = &gpio_write_replace; // 6 func_table->gpio_interrupt_handler_init_replace = &gpio_interrupt_handler_init_replace; func_table->gpio_wait_interrupt_replace = &gpio_wait_interrupt_replace; } /* Store mraa_board_t subplatform allocated by this library */ char ftdi_4222_platform_name[] = "FTDI FT4222"; bool Ftdi_4222_Shim::setup_io() { int numI2cGpioExpanderPins = _detect_io_expander(); int numUsbGpio = gpioPinsPerFt4222 + numI2cGpioExpanderPins; int numI2cBusses = 1 + ft4222_detect_i2c_switch(); int numUsbPins = numUsbGpio + 2 * (numI2cBusses - 1); // Add SDA and SCL for each i2c switch bus mraa_pincapabilities_t pinCapsI2c = (mraa_pincapabilities_t){ 1, 0, 0, 0, 0, 1, 0, 0 }; mraa_pincapabilities_t pinCapsI2cGpio = (mraa_pincapabilities_t){ 1, 1, 0, 0, 0, 1, 0, 0 }; mraa_pincapabilities_t pinCapsGpio = (mraa_pincapabilities_t){ 1, 1, 0, 0, 0, 0, 0, 0 }; _board.platform_name = &ftdi_4222_platform_name[0]; _board.platform_type = MRAA_FTDI_FT4222; _board.phy_pin_count = numUsbPins; _board.gpio_count = numUsbGpio; int bus = 0; _board.i2c_bus_count = numI2cBusses; _board.def_i2c_bus = bus; _board.i2c_bus[bus].bus_id = bus; /* Save off an I2C bus-to-shim value */ _i2c_bus_to_shim[bus] = this; // I2c pins (these are virtual, entries are required to configure i2c layer) // We currently assume that GPIO 0/1 are reserved for i2c operation _pins.push_back(mraa_pininfo_t()); strncpy(&_pins.back().name[0], "IGPIO0/SCL0", MRAA_PIN_NAME_SIZE); _pins.back().capabilities = pinCapsI2cGpio; _pins.back().gpio.pinmap = 512 + _pins.size() - 1; _pins.back().gpio.mux_total = 0; _pins.back().i2c.mux_total = 0; _board.i2c_bus[bus].scl = _pins.size() - 1; /* Save off a GPIO ndx-to-shim value */ _gpio_pin_to_shim[_pins.size() - 1] = this; _pins.push_back(mraa_pininfo_t()); strncpy(&_pins.back().name[0], "IGPIO1/SDA0", MRAA_PIN_NAME_SIZE); _pins.back().capabilities = pinCapsI2cGpio; _pins.back().gpio.pinmap = 512 + _pins.size() - 1; _pins.back().gpio.mux_total = 0; _pins.back().i2c.mux_total = 0; _board.i2c_bus[bus].sda = _pins.size() - 1; /* Save off a GPIO ndx-to-shim value */ _gpio_pin_to_shim[_pins.size() - 1] = this; // FTDI4222 gpio _pins.push_back(mraa_pininfo_t()); strncpy(&_pins.back().name[0], "INT-GPIO2", MRAA_PIN_NAME_SIZE); _pins.back().capabilities = pinCapsGpio; _pins.back().gpio.pinmap = 512 + _pins.size() - 1; _pins.back().gpio.mux_total = 0; /* Save off a GPIO ndx-to-shim value */ _gpio_pin_to_shim[_pins.size() - 1] = this; _pins.push_back(mraa_pininfo_t()); strncpy(&_pins.back().name[0], "INT-GPIO3", MRAA_PIN_NAME_SIZE); _pins.back().capabilities = pinCapsGpio; _pins.back().gpio.pinmap = 512 + _pins.size() - 1; _pins.back().gpio.mux_total = 0; /* Save off a GPIO ndx-to-shim value */ _gpio_pin_to_shim[_pins.size() - 1] = this; // Virtual gpio pins on i2c I/O expander. for (int i = 0; i < numI2cGpioExpanderPins; ++i) { _pins.push_back(mraa_pininfo_t()); snprintf(&_pins.back().name[0], MRAA_PIN_NAME_SIZE, "EXP-GPIO%d", i); _pins.back().capabilities = pinCapsGpio; _pins.back().gpio.pinmap = 512 + _pins.size() - 1; _pins.back().gpio.mux_total = 0; /* Save off a GPIO ndx-to-shim value */ _gpio_pin_to_shim[_pins.size() - 1] = this; } // Now add any extra i2c buses behind i2c switch for (bus = 1; bus < numI2cBusses; ++bus) { _board.i2c_bus[bus].bus_id = bus; _pins.back().i2c.mux_total = 0; snprintf(&_pins.back().name[0], MRAA_PIN_NAME_SIZE, "SDA%d", bus); _pins.back().capabilities = pinCapsI2c; _board.i2c_bus[bus].sda = _pins.size() - 1; _pins.push_back(mraa_pininfo_t()); snprintf(&_pins.back().name[0], MRAA_PIN_NAME_SIZE, "SCL%d", bus); _pins.back().capabilities = pinCapsI2c; _pins.back().i2c.mux_total = 0; _board.i2c_bus[bus].scl = _pins.size() - 1; _pins.push_back(mraa_pininfo_t()); } /* The board pins points to the shim pins vector */ _board.pins = &_pins[0]; _board.adv_func = &_adv_func_table; ft4222_populate_i2c_func_table(_board.adv_func); ft4222_populate_gpio_func_table(_board.adv_func); /* Success, return the sub platform */ return true; } bool Ftdi_4222_Shim::init_ftdi_gpios() { /* Setting the direction requires a re-init, which means the * previous resources should also be un-initialized first */ if (h_gpio) FT4222_UnInitialize(h_gpio); /* Use GPIO2 as GPIO (not suspend output) */ return (FT4222_SetSuspendOut(h_gpio, 0) == FT4222_OK) && /* Use GPIO3 as GPIO (not interrupt for I/O expander) */ (FT4222_SetWakeUpInterrupt(h_gpio, 0) == FT4222_OK) && (FT4222_GPIO_Init(h_gpio, &pinDirection[0]) == FT4222_OK); } } /* namespace ft4222 */ /* One C method exposed for loading a platform */ mraa_result_t mraa_usb_platform_extender(mraa_board_t* board) { /* If no board provided return unknown */ if (board == NULL) return MRAA_ERROR_PLATFORM_NOT_INITIALISED; /* Attempt to initialize an FT4222 shim and assign it as a sub-platform */ board->sub_platform = ft4222::Ftdi_4222_Shim::init_and_setup_mraa_board(); /* No sub-platform returned, drop out */ if (board->sub_platform == NULL) return MRAA_ERROR_PLATFORM_NOT_INITIALISED; syslog(LOG_NOTICE, "Added subplatform of type: %s", board->sub_platform->platform_name); return MRAA_SUCCESS; }
33.287879
125
0.650805
nazeer22
3a37d7f6f9925392d8e5b90d31018ca11d1e5f1f
8,114
cpp
C++
tests/tests.cpp
mfdeakin/nd_array
0315b77cbda7dc85e47fed79dfc4daead2ff6768
[ "MIT" ]
null
null
null
tests/tests.cpp
mfdeakin/nd_array
0315b77cbda7dc85e47fed79dfc4daead2ff6768
[ "MIT" ]
null
null
null
tests/tests.cpp
mfdeakin/nd_array
0315b77cbda7dc85e47fed79dfc4daead2ff6768
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "nd_array/nd_array.hpp" TEST_CASE("get, set, slice, reshape", "[ND_Array]") { ND_Array<int, 2, 3, 5> arr; int count = 1; for(decltype(arr)::size_type i = 0; i < arr.extent(0); ++i) { for(decltype(arr)::size_type j = 0; j < arr.extent(1); ++j) { for(decltype(arr)::size_type k = 0; k < arr.extent(2); ++k) { arr(i, j, k) = count; count++; } } } count = 1; for(decltype(arr)::size_type i = 0; i < 2; ++i) { for(decltype(arr)::size_type j = 0; j < 3; ++j) { for(decltype(arr)::size_type k = 0; k < 5; ++k) { REQUIRE(arr(i, j, k) == count); count++; } } } ND_Array<int, 3, 5> &slice1 = arr.outer_slice(0); using Slice1T = std::remove_reference<decltype(slice1)>::type; count = 1; for(Slice1T::size_type j = 0; j < 3; ++j) { for(Slice1T::size_type k = 0; k < 5; ++k) { REQUIRE(slice1(j, k) == count); count++; } } ND_Array<int, 3, 5> &slice2 = arr.outer_slice(1); using Slice2T = std::remove_reference<decltype(slice2)>::type; for(Slice2T::size_type j = 0; j < 3; ++j) { for(Slice2T::size_type k = 0; k < 5; ++k) { REQUIRE(slice2(j, k) == count); count++; } } ND_Array<int, 5, 3> &reshape = slice2.template reshape<ND_Array<int, 5, 3>>(); using ReshapeT = std::remove_reference<decltype(reshape)>::type; for(ReshapeT::size_type i = 0; i < 3; i++) { REQUIRE(&reshape(0, i) == &slice2(0, i)); } } TEST_CASE("iterate 1D", "[ND_Array]") { ND_Array<int, 11> arr; int count = 0; for(decltype(arr)::size_type i = 0; i < arr.extent(0); i++) { arr(i) = count; count++; } auto itr = arr.begin(); count = 0; for(int i = 0; i < arr.extent(0); i++) { REQUIRE(*itr == count); REQUIRE(arr.index(itr, 0) == i); count++; ++itr; } } TEST_CASE("iterate 3D", "[ND_Array]") { ND_Array<int, 5, 7, 11> arr; int count = 0; for(int i = 0; i < arr.extent(0); i++) { for(int j = 0; j < arr.extent(1); j++) { for(int k = 0; k < arr.extent(2); k++) { arr(i, j, k) = count; count++; } } } auto itr = arr.begin(); count = 0; for(int i = 0; i < arr.extent(0); i++) { for(int j = 0; j < arr.extent(1); j++) { for(int k = 0; k < arr.extent(2); k++) { REQUIRE(*itr == count); REQUIRE(arr.index(itr, 0) == i); REQUIRE(arr.index(itr, 1) == j); REQUIRE(arr.index(itr, 2) == k); count++; ++itr; } } } } TEST_CASE("fill", "[ND_Array]") { ND_Array<int, 7, 2, 3> arr; const int fill_val = 756; arr.fill(fill_val); for(int v : arr) { REQUIRE(v == fill_val); } } TEST_CASE("swap", "[ND_Array]") { ND_Array<int, 7, 2, 3> arr1, arr2; int i = 23; for(int &v : arr1) { v = i; i++; } for(int &v : arr2) { v = i; i++; } arr1.swap(arr2); i = 23; for(int v : arr2) { REQUIRE(v == i); i++; } for(int v : arr1) { REQUIRE(v == i); i++; } } TEST_CASE("castable", "[ND_Array]") { ND_Array<int, 6, 3> a1; ND_Array<int, 3, 6> a2 = static_cast<ND_Array<int, 3, 6>>(a1); ND_Array<int, 3, 6> &a3 = a2; ND_Array<int, 3, 6> &a4 = a1.reshape<ND_Array<int, 3, 6>>(); } /* Compile Time List Tests */ using ND_Array_0 = ND_Array<int, 2, 3, 5, 7, 11, 13, 17, 19>; static_assert(ND_Array_0::dimension() == 8, "Incorrect dimension"); static_assert(ND_Array_0::extent(0) == 2, "Incorrect extent"); static_assert(ND_Array_0::extent(1) == 3, "Incorrect extent"); static_assert(ND_Array_0::extent(2) == 5, "Incorrect extent"); static_assert(ND_Array_0::extent(3) == 7, "Incorrect extent"); static_assert(ND_Array_0::extent(4) == 11, "Incorrect extent"); static_assert(ND_Array_0::extent(5) == 13, "Incorrect extent"); static_assert(ND_Array_0::extent(6) == 17, "Incorrect extent"); static_assert(ND_Array_0::extent(7) == 19, "Incorrect extent"); static_assert(ND_Array_0::size() == 9699690, "Incorrect size"); static_assert(ND_Array_0::max_size() == 9699690, "Incorrect max size"); static_assert( ND_Array_0::empty() == false, "Incorrect empty - ND_Array should never be empty"); using Arr0 = ND_Array_internals_::CT_Array<int, 4>; static_assert(Arr0::len() == 1, "Incorrect CT Array Length"); static_assert(Arr0::sum() == 4, "Incorrect CT Array Sum"); static_assert(Arr0::product() == 4, "Incorrect CT Array Product"); static_assert(Arr0::slice_idx(0) == 0, "Incorrect 1D slice_idx"); static_assert(Arr0::slice_idx(1) == 1, "Incorrect 1D slice_idx"); static_assert(Arr0::slice_idx(2) == 2, "Incorrect 1D slice_idx"); static_assert(Arr0::slice_idx(3) == 3, "Incorrect 1D slice_idx"); using Arr1 = ND_Array_internals_::CT_Array<int, 1, 2, 3, 4>; static_assert(Arr1::len() == 4, "Incorrect CT Array Length"); static_assert(Arr1::sum() == 10, "Incorrect CT Array Sum"); static_assert(Arr1::product() == 24, "Incorrect CT Array Product"); using Arr2 = ND_Array_internals_::CT_Array<int, 0, 1>; static_assert(Arr1::slice_idx<Arr2>() == 12, "Incorrect Template Slice Index"); using Arr3 = ND_Array_internals_::CT_Array<int, 0, 0, 1>; static_assert(Arr1::slice_idx<Arr3>() == 4, "Incorrect Template Slice Index"); using Arr4 = ND_Array_internals_::CT_Array<int, 0, 0, 0, 1>; static_assert(Arr1::slice_idx<Arr4>() == 1, "Incorrect Template Slice Index"); static_assert(Arr1::slice_idx(0, 0, 0, 0) == 0, "Incorrect Runtime Slice Index"); static_assert(Arr1::slice_idx(0, 0, 0, 1) == 1, "Incorrect Runtime Slice Index"); static_assert(Arr1::slice_idx(0, 0, 0, 2) == 2, "Incorrect Runtime Slice Index"); static_assert(Arr1::slice_idx(0, 0, 0, 3) == 3, "Incorrect Runtime Slice Index"); static_assert(Arr1::slice_idx(0, 0, 1, 0) == 4, "Incorrect Runtime Slice Index"); static_assert(Arr1::slice_idx(0, 0, 1, 1) == 5, "Incorrect Runtime Slice Index"); static_assert(Arr1::slice_idx(0, 0, 1, 2) == 6, "Incorrect Runtime Slice Index"); static_assert(Arr1::slice_idx(0, 0, 1, 3) == 7, "Incorrect Runtime Slice Index"); static_assert(Arr1::slice_idx(0, 0, 2, 0) == 8, "Incorrect Runtime Slice Index"); static_assert(Arr1::slice_idx(0, 0, 2, 1) == 9, "Incorrect Runtime Slice Index"); static_assert(Arr1::slice_idx(0, 0, 2, 2) == 10, "Incorrect Runtime Slice Index"); static_assert(Arr1::slice_idx(0, 0, 2, 3) == 11, "Incorrect Runtime Slice Index"); static_assert(ND_Array_internals_::forward_truncate_array< 0, Arr1>::type::len() == 4, "forward_truncate_array failed"); static_assert(ND_Array_internals_::forward_truncate_array< 0, Arr1>::type::value(0) == 1, "forward_truncate_array failed"); static_assert(ND_Array_internals_::forward_truncate_array< 1, Arr1>::type::len() == 3, "forward_truncate_array failed"); static_assert(ND_Array_internals_::forward_truncate_array< 1, Arr1>::type::value(0) == 2, "forward_truncate_array failed"); static_assert(ND_Array_internals_::forward_truncate_array< 2, Arr1>::type::len() == 2, "forward_truncate_array failed"); static_assert(ND_Array_internals_::forward_truncate_array< 2, Arr1>::type::value(0) == 3, "forward_truncate_array failed"); static_assert(ND_Array_internals_::forward_truncate_array< 3, Arr1>::type::len() == 1, "forward_truncate_array failed"); static_assert(ND_Array_internals_::forward_truncate_array< 3, Arr1>::type::value(0) == 4, "forward_truncate_array failed");
31.088123
60
0.571358
mfdeakin
3a39a8b18959f4740d3b9b66ae5f7a7300ba6d38
1,188
hpp
C++
src/Factory/Module/Monitor/Monitor.hpp
codechecker123/aff3ct
030af3e990027fa803fb2c68f974c9ec0ee79b5d
[ "MIT" ]
null
null
null
src/Factory/Module/Monitor/Monitor.hpp
codechecker123/aff3ct
030af3e990027fa803fb2c68f974c9ec0ee79b5d
[ "MIT" ]
null
null
null
src/Factory/Module/Monitor/Monitor.hpp
codechecker123/aff3ct
030af3e990027fa803fb2c68f974c9ec0ee79b5d
[ "MIT" ]
null
null
null
#ifndef FACTORY_MONITOR_HPP #define FACTORY_MONITOR_HPP #include <string> #include "Module/Monitor/Monitor.hpp" #include "../../Factory.hpp" namespace aff3ct { namespace factory { extern const std::string Monitor_name; extern const std::string Monitor_prefix; struct Monitor : public Factory { class parameters : public Factory::parameters { public: // ------------------------------------------------------------------------------------------------- PARAMETERS // empty // ---------------------------------------------------------------------------------------------------- METHODS explicit parameters(const std::string &p = Monitor_prefix); virtual ~parameters(); virtual Monitor::parameters* clone() const; // parameters construction virtual void get_description(arg_map &req_args, arg_map &opt_args ) const; virtual void store (const arg_val_map &vals ); virtual void get_headers (std::map<std::string,header_list>& headers, const bool full = true) const; protected: parameters(const std::string &n, const std::string &p); }; }; } } #endif /* FACTORY_MONITOR_HPP */
28.285714
113
0.560606
codechecker123
3a3c9562607079184679341cadf62eab8009bac1
1,880
ipp
C++
rice/cpp_api/Struct.ipp
lutaml/rice
f60f0efa5761d1b12fb4a8542c3ef13edbfb51c1
[ "BSD-2-Clause" ]
205
2015-01-05T04:11:36.000Z
2022-03-22T19:08:16.000Z
rice/cpp_api/Struct.ipp
lutaml/rice
f60f0efa5761d1b12fb4a8542c3ef13edbfb51c1
[ "BSD-2-Clause" ]
91
2015-01-01T19:06:47.000Z
2022-03-20T23:12:04.000Z
rice/cpp_api/Struct.ipp
lutaml/rice
f60f0efa5761d1b12fb4a8542c3ef13edbfb51c1
[ "BSD-2-Clause" ]
32
2015-01-17T01:00:51.000Z
2022-03-18T04:12:59.000Z
#include "Symbol.hpp" namespace Rice { inline Struct& Struct::initialize(Module module, Identifier name) { Class struct_class(rb_cStruct); Object type = struct_class.vcall("new", this->members()); set_value(type); module.const_set(name, type); return *this; } inline Struct& Struct::define_member(Identifier name) { if (value() != rb_cObject) { throw std::runtime_error("struct is already initialized"); } members_.push_back(name.to_sym()); return *this; } inline Array Struct::members() const { if (value() == rb_cObject) { // Struct is not yet defined return Array(members_.begin(), members_.end()); } else { // Struct is defined, call Ruby API return rb_struct_s_members(this->value()); } } inline Struct::Instance Struct::new_instance(Array args) const { Object instance = const_cast<Struct*>(this)->vcall("new", args); return Instance(*this, instance); } inline Struct::Instance::Instance(Struct const& type, Array args) : Builtin_Object<T_STRUCT>(type.new_instance(args)), type_(type) { } inline Struct::Instance::Instance(Struct const& type, Object s) : Builtin_Object<T_STRUCT>(s), type_(type) { } inline Struct define_struct() { return Struct(); } template<typename T> inline Object Struct::Instance::operator[](T index) { return rb_struct_aref(value(), ULONG2NUM(index)); } template<> inline Object Struct::Instance::operator[]<Identifier>(Identifier member) { return rb_struct_aref(value(), Symbol(member)); } template<> inline Object Struct::Instance::operator[]<char const*>(char const* name) { return (*this)[Identifier(name)]; } } namespace Rice::detail { template<> struct Type<Struct> { static bool verify() { return true; } }; }
20.215054
75
0.645213
lutaml
3a3d4e86b4329677a5de0bdf88b8621c5a4e7d49
3,507
hpp
C++
src/libs/common/atomic/atomic.hpp
warm-byte/DTC
ff98a585c07712000e486cfd2d71515e6538435f
[ "Apache-2.0" ]
24
2021-08-22T12:17:50.000Z
2022-03-03T06:39:00.000Z
src/libs/common/atomic/atomic.hpp
warm-byte/DTC
ff98a585c07712000e486cfd2d71515e6538435f
[ "Apache-2.0" ]
2
2021-09-03T05:57:11.000Z
2021-09-03T05:59:38.000Z
src/libs/common/atomic/atomic.hpp
warm-byte/DTC
ff98a585c07712000e486cfd2d71515e6538435f
[ "Apache-2.0" ]
15
2021-08-22T14:44:22.000Z
2022-01-30T02:03:22.000Z
/* * Copyright [2021] JD.com, 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 "atomic.h" struct AtomicU32 { private: typedef uint32_t V; atomic_t count; public: ~AtomicU32(void) { } AtomicU32(V v = 0) { set(v); } inline V get(void) const { return atomic_read((atomic_t *)&count); } inline V set(V v) { atomic_set(&count, v); return v; } inline V add(V v) { return atomic_add_return(v, &count); } inline V sub(V v) { return atomic_sub_return(v, &count); } inline V clear(void) { return atomic_clear(&count); } inline V inc(void) { return add(1); } inline V dec(void) { return sub(1); } inline operator V(void) const { return get(); } inline V operator=(V v) { return set(v); } inline V operator+=(V v) { return add(v); } inline V operator-=(V v) { return sub(v); } inline V operator++(void) { return inc(); } inline V operator--(void) { return dec(); } inline V operator++(int) { return inc() - 1; } inline V operator--(int) { return dec() + 1; } }; struct AtomicS32 { private: typedef int32_t V; atomic_t count; public: ~AtomicS32(void) { } AtomicS32(V v = 0) { set(v); } inline V get(void) const { return atomic_read((atomic_t *)&count); } inline V set(V v) { atomic_set(&count, v); return v; } inline V add(V v) { return atomic_add_return(v, &count); } inline V sub(V v) { return atomic_sub_return(v, &count); } inline V clear(void) { return atomic_clear(&count); } inline V inc(void) { return add(1); } inline V dec(void) { return sub(1); } inline operator V(void) const { return get(); } inline V operator=(V v) { return set(v); } inline V operator+=(V v) { return add(v); } inline V operator-=(V v) { return sub(v); } inline V operator++(void) { return inc(); } inline V operator--(void) { return dec(); } inline V operator++(int) { return inc() - 1; } inline V operator--(int) { return dec() + 1; } }; #if HAS_ATOMIC8 struct AtomicS64 { private: typedef int64_t V; atomic8_t count; public: ~AtomicS64(void) { } AtomicS64(V v = 0) { set(v); } inline V get(void) const { return atomic8_read((atomic8_t *)&count); } inline V set(V v) { atomic8_set(&count, v); return v; } inline V add(V v) { return atomic8_add_return(v, &count); } inline V sub(V v) { return atomic8_sub_return(v, &count); } inline V clear(void) { return atomic8_clear(&count); } inline V inc(void) { return add(1); } inline V dec(void) { return sub(1); } inline operator V(void) const { return get(); } inline V operator=(V v) { return set(v); } inline V operator+=(V v) { return add(v); } inline V operator-=(V v) { return sub(v); } inline V operator++(void) { return inc(); } inline V operator--(void) { return dec(); } inline V operator++(int) { return inc() - 1; } inline V operator--(int) { return dec() + 1; } }; #endif
13.972112
74
0.618477
warm-byte
3a4046edcc74c2c4663661e3160eeb62399ce8ec
4,186
cpp
C++
tests/gt_main.cpp
mbits-libs/diags
6206ba7760f972787191803e234aa96a180a70e2
[ "MIT" ]
null
null
null
tests/gt_main.cpp
mbits-libs/diags
6206ba7760f972787191803e234aa96a180a70e2
[ "MIT" ]
null
null
null
tests/gt_main.cpp
mbits-libs/diags
6206ba7760f972787191803e234aa96a180a70e2
[ "MIT" ]
null
null
null
/* This file is taken almost verbatim from gmock_main.cc. Therefore copyright claim is retained from original file. */ // Copyright 2008, Google Inc. // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) /* Additionally, any changes to the source code are covered by: */ /* * Copyright (C) 2016 midnightBITS * * 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 <filesystem> #include <iostream> #include <string_view> #include <support/default_data_path.hpp> #include "gtest/gtest.h" std::filesystem::path TESTING_data_path = default_data_path; namespace { template <typename String> static bool ParseStringFlag(std::string_view str, std::string_view flag, String* value) { if (str.size() < 2 || str.substr(0, 2) != "--") return false; str = str.substr(2); if (str.size() < flag.size() || str.substr(0, flag.size()) != flag) return false; str = str.substr(flag.size()); if (str.empty() || str.front() != '=') return false; str = str.substr(1); if (str.empty()) return false; value->assign(str); return true; } } // namespace #if GTEST_OS_WINDOWS #include <tchar.h> int _tmain(int argc, TCHAR** argv) #else int main(int argc, char** argv) #endif { std::cout << "Running main() from gt_main.cpp\n"; testing::InitGoogleTest(&argc, argv); if (argc > 0) { for (int i = 1; i != argc; i++) { std::string value; if (ParseStringFlag(argv[i], "data_path", &value) && !value.empty()) { printf("Note: data used from path: %s\n", value.c_str()); TESTING_data_path = value; } } } return RUN_ALL_TESTS(); }
36.4
73
0.71548
mbits-libs
3a415f1aa7a8bd748178c4c100b995993acc6be7
3,272
cpp
C++
src/multipole/MultipoleProfileCalculator/DipoleCalculator.cpp
patwonder/pbrt-v2-skin
a6a58e5287925798c2d37adea6054dbec4587e4b
[ "BSD-2-Clause" ]
3
2020-12-09T00:03:29.000Z
2021-07-03T13:31:41.000Z
src/multipole/MultipoleProfileCalculator/DipoleCalculator.cpp
patwonder/pbrt-v2-skin
a6a58e5287925798c2d37adea6054dbec4587e4b
[ "BSD-2-Clause" ]
null
null
null
src/multipole/MultipoleProfileCalculator/DipoleCalculator.cpp
patwonder/pbrt-v2-skin
a6a58e5287925798c2d37adea6054dbec4587e4b
[ "BSD-2-Clause" ]
1
2020-11-28T12:33:24.000Z
2020-11-28T12:33:24.000Z
/* Copyright(c) 2013-2014 Yifan Wu. This file is part of fork of pbrt (pbrt-v2-skin). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "stdafx.h" #include "DipoleCalculator.h" #include <cmath> #include "numutil.h" static float FresnelDiffuseReflectance(float eta) { if (eta >= 1.f) { return -1.4399f / (eta * eta) + 0.7099f / eta + 0.6681f + 0.0636f * eta; } else { float eta2 = eta * eta; return -0.4399f + 0.7099f / eta - 0.3319f / eta2 + 0.0636f / (eta2 * eta); } } static float A(float Fdr) { return (1.f + Fdr) / (1.f - Fdr); } DipoleCalculator::DipoleCalculator(float eta_0, float eta_d, float d, float sigma_a, float sigmap_s, int32 zi, bool lerpOnThinSlab) { this->d = d; float sigmap_t = sigma_a + sigmap_s; sigma_tr = sqrt(3 * sigma_a * sigmap_t); alphap = sigmap_s / sigmap_t; float Fdr0 = FresnelDiffuseReflectance(eta_0); float Fdrd = FresnelDiffuseReflectance(eta_d); float A_0 = A(Fdr0), A_d = A(Fdrd); float D = 1.f / (3.f * sigmap_t); float zb_0 = 2.f * A_0 * D, zb_d = 2.f * A_d * D; float l = 1.f / sigmap_t; if (lerpOnThinSlab && l > d * .5f) { l = d * .5f; } zpos = 2.f * (float)zi * (d + zb_0 + zb_d) + l; zneg = zpos - 2.f * (l + zb_0); } float DipoleCalculator::Rd(float dsq) const { float dpos = sqrt(dsq + zpos * zpos); float dneg = sqrt(dsq + zneg * zneg); float dpos3 = dpos * dpos * dpos; float dneg3 = dneg * dneg * dneg; float rd = alphap * INV_FOURPI * ( zpos * (1 + sigma_tr * dpos) * exp(-sigma_tr * dpos) / dpos3 - zneg * (1 + sigma_tr * dneg) * exp(-sigma_tr * dneg) / dneg3); return rd; } float DipoleCalculator::Td(float dsq) const { float dpos = sqrt(dsq + (d - zpos) * (d - zpos)); float dneg = sqrt(dsq + (d - zneg) * (d - zneg)); float dpos3 = dpos * dpos * dpos; float dneg3 = dneg * dneg * dneg; float td = alphap * INV_FOURPI * ( (d - zpos) * (1 + sigma_tr * dpos) * exp(-sigma_tr * dpos) / dpos3 - (d - zneg) * (1 + sigma_tr * dneg) * exp(-sigma_tr * dneg) / dneg3); return td; }
35.565217
76
0.676039
patwonder
3a44e3dc47bc8695a2737ab6467ca8d4e14822b3
5,776
hpp
C++
libraries/chain/include/xgt/chain/global_property_object.hpp
raggi/xgt
ab7dedab2230eadb500a556abe6468d686d7db55
[ "MIT" ]
6
2021-05-11T20:44:13.000Z
2021-12-02T01:26:43.000Z
libraries/chain/include/xgt/chain/global_property_object.hpp
raggi/xgt
ab7dedab2230eadb500a556abe6468d686d7db55
[ "MIT" ]
26
2021-06-08T16:20:23.000Z
2022-03-30T03:42:21.000Z
libraries/chain/include/xgt/chain/global_property_object.hpp
raggi/xgt
ab7dedab2230eadb500a556abe6468d686d7db55
[ "MIT" ]
7
2021-06-16T17:36:14.000Z
2021-12-02T01:27:06.000Z
#pragma once #include <xgt/chain/xgt_fwd.hpp> #include <fc/uint128.hpp> #include <xgt/chain/xgt_object_types.hpp> #include <xgt/protocol/asset.hpp> namespace xgt { namespace chain { using xgt::protocol::asset; using xgt::protocol::price; /** * @class dynamic_global_property_object * @brief Maintains global state information * @ingroup object * @ingroup implementation * * This is an implementation detail. The values here are calculated during normal chain operations and reflect the * current values of global blockchain properties. */ class dynamic_global_property_object : public object< dynamic_global_property_object_type, dynamic_global_property_object> { public: template< typename Constructor, typename Allocator > dynamic_global_property_object( Constructor&& c, allocator< Allocator > a ) { c( *this ); } dynamic_global_property_object(){} id_type id; uint32_t head_block_number = 0; block_id_type head_block_id; time_point_sec time; wallet_name_type current_witness; fc::sha256 mining_target; time_point_sec last_mining_recalc_time; // @since 1.1.2 - Deprecated /** * The total POW accumulated, aka the sum of num_pow_witness at the time new POW is added */ uint64_t total_pow = -1; /** * The current count of how many pending POW witnesses there are, determines the difficulty * of doing pow */ uint32_t num_pow_witnesses = 0; asset virtual_supply = asset( 0, XGT_SYMBOL ); asset current_supply = asset( 0, XGT_SYMBOL ); asset confidential_supply = asset( 0, XGT_SYMBOL ); ///< total asset held in confidential balances /** * Maximum block size is decided by the set of active witnesses which change every round. * Each witness posts what they think the maximum size should be as part of their witness * properties, the median size is chosen to be the maximum block size for the round. * * @note the minimum value for maximum_block_size is defined by the protocol to prevent the * network from getting stuck by witnesses attempting to set this too low. */ uint32_t maximum_block_size = 0; /** * The size of the block that is partitioned for actions. * Required actions can only be delayed if they take up more than this amount. More can be * included, but are not required. Block generation should only include transactions up * to maximum_block_size - required_actions_parition_size to ensure required actions are * not delayed when they should not be. */ uint16_t required_actions_partition_percent = 0; /** * The current absolute slot number. Equal to the total * number of slots since genesis. Also equal to the total * number of missed slots plus head_block_number. */ uint64_t current_aslot = 0; /** * used to compute witness participation. */ fc::uint128_t recent_slots_filled; uint8_t participation_count = 0; ///< Divide by 128 to compute participation percentage uint32_t last_irreversible_block_num = 0; /** * The number of votes regenerated per day. Any user voting slower than this rate will be * "wasting" voting power through spillover; any user voting faster than this rate will have * their votes reduced. */ uint32_t target_votes_per_period = XGT_INITIAL_VOTE_POWER_RATE; uint32_t delegation_return_period = XGT_VOTING_ENERGY_REGENERATION_SECONDS; uint64_t reverse_auction_seconds = 0; //settings used to compute payments for every proposal time_point_sec next_maintenance_time; time_point_sec last_budget_time; uint16_t downvote_pool_percent = 0; asset xtt_creation_fee = asset( 1000, XGT_SYMBOL ); }; typedef multi_index_container< dynamic_global_property_object, indexed_by< ordered_unique< tag< by_id >, member< dynamic_global_property_object, dynamic_global_property_object::id_type, &dynamic_global_property_object::id > > >, allocator< dynamic_global_property_object > > dynamic_global_property_index; } } // xgt::chain #ifdef ENABLE_MIRA namespace mira { template<> struct is_static_length< xgt::chain::dynamic_global_property_object > : public boost::true_type {}; } // mira #endif FC_REFLECT( xgt::chain::dynamic_global_property_object, (id) (head_block_number) (head_block_id) (time) (current_witness) (mining_target) (total_pow) (num_pow_witnesses) (virtual_supply) (current_supply) (confidential_supply) (maximum_block_size) (required_actions_partition_percent) (current_aslot) (recent_slots_filled) (participation_count) (last_irreversible_block_num) (target_votes_per_period) (delegation_return_period) (reverse_auction_seconds) (next_maintenance_time) (last_budget_time) (downvote_pool_percent) (xtt_creation_fee) ) CHAINBASE_SET_INDEX_TYPE( xgt::chain::dynamic_global_property_object, xgt::chain::dynamic_global_property_index )
35.875776
132
0.637639
raggi
3a4de6d299b8a16a7dcaadef8d56997d5840fa0d
3,572
cpp
C++
NOLF/ClientShellDLL/FolderEffects.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
38
2019-09-16T14:46:42.000Z
2022-03-10T20:28:10.000Z
NOLF/ClientShellDLL/FolderEffects.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
39
2019-08-12T01:35:33.000Z
2022-02-28T16:48:16.000Z
NOLF/ClientShellDLL/FolderEffects.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
6
2019-09-17T12:49:18.000Z
2022-03-10T20:28:12.000Z
// FolderEffects.cpp: implementation of the CFolderEffects class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "FolderEffects.h" #include "FolderMgr.h" #include "FolderCommands.h" #include "ClientRes.h" #include "GameClientShell.h" #include "GameSettings.h" extern CGameClientShell* g_pGameClientShell; namespace { int kHeaderWidth = 300; int kSliderWidth = 200; int kSpacerWidth = 25; int kTotalWidth = kHeaderWidth + kSpacerWidth; } ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CFolderEffects::CFolderEffects() { m_bTracers = LTFALSE; m_bShellCasings = LTFALSE; m_bMuzzleLight = LTFALSE; m_bWeather = LTFALSE; m_nImpact = 2; m_nDebris = 2; } CFolderEffects::~CFolderEffects() { Term(); } // Build the folder LTBOOL CFolderEffects::Build() { if (g_pLayoutMgr->HasCustomValue(FOLDER_ID_EFFECTS,"ColumnWidth")) { kTotalWidth = g_pLayoutMgr->GetFolderCustomInt(FOLDER_ID_EFFECTS,"ColumnWidth"); LTFLOAT yr = g_pInterfaceResMgr->GetYRatio(); kTotalWidth *= yr; kHeaderWidth = kTotalWidth - kSpacerWidth; } if (g_pLayoutMgr->HasCustomValue(FOLDER_ID_EFFECTS,"SliderWidth")) kSliderWidth = g_pLayoutMgr->GetFolderCustomInt(FOLDER_ID_EFFECTS,"SliderWidth"); CreateTitle(IDS_TITLE_EFFECTS); CToggleCtrl* pToggle = AddToggle(IDS_TRACERS, IDS_HELP_TRACERS, kTotalWidth, &m_bTracers ); pToggle->SetOnString(IDS_ON); pToggle->SetOffString(IDS_OFF); pToggle = AddToggle(IDS_SHELLCASINGS, IDS_HELP_SHELLCASINGS, kTotalWidth, &m_bShellCasings ); pToggle->SetOnString(IDS_ON); pToggle->SetOffString(IDS_OFF); pToggle = AddToggle(IDS_MUZZLELIGHT, IDS_HELP_MUZZLELIGHT, kTotalWidth, &m_bMuzzleLight ); pToggle->SetOnString(IDS_ON); pToggle->SetOffString(IDS_OFF); pToggle = AddToggle(IDS_WEATHER, IDS_HELP_WEATHER, kTotalWidth, &m_bWeather ); pToggle->SetOnString(IDS_ON); pToggle->SetOffString(IDS_OFF); CCycleCtrl *pCycle = AddCycleItem(IDS_IMPACT,IDS_HELP_IMPACTS,kHeaderWidth,kSpacerWidth,&m_nImpact); pCycle->AddString(IDS_LOW); pCycle->AddString(IDS_MEDIUM); pCycle->AddString(IDS_HIGH); pCycle = AddCycleItem(IDS_DEBRIS,IDS_HELP_DEBRIS,kHeaderWidth,kSpacerWidth,&m_nDebris); pCycle->AddString(IDS_LOW); pCycle->AddString(IDS_MEDIUM); pCycle->AddString(IDS_HIGH); // Make sure to call the base class if (!CBaseFolder::Build()) return LTFALSE; UseBack(LTTRUE,LTTRUE); return LTTRUE; } void CFolderEffects::Term() { // Make sure to call the base class CBaseFolder::Term(); } uint32 CFolderEffects::OnCommand(uint32 dwCommand, uint32 dwParam1, uint32 dwParam2) { return CBaseFolder::OnCommand(dwCommand,dwParam1,dwParam2); }; void CFolderEffects::OnFocus(LTBOOL bFocus) { if (bFocus) { m_bTracers = (LTBOOL)GetConsoleInt("Tracers",1); m_bShellCasings = (LTBOOL)GetConsoleInt("ShellCasings",1); m_bMuzzleLight = (LTBOOL)GetConsoleInt("MuzzleLight",1); m_bWeather = (LTBOOL)GetConsoleInt("EnableWeatherFX",1); m_nImpact = GetConsoleInt("ImpactFXLevel",2); m_nDebris = GetConsoleInt("DebrisFXLevel",2); UpdateData(LTFALSE); } else { UpdateData(LTTRUE); WriteConsoleInt("Tracers",(int)m_bTracers); WriteConsoleInt("ShellCasings",(int)m_bShellCasings); WriteConsoleInt("MuzzleLight",(int)m_bMuzzleLight); WriteConsoleInt("EnableWeatherFX",(int)m_bWeather); WriteConsoleInt("ImpactFXLevel",m_nImpact); WriteConsoleInt("DebrisFXLevel",m_nDebris); } CBaseFolder::OnFocus(bFocus); }
25.884058
101
0.720325
haekb
3a4e03b4e1e5777b26cc288ff485f1171a79be92
953
cpp
C++
OpenDeformer/material/invertibleNeoHookean.cpp
OpenDeformerDev/OpenDeformer
f212a534acd4ebb94018b31074899599592d6680
[ "MIT" ]
8
2015-10-24T03:39:05.000Z
2017-04-29T21:32:56.000Z
OpenDeformer/material/invertibleNeoHookean.cpp
OpenDeformerDev/OpenDeformer
f212a534acd4ebb94018b31074899599592d6680
[ "MIT" ]
null
null
null
OpenDeformer/material/invertibleNeoHookean.cpp
OpenDeformerDev/OpenDeformer
f212a534acd4ebb94018b31074899599592d6680
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "invertibleNeoHookean.h" namespace ODER { InvertibleNeoHookeanMaterial::InvertibleNeoHookeanMaterial(Scalar rho, Scalar youngs, Scalar possion, Scalar inversionTrashold) : InvertibleHyperelasticMaterial(rho, inversionTrashold) { lambda = possion * youngs / ((Scalar(1.0) + possion) * (Scalar(1.0) - Scalar(2.0) * possion)); mu = youngs / (Scalar(2.0) * (Scalar(1.0) + possion)); } void InvertibleNeoHookeanMaterial::getEnergyGradient(const Scalar *invariants, Scalar *gradient) const { gradient[0] = Scalar(0.5) * mu; gradient[1] = Scalar(0); gradient[2] = (Scalar(-0.5) * mu + Scalar(0.25) * lambda * log(invariants[2])) / invariants[2]; } void InvertibleNeoHookeanMaterial::getEnergyHassian(const Scalar *invariants, Scalar *hassian) const { Initiation(hassian, 6); hassian[5] = (Scalar(0.5) * mu + Scalar(0.25) * lambda * (Scalar(1.0) - log(invariants[2]))) / (invariants[2] * invariants[2]); } }
45.380952
129
0.704092
OpenDeformerDev
3a502c538edc1c5c418b8edd5b1da8f104a37526
109
hh
C++
src/elle/log/fwd.hh
infinitio/elle
d9bec976a1217137436db53db39cda99e7024ce4
[ "Apache-2.0" ]
null
null
null
src/elle/log/fwd.hh
infinitio/elle
d9bec976a1217137436db53db39cda99e7024ce4
[ "Apache-2.0" ]
null
null
null
src/elle/log/fwd.hh
infinitio/elle
d9bec976a1217137436db53db39cda99e7024ce4
[ "Apache-2.0" ]
null
null
null
#pragma once namespace elle { namespace log { namespace detail { struct Send; } } }
8.384615
20
0.550459
infinitio
3a58567d273653f1a6ff25b31455fb7735d87937
289
cpp
C++
Engine/VulkanVertexShader.cpp
ebithril/Cerberus
8c5034bbb4fcdcc2cdb4495631176a2595c22dc7
[ "MIT" ]
1
2017-08-13T20:41:57.000Z
2017-08-13T20:41:57.000Z
Engine/VulkanVertexShader.cpp
ebithril/Cerberus
8c5034bbb4fcdcc2cdb4495631176a2595c22dc7
[ "MIT" ]
null
null
null
Engine/VulkanVertexShader.cpp
ebithril/Cerberus
8c5034bbb4fcdcc2cdb4495631176a2595c22dc7
[ "MIT" ]
null
null
null
#include "VulkanVertexShader.h" #include <FileOperations.h> void VulkanVertexShader::LoadShader(const String& ShaderFileName) { Array<int8> Glsl; ReadFileIntoArray(ShaderFileName, Glsl); Array<uint32> Spirv = CompileGLSL(ShaderFileName, ShaderType::VertexShader, Glsl); }
24.083333
84
0.761246
ebithril
3a598c10355a5afcb7cb406fff6c743cf8fad2b5
2,090
cpp
C++
DLLinjector/DLLinjector/DLLinjector.cpp
Rr42/SampleDLLInjector
d75b9329e059f25594d91691648dd1d0b917cb7c
[ "MIT" ]
null
null
null
DLLinjector/DLLinjector/DLLinjector.cpp
Rr42/SampleDLLInjector
d75b9329e059f25594d91691648dd1d0b917cb7c
[ "MIT" ]
null
null
null
DLLinjector/DLLinjector/DLLinjector.cpp
Rr42/SampleDLLInjector
d75b9329e059f25594d91691648dd1d0b917cb7c
[ "MIT" ]
null
null
null
// DLLinjector.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" int main() { // path to our dll LPCSTR DllPath = "E:\\Dev\\DLLinjector\\DLLinjector\\Debug\\SampleDLL.dll"; // Process ID of destination DWORD wPid = 0; // Open a handle to target process HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, wPid); // Allocate memory for the dllpath in the target process // length of the path string + null terminator LPVOID pDllPath = VirtualAllocEx(hProcess, 0, strlen(DllPath) + 1, MEM_COMMIT, PAGE_READWRITE); // Write the path to the address of the memory we just allocated // in the target process WriteProcessMemory(hProcess, pDllPath, (LPVOID)DllPath, strlen(DllPath) + 1, 0); // Create a Remote Thread in the target process which // calls LoadLibraryA as our dllpath as an argument -> program loads our dll HANDLE hLoadThread = CreateRemoteThread(hProcess, 0, 0, (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "LoadLibraryA"), pDllPath, 0, 0); // Wait for the execution of our loader thread to finish WaitForSingleObject(hLoadThread, INFINITE); std::cout << "Dll path allocated at: " << std::hex << pDllPath << std::endl; std::cin.get(); // Free the memory allocated for our dll path VirtualFreeEx(hProcess, pDllPath, strlen(DllPath) + 1, MEM_RELEASE); return 0; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
38.703704
136
0.709569
Rr42
3a5d6484c5c9e7ff14a3be45ff7fd88b89d3b3fd
6,458
cpp
C++
distributed/components.cpp
sithhell/hpxcbenchmarks
3687081a1bab5ffa872576f4ff8267f32d4fcc85
[ "BSL-1.0" ]
1
2020-10-24T14:12:59.000Z
2020-10-24T14:12:59.000Z
distributed/components.cpp
sithhell/hpxcbenchmarks
3687081a1bab5ffa872576f4ff8267f32d4fcc85
[ "BSL-1.0" ]
null
null
null
distributed/components.cpp
sithhell/hpxcbenchmarks
3687081a1bab5ffa872576f4ff8267f32d4fcc85
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2017-2018 Thomas Heller // // 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 <benchmark/benchmark.h> #include <hpx/hpx_main.hpp> #include <hpx/runtime/serialization/detail/preprocess.hpp> #include <hpx/include/serialization.hpp> #include <hpx/include/async.hpp> #include <hpx/include/actions.hpp> #include <hpx/include/components.hpp> #include <support/dummy.hpp> struct simple_component : hpx::components::component_base<simple_component> { int foo() { return dummy(); } HPX_DEFINE_COMPONENT_ACTION(simple_component, foo, foo_action); HPX_DEFINE_COMPONENT_DIRECT_ACTION(simple_component, foo, foo_direct_action); }; struct managed_component : hpx::components::managed_component_base<managed_component> { int foo() { return dummy(); } HPX_DEFINE_COMPONENT_ACTION(managed_component, foo, foo_action); HPX_DEFINE_COMPONENT_DIRECT_ACTION(managed_component, foo, foo_direct_action); }; typedef hpx::components::component<simple_component> simple_component_server; HPX_REGISTER_COMPONENT(simple_component_server, component_server); typedef hpx::components::managed_component<managed_component> managed_component_server; HPX_REGISTER_COMPONENT(managed_component_server, managed_component_server); static void simple_component_local(benchmark::State& state) { hpx::id_type dest = hpx::find_here(); for (auto _: state) { hpx::id_type id = hpx::new_<simple_component>(dest).get(); } } BENCHMARK(simple_component_local) ->UseRealTime() ; static void simple_component_remote(benchmark::State& state) { hpx::id_type dest = hpx::find_all_localities()[1]; for (auto _: state) { hpx::id_type id = hpx::new_<simple_component>(dest).get(); } } BENCHMARK(simple_component_remote) ->UseRealTime() ; static void simple_component_action_ptr(benchmark::State& state) { hpx::id_type dest = hpx::find_here(); hpx::id_type id = hpx::new_<simple_component>(dest).get(); auto ptr = hpx::get_ptr<simple_component>(id).get(); for (auto _: state) { benchmark::DoNotOptimize(ptr->foo()); } } BENCHMARK(simple_component_action_ptr) ->UseRealTime() ; static void simple_component_action_id(benchmark::State& state) { hpx::id_type dest = hpx::find_here(); hpx::id_type id = hpx::new_<simple_component>(dest).get(); for (auto _: state) { simple_component::foo_action act; benchmark::DoNotOptimize(act(id)); } } BENCHMARK(simple_component_action_id) ->UseRealTime() ; static void simple_component_direct_action_id(benchmark::State& state) { hpx::id_type dest = hpx::find_here(); hpx::id_type id = hpx::new_<simple_component>(dest).get(); for (auto _: state) { simple_component::foo_direct_action act; benchmark::DoNotOptimize(act(id)); } } BENCHMARK(simple_component_action_id) ->UseRealTime() ; static void simple_component_action_id_remote(benchmark::State& state) { hpx::id_type dest = hpx::find_all_localities()[1]; hpx::id_type id = hpx::new_<simple_component>(dest).get(); for (auto _: state) { simple_component::foo_action act; benchmark::DoNotOptimize(act(id)); } } BENCHMARK(simple_component_action_id_remote) ->UseRealTime() ; static void simple_component_direct_action_id_remote(benchmark::State& state) { hpx::id_type dest = hpx::find_all_localities()[1]; hpx::id_type id = hpx::new_<simple_component>(dest).get(); for (auto _: state) { simple_component::foo_direct_action act; benchmark::DoNotOptimize(act(id)); } } BENCHMARK(simple_component_action_id_remote) ->UseRealTime() ; static void managed_component_local(benchmark::State& state) { hpx::id_type dest = hpx::find_here(); for (auto _: state) { hpx::id_type id = hpx::new_<managed_component>(dest).get(); } } BENCHMARK(managed_component_local) ->UseRealTime() ; static void managed_component_remote(benchmark::State& state) { hpx::id_type dest = hpx::find_all_localities()[1]; for (auto _: state) { hpx::id_type id = hpx::new_<managed_component>(dest).get(); } } BENCHMARK(managed_component_remote) ->UseRealTime() ; static void managed_component_action_ptr(benchmark::State& state) { hpx::id_type dest = hpx::find_here(); hpx::id_type id = hpx::new_<managed_component>(dest).get(); auto ptr = hpx::get_ptr<managed_component>(id).get(); for (auto _: state) { benchmark::DoNotOptimize(ptr->foo()); } } BENCHMARK(managed_component_action_ptr) ->UseRealTime() ; static void managed_component_action_id(benchmark::State& state) { hpx::id_type dest = hpx::find_here(); hpx::id_type id = hpx::new_<managed_component>(dest).get(); for (auto _: state) { managed_component::foo_action act; benchmark::DoNotOptimize(act(id)); } } BENCHMARK(managed_component_action_id) ->UseRealTime() ; static void managed_component_direct_action_id(benchmark::State& state) { hpx::id_type dest = hpx::find_here(); hpx::id_type id = hpx::new_<managed_component>(dest).get(); for (auto _: state) { managed_component::foo_direct_action act; benchmark::DoNotOptimize(act(id)); } } BENCHMARK(managed_component_action_id) ->UseRealTime() ; static void managed_component_action_id_remote(benchmark::State& state) { hpx::id_type dest = hpx::find_all_localities()[1]; hpx::id_type id = hpx::new_<managed_component>(dest).get(); for (auto _: state) { managed_component::foo_action act; benchmark::DoNotOptimize(act(id)); } } BENCHMARK(managed_component_action_id_remote) ->UseRealTime() ; static void managed_component_direct_action_id_remote(benchmark::State& state) { hpx::id_type dest = hpx::find_all_localities()[1]; hpx::id_type id = hpx::new_<managed_component>(dest).get(); for (auto _: state) { managed_component::foo_direct_action act; benchmark::DoNotOptimize(act(id)); } } BENCHMARK(managed_component_action_id_remote) ->UseRealTime() ; int main(int argc, char **argv) { benchmark::Initialize(&argc, argv); benchmark::RunSpecifiedBenchmarks(); return 0; }
26.467213
82
0.693868
sithhell
3a5e5877a2c451656d839d7b36cd1c2cab56cc82
90,007
cpp
C++
Source/Mesh/geometry.cpp
INM-RAS/INMOST
2846aa63c1fc11c406cb2d558646237223183201
[ "BSD-3-Clause" ]
null
null
null
Source/Mesh/geometry.cpp
INM-RAS/INMOST
2846aa63c1fc11c406cb2d558646237223183201
[ "BSD-3-Clause" ]
7
2015-01-05T16:41:55.000Z
2015-01-17T11:21:06.000Z
Source/Mesh/geometry.cpp
INM-RAS/INMOST
2846aa63c1fc11c406cb2d558646237223183201
[ "BSD-3-Clause" ]
null
null
null
#include "inmost.h" #if defined(USE_MESH) #include <deque> using namespace std; const std::string normal_name = "PROTECTED_GEOM_UTIL_NORMAL"; const std::string measure_name = "PROTECTED_GEOM_UTIL_MEASURE"; const std::string centroid_name = "PROTECTED_GEOM_UTIL_CENTROID"; const std::string barycenter_name = "PROTECTED_GEOM_UTIL_BARYCENTER"; namespace INMOST { typedef struct orient_face_t { Edge bridge; Node first; Face face; orient_face_t(Edge _bridge, Node _first, Face _face) :bridge(_bridge),first(_first),face(_face) { } } orient_face; __INLINE static void vec_diff(const Storage::real * vecin1, const Storage::real * vecin2, Storage::real * vecout, unsigned int size) { for(unsigned int i = 0; i < size; i++) vecout[i] = vecin1[i] - vecin2[i]; } __INLINE static void vec_diff(const Storage::real_array & vecin1, const Storage::real * vecin2, Storage::real * vecout, unsigned int size) { for(unsigned int i = 0; i < size; i++) vecout[i] = vecin1[i] - vecin2[i]; } __INLINE static void vec_diff(const Storage::real_array & vecin1,const Storage::real_array & vecin2, Storage::real * vecout, unsigned int size) { for(unsigned int i = 0; i < size; i++) vecout[i] = vecin1[i] - vecin2[i]; } __INLINE static void vec_cross_product(const Storage::real * vecin1, const Storage::real * vecin2, Storage::real * vecout) { Storage::real temp[3]; temp[0] = vecin1[1]*vecin2[2] - vecin1[2]*vecin2[1]; temp[1] = vecin1[2]*vecin2[0] - vecin1[0]*vecin2[2]; temp[2] = vecin1[0]*vecin2[1] - vecin1[1]*vecin2[0]; vecout[0] = temp[0]; vecout[1] = temp[1]; vecout[2] = temp[2]; } __INLINE static Storage::real vec_dot_product(const Storage::real * vecin1,const Storage::real * vecin2, unsigned int size) { Storage::real ret = 0; for(unsigned int i = 0; i < size; i++) ret += vecin1[i]*vecin2[i]; return ret; } __INLINE static Storage::real vec_len2(const Storage::real * vecin, unsigned int size) { return vec_dot_product(vecin,vecin,size); } __INLINE static Storage::real vec_len(const Storage::real * vecin, unsigned int size) { return ::sqrt(vec_len2(vecin,size)); } __INLINE static Storage::real det3d(Storage::real a, Storage::real b, Storage::real c, Storage::real d, Storage::real e, Storage::real f, Storage::real g, Storage::real h, Storage::real i ) { return a*e*i - c*e*g + b*f*g - a*f*h + c*d*h - b*d*i; } __INLINE static Storage::real det3v(const Storage::real * x,const Storage::real * y,const Storage::real * z) { return det3d(x[0], x[1], x[2], y[0], y[1], y[2], z[0], z[1], z[2]); } __INLINE static Storage::real det4v(const Storage::real * w, const Storage::real * x, const Storage::real * y, const Storage::real * z) { return det3d(x[0]-w[0], x[1]-w[1], x[2]-w[2], y[0]-w[0], y[1]-w[1], y[2]-w[2], z[0]-w[0], z[1]-w[1], z[2]-w[2]); } __INLINE static Storage::real vec_normalize(Storage::real * vecin, unsigned int size) { Storage::real len = 0; for(unsigned int i = 0; i < size; i++) len += vecin[i]*vecin[i]; len = ::sqrt(len); for(unsigned int i = 0; i < size; i++) vecin[i] /= len; return len; } __INLINE static Storage::real triarea3d(const Storage::real p1[3], const Storage::real p2[3], const Storage::real p3[3]) { Storage::real v12[3], v13[3], v23[3], l12, l13, l23, halfperim; vec_diff(p2,p1,v12,3); vec_diff(p3,p1,v13,3); vec_diff(p3,p2,v23,3); l12 = vec_len(v12,3); l13 = vec_len(v13,3); l23 = vec_len(v23,3); halfperim = 0.5*(l12+l13+l23); return sqrt(std::max(0.0, halfperim * (halfperim - l12) * (halfperim - l13) * (halfperim - l23))); } __INLINE static bool inside_tet(const Storage::real p1[3], const Storage::real p2[3], const Storage::real p3[3], const Storage::real p4[3], const Storage::real p[3], Storage::real eps) { Storage::real T[9], b[3], det, coef[4]; T[0] = p2[0] - p1[0]; T[1] = p3[0] - p1[0]; T[2] = p4[0] - p1[0]; T[3] = p2[1] - p1[1]; T[4] = p3[1] - p1[1]; T[5] = p4[1] - p1[1]; T[6] = p2[2] - p1[2]; T[7] = p3[2] - p1[2]; T[8] = p4[2] - p1[2]; b[0] = p[0] - p1[0]; b[1] = p[1] - p1[1]; b[2] = p[2] - p1[2]; det = T[0] * (T[4] * T[8] - T[5] * T[7]) + T[1] * (T[5] * T[6] - T[3] * T[8]) + T[2] * (T[3] * T[7] - T[4] * T[6]); coef[1] = ((T[4] * T[8] - T[5] * T[7]) * b[0] + (T[2] * T[7] - T[1] * T[8]) * b[1] + (T[1] * T[5] - T[2] * T[4]) * b[2]) / det; coef[2] = ((T[5] * T[6] - T[3] * T[8]) * b[0] + (T[0] * T[8] - T[2] * T[6]) * b[1] + (T[2] * T[3] - T[0] * T[5]) * b[2]) / det; coef[3] = ((T[3] * T[7] - T[4] * T[6]) * b[0] + (T[1] * T[6] - T[0] * T[7]) * b[1] + (T[0] * T[4] - T[1] * T[3]) * b[2]) / det; coef[0] = 1.0 - coef[1] - coef[2] - coef[3]; return coef[0] >= -eps && coef[1] >= -eps && coef[2] >= -eps && coef[3] >= -eps; } __INLINE static bool inside_tet_print(const Storage::real p1[3], const Storage::real p2[3], const Storage::real p3[3], const Storage::real p4[3], const Storage::real p[3], Storage::real eps, std::ostream & sout) { Storage::real T[9], b[3], det, coef[4]; T[0] = p2[0] - p1[0]; T[1] = p3[0] - p1[0]; T[2] = p4[0] - p1[0]; T[3] = p2[1] - p1[1]; T[4] = p3[1] - p1[1]; T[5] = p4[1] - p1[1]; T[6] = p2[2] - p1[2]; T[7] = p3[2] - p1[2]; T[8] = p4[2] - p1[2]; b[0] = p[0] - p1[0]; b[1] = p[1] - p1[1]; b[2] = p[2] - p1[2]; det = T[0] * (T[4] * T[8] - T[5] * T[7]) + T[1] * (T[5] * T[6] - T[3] * T[8]) + T[2] * (T[3] * T[7] - T[4] * T[6]); coef[1] = ((T[4] * T[8] - T[5] * T[7]) * b[0] + (T[2] * T[7] - T[1] * T[8]) * b[1] + (T[1] * T[5] - T[2] * T[4]) * b[2]) / det; coef[2] = ((T[5] * T[6] - T[3] * T[8]) * b[0] + (T[0] * T[8] - T[2] * T[6]) * b[1] + (T[2] * T[3] - T[0] * T[5]) * b[2]) / det; coef[3] = ((T[3] * T[7] - T[4] * T[6]) * b[0] + (T[1] * T[6] - T[0] * T[7]) * b[1] + (T[0] * T[4] - T[1] * T[3]) * b[2]) / det; coef[0] = 1.0 - coef[1] - coef[2] - coef[3]; sout << coef[0] << " " << coef[1] << " " << coef[2] << " " << coef[3]; bool test = coef[0] >= -eps && coef[1] >= -eps && coef[2] >= -eps && coef[3] >= -eps; if (test) sout << " hit!"; return test; } ElementArray<Cell> Cell::NeighbouringCells() const { ElementArray<Cell> ret(GetMeshLink()); ElementArray<Face> faces = getFaces(); for(ElementArray<Face>::iterator f = faces.begin(); f != faces.end(); f++) { Cell c = Neighbour(f->self()); if( c.isValid() ) ret.push_back(c); } return ret; } bool Edge::SameLine(const ElementArray<Node>& nodes) const { Storage::real eps = GetMeshLink()->GetEpsilon(); Storage::real_array va = getBeg().Coords(), vb = getEnd().Coords(), vc; for (ElementArray<Node>::const_iterator it = nodes.begin(); it != nodes.end(); ++it) { vc = it->Coords(); if (triarea3d(va.data(), vb.data(), vc.data()) > eps) return false; } return true; } bool Edge::SameLine(const ElementArray<Edge>& edges) { Storage::real eps = edges.GetMeshLink()->GetEpsilon(), v[3] = { 0,0,0 }, alpha, xa[3] = { 0,0,0 }, xv[3] = { 0,0,0 }, vtv; Storage::integer mdim = edges.GetMeshLink()->GetDimensions(); Storage::real_array a = edges[0].getBeg().Coords(), b = edges[0].getEnd().Coords(); //first edge start and direction vec_diff(b.data(), a.data(), v, mdim); vtv = vec_dot_product(v, v, mdim); for (ElementArray<Edge>::size_type it = 1; it < edges.size(); ++it) { Element::adj_type const& lc = edges.GetMeshLink()->LowConn(edges[it].GetHandle()); for (Element::adj_type::const_iterator jt = lc.begin(); jt != lc.end(); ++jt) { Storage::real_array xn = Node(edges.GetMeshLink(), *jt).Coords(); //project vector to node vec_diff(xn.data(), a.data(), xa, mdim); alpha = vec_dot_product(v, xa, mdim) / vtv; for (Storage::integer k = 0; k < mdim; ++k) xv[k] = a[k] + alpha * v[k]; // check positions match vec_diff(xn.data(), xv, xa, mdim); if (vec_len2(xa, mdim) > eps * eps) return false; } } return true; } bool Face::SamePlane(const ElementArray<Node>& nodes) const { Storage::real eps = GetMeshLink()->GetEpsilon(), nf[3] = { 0,0,0 }, xf[3] = { 0,0,0 }, d; Storage::integer mdim = GetMeshLink()->GetDimensions(); UnitNormal(nf); Centroid(xf); d = vec_dot_product(nf, xf, mdim); for (ElementArray<Node>::const_iterator it = nodes.begin(); it != nodes.end(); ++it) { Storage::real_array xn = it->Coords(); if (fabs(vec_dot_product(nf, xn.data(), mdim) - d) > eps) return false; } return true; } bool Face::SamePlane(const ElementArray<Edge>& edges) const { Storage::real eps = GetMeshLink()->GetEpsilon(), nf[3] = { 0,0,0 }, xf[3] = { 0,0,0 }, d; Storage::integer mdim = GetMeshLink()->GetDimensions(); UnitNormal(nf); Centroid(xf); d = vec_dot_product(xf, nf, mdim); for (ElementArray<Edge>::const_iterator it = edges.begin(); it != edges.end(); ++it) { Element::adj_type const& lc = GetMeshLink()->LowConn(*it); for (Element::adj_type::const_iterator jt = lc.begin(); jt != lc.end(); ++jt) { Storage::real_array xn = Node(GetMeshLink(), *jt).Coords(); if (fabs(vec_dot_product(nf, xn.data(), mdim) - d) > eps) return false; } } return true; } bool Face::SamePlane(const ElementArray<Face>& faces) { Storage::real eps = faces.GetMeshLink()->GetEpsilon(), nf[3] = { 0,0,0 }, xf[3] = { 0,0,0 }, nf2[3] = { 0,0,0 }, xf2[3] = { 0,0,0 }, d; Storage::integer mdim = faces.GetMeshLink()->GetDimensions(); faces[0].UnitNormal(nf); faces[0].Centroid(xf); d = vec_dot_product(nf, xf, mdim); for (ElementArray<Face>::size_type it = 1; it < faces.size(); ++it) { faces[it].Centroid(xf2); if (fabs(vec_dot_product(nf, xf2, mdim) - d) > eps) return false; else { faces[it].UnitNormal(nf2); if (fabs(fabs(vec_dot_product(nf, nf2, mdim)) - 1) > eps) return false; } } return true; } Cell Cell::Neighbour(Face f) const { Cell b = f->BackCell(); if( b == self() ) return f->FrontCell(); return b; } bool Face::Inside(const Storage::real * point) const { Mesh * mesh = GetMeshLink(); real eps = mesh->GetEpsilon(); integer dim = mesh->GetDimensions(); integer mdim = GetElementDimension(); if(mdim < 2) { // check whether point lies on edge real v1[3], v2[3], v12[3], r1[3], r2[3], nrm[3], area, h, len; ElementArray<Node> nodes = getNodes(); assert(nodes.size() == 2);// nodes[0].Centroid(v1); nodes[1].Centroid(v2); vec_diff(point,v1,r1,dim); vec_diff(point,v2,r2,dim); vec_diff(v2,v1,v12,dim); len = vec_len(v12,dim); assert(len > 1e-20); vec_cross_product(r1,v12,nrm); area = vec_len(nrm,dim); h = area / len; if( h > eps ) return false; // point does not lie on line return vec_dot_product(r1,r2,dim) <= 0.0; // point is between edge nodes } real nrm[3], cnt[3], v[3]; UnitNormal(nrm); Centroid(cnt); vec_diff(cnt,point,v,dim); real d = vec_dot_product(nrm,v,dim); if(fabs(d) > eps) return false; // point is too far from the face plane // 2d algorithm from Cell::Inside real data[9][3]; for(int k = 0; k < 9; k++) for(int j = 0; j < 3; j++) data[k][j] = 0; Centroid(data[0]); ElementArray<Node> nodes = getNodes(); for(int i = 0; i < static_cast<int>(nodes.size()); i++) { int j = (i+1)%nodes.size(); nodes[i].Centroid(data[1]); nodes[j].Centroid(data[2]); vec_diff(point,data[0],data[3],dim); vec_diff(point,data[1],data[4],dim); vec_diff(point,data[2],data[5],dim); vec_cross_product(data[3],data[4],data[6]); vec_cross_product(data[4],data[5],data[7]); vec_cross_product(data[5],data[3],data[8]); if( vec_dot_product(data[6],data[7],dim) >= 0 && vec_dot_product(data[7],data[8],dim) >= 0 && vec_dot_product(data[8],data[6],dim) >= 0 ) return true; //inside one of the triangles } return false; } bool Cell::Inside(const Storage::real * point) const//check for 2d case { Mesh * mesh = GetMeshLink(); integer dim = GetElementDimension(); if( dim == 3 ) { #if 0 std::map<HandleType,real,16> hits; real ray[3]; ray[0] = rand()/(real)RAND_MAX; ray[1] = rand()/(real)RAND_MAX; ray[2] = rand()/(real)RAND_MAX; CastRay(point,ray,hits); if( hits.size()%2 == 0 ) return false; return true; #elif 1 assert(mesh->GetDimensions() == 3); integer vp = 0; integer vm = 0; integer vz = 0; real eps = mesh->GetEpsilon(); real c, d, v0[3]; real_array v1,v2; //ElementArray<Face> data = getFaces(); Element::adj_type const& data = mesh->LowConn(GetHandle()); MarkerType rev = 0, mrk; //for non-orientable meshes this check is not good if (!mesh->HaveGeometricData(ORIENTATION, FACE)) { Edge e0, e1, ej, en; Node e0b, e0e, e1b, e1e, ene, enb; Face cur(mesh,data[0]); mrk = mesh->CreatePrivateMarker(); rev = mesh->CreatePrivateMarker(); //reverse orientation //data.SetPrivateMarker(mrk); //0-th face orientation is default for (unsigned k = 0; k < data.size(); ++k) mesh->SetPrivateMarker(data[k], mrk); cur->RemPrivateMarker(mrk); Node n1, n2; //to retrive edge bool reverse = false; //reverse orientation in considered face std::deque< orient_face > stack; //edge and first node and face for visiting //todo: can do faster by retriving edges and going over their nodes //should not use FindSharedAdjacency Element::adj_type const & cur_edges = mesh->LowConn(cur->GetHandle()); //ElementArray<Edge> edges = cur->getEdges(); do { e0 = Edge(mesh, cur_edges[0]); e1 = Edge(mesh, cur_edges[1]); e0b = e0.getBeg(); e0e = e0.getEnd(); e1b = e1.getBeg(); e1e = e1.getEnd(); //figure out starting node order if (e0b == e1b || e0b == e1e) { n1 = e0e; n2 = e0b; } else { n1 = e0b; n2 = e0e; } //schedule unvisited adjacent faces for (unsigned j = 0; j < cur_edges.size(); j++) { //schedule face adjacent to considered edge ej = Edge(mesh, cur_edges[j]); en = Edge(mesh, cur_edges[(j + 1) % cur_edges.size()]); //ElementArray<Face> adjacent = ej->getFaces(mrk); Element::adj_type const& adjacent = mesh->HighConn(ej->GetHandle()); for (unsigned q = 0; q < adjacent.size(); ++q) { if (mesh->GetPrivateMarker(adjacent[q], mrk)) { mesh->RemPrivateMarker(adjacent[q], mrk); stack.push_back(orient_face(ej, reverse ? n2 : n1, Face(mesh, adjacent[q]))); } } //update edge nodes n1 = n2; //current end is new begin enb = en.getBeg(); ene = en.getEnd(); //find new end if (n2 == enb) n2 = ene; else n2 = enb; } if (stack.empty()) break; //get entry from stack orient_face r = stack.front(); //remove face from stack stack.pop_front(); //retrive edges for new face //edges = r.face->getEdges(); Element::adj_type const & redges = mesh->LowConn(r.face->GetHandle()); e0 = Edge(mesh, redges[0]); e1 = Edge(mesh, redges[1]); e0b = e0.getBeg(); e0e = e0.getEnd(); e1b = e1.getBeg(); e1e = e1.getEnd(); reverse = false; //figure out starting node order if (e0b == e1b || e0b == e1e) { n1 = e0e; n2 = e0b; } else { n1 = e0b; n2 = e0e; } //find out common edge orientation for (unsigned j = 0; j < redges.size(); j++) { ej = Edge(mesh, redges[j]); en = Edge(mesh, redges[(j + 1) % redges.size()]); if (ej == r.bridge) //found the edge { //reverse ordering on this face if (r.first == n1) { r.face->SetPrivateMarker(rev); reverse = true; } break; } //update edge nodes n1 = n2; //current end is new begin //find new end enb = en.getBeg(); ene = en.getEnd(); if (n2 == enb) n2 = ene; else n2 = enb; } } while (true); for (unsigned k = 0; k < data.size(); ++k) mesh->RemPrivateMarker(data[k], mrk); mesh->ReleasePrivateMarker(mrk); } for(unsigned k = 0; k < data.size(); k++) { Face f(mesh, data[k]); d = 0.0; ElementArray<Node> nodes = f.getNodes(); f.Centroid(v0); v1 = nodes.back().Coords(); for (ElementArray<Node>::size_type i = 0; i<nodes.size(); i++) { v2 = nodes[i].Coords(); d += c = det4v(point, v0, v1.data(), v2.data()); v1.swap(v2); } if (rev) c = f.GetPrivateMarker(rev) ? -1.0 : 1.0; else c = f.FaceOrientedOutside(self()) ? 1.0 : -1.0; //af = f.Area(); //d /= af; if(c*d > eps) vp++; else if(c*d < -eps) vm++; else vz++; } if (rev) { //data.RemPrivateMarker(rev); for (unsigned k = 0; k < data.size(); ++k) mesh->RemPrivateMarker(data[k], rev); mesh->ReleasePrivateMarker(rev); } if(vp*vm > 0) return false; else if( vz == 0 ) return true; else return true; #else Element::adj_type const& data = mesh->LowConn(GetHandle()); Storage::real p1[3], eps = mesh->GetEpsilon(); Centroid(p1); for (unsigned k = 0; k < data.size(); k++) { Face f(mesh, data[k]); ElementArray<Node> nodes = f.getNodes(); Storage::real_array p2 = nodes[0].Coords(); Storage::real_array p3 = nodes[1].Coords(); for (ElementArray<Node>::size_type i = 1; i < nodes.size() - 1; i++) { Storage::real_array p4 = nodes[i + 1].Coords(); if (inside_tet(p1, p2.data(), p3.data(), p4.data(), point, eps)) return true; p3.swap(p4); } } return false; #endif } else { int mdim = mesh->GetDimensions(); assert(mdim <= 3); Storage::real data[9][3]; if( mdim < 3 ) { memset(data,0,sizeof(Storage::real)*9*3); } Centroid(data[0]); ElementArray<Node> nodes = getNodes(); for(int i = 0; i < static_cast<int>(nodes.size()); i++) { int j = (i+1)%nodes.size(); nodes[i].Centroid(data[1]); nodes[j].Centroid(data[2]); vec_diff(point,data[0],data[3],mdim); vec_diff(point,data[1],data[4],mdim); vec_diff(point,data[2],data[5],mdim); vec_cross_product(data[3],data[4],data[6]); vec_cross_product(data[4],data[5],data[7]); vec_cross_product(data[5],data[3],data[8]); if( vec_dot_product(data[6],data[7],mdim) >= 0 && vec_dot_product(data[7],data[8],mdim) >= 0 && vec_dot_product(data[6],data[8],mdim) >= 0 ) return true; //inside one of the triangles } return false; } } bool Cell::InsidePrint(const Storage::real* point, std::ostream& sout) const//check for 2d case { Mesh* mesh = GetMeshLink(); integer dim = GetElementDimension(); if (dim == 3) { #if 0 std::map<HandleType, real, 16> hits; real ray[3]; ray[0] = rand() / (real)RAND_MAX; ray[1] = rand() / (real)RAND_MAX; ray[2] = rand() / (real)RAND_MAX; CastRay(point, ray, hits); if (hits.size() % 2 == 0) return false; return true; #elif 1 assert(mesh->GetDimensions() == 3); integer vp = 0; integer vm = 0; integer vz = 0; real eps = mesh->GetEpsilon(); real c, d, af, v0[3], x0[3]; real_array v1, v2; //ElementArray<Face> data = getFaces(); Element::adj_type const& data = mesh->LowConn(GetHandle()); MarkerType rev = 0, mrk; //for non-orientable meshes this check is not good if (!mesh->HaveGeometricData(ORIENTATION, FACE)) { Edge e0, e1, ej, en; Node e0b, e0e, e1b, e1e, ene, enb; Face cur(mesh, data[0]); mrk = mesh->CreatePrivateMarker(); rev = mesh->CreatePrivateMarker(); //reverse orientation //data.SetPrivateMarker(mrk); //0-th face orientation is default for (unsigned k = 0; k < data.size(); ++k) mesh->SetPrivateMarker(data[k], mrk); cur->RemPrivateMarker(mrk); Node n1, n2; //to retrive edge bool reverse = false; //reverse orientation in considered face std::deque< orient_face > stack; //edge and first node and face for visiting //todo: can do faster by retriving edges and going over their nodes //should not use FindSharedAdjacency Element::adj_type const& cur_edges = mesh->LowConn(cur->GetHandle()); //ElementArray<Edge> edges = cur->getEdges(); do { e0 = Edge(mesh, cur_edges[0]); e1 = Edge(mesh, cur_edges[1]); e0b = e0.getBeg(); e0e = e0.getEnd(); e1b = e1.getBeg(); e1e = e1.getEnd(); //figure out starting node order if (e0b == e1b || e0b == e1e) { n1 = e0e; n2 = e0b; } else { n1 = e0b; n2 = e0e; } //schedule unvisited adjacent faces for (unsigned j = 0; j < cur_edges.size(); j++) { //schedule face adjacent to considered edge ej = Edge(mesh, cur_edges[j]); en = Edge(mesh, cur_edges[(j + 1) % cur_edges.size()]); //ElementArray<Face> adjacent = ej->getFaces(mrk); Element::adj_type const& adjacent = mesh->HighConn(ej->GetHandle()); for (unsigned q = 0; q < adjacent.size(); ++q) { if (mesh->GetPrivateMarker(adjacent[q], mrk)) { mesh->RemPrivateMarker(adjacent[q], mrk); stack.push_back(orient_face(ej, reverse ? n2 : n1, Face(mesh, adjacent[q]))); } } //update edge nodes n1 = n2; //current end is new begin enb = en.getBeg(); ene = en.getEnd(); //find new end if (n2 == enb) n2 = ene; else n2 = enb; } if (stack.empty()) break; //get entry from stack orient_face r = stack.front(); //remove face from stack stack.pop_front(); //retrive edges for new face //edges = r.face->getEdges(); Element::adj_type const& redges = mesh->LowConn(r.face->GetHandle()); e0 = Edge(mesh, redges[0]); e1 = Edge(mesh, redges[1]); e0b = e0.getBeg(); e0e = e0.getEnd(); e1b = e1.getBeg(); e1e = e1.getEnd(); reverse = false; //figure out starting node order if (e0b == e1b || e0b == e1e) { n1 = e0e; n2 = e0b; } else { n1 = e0b; n2 = e0e; } //find out common edge orientation for (unsigned j = 0; j < redges.size(); j++) { ej = Edge(mesh, redges[j]); en = Edge(mesh, redges[(j + 1) % redges.size()]); if (ej == r.bridge) //found the edge { //reverse ordering on this face if (r.first == n1) { r.face->SetPrivateMarker(rev); reverse = true; } break; } //update edge nodes n1 = n2; //current end is new begin //find new end enb = en.getBeg(); ene = en.getEnd(); if (n2 == enb) n2 = ene; else n2 = enb; } } while (true); for (unsigned k = 0; k < data.size(); ++k) mesh->RemPrivateMarker(data[k], mrk); mesh->ReleasePrivateMarker(mrk); } Centroid(x0); for (unsigned k = 0; k < data.size(); k++) { Face f(mesh, data[k]); d = 0.0; ElementArray<Node> nodes = f.getNodes(); f.Centroid(v0); v1 = nodes.back().Coords(); for (ElementArray<Node>::size_type i = 0; i < nodes.size(); i++) { v2 = nodes[i].Coords(); d += c = det4v(point, v0, v1.data(), v2.data()); sout << "tet " << i; inside_tet_print(x0, v0, v1.data(), v2.data(), point, eps, sout); sout << std::endl; v1.swap(v2); } if (rev) c = f.GetPrivateMarker(rev) ? -1.0 : 1.0; else c = f.FaceOrientedOutside(self()) ? 1.0 : -1.0; af = f.Area(); sout << "FACE:" << f.LocalID() << " nodes " << nodes.size() << " flat " << (f.Planarity() ? "true" : "false"); sout << " area " << af << " ornt " << c << " d " << d << " d/a " << d / af << " eps " << eps; sout << " test " << (c * d > eps ? "p" : (c * d < -eps ? "n" : "z")); sout << std::endl; //d /= af; if (c * d > eps) vp++; else if (c * d < -eps) vm++; else vz++; } if (rev) { //data.RemPrivateMarker(rev); for (unsigned k = 0; k < data.size(); ++k) mesh->RemPrivateMarker(data[k], rev); mesh->ReleasePrivateMarker(rev); } sout << "p " << vp << " n " << vm << " z " << vz << std::endl; if (vp * vm > 0) return false; //no hit else if (vz == 0) return true; //hit at boundary else return true; //hit inside cell #else Element::adj_type const& data = mesh->LowConn(GetHandle()); Storage::real p1[3], eps = mesh->GetEpsilon(); Centroid(p1); for (unsigned k = 0; k < data.size(); k++) { Face f(mesh, data[k]); ElementArray<Node> nodes = f.getNodes(); Storage::real_array p2 = nodes[0].Coords(); Storage::real_array p3 = nodes[1].Coords(); for (ElementArray<Node>::size_type i = 1; i < nodes.size() - 1; i++) { Storage::real_array p4 = nodes[i + 1].Coords(); if (inside_tet(p1, p2.data(), p3.data(), p4.data(), point, eps)) return true; p3.swap(p4); } } return false; #endif } else { int mdim = mesh->GetDimensions(); assert(mdim <= 3); Storage::real data[9][3]; if (mdim < 3) { memset(data, 0, sizeof(Storage::real) * 9 * 3); } Centroid(data[0]); ElementArray<Node> nodes = getNodes(); for (int i = 0; i < static_cast<int>(nodes.size()); i++) { int j = (i + 1) % nodes.size(); nodes[i].Centroid(data[1]); nodes[j].Centroid(data[2]); vec_diff(point, data[0], data[3], mdim); vec_diff(point, data[1], data[4], mdim); vec_diff(point, data[2], data[5], mdim); vec_cross_product(data[3], data[4], data[6]); vec_cross_product(data[4], data[5], data[7]); vec_cross_product(data[5], data[3], data[8]); if (vec_dot_product(data[6], data[7], mdim) >= 0 && vec_dot_product(data[7], data[8], mdim) >= 0 && vec_dot_product(data[6], data[8], mdim) >= 0) return true; //inside one of the triangles } return false; } } void Face::UnitNormal(real * nrm) const { Mesh * m = GetMeshLink(); m->GetGeometricData(GetHandle(),NORMAL,nrm); integer dim = m->GetDimensions(); real l = ::sqrt(vec_dot_product(nrm,nrm,dim)); if(::fabs(l) > m->GetEpsilon()) { for(integer i = 0; i < dim; i++) nrm[i] /= l; } } void Face::OrientedNormal(Cell c, Storage::real * nrm) const { Normal(nrm); if( !FaceOrientedOutside(c) ) { integer dim = GetMeshLink()->GetDimensions(); for(integer i = 0; i < dim; i++) nrm[i] = -nrm[i]; } } void Face::OrientedUnitNormal(Cell c, Storage::real * nrm) const { UnitNormal(nrm); if( !FaceOrientedOutside(c) ) { integer dim = GetMeshLink()->GetDimensions(); for(integer i = 0; i < dim; i++) nrm[i] = -nrm[i]; } } bool Mesh::TestClosure(const HandleType * elements, integer num) const { integer i; std::map<HandleType,int> e_visit; std::map<HandleType,int>::iterator it; if( !HideMarker() ) { for(i = 0; i < num; i++) { Element::adj_type const & lc = LowConn(elements[i]); for(Element::adj_type::size_type jt = 0; jt < lc.size(); jt++) e_visit[lc[jt]]++; } } else { for(i = 0; i < num; i++) if( !GetMarker(elements[i],HideMarker()) ) { Element::adj_type const & lc = LowConn(elements[i]); for(Element::adj_type::size_type jt = 0; jt < lc.size(); jt++) { if( !GetMarker(lc[jt],HideMarker()) ) e_visit[lc[jt]]++; } } } for(it = e_visit.begin(); it != e_visit.end(); it++) if( it->second != 2 ) return false; return true; } Element::GeometricType Mesh::ComputeGeometricType(ElementType etype, const HandleType * lc, INMOST_DATA_ENUM_TYPE size) { Element::GeometricType ret = Element::Unset; INMOST_DATA_ENUM_TYPE s = 0; if( isMeshModified() ) s = Mesh::Count(lc,size,HideMarker()); else s = size; int dmax = -1, dmin = 4; if( s == 0 && etype != NODE) return ret; switch(etype) { case NODE: ret = Element::Vertex; break; case EDGE: if( s == 1 ) ret = Element::Vertex; else if( s == 2 ) ret = Element::Line; break; case FACE: for (INMOST_DATA_ENUM_TYPE k = 0; k < size; ++k) if( !Hidden(lc[k]) ) { int d = Element::GetGeometricDimension(GetGeometricType(lc[k])); if (dmax < d) dmax = d; if (dmin > d) dmin = d; } if (dmax != dmin) { ret = Element::MultiLine; } else if( dmax == 0 ) { ret = Element::Line; } else { if( !GetTopologyCheck(NEED_TEST_CLOSURE) || TestClosure(lc,size) ) { if( s == 3 ) ret = Element::Tri; else if( s == 4 ) ret = Element::Quad; else ret = Element::Polygon; } else ret = Element::MultiLine; } break; case CELL: for (INMOST_DATA_ENUM_TYPE k = 0; k < size; ++k) if( !Hidden(lc[k]) ) { int d = Element::GetGeometricDimension(GetGeometricType(lc[k])); if (dmax < d) dmax = d; if (dmin > d) dmin = d; } if (dmax != dmin) { ret = Element::MultiPolygon; } else if( dmax == 1 ) { if( !GetTopologyCheck(NEED_TEST_CLOSURE) || TestClosure(lc,size) ) { if( s == 3 ) ret = Element::Tri; else if( s == 4 ) ret = Element::Quad; else ret = Element::Polygon; } else ret = Element::MultiLine; } else { if( !GetTopologyCheck(NEED_TEST_CLOSURE) || TestClosure(lc,size) ) { // for simple cells there is no more then one common edge // otherwise the cell should be treated as polyhedron bool check = true; MarkerType common = CreatePrivateMarker(); for(INMOST_DATA_ENUM_TYPE i = 0; i < s; ++i) { const Element::adj_type & ilc = LowConn(lc[i]); // access edges of the i-th face for(INMOST_DATA_ENUM_TYPE r = 0; r < ilc.size(); ++r ) SetPrivateMarker(ilc[r],common); for(INMOST_DATA_ENUM_TYPE j = i+1; j < s; ++j ) { const Element::adj_type & jlc = LowConn(lc[j]); // access edges of the j-th face int cnt = 0; for(INMOST_DATA_ENUM_TYPE r = 0; r < jlc.size(); ++r ) if( GetPrivateMarker(jlc[r],common) ) cnt++; if( cnt > 1 ) check = false; } for(INMOST_DATA_ENUM_TYPE r = 0; r < ilc.size(); ++r ) RemPrivateMarker(ilc[r],common); } ReleasePrivateMarker(common); if( check ) { //test c_faces closure, if no closure, set as MultiPolygon INMOST_DATA_ENUM_TYPE quads = 0,tris = 0,i; for(i = 0; i < size; i++) if( !Hidden(lc[i]) ) { if( GetGeometricType(lc[i]) == Element::Tri ) tris++; else if( GetGeometricType(lc[i]) == Element::Quad ) quads++; } if( tris == 4 && s == 4 ) ret = Element::Tet; else if( quads == 6 && s == 6 ) ret = Element::Hex; else if( tris == 4 && quads == 1 && s == tris+quads) ret = Element::Pyramid; else if( quads == 3 && tris == 2 && s == tris+quads) ret = Element::Prism; else ret = Element::Polyhedron; } else ret = Element::Polyhedron; } else ret = Element::MultiPolygon; } break; case ESET: ret = Element::Set; break; } return ret; } Storage::real Edge::Length() const { Storage::real ret; GetMeshLink()->GetGeometricData(GetHandle(),MEASURE,&ret); return ret; } Storage::real Face::Area() const { real ret; GetMeshLink()->GetGeometricData(GetHandle(),MEASURE,&ret); return ret; } void Face::Normal(real * nrm) const { GetMeshLink()->GetGeometricData(GetHandle(),NORMAL,nrm); } Storage::real Cell::Volume() const { real ret; GetMeshLink()->GetGeometricData(GetHandle(),MEASURE,&ret); return ret; } void Element::ComputeGeometricType() const { GetMeshLink()->ComputeGeometricType(GetHandle()); } void Mesh::ComputeGeometricType(HandleType h) { SetGeometricType(h,Element::Unset); if( GetElementType() > NODE ) { Element::adj_type const & lc = LowConn(h); if( !lc.empty() ) SetGeometricType(h,ComputeGeometricType(GetHandleElementType(h),lc.data(),static_cast<integer>(lc.size()))); } else SetGeometricType(h,Element::Vertex); } void Mesh::RecomputeGeometricData(HandleType e, GeometricData d) { if (d == ORIENTATION && HaveGeometricData(ORIENTATION, FACE)) { if (GetHandleElementType(e) == CELL) //then correct the normal { Element::adj_type& lc = LowConn(e); //faces for (Element::adj_type::iterator it = lc.begin(); it != lc.end(); ++it) if (!GetMarker(*it, HideMarker())) { Element::adj_type & hc = HighConn(*it); if( Mesh::Count(&hc[0],hc.size(),HideMarker()) == 1 || hc[Mesh::getNext(hc.data(), (enumerator)hc.size(), ENUMUNDEF, HideMarker())] == e) Face(this, *it)->FixNormalOrientation(); } } else if (GetHandleElementType(e) == FACE) Face(this, e)->FixNormalOrientation(); } else if (HaveGeometricData(d, GetHandleElementType(e))) //compute centroid first { Tag t = GetGeometricTag(d); Storage::real* a = static_cast<Storage::real*>(MGetDenseLink(e, t)); HideGeometricData(d, GetHandleElementType(e)); GetGeometricData(e, d, a); ShowGeometricData(d, GetHandleElementType(e)); } } void Mesh::RecomputeGeometricData(HandleType e) { RecomputeGeometricData(e, CENTROID); RecomputeGeometricData(e, NORMAL); RecomputeGeometricData(e, ORIENTATION); RecomputeGeometricData(e, MEASURE); RecomputeGeometricData(e, BARYCENTER); //static std::map<Element *, int> numfixes; /* GeometricData d ; for(d = CENTROID; d <= NORMAL; d++) // first compute centroids and normals { if( HaveGeometricData(d,GetHandleElementType(e)) ) //compute centroid first { Tag t = GetGeometricTag(d); Storage::real * a = static_cast<Storage::real *>(MGetDenseLink(e,t)); HideGeometricData(d,GetHandleElementType(e)); GetGeometricData(e,d,a); ShowGeometricData(d,GetHandleElementType(e)); } } if( HaveGeometricData(ORIENTATION,FACE) ) { if( GetHandleElementType(e) == CELL ) //then correct the normal { Element::adj_type & lc = LowConn(e); //faces for(Element::adj_type::iterator it = lc.begin(); it != lc.end(); ++it) if( !GetMarker(*it,HideMarker()) ) { //Element::adj_type & hc = HighConn(e); //if( Mesh::Count(&hc[0],hc.size(),HideMarker()) == 1 ) Face(this,*it)->FixNormalOrientation(); } } else if( GetHandleElementType(e) == FACE ) Face(this,e)->FixNormalOrientation(); } for(d = MEASURE; d <= BARYCENTER; d++) // compute the rest { if( HaveGeometricData(d,GetHandleElementType(e)) ) { Tag t = GetGeometricTag(d); Storage::real * a = static_cast<Storage::real *>(MGetDenseLink(e,t)); HideGeometricData(d,GetHandleElementType(e)); GetGeometricData(e,d,a); ShowGeometricData(d,GetHandleElementType(e)); } } */ } void Mesh::RemoveGeometricData(GeomParam table) { for(GeomParam::iterator it = table.begin(); it != table.end(); ++it) { if( it->first == MEASURE ) { if(measure_tag.isValid()) measure_tag = DeleteTag(measure_tag ,it->second); for(ElementType etype = EDGE; etype <= CELL; etype = etype << 1) if( etype & it->second) HideGeometricData(MEASURE,etype); } if( it->first == CENTROID ) { if(centroid_tag.isValid()) centroid_tag = DeleteTag(centroid_tag ,it->second); for(ElementType etype = EDGE; etype <= CELL; etype = etype << 1) if( etype & it->second) HideGeometricData(CENTROID,etype); } if( it->first == BARYCENTER ) { if(barycenter_tag.isValid()) barycenter_tag = DeleteTag(barycenter_tag,it->second); for(ElementType etype = EDGE; etype <= CELL; etype = etype << 1) if( etype & it->second) HideGeometricData(BARYCENTER,etype); } if( it->first == NORMAL ) { if(normal_tag.isValid()) normal_tag = DeleteTag(normal_tag ,it->second); for(ElementType etype = FACE; etype <= CELL; etype = etype << 1) if( etype & it->second) HideGeometricData(NORMAL,etype); } if( it->first == ORIENTATION) if( FACE & it->second) HideGeometricData(ORIENTATION,FACE); } } void Mesh::RestoreGeometricTags() { for(GeometricData gtype = MEASURE; gtype <= NORMAL; gtype++) { bool restore = false; for(ElementType etype = EDGE; etype <= CELL && !restore; etype = NextElementType(etype)) if( HaveGeometricData(gtype,etype) ) restore = true; if( restore ) { switch(gtype) { case MEASURE: measure_tag = GetTag(measure_name); break; case CENTROID: centroid_tag = GetTag(centroid_name); break; case BARYCENTER: barycenter_tag = GetTag(barycenter_name); break; case NORMAL: normal_tag = GetTag(normal_name); break; } } } } void Mesh::RepairGeometricTags() { if( HaveTag(measure_name) ) { measure_tag = GetTag(measure_name); for(ElementType etype = EDGE; etype <= CELL; etype = NextElementType(etype)) if( measure_tag.isDefined(etype) && !HaveGeometricData(MEASURE,etype) ) ShowGeometricData(MEASURE,etype); } if( HaveTag(centroid_name) ) { centroid_tag = GetTag(centroid_name); for(ElementType etype = EDGE; etype <= CELL; etype = NextElementType(etype)) if( centroid_tag.isDefined(etype) && !HaveGeometricData(CENTROID,etype) ) ShowGeometricData(CENTROID,etype); } if( HaveTag(barycenter_name) ) { barycenter_tag = GetTag(barycenter_name); for(ElementType etype = EDGE; etype <= CELL; etype = NextElementType(etype)) if( barycenter_tag.isDefined(etype) && !HaveGeometricData(BARYCENTER,etype) ) ShowGeometricData(BARYCENTER,etype); } if( HaveTag(normal_name) ) { normal_tag = GetTag(normal_name); for(ElementType etype = EDGE; etype <= CELL; etype = NextElementType(etype)) if( normal_tag.isDefined(etype) && !HaveGeometricData(NORMAL,etype) ) ShowGeometricData(NORMAL,etype); } } void Mesh::PrepareGeometricData(GeomParam table) { for(GeomParam::iterator it = table.begin(); it != table.end(); ++it) { GeometricData types = it->first; ElementType mask = it->second; if( types == ORIENTATION ) { //std::cout << "ORIENTATION" << std::endl; if( mask & FACE ) { if( HideMarker() ) { MarkerType hm = HideMarker(); #if defined(USE_OMP) #pragma omp parallel for #endif for(integer e = 0; e < FaceLastLocalID(); ++e) { if( isValidElement(FACE,e) ) { HandleType h = ComposeHandle(FACE,e); if( !GetMarker(h,hm) ) Face(this,h)->FixNormalOrientation(); } } } else { //std::cout << "Fix orientation" << std::endl; #if defined(USE_OMP) #pragma omp parallel for #endif for(integer e = 0; e < FaceLastLocalID(); ++e) if( isValidElement(FACE,e) ) Face(this,ComposeHandle(FACE,e))->FixNormalOrientation(); } } ShowGeometricData(ORIENTATION,FACE); } if( types == MEASURE ) { //std::cout << "MEASURE" << std::endl; for(ElementType etype = EDGE; etype <= CELL; etype = NextElementType(etype)) { if( (mask & etype) && !HaveGeometricData(MEASURE,etype)) { measure_tag = CreateTag(measure_name,DATA_REAL,etype,NONE,1); if( HideMarker() ) { MarkerType hm = HideMarker(); #if defined(USE_OMP) #pragma omp parallel for #endif for(integer e = 0; e < LastLocalID(etype); ++e) if( isValidElement(etype,e) ) { HandleType h = ComposeHandle(etype,e); if( !GetMarker(h,hm) ) GetGeometricData(h,MEASURE,static_cast<Storage::real *>(MGetDenseLink(h,measure_tag))); } } else { #if defined(USE_OMP) #pragma omp parallel for #endif for(integer e = 0; e < LastLocalID(etype); ++e) if( isValidElement(etype,e) ) { HandleType h = ComposeHandle(etype,e); GetGeometricData(h,MEASURE,static_cast<Storage::real *>(MGetDenseLink(h,measure_tag))); } } ShowGeometricData(MEASURE,etype); } } } if( types == CENTROID ) { //std::cout << "CENTROID" << std::endl; for(ElementType etype = EDGE; etype <= CELL; etype = NextElementType(etype)) { if( (mask & etype) && !HaveGeometricData(CENTROID,etype)) { centroid_tag = CreateTag(centroid_name,DATA_REAL,etype,NONE,GetDimensions()); if( HideMarker() ) { MarkerType hm = HideMarker(); #if defined(USE_OMP) #pragma omp parallel for #endif for(integer k = 0; k < LastLocalID(etype); ++k) if( isValidElement(etype,k) ) { HandleType h = ComposeHandle(etype,k); if( !GetMarker(h,hm) ) GetGeometricData(h,CENTROID,static_cast<Storage::real *>(MGetDenseLink(h,centroid_tag))); } } else { #if defined(USE_OMP) #pragma omp parallel for #endif for(integer k = 0; k < LastLocalID(etype); ++k) if( isValidElement(etype,k) ) { HandleType h = ComposeHandle(etype,k); GetGeometricData(h,CENTROID,static_cast<Storage::real *>(MGetDenseLink(h,centroid_tag))); } } ShowGeometricData(CENTROID,etype); } } } if( types == BARYCENTER ) { //std::cout << "BARYCENTER" << std::endl; for(ElementType etype = EDGE; etype <= CELL; etype = NextElementType(etype)) { if( (mask & etype) && !HaveGeometricData(BARYCENTER,etype)) { barycenter_tag = CreateTag(barycenter_name,DATA_REAL,etype,NONE,GetDimensions()); if( HideMarker() ) { MarkerType hm = HideMarker(); #if defined(USE_OMP) #pragma omp parallel for #endif for(integer e = 0; e < LastLocalID(etype); ++e) if( isValidElement(etype,e) ) { HandleType h = ComposeHandle(etype,e); if( !GetMarker(h,hm) ) GetGeometricData(h,BARYCENTER,static_cast<Storage::real *>(MGetDenseLink(h,barycenter_tag))); } } else { #if defined(USE_OMP) #pragma omp parallel for #endif for(integer e = 0; e < LastLocalID(etype); ++e) if( isValidElement(etype,e) ) { HandleType h = ComposeHandle(etype,e); GetGeometricData(h,BARYCENTER,static_cast<Storage::real *>(MGetDenseLink(h,barycenter_tag))); } } ShowGeometricData(BARYCENTER,etype); } } } if( types == NORMAL ) { //std::cout << "NORMAL" << std::endl; for(ElementType etype = FACE; etype <= CELL; etype = NextElementType(etype)) { if( (mask & etype) && !HaveGeometricData(NORMAL,etype)) { normal_tag = CreateTag(normal_name,DATA_REAL,etype,NONE,GetDimensions()); if( HideMarker() ) { MarkerType hm = HideMarker(); #if defined(USE_OMP) #pragma omp parallel for #endif for(integer e = 0; e < LastLocalID(etype); ++e) if( isValidElement(etype,e) ) { HandleType h = ComposeHandle(etype,e); if( !GetMarker(h,hm) ) GetGeometricData(h,NORMAL,static_cast<Storage::real *>(MGetDenseLink(h,normal_tag))); } } else { #if defined(USE_OMP) #pragma omp parallel for #endif for(integer e = 0; e < LastLocalID(etype); ++e) if( isValidElement(etype,e) ) { HandleType h = ComposeHandle(etype,e); GetGeometricData(h,NORMAL,static_cast<Storage::real *>(MGetDenseLink(h,normal_tag))); } } ShowGeometricData(NORMAL,etype); } } } } } bool Cell::CheckConvexity() const {return GetMeshLink()->CheckConvexity(getFaces());} bool Mesh::CheckConvexity(const ElementArray<Face> & faces) const { if( !faces.empty() ) { std::vector<Storage::real> x(faces.size()*6,0.0); Storage::real * n = &x[faces.size()*3]; Storage::real eps = GetEpsilon(); //precompute data for all faces #if defined(USE_OMP) #pragma omp critical (reorder_edges) #endif { //collect data safely so that nobody changes it for(ElementArray<Face>::size_type j = 0; j != faces.size(); ++j) { faces[j].Centroid(&x[j*3]); faces[j].UnitNormal(&n[j*3]); } } //run comparison for(ElementArray<Face>::size_type j = 0; j != faces.size(); ++j) { Storage::real dota = 0, dots = 0, dotv, v[3] = {0.,0.,0.}; for(ElementArray<Face>::size_type m = 0; m != faces.size(); ++m) { vec_diff(&x[m*3],&x[j*3],v,3); dotv = vec_dot_product(&n[j*3],v,3); dots += dotv; dota += fabs(dotv); } if( fabs(fabs(dots) - dota) > eps ) return false; } } return true; } void Mesh::FacesOrientation(ElementArray<Face> & faces, MarkerType rev) { //can copy orientation-independent algorithm from //incident_matrix.hpp: incident_matrix::compute_measure //assume mdim is of size 3 at most if( !faces.empty() ) { if( CheckConvexity(faces) ) //simpler algorithm { std::vector<Storage::real> x(faces.size()*6); Storage::real * n = &x[faces.size()*3]; Storage::real xc[3] = {0.,0.,0.}, v[3] = {0.,0.,0.}; for(ElementArray<Face>::size_type j = 0; j != faces.size(); ++j) { faces[j].Centroid(&x[j*3]); faces[j].UnitNormal(&n[j*3]); xc[0] += x[j*3+0]; xc[1] += x[j*3+1]; xc[2] += x[j*3+2]; } xc[0] /= (Storage::real)faces.size(); xc[1] /= (Storage::real)faces.size(); xc[2] /= (Storage::real)faces.size(); for(ElementArray<Face>::size_type j = 0; j != faces.size(); ++j) { vec_diff(&x[j*3],xc,v,3); if( vec_dot_product(&n[j*3],v,3) < 0 ) { if( isPrivate(rev) ) faces[j].SetPrivateMarker(rev); else faces[j].SetMarker(rev); } } } else { Edge e0, e1, ej, en; Node e0b, e0e, e1b, e1e, ene, enb; //real was = *ret/3.0; Face cur = faces[0]; Mesh * mesh = faces.GetMeshLink(); //firstly, have to figure out orientation of each face //mark all faces, so that we can perform adjacency retrival MarkerType mrk = mesh->CreatePrivateMarker(); //MarkerType rev = mesh->CreatePrivateMarker(); //reverse orientation faces.SetPrivateMarker(mrk); //0-th face orientation is default cur->RemPrivateMarker(mrk); Node n1,n2; //to retrive edge bool reverse = false; //reverse orientation in considered face std::deque< orient_face > stack; //edge and first node and face for visiting //ElementArray<Edge> edges = cur->getEdges(); Element::adj_type const& cur_edges = mesh->LowConn(cur->GetHandle()); do { e0 = Edge(mesh, cur_edges[0]); e1 = Edge(mesh, cur_edges[1]); e0b = e0.getBeg(); e0e = e0.getEnd(); e1b = e1.getBeg(); e1e = e1.getEnd(); //figure out starting node order if (e0b == e1b || e0b == e1e) { n1 = e0e; n2 = e0b; } else { n1 = e0b; n2 = e0e; } //schedule unvisited adjacent faces for (unsigned j = 0; j < cur_edges.size(); j++) { //schedule face adjacent to considered edge ej = Edge(mesh, cur_edges[j]); en = Edge(mesh, cur_edges[(j + 1) % cur_edges.size()]); //ElementArray<Face> adjacent = edges[j]->getFaces(mrk); Element::adj_type const& adjacent = mesh->HighConn(ej->GetHandle()); for (unsigned q = 0; q < adjacent.size(); ++q) { if (mesh->GetPrivateMarker(adjacent[q], mrk)) { mesh->RemPrivateMarker(adjacent[q], mrk); stack.push_back(orient_face(ej, reverse ? n2 : n1, Face(mesh, adjacent[q]))); } } /* assert(adjacent.size() <= 1); if( !adjacent.empty() ) { adjacent.RemPrivateMarker(mrk); stack.push_back(orient_face(edges[j],reverse ? n2 : n1,adjacent[0])); } */ //update edge nodes n1 = n2; //current end is new begin //find new end enb = en.getBeg(); ene = en.getEnd(); //find new end if (n2 == enb) n2 = ene; else n2 = enb; } if( stack.empty() ) break; //get entry from stack orient_face r = stack.front(); //remove face from stack stack.pop_front(); //retrive edges for new face //edges = r.face->getEdges(); Element::adj_type const& redges = mesh->LowConn(r.face->GetHandle()); e0 = Edge(mesh, redges[0]); e1 = Edge(mesh, redges[1]); e0b = e0.getBeg(); e0e = e0.getEnd(); e1b = e1.getBeg(); e1e = e1.getEnd(); reverse = false; //figure out starting node order if (e0b == e1b || e0b == e1e) { n1 = e0e; n2 = e0b; } else { n1 = e0b; n2 = e0e; } //find out common edge orientation for(unsigned j = 0; j < redges.size(); j++) { ej = Edge(mesh, redges[j]); en = Edge(mesh, redges[(j + 1) % redges.size()]); if( ej == r.bridge ) //found the edge { //reverse ordering on this face if( r.first == n1 ) { if( isPrivate(rev) ) r.face->SetPrivateMarker(rev); else r.face->SetMarker(rev); reverse = true; } break; } //update edge nodes n1 = n2; //current end is new begin //find new end enb = en.getBeg(); ene = en.getEnd(); if (n2 == enb) n2 = ene; else n2 = enb; } } while(true); faces.RemPrivateMarker(mrk); mesh->ReleasePrivateMarker(mrk); //faces.RemPrivateMarker(rev); } } } void Mesh::GetGeometricData(HandleType e, GeometricData type, Storage::real * ret) { assert(e != InvalidHandle()); assert(ret != NULL); assert(type == MEASURE || type == CENTROID || type == BARYCENTER || type == NORMAL); ElementType etype = GetHandleElementType(e); integer edim = Element::GetGeometricDimension(GetGeometricType(e)); integer mdim = GetDimensions(); switch(type) { case MEASURE: if( HaveGeometricData(MEASURE,etype) )// && !(UpdateGeometryMarker() && GetMarker(e, UpdateGeometryMarker()))) { //if (UpdateGeometryMarker() && GetMarker(e, UpdateGeometryMarker())) RecomputeGeometricData(e); *ret = static_cast<Storage::real *>(MGetDenseLink(e,measure_tag))[0]; //~ if( isnan(*ret) || fabs(*ret) < 1e-15 ) throw -1; } else { switch(edim) { case 0: *ret = 0; break; case 1: //length of edge { ElementArray<Node> nodes = Element(this,e)->getNodes(); if( nodes.size() > 1 ) { real c[3] = {0,0,0}; real_array v0 = nodes[0].Coords(); real_array v1 = nodes[1].Coords(); vec_diff(v0.data(),v1.data(),c,mdim); *ret = vec_len(c,mdim); } else *ret = 0; //~ if( isnan(*ret) || fabs(*ret) < 1e-15 ) throw -1; break; } case 2: //area of face { ElementArray<Node> nodes = Element(this,e)->getNodes(); if( nodes.size() > 2 ) { *ret = 0; real nt[3] = { 0,0,0 }, l1[3] = { 0,0,0 }, l2[3] = { 0,0,0 }, n0[3] = { 0,0,0 };// , ss, at; real_array v0, v1, v2; v0 = nodes[0].Coords(); for(int i = 1; i < (int)nodes.size()-1; i++) { v1 = nodes[i].Coords(); v2 = nodes[i+1].Coords(); vec_diff(v1,v0,l1,mdim); vec_diff(v2,v0,l2,mdim); vec_cross_product(l1,l2,nt); for(int q = 0; q < 3; ++q) n0[q] += nt[q]*0.5; } *ret = vec_len(n0,3); //code below is not really needed /* for(int i = 1; i < (int)nodes.size()-1; i++) { v1 = nodes[i].Coords(); v2 = nodes[i+1].Coords(); vec_diff(v1,v0,l1,mdim); vec_diff(v2,v0,l2,mdim); vec_cross_product(l1,l2,nt); for(int q = 0; q < 3; ++q) nt[q] *= 0.5; ss = vec_dot_product(n0,nt,3); if( ss ) ss /= fabs(ss); at = sqrt(vec_dot_product(nt,nt,3))*ss; *ret += at; } */ if( *ret != *ret ) std::cout << "area is nan" << std::endl; *ret = fabs(*ret); } else *ret = 0; //~ if( isnan(*ret) || fabs(*ret) < 1e-15 ) throw -1; break; } case 3: //volume of cell { //bool print = false; //redo: Cell me = Cell(this,e); ElementArray<Face> faces = me->getFaces(); bool ornt = true;//!HaveGeometricData(ORIENTATION,FACE); //bool ornt = !HaveGeometricData(ORIENTATION,FACE); //bool ornt = !CheckConvexity(faces); MarkerType rev = 0; if( ornt ) { rev = CreatePrivateMarker(); FacesOrientation(faces,rev); } real vol = 0, a, at, volp; real x[3] = {0,0,0}, n0[3] = {0,0,0}, s, ss; real l1[3] = {0,0,0}, l2[3] = {0,0,0}; real nt[3] = {0,0,0}; //me.Centroid(cx); //if( print ) std::cout << "cx: " << cx[0] << " " << cx[1] << " " << cx[2] << std::endl; for(unsigned j = 0; j < faces.size(); j++) { //compute normal to face ElementArray<Node> nodes = faces[j].getNodes(); if( ornt ) s = faces[j].GetPrivateMarker(rev) ? -1.0 : 1.0; else s = faces[j].FaceOrientedOutside(me) ? 1.0 : -1.0; x[0] = x[1] = x[2] = 0; n0[0] = n0[1] = n0[2] = 0; a = 0; real_array v0 = nodes[0].Coords(), v1, v2; for(int i = 1; i < (int)nodes.size()-1; i++) { v1 = nodes[i].Coords(); v2 = nodes[i+1].Coords(); vec_diff(v1,v0,l1,mdim); vec_diff(v2,v0,l2,mdim); vec_cross_product(l1,l2,nt); for(int q = 0; q < 3; ++q) n0[q] += nt[q]*0.5; } for(int i = 1; i < (int)nodes.size()-1; i++) { v1 = nodes[i].Coords(); v2 = nodes[i+1].Coords(); vec_diff(v1,v0,l1,mdim); vec_diff(v2,v0,l2,mdim); vec_cross_product(l1,l2,nt); for(int q = 0; q < 3; ++q) nt[q] *= 0.5; ss = vec_dot_product(n0,nt,3); if( ss ) ss /= fabs(ss); at = sqrt(vec_dot_product(nt,nt,3))*ss; //same as faces[j].Barycenter(x) for(int q = 0; q < 3; ++q) x[q] += at*(v0[q]+v1[q]+v2[q])/3.0; a += at; } if( a ) { for(int q = 0; q < 3; ++q) x[q] = x[q]/a; } else Element(this,e).Centroid(x); volp = vec_dot_product(x,n0,3) / 3.0; vol += s*volp; } if( ornt ) { if( vol < 0.0 ) vol = -vol; faces.RemPrivateMarker(rev); ReleasePrivateMarker(rev); } assert(vol > 0); *ret = vol; break; } } } //~ if( isnan(*ret) || fabs(*ret) < 1e-15 ) throw -1; break; case CENTROID: if(etype == NODE ) memcpy(ret,MGetDenseLink(e,CoordsTag()),sizeof(real)*mdim); else if(HaveGeometricData(CENTROID,etype) )//&& !(UpdateGeometryMarker() && GetMarker(e, UpdateGeometryMarker()))) { //if (UpdateGeometryMarker() && GetMarker(e, UpdateGeometryMarker())) RecomputeGeometricData(e); memcpy(ret,MGetDenseLink(e,centroid_tag),sizeof(real)*mdim); } else { ElementArray<Node> nodes = Element(this,e).getNodes(); memset(ret,0,sizeof(real)*mdim); for(unsigned k = 0; k < nodes.size(); ++k) { for(int q = 0; q < mdim; ++q) ret[q] += nodes[k].Coords()[q]; } for(int q = 0; q < mdim; ++q) ret[q] /= (real)nodes.size(); } break; case BARYCENTER: if(etype == NODE ) memcpy(ret,MGetDenseLink(e,CoordsTag()),sizeof(real)*mdim); else if(HaveGeometricData(BARYCENTER,etype) )//&& !(UpdateGeometryMarker() && GetMarker(e, UpdateGeometryMarker()))) { //if (UpdateGeometryMarker() && GetMarker(e, UpdateGeometryMarker())) RecomputeGeometricData(e); memcpy(ret,MGetDenseLink(e,barycenter_tag),sizeof(real)*mdim); } else { memset(ret,0,sizeof(real)*mdim); if( edim == 1 ) { ElementArray<Node> n = Element(this,e)->getNodes(); if( n.size() == 2 ) { real_array v0 = n[0].Coords(); real_array v1 = n[1].Coords(); for(integer j = 0; j < dim; j++) ret[j] = (v0[j] + v1[j])*0.5; } else if( n.size() == 1 ) { real_array v0 = n[0].Coords(); for(integer j = 0; j < dim; j++) ret[j] = v0[j]; } } else if( edim == 2 ) { ElementArray<Node> nodes = Element(this,e)->getNodes(); if( nodes.size() > 2 ) { *ret = 0; real nt[3] = {0,0,0}, l1[3] = {0,0,0}, l2[3] = {0,0,0}; real c[3] = {0,0,0}, n0[3] = {0,0,0}, ss; real_array v0 = nodes[0].Coords(), v1, v2; for(int i = 1; i < (int)nodes.size()-1; i++) { v1 = nodes[i].Coords(); v2 = nodes[i+1].Coords(); vec_diff(v1,v0,l1,mdim); vec_diff(v2,v0,l2,mdim); vec_cross_product(l1,l2,nt); for(int q = 0; q < 3; ++q) n0[q] += nt[q]*0.5; } real a = 0, at; for(int i = 1; i < (int)nodes.size()-1; i++) { v1 = nodes[i].Coords(); v2 = nodes[i+1].Coords(); vec_diff(v1,v0,l1,mdim); vec_diff(v2,v0,l2,mdim); vec_cross_product(l1,l2,nt); for(int q = 0; q < 3; ++q) nt[q] *= 0.5; ss = vec_dot_product(n0,nt,3); if( ss ) ss /= fabs(ss); at = sqrt(vec_dot_product(nt,nt,3))*ss; for(int q = 0; q < mdim; ++q) c[q] += at*(v0[q]+v1[q]+v2[q])/3.0; a += at; } if( a ) { for(int q = 0; q < mdim; ++q) ret[q] = c[q]/a; } else Element(this,e).Centroid(ret); } } else if( edim == 3 ) { Cell me = Cell(this,e); ElementArray<Face> faces = me->getFaces(); bool ornt = true;//!HaveGeometricData(ORIENTATION,FACE); //bool ornt = !CheckConvexity(faces); //bool ornt = !HaveGeometricData(ORIENTATION,FACE); MarkerType rev = 0; if( ornt ) { rev = CreatePrivateMarker(); FacesOrientation(faces,rev); } real vol = 0, a, at, volp; real x[3] = {0,0,0}, nt[3] = {0,0,0}, s; real c[3] = { 0,0,0 };// , c2[3] = { 0,0,0 }; real n0[3] = { 0,0,0 }, ss;// , xc[3] = { 0,0,0 }; real l1[3] = {0,0,0}, l2[3] = {0,0,0}; for(unsigned j = 0; j < faces.size(); j++) { //compute normal to face ElementArray<Node> nodes = faces[j].getNodes(); if( ornt ) s = faces[j].GetPrivateMarker(rev) ? -1.0 : 1.0; else s = faces[j].FaceOrientedOutside(me) ? 1.0 : -1.0; n0[0] = n0[1] = n0[2] = 0; x[0] = x[1] = x[2] = 0; a = 0; real_array v0 = nodes[0].Coords(), v1, v2; for(int i = 1; i < (int)nodes.size()-1; i++) { v1 = nodes[i].Coords(); v2 = nodes[i+1].Coords(); vec_diff(v1,v0,l1,mdim); vec_diff(v2,v0,l2,mdim); vec_cross_product(l1,l2,nt); for(int q = 0; q < 3; ++q) n0[q] += nt[q]*0.5; } for(int i = 1; i < (int)nodes.size()-1; i++) { v1 = nodes[i].Coords(); v2 = nodes[i+1].Coords(); vec_diff(v1,v0,l1,mdim); vec_diff(v2,v0,l2,mdim); vec_cross_product(l1,l2,nt); for(int q = 0; q < 3; ++q) nt[q] *= 0.5; ss = vec_dot_product(n0,nt,3); if( ss ) ss /= fabs(ss); at = sqrt(vec_dot_product(nt,nt,3))*ss; //same as faces[j].Centroid(x) for(int q = 0; q < 3; ++q) { x[q] += at*(v0[q]+v1[q]+v2[q])/3.0; c[q] += s*nt[q]*(pow(v0[q]+v1[q],2)+pow(v1[q]+v2[q],2)+pow(v2[q]+v0[q],2))/24.0; } a += at; } if( a ) { for(int q = 0; q < 3; ++q) x[q] = x[q]/a; } else faces[j].Centroid(x); //vec_diff(xc, x, l1, mdim); //volp = s * vec_dot_product(l1, n0, 3) / 3.0; volp = s * vec_dot_product(x, n0, 3) / 3.0; //for(int q = 0; q < 3; ++q) // c[q] += 0.75 * x[q] * volp; vol += volp; } if( ornt ) { if( vol < 0.0 ) { vol = -vol; for(int q = 0; q < 3; ++q) c[q] = -c[q]; } faces.RemPrivateMarker(rev); ReleasePrivateMarker(rev); } if( vol ) { for (int q = 0; q < mdim; ++q) c[q] = c[q] / vol;// +xc[q]; //for (int q = 0; q < mdim; ++q) // c2[q] /= vol; //real c3[3] = { 0,0,0 }; for (int q = 0; q < mdim; ++q) ret[q] = c[q]; //me.Centroid(c3); //#pragma omp critical // std::cout << "c1 " << c[0] << " " << c[1] << " " << c[2] << " c2 " << c2[0] << " " << c2[1] << " " << c2[2] << " c3 " << c3[0] << " " << c3[1] << " " << c3[2] << std::endl; } else me.Centroid(ret);//for(int q = 0; q < mdim; ++q) ret[q] = cx[q]; //std::cout << ret[0] << " " << ret[1] << " " << ret[2] << std::endl; } } break; case NORMAL: { if( HaveGeometricData(NORMAL,etype) )//&& !(UpdateGeometryMarker() && GetMarker(e, UpdateGeometryMarker()))) { //if (UpdateGeometryMarker() && GetMarker(e, UpdateGeometryMarker())) RecomputeGeometricData(e); memcpy(ret,MGetDenseLink(e,normal_tag),sizeof(real)*mdim); } else { memset(ret,0,sizeof(real)*mdim); if( edim == 2 )//&& mdim == 3) { ElementArray<Node> nodes = Element(this,e)->getNodes(); real n[3] = {0,0,0}, l1[3] = {0,0,0}, l2[3] = {0,0,0}; real nt[3] = {0,0,0}; real_array v0 = nodes[0].Coords(); for(int i = 1; i < (int)nodes.size()-1; i++) { real_array v1 = nodes[i].Coords(); real_array v2 = nodes[i+1].Coords(); vec_diff(v1,v0,l1,mdim); vec_diff(v2,v0,l2,mdim); vec_cross_product(l1,l2,nt); for(int q = 0; q < 3; ++q) n[q] += nt[q]*0.5; } for(int q = 0; q < mdim; ++q) ret[q] = n[q]; } else if( edim == 1 )//&& mdim == 2 ) { ElementArray<Node> nodes = Element(this,e)->getNodes(); if( nodes.size() > 1 ) { Storage::real_array a = nodes[0].Coords(); Storage::real_array b = nodes[1].Coords(); ret[0] = b[1] - a[1]; ret[1] = a[0] - b[0]; Storage::real l = ::sqrt(ret[0]*ret[0]+ret[1]*ret[1]); if( l ) { ret[0] /= l; ret[1] /= l; } l = ::sqrt((a[0]-b[0])*(a[0]-b[0])+(a[1]-b[1])*(a[1]-b[1])); ret[0] *= l; ret[1] *= l; } } } } break; } //~ if( type == MEASURE ) //~ { //~ if( isnan(*ret) || fabs(*ret) < 1e-15 ) throw -1; //~ } } bool Element::Planarity() const { Mesh * m = GetMeshLink(); integer dim = m->GetDimensions(); if( dim < 3 ) return true; ElementArray<Node> nodes = getNodes(); if( nodes.size() <= 3 ) return true; /* ElementArray<Node>::size_type i, s = nodes.size(); Storage::real c[3] = {0,0,0}, n[3] = {0,0,0}, v[3] = {0,0,0}; getAsFace()->Normal(n); Centroid(c); for(i = 0; i < s; i++) { vec_diff(nodes[i].Coords().data(),c,v,3); if( ::fabs(vec_dot_product(v,n,3)) > m->GetEpsilon() ) return false; } */ INMOST_DATA_REAL_TYPE l1[3] = {0,0,0}, l2[3] = {0,0,0}, nt[3] = {0,0,0}, n0[3] = {0,0,0}; real_array v0, v1, v2; v0 = nodes[0].Coords(); for(int i = 1; i < (int)nodes.size()-1; i++) { v1 = nodes[i].Coords(); v2 = nodes[i+1].Coords(); vec_diff(v1,v0,l1,dim); vec_diff(v2,v0,l2,dim); vec_cross_product(l1,l2,nt); for(int q = 0; q < 3; ++q) n0[q] += nt[q]*0.5; } vec_normalize(n0,3); for(int i = 1; i < (int)nodes.size()-1; i++) { v1 = nodes[i].Coords(); v2 = nodes[i+1].Coords(); vec_diff(v1,v0,l1,dim); vec_diff(v2,v0,l2,dim); vec_cross_product(l1,l2,nt); vec_normalize(nt,3); if( fabs(fabs(vec_dot_product(n0,nt,3))-1) > m->GetEpsilon() ) return false; } return true; } bool Cell::Closure() const { adj_type & lc = GetMeshLink()->LowConn(GetHandle()); return lc.size() > 0 ? GetMeshLink()->TestClosure(lc.data(),static_cast<integer>(lc.size())) : false; } bool Face::Closure() const { adj_type & lc = GetMeshLink()->LowConn(GetHandle()); return lc.size() > 0 ? GetMeshLink()->TestClosure(lc.data(),static_cast<integer>(lc.size())) : false; } bool Element::Boundary() const { switch(GetElementType()) { case FACE: if( !getAsFace()->FrontCell().isValid() ) return true; return false; case CELL: case EDGE: case NODE: { ElementArray<Element> faces = getAdjElements(FACE); for(ElementArray<Element>::iterator it = faces.begin(); it != faces.end(); it++) if( it->Boundary() ) return true; return false; } default: return false; } return false; } std::ostream & spaces(std::ostream & out, int print) { while(print) {out << " "; print--;} return out; } bool Face::CheckNormalOrientation() const { Mesh * mesh = GetMeshLink(); //integer dim = mesh->GetDimensions(); Cell c1 = BackCell(); if( c1.isValid() ) { if( c1.CheckConvexity() ) //simpler algorithm { Storage::real xc[3] = {0.,0.,0.}; Storage::real xf[3] = {0.,0.,0.}; Storage::real nf[3] = {0.,0.,0.}; Storage::real v[3] = {0.,0.,0.}; c1.Centroid(xc); Centroid(xf); UnitNormal(nf); vec_diff(xf,xc,v,3); if( vec_dot_product(nf,v,3) < 0 ) return false; } else { MarkerType mrk = mesh->CreatePrivateMarker(); MarkerType rev = mesh->CreatePrivateMarker(); //reverse orientation Storage::real measure = 0; //ElementArray<Face> data = c1.getFaces(); Element::adj_type const& data = mesh->LowConn(c1.GetHandle()); Face cur = *this; //firstly, have to figure out orientation of each face //mark all faces, so that we can perform adjacency retrival #if defined(USE_OMP) #pragma omp critical (reorder_edges) #endif { Edge e0, e1, ej, en; Node e0b, e0e, e1b, e1e, ene, enb; //data.SetPrivateMarker(mrk); //0-th face orientation is default for (unsigned k = 0; k < data.size(); ++k) mesh->SetPrivateMarker(data[k], mrk); cur->RemPrivateMarker(mrk); Node n1,n2; //to retrive edge bool reverse = false; //reverse orientation in considered face std::deque< orient_face > stack; //edge and first node and face for visiting //ElementArray<Edge> edges; //edges = cur->getEdges(); Element::adj_type const& cur_edges = mesh->LowConn(cur->GetHandle()); do { e0 = Edge(mesh, cur_edges[0]); e1 = Edge(mesh, cur_edges[1]); e0b = e0.getBeg(); e0e = e0.getEnd(); e1b = e1.getBeg(); e1e = e1.getEnd(); //figure out starting node order if (e0b == e1b || e0b == e1e) { n1 = e0e; n2 = e0b; } else { n1 = e0b; n2 = e0e; } //schedule unvisited adjacent faces for(unsigned j = 0; j < cur_edges.size(); j++) { //schedule face adjacent to considered edge ej = Edge(mesh, cur_edges[j]); en = Edge(mesh, cur_edges[(j + 1) % cur_edges.size()]); //ElementArray<Face> adjacent = edges[j]->getFaces(mrk); Element::adj_type const& adjacent = mesh->HighConn(ej->GetHandle()); for (unsigned q = 0; q < adjacent.size(); ++q) { if (mesh->GetPrivateMarker(adjacent[q], mrk)) { mesh->RemPrivateMarker(adjacent[q], mrk); stack.push_back(orient_face(ej, reverse ? n2 : n1, Face(mesh, adjacent[q]))); } } /* assert(adjacent.size() <= 1); if( !adjacent.empty() ) { adjacent.RemPrivateMarker(mrk); stack.push_back(orient_face(edges[j],reverse ? n2 : n1,adjacent[0])); } */ //update edge nodes n1 = n2; //current end is new begin //find new end enb = en.getBeg(); ene = en.getEnd(); //find new end if (n2 == enb) n2 = ene; else n2 = enb; } if( stack.empty() ) break; //get entry from stack orient_face r = stack.front(); //remove face from stack stack.pop_front(); //retrive edges for new face //edges = r.face->getEdges(); Element::adj_type const& redges = mesh->LowConn(r.face->GetHandle()); e0 = Edge(mesh, redges[0]); e1 = Edge(mesh, redges[1]); e0b = e0.getBeg(); e0e = e0.getEnd(); e1b = e1.getBeg(); e1e = e1.getEnd(); reverse = false; //figure out starting node order if (e0b == e1b || e0b == e1e) { n1 = e0e; n2 = e0b; } else { n1 = e0b; n2 = e0e; } //find out common edge orientation for(unsigned j = 0; j < redges.size(); j++) { ej = Edge(mesh, redges[j]); en = Edge(mesh, redges[(j + 1) % redges.size()]); if( ej == r.bridge ) //found the edge { //reverse ordering on this face if( r.first == n1 ) { r.face->SetPrivateMarker(rev); reverse = true; } break; } //update edge nodes n1 = n2; //current end is new begin //find new end enb = en.getBeg(); ene = en.getEnd(); if (n2 == enb) n2 = ene; else n2 = enb; } } while(true); //data.RemPrivateMarker(mrk); for (unsigned k = 0; k < data.size(); ++k) mesh->RemPrivateMarker(data[k], mrk); mesh->ReleasePrivateMarker(mrk); Storage::real nrm[3], cnt[3]; for(unsigned j = 0; j < data.size(); j++) { Face f(mesh, data[j]); //std::cout << (data[j].GetPrivateMarker(rev) ? 0:1); //compute normal to face f.Barycenter(cnt); f.Normal(nrm); measure += (f.GetPrivateMarker(rev) ? -1.0 : 1.0)*vec_dot_product(cnt,nrm,3); } } //std::cout << "cur" << (cur->GetPrivateMarker(rev) ? 0:1) << " " << measure << " "; //bool have_rev = cur->GetPrivateMarker(rev); //data.RemPrivateMarker(rev); for (unsigned k = 0; k < data.size(); ++k) mesh->RemPrivateMarker(data[k], rev); mesh->ReleasePrivateMarker(rev); if( (measure < 0 ))// && !have_rev) || (measure > 0 && have_rev)) return false; } } return true; } bool Face::FixNormalOrientation(bool allow_swap) const { if( !CheckNormalOrientation() ) { if( allow_swap && FrontCell().isValid() ) SwapCells(); else { #if defined(USE_OMP) #pragma omp critical (reorder_edges) #endif { ReorderEdges(); //this is not thread-safe with respect to CheckNormalOrientation if( GetMeshLink()->HaveGeometricData(NORMAL,FACE) ) { real_array nrm = GetMeshLink()->RealArrayDF(GetHandle(),GetMeshLink()->GetGeometricTag(NORMAL)); for(real_array::size_type it = 0; it < nrm.size(); ++it) nrm[it] = -nrm[it]; } } } return true; } return false; } Storage::real meantri(Storage::real * v0, Storage::real * v1, Storage::real * v2, Storage::integer dim, const MeanFunc & f, Storage::real time) { Storage::real value = 0; static const Storage::real w[4] = { -0.149570044467670, 0.175615257433204, 0.053347235608839 , 0.077113760890257}; static const Storage::real a[4][3] = { {0.333333333333333,0.333333333333333,0.333333333333333}, {0.479308067841923,0.260345966079038,0.260345966079038}, {0.869739794195568,0.065130102902216,0.065130102902216}, {0.638444188569809,0.312865496004875,0.048690315425316} }; Storage::real XYG[13][3]; for (Storage::integer i = 0 ; i < dim; i++) XYG[0][i] = 0.33333333333333333333*(v0[i]+v1[i]+v2[i]); value += w[0] * f.func(XYG[0],time); for (int i = 0 ; i < 3 ; i++ ) { for (Storage::integer j = 0 ; j < dim; j++) XYG[1+i][j] = v0[j] + (v1[j] - v0[j]) * a[1][i] + (v2[j] - v0[j])*a[1][(i+1)%3]; value += w[1] * f.func(XYG[1+i],time); } for (int i = 0 ; i < 3 ; i++ ) { for (Storage::integer j = 0 ; j < dim; j++) XYG[4+i][j] = v0[j] + (v1[j] - v0[j]) * a[2][i] + (v2[j] - v0[j])*a[2][(i+1)%3]; value += w[2] * f.func(XYG[4+i],time); } for (int i = 0 ; i < 3 ; i++ ) { for (Storage::integer j = 0 ; j < dim; j++) { XYG[7+2*i][j] = v0[j] + (v1[j] - v0[j]) * a[3][i] + (v2[j] - v0[j])*a[3][(i+1)%3]; XYG[8+2*i][j] = v0[j] + (v1[j] - v0[j]) * a[3][(i+1)%3] + (v2[j] - v0[j])*a[3][i]; } value += w[3] * f.func(XYG[7+2*i],time); value += w[3] * f.func(XYG[8+2*i],time); } return value; } Storage::real meantet(Storage::real* v0, Storage::real* v1, Storage::real* v2, Storage::real* v3, const MeanFunc & f, Storage::real time) { Storage::real value; static const Storage::real T5A = 0.25, W5A = 0.11851851851852; static const Storage::real T5B = 0.09197107805272, T5C = 0.72408676584183, W5B = 0.07193708377902; static const Storage::real T5D = 0.31979362782963, T5E = 0.04061911651111; static const Storage::real W5C = 0.06906820722627; static const Storage::real T5F = 0.05635083268963, T5G = 0.44364916731037; static const Storage::real W5D = 0.05291005291005; static const Storage::real w[15] = { W5A,W5B,W5B,W5B,W5B,W5C,W5C,W5C,W5C,W5D,W5D,W5D,W5D,W5D,W5D }; Storage::real XYG[15][3]; for (int i = 0; i < 3; i++) { XYG[0][i] = T5A * (v0[i] + v1[i] + v2[i] + v3[i]); XYG[1][i] = T5C * v0[i] + T5B * (v1[i] + v2[i] + v3[i]); XYG[2][i] = T5C * v1[i] + T5B * (v0[i] + v2[i] + v3[i]); XYG[3][i] = T5C * v2[i] + T5B * (v0[i] + v1[i] + v3[i]); XYG[4][i] = T5C * v3[i] + T5B * (v0[i] + v1[i] + v2[i]); XYG[5][i] = T5E * v0[i] + T5D * (v1[i] + v2[i] + v3[i]); XYG[6][i] = T5E * v1[i] + T5D * (v0[i] + v2[i] + v3[i]); XYG[7][i] = T5E * v2[i] + T5D * (v0[i] + v1[i] + v3[i]); XYG[8][i] = T5E * v3[i] + T5D * (v0[i] + v1[i] + v2[i]); XYG[9][i] = T5F * (v0[i] + v1[i]) + T5G * (v2[i] + v3[i]); XYG[10][i] = T5G * (v0[i] + v1[i]) + T5F * (v2[i] + v3[i]); XYG[11][i] = T5F * (v0[i] + v3[i]) + T5G * (v1[i] + v2[i]); XYG[12][i] = T5G * (v0[i] + v3[i]) + T5F * (v1[i] + v2[i]); XYG[13][i] = T5F * (v0[i] + v2[i]) + T5G * (v1[i] + v3[i]); XYG[14][i] = T5G * (v0[i] + v2[i]) + T5F * (v1[i] + v3[i]); } value = 0; for (int i = 0; i < 15; i++) value += w[i] * f.func(XYG[i], time); return value; } Storage::real Element::Mean(const MeanFunc & f,Storage::real time) const { Mesh * m = GetMeshLink(); if( GetElementDimension() == 2 ) { integer dim = m->GetDimensions(); real val = 0, vol = 0, tvol,tval; real v1[3] = {0,0,0},v2[3] = {0,0,0}, product[3] = {0,0,0}; ElementArray<Node> nodes = getNodes(); real_array av0 = nodes.front().Coords(); for(ElementArray<Node>::iterator it = ++nodes.begin(); it != nodes.end(); it++) { ElementArray<Node>::iterator jt = it++; if( it == nodes.end() ) break; real_array av1 = jt->Coords(); real_array av2 = it->Coords(); tval = meantri(av0.data(),av1.data(),av2.data(),dim,f,time); vec_diff(av1.data(),av0.data(),v1,dim); vec_diff(av2.data(),av0.data(),v2,dim); vec_cross_product(v1,v2,product); tvol = sqrt(vec_dot_product(product,product,dim))*0.5; val += tval*tvol; vol += tvol; it = jt; } return val / vol; } else if( GetElementDimension() == 3 ) { ElementArray<Element> rfaces = getAdjElements(FACE); array<int> n(static_cast<array<int>::size_type>(rfaces.size())); array<real> v; int k = 0; for(ElementArray<Element>::iterator f = rfaces.begin(); f != rfaces.end(); f++) { ElementArray<Node> nodes = f->getNodes(); int nn = n[k] = static_cast<int>(nodes.size()); for(int i = 0; i < nn; i++) { real_array a = nodes[i].Coords(); v.insert(v.end(),a.begin(),a.end()); } k++; } int j = 0; real x[3] = {0,0,0}, y[3], d, vol = 0, c; for(array<int>::size_type i = 0; i < n.size(); i++) { y[0] = y[1] = y[2] = d = 0; for(array<int>::size_type k = 1; k < static_cast<array<int>::size_type>(n[i] - 1); k++) { d += c = det3v(&v[j*3],&v[(j+k)*3],&v[(j+k+1)*3]); y[0] += c * (v[j*3+0] + v[(j+k)*3+0] + v[(j+k+1)*3+0]); y[1] += c * (v[j*3+1] + v[(j+k)*3+1] + v[(j+k+1)*3+1]); y[2] += c * (v[j*3+2] + v[(j+k)*3+2] + v[(j+k+1)*3+2]); } int orient = rfaces[static_cast<ElementArray<Element>::size_type>(i)]->getAsFace()->FaceOrientedOutside(getAsCell())?1:-1; x[0] += orient*y[0]; x[1] += orient*y[1]; x[2] += orient*y[2]; vol += orient*d; j += n[i]; } x[0] /= 4.0 * vol; x[1] /= 4.0 * vol; x[2] /= 4.0 * vol; vol /= 6; j = 0; vol = 0; real tvol, tval, val = 0; real vv0[3], vv1[3], vv2[3], prod[3]; for(array<int>::size_type i = 0; i < n.size(); i++) { for(array<int>::size_type k = 1; k < static_cast<array<int>::size_type>(n[i] - 1); k++) { vec_diff(&v[j*3],x,vv0,3); vec_diff(&v[(j+k)*3],x,vv1,3); vec_diff(&v[(j+k+1)*3],x,vv2,3); vec_cross_product(vv1,vv2,prod); tvol = vec_dot_product(vv0,prod,3)/6.0 * (rfaces[static_cast<ElementArray<Element>::size_type>(i)]->getAsFace()->FaceOrientedOutside(getAsCell())?1:-1); tval = meantet(x,&v[j*3],&v[(j+k)*3],&v[(j+k+1)*3],f,time); val += tval * tvol; vol += tvol; } j+=n[i]; } return val / vol; } else if ( GetElementDimension() == 1 ) //Mean value over line. { ElementArray<Node> nodes = getNodes(); integer dim = m->GetDimensions(); real_array x1 = nodes[0].Coords(); real_array x2 = nodes[1].Coords(); real middle[3]; for (integer i = 0 ; i < dim ; i++) middle[i] = (x1[i]+x2[i])*0.5; //Simpson formula return (f.func(x1.data(),time) + 4*f.func(middle,time) + f.func(x2.data(),time))/6.0; } return 0; } const Tag & Mesh::GetGeometricTag(GeometricData type) const { switch(type) { case MEASURE: return measure_tag; case CENTROID: return centroid_tag; case BARYCENTER: return barycenter_tag; case NORMAL: return normal_tag; } assert(false); static const Tag t; //invalid tag return t; } ElementArray<Face> Mesh::GatherBoundaryFaces() { ElementArray<Face> ret(this); for(integer f = 0; f < FaceLastLocalID(); f++) if( isValidElement(FACE,f) ) { Face ef = Face(this,ComposeHandle(FACE,f)); if( ef->Boundary() ) ret.push_back(ef); } return ret; } ElementArray<Face> Mesh::GatherInteriorFaces() { ElementArray<Face> ret(this); if( GetMeshState() == Mesh::Serial ) { for(integer f = 0; f < FaceLastLocalID(); f++) if( isValidElement(FACE,f) ) { Face ef = Face(this,ComposeHandle(FACE,f)); if( ef->nbAdjElements(CELL) == 2 ) ret.push_back(ef); } } else { for(integer f = 0; f < FaceLastLocalID(); f++) if( isValidElement(FACE,f) ) { Face ef = Face(this,ComposeHandle(FACE,f)); ElementArray<Cell> cells = ef->getCells(); if( cells.size() == 2 && cells[0].GetStatus() != Element::Ghost && cells[1].GetStatus() != Element::Ghost) ret.push_back(ef); } } return ret; } Storage::integer Mesh::CountBoundaryFaces() { integer ret = 0; for(integer f = 0; f < FaceLastLocalID(); f++) if( isValidElement(FACE,f) ) { Face ef = Face(this,ComposeHandle(FACE,f)); if( ef->Boundary() ) ret++; } return ret; } Storage::integer Mesh::CountInteriorFaces() { integer ret = 0; if( GetMeshState() == Mesh::Serial ) { for(integer f = 0; f < FaceLastLocalID(); f++) if( isValidElement(FACE,f) ) { Face ef = Face(this,ComposeHandle(FACE,f)); if( ef->nbAdjElements(CELL) == 2 ) ret++; } } else { for(integer f = 0; f < FaceLastLocalID(); f++) if( isValidElement(FACE,f) ) { Face ef = Face(this,ComposeHandle(FACE,f)); ElementArray<Cell> cells = ef->getCells(); if( cells.size() == 2 && cells[0].GetStatus() != Element::Ghost && cells[1].GetStatus() != Element::Ghost) ret++; } } return ret; } void Element::CastRay(const real * pos, const real * dir, std::map<HandleType, real> & hits) const { Mesh * mm = GetMeshLink(); unsigned dim = mm->GetDimensions(); Storage::real eps = mm->GetEpsilon(); switch(GetElementType()) { case NODE: { Storage::real_array coords = getAsNode()->Coords(); Storage::real vec[3],ndir[3], lvec, ldir; for(unsigned k = 0; k < dim; k++) { vec[k] = (coords[k]-pos[k]); ndir[k] = dir[k]; } lvec = vec_normalize(vec,dim); ldir = vec_normalize(ndir,dim); if( vec_dot_product(vec,ndir,dim) >= 1.0 - eps ) hits[GetHandle()] = lvec/ldir; } break; case EDGE: { throw NotImplemented; } break; case FACE: { HandleType shr_nodes[2]; Storage::real tri[3][3]; Centroid(tri[2]); ElementArray<Node> nodes = getNodes(); memcpy(tri[0],nodes[0].Coords().data(),sizeof(Storage::real)*dim); for(ElementArray<Node>::size_type q = 0; q < nodes.size(); q++) { memcpy(tri[1],nodes[(q+1)%nodes.size()].Coords().data(),sizeof(Storage::real)*dim); Storage::real a[3],b[3],c[3],n[3], d, k, m, l; Storage::real dot00,dot01,dot02,dot11,dot12,invdenom, uq,vq; a[0] = tri[0][0] - tri[2][0]; a[1] = tri[0][1] - tri[2][1]; b[0] = tri[1][0] - tri[2][0]; b[1] = tri[1][1] - tri[2][1]; if( dim > 2 ) { a[2] = tri[0][2] - tri[2][2]; b[2] = tri[1][2] - tri[2][2]; } else a[2] = b[2] = 0; vec_cross_product(a,b,n); d = -vec_dot_product(n,tri[2],dim); m = vec_dot_product(n,dir,dim); if( !(::fabs(m) < 1.0e-25) ) { l = vec_dot_product(n,pos,dim); k = -(d + l)/m; if( k >= 0 ) { c[0] = pos[0] + k*dir[0] - tri[2][0]; c[1] = pos[1] + k*dir[1] - tri[2][1]; if( dim > 2 ) c[2] = pos[2] + k*dir[2] - tri[2][2]; else c[2] = 0; dot00 = vec_dot_product(a,a,dim); dot01 = vec_dot_product(a,b,dim); dot02 = vec_dot_product(a,c,dim); dot11 = vec_dot_product(b,b,dim); dot12 = vec_dot_product(b,c,dim); invdenom = (dot00*dot11 - dot01*dot01); uq = (dot11*dot02-dot01*dot12); vq = (dot00*dot12-dot01*dot02); //std::cout << "uq " << uq << " vq " << vq << " invdenom " << invdenom << std::endl; if( !(::fabs(invdenom) < 1.0e-25 ))//&& ::fabs(uq) >= 0.0 && ::fabs(vq) >= 0.0) ) { uq = uq/invdenom; vq = vq/invdenom; if( uq >= -eps && vq >= -eps ) { if( 1.0-(uq+vq) >= -eps ) { if( 1.0-(uq+vq) <= eps ) { shr_nodes[0] = nodes.at(q); shr_nodes[1] = nodes.at((q+1)%nodes.size()); if( uq <= eps && vq >= -eps ) hits[shr_nodes[0]] = k; else if ( uq >= -eps && vq <= eps ) hits[shr_nodes[1]] = k; else hits[mm->FindSharedAdjacency(shr_nodes,2)]= k; } else { hits[GetHandle()] = k; } break; //we shouldn't have more then one intersection } } } } } memcpy(tri[0],tri[1],sizeof(Storage::real)*dim); } } break; case CELL: { ElementArray<Face> faces = getFaces(); for(ElementArray<Face>::iterator it = faces.begin(); it != faces.end(); ++it) it->CastRay(pos,dir,hits); } break; /* case ESET: //cast ray through set of elements, probably accelerate by tree throw NotImplemented; break; case MESH: //cast ray through all elements, probably accelerate by tree throw NotImplemented; break; */ } } /// Wachspress interpolation from nodes to arbitrary point inside 2d face /// x point, should be inside face /// f 2d face /// nodes_stencil array of pairs (handle of node, interpolation coefficient) /// /// Example: /// std::map<HandleType,double> nodes_stencil; /// wachspress_2d(x, f, nodes_stencil); /// double xvalue = 0.0; /// for(std::map<HandleType,double>::const_iterator it = nodes_stencil.begin(); it != nodes_stencil.end(); ++it) /// { /// xvalue += it->second * tag_value.Real(it->first); /// } void Mesh::WachspressInterpolation2D(const real * x, const Face & f, std::map<HandleType,real> & nodes_stencil) const { ElementArray<Node> nodes = f.getNodes(); int n = (int)nodes.size(); INMOST_DATA_REAL_TYPE dx[3]; INMOST_DATA_REAL_TYPE weight_sum = 0.0; INMOST_DATA_REAL_TYPE areaface = f.Area(); bool edge_interpolation = false; int edgenode1 = -1, edgenode2 = -1; for(int i = 0; i < n && !edge_interpolation; i++) { int prev = (i+n-1)%n, next = (i+1)%n; real_array xthis = nodes[i].Coords(); vec_diff(x,xthis.data(),dx,3); real_array xprev = nodes[prev].Coords(); real_array xnext = nodes[next].Coords(); INMOST_DATA_REAL_TYPE area1 = triarea3d(x,xprev.data(),xthis.data()); edge_interpolation = area1 < GetEpsilon() * areaface; if( !edge_interpolation ) { INMOST_DATA_REAL_TYPE area2 = triarea3d(x,xthis.data(),xnext.data()); edge_interpolation = area2 < GetEpsilon() * areaface; if( !edge_interpolation ) { INMOST_DATA_REAL_TYPE area = triarea3d(xthis.data(),xprev.data(),xnext.data()); INMOST_DATA_REAL_TYPE weight = area / (area1 * area2); weight_sum += weight; nodes_stencil[nodes[i].GetHandle()] = weight; } else { edgenode1 = i; edgenode2 = next; } } else { edgenode1 = prev; edgenode2 = i; } } if( edge_interpolation ) { if( !nodes_stencil.empty() ) nodes_stencil.clear(); INMOST_DATA_REAL_TYPE v12[3], v[3], alpha; real_array x1 = nodes[edgenode1].Coords(); real_array x2 = nodes[edgenode2].Coords(); vec_diff(x2.data(),x1.data(),v12,3); vec_diff(x,x1.data(),v,3); alpha = vec_dot_product(v12,v,3) / vec_dot_product(v12,v12,3); nodes_stencil[nodes[edgenode1].GetHandle()] = 1.0 - alpha; nodes_stencil[nodes[edgenode2].GetHandle()] = alpha; } else if( weight_sum ) for(std::map<HandleType,real>::iterator it = nodes_stencil.begin(); it != nodes_stencil.end(); ++it) it->second /= weight_sum; } void Mesh::WachspressInterpolation3D(const real * x, const Cell & c, std::map<HandleType,real> & nodes_stencil) const { ElementArray<Node> nodes = c.getNodes(); int n = (int)nodes.size(); ElementArray<Face> cfaces = c.getFaces(), faces; Face swp; INMOST_DATA_REAL_TYPE weight_sum = 0; INMOST_DATA_REAL_TYPE* nrm = new INMOST_DATA_REAL_TYPE[cfaces.size() * 4]; // oriented unit normal to face INMOST_DATA_REAL_TYPE* h = nrm + 3 * cfaces.size(); for(int i = 0; i < n; i++) { INMOST_DATA_REAL_TYPE xthis[3], v[3]; nodes[i].Centroid(xthis); faces = cfaces; faces.Intersect(nodes[i].getFaces()); int nf = (int)faces.size(); INMOST_DATA_REAL_TYPE nrm_mean[3] = {0,0,0}, cross[3]; for(int j = 0; j < nf; j++) { faces[j].OrientedUnitNormal(c,nrm+3*j); for(int k = 0; k < 3; k++) nrm_mean[k] += nrm[3*j+k]; } for(int k = 0; k < 3; k++) nrm_mean[k] /= nf; // sort faces counter-clockwise relative to mean normal for(int j = 0; j < nf-1; j++) for(int k = j+1; k < nf-1; k++) { vec_cross_product(nrm+3*j, nrm+3*k, cross); if( vec_dot_product(nrm_mean,cross,3) < 0 ) { swp = faces[j]; faces[j] = faces[k]; faces[k] = swp; for(int l = 0; l < 3; l++) { cross[l] = nrm[3*j+l]; nrm[3*j+l] = nrm[3*k+l]; nrm[3*k+l] = cross[l]; } } } vec_diff(xthis,x,v,3); for(int j = 0; j < nf; j++) { h[j] = vec_dot_product(nrm+3*j,v,3); //if( h[j] < -1e-8 ) //{ //std::cerr << __FILE__ << ":" << __LINE__ << " point is outside of cell" << std::endl; //h[j] = fabs(h[j]); //} //else if(fabs(h[j]) < GetEpsilon()) // point on the face plane { INMOST_DATA_REAL_TYPE xf[3]; for(int k = 0; k < 3; k++) xf[k] = x[k] + h[j]*nrm[3*j+k]; if( !nodes_stencil.empty() ) nodes_stencil.clear(); WachspressInterpolation2D(xf,faces[j],nodes_stencil); return; } } INMOST_DATA_REAL_TYPE weight = 0.0; for(int j = 0; j < nf-2; j++) { INMOST_DATA_REAL_TYPE tet_weight = fabs(det3v(nrm+3*j, nrm+3*(j+1), nrm+3*(nf-1))) / (h[j]*h[j+1]*h[nf-1]); weight += tet_weight; } nodes_stencil[nodes[i].GetHandle()] = weight; weight_sum += weight; } //delete[] h; delete[] nrm; if( weight_sum ) for(std::map<HandleType,real>::iterator it = nodes_stencil.begin(); it != nodes_stencil.end(); ++it) it->second /= weight_sum; } void UnpackBoundary(const Tag & tag, const Element & element, const INMOST_DATA_BULK_TYPE * data, INMOST_DATA_ENUM_TYPE size) { if( size ) { const Storage::integer * recv = static_cast<const Storage::integer *>(static_cast<const void *>(data)); Storage::integer_array arr = element->IntegerArray(tag); for(INMOST_DATA_ENUM_TYPE k = 0; k < size; ++k) { if( std::find(arr.begin(),arr.end(),recv[k]) == arr.end() ) arr.push_back(recv[k]); } } } void Mesh::MarkBoundaryFaces(MarkerType boundary_marker) { if( GetProcessorsNumber() > 1 ) { Tag tag_bnd = CreateTag("CALC_BOUNDARY",DATA_INTEGER,FACE,NONE); //we need shared unique numbers on cells if( !HaveGlobalID(CELL) ) AssignGlobalID(CELL); #if defined(USE_OMP) #pragma omp parallel for #endif for(integer it = 0; it < FaceLastLocalID(); ++it) if( isValidFace(it) ) { Face face = FaceByLocalID(it); integer_array arr = face->IntegerArray(tag_bnd); ElementArray<Cell> adj = face->getCells(); for(ElementArray<Cell>::iterator jt = adj.begin(); jt != adj.end(); jt++) arr.push_back(jt->GlobalID()); } ReduceData(tag_bnd,FACE,0,UnpackBoundary); ExchangeData(tag_bnd,FACE,0); #if defined(USE_OMP) #pragma omp parallel for #endif for(integer it = 0; it < FaceLastLocalID(); ++it) if( isValidFace(it) ) { Face face = FaceByLocalID(it); assert(face->IntegerArray(tag_bnd).size() <= 2); if( face->IntegerArray(tag_bnd).size() == 1 ) face->SetMarker(boundary_marker); else face->RemMarker(boundary_marker); } DeleteTag(tag_bnd); } else //nothing to worry about { #if defined(USE_OMP) #pragma omp parallel for #endif for(integer it = 0; it < FaceLastLocalID(); ++it) if( isValidFace(it) ) { Face face = FaceByLocalID(it); if( face->Boundary() ) face->SetMarker(boundary_marker); else face->RemMarker(boundary_marker); } } } } #endif
30.397501
212
0.55909
INM-RAS
3a5ee82aa4cb530b49875f5bef8fb32fef6504df
482
cpp
C++
ArcManagedFBX/FBXLight.cpp
arcanedreams/ArcManagedFBX
ea26f00e46166c37d887a9bd0475fdf5505fc03c
[ "MIT" ]
17
2015-06-06T08:04:08.000Z
2017-08-17T04:54:47.000Z
ArcManagedFBX/FBXLight.cpp
ArcaneDreams/ArcManagedFbx
ea26f00e46166c37d887a9bd0475fdf5505fc03c
[ "MIT" ]
4
2018-01-01T19:56:16.000Z
2018-10-10T00:04:04.000Z
ArcManagedFBX/FBXLight.cpp
ArcaneDreams/ArcManagedFbx
ea26f00e46166c37d887a9bd0475fdf5505fc03c
[ "MIT" ]
7
2015-11-18T17:10:30.000Z
2017-07-06T18:12:22.000Z
#include "Stdafx.h" #include "FBXLight.h" using namespace ArcManagedFBX; ARC_DEFAULT_INTERNAL_CONSTRUCTOR_INHERIT_IMPL(FBXLight,FBXNodeAttribute,FbxLight) ARC_DEFAULT_CONSTRUCTORS_IMPL(FBXLight) void ArcManagedFBX::FBXLight::SetShadowTexture(FBXTexture^ textureInstance) { this->GetFBXLight()->SetShadowTexture(textureInstance->GetFBXTexture()); } FBXTexture^ ArcManagedFBX::FBXLight::GetShadowTexture() { return gcnew FBXTexture(this->GetFBXLight()->GetShadowTexture()); }
24.1
81
0.819502
arcanedreams
3a5f2b2d2f355edb94f4c1a7d1dc41bae4009309
625
hh
C++
skysim/onnc-cimHW/lib/op.template.hh
ONNC/ONNC-CIM
dd15eae6b22b39dcd2bff179e14ad0eda40e4338
[ "BSD-3-Clause" ]
2
2021-07-05T02:26:11.000Z
2022-01-11T10:37:20.000Z
skysim/onnc-cimHW/lib/op.template.hh
ONNC/ONNC-CIM
dd15eae6b22b39dcd2bff179e14ad0eda40e4338
[ "BSD-3-Clause" ]
null
null
null
skysim/onnc-cimHW/lib/op.template.hh
ONNC/ONNC-CIM
dd15eae6b22b39dcd2bff179e14ad0eda40e4338
[ "BSD-3-Clause" ]
1
2022-01-11T10:39:01.000Z
2022-01-11T10:39:01.000Z
//===- ${OperatorName}.hh -------------------------------------------------===// // // The CIM Hardware Simulator Project // // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #pragma once #include "hardware/ComputeUnit.hh" #include <cimHWOp.hh> namespace cimHW { class cimHW${OperatorName}Op : public cimHWOp { public: cimHW${OperatorName}Op( const std::string &configFile ${argument_list} ); virtual void simulate() final; private: // Use a compute unit ComputeUnit m_cimCU; }; } // namespace cimHW
21.551724
80
0.4992
ONNC
3a6965d0e1cfe09408521c2c6bf698cdac49447c
805
hpp
C++
csf_workspace/ec/src/device_io/ec_device_io/hi/csf_hichannel_manager.hpp
Kitty-Kitty/csf_library
011e56fb8b687818d20b9998a0cdb72332375534
[ "BSD-2-Clause" ]
2
2019-12-17T13:16:48.000Z
2019-12-17T13:16:51.000Z
csf_workspace/ec/src/device_io/ec_device_io/hi/csf_hichannel_manager.hpp
Kitty-Kitty/csf_library
011e56fb8b687818d20b9998a0cdb72332375534
[ "BSD-2-Clause" ]
null
null
null
csf_workspace/ec/src/device_io/ec_device_io/hi/csf_hichannel_manager.hpp
Kitty-Kitty/csf_library
011e56fb8b687818d20b9998a0cdb72332375534
[ "BSD-2-Clause" ]
null
null
null
/******************************************************************************* * *Copyright: armuxinxian@aliyun.com * *Author: f * *File name: csf_hichannel_manager.hpp * *Version: 1.0 * *Date: 03-12月-2019 13:50:14 * *Description: Class(csf_hichannel_manager) 表示海思媒体通道管理器 * *Others: * *History: * *******************************************************************************/ #if !defined(CSF_HICHANNEL_MANAGER_H_INCLUDED_) #define CSF_HICHANNEL_MANAGER_H_INCLUDED_ #include "csf_hichannel.hpp" #include "csf_mdmanager_template.hpp" namespace ec { namespace core { /** * 表示海思媒体通道管理器 * @author f * @version 1.0 * @created 02-12月-2019 18:38:27 */ typedef csf_mdmanager_template<csf_hichannel> csf_hichannel_manager; } } #endif // !defined(CSF_HICHANNEL_MANAGER_H_INCLUDED_)
18.72093
81
0.58882
Kitty-Kitty
3a7257b7c17bb29c7b941af4f312f385ac33bc38
5,105
hpp
C++
arbor/util/range.hpp
kanzl/arbor
86b1eb065ac252bf0026de7cf7cbc6748a528254
[ "BSD-3-Clause" ]
53
2018-10-18T12:08:21.000Z
2022-03-26T22:03:51.000Z
arbor/util/range.hpp
kanzl/arbor
86b1eb065ac252bf0026de7cf7cbc6748a528254
[ "BSD-3-Clause" ]
864
2018-10-01T08:06:00.000Z
2022-03-31T08:06:48.000Z
arbor/util/range.hpp
kanzl/arbor
86b1eb065ac252bf0026de7cf7cbc6748a528254
[ "BSD-3-Clause" ]
37
2019-03-03T16:18:49.000Z
2022-03-24T10:39:51.000Z
#pragma once /* Present a pair of iterators as a non-owning collection. * * Two public member fields, `left` and `right`, describe * the half-open interval [`left`, `right`). * * Constness of the range object only affects mutability * of the iterators, and does not relate to the constness * of the data to which the iterators refer. * * The `right` field may differ in type from the `left` field, * in which case it is regarded as a sentinel type; the end of * the interval is then marked by the first successor `i` of * `left` that satisfies `i==right`. * * For an iterator `i` and sentinel `s`, it is expected that * the tests `i==s` and `i!=s` are well defined, with the * corresponding semantics. */ #include <cstddef> #include <iterator> #include <limits> #include <stdexcept> #include <type_traits> #include <utility> #include <arbor/assert.hpp> #include "util/counter.hpp" #include "util/iterutil.hpp" #include "util/meta.hpp" #include "util/sentinel.hpp" namespace arb { namespace util { template <typename U, typename S = U> struct range { using iterator = U; using sentinel = S; using const_iterator = iterator; using difference_type = typename std::iterator_traits<iterator>::difference_type; using size_type = std::make_unsigned_t<difference_type>; using value_type = typename std::iterator_traits<iterator>::value_type; using reference = typename std::iterator_traits<iterator>::reference; using const_reference = const value_type&; iterator left; sentinel right; range() = default; range(const range&) = default; range(range&&) = default; template <typename U1, typename U2> range(U1&& l, U2&& r): left(std::forward<U1>(l)), right(std::forward<U2>(r)) {} template <typename U1, typename U2> range(const std::pair<U1, U2>& p): left(p.first), right(p.second) {} template < typename U1, typename U2, typename = std::enable_if_t< std::is_constructible<iterator, U1>::value && std::is_constructible<sentinel, U2>::value> > range(const range<U1, U2>& other): left(other.left), right(other.right) {} range& operator=(const range&) = default; range& operator=(range&&) = default; template <typename U1, typename U2> range& operator=(const range<U1, U2>& other) { left = other.left; right = other.right; return *this; } bool empty() const { return left == right; } iterator begin() const { return left; } const_iterator cbegin() const { return left; } sentinel end() const { return right; } sentinel cend() const { return right; } template <typename V = iterator> std::enable_if_t<is_forward_iterator<V>::value, size_type> size() const { return util::distance(begin(), end()); } constexpr size_type max_size() const { return std::numeric_limits<size_type>::max(); } void swap(range& other) { std::swap(left, other.left); std::swap(right, other.right); } decltype(auto) front() const { return *left; } decltype(auto) back() const { return *upto(left, right); } template <typename V = iterator> std::enable_if_t<is_random_access_iterator<V>::value, decltype(*left)> operator[](difference_type n) const { return *std::next(begin(), n); } template <typename V = iterator> std::enable_if_t<is_random_access_iterator<V>::value, decltype(*left)> at(difference_type n) const { if (size_type(n) >= size()) { throw std::out_of_range("out of range in range"); } return (*this)[n]; } // Expose `data` method if a pointer range. template <typename V = iterator, typename W = sentinel> std::enable_if_t<std::is_same<V, W>::value && std::is_pointer<V>::value, iterator> data() const { return left; } }; template <typename U, typename V> range<U, V> make_range(const U& left, const V& right) { return range<U, V>(left, right); } template <typename U, typename V> range<U, V> make_range(const std::pair<U, V>& iterators) { return range<U, V>(iterators.first, iterators.second); } // From pointer and length template <typename T> range<T, T> range_n(T t, size_t n) { return {t, t + n}; } // Present a possibly sentinel-terminated range as an STL-compatible sequence // using the sentinel_iterator adaptor. template <typename Seq> auto canonical_view(Seq&& s) { using std::begin; using std::end; return make_range( make_sentinel_iterator(begin(s), end(s)), make_sentinel_end(begin(s), end(s))); } // Strictly evaluate end point in sentinel-terminated range and present as a range over // iterators. Note: O(N) behaviour with forward iterator ranges or sentinel-terminated ranges. template <typename Seq> auto strict_view(Seq&& s) { using std::begin; using std::end; auto b = begin(s); auto e = end(s); return make_range(b, b==e? b: std::next(util::upto(b, e))); } } // namespace util } // namespace arb
28.049451
94
0.650343
kanzl
b91ac65ecaeb263d2c0b4ae98273629f72b0529e
1,411
cpp
C++
codeforces/E - Radio stations/Wrong answer on test 46.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/E - Radio stations/Wrong answer on test 46.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/E - Radio stations/Wrong answer on test 46.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Sep/22/2018 16:42 * solution_verdict: Wrong answer on test 46 language: GNU C++14 * run_time: 249 ms memory_used: 5300 KB * problem: https://codeforces.com/contest/762/problem/E ****************************************************************************************/ #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>ordered_set; const int N=1e5,R=1e9,F=1e4; int cnt;ordered_set st[F+2]; struct data { int x,r,f; }arr[N+2]; bool cmp(data A,data B) { return A.r>B.r; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n,k;cin>>n>>k; for(int i=1;i<=n;i++) cin>>arr[i].x>>arr[i].r>>arr[i].f; sort(arr+1,arr+n+1,cmp); int ans=0; for(int i=1;i<=n;i++) { for(int j=max(1,arr[i].f-k);j<=min(F,arr[i].f+k);j++) { ans+=st[j].order_of_key(arr[i].x+arr[i].r+1); ans-=st[j].order_of_key(arr[i].x-arr[i].r); } st[arr[i].f].insert(arr[i].x); } cout<<ans<<endl; return 0; }
33.595238
111
0.483345
kzvd4729
b91fe07ac54a8e5aa9941ffc92676d2d845bd5cb
498
cpp
C++
components/agro_mesh/helper/convert.cpp
thmalmeida/agro_mesh
fbce39d2e08d02495ecd3b55b2e826449b9dc3b7
[ "MIT" ]
2
2021-07-19T12:03:39.000Z
2021-07-22T18:37:45.000Z
components/agro_mesh/helper/convert.cpp
thmalmeida/agro_mesh
fbce39d2e08d02495ecd3b55b2e826449b9dc3b7
[ "MIT" ]
null
null
null
components/agro_mesh/helper/convert.cpp
thmalmeida/agro_mesh
fbce39d2e08d02495ecd3b55b2e826449b9dc3b7
[ "MIT" ]
1
2021-07-08T09:07:10.000Z
2021-07-08T09:07:10.000Z
#include "convert.hpp" #include <ctype.h> /** * Adapted from https://stackoverflow.com/a/1086059 */ long long strntoll(const char *s, std::size_t n) noexcept { long long x = 0; bool negative = false; if(n == 0) return 0; if(s[0] == '-') { s++; n--; negative = true; } else if(s[0] == '+') { s++; n--; } while(isdigit(s[0]) && n--) { x = x * 10 + (s[0] - '0'); s++; } return x * (negative ? -1 : 1); }
16.6
57
0.441767
thmalmeida
b921dc406e1a8f761320da8a89b3a9eb9e1320ba
1,257
cpp
C++
ArduinoSTL/extras/uClibc++-OriginalFiles/tests/combotest.cpp
Silmaen/ArduinoLibraries
c702234b0e11978977cf8f6fc7454452d67afa33
[ "BSD-3-Clause" ]
3
2019-08-27T02:11:00.000Z
2021-01-16T16:31:52.000Z
ArduinoSTL/extras/uClibc++-OriginalFiles/tests/combotest.cpp
Silmaen/ArduinoLibraries
c702234b0e11978977cf8f6fc7454452d67afa33
[ "BSD-3-Clause" ]
41
2019-08-28T21:32:18.000Z
2022-03-02T13:42:19.000Z
ArduinoSTL/extras/uClibc++-OriginalFiles/tests/combotest.cpp
Silmaen/ArduinoLibraries
c702234b0e11978977cf8f6fc7454452d67afa33
[ "BSD-3-Clause" ]
4
2020-03-18T16:06:17.000Z
2021-06-15T04:29:42.000Z
/* * The purpose of theses tests is to test strange combinations of code which doesn't * properly belong in a unit test. For example, does pushing an object into a vector * contained in a map work properly? That doesn't really belong in either the map * or the vector tests. So we put it here until we find some place better to put things. */ #include <iostream> #include <map> #include <string> #include <vector> #include "testframework.h" bool canInsertIntoVectorInMap() { std::map<std::string, std::vector<void *> > test; std::vector<void *> tempvec; tempvec.clear(); tempvec.push_back((void *)1); tempvec.push_back((void *)2); test["2e"] = tempvec; tempvec.clear(); tempvec.push_back((void *)1); test["1e"] = tempvec; tempvec.clear(); test["0e"] = tempvec; if( test["0e"].size() != 0 ){ return false; } if( test["1e"].size() != 1 ){ return false; } if( test["2e"].size() != 2 ){ return false; } test["2e"].push_back((void *)7); if( test["2e"].size() != 3 ){ return false; } return true; } int main() { std::cout << "Beginning combo tests" << std::endl; TestFramework::init(); TestFramework::AssertReturns<bool>(canInsertIntoVectorInMap, true); TestFramework::results(); }
19.640625
89
0.645982
Silmaen
b927b12c286d5594a0b63ed772eb9ddec7310bb3
205
cpp
C++
use-gtest/sample1/hello.cpp
lua511/draft-cxx-testing
1afa0bb8b406d38bcabce471b90decc6cf6eae65
[ "MIT" ]
null
null
null
use-gtest/sample1/hello.cpp
lua511/draft-cxx-testing
1afa0bb8b406d38bcabce471b90decc6cf6eae65
[ "MIT" ]
null
null
null
use-gtest/sample1/hello.cpp
lua511/draft-cxx-testing
1afa0bb8b406d38bcabce471b90decc6cf6eae65
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> using namespace testing; TEST(SUITE1,CASE1) { int a = 5; ASSERT_EQ(a,5); } int main(int argc, char *argv[]) { InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
20.5
34
0.64878
lua511
b929673d051e945f51f2c86d63d6953ae2e391a0
2,612
cc
C++
google/cloud/appengine/instances_client.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
80
2017-11-24T00:19:45.000Z
2019-01-25T10:24:33.000Z
google/cloud/appengine/instances_client.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
1,579
2017-11-24T01:01:21.000Z
2019-01-28T23:41:21.000Z
google/cloud/appengine/instances_client.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
51
2017-11-24T00:56:11.000Z
2019-01-18T20:35:02.000Z
// Copyright 2022 Google LLC // // 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 // // https://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. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/appengine/v1/appengine.proto #include "google/cloud/appengine/instances_client.h" #include "google/cloud/appengine/internal/instances_option_defaults.h" #include <memory> namespace google { namespace cloud { namespace appengine { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN InstancesClient::InstancesClient( std::shared_ptr<InstancesConnection> connection, Options opts) : connection_(std::move(connection)), options_(internal::MergeOptions( std::move(opts), appengine_internal::InstancesDefaultOptions( connection_->options()))) {} InstancesClient::~InstancesClient() = default; StreamRange<google::appengine::v1::Instance> InstancesClient::ListInstances( google::appengine::v1::ListInstancesRequest request, Options opts) { internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_)); return connection_->ListInstances(std::move(request)); } StatusOr<google::appengine::v1::Instance> InstancesClient::GetInstance( google::appengine::v1::GetInstanceRequest const& request, Options opts) { internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_)); return connection_->GetInstance(request); } future<StatusOr<google::appengine::v1::OperationMetadataV1>> InstancesClient::DeleteInstance( google::appengine::v1::DeleteInstanceRequest const& request, Options opts) { internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_)); return connection_->DeleteInstance(request); } future<StatusOr<google::appengine::v1::Instance>> InstancesClient::DebugInstance( google::appengine::v1::DebugInstanceRequest const& request, Options opts) { internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_)); return connection_->DebugInstance(request); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace appengine } // namespace cloud } // namespace google
39.575758
80
0.758423
sydney-munro
b93861015eb6d87ff060465ae5e2a20fab05210a
2,846
hpp
C++
src/core/kext/Classes/IOLogWrapper.hpp
gkb/Karabiner
f47307d4fc89a4c421d10157d059293c508f721a
[ "Unlicense" ]
null
null
null
src/core/kext/Classes/IOLogWrapper.hpp
gkb/Karabiner
f47307d4fc89a4c421d10157d059293c508f721a
[ "Unlicense" ]
null
null
null
src/core/kext/Classes/IOLogWrapper.hpp
gkb/Karabiner
f47307d4fc89a4c421d10157d059293c508f721a
[ "Unlicense" ]
null
null
null
#ifndef IOLOGWRAPPER_HPP #define IOLOGWRAPPER_HPP #include <IOKit/IOLib.h> #include "Config.hpp" #define IOLOG_DEBUG(...) \ { \ if (!org_pqrs_Karabiner::IOLogWrapper::suppressed()) { \ if (Config::get_debug()) { \ IOLog("org.pqrs.Karabiner --Debug-- " __VA_ARGS__); \ } \ } \ } #define IOLOG_DEBUG_POINTING(...) \ { \ if (!org_pqrs_Karabiner::IOLogWrapper::suppressed()) { \ if (Config::get_debug_pointing()) { \ IOLog("org.pqrs.Karabiner --Debug-- " __VA_ARGS__); \ } \ } \ } #define IOLOG_DEVEL(...) \ { \ if (!org_pqrs_Karabiner::IOLogWrapper::suppressed()) { \ if (Config::get_debug_devel()) { \ IOLog("org.pqrs.Karabiner --Devel-- " __VA_ARGS__); \ } \ } \ } #define IOLOG_ERROR(...) \ { \ if (!org_pqrs_Karabiner::IOLogWrapper::suppressed()) { \ IOLog("org.pqrs.Karabiner --Error-- " __VA_ARGS__); \ } \ } #define IOLOG_INFO(...) \ { \ if (!org_pqrs_Karabiner::IOLogWrapper::suppressed()) { \ IOLog("org.pqrs.Karabiner --Info-- " __VA_ARGS__); \ } \ } #define IOLOG_WARN(...) \ { \ if (!org_pqrs_Karabiner::IOLogWrapper::suppressed()) { \ IOLog("org.pqrs.Karabiner --Warn-- " __VA_ARGS__); \ } \ } // ------------------------------------------------------------ namespace org_pqrs_Karabiner { class IOLogWrapper final { public: static bool suppressed(void) { return suppressed_; } static void suppress(bool v) { suppressed_ = v; } class ScopedSuppress final { public: ScopedSuppress(void) { original = suppressed(); suppress(true); } ~ScopedSuppress(void) { suppress(original); } private: bool original; }; private: static bool suppressed_; }; } #endif
36.025316
63
0.358398
gkb
b93871cf13aad04871b67446babb813de3dcbfd4
360
hpp
C++
modules/scene_manager/include/visualization_msgs/msg/marker.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
1
2020-05-19T14:33:49.000Z
2020-05-19T14:33:49.000Z
ros2_mod_ws/install/include/visualization_msgs/msg/marker.hpp
mintforpeople/robobo-ros2-ios-port
1a5650304bd41060925ebba41d6c861d5062bfae
[ "Apache-2.0" ]
3
2019-11-14T12:20:06.000Z
2020-08-07T13:51:10.000Z
modules/scene_manager/include/visualization_msgs/msg/marker.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
// generated from rosidl_generator_cpp/resource/msg.hpp.em // generated code does not contain a copyright notice #ifndef VISUALIZATION_MSGS__MSG__MARKER_HPP_ #define VISUALIZATION_MSGS__MSG__MARKER_HPP_ #include "visualization_msgs/msg/marker__struct.hpp" #include "visualization_msgs/msg/marker__traits.hpp" #endif // VISUALIZATION_MSGS__MSG__MARKER_HPP_
32.727273
58
0.852778
Omnirobotic
b938caf65e8e0cac04e9ab866ee8e4a88a8f42c0
2,414
cpp
C++
src/tools/animatedwidget.cpp
bubapl/QupZilla
3555a92eaf864fb00cce0c325c4afef582bd2024
[ "BSD-3-Clause" ]
1
2017-05-21T15:31:02.000Z
2017-05-21T15:31:02.000Z
src/tools/animatedwidget.cpp
bubapl/QupZilla
3555a92eaf864fb00cce0c325c4afef582bd2024
[ "BSD-3-Clause" ]
null
null
null
src/tools/animatedwidget.cpp
bubapl/QupZilla
3555a92eaf864fb00cce0c325c4afef582bd2024
[ "BSD-3-Clause" ]
null
null
null
/* ============================================================ * QupZilla - WebKit based browser * Copyright (C) 2010-2012 David Rosca <nowrep@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ============================================================ */ #include "animatedwidget.h" #include <QDebug> AnimatedWidget::AnimatedWidget(const Direction &direction, int duration, QWidget* parent) : QWidget(parent) , m_widget(new QWidget(this)) , Y_SHOWN(0) , Y_HIDDEN(0) , m_direction(direction) { m_positionAni = new QPropertyAnimation(m_widget, "pos"); m_positionAni->setDuration(duration); m_heightAni = new QPropertyAnimation(this, "fixedheight"); m_heightAni->setDuration(duration); m_aniGroup = new QParallelAnimationGroup(this); m_aniGroup->addAnimation(m_positionAni); m_aniGroup->addAnimation(m_heightAni); setMaximumHeight(0); } void AnimatedWidget::startAnimation() { if (m_direction == Down) { Y_SHOWN = 0; Y_HIDDEN = -m_widget->height(); } else if (m_direction == Up) { Y_SHOWN = 0; Y_HIDDEN = 0; } m_widget->move(QPoint(m_widget->pos().x(), Y_HIDDEN)); m_positionAni->setEndValue(QPoint(m_widget->pos().x(), Y_SHOWN)); m_heightAni->setEndValue(m_widget->height()); m_aniGroup->start(); } void AnimatedWidget::hide() { m_positionAni->setEndValue(QPoint(m_widget->pos().x(), Y_HIDDEN)); m_heightAni->setEndValue(0); m_aniGroup->start(); connect(m_aniGroup, SIGNAL(finished()), this, SLOT(close())); } void AnimatedWidget::resizeEvent(QResizeEvent* event) { if (event->size().width() != m_widget->width()) { m_widget->resize(event->size().width(), m_widget->height()); } QWidget::resizeEvent(event); } AnimatedWidget::~AnimatedWidget() { }
29.802469
89
0.658658
bubapl
b93ca65b96469a57f474a835d3885129782e79d3
190
hpp
C++
src/agl/engine/mesh_instance/all.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
src/agl/engine/mesh_instance/all.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
src/agl/engine/mesh_instance/all.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
#pragma once #include "bounding_box.hpp" #include "mesh_instance.hpp" #include "mesh.hpp" #include "primitive.hpp" #include "primitives.hpp" #include "uniform.hpp" #include "upload_to.hpp"
19
28
0.757895
the-last-willy
b9435cd02e06e6ad4abcfd1a1fe4d855330928ac
196
hpp
C++
src/shell/ParseLine.hpp
amsobr/iotool
233ec320ee25c96d34332fe847663682c4aa0a91
[ "MIT" ]
null
null
null
src/shell/ParseLine.hpp
amsobr/iotool
233ec320ee25c96d34332fe847663682c4aa0a91
[ "MIT" ]
4
2022-03-13T23:07:12.000Z
2022-03-13T23:10:09.000Z
src/shell/ParseLine.hpp
amsobr/iotool
233ec320ee25c96d34332fe847663682c4aa0a91
[ "MIT" ]
null
null
null
// // Created by to on 20/02/22. // #pragma once #include <tuple> #include <rps/ArgumentList.hpp> std::tuple<std::string, std::string, rps::ArgumentList> parseLine(std::string const& line );
15.076923
92
0.683673
amsobr
b944e8331911cc7a0f6ae062ba118ea6b37dfa8d
519
cpp
C++
daily_challenge/March_LeetCoding_Challenge_2021/integerToRoman.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
1
2021-01-27T16:37:36.000Z
2021-01-27T16:37:36.000Z
daily_challenge/March_LeetCoding_Challenge_2021/integerToRoman.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
daily_challenge/March_LeetCoding_Challenge_2021/integerToRoman.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
class Solution { public: string intToRoman(int num) { vector<int> integer = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000}; vector<string> roman = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"}; int i = 12; string ans = ""; while (num > 0) { int div = num / integer[i]; num = num % integer[i]; while (div--) ans = ans + roman[i]; i--; } return ans; } };
27.315789
68
0.396917
archit-1997
b946e91a263c99eb151b46c878884a0b07d4b34f
1,475
hpp
C++
Common/interface/Variadic.hpp
NTUHEP-Tstar/ManagerUtils
2536174671e537f210c330fe739f4cf0615e735e
[ "MIT" ]
null
null
null
Common/interface/Variadic.hpp
NTUHEP-Tstar/ManagerUtils
2536174671e537f210c330fe739f4cf0615e735e
[ "MIT" ]
null
null
null
Common/interface/Variadic.hpp
NTUHEP-Tstar/ManagerUtils
2536174671e537f210c330fe739f4cf0615e735e
[ "MIT" ]
null
null
null
/******************************************************************************* * * Filename : Variadic.hpp * Description : Template functions for aiding with Variadic functions of same type * by contracting all arguments into a std::vector<T> * Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ] * *******************************************************************************/ #ifndef MANAGERUTILS_COMMON_VARIADIC_HPP #define MANAGERUTILS_COMMON_VARIADIC_HPP #include <vector> namespace mgr { /******************************************************************************* * Single Entry function *******************************************************************************/ template<typename OBJTYPE, typename ARGTYPE> std::vector<OBJTYPE> MakeVector( ARGTYPE first ); /******************************************************************************* * Multi entry argument input *******************************************************************************/ template<typename OBJTYPE, typename ARGTYPE, typename ... VARTYPE> std::vector<OBJTYPE> MakeVector( ARGTYPE first, VARTYPE ... arg ); };/* mgr */ /******************************************************************************* * Including implementation src code *******************************************************************************/ #include "ManagerUtils/Common/src/Variadic.ipp" #endif/* end of include guard: MANAGERUTILS_COMMON_VARIADIC_HPP */
39.864865
83
0.414915
NTUHEP-Tstar
b948532f7f4bc76b8ca1038f91d6fe3ca3f4e118
4,219
cpp
C++
src/tools/hldaestimator/mainHLDAEstimator.cpp
atk-/bavieca-0014
031216739b4800285af717f22f44ecda54675139
[ "Apache-2.0" ]
null
null
null
src/tools/hldaestimator/mainHLDAEstimator.cpp
atk-/bavieca-0014
031216739b4800285af717f22f44ecda54675139
[ "Apache-2.0" ]
null
null
null
src/tools/hldaestimator/mainHLDAEstimator.cpp
atk-/bavieca-0014
031216739b4800285af717f22f44ecda54675139
[ "Apache-2.0" ]
null
null
null
/*---------------------------------------------------------------------------------------------* * Copyright (C) 2012 Daniel Bolaños - www.bltek.com - Boulder Language Technologies * * * * www.bavieca.org is the website of the Bavieca Speech Recognition Toolkit * * * * 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 "CommandLineManager.h" #include "ConfigurationFeatures.h" #include "HLDAEstimator.h" #include "HMMManager.h" #include "PhoneSet.h" using namespace Bavieca; // main for the tool "hldaestimator" int main(int argc, char *argv[]) { try { // define the parameters CommandLineManager commandLineManager("hldaestimator",SYSTEM_VERSION,SYSTEM_AUTHOR,SYSTEM_DATE); commandLineManager.defineParameter("-pho","phonetic symbol set",PARAMETER_TYPE_FILE,false); commandLineManager.defineParameter("-mod","acoustic models",PARAMETER_TYPE_FILE,false); commandLineManager.defineParameter("-acc","input accumulator filelist",PARAMETER_TYPE_FILE,false); commandLineManager.defineParameter("-itt","number of iterations for transform update", PARAMETER_TYPE_INTEGER,true,"[1|100]","10"); commandLineManager.defineParameter("-itp","number of iterations for parameter update", PARAMETER_TYPE_INTEGER,true,"[1|100]","10"); commandLineManager.defineParameter("-red","dimensionality reduction",PARAMETER_TYPE_INTEGER,true,NULL,"13"); commandLineManager.defineParameter("-out","output folder",PARAMETER_TYPE_FOLDER,false); // parse the parameters if (commandLineManager.parseParameters(argc,argv) == false) { return -1; } // retrieve the parameters const char *strFilePhoneSet = commandLineManager.getParameterValue("-pho"); const char *strFileModels = commandLineManager.getParameterValue("-mod"); const char *strFileAccList = commandLineManager.getParameterValue("-acc"); int iIterationsTransformUpdate = atoi(commandLineManager.getParameterValue("-itt")); int iIterationsParameterUpdate = atoi(commandLineManager.getParameterValue("-itp")); int iDimensionalityReduction = atoi(commandLineManager.getParameterValue("-red")); const char *strFolderOutput = commandLineManager.getParameterValue("-out"); // load the phone set PhoneSet phoneSet(strFilePhoneSet); phoneSet.load(); // load the HMM-models HMMManager hmmManager(&phoneSet,HMM_PURPOSE_ESTIMATION); hmmManager.load(strFileModels); hmmManager.initializeEstimation(ACCUMULATOR_TYPE_PHYSICAL, hmmManager.getContextModelingOrderHMM(),hmmManager.getContextModelingOrderHMMCW()); // initialize the HLDA estimator HLDAEstimator hldaEstimator(&hmmManager,strFileAccList,iDimensionalityReduction, iIterationsTransformUpdate,iIterationsParameterUpdate,strFolderOutput); // do the actual estimation hldaEstimator.estimate(); } catch (ExceptionBase &e) { std::cerr << e.what() << std::endl; return -1; } return 0; }
49.635294
111
0.599668
atk-
b94f958f02afb542279fe09abdebcd1747b12eb9
354
cpp
C++
Source/HeliumRain/Quests/FlareQuestStep.cpp
fdsalbj/HeliumRain
a429db86e59e3c8d71c306a20c7abd2899a36464
[ "BSD-3-Clause" ]
2
2016-09-20T18:48:21.000Z
2021-03-30T02:42:59.000Z
Source/HeliumRain/Quests/FlareQuestStep.cpp
fdsalbj/HeliumRain
a429db86e59e3c8d71c306a20c7abd2899a36464
[ "BSD-3-Clause" ]
null
null
null
Source/HeliumRain/Quests/FlareQuestStep.cpp
fdsalbj/HeliumRain
a429db86e59e3c8d71c306a20c7abd2899a36464
[ "BSD-3-Clause" ]
null
null
null
#include "Flare.h" #include "FlareQuestStep.h" #define LOCTEXT_NAMESPACE "FlareQuestStep" /*---------------------------------------------------- Constructor ----------------------------------------------------*/ UFlareQuestStep::UFlareQuestStep(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } #undef LOCTEXT_NAMESPACE
19.666667
77
0.556497
fdsalbj
b9526e4bd7ef7aa49999b0ed06ced008710423b6
248
hh
C++
dune/grid/multiscale/exists.hh
dune-community/dune-grid-multiscale
cda095af3c472fb173717239527741439f5c0af6
[ "BSD-2-Clause" ]
1
2020-02-08T04:10:46.000Z
2020-02-08T04:10:46.000Z
dune/grid/multiscale/exists.hh
dune-community/dune-grid-multiscale
cda095af3c472fb173717239527741439f5c0af6
[ "BSD-2-Clause" ]
4
2019-05-09T08:05:19.000Z
2019-06-28T11:57:35.000Z
dune/grid/multiscale/exists.hh
pymor/dune-grid-multiscale
cda095af3c472fb173717239527741439f5c0af6
[ "BSD-2-Clause" ]
1
2020-02-08T04:10:49.000Z
2020-02-08T04:10:49.000Z
// This file is part of the dune-grid-multiscale project: // http://users.dune-project.org/projects/dune-grid-multiscale // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // I do
35.428571
78
0.741935
dune-community
b955159fc2e48505b1a4d6ef1a0e5c20564efba9
5,288
cpp
C++
warning.cpp
wisd0me/plog-converter
e534fa5873c9036f5193a28be19e1ded9738586a
[ "Apache-2.0" ]
null
null
null
warning.cpp
wisd0me/plog-converter
e534fa5873c9036f5193a28be19e1ded9738586a
[ "Apache-2.0" ]
null
null
null
warning.cpp
wisd0me/plog-converter
e534fa5873c9036f5193a28be19e1ded9738586a
[ "Apache-2.0" ]
null
null
null
// 2006-2008 (c) Viva64.com Team // 2008-2020 (c) OOO "Program Verification Systems" // 2020 (c) PVS-Studio LLC #include "warning.h" namespace PlogConverter { AnalyzerType Warning::GetType() const { const auto errorCode = GetErrorCode(); if ((errorCode >= 100 && errorCode <= 499) || errorCode == 4) { return AnalyzerType::Viva64; } else if (errorCode >= 1 && errorCode <= 99) { return AnalyzerType::Fail; } else if (errorCode >= 500 && errorCode <= 799) { return AnalyzerType::General; } else if (errorCode >= 800 && errorCode <= 999) { return AnalyzerType::Optimization; } else if (errorCode >= 1000 && errorCode <= 1999) { return AnalyzerType::General; } else if (errorCode >= 2000 && errorCode <= 2499) { return AnalyzerType::CustomerSpecific; } else if (errorCode >= 2500 && errorCode <= 2999) { return AnalyzerType::Misra; } else if (errorCode >= 3000 && errorCode <= 3999) { return AnalyzerType::General; // C# } else if (errorCode >= 6000 && errorCode <= 6999) { return AnalyzerType::General; // Java } else if (IsExternalMessage()) { return AnalyzerType::General; // External tools } return AnalyzerType::Unknown; } Warning Warning::GetDocumentationLinkMessage() { Warning docsMessage; docsMessage.code = "Help:"; docsMessage.level = 1; docsMessage.positions = { {"www.viva64.com/en/w", 1 } }; docsMessage.message = "The documentation for all analyzer warnings is available here: https://www.viva64.com/en/w/."; return docsMessage; } bool Warning::IsDocumentationLinkMessage() const { return code == "Help:"; } bool Warning::IsRenewMessage() const { return code == "Renew"; } bool Warning::IsExternalMessage() const { return code == "External"; } bool Warning::IsUpdateMessage() const { return code == "Update"; } bool Warning::IsTrialMessage() const { return code == "Trial"; } unsigned Warning::GetErrorCode() const { if ( code.empty() || code.front() != 'V' || !std::all_of(code.begin() + 1, code.end(), [](char c) { return isdigit(c); })) { return 0; } return static_cast<unsigned>(atoi(code.c_str() + 1)); } std::string Warning::GetVivaUrl() const { if (IsRenewMessage()) { return "https://www.viva64.com/en/renewal/"; } if (IsExternalMessage()) { return "https://www.viva64.com/en/w/"; } if (IsUpdateMessage()) { return "https://www.viva64.com/en/pvs-studio-download/"; } if (IsTrialMessage()) { return "https://www.viva64.com/en/pvs-studio-download/#trial_form"; } const auto errorCode = GetErrorCode(); if (errorCode != 0) { return "https://www.viva64.com/en/w/v" + LeftPad(std::to_string(errorCode), 3, '0') + '/'; } return {}; } std::string Warning::GetCWEUrl() const { if (!HasCWE()) { return {}; } return "https://cwe.mitre.org/data/definitions/" + std::to_string(cwe) + ".html"; } std::string Warning::GetCWEString() const { return cwe == 0 ? "" : CWEPrefix + std::to_string(cwe); } std::string Warning::GetMISRAString() const { return std::string(Warning::MISRACorePrefix) + misra; } std::string Warning::GetMISRAStringWithLanguagePrefix() const { if (misra.find('-') != std::string::npos) return MISRAPrefixCPlusPlus + misra; else if (misra.find('.') != std::string::npos) return MISRAPrefixC + misra; else return ""; } bool Warning::HasCWE() const { return cwe != 0; } bool Warning::HasMISRA() const { return !misra.empty(); } bool Warning::HasProjects() const { return !projects.empty(); } std::string Warning::GetLevelString() const { return GetLevelString("error", "warning", "note"); } std::string Warning::GetLevelString(const std::string &l01, const std::string &l2, const std::string &l3) const { return GetLevelString(l01, l01, l2, l3); } std::string Warning::GetLevelString(const std::string &l0, const std::string &l1, const std::string &l2, const std::string &l3) const { switch (level) { case 3: return l3; case 2: return l2; case 1: return l1; default: return l0; } } void Warning::Clear() { //TODO: *this = {}; } std::vector<unsigned> Warning::GetExtendedLines() const { if (!additionalLines.empty()) { return additionalLines; } std::vector<unsigned> res; if (positions.size() <= 1) { return res; } for (const auto &pos : positions) { if (pos.file == positions.front().file) { res.push_back(pos.line); } } return res; } const NavigationInfo &Warning::GetNavigationInfo() const { static const NavigationInfo empty; return positions.empty() ? empty : positions.front().navigation; } const std::string &Warning::GetFile() const { static const std::string empty; return positions.empty() ? empty : positions.front().file; } unsigned Warning::GetLine() const { return positions.empty() ? 0 : positions.front().line; } unsigned Warning::GetEndLine() const { return positions.empty() ? 0 : positions.front().endLine; } unsigned Warning::GetStartColumn() const { return positions.empty() ? 0 : positions.front().column; } unsigned Warning::GetEndColumn() const { return positions.empty() ? 0 : positions.front().endColumn; } }
19.954717
133
0.642587
wisd0me
b957065047f092aa6711898318ad23a7f2a0b65b
8,934
cpp
C++
CityRenderingEngine/generator/Chunk.cpp
roooodcastro/city-rendering-engine
eb0f2f948ab509baf7f5e08ec05f6eb510805eac
[ "MIT" ]
2
2021-03-13T13:33:25.000Z
2021-03-13T14:19:18.000Z
CityRenderingEngine/generator/Chunk.cpp
roooodcastro/city-rendering-engine
eb0f2f948ab509baf7f5e08ec05f6eb510805eac
[ "MIT" ]
1
2020-05-23T05:48:01.000Z
2020-05-24T08:36:06.000Z
CityRenderingEngine/generator/Chunk.cpp
roooodcastro/city-rendering-engine
eb0f2f948ab509baf7f5e08ec05f6eb510805eac
[ "MIT" ]
1
2021-03-13T13:33:33.000Z
2021-03-13T13:33:33.000Z
#include "Chunk.h" Chunk::Chunk(void) : Entity(), Resource() { this->intersections = new std::vector<Intersection*>(); this->intersections->reserve(100); this->roads = new std::vector<Road*>(); this->cityBlocks = new std::vector<CityBlock*>(); this->setRenderRadius((Chunk::CHUNK_SIZE * 1.42f) / 2.0f); this->city = nullptr; this->safeToDelete = false; this->childEntities->reserve(500); } Chunk::Chunk(const Vector2 &position, City *city) : Entity(), Resource() { this->position = Vector3(position.x + 500.0f, 0, position.y + 500.0f); this->intersections = new std::vector<Intersection*>(); this->intersections->reserve(100); this->roads = new std::vector<Road*>(); this->cityBlocks = new std::vector<CityBlock*>(); this->setRenderRadius((Chunk::CHUNK_SIZE * 1.42f) / 2.0f); this->city = city; this->safeToDelete = false; this->childEntities->reserve(500); float groundScale = ((float) Chunk::CHUNK_SIZE) / 2.0f; Vector3 groundPos = Vector3(this->position.x, this->position.y - 0.1f, this->position.z); this->ground = new Entity(groundPos, Vector3(0, 0, 0), Vector3(groundScale, 1, groundScale)); this->ground->setModel(Model::getOrCreate(MODEL_GROUND, "resources/meshes/plane.obj", false)); } Chunk::~Chunk(void) { if (intersections != nullptr) { //intersections->clear(); delete intersections; intersections = nullptr; } if (roads != nullptr) { //roads->clear(); delete roads; roads = nullptr; } if (cityBlocks != nullptr) { //cityBlocks->clear(); delete cityBlocks; cityBlocks = nullptr; } city = nullptr; } void Chunk::calculateModelMatrix(Vector3 addPos, Vector3 addRot, Vector3 addSiz, bool pDiff, bool rDiff, bool sDiff) { // A Chunk won't be rendered itself, so it does not need a modelMatrix // We only need to update its children's modelMatrix if (numChildEntities > 0) { for(auto it = childEntities->begin(); it != childEntities->end(); it++) { // We also don't pass any derived transform values, as all children will have world coordinate transforms (*it)->calculateModelMatrix(Vector3(), Vector3(), Vector3(1, 1, 1), false, false, false); } } } void Chunk::update(float millisElapsed) { calculateModelMatrix(Vector3(), Vector3(), Vector3(1, 1, 1), false, false, false); ground->update(millisElapsed); // Update the distanceToCamera if that's changed if (Naquadah::getInstance()->getCurrentScene()->getCamera()->hasChanged()) { Camera *camera = Naquadah::getInstance()->getCurrentScene()->getCamera(); Vector3 dir = position - camera->getPosition(); distanceToCamera = Vector3::dot(dir, dir); } if (numChildEntities > 0) { for (std::vector<Entity*>::iterator it = childEntities->begin(); it != childEntities->end(); it++) { (*it)->update(millisElapsed); } } } void Chunk::draw(float millisElapsed) { if (numChildEntities > 0) { Frustum *frustum = Naquadah::getInstance()->getCurrentScene()->getFrustum(); for (auto it = childEntities->begin(); it != childEntities->end(); ++it) { if (frustum->isEntityInside(*it)) { (*it)->draw(millisElapsed); } } } Texture *grass = Texture::getOrCreate(TEXTURE_GRASS, "resources/textures/grass_1.jpg", true); Naquadah::getInstance()->getCurrentScene()->useShader(Shader::getOrCreate(SHADER_LIGHT_BASIC, "resources/shaders/vertNormal.glsl", "resources/shaders/fragLight.glsl", false)); Shader *shader = Naquadah::getRenderer()->getCurrentShader(); int numFloors = -1; shader->getShaderParameter("numFloors")->setValue(&numFloors, false); shader->updateShaderParameters(false); grass->bindTexture(shader->getShaderProgram(), TEXTURE0); ground->draw(millisElapsed); } void Chunk::addIntersection(Intersection *intersection) { intersections->push_back(intersection); intersection->addChunkSharing(); addChild(intersection); } void Chunk::removeIntersection(Intersection *intersection) { auto itEnd = intersections->end(); intersections->erase(std::remove(intersections->begin(), itEnd, intersection), itEnd); intersection->removeChunkSharing(); removeChild(intersection); } bool Chunk::hasIntersection(Intersection *intersection) { auto itEnd = intersections->end(); for (auto it = intersections->begin(); it != itEnd; it++) { if (*it == intersection) return true; } return false; } void Chunk::addRoad(Road *road) { roads->push_back(road); road->addChunkSharing(); addChild(road); } void Chunk::removeRoad(Road *road) { auto itEnd = roads->end(); roads->erase(std::remove(roads->begin(), itEnd, road), itEnd); road->removeChunkSharing(); removeChild(road); } void Chunk::addCityBlock(CityBlock *cityBlock) { cityBlocks->push_back(cityBlock); cityBlock->addChunkSharing(); addChild(cityBlock); } void Chunk::removeCityBlock(CityBlock *cityBlock) { auto itEnd = cityBlocks->end(); cityBlocks->erase(std::remove(cityBlocks->begin(), itEnd, cityBlock), itEnd); cityBlock->removeChunkSharing(); removeChild(cityBlock); } Intersection *Chunk::getClosestIntersectionTo(const Vector3 &position) { auto it = intersections->begin(); auto endIt = intersections->end(); Intersection *closest = nullptr; float closestDistance = 999999.9f; for (; it != endIt; it++) { float distance = (position - (*it)->getPosition()).getLength(); if (distance < closestDistance) { closest = (*it); closestDistance = distance; } } return closest; } std::vector<Intersection*> Chunk::getClosestIntersectionsTo(Intersection *intersection, int number) { std::vector<Intersection*> orderedIntersections = std::vector<Intersection*>(); std::vector<float> distances = std::vector<float>(); auto itEnd = intersections->end(); for (auto it = intersections->begin(); it != itEnd; it++) { float distance = abs((intersection->getWorldPosition() - (*it)->getWorldPosition()).getLength()); bool inserted = false; int distancesSize = (int) distances.size(); for (int i = 0; i < distancesSize; i++) { if (distance <= distances.at(i) && distance != 0.0f) { orderedIntersections.insert(orderedIntersections.begin() + i, (*it)); distances.insert(distances.begin() + i, distance); inserted = true; break; } } if (!inserted && distance != 0.0f) { orderedIntersections.push_back((*it)); distances.push_back(distance); } } if (orderedIntersections.size() > number) { orderedIntersections.erase(orderedIntersections.begin() + number, orderedIntersections.end()); orderedIntersections.shrink_to_fit(); } return orderedIntersections; } void Chunk::load() { } void Chunk::unload() { // Unload the CityBlocks auto itEnd = cityBlocks->end(); for (auto it = cityBlocks->begin(); it != itEnd; it++) { removeChild(*it); if ((*it)->getNumChunksSharing() <= 1) { delete *it; } else { (*it)->removeChunkSharing(); } } cityBlocks->clear(); // Unload the Intersections for (auto it = intersections->begin(); it != intersections->end(); it++) { removeChild(*it); if ((*it)->getNumChunksSharing() <= 1) { (*it)->disconnectFromAll(this); delete *it; } else { (*it)->removeChunkSharing(); } } intersections->clear(); // TODO: Find and fix a small memoryleak on the chunk loading/unloading, about 4kb each 20 or so chunks // Unload the Roads for (auto it = roads->begin(); it != roads->end(); it++) { //removeChild(*it); //if (((*it)->getPointA() == nullptr || (*it)->getPointA()->getNumChunksSharing() <= 1) //&& ((*it)->getPointB() == nullptr || (*it)->getPointB()->getNumChunksSharing() <= 1)) { //delete *it; //} } roads->clear(); } void Chunk::unloadOpenGL() { auto itEnd = cityBlocks->end(); for (auto it = cityBlocks->begin(); it != itEnd; it++) { if ((*it)->getNumChunksSharing() <= 1) { (*it)->unloadOpenGL(); } } } void Chunk::saveToFile() { } std::string Chunk::getFileName() { return Chunk::getFileName(Vector2(position.x, position.z)); } bool Chunk::chunkExists(const Vector2 &position) { return FileIO::fileExists(Chunk::getFileName(position)); } Chunk *Chunk::loadChunk(const Vector2 &position, City *city) { //Chunk *chunk = new Chunk(position, city); //return chunk; return nullptr; }
35.173228
118
0.622565
roooodcastro
b95744092100f79b608aca304a277bb314f40569
7,780
cpp
C++
server/src/entities/Worm.cpp
gabyrobles93/worms-game-remake
b97781f39369f807ae8c8316f7f313353d7a2df7
[ "MIT" ]
2
2019-04-24T18:27:29.000Z
2020-04-06T17:15:34.000Z
server/src/entities/Worm.cpp
gabyrobles93/tp-final-taller
b97781f39369f807ae8c8316f7f313353d7a2df7
[ "MIT" ]
null
null
null
server/src/entities/Worm.cpp
gabyrobles93/tp-final-taller
b97781f39369f807ae8c8316f7f313353d7a2df7
[ "MIT" ]
null
null
null
#include "Worm.h" #include <iostream> Worm::Worm(std::string n, int id, int team_id, int h, b2World& world, float posX, float posY) : world(world) { b2BodyDef wormDef; wormDef.type = b2_dynamicBody; wormDef.fixedRotation = true; wormDef.allowSleep = true; wormDef.position.Set(posX, posY); b2Body* body = world.CreateBody(&wormDef); body->SetUserData(this); //b2PolygonShape wormShape; //wormShape.SetAsBox(WORM_WIDTH/2, WORM_HEIGHT/2); b2CircleShape wormShape; wormShape.m_radius = WORM_RADIUS; b2FixtureDef wormFixture; wormFixture.shape = &wormShape; wormFixture.density = WORM_DENSITY; wormFixture.friction = WORM_FRICTION; wormFixture.filter.categoryBits = WORM_PHYSIC; wormFixture.filter.maskBits = STRUCTURE_PHYSIC | WATER_PHYSIC; body->CreateFixture(&wormFixture); this->body = body; this->numFootContacts = 0; this->id = id; this->inclination = NONE; this->health = h; this->team_id = team_id; this->name = n; this->angle = 0; this->falling = false; this->mirrored = false; this->hurtInTurn = false; this->affectedByExplosion = false; this->shootedInTurn = false; this->weapon = w_null; this->direction_angle = 0; this->fallenDistance = 0; this->falled = false; } Worm::~Worm(void) { if (this->body) { this->world.DestroyBody(this->body); } } void Worm::frontJump(void) { if (this->numFootContacts <= 0) return; float factor; mirrored == true ? factor = 1.0 : factor = -1.0; float x_impulse = this->body->GetMass() * gConfiguration.WORM_FRONT_JUMP_X_IMPULSE; float y_impulse = this->body->GetMass() * gConfiguration.WORM_FRONT_JUMP_Y_IMPULSE; this->body->ApplyLinearImpulse(b2Vec2(x_impulse * factor,-y_impulse), this->body->GetWorldCenter(), true); } void Worm::backJump(void) { if (this->numFootContacts <= 0) return; float factor; mirrored == true ? factor = 1.0 : factor = -1.0; float x_impulse = this->body->GetMass() * gConfiguration.WORM_BACK_JUMP_X_IMPULSE; float y_impulse = this->body->GetMass() * gConfiguration.WORM_BACK_JUMP_Y_IMPULSE; this->body->ApplyLinearImpulse(b2Vec2(-x_impulse * factor, -y_impulse), this->body->GetWorldCenter(), true); } void Worm::moveRight(void) { if (isGrounded() && !affectedByExplosion) { b2Vec2 velocity; velocity.x = cosf(angle) * gConfiguration.WORM_SPEED; velocity.y = sinf(angle) * gConfiguration.WORM_SPEED; this->body->SetLinearVelocity(velocity); this->mirrored = true; } } void Worm::moveLeft(void) { if (isGrounded() && !affectedByExplosion) { b2Vec2 velocity; // = this->body->GetLinearVelocity(); velocity.x = cosf(angle) * -gConfiguration.WORM_SPEED; velocity.y = sinf(angle) * -gConfiguration.WORM_SPEED; this->body->SetLinearVelocity(velocity); this->mirrored = false; } } bool Worm::isMirrored(void) { return this->mirrored; } float Worm::getPosX(void) { return this->body->GetPosition().x; } float Worm::getPosY(void) { return this->body->GetPosition().y; } int Worm::getId(void) { return this->id; } int Worm::getTeam(void) { return this->team_id; } int Worm::getHealth(void) { return this->health; } std::string Worm::getName(void) { return this->name; } void Worm::addFootContact(void) { this->numFootContacts++; } void Worm::deleteFootContact(void) { this->numFootContacts--; } void Worm::shoot() { this->shootedInTurn = true; this->weapon = w_null; } void Worm::hurt(int damage) { if (this->health - damage < 0) { kill(); } else { this->health -=damage; } this->hurtInTurn = true; } bool Worm::isWalking(void) { b2Vec2 velocity = this->body->GetLinearVelocity(); return (velocity.y || velocity.x) && isGrounded(); } bool Worm::isMoving(void) { b2Vec2 velocity = this->body->GetLinearVelocity(); return velocity.y || velocity.x; //return this->wormPhysic.haveHorizontalSpeed() || this->wormPhysic.haveVerticalSpeed(); } bool Worm::isFalling(void) { b2Vec2 velocity = this->body->GetLinearVelocity(); return !isGrounded() && velocity.y;// && !jumping; } bool Worm::isGrounded(void) { return numFootContacts > 0; } bool Worm::isDead(void) { return this->health == 0; } void Worm::setAngle(float angle) { this->angle = angle; } void Worm::setFalling(bool falling) { this->falling = falling; } void Worm::update() { if (!this->isGrounded()) { if (this->falled && (getPosY() < this->fallenDistance)) { this->fallenDistance = getPosY(); } else if (!this->falled){ this->fallenDistance = getPosY(); this->falled = true; } } else if (isGrounded() && (falled)) { this->fallenDistance = getPosY() - this->fallenDistance; if (this->fallenDistance > gConfiguration.WORM_MAX_FALL_DISTANCE) { hurt(this->fallenDistance); } this->falled = false; this->fallenDistance = 0; } if (!this->body->GetLinearVelocity().x && !this->body->GetLinearVelocity().y) { this->affectedByExplosion = false; } b2Vec2 mov_speed = this->body->GetLinearVelocity(); if (round(mov_speed.x) == 0) { if (mov_speed.y > 0) { this->direction_angle = 180; return; } if (mov_speed.y < 0) { this->direction_angle = 0; return; } } if (round(mov_speed.y) == 0) { if (mov_speed.x > 0) { this->direction_angle = 90; return; } if (mov_speed.x < 0) { this->direction_angle = 270; return; } } int ang = atan(mov_speed.x/mov_speed.y) * gConfiguration.RADTODEG; // Primer cuad rante if (mov_speed.y < 0 && mov_speed.x > 0) { this->direction_angle = -ang; } // Segundo cuadrante if (mov_speed.y < 0 && mov_speed.x < 0) { this->direction_angle = 360 - ang; } // Tercer cuadrante if (mov_speed.y > 0 && mov_speed.x < 0) { this->direction_angle = 180 - ang; } // Cuarto cuadrante if (mov_speed.y > 0 && mov_speed.x > 0) { this->direction_angle = 180 - ang; } if (getPosY() > gConfiguration.WORLD_Y_LIMIT) { this->kill(); } if (normalX < 0 && normalY < 0 && !mirrored) { this->inclination = DOWN; } else if (normalX > 0 && normalY < 0 && !mirrored) { this->inclination = UP; } else if (normalX < 0 && normalY < 0 && mirrored) { this->inclination = UP; } else if (normalX > 0 && normalY < 0 && mirrored) { this->inclination = DOWN; } else this->inclination = NONE; } bool Worm::isAffectedByExplosion() { return this->affectedByExplosion; } void Worm::setAffectedByExplosion(){ this->affectedByExplosion = true; } void Worm::kill() { this->health = 0; this->hurtInTurn = true; } void Worm::refreshByNewTurn(void) { this->hurtInTurn = false; this->shootedInTurn = false; } bool Worm::gotHurtInTurn(void) { return this->hurtInTurn; } bool Worm::didShootInTurn(void) { return this->shootedInTurn; } void Worm::setPosition(float posX, float posY) { this->body->SetTransform(b2Vec2(posX, posY), this->body->GetAngle()); this->body->SetAwake(true); } void Worm::setNormal(b2Vec2 normal) { this->normalX = normal.x; this->normalY = normal.y; } worm_inclination_t Worm::getInclination() { return this->inclination; } int Worm::getDirectionAngle() { return this->direction_angle; } void Worm::pickWeapon(weapon_t weapon) { this->weapon = weapon; }
25.25974
112
0.619537
gabyrobles93
b95a14ef1fbe506a4ee0ba9add9273d2ab640531
2,050
cpp
C++
Tetris/Tetris/Source/SceneIntro.cpp
punto16/Project1-NosusStudio
3f0f4356d49bd0c78061febec4c1c892c21a5610
[ "MIT" ]
null
null
null
Tetris/Tetris/Source/SceneIntro.cpp
punto16/Project1-NosusStudio
3f0f4356d49bd0c78061febec4c1c892c21a5610
[ "MIT" ]
null
null
null
Tetris/Tetris/Source/SceneIntro.cpp
punto16/Project1-NosusStudio
3f0f4356d49bd0c78061febec4c1c892c21a5610
[ "MIT" ]
null
null
null
#include "SceneIntro.h" #include "Application.h" #include "ModuleTextures.h" #include "ModuleRender.h" #include "ModuleAudio.h" #include "ModuleInput.h" #include "ModuleFadeToBlack.h" SceneIntro::SceneIntro(bool startEnabled) : Module(startEnabled) { } SceneIntro::~SceneIntro() { } // Load assets bool SceneIntro::Start() { LOG("Loading background assets"); bool ret = true; bgTexture = App->textures->Load("Assets/Sprites/sprite_title.png"); introTexture = App->textures->Load("Assets/Sprites/PreTitle.png"); App->audio->PlayMusic("", 1.0f); App->render->camera.x = 0; App->render->camera.y = 0; return ret; } Update_Status SceneIntro::Update() { if ((!play_intro) && (App->input->keys[SDL_SCANCODE_SPACE] == Key_State::KEY_DOWN)) { App->fade->FadeToBlack(this, (Module*)App->sceneMenu, 90); } else if ((!play_intro)&&(App->input->keys[SDL_SCANCODE_ESCAPE] == Key_State::KEY_DOWN)) { return Update_Status::UPDATE_STOP; } else if ((play_intro) && (App->input->keys[SDL_SCANCODE_SPACE] == Key_State::KEY_DOWN)) { uint tex_w, tex_h; App->textures->GetTextureSize(introTexture, tex_w, tex_h); App->render->camera.y = ((tex_h - SCREEN_HEIGHT) * SCREEN_SIZE); } return Update_Status::UPDATE_CONTINUE; } // Update: draw background Update_Status SceneIntro::PostUpdate() { // Draw everything -------------------------------------- uint tex_w, tex_h; App->textures->GetTextureSize(introTexture, tex_w, tex_h); int camera = ((App->render->camera.y / SCREEN_SIZE) + SCREEN_HEIGHT); if (camera == tex_h) { counter--; } else { App->render->camera.y++; } if (counter == 0) { play_intro = false; } if (play_intro) { App->render->Blit(introTexture, 0, 0, NULL); } else { App->render->camera.y = 0; App->render->Blit(bgTexture, 0, 0, NULL); } return Update_Status::UPDATE_CONTINUE; } bool SceneIntro::CleanUp() { LOG("Deleting background assets"); App->textures->Unload(bgTexture); return true; }
22.043011
89
0.647317
punto16
b95d0435e803f9fbfea9bb82612cea37210199a4
665
cpp
C++
test/zisa/unit_test/io/colors.cpp
1uc/ZisaFVM
75fcedb3bece66499e011228a39d8a364b50fd74
[ "MIT" ]
null
null
null
test/zisa/unit_test/io/colors.cpp
1uc/ZisaFVM
75fcedb3bece66499e011228a39d8a364b50fd74
[ "MIT" ]
null
null
null
test/zisa/unit_test/io/colors.cpp
1uc/ZisaFVM
75fcedb3bece66499e011228a39d8a364b50fd74
[ "MIT" ]
1
2021-08-24T11:52:51.000Z
2021-08-24T11:52:51.000Z
// SPDX-License-Identifier: MIT // Copyright (c) 2021 ETH Zurich, Luc Grosheintz-Laval #include <zisa/testing/testing_framework.hpp> #include <random> #include <zisa/io/colors.hpp> TEST_CASE("Color Conversions") { zisa::RGBColor rgb{0.3, 0.1, 0.4}; auto xyz = zisa::rgb2xyz(rgb); float tol = 1e-4; SECTION("RGB <-> XYZ") { auto approx = xyz2rgb(rgb2xyz(rgb)); REQUIRE(almost_equal(rgb, approx, tol)); } SECTION("XYZ <-> LAB") { auto approx = lab2xyz(xyz2lab(xyz)); REQUIRE(almost_equal(xyz, approx, tol)); } SECTION("RGB <-> LAB") { auto approx = lab2rgb(rgb2lab(rgb)); REQUIRE(almost_equal(rgb, approx, tol)); } }
21.451613
54
0.645113
1uc
b95d14c044f689e6483dfe36518438bf04eb6d91
5,998
cpp
C++
src/ripple/shamap/impl/SHAMapTreeNode.cpp
BRTNetwork/brtd
5bda54d04a669bfbe4cfd4bb5399d56caeaf5a1a
[ "BSL-1.0" ]
null
null
null
src/ripple/shamap/impl/SHAMapTreeNode.cpp
BRTNetwork/brtd
5bda54d04a669bfbe4cfd4bb5399d56caeaf5a1a
[ "BSL-1.0" ]
null
null
null
src/ripple/shamap/impl/SHAMapTreeNode.cpp
BRTNetwork/brtd
5bda54d04a669bfbe4cfd4bb5399d56caeaf5a1a
[ "BSL-1.0" ]
null
null
null
//------------------------------------------------------------------------------ /* This file is part of brtd: https://github.com/BRTNetwork/brtd Copyright (c) 2012, 2013 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <ripple/basics/Log.h> #include <ripple/basics/Slice.h> #include <ripple/basics/contract.h> #include <ripple/basics/safe_cast.h> #include <ripple/beast/core/LexicalCast.h> #include <ripple/protocol/HashPrefix.h> #include <ripple/protocol/digest.h> #include <ripple/shamap/SHAMapAccountStateLeafNode.h> #include <ripple/shamap/SHAMapInnerNode.h> #include <ripple/shamap/SHAMapLeafNode.h> #include <ripple/shamap/SHAMapTreeNode.h> #include <ripple/shamap/SHAMapTxLeafNode.h> #include <ripple/shamap/SHAMapTxPlusMetaLeafNode.h> #include <mutex> #include <openssl/sha.h> namespace ripple { std::shared_ptr<SHAMapTreeNode> SHAMapTreeNode::makeTransaction( Slice data, SHAMapHash const& hash, bool hashValid) { // FIXME: using a Serializer results in a copy; avoid it? Serializer s(data.begin(), data.size()); auto item = std::make_shared<SHAMapItem const>( sha512Half(HashPrefix::transactionID, data), s); if (hashValid) return std::make_shared<SHAMapTxLeafNode>(std::move(item), 0, hash); return std::make_shared<SHAMapTxLeafNode>(std::move(item), 0); } std::shared_ptr<SHAMapTreeNode> SHAMapTreeNode::makeTransactionWithMeta( Slice data, SHAMapHash const& hash, bool hashValid) { Serializer s(data.data(), data.size()); uint256 tag; if (s.size() < tag.bytes) Throw<std::runtime_error>("Short TXN+MD node"); // FIXME: improve this interface so that the above check isn't needed if (!s.getBitString(tag, s.size() - tag.bytes)) Throw<std::out_of_range>( "Short TXN+MD node (" + std::to_string(s.size()) + ")"); s.chop(tag.bytes); auto item = std::make_shared<SHAMapItem const>(tag, s.peekData()); if (hashValid) return std::make_shared<SHAMapTxPlusMetaLeafNode>( std::move(item), 0, hash); return std::make_shared<SHAMapTxPlusMetaLeafNode>(std::move(item), 0); } std::shared_ptr<SHAMapTreeNode> SHAMapTreeNode::makeAccountState( Slice data, SHAMapHash const& hash, bool hashValid) { Serializer s(data.data(), data.size()); uint256 tag; if (s.size() < tag.bytes) Throw<std::runtime_error>("short AS node"); // FIXME: improve this interface so that the above check isn't needed if (!s.getBitString(tag, s.size() - tag.bytes)) Throw<std::out_of_range>( "Short AS node (" + std::to_string(s.size()) + ")"); s.chop(tag.bytes); if (tag.isZero()) Throw<std::runtime_error>("Invalid AS node"); auto item = std::make_shared<SHAMapItem const>(tag, s.peekData()); if (hashValid) return std::make_shared<SHAMapAccountStateLeafNode>( std::move(item), 0, hash); return std::make_shared<SHAMapAccountStateLeafNode>(std::move(item), 0); } std::shared_ptr<SHAMapTreeNode> SHAMapTreeNode::makeFromWire(Slice rawNode) { if (rawNode.empty()) return {}; auto const type = rawNode[rawNode.size() - 1]; rawNode.remove_suffix(1); bool const hashValid = false; SHAMapHash const hash; if (type == wireTypeTransaction) return makeTransaction(rawNode, hash, hashValid); if (type == wireTypeAccountState) return makeAccountState(rawNode, hash, hashValid); if (type == wireTypeInner) return SHAMapInnerNode::makeFullInner(rawNode, hash, hashValid); if (type == wireTypeCompressedInner) return SHAMapInnerNode::makeCompressedInner(rawNode); if (type == wireTypeTransactionWithMeta) return makeTransactionWithMeta(rawNode, hash, hashValid); Throw<std::runtime_error>( "wire: Unknown type (" + std::to_string(type) + ")"); } std::shared_ptr<SHAMapTreeNode> SHAMapTreeNode::makeFromPrefix(Slice rawNode, SHAMapHash const& hash) { if (rawNode.size() < 4) Throw<std::runtime_error>("prefix: short node"); // FIXME: Use SerialIter::get32? // Extract the prefix auto const type = safe_cast<HashPrefix>( (safe_cast<std::uint32_t>(rawNode[0]) << 24) + (safe_cast<std::uint32_t>(rawNode[1]) << 16) + (safe_cast<std::uint32_t>(rawNode[2]) << 8) + (safe_cast<std::uint32_t>(rawNode[3]))); rawNode.remove_prefix(4); bool const hashValid = true; if (type == HashPrefix::transactionID) return makeTransaction(rawNode, hash, hashValid); if (type == HashPrefix::leafNode) return makeAccountState(rawNode, hash, hashValid); if (type == HashPrefix::innerNode) return SHAMapInnerNode::makeFullInner(rawNode, hash, hashValid); if (type == HashPrefix::txNode) return makeTransactionWithMeta(rawNode, hash, hashValid); Throw<std::runtime_error>( "prefix: unknown type (" + std::to_string(safe_cast<std::underlying_type_t<HashPrefix>>(type)) + ")"); } std::string SHAMapTreeNode::getString(const SHAMapNodeID& id) const { return to_string(id); } } // namespace ripple
31.07772
80
0.662554
BRTNetwork
b95f56845e6dbd38fe62e8d104576f39856b0518
1,629
cpp
C++
pysim/systems/defaultsystemcollection1/cppsource/PredatorPrey.cpp
sspasweden/pysim
474e71933e7e639e9aff68844ae27e7c7ab5aa01
[ "BSD-3-Clause" ]
3
2019-10-31T14:08:17.000Z
2020-02-08T15:44:45.000Z
pysim/systems/defaultsystemcollection1/cppsource/PredatorPrey.cpp
sspasweden/pysim
474e71933e7e639e9aff68844ae27e7c7ab5aa01
[ "BSD-3-Clause" ]
4
2019-10-31T14:07:43.000Z
2020-06-01T07:56:44.000Z
pysim/systems/defaultsystemcollection1/cppsource/PredatorPrey.cpp
sspasweden/pysim
474e71933e7e639e9aff68844ae27e7c7ab5aa01
[ "BSD-3-Clause" ]
null
null
null
#include "PredatorPrey.h" #include "factory.hpp" std::string PredatorPrey::getDocs(){ return std::string( "System representing the Predator Prey equations for population dynamics\n\n" "The predator-prey equations, are a pair of first order, " "non-linear, differential equations frequently used to describe the " "dynamics of biological systems in which two species interact, one as " "a predator and the other as prey. The populations change through time " "according to the pair of equations :" "$$\\\\frac{dx}{dt} = x(\\\\alpha-\\\\beta y)$$\n" "$$\\\\frac{dy}{dt} = -y(\\\\gamma-\\\\delta x)$$\n" "where x is the number of prey, y is the number of predators, and alpha, " "beta, gamme, delta are parameters describing the interaction.\n\n" "For further information see: http://en.wikipedia.org/wiki/Lotka%E2%80%93Volterra_equation" ); } PredatorPrey::PredatorPrey(void) { INPUT(alfa,"Exponential growth constant") INPUT(beta, "Constand for rate of predation upon prey") INPUT(gamma, "Loss rate of predators") INPUT(delta,"Growth constant for predator population") INPUT(x0, "Initial prey population") INPUT(y0, "Initial predator population") STATE(x,dx,"Number of Prey") STATE(y,dy, "Number of Predators") x0 = 1; //number of animals of type X y0 = 2; //number of animals of type Y alfa = 1.5; beta = 1; gamma = 3; delta = 1; } void PredatorPrey::doStep(double time){ dx = x*(alfa-beta*y); dy = -y*(gamma-delta*x); } REGISTER_SYSTEM(PredatorPrey);
33.244898
99
0.646409
sspasweden
b96a7745a8ea69c039b0169036423da0c3d25547
13,575
cpp
C++
src/Externals/log4cpp/src/PropertyConfiguratorImpl.cpp
benjaminlarson/SCIRunGUIPrototype
ed34ee11cda114e3761bd222a71a9f397517914d
[ "Unlicense" ]
null
null
null
src/Externals/log4cpp/src/PropertyConfiguratorImpl.cpp
benjaminlarson/SCIRunGUIPrototype
ed34ee11cda114e3761bd222a71a9f397517914d
[ "Unlicense" ]
null
null
null
src/Externals/log4cpp/src/PropertyConfiguratorImpl.cpp
benjaminlarson/SCIRunGUIPrototype
ed34ee11cda114e3761bd222a71a9f397517914d
[ "Unlicense" ]
null
null
null
/* * PropertyConfiguratorImpl.cpp * * Copyright 2002, Log4cpp Project. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #include "PortabilityImpl.hh" #ifdef LOG4CPP_HAVE_UNISTD_H #include <unistd.h> #endif #ifdef LOG4CPP_HAVE_IO_H # include <io.h> #endif #include <iostream> #include <string> #include <fstream> #include <log4cpp/Category.hh> // appenders #include <log4cpp/Appender.hh> #include <log4cpp/OstreamAppender.hh> #include <log4cpp/FileAppender.hh> #include <log4cpp/RollingFileAppender.hh> #include <log4cpp/AbortAppender.hh> #ifdef WIN32 #include <log4cpp/Win32DebugAppender.hh> #include <log4cpp/NTEventLogAppender.hh> #endif #include <log4cpp/RemoteSyslogAppender.hh> #ifdef LOG4CPP_HAVE_LIBIDSA #include <log4cpp/IdsaAppender.hh> #endif // LOG4CPP_HAVE_LIBIDSA #ifdef LOG4CPP_HAVE_SYSLOG #include <log4cpp/SyslogAppender.hh> #endif // layouts #include <log4cpp/Layout.hh> #include <log4cpp/BasicLayout.hh> #include <log4cpp/SimpleLayout.hh> #include <log4cpp/PatternLayout.hh> #include <log4cpp/Priority.hh> #include <log4cpp/NDC.hh> #include <list> #include <vector> #include <iterator> #include "PropertyConfiguratorImpl.hh" #include "StringUtil.hh" namespace log4cpp { PropertyConfiguratorImpl::PropertyConfiguratorImpl() { } PropertyConfiguratorImpl::~PropertyConfiguratorImpl() { } void PropertyConfiguratorImpl::doConfigure(const std::string& initFileName) throw (ConfigureFailure) { std::ifstream initFile(initFileName.c_str()); if (!initFile) { throw ConfigureFailure(std::string("File ") + initFileName + " does not exist"); } doConfigure(initFile); } void PropertyConfiguratorImpl::doConfigure(std::istream& in) throw (ConfigureFailure) { // parse the file to get all of the configuration _properties.load(in); instantiateAllAppenders(); // get categories std::vector<std::string> catList; getCategories(catList); // configure each category for(std::vector<std::string>::const_iterator iter = catList.begin(); iter != catList.end(); ++iter) { configureCategory(*iter); } } void PropertyConfiguratorImpl::instantiateAllAppenders() throw(ConfigureFailure) { std::string currentAppender; std::string prefix("appender"); Properties::const_iterator from = _properties.lower_bound(prefix + '.'); Properties::const_iterator to = _properties.lower_bound(prefix + '/'); for(Properties::const_iterator i = from; i != to; ++i) { const std::string& key = (*i).first; const std::string& value = (*i).second; std::list<std::string> propNameParts; std::back_insert_iterator<std::list<std::string> > pnpIt(propNameParts); StringUtil::split(pnpIt, key, '.'); std::list<std::string>::const_iterator i2 = propNameParts.begin(); std::list<std::string>::const_iterator iEnd = propNameParts.end(); if (++i2 == iEnd) { throw ConfigureFailure(std::string("missing appender name")); } const std::string appenderName = *i2++; /* WARNING, approaching lame code section: skipping of the Appenders properties only to get them again in instantiateAppender. */ if (appenderName == currentAppender) { // simply skip properties for the current appender } else { if (i2 == iEnd) { // a new appender currentAppender = appenderName; _allAppenders[currentAppender] = instantiateAppender(currentAppender); } else { throw ConfigureFailure(std::string("partial appender definition : ") + key); } } } } void PropertyConfiguratorImpl::configureCategory(const std::string& categoryName) throw (ConfigureFailure) { // start by reading the "rootCategory" key std::string tempCatName = (categoryName == "rootCategory") ? categoryName : "category." + categoryName; Properties::iterator iter = _properties.find(tempCatName); if (iter == _properties.end()) throw ConfigureFailure(std::string("Unable to find category: ") + tempCatName); // need to get the root instance of the category Category& category = (categoryName == "rootCategory") ? Category::getRoot() : Category::getInstance(categoryName); std::list<std::string> tokens; std::back_insert_iterator<std::list<std::string> > tokIt(tokens); StringUtil::split(tokIt, (*iter).second, ','); std::list<std::string>::const_iterator i = tokens.begin(); std::list<std::string>::const_iterator iEnd = tokens.end(); Priority::Value priority = Priority::NOTSET; if (i != iEnd) { std::string priorityName = StringUtil::trim(*i++); try { if (priorityName != "") { priority = Priority::getPriorityValue(priorityName); } } catch(std::invalid_argument& e) { throw ConfigureFailure(std::string(e.what()) + " for category '" + categoryName + "'"); } } category.setPriority(priority); bool additive = _properties.getBool("additivity." + categoryName, true); category.setAdditivity(additive); category.removeAllAppenders(); for(/**/; i != iEnd; ++i) { std::string appenderName = StringUtil::trim(*i); AppenderMap::const_iterator appIt = _allAppenders.find(appenderName); if (appIt == _allAppenders.end()) { // appender not found; throw ConfigureFailure(std::string("Appender '") + appenderName + "' not found for category '" + categoryName + "'"); } else { /* pass by reference, i.e. don't transfer ownership */ category.addAppender(*((*appIt).second)); } } } Appender* PropertyConfiguratorImpl::instantiateAppender(const std::string& appenderName) { Appender* appender = NULL; std::string appenderPrefix = std::string("appender.") + appenderName; // determine the type by the appenderName Properties::iterator key = _properties.find(appenderPrefix); if (key == _properties.end()) throw ConfigureFailure(std::string("Appender '") + appenderName + "' not defined"); std::string::size_type length = (*key).second.find_last_of("."); std::string appenderType = (length == std::string::npos) ? (*key).second : (*key).second.substr(length+1); // and instantiate the appropriate object if (appenderType == "ConsoleAppender") { appender = new OstreamAppender(appenderName, &std::cout); } else if (appenderType == "FileAppender") { std::string fileName = _properties.getString(appenderPrefix + ".fileName", "foobar"); bool append = _properties.getBool(appenderPrefix + ".append", true); appender = new FileAppender(appenderName, fileName, append); } else if (appenderType == "RollingFileAppender") { std::string fileName = _properties.getString(appenderPrefix + ".fileName", "foobar"); size_t maxFileSize = _properties.getInt(appenderPrefix + ".maxFileSize", 10*1024*1024); int maxBackupIndex = _properties.getInt(appenderPrefix + ".maxBackupIndex", 1); bool append = _properties.getBool(appenderPrefix + ".append", true); appender = new RollingFileAppender(appenderName, fileName, maxFileSize, maxBackupIndex, append); } else if (appenderType == "SyslogAppender") { std::string syslogName = _properties.getString(appenderPrefix + ".syslogName", "syslog"); std::string syslogHost = _properties.getString(appenderPrefix + ".syslogHost", "localhost"); int facility = _properties.getInt(appenderPrefix + ".facility", -1) * 8; // * 8 to get LOG_KERN, etc. compatible values. int portNumber = _properties.getInt(appenderPrefix + ".portNumber", -1); appender = new RemoteSyslogAppender(appenderName, syslogName, syslogHost, facility, portNumber); } #ifdef LOG4CPP_HAVE_SYSLOG else if (appenderType == "LocalSyslogAppender") { std::string syslogName = _properties.getString(appenderPrefix + ".syslogName", "syslog"); int facility = _properties.getInt(appenderPrefix + ".facility", -1) * 8; // * 8 to get LOG_KERN, etc. compatible values. appender = new SyslogAppender(appenderName, syslogName, facility); } #endif // LOG4CPP_HAVE_SYSLOG else if (appenderType == "AbortAppender") { appender = new AbortAppender(appenderName); } #ifdef LOG4CPP_HAVE_LIBIDSA else if (appenderType == "IdsaAppender") { // default idsa name ??? std::string idsaName = _properties.getString(appenderPrefix + ".idsaName", "foobar"); appender = new IdsaAppender(appenderName, idsaname); } #endif // LOG4CPP_HAVE_LIBIDSA #ifdef WIN32 // win32 debug appender else if (appenderType == "Win32DebugAppender") { appender = new Win32DebugAppender(appenderName); } // win32 NT event log appender else if (appenderType == "NTEventLogAppender") { std::string source = _properties.getString(appenderPrefix + ".source", "foobar"); appender = new NTEventLogAppender(appenderName, source); } #endif // WIN32 else { throw ConfigureFailure(std::string("Appender '") + appenderName + "' has unknown type '" + appenderType + "'"); } if (appender->requiresLayout()) { setLayout(appender, appenderName); } // set threshold std::string thresholdName = _properties.getString(appenderPrefix + ".threshold", ""); try { if (thresholdName != "") { appender->setThreshold(Priority::getPriorityValue(thresholdName)); } } catch(std::invalid_argument& e) { delete appender; // fix for #3109495 throw ConfigureFailure(std::string(e.what()) + " for threshold of appender '" + appenderName + "'"); } return appender; } void PropertyConfiguratorImpl::setLayout(Appender* appender, const std::string& appenderName) { // determine the type by appenderName std::string tempString; Properties::iterator key = _properties.find(std::string("appender.") + appenderName + ".layout"); if (key == _properties.end()) throw ConfigureFailure(std::string("Missing layout property for appender '") + appenderName + "'"); std::string::size_type length = (*key).second.find_last_of("."); std::string layoutType = (length == std::string::npos) ? (*key).second : (*key).second.substr(length+1); Layout* layout; // and instantiate the appropriate object if (layoutType == "BasicLayout") { layout = new BasicLayout(); } else if (layoutType == "SimpleLayout") { layout = new SimpleLayout(); } else if (layoutType == "PatternLayout") { // need to read the properties to configure this one PatternLayout* patternLayout = new PatternLayout(); key = _properties.find(std::string("appender.") + appenderName + ".layout.ConversionPattern"); if (key == _properties.end()) { // leave default pattern } else { // set pattern patternLayout->setConversionPattern((*key).second); } layout = patternLayout; } else { throw ConfigureFailure(std::string("Unknown layout type '" + layoutType + "' for appender '") + appenderName + "'"); } appender->setLayout(layout); } /** * Get the categories contained within the map of properties. Since * the category looks something like "category.xxxxx.yyy.zzz", we need * to search the entire map to figure out which properties are category * listings. Seems like there might be a more elegant solution. */ void PropertyConfiguratorImpl::getCategories(std::vector<std::string>& categories) const { categories.clear(); // add the root category first categories.push_back(std::string("rootCategory")); // then look for "category." std::string prefix("category"); Properties::const_iterator from = _properties.lower_bound(prefix + '.'); Properties::const_iterator to = _properties.lower_bound(prefix + (char)('.' + 1)); for (Properties::const_iterator iter = from; iter != to; iter++) { categories.push_back((*iter).first.substr(prefix.size() + 1)); } } }
39.462209
133
0.601179
benjaminlarson